From b4829a28035458ebc863160051b85e320e96f5c8 Mon Sep 17 00:00:00 2001 From: carptopus Date: Thu, 15 Oct 2026 11:23:18 +0800 Subject: [PATCH 01/51] Maintain Windows candidates, provider quotas and reading layout --- .github/workflows/build.yml | 160 - .github/workflows/sync.yml | 383 - .github/workflows/windows-candidate.yml | 151 + .github/workflows/windows-release.yml | 95 + .gitignore | 9 + .npmignore | 1 + package-lock.json | 8866 ------------------ package.json | 8 + pnpm-lock.yaml | 6300 +++++++++++++ pnpm-workspace.yaml | 9 + release/acceptance/.gitkeep | 1 + scripts/build-from-upstream.js | 22 +- scripts/check-scripts.js | 13 + scripts/fetch-msstore.js | 7 +- scripts/frontend-source-smoke.js | 75 + scripts/maintenance-smoke.js | 149 + scripts/patch-model-picker-submenu.js | 76 +- scripts/patch-policy.js | 3 + scripts/patch-provider-quota.js | 337 + scripts/patch-reading-layout.js | 121 + scripts/patch-test-isolation.js | 84 + scripts/patch-updater.js | 37 +- scripts/reading-layout-smoke.js | 37 + scripts/runtime/reading-width.mjs | 73 + scripts/runtime/rebuild-test-environment.cjs | 20 + scripts/runtime/rebuild-test-isolation.cjs | 60 + scripts/sync-upstream.js | 34 +- scripts/windows-artifacts.js | 43 + scripts/windows-maintenance.js | 335 + scripts/windows-runtime-checks.js | 145 + 30 files changed, 8220 insertions(+), 9434 deletions(-) delete mode 100644 .github/workflows/build.yml delete mode 100644 .github/workflows/sync.yml create mode 100644 .github/workflows/windows-candidate.yml create mode 100644 .github/workflows/windows-release.yml delete mode 100644 package-lock.json create mode 100644 pnpm-lock.yaml create mode 100644 pnpm-workspace.yaml create mode 100644 release/acceptance/.gitkeep create mode 100644 scripts/check-scripts.js create mode 100644 scripts/frontend-source-smoke.js create mode 100644 scripts/maintenance-smoke.js create mode 100644 scripts/patch-provider-quota.js create mode 100644 scripts/patch-reading-layout.js create mode 100644 scripts/patch-test-isolation.js create mode 100644 scripts/reading-layout-smoke.js create mode 100644 scripts/runtime/reading-width.mjs create mode 100644 scripts/runtime/rebuild-test-environment.cjs create mode 100644 scripts/runtime/rebuild-test-isolation.cjs create mode 100644 scripts/windows-artifacts.js create mode 100644 scripts/windows-maintenance.js create mode 100644 scripts/windows-runtime-checks.js diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml deleted file mode 100644 index 57a33190..00000000 --- a/.github/workflows/build.yml +++ /dev/null @@ -1,160 +0,0 @@ -name: Build Artifacts - -on: - push: - branches: [master, main] - tags: ["v*"] - paths-ignore: - - "**/*.md" - - "docs/**" - workflow_dispatch: - inputs: - platform: - description: "Target platform" - required: true - type: choice - options: [all, mac, windows, linux] - -permissions: - contents: read - -concurrency: - group: build-${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -env: - NODE_VERSION: "24" - -jobs: - build-mac: - if: ${{ github.event_name != 'workflow_dispatch' || inputs.platform == 'all' || inputs.platform == 'mac' }} - runs-on: ${{ matrix.runner }} - strategy: - fail-fast: false - matrix: - include: - - arch: x64 - runner: macos-15-intel - - arch: arm64 - runner: macos-15 - steps: - - uses: actions/checkout@v6 - - uses: actions/setup-node@v6 - with: - node-version: ${{ env.NODE_VERSION }} - cache: npm - - run: | - npm ci - - run: | - brew install --quiet sevenzip - - name: Test patch and build scripts on macOS - run: npm test - - run: node scripts/sync-upstream.js --force --skip-win - - name: Check upstream patch compatibility - run: node scripts/patch-all.js mac-${{ matrix.arch }} --check --report patch-reports/mac-${{ matrix.arch }}-check - - - name: Patch - run: node scripts/patch-all.js mac-${{ matrix.arch }} --report patch-reports/mac-${{ matrix.arch }}-apply - - - name: Upload patch compatibility reports - if: always() - uses: actions/upload-artifact@v7 - with: - name: Patch-Reports-macOS-${{ matrix.arch }} - path: patch-reports/ - if-no-files-found: ignore - - run: npm run build:mac-${{ matrix.arch }} - - uses: actions/upload-artifact@v7 - with: - name: Codex-macOS-${{ matrix.arch }} - path: out/*.dmg - if-no-files-found: error - - build-windows: - if: ${{ github.event_name != 'workflow_dispatch' || inputs.platform == 'all' || inputs.platform == 'windows' }} - runs-on: windows-latest - steps: - - uses: actions/checkout@v6 - - uses: actions/setup-node@v6 - with: - node-version: ${{ env.NODE_VERSION }} - cache: npm - - run: | - npm ci - - run: npm test - - run: | - choco install 7zip -y - - name: Add 7zz alias - run: | - Copy-Item "C:\Program Files\7-Zip\7z.exe" "C:\Program Files\7-Zip\7zz.exe" - echo "C:\Program Files\7-Zip" | Out-File -Append -Encoding utf8 $env:GITHUB_PATH - - run: node scripts/sync-upstream.js --force --skip-mac - - name: Check upstream patch compatibility - run: node scripts/patch-all.js win --check --report patch-reports/windows-x64-check - - - name: Patch - run: node scripts/patch-all.js win --report patch-reports/windows-x64-apply - - - name: Upload patch compatibility reports - if: always() - uses: actions/upload-artifact@v7 - with: - name: Patch-Reports-Windows-x64 - path: patch-reports/ - if-no-files-found: ignore - - run: npm run build:win-x64 - - uses: actions/upload-artifact@v7 - with: - name: Codex-Windows-x64 - path: out/*.zip - if-no-files-found: error - - build-linux: - if: ${{ github.event_name != 'workflow_dispatch' || inputs.platform == 'all' || inputs.platform == 'linux' }} - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - arch: [x64, arm64] - steps: - - uses: actions/checkout@v6 - - name: Free disk space - run: | - echo "Disk space before cleanup:" - df -h / - sudo rm -rf /usr/local/lib/android /usr/share/dotnet /opt/ghc /usr/local/.ghcup - sudo apt-get clean - echo "Disk space after cleanup:" - df -h / - - uses: actions/setup-node@v6 - with: - node-version: ${{ env.NODE_VERSION }} - cache: npm - - run: | - npm ci - - run: | - sudo apt-get update - sudo apt-get install -y rpm fakeroot dpkg 7zip unzip - - run: node scripts/sync-upstream.js --force --skip-win - - name: Check upstream patch compatibility - run: node scripts/patch-all.js mac-${{ matrix.arch }} --check --report patch-reports/linux-${{ matrix.arch }}-check - - - name: Patch - run: node scripts/patch-all.js mac-${{ matrix.arch }} --report patch-reports/linux-${{ matrix.arch }}-apply - - - name: Upload patch compatibility reports - if: always() - uses: actions/upload-artifact@v7 - with: - name: Patch-Reports-Linux-${{ matrix.arch }} - path: patch-reports/ - if-no-files-found: ignore - - run: npm run build:linux-${{ matrix.arch }} - - uses: actions/upload-artifact@v7 - with: - name: Codex-Linux-${{ matrix.arch }} - path: | - out/make/deb/**/*.deb - out/make/rpm/**/*.rpm - out/make/zip/**/*.zip - if-no-files-found: error diff --git a/.github/workflows/sync.yml b/.github/workflows/sync.yml deleted file mode 100644 index 48d47692..00000000 --- a/.github/workflows/sync.yml +++ /dev/null @@ -1,383 +0,0 @@ -name: Sync Upstream & Patch - -on: - schedule: - - cron: "0 8 * * *" # Daily 08:00 UTC - workflow_dispatch: - inputs: - force: - description: "Force sync even without version change" - type: boolean - -env: - NODE_VERSION: "24" - -permissions: - contents: read - -concurrency: - group: sync-upstream-${{ github.ref }} - cancel-in-progress: false - -jobs: - check: - runs-on: ubuntu-latest - outputs: - has_update: ${{ steps.detect.outputs.has_update }} - latest_version: ${{ steps.detect.outputs.latest_version }} - steps: - - name: Checkout - uses: actions/checkout@v6 - - - name: Setup Node.js - uses: actions/setup-node@v6 - with: - node-version: ${{ env.NODE_VERSION }} - cache: npm - - - name: Install dependencies - run: npm ci - - - name: Test patch and build scripts - run: npm test - - - name: Check upstream versions - id: detect - run: | - RESULT="$(node scripts/check-update.js --state-file .github/upstream-versions.json --json --force)" - echo "$RESULT" > /tmp/codex-version-check.json - - LATEST_VERSION="$(node -e " - const fs = require('fs'); - const result = JSON.parse(fs.readFileSync('/tmp/codex-version-check.json', 'utf8')); - const platforms = result.platforms || {}; - const latest = platforms['macOS-arm64'] || platforms['macOS-x64'] || platforms.Windows; - process.stdout.write(latest?.version || ''); - ")" - - HAS_UPDATE="$(node -e " - const fs = require('fs'); - const result = JSON.parse(fs.readFileSync('/tmp/codex-version-check.json', 'utf8')); - process.stdout.write(result.hasUpdates ? 'true' : 'false'); - ")" - - echo "latest_version=$LATEST_VERSION" >> "$GITHUB_OUTPUT" - - if [ "${{ github.event_name == 'workflow_dispatch' && inputs.force }}" = "true" ]; then - echo "has_update=true" >> "$GITHUB_OUTPUT" - echo "Manual force sync requested." - elif [ "$HAS_UPDATE" = "true" ]; then - echo "has_update=true" >> "$GITHUB_OUTPUT" - echo "Upstream update detected: ${LATEST_VERSION}" - else - echo "has_update=false" >> "$GITHUB_OUTPUT" - echo "No upstream update detected. Platform versions match the saved state." - fi - - # ────────────────────────────────────────────── - # Each platform: sync + patch + build in one job - # (src/ is gitignored, so it must be generated per-runner) - # ────────────────────────────────────────────── - build-mac: - needs: check - if: needs.check.outputs.has_update == 'true' - runs-on: ${{ matrix.runner }} - strategy: - fail-fast: false - matrix: - include: - - arch: x64 - runner: macos-15-intel - - arch: arm64 - runner: macos-15 - steps: - - name: Checkout - uses: actions/checkout@v6 - - - name: Setup Node.js - uses: actions/setup-node@v6 - with: - node-version: ${{ env.NODE_VERSION }} - cache: npm - - - name: Install dependencies - run: | - npm ci - - - name: Install tools - run: | - brew install --quiet sevenzip - - - name: Test patch and build scripts on macOS - run: npm test - - - name: Sync upstream (macOS only) - run: node scripts/sync-upstream.js --force --skip-win - - - name: Check upstream patch compatibility - run: node scripts/patch-all.js mac-${{ matrix.arch }} --check --report patch-reports/mac-${{ matrix.arch }}-check - - - name: Patch - run: node scripts/patch-all.js mac-${{ matrix.arch }} --report patch-reports/mac-${{ matrix.arch }}-apply - - - name: Upload patch compatibility reports - if: always() - uses: actions/upload-artifact@v7 - with: - name: Patch-Reports-macOS-${{ matrix.arch }} - path: patch-reports/ - if-no-files-found: ignore - - - name: Build - run: npm run build:mac-${{ matrix.arch }} - - - name: Upload artifacts - uses: actions/upload-artifact@v7 - with: - name: Codex-macOS-${{ matrix.arch }} - path: out/*.dmg - if-no-files-found: error - - build-windows: - needs: check - if: needs.check.outputs.has_update == 'true' - runs-on: windows-latest - steps: - - name: Checkout - uses: actions/checkout@v6 - - - name: Setup Node.js - uses: actions/setup-node@v6 - with: - node-version: ${{ env.NODE_VERSION }} - cache: npm - - - name: Install dependencies - run: | - npm ci - - - name: Install tools - run: | - choco install 7zip -y - - - name: Add 7zz alias - run: | - Copy-Item "C:\Program Files\7-Zip\7z.exe" "C:\Program Files\7-Zip\7zz.exe" - echo "C:\Program Files\7-Zip" | Out-File -Append -Encoding utf8 $env:GITHUB_PATH - - - name: Sync upstream (Windows only) - run: node scripts/sync-upstream.js --force --skip-mac - - - name: Check upstream patch compatibility - run: node scripts/patch-all.js win --check --report patch-reports/windows-x64-check - - - name: Patch - run: node scripts/patch-all.js win --report patch-reports/windows-x64-apply - - - name: Upload patch compatibility reports - if: always() - uses: actions/upload-artifact@v7 - with: - name: Patch-Reports-Windows-x64 - path: patch-reports/ - if-no-files-found: ignore - - - name: Build - run: npm run build:win-x64 - - - name: Upload artifacts - uses: actions/upload-artifact@v7 - with: - name: Codex-Windows-x64 - path: out/*.zip - if-no-files-found: error - - build-linux: - needs: check - if: needs.check.outputs.has_update == 'true' - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - arch: [x64, arm64] - steps: - - name: Checkout - uses: actions/checkout@v6 - - - name: Free disk space - run: | - echo "Disk space before cleanup:" - df -h / - sudo rm -rf /usr/local/lib/android /usr/share/dotnet /opt/ghc /usr/local/.ghcup - sudo apt-get clean - echo "Disk space after cleanup:" - df -h / - - - name: Setup Node.js - uses: actions/setup-node@v6 - with: - node-version: ${{ env.NODE_VERSION }} - cache: npm - - - name: Install system dependencies - run: | - sudo apt-get update - sudo apt-get install -y rpm fakeroot dpkg 7zip unzip - - - name: Install dependencies - run: | - npm ci - - - name: Sync upstream (macOS ZIP for unix, skip Windows) - run: node scripts/sync-upstream.js --force --skip-win - - - name: Check upstream patch compatibility - run: node scripts/patch-all.js mac-${{ matrix.arch }} --check --report patch-reports/linux-${{ matrix.arch }}-check - - - name: Patch - run: node scripts/patch-all.js mac-${{ matrix.arch }} --report patch-reports/linux-${{ matrix.arch }}-apply - - - name: Upload patch compatibility reports - if: always() - uses: actions/upload-artifact@v7 - with: - name: Patch-Reports-Linux-${{ matrix.arch }} - path: patch-reports/ - if-no-files-found: ignore - - - name: Build - run: npm run build:linux-${{ matrix.arch }} - - - name: Upload artifacts - uses: actions/upload-artifact@v7 - with: - name: Codex-Linux-${{ matrix.arch }} - path: | - out/make/deb/**/*.deb - out/make/rpm/**/*.rpm - out/make/zip/**/*.zip - if-no-files-found: error - - # ────────────────────────────────────────────── - # 持久化上游版本 + 标签/发布 - # ────────────────────────────────────────────── - release: - needs: [check, build-mac, build-windows, build-linux] - if: >- - always() && - needs.check.result == 'success' && - needs.check.outputs.has_update == 'true' && - needs.build-mac.result == 'success' && - needs.build-windows.result == 'success' && - needs.build-linux.result == 'success' - runs-on: ubuntu-latest - permissions: - contents: write - steps: - - name: Checkout - uses: actions/checkout@v6 - with: - token: ${{ secrets.PAT_TOKEN || secrets.GITHUB_TOKEN }} - - - name: Setup Node.js - uses: actions/setup-node@v6 - with: - node-version: ${{ env.NODE_VERSION }} - - - name: Install dependencies - run: npm ci - - - name: Download all artifacts - uses: actions/download-artifact@v7 - with: - path: artifacts - - - name: Validate required artifacts - shell: bash - run: | - required_artifacts=( - "Codex-macOS-x64" - "Codex-macOS-arm64" - "Codex-Windows-x64" - "Codex-Linux-x64" - "Codex-Linux-arm64" - ) - - missing=0 - for artifact in "${required_artifacts[@]}"; do - if [ ! -d "artifacts/$artifact" ] || [ -z "$(find "artifacts/$artifact" -type f -print -quit)" ]; then - echo "::error::Missing or empty required artifact: $artifact" - missing=1 - fi - done - - if [ "$missing" -ne 0 ]; then - exit 1 - fi - - - name: Display structure - run: ls -lhR artifacts/ - - - name: Get upstream version and tag - id: version - run: | - RESULT=$(node scripts/check-update.js --state-file .github/upstream-versions.json --json --force --save) - MAC_ARM64=$(echo "$RESULT" | node -e "let d='';process.stdin.on('data',c=>d+=c);process.stdin.on('end',()=>{try{const j=JSON.parse(d);console.log(j.platforms?.['macOS-arm64']?.version||'')}catch{console.log('')}})") - MAC_X64=$(echo "$RESULT" | node -e "let d='';process.stdin.on('data',c=>d+=c);process.stdin.on('end',()=>{try{const j=JSON.parse(d);console.log(j.platforms?.['macOS-x64']?.version||'')}catch{console.log('')}})") - WIN_VER=$(echo "$RESULT" | node -e "let d='';process.stdin.on('data',c=>d+=c);process.stdin.on('end',()=>{try{const j=JSON.parse(d);console.log(j.platforms?.Windows?.version||'')}catch{console.log('')}})") - - VERSION="${MAC_ARM64:-${MAC_X64:-$WIN_VER}}" - echo "version=$VERSION" >> "$GITHUB_OUTPUT" - echo "mac_arm64=$MAC_ARM64" >> "$GITHUB_OUTPUT" - echo "mac_x64=$MAC_X64" >> "$GITHUB_OUTPUT" - echo "win_version=$WIN_VER" >> "$GITHUB_OUTPUT" - - if [ -z "$VERSION" ]; then echo "No version detected"; exit 0; fi - - node -e " - const fs=require('fs'), p=JSON.parse(fs.readFileSync('package.json','utf8')); - p.version='$VERSION'; - fs.writeFileSync('package.json', JSON.stringify(p,null,2)+'\n'); - " - - git config user.name "github-actions[bot]" - git config user.email "github-actions[bot]@users.noreply.github.com" - - git add package.json .github/upstream-versions.json - git diff --cached --quiet && echo "No version change" && exit 0 - - git commit -m "Update upstream versions for ${VERSION}" - - if git ls-remote --exit-code --tags origin "refs/tags/v${VERSION}" >/dev/null 2>&1; then - echo "Tag v${VERSION} already exists; updating the version state and existing release." - git push origin HEAD - else - git tag -a "v${VERSION}" -m "Codex ${VERSION}" - git push origin HEAD --tags - fi - - - name: Create Release - if: steps.version.outputs.version != '' - uses: softprops/action-gh-release@v3 - with: - tag_name: v${{ steps.version.outputs.version }} - name: Codex ${{ steps.version.outputs.version }} - body: | - ## Upstream Versions - | Platform | Version | - |----------|---------| - | macOS arm64 | `${{ steps.version.outputs.mac_arm64 || 'N/A' }}` | - | macOS x64 | `${{ steps.version.outputs.mac_x64 || 'N/A' }}` | - | Windows x64 | `${{ steps.version.outputs.win_version || 'N/A' }}` | - | Linux | uses macOS ASAR | - - Patch compatibility reports and optional-patch warnings are available in the [Actions run](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}) Summary and `Patch-Reports-*` artifacts. - files: | - artifacts/**/*.dmg - artifacts/**/*.zip - artifacts/**/*.deb - artifacts/**/*.rpm - artifacts/**/*.exe - draft: false - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/windows-candidate.yml b/.github/workflows/windows-candidate.yml new file mode 100644 index 00000000..590bdfb2 --- /dev/null +++ b/.github/workflows/windows-candidate.yml @@ -0,0 +1,151 @@ +name: Windows Candidate + +on: + push: + branches: [master, 'maintenance/**', 'candidate/**'] + paths-ignore: ['**/*.md'] + pull_request: + branches: [master] + schedule: + - cron: '0 8 * * *' + workflow_dispatch: + inputs: + upstream_version: + description: 'Exact available Windows MSIX version; blank selects newest x64' + type: string + source_run_id: + description: 'Reuse verified Windows-Source artifact from this repository run' + type: string + +permissions: + contents: read + actions: read + +concurrency: + group: windows-candidate-${{ github.ref }} + cancel-in-progress: ${{ github.event_name != 'schedule' }} + +jobs: + candidate: + runs-on: windows-latest + timeout-minutes: 40 + steps: + - uses: actions/checkout@v6 + - uses: pnpm/action-setup@v4 + with: + version: 10.33.0 + - uses: actions/setup-node@v6 + with: + node-version: '24.14.1' + cache: pnpm + - name: Install tooling without native builds or Electron download + run: pnpm install --frozen-lockfile --ignore-scripts + - name: Syntax and upstream regression checks + run: | + pnpm check + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + pnpm test + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + pnpm test:maintenance + - name: Use runner 7-Zip + run: | + $sevenZip = 'C:\Program Files\7-Zip' + if (-not (Test-Path -LiteralPath "$sevenZip\7z.exe")) { throw 'Runner 7-Zip missing' } + $sevenZip | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append + - name: Restore last successfully constructed candidate observation + id: observation + if: github.event_name != 'pull_request' + uses: actions/cache/restore@v4 + with: + path: .cache/observed-candidate.json + key: windows-observed-${{ github.sha }}-${{ github.run_id }}-${{ github.run_attempt }} + restore-keys: | + windows-observed-${{ github.sha }}- + - name: Download fixed upstream source for a replay + if: github.event_name == 'workflow_dispatch' && inputs.source_run_id != '' + uses: actions/download-artifact@v7 + with: + github-token: ${{ github.token }} + run-id: ${{ inputs.source_run_id }} + name: Windows-Source + path: artifacts/replay + - name: Read current stable source for daily comparison + if: github.event_name == 'schedule' && steps.observation.outputs.cache-matched-key == '' + env: + GH_TOKEN: ${{ github.token }} + run: | + $releases = gh api "repos/$env:GITHUB_REPOSITORY/releases?per_page=100" | ConvertFrom-Json + if ($LASTEXITCODE -ne 0) { throw 'Cannot read releases' } + $stable = $releases | Where-Object { -not $_.draft -and -not $_.prerelease -and $_.tag_name -like 'win-*' } | Select-Object -First 1 + if ($stable) { + New-Item -ItemType Directory -Path artifacts/stable -Force | Out-Null + gh release download $stable.tag_name --repo $env:GITHUB_REPOSITORY --pattern candidate.json --dir artifacts/stable + if ($LASTEXITCODE -ne 0) { throw 'Stable source record missing' } + } + - name: Discover official Windows package + id: discover + if: github.event_name != 'pull_request' && (inputs.source_run_id == '' || github.event_name != 'workflow_dispatch') + env: + REQUESTED_VERSION: ${{ inputs.upstream_version }} + run: | + $arguments = @('scripts/windows-maintenance.js', 'discover', '--out', '.cache/windows-discovery.json') + if ($env:REQUESTED_VERSION) { $arguments += @('--version', $env:REQUESTED_VERSION) } + if (Test-Path .cache/observed-candidate.json) { $arguments += @('--stable-manifest', '.cache/observed-candidate.json') } + elseif (Test-Path artifacts/stable/candidate.json) { $arguments += @('--stable-manifest', 'artifacts/stable/candidate.json') } + node @arguments + - name: Build and verify fixed Windows candidate + if: github.event_name != 'pull_request' && (github.event_name != 'schedule' || steps.discover.outputs.has_update == 'true') + run: | + $arguments = @('scripts/windows-maintenance.js', 'candidate') + if (Test-Path artifacts/replay/upstream.json) { $arguments += @('--source', 'artifacts/replay/upstream.json') } + else { $arguments += @('--discovery', '.cache/windows-discovery.json') } + node @arguments + - name: Patch reports, including failures + if: always() + uses: actions/upload-artifact@v7 + with: + name: Windows-Patch-Reports + path: patch-reports/ + retention-days: 7 + if-no-files-found: ignore + - name: Candidate ZIP and provenance + if: success() && github.event_name != 'pull_request' && (github.event_name != 'schedule' || steps.discover.outputs.has_update == 'true') + uses: actions/upload-artifact@v7 + with: + name: Windows-Candidate + path: | + artifacts/candidate/* + !artifacts/candidate/*.msix + retention-days: 7 + compression-level: 0 + if-no-files-found: error + - name: Small verification records for local review + if: success() && github.event_name != 'pull_request' && (github.event_name != 'schedule' || steps.discover.outputs.has_update == 'true') + uses: actions/upload-artifact@v7 + with: + name: Windows-Verification + path: | + artifacts/candidate/*.json + artifacts/candidate/SHA256SUMS.txt + retention-days: 7 + if-no-files-found: error + - name: Original MSIX for replay and local archive + if: success() && github.event_name != 'pull_request' && (github.event_name != 'schedule' || steps.discover.outputs.has_update == 'true') + uses: actions/upload-artifact@v7 + with: + name: Windows-Source + path: | + artifacts/candidate/*.msix + artifacts/candidate/upstream.json + retention-days: 7 + compression-level: 0 + if-no-files-found: error + - name: Save successful candidate observation without modifying master + if: success() && github.event_name != 'pull_request' && (github.event_name != 'schedule' || steps.discover.outputs.has_update == 'true') + run: Copy-Item -LiteralPath artifacts/candidate/candidate.json -Destination .cache/observed-candidate.json + - name: Cache last constructed source version + if: success() && github.event_name != 'pull_request' && (github.event_name != 'schedule' || steps.discover.outputs.has_update == 'true') + uses: actions/cache/save@v4 + with: + path: .cache/observed-candidate.json + key: windows-observed-${{ github.sha }}-${{ github.run_id }}-${{ github.run_attempt }} diff --git a/.github/workflows/windows-release.yml b/.github/workflows/windows-release.yml new file mode 100644 index 00000000..79023c51 --- /dev/null +++ b/.github/workflows/windows-release.yml @@ -0,0 +1,95 @@ +name: Promote Verified Windows Candidate + +on: + workflow_dispatch: + inputs: + run_id: + description: 'Successful Windows Candidate run ID' + required: true + type: string + zip_sha256: + description: 'SHA-256 of the ZIP actually tested' + required: true + type: string + acceptance_path: + description: 'Reviewed public JSON acceptance record on master, e.g. release/acceptance/run-id.json' + required: true + type: string + +permissions: + contents: read + actions: read + +concurrency: + group: windows-formal-release + cancel-in-progress: false + +jobs: + promote: + if: github.ref == 'refs/heads/master' + runs-on: windows-latest + timeout-minutes: 20 + permissions: + contents: write + actions: read + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + - uses: actions/setup-node@v6 + with: + node-version: '24.14.1' + - name: Validate run identity and committed acceptance record + id: run + env: + GH_TOKEN: ${{ github.token }} + CANDIDATE_RUN: ${{ inputs.run_id }} + ACCEPTANCE_PATH: ${{ inputs.acceptance_path }} + run: | + if ($env:CANDIDATE_RUN -notmatch '^\d+$') { throw 'Invalid run ID' } + if ($env:ACCEPTANCE_PATH -notmatch '^release/acceptance/[A-Za-z0-9._-]+\.json$') { throw 'Acceptance must be under release/acceptance' } + git ls-files --error-unmatch -- $env:ACCEPTANCE_PATH + if ($LASTEXITCODE -ne 0) { throw 'Acceptance record is not tracked on master' } + $run = gh api "repos/$env:GITHUB_REPOSITORY/actions/runs/$env:CANDIDATE_RUN" | ConvertFrom-Json + if ($LASTEXITCODE -ne 0) { throw 'Cannot read candidate run' } + if ($run.status -ne 'completed' -or $run.conclusion -ne 'success' -or $run.path -ne '.github/workflows/windows-candidate.yml' -or $run.head_repository.full_name -ne $env:GITHUB_REPOSITORY) { throw 'Not a successful same-repository candidate run' } + git merge-base --is-ancestor $run.head_sha HEAD + if ($LASTEXITCODE -ne 0) { throw 'Candidate source has not been merged into master' } + "source_commit=$($run.head_sha)" >> $env:GITHUB_OUTPUT + "run_attempt=$($run.run_attempt)" >> $env:GITHUB_OUTPUT + - uses: actions/download-artifact@v7 + with: + github-token: ${{ github.token }} + run-id: ${{ inputs.run_id }} + name: Windows-Candidate + path: artifacts/candidate + - uses: actions/download-artifact@v7 + with: + github-token: ${{ github.token }} + run-id: ${{ inputs.run_id }} + name: Windows-Source + path: artifacts/candidate + - name: Verify original payload and all acceptance gates + id: verify + env: + CANDIDATE_RUN: ${{ inputs.run_id }} + CANDIDATE_HASH: ${{ inputs.zip_sha256 }} + CANDIDATE_SOURCE: ${{ steps.run.outputs.source_commit }} + CANDIDATE_ATTEMPT: ${{ steps.run.outputs.run_attempt }} + ACCEPTANCE_PATH: ${{ inputs.acceptance_path }} + run: | + node scripts/windows-maintenance.js verify-release --dir artifacts/candidate --acceptance $env:ACCEPTANCE_PATH --run-id $env:CANDIDATE_RUN --zip-sha256 $env:CANDIDATE_HASH --source-commit $env:CANDIDATE_SOURCE --run-attempt $env:CANDIDATE_ATTEMPT + - name: Publish the existing tested ZIP without rebuilding + env: + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ steps.verify.outputs.tag }} + SOURCE_COMMIT: ${{ steps.verify.outputs.source_commit }} + ZIP_NAME: ${{ steps.verify.outputs.zip_name }} + run: | + $existing = gh api "repos/$env:GITHUB_REPOSITORY/releases?per_page=100" | ConvertFrom-Json + if ($LASTEXITCODE -ne 0) { throw 'Cannot check existing release tags' } + if ($existing | Where-Object tag_name -eq $env:RELEASE_TAG) { throw 'Release already exists; overwriting is prohibited' } + $dir = 'artifacts/candidate' + $files = @("$dir/$env:ZIP_NAME", "$dir/SHA256SUMS.txt", "$dir/candidate.json", "$dir/upstream.json", "$dir/verify-report.json", "$dir/acceptance.json") + gh release create $env:RELEASE_TAG @files --repo $env:GITHUB_REPOSITORY --target $env:SOURCE_COMMIT --title $env:RELEASE_TAG --notes 'Windows x64 personal build. Published from the same accepted candidate; see provenance and acceptance records. Official runtime signature may be invalid after ASAR integrity changes.' + if ($LASTEXITCODE -ne 0) { throw 'Release failed' } diff --git a/.gitignore b/.gitignore index 07d5a077..1434063a 100644 --- a/.gitignore +++ b/.gitignore @@ -45,3 +45,12 @@ resources/bin/ resources/codex resources/codex.exe .claude/ + +# Local tools, upstream packages, candidates and isolated acceptance data +7-Zip/ +.cache/ +artifacts/ +/acceptance/ + +# Private maintenance documents and machine-local tools; never commit +/local/ diff --git a/.npmignore b/.npmignore index 98a20cf4..4809c672 100644 --- a/.npmignore +++ b/.npmignore @@ -1 +1,2 @@ # Not published to npm — this file silences the gitignore-fallback warning +/local/ diff --git a/package-lock.json b/package-lock.json deleted file mode 100644 index e5619a6b..00000000 --- a/package-lock.json +++ /dev/null @@ -1,8866 +0,0 @@ -{ - "name": "codex-rebuild", - "version": "26.623.81905", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "codex-rebuild", - "version": "26.623.81905", - "dependencies": { - "@sentry/electron": "^7.5.0", - "@sentry/node": "10.29.0", - "better-sqlite3": "^12.11.1", - "electron-context-menu": "^4.1.1", - "electron-squirrel-startup": "^1.0.1", - "encoding": "^0.1.13", - "immer": "^10.1.1", - "lodash": "^4.17.21", - "memoizee": "^0.4.15", - "mime-types": "^2.1.35", - "node-pty": "^1.1.0", - "shell-env": "^4.0.1", - "shlex": "^3.0.0", - "smol-toml": "^1.5.2", - "tslib": "^2.8.1", - "zod": "^4.1.13" - }, - "devDependencies": { - "@electron-forge/cli": "^7.10.2", - "@electron-forge/maker-deb": "^7.10.2", - "@electron-forge/maker-dmg": "^7.10.2", - "@electron-forge/maker-rpm": "^7.10.2", - "@electron-forge/maker-squirrel": "^7.10.2", - "@electron-forge/maker-zip": "^7.10.2", - "@electron-forge/plugin-auto-unpack-natives": "^7.10.2", - "@electron-forge/plugin-fuses": "^7.10.2", - "@electron/asar": "^4.1.2", - "@electron/fuses": "^1.8.0", - "@electron/rebuild": "^3.7.1", - "acorn": "^8.16.0", - "electron": "^42.0.1", - "fast-xml-parser": "^5.5.9" - } - }, - "node_modules/@apm-js-collab/code-transformer": { - "version": "0.8.2", - "license": "Apache-2.0" - }, - "node_modules/@apm-js-collab/tracing-hooks": { - "version": "0.3.1", - "license": "Apache-2.0", - "dependencies": { - "@apm-js-collab/code-transformer": "^0.8.0", - "debug": "^4.4.1", - "module-details-from-path": "^1.0.4" - } - }, - "node_modules/@electron-forge/cli": { - "version": "7.11.1", - "dev": true, - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/malept" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/subscription/pkg/npm-.electron-forge-cli?utm_medium=referral&utm_source=npm_fund" - } - ], - "license": "MIT", - "dependencies": { - "@electron-forge/core": "7.11.1", - "@electron-forge/core-utils": "7.11.1", - "@electron-forge/shared-types": "7.11.1", - "@electron/get": "^3.0.0", - "@inquirer/prompts": "^6.0.1", - "@listr2/prompt-adapter-inquirer": "^2.0.22", - "chalk": "^4.0.0", - "commander": "^11.1.0", - "debug": "^4.3.1", - "fs-extra": "^10.0.0", - "listr2": "^7.0.2", - "log-symbols": "^4.0.0", - "semver": "^7.2.1" - }, - "bin": { - "electron-forge": "dist/electron-forge.js", - "electron-forge-vscode-nix": "script/vscode.sh", - "electron-forge-vscode-win": "script/vscode.cmd" - }, - "engines": { - "node": ">= 16.4.0" - } - }, - "node_modules/@electron-forge/core": { - "version": "7.11.1", - "dev": true, - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/malept" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/subscription/pkg/npm-.electron-forge-core?utm_medium=referral&utm_source=npm_fund" - } - ], - "license": "MIT", - "dependencies": { - "@electron-forge/core-utils": "7.11.1", - "@electron-forge/maker-base": "7.11.1", - "@electron-forge/plugin-base": "7.11.1", - "@electron-forge/publisher-base": "7.11.1", - "@electron-forge/shared-types": "7.11.1", - "@electron-forge/template-base": "7.11.1", - "@electron-forge/template-vite": "7.11.1", - "@electron-forge/template-vite-typescript": "7.11.1", - "@electron-forge/template-webpack": "7.11.1", - "@electron-forge/template-webpack-typescript": "7.11.1", - "@electron-forge/tracer": "7.11.1", - "@electron/get": "^3.0.0", - "@electron/packager": "^18.3.5", - "@electron/rebuild": "^3.7.0", - "@malept/cross-spawn-promise": "^2.0.0", - "@vscode/sudo-prompt": "^9.3.1", - "chalk": "^4.0.0", - "debug": "^4.3.1", - "fast-glob": "^3.2.7", - "filenamify": "^4.1.0", - "find-up": "^5.0.0", - "fs-extra": "^10.0.0", - "global-dirs": "^3.0.0", - "got": "^11.8.5", - "interpret": "^3.1.1", - "jiti": "^2.4.2", - "listr2": "^7.0.2", - "lodash": "^4.17.20", - "log-symbols": "^4.0.0", - "node-fetch": "^2.6.7", - "rechoir": "^0.8.0", - "semver": "^7.2.1", - "source-map-support": "^0.5.13", - "username": "^5.1.0" - }, - "engines": { - "node": ">= 16.4.0" - } - }, - "node_modules/@electron-forge/core-utils": { - "version": "7.11.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@electron-forge/shared-types": "7.11.1", - "@electron/rebuild": "^3.7.0", - "@malept/cross-spawn-promise": "^2.0.0", - "chalk": "^4.0.0", - "debug": "^4.3.1", - "find-up": "^5.0.0", - "fs-extra": "^10.0.0", - "log-symbols": "^4.0.0", - "parse-author": "^2.0.0", - "semver": "^7.2.1" - }, - "engines": { - "node": ">= 16.4.0" - } - }, - "node_modules/@electron-forge/maker-base": { - "version": "7.11.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@electron-forge/shared-types": "7.11.1", - "fs-extra": "^10.0.0", - "which": "^2.0.2" - }, - "engines": { - "node": ">= 16.4.0" - } - }, - "node_modules/@electron-forge/maker-deb": { - "version": "7.11.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@electron-forge/maker-base": "7.11.1", - "@electron-forge/shared-types": "7.11.1" - }, - "engines": { - "node": ">= 16.4.0" - }, - "optionalDependencies": { - "electron-installer-debian": "^3.2.0" - } - }, - "node_modules/@electron-forge/maker-dmg": { - "version": "7.11.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@electron-forge/maker-base": "7.11.1", - "@electron-forge/shared-types": "7.11.1", - "fs-extra": "^10.0.0" - }, - "engines": { - "node": ">= 16.4.0" - }, - "optionalDependencies": { - "electron-installer-dmg": "^5.0.1" - } - }, - "node_modules/@electron-forge/maker-rpm": { - "version": "7.11.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@electron-forge/maker-base": "7.11.1", - "@electron-forge/shared-types": "7.11.1" - }, - "engines": { - "node": ">= 16.4.0" - }, - "optionalDependencies": { - "electron-installer-redhat": "^3.2.0" - } - }, - "node_modules/@electron-forge/maker-squirrel": { - "version": "7.11.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@electron-forge/maker-base": "7.11.1", - "@electron-forge/shared-types": "7.11.1", - "fs-extra": "^10.0.0" - }, - "engines": { - "node": ">= 16.4.0" - }, - "optionalDependencies": { - "electron-winstaller": "^5.3.0" - } - }, - "node_modules/@electron-forge/maker-zip": { - "version": "7.11.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@electron-forge/maker-base": "7.11.1", - "@electron-forge/shared-types": "7.11.1", - "cross-zip": "^4.0.0", - "fs-extra": "^10.0.0", - "got": "^11.8.5" - }, - "engines": { - "node": ">= 16.4.0" - } - }, - "node_modules/@electron-forge/plugin-auto-unpack-natives": { - "version": "7.11.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@electron-forge/plugin-base": "7.11.1", - "@electron-forge/shared-types": "7.11.1" - }, - "engines": { - "node": ">= 16.4.0" - } - }, - "node_modules/@electron-forge/plugin-base": { - "version": "7.11.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@electron-forge/shared-types": "7.11.1" - }, - "engines": { - "node": ">= 16.4.0" - } - }, - "node_modules/@electron-forge/plugin-fuses": { - "version": "7.11.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@electron-forge/plugin-base": "7.11.1", - "@electron-forge/shared-types": "7.11.1" - }, - "engines": { - "node": ">= 16.4.0" - }, - "peerDependencies": { - "@electron/fuses": "^1.0.0" - } - }, - "node_modules/@electron-forge/publisher-base": { - "version": "7.11.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@electron-forge/shared-types": "7.11.1" - }, - "engines": { - "node": ">= 16.4.0" - } - }, - "node_modules/@electron-forge/shared-types": { - "version": "7.11.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@electron-forge/tracer": "7.11.1", - "@electron/packager": "^18.3.5", - "@electron/rebuild": "^3.7.0", - "listr2": "^7.0.2" - }, - "engines": { - "node": ">= 16.4.0" - } - }, - "node_modules/@electron-forge/template-base": { - "version": "7.11.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@electron-forge/core-utils": "7.11.1", - "@electron-forge/shared-types": "7.11.1", - "@malept/cross-spawn-promise": "^2.0.0", - "debug": "^4.3.1", - "fs-extra": "^10.0.0", - "semver": "^7.2.1", - "username": "^5.1.0" - }, - "engines": { - "node": ">= 16.4.0" - } - }, - "node_modules/@electron-forge/template-vite": { - "version": "7.11.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@electron-forge/shared-types": "7.11.1", - "@electron-forge/template-base": "7.11.1", - "fs-extra": "^10.0.0" - }, - "engines": { - "node": ">= 16.4.0" - } - }, - "node_modules/@electron-forge/template-vite-typescript": { - "version": "7.11.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@electron-forge/shared-types": "7.11.1", - "@electron-forge/template-base": "7.11.1", - "fs-extra": "^10.0.0" - }, - "engines": { - "node": ">= 16.4.0" - } - }, - "node_modules/@electron-forge/template-webpack": { - "version": "7.11.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@electron-forge/shared-types": "7.11.1", - "@electron-forge/template-base": "7.11.1", - "fs-extra": "^10.0.0" - }, - "engines": { - "node": ">= 16.4.0" - } - }, - "node_modules/@electron-forge/template-webpack-typescript": { - "version": "7.11.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@electron-forge/shared-types": "7.11.1", - "@electron-forge/template-base": "7.11.1", - "fs-extra": "^10.0.0", - "typescript": "~5.4.5", - "webpack": "^5.69.1" - }, - "engines": { - "node": ">= 16.4.0" - } - }, - "node_modules/@electron-forge/tracer": { - "version": "7.11.1", - "dev": true, - "license": "MIT", - "dependencies": { - "chrome-trace-event": "^1.0.3" - }, - "engines": { - "node": ">= 14.17.5" - } - }, - "node_modules/@electron/asar": { - "version": "4.2.0", - "dev": true, - "license": "MIT", - "dependencies": { - "commander": "^13.1.0", - "glob": "^13.0.2", - "minimatch": "^10.0.1" - }, - "bin": { - "asar": "bin/asar.mjs" - }, - "engines": { - "node": ">=22.12.0" - } - }, - "node_modules/@electron/asar/node_modules/commander": { - "version": "13.1.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/@electron/fuses": { - "version": "1.8.0", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "chalk": "^4.1.1", - "fs-extra": "^9.0.1", - "minimist": "^1.2.5" - }, - "bin": { - "electron-fuses": "dist/bin.js" - } - }, - "node_modules/@electron/fuses/node_modules/fs-extra": { - "version": "9.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "at-least-node": "^1.0.0", - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@electron/get": { - "version": "3.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.1.1", - "env-paths": "^2.2.0", - "fs-extra": "^8.1.0", - "got": "^11.8.5", - "progress": "^2.0.3", - "semver": "^6.2.0", - "sumchecker": "^3.0.1" - }, - "engines": { - "node": ">=14" - }, - "optionalDependencies": { - "global-agent": "^3.0.0" - } - }, - "node_modules/@electron/get/node_modules/fs-extra": { - "version": "8.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "graceful-fs": "^4.2.0", - "jsonfile": "^4.0.0", - "universalify": "^0.1.0" - }, - "engines": { - "node": ">=6 <7 || >=8" - } - }, - "node_modules/@electron/get/node_modules/jsonfile": { - "version": "4.0.0", - "dev": true, - "license": "MIT", - "optionalDependencies": { - "graceful-fs": "^4.1.6" - } - }, - "node_modules/@electron/get/node_modules/semver": { - "version": "6.3.1", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/@electron/get/node_modules/universalify": { - "version": "0.1.2", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 4.0.0" - } - }, - "node_modules/@electron/node-gyp": { - "version": "10.2.0-electron.1", - "resolved": "git+ssh://git@github.com/electron/node-gyp.git#06b29aafb7708acef8b3669835c8a7857ebc92d2", - "integrity": "sha512-CrYo6TntjpoMO1SHjl5Pa/JoUsECNqNdB7Kx49WLQpWzPw53eEITJ2Hs9fh/ryUYDn4pxZz11StaBYBrLFJdqg==", - "dev": true, - "license": "MIT", - "dependencies": { - "env-paths": "^2.2.0", - "exponential-backoff": "^3.1.1", - "glob": "^8.1.0", - "graceful-fs": "^4.2.6", - "make-fetch-happen": "^10.2.1", - "nopt": "^6.0.0", - "proc-log": "^2.0.1", - "semver": "^7.3.5", - "tar": "^6.2.1", - "which": "^2.0.2" - }, - "bin": { - "node-gyp": "bin/node-gyp.js" - }, - "engines": { - "node": ">=12.13.0" - } - }, - "node_modules/@electron/node-gyp/node_modules/balanced-match": { - "version": "1.0.2", - "dev": true, - "license": "MIT" - }, - "node_modules/@electron/node-gyp/node_modules/brace-expansion": { - "version": "2.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0" - } - }, - "node_modules/@electron/node-gyp/node_modules/glob": { - "version": "8.1.0", - "dev": true, - "license": "ISC", - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^5.0.1", - "once": "^1.3.0" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/@electron/node-gyp/node_modules/minimatch": { - "version": "5.1.9", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^2.0.1" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@electron/notarize": { - "version": "2.5.0", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.1.1", - "fs-extra": "^9.0.1", - "promise-retry": "^2.0.1" - }, - "engines": { - "node": ">= 10.0.0" - } - }, - "node_modules/@electron/notarize/node_modules/fs-extra": { - "version": "9.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "at-least-node": "^1.0.0", - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@electron/osx-sign": { - "version": "1.3.3", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "compare-version": "^0.1.2", - "debug": "^4.3.4", - "fs-extra": "^10.0.0", - "isbinaryfile": "^4.0.8", - "minimist": "^1.2.6", - "plist": "^3.0.5" - }, - "bin": { - "electron-osx-flat": "bin/electron-osx-flat.js", - "electron-osx-sign": "bin/electron-osx-sign.js" - }, - "engines": { - "node": ">=12.0.0" - } - }, - "node_modules/@electron/packager": { - "version": "18.4.4", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "@electron/asar": "^3.2.13", - "@electron/get": "^3.0.0", - "@electron/notarize": "^2.1.0", - "@electron/osx-sign": "^1.0.5", - "@electron/universal": "^2.0.1", - "@electron/windows-sign": "^1.0.0", - "@malept/cross-spawn-promise": "^2.0.0", - "debug": "^4.0.1", - "extract-zip": "^2.0.0", - "filenamify": "^4.1.0", - "fs-extra": "^11.1.0", - "galactus": "^1.0.0", - "get-package-info": "^1.0.0", - "junk": "^3.1.0", - "parse-author": "^2.0.0", - "plist": "^3.0.0", - "prettier": "^3.4.2", - "resedit": "^2.0.0", - "resolve": "^1.1.6", - "semver": "^7.1.3", - "yargs-parser": "^21.1.1" - }, - "bin": { - "electron-packager": "bin/electron-packager.js" - }, - "engines": { - "node": ">= 16.13.0" - }, - "funding": { - "url": "https://github.com/electron/packager?sponsor=1" - } - }, - "node_modules/@electron/packager/node_modules/@electron/asar": { - "version": "3.4.1", - "dev": true, - "license": "MIT", - "dependencies": { - "commander": "^5.0.0", - "glob": "^7.1.6", - "minimatch": "^3.0.4" - }, - "bin": { - "asar": "bin/asar.js" - }, - "engines": { - "node": ">=10.12.0" - } - }, - "node_modules/@electron/packager/node_modules/balanced-match": { - "version": "1.0.2", - "dev": true, - "license": "MIT" - }, - "node_modules/@electron/packager/node_modules/brace-expansion": { - "version": "1.1.14", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/@electron/packager/node_modules/commander": { - "version": "5.1.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 6" - } - }, - "node_modules/@electron/packager/node_modules/fs-extra": { - "version": "11.3.5", - "dev": true, - "license": "MIT", - "dependencies": { - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" - }, - "engines": { - "node": ">=14.14" - } - }, - "node_modules/@electron/packager/node_modules/glob": { - "version": "7.2.3", - "dev": true, - "license": "ISC", - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/@electron/packager/node_modules/minimatch": { - "version": "3.1.5", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/@electron/rebuild": { - "version": "3.7.2", - "dev": true, - "license": "MIT", - "dependencies": { - "@electron/node-gyp": "https://github.com/electron/node-gyp#06b29aafb7708acef8b3669835c8a7857ebc92d2", - "@malept/cross-spawn-promise": "^2.0.0", - "chalk": "^4.0.0", - "debug": "^4.1.1", - "detect-libc": "^2.0.1", - "fs-extra": "^10.0.0", - "got": "^11.7.0", - "node-abi": "^3.45.0", - "node-api-version": "^0.2.0", - "ora": "^5.1.0", - "read-binary-file-arch": "^1.0.6", - "semver": "^7.3.5", - "tar": "^6.0.5", - "yargs": "^17.0.1" - }, - "bin": { - "electron-rebuild": "lib/cli.js" - }, - "engines": { - "node": ">=12.13.0" - } - }, - "node_modules/@electron/universal": { - "version": "2.0.3", - "dev": true, - "license": "MIT", - "dependencies": { - "@electron/asar": "^3.3.1", - "@malept/cross-spawn-promise": "^2.0.0", - "debug": "^4.3.1", - "dir-compare": "^4.2.0", - "fs-extra": "^11.1.1", - "minimatch": "^9.0.3", - "plist": "^3.1.0" - }, - "engines": { - "node": ">=16.4" - } - }, - "node_modules/@electron/universal/node_modules/@electron/asar": { - "version": "3.4.1", - "dev": true, - "license": "MIT", - "dependencies": { - "commander": "^5.0.0", - "glob": "^7.1.6", - "minimatch": "^3.0.4" - }, - "bin": { - "asar": "bin/asar.js" - }, - "engines": { - "node": ">=10.12.0" - } - }, - "node_modules/@electron/universal/node_modules/@electron/asar/node_modules/brace-expansion": { - "version": "1.1.14", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/@electron/universal/node_modules/@electron/asar/node_modules/minimatch": { - "version": "3.1.5", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/@electron/universal/node_modules/balanced-match": { - "version": "1.0.2", - "dev": true, - "license": "MIT" - }, - "node_modules/@electron/universal/node_modules/brace-expansion": { - "version": "2.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0" - } - }, - "node_modules/@electron/universal/node_modules/commander": { - "version": "5.1.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 6" - } - }, - "node_modules/@electron/universal/node_modules/fs-extra": { - "version": "11.3.5", - "dev": true, - "license": "MIT", - "dependencies": { - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" - }, - "engines": { - "node": ">=14.14" - } - }, - "node_modules/@electron/universal/node_modules/glob": { - "version": "7.2.3", - "dev": true, - "license": "ISC", - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/@electron/universal/node_modules/glob/node_modules/brace-expansion": { - "version": "1.1.14", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/@electron/universal/node_modules/glob/node_modules/minimatch": { - "version": "3.1.5", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/@electron/universal/node_modules/minimatch": { - "version": "9.0.9", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^2.0.2" - }, - "engines": { - "node": ">=16 || 14 >=14.17" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/@electron/windows-sign": { - "version": "1.2.2", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "cross-dirname": "^0.1.0", - "debug": "^4.3.4", - "fs-extra": "^11.1.1", - "minimist": "^1.2.8", - "postject": "^1.0.0-alpha.6" - }, - "bin": { - "electron-windows-sign": "bin/electron-windows-sign.js" - }, - "engines": { - "node": ">=14.14" - } - }, - "node_modules/@electron/windows-sign/node_modules/fs-extra": { - "version": "11.3.5", - "dev": true, - "license": "MIT", - "dependencies": { - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" - }, - "engines": { - "node": ">=14.14" - } - }, - "node_modules/@fastify/otel": { - "version": "0.18.0", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT", - "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.212.0", - "@opentelemetry/semantic-conventions": "^1.28.0", - "minimatch": "^10.2.4" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.9.0" - } - }, - "node_modules/@fastify/otel/node_modules/@opentelemetry/api-logs": { - "version": "0.212.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/api": "^1.3.0" - }, - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/@fastify/otel/node_modules/@opentelemetry/instrumentation": { - "version": "0.212.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/api-logs": "0.212.0", - "import-in-the-middle": "^2.0.6", - "require-in-the-middle": "^8.0.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@gar/promisify": { - "version": "1.1.3", - "dev": true, - "license": "MIT" - }, - "node_modules/@inquirer/checkbox": { - "version": "3.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^9.2.1", - "@inquirer/figures": "^1.0.6", - "@inquirer/type": "^2.0.0", - "ansi-escapes": "^4.3.2", - "yoctocolors-cjs": "^2.1.2" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@inquirer/confirm": { - "version": "4.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^9.2.1", - "@inquirer/type": "^2.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@inquirer/core": { - "version": "9.2.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/figures": "^1.0.6", - "@inquirer/type": "^2.0.0", - "@types/mute-stream": "^0.0.4", - "@types/node": "^22.5.5", - "@types/wrap-ansi": "^3.0.0", - "ansi-escapes": "^4.3.2", - "cli-width": "^4.1.0", - "mute-stream": "^1.0.0", - "signal-exit": "^4.1.0", - "strip-ansi": "^6.0.1", - "wrap-ansi": "^6.2.0", - "yoctocolors-cjs": "^2.1.2" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@inquirer/editor": { - "version": "3.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^9.2.1", - "@inquirer/type": "^2.0.0", - "external-editor": "^3.1.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@inquirer/expand": { - "version": "3.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^9.2.1", - "@inquirer/type": "^2.0.0", - "yoctocolors-cjs": "^2.1.2" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@inquirer/figures": { - "version": "1.0.15", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/@inquirer/input": { - "version": "3.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^9.2.1", - "@inquirer/type": "^2.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@inquirer/number": { - "version": "2.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^9.2.1", - "@inquirer/type": "^2.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@inquirer/password": { - "version": "3.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^9.2.1", - "@inquirer/type": "^2.0.0", - "ansi-escapes": "^4.3.2" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@inquirer/prompts": { - "version": "6.0.1", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@inquirer/checkbox": "^3.0.1", - "@inquirer/confirm": "^4.0.1", - "@inquirer/editor": "^3.0.1", - "@inquirer/expand": "^3.0.1", - "@inquirer/input": "^3.0.1", - "@inquirer/number": "^2.0.1", - "@inquirer/password": "^3.0.1", - "@inquirer/rawlist": "^3.0.1", - "@inquirer/search": "^2.0.1", - "@inquirer/select": "^3.0.1" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@inquirer/rawlist": { - "version": "3.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^9.2.1", - "@inquirer/type": "^2.0.0", - "yoctocolors-cjs": "^2.1.2" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@inquirer/search": { - "version": "2.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^9.2.1", - "@inquirer/figures": "^1.0.6", - "@inquirer/type": "^2.0.0", - "yoctocolors-cjs": "^2.1.2" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@inquirer/select": { - "version": "3.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^9.2.1", - "@inquirer/figures": "^1.0.6", - "@inquirer/type": "^2.0.0", - "ansi-escapes": "^4.3.2", - "yoctocolors-cjs": "^2.1.2" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@inquirer/type": { - "version": "2.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "mute-stream": "^1.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@jridgewell/gen-mapping": { - "version": "0.3.13", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.0", - "@jridgewell/trace-mapping": "^0.3.24" - } - }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.2", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/source-map": { - "version": "0.3.11", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.5", - "@jridgewell/trace-mapping": "^0.3.25" - } - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "dev": true, - "license": "MIT" - }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.31", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/resolve-uri": "^3.1.0", - "@jridgewell/sourcemap-codec": "^1.4.14" - } - }, - "node_modules/@listr2/prompt-adapter-inquirer": { - "version": "2.0.22", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/type": "^1.5.5" - }, - "engines": { - "node": ">=18.0.0" - }, - "peerDependencies": { - "@inquirer/prompts": ">= 3 < 8" - } - }, - "node_modules/@listr2/prompt-adapter-inquirer/node_modules/@inquirer/type": { - "version": "1.5.5", - "dev": true, - "license": "MIT", - "dependencies": { - "mute-stream": "^1.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@malept/cross-spawn-promise": { - "version": "2.0.0", - "dev": true, - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/malept" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/subscription/pkg/npm-.malept-cross-spawn-promise?utm_medium=referral&utm_source=npm_fund" - } - ], - "license": "Apache-2.0", - "dependencies": { - "cross-spawn": "^7.0.1" - }, - "engines": { - "node": ">= 12.13.0" - } - }, - "node_modules/@nodable/entities": { - "version": "2.1.0", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/nodable" - } - ], - "license": "MIT" - }, - "node_modules/@nodelib/fs.scandir": { - "version": "2.1.5", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "2.0.5", - "run-parallel": "^1.1.9" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.stat": { - "version": "2.0.5", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.walk": { - "version": "1.2.8", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.scandir": "2.1.5", - "fastq": "^1.6.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@npmcli/fs": { - "version": "2.1.2", - "dev": true, - "license": "ISC", - "dependencies": { - "@gar/promisify": "^1.1.3", - "semver": "^7.3.5" - }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } - }, - "node_modules/@npmcli/move-file": { - "version": "2.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "mkdirp": "^1.0.4", - "rimraf": "^3.0.2" - }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } - }, - "node_modules/@opentelemetry/api": { - "version": "1.9.1", - "license": "Apache-2.0", - "peer": true, - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/@opentelemetry/api-logs": { - "version": "0.208.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/api": "^1.3.0" - }, - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/@opentelemetry/context-async-hooks": { - "version": "2.7.1", - "license": "Apache-2.0", - "peer": true, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.10.0" - } - }, - "node_modules/@opentelemetry/core": { - "version": "2.7.1", - "license": "Apache-2.0", - "peer": true, - "dependencies": { - "@opentelemetry/semantic-conventions": "^1.29.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.10.0" - } - }, - "node_modules/@opentelemetry/instrumentation": { - "version": "0.208.0", - "license": "Apache-2.0", - "peer": true, - "dependencies": { - "@opentelemetry/api-logs": "0.208.0", - "import-in-the-middle": "^2.0.0", - "require-in-the-middle": "^8.0.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@opentelemetry/instrumentation-amqplib": { - "version": "0.55.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.208.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@opentelemetry/instrumentation-connect": { - "version": "0.52.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.208.0", - "@opentelemetry/semantic-conventions": "^1.27.0", - "@types/connect": "3.4.38" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@opentelemetry/instrumentation-dataloader": { - "version": "0.26.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.208.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@opentelemetry/instrumentation-express": { - "version": "0.57.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.208.0", - "@opentelemetry/semantic-conventions": "^1.27.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@opentelemetry/instrumentation-fs": { - "version": "0.28.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.208.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@opentelemetry/instrumentation-generic-pool": { - "version": "0.52.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.208.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@opentelemetry/instrumentation-graphql": { - "version": "0.56.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.208.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@opentelemetry/instrumentation-hapi": { - "version": "0.55.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.208.0", - "@opentelemetry/semantic-conventions": "^1.27.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@opentelemetry/instrumentation-http": { - "version": "0.208.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "2.2.0", - "@opentelemetry/instrumentation": "0.208.0", - "@opentelemetry/semantic-conventions": "^1.29.0", - "forwarded-parse": "2.1.2" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@opentelemetry/instrumentation-http/node_modules/@opentelemetry/core": { - "version": "2.2.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/semantic-conventions": "^1.29.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.10.0" - } - }, - "node_modules/@opentelemetry/instrumentation-ioredis": { - "version": "0.56.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.208.0", - "@opentelemetry/redis-common": "^0.38.2" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@opentelemetry/instrumentation-kafkajs": { - "version": "0.18.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.208.0", - "@opentelemetry/semantic-conventions": "^1.30.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@opentelemetry/instrumentation-knex": { - "version": "0.53.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.208.0", - "@opentelemetry/semantic-conventions": "^1.33.1" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@opentelemetry/instrumentation-koa": { - "version": "0.57.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.208.0", - "@opentelemetry/semantic-conventions": "^1.36.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.9.0" - } - }, - "node_modules/@opentelemetry/instrumentation-lru-memoizer": { - "version": "0.53.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.208.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@opentelemetry/instrumentation-mongodb": { - "version": "0.61.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.208.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@opentelemetry/instrumentation-mongoose": { - "version": "0.55.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.208.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@opentelemetry/instrumentation-mysql": { - "version": "0.54.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.208.0", - "@types/mysql": "2.15.27" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@opentelemetry/instrumentation-mysql2": { - "version": "0.55.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.208.0", - "@opentelemetry/semantic-conventions": "^1.33.0", - "@opentelemetry/sql-common": "^0.41.2" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@opentelemetry/instrumentation-pg": { - "version": "0.61.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.208.0", - "@opentelemetry/semantic-conventions": "^1.34.0", - "@opentelemetry/sql-common": "^0.41.2", - "@types/pg": "8.15.6", - "@types/pg-pool": "2.0.6" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@opentelemetry/instrumentation-redis": { - "version": "0.57.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.208.0", - "@opentelemetry/redis-common": "^0.38.2", - "@opentelemetry/semantic-conventions": "^1.27.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@opentelemetry/instrumentation-tedious": { - "version": "0.27.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.208.0", - "@types/tedious": "^4.0.14" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@opentelemetry/instrumentation-undici": { - "version": "0.19.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.208.0", - "@opentelemetry/semantic-conventions": "^1.24.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.7.0" - } - }, - "node_modules/@opentelemetry/redis-common": { - "version": "0.38.3", - "license": "Apache-2.0", - "engines": { - "node": "^18.19.0 || >=20.6.0" - } - }, - "node_modules/@opentelemetry/resources": { - "version": "2.7.1", - "license": "Apache-2.0", - "peer": true, - "dependencies": { - "@opentelemetry/core": "2.7.1", - "@opentelemetry/semantic-conventions": "^1.29.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.3.0 <1.10.0" - } - }, - "node_modules/@opentelemetry/sdk-trace-base": { - "version": "2.7.1", - "license": "Apache-2.0", - "peer": true, - "dependencies": { - "@opentelemetry/core": "2.7.1", - "@opentelemetry/resources": "2.7.1", - "@opentelemetry/semantic-conventions": "^1.29.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.3.0 <1.10.0" - } - }, - "node_modules/@opentelemetry/semantic-conventions": { - "version": "1.40.0", - "license": "Apache-2.0", - "peer": true, - "engines": { - "node": ">=14" - } - }, - "node_modules/@opentelemetry/sql-common": { - "version": "0.41.2", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "^2.0.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.1.0" - } - }, - "node_modules/@prisma/instrumentation": { - "version": "6.19.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": ">=0.52.0 <1" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.8" - } - }, - "node_modules/@sentry-internal/browser-utils": { - "version": "10.50.0", - "license": "MIT", - "dependencies": { - "@sentry/core": "10.50.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@sentry-internal/feedback": { - "version": "10.50.0", - "license": "MIT", - "dependencies": { - "@sentry/core": "10.50.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@sentry-internal/replay": { - "version": "10.50.0", - "license": "MIT", - "dependencies": { - "@sentry-internal/browser-utils": "10.50.0", - "@sentry/core": "10.50.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@sentry-internal/replay-canvas": { - "version": "10.50.0", - "license": "MIT", - "dependencies": { - "@sentry-internal/replay": "10.50.0", - "@sentry/core": "10.50.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@sentry/browser": { - "version": "10.50.0", - "license": "MIT", - "dependencies": { - "@sentry-internal/browser-utils": "10.50.0", - "@sentry-internal/feedback": "10.50.0", - "@sentry-internal/replay": "10.50.0", - "@sentry-internal/replay-canvas": "10.50.0", - "@sentry/core": "10.50.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@sentry/core": { - "version": "10.50.0", - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/@sentry/electron": { - "version": "7.13.0", - "license": "MIT", - "dependencies": { - "@sentry/browser": "10.50.0", - "@sentry/core": "10.50.0", - "@sentry/node": "10.50.0" - }, - "peerDependencies": { - "@sentry/node-native": "10.50.0" - }, - "peerDependenciesMeta": { - "@sentry/node-native": { - "optional": true - } - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/api-logs": { - "version": "0.214.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/api": "^1.3.0" - }, - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/core": { - "version": "2.6.1", - "license": "Apache-2.0", - "peer": true, - "dependencies": { - "@opentelemetry/semantic-conventions": "^1.29.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.10.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/instrumentation": { - "version": "0.214.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/api-logs": "0.214.0", - "import-in-the-middle": "^3.0.0", - "require-in-the-middle": "^8.0.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/instrumentation-amqplib": { - "version": "0.61.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.214.0", - "@opentelemetry/semantic-conventions": "^1.33.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/instrumentation-connect": { - "version": "0.57.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.214.0", - "@opentelemetry/semantic-conventions": "^1.27.0", - "@types/connect": "3.4.38" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/instrumentation-dataloader": { - "version": "0.31.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.214.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/instrumentation-fs": { - "version": "0.33.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.214.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/instrumentation-generic-pool": { - "version": "0.57.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.214.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/instrumentation-graphql": { - "version": "0.62.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.214.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/instrumentation-hapi": { - "version": "0.60.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.214.0", - "@opentelemetry/semantic-conventions": "^1.27.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/instrumentation-http": { - "version": "0.214.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "2.6.1", - "@opentelemetry/instrumentation": "0.214.0", - "@opentelemetry/semantic-conventions": "^1.29.0", - "forwarded-parse": "2.1.2" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/instrumentation-ioredis": { - "version": "0.62.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.214.0", - "@opentelemetry/redis-common": "^0.38.2", - "@opentelemetry/semantic-conventions": "^1.33.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/instrumentation-kafkajs": { - "version": "0.23.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.214.0", - "@opentelemetry/semantic-conventions": "^1.30.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/instrumentation-knex": { - "version": "0.58.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.214.0", - "@opentelemetry/semantic-conventions": "^1.33.1" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/instrumentation-koa": { - "version": "0.62.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.214.0", - "@opentelemetry/semantic-conventions": "^1.36.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.9.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/instrumentation-lru-memoizer": { - "version": "0.58.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.214.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/instrumentation-mongodb": { - "version": "0.67.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.214.0", - "@opentelemetry/semantic-conventions": "^1.33.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/instrumentation-mongoose": { - "version": "0.60.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.214.0", - "@opentelemetry/semantic-conventions": "^1.33.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/instrumentation-mysql": { - "version": "0.60.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.214.0", - "@opentelemetry/semantic-conventions": "^1.33.0", - "@types/mysql": "2.15.27" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/instrumentation-mysql2": { - "version": "0.60.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.214.0", - "@opentelemetry/semantic-conventions": "^1.33.0", - "@opentelemetry/sql-common": "^0.41.2" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/instrumentation-pg": { - "version": "0.66.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.214.0", - "@opentelemetry/semantic-conventions": "^1.34.0", - "@opentelemetry/sql-common": "^0.41.2", - "@types/pg": "8.15.6", - "@types/pg-pool": "2.0.7" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/instrumentation-redis": { - "version": "0.62.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.214.0", - "@opentelemetry/redis-common": "^0.38.2", - "@opentelemetry/semantic-conventions": "^1.27.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@sentry/electron/node_modules/@opentelemetry/instrumentation-tedious": { - "version": "0.33.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.214.0", - "@opentelemetry/semantic-conventions": "^1.33.0", - "@types/tedious": "^4.0.14" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@sentry/electron/node_modules/@prisma/instrumentation": { - "version": "7.6.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/instrumentation": "^0.207.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.8" - } - }, - "node_modules/@sentry/electron/node_modules/@prisma/instrumentation/node_modules/@opentelemetry/api-logs": { - "version": "0.207.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/api": "^1.3.0" - }, - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/@sentry/electron/node_modules/@prisma/instrumentation/node_modules/@opentelemetry/instrumentation": { - "version": "0.207.0", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/api-logs": "0.207.0", - "import-in-the-middle": "^2.0.0", - "require-in-the-middle": "^8.0.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.3.0" - } - }, - "node_modules/@sentry/electron/node_modules/@prisma/instrumentation/node_modules/import-in-the-middle": { - "version": "2.0.6", - "license": "Apache-2.0", - "dependencies": { - "acorn": "^8.15.0", - "acorn-import-attributes": "^1.9.5", - "cjs-module-lexer": "^2.2.0", - "module-details-from-path": "^1.0.4" - } - }, - "node_modules/@sentry/electron/node_modules/@sentry/node": { - "version": "10.50.0", - "license": "MIT", - "dependencies": { - "@fastify/otel": "0.18.0", - "@opentelemetry/api": "^1.9.1", - "@opentelemetry/core": "^2.6.1", - "@opentelemetry/instrumentation": "^0.214.0", - "@opentelemetry/instrumentation-amqplib": "0.61.0", - "@opentelemetry/instrumentation-connect": "0.57.0", - "@opentelemetry/instrumentation-dataloader": "0.31.0", - "@opentelemetry/instrumentation-fs": "0.33.0", - "@opentelemetry/instrumentation-generic-pool": "0.57.0", - "@opentelemetry/instrumentation-graphql": "0.62.0", - "@opentelemetry/instrumentation-hapi": "0.60.0", - "@opentelemetry/instrumentation-http": "0.214.0", - "@opentelemetry/instrumentation-ioredis": "0.62.0", - "@opentelemetry/instrumentation-kafkajs": "0.23.0", - "@opentelemetry/instrumentation-knex": "0.58.0", - "@opentelemetry/instrumentation-koa": "0.62.0", - "@opentelemetry/instrumentation-lru-memoizer": "0.58.0", - "@opentelemetry/instrumentation-mongodb": "0.67.0", - "@opentelemetry/instrumentation-mongoose": "0.60.0", - "@opentelemetry/instrumentation-mysql": "0.60.0", - "@opentelemetry/instrumentation-mysql2": "0.60.0", - "@opentelemetry/instrumentation-pg": "0.66.0", - "@opentelemetry/instrumentation-redis": "0.62.0", - "@opentelemetry/instrumentation-tedious": "0.33.0", - "@opentelemetry/sdk-trace-base": "^2.6.1", - "@opentelemetry/semantic-conventions": "^1.40.0", - "@prisma/instrumentation": "7.6.0", - "@sentry/core": "10.50.0", - "@sentry/node-core": "10.50.0", - "@sentry/opentelemetry": "10.50.0", - "import-in-the-middle": "^3.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@sentry/electron/node_modules/@sentry/node-core": { - "version": "10.50.0", - "license": "MIT", - "dependencies": { - "@sentry/core": "10.50.0", - "@sentry/opentelemetry": "10.50.0", - "import-in-the-middle": "^3.0.0" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.9.0", - "@opentelemetry/core": "^1.30.1 || ^2.1.0", - "@opentelemetry/exporter-trace-otlp-http": ">=0.57.0 <1", - "@opentelemetry/instrumentation": ">=0.57.1 <1", - "@opentelemetry/sdk-trace-base": "^1.30.1 || ^2.1.0", - "@opentelemetry/semantic-conventions": "^1.39.0" - }, - "peerDependenciesMeta": { - "@opentelemetry/api": { - "optional": true - }, - "@opentelemetry/core": { - "optional": true - }, - "@opentelemetry/exporter-trace-otlp-http": { - "optional": true - }, - "@opentelemetry/instrumentation": { - "optional": true - }, - "@opentelemetry/sdk-trace-base": { - "optional": true - }, - "@opentelemetry/semantic-conventions": { - "optional": true - } - } - }, - "node_modules/@sentry/electron/node_modules/@sentry/opentelemetry": { - "version": "10.50.0", - "license": "MIT", - "dependencies": { - "@sentry/core": "10.50.0" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.9.0", - "@opentelemetry/core": "^1.30.1 || ^2.1.0", - "@opentelemetry/sdk-trace-base": "^1.30.1 || ^2.1.0", - "@opentelemetry/semantic-conventions": "^1.39.0" - } - }, - "node_modules/@sentry/electron/node_modules/@types/pg-pool": { - "version": "2.0.7", - "license": "MIT", - "dependencies": { - "@types/pg": "*" - } - }, - "node_modules/@sentry/electron/node_modules/import-in-the-middle": { - "version": "3.0.1", - "license": "Apache-2.0", - "dependencies": { - "acorn": "^8.15.0", - "acorn-import-attributes": "^1.9.5", - "cjs-module-lexer": "^2.2.0", - "module-details-from-path": "^1.0.4" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@sentry/node": { - "version": "10.29.0", - "license": "MIT", - "dependencies": { - "@opentelemetry/api": "^1.9.0", - "@opentelemetry/context-async-hooks": "^2.2.0", - "@opentelemetry/core": "^2.2.0", - "@opentelemetry/instrumentation": "^0.208.0", - "@opentelemetry/instrumentation-amqplib": "0.55.0", - "@opentelemetry/instrumentation-connect": "0.52.0", - "@opentelemetry/instrumentation-dataloader": "0.26.0", - "@opentelemetry/instrumentation-express": "0.57.0", - "@opentelemetry/instrumentation-fs": "0.28.0", - "@opentelemetry/instrumentation-generic-pool": "0.52.0", - "@opentelemetry/instrumentation-graphql": "0.56.0", - "@opentelemetry/instrumentation-hapi": "0.55.0", - "@opentelemetry/instrumentation-http": "0.208.0", - "@opentelemetry/instrumentation-ioredis": "0.56.0", - "@opentelemetry/instrumentation-kafkajs": "0.18.0", - "@opentelemetry/instrumentation-knex": "0.53.0", - "@opentelemetry/instrumentation-koa": "0.57.0", - "@opentelemetry/instrumentation-lru-memoizer": "0.53.0", - "@opentelemetry/instrumentation-mongodb": "0.61.0", - "@opentelemetry/instrumentation-mongoose": "0.55.0", - "@opentelemetry/instrumentation-mysql": "0.54.0", - "@opentelemetry/instrumentation-mysql2": "0.55.0", - "@opentelemetry/instrumentation-pg": "0.61.0", - "@opentelemetry/instrumentation-redis": "0.57.0", - "@opentelemetry/instrumentation-tedious": "0.27.0", - "@opentelemetry/instrumentation-undici": "0.19.0", - "@opentelemetry/resources": "^2.2.0", - "@opentelemetry/sdk-trace-base": "^2.2.0", - "@opentelemetry/semantic-conventions": "^1.37.0", - "@prisma/instrumentation": "6.19.0", - "@sentry/core": "10.29.0", - "@sentry/node-core": "10.29.0", - "@sentry/opentelemetry": "10.29.0", - "import-in-the-middle": "^2", - "minimatch": "^9.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@sentry/node-core": { - "version": "10.29.0", - "license": "MIT", - "dependencies": { - "@apm-js-collab/tracing-hooks": "^0.3.1", - "@sentry/core": "10.29.0", - "@sentry/opentelemetry": "10.29.0", - "import-in-the-middle": "^2" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.9.0", - "@opentelemetry/context-async-hooks": "^1.30.1 || ^2.1.0 || ^2.2.0", - "@opentelemetry/core": "^1.30.1 || ^2.1.0 || ^2.2.0", - "@opentelemetry/instrumentation": ">=0.57.1 <1", - "@opentelemetry/resources": "^1.30.1 || ^2.1.0 || ^2.2.0", - "@opentelemetry/sdk-trace-base": "^1.30.1 || ^2.1.0 || ^2.2.0", - "@opentelemetry/semantic-conventions": "^1.37.0" - } - }, - "node_modules/@sentry/node-core/node_modules/@sentry/core": { - "version": "10.29.0", - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/@sentry/node/node_modules/@sentry/core": { - "version": "10.29.0", - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/@sentry/node/node_modules/balanced-match": { - "version": "1.0.2", - "license": "MIT" - }, - "node_modules/@sentry/node/node_modules/brace-expansion": { - "version": "2.1.0", - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0" - } - }, - "node_modules/@sentry/node/node_modules/minimatch": { - "version": "9.0.9", - "license": "ISC", - "dependencies": { - "brace-expansion": "^2.0.2" - }, - "engines": { - "node": ">=16 || 14 >=14.17" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/@sentry/opentelemetry": { - "version": "10.29.0", - "license": "MIT", - "dependencies": { - "@sentry/core": "10.29.0" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.9.0", - "@opentelemetry/context-async-hooks": "^1.30.1 || ^2.1.0 || ^2.2.0", - "@opentelemetry/core": "^1.30.1 || ^2.1.0 || ^2.2.0", - "@opentelemetry/sdk-trace-base": "^1.30.1 || ^2.1.0 || ^2.2.0", - "@opentelemetry/semantic-conventions": "^1.37.0" - } - }, - "node_modules/@sentry/opentelemetry/node_modules/@sentry/core": { - "version": "10.29.0", - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/@sindresorhus/is": { - "version": "4.6.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sindresorhus/is?sponsor=1" - } - }, - "node_modules/@szmarczak/http-timer": { - "version": "4.0.6", - "dev": true, - "license": "MIT", - "dependencies": { - "defer-to-connect": "^2.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@tootallnate/once": { - "version": "2.0.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 10" - } - }, - "node_modules/@types/appdmg": { - "version": "0.5.5", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/cacheable-request": { - "version": "6.0.3", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/http-cache-semantics": "*", - "@types/keyv": "^3.1.4", - "@types/node": "*", - "@types/responselike": "^1.0.0" - } - }, - "node_modules/@types/connect": { - "version": "3.4.38", - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/eslint": { - "version": "9.6.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "*", - "@types/json-schema": "*" - } - }, - "node_modules/@types/eslint-scope": { - "version": "3.7.7", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/eslint": "*", - "@types/estree": "*" - } - }, - "node_modules/@types/estree": { - "version": "1.0.9", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/fs-extra": { - "version": "9.0.13", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/http-cache-semantics": { - "version": "4.2.0", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/json-schema": { - "version": "7.0.15", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/keyv": { - "version": "3.1.4", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/mute-stream": { - "version": "0.0.4", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/mysql": { - "version": "2.15.27", - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/node": { - "version": "22.19.17", - "license": "MIT", - "dependencies": { - "undici-types": "~6.21.0" - } - }, - "node_modules/@types/pg": { - "version": "8.15.6", - "license": "MIT", - "dependencies": { - "@types/node": "*", - "pg-protocol": "*", - "pg-types": "^2.2.0" - } - }, - "node_modules/@types/pg-pool": { - "version": "2.0.6", - "license": "MIT", - "dependencies": { - "@types/pg": "*" - } - }, - "node_modules/@types/responselike": { - "version": "1.0.3", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/tedious": { - "version": "4.0.14", - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/wrap-ansi": { - "version": "3.0.0", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/yauzl": { - "version": "2.10.3", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@vscode/sudo-prompt": { - "version": "9.3.2", - "dev": true, - "license": "MIT" - }, - "node_modules/@webassemblyjs/ast": { - "version": "1.14.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@webassemblyjs/helper-numbers": "1.13.2", - "@webassemblyjs/helper-wasm-bytecode": "1.13.2" - } - }, - "node_modules/@webassemblyjs/floating-point-hex-parser": { - "version": "1.13.2", - "dev": true, - "license": "MIT" - }, - "node_modules/@webassemblyjs/helper-api-error": { - "version": "1.13.2", - "dev": true, - "license": "MIT" - }, - "node_modules/@webassemblyjs/helper-buffer": { - "version": "1.14.1", - "dev": true, - "license": "MIT" - }, - "node_modules/@webassemblyjs/helper-numbers": { - "version": "1.13.2", - "dev": true, - "license": "MIT", - "dependencies": { - "@webassemblyjs/floating-point-hex-parser": "1.13.2", - "@webassemblyjs/helper-api-error": "1.13.2", - "@xtuc/long": "4.2.2" - } - }, - "node_modules/@webassemblyjs/helper-wasm-bytecode": { - "version": "1.13.2", - "dev": true, - "license": "MIT" - }, - "node_modules/@webassemblyjs/helper-wasm-section": { - "version": "1.14.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@webassemblyjs/ast": "1.14.1", - "@webassemblyjs/helper-buffer": "1.14.1", - "@webassemblyjs/helper-wasm-bytecode": "1.13.2", - "@webassemblyjs/wasm-gen": "1.14.1" - } - }, - "node_modules/@webassemblyjs/ieee754": { - "version": "1.13.2", - "dev": true, - "license": "MIT", - "dependencies": { - "@xtuc/ieee754": "^1.2.0" - } - }, - "node_modules/@webassemblyjs/leb128": { - "version": "1.13.2", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@xtuc/long": "4.2.2" - } - }, - "node_modules/@webassemblyjs/utf8": { - "version": "1.13.2", - "dev": true, - "license": "MIT" - }, - "node_modules/@webassemblyjs/wasm-edit": { - "version": "1.14.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@webassemblyjs/ast": "1.14.1", - "@webassemblyjs/helper-buffer": "1.14.1", - "@webassemblyjs/helper-wasm-bytecode": "1.13.2", - "@webassemblyjs/helper-wasm-section": "1.14.1", - "@webassemblyjs/wasm-gen": "1.14.1", - "@webassemblyjs/wasm-opt": "1.14.1", - "@webassemblyjs/wasm-parser": "1.14.1", - "@webassemblyjs/wast-printer": "1.14.1" - } - }, - "node_modules/@webassemblyjs/wasm-gen": { - "version": "1.14.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@webassemblyjs/ast": "1.14.1", - "@webassemblyjs/helper-wasm-bytecode": "1.13.2", - "@webassemblyjs/ieee754": "1.13.2", - "@webassemblyjs/leb128": "1.13.2", - "@webassemblyjs/utf8": "1.13.2" - } - }, - "node_modules/@webassemblyjs/wasm-opt": { - "version": "1.14.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@webassemblyjs/ast": "1.14.1", - "@webassemblyjs/helper-buffer": "1.14.1", - "@webassemblyjs/wasm-gen": "1.14.1", - "@webassemblyjs/wasm-parser": "1.14.1" - } - }, - "node_modules/@webassemblyjs/wasm-parser": { - "version": "1.14.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@webassemblyjs/ast": "1.14.1", - "@webassemblyjs/helper-api-error": "1.13.2", - "@webassemblyjs/helper-wasm-bytecode": "1.13.2", - "@webassemblyjs/ieee754": "1.13.2", - "@webassemblyjs/leb128": "1.13.2", - "@webassemblyjs/utf8": "1.13.2" - } - }, - "node_modules/@webassemblyjs/wast-printer": { - "version": "1.14.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@webassemblyjs/ast": "1.14.1", - "@xtuc/long": "4.2.2" - } - }, - "node_modules/@xmldom/xmldom": { - "version": "0.9.10", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=14.6" - } - }, - "node_modules/@xtuc/ieee754": { - "version": "1.2.0", - "dev": true, - "license": "BSD-3-Clause" - }, - "node_modules/@xtuc/long": { - "version": "4.2.2", - "dev": true, - "license": "Apache-2.0" - }, - "node_modules/abbrev": { - "version": "1.1.1", - "dev": true, - "license": "ISC" - }, - "node_modules/acorn": { - "version": "8.16.0", - "license": "MIT", - "peer": true, - "bin": { - "acorn": "bin/acorn" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/acorn-import-attributes": { - "version": "1.9.5", - "license": "MIT", - "peerDependencies": { - "acorn": "^8" - } - }, - "node_modules/acorn-import-phases": { - "version": "1.0.4", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10.13.0" - }, - "peerDependencies": { - "acorn": "^8.14.0" - } - }, - "node_modules/agent-base": { - "version": "6.0.2", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "4" - }, - "engines": { - "node": ">= 6.0.0" - } - }, - "node_modules/agentkeepalive": { - "version": "4.6.0", - "dev": true, - "license": "MIT", - "dependencies": { - "humanize-ms": "^1.2.1" - }, - "engines": { - "node": ">= 8.0.0" - } - }, - "node_modules/aggregate-error": { - "version": "3.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "clean-stack": "^2.0.0", - "indent-string": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/ajv": { - "version": "8.20.0", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "fast-deep-equal": "^3.1.3", - "fast-uri": "^3.0.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/ajv-formats": { - "version": "2.1.1", - "dev": true, - "license": "MIT", - "dependencies": { - "ajv": "^8.0.0" - }, - "peerDependencies": { - "ajv": "^8.0.0" - }, - "peerDependenciesMeta": { - "ajv": { - "optional": true - } - } - }, - "node_modules/ajv-keywords": { - "version": "5.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.3" - }, - "peerDependencies": { - "ajv": "^8.8.2" - } - }, - "node_modules/ansi-escapes": { - "version": "4.3.2", - "dev": true, - "license": "MIT", - "dependencies": { - "type-fest": "^0.21.3" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/ansi-regex": { - "version": "5.0.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/ansi-styles": { - "version": "4.3.0", - "dev": true, - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/appdmg": { - "version": "0.6.6", - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "dependencies": { - "async": "^1.4.2", - "ds-store": "^0.1.5", - "execa": "^1.0.0", - "fs-temp": "^1.0.0", - "fs-xattr": "^0.3.0", - "image-size": "^0.7.4", - "is-my-json-valid": "^2.20.0", - "minimist": "^1.1.3", - "parse-color": "^1.0.0", - "path-exists": "^4.0.0", - "repeat-string": "^1.5.4" - }, - "bin": { - "appdmg": "bin/appdmg.js" - }, - "engines": { - "node": ">=8.5" - } - }, - "node_modules/async": { - "version": "1.5.2", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/at-least-node": { - "version": "1.0.0", - "dev": true, - "license": "ISC", - "engines": { - "node": ">= 4.0.0" - } - }, - "node_modules/author-regex": { - "version": "1.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.8" - } - }, - "node_modules/balanced-match": { - "version": "4.0.4", - "license": "MIT", - "engines": { - "node": "18 || 20 || >=22" - } - }, - "node_modules/base32-encode": { - "version": "1.2.0", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "to-data-view": "^1.1.0" - } - }, - "node_modules/base64-js": { - "version": "1.5.1", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/baseline-browser-mapping": { - "version": "2.10.27", - "dev": true, - "license": "Apache-2.0", - "bin": { - "baseline-browser-mapping": "dist/cli.cjs" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/better-sqlite3": { - "version": "12.11.1", - "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.11.1.tgz", - "integrity": "sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA==", - "hasInstallScript": true, - "license": "MIT", - "dependencies": { - "bindings": "^1.5.0", - "prebuild-install": "^7.1.1" - }, - "engines": { - "node": "20.x || 22.x || 23.x || 24.x || 25.x || 26.x" - } - }, - "node_modules/bindings": { - "version": "1.5.0", - "license": "MIT", - "dependencies": { - "file-uri-to-path": "1.0.0" - } - }, - "node_modules/bl": { - "version": "4.1.0", - "license": "MIT", - "dependencies": { - "buffer": "^5.5.0", - "inherits": "^2.0.4", - "readable-stream": "^3.4.0" - } - }, - "node_modules/bluebird": { - "version": "3.7.2", - "dev": true, - "license": "MIT" - }, - "node_modules/boolean": { - "version": "3.2.0", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/bplist-creator": { - "version": "0.0.8", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "stream-buffers": "~2.2.0" - } - }, - "node_modules/brace-expansion": { - "version": "5.0.5", - "license": "MIT", - "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "18 || 20 || >=22" - } - }, - "node_modules/braces": { - "version": "3.0.3", - "dev": true, - "license": "MIT", - "dependencies": { - "fill-range": "^7.1.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/browserslist": { - "version": "4.28.2", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "peer": true, - "dependencies": { - "baseline-browser-mapping": "^2.10.12", - "caniuse-lite": "^1.0.30001782", - "electron-to-chromium": "^1.5.328", - "node-releases": "^2.0.36", - "update-browserslist-db": "^1.2.3" - }, - "bin": { - "browserslist": "cli.js" - }, - "engines": { - "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" - } - }, - "node_modules/buffer": { - "version": "5.7.1", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.1.13" - } - }, - "node_modules/buffer-crc32": { - "version": "0.2.13", - "dev": true, - "license": "MIT", - "engines": { - "node": "*" - } - }, - "node_modules/buffer-from": { - "version": "1.1.2", - "dev": true, - "license": "MIT" - }, - "node_modules/cacache": { - "version": "16.1.3", - "dev": true, - "license": "ISC", - "dependencies": { - "@npmcli/fs": "^2.1.0", - "@npmcli/move-file": "^2.0.0", - "chownr": "^2.0.0", - "fs-minipass": "^2.1.0", - "glob": "^8.0.1", - "infer-owner": "^1.0.4", - "lru-cache": "^7.7.1", - "minipass": "^3.1.6", - "minipass-collect": "^1.0.2", - "minipass-flush": "^1.0.5", - "minipass-pipeline": "^1.2.4", - "mkdirp": "^1.0.4", - "p-map": "^4.0.0", - "promise-inflight": "^1.0.1", - "rimraf": "^3.0.2", - "ssri": "^9.0.0", - "tar": "^6.1.11", - "unique-filename": "^2.0.0" - }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } - }, - "node_modules/cacache/node_modules/balanced-match": { - "version": "1.0.2", - "dev": true, - "license": "MIT" - }, - "node_modules/cacache/node_modules/brace-expansion": { - "version": "2.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0" - } - }, - "node_modules/cacache/node_modules/glob": { - "version": "8.1.0", - "dev": true, - "license": "ISC", - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^5.0.1", - "once": "^1.3.0" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/cacache/node_modules/minimatch": { - "version": "5.1.9", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^2.0.1" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/cacache/node_modules/minipass": { - "version": "3.3.6", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/cacheable-lookup": { - "version": "5.0.4", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10.6.0" - } - }, - "node_modules/cacheable-request": { - "version": "7.0.4", - "dev": true, - "license": "MIT", - "dependencies": { - "clone-response": "^1.0.2", - "get-stream": "^5.1.0", - "http-cache-semantics": "^4.0.0", - "keyv": "^4.0.0", - "lowercase-keys": "^2.0.0", - "normalize-url": "^6.0.1", - "responselike": "^2.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/cacheable-request/node_modules/get-stream": { - "version": "5.2.0", - "dev": true, - "license": "MIT", - "dependencies": { - "pump": "^3.0.0" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/caniuse-lite": { - "version": "1.0.30001792", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/caniuse-lite" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "CC-BY-4.0" - }, - "node_modules/chalk": { - "version": "4.1.2", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/chardet": { - "version": "0.7.0", - "dev": true, - "license": "MIT" - }, - "node_modules/chownr": { - "version": "2.0.0", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=10" - } - }, - "node_modules/chrome-trace-event": { - "version": "1.0.4", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.0" - } - }, - "node_modules/cjs-module-lexer": { - "version": "2.2.0", - "license": "MIT" - }, - "node_modules/clean-stack": { - "version": "2.2.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/cli-cursor": { - "version": "4.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "restore-cursor": "^4.0.0" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/cli-spinners": { - "version": "2.9.2", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/cli-truncate": { - "version": "4.0.0", - "license": "MIT", - "dependencies": { - "slice-ansi": "^5.0.0", - "string-width": "^7.0.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/cli-width": { - "version": "4.1.0", - "dev": true, - "license": "ISC", - "engines": { - "node": ">= 12" - } - }, - "node_modules/cliui": { - "version": "8.0.1", - "dev": true, - "license": "ISC", - "dependencies": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.1", - "wrap-ansi": "^7.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/cliui/node_modules/emoji-regex": { - "version": "8.0.0", - "dev": true, - "license": "MIT" - }, - "node_modules/cliui/node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/cliui/node_modules/string-width": { - "version": "4.2.3", - "dev": true, - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/cliui/node_modules/wrap-ansi": { - "version": "7.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/clone": { - "version": "1.0.4", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.8" - } - }, - "node_modules/clone-response": { - "version": "1.0.3", - "dev": true, - "license": "MIT", - "dependencies": { - "mimic-response": "^1.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/color-convert": { - "version": "2.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/color-name": { - "version": "1.1.4", - "dev": true, - "license": "MIT" - }, - "node_modules/colorette": { - "version": "2.0.20", - "dev": true, - "license": "MIT" - }, - "node_modules/commander": { - "version": "11.1.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=16" - } - }, - "node_modules/compare-version": { - "version": "0.1.2", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/concat-map": { - "version": "0.0.1", - "dev": true, - "license": "MIT" - }, - "node_modules/cross-dirname": { - "version": "0.1.0", - "dev": true, - "license": "MIT" - }, - "node_modules/cross-spawn": { - "version": "7.0.6", - "license": "MIT", - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/cross-zip": { - "version": "4.0.1", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "engines": { - "node": ">=12.10" - } - }, - "node_modules/d": { - "version": "1.0.2", - "license": "ISC", - "dependencies": { - "es5-ext": "^0.10.64", - "type": "^2.7.2" - }, - "engines": { - "node": ">=0.12" - } - }, - "node_modules/debug": { - "version": "4.4.3", - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/decompress-response": { - "version": "6.0.0", - "license": "MIT", - "dependencies": { - "mimic-response": "^3.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/decompress-response/node_modules/mimic-response": { - "version": "3.1.0", - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/deep-extend": { - "version": "0.6.0", - "license": "MIT", - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/default-shell": { - "version": "2.2.0", - "license": "MIT", - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/defaults": { - "version": "1.0.4", - "dev": true, - "license": "MIT", - "dependencies": { - "clone": "^1.0.2" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/defer-to-connect": { - "version": "2.0.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - } - }, - "node_modules/define-data-property": { - "version": "1.1.4", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "es-define-property": "^1.0.0", - "es-errors": "^1.3.0", - "gopd": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/define-properties": { - "version": "1.2.1", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "define-data-property": "^1.0.1", - "has-property-descriptors": "^1.0.0", - "object-keys": "^1.1.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/detect-libc": { - "version": "2.1.2", - "license": "Apache-2.0", - "engines": { - "node": ">=8" - } - }, - "node_modules/detect-node": { - "version": "2.1.0", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/dir-compare": { - "version": "4.2.0", - "dev": true, - "license": "MIT", - "dependencies": { - "minimatch": "^3.0.5", - "p-limit": "^3.1.0 " - } - }, - "node_modules/dir-compare/node_modules/balanced-match": { - "version": "1.0.2", - "dev": true, - "license": "MIT" - }, - "node_modules/dir-compare/node_modules/brace-expansion": { - "version": "1.1.14", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/dir-compare/node_modules/minimatch": { - "version": "3.1.5", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/ds-store": { - "version": "0.1.6", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "bplist-creator": "~0.0.3", - "macos-alias": "~0.2.5", - "tn1150": "^0.1.0" - } - }, - "node_modules/eastasianwidth": { - "version": "0.2.0", - "dev": true, - "license": "MIT" - }, - "node_modules/electron": { - "version": "42.0.1", - "resolved": "https://registry.npmjs.org/electron/-/electron-42.0.1.tgz", - "integrity": "sha512-d8HnycE970DGESe91Nj30eonFBUcAI9EZ1TwUGJVzSAnJZdh0BkFEinAXjdklvDYst+bVDc8HsksCuqVLrnqdg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@electron/get": "^5.0.0", - "@types/node": "^24.9.0", - "extract-zip": "^2.0.1" - }, - "bin": { - "electron": "cli.js", - "install-electron": "install.js" - }, - "engines": { - "node": ">= 22.12.0" - } - }, - "node_modules/electron-context-menu": { - "version": "4.1.2", - "license": "MIT", - "dependencies": { - "cli-truncate": "^4.0.0", - "electron-dl": "^4.0.0", - "electron-is-dev": "^3.0.1" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/electron-dl": { - "version": "4.0.0", - "license": "MIT", - "dependencies": { - "ext-name": "^5.0.0", - "pupa": "^3.1.0", - "unused-filename": "^4.0.1" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/electron-installer-common": { - "version": "0.10.4", - "dev": true, - "license": "Apache-2.0", - "optional": true, - "dependencies": { - "@electron/asar": "^3.2.5", - "@malept/cross-spawn-promise": "^1.0.0", - "debug": "^4.1.1", - "fs-extra": "^9.0.0", - "glob": "^7.1.4", - "lodash": "^4.17.15", - "parse-author": "^2.0.0", - "semver": "^7.1.1", - "tmp-promise": "^3.0.2" - }, - "engines": { - "node": ">= 10.0.0" - }, - "funding": { - "url": "https://github.com/electron-userland/electron-installer-common?sponsor=1" - }, - "optionalDependencies": { - "@types/fs-extra": "^9.0.1" - } - }, - "node_modules/electron-installer-common/node_modules/@electron/asar": { - "version": "3.4.1", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "commander": "^5.0.0", - "glob": "^7.1.6", - "minimatch": "^3.0.4" - }, - "bin": { - "asar": "bin/asar.js" - }, - "engines": { - "node": ">=10.12.0" - } - }, - "node_modules/electron-installer-common/node_modules/@malept/cross-spawn-promise": { - "version": "1.1.1", - "dev": true, - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/malept" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/subscription/pkg/npm-.malept-cross-spawn-promise?utm_medium=referral&utm_source=npm_fund" - } - ], - "license": "Apache-2.0", - "optional": true, - "dependencies": { - "cross-spawn": "^7.0.1" - }, - "engines": { - "node": ">= 10" - } - }, - "node_modules/electron-installer-common/node_modules/balanced-match": { - "version": "1.0.2", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/electron-installer-common/node_modules/brace-expansion": { - "version": "1.1.14", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/electron-installer-common/node_modules/commander": { - "version": "5.1.0", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">= 6" - } - }, - "node_modules/electron-installer-common/node_modules/fs-extra": { - "version": "9.1.0", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "at-least-node": "^1.0.0", - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/electron-installer-common/node_modules/glob": { - "version": "7.2.3", - "dev": true, - "license": "ISC", - "optional": true, - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/electron-installer-common/node_modules/minimatch": { - "version": "3.1.5", - "dev": true, - "license": "ISC", - "optional": true, - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/electron-installer-debian": { - "version": "3.2.0", - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin", - "linux" - ], - "dependencies": { - "@malept/cross-spawn-promise": "^1.0.0", - "debug": "^4.1.1", - "electron-installer-common": "^0.10.2", - "fs-extra": "^9.0.0", - "get-folder-size": "^2.0.1", - "lodash": "^4.17.4", - "word-wrap": "^1.2.3", - "yargs": "^16.0.2" - }, - "bin": { - "electron-installer-debian": "src/cli.js" - }, - "engines": { - "node": ">= 10.0.0" - } - }, - "node_modules/electron-installer-debian/node_modules/@malept/cross-spawn-promise": { - "version": "1.1.1", - "dev": true, - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/malept" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/subscription/pkg/npm-.malept-cross-spawn-promise?utm_medium=referral&utm_source=npm_fund" - } - ], - "license": "Apache-2.0", - "optional": true, - "dependencies": { - "cross-spawn": "^7.0.1" - }, - "engines": { - "node": ">= 10" - } - }, - "node_modules/electron-installer-debian/node_modules/cliui": { - "version": "7.0.4", - "dev": true, - "license": "ISC", - "optional": true, - "dependencies": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.0", - "wrap-ansi": "^7.0.0" - } - }, - "node_modules/electron-installer-debian/node_modules/emoji-regex": { - "version": "8.0.0", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/electron-installer-debian/node_modules/fs-extra": { - "version": "9.1.0", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "at-least-node": "^1.0.0", - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/electron-installer-debian/node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/electron-installer-debian/node_modules/string-width": { - "version": "4.2.3", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/electron-installer-debian/node_modules/wrap-ansi": { - "version": "7.0.0", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/electron-installer-debian/node_modules/yargs": { - "version": "16.2.0", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "cliui": "^7.0.2", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.0", - "y18n": "^5.0.5", - "yargs-parser": "^20.2.2" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/electron-installer-debian/node_modules/yargs-parser": { - "version": "20.2.9", - "dev": true, - "license": "ISC", - "optional": true, - "engines": { - "node": ">=10" - } - }, - "node_modules/electron-installer-dmg": { - "version": "5.0.1", - "dev": true, - "license": "Apache-2.0", - "optional": true, - "dependencies": { - "@types/appdmg": "^0.5.5", - "debug": "^4.3.2", - "minimist": "^1.2.7" - }, - "bin": { - "electron-installer-dmg": "dist/electron-installer-dmg-bin.js" - }, - "engines": { - "node": ">= 16" - }, - "optionalDependencies": { - "appdmg": "^0.6.4" - } - }, - "node_modules/electron-installer-redhat": { - "version": "3.4.0", - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin", - "linux" - ], - "dependencies": { - "@malept/cross-spawn-promise": "^1.0.0", - "debug": "^4.1.1", - "electron-installer-common": "^0.10.2", - "fs-extra": "^9.0.0", - "lodash": "^4.17.15", - "word-wrap": "^1.2.3", - "yargs": "^16.0.2" - }, - "bin": { - "electron-installer-redhat": "src/cli.js" - }, - "engines": { - "node": ">= 10.0.0" - } - }, - "node_modules/electron-installer-redhat/node_modules/@malept/cross-spawn-promise": { - "version": "1.1.1", - "dev": true, - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/malept" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/subscription/pkg/npm-.malept-cross-spawn-promise?utm_medium=referral&utm_source=npm_fund" - } - ], - "license": "Apache-2.0", - "optional": true, - "dependencies": { - "cross-spawn": "^7.0.1" - }, - "engines": { - "node": ">= 10" - } - }, - "node_modules/electron-installer-redhat/node_modules/cliui": { - "version": "7.0.4", - "dev": true, - "license": "ISC", - "optional": true, - "dependencies": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.0", - "wrap-ansi": "^7.0.0" - } - }, - "node_modules/electron-installer-redhat/node_modules/emoji-regex": { - "version": "8.0.0", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/electron-installer-redhat/node_modules/fs-extra": { - "version": "9.1.0", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "at-least-node": "^1.0.0", - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/electron-installer-redhat/node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/electron-installer-redhat/node_modules/string-width": { - "version": "4.2.3", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/electron-installer-redhat/node_modules/wrap-ansi": { - "version": "7.0.0", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/electron-installer-redhat/node_modules/yargs": { - "version": "16.2.0", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "cliui": "^7.0.2", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.0", - "y18n": "^5.0.5", - "yargs-parser": "^20.2.2" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/electron-installer-redhat/node_modules/yargs-parser": { - "version": "20.2.9", - "dev": true, - "license": "ISC", - "optional": true, - "engines": { - "node": ">=10" - } - }, - "node_modules/electron-is-dev": { - "version": "3.0.1", - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/electron-squirrel-startup": { - "version": "1.0.1", - "license": "Apache-2.0", - "dependencies": { - "debug": "^2.2.0" - } - }, - "node_modules/electron-squirrel-startup/node_modules/debug": { - "version": "2.6.9", - "license": "MIT", - "dependencies": { - "ms": "2.0.0" - } - }, - "node_modules/electron-squirrel-startup/node_modules/ms": { - "version": "2.0.0", - "license": "MIT" - }, - "node_modules/electron-to-chromium": { - "version": "1.5.352", - "dev": true, - "license": "ISC" - }, - "node_modules/electron-winstaller": { - "version": "5.4.0", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@electron/asar": "^3.2.1", - "debug": "^4.1.1", - "fs-extra": "^7.0.1", - "lodash": "^4.17.21", - "temp": "^0.9.0" - }, - "engines": { - "node": ">=8.0.0" - }, - "optionalDependencies": { - "@electron/windows-sign": "^1.1.2" - } - }, - "node_modules/electron-winstaller/node_modules/@electron/asar": { - "version": "3.4.1", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "commander": "^5.0.0", - "glob": "^7.1.6", - "minimatch": "^3.0.4" - }, - "bin": { - "asar": "bin/asar.js" - }, - "engines": { - "node": ">=10.12.0" - } - }, - "node_modules/electron-winstaller/node_modules/balanced-match": { - "version": "1.0.2", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/electron-winstaller/node_modules/brace-expansion": { - "version": "1.1.14", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/electron-winstaller/node_modules/commander": { - "version": "5.1.0", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">= 6" - } - }, - "node_modules/electron-winstaller/node_modules/fs-extra": { - "version": "7.0.1", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "graceful-fs": "^4.1.2", - "jsonfile": "^4.0.0", - "universalify": "^0.1.0" - }, - "engines": { - "node": ">=6 <7 || >=8" - } - }, - "node_modules/electron-winstaller/node_modules/glob": { - "version": "7.2.3", - "dev": true, - "license": "ISC", - "optional": true, - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/electron-winstaller/node_modules/jsonfile": { - "version": "4.0.0", - "dev": true, - "license": "MIT", - "optional": true, - "optionalDependencies": { - "graceful-fs": "^4.1.6" - } - }, - "node_modules/electron-winstaller/node_modules/minimatch": { - "version": "3.1.5", - "dev": true, - "license": "ISC", - "optional": true, - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/electron-winstaller/node_modules/universalify": { - "version": "0.1.2", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">= 4.0.0" - } - }, - "node_modules/electron/node_modules/@electron/get": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/@electron/get/-/get-5.0.0.tgz", - "integrity": "sha512-pjoBpru1KdEtcExBnuHAP1cAc/5faoedw0hzJkL3o4/IJp7HNF1+fbrdxT3gMYRX2oJfvnA/WXeCTVQpYYxyJA==", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.1.1", - "env-paths": "^3.0.0", - "graceful-fs": "^4.2.11", - "progress": "^2.0.3", - "semver": "^7.6.3", - "sumchecker": "^3.0.1" - }, - "engines": { - "node": ">=22.12.0" - }, - "optionalDependencies": { - "undici": "^7.24.4" - } - }, - "node_modules/electron/node_modules/@types/node": { - "version": "24.12.2", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~7.16.0" - } - }, - "node_modules/electron/node_modules/env-paths": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz", - "integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/electron/node_modules/undici-types": { - "version": "7.16.0", - "dev": true, - "license": "MIT" - }, - "node_modules/emoji-regex": { - "version": "10.6.0", - "license": "MIT" - }, - "node_modules/encode-utf8": { - "version": "1.0.3", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/encoding": { - "version": "0.1.13", - "license": "MIT", - "peer": true, - "dependencies": { - "iconv-lite": "^0.6.2" - } - }, - "node_modules/end-of-stream": { - "version": "1.4.5", - "license": "MIT", - "dependencies": { - "once": "^1.4.0" - } - }, - "node_modules/enhanced-resolve": { - "version": "5.21.0", - "dev": true, - "license": "MIT", - "dependencies": { - "graceful-fs": "^4.2.4", - "tapable": "^2.3.3" - }, - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/env-paths": { - "version": "2.2.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/err-code": { - "version": "2.0.3", - "dev": true, - "license": "MIT" - }, - "node_modules/error-ex": { - "version": "1.3.4", - "dev": true, - "license": "MIT", - "dependencies": { - "is-arrayish": "^0.2.1" - } - }, - "node_modules/es-define-property": { - "version": "1.0.1", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-errors": { - "version": "1.3.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-module-lexer": { - "version": "2.1.0", - "dev": true, - "license": "MIT" - }, - "node_modules/es5-ext": { - "version": "0.10.64", - "hasInstallScript": true, - "license": "ISC", - "dependencies": { - "es6-iterator": "^2.0.3", - "es6-symbol": "^3.1.3", - "esniff": "^2.0.1", - "next-tick": "^1.1.0" - }, - "engines": { - "node": ">=0.10" - } - }, - "node_modules/es6-error": { - "version": "4.1.1", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/es6-iterator": { - "version": "2.0.3", - "license": "MIT", - "dependencies": { - "d": "1", - "es5-ext": "^0.10.35", - "es6-symbol": "^3.1.1" - } - }, - "node_modules/es6-symbol": { - "version": "3.1.4", - "license": "ISC", - "dependencies": { - "d": "^1.0.2", - "ext": "^1.7.0" - }, - "engines": { - "node": ">=0.12" - } - }, - "node_modules/es6-weak-map": { - "version": "2.0.3", - "license": "ISC", - "dependencies": { - "d": "1", - "es5-ext": "^0.10.46", - "es6-iterator": "^2.0.3", - "es6-symbol": "^3.1.1" - } - }, - "node_modules/escalade": { - "version": "3.2.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/escape-goat": { - "version": "4.0.0", - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/escape-string-regexp": { - "version": "4.0.0", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/eslint-scope": { - "version": "5.1.1", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "esrecurse": "^4.3.0", - "estraverse": "^4.1.1" - }, - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/esniff": { - "version": "2.0.1", - "license": "ISC", - "dependencies": { - "d": "^1.0.1", - "es5-ext": "^0.10.62", - "event-emitter": "^0.3.5", - "type": "^2.7.2" - }, - "engines": { - "node": ">=0.10" - } - }, - "node_modules/esrecurse": { - "version": "4.3.0", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "estraverse": "^5.2.0" - }, - "engines": { - "node": ">=4.0" - } - }, - "node_modules/esrecurse/node_modules/estraverse": { - "version": "5.3.0", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=4.0" - } - }, - "node_modules/estraverse": { - "version": "4.3.0", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=4.0" - } - }, - "node_modules/event-emitter": { - "version": "0.3.5", - "license": "MIT", - "dependencies": { - "d": "1", - "es5-ext": "~0.10.14" - } - }, - "node_modules/eventemitter3": { - "version": "5.0.4", - "dev": true, - "license": "MIT" - }, - "node_modules/events": { - "version": "3.3.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.8.x" - } - }, - "node_modules/execa": { - "version": "1.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "cross-spawn": "^6.0.0", - "get-stream": "^4.0.0", - "is-stream": "^1.1.0", - "npm-run-path": "^2.0.0", - "p-finally": "^1.0.0", - "signal-exit": "^3.0.0", - "strip-eof": "^1.0.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/execa/node_modules/cross-spawn": { - "version": "6.0.6", - "dev": true, - "license": "MIT", - "dependencies": { - "nice-try": "^1.0.4", - "path-key": "^2.0.1", - "semver": "^5.5.0", - "shebang-command": "^1.2.0", - "which": "^1.2.9" - }, - "engines": { - "node": ">=4.8" - } - }, - "node_modules/execa/node_modules/path-key": { - "version": "2.0.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/execa/node_modules/semver": { - "version": "5.7.2", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver" - } - }, - "node_modules/execa/node_modules/shebang-command": { - "version": "1.2.0", - "dev": true, - "license": "MIT", - "dependencies": { - "shebang-regex": "^1.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/execa/node_modules/shebang-regex": { - "version": "1.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/execa/node_modules/signal-exit": { - "version": "3.0.7", - "dev": true, - "license": "ISC" - }, - "node_modules/execa/node_modules/which": { - "version": "1.3.1", - "dev": true, - "license": "ISC", - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "which": "bin/which" - } - }, - "node_modules/expand-template": { - "version": "2.0.3", - "license": "(MIT OR WTFPL)", - "engines": { - "node": ">=6" - } - }, - "node_modules/exponential-backoff": { - "version": "3.1.3", - "dev": true, - "license": "Apache-2.0" - }, - "node_modules/ext": { - "version": "1.7.0", - "license": "ISC", - "dependencies": { - "type": "^2.7.2" - } - }, - "node_modules/ext-list": { - "version": "2.2.2", - "license": "MIT", - "dependencies": { - "mime-db": "^1.28.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/ext-name": { - "version": "5.0.0", - "license": "MIT", - "dependencies": { - "ext-list": "^2.0.0", - "sort-keys-length": "^1.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/external-editor": { - "version": "3.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "chardet": "^0.7.0", - "iconv-lite": "^0.4.24", - "tmp": "^0.0.33" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/external-editor/node_modules/iconv-lite": { - "version": "0.4.24", - "dev": true, - "license": "MIT", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/extract-zip": { - "version": "2.0.1", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "debug": "^4.1.1", - "get-stream": "^5.1.0", - "yauzl": "^2.10.0" - }, - "bin": { - "extract-zip": "cli.js" - }, - "engines": { - "node": ">= 10.17.0" - }, - "optionalDependencies": { - "@types/yauzl": "^2.9.1" - } - }, - "node_modules/extract-zip/node_modules/get-stream": { - "version": "5.2.0", - "dev": true, - "license": "MIT", - "dependencies": { - "pump": "^3.0.0" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/fast-deep-equal": { - "version": "3.1.3", - "dev": true, - "license": "MIT" - }, - "node_modules/fast-glob": { - "version": "3.3.3", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "^2.0.2", - "@nodelib/fs.walk": "^1.2.3", - "glob-parent": "^5.1.2", - "merge2": "^1.3.0", - "micromatch": "^4.0.8" - }, - "engines": { - "node": ">=8.6.0" - } - }, - "node_modules/fast-uri": { - "version": "3.1.2", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "BSD-3-Clause" - }, - "node_modules/fast-xml-builder": { - "version": "1.1.9", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT", - "dependencies": { - "path-expression-matcher": "^1.1.3" - } - }, - "node_modules/fast-xml-parser": { - "version": "5.7.3", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT", - "dependencies": { - "@nodable/entities": "^2.1.0", - "fast-xml-builder": "^1.1.7", - "path-expression-matcher": "^1.5.0", - "strnum": "^2.2.3" - }, - "bin": { - "fxparser": "src/cli/cli.js" - } - }, - "node_modules/fastq": { - "version": "1.20.1", - "dev": true, - "license": "ISC", - "dependencies": { - "reusify": "^1.0.4" - } - }, - "node_modules/fd-slicer": { - "version": "1.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "pend": "~1.2.0" - } - }, - "node_modules/file-uri-to-path": { - "version": "1.0.0", - "license": "MIT" - }, - "node_modules/filename-reserved-regex": { - "version": "2.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/filenamify": { - "version": "4.3.0", - "dev": true, - "license": "MIT", - "dependencies": { - "filename-reserved-regex": "^2.0.0", - "strip-outer": "^1.0.1", - "trim-repeated": "^1.0.0" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/fill-range": { - "version": "7.1.1", - "dev": true, - "license": "MIT", - "dependencies": { - "to-regex-range": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/find-up": { - "version": "5.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "locate-path": "^6.0.0", - "path-exists": "^4.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/flora-colossus": { - "version": "2.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.3.4", - "fs-extra": "^10.1.0" - }, - "engines": { - "node": ">= 12" - } - }, - "node_modules/fmix": { - "version": "0.1.0", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "imul": "^1.0.0" - } - }, - "node_modules/forwarded-parse": { - "version": "2.1.2", - "license": "MIT" - }, - "node_modules/fs-constants": { - "version": "1.0.0", - "license": "MIT" - }, - "node_modules/fs-extra": { - "version": "10.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/fs-minipass": { - "version": "2.1.0", - "dev": true, - "license": "ISC", - "dependencies": { - "minipass": "^3.0.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/fs-minipass/node_modules/minipass": { - "version": "3.3.6", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/fs-temp": { - "version": "1.2.1", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "random-path": "^0.1.0" - } - }, - "node_modules/fs-xattr": { - "version": "0.3.1", - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "!win32" - ], - "engines": { - "node": ">=8.6.0" - } - }, - "node_modules/fs.realpath": { - "version": "1.0.0", - "dev": true, - "license": "ISC" - }, - "node_modules/function-bind": { - "version": "1.1.2", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/galactus": { - "version": "1.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.3.4", - "flora-colossus": "^2.0.0", - "fs-extra": "^10.1.0" - }, - "engines": { - "node": ">= 12" - } - }, - "node_modules/gar": { - "version": "1.0.4", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/generate-function": { - "version": "2.3.1", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "is-property": "^1.0.2" - } - }, - "node_modules/generate-object-property": { - "version": "1.2.0", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "is-property": "^1.0.0" - } - }, - "node_modules/get-caller-file": { - "version": "2.0.5", - "dev": true, - "license": "ISC", - "engines": { - "node": "6.* || 8.* || >= 10.*" - } - }, - "node_modules/get-east-asian-width": { - "version": "1.5.0", - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/get-folder-size": { - "version": "2.0.1", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "gar": "^1.0.4", - "tiny-each-async": "2.0.3" - }, - "bin": { - "get-folder-size": "bin/get-folder-size" - } - }, - "node_modules/get-package-info": { - "version": "1.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "bluebird": "^3.1.1", - "debug": "^2.2.0", - "lodash.get": "^4.0.0", - "read-pkg-up": "^2.0.0" - }, - "engines": { - "node": ">= 4.0" - } - }, - "node_modules/get-package-info/node_modules/debug": { - "version": "2.6.9", - "dev": true, - "license": "MIT", - "dependencies": { - "ms": "2.0.0" - } - }, - "node_modules/get-package-info/node_modules/ms": { - "version": "2.0.0", - "dev": true, - "license": "MIT" - }, - "node_modules/get-stream": { - "version": "4.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "pump": "^3.0.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/github-from-package": { - "version": "0.0.0", - "license": "MIT" - }, - "node_modules/glob": { - "version": "13.0.6", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "minimatch": "^10.2.2", - "minipass": "^7.1.3", - "path-scurry": "^2.0.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/glob-parent": { - "version": "5.1.2", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/glob-to-regexp": { - "version": "0.4.1", - "dev": true, - "license": "BSD-2-Clause" - }, - "node_modules/global-agent": { - "version": "3.0.0", - "dev": true, - "license": "BSD-3-Clause", - "optional": true, - "dependencies": { - "boolean": "^3.0.1", - "es6-error": "^4.1.1", - "matcher": "^3.0.0", - "roarr": "^2.15.3", - "semver": "^7.3.2", - "serialize-error": "^7.0.1" - }, - "engines": { - "node": ">=10.0" - } - }, - "node_modules/global-dirs": { - "version": "3.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "ini": "2.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/globalthis": { - "version": "1.0.4", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "define-properties": "^1.2.1", - "gopd": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/gopd": { - "version": "1.2.0", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/got": { - "version": "11.8.6", - "dev": true, - "license": "MIT", - "dependencies": { - "@sindresorhus/is": "^4.0.0", - "@szmarczak/http-timer": "^4.0.5", - "@types/cacheable-request": "^6.0.1", - "@types/responselike": "^1.0.0", - "cacheable-lookup": "^5.0.3", - "cacheable-request": "^7.0.2", - "decompress-response": "^6.0.0", - "http2-wrapper": "^1.0.0-beta.5.2", - "lowercase-keys": "^2.0.0", - "p-cancelable": "^2.0.0", - "responselike": "^2.0.0" - }, - "engines": { - "node": ">=10.19.0" - }, - "funding": { - "url": "https://github.com/sindresorhus/got?sponsor=1" - } - }, - "node_modules/graceful-fs": { - "version": "4.2.11", - "dev": true, - "license": "ISC" - }, - "node_modules/has-flag": { - "version": "4.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/has-property-descriptors": { - "version": "1.0.2", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "es-define-property": "^1.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/hasown": { - "version": "2.0.3", - "dev": true, - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/hosted-git-info": { - "version": "2.8.9", - "dev": true, - "license": "ISC" - }, - "node_modules/http-cache-semantics": { - "version": "4.2.0", - "dev": true, - "license": "BSD-2-Clause" - }, - "node_modules/http-proxy-agent": { - "version": "5.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "@tootallnate/once": "2", - "agent-base": "6", - "debug": "4" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/http2-wrapper": { - "version": "1.0.3", - "dev": true, - "license": "MIT", - "dependencies": { - "quick-lru": "^5.1.1", - "resolve-alpn": "^1.0.0" - }, - "engines": { - "node": ">=10.19.0" - } - }, - "node_modules/https-proxy-agent": { - "version": "5.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "agent-base": "6", - "debug": "4" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/human-signals": { - "version": "2.1.0", - "license": "Apache-2.0", - "engines": { - "node": ">=10.17.0" - } - }, - "node_modules/humanize-ms": { - "version": "1.2.1", - "dev": true, - "license": "MIT", - "dependencies": { - "ms": "^2.0.0" - } - }, - "node_modules/iconv-lite": { - "version": "0.6.3", - "license": "MIT", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/ieee754": { - "version": "1.2.1", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "BSD-3-Clause" - }, - "node_modules/image-size": { - "version": "0.7.5", - "dev": true, - "license": "MIT", - "optional": true, - "bin": { - "image-size": "bin/image-size.js" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/immer": { - "version": "10.2.0", - "license": "MIT", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/immer" - } - }, - "node_modules/import-in-the-middle": { - "version": "2.0.6", - "license": "Apache-2.0", - "dependencies": { - "acorn": "^8.15.0", - "acorn-import-attributes": "^1.9.5", - "cjs-module-lexer": "^2.2.0", - "module-details-from-path": "^1.0.4" - } - }, - "node_modules/imul": { - "version": "1.0.1", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/imurmurhash": { - "version": "0.1.4", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.8.19" - } - }, - "node_modules/indent-string": { - "version": "4.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/infer-owner": { - "version": "1.0.4", - "dev": true, - "license": "ISC" - }, - "node_modules/inflight": { - "version": "1.0.6", - "dev": true, - "license": "ISC", - "dependencies": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "node_modules/inherits": { - "version": "2.0.4", - "license": "ISC" - }, - "node_modules/ini": { - "version": "2.0.0", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=10" - } - }, - "node_modules/interpret": { - "version": "3.1.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/ip-address": { - "version": "10.2.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 12" - } - }, - "node_modules/is-arrayish": { - "version": "0.2.1", - "dev": true, - "license": "MIT" - }, - "node_modules/is-core-module": { - "version": "2.16.2", - "dev": true, - "license": "MIT", - "dependencies": { - "hasown": "^2.0.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-extglob": { - "version": "2.1.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-fullwidth-code-point": { - "version": "4.0.0", - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/is-glob": { - "version": "4.0.3", - "dev": true, - "license": "MIT", - "dependencies": { - "is-extglob": "^2.1.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-interactive": { - "version": "1.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/is-lambda": { - "version": "1.0.1", - "dev": true, - "license": "MIT" - }, - "node_modules/is-my-ip-valid": { - "version": "1.0.1", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/is-my-json-valid": { - "version": "2.20.6", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "generate-function": "^2.0.0", - "generate-object-property": "^1.1.0", - "is-my-ip-valid": "^1.0.0", - "jsonpointer": "^5.0.0", - "xtend": "^4.0.0" - } - }, - "node_modules/is-number": { - "version": "7.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.12.0" - } - }, - "node_modules/is-plain-obj": { - "version": "1.1.0", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-promise": { - "version": "2.2.2", - "license": "MIT" - }, - "node_modules/is-property": { - "version": "1.0.2", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/is-stream": { - "version": "1.1.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-unicode-supported": { - "version": "0.1.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/isbinaryfile": { - "version": "4.0.10", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 8.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/gjtorikian/" - } - }, - "node_modules/isexe": { - "version": "2.0.0", - "license": "ISC" - }, - "node_modules/jest-worker": { - "version": "27.5.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*", - "merge-stream": "^2.0.0", - "supports-color": "^8.0.0" - }, - "engines": { - "node": ">= 10.13.0" - } - }, - "node_modules/jest-worker/node_modules/supports-color": { - "version": "8.1.1", - "dev": true, - "license": "MIT", - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/supports-color?sponsor=1" - } - }, - "node_modules/jiti": { - "version": "2.7.0", - "dev": true, - "license": "MIT", - "bin": { - "jiti": "lib/jiti-cli.mjs" - } - }, - "node_modules/json-buffer": { - "version": "3.0.1", - "dev": true, - "license": "MIT" - }, - "node_modules/json-schema-traverse": { - "version": "1.0.0", - "dev": true, - "license": "MIT" - }, - "node_modules/json-stringify-safe": { - "version": "5.0.1", - "dev": true, - "license": "ISC", - "optional": true - }, - "node_modules/jsonfile": { - "version": "6.2.1", - "dev": true, - "license": "MIT", - "dependencies": { - "universalify": "^2.0.0" - }, - "optionalDependencies": { - "graceful-fs": "^4.1.6" - } - }, - "node_modules/jsonpointer": { - "version": "5.0.1", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/junk": { - "version": "3.1.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/keyv": { - "version": "4.5.4", - "dev": true, - "license": "MIT", - "dependencies": { - "json-buffer": "3.0.1" - } - }, - "node_modules/listr2": { - "version": "7.0.2", - "dev": true, - "license": "MIT", - "dependencies": { - "cli-truncate": "^3.1.0", - "colorette": "^2.0.20", - "eventemitter3": "^5.0.1", - "log-update": "^5.0.1", - "rfdc": "^1.3.0", - "wrap-ansi": "^8.1.0" - }, - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/listr2/node_modules/ansi-regex": { - "version": "6.2.2", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" - } - }, - "node_modules/listr2/node_modules/ansi-styles": { - "version": "6.2.3", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/listr2/node_modules/cli-truncate": { - "version": "3.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "slice-ansi": "^5.0.0", - "string-width": "^5.0.0" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/listr2/node_modules/emoji-regex": { - "version": "9.2.2", - "dev": true, - "license": "MIT" - }, - "node_modules/listr2/node_modules/string-width": { - "version": "5.1.2", - "dev": true, - "license": "MIT", - "dependencies": { - "eastasianwidth": "^0.2.0", - "emoji-regex": "^9.2.2", - "strip-ansi": "^7.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/listr2/node_modules/strip-ansi": { - "version": "7.2.0", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^6.2.2" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" - } - }, - "node_modules/listr2/node_modules/wrap-ansi": { - "version": "8.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^6.1.0", - "string-width": "^5.0.1", - "strip-ansi": "^7.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/load-json-file": { - "version": "2.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "graceful-fs": "^4.1.2", - "parse-json": "^2.2.0", - "pify": "^2.0.0", - "strip-bom": "^3.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/loader-runner": { - "version": "4.3.2", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.11.5" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/webpack" - } - }, - "node_modules/locate-path": { - "version": "6.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "p-locate": "^5.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/lodash": { - "version": "4.18.1", - "license": "MIT" - }, - "node_modules/lodash.get": { - "version": "4.4.2", - "dev": true, - "license": "MIT" - }, - "node_modules/log-symbols": { - "version": "4.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "chalk": "^4.1.0", - "is-unicode-supported": "^0.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/log-update": { - "version": "5.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-escapes": "^5.0.0", - "cli-cursor": "^4.0.0", - "slice-ansi": "^5.0.0", - "strip-ansi": "^7.0.1", - "wrap-ansi": "^8.0.1" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/log-update/node_modules/ansi-escapes": { - "version": "5.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "type-fest": "^1.0.2" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/log-update/node_modules/ansi-regex": { - "version": "6.2.2", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" - } - }, - "node_modules/log-update/node_modules/ansi-styles": { - "version": "6.2.3", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/log-update/node_modules/emoji-regex": { - "version": "9.2.2", - "dev": true, - "license": "MIT" - }, - "node_modules/log-update/node_modules/string-width": { - "version": "5.1.2", - "dev": true, - "license": "MIT", - "dependencies": { - "eastasianwidth": "^0.2.0", - "emoji-regex": "^9.2.2", - "strip-ansi": "^7.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/log-update/node_modules/strip-ansi": { - "version": "7.2.0", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^6.2.2" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" - } - }, - "node_modules/log-update/node_modules/type-fest": { - "version": "1.4.0", - "dev": true, - "license": "(MIT OR CC0-1.0)", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/log-update/node_modules/wrap-ansi": { - "version": "8.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^6.1.0", - "string-width": "^5.0.1", - "strip-ansi": "^7.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/lowercase-keys": { - "version": "2.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/lru-cache": { - "version": "7.18.3", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/lru-queue": { - "version": "0.1.0", - "license": "MIT", - "dependencies": { - "es5-ext": "~0.10.2" - } - }, - "node_modules/macos-alias": { - "version": "0.2.12", - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "dependencies": { - "nan": "^2.4.0" - } - }, - "node_modules/make-fetch-happen": { - "version": "10.2.1", - "dev": true, - "license": "ISC", - "dependencies": { - "agentkeepalive": "^4.2.1", - "cacache": "^16.1.0", - "http-cache-semantics": "^4.1.0", - "http-proxy-agent": "^5.0.0", - "https-proxy-agent": "^5.0.0", - "is-lambda": "^1.0.1", - "lru-cache": "^7.7.1", - "minipass": "^3.1.6", - "minipass-collect": "^1.0.2", - "minipass-fetch": "^2.0.3", - "minipass-flush": "^1.0.5", - "minipass-pipeline": "^1.2.4", - "negotiator": "^0.6.3", - "promise-retry": "^2.0.1", - "socks-proxy-agent": "^7.0.0", - "ssri": "^9.0.0" - }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } - }, - "node_modules/make-fetch-happen/node_modules/minipass": { - "version": "3.3.6", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/map-age-cleaner": { - "version": "0.1.3", - "dev": true, - "license": "MIT", - "dependencies": { - "p-defer": "^1.0.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/matcher": { - "version": "3.0.0", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "escape-string-regexp": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/mem": { - "version": "4.3.0", - "dev": true, - "license": "MIT", - "dependencies": { - "map-age-cleaner": "^0.1.1", - "mimic-fn": "^2.0.0", - "p-is-promise": "^2.0.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/memoizee": { - "version": "0.4.17", - "license": "ISC", - "dependencies": { - "d": "^1.0.2", - "es5-ext": "^0.10.64", - "es6-weak-map": "^2.0.3", - "event-emitter": "^0.3.5", - "is-promise": "^2.2.2", - "lru-queue": "^0.1.0", - "next-tick": "^1.1.0", - "timers-ext": "^0.1.7" - }, - "engines": { - "node": ">=0.12" - } - }, - "node_modules/merge-stream": { - "version": "2.0.0", - "license": "MIT" - }, - "node_modules/merge2": { - "version": "1.4.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, - "node_modules/micromatch": { - "version": "4.0.8", - "dev": true, - "license": "MIT", - "dependencies": { - "braces": "^3.0.3", - "picomatch": "^2.3.1" - }, - "engines": { - "node": ">=8.6" - } - }, - "node_modules/mime-db": { - "version": "1.54.0", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "2.1.35", - "license": "MIT", - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types/node_modules/mime-db": { - "version": "1.52.0", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mimic-fn": { - "version": "2.1.0", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/mimic-response": { - "version": "1.0.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/minimatch": { - "version": "10.2.5", - "license": "BlueOak-1.0.0", - "dependencies": { - "brace-expansion": "^5.0.5" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/minimist": { - "version": "1.2.8", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/minipass": { - "version": "7.1.3", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "node_modules/minipass-collect": { - "version": "1.0.2", - "dev": true, - "license": "ISC", - "dependencies": { - "minipass": "^3.0.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/minipass-collect/node_modules/minipass": { - "version": "3.3.6", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/minipass-fetch": { - "version": "2.1.2", - "dev": true, - "license": "MIT", - "dependencies": { - "minipass": "^3.1.6", - "minipass-sized": "^1.0.3", - "minizlib": "^2.1.2" - }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - }, - "optionalDependencies": { - "encoding": "^0.1.13" - } - }, - "node_modules/minipass-fetch/node_modules/minipass": { - "version": "3.3.6", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/minipass-flush": { - "version": "1.0.7", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "minipass": "^3.0.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/minipass-flush/node_modules/minipass": { - "version": "3.3.6", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/minipass-pipeline": { - "version": "1.2.4", - "dev": true, - "license": "ISC", - "dependencies": { - "minipass": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/minipass-pipeline/node_modules/minipass": { - "version": "3.3.6", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/minipass-sized": { - "version": "1.0.3", - "dev": true, - "license": "ISC", - "dependencies": { - "minipass": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/minipass-sized/node_modules/minipass": { - "version": "3.3.6", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/minizlib": { - "version": "2.1.2", - "dev": true, - "license": "MIT", - "dependencies": { - "minipass": "^3.0.0", - "yallist": "^4.0.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/minizlib/node_modules/minipass": { - "version": "3.3.6", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/mkdirp": { - "version": "1.0.4", - "dev": true, - "license": "MIT", - "bin": { - "mkdirp": "bin/cmd.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/mkdirp-classic": { - "version": "0.5.3", - "license": "MIT" - }, - "node_modules/module-details-from-path": { - "version": "1.0.4", - "license": "MIT" - }, - "node_modules/ms": { - "version": "2.1.3", - "license": "MIT" - }, - "node_modules/murmur-32": { - "version": "0.2.0", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "encode-utf8": "^1.0.3", - "fmix": "^0.1.0", - "imul": "^1.0.0" - } - }, - "node_modules/mute-stream": { - "version": "1.0.0", - "dev": true, - "license": "ISC", - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/nan": { - "version": "2.26.2", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/napi-build-utils": { - "version": "2.0.0", - "license": "MIT" - }, - "node_modules/negotiator": { - "version": "0.6.4", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/neo-async": { - "version": "2.6.2", - "dev": true, - "license": "MIT" - }, - "node_modules/next-tick": { - "version": "1.1.0", - "license": "ISC" - }, - "node_modules/nice-try": { - "version": "1.0.5", - "dev": true, - "license": "MIT" - }, - "node_modules/node-abi": { - "version": "3.92.0", - "license": "MIT", - "dependencies": { - "semver": "^7.3.5" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/node-addon-api": { - "version": "7.1.1", - "license": "MIT" - }, - "node_modules/node-api-version": { - "version": "0.2.1", - "dev": true, - "license": "MIT", - "dependencies": { - "semver": "^7.3.5" - } - }, - "node_modules/node-fetch": { - "version": "2.7.0", - "dev": true, - "license": "MIT", - "dependencies": { - "whatwg-url": "^5.0.0" - }, - "engines": { - "node": "4.x || >=6.0.0" - }, - "peerDependencies": { - "encoding": "^0.1.0" - }, - "peerDependenciesMeta": { - "encoding": { - "optional": true - } - } - }, - "node_modules/node-pty": { - "version": "1.1.0", - "hasInstallScript": true, - "license": "MIT", - "dependencies": { - "node-addon-api": "^7.1.0" - } - }, - "node_modules/node-releases": { - "version": "2.0.38", - "dev": true, - "license": "MIT" - }, - "node_modules/nopt": { - "version": "6.0.0", - "dev": true, - "license": "ISC", - "dependencies": { - "abbrev": "^1.0.0" - }, - "bin": { - "nopt": "bin/nopt.js" - }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } - }, - "node_modules/normalize-package-data": { - "version": "2.5.0", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "hosted-git-info": "^2.1.4", - "resolve": "^1.10.0", - "semver": "2 || 3 || 4 || 5", - "validate-npm-package-license": "^3.0.1" - } - }, - "node_modules/normalize-package-data/node_modules/semver": { - "version": "5.7.2", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver" - } - }, - "node_modules/normalize-url": { - "version": "6.1.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/npm-run-path": { - "version": "2.0.2", - "dev": true, - "license": "MIT", - "dependencies": { - "path-key": "^2.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/npm-run-path/node_modules/path-key": { - "version": "2.0.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/object-keys": { - "version": "1.1.1", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/once": { - "version": "1.4.0", - "license": "ISC", - "dependencies": { - "wrappy": "1" - } - }, - "node_modules/onetime": { - "version": "5.1.2", - "license": "MIT", - "dependencies": { - "mimic-fn": "^2.1.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/ora": { - "version": "5.4.1", - "dev": true, - "license": "MIT", - "dependencies": { - "bl": "^4.1.0", - "chalk": "^4.1.0", - "cli-cursor": "^3.1.0", - "cli-spinners": "^2.5.0", - "is-interactive": "^1.0.0", - "is-unicode-supported": "^0.1.0", - "log-symbols": "^4.1.0", - "strip-ansi": "^6.0.0", - "wcwidth": "^1.0.1" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/ora/node_modules/cli-cursor": { - "version": "3.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "restore-cursor": "^3.1.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/ora/node_modules/restore-cursor": { - "version": "3.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "onetime": "^5.1.0", - "signal-exit": "^3.0.2" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/ora/node_modules/signal-exit": { - "version": "3.0.7", - "dev": true, - "license": "ISC" - }, - "node_modules/os-tmpdir": { - "version": "1.0.2", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/p-cancelable": { - "version": "2.1.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/p-defer": { - "version": "1.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/p-finally": { - "version": "1.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/p-is-promise": { - "version": "2.1.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/p-limit": { - "version": "3.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "yocto-queue": "^0.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-locate": { - "version": "5.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "p-limit": "^3.0.2" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-map": { - "version": "4.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "aggregate-error": "^3.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-try": { - "version": "1.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/parse-author": { - "version": "2.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "author-regex": "^1.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/parse-color": { - "version": "1.0.0", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "color-convert": "~0.5.0" - } - }, - "node_modules/parse-color/node_modules/color-convert": { - "version": "0.5.3", - "dev": true, - "optional": true - }, - "node_modules/parse-json": { - "version": "2.2.0", - "dev": true, - "license": "MIT", - "dependencies": { - "error-ex": "^1.2.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/path-exists": { - "version": "4.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/path-expression-matcher": { - "version": "1.5.0", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT", - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/path-is-absolute": { - "version": "1.0.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/path-key": { - "version": "3.1.1", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/path-parse": { - "version": "1.0.7", - "dev": true, - "license": "MIT" - }, - "node_modules/path-scurry": { - "version": "2.0.2", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "lru-cache": "^11.0.0", - "minipass": "^7.1.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/path-scurry/node_modules/lru-cache": { - "version": "11.3.6", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/path-type": { - "version": "2.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "pify": "^2.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/pe-library": { - "version": "1.0.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=14", - "npm": ">=7" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/jet2jet" - } - }, - "node_modules/pend": { - "version": "1.2.0", - "dev": true, - "license": "MIT" - }, - "node_modules/pg-int8": { - "version": "1.0.1", - "license": "ISC", - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/pg-protocol": { - "version": "1.13.0", - "license": "MIT" - }, - "node_modules/pg-types": { - "version": "2.2.0", - "license": "MIT", - "dependencies": { - "pg-int8": "1.0.1", - "postgres-array": "~2.0.0", - "postgres-bytea": "~1.0.0", - "postgres-date": "~1.0.4", - "postgres-interval": "^1.1.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/picocolors": { - "version": "1.1.1", - "dev": true, - "license": "ISC" - }, - "node_modules/picomatch": { - "version": "2.3.2", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/pify": { - "version": "2.3.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/plist": { - "version": "3.1.1", - "dev": true, - "license": "MIT", - "dependencies": { - "@xmldom/xmldom": "^0.9.10", - "base64-js": "^1.5.1", - "xmlbuilder": "^15.1.1" - }, - "engines": { - "node": ">=10.4.0" - } - }, - "node_modules/postgres-array": { - "version": "2.0.0", - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/postgres-bytea": { - "version": "1.0.1", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/postgres-date": { - "version": "1.0.7", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/postgres-interval": { - "version": "1.2.0", - "license": "MIT", - "dependencies": { - "xtend": "^4.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/postject": { - "version": "1.0.0-alpha.6", - "dev": true, - "license": "MIT", - "dependencies": { - "commander": "^9.4.0" - }, - "bin": { - "postject": "dist/cli.js" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/postject/node_modules/commander": { - "version": "9.5.0", - "dev": true, - "license": "MIT", - "engines": { - "node": "^12.20.0 || >=14" - } - }, - "node_modules/prebuild-install": { - "version": "7.1.3", - "license": "MIT", - "dependencies": { - "detect-libc": "^2.0.0", - "expand-template": "^2.0.3", - "github-from-package": "0.0.0", - "minimist": "^1.2.3", - "mkdirp-classic": "^0.5.3", - "napi-build-utils": "^2.0.0", - "node-abi": "^3.3.0", - "pump": "^3.0.0", - "rc": "^1.2.7", - "simple-get": "^4.0.0", - "tar-fs": "^2.0.0", - "tunnel-agent": "^0.6.0" - }, - "bin": { - "prebuild-install": "bin.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/prettier": { - "version": "3.8.3", - "dev": true, - "license": "MIT", - "bin": { - "prettier": "bin/prettier.cjs" - }, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/prettier/prettier?sponsor=1" - } - }, - "node_modules/proc-log": { - "version": "2.0.1", - "dev": true, - "license": "ISC", - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } - }, - "node_modules/progress": { - "version": "2.0.3", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/promise-inflight": { - "version": "1.0.1", - "dev": true, - "license": "ISC" - }, - "node_modules/promise-retry": { - "version": "2.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "err-code": "^2.0.2", - "retry": "^0.12.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/pump": { - "version": "3.0.4", - "license": "MIT", - "dependencies": { - "end-of-stream": "^1.1.0", - "once": "^1.3.1" - } - }, - "node_modules/pupa": { - "version": "3.3.0", - "license": "MIT", - "dependencies": { - "escape-goat": "^4.0.0" - }, - "engines": { - "node": ">=12.20" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/queue-microtask": { - "version": "1.2.3", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/quick-lru": { - "version": "5.1.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/random-path": { - "version": "0.1.2", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "base32-encode": "^0.1.0 || ^1.0.0", - "murmur-32": "^0.1.0 || ^0.2.0" - } - }, - "node_modules/rc": { - "version": "1.2.8", - "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", - "dependencies": { - "deep-extend": "^0.6.0", - "ini": "~1.3.0", - "minimist": "^1.2.0", - "strip-json-comments": "~2.0.1" - }, - "bin": { - "rc": "cli.js" - } - }, - "node_modules/rc/node_modules/ini": { - "version": "1.3.8", - "license": "ISC" - }, - "node_modules/read-binary-file-arch": { - "version": "1.0.6", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.3.4" - }, - "bin": { - "read-binary-file-arch": "cli.js" - } - }, - "node_modules/read-pkg": { - "version": "2.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "load-json-file": "^2.0.0", - "normalize-package-data": "^2.3.2", - "path-type": "^2.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/read-pkg-up": { - "version": "2.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "find-up": "^2.0.0", - "read-pkg": "^2.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/read-pkg-up/node_modules/find-up": { - "version": "2.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "locate-path": "^2.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/read-pkg-up/node_modules/locate-path": { - "version": "2.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "p-locate": "^2.0.0", - "path-exists": "^3.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/read-pkg-up/node_modules/p-limit": { - "version": "1.3.0", - "dev": true, - "license": "MIT", - "dependencies": { - "p-try": "^1.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/read-pkg-up/node_modules/p-locate": { - "version": "2.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "p-limit": "^1.1.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/read-pkg-up/node_modules/path-exists": { - "version": "3.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/readable-stream": { - "version": "3.6.2", - "license": "MIT", - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/rechoir": { - "version": "0.8.0", - "dev": true, - "license": "MIT", - "dependencies": { - "resolve": "^1.20.0" - }, - "engines": { - "node": ">= 10.13.0" - } - }, - "node_modules/repeat-string": { - "version": "1.6.1", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">=0.10" - } - }, - "node_modules/require-directory": { - "version": "2.1.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/require-from-string": { - "version": "2.0.2", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/require-in-the-middle": { - "version": "8.0.1", - "license": "MIT", - "dependencies": { - "debug": "^4.3.5", - "module-details-from-path": "^1.0.3" - }, - "engines": { - "node": ">=9.3.0 || >=8.10.0 <9.0.0" - } - }, - "node_modules/resedit": { - "version": "2.0.3", - "dev": true, - "license": "MIT", - "dependencies": { - "pe-library": "^1.0.1" - }, - "engines": { - "node": ">=14", - "npm": ">=7" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/jet2jet" - } - }, - "node_modules/resolve": { - "version": "1.22.12", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "is-core-module": "^2.16.1", - "path-parse": "^1.0.7", - "supports-preserve-symlinks-flag": "^1.0.0" - }, - "bin": { - "resolve": "bin/resolve" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/resolve-alpn": { - "version": "1.2.1", - "dev": true, - "license": "MIT" - }, - "node_modules/responselike": { - "version": "2.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "lowercase-keys": "^2.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/restore-cursor": { - "version": "4.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "onetime": "^5.1.0", - "signal-exit": "^3.0.2" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/restore-cursor/node_modules/signal-exit": { - "version": "3.0.7", - "dev": true, - "license": "ISC" - }, - "node_modules/retry": { - "version": "0.12.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 4" - } - }, - "node_modules/reusify": { - "version": "1.1.0", - "dev": true, - "license": "MIT", - "engines": { - "iojs": ">=1.0.0", - "node": ">=0.10.0" - } - }, - "node_modules/rfdc": { - "version": "1.4.1", - "dev": true, - "license": "MIT" - }, - "node_modules/rimraf": { - "version": "3.0.2", - "dev": true, - "license": "ISC", - "dependencies": { - "glob": "^7.1.3" - }, - "bin": { - "rimraf": "bin.js" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/rimraf/node_modules/balanced-match": { - "version": "1.0.2", - "dev": true, - "license": "MIT" - }, - "node_modules/rimraf/node_modules/brace-expansion": { - "version": "1.1.14", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/rimraf/node_modules/glob": { - "version": "7.2.3", - "dev": true, - "license": "ISC", - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/rimraf/node_modules/minimatch": { - "version": "3.1.5", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/roarr": { - "version": "2.15.4", - "dev": true, - "license": "BSD-3-Clause", - "optional": true, - "dependencies": { - "boolean": "^3.0.1", - "detect-node": "^2.0.4", - "globalthis": "^1.0.1", - "json-stringify-safe": "^5.0.1", - "semver-compare": "^1.0.0", - "sprintf-js": "^1.1.2" - }, - "engines": { - "node": ">=8.0" - } - }, - "node_modules/run-parallel": { - "version": "1.2.0", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "queue-microtask": "^1.2.2" - } - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "license": "MIT" - }, - "node_modules/schema-utils": { - "version": "4.3.3", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/json-schema": "^7.0.9", - "ajv": "^8.9.0", - "ajv-formats": "^2.1.1", - "ajv-keywords": "^5.1.0" - }, - "engines": { - "node": ">= 10.13.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/webpack" - } - }, - "node_modules/semver": { - "version": "7.7.4", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/semver-compare": { - "version": "1.0.0", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/serialize-error": { - "version": "7.0.1", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "type-fest": "^0.13.1" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/serialize-error/node_modules/type-fest": { - "version": "0.13.1", - "dev": true, - "license": "(MIT OR CC0-1.0)", - "optional": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/shebang-command": { - "version": "2.0.0", - "license": "MIT", - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/shebang-regex": { - "version": "3.0.0", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/shell-env": { - "version": "4.0.3", - "license": "MIT", - "dependencies": { - "default-shell": "^2.0.0", - "execa": "^5.1.1", - "strip-ansi": "^7.0.1" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/shell-env/node_modules/ansi-regex": { - "version": "6.2.2", - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" - } - }, - "node_modules/shell-env/node_modules/execa": { - "version": "5.1.1", - "license": "MIT", - "dependencies": { - "cross-spawn": "^7.0.3", - "get-stream": "^6.0.0", - "human-signals": "^2.1.0", - "is-stream": "^2.0.0", - "merge-stream": "^2.0.0", - "npm-run-path": "^4.0.1", - "onetime": "^5.1.2", - "signal-exit": "^3.0.3", - "strip-final-newline": "^2.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sindresorhus/execa?sponsor=1" - } - }, - "node_modules/shell-env/node_modules/get-stream": { - "version": "6.0.1", - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/shell-env/node_modules/is-stream": { - "version": "2.0.1", - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/shell-env/node_modules/npm-run-path": { - "version": "4.0.1", - "license": "MIT", - "dependencies": { - "path-key": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/shell-env/node_modules/signal-exit": { - "version": "3.0.7", - "license": "ISC" - }, - "node_modules/shell-env/node_modules/strip-ansi": { - "version": "7.2.0", - "license": "MIT", - "dependencies": { - "ansi-regex": "^6.2.2" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" - } - }, - "node_modules/shlex": { - "version": "3.0.0", - "license": "MIT" - }, - "node_modules/signal-exit": { - "version": "4.1.0", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/simple-concat": { - "version": "1.0.1", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/simple-get": { - "version": "4.0.1", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "decompress-response": "^6.0.0", - "once": "^1.3.1", - "simple-concat": "^1.0.0" - } - }, - "node_modules/slice-ansi": { - "version": "5.0.0", - "license": "MIT", - "dependencies": { - "ansi-styles": "^6.0.0", - "is-fullwidth-code-point": "^4.0.0" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/slice-ansi?sponsor=1" - } - }, - "node_modules/slice-ansi/node_modules/ansi-styles": { - "version": "6.2.3", - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/smart-buffer": { - "version": "4.2.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 6.0.0", - "npm": ">= 3.0.0" - } - }, - "node_modules/smol-toml": { - "version": "1.6.1", - "license": "BSD-3-Clause", - "engines": { - "node": ">= 18" - }, - "funding": { - "url": "https://github.com/sponsors/cyyynthia" - } - }, - "node_modules/socks": { - "version": "2.8.8", - "dev": true, - "license": "MIT", - "dependencies": { - "ip-address": "^10.1.1", - "smart-buffer": "^4.2.0" - }, - "engines": { - "node": ">= 10.0.0", - "npm": ">= 3.0.0" - } - }, - "node_modules/socks-proxy-agent": { - "version": "7.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "agent-base": "^6.0.2", - "debug": "^4.3.3", - "socks": "^2.6.2" - }, - "engines": { - "node": ">= 10" - } - }, - "node_modules/sort-keys": { - "version": "1.1.2", - "license": "MIT", - "dependencies": { - "is-plain-obj": "^1.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/sort-keys-length": { - "version": "1.0.1", - "license": "MIT", - "dependencies": { - "sort-keys": "^1.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/source-map": { - "version": "0.6.1", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/source-map-support": { - "version": "0.5.21", - "dev": true, - "license": "MIT", - "dependencies": { - "buffer-from": "^1.0.0", - "source-map": "^0.6.0" - } - }, - "node_modules/spdx-correct": { - "version": "3.2.0", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "spdx-expression-parse": "^3.0.0", - "spdx-license-ids": "^3.0.0" - } - }, - "node_modules/spdx-exceptions": { - "version": "2.5.0", - "dev": true, - "license": "CC-BY-3.0" - }, - "node_modules/spdx-expression-parse": { - "version": "3.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "spdx-exceptions": "^2.1.0", - "spdx-license-ids": "^3.0.0" - } - }, - "node_modules/spdx-license-ids": { - "version": "3.0.23", - "dev": true, - "license": "CC0-1.0" - }, - "node_modules/sprintf-js": { - "version": "1.1.3", - "dev": true, - "license": "BSD-3-Clause", - "optional": true - }, - "node_modules/ssri": { - "version": "9.0.1", - "dev": true, - "license": "ISC", - "dependencies": { - "minipass": "^3.1.1" - }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } - }, - "node_modules/ssri/node_modules/minipass": { - "version": "3.3.6", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/stream-buffers": { - "version": "2.2.0", - "dev": true, - "license": "Unlicense", - "optional": true, - "engines": { - "node": ">= 0.10.0" - } - }, - "node_modules/string_decoder": { - "version": "1.3.0", - "license": "MIT", - "dependencies": { - "safe-buffer": "~5.2.0" - } - }, - "node_modules/string-width": { - "version": "7.2.0", - "license": "MIT", - "dependencies": { - "emoji-regex": "^10.3.0", - "get-east-asian-width": "^1.0.0", - "strip-ansi": "^7.1.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/string-width/node_modules/ansi-regex": { - "version": "6.2.2", - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" - } - }, - "node_modules/string-width/node_modules/strip-ansi": { - "version": "7.2.0", - "license": "MIT", - "dependencies": { - "ansi-regex": "^6.2.2" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" - } - }, - "node_modules/strip-ansi": { - "version": "6.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-bom": { - "version": "3.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/strip-eof": { - "version": "1.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/strip-final-newline": { - "version": "2.0.0", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/strip-json-comments": { - "version": "2.0.1", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/strip-outer": { - "version": "1.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "escape-string-regexp": "^1.0.2" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/strip-outer/node_modules/escape-string-regexp": { - "version": "1.0.5", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.8.0" - } - }, - "node_modules/strnum": { - "version": "2.3.0", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT" - }, - "node_modules/sumchecker": { - "version": "3.0.1", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "debug": "^4.1.0" - }, - "engines": { - "node": ">= 8.0" - } - }, - "node_modules/supports-color": { - "version": "7.2.0", - "dev": true, - "license": "MIT", - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/supports-preserve-symlinks-flag": { - "version": "1.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/tapable": { - "version": "2.3.3", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/webpack" - } - }, - "node_modules/tar": { - "version": "6.2.1", - "dev": true, - "license": "ISC", - "dependencies": { - "chownr": "^2.0.0", - "fs-minipass": "^2.0.0", - "minipass": "^5.0.0", - "minizlib": "^2.1.1", - "mkdirp": "^1.0.3", - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/tar-fs": { - "version": "2.1.4", - "license": "MIT", - "dependencies": { - "chownr": "^1.1.1", - "mkdirp-classic": "^0.5.2", - "pump": "^3.0.0", - "tar-stream": "^2.1.4" - } - }, - "node_modules/tar-fs/node_modules/chownr": { - "version": "1.1.4", - "license": "ISC" - }, - "node_modules/tar-stream": { - "version": "2.2.0", - "license": "MIT", - "dependencies": { - "bl": "^4.0.3", - "end-of-stream": "^1.4.1", - "fs-constants": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^3.1.1" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/tar/node_modules/minipass": { - "version": "5.0.0", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=8" - } - }, - "node_modules/temp": { - "version": "0.9.4", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "mkdirp": "^0.5.1", - "rimraf": "~2.6.2" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/temp/node_modules/balanced-match": { - "version": "1.0.2", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/temp/node_modules/brace-expansion": { - "version": "1.1.14", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/temp/node_modules/glob": { - "version": "7.2.3", - "dev": true, - "license": "ISC", - "optional": true, - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/temp/node_modules/minimatch": { - "version": "3.1.5", - "dev": true, - "license": "ISC", - "optional": true, - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/temp/node_modules/mkdirp": { - "version": "0.5.6", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "minimist": "^1.2.6" - }, - "bin": { - "mkdirp": "bin/cmd.js" - } - }, - "node_modules/temp/node_modules/rimraf": { - "version": "2.6.3", - "dev": true, - "license": "ISC", - "optional": true, - "dependencies": { - "glob": "^7.1.3" - }, - "bin": { - "rimraf": "bin.js" - } - }, - "node_modules/terser": { - "version": "5.47.1", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "@jridgewell/source-map": "^0.3.3", - "acorn": "^8.15.0", - "commander": "^2.20.0", - "source-map-support": "~0.5.20" - }, - "bin": { - "terser": "bin/terser" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/terser-webpack-plugin": { - "version": "5.5.0", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/trace-mapping": "^0.3.25", - "jest-worker": "^27.4.5", - "schema-utils": "^4.3.0", - "terser": "^5.31.1" - }, - "engines": { - "node": ">= 10.13.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/webpack" - }, - "peerDependencies": { - "webpack": "^5.1.0" - }, - "peerDependenciesMeta": { - "@swc/core": { - "optional": true - }, - "esbuild": { - "optional": true - }, - "uglify-js": { - "optional": true - } - } - }, - "node_modules/terser/node_modules/commander": { - "version": "2.20.3", - "dev": true, - "license": "MIT" - }, - "node_modules/timers-ext": { - "version": "0.1.8", - "license": "ISC", - "dependencies": { - "es5-ext": "^0.10.64", - "next-tick": "^1.1.0" - }, - "engines": { - "node": ">=0.12" - } - }, - "node_modules/tiny-each-async": { - "version": "2.0.3", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/tmp": { - "version": "0.0.33", - "dev": true, - "license": "MIT", - "dependencies": { - "os-tmpdir": "~1.0.2" - }, - "engines": { - "node": ">=0.6.0" - } - }, - "node_modules/tmp-promise": { - "version": "3.0.3", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tmp": "^0.2.0" - } - }, - "node_modules/tmp-promise/node_modules/tmp": { - "version": "0.2.5", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">=14.14" - } - }, - "node_modules/tn1150": { - "version": "0.1.0", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "unorm": "^1.4.1" - }, - "engines": { - "node": ">=0.12" - } - }, - "node_modules/to-data-view": { - "version": "1.1.0", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/to-regex-range": { - "version": "5.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "is-number": "^7.0.0" - }, - "engines": { - "node": ">=8.0" - } - }, - "node_modules/tr46": { - "version": "0.0.3", - "dev": true, - "license": "MIT" - }, - "node_modules/trim-repeated": { - "version": "1.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "escape-string-regexp": "^1.0.2" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/trim-repeated/node_modules/escape-string-regexp": { - "version": "1.0.5", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.8.0" - } - }, - "node_modules/tslib": { - "version": "2.8.1", - "license": "0BSD" - }, - "node_modules/tunnel-agent": { - "version": "0.6.0", - "license": "Apache-2.0", - "dependencies": { - "safe-buffer": "^5.0.1" - }, - "engines": { - "node": "*" - } - }, - "node_modules/type": { - "version": "2.7.3", - "license": "ISC" - }, - "node_modules/type-fest": { - "version": "0.21.3", - "dev": true, - "license": "(MIT OR CC0-1.0)", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/typescript": { - "version": "5.4.5", - "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/undici": { - "version": "7.25.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-7.25.0.tgz", - "integrity": "sha512-xXnp4kTyor2Zq+J1FfPI6Eq3ew5h6Vl0F/8d9XU5zZQf1tX9s2Su1/3PiMmUANFULpmksxkClamIZcaUqryHsQ==", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">=20.18.1" - } - }, - "node_modules/undici-types": { - "version": "6.21.0", - "license": "MIT" - }, - "node_modules/unique-filename": { - "version": "2.0.1", - "dev": true, - "license": "ISC", - "dependencies": { - "unique-slug": "^3.0.0" - }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } - }, - "node_modules/unique-slug": { - "version": "3.0.0", - "dev": true, - "license": "ISC", - "dependencies": { - "imurmurhash": "^0.1.4" - }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } - }, - "node_modules/universalify": { - "version": "2.0.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 10.0.0" - } - }, - "node_modules/unorm": { - "version": "1.6.0", - "dev": true, - "license": "MIT or GPL-2.0", - "optional": true, - "engines": { - "node": ">= 0.4.0" - } - }, - "node_modules/unused-filename": { - "version": "4.0.1", - "license": "MIT", - "dependencies": { - "escape-string-regexp": "^5.0.0", - "path-exists": "^5.0.0" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/unused-filename/node_modules/escape-string-regexp": { - "version": "5.0.0", - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/unused-filename/node_modules/path-exists": { - "version": "5.0.0", - "license": "MIT", - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - } - }, - "node_modules/update-browserslist-db": { - "version": "1.2.3", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "escalade": "^3.2.0", - "picocolors": "^1.1.1" - }, - "bin": { - "update-browserslist-db": "cli.js" - }, - "peerDependencies": { - "browserslist": ">= 4.21.0" - } - }, - "node_modules/username": { - "version": "5.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "execa": "^1.0.0", - "mem": "^4.3.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/util-deprecate": { - "version": "1.0.2", - "license": "MIT" - }, - "node_modules/validate-npm-package-license": { - "version": "3.0.4", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "spdx-correct": "^3.0.0", - "spdx-expression-parse": "^3.0.0" - } - }, - "node_modules/watchpack": { - "version": "2.5.1", - "dev": true, - "license": "MIT", - "dependencies": { - "glob-to-regexp": "^0.4.1", - "graceful-fs": "^4.1.2" - }, - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/wcwidth": { - "version": "1.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "defaults": "^1.0.3" - } - }, - "node_modules/webidl-conversions": { - "version": "3.0.1", - "dev": true, - "license": "BSD-2-Clause" - }, - "node_modules/webpack": { - "version": "5.106.2", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@types/eslint-scope": "^3.7.7", - "@types/estree": "^1.0.8", - "@types/json-schema": "^7.0.15", - "@webassemblyjs/ast": "^1.14.1", - "@webassemblyjs/wasm-edit": "^1.14.1", - "@webassemblyjs/wasm-parser": "^1.14.1", - "acorn": "^8.16.0", - "acorn-import-phases": "^1.0.3", - "browserslist": "^4.28.1", - "chrome-trace-event": "^1.0.2", - "enhanced-resolve": "^5.20.0", - "es-module-lexer": "^2.0.0", - "eslint-scope": "5.1.1", - "events": "^3.2.0", - "glob-to-regexp": "^0.4.1", - "graceful-fs": "^4.2.11", - "loader-runner": "^4.3.1", - "mime-db": "^1.54.0", - "neo-async": "^2.6.2", - "schema-utils": "^4.3.3", - "tapable": "^2.3.0", - "terser-webpack-plugin": "^5.3.17", - "watchpack": "^2.5.1", - "webpack-sources": "^3.3.4" - }, - "bin": { - "webpack": "bin/webpack.js" - }, - "engines": { - "node": ">=10.13.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/webpack" - }, - "peerDependenciesMeta": { - "webpack-cli": { - "optional": true - } - } - }, - "node_modules/webpack-sources": { - "version": "3.4.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/whatwg-url": { - "version": "5.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "tr46": "~0.0.3", - "webidl-conversions": "^3.0.0" - } - }, - "node_modules/which": { - "version": "2.0.2", - "license": "ISC", - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/word-wrap": { - "version": "1.2.5", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/wrap-ansi": { - "version": "6.2.0", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/wrap-ansi/node_modules/emoji-regex": { - "version": "8.0.0", - "dev": true, - "license": "MIT" - }, - "node_modules/wrap-ansi/node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/wrap-ansi/node_modules/string-width": { - "version": "4.2.3", - "dev": true, - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/wrappy": { - "version": "1.0.2", - "license": "ISC" - }, - "node_modules/xmlbuilder": { - "version": "15.1.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8.0" - } - }, - "node_modules/xtend": { - "version": "4.0.2", - "license": "MIT", - "engines": { - "node": ">=0.4" - } - }, - "node_modules/y18n": { - "version": "5.0.8", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=10" - } - }, - "node_modules/yallist": { - "version": "4.0.0", - "dev": true, - "license": "ISC" - }, - "node_modules/yargs": { - "version": "17.7.2", - "dev": true, - "license": "MIT", - "dependencies": { - "cliui": "^8.0.1", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.3", - "y18n": "^5.0.5", - "yargs-parser": "^21.1.1" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/yargs-parser": { - "version": "21.1.1", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/yargs/node_modules/emoji-regex": { - "version": "8.0.0", - "dev": true, - "license": "MIT" - }, - "node_modules/yargs/node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/yargs/node_modules/string-width": { - "version": "4.2.3", - "dev": true, - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/yauzl": { - "version": "2.10.0", - "dev": true, - "license": "MIT", - "dependencies": { - "buffer-crc32": "~0.2.3", - "fd-slicer": "~1.1.0" - } - }, - "node_modules/yocto-queue": { - "version": "0.1.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/yoctocolors-cjs": { - "version": "2.1.3", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/zod": { - "version": "4.4.3", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/colinhacks" - } - } - } -} diff --git a/package.json b/package.json index bec08caa..fda9f416 100644 --- a/package.json +++ b/package.json @@ -2,6 +2,9 @@ "name": "codex-rebuild", "productName": "Codex", "version": "26.1007.71326", + "packageManager": "pnpm@10.33.0", + "codexRebuildRevision": 2, + "engines": { "node": ">=24 <25" }, "description": "Codex Electron App - Cross-platform Build", "main": "src/.vite/build/bootstrap.js", "scripts": { @@ -23,6 +26,11 @@ "build:linux": "npm run build:linux-x64 && npm run build:linux-arm64", "build:all": "npm run build:mac && npm run build:win && npm run build:linux", "test": "node --test scripts/*.test.js", + "check": "node scripts/check-scripts.js", + "test:maintenance": "node scripts/maintenance-smoke.js", + "windows:check-update": "node scripts/windows-maintenance.js discover", + "windows:candidate": "node scripts/windows-maintenance.js candidate", + "windows:verify-release": "node scripts/windows-maintenance.js verify-release", "sync": "node scripts/sync-upstream.js", "check-update": "node scripts/check-update.js", "bump-version": "node scripts/bump-version.js", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 00000000..0d5a6e91 --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,6300 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + '@sentry/electron': + specifier: ^7.5.0 + version: 7.13.0 + '@sentry/node': + specifier: 10.29.0 + version: 10.29.0 + better-sqlite3: + specifier: ^12.11.1 + version: 12.11.1 + electron-context-menu: + specifier: ^4.1.1 + version: 4.1.2 + electron-squirrel-startup: + specifier: ^1.0.1 + version: 1.0.1 + encoding: + specifier: ^0.1.13 + version: 0.1.13 + immer: + specifier: ^10.1.1 + version: 10.2.0 + lodash: + specifier: ^4.17.21 + version: 4.18.1 + memoizee: + specifier: ^0.4.15 + version: 0.4.17 + mime-types: + specifier: ^2.1.35 + version: 2.1.35 + node-pty: + specifier: ^1.1.0 + version: 1.1.0 + shell-env: + specifier: ^4.0.1 + version: 4.0.3 + shlex: + specifier: ^3.0.0 + version: 3.0.0 + smol-toml: + specifier: ^1.5.2 + version: 1.6.1 + tslib: + specifier: ^2.8.1 + version: 2.8.1 + zod: + specifier: ^4.1.13 + version: 4.4.3 + devDependencies: + '@electron-forge/cli': + specifier: ^7.10.2 + version: 7.11.1(encoding@0.1.13) + '@electron-forge/maker-deb': + specifier: ^7.10.2 + version: 7.11.1 + '@electron-forge/maker-dmg': + specifier: ^7.10.2 + version: 7.11.1 + '@electron-forge/maker-rpm': + specifier: ^7.10.2 + version: 7.11.1 + '@electron-forge/maker-squirrel': + specifier: ^7.10.2 + version: 7.11.1 + '@electron-forge/maker-zip': + specifier: ^7.10.2 + version: 7.11.1 + '@electron-forge/plugin-auto-unpack-natives': + specifier: ^7.10.2 + version: 7.11.1 + '@electron-forge/plugin-fuses': + specifier: ^7.10.2 + version: 7.11.1(@electron/fuses@1.8.0) + '@electron/asar': + specifier: ^4.1.2 + version: 4.2.0 + '@electron/fuses': + specifier: ^1.8.0 + version: 1.8.0 + '@electron/rebuild': + specifier: ^3.7.1 + version: 3.7.2 + acorn: + specifier: ^8.16.0 + version: 8.16.0 + electron: + specifier: ^42.0.1 + version: 42.0.1 + fast-xml-parser: + specifier: ^5.5.9 + version: 5.7.3 + +packages: + + '@apm-js-collab/code-transformer@0.8.2': + resolution: {integrity: sha512-YRjJjNq5KFSjDUoqu5pFUWrrsvGOxl6c3bu+uMFc9HNNptZ2rNU/TI2nLw4jnhQNtka972Ee2m3uqbvDQtPeCA==} + + '@apm-js-collab/tracing-hooks@0.3.1': + resolution: {integrity: sha512-Vu1CbmPURlN5fTboVuKMoJjbO5qcq9fA5YXpskx3dXe/zTBvjODFoerw+69rVBlRLrJpwPqSDqEuJDEKIrTldw==} + + '@electron-forge/cli@7.11.1': + resolution: {integrity: sha512-pk8AoLsr7t7LBAt0cFD06XFA6uxtPdvtLx06xeal7O9o7GHGCbj29WGwFoJ8Br/ENM0Ho868S3PrAn1PtBXt5g==} + engines: {node: '>= 16.4.0'} + hasBin: true + + '@electron-forge/core-utils@7.11.1': + resolution: {integrity: sha512-9UxRWVsfcziBsbAA2MS0Oz4yYovQCO2BhnGIfsbKNTBtMc/RcVSxAS0NMyymce44i43p1ZC/FqWhnt1XqYw3bQ==} + engines: {node: '>= 16.4.0'} + + '@electron-forge/core@7.11.1': + resolution: {integrity: sha512-YtuPLzggPKPabFAD2rOZFE0s7f4KaUTpGRduhSMbZUqpqD1TIPyfoDBpYiZvao3Ht8pyZeOJjbzcC0LpFs9gIQ==} + engines: {node: '>= 16.4.0'} + + '@electron-forge/maker-base@7.11.1': + resolution: {integrity: sha512-yhZrCGoN6bDeiB5DHFaueZ1h84AReElEj+f0hl2Ph4UbZnO0cnLpbx+Bs+XfMLAiA+beC8muB5UDK5ysfuT9BQ==} + engines: {node: '>= 16.4.0'} + + '@electron-forge/maker-deb@7.11.1': + resolution: {integrity: sha512-QTYiryQLYPDkq6pIfBmx0GQ6D8QatUkowH7rTlW5MnCUa0uumX0Xu7yGIjesuwW37fxT3Lv4xi+FSXMCm2eC1w==} + engines: {node: '>= 16.4.0'} + + '@electron-forge/maker-dmg@7.11.1': + resolution: {integrity: sha512-7zs5/Ewz1PcOl4N1102stFgBiFGWxU18+UPFUSd/fgf9MErBl4HBWuVNMIHyeJ/56rdfkcmTxTqE+9TBEYrZcg==} + engines: {node: '>= 16.4.0'} + + '@electron-forge/maker-rpm@7.11.1': + resolution: {integrity: sha512-iEfJPRQQyaTqk2EbUfZgulChNWvxGXeYUH0xBX/r5cj1pL4vcJXt3jLMQBVn3mk/0Ytv9UWRs8R/XuNWX6sf2w==} + engines: {node: '>= 16.4.0'} + + '@electron-forge/maker-squirrel@7.11.1': + resolution: {integrity: sha512-oSg7fgad6l+X0DjtRkSpMzB0AjzyDO4mb2gzM4kTodkP1ADeiMi08bxy0ZeCESqLm5+fG72cAPmEr3BAPvI1yw==} + engines: {node: '>= 16.4.0'} + + '@electron-forge/maker-zip@7.11.1': + resolution: {integrity: sha512-30rcp0AbJLfkFBX2hmO14LKXx7z9V61LffTVbTCFMh5vUB2kZvcA5xAhsBk2oUJWfGVxe1DuSEU0rDR9bUMHUg==} + engines: {node: '>= 16.4.0'} + + '@electron-forge/plugin-auto-unpack-natives@7.11.1': + resolution: {integrity: sha512-5uRM3WNv7jIeDt8pLP3V4U2puWHPGJ/3qRuSE47RKgTp5qxpZidWHSYcEJJxjoqOL/7KFwSqKSQ/a36GoZV4Fg==} + engines: {node: '>= 16.4.0'} + + '@electron-forge/plugin-base@7.11.1': + resolution: {integrity: sha512-lKpSOV1GA3FoYiD9k05i6v4KaQVmojnRgCr7d6VL1bFp13QOtXSaAWhFI9mtSY7rGElOacX6Zt7P7rPoB8T9eQ==} + engines: {node: '>= 16.4.0'} + + '@electron-forge/plugin-fuses@7.11.1': + resolution: {integrity: sha512-Td517mHf+RjQAayFDM2kKb7NaGdRXrZfPbc7KOHlGbXthp5YTkFu2cCZGWokiqt1y1wsFaAodULhqBIg7vbbbw==} + engines: {node: '>= 16.4.0'} + peerDependencies: + '@electron/fuses': ^1.0.0 + + '@electron-forge/publisher-base@7.11.1': + resolution: {integrity: sha512-rXE9oMFGMtdQrixnumWYH5TTGsp99iPHZb3jI74YWq518ctCh6DlIgWlhf6ok2X0+lhWovcIb45KJucUFAQ13w==} + engines: {node: '>= 16.4.0'} + + '@electron-forge/shared-types@7.11.1': + resolution: {integrity: sha512-vvBWdAEh53UJlDGUevpaJk1+sqDMQibfrbHR+0IPA4MPyQex7/Uhv3vYH9oGHujBVAChQahjAuJt0fG6IJBLZg==} + engines: {node: '>= 16.4.0'} + + '@electron-forge/template-base@7.11.1': + resolution: {integrity: sha512-XpTaEf+EfQw+0BlSAtSpZKYIKYvKu4raNzSGHZZoSYHp+HDC7R+MlpFQmSJiGdYQzQ14C+uxO42tVjgM0DMbpw==} + engines: {node: '>= 16.4.0'} + + '@electron-forge/template-vite-typescript@7.11.1': + resolution: {integrity: sha512-Us4AHXFb+4z+gXgZImSqMBS63oKnsQWLOhqRg321xiDzu2UcQPlwgWNb4rAEKNVC1e7LXrUNDHuBiTrQkvWXbg==} + engines: {node: '>= 16.4.0'} + + '@electron-forge/template-vite@7.11.1': + resolution: {integrity: sha512-Or8Lxf4awoeUZoMTKJEw5KQDIhqOFs24WhVka3yZXxc6VgVWN79KmYKYM6uM/YMQttmafhsBhY2t1Lxo1WR/ug==} + engines: {node: '>= 16.4.0'} + + '@electron-forge/template-webpack-typescript@7.11.1': + resolution: {integrity: sha512-6ExfFnFkHBz8rvRFTFg5HVGTC12uJpbVk4q8DVg0R8rhhxhqiVNh8lF2UPtZ2yT2UtGWjXNVlyP3Y3T6q6E3GQ==} + engines: {node: '>= 16.4.0'} + + '@electron-forge/template-webpack@7.11.1': + resolution: {integrity: sha512-15lbXxi+er461MPk6sbwAOyjofAHwmQjTvxNCiNpaU2naEwbj3t0SlLq/BMr5HxnVOaMmA7+lKV9afkIom+d4Q==} + engines: {node: '>= 16.4.0'} + + '@electron-forge/tracer@7.11.1': + resolution: {integrity: sha512-tiB6cglVQFcSw9N8GRwVwZUeB9u0DOx2Mj7aFXBUsFLUYQapvVGv51tUSy/UAW5lvmubGscYIILuVko+II3+NA==} + engines: {node: '>= 14.17.5'} + + '@electron/asar@3.4.1': + resolution: {integrity: sha512-i4/rNPRS84t0vSRa2HorerGRXWyF4vThfHesw0dmcWHp+cspK743UanA0suA5Q5y8kzY2y6YKrvbIUn69BCAiA==} + engines: {node: '>=10.12.0'} + hasBin: true + + '@electron/asar@4.2.0': + resolution: {integrity: sha512-npW1NW5yy8EB9XY/vEw9sUdgmq0sJEhmSBb6bqyFOAw1CSkrhvAvO6QWlW8CdIMo8VN1lkdF345l/MeW0LrY0Q==} + engines: {node: '>=22.12.0'} + hasBin: true + + '@electron/fuses@1.8.0': + resolution: {integrity: sha512-zx0EIq78WlY/lBb1uXlziZmDZI4ubcCXIMJ4uGjXzZW0nS19TjSPeXPAjzzTmKQlJUZm0SbmZhPKP7tuQ1SsEw==} + hasBin: true + + '@electron/get@3.1.0': + resolution: {integrity: sha512-F+nKc0xW+kVbBRhFzaMgPy3KwmuNTYX1fx6+FxxoSnNgwYX6LD7AKBTWkU0MQ6IBoe7dz069CNkR673sPAgkCQ==} + engines: {node: '>=14'} + + '@electron/get@5.0.0': + resolution: {integrity: sha512-pjoBpru1KdEtcExBnuHAP1cAc/5faoedw0hzJkL3o4/IJp7HNF1+fbrdxT3gMYRX2oJfvnA/WXeCTVQpYYxyJA==} + engines: {node: '>=22.12.0'} + + '@electron/node-gyp@https://codeload.github.com/electron/node-gyp/tar.gz/06b29aafb7708acef8b3669835c8a7857ebc92d2': + resolution: {tarball: https://codeload.github.com/electron/node-gyp/tar.gz/06b29aafb7708acef8b3669835c8a7857ebc92d2} + version: 10.2.0-electron.1 + engines: {node: '>=12.13.0'} + hasBin: true + + '@electron/notarize@2.5.0': + resolution: {integrity: sha512-jNT8nwH1f9X5GEITXaQ8IF/KdskvIkOFfB2CvwumsveVidzpSc+mvhhTMdAGSYF3O+Nq49lJ7y+ssODRXu06+A==} + engines: {node: '>= 10.0.0'} + + '@electron/osx-sign@1.3.3': + resolution: {integrity: sha512-KZ8mhXvWv2rIEgMbWZ4y33bDHyUKMXnx4M0sTyPNK/vcB81ImdeY9Ggdqy0SWbMDgmbqyQ+phgejh6V3R2QuSg==} + engines: {node: '>=12.0.0'} + hasBin: true + + '@electron/packager@18.4.4': + resolution: {integrity: sha512-fTUCmgL25WXTcFpM1M72VmFP8w3E4d+KNzWxmTDRpvwkfn/S206MAtM2cy0GF78KS9AwASMOUmlOIzCHeNxcGQ==} + engines: {node: '>= 16.13.0'} + hasBin: true + + '@electron/rebuild@3.7.2': + resolution: {integrity: sha512-19/KbIR/DAxbsCkiaGMXIdPnMCJLkcf8AvGnduJtWBs/CBwiAjY1apCqOLVxrXg+rtXFCngbXhBanWjxLUt1Mg==} + engines: {node: '>=12.13.0'} + hasBin: true + + '@electron/universal@2.0.3': + resolution: {integrity: sha512-Wn9sPYIVFRFl5HmwMJkARCCf7rqK/EurkfQ/rJZ14mHP3iYTjZSIOSVonEAnhWeAXwtw7zOekGRlc6yTtZ0t+g==} + engines: {node: '>=16.4'} + + '@electron/windows-sign@1.2.2': + resolution: {integrity: sha512-dfZeox66AvdPtb2lD8OsIIQh12Tp0GNCRUDfBHIKGpbmopZto2/A8nSpYYLoedPIHpqkeblZ/k8OV0Gy7PYuyQ==} + engines: {node: '>=14.14'} + hasBin: true + + '@fastify/otel@0.18.0': + resolution: {integrity: sha512-3TASCATfw+ctICSb4ymrv7iCm0qJ0N9CarB+CZ7zIJ7KqNbwI5JjyDL1/sxoC0ccTO1Zyd1iQ+oqncPg5FJXaA==} + peerDependencies: + '@opentelemetry/api': ^1.9.0 + + '@gar/promisify@1.1.3': + resolution: {integrity: sha512-k2Ty1JcVojjJFwrg/ThKi2ujJ7XNLYaFGNB/bWT9wGR+oSMJHMa5w+CUq6p/pVrKeNNgA7pCqEcjSnHVoqJQFw==} + + '@inquirer/checkbox@3.0.1': + resolution: {integrity: sha512-0hm2nrToWUdD6/UHnel/UKGdk1//ke5zGUpHIvk5ZWmaKezlGxZkOJXNSWsdxO/rEqTkbB3lNC2J6nBElV2aAQ==} + engines: {node: '>=18'} + + '@inquirer/confirm@4.0.1': + resolution: {integrity: sha512-46yL28o2NJ9doViqOy0VDcoTzng7rAb6yPQKU7VDLqkmbCaH4JqK4yk4XqlzNWy9PVC5pG1ZUXPBQv+VqnYs2w==} + engines: {node: '>=18'} + + '@inquirer/core@9.2.1': + resolution: {integrity: sha512-F2VBt7W/mwqEU4bL0RnHNZmC/OxzNx9cOYxHqnXX3MP6ruYvZUZAW9imgN9+h/uBT/oP8Gh888J2OZSbjSeWcg==} + engines: {node: '>=18'} + + '@inquirer/editor@3.0.1': + resolution: {integrity: sha512-VA96GPFaSOVudjKFraokEEmUQg/Lub6OXvbIEZU1SDCmBzRkHGhxoFAVaF30nyiB4m5cEbDgiI2QRacXZ2hw9Q==} + engines: {node: '>=18'} + + '@inquirer/expand@3.0.1': + resolution: {integrity: sha512-ToG8d6RIbnVpbdPdiN7BCxZGiHOTomOX94C2FaT5KOHupV40tKEDozp12res6cMIfRKrXLJyexAZhWVHgbALSQ==} + engines: {node: '>=18'} + + '@inquirer/figures@1.0.15': + resolution: {integrity: sha512-t2IEY+unGHOzAaVM5Xx6DEWKeXlDDcNPeDyUpsRc6CUhBfU3VQOEl+Vssh7VNp1dR8MdUJBWhuObjXCsVpjN5g==} + engines: {node: '>=18'} + + '@inquirer/input@3.0.1': + resolution: {integrity: sha512-BDuPBmpvi8eMCxqC5iacloWqv+5tQSJlUafYWUe31ow1BVXjW2a5qe3dh4X/Z25Wp22RwvcaLCc2siHobEOfzg==} + engines: {node: '>=18'} + + '@inquirer/number@2.0.1': + resolution: {integrity: sha512-QpR8jPhRjSmlr/mD2cw3IR8HRO7lSVOnqUvQa8scv1Lsr3xoAMMworcYW3J13z3ppjBFBD2ef1Ci6AE5Qn8goQ==} + engines: {node: '>=18'} + + '@inquirer/password@3.0.1': + resolution: {integrity: sha512-haoeEPUisD1NeE2IanLOiFr4wcTXGWrBOyAyPZi1FfLJuXOzNmxCJPgUrGYKVh+Y8hfGJenIfz5Wb/DkE9KkMQ==} + engines: {node: '>=18'} + + '@inquirer/prompts@6.0.1': + resolution: {integrity: sha512-yl43JD/86CIj3Mz5mvvLJqAOfIup7ncxfJ0Btnl0/v5TouVUyeEdcpknfgc+yMevS/48oH9WAkkw93m7otLb/A==} + engines: {node: '>=18'} + + '@inquirer/rawlist@3.0.1': + resolution: {integrity: sha512-VgRtFIwZInUzTiPLSfDXK5jLrnpkuSOh1ctfaoygKAdPqjcjKYmGh6sCY1pb0aGnCGsmhUxoqLDUAU0ud+lGXQ==} + engines: {node: '>=18'} + + '@inquirer/search@2.0.1': + resolution: {integrity: sha512-r5hBKZk3g5MkIzLVoSgE4evypGqtOannnB3PKTG9NRZxyFRKcfzrdxXXPcoJQsxJPzvdSU2Rn7pB7lw0GCmGAg==} + engines: {node: '>=18'} + + '@inquirer/select@3.0.1': + resolution: {integrity: sha512-lUDGUxPhdWMkN/fHy1Lk7pF3nK1fh/gqeyWXmctefhxLYxlDsc7vsPBEpxrfVGDsVdyYJsiJoD4bJ1b623cV1Q==} + engines: {node: '>=18'} + + '@inquirer/type@1.5.5': + resolution: {integrity: sha512-MzICLu4yS7V8AA61sANROZ9vT1H3ooca5dSmI1FjZkzq7o/koMsRfQSzRtFo+F3Ao4Sf1C0bpLKejpKB/+j6MA==} + engines: {node: '>=18'} + + '@inquirer/type@2.0.0': + resolution: {integrity: sha512-XvJRx+2KR3YXyYtPUUy+qd9i7p+GO9Ko6VIIpWlBrpWwXDv8WLFeHTxz35CfQFUiBMLXlGHhGzys7lqit9gWag==} + engines: {node: '>=18'} + + '@jridgewell/gen-mapping@0.3.13': + resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/source-map@0.3.11': + resolution: {integrity: sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==} + + '@jridgewell/sourcemap-codec@1.5.5': + resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@listr2/prompt-adapter-inquirer@2.0.22': + resolution: {integrity: sha512-hV36ZoY+xKL6pYOt1nPNnkciFkn89KZwqLhAFzJvYysAvL5uBQdiADZx/8bIDXIukzzwG0QlPYolgMzQUtKgpQ==} + engines: {node: '>=18.0.0'} + peerDependencies: + '@inquirer/prompts': '>= 3 < 8' + + '@malept/cross-spawn-promise@1.1.1': + resolution: {integrity: sha512-RTBGWL5FWQcg9orDOCcp4LvItNzUPcyEU9bwaeJX0rJ1IQxzucC48Y0/sQLp/g6t99IQgAlGIaesJS+gTn7tVQ==} + engines: {node: '>= 10'} + + '@malept/cross-spawn-promise@2.0.0': + resolution: {integrity: sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==} + engines: {node: '>= 12.13.0'} + + '@nodable/entities@2.1.0': + resolution: {integrity: sha512-nyT7T3nbMyBI/lvr6L5TyWbFJAI9FTgVRakNoBqCD+PmID8DzFrrNdLLtHMwMszOtqZa8PAOV24ZqDnQrhQINA==} + + '@nodelib/fs.scandir@2.1.5': + resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==} + engines: {node: '>= 8'} + + '@nodelib/fs.stat@2.0.5': + resolution: {integrity: sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==} + engines: {node: '>= 8'} + + '@nodelib/fs.walk@1.2.8': + resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==} + engines: {node: '>= 8'} + + '@npmcli/fs@2.1.2': + resolution: {integrity: sha512-yOJKRvohFOaLqipNtwYB9WugyZKhC/DZC4VYPmpaCzDBrA8YpK3qHZ8/HGscMnE4GqbkLNuVcCnxkeQEdGt6LQ==} + engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} + + '@npmcli/move-file@2.0.1': + resolution: {integrity: sha512-mJd2Z5TjYWq/ttPLLGqArdtnC74J6bOzg4rMDnN+p1xTacZ2yPRCk2y0oSWQtygLR9YVQXgOcONrwtnk3JupxQ==} + engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} + deprecated: This functionality has been moved to @npmcli/fs + + '@opentelemetry/api-logs@0.207.0': + resolution: {integrity: sha512-lAb0jQRVyleQQGiuuvCOTDVspc14nx6XJjP4FspJ1sNARo3Regq4ZZbrc3rN4b1TYSuUCvgH+UXUPug4SLOqEQ==} + engines: {node: '>=8.0.0'} + + '@opentelemetry/api-logs@0.208.0': + resolution: {integrity: sha512-CjruKY9V6NMssL/T1kAFgzosF1v9o6oeN+aX5JB/C/xPNtmgIJqcXHG7fA82Ou1zCpWGl4lROQUKwUNE1pMCyg==} + engines: {node: '>=8.0.0'} + + '@opentelemetry/api-logs@0.212.0': + resolution: {integrity: sha512-TEEVrLbNROUkYY51sBJGk7lO/OLjuepch8+hmpM6ffMJQ2z/KVCjdHuCFX6fJj8OkJP2zckPjrJzQtXU3IAsFg==} + engines: {node: '>=8.0.0'} + + '@opentelemetry/api-logs@0.214.0': + resolution: {integrity: sha512-40lSJeqYO8Uz2Yj7u94/SJWE/wONa7rmMKjI1ZcIjgf3MHNHv1OZUCrCETGuaRF62d5pQD1wKIW+L4lmSMTzZA==} + engines: {node: '>=8.0.0'} + + '@opentelemetry/api@1.9.1': + resolution: {integrity: sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==} + engines: {node: '>=8.0.0'} + + '@opentelemetry/context-async-hooks@2.7.1': + resolution: {integrity: sha512-OPFBYuXEn1E4ja3Y6eeA7O+ZnLBNcXTV5Cgsn1VaqBZ6hC5FnpZPLBNme1LJY8ZtF4aOujPKFoeWN4ik487KuQ==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': '>=1.0.0 <1.10.0' + + '@opentelemetry/core@2.2.0': + resolution: {integrity: sha512-FuabnnUm8LflnieVxs6eP7Z383hgQU4W1e3KJS6aOG3RxWxcHyBxH8fDMHNgu/gFx/M2jvTOW/4/PHhLz6bjWw==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': '>=1.0.0 <1.10.0' + + '@opentelemetry/core@2.6.1': + resolution: {integrity: sha512-8xHSGWpJP9wBxgBpnqGL0R3PbdWQndL1Qp50qrg71+B28zK5OQmUgcDKLJgzyAAV38t4tOyLMGDD60LneR5W8g==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': '>=1.0.0 <1.10.0' + + '@opentelemetry/core@2.7.1': + resolution: {integrity: sha512-QAqIj32AtK6+pEVNG7EOVxHdE06RP+FM5qpiEJ4RtDcFIqKUZHYhl7/7UY5efhwmwNAg7j8QbJVBLxMerc0+gw==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': '>=1.0.0 <1.10.0' + + '@opentelemetry/instrumentation-amqplib@0.55.0': + resolution: {integrity: sha512-5ULoU8p+tWcQw5PDYZn8rySptGSLZHNX/7srqo2TioPnAAcvTy6sQFQXsNPrAnyRRtYGMetXVyZUy5OaX1+IfA==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-amqplib@0.61.0': + resolution: {integrity: sha512-mCKoyTGfRNisge4br0NpOFSy2Z1NnEW8hbCJdUDdJFHrPqVzc4IIBPA/vX0U+LUcQqrQvJX+HMIU0dbDRe0i0Q==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-connect@0.52.0': + resolution: {integrity: sha512-GXPxfNB5szMbV3I9b7kNWSmQBoBzw7MT0ui6iU/p+NIzVx3a06Ri2cdQO7tG9EKb4aKSLmfX9Cw5cKxXqX6Ohg==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-connect@0.57.0': + resolution: {integrity: sha512-FMEBChnI4FLN5TE9DHwfH7QpNir1JzXno1uz/TAucVdLCyrG0jTrKIcNHt/i30A0M2AunNBCkcd8Ei26dIPKdg==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-dataloader@0.26.0': + resolution: {integrity: sha512-P2BgnFfTOarZ5OKPmYfbXfDFjQ4P9WkQ1Jji7yH5/WwB6Wm/knynAoA1rxbjWcDlYupFkyT0M1j6XLzDzy0aCA==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-dataloader@0.31.0': + resolution: {integrity: sha512-f654tZFQXS5YeLDNb9KySrwtg7SnqZN119FauD7acBoTzuLduaiGTNz88ixcVSOOMGZ+EjJu/RFtx5klObC95g==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-express@0.57.0': + resolution: {integrity: sha512-HAdx/o58+8tSR5iW+ru4PHnEejyKrAy9fYFhlEI81o10nYxrGahnMAHWiSjhDC7UQSY3I4gjcPgSKQz4rm/asg==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-fs@0.28.0': + resolution: {integrity: sha512-FFvg8fq53RRXVBRHZViP+EMxMR03tqzEGpuq55lHNbVPyFklSVfQBN50syPhK5UYYwaStx0eyCtHtbRreusc5g==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-fs@0.33.0': + resolution: {integrity: sha512-sCZWXGalQ01wr3tAhSR9ucqFJ0phidpAle6/17HVjD6gN8FLmZMK/8sKxdXYHy3PbnlV1P4zeiSVFNKpbFMNLA==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-generic-pool@0.52.0': + resolution: {integrity: sha512-ISkNcv5CM2IwvsMVL31Tl61/p2Zm2I2NAsYq5SSBgOsOndT0TjnptjufYVScCnD5ZLD1tpl4T3GEYULLYOdIdQ==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-generic-pool@0.57.0': + resolution: {integrity: sha512-orhmlaK+ZIW9hKU+nHTbXrCSXZcH83AescTqmpamHRobRmYSQwRbD0a1odc0yAzuzOtxYiHiXAnpnIpaSSY7Ow==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-graphql@0.56.0': + resolution: {integrity: sha512-IPvNk8AFoVzTAM0Z399t34VDmGDgwT6rIqCUug8P9oAGerl2/PEIYMPOl/rerPGu+q8gSWdmbFSjgg7PDVRd3Q==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-graphql@0.62.0': + resolution: {integrity: sha512-3YNuLVPUxafXkH1jBAbGsKNsP3XVzcFDhCDCE3OqBwCwShlqQbLMRMFh1T/d5jaVZiGVmSsfof+ICKD2iOV8xg==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-hapi@0.55.0': + resolution: {integrity: sha512-prqAkRf9e4eEpy4G3UcR32prKE8NLNlA90TdEU1UsghOTg0jUvs40Jz8LQWFEs5NbLbXHYGzB4CYVkCI8eWEVQ==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-hapi@0.60.0': + resolution: {integrity: sha512-aNljZKYrEa7obLAxd1bCEDxF7kzCLGXTuTJZ8lMR9rIVEjmuKBXN1gfqpm/OB//Zc2zP4iIve1jBp7sr3mQV6w==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-http@0.208.0': + resolution: {integrity: sha512-rhmK46DRWEbQQB77RxmVXGyjs6783crXCnFjYQj+4tDH/Kpv9Rbg3h2kaNyp5Vz2emF1f9HOQQvZoHzwMWOFZQ==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-http@0.214.0': + resolution: {integrity: sha512-FlkDhZDRjDJDcO2LcSCtjRpkal1NJ8y0fBqBhTvfAR3JSYY2jAIj1kSS5IjmEBt4c3aWv+u/lqLuoCDrrKCSKg==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-ioredis@0.56.0': + resolution: {integrity: sha512-XSWeqsd3rKSsT3WBz/JKJDcZD4QYElZEa0xVdX8f9dh4h4QgXhKRLorVsVkK3uXFbC2sZKAS2Ds+YolGwD83Dg==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-ioredis@0.62.0': + resolution: {integrity: sha512-ZYt//zcPve8qklaZX+5Z4MkU7UpEkFRrxsf2cnaKYBitqDnsCN69CPAuuMOX6NYdW2rG9sFy7V/QWtBlP5XiNQ==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-kafkajs@0.18.0': + resolution: {integrity: sha512-KCL/1HnZN5zkUMgPyOxfGjLjbXjpd4odDToy+7c+UsthIzVLFf99LnfIBE8YSSrYE4+uS7OwJMhvhg3tWjqMBg==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-kafkajs@0.23.0': + resolution: {integrity: sha512-4K+nVo+zI+aDz0Z85SObwbdixIbzS9moIuKJaYsdlzcHYnKOPtB7ya8r8Ezivy/GVIBHiKJVq4tv+BEkgOMLaQ==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-knex@0.53.0': + resolution: {integrity: sha512-xngn5cH2mVXFmiT1XfQ1aHqq1m4xb5wvU6j9lSgLlihJ1bXzsO543cpDwjrZm2nMrlpddBf55w8+bfS4qDh60g==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-knex@0.58.0': + resolution: {integrity: sha512-Hc/o8fSsaWxZ8r1Yw4rNDLwTpUopTf4X32y4W6UhlHmW8Wizz8wfhgOKIelSeqFVTKBBPIDUOsQWuIMxBmu8Bw==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-koa@0.57.0': + resolution: {integrity: sha512-3JS8PU/D5E3q295mwloU2v7c7/m+DyCqdu62BIzWt+3u9utjxC9QS7v6WmUNuoDN3RM+Q+D1Gpj13ERo+m7CGg==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.9.0 + + '@opentelemetry/instrumentation-koa@0.62.0': + resolution: {integrity: sha512-uVip0VuGUQXZ+vFxkKxAUNq8qNl+VFlyHDh/U6IQ8COOEDfbEchdaHnpFrMYF3psZRUuoSIgb7xOeXj00RdwDA==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.9.0 + + '@opentelemetry/instrumentation-lru-memoizer@0.53.0': + resolution: {integrity: sha512-LDwWz5cPkWWr0HBIuZUjslyvijljTwmwiItpMTHujaULZCxcYE9eU44Qf/pbVC8TulT0IhZi+RoGvHKXvNhysw==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-lru-memoizer@0.58.0': + resolution: {integrity: sha512-6grM3TdMyHzlGY1cUA+mwoPueB1F3dYKgKtZIH6jOFXqfHAByyLTc+6PFjGM9tKh52CFBJaDwodNlL/Td39z7Q==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-mongodb@0.61.0': + resolution: {integrity: sha512-OV3i2DSoY5M/pmLk+68xr5RvkHU8DRB3DKMzYJdwDdcxeLs62tLbkmRyqJZsYf3Ht7j11rq35pHOWLuLzXL7pQ==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-mongodb@0.67.0': + resolution: {integrity: sha512-1WJp5N1lYfHq2IhECOTewFs5Tf2NfUOwQRqs/rZdXKTezArMlucxgzAaqcgp3A3YREXopXTpXHsxZTGHjNhMdQ==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-mongoose@0.55.0': + resolution: {integrity: sha512-5afj0HfF6aM6Nlqgu6/PPHFk8QBfIe3+zF9FGpX76jWPS0/dujoEYn82/XcLSaW5LPUDW8sni+YeK0vTBNri+w==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-mongoose@0.60.0': + resolution: {integrity: sha512-8BahAZpKsOoc+lrZGb7Ofn4g3z8qtp5IxDfvAVpKXsEheQN7ONMH5djT5ihy6yf8yyeQJGS0gXFfpEAEeEHqQg==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-mysql2@0.55.0': + resolution: {integrity: sha512-0cs8whQG55aIi20gnK8B7cco6OK6N+enNhW0p5284MvqJ5EPi+I1YlWsWXgzv/V2HFirEejkvKiI4Iw21OqDWg==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-mysql2@0.60.0': + resolution: {integrity: sha512-m/5d3bxQALllCzezYDk/6vajh0tj5OijMMvOZGr+qN1NMXm1dzMNwyJ0gNZW7Fo3YFRyj/jJMxIw+W7d525dlw==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-mysql@0.54.0': + resolution: {integrity: sha512-bqC1YhnwAeWmRzy1/Xf9cDqxNG2d/JDkaxnqF5N6iJKN1eVWI+vg7NfDkf52/Nggp3tl1jcC++ptC61BD6738A==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-mysql@0.60.0': + resolution: {integrity: sha512-08pO8GFPEIz2zquKDGteBZDNmwketdgH8hTe9rVYgW9kCJXq1Psj3wPQGx+VaX4ZJKCfPeoLMYup9+cxHvZyVQ==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-pg@0.61.0': + resolution: {integrity: sha512-UeV7KeTnRSM7ECHa3YscoklhUtTQPs6V6qYpG283AB7xpnPGCUCUfECFT9jFg6/iZOQTt3FHkB1wGTJCNZEvPw==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-pg@0.66.0': + resolution: {integrity: sha512-KxfLGXBb7k2ueaPJfq2GXBDXBly8P+SpR/4Mj410hhNgmQF3sCqwXvUBQxZQkDAmsdBAoenM+yV1LhtsMRamcA==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-redis@0.57.0': + resolution: {integrity: sha512-bCxTHQFXzrU3eU1LZnOZQ3s5LURxQPDlU3/upBzlWY77qOI1GZuGofazj3jtzjctMJeBEJhNwIFEgRPBX1kp/Q==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-redis@0.62.0': + resolution: {integrity: sha512-y3pPpot7WzR/8JtHcYlTYsyY8g+pbFhAqbwAuG5bLPnR6v6pt1rQc0DpH0OlGP/9CZbWBP+Zhwp9yFoygf/ZXQ==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-tedious@0.27.0': + resolution: {integrity: sha512-jRtyUJNZppPBjPae4ZjIQ2eqJbcRaRfJkr0lQLHFmOU/no5A6e9s1OHLd5XZyZoBJ/ymngZitanyRRA5cniseA==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-tedious@0.33.0': + resolution: {integrity: sha512-Q6WQwAD01MMTub31GlejoiFACYNw26J426wyjvU7by7fDIr2nZXNW4vhTGs7i7F0TnXBO3xN688g1tdUgYwJ5w==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation-undici@0.19.0': + resolution: {integrity: sha512-Pst/RhR61A2OoZQZkn6OLpdVpXp6qn3Y92wXa6umfJe9rV640r4bc6SWvw4pPN6DiQqPu2c8gnSSZPDtC6JlpQ==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.7.0 + + '@opentelemetry/instrumentation@0.207.0': + resolution: {integrity: sha512-y6eeli9+TLKnznrR8AZlQMSJT7wILpXH+6EYq5Vf/4Ao+huI7EedxQHwRgVUOMLFbe7VFDvHJrX9/f4lcwnJsA==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation@0.208.0': + resolution: {integrity: sha512-Eju0L4qWcQS+oXxi6pgh7zvE2byogAkcsVv0OjHF/97iOz1N/aKE6etSGowYkie+YA1uo6DNwdSxaaNnLvcRlA==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation@0.212.0': + resolution: {integrity: sha512-IyXmpNnifNouMOe0I/gX7ENfv2ZCNdYTF0FpCsoBcpbIHzk81Ww9rQTYTnvghszCg7qGrIhNvWC8dhEifgX9Jg==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/instrumentation@0.214.0': + resolution: {integrity: sha512-MHqEX5Dk59cqVah5LiARMACku7jXSVk9iVDWOea4x3cr7VfdByeDCURK6o1lntT1JS/Tsovw01UJrBhN3/uC5w==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + + '@opentelemetry/redis-common@0.38.3': + resolution: {integrity: sha512-VCghU1JYs/4gP6Gqf/xro9MEsZ7LrMv2uONVsaESKL38ZOB9BqnI98FfS23wjMnHlpuE+TTaWSoAVNpTwYXzjw==} + engines: {node: ^18.19.0 || >=20.6.0} + + '@opentelemetry/resources@2.7.1': + resolution: {integrity: sha512-DeT6KKolmC4e/dRQvMQ/RwlnzhaqeiFOXY5ngoOPJ07GgVVKxZOg9EcrNZb5aTzUn+iCrJldAgOfQm1O/QfPAQ==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': '>=1.3.0 <1.10.0' + + '@opentelemetry/sdk-trace-base@2.7.1': + resolution: {integrity: sha512-NAYIlsF8MPUsKqJMiDQJTMPOmlbawC1Iz/omMLygZ1C9am8fTKYjTaI+OZM+WTY3t3Glo0wnOg/6/pac6RGPPw==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': '>=1.3.0 <1.10.0' + + '@opentelemetry/semantic-conventions@1.40.0': + resolution: {integrity: sha512-cifvXDhcqMwwTlTK04GBNeIe7yyo28Mfby85QXFe1Yk8nmi36Ab/5UQwptOx84SsoGNRg+EVSjwzfSZMy6pmlw==} + engines: {node: '>=14'} + + '@opentelemetry/sql-common@0.41.2': + resolution: {integrity: sha512-4mhWm3Z8z+i508zQJ7r6Xi7y4mmoJpdvH0fZPFRkWrdp5fq7hhZ2HhYokEOLkfqSMgPR4Z9EyB3DBkbKGOqZiQ==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.1.0 + + '@prisma/instrumentation@6.19.0': + resolution: {integrity: sha512-QcuYy25pkXM8BJ37wVFBO7Zh34nyRV1GOb2n3lPkkbRYfl4hWl3PTcImP41P0KrzVXfa/45p6eVCos27x3exIg==} + peerDependencies: + '@opentelemetry/api': ^1.8 + + '@prisma/instrumentation@7.6.0': + resolution: {integrity: sha512-ZPW2gRiwpPzEfgeZgaekhqXrbW+Y2RJKHVqUmlhZhKzRNCcvR6DykzylDrynpArKKRQtLxoZy36fK7U0p3pdgQ==} + peerDependencies: + '@opentelemetry/api': ^1.8 + + '@sentry-internal/browser-utils@10.50.0': + resolution: {integrity: sha512-42bxyRTxnCmYlWnvz4CxikuQNanw8UNma2WJrtxJ0f1MAJV2GhQGSHDLnA+lvFlmiz6qct3pfen/NXGyOTegTA==} + engines: {node: '>=18'} + + '@sentry-internal/feedback@10.50.0': + resolution: {integrity: sha512-0k9XZF0wn86f77mIO2U3gNNyDZooy139CnEanRzHinrN106vVzvBZ6TUEQoHtoO1fqQxr+nWWVrqV/PXUqk47w==} + engines: {node: '>=18'} + + '@sentry-internal/replay-canvas@10.50.0': + resolution: {integrity: sha512-jx6RKBmcJSWdI92qDGS/sBv1w+7Cww879Z/moX7bw7ipHa/Ts3iDcB3rgZwvhmi17U+mvYsbJeL2DXkPo3TjPw==} + engines: {node: '>=18'} + + '@sentry-internal/replay@10.50.0': + resolution: {integrity: sha512-51FYNfnvVLAWw1rrEWPFfwHuMRb9mkVCFGA4J9/un7SpeGBsQDziGB0Di4fsCxI7+EdSBpfLHPF0csKtCCw0oQ==} + engines: {node: '>=18'} + + '@sentry/browser@10.50.0': + resolution: {integrity: sha512-1f6rAvET6myiTaSeYqvaaBwvq1LfxqWjAPIoAW/NVC9bPMkeEcuvgDajHrnZMrBeWoJ81NMyoLkyX+iOc7MoFA==} + engines: {node: '>=18'} + + '@sentry/core@10.29.0': + resolution: {integrity: sha512-olQ2DU9dA/Bwsz3PtA9KNXRMqBWRQSkPw+MxwWEoU1K1qtiM9L0j6lbEFb5iSY3d7WYD5MB+1d5COugjSBrHtw==} + engines: {node: '>=18'} + + '@sentry/core@10.50.0': + resolution: {integrity: sha512-J4A+vzUO3adl0TkFCjaN1+4miamrjHiEIYuLHiuu1lmAjq5WIVw32ObvAh4yMwNtxyaEMosTrrh5M6f12XSJFg==} + engines: {node: '>=18'} + + '@sentry/electron@7.13.0': + resolution: {integrity: sha512-zW/1c9fKafCZsvhRRp9mIDH9bSvzBiIUwoN087zDDHc0vatVsqqai8nUk0bUewwYZY4Inia7r5w+kPWi8LXZzg==} + peerDependencies: + '@sentry/node-native': 10.50.0 + peerDependenciesMeta: + '@sentry/node-native': + optional: true + + '@sentry/node-core@10.29.0': + resolution: {integrity: sha512-f/Y0okHhPPb5HnYNBqCivJ2YuXtSadvcIx16dzU5mHQxZhgGednUCPEX7rsvPcd4HneQz12HKLqxbAmNu+b3FA==} + engines: {node: '>=18'} + peerDependencies: + '@opentelemetry/api': ^1.9.0 + '@opentelemetry/context-async-hooks': ^1.30.1 || ^2.1.0 || ^2.2.0 + '@opentelemetry/core': ^1.30.1 || ^2.1.0 || ^2.2.0 + '@opentelemetry/instrumentation': '>=0.57.1 <1' + '@opentelemetry/resources': ^1.30.1 || ^2.1.0 || ^2.2.0 + '@opentelemetry/sdk-trace-base': ^1.30.1 || ^2.1.0 || ^2.2.0 + '@opentelemetry/semantic-conventions': ^1.37.0 + + '@sentry/node-core@10.50.0': + resolution: {integrity: sha512-Eb1BYf4Lc7ZYmdX3acKP6SgyGikrBA370gbGHaWI5jRu7G7vig8sIu1ghPmY5AlvqBPOetado7GniXr6fAXbTw==} + engines: {node: '>=18'} + peerDependencies: + '@opentelemetry/api': ^1.9.0 + '@opentelemetry/core': ^1.30.1 || ^2.1.0 + '@opentelemetry/exporter-trace-otlp-http': '>=0.57.0 <1' + '@opentelemetry/instrumentation': '>=0.57.1 <1' + '@opentelemetry/sdk-trace-base': ^1.30.1 || ^2.1.0 + '@opentelemetry/semantic-conventions': ^1.39.0 + peerDependenciesMeta: + '@opentelemetry/api': + optional: true + '@opentelemetry/core': + optional: true + '@opentelemetry/exporter-trace-otlp-http': + optional: true + '@opentelemetry/instrumentation': + optional: true + '@opentelemetry/sdk-trace-base': + optional: true + '@opentelemetry/semantic-conventions': + optional: true + + '@sentry/node@10.29.0': + resolution: {integrity: sha512-9j8VzV06VCj+H8tlxpfa7BNN4HzH5exv68WOufdMTXzzWLOXnzrdNDoYplm1G2S3LMvWsc1SVI3a8A0yBY7oWg==} + engines: {node: '>=18'} + + '@sentry/node@10.50.0': + resolution: {integrity: sha512-TvwzFQu8MGKzMQ2/tqxcNzFA8UG2kKTB+GDmA4uOzx3+GT849YZRRSJzEXCmYhk1teVd2fbmgqyYY2nyLF5a+Q==} + engines: {node: '>=18'} + + '@sentry/opentelemetry@10.29.0': + resolution: {integrity: sha512-5QvtAwS73HlI/+OTF1poAFELzsc0se+PHmMsXGGrOeNBvjCr3ZE8qvke09aeMn7uRImf3Nc9J6i2KtSHJnbKPA==} + engines: {node: '>=18'} + peerDependencies: + '@opentelemetry/api': ^1.9.0 + '@opentelemetry/context-async-hooks': ^1.30.1 || ^2.1.0 || ^2.2.0 + '@opentelemetry/core': ^1.30.1 || ^2.1.0 || ^2.2.0 + '@opentelemetry/sdk-trace-base': ^1.30.1 || ^2.1.0 || ^2.2.0 + '@opentelemetry/semantic-conventions': ^1.37.0 + + '@sentry/opentelemetry@10.50.0': + resolution: {integrity: sha512-axn3pgDPveGdaMUC0abMCmFN7ux2pA5ebPufCef4lMIsyg7BBQvaEJ+vE19wjstMaBCAJGsdZlL3eeP2rtgRMw==} + engines: {node: '>=18'} + peerDependencies: + '@opentelemetry/api': ^1.9.0 + '@opentelemetry/core': ^1.30.1 || ^2.1.0 + '@opentelemetry/sdk-trace-base': ^1.30.1 || ^2.1.0 + '@opentelemetry/semantic-conventions': ^1.39.0 + + '@sindresorhus/is@4.6.0': + resolution: {integrity: sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==} + engines: {node: '>=10'} + + '@szmarczak/http-timer@4.0.6': + resolution: {integrity: sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==} + engines: {node: '>=10'} + + '@tootallnate/once@2.0.1': + resolution: {integrity: sha512-HqmEUIGRJ5fSXchkVgR5F7qn48bDBzv0kWj/Kfu5e6uci4UlEeng4331LnBkWffb++Ei3FOVLxo8JJWMFBDMeQ==} + engines: {node: '>= 10'} + + '@types/appdmg@0.5.5': + resolution: {integrity: sha512-G+n6DgZTZFOteITE30LnWj+HRVIGr7wMlAiLWOO02uJFWVEitaPU9JVXm9wJokkgshBawb2O1OykdcsmkkZfgg==} + + '@types/cacheable-request@6.0.3': + resolution: {integrity: sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw==} + + '@types/connect@3.4.38': + resolution: {integrity: sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==} + + '@types/eslint-scope@3.7.7': + resolution: {integrity: sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg==} + + '@types/eslint@9.6.1': + resolution: {integrity: sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag==} + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + + '@types/fs-extra@9.0.13': + resolution: {integrity: sha512-nEnwB++1u5lVDM2UI4c1+5R+FYaKfaAzS4OococimjVm3nQw3TuzH5UNsocrcTBbhnerblyHj4A49qXbIiZdpA==} + + '@types/http-cache-semantics@4.2.0': + resolution: {integrity: sha512-L3LgimLHXtGkWikKnsPg0/VFx9OGZaC+eN1u4r+OB1XRqH3meBIAVC2zr1WdMH+RHmnRkqliQAOHNJ/E0j/e0Q==} + + '@types/json-schema@7.0.15': + resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} + + '@types/keyv@3.1.4': + resolution: {integrity: sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==} + + '@types/mute-stream@0.0.4': + resolution: {integrity: sha512-CPM9nzrCPPJHQNA9keH9CVkVI+WR5kMa+7XEs5jcGQ0VoAGnLv242w8lIVgwAEfmE4oufJRaTc9PNLQl0ioAow==} + + '@types/mysql@2.15.27': + resolution: {integrity: sha512-YfWiV16IY0OeBfBCk8+hXKmdTKrKlwKN1MNKAPBu5JYxLwBEZl7QzeEpGnlZb3VMGJrrGmB84gXiH+ofs/TezA==} + + '@types/node@22.19.17': + resolution: {integrity: sha512-wGdMcf+vPYM6jikpS/qhg6WiqSV/OhG+jeeHT/KlVqxYfD40iYJf9/AE1uQxVWFvU7MipKRkRv8NSHiCGgPr8Q==} + + '@types/node@24.12.2': + resolution: {integrity: sha512-A1sre26ke7HDIuY/M23nd9gfB+nrmhtYyMINbjI1zHJxYteKR6qSMX56FsmjMcDb3SMcjJg5BiRRgOCC/yBD0g==} + + '@types/pg-pool@2.0.6': + resolution: {integrity: sha512-TaAUE5rq2VQYxab5Ts7WZhKNmuN78Q6PiFonTDdpbx8a1H0M1vhy3rhiMjl+e2iHmogyMw7jZF4FrE6eJUy5HQ==} + + '@types/pg-pool@2.0.7': + resolution: {integrity: sha512-U4CwmGVQcbEuqpyju8/ptOKg6gEC+Tqsvj2xS9o1g71bUh8twxnC6ZL5rZKCsGN0iyH0CwgUyc9VR5owNQF9Ng==} + + '@types/pg@8.15.6': + resolution: {integrity: sha512-NoaMtzhxOrubeL/7UZuNTrejB4MPAJ0RpxZqXQf2qXuVlTPuG6Y8p4u9dKRaue4yjmC7ZhzVO2/Yyyn25znrPQ==} + + '@types/responselike@1.0.3': + resolution: {integrity: sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw==} + + '@types/tedious@4.0.14': + resolution: {integrity: sha512-KHPsfX/FoVbUGbyYvk1q9MMQHLPeRZhRJZdO45Q4YjvFkv4hMNghCWTvy7rdKessBsmtz4euWCWAB6/tVpI1Iw==} + + '@types/wrap-ansi@3.0.0': + resolution: {integrity: sha512-ltIpx+kM7g/MLRZfkbL7EsCEjfzCcScLpkg37eXEtx5kmrAKBkTJwd1GIAjDSL8wTpM6Hzn5YO4pSb91BEwu1g==} + + '@types/yauzl@2.10.3': + resolution: {integrity: sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==} + + '@vscode/sudo-prompt@9.3.2': + resolution: {integrity: sha512-gcXoCN00METUNFeQOFJ+C9xUI0DKB+0EGMVg7wbVYRHBw2Eq3fKisDZOkRdOz3kqXRKOENMfShPOmypw1/8nOw==} + + '@webassemblyjs/ast@1.14.1': + resolution: {integrity: sha512-nuBEDgQfm1ccRp/8bCQrx1frohyufl4JlbMMZ4P1wpeOfDhF6FQkxZJ1b/e+PLwr6X1Nhw6OLme5usuBWYBvuQ==} + + '@webassemblyjs/floating-point-hex-parser@1.13.2': + resolution: {integrity: sha512-6oXyTOzbKxGH4steLbLNOu71Oj+C8Lg34n6CqRvqfS2O71BxY6ByfMDRhBytzknj9yGUPVJ1qIKhRlAwO1AovA==} + + '@webassemblyjs/helper-api-error@1.13.2': + resolution: {integrity: sha512-U56GMYxy4ZQCbDZd6JuvvNV/WFildOjsaWD3Tzzvmw/mas3cXzRJPMjP83JqEsgSbyrmaGjBfDtV7KDXV9UzFQ==} + + '@webassemblyjs/helper-buffer@1.14.1': + resolution: {integrity: sha512-jyH7wtcHiKssDtFPRB+iQdxlDf96m0E39yb0k5uJVhFGleZFoNw1c4aeIcVUPPbXUVJ94wwnMOAqUHyzoEPVMA==} + + '@webassemblyjs/helper-numbers@1.13.2': + resolution: {integrity: sha512-FE8aCmS5Q6eQYcV3gI35O4J789wlQA+7JrqTTpJqn5emA4U2hvwJmvFRC0HODS+3Ye6WioDklgd6scJ3+PLnEA==} + + '@webassemblyjs/helper-wasm-bytecode@1.13.2': + resolution: {integrity: sha512-3QbLKy93F0EAIXLh0ogEVR6rOubA9AoZ+WRYhNbFyuB70j3dRdwH9g+qXhLAO0kiYGlg3TxDV+I4rQTr/YNXkA==} + + '@webassemblyjs/helper-wasm-section@1.14.1': + resolution: {integrity: sha512-ds5mXEqTJ6oxRoqjhWDU83OgzAYjwsCV8Lo/N+oRsNDmx/ZDpqalmrtgOMkHwxsG0iI//3BwWAErYRHtgn0dZw==} + + '@webassemblyjs/ieee754@1.13.2': + resolution: {integrity: sha512-4LtOzh58S/5lX4ITKxnAK2USuNEvpdVV9AlgGQb8rJDHaLeHciwG4zlGr0j/SNWlr7x3vO1lDEsuePvtcDNCkw==} + + '@webassemblyjs/leb128@1.13.2': + resolution: {integrity: sha512-Lde1oNoIdzVzdkNEAWZ1dZ5orIbff80YPdHx20mrHwHrVNNTjNr8E3xz9BdpcGqRQbAEa+fkrCb+fRFTl/6sQw==} + + '@webassemblyjs/utf8@1.13.2': + resolution: {integrity: sha512-3NQWGjKTASY1xV5m7Hr0iPeXD9+RDobLll3T9d2AO+g3my8xy5peVyjSag4I50mR1bBSN/Ct12lo+R9tJk0NZQ==} + + '@webassemblyjs/wasm-edit@1.14.1': + resolution: {integrity: sha512-RNJUIQH/J8iA/1NzlE4N7KtyZNHi3w7at7hDjvRNm5rcUXa00z1vRz3glZoULfJ5mpvYhLybmVcwcjGrC1pRrQ==} + + '@webassemblyjs/wasm-gen@1.14.1': + resolution: {integrity: sha512-AmomSIjP8ZbfGQhumkNvgC33AY7qtMCXnN6bL2u2Js4gVCg8fp735aEiMSBbDR7UQIj90n4wKAFUSEd0QN2Ukg==} + + '@webassemblyjs/wasm-opt@1.14.1': + resolution: {integrity: sha512-PTcKLUNvBqnY2U6E5bdOQcSM+oVP/PmrDY9NzowJjislEjwP/C4an2303MCVS2Mg9d3AJpIGdUFIQQWbPds0Sw==} + + '@webassemblyjs/wasm-parser@1.14.1': + resolution: {integrity: sha512-JLBl+KZ0R5qB7mCnud/yyX08jWFw5MsoalJ1pQ4EdFlgj9VdXKGuENGsiCIjegI1W7p91rUlcB/LB5yRJKNTcQ==} + + '@webassemblyjs/wast-printer@1.14.1': + resolution: {integrity: sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw==} + + '@xmldom/xmldom@0.9.10': + resolution: {integrity: sha512-A9gOqLdi6cV4ibazAjcQufGj0B1y/vDqYrcuP6d/6x8P27gRS8643Dj9o1dEKtB6O7fwxb2FgBmJS2mX7gpvdw==} + engines: {node: '>=14.6'} + + '@xtuc/ieee754@1.2.0': + resolution: {integrity: sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==} + + '@xtuc/long@4.2.2': + resolution: {integrity: sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==} + + abbrev@1.1.1: + resolution: {integrity: sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==} + + acorn-import-attributes@1.9.5: + resolution: {integrity: sha512-n02Vykv5uA3eHGM/Z2dQrcD56kL8TyDb2p1+0P83PClMnC/nc+anbQRhIOWnSq4Ke/KvDPrY3C9hDtC/A3eHnQ==} + peerDependencies: + acorn: ^8 + + acorn-import-phases@1.0.4: + resolution: {integrity: sha512-wKmbr/DDiIXzEOiWrTTUcDm24kQ2vGfZQvM2fwg2vXqR5uW6aapr7ObPtj1th32b9u90/Pf4AItvdTh42fBmVQ==} + engines: {node: '>=10.13.0'} + peerDependencies: + acorn: ^8.14.0 + + acorn@8.16.0: + resolution: {integrity: sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==} + engines: {node: '>=0.4.0'} + hasBin: true + + agent-base@6.0.2: + resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==} + engines: {node: '>= 6.0.0'} + + agentkeepalive@4.6.0: + resolution: {integrity: sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==} + engines: {node: '>= 8.0.0'} + + aggregate-error@3.1.0: + resolution: {integrity: sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==} + engines: {node: '>=8'} + + ajv-formats@2.1.1: + resolution: {integrity: sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==} + peerDependencies: + ajv: ^8.0.0 + peerDependenciesMeta: + ajv: + optional: true + + ajv-keywords@5.1.0: + resolution: {integrity: sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==} + peerDependencies: + ajv: ^8.8.2 + + ajv@8.20.0: + resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} + + ansi-escapes@4.3.2: + resolution: {integrity: sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==} + engines: {node: '>=8'} + + ansi-escapes@5.0.0: + resolution: {integrity: sha512-5GFMVX8HqE/TB+FuBJGuO5XG0WrsA6ptUqoODaT/n9mmUaZFkqnBueB4leqGBCmrUHnCnC4PCZTCd0E7QQ83bA==} + engines: {node: '>=12'} + + ansi-regex@5.0.1: + resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} + engines: {node: '>=8'} + + ansi-regex@6.2.2: + resolution: {integrity: sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==} + engines: {node: '>=12'} + + ansi-styles@4.3.0: + resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} + engines: {node: '>=8'} + + ansi-styles@6.2.3: + resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==} + engines: {node: '>=12'} + + appdmg@0.6.6: + resolution: {integrity: sha512-GRmFKlCG+PWbcYF4LUNonTYmy0GjguDy6Jh9WP8mpd0T6j80XIJyXBiWlD0U+MLNhqV9Nhx49Gl9GpVToulpLg==} + engines: {node: '>=8.5'} + os: [darwin] + hasBin: true + + async@1.5.2: + resolution: {integrity: sha512-nSVgobk4rv61R9PUSDtYt7mPVB2olxNR5RWJcAsH676/ef11bUZwvu7+RGYrYauVdDPcO519v68wRhXQtxsV9w==} + + at-least-node@1.0.0: + resolution: {integrity: sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==} + engines: {node: '>= 4.0.0'} + + author-regex@1.0.0: + resolution: {integrity: sha512-KbWgR8wOYRAPekEmMXrYYdc7BRyhn2Ftk7KWfMUnQ43hFdojWEFRxhhRUm3/OFEdPa1r0KAvTTg9YQK57xTe0g==} + engines: {node: '>=0.8'} + + balanced-match@1.0.2: + resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + + balanced-match@4.0.4: + resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} + engines: {node: 18 || 20 || >=22} + + base32-encode@1.2.0: + resolution: {integrity: sha512-cHFU8XeRyx0GgmoWi5qHMCVRiqU6J3MHWxVgun7jggCBUpVzm1Ir7M9dYr2whjSNc3tFeXfQ/oZjQu/4u55h9A==} + + base64-js@1.5.1: + resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} + + baseline-browser-mapping@2.10.27: + resolution: {integrity: sha512-zEs/ufmZoUd7WftKpKyXaT6RFxpQ5Qm9xytKRHvJfxFV9DFJkZph9RvJ1LcOUi0Z1ZVijMte65JbILeV+8QQEA==} + engines: {node: '>=6.0.0'} + hasBin: true + + better-sqlite3@12.11.1: + resolution: {integrity: sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA==} + engines: {node: 20.x || 22.x || 23.x || 24.x || 25.x || 26.x} + + bindings@1.5.0: + resolution: {integrity: sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==} + + bl@4.1.0: + resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==} + + bluebird@3.7.2: + resolution: {integrity: sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==} + + boolean@3.2.0: + resolution: {integrity: sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==} + deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info. + + bplist-creator@0.0.8: + resolution: {integrity: sha512-Za9JKzD6fjLC16oX2wsXfc+qBEhJBJB1YPInoAQpMLhDuj5aVOv1baGeIQSq1Fr3OCqzvsoQcSBSwGId/Ja2PA==} + + brace-expansion@1.1.14: + resolution: {integrity: sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g==} + + brace-expansion@2.1.0: + resolution: {integrity: sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w==} + + brace-expansion@5.0.5: + resolution: {integrity: sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==} + engines: {node: 18 || 20 || >=22} + + braces@3.0.3: + resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} + engines: {node: '>=8'} + + browserslist@4.28.2: + resolution: {integrity: sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==} + engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} + hasBin: true + + buffer-crc32@0.2.13: + resolution: {integrity: sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==} + + buffer-from@1.1.2: + resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} + + buffer@5.7.1: + resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==} + + cacache@16.1.3: + resolution: {integrity: sha512-/+Emcj9DAXxX4cwlLmRI9c166RuL3w30zp4R7Joiv2cQTtTtA+jeuCAjH3ZlGnYS3tKENSrKhAzVVP9GVyzeYQ==} + engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} + + cacheable-lookup@5.0.4: + resolution: {integrity: sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==} + engines: {node: '>=10.6.0'} + + cacheable-request@7.0.4: + resolution: {integrity: sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg==} + engines: {node: '>=8'} + + caniuse-lite@1.0.30001792: + resolution: {integrity: sha512-hVLMUZFgR4JJ6ACt1uEESvQN1/dBVqPAKY0hgrV70eN3391K6juAfTjKZLKvOMsx8PxA7gsY1/tLMMTcfFLLpw==} + + chalk@4.1.2: + resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} + engines: {node: '>=10'} + + chardet@0.7.0: + resolution: {integrity: sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==} + + chownr@1.1.4: + resolution: {integrity: sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==} + + chownr@2.0.0: + resolution: {integrity: sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==} + engines: {node: '>=10'} + + chrome-trace-event@1.0.4: + resolution: {integrity: sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ==} + engines: {node: '>=6.0'} + + cjs-module-lexer@2.2.0: + resolution: {integrity: sha512-4bHTS2YuzUvtoLjdy+98ykbNB5jS0+07EvFNXerqZQJ89F7DI6ET7OQo/HJuW6K0aVsKA9hj9/RVb2kQVOrPDQ==} + + clean-stack@2.2.0: + resolution: {integrity: sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==} + engines: {node: '>=6'} + + cli-cursor@3.1.0: + resolution: {integrity: sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==} + engines: {node: '>=8'} + + cli-cursor@4.0.0: + resolution: {integrity: sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + + cli-spinners@2.9.2: + resolution: {integrity: sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==} + engines: {node: '>=6'} + + cli-truncate@3.1.0: + resolution: {integrity: sha512-wfOBkjXteqSnI59oPcJkcPl/ZmwvMMOj340qUIY1SKZCv0B9Cf4D4fAucRkIKQmsIuYK3x1rrgU7MeGRruiuiA==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + + cli-truncate@4.0.0: + resolution: {integrity: sha512-nPdaFdQ0h/GEigbPClz11D0v/ZJEwxmeVZGeMo3Z5StPtUTkA9o1lD6QwoirYiSDzbcwn2XcjwmCp68W1IS4TA==} + engines: {node: '>=18'} + + cli-width@4.1.0: + resolution: {integrity: sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==} + engines: {node: '>= 12'} + + cliui@7.0.4: + resolution: {integrity: sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==} + + cliui@8.0.1: + resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==} + engines: {node: '>=12'} + + clone-response@1.0.3: + resolution: {integrity: sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA==} + + clone@1.0.4: + resolution: {integrity: sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==} + engines: {node: '>=0.8'} + + color-convert@0.5.3: + resolution: {integrity: sha512-RwBeO/B/vZR3dfKL1ye/vx8MHZ40ugzpyfeVG5GsiuGnrlMWe2o8wxBbLCpw9CsxV+wHuzYlCiWnybrIA0ling==} + + color-convert@2.0.1: + resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} + engines: {node: '>=7.0.0'} + + color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + + colorette@2.0.20: + resolution: {integrity: sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==} + + commander@11.1.0: + resolution: {integrity: sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==} + engines: {node: '>=16'} + + commander@13.1.0: + resolution: {integrity: sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw==} + engines: {node: '>=18'} + + commander@2.20.3: + resolution: {integrity: sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==} + + commander@5.1.0: + resolution: {integrity: sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg==} + engines: {node: '>= 6'} + + commander@9.5.0: + resolution: {integrity: sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==} + engines: {node: ^12.20.0 || >=14} + + compare-version@0.1.2: + resolution: {integrity: sha512-pJDh5/4wrEnXX/VWRZvruAGHkzKdr46z11OlTPN+VrATlWWhSKewNCJ1futCO5C7eJB3nPMFZA1LeYtcFboZ2A==} + engines: {node: '>=0.10.0'} + + concat-map@0.0.1: + resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} + + cross-dirname@0.1.0: + resolution: {integrity: sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q==} + + cross-spawn@6.0.6: + resolution: {integrity: sha512-VqCUuhcd1iB+dsv8gxPttb5iZh/D0iubSP21g36KXdEuf6I5JiioesUVjpCdHV9MZRUfVFlvwtIUyPfxo5trtw==} + engines: {node: '>=4.8'} + + cross-spawn@7.0.6: + resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + engines: {node: '>= 8'} + + cross-zip@4.0.1: + resolution: {integrity: sha512-n63i0lZ0rvQ6FXiGQ+/JFCKAUyPFhLQYJIqKaa+tSJtfKeULF/IDNDAbdnSIxgS4NTuw2b0+lj8LzfITuq+ZxQ==} + engines: {node: '>=12.10'} + + d@1.0.2: + resolution: {integrity: sha512-MOqHvMWF9/9MX6nza0KgvFH4HpMU0EF5uUDXqX/BtxtU8NfB0QzRtJ8Oe/6SuS4kbhyzVJwjd97EA4PKrzJ8bw==} + engines: {node: '>=0.12'} + + debug@2.6.9: + resolution: {integrity: sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + debug@4.4.3: + resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + decompress-response@6.0.0: + resolution: {integrity: sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==} + engines: {node: '>=10'} + + deep-extend@0.6.0: + resolution: {integrity: sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==} + engines: {node: '>=4.0.0'} + + default-shell@2.2.0: + resolution: {integrity: sha512-sPpMZcVhRQ0nEMDtuMJ+RtCxt7iHPAMBU+I4tAlo5dU1sjRpNax0crj6nR3qKpvVnckaQ9U38enXcwW9nZJeCw==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + + defaults@1.0.4: + resolution: {integrity: sha512-eFuaLoy/Rxalv2kr+lqMlUnrDWV+3j4pljOIJgLIhI058IQfWJ7vXhyEIHu+HtC738klGALYxOKDO0bQP3tg8A==} + + defer-to-connect@2.0.1: + resolution: {integrity: sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg==} + engines: {node: '>=10'} + + define-data-property@1.1.4: + resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==} + engines: {node: '>= 0.4'} + + define-properties@1.2.1: + resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==} + engines: {node: '>= 0.4'} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + detect-node@2.1.0: + resolution: {integrity: sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==} + + dir-compare@4.2.0: + resolution: {integrity: sha512-2xMCmOoMrdQIPHdsTawECdNPwlVFB9zGcz3kuhmBO6U3oU+UQjsue0i8ayLKpgBcm+hcXPMVSGUN9d+pvJ6+VQ==} + + ds-store@0.1.6: + resolution: {integrity: sha512-kY21M6Lz+76OS3bnCzjdsJSF7LBpLYGCVfavW8TgQD2XkcqIZ86W0y9qUDZu6fp7SIZzqosMDW2zi7zVFfv4hw==} + + eastasianwidth@0.2.0: + resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} + + electron-context-menu@4.1.2: + resolution: {integrity: sha512-9xYTUV0oRqKL50N9W71IrXNdVRB0LuBp3R1zkUdUc2wfIa2/QZwYYj5RLuO7Tn7ZSLVIaO3X6u+EIBK+cBvzrQ==} + engines: {node: '>=18'} + + electron-dl@4.0.0: + resolution: {integrity: sha512-USiB9816d2JzKv0LiSbreRfTg5lDk3lWh0vlx/gugCO92ZIJkHVH0UM18EHvKeadErP6Xn4yiTphWzYfbA2Ong==} + engines: {node: '>=18'} + + electron-installer-common@0.10.4: + resolution: {integrity: sha512-8gMNPXfAqUE5CfXg8RL0vXpLE9HAaPkgLXVoHE3BMUzogMWenf4LmwQ27BdCUrEhkjrKl+igs2IHJibclR3z3Q==} + engines: {node: '>= 10.0.0'} + + electron-installer-debian@3.2.0: + resolution: {integrity: sha512-58ZrlJ1HQY80VucsEIG9tQ//HrTlG6sfofA3nRGr6TmkX661uJyu4cMPPh6kXW+aHdq/7+q25KyQhDrXvRL7jw==} + engines: {node: '>= 10.0.0'} + os: [darwin, linux] + hasBin: true + + electron-installer-dmg@5.0.1: + resolution: {integrity: sha512-qOa1aAQdX57C+vzhDk3549dd/PRlNL4F8y736MTD1a43qptD+PvHY97Bo9gSf+OZ8iUWE7BrYSpk/FgLUe40EA==} + engines: {node: '>= 16'} + hasBin: true + + electron-installer-redhat@3.4.0: + resolution: {integrity: sha512-gEISr3U32Sgtj+fjxUAlSDo3wyGGq6OBx7rF5UdpIgbnpUvMN4W5uYb0ThpnAZ42VEJh/3aODQXHbFS4f5J3Iw==} + engines: {node: '>= 10.0.0'} + os: [darwin, linux] + hasBin: true + + electron-is-dev@3.0.1: + resolution: {integrity: sha512-8TjjAh8Ec51hUi3o4TaU0mD3GMTOESi866oRNavj9A3IQJ7pmv+MJVmdZBFGw4GFT36X7bkqnuDNYvkQgvyI8Q==} + engines: {node: '>=18'} + + electron-squirrel-startup@1.0.1: + resolution: {integrity: sha512-sTfFIHGku+7PsHLJ7v0dRcZNkALrV+YEozINTW8X1nM//e5O3L+rfYuvSW00lmGHnYmUjARZulD8F2V8ISI9RA==} + + electron-to-chromium@1.5.352: + resolution: {integrity: sha512-9wHk8x6dyuimoe18EdiDPWKExNdxYqo4fn4FwOVVper6RxT3cmpBwBkWWfSOCYJjQdIco/nPhJhNLmn4Ufg1Yg==} + + electron-winstaller@5.4.0: + resolution: {integrity: sha512-bO3y10YikuUwUuDUQRM4KfwNkKhnpVO7IPdbsrejwN9/AABJzzTQ4GeHwyzNSrVO+tEH3/Np255a3sVZpZDjvg==} + engines: {node: '>=8.0.0'} + + electron@42.0.1: + resolution: {integrity: sha512-d8HnycE970DGESe91Nj30eonFBUcAI9EZ1TwUGJVzSAnJZdh0BkFEinAXjdklvDYst+bVDc8HsksCuqVLrnqdg==} + engines: {node: '>= 22.12.0'} + hasBin: true + + emoji-regex@10.6.0: + resolution: {integrity: sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==} + + emoji-regex@8.0.0: + resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} + + emoji-regex@9.2.2: + resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==} + + encode-utf8@1.0.3: + resolution: {integrity: sha512-ucAnuBEhUK4boH2HjVYG5Q2mQyPorvv0u/ocS+zhdw0S8AlHYY+GOFhP1Gio5z4icpP2ivFSvhtFjQi8+T9ppw==} + + encoding@0.1.13: + resolution: {integrity: sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==} + + end-of-stream@1.4.5: + resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==} + + enhanced-resolve@5.21.0: + resolution: {integrity: sha512-otxSQPw4lkOZWkHpB3zaEQs6gWYEsmX4xQF68ElXC/TWvGxGMSGOvoNbaLXm6/cS/fSfHtsEdw90y20PCd+sCA==} + engines: {node: '>=10.13.0'} + + env-paths@2.2.1: + resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==} + engines: {node: '>=6'} + + env-paths@3.0.0: + resolution: {integrity: sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + + err-code@2.0.3: + resolution: {integrity: sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==} + + error-ex@1.3.4: + resolution: {integrity: sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==} + + es-define-property@1.0.1: + resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} + engines: {node: '>= 0.4'} + + es-errors@1.3.0: + resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} + engines: {node: '>= 0.4'} + + es-module-lexer@2.1.0: + resolution: {integrity: sha512-n27zTYMjYu1aj4MjCWzSP7G9r75utsaoc8m61weK+W8JMBGGQybd43GstCXZ3WNmSFtGT9wi59qQTW6mhTR5LQ==} + + es5-ext@0.10.64: + resolution: {integrity: sha512-p2snDhiLaXe6dahss1LddxqEm+SkuDvV8dnIQG0MWjyHpcMNfXKPE+/Cc0y+PhxJX3A4xGNeFCj5oc0BUh6deg==} + engines: {node: '>=0.10'} + + es6-error@4.1.1: + resolution: {integrity: sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==} + + es6-iterator@2.0.3: + resolution: {integrity: sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g==} + + es6-symbol@3.1.4: + resolution: {integrity: sha512-U9bFFjX8tFiATgtkJ1zg25+KviIXpgRvRHS8sau3GfhVzThRQrOeksPeT0BWW2MNZs1OEWJ1DPXOQMn0KKRkvg==} + engines: {node: '>=0.12'} + + es6-weak-map@2.0.3: + resolution: {integrity: sha512-p5um32HOTO1kP+w7PRnB+5lQ43Z6muuMuIMffvDN8ZB4GcnjLBV6zGStpbASIMk4DCAvEaamhe2zhyCb/QXXsA==} + + escalade@3.2.0: + resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} + engines: {node: '>=6'} + + escape-goat@4.0.0: + resolution: {integrity: sha512-2Sd4ShcWxbx6OY1IHyla/CVNwvg7XwZVoXZHcSu9w9SReNP1EzzD5T8NWKIR38fIqEns9kDWKUQTXXAmlDrdPg==} + engines: {node: '>=12'} + + escape-string-regexp@1.0.5: + resolution: {integrity: sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==} + engines: {node: '>=0.8.0'} + + escape-string-regexp@4.0.0: + resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} + engines: {node: '>=10'} + + escape-string-regexp@5.0.0: + resolution: {integrity: sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==} + engines: {node: '>=12'} + + eslint-scope@5.1.1: + resolution: {integrity: sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==} + engines: {node: '>=8.0.0'} + + esniff@2.0.1: + resolution: {integrity: sha512-kTUIGKQ/mDPFoJ0oVfcmyJn4iBDRptjNVIzwIFR7tqWXdVI9xfA2RMwY/gbSpJG3lkdWNEjLap/NqVHZiJsdfg==} + engines: {node: '>=0.10'} + + esrecurse@4.3.0: + resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==} + engines: {node: '>=4.0'} + + estraverse@4.3.0: + resolution: {integrity: sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==} + engines: {node: '>=4.0'} + + estraverse@5.3.0: + resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==} + engines: {node: '>=4.0'} + + event-emitter@0.3.5: + resolution: {integrity: sha512-D9rRn9y7kLPnJ+hMq7S/nhvoKwwvVJahBi2BPmx3bvbsEdK3W9ii8cBSGjP+72/LnM4n6fo3+dkCX5FeTQruXA==} + + eventemitter3@5.0.4: + resolution: {integrity: sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==} + + events@3.3.0: + resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==} + engines: {node: '>=0.8.x'} + + execa@1.0.0: + resolution: {integrity: sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==} + engines: {node: '>=6'} + + execa@5.1.1: + resolution: {integrity: sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==} + engines: {node: '>=10'} + + expand-template@2.0.3: + resolution: {integrity: sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==} + engines: {node: '>=6'} + + exponential-backoff@3.1.3: + resolution: {integrity: sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA==} + + ext-list@2.2.2: + resolution: {integrity: sha512-u+SQgsubraE6zItfVA0tBuCBhfU9ogSRnsvygI7wht9TS510oLkBRXBsqopeUG/GBOIQyKZO9wjTqIu/sf5zFA==} + engines: {node: '>=0.10.0'} + + ext-name@5.0.0: + resolution: {integrity: sha512-yblEwXAbGv1VQDmow7s38W77hzAgJAO50ztBLMcUyUBfxv1HC+LGwtiEN+Co6LtlqT/5uwVOxsD4TNIilWhwdQ==} + engines: {node: '>=4'} + + ext@1.7.0: + resolution: {integrity: sha512-6hxeJYaL110a9b5TEJSj0gojyHQAmA2ch5Os+ySCiA1QGdS697XWY1pzsrSjqA9LDEEgdB/KypIlR59RcLuHYw==} + + external-editor@3.1.0: + resolution: {integrity: sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==} + engines: {node: '>=4'} + + extract-zip@2.0.1: + resolution: {integrity: sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==} + engines: {node: '>= 10.17.0'} + hasBin: true + + fast-deep-equal@3.1.3: + resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + + fast-glob@3.3.3: + resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==} + engines: {node: '>=8.6.0'} + + fast-uri@3.1.2: + resolution: {integrity: sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==} + + fast-xml-builder@1.1.9: + resolution: {integrity: sha512-jcyKVSEX13iseJqg7n/KWw+xnu/7fdrZ333Fac54KjHDIELVCfDDJXYIm6DTJ0Su4gSzrhqiK0DzY/wZbF40mw==} + + fast-xml-parser@5.7.3: + resolution: {integrity: sha512-C0AaNuC+mscy6vrAQKAc/rMq+zAPHodfHGZu4sGVehvAQt/JLG1O5zEcYcXSY5zSqr4YVgxsB+pHXTq0i7eDlg==} + hasBin: true + + fastq@1.20.1: + resolution: {integrity: sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==} + + fd-slicer@1.1.0: + resolution: {integrity: sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==} + + file-uri-to-path@1.0.0: + resolution: {integrity: sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==} + + filename-reserved-regex@2.0.0: + resolution: {integrity: sha512-lc1bnsSr4L4Bdif8Xb/qrtokGbq5zlsms/CYH8PP+WtCkGNF65DPiQY8vG3SakEdRn8Dlnm+gW/qWKKjS5sZzQ==} + engines: {node: '>=4'} + + filenamify@4.3.0: + resolution: {integrity: sha512-hcFKyUG57yWGAzu1CMt/dPzYZuv+jAJUT85bL8mrXvNe6hWj6yEHEc4EdcgiA6Z3oi1/9wXJdZPXF2dZNgwgOg==} + engines: {node: '>=8'} + + fill-range@7.1.1: + resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} + engines: {node: '>=8'} + + find-up@2.1.0: + resolution: {integrity: sha512-NWzkk0jSJtTt08+FBFMvXoeZnOJD+jTtsRmBYbAIzJdX6l7dLgR7CTubCM5/eDdPUBvLCeVasP1brfVR/9/EZQ==} + engines: {node: '>=4'} + + find-up@5.0.0: + resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} + engines: {node: '>=10'} + + flora-colossus@2.0.0: + resolution: {integrity: sha512-dz4HxH6pOvbUzZpZ/yXhafjbR2I8cenK5xL0KtBFb7U2ADsR+OwXifnxZjij/pZWF775uSCMzWVd+jDik2H2IA==} + engines: {node: '>= 12'} + + fmix@0.1.0: + resolution: {integrity: sha512-Y6hyofImk9JdzU8k5INtTXX1cu8LDlePWDFU5sftm9H+zKCr5SGrVjdhkvsim646cw5zD0nADj8oHyXMZmCZ9w==} + + forwarded-parse@2.1.2: + resolution: {integrity: sha512-alTFZZQDKMporBH77856pXgzhEzaUVmLCDk+egLgIgHst3Tpndzz8MnKe+GzRJRfvVdn69HhpW7cmXzvtLvJAw==} + + fs-constants@1.0.0: + resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==} + + fs-extra@10.1.0: + resolution: {integrity: sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==} + engines: {node: '>=12'} + + fs-extra@11.3.5: + resolution: {integrity: sha512-eKpRKAovdpZtR1WopLHxlBWvAgPny3c4gX1G5Jhwmmw4XJj0ifSD5qB5TOo8hmA0wlRKDAOAhEE1yVPgs6Fgcg==} + engines: {node: '>=14.14'} + + fs-extra@7.0.1: + resolution: {integrity: sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==} + engines: {node: '>=6 <7 || >=8'} + + fs-extra@8.1.0: + resolution: {integrity: sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==} + engines: {node: '>=6 <7 || >=8'} + + fs-extra@9.1.0: + resolution: {integrity: sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==} + engines: {node: '>=10'} + + fs-minipass@2.1.0: + resolution: {integrity: sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==} + engines: {node: '>= 8'} + + fs-temp@1.2.1: + resolution: {integrity: sha512-okTwLB7/Qsq82G6iN5zZJFsOfZtx2/pqrA7Hk/9fvy+c+eJS9CvgGXT2uNxwnI14BDY9L/jQPkaBgSvlKfSW9w==} + + fs-xattr@0.3.1: + resolution: {integrity: sha512-UVqkrEW0GfDabw4C3HOrFlxKfx0eeigfRne69FxSBdHIP8Qt5Sq6Pu3RM9KmMlkygtC4pPKkj5CiPO5USnj2GA==} + engines: {node: '>=8.6.0'} + os: ['!win32'] + + fs.realpath@1.0.0: + resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==} + + function-bind@1.1.2: + resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} + + galactus@1.0.0: + resolution: {integrity: sha512-R1fam6D4CyKQGNlvJne4dkNF+PvUUl7TAJInvTGa9fti9qAv95quQz29GXapA4d8Ec266mJJxFVh82M4GIIGDQ==} + engines: {node: '>= 12'} + + gar@1.0.4: + resolution: {integrity: sha512-w4n9cPWyP7aHxKxYHFQMegj7WIAsL/YX/C4Bs5Rr8s1H9M1rNtRWRsw+ovYMkXDQ5S4ZbYHsHAPmevPjPgw44w==} + deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info. + + generate-function@2.3.1: + resolution: {integrity: sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==} + + generate-object-property@1.2.0: + resolution: {integrity: sha512-TuOwZWgJ2VAMEGJvAyPWvpqxSANF0LDpmyHauMjFYzaACvn+QTT/AZomvPCzVBV7yDN3OmwHQ5OvHaeLKre3JQ==} + + get-caller-file@2.0.5: + resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} + engines: {node: 6.* || 8.* || >= 10.*} + + get-east-asian-width@1.5.0: + resolution: {integrity: sha512-CQ+bEO+Tva/qlmw24dCejulK5pMzVnUOFOijVogd3KQs07HnRIgp8TGipvCCRT06xeYEbpbgwaCxglFyiuIcmA==} + engines: {node: '>=18'} + + get-folder-size@2.0.1: + resolution: {integrity: sha512-+CEb+GDCM7tkOS2wdMKTn9vU7DgnKUTuDlehkNJKNSovdCOVxs14OfKCk4cvSaR3za4gj+OBdl9opPN9xrJ0zA==} + hasBin: true + + get-package-info@1.0.0: + resolution: {integrity: sha512-SCbprXGAPdIhKAXiG+Mk6yeoFH61JlYunqdFQFHDtLjJlDjFf6x07dsS8acO+xWt52jpdVo49AlVDnUVK1sDNw==} + engines: {node: '>= 4.0'} + + get-stream@4.1.0: + resolution: {integrity: sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w==} + engines: {node: '>=6'} + + get-stream@5.2.0: + resolution: {integrity: sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==} + engines: {node: '>=8'} + + get-stream@6.0.1: + resolution: {integrity: sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==} + engines: {node: '>=10'} + + github-from-package@0.0.0: + resolution: {integrity: sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==} + + glob-parent@5.1.2: + resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} + engines: {node: '>= 6'} + + glob-to-regexp@0.4.1: + resolution: {integrity: sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==} + + glob@13.0.6: + resolution: {integrity: sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==} + engines: {node: 18 || 20 || >=22} + + glob@7.2.3: + resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} + deprecated: Glob versions prior to v9 are no longer supported + + glob@8.1.0: + resolution: {integrity: sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ==} + engines: {node: '>=12'} + deprecated: Glob versions prior to v9 are no longer supported + + global-agent@3.0.0: + resolution: {integrity: sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==} + engines: {node: '>=10.0'} + + global-dirs@3.0.1: + resolution: {integrity: sha512-NBcGGFbBA9s1VzD41QXDG+3++t9Mn5t1FpLdhESY6oKY4gYTFpX4wO3sqGUa0Srjtbfj3szX0RnemmrVRUdULA==} + engines: {node: '>=10'} + + globalthis@1.0.4: + resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==} + engines: {node: '>= 0.4'} + + gopd@1.2.0: + resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} + engines: {node: '>= 0.4'} + + got@11.8.6: + resolution: {integrity: sha512-6tfZ91bOr7bOXnK7PRDCGBLa1H4U080YHNaAQ2KsMGlLEzRbk44nsZF2E1IeRc3vtJHPVbKCYgdFbaGO2ljd8g==} + engines: {node: '>=10.19.0'} + + graceful-fs@4.2.11: + resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} + + has-flag@4.0.0: + resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} + engines: {node: '>=8'} + + has-property-descriptors@1.0.2: + resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==} + + hasown@2.0.3: + resolution: {integrity: sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==} + engines: {node: '>= 0.4'} + + hosted-git-info@2.8.9: + resolution: {integrity: sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==} + + http-cache-semantics@4.2.0: + resolution: {integrity: sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==} + + http-proxy-agent@5.0.0: + resolution: {integrity: sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==} + engines: {node: '>= 6'} + + http2-wrapper@1.0.3: + resolution: {integrity: sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg==} + engines: {node: '>=10.19.0'} + + https-proxy-agent@5.0.1: + resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==} + engines: {node: '>= 6'} + + human-signals@2.1.0: + resolution: {integrity: sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==} + engines: {node: '>=10.17.0'} + + humanize-ms@1.2.1: + resolution: {integrity: sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==} + + iconv-lite@0.4.24: + resolution: {integrity: sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==} + engines: {node: '>=0.10.0'} + + iconv-lite@0.6.3: + resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==} + engines: {node: '>=0.10.0'} + + ieee754@1.2.1: + resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==} + + image-size@0.7.5: + resolution: {integrity: sha512-Hiyv+mXHfFEP7LzUL/llg9RwFxxY+o9N3JVLIeG5E7iFIFAalxvRU9UZthBdYDEVnzHMgjnKJPPpay5BWf1g9g==} + engines: {node: '>=6.9.0'} + hasBin: true + + immer@10.2.0: + resolution: {integrity: sha512-d/+XTN3zfODyjr89gM3mPq1WNX2B8pYsu7eORitdwyA2sBubnTl3laYlBk4sXY5FUa5qTZGBDPJICVbvqzjlbw==} + + import-in-the-middle@2.0.6: + resolution: {integrity: sha512-3vZV3jX0XRFW3EJDTwzWoZa+RH1b8eTTx6YOCjglrLyPuepwoBti1k3L2dKwdCUrnVEfc5CuRuGstaC/uQJJaw==} + + import-in-the-middle@3.0.1: + resolution: {integrity: sha512-pYkiyXVL2Mf3pozdlDGV6NAObxQx13Ae8knZk1UJRJ6uRW/ZRmTGHlQYtrsSl7ubuE5F8CD1z+s1n4RHNuTtuA==} + engines: {node: '>=18'} + + imul@1.0.1: + resolution: {integrity: sha512-WFAgfwPLAjU66EKt6vRdTlKj4nAgIDQzh29JonLa4Bqtl6D8JrIMvWjCnx7xEjVNmP3U0fM5o8ZObk7d0f62bA==} + engines: {node: '>=0.10.0'} + + imurmurhash@0.1.4: + resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} + engines: {node: '>=0.8.19'} + + indent-string@4.0.0: + resolution: {integrity: sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==} + engines: {node: '>=8'} + + infer-owner@1.0.4: + resolution: {integrity: sha512-IClj+Xz94+d7irH5qRyfJonOdfTzuDaifE6ZPWfx0N0+/ATZCbuTPq2prFl526urkQd90WyUKIh1DfBQ2hMz9A==} + + inflight@1.0.6: + resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==} + deprecated: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful. + + inherits@2.0.4: + resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} + + ini@1.3.8: + resolution: {integrity: sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==} + + ini@2.0.0: + resolution: {integrity: sha512-7PnF4oN3CvZF23ADhA5wRaYEQpJ8qygSkbtTXWBeXWXmEVRXK+1ITciHWwHhsjv1TmW0MgacIv6hEi5pX5NQdA==} + engines: {node: '>=10'} + + interpret@3.1.1: + resolution: {integrity: sha512-6xwYfHbajpoF0xLW+iwLkhwgvLoZDfjYfoFNu8ftMoXINzwuymNLd9u/KmwtdT2GbR+/Cz66otEGEVVUHX9QLQ==} + engines: {node: '>=10.13.0'} + + ip-address@10.2.0: + resolution: {integrity: sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==} + engines: {node: '>= 12'} + + is-arrayish@0.2.1: + resolution: {integrity: sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==} + + is-core-module@2.16.2: + resolution: {integrity: sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==} + engines: {node: '>= 0.4'} + + is-extglob@2.1.1: + resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} + engines: {node: '>=0.10.0'} + + is-fullwidth-code-point@3.0.0: + resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} + engines: {node: '>=8'} + + is-fullwidth-code-point@4.0.0: + resolution: {integrity: sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==} + engines: {node: '>=12'} + + is-glob@4.0.3: + resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} + engines: {node: '>=0.10.0'} + + is-interactive@1.0.0: + resolution: {integrity: sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w==} + engines: {node: '>=8'} + + is-lambda@1.0.1: + resolution: {integrity: sha512-z7CMFGNrENq5iFB9Bqo64Xk6Y9sg+epq1myIcdHaGnbMTYOxvzsEtdYqQUylB7LxfkvgrrjP32T6Ywciio9UIQ==} + + is-my-ip-valid@1.0.1: + resolution: {integrity: sha512-jxc8cBcOWbNK2i2aTkCZP6i7wkHF1bqKFrwEHuN5Jtg5BSaZHUZQ/JTOJwoV41YvHnOaRyWWh72T/KvfNz9DJg==} + + is-my-json-valid@2.20.6: + resolution: {integrity: sha512-1JQwulVNjx8UqkPE/bqDaxtH4PXCe/2VRh/y3p99heOV87HG4Id5/VfDswd+YiAfHcRTfDlWgISycnHuhZq1aw==} + + is-number@7.0.0: + resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} + engines: {node: '>=0.12.0'} + + is-plain-obj@1.1.0: + resolution: {integrity: sha512-yvkRyxmFKEOQ4pNXCmJG5AEQNlXJS5LaONXo5/cLdTZdWvsZ1ioJEonLGAosKlMWE8lwUy/bJzMjcw8az73+Fg==} + engines: {node: '>=0.10.0'} + + is-promise@2.2.2: + resolution: {integrity: sha512-+lP4/6lKUBfQjZ2pdxThZvLUAafmZb8OAxFb8XXtiQmS35INgr85hdOGoEs124ez1FCnZJt6jau/T+alh58QFQ==} + + is-property@1.0.2: + resolution: {integrity: sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==} + + is-stream@1.1.0: + resolution: {integrity: sha512-uQPm8kcs47jx38atAcWTVxyltQYoPT68y9aWYdV6yWXSyW8mzSat0TL6CiWdZeCdF3KrAvpVtnHbTv4RN+rqdQ==} + engines: {node: '>=0.10.0'} + + is-stream@2.0.1: + resolution: {integrity: sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==} + engines: {node: '>=8'} + + is-unicode-supported@0.1.0: + resolution: {integrity: sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==} + engines: {node: '>=10'} + + isbinaryfile@4.0.10: + resolution: {integrity: sha512-iHrqe5shvBUcFbmZq9zOQHBoeOhZJu6RQGrDpBgenUm/Am+F3JM2MgQj+rK3Z601fzrL5gLZWtAPH2OBaSVcyw==} + engines: {node: '>= 8.0.0'} + + isexe@2.0.0: + resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + + jest-worker@27.5.1: + resolution: {integrity: sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==} + engines: {node: '>= 10.13.0'} + + jiti@2.7.0: + resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} + hasBin: true + + json-buffer@3.0.1: + resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==} + + json-schema-traverse@1.0.0: + resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==} + + json-stringify-safe@5.0.1: + resolution: {integrity: sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==} + + jsonfile@4.0.0: + resolution: {integrity: sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==} + + jsonfile@6.2.1: + resolution: {integrity: sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==} + + jsonpointer@5.0.1: + resolution: {integrity: sha512-p/nXbhSEcu3pZRdkW1OfJhpsVtW1gd4Wa1fnQc9YLiTfAjn0312eMKimbdIQzuZl9aa9xUGaRlP9T/CJE/ditQ==} + engines: {node: '>=0.10.0'} + + junk@3.1.0: + resolution: {integrity: sha512-pBxcB3LFc8QVgdggvZWyeys+hnrNWg4OcZIU/1X59k5jQdLBlCsYGRQaz234SqoRLTCgMH00fY0xRJH+F9METQ==} + engines: {node: '>=8'} + + keyv@4.5.4: + resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} + + listr2@7.0.2: + resolution: {integrity: sha512-rJysbR9GKIalhTbVL2tYbF2hVyDnrf7pFUZBwjPaMIdadYHmeT+EVi/Bu3qd7ETQPahTotg2WRCatXwRBW554g==} + engines: {node: '>=16.0.0'} + + load-json-file@2.0.0: + resolution: {integrity: sha512-3p6ZOGNbiX4CdvEd1VcE6yi78UrGNpjHO33noGwHCnT/o2fyllJDepsm8+mFFv/DvtwFHht5HIHSyOy5a+ChVQ==} + engines: {node: '>=4'} + + loader-runner@4.3.2: + resolution: {integrity: sha512-DFEqQ3ihfS9blba08cLfYf1NRAIEm+dDjic073DRDc3/JspI/8wYmtDsHwd3+4hwvdxSK7PGaElfTmm0awWJ4w==} + engines: {node: '>=6.11.5'} + + locate-path@2.0.0: + resolution: {integrity: sha512-NCI2kiDkyR7VeEKm27Kda/iQHyKJe1Bu0FlTbYp3CqJu+9IFe9bLyAjMxf5ZDDbEg+iMPzB5zYyUTSm8wVTKmA==} + engines: {node: '>=4'} + + locate-path@6.0.0: + resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} + engines: {node: '>=10'} + + lodash.get@4.4.2: + resolution: {integrity: sha512-z+Uw/vLuy6gQe8cfaFWD7p0wVv8fJl3mbzXh33RS+0oW2wvUqiRXiQ69gLWSLpgB5/6sU+r6BlQR0MBILadqTQ==} + deprecated: This package is deprecated. Use the optional chaining (?.) operator instead. + + lodash@4.18.1: + resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==} + + log-symbols@4.1.0: + resolution: {integrity: sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==} + engines: {node: '>=10'} + + log-update@5.0.1: + resolution: {integrity: sha512-5UtUDQ/6edw4ofyljDNcOVJQ4c7OjDro4h3y8e1GQL5iYElYclVHJ3zeWchylvMaKnDbDilC8irOVyexnA/Slw==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + + lowercase-keys@2.0.0: + resolution: {integrity: sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==} + engines: {node: '>=8'} + + lru-cache@11.3.6: + resolution: {integrity: sha512-Gf/KoL3C/MlI7Bt0PGI9I+TeTC/I6r/csU58N4BSNc4lppLBeKsOdFYkK+dX0ABDUMJNfCHTyPpzwwO21Awd3A==} + engines: {node: 20 || >=22} + + lru-cache@7.18.3: + resolution: {integrity: sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==} + engines: {node: '>=12'} + + lru-queue@0.1.0: + resolution: {integrity: sha512-BpdYkt9EvGl8OfWHDQPISVpcl5xZthb+XPsbELj5AQXxIC8IriDZIQYjBJPEm5rS420sjZ0TLEzRcq5KdBhYrQ==} + + macos-alias@0.2.12: + resolution: {integrity: sha512-yiLHa7cfJcGRFq4FrR4tMlpNHb4Vy4mWnpajlSSIFM5k4Lv8/7BbbDLzCAVogWNl0LlLhizRp1drXv0hK9h0Yw==} + os: [darwin] + + make-fetch-happen@10.2.1: + resolution: {integrity: sha512-NgOPbRiaQM10DYXvN3/hhGVI2M5MtITFryzBGxHM5p4wnFxsVCbxkrBrDsk+EZ5OB4jEOT7AjDxtdF+KVEFT7w==} + engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} + + map-age-cleaner@0.1.3: + resolution: {integrity: sha512-bJzx6nMoP6PDLPBFmg7+xRKeFZvFboMrGlxmNj9ClvX53KrmvM5bXFXEWjbz4cz1AFn+jWJ9z/DJSz7hrs0w3w==} + engines: {node: '>=6'} + + matcher@3.0.0: + resolution: {integrity: sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==} + engines: {node: '>=10'} + + mem@4.3.0: + resolution: {integrity: sha512-qX2bG48pTqYRVmDB37rn/6PT7LcR8T7oAX3bf99u1Tt1nzxYfxkgqDwUwolPlXweM0XzBOBFzSx4kfp7KP1s/w==} + engines: {node: '>=6'} + + memoizee@0.4.17: + resolution: {integrity: sha512-DGqD7Hjpi/1or4F/aYAspXKNm5Yili0QDAFAY4QYvpqpgiY6+1jOfqpmByzjxbWd/T9mChbCArXAbDAsTm5oXA==} + engines: {node: '>=0.12'} + + merge-stream@2.0.0: + resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==} + + merge2@1.4.1: + resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==} + engines: {node: '>= 8'} + + micromatch@4.0.8: + resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==} + engines: {node: '>=8.6'} + + mime-db@1.52.0: + resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==} + engines: {node: '>= 0.6'} + + mime-db@1.54.0: + resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==} + engines: {node: '>= 0.6'} + + mime-types@2.1.35: + resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==} + engines: {node: '>= 0.6'} + + mimic-fn@2.1.0: + resolution: {integrity: sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==} + engines: {node: '>=6'} + + mimic-response@1.0.1: + resolution: {integrity: sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==} + engines: {node: '>=4'} + + mimic-response@3.1.0: + resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==} + engines: {node: '>=10'} + + minimatch@10.2.5: + resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==} + engines: {node: 18 || 20 || >=22} + + minimatch@3.1.5: + resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==} + + minimatch@5.1.9: + resolution: {integrity: sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==} + engines: {node: '>=10'} + + minimatch@9.0.9: + resolution: {integrity: sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==} + engines: {node: '>=16 || 14 >=14.17'} + + minimist@1.2.8: + resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} + + minipass-collect@1.0.2: + resolution: {integrity: sha512-6T6lH0H8OG9kITm/Jm6tdooIbogG9e0tLgpY6mphXSm/A9u8Nq1ryBG+Qspiub9LjWlBPsPS3tWQ/Botq4FdxA==} + engines: {node: '>= 8'} + + minipass-fetch@2.1.2: + resolution: {integrity: sha512-LT49Zi2/WMROHYoqGgdlQIZh8mLPZmOrN2NdJjMXxYe4nkN6FUyuPuOAOedNJDrx0IRGg9+4guZewtp8hE6TxA==} + engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} + + minipass-flush@1.0.7: + resolution: {integrity: sha512-TbqTz9cUwWyHS2Dy89P3ocAGUGxKjjLuR9z8w4WUTGAVgEj17/4nhgo2Du56i0Fm3Pm30g4iA8Lcqctc76jCzA==} + engines: {node: '>= 8'} + + minipass-pipeline@1.2.4: + resolution: {integrity: sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A==} + engines: {node: '>=8'} + + minipass-sized@1.0.3: + resolution: {integrity: sha512-MbkQQ2CTiBMlA2Dm/5cY+9SWFEN8pzzOXi6rlM5Xxq0Yqbda5ZQy9sU75a673FE9ZK0Zsbr6Y5iP6u9nktfg2g==} + engines: {node: '>=8'} + + minipass@3.3.6: + resolution: {integrity: sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==} + engines: {node: '>=8'} + + minipass@5.0.0: + resolution: {integrity: sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==} + engines: {node: '>=8'} + + minipass@7.1.3: + resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==} + engines: {node: '>=16 || 14 >=14.17'} + + minizlib@2.1.2: + resolution: {integrity: sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==} + engines: {node: '>= 8'} + + mkdirp-classic@0.5.3: + resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==} + + mkdirp@0.5.6: + resolution: {integrity: sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==} + hasBin: true + + mkdirp@1.0.4: + resolution: {integrity: sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==} + engines: {node: '>=10'} + hasBin: true + + module-details-from-path@1.0.4: + resolution: {integrity: sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w==} + + ms@2.0.0: + resolution: {integrity: sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==} + + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + + murmur-32@0.2.0: + resolution: {integrity: sha512-ZkcWZudylwF+ir3Ld1n7gL6bI2mQAzXvSobPwVtu8aYi2sbXeipeSkdcanRLzIofLcM5F53lGaKm2dk7orBi7Q==} + + mute-stream@1.0.0: + resolution: {integrity: sha512-avsJQhyd+680gKXyG/sQc0nXaC6rBkPOfyHYcFb9+hdkqQkR9bdnkJ0AMZhke0oesPqIO+mFFJ+IdBc7mst4IA==} + engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} + + nan@2.26.2: + resolution: {integrity: sha512-0tTvBTYkt3tdGw22nrAy50x7gpbGCCFH3AFcyS5WiUu7Eu4vWlri1woE6qHBSfy11vksDqkiwjOnlR7WV8G1Hw==} + + napi-build-utils@2.0.0: + resolution: {integrity: sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==} + + negotiator@0.6.4: + resolution: {integrity: sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w==} + engines: {node: '>= 0.6'} + + neo-async@2.6.2: + resolution: {integrity: sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==} + + next-tick@1.1.0: + resolution: {integrity: sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==} + + nice-try@1.0.5: + resolution: {integrity: sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==} + + node-abi@3.92.0: + resolution: {integrity: sha512-KdHvFWZjEKDf0cakgFjebl371GPsISX2oZHcuyKqM7DtogIsHrqKeLTo8wBHxaXRAQlY2PsPlZmfo+9ZCxEREQ==} + engines: {node: '>=10'} + + node-addon-api@7.1.1: + resolution: {integrity: sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==} + + node-api-version@0.2.1: + resolution: {integrity: sha512-2xP/IGGMmmSQpI1+O/k72jF/ykvZ89JeuKX3TLJAYPDVLUalrshrLHkeVcCCZqG/eEa635cr8IBYzgnDvM2O8Q==} + + node-fetch@2.7.0: + resolution: {integrity: sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==} + engines: {node: 4.x || >=6.0.0} + peerDependencies: + encoding: ^0.1.0 + peerDependenciesMeta: + encoding: + optional: true + + node-pty@1.1.0: + resolution: {integrity: sha512-20JqtutY6JPXTUnL0ij1uad7Qe1baT46lyolh2sSENDd4sTzKZ4nmAFkeAARDKwmlLjPx6XKRlwRUxwjOy+lUg==} + + node-releases@2.0.38: + resolution: {integrity: sha512-3qT/88Y3FbH/Kx4szpQQ4HzUbVrHPKTLVpVocKiLfoYvw9XSGOX2FmD2d6DrXbVYyAQTF2HeF6My8jmzx7/CRw==} + + nopt@6.0.0: + resolution: {integrity: sha512-ZwLpbTgdhuZUnZzjd7nb1ZV+4DoiC6/sfiVKok72ym/4Tlf+DFdlHYmT2JPmcNNWV6Pi3SDf1kT+A4r9RTuT9g==} + engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} + hasBin: true + + normalize-package-data@2.5.0: + resolution: {integrity: sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==} + + normalize-url@6.1.0: + resolution: {integrity: sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==} + engines: {node: '>=10'} + + npm-run-path@2.0.2: + resolution: {integrity: sha512-lJxZYlT4DW/bRUtFh1MQIWqmLwQfAxnqWG4HhEdjMlkrJYnJn0Jrr2u3mgxqaWsdiBc76TYkTG/mhrnYTuzfHw==} + engines: {node: '>=4'} + + npm-run-path@4.0.1: + resolution: {integrity: sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==} + engines: {node: '>=8'} + + object-keys@1.1.1: + resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==} + engines: {node: '>= 0.4'} + + once@1.4.0: + resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} + + onetime@5.1.2: + resolution: {integrity: sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==} + engines: {node: '>=6'} + + ora@5.4.1: + resolution: {integrity: sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==} + engines: {node: '>=10'} + + os-tmpdir@1.0.2: + resolution: {integrity: sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==} + engines: {node: '>=0.10.0'} + + p-cancelable@2.1.1: + resolution: {integrity: sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==} + engines: {node: '>=8'} + + p-defer@1.0.0: + resolution: {integrity: sha512-wB3wfAxZpk2AzOfUMJNL+d36xothRSyj8EXOa4f6GMqYDN9BJaaSISbsk+wS9abmnebVw95C2Kb5t85UmpCxuw==} + engines: {node: '>=4'} + + p-finally@1.0.0: + resolution: {integrity: sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow==} + engines: {node: '>=4'} + + p-is-promise@2.1.0: + resolution: {integrity: sha512-Y3W0wlRPK8ZMRbNq97l4M5otioeA5lm1z7bkNkxCka8HSPjR0xRWmpCmc9utiaLP9Jb1eD8BgeIxTW4AIF45Pg==} + engines: {node: '>=6'} + + p-limit@1.3.0: + resolution: {integrity: sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==} + engines: {node: '>=4'} + + p-limit@3.1.0: + resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==} + engines: {node: '>=10'} + + p-locate@2.0.0: + resolution: {integrity: sha512-nQja7m7gSKuewoVRen45CtVfODR3crN3goVQ0DDZ9N3yHxgpkuBhZqsaiotSQRrADUrne346peY7kT3TSACykg==} + engines: {node: '>=4'} + + p-locate@5.0.0: + resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} + engines: {node: '>=10'} + + p-map@4.0.0: + resolution: {integrity: sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ==} + engines: {node: '>=10'} + + p-try@1.0.0: + resolution: {integrity: sha512-U1etNYuMJoIz3ZXSrrySFjsXQTWOx2/jdi86L+2pRvph/qMKL6sbcCYdH23fqsbm8TH2Gn0OybpT4eSFlCVHww==} + engines: {node: '>=4'} + + parse-author@2.0.0: + resolution: {integrity: sha512-yx5DfvkN8JsHL2xk2Os9oTia467qnvRgey4ahSm2X8epehBLx/gWLcy5KI+Y36ful5DzGbCS6RazqZGgy1gHNw==} + engines: {node: '>=0.10.0'} + + parse-color@1.0.0: + resolution: {integrity: sha512-fuDHYgFHJGbpGMgw9skY/bj3HL/Jrn4l/5rSspy00DoT4RyLnDcRvPxdZ+r6OFwIsgAuhDh4I09tAId4mI12bw==} + + parse-json@2.2.0: + resolution: {integrity: sha512-QR/GGaKCkhwk1ePQNYDRKYZ3mwU9ypsKhB0XyFnLQdomyEqk3e8wpW3V5Jp88zbxK4n5ST1nqo+g9juTpownhQ==} + engines: {node: '>=0.10.0'} + + path-exists@3.0.0: + resolution: {integrity: sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==} + engines: {node: '>=4'} + + path-exists@4.0.0: + resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} + engines: {node: '>=8'} + + path-exists@5.0.0: + resolution: {integrity: sha512-RjhtfwJOxzcFmNOi6ltcbcu4Iu+FL3zEj83dk4kAS+fVpTxXLO1b38RvJgT/0QwvV/L3aY9TAnyv0EOqW4GoMQ==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + + path-expression-matcher@1.5.0: + resolution: {integrity: sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ==} + engines: {node: '>=14.0.0'} + + path-is-absolute@1.0.1: + resolution: {integrity: sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==} + engines: {node: '>=0.10.0'} + + path-key@2.0.1: + resolution: {integrity: sha512-fEHGKCSmUSDPv4uoj8AlD+joPlq3peND+HRYyxFz4KPw4z926S/b8rIuFs2FYJg3BwsxJf6A9/3eIdLaYC+9Dw==} + engines: {node: '>=4'} + + path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + + path-parse@1.0.7: + resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} + + path-scurry@2.0.2: + resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==} + engines: {node: 18 || 20 || >=22} + + path-type@2.0.0: + resolution: {integrity: sha512-dUnb5dXUf+kzhC/W/F4e5/SkluXIFf5VUHolW1Eg1irn1hGWjPGdsRcvYJ1nD6lhk8Ir7VM0bHJKsYTx8Jx9OQ==} + engines: {node: '>=4'} + + pe-library@1.0.1: + resolution: {integrity: sha512-nh39Mo1eGWmZS7y+mK/dQIqg7S1lp38DpRxkyoHf0ZcUs/HDc+yyTjuOtTvSMZHmfSLuSQaX945u05Y2Q6UWZg==} + engines: {node: '>=14', npm: '>=7'} + + pend@1.2.0: + resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==} + + pg-int8@1.0.1: + resolution: {integrity: sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==} + engines: {node: '>=4.0.0'} + + pg-protocol@1.13.0: + resolution: {integrity: sha512-zzdvXfS6v89r6v7OcFCHfHlyG/wvry1ALxZo4LqgUoy7W9xhBDMaqOuMiF3qEV45VqsN6rdlcehHrfDtlCPc8w==} + + pg-types@2.2.0: + resolution: {integrity: sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==} + engines: {node: '>=4'} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@2.3.2: + resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==} + engines: {node: '>=8.6'} + + pify@2.3.0: + resolution: {integrity: sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==} + engines: {node: '>=0.10.0'} + + plist@3.1.1: + resolution: {integrity: sha512-ZIfcLJC+7E7FBFnDxm9MPmt7D+DidyQ26lewieO75AdhA2ayMtsJSES0iWzqJQbcVRSrTufQoy0DR94xHue0oA==} + engines: {node: '>=10.4.0'} + + postgres-array@2.0.0: + resolution: {integrity: sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==} + engines: {node: '>=4'} + + postgres-bytea@1.0.1: + resolution: {integrity: sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==} + engines: {node: '>=0.10.0'} + + postgres-date@1.0.7: + resolution: {integrity: sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==} + engines: {node: '>=0.10.0'} + + postgres-interval@1.2.0: + resolution: {integrity: sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==} + engines: {node: '>=0.10.0'} + + postject@1.0.0-alpha.6: + resolution: {integrity: sha512-b9Eb8h2eVqNE8edvKdwqkrY6O7kAwmI8kcnBv1NScolYJbo59XUF0noFq+lxbC1yN20bmC0WBEbDC5H/7ASb0A==} + engines: {node: '>=14.0.0'} + hasBin: true + + prebuild-install@7.1.3: + resolution: {integrity: sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==} + engines: {node: '>=10'} + deprecated: No longer maintained. Please contact the author of the relevant native addon; alternatives are available. + hasBin: true + + prettier@3.8.3: + resolution: {integrity: sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw==} + engines: {node: '>=14'} + hasBin: true + + proc-log@2.0.1: + resolution: {integrity: sha512-Kcmo2FhfDTXdcbfDH76N7uBYHINxc/8GW7UAVuVP9I+Va3uHSerrnKV6dLooga/gh7GlgzuCCr/eoldnL1muGw==} + engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} + + progress@2.0.3: + resolution: {integrity: sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==} + engines: {node: '>=0.4.0'} + + promise-inflight@1.0.1: + resolution: {integrity: sha512-6zWPyEOFaQBJYcGMHBKTKJ3u6TBsnMFOIZSa6ce1e/ZrrsOlnHRHbabMjLiBYKp+n44X9eUI6VUPaukCXHuG4g==} + peerDependencies: + bluebird: '*' + peerDependenciesMeta: + bluebird: + optional: true + + promise-retry@2.0.1: + resolution: {integrity: sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==} + engines: {node: '>=10'} + + pump@3.0.4: + resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==} + + pupa@3.3.0: + resolution: {integrity: sha512-LjgDO2zPtoXP2wJpDjZrGdojii1uqO0cnwKoIoUzkfS98HDmbeiGmYiXo3lXeFlq2xvne1QFQhwYXSUCLKtEuA==} + engines: {node: '>=12.20'} + + queue-microtask@1.2.3: + resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==} + + quick-lru@5.1.1: + resolution: {integrity: sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==} + engines: {node: '>=10'} + + random-path@0.1.2: + resolution: {integrity: sha512-4jY0yoEaQ5v9StCl5kZbNIQlg1QheIDBrdkDn53EynpPb9FgO6//p3X/tgMnrC45XN6QZCzU1Xz/+pSSsJBpRw==} + + rc@1.2.8: + resolution: {integrity: sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==} + hasBin: true + + read-binary-file-arch@1.0.6: + resolution: {integrity: sha512-BNg9EN3DD3GsDXX7Aa8O4p92sryjkmzYYgmgTAc6CA4uGLEDzFfxOxugu21akOxpcXHiEgsYkC6nPsQvLLLmEg==} + hasBin: true + + read-pkg-up@2.0.0: + resolution: {integrity: sha512-1orxQfbWGUiTn9XsPlChs6rLie/AV9jwZTGmu2NZw/CUDJQchXJFYE0Fq5j7+n558T1JhDWLdhyd1Zj+wLY//w==} + engines: {node: '>=4'} + + read-pkg@2.0.0: + resolution: {integrity: sha512-eFIBOPW7FGjzBuk3hdXEuNSiTZS/xEMlH49HxMyzb0hyPfu4EhVjT2DH32K1hSSmVq4sebAWnZuuY5auISUTGA==} + engines: {node: '>=4'} + + readable-stream@3.6.2: + resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==} + engines: {node: '>= 6'} + + rechoir@0.8.0: + resolution: {integrity: sha512-/vxpCXddiX8NGfGO/mTafwjq4aFa/71pvamip0++IQk3zG8cbCj0fifNPrjjF1XMXUne91jL9OoxmdykoEtifQ==} + engines: {node: '>= 10.13.0'} + + repeat-string@1.6.1: + resolution: {integrity: sha512-PV0dzCYDNfRi1jCDbJzpW7jNNDRuCOG/jI5ctQcGKt/clZD+YcPS3yIlWuTJMmESC8aevCFmWJy5wjAFgNqN6w==} + engines: {node: '>=0.10'} + + require-directory@2.1.1: + resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==} + engines: {node: '>=0.10.0'} + + require-from-string@2.0.2: + resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} + engines: {node: '>=0.10.0'} + + require-in-the-middle@8.0.1: + resolution: {integrity: sha512-QT7FVMXfWOYFbeRBF6nu+I6tr2Tf3u0q8RIEjNob/heKY/nh7drD/k7eeMFmSQgnTtCzLDcCu/XEnpW2wk4xCQ==} + engines: {node: '>=9.3.0 || >=8.10.0 <9.0.0'} + + resedit@2.0.3: + resolution: {integrity: sha512-oTeemxwoMuxxTYxXUwjkrOPfngTQehlv0/HoYFNkB4uzsP1Un1A9nI8JQKGOFkxpqkC7qkMs0lUsGrvUlbLNUA==} + engines: {node: '>=14', npm: '>=7'} + + resolve-alpn@1.2.1: + resolution: {integrity: sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g==} + + resolve@1.22.12: + resolution: {integrity: sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==} + engines: {node: '>= 0.4'} + hasBin: true + + responselike@2.0.1: + resolution: {integrity: sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw==} + + restore-cursor@3.1.0: + resolution: {integrity: sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==} + engines: {node: '>=8'} + + restore-cursor@4.0.0: + resolution: {integrity: sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + + retry@0.12.0: + resolution: {integrity: sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==} + engines: {node: '>= 4'} + + reusify@1.1.0: + resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==} + engines: {iojs: '>=1.0.0', node: '>=0.10.0'} + + rfdc@1.4.1: + resolution: {integrity: sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==} + + rimraf@2.6.3: + resolution: {integrity: sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==} + deprecated: Rimraf versions prior to v4 are no longer supported + hasBin: true + + rimraf@3.0.2: + resolution: {integrity: sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==} + deprecated: Rimraf versions prior to v4 are no longer supported + hasBin: true + + roarr@2.15.4: + resolution: {integrity: sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==} + engines: {node: '>=8.0'} + + run-parallel@1.2.0: + resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==} + + safe-buffer@5.2.1: + resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} + + safer-buffer@2.1.2: + resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + + schema-utils@4.3.3: + resolution: {integrity: sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA==} + engines: {node: '>= 10.13.0'} + + semver-compare@1.0.0: + resolution: {integrity: sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==} + + semver@5.7.2: + resolution: {integrity: sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==} + hasBin: true + + semver@6.3.1: + resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==} + hasBin: true + + semver@7.7.4: + resolution: {integrity: sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==} + engines: {node: '>=10'} + hasBin: true + + serialize-error@7.0.1: + resolution: {integrity: sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==} + engines: {node: '>=10'} + + shebang-command@1.2.0: + resolution: {integrity: sha512-EV3L1+UQWGor21OmnvojK36mhg+TyIKDh3iFBKBohr5xeXIhNBcx8oWdgkTEEQ+BEFFYdLRuqMfd5L84N1V5Vg==} + engines: {node: '>=0.10.0'} + + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + + shebang-regex@1.0.0: + resolution: {integrity: sha512-wpoSFAxys6b2a2wHZ1XpDSgD7N9iVjg29Ph9uV/uaP9Ex/KXlkTZTeddxDPSYQpgvzKLGJke2UU0AzoGCjNIvQ==} + engines: {node: '>=0.10.0'} + + shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + + shell-env@4.0.3: + resolution: {integrity: sha512-Ioe5h+hCDZ7pKL5+JGzbtPvZ5ESMHePZ8nLxohlDL+twmlcmutttMhRkrQOed8DeLT8mkYBgbwZfohe8pqaA3g==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + + shlex@3.0.0: + resolution: {integrity: sha512-jHPXQQk9d/QXCvJuLPYMOYWez3c43sORAgcIEoV7bFv5AJSJRAOyw5lQO12PMfd385qiLRCaDt7OtEzgrIGZUA==} + + signal-exit@3.0.7: + resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==} + + signal-exit@4.1.0: + resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} + engines: {node: '>=14'} + + simple-concat@1.0.1: + resolution: {integrity: sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==} + + simple-get@4.0.1: + resolution: {integrity: sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==} + + slice-ansi@5.0.0: + resolution: {integrity: sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ==} + engines: {node: '>=12'} + + smart-buffer@4.2.0: + resolution: {integrity: sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==} + engines: {node: '>= 6.0.0', npm: '>= 3.0.0'} + + smol-toml@1.6.1: + resolution: {integrity: sha512-dWUG8F5sIIARXih1DTaQAX4SsiTXhInKf1buxdY9DIg4ZYPZK5nGM1VRIYmEbDbsHt7USo99xSLFu5Q1IqTmsg==} + engines: {node: '>= 18'} + + socks-proxy-agent@7.0.0: + resolution: {integrity: sha512-Fgl0YPZ902wEsAyiQ+idGd1A7rSFx/ayC1CQVMw5P+EQx2V0SgpGtf6OKFhVjPflPUl9YMmEOnmfjCdMUsygww==} + engines: {node: '>= 10'} + + socks@2.8.8: + resolution: {integrity: sha512-NlGELfPrgX2f1TAAcz0WawlLn+0r3FyhhCRpFFK2CemXenPYvzMWWZINv3eDNo9ucdwme7oCHRY0Jnbs4aIkog==} + engines: {node: '>= 10.0.0', npm: '>= 3.0.0'} + + sort-keys-length@1.0.1: + resolution: {integrity: sha512-GRbEOUqCxemTAk/b32F2xa8wDTs+Z1QHOkbhJDQTvv/6G3ZkbJ+frYWsTcc7cBB3Fu4wy4XlLCuNtJuMn7Gsvw==} + engines: {node: '>=0.10.0'} + + sort-keys@1.1.2: + resolution: {integrity: sha512-vzn8aSqKgytVik0iwdBEi+zevbTYZogewTUM6dtpmGwEcdzbub/TX4bCzRhebDCRC3QzXgJsLRKB2V/Oof7HXg==} + engines: {node: '>=0.10.0'} + + source-map-support@0.5.21: + resolution: {integrity: sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==} + + source-map@0.6.1: + resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==} + engines: {node: '>=0.10.0'} + + spdx-correct@3.2.0: + resolution: {integrity: sha512-kN9dJbvnySHULIluDHy32WHRUu3Og7B9sbY7tsFLctQkIqnMh3hErYgdMjTYuqmcXX+lK5T1lnUt3G7zNswmZA==} + + spdx-exceptions@2.5.0: + resolution: {integrity: sha512-PiU42r+xO4UbUS1buo3LPJkjlO7430Xn5SVAhdpzzsPHsjbYVflnnFdATgabnLude+Cqu25p6N+g2lw/PFsa4w==} + + spdx-expression-parse@3.0.1: + resolution: {integrity: sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==} + + spdx-license-ids@3.0.23: + resolution: {integrity: sha512-CWLcCCH7VLu13TgOH+r8p1O/Znwhqv/dbb6lqWy67G+pT1kHmeD/+V36AVb/vq8QMIQwVShJ6Ssl5FPh0fuSdw==} + + sprintf-js@1.1.3: + resolution: {integrity: sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==} + + ssri@9.0.1: + resolution: {integrity: sha512-o57Wcn66jMQvfHG1FlYbWeZWW/dHZhJXjpIcTfXldXEk5nz5lStPo3mK0OJQfGR3RbZUlbISexbljkJzuEj/8Q==} + engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} + + stream-buffers@2.2.0: + resolution: {integrity: sha512-uyQK/mx5QjHun80FLJTfaWE7JtwfRMKBLkMne6udYOmvH0CawotVa7TfgYHzAnpphn4+TweIx1QKMnRIbipmUg==} + engines: {node: '>= 0.10.0'} + + string-width@4.2.3: + resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} + engines: {node: '>=8'} + + string-width@5.1.2: + resolution: {integrity: sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==} + engines: {node: '>=12'} + + string-width@7.2.0: + resolution: {integrity: sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==} + engines: {node: '>=18'} + + string_decoder@1.3.0: + resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==} + + strip-ansi@6.0.1: + resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} + engines: {node: '>=8'} + + strip-ansi@7.2.0: + resolution: {integrity: sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==} + engines: {node: '>=12'} + + strip-bom@3.0.0: + resolution: {integrity: sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==} + engines: {node: '>=4'} + + strip-eof@1.0.0: + resolution: {integrity: sha512-7FCwGGmx8mD5xQd3RPUvnSpUXHM3BWuzjtpD4TXsfcZ9EL4azvVVUscFYwD9nx8Kh+uCBC00XBtAykoMHwTh8Q==} + engines: {node: '>=0.10.0'} + + strip-final-newline@2.0.0: + resolution: {integrity: sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==} + engines: {node: '>=6'} + + strip-json-comments@2.0.1: + resolution: {integrity: sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==} + engines: {node: '>=0.10.0'} + + strip-outer@1.0.1: + resolution: {integrity: sha512-k55yxKHwaXnpYGsOzg4Vl8+tDrWylxDEpknGjhTiZB8dFRU5rTo9CAzeycivxV3s+zlTKwrs6WxMxR95n26kwg==} + engines: {node: '>=0.10.0'} + + strnum@2.3.0: + resolution: {integrity: sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q==} + + sumchecker@3.0.1: + resolution: {integrity: sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==} + engines: {node: '>= 8.0'} + + supports-color@7.2.0: + resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} + engines: {node: '>=8'} + + supports-color@8.1.1: + resolution: {integrity: sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==} + engines: {node: '>=10'} + + supports-preserve-symlinks-flag@1.0.0: + resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} + engines: {node: '>= 0.4'} + + tapable@2.3.3: + resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==} + engines: {node: '>=6'} + + tar-fs@2.1.4: + resolution: {integrity: sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==} + + tar-stream@2.2.0: + resolution: {integrity: sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==} + engines: {node: '>=6'} + + tar@6.2.1: + resolution: {integrity: sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==} + engines: {node: '>=10'} + + temp@0.9.4: + resolution: {integrity: sha512-yYrrsWnrXMcdsnu/7YMYAofM1ktpL5By7vZhf15CrXijWWrEYZks5AXBudalfSWJLlnen/QUJUB5aoB0kqZUGA==} + engines: {node: '>=6.0.0'} + + terser-webpack-plugin@5.5.0: + resolution: {integrity: sha512-UYhptBwhWvfIjKd/UuFo6D8uq9xpGLDK+z8EDsj/zWhrTaH34cKEbrkMKfV5YWqGBvAYA3tlzZbs2R+qYrbQJA==} + engines: {node: '>= 10.13.0'} + peerDependencies: + '@swc/core': '*' + esbuild: '*' + uglify-js: '*' + webpack: ^5.1.0 + peerDependenciesMeta: + '@swc/core': + optional: true + esbuild: + optional: true + uglify-js: + optional: true + + terser@5.47.1: + resolution: {integrity: sha512-tPbLXTI6ohPASb/1YViL428oEHu6/qv1OxqYnfaonVCFHqx4+wCd95pHrQWsL5X4pl90CTyW9piSAsS2L0VoMw==} + engines: {node: '>=10'} + hasBin: true + + timers-ext@0.1.8: + resolution: {integrity: sha512-wFH7+SEAcKfJpfLPkrgMPvvwnEtj8W4IurvEyrKsDleXnKLCDw71w8jltvfLa8Rm4qQxxT4jmDBYbJG/z7qoww==} + engines: {node: '>=0.12'} + + tiny-each-async@2.0.3: + resolution: {integrity: sha512-5ROII7nElnAirvFn8g7H7MtpfV1daMcyfTGQwsn/x2VtyV+VPiO5CjReCJtWLvoKTDEDmZocf3cNPraiMnBXLA==} + + tmp-promise@3.0.3: + resolution: {integrity: sha512-RwM7MoPojPxsOBYnyd2hy0bxtIlVrihNs9pj5SUvY8Zz1sQcQG2tG1hSr8PDxfgEB8RNKDhqbIlroIarSNDNsQ==} + + tmp@0.0.33: + resolution: {integrity: sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==} + engines: {node: '>=0.6.0'} + + tmp@0.2.5: + resolution: {integrity: sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow==} + engines: {node: '>=14.14'} + + tn1150@0.1.0: + resolution: {integrity: sha512-DbplOfQFkqG5IHcDyyrs/lkvSr3mPUVsFf/RbDppOshs22yTPnSJWEe6FkYd1txAwU/zcnR905ar2fi4kwF29w==} + engines: {node: '>=0.12'} + + to-data-view@1.1.0: + resolution: {integrity: sha512-1eAdufMg6mwgmlojAx3QeMnzB/BTVp7Tbndi3U7ftcT2zCZadjxkkmLmd97zmaxWi+sgGcgWrokmpEoy0Dn0vQ==} + + to-regex-range@5.0.1: + resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} + engines: {node: '>=8.0'} + + tr46@0.0.3: + resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==} + + trim-repeated@1.0.0: + resolution: {integrity: sha512-pkonvlKk8/ZuR0D5tLW8ljt5I8kmxp2XKymhepUeOdCEfKpZaktSArkLHZt76OB1ZvO9bssUsDty4SWhLvZpLg==} + engines: {node: '>=0.10.0'} + + tslib@2.8.1: + resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + + tunnel-agent@0.6.0: + resolution: {integrity: sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==} + + type-fest@0.13.1: + resolution: {integrity: sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==} + engines: {node: '>=10'} + + type-fest@0.21.3: + resolution: {integrity: sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==} + engines: {node: '>=10'} + + type-fest@1.4.0: + resolution: {integrity: sha512-yGSza74xk0UG8k+pLh5oeoYirvIiWo5t0/o3zHHAO2tRDiZcxWP7fywNlXhqb6/r6sWvwi+RsyQMWhVLe4BVuA==} + engines: {node: '>=10'} + + type@2.7.3: + resolution: {integrity: sha512-8j+1QmAbPvLZow5Qpi6NCaN8FB60p/6x8/vfNqOk/hC+HuvFZhL4+WfekuhQLiqFZXOgQdrs3B+XxEmCc6b3FQ==} + + typescript@5.4.5: + resolution: {integrity: sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==} + engines: {node: '>=14.17'} + hasBin: true + + undici-types@6.21.0: + resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} + + undici-types@7.16.0: + resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==} + + undici@7.25.0: + resolution: {integrity: sha512-xXnp4kTyor2Zq+J1FfPI6Eq3ew5h6Vl0F/8d9XU5zZQf1tX9s2Su1/3PiMmUANFULpmksxkClamIZcaUqryHsQ==} + engines: {node: '>=20.18.1'} + + unique-filename@2.0.1: + resolution: {integrity: sha512-ODWHtkkdx3IAR+veKxFV+VBkUMcN+FaqzUUd7IZzt+0zhDZFPFxhlqwPF3YQvMHx1TD0tdgYl+kuPnJ8E6ql7A==} + engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} + + unique-slug@3.0.0: + resolution: {integrity: sha512-8EyMynh679x/0gqE9fT9oilG+qEt+ibFyqjuVTsZn1+CMxH+XLlpvr2UZx4nVcCwTpx81nICr2JQFkM+HPLq4w==} + engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} + + universalify@0.1.2: + resolution: {integrity: sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==} + engines: {node: '>= 4.0.0'} + + universalify@2.0.1: + resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==} + engines: {node: '>= 10.0.0'} + + unorm@1.6.0: + resolution: {integrity: sha512-b2/KCUlYZUeA7JFUuRJZPUtr4gZvBh7tavtv4fvk4+KV9pfGiR6CQAQAWl49ZpR3ts2dk4FYkP7EIgDJoiOLDA==} + engines: {node: '>= 0.4.0'} + + unused-filename@4.0.1: + resolution: {integrity: sha512-ZX6U1J04K1FoSUeoX1OicAhw4d0aro2qo+L8RhJkiGTNtBNkd/Fi1Wxoc9HzcVu6HfOzm0si/N15JjxFmD1z6A==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + + update-browserslist-db@1.2.3: + resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==} + hasBin: true + peerDependencies: + browserslist: '>= 4.21.0' + + username@5.1.0: + resolution: {integrity: sha512-PCKbdWw85JsYMvmCv5GH3kXmM66rCd9m1hBEDutPNv94b/pqCMT4NtcKyeWYvLFiE8b+ha1Jdl8XAaUdPn5QTg==} + engines: {node: '>=8'} + + util-deprecate@1.0.2: + resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} + + validate-npm-package-license@3.0.4: + resolution: {integrity: sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==} + + watchpack@2.5.1: + resolution: {integrity: sha512-Zn5uXdcFNIA1+1Ei5McRd+iRzfhENPCe7LeABkJtNulSxjma+l7ltNx55BWZkRlwRnpOgHqxnjyaDgJnNXnqzg==} + engines: {node: '>=10.13.0'} + + wcwidth@1.0.1: + resolution: {integrity: sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg==} + + webidl-conversions@3.0.1: + resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==} + + webpack-sources@3.4.1: + resolution: {integrity: sha512-eACpxRN02yaawnt+uUNIF7Qje6A9zArxBbcAJjK1PK3S9Ycg5jIuJ8pW4q8EMnwNZCEGltcjkRx1QzOxOkKD8A==} + engines: {node: '>=10.13.0'} + + webpack@5.106.2: + resolution: {integrity: sha512-wGN3qcrBQIFmQ/c0AiOAQBvrZ5lmY8vbbMv4Mxfgzqd/B6+9pXtLo73WuS1dSGXM5QYY3hZnIbvx+K1xxe6FyA==} + engines: {node: '>=10.13.0'} + hasBin: true + peerDependencies: + webpack-cli: '*' + peerDependenciesMeta: + webpack-cli: + optional: true + + whatwg-url@5.0.0: + resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==} + + which@1.3.1: + resolution: {integrity: sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==} + hasBin: true + + which@2.0.2: + resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} + engines: {node: '>= 8'} + hasBin: true + + word-wrap@1.2.5: + resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} + engines: {node: '>=0.10.0'} + + wrap-ansi@6.2.0: + resolution: {integrity: sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==} + engines: {node: '>=8'} + + wrap-ansi@7.0.0: + resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} + engines: {node: '>=10'} + + wrap-ansi@8.1.0: + resolution: {integrity: sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==} + engines: {node: '>=12'} + + wrappy@1.0.2: + resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} + + xmlbuilder@15.1.1: + resolution: {integrity: sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==} + engines: {node: '>=8.0'} + + xtend@4.0.2: + resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==} + engines: {node: '>=0.4'} + + y18n@5.0.8: + resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} + engines: {node: '>=10'} + + yallist@4.0.0: + resolution: {integrity: sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==} + + yargs-parser@20.2.9: + resolution: {integrity: sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==} + engines: {node: '>=10'} + + yargs-parser@21.1.1: + resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} + engines: {node: '>=12'} + + yargs@16.2.0: + resolution: {integrity: sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==} + engines: {node: '>=10'} + + yargs@17.7.2: + resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==} + engines: {node: '>=12'} + + yauzl@2.10.0: + resolution: {integrity: sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==} + + yocto-queue@0.1.0: + resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} + engines: {node: '>=10'} + + yoctocolors-cjs@2.1.3: + resolution: {integrity: sha512-U/PBtDf35ff0D8X8D0jfdzHYEPFxAI7jJlxZXwCSez5M3190m+QobIfh+sWDWSHMCWWJN2AWamkegn6vr6YBTw==} + engines: {node: '>=18'} + + zod@4.4.3: + resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==} + +snapshots: + + '@apm-js-collab/code-transformer@0.8.2': {} + + '@apm-js-collab/tracing-hooks@0.3.1': + dependencies: + '@apm-js-collab/code-transformer': 0.8.2 + debug: 4.4.3 + module-details-from-path: 1.0.4 + transitivePeerDependencies: + - supports-color + + '@electron-forge/cli@7.11.1(encoding@0.1.13)': + dependencies: + '@electron-forge/core': 7.11.1(encoding@0.1.13) + '@electron-forge/core-utils': 7.11.1 + '@electron-forge/shared-types': 7.11.1 + '@electron/get': 3.1.0 + '@inquirer/prompts': 6.0.1 + '@listr2/prompt-adapter-inquirer': 2.0.22(@inquirer/prompts@6.0.1) + chalk: 4.1.2 + commander: 11.1.0 + debug: 4.4.3 + fs-extra: 10.1.0 + listr2: 7.0.2 + log-symbols: 4.1.0 + semver: 7.7.4 + transitivePeerDependencies: + - '@swc/core' + - bluebird + - encoding + - esbuild + - supports-color + - uglify-js + - webpack-cli + + '@electron-forge/core-utils@7.11.1': + dependencies: + '@electron-forge/shared-types': 7.11.1 + '@electron/rebuild': 3.7.2 + '@malept/cross-spawn-promise': 2.0.0 + chalk: 4.1.2 + debug: 4.4.3 + find-up: 5.0.0 + fs-extra: 10.1.0 + log-symbols: 4.1.0 + parse-author: 2.0.0 + semver: 7.7.4 + transitivePeerDependencies: + - bluebird + - supports-color + + '@electron-forge/core@7.11.1(encoding@0.1.13)': + dependencies: + '@electron-forge/core-utils': 7.11.1 + '@electron-forge/maker-base': 7.11.1 + '@electron-forge/plugin-base': 7.11.1 + '@electron-forge/publisher-base': 7.11.1 + '@electron-forge/shared-types': 7.11.1 + '@electron-forge/template-base': 7.11.1 + '@electron-forge/template-vite': 7.11.1 + '@electron-forge/template-vite-typescript': 7.11.1 + '@electron-forge/template-webpack': 7.11.1 + '@electron-forge/template-webpack-typescript': 7.11.1 + '@electron-forge/tracer': 7.11.1 + '@electron/get': 3.1.0 + '@electron/packager': 18.4.4 + '@electron/rebuild': 3.7.2 + '@malept/cross-spawn-promise': 2.0.0 + '@vscode/sudo-prompt': 9.3.2 + chalk: 4.1.2 + debug: 4.4.3 + fast-glob: 3.3.3 + filenamify: 4.3.0 + find-up: 5.0.0 + fs-extra: 10.1.0 + global-dirs: 3.0.1 + got: 11.8.6 + interpret: 3.1.1 + jiti: 2.7.0 + listr2: 7.0.2 + lodash: 4.18.1 + log-symbols: 4.1.0 + node-fetch: 2.7.0(encoding@0.1.13) + rechoir: 0.8.0 + semver: 7.7.4 + source-map-support: 0.5.21 + username: 5.1.0 + transitivePeerDependencies: + - '@swc/core' + - bluebird + - encoding + - esbuild + - supports-color + - uglify-js + - webpack-cli + + '@electron-forge/maker-base@7.11.1': + dependencies: + '@electron-forge/shared-types': 7.11.1 + fs-extra: 10.1.0 + which: 2.0.2 + transitivePeerDependencies: + - bluebird + - supports-color + + '@electron-forge/maker-deb@7.11.1': + dependencies: + '@electron-forge/maker-base': 7.11.1 + '@electron-forge/shared-types': 7.11.1 + optionalDependencies: + electron-installer-debian: 3.2.0 + transitivePeerDependencies: + - bluebird + - supports-color + + '@electron-forge/maker-dmg@7.11.1': + dependencies: + '@electron-forge/maker-base': 7.11.1 + '@electron-forge/shared-types': 7.11.1 + fs-extra: 10.1.0 + optionalDependencies: + electron-installer-dmg: 5.0.1 + transitivePeerDependencies: + - bluebird + - supports-color + + '@electron-forge/maker-rpm@7.11.1': + dependencies: + '@electron-forge/maker-base': 7.11.1 + '@electron-forge/shared-types': 7.11.1 + optionalDependencies: + electron-installer-redhat: 3.4.0 + transitivePeerDependencies: + - bluebird + - supports-color + + '@electron-forge/maker-squirrel@7.11.1': + dependencies: + '@electron-forge/maker-base': 7.11.1 + '@electron-forge/shared-types': 7.11.1 + fs-extra: 10.1.0 + optionalDependencies: + electron-winstaller: 5.4.0 + transitivePeerDependencies: + - bluebird + - supports-color + + '@electron-forge/maker-zip@7.11.1': + dependencies: + '@electron-forge/maker-base': 7.11.1 + '@electron-forge/shared-types': 7.11.1 + cross-zip: 4.0.1 + fs-extra: 10.1.0 + got: 11.8.6 + transitivePeerDependencies: + - bluebird + - supports-color + + '@electron-forge/plugin-auto-unpack-natives@7.11.1': + dependencies: + '@electron-forge/plugin-base': 7.11.1 + '@electron-forge/shared-types': 7.11.1 + transitivePeerDependencies: + - bluebird + - supports-color + + '@electron-forge/plugin-base@7.11.1': + dependencies: + '@electron-forge/shared-types': 7.11.1 + transitivePeerDependencies: + - bluebird + - supports-color + + '@electron-forge/plugin-fuses@7.11.1(@electron/fuses@1.8.0)': + dependencies: + '@electron-forge/plugin-base': 7.11.1 + '@electron-forge/shared-types': 7.11.1 + '@electron/fuses': 1.8.0 + transitivePeerDependencies: + - bluebird + - supports-color + + '@electron-forge/publisher-base@7.11.1': + dependencies: + '@electron-forge/shared-types': 7.11.1 + transitivePeerDependencies: + - bluebird + - supports-color + + '@electron-forge/shared-types@7.11.1': + dependencies: + '@electron-forge/tracer': 7.11.1 + '@electron/packager': 18.4.4 + '@electron/rebuild': 3.7.2 + listr2: 7.0.2 + transitivePeerDependencies: + - bluebird + - supports-color + + '@electron-forge/template-base@7.11.1': + dependencies: + '@electron-forge/core-utils': 7.11.1 + '@electron-forge/shared-types': 7.11.1 + '@malept/cross-spawn-promise': 2.0.0 + debug: 4.4.3 + fs-extra: 10.1.0 + semver: 7.7.4 + username: 5.1.0 + transitivePeerDependencies: + - bluebird + - supports-color + + '@electron-forge/template-vite-typescript@7.11.1': + dependencies: + '@electron-forge/shared-types': 7.11.1 + '@electron-forge/template-base': 7.11.1 + fs-extra: 10.1.0 + transitivePeerDependencies: + - bluebird + - supports-color + + '@electron-forge/template-vite@7.11.1': + dependencies: + '@electron-forge/shared-types': 7.11.1 + '@electron-forge/template-base': 7.11.1 + fs-extra: 10.1.0 + transitivePeerDependencies: + - bluebird + - supports-color + + '@electron-forge/template-webpack-typescript@7.11.1': + dependencies: + '@electron-forge/shared-types': 7.11.1 + '@electron-forge/template-base': 7.11.1 + fs-extra: 10.1.0 + typescript: 5.4.5 + webpack: 5.106.2 + transitivePeerDependencies: + - '@swc/core' + - bluebird + - esbuild + - supports-color + - uglify-js + - webpack-cli + + '@electron-forge/template-webpack@7.11.1': + dependencies: + '@electron-forge/shared-types': 7.11.1 + '@electron-forge/template-base': 7.11.1 + fs-extra: 10.1.0 + transitivePeerDependencies: + - bluebird + - supports-color + + '@electron-forge/tracer@7.11.1': + dependencies: + chrome-trace-event: 1.0.4 + + '@electron/asar@3.4.1': + dependencies: + commander: 5.1.0 + glob: 7.2.3 + minimatch: 3.1.5 + + '@electron/asar@4.2.0': + dependencies: + commander: 13.1.0 + glob: 13.0.6 + minimatch: 10.2.5 + + '@electron/fuses@1.8.0': + dependencies: + chalk: 4.1.2 + fs-extra: 9.1.0 + minimist: 1.2.8 + + '@electron/get@3.1.0': + dependencies: + debug: 4.4.3 + env-paths: 2.2.1 + fs-extra: 8.1.0 + got: 11.8.6 + progress: 2.0.3 + semver: 6.3.1 + sumchecker: 3.0.1 + optionalDependencies: + global-agent: 3.0.0 + transitivePeerDependencies: + - supports-color + + '@electron/get@5.0.0': + dependencies: + debug: 4.4.3 + env-paths: 3.0.0 + graceful-fs: 4.2.11 + progress: 2.0.3 + semver: 7.7.4 + sumchecker: 3.0.1 + optionalDependencies: + undici: 7.25.0 + transitivePeerDependencies: + - supports-color + + '@electron/node-gyp@https://codeload.github.com/electron/node-gyp/tar.gz/06b29aafb7708acef8b3669835c8a7857ebc92d2': + dependencies: + env-paths: 2.2.1 + exponential-backoff: 3.1.3 + glob: 8.1.0 + graceful-fs: 4.2.11 + make-fetch-happen: 10.2.1 + nopt: 6.0.0 + proc-log: 2.0.1 + semver: 7.7.4 + tar: 6.2.1 + which: 2.0.2 + transitivePeerDependencies: + - bluebird + - supports-color + + '@electron/notarize@2.5.0': + dependencies: + debug: 4.4.3 + fs-extra: 9.1.0 + promise-retry: 2.0.1 + transitivePeerDependencies: + - supports-color + + '@electron/osx-sign@1.3.3': + dependencies: + compare-version: 0.1.2 + debug: 4.4.3 + fs-extra: 10.1.0 + isbinaryfile: 4.0.10 + minimist: 1.2.8 + plist: 3.1.1 + transitivePeerDependencies: + - supports-color + + '@electron/packager@18.4.4': + dependencies: + '@electron/asar': 3.4.1 + '@electron/get': 3.1.0 + '@electron/notarize': 2.5.0 + '@electron/osx-sign': 1.3.3 + '@electron/universal': 2.0.3 + '@electron/windows-sign': 1.2.2 + '@malept/cross-spawn-promise': 2.0.0 + debug: 4.4.3 + extract-zip: 2.0.1 + filenamify: 4.3.0 + fs-extra: 11.3.5 + galactus: 1.0.0 + get-package-info: 1.0.0 + junk: 3.1.0 + parse-author: 2.0.0 + plist: 3.1.1 + prettier: 3.8.3 + resedit: 2.0.3 + resolve: 1.22.12 + semver: 7.7.4 + yargs-parser: 21.1.1 + transitivePeerDependencies: + - supports-color + + '@electron/rebuild@3.7.2': + dependencies: + '@electron/node-gyp': https://codeload.github.com/electron/node-gyp/tar.gz/06b29aafb7708acef8b3669835c8a7857ebc92d2 + '@malept/cross-spawn-promise': 2.0.0 + chalk: 4.1.2 + debug: 4.4.3 + detect-libc: 2.1.2 + fs-extra: 10.1.0 + got: 11.8.6 + node-abi: 3.92.0 + node-api-version: 0.2.1 + ora: 5.4.1 + read-binary-file-arch: 1.0.6 + semver: 7.7.4 + tar: 6.2.1 + yargs: 17.7.2 + transitivePeerDependencies: + - bluebird + - supports-color + + '@electron/universal@2.0.3': + dependencies: + '@electron/asar': 3.4.1 + '@malept/cross-spawn-promise': 2.0.0 + debug: 4.4.3 + dir-compare: 4.2.0 + fs-extra: 11.3.5 + minimatch: 9.0.9 + plist: 3.1.1 + transitivePeerDependencies: + - supports-color + + '@electron/windows-sign@1.2.2': + dependencies: + cross-dirname: 0.1.0 + debug: 4.4.3 + fs-extra: 11.3.5 + minimist: 1.2.8 + postject: 1.0.0-alpha.6 + transitivePeerDependencies: + - supports-color + + '@fastify/otel@0.18.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.212.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + minimatch: 10.2.5 + transitivePeerDependencies: + - supports-color + + '@gar/promisify@1.1.3': {} + + '@inquirer/checkbox@3.0.1': + dependencies: + '@inquirer/core': 9.2.1 + '@inquirer/figures': 1.0.15 + '@inquirer/type': 2.0.0 + ansi-escapes: 4.3.2 + yoctocolors-cjs: 2.1.3 + + '@inquirer/confirm@4.0.1': + dependencies: + '@inquirer/core': 9.2.1 + '@inquirer/type': 2.0.0 + + '@inquirer/core@9.2.1': + dependencies: + '@inquirer/figures': 1.0.15 + '@inquirer/type': 2.0.0 + '@types/mute-stream': 0.0.4 + '@types/node': 22.19.17 + '@types/wrap-ansi': 3.0.0 + ansi-escapes: 4.3.2 + cli-width: 4.1.0 + mute-stream: 1.0.0 + signal-exit: 4.1.0 + strip-ansi: 6.0.1 + wrap-ansi: 6.2.0 + yoctocolors-cjs: 2.1.3 + + '@inquirer/editor@3.0.1': + dependencies: + '@inquirer/core': 9.2.1 + '@inquirer/type': 2.0.0 + external-editor: 3.1.0 + + '@inquirer/expand@3.0.1': + dependencies: + '@inquirer/core': 9.2.1 + '@inquirer/type': 2.0.0 + yoctocolors-cjs: 2.1.3 + + '@inquirer/figures@1.0.15': {} + + '@inquirer/input@3.0.1': + dependencies: + '@inquirer/core': 9.2.1 + '@inquirer/type': 2.0.0 + + '@inquirer/number@2.0.1': + dependencies: + '@inquirer/core': 9.2.1 + '@inquirer/type': 2.0.0 + + '@inquirer/password@3.0.1': + dependencies: + '@inquirer/core': 9.2.1 + '@inquirer/type': 2.0.0 + ansi-escapes: 4.3.2 + + '@inquirer/prompts@6.0.1': + dependencies: + '@inquirer/checkbox': 3.0.1 + '@inquirer/confirm': 4.0.1 + '@inquirer/editor': 3.0.1 + '@inquirer/expand': 3.0.1 + '@inquirer/input': 3.0.1 + '@inquirer/number': 2.0.1 + '@inquirer/password': 3.0.1 + '@inquirer/rawlist': 3.0.1 + '@inquirer/search': 2.0.1 + '@inquirer/select': 3.0.1 + + '@inquirer/rawlist@3.0.1': + dependencies: + '@inquirer/core': 9.2.1 + '@inquirer/type': 2.0.0 + yoctocolors-cjs: 2.1.3 + + '@inquirer/search@2.0.1': + dependencies: + '@inquirer/core': 9.2.1 + '@inquirer/figures': 1.0.15 + '@inquirer/type': 2.0.0 + yoctocolors-cjs: 2.1.3 + + '@inquirer/select@3.0.1': + dependencies: + '@inquirer/core': 9.2.1 + '@inquirer/figures': 1.0.15 + '@inquirer/type': 2.0.0 + ansi-escapes: 4.3.2 + yoctocolors-cjs: 2.1.3 + + '@inquirer/type@1.5.5': + dependencies: + mute-stream: 1.0.0 + + '@inquirer/type@2.0.0': + dependencies: + mute-stream: 1.0.0 + + '@jridgewell/gen-mapping@0.3.13': + dependencies: + '@jridgewell/sourcemap-codec': 1.5.5 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/source-map@0.3.11': + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/sourcemap-codec@1.5.5': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.5.5 + + '@listr2/prompt-adapter-inquirer@2.0.22(@inquirer/prompts@6.0.1)': + dependencies: + '@inquirer/prompts': 6.0.1 + '@inquirer/type': 1.5.5 + + '@malept/cross-spawn-promise@1.1.1': + dependencies: + cross-spawn: 7.0.6 + optional: true + + '@malept/cross-spawn-promise@2.0.0': + dependencies: + cross-spawn: 7.0.6 + + '@nodable/entities@2.1.0': {} + + '@nodelib/fs.scandir@2.1.5': + dependencies: + '@nodelib/fs.stat': 2.0.5 + run-parallel: 1.2.0 + + '@nodelib/fs.stat@2.0.5': {} + + '@nodelib/fs.walk@1.2.8': + dependencies: + '@nodelib/fs.scandir': 2.1.5 + fastq: 1.20.1 + + '@npmcli/fs@2.1.2': + dependencies: + '@gar/promisify': 1.1.3 + semver: 7.7.4 + + '@npmcli/move-file@2.0.1': + dependencies: + mkdirp: 1.0.4 + rimraf: 3.0.2 + + '@opentelemetry/api-logs@0.207.0': + dependencies: + '@opentelemetry/api': 1.9.1 + + '@opentelemetry/api-logs@0.208.0': + dependencies: + '@opentelemetry/api': 1.9.1 + + '@opentelemetry/api-logs@0.212.0': + dependencies: + '@opentelemetry/api': 1.9.1 + + '@opentelemetry/api-logs@0.214.0': + dependencies: + '@opentelemetry/api': 1.9.1 + + '@opentelemetry/api@1.9.1': {} + + '@opentelemetry/context-async-hooks@2.7.1(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + + '@opentelemetry/core@2.2.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/semantic-conventions': 1.40.0 + + '@opentelemetry/core@2.6.1(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/semantic-conventions': 1.40.0 + + '@opentelemetry/core@2.7.1(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/semantic-conventions': 1.40.0 + + '@opentelemetry/instrumentation-amqplib@0.55.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-amqplib@0.61.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-connect@0.52.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + '@types/connect': 3.4.38 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-connect@0.57.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + '@types/connect': 3.4.38 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-dataloader@0.26.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-dataloader@0.31.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-express@0.57.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-fs@0.28.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-fs@0.33.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-generic-pool@0.52.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-generic-pool@0.57.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-graphql@0.56.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-graphql@0.62.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-hapi@0.55.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-hapi@0.60.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-http@0.208.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.2.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + forwarded-parse: 2.1.2 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-http@0.214.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.6.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + forwarded-parse: 2.1.2 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-ioredis@0.56.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + '@opentelemetry/redis-common': 0.38.3 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-ioredis@0.62.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + '@opentelemetry/redis-common': 0.38.3 + '@opentelemetry/semantic-conventions': 1.40.0 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-kafkajs@0.18.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-kafkajs@0.23.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-knex@0.53.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-knex@0.58.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-koa@0.57.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-koa@0.62.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-lru-memoizer@0.53.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-lru-memoizer@0.58.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-mongodb@0.61.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-mongodb@0.67.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-mongoose@0.55.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-mongoose@0.60.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-mysql2@0.55.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + '@opentelemetry/sql-common': 0.41.2(@opentelemetry/api@1.9.1) + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-mysql2@0.60.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + '@opentelemetry/sql-common': 0.41.2(@opentelemetry/api@1.9.1) + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-mysql@0.54.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + '@types/mysql': 2.15.27 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-mysql@0.60.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + '@types/mysql': 2.15.27 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-pg@0.61.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + '@opentelemetry/sql-common': 0.41.2(@opentelemetry/api@1.9.1) + '@types/pg': 8.15.6 + '@types/pg-pool': 2.0.6 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-pg@0.66.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + '@opentelemetry/sql-common': 0.41.2(@opentelemetry/api@1.9.1) + '@types/pg': 8.15.6 + '@types/pg-pool': 2.0.7 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-redis@0.57.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + '@opentelemetry/redis-common': 0.38.3 + '@opentelemetry/semantic-conventions': 1.40.0 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-redis@0.62.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + '@opentelemetry/redis-common': 0.38.3 + '@opentelemetry/semantic-conventions': 1.40.0 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-tedious@0.27.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + '@types/tedious': 4.0.14 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-tedious@0.33.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + '@types/tedious': 4.0.14 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation-undici@0.19.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation@0.207.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/api-logs': 0.207.0 + import-in-the-middle: 2.0.6 + require-in-the-middle: 8.0.1 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation@0.208.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/api-logs': 0.208.0 + import-in-the-middle: 2.0.6 + require-in-the-middle: 8.0.1 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation@0.212.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/api-logs': 0.212.0 + import-in-the-middle: 2.0.6 + require-in-the-middle: 8.0.1 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/instrumentation@0.214.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/api-logs': 0.214.0 + import-in-the-middle: 3.0.1 + require-in-the-middle: 8.0.1 + transitivePeerDependencies: + - supports-color + + '@opentelemetry/redis-common@0.38.3': {} + + '@opentelemetry/resources@2.7.1(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + + '@opentelemetry/sdk-trace-base@2.7.1(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/resources': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + + '@opentelemetry/semantic-conventions@1.40.0': {} + + '@opentelemetry/sql-common@0.41.2(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + + '@prisma/instrumentation@6.19.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + transitivePeerDependencies: + - supports-color + + '@prisma/instrumentation@7.6.0(@opentelemetry/api@1.9.1)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/instrumentation': 0.207.0(@opentelemetry/api@1.9.1) + transitivePeerDependencies: + - supports-color + + '@sentry-internal/browser-utils@10.50.0': + dependencies: + '@sentry/core': 10.50.0 + + '@sentry-internal/feedback@10.50.0': + dependencies: + '@sentry/core': 10.50.0 + + '@sentry-internal/replay-canvas@10.50.0': + dependencies: + '@sentry-internal/replay': 10.50.0 + '@sentry/core': 10.50.0 + + '@sentry-internal/replay@10.50.0': + dependencies: + '@sentry-internal/browser-utils': 10.50.0 + '@sentry/core': 10.50.0 + + '@sentry/browser@10.50.0': + dependencies: + '@sentry-internal/browser-utils': 10.50.0 + '@sentry-internal/feedback': 10.50.0 + '@sentry-internal/replay': 10.50.0 + '@sentry-internal/replay-canvas': 10.50.0 + '@sentry/core': 10.50.0 + + '@sentry/core@10.29.0': {} + + '@sentry/core@10.50.0': {} + + '@sentry/electron@7.13.0': + dependencies: + '@sentry/browser': 10.50.0 + '@sentry/core': 10.50.0 + '@sentry/node': 10.50.0 + transitivePeerDependencies: + - '@opentelemetry/exporter-trace-otlp-http' + - supports-color + + '@sentry/node-core@10.29.0(@opentelemetry/api@1.9.1)(@opentelemetry/context-async-hooks@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/core@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/instrumentation@0.208.0(@opentelemetry/api@1.9.1))(@opentelemetry/resources@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/sdk-trace-base@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/semantic-conventions@1.40.0)': + dependencies: + '@apm-js-collab/tracing-hooks': 0.3.1 + '@opentelemetry/api': 1.9.1 + '@opentelemetry/context-async-hooks': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + '@opentelemetry/resources': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + '@sentry/core': 10.29.0 + '@sentry/opentelemetry': 10.29.0(@opentelemetry/api@1.9.1)(@opentelemetry/context-async-hooks@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/core@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/sdk-trace-base@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/semantic-conventions@1.40.0) + import-in-the-middle: 2.0.6 + transitivePeerDependencies: + - supports-color + + '@sentry/node-core@10.50.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/instrumentation@0.214.0(@opentelemetry/api@1.9.1))(@opentelemetry/sdk-trace-base@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/semantic-conventions@1.40.0)': + dependencies: + '@sentry/core': 10.50.0 + '@sentry/opentelemetry': 10.50.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/sdk-trace-base@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/semantic-conventions@1.40.0) + import-in-the-middle: 3.0.1 + optionalDependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + + '@sentry/node@10.29.0': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/context-async-hooks': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-amqplib': 0.55.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-connect': 0.52.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-dataloader': 0.26.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-express': 0.57.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-fs': 0.28.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-generic-pool': 0.52.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-graphql': 0.56.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-hapi': 0.55.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-http': 0.208.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-ioredis': 0.56.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-kafkajs': 0.18.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-knex': 0.53.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-koa': 0.57.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-lru-memoizer': 0.53.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-mongodb': 0.61.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-mongoose': 0.55.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-mysql': 0.54.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-mysql2': 0.55.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-pg': 0.61.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-redis': 0.57.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-tedious': 0.27.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-undici': 0.19.0(@opentelemetry/api@1.9.1) + '@opentelemetry/resources': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + '@prisma/instrumentation': 6.19.0(@opentelemetry/api@1.9.1) + '@sentry/core': 10.29.0 + '@sentry/node-core': 10.29.0(@opentelemetry/api@1.9.1)(@opentelemetry/context-async-hooks@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/core@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/instrumentation@0.208.0(@opentelemetry/api@1.9.1))(@opentelemetry/resources@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/sdk-trace-base@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/semantic-conventions@1.40.0) + '@sentry/opentelemetry': 10.29.0(@opentelemetry/api@1.9.1)(@opentelemetry/context-async-hooks@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/core@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/sdk-trace-base@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/semantic-conventions@1.40.0) + import-in-the-middle: 2.0.6 + minimatch: 9.0.9 + transitivePeerDependencies: + - supports-color + + '@sentry/node@10.50.0': + dependencies: + '@fastify/otel': 0.18.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-amqplib': 0.61.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-connect': 0.57.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-dataloader': 0.31.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-fs': 0.33.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-generic-pool': 0.57.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-graphql': 0.62.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-hapi': 0.60.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-http': 0.214.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-ioredis': 0.62.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-kafkajs': 0.23.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-knex': 0.58.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-koa': 0.62.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-lru-memoizer': 0.58.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-mongodb': 0.67.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-mongoose': 0.60.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-mysql': 0.60.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-mysql2': 0.60.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-pg': 0.66.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-redis': 0.62.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation-tedious': 0.33.0(@opentelemetry/api@1.9.1) + '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + '@prisma/instrumentation': 7.6.0(@opentelemetry/api@1.9.1) + '@sentry/core': 10.50.0 + '@sentry/node-core': 10.50.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/instrumentation@0.214.0(@opentelemetry/api@1.9.1))(@opentelemetry/sdk-trace-base@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/semantic-conventions@1.40.0) + '@sentry/opentelemetry': 10.50.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/sdk-trace-base@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/semantic-conventions@1.40.0) + import-in-the-middle: 3.0.1 + transitivePeerDependencies: + - '@opentelemetry/exporter-trace-otlp-http' + - supports-color + + '@sentry/opentelemetry@10.29.0(@opentelemetry/api@1.9.1)(@opentelemetry/context-async-hooks@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/core@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/sdk-trace-base@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/semantic-conventions@1.40.0)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/context-async-hooks': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + '@sentry/core': 10.29.0 + + '@sentry/opentelemetry@10.50.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/sdk-trace-base@2.7.1(@opentelemetry/api@1.9.1))(@opentelemetry/semantic-conventions@1.40.0)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.40.0 + '@sentry/core': 10.50.0 + + '@sindresorhus/is@4.6.0': {} + + '@szmarczak/http-timer@4.0.6': + dependencies: + defer-to-connect: 2.0.1 + + '@tootallnate/once@2.0.1': {} + + '@types/appdmg@0.5.5': + dependencies: + '@types/node': 24.12.2 + optional: true + + '@types/cacheable-request@6.0.3': + dependencies: + '@types/http-cache-semantics': 4.2.0 + '@types/keyv': 3.1.4 + '@types/node': 24.12.2 + '@types/responselike': 1.0.3 + + '@types/connect@3.4.38': + dependencies: + '@types/node': 24.12.2 + + '@types/eslint-scope@3.7.7': + dependencies: + '@types/eslint': 9.6.1 + '@types/estree': 1.0.9 + + '@types/eslint@9.6.1': + dependencies: + '@types/estree': 1.0.9 + '@types/json-schema': 7.0.15 + + '@types/estree@1.0.9': {} + + '@types/fs-extra@9.0.13': + dependencies: + '@types/node': 24.12.2 + optional: true + + '@types/http-cache-semantics@4.2.0': {} + + '@types/json-schema@7.0.15': {} + + '@types/keyv@3.1.4': + dependencies: + '@types/node': 24.12.2 + + '@types/mute-stream@0.0.4': + dependencies: + '@types/node': 24.12.2 + + '@types/mysql@2.15.27': + dependencies: + '@types/node': 24.12.2 + + '@types/node@22.19.17': + dependencies: + undici-types: 6.21.0 + + '@types/node@24.12.2': + dependencies: + undici-types: 7.16.0 + + '@types/pg-pool@2.0.6': + dependencies: + '@types/pg': 8.15.6 + + '@types/pg-pool@2.0.7': + dependencies: + '@types/pg': 8.15.6 + + '@types/pg@8.15.6': + dependencies: + '@types/node': 24.12.2 + pg-protocol: 1.13.0 + pg-types: 2.2.0 + + '@types/responselike@1.0.3': + dependencies: + '@types/node': 24.12.2 + + '@types/tedious@4.0.14': + dependencies: + '@types/node': 24.12.2 + + '@types/wrap-ansi@3.0.0': {} + + '@types/yauzl@2.10.3': + dependencies: + '@types/node': 24.12.2 + optional: true + + '@vscode/sudo-prompt@9.3.2': {} + + '@webassemblyjs/ast@1.14.1': + dependencies: + '@webassemblyjs/helper-numbers': 1.13.2 + '@webassemblyjs/helper-wasm-bytecode': 1.13.2 + + '@webassemblyjs/floating-point-hex-parser@1.13.2': {} + + '@webassemblyjs/helper-api-error@1.13.2': {} + + '@webassemblyjs/helper-buffer@1.14.1': {} + + '@webassemblyjs/helper-numbers@1.13.2': + dependencies: + '@webassemblyjs/floating-point-hex-parser': 1.13.2 + '@webassemblyjs/helper-api-error': 1.13.2 + '@xtuc/long': 4.2.2 + + '@webassemblyjs/helper-wasm-bytecode@1.13.2': {} + + '@webassemblyjs/helper-wasm-section@1.14.1': + dependencies: + '@webassemblyjs/ast': 1.14.1 + '@webassemblyjs/helper-buffer': 1.14.1 + '@webassemblyjs/helper-wasm-bytecode': 1.13.2 + '@webassemblyjs/wasm-gen': 1.14.1 + + '@webassemblyjs/ieee754@1.13.2': + dependencies: + '@xtuc/ieee754': 1.2.0 + + '@webassemblyjs/leb128@1.13.2': + dependencies: + '@xtuc/long': 4.2.2 + + '@webassemblyjs/utf8@1.13.2': {} + + '@webassemblyjs/wasm-edit@1.14.1': + dependencies: + '@webassemblyjs/ast': 1.14.1 + '@webassemblyjs/helper-buffer': 1.14.1 + '@webassemblyjs/helper-wasm-bytecode': 1.13.2 + '@webassemblyjs/helper-wasm-section': 1.14.1 + '@webassemblyjs/wasm-gen': 1.14.1 + '@webassemblyjs/wasm-opt': 1.14.1 + '@webassemblyjs/wasm-parser': 1.14.1 + '@webassemblyjs/wast-printer': 1.14.1 + + '@webassemblyjs/wasm-gen@1.14.1': + dependencies: + '@webassemblyjs/ast': 1.14.1 + '@webassemblyjs/helper-wasm-bytecode': 1.13.2 + '@webassemblyjs/ieee754': 1.13.2 + '@webassemblyjs/leb128': 1.13.2 + '@webassemblyjs/utf8': 1.13.2 + + '@webassemblyjs/wasm-opt@1.14.1': + dependencies: + '@webassemblyjs/ast': 1.14.1 + '@webassemblyjs/helper-buffer': 1.14.1 + '@webassemblyjs/wasm-gen': 1.14.1 + '@webassemblyjs/wasm-parser': 1.14.1 + + '@webassemblyjs/wasm-parser@1.14.1': + dependencies: + '@webassemblyjs/ast': 1.14.1 + '@webassemblyjs/helper-api-error': 1.13.2 + '@webassemblyjs/helper-wasm-bytecode': 1.13.2 + '@webassemblyjs/ieee754': 1.13.2 + '@webassemblyjs/leb128': 1.13.2 + '@webassemblyjs/utf8': 1.13.2 + + '@webassemblyjs/wast-printer@1.14.1': + dependencies: + '@webassemblyjs/ast': 1.14.1 + '@xtuc/long': 4.2.2 + + '@xmldom/xmldom@0.9.10': {} + + '@xtuc/ieee754@1.2.0': {} + + '@xtuc/long@4.2.2': {} + + abbrev@1.1.1: {} + + acorn-import-attributes@1.9.5(acorn@8.16.0): + dependencies: + acorn: 8.16.0 + + acorn-import-phases@1.0.4(acorn@8.16.0): + dependencies: + acorn: 8.16.0 + + acorn@8.16.0: {} + + agent-base@6.0.2: + dependencies: + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + agentkeepalive@4.6.0: + dependencies: + humanize-ms: 1.2.1 + + aggregate-error@3.1.0: + dependencies: + clean-stack: 2.2.0 + indent-string: 4.0.0 + + ajv-formats@2.1.1(ajv@8.20.0): + optionalDependencies: + ajv: 8.20.0 + + ajv-keywords@5.1.0(ajv@8.20.0): + dependencies: + ajv: 8.20.0 + fast-deep-equal: 3.1.3 + + ajv@8.20.0: + dependencies: + fast-deep-equal: 3.1.3 + fast-uri: 3.1.2 + json-schema-traverse: 1.0.0 + require-from-string: 2.0.2 + + ansi-escapes@4.3.2: + dependencies: + type-fest: 0.21.3 + + ansi-escapes@5.0.0: + dependencies: + type-fest: 1.4.0 + + ansi-regex@5.0.1: {} + + ansi-regex@6.2.2: {} + + ansi-styles@4.3.0: + dependencies: + color-convert: 2.0.1 + + ansi-styles@6.2.3: {} + + appdmg@0.6.6: + dependencies: + async: 1.5.2 + ds-store: 0.1.6 + execa: 1.0.0 + fs-temp: 1.2.1 + fs-xattr: 0.3.1 + image-size: 0.7.5 + is-my-json-valid: 2.20.6 + minimist: 1.2.8 + parse-color: 1.0.0 + path-exists: 4.0.0 + repeat-string: 1.6.1 + optional: true + + async@1.5.2: + optional: true + + at-least-node@1.0.0: {} + + author-regex@1.0.0: {} + + balanced-match@1.0.2: {} + + balanced-match@4.0.4: {} + + base32-encode@1.2.0: + dependencies: + to-data-view: 1.1.0 + optional: true + + base64-js@1.5.1: {} + + baseline-browser-mapping@2.10.27: {} + + better-sqlite3@12.11.1: + dependencies: + bindings: 1.5.0 + prebuild-install: 7.1.3 + + bindings@1.5.0: + dependencies: + file-uri-to-path: 1.0.0 + + bl@4.1.0: + dependencies: + buffer: 5.7.1 + inherits: 2.0.4 + readable-stream: 3.6.2 + + bluebird@3.7.2: {} + + boolean@3.2.0: + optional: true + + bplist-creator@0.0.8: + dependencies: + stream-buffers: 2.2.0 + optional: true + + brace-expansion@1.1.14: + dependencies: + balanced-match: 1.0.2 + concat-map: 0.0.1 + + brace-expansion@2.1.0: + dependencies: + balanced-match: 1.0.2 + + brace-expansion@5.0.5: + dependencies: + balanced-match: 4.0.4 + + braces@3.0.3: + dependencies: + fill-range: 7.1.1 + + browserslist@4.28.2: + dependencies: + baseline-browser-mapping: 2.10.27 + caniuse-lite: 1.0.30001792 + electron-to-chromium: 1.5.352 + node-releases: 2.0.38 + update-browserslist-db: 1.2.3(browserslist@4.28.2) + + buffer-crc32@0.2.13: {} + + buffer-from@1.1.2: {} + + buffer@5.7.1: + dependencies: + base64-js: 1.5.1 + ieee754: 1.2.1 + + cacache@16.1.3: + dependencies: + '@npmcli/fs': 2.1.2 + '@npmcli/move-file': 2.0.1 + chownr: 2.0.0 + fs-minipass: 2.1.0 + glob: 8.1.0 + infer-owner: 1.0.4 + lru-cache: 7.18.3 + minipass: 3.3.6 + minipass-collect: 1.0.2 + minipass-flush: 1.0.7 + minipass-pipeline: 1.2.4 + mkdirp: 1.0.4 + p-map: 4.0.0 + promise-inflight: 1.0.1 + rimraf: 3.0.2 + ssri: 9.0.1 + tar: 6.2.1 + unique-filename: 2.0.1 + transitivePeerDependencies: + - bluebird + + cacheable-lookup@5.0.4: {} + + cacheable-request@7.0.4: + dependencies: + clone-response: 1.0.3 + get-stream: 5.2.0 + http-cache-semantics: 4.2.0 + keyv: 4.5.4 + lowercase-keys: 2.0.0 + normalize-url: 6.1.0 + responselike: 2.0.1 + + caniuse-lite@1.0.30001792: {} + + chalk@4.1.2: + dependencies: + ansi-styles: 4.3.0 + supports-color: 7.2.0 + + chardet@0.7.0: {} + + chownr@1.1.4: {} + + chownr@2.0.0: {} + + chrome-trace-event@1.0.4: {} + + cjs-module-lexer@2.2.0: {} + + clean-stack@2.2.0: {} + + cli-cursor@3.1.0: + dependencies: + restore-cursor: 3.1.0 + + cli-cursor@4.0.0: + dependencies: + restore-cursor: 4.0.0 + + cli-spinners@2.9.2: {} + + cli-truncate@3.1.0: + dependencies: + slice-ansi: 5.0.0 + string-width: 5.1.2 + + cli-truncate@4.0.0: + dependencies: + slice-ansi: 5.0.0 + string-width: 7.2.0 + + cli-width@4.1.0: {} + + cliui@7.0.4: + dependencies: + string-width: 4.2.3 + strip-ansi: 6.0.1 + wrap-ansi: 7.0.0 + optional: true + + cliui@8.0.1: + dependencies: + string-width: 4.2.3 + strip-ansi: 6.0.1 + wrap-ansi: 7.0.0 + + clone-response@1.0.3: + dependencies: + mimic-response: 1.0.1 + + clone@1.0.4: {} + + color-convert@0.5.3: + optional: true + + color-convert@2.0.1: + dependencies: + color-name: 1.1.4 + + color-name@1.1.4: {} + + colorette@2.0.20: {} + + commander@11.1.0: {} + + commander@13.1.0: {} + + commander@2.20.3: {} + + commander@5.1.0: {} + + commander@9.5.0: {} + + compare-version@0.1.2: {} + + concat-map@0.0.1: {} + + cross-dirname@0.1.0: {} + + cross-spawn@6.0.6: + dependencies: + nice-try: 1.0.5 + path-key: 2.0.1 + semver: 5.7.2 + shebang-command: 1.2.0 + which: 1.3.1 + + cross-spawn@7.0.6: + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.2 + + cross-zip@4.0.1: {} + + d@1.0.2: + dependencies: + es5-ext: 0.10.64 + type: 2.7.3 + + debug@2.6.9: + dependencies: + ms: 2.0.0 + + debug@4.4.3: + dependencies: + ms: 2.1.3 + + decompress-response@6.0.0: + dependencies: + mimic-response: 3.1.0 + + deep-extend@0.6.0: {} + + default-shell@2.2.0: {} + + defaults@1.0.4: + dependencies: + clone: 1.0.4 + + defer-to-connect@2.0.1: {} + + define-data-property@1.1.4: + dependencies: + es-define-property: 1.0.1 + es-errors: 1.3.0 + gopd: 1.2.0 + optional: true + + define-properties@1.2.1: + dependencies: + define-data-property: 1.1.4 + has-property-descriptors: 1.0.2 + object-keys: 1.1.1 + optional: true + + detect-libc@2.1.2: {} + + detect-node@2.1.0: + optional: true + + dir-compare@4.2.0: + dependencies: + minimatch: 3.1.5 + p-limit: 3.1.0 + + ds-store@0.1.6: + dependencies: + bplist-creator: 0.0.8 + macos-alias: 0.2.12 + tn1150: 0.1.0 + optional: true + + eastasianwidth@0.2.0: {} + + electron-context-menu@4.1.2: + dependencies: + cli-truncate: 4.0.0 + electron-dl: 4.0.0 + electron-is-dev: 3.0.1 + + electron-dl@4.0.0: + dependencies: + ext-name: 5.0.0 + pupa: 3.3.0 + unused-filename: 4.0.1 + + electron-installer-common@0.10.4: + dependencies: + '@electron/asar': 3.4.1 + '@malept/cross-spawn-promise': 1.1.1 + debug: 4.4.3 + fs-extra: 9.1.0 + glob: 7.2.3 + lodash: 4.18.1 + parse-author: 2.0.0 + semver: 7.7.4 + tmp-promise: 3.0.3 + optionalDependencies: + '@types/fs-extra': 9.0.13 + transitivePeerDependencies: + - supports-color + optional: true + + electron-installer-debian@3.2.0: + dependencies: + '@malept/cross-spawn-promise': 1.1.1 + debug: 4.4.3 + electron-installer-common: 0.10.4 + fs-extra: 9.1.0 + get-folder-size: 2.0.1 + lodash: 4.18.1 + word-wrap: 1.2.5 + yargs: 16.2.0 + transitivePeerDependencies: + - supports-color + optional: true + + electron-installer-dmg@5.0.1: + dependencies: + '@types/appdmg': 0.5.5 + debug: 4.4.3 + minimist: 1.2.8 + optionalDependencies: + appdmg: 0.6.6 + transitivePeerDependencies: + - supports-color + optional: true + + electron-installer-redhat@3.4.0: + dependencies: + '@malept/cross-spawn-promise': 1.1.1 + debug: 4.4.3 + electron-installer-common: 0.10.4 + fs-extra: 9.1.0 + lodash: 4.18.1 + word-wrap: 1.2.5 + yargs: 16.2.0 + transitivePeerDependencies: + - supports-color + optional: true + + electron-is-dev@3.0.1: {} + + electron-squirrel-startup@1.0.1: + dependencies: + debug: 2.6.9 + transitivePeerDependencies: + - supports-color + + electron-to-chromium@1.5.352: {} + + electron-winstaller@5.4.0: + dependencies: + '@electron/asar': 3.4.1 + debug: 4.4.3 + fs-extra: 7.0.1 + lodash: 4.18.1 + temp: 0.9.4 + optionalDependencies: + '@electron/windows-sign': 1.2.2 + transitivePeerDependencies: + - supports-color + optional: true + + electron@42.0.1: + dependencies: + '@electron/get': 5.0.0 + '@types/node': 24.12.2 + extract-zip: 2.0.1 + transitivePeerDependencies: + - supports-color + + emoji-regex@10.6.0: {} + + emoji-regex@8.0.0: {} + + emoji-regex@9.2.2: {} + + encode-utf8@1.0.3: + optional: true + + encoding@0.1.13: + dependencies: + iconv-lite: 0.6.3 + + end-of-stream@1.4.5: + dependencies: + once: 1.4.0 + + enhanced-resolve@5.21.0: + dependencies: + graceful-fs: 4.2.11 + tapable: 2.3.3 + + env-paths@2.2.1: {} + + env-paths@3.0.0: {} + + err-code@2.0.3: {} + + error-ex@1.3.4: + dependencies: + is-arrayish: 0.2.1 + + es-define-property@1.0.1: + optional: true + + es-errors@1.3.0: {} + + es-module-lexer@2.1.0: {} + + es5-ext@0.10.64: + dependencies: + es6-iterator: 2.0.3 + es6-symbol: 3.1.4 + esniff: 2.0.1 + next-tick: 1.1.0 + + es6-error@4.1.1: + optional: true + + es6-iterator@2.0.3: + dependencies: + d: 1.0.2 + es5-ext: 0.10.64 + es6-symbol: 3.1.4 + + es6-symbol@3.1.4: + dependencies: + d: 1.0.2 + ext: 1.7.0 + + es6-weak-map@2.0.3: + dependencies: + d: 1.0.2 + es5-ext: 0.10.64 + es6-iterator: 2.0.3 + es6-symbol: 3.1.4 + + escalade@3.2.0: {} + + escape-goat@4.0.0: {} + + escape-string-regexp@1.0.5: {} + + escape-string-regexp@4.0.0: + optional: true + + escape-string-regexp@5.0.0: {} + + eslint-scope@5.1.1: + dependencies: + esrecurse: 4.3.0 + estraverse: 4.3.0 + + esniff@2.0.1: + dependencies: + d: 1.0.2 + es5-ext: 0.10.64 + event-emitter: 0.3.5 + type: 2.7.3 + + esrecurse@4.3.0: + dependencies: + estraverse: 5.3.0 + + estraverse@4.3.0: {} + + estraverse@5.3.0: {} + + event-emitter@0.3.5: + dependencies: + d: 1.0.2 + es5-ext: 0.10.64 + + eventemitter3@5.0.4: {} + + events@3.3.0: {} + + execa@1.0.0: + dependencies: + cross-spawn: 6.0.6 + get-stream: 4.1.0 + is-stream: 1.1.0 + npm-run-path: 2.0.2 + p-finally: 1.0.0 + signal-exit: 3.0.7 + strip-eof: 1.0.0 + + execa@5.1.1: + dependencies: + cross-spawn: 7.0.6 + get-stream: 6.0.1 + human-signals: 2.1.0 + is-stream: 2.0.1 + merge-stream: 2.0.0 + npm-run-path: 4.0.1 + onetime: 5.1.2 + signal-exit: 3.0.7 + strip-final-newline: 2.0.0 + + expand-template@2.0.3: {} + + exponential-backoff@3.1.3: {} + + ext-list@2.2.2: + dependencies: + mime-db: 1.54.0 + + ext-name@5.0.0: + dependencies: + ext-list: 2.2.2 + sort-keys-length: 1.0.1 + + ext@1.7.0: + dependencies: + type: 2.7.3 + + external-editor@3.1.0: + dependencies: + chardet: 0.7.0 + iconv-lite: 0.4.24 + tmp: 0.0.33 + + extract-zip@2.0.1: + dependencies: + debug: 4.4.3 + get-stream: 5.2.0 + yauzl: 2.10.0 + optionalDependencies: + '@types/yauzl': 2.10.3 + transitivePeerDependencies: + - supports-color + + fast-deep-equal@3.1.3: {} + + fast-glob@3.3.3: + dependencies: + '@nodelib/fs.stat': 2.0.5 + '@nodelib/fs.walk': 1.2.8 + glob-parent: 5.1.2 + merge2: 1.4.1 + micromatch: 4.0.8 + + fast-uri@3.1.2: {} + + fast-xml-builder@1.1.9: + dependencies: + path-expression-matcher: 1.5.0 + + fast-xml-parser@5.7.3: + dependencies: + '@nodable/entities': 2.1.0 + fast-xml-builder: 1.1.9 + path-expression-matcher: 1.5.0 + strnum: 2.3.0 + + fastq@1.20.1: + dependencies: + reusify: 1.1.0 + + fd-slicer@1.1.0: + dependencies: + pend: 1.2.0 + + file-uri-to-path@1.0.0: {} + + filename-reserved-regex@2.0.0: {} + + filenamify@4.3.0: + dependencies: + filename-reserved-regex: 2.0.0 + strip-outer: 1.0.1 + trim-repeated: 1.0.0 + + fill-range@7.1.1: + dependencies: + to-regex-range: 5.0.1 + + find-up@2.1.0: + dependencies: + locate-path: 2.0.0 + + find-up@5.0.0: + dependencies: + locate-path: 6.0.0 + path-exists: 4.0.0 + + flora-colossus@2.0.0: + dependencies: + debug: 4.4.3 + fs-extra: 10.1.0 + transitivePeerDependencies: + - supports-color + + fmix@0.1.0: + dependencies: + imul: 1.0.1 + optional: true + + forwarded-parse@2.1.2: {} + + fs-constants@1.0.0: {} + + fs-extra@10.1.0: + dependencies: + graceful-fs: 4.2.11 + jsonfile: 6.2.1 + universalify: 2.0.1 + + fs-extra@11.3.5: + dependencies: + graceful-fs: 4.2.11 + jsonfile: 6.2.1 + universalify: 2.0.1 + + fs-extra@7.0.1: + dependencies: + graceful-fs: 4.2.11 + jsonfile: 4.0.0 + universalify: 0.1.2 + optional: true + + fs-extra@8.1.0: + dependencies: + graceful-fs: 4.2.11 + jsonfile: 4.0.0 + universalify: 0.1.2 + + fs-extra@9.1.0: + dependencies: + at-least-node: 1.0.0 + graceful-fs: 4.2.11 + jsonfile: 6.2.1 + universalify: 2.0.1 + + fs-minipass@2.1.0: + dependencies: + minipass: 3.3.6 + + fs-temp@1.2.1: + dependencies: + random-path: 0.1.2 + optional: true + + fs-xattr@0.3.1: + optional: true + + fs.realpath@1.0.0: {} + + function-bind@1.1.2: {} + + galactus@1.0.0: + dependencies: + debug: 4.4.3 + flora-colossus: 2.0.0 + fs-extra: 10.1.0 + transitivePeerDependencies: + - supports-color + + gar@1.0.4: + optional: true + + generate-function@2.3.1: + dependencies: + is-property: 1.0.2 + optional: true + + generate-object-property@1.2.0: + dependencies: + is-property: 1.0.2 + optional: true + + get-caller-file@2.0.5: {} + + get-east-asian-width@1.5.0: {} + + get-folder-size@2.0.1: + dependencies: + gar: 1.0.4 + tiny-each-async: 2.0.3 + optional: true + + get-package-info@1.0.0: + dependencies: + bluebird: 3.7.2 + debug: 2.6.9 + lodash.get: 4.4.2 + read-pkg-up: 2.0.0 + transitivePeerDependencies: + - supports-color + + get-stream@4.1.0: + dependencies: + pump: 3.0.4 + + get-stream@5.2.0: + dependencies: + pump: 3.0.4 + + get-stream@6.0.1: {} + + github-from-package@0.0.0: {} + + glob-parent@5.1.2: + dependencies: + is-glob: 4.0.3 + + glob-to-regexp@0.4.1: {} + + glob@13.0.6: + dependencies: + minimatch: 10.2.5 + minipass: 7.1.3 + path-scurry: 2.0.2 + + glob@7.2.3: + dependencies: + fs.realpath: 1.0.0 + inflight: 1.0.6 + inherits: 2.0.4 + minimatch: 3.1.5 + once: 1.4.0 + path-is-absolute: 1.0.1 + + glob@8.1.0: + dependencies: + fs.realpath: 1.0.0 + inflight: 1.0.6 + inherits: 2.0.4 + minimatch: 5.1.9 + once: 1.4.0 + + global-agent@3.0.0: + dependencies: + boolean: 3.2.0 + es6-error: 4.1.1 + matcher: 3.0.0 + roarr: 2.15.4 + semver: 7.7.4 + serialize-error: 7.0.1 + optional: true + + global-dirs@3.0.1: + dependencies: + ini: 2.0.0 + + globalthis@1.0.4: + dependencies: + define-properties: 1.2.1 + gopd: 1.2.0 + optional: true + + gopd@1.2.0: + optional: true + + got@11.8.6: + dependencies: + '@sindresorhus/is': 4.6.0 + '@szmarczak/http-timer': 4.0.6 + '@types/cacheable-request': 6.0.3 + '@types/responselike': 1.0.3 + cacheable-lookup: 5.0.4 + cacheable-request: 7.0.4 + decompress-response: 6.0.0 + http2-wrapper: 1.0.3 + lowercase-keys: 2.0.0 + p-cancelable: 2.1.1 + responselike: 2.0.1 + + graceful-fs@4.2.11: {} + + has-flag@4.0.0: {} + + has-property-descriptors@1.0.2: + dependencies: + es-define-property: 1.0.1 + optional: true + + hasown@2.0.3: + dependencies: + function-bind: 1.1.2 + + hosted-git-info@2.8.9: {} + + http-cache-semantics@4.2.0: {} + + http-proxy-agent@5.0.0: + dependencies: + '@tootallnate/once': 2.0.1 + agent-base: 6.0.2 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + http2-wrapper@1.0.3: + dependencies: + quick-lru: 5.1.1 + resolve-alpn: 1.2.1 + + https-proxy-agent@5.0.1: + dependencies: + agent-base: 6.0.2 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + human-signals@2.1.0: {} + + humanize-ms@1.2.1: + dependencies: + ms: 2.1.3 + + iconv-lite@0.4.24: + dependencies: + safer-buffer: 2.1.2 + + iconv-lite@0.6.3: + dependencies: + safer-buffer: 2.1.2 + + ieee754@1.2.1: {} + + image-size@0.7.5: + optional: true + + immer@10.2.0: {} + + import-in-the-middle@2.0.6: + dependencies: + acorn: 8.16.0 + acorn-import-attributes: 1.9.5(acorn@8.16.0) + cjs-module-lexer: 2.2.0 + module-details-from-path: 1.0.4 + + import-in-the-middle@3.0.1: + dependencies: + acorn: 8.16.0 + acorn-import-attributes: 1.9.5(acorn@8.16.0) + cjs-module-lexer: 2.2.0 + module-details-from-path: 1.0.4 + + imul@1.0.1: + optional: true + + imurmurhash@0.1.4: {} + + indent-string@4.0.0: {} + + infer-owner@1.0.4: {} + + inflight@1.0.6: + dependencies: + once: 1.4.0 + wrappy: 1.0.2 + + inherits@2.0.4: {} + + ini@1.3.8: {} + + ini@2.0.0: {} + + interpret@3.1.1: {} + + ip-address@10.2.0: {} + + is-arrayish@0.2.1: {} + + is-core-module@2.16.2: + dependencies: + hasown: 2.0.3 + + is-extglob@2.1.1: {} + + is-fullwidth-code-point@3.0.0: {} + + is-fullwidth-code-point@4.0.0: {} + + is-glob@4.0.3: + dependencies: + is-extglob: 2.1.1 + + is-interactive@1.0.0: {} + + is-lambda@1.0.1: {} + + is-my-ip-valid@1.0.1: + optional: true + + is-my-json-valid@2.20.6: + dependencies: + generate-function: 2.3.1 + generate-object-property: 1.2.0 + is-my-ip-valid: 1.0.1 + jsonpointer: 5.0.1 + xtend: 4.0.2 + optional: true + + is-number@7.0.0: {} + + is-plain-obj@1.1.0: {} + + is-promise@2.2.2: {} + + is-property@1.0.2: + optional: true + + is-stream@1.1.0: {} + + is-stream@2.0.1: {} + + is-unicode-supported@0.1.0: {} + + isbinaryfile@4.0.10: {} + + isexe@2.0.0: {} + + jest-worker@27.5.1: + dependencies: + '@types/node': 24.12.2 + merge-stream: 2.0.0 + supports-color: 8.1.1 + + jiti@2.7.0: {} + + json-buffer@3.0.1: {} + + json-schema-traverse@1.0.0: {} + + json-stringify-safe@5.0.1: + optional: true + + jsonfile@4.0.0: + optionalDependencies: + graceful-fs: 4.2.11 + + jsonfile@6.2.1: + dependencies: + universalify: 2.0.1 + optionalDependencies: + graceful-fs: 4.2.11 + + jsonpointer@5.0.1: + optional: true + + junk@3.1.0: {} + + keyv@4.5.4: + dependencies: + json-buffer: 3.0.1 + + listr2@7.0.2: + dependencies: + cli-truncate: 3.1.0 + colorette: 2.0.20 + eventemitter3: 5.0.4 + log-update: 5.0.1 + rfdc: 1.4.1 + wrap-ansi: 8.1.0 + + load-json-file@2.0.0: + dependencies: + graceful-fs: 4.2.11 + parse-json: 2.2.0 + pify: 2.3.0 + strip-bom: 3.0.0 + + loader-runner@4.3.2: {} + + locate-path@2.0.0: + dependencies: + p-locate: 2.0.0 + path-exists: 3.0.0 + + locate-path@6.0.0: + dependencies: + p-locate: 5.0.0 + + lodash.get@4.4.2: {} + + lodash@4.18.1: {} + + log-symbols@4.1.0: + dependencies: + chalk: 4.1.2 + is-unicode-supported: 0.1.0 + + log-update@5.0.1: + dependencies: + ansi-escapes: 5.0.0 + cli-cursor: 4.0.0 + slice-ansi: 5.0.0 + strip-ansi: 7.2.0 + wrap-ansi: 8.1.0 + + lowercase-keys@2.0.0: {} + + lru-cache@11.3.6: {} + + lru-cache@7.18.3: {} + + lru-queue@0.1.0: + dependencies: + es5-ext: 0.10.64 + + macos-alias@0.2.12: + dependencies: + nan: 2.26.2 + optional: true + + make-fetch-happen@10.2.1: + dependencies: + agentkeepalive: 4.6.0 + cacache: 16.1.3 + http-cache-semantics: 4.2.0 + http-proxy-agent: 5.0.0 + https-proxy-agent: 5.0.1 + is-lambda: 1.0.1 + lru-cache: 7.18.3 + minipass: 3.3.6 + minipass-collect: 1.0.2 + minipass-fetch: 2.1.2 + minipass-flush: 1.0.7 + minipass-pipeline: 1.2.4 + negotiator: 0.6.4 + promise-retry: 2.0.1 + socks-proxy-agent: 7.0.0 + ssri: 9.0.1 + transitivePeerDependencies: + - bluebird + - supports-color + + map-age-cleaner@0.1.3: + dependencies: + p-defer: 1.0.0 + + matcher@3.0.0: + dependencies: + escape-string-regexp: 4.0.0 + optional: true + + mem@4.3.0: + dependencies: + map-age-cleaner: 0.1.3 + mimic-fn: 2.1.0 + p-is-promise: 2.1.0 + + memoizee@0.4.17: + dependencies: + d: 1.0.2 + es5-ext: 0.10.64 + es6-weak-map: 2.0.3 + event-emitter: 0.3.5 + is-promise: 2.2.2 + lru-queue: 0.1.0 + next-tick: 1.1.0 + timers-ext: 0.1.8 + + merge-stream@2.0.0: {} + + merge2@1.4.1: {} + + micromatch@4.0.8: + dependencies: + braces: 3.0.3 + picomatch: 2.3.2 + + mime-db@1.52.0: {} + + mime-db@1.54.0: {} + + mime-types@2.1.35: + dependencies: + mime-db: 1.52.0 + + mimic-fn@2.1.0: {} + + mimic-response@1.0.1: {} + + mimic-response@3.1.0: {} + + minimatch@10.2.5: + dependencies: + brace-expansion: 5.0.5 + + minimatch@3.1.5: + dependencies: + brace-expansion: 1.1.14 + + minimatch@5.1.9: + dependencies: + brace-expansion: 2.1.0 + + minimatch@9.0.9: + dependencies: + brace-expansion: 2.1.0 + + minimist@1.2.8: {} + + minipass-collect@1.0.2: + dependencies: + minipass: 3.3.6 + + minipass-fetch@2.1.2: + dependencies: + minipass: 3.3.6 + minipass-sized: 1.0.3 + minizlib: 2.1.2 + optionalDependencies: + encoding: 0.1.13 + + minipass-flush@1.0.7: + dependencies: + minipass: 3.3.6 + + minipass-pipeline@1.2.4: + dependencies: + minipass: 3.3.6 + + minipass-sized@1.0.3: + dependencies: + minipass: 3.3.6 + + minipass@3.3.6: + dependencies: + yallist: 4.0.0 + + minipass@5.0.0: {} + + minipass@7.1.3: {} + + minizlib@2.1.2: + dependencies: + minipass: 3.3.6 + yallist: 4.0.0 + + mkdirp-classic@0.5.3: {} + + mkdirp@0.5.6: + dependencies: + minimist: 1.2.8 + optional: true + + mkdirp@1.0.4: {} + + module-details-from-path@1.0.4: {} + + ms@2.0.0: {} + + ms@2.1.3: {} + + murmur-32@0.2.0: + dependencies: + encode-utf8: 1.0.3 + fmix: 0.1.0 + imul: 1.0.1 + optional: true + + mute-stream@1.0.0: {} + + nan@2.26.2: + optional: true + + napi-build-utils@2.0.0: {} + + negotiator@0.6.4: {} + + neo-async@2.6.2: {} + + next-tick@1.1.0: {} + + nice-try@1.0.5: {} + + node-abi@3.92.0: + dependencies: + semver: 7.7.4 + + node-addon-api@7.1.1: {} + + node-api-version@0.2.1: + dependencies: + semver: 7.7.4 + + node-fetch@2.7.0(encoding@0.1.13): + dependencies: + whatwg-url: 5.0.0 + optionalDependencies: + encoding: 0.1.13 + + node-pty@1.1.0: + dependencies: + node-addon-api: 7.1.1 + + node-releases@2.0.38: {} + + nopt@6.0.0: + dependencies: + abbrev: 1.1.1 + + normalize-package-data@2.5.0: + dependencies: + hosted-git-info: 2.8.9 + resolve: 1.22.12 + semver: 5.7.2 + validate-npm-package-license: 3.0.4 + + normalize-url@6.1.0: {} + + npm-run-path@2.0.2: + dependencies: + path-key: 2.0.1 + + npm-run-path@4.0.1: + dependencies: + path-key: 3.1.1 + + object-keys@1.1.1: + optional: true + + once@1.4.0: + dependencies: + wrappy: 1.0.2 + + onetime@5.1.2: + dependencies: + mimic-fn: 2.1.0 + + ora@5.4.1: + dependencies: + bl: 4.1.0 + chalk: 4.1.2 + cli-cursor: 3.1.0 + cli-spinners: 2.9.2 + is-interactive: 1.0.0 + is-unicode-supported: 0.1.0 + log-symbols: 4.1.0 + strip-ansi: 6.0.1 + wcwidth: 1.0.1 + + os-tmpdir@1.0.2: {} + + p-cancelable@2.1.1: {} + + p-defer@1.0.0: {} + + p-finally@1.0.0: {} + + p-is-promise@2.1.0: {} + + p-limit@1.3.0: + dependencies: + p-try: 1.0.0 + + p-limit@3.1.0: + dependencies: + yocto-queue: 0.1.0 + + p-locate@2.0.0: + dependencies: + p-limit: 1.3.0 + + p-locate@5.0.0: + dependencies: + p-limit: 3.1.0 + + p-map@4.0.0: + dependencies: + aggregate-error: 3.1.0 + + p-try@1.0.0: {} + + parse-author@2.0.0: + dependencies: + author-regex: 1.0.0 + + parse-color@1.0.0: + dependencies: + color-convert: 0.5.3 + optional: true + + parse-json@2.2.0: + dependencies: + error-ex: 1.3.4 + + path-exists@3.0.0: {} + + path-exists@4.0.0: {} + + path-exists@5.0.0: {} + + path-expression-matcher@1.5.0: {} + + path-is-absolute@1.0.1: {} + + path-key@2.0.1: {} + + path-key@3.1.1: {} + + path-parse@1.0.7: {} + + path-scurry@2.0.2: + dependencies: + lru-cache: 11.3.6 + minipass: 7.1.3 + + path-type@2.0.0: + dependencies: + pify: 2.3.0 + + pe-library@1.0.1: {} + + pend@1.2.0: {} + + pg-int8@1.0.1: {} + + pg-protocol@1.13.0: {} + + pg-types@2.2.0: + dependencies: + pg-int8: 1.0.1 + postgres-array: 2.0.0 + postgres-bytea: 1.0.1 + postgres-date: 1.0.7 + postgres-interval: 1.2.0 + + picocolors@1.1.1: {} + + picomatch@2.3.2: {} + + pify@2.3.0: {} + + plist@3.1.1: + dependencies: + '@xmldom/xmldom': 0.9.10 + base64-js: 1.5.1 + xmlbuilder: 15.1.1 + + postgres-array@2.0.0: {} + + postgres-bytea@1.0.1: {} + + postgres-date@1.0.7: {} + + postgres-interval@1.2.0: + dependencies: + xtend: 4.0.2 + + postject@1.0.0-alpha.6: + dependencies: + commander: 9.5.0 + + prebuild-install@7.1.3: + dependencies: + detect-libc: 2.1.2 + expand-template: 2.0.3 + github-from-package: 0.0.0 + minimist: 1.2.8 + mkdirp-classic: 0.5.3 + napi-build-utils: 2.0.0 + node-abi: 3.92.0 + pump: 3.0.4 + rc: 1.2.8 + simple-get: 4.0.1 + tar-fs: 2.1.4 + tunnel-agent: 0.6.0 + + prettier@3.8.3: {} + + proc-log@2.0.1: {} + + progress@2.0.3: {} + + promise-inflight@1.0.1: {} + + promise-retry@2.0.1: + dependencies: + err-code: 2.0.3 + retry: 0.12.0 + + pump@3.0.4: + dependencies: + end-of-stream: 1.4.5 + once: 1.4.0 + + pupa@3.3.0: + dependencies: + escape-goat: 4.0.0 + + queue-microtask@1.2.3: {} + + quick-lru@5.1.1: {} + + random-path@0.1.2: + dependencies: + base32-encode: 1.2.0 + murmur-32: 0.2.0 + optional: true + + rc@1.2.8: + dependencies: + deep-extend: 0.6.0 + ini: 1.3.8 + minimist: 1.2.8 + strip-json-comments: 2.0.1 + + read-binary-file-arch@1.0.6: + dependencies: + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + read-pkg-up@2.0.0: + dependencies: + find-up: 2.1.0 + read-pkg: 2.0.0 + + read-pkg@2.0.0: + dependencies: + load-json-file: 2.0.0 + normalize-package-data: 2.5.0 + path-type: 2.0.0 + + readable-stream@3.6.2: + dependencies: + inherits: 2.0.4 + string_decoder: 1.3.0 + util-deprecate: 1.0.2 + + rechoir@0.8.0: + dependencies: + resolve: 1.22.12 + + repeat-string@1.6.1: + optional: true + + require-directory@2.1.1: {} + + require-from-string@2.0.2: {} + + require-in-the-middle@8.0.1: + dependencies: + debug: 4.4.3 + module-details-from-path: 1.0.4 + transitivePeerDependencies: + - supports-color + + resedit@2.0.3: + dependencies: + pe-library: 1.0.1 + + resolve-alpn@1.2.1: {} + + resolve@1.22.12: + dependencies: + es-errors: 1.3.0 + is-core-module: 2.16.2 + path-parse: 1.0.7 + supports-preserve-symlinks-flag: 1.0.0 + + responselike@2.0.1: + dependencies: + lowercase-keys: 2.0.0 + + restore-cursor@3.1.0: + dependencies: + onetime: 5.1.2 + signal-exit: 3.0.7 + + restore-cursor@4.0.0: + dependencies: + onetime: 5.1.2 + signal-exit: 3.0.7 + + retry@0.12.0: {} + + reusify@1.1.0: {} + + rfdc@1.4.1: {} + + rimraf@2.6.3: + dependencies: + glob: 7.2.3 + optional: true + + rimraf@3.0.2: + dependencies: + glob: 7.2.3 + + roarr@2.15.4: + dependencies: + boolean: 3.2.0 + detect-node: 2.1.0 + globalthis: 1.0.4 + json-stringify-safe: 5.0.1 + semver-compare: 1.0.0 + sprintf-js: 1.1.3 + optional: true + + run-parallel@1.2.0: + dependencies: + queue-microtask: 1.2.3 + + safe-buffer@5.2.1: {} + + safer-buffer@2.1.2: {} + + schema-utils@4.3.3: + dependencies: + '@types/json-schema': 7.0.15 + ajv: 8.20.0 + ajv-formats: 2.1.1(ajv@8.20.0) + ajv-keywords: 5.1.0(ajv@8.20.0) + + semver-compare@1.0.0: + optional: true + + semver@5.7.2: {} + + semver@6.3.1: {} + + semver@7.7.4: {} + + serialize-error@7.0.1: + dependencies: + type-fest: 0.13.1 + optional: true + + shebang-command@1.2.0: + dependencies: + shebang-regex: 1.0.0 + + shebang-command@2.0.0: + dependencies: + shebang-regex: 3.0.0 + + shebang-regex@1.0.0: {} + + shebang-regex@3.0.0: {} + + shell-env@4.0.3: + dependencies: + default-shell: 2.2.0 + execa: 5.1.1 + strip-ansi: 7.2.0 + + shlex@3.0.0: {} + + signal-exit@3.0.7: {} + + signal-exit@4.1.0: {} + + simple-concat@1.0.1: {} + + simple-get@4.0.1: + dependencies: + decompress-response: 6.0.0 + once: 1.4.0 + simple-concat: 1.0.1 + + slice-ansi@5.0.0: + dependencies: + ansi-styles: 6.2.3 + is-fullwidth-code-point: 4.0.0 + + smart-buffer@4.2.0: {} + + smol-toml@1.6.1: {} + + socks-proxy-agent@7.0.0: + dependencies: + agent-base: 6.0.2 + debug: 4.4.3 + socks: 2.8.8 + transitivePeerDependencies: + - supports-color + + socks@2.8.8: + dependencies: + ip-address: 10.2.0 + smart-buffer: 4.2.0 + + sort-keys-length@1.0.1: + dependencies: + sort-keys: 1.1.2 + + sort-keys@1.1.2: + dependencies: + is-plain-obj: 1.1.0 + + source-map-support@0.5.21: + dependencies: + buffer-from: 1.1.2 + source-map: 0.6.1 + + source-map@0.6.1: {} + + spdx-correct@3.2.0: + dependencies: + spdx-expression-parse: 3.0.1 + spdx-license-ids: 3.0.23 + + spdx-exceptions@2.5.0: {} + + spdx-expression-parse@3.0.1: + dependencies: + spdx-exceptions: 2.5.0 + spdx-license-ids: 3.0.23 + + spdx-license-ids@3.0.23: {} + + sprintf-js@1.1.3: + optional: true + + ssri@9.0.1: + dependencies: + minipass: 3.3.6 + + stream-buffers@2.2.0: + optional: true + + string-width@4.2.3: + dependencies: + emoji-regex: 8.0.0 + is-fullwidth-code-point: 3.0.0 + strip-ansi: 6.0.1 + + string-width@5.1.2: + dependencies: + eastasianwidth: 0.2.0 + emoji-regex: 9.2.2 + strip-ansi: 7.2.0 + + string-width@7.2.0: + dependencies: + emoji-regex: 10.6.0 + get-east-asian-width: 1.5.0 + strip-ansi: 7.2.0 + + string_decoder@1.3.0: + dependencies: + safe-buffer: 5.2.1 + + strip-ansi@6.0.1: + dependencies: + ansi-regex: 5.0.1 + + strip-ansi@7.2.0: + dependencies: + ansi-regex: 6.2.2 + + strip-bom@3.0.0: {} + + strip-eof@1.0.0: {} + + strip-final-newline@2.0.0: {} + + strip-json-comments@2.0.1: {} + + strip-outer@1.0.1: + dependencies: + escape-string-regexp: 1.0.5 + + strnum@2.3.0: {} + + sumchecker@3.0.1: + dependencies: + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + supports-color@7.2.0: + dependencies: + has-flag: 4.0.0 + + supports-color@8.1.1: + dependencies: + has-flag: 4.0.0 + + supports-preserve-symlinks-flag@1.0.0: {} + + tapable@2.3.3: {} + + tar-fs@2.1.4: + dependencies: + chownr: 1.1.4 + mkdirp-classic: 0.5.3 + pump: 3.0.4 + tar-stream: 2.2.0 + + tar-stream@2.2.0: + dependencies: + bl: 4.1.0 + end-of-stream: 1.4.5 + fs-constants: 1.0.0 + inherits: 2.0.4 + readable-stream: 3.6.2 + + tar@6.2.1: + dependencies: + chownr: 2.0.0 + fs-minipass: 2.1.0 + minipass: 5.0.0 + minizlib: 2.1.2 + mkdirp: 1.0.4 + yallist: 4.0.0 + + temp@0.9.4: + dependencies: + mkdirp: 0.5.6 + rimraf: 2.6.3 + optional: true + + terser-webpack-plugin@5.5.0(webpack@5.106.2): + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + jest-worker: 27.5.1 + schema-utils: 4.3.3 + terser: 5.47.1 + webpack: 5.106.2 + + terser@5.47.1: + dependencies: + '@jridgewell/source-map': 0.3.11 + acorn: 8.16.0 + commander: 2.20.3 + source-map-support: 0.5.21 + + timers-ext@0.1.8: + dependencies: + es5-ext: 0.10.64 + next-tick: 1.1.0 + + tiny-each-async@2.0.3: + optional: true + + tmp-promise@3.0.3: + dependencies: + tmp: 0.2.5 + optional: true + + tmp@0.0.33: + dependencies: + os-tmpdir: 1.0.2 + + tmp@0.2.5: + optional: true + + tn1150@0.1.0: + dependencies: + unorm: 1.6.0 + optional: true + + to-data-view@1.1.0: + optional: true + + to-regex-range@5.0.1: + dependencies: + is-number: 7.0.0 + + tr46@0.0.3: {} + + trim-repeated@1.0.0: + dependencies: + escape-string-regexp: 1.0.5 + + tslib@2.8.1: {} + + tunnel-agent@0.6.0: + dependencies: + safe-buffer: 5.2.1 + + type-fest@0.13.1: + optional: true + + type-fest@0.21.3: {} + + type-fest@1.4.0: {} + + type@2.7.3: {} + + typescript@5.4.5: {} + + undici-types@6.21.0: {} + + undici-types@7.16.0: {} + + undici@7.25.0: + optional: true + + unique-filename@2.0.1: + dependencies: + unique-slug: 3.0.0 + + unique-slug@3.0.0: + dependencies: + imurmurhash: 0.1.4 + + universalify@0.1.2: {} + + universalify@2.0.1: {} + + unorm@1.6.0: + optional: true + + unused-filename@4.0.1: + dependencies: + escape-string-regexp: 5.0.0 + path-exists: 5.0.0 + + update-browserslist-db@1.2.3(browserslist@4.28.2): + dependencies: + browserslist: 4.28.2 + escalade: 3.2.0 + picocolors: 1.1.1 + + username@5.1.0: + dependencies: + execa: 1.0.0 + mem: 4.3.0 + + util-deprecate@1.0.2: {} + + validate-npm-package-license@3.0.4: + dependencies: + spdx-correct: 3.2.0 + spdx-expression-parse: 3.0.1 + + watchpack@2.5.1: + dependencies: + glob-to-regexp: 0.4.1 + graceful-fs: 4.2.11 + + wcwidth@1.0.1: + dependencies: + defaults: 1.0.4 + + webidl-conversions@3.0.1: {} + + webpack-sources@3.4.1: {} + + webpack@5.106.2: + dependencies: + '@types/eslint-scope': 3.7.7 + '@types/estree': 1.0.9 + '@types/json-schema': 7.0.15 + '@webassemblyjs/ast': 1.14.1 + '@webassemblyjs/wasm-edit': 1.14.1 + '@webassemblyjs/wasm-parser': 1.14.1 + acorn: 8.16.0 + acorn-import-phases: 1.0.4(acorn@8.16.0) + browserslist: 4.28.2 + chrome-trace-event: 1.0.4 + enhanced-resolve: 5.21.0 + es-module-lexer: 2.1.0 + eslint-scope: 5.1.1 + events: 3.3.0 + glob-to-regexp: 0.4.1 + graceful-fs: 4.2.11 + loader-runner: 4.3.2 + mime-db: 1.54.0 + neo-async: 2.6.2 + schema-utils: 4.3.3 + tapable: 2.3.3 + terser-webpack-plugin: 5.5.0(webpack@5.106.2) + watchpack: 2.5.1 + webpack-sources: 3.4.1 + transitivePeerDependencies: + - '@swc/core' + - esbuild + - uglify-js + + whatwg-url@5.0.0: + dependencies: + tr46: 0.0.3 + webidl-conversions: 3.0.1 + + which@1.3.1: + dependencies: + isexe: 2.0.0 + + which@2.0.2: + dependencies: + isexe: 2.0.0 + + word-wrap@1.2.5: + optional: true + + wrap-ansi@6.2.0: + dependencies: + ansi-styles: 4.3.0 + string-width: 4.2.3 + strip-ansi: 6.0.1 + + wrap-ansi@7.0.0: + dependencies: + ansi-styles: 4.3.0 + string-width: 4.2.3 + strip-ansi: 6.0.1 + + wrap-ansi@8.1.0: + dependencies: + ansi-styles: 6.2.3 + string-width: 5.1.2 + strip-ansi: 7.2.0 + + wrappy@1.0.2: {} + + xmlbuilder@15.1.1: {} + + xtend@4.0.2: {} + + y18n@5.0.8: {} + + yallist@4.0.0: {} + + yargs-parser@20.2.9: + optional: true + + yargs-parser@21.1.1: {} + + yargs@16.2.0: + dependencies: + cliui: 7.0.4 + escalade: 3.2.0 + get-caller-file: 2.0.5 + require-directory: 2.1.1 + string-width: 4.2.3 + y18n: 5.0.8 + yargs-parser: 20.2.9 + optional: true + + yargs@17.7.2: + dependencies: + cliui: 8.0.1 + escalade: 3.2.0 + get-caller-file: 2.0.5 + require-directory: 2.1.1 + string-width: 4.2.3 + y18n: 5.0.8 + yargs-parser: 21.1.1 + + yauzl@2.10.0: + dependencies: + buffer-crc32: 0.2.13 + fd-slicer: 1.1.0 + + yocto-queue@0.1.0: {} + + yoctocolors-cjs@2.1.3: {} + + zod@4.4.3: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 00000000..e617964f --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,9 @@ +packages: + - '.' + +# Windows packaging reuses the official runtime and native modules. +# Both local checks and CI packaging work without dependency build scripts. +ignoredBuiltDependencies: + - better-sqlite3 + - electron + - node-pty diff --git a/release/acceptance/.gitkeep b/release/acceptance/.gitkeep new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/release/acceptance/.gitkeep @@ -0,0 +1 @@ + diff --git a/scripts/build-from-upstream.js b/scripts/build-from-upstream.js index 5b23c883..9a7c6a78 100644 --- a/scripts/build-from-upstream.js +++ b/scripts/build-from-upstream.js @@ -17,6 +17,7 @@ const path = require("path"); const { execSync, execFileSync } = require("child_process"); const { findUpstreamCodex, getCodexBinarySource } = require("./codex-binary-policy"); const { validateWindowsPackage } = require("./sync-upstream"); +const { validateSource } = require("./windows-artifacts"); const PROJECT_ROOT = path.resolve(__dirname, ".."); const SRC_DIR = path.join(PROJECT_ROOT, "src"); @@ -232,7 +233,9 @@ function buildMac(platform) { } // 1. Find the .app in the ZIP extract cache - const tempDir = path.join(require("os").tmpdir(), "codex-sync"); + const tempDir = process.env.CODEX_SYNC_DIR + ? path.resolve(process.env.CODEX_SYNC_DIR) + : path.join(require("os").tmpdir(), "codex-sync"); const variant = platform === "mac-arm64" ? "arm64" : "x64"; const extractDir = path.join(tempDir, `${variant}-extract`); @@ -304,7 +307,7 @@ function buildMac(platform) { // ─── Windows build ────────────────────────────────────────────── -function buildWin(platform) { +function buildWin(platform, { deferZip = false } = {}) { const platformDir = path.join(SRC_DIR, platform); const asarDir = path.join(platformDir, "_asar"); @@ -314,7 +317,9 @@ function buildWin(platform) { } // Windows: use the MSIX extract cache - const tempDir = path.join(require("os").tmpdir(), "codex-sync"); + const tempDir = process.env.CODEX_SYNC_DIR + ? path.resolve(process.env.CODEX_SYNC_DIR) + : path.join(require("os").tmpdir(), "codex-sync"); const extractDir = path.join(tempDir, "win-extract"); const appDir = path.join(extractDir, "app"); @@ -329,8 +334,12 @@ function buildWin(platform) { // 即使绕过同步步骤,也禁止将旧的 ARM64 缓存打包成 x64 产物。 try { + const sourcePath = path.join(extractDir, "verified-windows-source.json"); + const expected = process.env.CODEX_REQUIRE_PINNED_SOURCE === "1" + ? validateSource(JSON.parse(fs.readFileSync(sourcePath, "utf8"))) + : { architecture: "x64" }; const identity = validateWindowsPackage(extractDir, { - architecture: "x64", + ...expected, }); console.log(` [verify] MSIX ${identity.architecture}, version ${identity.version}`); } catch (e) { @@ -375,6 +384,8 @@ function buildWin(platform) { // 保留上游 Windows CLI,使 app-server、code-mode host 与本地工具运行时版本一致。 keepUpstreamCodex(platform, resourcesDir, "codex.exe"); + if (deferZip) { console.log(" [verify] ZIP deferred until real Windows runtime checks pass"); return; } + // Create ZIP const version = getVersion(asarDir); const zipName = `Codex-win-x64-${version}.zip`; @@ -534,7 +545,7 @@ function main() { if (platform.startsWith("mac")) { buildMac(platform); } else { - buildWin(platform); + buildWin(platform, { deferZip: args.includes("--defer-zip") }); } } @@ -544,6 +555,7 @@ module.exports = { assertWindowsPortableRuntime, computeAsarHeaderHash, createDmg, + createZip, ensureWindowsPortableLauncher, isOwlRuntime, isRetryableHdiutilError, diff --git a/scripts/check-scripts.js b/scripts/check-scripts.js new file mode 100644 index 00000000..b8a11ea4 --- /dev/null +++ b/scripts/check-scripts.js @@ -0,0 +1,13 @@ +#!/usr/bin/env node +const fs = require("node:fs"); +const path = require("node:path"); +const { execFileSync } = require("node:child_process"); +const root = path.resolve(__dirname, ".."); +const files = fs.readdirSync(__dirname).filter((name) => /\.(?:js|cjs)$/.test(name)); +files.push("../forge.config.js", "runtime/image-generation-auth.cjs"); +files.push("runtime/rebuild-test-isolation.cjs"); +files.push("runtime/rebuild-test-environment.cjs"); +files.push("runtime/reading-width.mjs"); +for (const file of files) execFileSync(process.execPath, ["--check", path.join(__dirname, file)], { stdio: "inherit" }); +JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")); +console.log(`脚本语法检查通过:${files.length} 个文件`); diff --git a/scripts/fetch-msstore.js b/scripts/fetch-msstore.js index 47806671..9def1d97 100644 --- a/scripts/fetch-msstore.js +++ b/scripts/fetch-msstore.js @@ -404,12 +404,7 @@ async function getDownloadUrl(updateID, revisionNumber, ring, digest) { if (fileDigest === digest && url) return url; } - // 如果 digest 匹配不到,返回第一个 URL - for (const loc of locations) { - const url = deepFind(loc, "Url"); - if (url && typeof url === "string" && url.startsWith("http")) return url; - } - + // 不得将其他包的 URL 作为主包下载地址。 return ""; } diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js new file mode 100644 index 00000000..8c162c83 --- /dev/null +++ b/scripts/frontend-source-smoke.js @@ -0,0 +1,75 @@ +#!/usr/bin/env node +/** 在真实已补丁资源上执行发送门槛表达式;未知结构不能当通过。 */ +const fs = require("node:fs"); +const path = require("node:path"); +const vm = require("node:vm"); +const assert = require("node:assert/strict"); +const { parse } = require("acorn"); +function walk(node, visit) { + if (!node || typeof node !== "object") return; + if (node.type) visit(node); + for (const value of Object.values(node)) { + if (Array.isArray(value)) value.forEach(child => walk(child, visit)); + else if (value?.type) walk(value, visit); + } +} +function verifyFrontendSource(assets) { + const files = fs.readdirSync(assets).filter(name => name.endsWith(".js")); + const primary = files.filter(name => /^app-primary-/.test(name) && fs.readFileSync(path.join(assets, name), "utf8").includes("const __codexQuotaThreadProvider=")); + assert.equal(primary.length, 1); + const source = fs.readFileSync(path.join(assets, primary[0]), "utf8"), ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + let guard, disabled, config, scope, quota = [], loading; + walk(ast, node => { + if (node.type === "VariableDeclaration" && node.declarations.some(d => d.id.name === "__codexUsesCustomProvider")) guard = node; + if (node.type === "VariableDeclarator" && node.init?.type === "LogicalExpression" && source.slice(node.init.start, node.init.end).includes("!__codexUsesCustomProvider")) disabled = node; + }); + assert.ok(guard && disabled); + walk(guard, node => { + if (node.type === "MemberExpression" && node.property.name === "isConfigDataPending") config = node.object.name; + if (node.type === "MemberExpression" && node.property.name === "kind") scope = node.object.object.name; + }); + const names = new Set(); + walk(disabled.init, node => { + if (node.type === "Identifier") names.add(node.name); + if (node.type === "LogicalExpression" && node.left?.type === "UnaryExpression" && node.left.argument.name === "__codexUsesCustomProvider") quota.push(node.right.name); + if (node.type === "MemberExpression" && node.property.name === "isLoading") loading = node.object.name; + }); + assert.equal(quota.length, 2); assert.ok(config && scope && loading); + const lookup = guard.declarations[0].init; + const external = { base_url: "https://provider.example/v1", requires_openai_auth: true }; + const scenarios = [ + { name: "第三方服务不受官方额度禁发", provider: "local", endpoint: external, expected: false }, + { name: "保存的官方任务不跟随全局第三方", saved: "openai", provider: "local", endpoint: external, expected: true }, + { name: "保存的第三方任务优先", saved: "local", provider: "openai", endpoint: external, expected: false }, + { name: "官方保留额度限制", provider: "openai", endpoint: external, expected: true }, + { name: "第三方无端点仍受保护", provider: "local", endpoint: {}, expected: true }, + { name: "ChatGPT 端点仍受保护", provider: "local", endpoint: { base_url: "https://chatgpt.com/backend-api/codex" }, expected: true }, + { name: "ChatGPT 子域仍受保护", provider: "local", endpoint: { base_url: "https://api.chatgpt.com./" }, expected: true }, + { name: "非法端点保留限制", provider: "local", endpoint: { base_url: "file:///tmp" }, expected: true }, + { name: "配置未就绪保留限制", provider: "local", endpoint: external, pending: true, expected: true }, + { name: "云任务不绕过", provider: "local", endpoint: external, kind: "cloud", expected: true }, + { name: "新建本地允许第三方", provider: "local", endpoint: external, kind: "new", expected: false }, + { name: "新建云原型不绕过", provider: "local", endpoint: external, kind: "new", cloud: true, expected: true }, + { name: "第三方真实加载错误仍阻止发送", provider: "local", endpoint: external, loading: true, expected: true }, + ]; + const results = []; + for (const scenario of scenarios) { + const context = Object.fromEntries([...names].map(name => [name, false])); + Object.assign(context, { URL, [config]: { isConfigDataPending: !!scenario.pending, resolvedConfig: { model_provider: scenario.provider, model_providers: { local: scenario.endpoint } } }, + [scope]: { value: { kind: scenario.kind || "local", cloudThreadPrototype: scenario.cloud } }, [loading]: { isLoading: !!scenario.loading }, + [lookup.callee.name]: () => scenario.saved, [lookup.arguments[0].name]: null, [lookup.arguments[1].name]: "fixture-thread" }); + for (const name of quota) context[name] = true; + const actual = vm.runInNewContext(source.slice(guard.start, guard.end) + `\nBoolean(${source.slice(disabled.init.start, disabled.init.end)})`, context, { timeout: 1000 }); + assert.equal(actual, scenario.expected, scenario.name); results.push(scenario.name); + } + const settings = files.filter(name => /^general-settings-/.test(name) + && fs.readFileSync(path.join(assets, name), "utf8").includes("settings.appearance.visualStyle")); assert.equal(settings.length, 1); + assert.match(fs.readFileSync(path.join(assets, settings[0]), "utf8"), /jsx\)\(__CodexRebuildReadingWidth/); + const shared = files.filter(name => /^app-shared-/.test(name) && fs.readFileSync(path.join(assets, name), "utf8").includes("codex-rebuild-dialog-default")); + assert.equal(shared.length, 1); + const dialogs = fs.readFileSync(path.join(assets, shared[0]), "utf8"); + assert.match(dialogs, /codex-rebuild-dialog-editor h-\[720px\] max-w-full max-h-full/); + return { passed: true, quotaScenarios: results, nativeAppearanceRow: true, dialogHeightPreserved: true }; +} +if (require.main === module) console.log(JSON.stringify(verifyFrontendSource(path.resolve(process.argv[2] || "src/win/_asar/webview/assets")), null, 2)); +module.exports = { verifyFrontendSource }; diff --git a/scripts/maintenance-smoke.js b/scripts/maintenance-smoke.js new file mode 100644 index 00000000..d2ba74ff --- /dev/null +++ b/scripts/maintenance-smoke.js @@ -0,0 +1,149 @@ +#!/usr/bin/env node +/** 可重复的维护链功能测试:使用合成制品与 Electron 替身,不宣称 GUI 已验收。 */ +const fs = require("node:fs"); +const path = require("node:path"); +const os = require("node:os"); +const crypto = require("node:crypto"); +const assert = require("node:assert/strict"); +const { spawnSync } = require("node:child_process"); +const { requiredChecks } = require("./windows-maintenance"); +const temporary = fs.mkdtempSync(path.join(os.tmpdir(), "codex-maintenance-smoke-")); +const scriptRoot = __dirname; +const hash = (value) => crypto.createHash("sha256").update(value).digest("hex"); +const write = (file, value) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, value); }; +const json = (file, value) => write(file, JSON.stringify(value)); +let checks = 0; +function run(script, args, expected = 0, env = {}) { + const result = spawnSync(process.execPath, [path.join(scriptRoot, script), ...args], { + encoding: "utf8", env: { ...process.env, GITHUB_ACTIONS: "false", GITHUB_OUTPUT: "", GITHUB_STEP_SUMMARY: "", ...env }, + }); + assert.equal(result.error, undefined); + if (expected === 0) assert.equal(result.status, 0, result.stdout + result.stderr); + else assert.notEqual(result.status, 0, "本应拒绝此输入"); + checks++; + return result; +} +try { + if (process.platform === "win32") { + const env = require("./windows-runtime-checks").isolatedEnvironment(path.join(temporary, "native-profile")); + const native = spawnSync("pwsh", ["-NoProfile", "-Command", "[pscustomobject]@{appData=[Environment]::GetFolderPath([Environment+SpecialFolder]::ApplicationData);local=[Environment]::GetFolderPath([Environment+SpecialFolder]::LocalApplicationData)}|ConvertTo-Json -Compress"], { env, encoding: "utf8" }); + assert.equal(native.status, 0, native.stderr); + const actual = JSON.parse(native.stdout); + assert.equal(path.resolve(actual.appData).toLowerCase(), env.APPDATA.toLowerCase()); + assert.equal(path.resolve(actual.local).toLowerCase(), env.LOCALAPPDATA.toLowerCase()); checks++; + } + run("windows-maintenance.js", ["candidate"], 1); + const discoveryPreload = path.join(temporary, "discovery-preload.cjs"); + write(discoveryPreload, `const target=require.resolve(${JSON.stringify(path.join(scriptRoot, "fetch-msstore.js"))}); require.cache[target]={id:target,filename:target,loaded:true,exports:{getCookie:async()=>"cookie",getAppInfo:async()=>({categoryId:"fixture"}),getFileList:async()=>["26.1007.9446.0","26.917.71314.0","26.1007.2314.0"].map(v=>({name:"OpenAI.Codex_"+v+"_x64__2p2nqsd0c76g0.msix",size:"10",digest:Buffer.alloc(20).toString("base64"),updateID:v,revisionNumber:"1"})),getDownloadUrl:async()=>"https://tlu.dl.delivery.mp.microsoft.com/fixture.msix"}};`); + const discoveryOutput = path.join(temporary, "discovery.json"); + const observed = path.join(temporary, "observed.json"); + json(observed, { schemaVersion: 1, upstream: { version: "26.1007.9446.0" } }); + const discovered = spawnSync(process.execPath, ["--require", discoveryPreload, path.join(scriptRoot, "windows-maintenance.js"), "discover", "--out", discoveryOutput, "--stable-manifest", observed], { encoding: "utf8", env: { ...process.env, GITHUB_OUTPUT: "" } }); + assert.equal(discovered.status, 0, discovered.stderr); + assert.match(discovered.stdout, /has_update=false/); + assert.equal(JSON.parse(fs.readFileSync(discoveryOutput)).version, "26.1007.9446.0"); + checks++; + json(observed, { schemaVersion: 1, upstream: { version: "26.1007.2314.0" } }); + const changed = spawnSync(process.execPath, ["--require", discoveryPreload, path.join(scriptRoot, "windows-maintenance.js"), "discover", "--out", discoveryOutput, "--stable-manifest", observed], { encoding: "utf8", env: { ...process.env, GITHUB_OUTPUT: "" } }); + assert.equal(changed.status, 0, changed.stderr); + assert.match(changed.stdout, /has_update=true/); + checks++; + for (const mode of ["commonjs", "module"]) { + const source = path.join(temporary, mode, "src"); + const asar = path.join(source, "win", "_asar"); + const testRoot = path.join(temporary, mode, "isolated"); + json(path.join(asar, "package.json"), { type: mode, main: "bootstrap.js" }); + const nativeImport = mode === "module" ? 'import {app} from "electron";' : 'const {app}=require("electron");'; + write(path.join(asar, "bootstrap.js"), '"use strict";\n' + nativeImport + '\nfunction resolveUserData({env}){return env.CODEX_ELECTRON_USER_DATA_PATH;} app.setName("fixture"),app.setPath("userData",resolveUserData({env:process.env})); app.requestSingleInstanceLock(); console.log("fixture started");\n'); + const mock = 'let data="",session="",named=false; exports.app={setName:()=>named=true,setPath:(k,v)=>{if(!named)throw Error("Owl path API too early");if(k==="userData")data=v;if(k==="sessionData")session=v;},getPath:k=>k==="sessionData"?session:data,requestSingleInstanceLock:()=>{if(session!==data)throw Error("sessionData not isolated before lock");return true;},whenReady:()=>Promise.resolve(),exit:()=>{process.exitCode=1;}};'; + json(path.join(asar, "node_modules", "electron", "package.json"), { type: "commonjs", main: "index.js" }); + write(path.join(asar, "node_modules", "electron", "index.js"), mock); + const entry = path.join(asar, "bootstrap.js"); + const before = fs.readFileSync(entry); + run("patch-test-isolation.js", ["win", "--check"], 0, { CODEX_PATCH_SOURCE_DIR: source }); + assert.deepEqual(fs.readFileSync(entry), before); + run("patch-test-isolation.js", ["win"], 0, { CODEX_PATCH_SOURCE_DIR: source }); + const patched = fs.readFileSync(entry); + run("patch-test-isolation.js", ["win"], 0, { CODEX_PATCH_SOURCE_DIR: source }); + assert.deepEqual(fs.readFileSync(entry), patched); + const started = spawnSync(process.execPath, [entry], { encoding: "utf8", env: { ...process.env, CODEX_REBUILD_TEST_ROOT: testRoot } }); + assert.equal(started.status, 0, started.stderr); + const proof = JSON.parse(fs.readFileSync(path.join(testRoot, "isolation-runtime.json"))); + assert.equal(proof.codexHome, path.join(testRoot, "codex-home")); + assert.equal(proof.userData, path.join(testRoot, "electron-user-data")); + assert.ok(fs.readFileSync(entry, "utf8").startsWith('"use strict";')); + checks++; + write(entry, '"use strict";\nconsole.log("unknown native bootstrap");\n'); + run("patch-test-isolation.js", ["win", "--check"], 1, { CODEX_PATCH_SOURCE_DIR: source }); + } + const updaterSource = path.join(temporary, "updater", "win", "_asar", ".vite", "build"); + write(path.join(updaterSource, "gates.js"), 'const gates={shouldIncludeWindowsUpdater(){return true},shouldIncludeWindowsMsixUpdater(){return true},shouldIncludeUpdater(){return true}};'); + run("patch-updater.js", ["win"], 0, { CODEX_PATCH_SOURCE_DIR: path.join(temporary, "updater") }); + assert.equal((fs.readFileSync(path.join(updaterSource, "gates.js"), "utf8").match(/return !1/g) || []).length, 3); + write(path.join(updaterSource, "caller.js"), "gates.shouldIncludeUpdater(1,2,3);"); + const callerResult = run("patch-updater.js", ["win"], 0, { CODEX_PATCH_SOURCE_DIR: path.join(temporary, "updater") }); + assert.match(callerResult.stdout, /call sites only/); + assert.doesNotMatch(callerResult.stdout, /\[!\]/); + fs.unlinkSync(path.join(updaterSource, "caller.js")); + write(path.join(updaterSource, "gates.js"), "const changed=true;"); + assert.match(run("patch-updater.js", ["win"], 0, { CODEX_PATCH_SOURCE_DIR: path.join(temporary, "updater") }).stdout, /\[!\]/); + + const pickerRoot = path.join(temporary, "picker"); + const pickerFile = path.join(pickerRoot, "win", "_asar", "webview", "assets", "model-picker.js"); + const nativePicker = 'function picker(input){const {modelListConfig:list,menuView:view,onToggleMenuView:toggle}=input;const items=list.options.map(option=>ui.jsx(menu.Item,{"data-model-selected":option.selected,role:`menuitemradio`,onSelect:event=>{event.preventDefault();option.onSelect();toggle(`simple`)}}));return ui.jsx("div",{"data-model-picker-view":view,children:items});}'; + write(pickerFile, nativePicker); + const nativeCheck = run("patch-model-picker-submenu.js", ["win", "--check"], 0, { CODEX_PATCH_SOURCE_DIR: pickerRoot }); + assert.match(nativeCheck.stdout, /native inline model list verified/); + run("patch-model-picker-submenu.js", ["win"], 0, { CODEX_PATCH_SOURCE_DIR: pickerRoot }); + assert.equal(fs.readFileSync(pickerFile, "utf8"), nativePicker); + write(pickerFile, nativePicker.replace("event.preventDefault();", "")); + run("patch-model-picker-submenu.js", ["win"], 1, { CODEX_PATCH_SOURCE_DIR: pickerRoot }); + write(pickerFile, nativePicker.replace("ui.jsx(\"div\"", "ui.jsx(menu.FlyoutSubmenuItem")); + run("patch-model-picker-submenu.js", ["win"], 1, { CODEX_PATCH_SOURCE_DIR: pickerRoot }); + + const candidate = path.join(temporary, "candidate"); + const zip = Buffer.from("synthetic ZIP payload for promotion checks"); + const msix = Buffer.from("synthetic official source for provenance checks"); + const sha = "1".repeat(40); + const source = { schemaVersion: 1, version: "26.1007.9446.0", architecture: "x64", packageName: "OpenAI.Codex_26.1007.9446.0_x64__2p2nqsd0c76g0.msix", size: msix.length, sha256: hash(msix) }; + const metadata = { schemaVersion: 1, repository: "Carptopus/CodexDesktop-Rebuild", sourceCommit: sha, runId: "123", runAttempt: "1", revision: 1, upstream: source, + zip: { name: "candidate.zip", size: zip.length, sha256: hash(zip) }, gate: { canPromote: true, blocks: [] } }; + const report = { upstream: source, gate: metadata.gate, cliInitialize: { passed: true }, updater: { disabled: true }, integrityHashEmbedded: true, components: { passed: true }, desktopSmoke: { passed: true } }; + const approval = { schemaVersion: 1, sourceCommit: sha, zipSha256: hash(zip), runId: "123", tester: "fixture", testedAt: "2026-10-14T12:00:00Z", isolationEvidence: "synthetic proof", rollbackEvidence: "synthetic proof", checks: Object.fromEntries(requiredChecks.map((name) => [name, "passed"])) }; + write(path.join(candidate, "candidate.zip"), zip); + write(path.join(candidate, source.packageName), msix); + json(path.join(candidate, "upstream.json"), source); + json(path.join(candidate, "candidate.json"), metadata); + json(path.join(candidate, "verify-report.json"), report); + const acceptance = path.join(temporary, "approval.json"); + json(acceptance, approval); + const arguments = ["verify-release", "--dir", candidate, "--acceptance", acceptance, "--repository", metadata.repository, + "--run-id", "123", "--run-attempt", "1", "--source-commit", sha, "--zip-sha256", hash(zip)]; + run("windows-maintenance.js", arguments); + for (const key of ["components", "desktopSmoke"]) { + for (const value of [undefined, { passed: false }]) { + json(path.join(candidate, "verify-report.json"), { ...report, [key]: value }); + run("windows-maintenance.js", arguments, 1); + } + } + json(path.join(candidate, "verify-report.json"), report); + for (const key of requiredChecks) { + json(acceptance, { ...approval, checks: { ...approval.checks, [key]: "pending" } }); + run("windows-maintenance.js", arguments, 1); + } + json(acceptance, approval); + write(path.join(candidate, "candidate.zip"), "changed ZIP"); + run("windows-maintenance.js", arguments, 1); + write(path.join(candidate, "candidate.zip"), zip); + write(path.join(candidate, source.packageName), "changed MSIX"); + run("windows-maintenance.js", arguments, 1); + write(path.join(candidate, source.packageName), msix); + json(path.join(candidate, "candidate.json"), { ...metadata, gate: { canPromote: false, blocks: ["necessary patch needs review"] } }); + run("windows-maintenance.js", arguments, 1); + json(path.join(candidate, "candidate.json"), metadata); + run("windows-maintenance.js", arguments.map((value) => value === "123" ? "999" : value), 1); + run("windows-maintenance.js", arguments.map((value) => value === sha ? "2".repeat(40) : value), 1); + console.log(`维护链功能测试通过:${checks} 个 CLI 场景;实际 GUI、原始 MSIX 和签名由候选验收覆盖。`); +} finally { + fs.rmSync(temporary, { recursive: true, force: true }); +} diff --git a/scripts/patch-model-picker-submenu.js b/scripts/patch-model-picker-submenu.js index 44aee154..9ad308fb 100644 --- a/scripts/patch-model-picker-submenu.js +++ b/scripts/patch-model-picker-submenu.js @@ -57,7 +57,8 @@ function findTargets(platform) { if (!file.endsWith(".js")) continue; const filePath = path.join(assetsDir, file); const source = fs.readFileSync(filePath, "utf-8"); - if (TARGET_SIGNATURES.every((signature) => source.includes(signature))) { + if (TARGET_SIGNATURES.every((signature) => source.includes(signature)) + || ["data-model-picker-view", "data-model-selected", "modelListConfig"].every((signature) => source.includes(signature))) { targets.push({ platform: currentPlatform, path: filePath, source }); } } @@ -74,6 +75,69 @@ function parseOk(code) { } } +// 26.1007 使用同一菜单内的 simple/advanced 两个面板。 +// 必须确认模型项、事件处理和菜单容器的结构,不能仅凭旧标记消失跳过。 +function inspectNativeModelList(source) { + const ast = acorn.parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const candidates = []; + const walk = (node, visit) => { + if (!node || typeof node !== "object") return; + if (node.type) visit(node); + for (const value of Object.values(node)) { + if (Array.isArray(value)) value.forEach((child) => walk(child, visit)); + else if (value && typeof value === "object" && value.type) walk(value, visit); + } + }; + const keyName = (node) => node?.name || node?.value; + const staticValue = (node) => node?.type === "Literal" ? node.value + : node?.type === "TemplateLiteral" && node.expressions.length === 0 ? node.quasis[0].value.cooked : undefined; + walk(ast, (fn) => { + if (fn.type !== "FunctionDeclaration") return; + const patterns = fn.params.filter((node) => node.type === "ObjectPattern"); + for (const statement of fn.body.body) { + if (statement.type !== "VariableDeclaration") continue; + for (const declaration of statement.declarations) { + if (declaration.id.type === "ObjectPattern" && declaration.init?.type === "Identifier" + && fn.params.some((param) => param.type === "Identifier" && param.name === declaration.init.name)) patterns.push(declaration.id); + } + } + const pattern = patterns.find((node) => ["modelListConfig", "menuView", "onToggleMenuView"] + .every((name) => node.properties.some((prop) => keyName(prop.key) === name && prop.value?.type === "Identifier"))); + if (!pattern) return; + const binding = (name) => pattern.properties.find((prop) => keyName(prop.key) === name).value.name; + let panel = false, optionsMap = false, directRows = 0, flyout = false; + walk(fn.body, (node) => { + if (node.type === "MemberExpression" && keyName(node.property) === "FlyoutSubmenuItem") flyout = true; + if (node.type === "Property" && keyName(node.key) === "data-model-picker-view" + && node.value.type === "Identifier" && node.value.name === binding("menuView")) panel = true; + if (node.type !== "CallExpression") return; + const callee = node.callee; + if (callee.type === "MemberExpression" && keyName(callee.property) === "map" + && callee.object.type === "MemberExpression" && keyName(callee.object.property) === "options" + && callee.object.object.type === "Identifier" && callee.object.object.name === binding("modelListConfig")) optionsMap = true; + const component = node.arguments[0], props = node.arguments[1]; + if (component?.type !== "MemberExpression" || keyName(component.property) !== "Item" || props?.type !== "ObjectExpression") return; + const properties = props.properties; + if (!properties.some((prop) => keyName(prop.key) === "data-model-selected") + || !properties.some((prop) => keyName(prop.key) === "role" && staticValue(prop.value) === "menuitemradio")) return; + const onSelect = properties.find((prop) => keyName(prop.key) === "onSelect")?.value; + if (!onSelect || !["ArrowFunctionExpression", "FunctionExpression"].includes(onSelect.type)) return; + let preventDefault = false, select = false, returnToPanel = false; + walk(onSelect.body, (call) => { + if (call.type !== "CallExpression") return; + if (call.callee.type === "MemberExpression" && keyName(call.callee.property) === "preventDefault") preventDefault = true; + if (call.callee.type === "MemberExpression" && keyName(call.callee.property) === "onSelect") select = true; + if (call.callee.type === "Identifier" && call.callee.name === binding("onToggleMenuView") + && staticValue(call.arguments[0]) === "simple") returnToPanel = true; + }); + if (preventDefault && select && returnToPanel) directRows++; + }); + if (panel && optionsMap && directRows > 0 && !flyout) candidates.push({ functionName: fn.id.name, directRows }); + }); + if (candidates.length > 1) throw new Error("Multiple native model-list implementations need review"); + return candidates[0] || null; +} + function patchSource(source) { const rowPropsMatches = [...source.matchAll(ROW_PROPS_RE)]; if (rowPropsMatches.length !== 1) { @@ -137,6 +201,16 @@ function main() { let failed = 0; for (const target of targets) { const label = relPath(target.path); + const native = inspectNativeModelList(target.source); + if (native) { + console.log(` [ok] ${label}: native inline model list verified (${native.functionName}, ${native.directRows} direct row renderer); submenu patch not needed`); + continue; + } + if (!TARGET_SIGNATURES.every((signature) => target.source.includes(signature))) { + console.log(` [x] ${label}: native model-list structure changed; needs explicit adaptation`); + failed++; + continue; + } const result = patchSource(target.source); if (result.status === "already-patched") { diff --git a/scripts/patch-policy.js b/scripts/patch-policy.js index a651decd..317a4be5 100644 --- a/scripts/patch-policy.js +++ b/scripts/patch-policy.js @@ -20,6 +20,9 @@ const PATCH_POLICY = [ { script: "patch-codex-home-env.js", feature: "用户配置目录传递" }, { script: "patch-image-generation-auth.js", feature: "API-key 图片生成" }, { script: "patch-windows-portable-runtime.js", feature: "Windows 便携运行时" }, + { script: "patch-test-isolation.js", feature: "Windows 验收数据隔离" }, + { script: "patch-provider-quota.js", feature: "真实 Provider 额度发送门槛" }, + { script: "patch-reading-layout.js", feature: "可配置正文宽度与排版" }, { script: "patch-model-catalog-filter.js", feature: "模型目录过滤" }, { script: "patch-model-picker-submenu.js", feature: "模型选择器子菜单" }, { script: "patch-thread-file-manager-action.js", feature: "会话文件管理器入口" }, diff --git a/scripts/patch-provider-quota.js b/scripts/patch-provider-quota.js new file mode 100644 index 00000000..36f4eaae --- /dev/null +++ b/scripts/patch-provider-quota.js @@ -0,0 +1,337 @@ +#!/usr/bin/env node +/** + * 来源:DevSplash da84a96c,按真实端点隔离额度发送门槛。 + * Scope the desktop composer's OpenAI quota gates to the effective provider. + * requires_openai_auth selects credentials, not the provider receiving requests. + * Keep account quota state intact; only explicit custom endpoints ignore it. + */ +const fs = require("fs"); +const path = require("path"); +const { parse } = require("acorn"); +const { SRC_DIR, relPath } = require("./patch-util"); + +const MARKER = "/* Codex custom provider quota patch */"; +const CUSTOM = "__codexUsesCustomProvider"; +const PROVIDER = "__codexQuotaProvider"; +const THREAD_PROVIDER = "__codexQuotaThreadProvider"; +const PROVIDER_CONFIG = "__codexQuotaProviderConfig"; +const PLATFORMS = ["mac-arm64", "mac-x64", "win", "unix"]; + +function walk(node, visit, root = node, ownScope = false) { + if (!node || typeof node !== "object" || !node.type) return; + if (ownScope && node !== root && /Function/.test(node.type)) return; + visit(node); + for (const value of Object.values(node)) { + if (Array.isArray(value)) { + for (const child of value) walk(child, visit, root, ownScope); + } else if (value?.type) { + walk(value, visit, root, ownScope); + } + } +} + +function nodes(root, predicate, ownScope = false) { + const found = []; + walk(root, node => { if (predicate(node)) found.push(node); }, root, ownScope); + return found; +} + +function unwrap(node) { + return node?.type === "ChainExpression" ? node.expression : node; +} + +function value(node) { + if (node?.type === "Literal") return node.value; + if (node?.type === "TemplateLiteral" && node.expressions.length === 0) { + return node.quasis[0].value.cooked; + } + return null; +} + +function property(node) { + const member = unwrap(node); + if (member?.type !== "MemberExpression" && member?.type !== "Property") return null; + const key = member.property ?? member.key; + return !member.computed && key.type === "Identifier" ? key.name : value(key); +} + +function parseModule(source) { + return parse(source, { ecmaVersion: "latest", sourceType: "module" }); +} + +function binding(node) { + if (node.type === "VariableDeclarator" && node.id.type === "Identifier") { + return { name: node.id.name, init: node.init, node }; + } + if (node.type === "AssignmentExpression" && node.left.type === "Identifier") { + return { name: node.left.name, init: node.right, node }; + } + return null; +} + +function importFor(ast, localName) { + for (const declaration of ast.body) { + if (declaration.type !== "ImportDeclaration") continue; + const specifier = declaration.specifiers.find(s => s.local.name === localName); + if (specifier?.type === "ImportSpecifier") { + return { source: declaration.source.value, name: specifier.imported.name }; + } + } + return null; +} + +function exportFor(ast, localName) { + for (const declaration of ast.body) { + if (declaration.type !== "ExportNamedDeclaration") continue; + const specifier = declaration.specifiers.find(s => s.local.name === localName); + if (specifier) return specifier.exported.name; + } + return null; +} + +function getQuotaMetadata(source) { + const ast = parseModule(source); + const hardBlockAtoms = nodes(ast, node => { + const item = binding(node); + if (item?.init?.type !== "CallExpression") return false; + return item.init.arguments.some(arg => arg.type === "ArrowFunctionExpression" && + property(arg.body) === "hardBlocked" && + unwrap(arg.body).object.type === "CallExpression"); + }).map(node => binding(node).name); + // Upstream's ordinary-model presets already resolve thread provider before + // config.model_provider. Reuse that exact thread-summary atom, not its name, + // the provider's display name, an auth flag, or a particular model slug. + const providerReads = nodes(ast, node => node.type === "LogicalExpression" && + node.operator === "??" && node.left.type === "CallExpression" && + node.left.arguments.length === 2 && property(node.right) === "model_provider"); + if (hardBlockAtoms.length !== 1 || providerReads.length !== 1) { + throw new Error("OpenAI quota atom or effective thread-provider lookup is ambiguous/missing"); + } + const hardBlockExport = exportFor(ast, hardBlockAtoms[0]); + const threadProviderImport = importFor(ast, providerReads[0].left.arguments[0].name); + if (!hardBlockExport || !threadProviderImport) { + throw new Error("OpenAI quota/thread-provider module bindings not found"); + } + return { hardBlockExport, threadProviderImport }; +} + +function importedLocal(ast, source, exportedName) { + for (const declaration of ast.body) { + if (declaration.type !== "ImportDeclaration" || declaration.source.value !== source) continue; + const specifier = declaration.specifiers.find(s => s.imported?.name === exportedName); + if (specifier) return specifier.local.name; + } + return null; +} + +function quotaAtoms(ast, source) { + return new Set(nodes(ast, node => { + const item = binding(node); + if (item?.init?.type !== "CallExpression") return false; + return item.init.arguments.some(arg => { + if (arg.type !== "ArrowFunctionExpression") return false; + const text = source.slice(arg.start, arg.end); + return ["authMethod", "authenticatedAccountId", "rate_limit", "allowed", + "windowMinutes", "resetsAt"].every(key => text.includes(key)); + }); + }).map(node => binding(node).name)); +} + +function unique(items, label) { + if (items.length !== 1) throw new Error(`${label} is ambiguous/missing (${items.length})`); + return items[0]; +} + +// This function is embedded into the frontend and must remain self-contained. +// A custom provider ID does not imply a custom endpoint: without base_url, +// ChatGPT authentication still defaults to chatgpt.com/backend-api/codex. +function hasExternalBaseUrl(provider) { + if (typeof provider?.base_url !== "string" || !provider.base_url.trim()) return false; + try { + const endpoint = new URL(provider.base_url); + if (endpoint.protocol !== "https:" && endpoint.protocol !== "http:") return false; + const host = endpoint.hostname.toLowerCase().replace(/\.$/, ""); + if (!host) return false; + return !["chatgpt.com", "chat.openai.com"].some(domain => + host === domain || host.endsWith(`.${domain}`)); + } catch { + return false; + } +} + +function patchSource(source, metadata, initialImport) { + try { + const updating = source.includes(MARKER); + const ast = parseModule(source); + const hardBlockAtom = importedLocal(ast, initialImport, metadata.hardBlockExport); + const threadProviderAtom = importedLocal(ast, metadata.threadProviderImport.source, + metadata.threadProviderImport.name); + if (!hardBlockAtom || !threadProviderAtom) throw new Error("Composer quota/provider imports not found"); + if (!updating && [CUSTOM, PROVIDER, THREAD_PROVIDER, PROVIDER_CONFIG] + .some(name => source.includes(name))) { + throw new Error("Custom-provider patch binding already exists without its marker"); + } + const nativeQuotaAtoms = quotaAtoms(ast, source); + const composer = unique(ast.body.filter(node => node.type === "FunctionDeclaration" && + nodes(node, child => property(child) === "submitDisabled", true).length > 0 && + nodes(node, child => property(child) === "resolvedConfig").length > 0), + "Provider-aware composer"); + const ownNodes = nodes(composer, () => true, true); + const memberReads = nodes(composer, node => unwrap(node)?.type === "MemberExpression"); + const declarations = ownNodes.filter(node => node.type === "VariableDeclarator"); + const submit = unique(ownNodes.filter(node => node.type === "Property" && + property(node) === "submitDisabled" && node.value.type === "Identifier" && + declarations.some(decl => decl.id.name === node.value.name && decl.init)), + "Submit-disabled property"); + const disabled = unique(declarations.filter(node => node.id.name === submit.value.name && node.init), + "Submit-disabled expression"); + const referenced = new Set(nodes(disabled.init, node => node.type === "Identifier").map(node => node.name)); + const hardBlock = unique(declarations.filter(node => referenced.has(node.id.name) && + node.init?.type === "CallExpression" && node.init.arguments[0]?.name === hardBlockAtom && + node.init.arguments.length === 2), "Host quota gate"); + const baseBlock = unique(declarations.filter(node => referenced.has(node.id.name) && node.init && + nodes(node.init, child => child.type === "CallExpression" && child.arguments.length === 1 && + nativeQuotaAtoms.has(child.arguments[0].name)).length > 0), "Account quota gate"); + const configNames = new Set(memberReads.filter(node => property(node) === "resolvedConfig") + .map(node => unwrap(node).object.name)); + const pendingNames = new Set(memberReads.filter(node => property(node) === "isConfigDataPending") + .map(node => unwrap(node).object.name)); + const config = unique(declarations.filter(node => configNames.has(node.id.name) && + pendingNames.has(node.id.name) && node.init?.type === "CallExpression"), "Resolved composer config"); + const target = config.init.arguments[0]; + const targets = target?.type === "ObjectExpression" ? [target] : ownNodes + .map(binding).filter(item => item?.name === target?.name && item.init?.type === "ObjectExpression") + .map(item => item.init); + const targetObject = unique(targets, "Composer config target"); + const conversation = targetObject.properties.find(prop => property(prop) === "conversationId")?.value; + const host = targetObject.properties.find(prop => property(prop) === "hostId")?.value; + if (conversation?.type !== "Identifier" || host?.type !== "Identifier") { + throw new Error("Composer config target lacks conversation/host identifiers"); + } + function resolveAlias(name) { + const seen = new Set(); + while (!seen.has(name)) { + seen.add(name); + const alias = declarations.find(node => node.id.name === name && node.init?.type === "Identifier"); + if (!alias) break; + name = alias.init.name; + } + return name; + } + if (resolveAlias(host.name) !== resolveAlias(hardBlock.init.arguments[1].name)) { + throw new Error("Composer config and quota hosts differ"); + } + const scopes = [...new Set(ownNodes.filter(node => property(node) === "kind" && + property(unwrap(node).object) === "value") + .map(node => unwrap(unwrap(node).object).object.name))]; + const scope = unique(scopes, "Composer scope"); + const statement = unique(composer.body.body.filter(node => node.type === "VariableDeclaration" && + node.declarations.includes(disabled)), "Submit-disabled declaration"); + if (config.end > statement.start) throw new Error("Composer config is resolved after submission gating"); + const guard = `${MARKER}\nconst ${THREAD_PROVIDER}=${source.slice(hardBlock.init.callee.start, hardBlock.init.callee.end)}(${threadProviderAtom},${conversation.name}),` + + `${PROVIDER}=${THREAD_PROVIDER}??(${config.id.name}.isConfigDataPending?null:${config.id.name}.resolvedConfig?.model_provider),` + + `${PROVIDER_CONFIG}=${config.id.name}.isConfigDataPending?null:${config.id.name}.resolvedConfig?.model_providers?.[${PROVIDER}],` + + `${CUSTOM}=(${scope}.value.kind===\`local\`||${scope}.value.kind===\`new\`&&!${scope}.value.cloudThreadPrototype)` + + `&&typeof ${PROVIDER}===\`string\`&&${PROVIDER}.trim().length>0&&${PROVIDER}!==\`openai\`` + + `&&(${hasExternalBaseUrl.toString()})(${PROVIDER_CONFIG});`; + const edits = []; + if (updating) { + // Upgrade the previous provider-ID-only guard as well as fresh sources. + // Keep the existing hook and quota-gate reads in their original positions. + const oldGuard = unique(composer.body.body.filter(node => node.type === "VariableDeclaration" && + node.declarations.some(decl => decl.id.name === CUSTOM)), "Existing provider guard"); + const oldNames = oldGuard.declarations.map(decl => decl.id.name).join(","); + if (oldGuard.kind !== "const" || ![ + [THREAD_PROVIDER, PROVIDER, CUSTOM].join(","), + [THREAD_PROVIDER, PROVIDER, PROVIDER_CONFIG, CUSTOM].join(","), + ].includes(oldNames) || oldGuard.end > statement.start || + source.slice(oldGuard.end, statement.start).trim()) { + throw new Error("Existing provider guard structure changed"); + } + const markerStart = source.lastIndexOf(MARKER, oldGuard.start); + if (markerStart < 0 || source.slice(markerStart + MARKER.length, oldGuard.start).trim()) { + throw new Error("Existing provider guard marker is misplaced"); + } + edits.push({ start: markerStart, end: oldGuard.end, text: guard }); + } else { + edits.push({ start: statement.start, end: statement.start, text: guard }); + } + for (const gate of [hardBlock, baseBlock]) { + const read = unique(nodes(disabled.init, node => node.type === "Identifier" && + node.name === gate.id.name), `Submit read of ${gate.id.name}`); + if (updating) { + unique(nodes(disabled.init, node => node.type === "LogicalExpression" && + node.operator === "&&" && node.left.type === "UnaryExpression" && + node.left.operator === "!" && node.left.argument.name === CUSTOM && + node.right === read), `Existing guard for ${gate.id.name}`); + } else { + edits.push({ start: read.start, end: read.end, text: `(!${CUSTOM}&&${gate.id.name})` }); + } + } + let code = source; + for (const edit of edits.sort((a, b) => b.start - a.start)) { + code = code.slice(0, edit.start) + edit.text + code.slice(edit.end); + } + parseModule(code); + if (code === source) return { status: "already", code: source }; + return { status: "patched", code, changes: [ + "resolve the effective provider from the saved thread, then the current host/workspace config", + "ignore OpenAI submission quota gates only for explicit non-ChatGPT custom endpoints", + ] }; + } catch (error) { + return { status: "error", code: source, reason: error.message }; + } +} + +function main() { + const args = process.argv.slice(2); + const platform = args.find(arg => PLATFORMS.includes(arg)); + const check = args.includes("--check"); + const directories = (platform ? [platform] : PLATFORMS) + .map(plat => ({ platform: plat, path: path.join(SRC_DIR, plat, "_asar", "webview", "assets") })) + .filter(dir => fs.existsSync(dir.path)); + const legacy = path.join(SRC_DIR, "webview", "assets"); + if (!directories.length && fs.existsSync(legacy)) directories.push({ platform: "legacy", path: legacy }); + let patched = 0; + let failed = 0; + for (const directory of directories) { + try { + const files = fs.readdirSync(directory.path).filter(name => name.endsWith(".js")) + .map(name => ({ name, source: fs.readFileSync(path.join(directory.path, name), "utf8") })); + const candidates = []; + const diagnostics = []; + for (const file of files.filter(file => file.source.includes("hardBlocked") && + file.source.includes("model_provider") && file.source.includes("additional_rate_limits"))) { + try { candidates.push({ file, metadata: getQuotaMetadata(file.source) }); } + catch (error) { diagnostics.push(`${file.name}: ${error.message}`); } + } + if (!candidates.length) throw new Error(`OpenAI quota metadata not found; ${diagnostics.join("; ")}`); + const { file: initial, metadata } = unique(candidates, "OpenAI quota metadata bundle"); + const primary = unique(files.filter(file => file.name !== initial.name && + file.source.includes(`./${initial.name}`) && file.source.includes("submitDisabled") && + file.source.includes("resolvedConfig") && file.source.includes("isConfigDataPending")), + "Composer bundle"); + const result = patchSource(primary.source, metadata, `./${initial.name}`); + if (result.status === "error") throw new Error(result.reason); + const filePath = path.join(directory.path, primary.name); + console.log(` [${directory.platform}] ${relPath(filePath)}`); + if (result.status === "already") { + console.log(" [ok] Custom-provider quota patch already applied"); + } else { + for (const change of result.changes) console.log(` * ${change}`); + if (!check) { fs.writeFileSync(filePath, result.code, "utf8"); patched++; } + else console.log(" [?] dry-run; no file written"); + } + } catch (error) { + console.error(` [x] ${directory.platform}: ${error.message}`); + failed++; + } + } + if (!directories.length) { console.error(" [x] 缺少目标平台界面资源"); process.exitCode = 1; } + else if (failed) console.error(` [x] ${failed} platform(s) failed`); + else console.log(` [ok] ${patched} bundle(s) patched`); + if (failed) process.exitCode = 1; +} + +if (require.main === module) main(); +module.exports = { MARKER, getQuotaMetadata, patchSource }; diff --git a/scripts/patch-reading-layout.js b/scripts/patch-reading-layout.js new file mode 100644 index 00000000..d6aaba1b --- /dev/null +++ b/scripts/patch-reading-layout.js @@ -0,0 +1,121 @@ +#!/usr/bin/env node +/** 保留原生外观设置页,追加正文宽度偏好与限定作用域的排版样式。 */ +const fs = require("node:fs"); +const path = require("node:path"); +const { parse } = require("acorn"); +const { SRC_DIR } = require("./patch-util"); +const MODULE = "codex-rebuild-reading-width.js"; +const MARKER = "__CodexRebuildReadingWidth"; + +function walk(node, visit) { + if (!node || typeof node !== "object") return; + if (node.type) visit(node); + for (const value of Object.values(node)) { + if (Array.isArray(value)) value.forEach(child => walk(child, visit)); + else if (value?.type) walk(value, visit); + } +} +function key(node) { return node?.name ?? node?.value; } +function literal(node) { return node?.type === "Literal" ? node.value : node?.type === "TemplateLiteral" && !node.expressions.length ? node.quasis[0].value.cooked : null; } + +function patchDialogs(source) { + if (source.includes("codex-rebuild-dialog-default")) return source; + const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const functions = ast.body.filter(node => node.type === "FunctionDeclaration" && node.params.length === 1 && node.body.body.length === 1 + && node.body.body[0].type === "ReturnStatement" && ["narrow", "compact", "wide", "xwide", "xxwide", "editor"].every(value => source.slice(node.start, node.end).includes(`\`${value}\``)) + && source.slice(node.start, node.end).includes("w-[380px]")); + if (functions.length !== 1) throw new Error("原生对话框尺寸映射结构未知"); + const edits = [], seen = new Set(); + let branch = functions[0].body.body[0].argument; + while (branch.type === "ConditionalExpression") { + const name = literal(branch.test.right); + if (["narrow", "feature", "compact", "wide", "xwide", "xxwide", "editor"].includes(name)) { + const classes = literal(branch.consequent); + if (typeof classes !== "string" || !/(?:^|\s)w-(?:\[[^\]]+\]|[\w.]+)/.test(classes)) throw new Error(`对话框 ${name} 宽度结构未知`); + const replaced = classes.replace(/(?:^|\s)w-(?:\[[^\]]+\]|[\w.]+)/, ` codex-rebuild-dialog-${name}`).trim(); + edits.push({ start: branch.consequent.start, end: branch.consequent.end, text: JSON.stringify(replaced) }); seen.add(name); + } + branch = branch.alternate; + } + if (seen.size !== 7 || literal(branch) !== "w-130") throw new Error("原生默认对话框宽度结构未知"); + edits.push({ start: branch.start, end: branch.end, text: '"codex-rebuild-dialog-default"' }); + let patched = source; + for (const edit of edits.sort((a, b) => b.start - a.start)) patched = patched.slice(0, edit.start) + edit.text + patched.slice(edit.end); + parse(patched, { ecmaVersion: "latest", sourceType: "module" }); + return patched; +} + +function patchSettings(source) { + if (source.includes(MARKER)) { + if (!source.includes(MODULE) || !source.includes(`jsx)(${MARKER}`)) throw new Error("阅读布局标记不完整"); + return source; + } + const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const sections = ast.body.filter(node => node.type === "FunctionDeclaration" && source.slice(node.start, node.end).includes("settings.appearance.visualStyle")); + if (sections.length !== 1) throw new Error("原生外观设置分区结构未知"); + const section = sections[0], arrays = [], states = [], intlCalls = []; + walk(section, node => { + if (node.type === "ArrayExpression" && node.elements.some(element => element?.type === "CallExpression" && element.arguments[1]?.type === "ObjectExpression" + && element.arguments[1].properties.some(prop => key(prop.key) === "section" && literal(prop.value) === "visual"))) arrays.push(node); + if (node.type === "CallExpression" && node.callee.type === "SequenceExpression") { + const callee = node.callee.expressions.at(-1); + if (callee.type === "MemberExpression" && key(callee.property) === "useState") states.push(callee.object.name); + } + }); + if (arrays.length !== 1 || !states.length || new Set(states).size !== 1) throw new Error("外观设置 React/行结构未知"); + const child = arrays[0].elements.find(element => element?.type === "CallExpression" && element.arguments[1]?.properties?.some(prop => key(prop.key) === "section" && literal(prop.value) === "visual")); + const jsx = child.callee.expressions.at(-1).object.name; + const fonts = ast.body.filter(node => node.type === "FunctionDeclaration" && source.slice(node.start, node.end).includes("settings.appearance.uiFontSize.description")); + if (fonts.length !== 1) throw new Error("原生设置行结构未知"); + let row; + walk(fonts[0], node => { + if (node.type !== "CallExpression" || node.arguments[0]?.type !== "Identifier" || node.arguments[1]?.type !== "ObjectExpression") return; + const names = node.arguments[1].properties.map(prop => key(prop.key)); + if (["label", "description", "control"].every(name => names.includes(name))) row = node.arguments[0].name; + }); + // 从原生设置组件的 formatMessage 接收者,反向识别 useIntl 调用。 + const fontDeclarations = []; + walk(fonts[0], node => { if (node.type === "VariableDeclarator") fontDeclarations.push(node); }); + walk(fonts[0], node => { + if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && key(node.callee.property) === "formatMessage") { + const declaration = fontDeclarations.find(item => item.id.name === node.callee.object.name && item.init?.type === "CallExpression" && item.init.callee.type === "Identifier"); + if (declaration) intlCalls.push(declaration.init.callee.name); + } + }); + if (!row || !intlCalls.length || new Set(intlCalls).size !== 1) throw new Error("原生设置行/语言上下文未知"); + const at = arrays[0].end - 1; + const result = `import {renderReadingWidth as __renderCodexReadingWidth} from "./${MODULE}";\n` + + source.slice(0, at) + `,(0,${jsx}.jsx)(${MARKER},{})` + source.slice(at) + + `\nfunction ${MARKER}(){return __renderCodexReadingWidth(${states[0]},${jsx},${row},${intlCalls[0]}());}\n`; + parse(result, { ecmaVersion: "latest", sourceType: "module" }); + return result; +} + +function main() { + if (!process.argv.includes("win")) { console.log("[skip] Windows reading layout patch not applicable"); return; } + const directory = path.join(SRC_DIR, "win", "_asar", "webview", "assets"); + const files = fs.readdirSync(directory).filter(name => name.endsWith(".js")); + const settings = files.filter(name => /^general-settings-/.test(name) + && fs.readFileSync(path.join(directory, name), "utf8").includes("settings.appearance.visualStyle")); + if (settings.length !== 1) throw new Error("原生设置资源缺失或不唯一"); + const entry = files.filter(name => /^app-initial-/.test(name) && fs.readFileSync(path.join(directory, name), "utf8").includes("thread-content-responsive-max-width")); + if (entry.length !== 1) throw new Error("正文响应式宽度结构未知"); + const settingsPath = path.join(directory, settings[0]); + const settingsSource = fs.readFileSync(settingsPath, "utf8"), patched = patchSettings(settingsSource); + const entryPath = path.join(directory, entry[0]), source = fs.readFileSync(entryPath, "utf8"); + const loader = `import "./${MODULE}";\n`; + const entryPatched = source.includes(MODULE) ? source : loader + source; + parse(entryPatched, { ecmaVersion: "latest", sourceType: "module" }); + const dialogTargets = files.filter(name => /^app-shared-/.test(name) && fs.readFileSync(path.join(directory, name), "utf8").includes("codex-dialog")); + if (dialogTargets.length !== 1) throw new Error("原生对话框资源缺失或不唯一"); + const dialogPath = path.join(directory, dialogTargets[0]); + const dialogPatched = patchDialogs(fs.readFileSync(dialogPath, "utf8")); + if (process.argv.includes("--check")) { console.log("[ok] 原生外观设置/响应式正文结构已核对,8 档宽度及排版样式可注入"); return; } + fs.writeFileSync(settingsPath, patched); + fs.writeFileSync(entryPath, entryPatched); + fs.writeFileSync(dialogPath, dialogPatched); + fs.copyFileSync(path.join(__dirname, "runtime", "reading-width.mjs"), path.join(directory, MODULE)); + console.log("[ok] 已加入原生正文宽度设置、代码/表格宽度同步、对话框扩宽及粗体着色"); +} +if (require.main === module) main(); +module.exports = { patchSettings }; diff --git a/scripts/patch-test-isolation.js b/scripts/patch-test-isolation.js new file mode 100644 index 00000000..36f54c9c --- /dev/null +++ b/scripts/patch-test-isolation.js @@ -0,0 +1,84 @@ +#!/usr/bin/env node +/** Owl 入口前仅传入环境;官方 userData 设置后、单实例锁前挂载真实隔离检查。 */ +const fs = require("node:fs"); +const path = require("node:path"); +const { parse } = require("acorn"); +const { SRC_DIR } = require("./patch-util"); +const environmentModule = "codex-rebuild-test-environment.cjs"; +const isolationModule = "codex-rebuild-test-isolation.cjs"; +function walk(node, visit, parent) { + if (!node || typeof node !== "object") return; + if (node.type) visit(node, parent); + for (const value of Object.values(node)) { + if (Array.isArray(value)) value.forEach(child => walk(child, visit, node)); + else if (value?.type) walk(value, visit, node); + } +} +function literal(node) { return node?.type === "Literal" ? node.value : node?.type === "TemplateLiteral" && !node.expressions.length ? node.quasis[0].value.cooked : undefined; } +function astOf(source, moduleMode) { return parse(source, { ecmaVersion: "latest", sourceType: moduleMode ? "module" : "script", allowHashBang: true }); } +function main() { + if (!process.argv.includes("win")) { console.log("[skip] Windows test isolation patch not applicable"); return; } + const directory = path.join(SRC_DIR, "win", "_asar"); + const manifest = JSON.parse(fs.readFileSync(path.join(directory, "package.json"), "utf8")); + if (typeof manifest.main !== "string") throw new Error("上游缺少真实 main 入口"); + const entry = path.resolve(directory, manifest.main); + if (!entry.startsWith(directory + path.sep)) throw new Error("上游入口逃出 ASAR 目录"); + const mode = file => file.endsWith(".mjs") || !file.endsWith(".cjs") && manifest.type === "module"; + const entrySource = fs.readFileSync(entry, "utf8"), entryAst = astOf(entrySource, mode(entry)); + const environmentLoader = mode(entry) ? `import "./${environmentModule}";` : `require("./${environmentModule}");`; + const first = entryAst.body.find(node => !node.directive); + const edits = new Map(); + const add = (file, edit) => { const list = edits.get(file) || []; list.push(edit); edits.set(file, list); }; + if (entrySource.includes("Desktop network requirements prevented startup") && !entrySource.includes("native-startup-error.json")) { + const catches = []; + walk(entryAst, node => { + if (node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement" && sourceOf(node).includes("Desktop network requirements prevented startup")) catches.push(node); + }); + function sourceOf(node) { return entrySource.slice(node.start, node.end); } + if (catches.length !== 1 || catches[0].params[0]?.type !== "Identifier" || mode(entry)) throw new Error("官方启动失败处理结构未知"); + const error = catches[0].params[0].name; + add(entry, { at: catches[0].body.start + 1, text: `if(process.env.CODEX_REBUILD_SMOKE_EXIT==="1"&&process.env.CODEX_REBUILD_TEST_ROOT){try{require("node:fs").writeFileSync(require("node:path").join(process.env.CODEX_REBUILD_TEST_ROOT,"native-startup-error.json"),JSON.stringify({message:${error}?.message??String(${error}),stack:${error}?.stack,cause:${error}?.cause?.message}));}catch{}}` }); + } + if (!entrySource.includes(environmentModule)) { + if (entrySource.includes(isolationModule)) throw new Error("旧隔离模块仍位于最早入口,请从原始官方资源重新应用"); + const directives = entryAst.body.filter(node => node.directive); + const offset = Math.max(entrySource.startsWith("#!") ? entrySource.indexOf("\n") + 1 : 0, ...directives.map(node => node.end)); + add(entry, { at: offset, text: `\n${environmentLoader}\n` }); + } else if (!first || entrySource.slice(first.start, first.end) !== environmentLoader) throw new Error("隔离环境入口位置异常"); + const targets = []; + const build = path.dirname(entry); + for (const name of fs.readdirSync(build).filter(name => /\.(?:js|cjs|mjs)$/.test(name))) { + if ([environmentModule, isolationModule].includes(name)) continue; + const file = path.join(build, name), source = fs.readFileSync(file, "utf8"); + if (!source.includes("CODEX_ELECTRON_USER_DATA_PATH") || !source.includes("requestSingleInstanceLock")) continue; + const ast = astOf(source, mode(file)), calls = [], locks = []; + walk(ast, (node, parent) => { + if (node.type !== "CallExpression" || node.callee.type !== "MemberExpression") return; + if (node.callee.property.name === "setPath" && literal(node.arguments[0]) === "userData" && node.arguments[1]?.type === "CallExpression") calls.push({ node, parent }); + if (node.callee.property.name === "requestSingleInstanceLock") locks.push(node); + }); + if (calls.length !== 1 || calls[0].parent.type !== "SequenceExpression") throw new Error(`官方 User Data 初始化结构未知:${name}`); + const call = calls[0].node; + const startupLocks = locks.filter(lock => lock.start > call.end && ast.body.some(statement => statement.type === "IfStatement" && statement.start <= lock.start && statement.end >= lock.end) + || lock.start > call.end && ast.body.some(statement => statement.type === "ExpressionStatement" && statement.start <= lock.start && statement.end >= lock.end)); + if (startupLocks.length !== 1) throw new Error("官方启动单实例锁缺失或不唯一"); + const resolver = ast.body.find(node => node.type === "FunctionDeclaration" && node.id.name === call.arguments[1].callee.name); + if (!resolver || !source.slice(resolver.start, resolver.end).includes("CODEX_ELECTRON_USER_DATA_PATH")) throw new Error("官方 User Data 环境解析结构未知"); + const hook = mode(file) ? `await import("./${isolationModule}")` : `require("./${isolationModule}")`; + if (!source.includes(isolationModule)) add(file, { at: call.end, text: `,${hook}` }); + else if (!source.slice(call.end).startsWith(`,${hook}`)) throw new Error("隔离模块未紧邻官方 User Data 设置"); + targets.push(file); + } + if (targets.length !== 1) throw new Error("官方 bootstrap 隔离挂载点缺失或不唯一"); + const patched = new Map(); + for (const [file, list] of edits) { + let source = fs.readFileSync(file, "utf8"); + for (const edit of list.sort((a,b) => b.at-a.at)) source = source.slice(0,edit.at)+edit.text+source.slice(edit.at); + astOf(source, mode(file)); patched.set(file, source); + } + if (process.argv.includes("--check")) { console.log(`[ok] Owl 环境入口及官方 bootstrap/单实例锁前挂载点已核对:${path.basename(targets[0])}`); return; } + for (const [file, source] of patched) fs.writeFileSync(file, source); + for (const name of [environmentModule, isolationModule]) fs.copyFileSync(path.join(__dirname, "runtime", name.replace("codex-", "")), path.join(build, name)); + console.log("[ok] 入口传入隔离环境;官方 userData 初始化后验证路径、配置 sessionData,先于单实例锁"); +} +if (require.main === module) main(); diff --git a/scripts/patch-updater.js b/scripts/patch-updater.js index 1ea39362..89212cc7 100644 --- a/scripts/patch-updater.js +++ b/scripts/patch-updater.js @@ -68,6 +68,25 @@ function collectPatches(ast, source) { return patches; } +// 独立后置检查:没有目标和不认识的函数体不能当成更新已关闭。 +function auditUpdaterSource(source) { + const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const methods = []; + walk(ast, (node) => { + if (!["Property", "MethodDefinition", "FunctionDeclaration"].includes(node.type)) return; + const name = node.key?.name || node.key?.value || node.id?.name; + if (!UPDATER_METHODS.has(name)) return; + const body = node.type === "FunctionDeclaration" ? node.body : node.value?.body; + const statement = body?.type === "BlockStatement" && body.body.length === 1 ? body.body[0] : null; + const result = statement?.type === "ReturnStatement" ? statement.argument : null; + const disabled = result?.type === "Literal" && result.value === false + || result?.type === "UnaryExpression" && result.operator === "!" + && result.argument?.type === "Literal" && result.argument.value === 1; + methods.push({ name, disabled: Boolean(disabled) }); + }); + return methods; +} + function locateTargets(platform) { const platforms = platform ? [platform] @@ -83,10 +102,7 @@ function locateTargets(platform) { if (!f.endsWith(".js")) continue; const fp = path.join(buildDir, f); const src = fs.readFileSync(fp, "utf-8"); - if ( - src.includes("shouldIncludeSparkle") && - src.includes("shouldIncludeUpdater") - ) { + if ([...UPDATER_METHODS].some((name) => src.includes(name))) { targets.push({ platform: plat, path: fp }); } } @@ -101,7 +117,7 @@ function main() { const targets = locateTargets(platform); if (targets.length === 0) { - console.log(" [ok] No updater targets found"); + console.log(" [!] No updater targets found; updater state needs review"); return; } @@ -112,7 +128,12 @@ function main() { const patches = collectPatches(ast, source); if (patches.length === 0) { - console.log(" [ok] Already patched or no match"); + const methods = auditUpdaterSource(source); + console.log(methods.length === 0 + ? " [ok] Updater call sites only; this bundle defines no gates" + : methods.every((method) => method.disabled) + ? " [ok] Updater methods are explicitly disabled" + : " [!] No supported updater method matched; updater state needs review"); continue; } @@ -133,4 +154,6 @@ function main() { } } -main(); +if (require.main === module) main(); + +module.exports = { auditUpdaterSource }; diff --git a/scripts/reading-layout-smoke.js b/scripts/reading-layout-smoke.js new file mode 100644 index 00000000..83a52bd8 --- /dev/null +++ b/scripts/reading-layout-smoke.js @@ -0,0 +1,37 @@ +#!/usr/bin/env node +/** 在现有浏览器验证阅读运行模块;模拟官方 CSS 变量契约,不冒充完整 Electron 验收。 */ +const http = require("node:http"); +const fs = require("node:fs"); +const path = require("node:path"); +const html = `阅读布局功能验证 + + +

阅读布局功能验证

模拟官方布局契约,执行真实阅读偏好模块;完整设置页面仍需候选 GUI 验收。

运行中
+
粗体内容
代码块
表格
输入区域
对话框
+`; +const server = http.createServer((req,res)=>{ + res.setHeader("Cache-Control", "no-store"); + if(req.url === "/reading-width.mjs"){res.setHeader("Content-Type","text/javascript; charset=utf-8");res.end(fs.readFileSync(path.join(__dirname,"runtime","reading-width.mjs")));} + else{res.setHeader("Content-Type","text/html; charset=utf-8");res.end(html);} +}); +server.listen(Number(process.env.REBUILD_SMOKE_PORT || 0),"127.0.0.1",()=>console.log(`Reading smoke: http://127.0.0.1:${server.address().port}/`)); diff --git a/scripts/runtime/reading-width.mjs b/scripts/runtime/reading-width.mjs new file mode 100644 index 00000000..a5d84f9d --- /dev/null +++ b/scripts/runtime/reading-width.mjs @@ -0,0 +1,73 @@ +// 只保存阅读布局偏好,认证、Provider 与任务配置由原程序管理。 +export const WIDTHS = ["default", "800", "960", "1120", "1280", "1440", "1600", "full"]; +export const STORAGE_KEY = "codex-rebuild:reading-width:v1"; +const STYLE_ID = "codex-rebuild-reading-style"; +let installed = false; + +export function readingCss(value) { + if (!WIDTHS.includes(value)) throw new Error("未知的正文宽度档位"); + const width = value === "full" ? "100%" : `${value}px`; + const selected = value === "default" ? "" : `html[data-codex-rebuild-reading-width] body{--thread-content-max-width:${width};--thread-content-expanded-max-width:${width};--thread-content-compact-max-width:${width}}`; + return `${selected} +[data-selected-text-overlay-target]{--markdown-wide-block-max-width:var(--thread-content-max-width,100%)} +:is([data-codex-window-type=browser],[data-codex-window-type=chrome-extension],[data-codex-window-type=electron]) [data-selected-text-overlay-target] strong{color:var(--color-token-charts-green,var(--green-500,#00a240))} +${Object.entries({ narrow: 520, feature: 600, compact: 640, wide: 800, xwide: 860, xxwide: 1040, editor: 800, default: 720 }).map(([name, size]) => `.codex-dialog.codex-rebuild-dialog-${name}{width:min(${size}px,calc(100vw / var(--codex-window-zoom,1) - 32px));max-width:calc(100vw / var(--codex-window-zoom,1) - 32px)}`).join("\n")} +`; +} + +function preference() { + const value = localStorage.getItem(STORAGE_KEY) ?? "default"; + if (!WIDTHS.includes(value)) throw new Error("正文宽度设置无效,请重新选择"); + return value; +} + +function apply(value) { + let style = document.getElementById(STYLE_ID); + if (!style) { style = document.createElement("style"); style.id = STYLE_ID; document.head.append(style); } + style.textContent = readingCss(value); + document.documentElement.dataset.codexRebuildReadingWidth = value; +} + +export function installReadingStyle() { + if (installed || typeof document === "undefined") return; + installed = true; + try { apply(preference()); } catch (error) { console.error("[rebuild-reading]", error.message); apply("default"); } + window.addEventListener("storage", event => { + if (event.key !== STORAGE_KEY && event.key !== null) return; + try { apply(preference()); window.dispatchEvent(new Event("codex-rebuild-reading-change")); } + catch (error) { console.error("[rebuild-reading]", error.message); } + }); +} + +export function renderReadingWidth(react, ui, Row, intl) { + const chinese = String(intl.locale).startsWith("zh"); + const [value, setValue] = react.useState(() => { try { return preference(); } catch { return "default"; } }); + const [error, setError] = react.useState(() => { try { preference(); return ""; } catch (error) { return error.message; } }); + react.useEffect(() => { + const update = () => { try { setValue(preference()); setError(""); } catch (error) { setError(error.message); } }; + window.addEventListener("codex-rebuild-reading-change", update); + return () => window.removeEventListener("codex-rebuild-reading-change", update); + }, []); + return ui.jsx(Row, { + label: chinese ? "聊天正文宽度" : "Chat content width", + description: error || (chinese ? "正文、输入区域及代码块/表格同步调整,窗口较窄时自动收缩。" : "Adjust chats, composer and wide blocks; shrink to fit smaller windows."), + control: ui.jsxs("select", { + "aria-label": chinese ? "聊天正文宽度" : "Chat content width", + "data-codex-rebuild-width-control": "true", + className: "rounded-md border border-default bg-surface px-3 py-1.5 text-sm text-default", + value, + onChange: event => { + const next = event.currentTarget.value; + try { + if (!WIDTHS.includes(next)) throw new Error("未知的正文宽度档位"); + localStorage.setItem(STORAGE_KEY, next); apply(next); setValue(next); setError(""); + window.dispatchEvent(new Event("codex-rebuild-reading-change")); + } catch (error) { setError(error.message); } + }, + children: WIDTHS.map(option => ui.jsx("option", { value: option, + children: option === "default" ? (chinese ? "默认" : "Default") : option === "full" ? (chinese ? "全宽" : "Full width") : `${option} ${chinese ? "像素" : "px"}` }, option)), + }), + }); +} + +installReadingStyle(); diff --git a/scripts/runtime/rebuild-test-environment.cjs b/scripts/runtime/rebuild-test-environment.cjs new file mode 100644 index 00000000..9dcfdaac --- /dev/null +++ b/scripts/runtime/rebuild-test-environment.cjs @@ -0,0 +1,20 @@ +// Owl 的入口前阶段只设置环境;Electron 路径 API 要等原生 bootstrap 初始化。 +if (process.env.CODEX_REBUILD_TEST_ROOT) { + const fs = require("node:fs"), path = require("node:path"); + const root = process.env.CODEX_REBUILD_TEST_ROOT; + if (!path.isAbsolute(root)) throw new Error("验收数据根目录必须是绝对路径"); + process.on("uncaughtExceptionMonitor", error => { + try { fs.writeFileSync(path.join(root, "startup-error.json"), JSON.stringify({ message: error.message, stack: error.stack })); } catch {} + }); + for (const [key, name] of [["CODEX_HOME", "codex-home"], ["CODEX_ELECTRON_USER_DATA_PATH", "electron-user-data"]]) { + const directory = path.join(path.resolve(root), name); + fs.mkdirSync(directory, { recursive: true }); process.env[key] = directory; + } + if (process.env.CODEX_REBUILD_SMOKE_EXIT === "1") { + const record = (name, value) => fs.writeFileSync(path.join(root, name), JSON.stringify(value)); + record("test-environment.json", { pid: process.pid, codexHome: process.env.CODEX_HOME, userData: process.env.CODEX_ELECTRON_USER_DATA_PATH }); + const app = require("electron").app, exit = app.exit; + app.exit = function(code) { record("app-exit.json", { code, stack: new Error("app.exit caller").stack }); return exit.call(app, code); }; + process.on("exit", code => record("process-exit.json", { code })); + } +} diff --git a/scripts/runtime/rebuild-test-isolation.cjs b/scripts/runtime/rebuild-test-isolation.cjs new file mode 100644 index 00000000..eefe7be3 --- /dev/null +++ b/scripts/runtime/rebuild-test-isolation.cjs @@ -0,0 +1,60 @@ +// 仅在独立验收启动器显式给出测试根目录时生效。 +const testRoot = process.env.CODEX_REBUILD_TEST_ROOT; +if (testRoot) { + const fs = require("node:fs"); + const path = require("node:path"); + const { app } = require("electron"); + if (!path.isAbsolute(testRoot)) throw new Error("验收数据根目录必须是绝对路径"); + const root = path.resolve(testRoot); + const codexHome = path.join(root, "codex-home"); + const userData = path.join(root, "electron-user-data"); + fs.mkdirSync(codexHome, { recursive: true }); + fs.mkdirSync(userData, { recursive: true }); + process.env.CODEX_HOME = codexHome; + process.env.CODEX_ELECTRON_USER_DATA_PATH = userData; + fs.writeFileSync(path.join(root, "isolation-hook.json"), JSON.stringify({ pid: process.pid, stage: "native-user-data-set", actualUserData: app.getPath("userData") })); + if (path.resolve(app.getPath("userData")) !== userData) throw new Error("官方 bootstrap 未采用验收 User Data,停止启动"); + app.setPath("sessionData", userData); + if (process.env.CODEX_REBUILD_SMOKE_EXIT === "1") { + const proof = { pid: process.pid, startedAt: new Date().toISOString(), windowLoaded: false }; + const save = () => fs.writeFileSync(path.join(root, "desktop-smoke.json"), JSON.stringify(proof, null, 2)); + app.on("browser-window-created", (_event, window) => { + window.webContents.once("did-finish-load", async () => { + const bounds = window.getBounds(); + if (bounds.width < 300 || bounds.height < 200) return; + // HTML 加载事件不等于 React 可用;等待真实阅读模块和可见 UI 控件。 + try { + const deadline = Date.now() + 30000; + while (Date.now() < deadline && !window.isDestroyed()) { + const renderer = await window.webContents.executeJavaScript('({readingStyle:!!document.getElementById("codex-rebuild-reading-style"),controls:document.querySelectorAll("button,input,[role=button]").length,textLength:document.body?.innerText.trim().length||0})'); + if (renderer.readingStyle && renderer.controls > 0 && renderer.textLength > 0) { + Object.assign(proof, { windowLoaded: true, loadedAt: new Date().toISOString(), url: window.webContents.getURL(), renderer }); + save(); setTimeout(() => app.quit(), 1500); return; + } + await new Promise(resolve => setTimeout(resolve, 500)); + } + proof.failure = "窗口 HTML 已加载,但阅读模块/真实 UI 控件未就绪"; save(); + } catch (error) { proof.failure = error.message; save(); } + }); + window.webContents.on("did-fail-load", (_event, code, description, _url, mainFrame) => { + if (!mainFrame || code === -3) return; + proof.failure = `${code}: ${description}`; save(); + }); + window.webContents.on("render-process-gone", (_event, details) => { proof.failure = details.reason; save(); }); + }); + save(); + } + app.whenReady().then(() => { + const actual = app.getPath("userData"); + if (path.resolve(actual) !== userData || path.resolve(process.env.CODEX_HOME) !== codexHome) { + console.error("[rebuild-isolation] 启动后数据目录被其他逻辑改写,停止验收"); + app.exit(1); + return; + } + fs.writeFileSync(path.join(root, "isolation-runtime.json"), JSON.stringify({ + schemaVersion: 1, pid: process.pid, recordedAt: new Date().toISOString(), + executable: process.execPath, codexHome, userData: actual, sessionData: app.getPath("sessionData"), + note: "Electron 路径已核实;单实例锁与 Owl 外层行为仍需 GUI 验证", + }, null, 2) + "\n"); + }); +} diff --git a/scripts/sync-upstream.js b/scripts/sync-upstream.js index dab0742e..f5763659 100644 --- a/scripts/sync-upstream.js +++ b/scripts/sync-upstream.js @@ -22,6 +22,7 @@ const http = require("http"); const fs = require("fs"); const path = require("path"); const { execSync, execFileSync } = require("child_process"); +const { verifySourceFile, writeJson } = require("./windows-artifacts"); // TLS certs for MS delivery CDN const certsDir = path.join(__dirname, "certs"); @@ -34,7 +35,9 @@ https.globalAgent.options.ca = extraCAs; const PROJECT_ROOT = path.resolve(__dirname, ".."); const SRC_DIR = path.join(PROJECT_ROOT, "src"); -const TEMP_DIR = path.join(require("os").tmpdir(), "codex-sync"); +const TEMP_DIR = process.env.CODEX_SYNC_DIR + ? path.resolve(process.env.CODEX_SYNC_DIR) + : path.join(require("os").tmpdir(), "codex-sync"); const VERSION_FILE = path.join(__dirname, ".versions.json"); const APPCAST_ARM64 = "https://persistent.oaistatic.com/codex-app-prod/appcast.xml"; @@ -339,13 +342,15 @@ async function getAppcastVersion(url) { }; } -async function getWindowsVersion() { +async function getWindowsVersion(expectedVersion) { const msstore = require("./fetch-msstore"); const cookie = await msstore.getCookie(); const info = await msstore.getAppInfo("9plm9xgg6vks", "US"); if (!info.categoryId) throw new Error("No CategoryID"); const pkgs = await msstore.getFileList(cookie, info.categoryId, "Retail"); - const pkg = selectWindowsPackage(pkgs); + const pkg = selectWindowsPackage(expectedVersion + ? pkgs.filter((item) => item.name.startsWith(`OpenAI.Codex_${expectedVersion}_x64__`)) + : pkgs); const url = await msstore.getDownloadUrl(pkg.updateID, pkg.revisionNumber, "Retail", pkg.digest); if (!url) throw new Error(`No download URL for Windows x64 package: ${pkg.name}`); const verMatch = pkg.name.match(/_(\d+\.\d+\.\d+(?:\.\d+)?)_/); @@ -355,13 +360,22 @@ async function getWindowsVersion() { url, packageName: pkg.name, architecture: WINDOWS_TARGET_ARCH, + size: Number(pkg.size), + storeDigest: pkg.digest, }; } function selectWindowsPackage(pkgs) { - const pkg = pkgs.find(({ name }) => + const pkg = pkgs.filter(({ name }) => typeof name === "string" && WINDOWS_X64_MSIX_RE.test(name) - ); + ).sort((left, right) => { + const a = left.name.match(/_(\d+(?:\.\d+){2,3})_/)[1].split(".").map(Number); + const b = right.name.match(/_(\d+(?:\.\d+){2,3})_/)[1].split(".").map(Number); + for (let index = 0; index < 4; index++) { + if ((a[index] || 0) !== (b[index] || 0)) return (b[index] || 0) - (a[index] || 0); + } + return left.name.localeCompare(right.name); + })[0]; if (pkg) return pkg; @@ -450,12 +464,17 @@ async function syncWin(destDir, info) { const msixPath = path.join(TEMP_DIR, info.packageName || `codex-win-${info.version}.msix`); const extractDir = path.join(TEMP_DIR, "win-extract"); - if (!fs.existsSync(msixPath)) { + if (info.localPackage) { + await verifySourceFile(info, info.localPackage); + if (path.resolve(info.localPackage) !== path.resolve(msixPath)) fs.copyFileSync(info.localPackage, msixPath); + } else if (!fs.existsSync(msixPath)) { curlDownload(info.url, msixPath, "Windows MSIX"); } else { console.log(` [cache] ${msixPath}`); } + if (info.sha256) await verifySourceFile(info, msixPath); + console.log(" [unzip]"); clearDir(extractDir); extractArchive(msixPath, extractDir); @@ -470,6 +489,7 @@ async function syncWin(destDir, info) { } assembleOutput(resourcesDir, destDir, "Windows"); + if (info.sha256) writeJson(path.join(extractDir, "verified-windows-source.json"), info); return info; } @@ -586,6 +606,8 @@ async function main() { } module.exports = { + getWindowsVersion, + syncWin, readWindowsPackageIdentity, selectWindowsPackage, validateWindowsPackage, diff --git a/scripts/windows-artifacts.js b/scripts/windows-artifacts.js new file mode 100644 index 00000000..c1fe1faa --- /dev/null +++ b/scripts/windows-artifacts.js @@ -0,0 +1,43 @@ +const fs = require("node:fs"); +const path = require("node:path"); +const crypto = require("node:crypto"); + +function writeJson(file, value) { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, JSON.stringify(value, null, 2) + "\n", "utf8"); +} + +async function sha256(file) { + const hash = crypto.createHash("sha256"); + for await (const chunk of fs.createReadStream(file)) hash.update(chunk); + return hash.digest("hex"); +} + +function validateSource(source) { + if (source.schemaVersion !== 1 || source.architecture !== "x64" + || !/^\d+(?:\.\d+){3}$/.test(source.version) + || source.packageName !== path.basename(source.packageName || "") + || !/^OpenAI\.Codex_\d+(?:\.\d+){3}_x64__[\w]+\.msix$/.test(source.packageName || "") + || !source.packageName.startsWith(`OpenAI.Codex_${source.version}_x64__`) + || !/^[a-f0-9]{64}$/.test(source.sha256 || "") + || !Number.isSafeInteger(source.size) || source.size <= 0) { + throw new Error("固定 Windows 来源记录无效,请纠正版本、主包名、架构、大小或 SHA-256"); + } + return source; +} + +async function verifySourceFile(source, file) { + validateSource(source); + if (fs.statSync(file).size !== source.size || await sha256(file) !== source.sha256) { + throw new Error(`官方包内容校验失败,禁止使用缓存:${source.packageName}`); + } +} + +function confinedFile(directory, name) { + if (!name || path.basename(name) !== name || /[\\/]/.test(name) || name === "." || name === "..") { + throw new Error("制品文件名必须位于候选目录内"); + } + return path.join(directory, name); +} + +module.exports = { writeJson, sha256, validateSource, verifySourceFile, confinedFile }; diff --git a/scripts/windows-maintenance.js b/scripts/windows-maintenance.js new file mode 100644 index 00000000..58273809 --- /dev/null +++ b/scripts/windows-maintenance.js @@ -0,0 +1,335 @@ +#!/usr/bin/env node +/** Windows 候选链:固定输入、诊断出包与正式晋升校验。 */ +const fs = require("node:fs"); +const path = require("node:path"); +const os = require("node:os"); +const crypto = require("node:crypto"); +const { execFileSync, spawn } = require("node:child_process"); +const { writeJson, sha256, validateSource, verifySourceFile, confinedFile } = require("./windows-artifacts"); +const root = path.resolve(__dirname, ".."); +const requiredChecks = [ + "isolation", "start-exit", "authentication", "thread-history", "provider-switch", + "model-catalog", "compaction", "archive-delete", "browser-auth", "plugins-skills", + "worker-config", "updater-disabled", "program-rollback", "data-restore", "reading-layout", +]; + +function readJson(file) { return JSON.parse(fs.readFileSync(file, "utf8")); } +function argsOf(args) { + const options = {}; + for (let i = 0; i < args.length; i += 2) { + if (!args[i].startsWith("--") || !args[i + 1] || args[i + 1].startsWith("--")) { + throw new Error(`无效参数:${args[i]}`); + } + options[args[i].slice(2)] = args[i + 1]; + } + return options; +} + +function runScript(name, args = [], env = {}) { + execFileSync(process.execPath, [path.join(__dirname, name), ...args], { + cwd: root, env: { ...process.env, ...env }, stdio: "inherit", + }); +} + +function output(name, value) { + console.log(`${name}=${value}`); + if (process.env.GITHUB_OUTPUT) fs.appendFileSync(process.env.GITHUB_OUTPUT, `${name}=${value}\n`); +} + +async function discover(options) { + const { getWindowsVersion } = require("./sync-upstream"); + const info = await getWindowsVersion(options.version); + if (!Number.isSafeInteger(info.size) || info.size <= 0 || !info.storeDigest) { + throw new Error("Store 没有提供可验证的包大小或摘要"); + } + writeJson(path.resolve(options.out || ".cache/windows-discovery.json"), { + schemaVersion: 1, ...info, checkedAt: new Date().toISOString(), + }); + let approvedVersion = ""; + if (options["stable-manifest"]) { + const prior = readJson(options["stable-manifest"]); + if (prior.schemaVersion !== 1 || !/^\d+(?:\.\d+){3}$/.test(prior.upstream?.version || "")) { + throw new Error("历史候选版本记录无效,不能据此跳过构建"); + } + approvedVersion = prior.upstream.version; + } + output("version", info.version); + output("has_update", String(info.version !== approvedVersion)); +} + +async function verifyStoreDigest(file, expected) { + // Windows Update File/Digest 是 SHA-1;未知格式明确拒绝,不能跳过校验。 + const bytes = Buffer.from(expected, "base64"); + if (bytes.length !== 20) throw new Error("未知 Store 摘要格式,需要核对来源接口"); + const hash = crypto.createHash("sha1"); + for await (const chunk of fs.createReadStream(file)) hash.update(chunk); + if (!hash.digest().equals(bytes)) throw new Error("下载文件与 Store 摘要不符"); +} + +async function prepareSource(options, directory) { + if (options.source) { + const source = validateSource(readJson(path.resolve(options.source))); + const file = options.msix ? path.resolve(options.msix) + : confinedFile(path.dirname(path.resolve(options.source)), source.packageName); + await verifySourceFile(source, file); + const destination = confinedFile(directory, source.packageName); + if (path.resolve(file) !== path.resolve(destination)) fs.copyFileSync(file, destination); + writeJson(path.join(directory, "upstream.json"), source); + return source; + } + if (!options.discovery) throw new Error("候选需要 --discovery,或 --source 加已归档的 MSIX"); + const discovery = readJson(path.resolve(options.discovery)); + const file = confinedFile(directory, discovery.packageName); + const url = new URL(discovery.url); + if (discovery.architecture !== "x64" || !["http:", "https:"].includes(url.protocol) + || !/(^|\.)delivery\.mp\.microsoft\.com$/i.test(url.hostname)) { + throw new Error("下载来源必须是微软官方 Windows Update CDN 的 x64 主包"); + } + execFileSync("curl.exe", ["--fail", "--location", "--retry", "3", "--retry-delay", "2", + "--connect-timeout", "30", "--max-time", "900", "--output", file, discovery.url], { stdio: "inherit" }); + if (fs.statSync(file).size !== discovery.size) throw new Error("MSIX 下载大小不符"); + await verifyStoreDigest(file, discovery.storeDigest); + const source = validateSource({ ...discovery, sha256: await sha256(file) }); + writeJson(path.join(directory, "upstream.json"), source); + return source; +} + +function inspectUpdater(asarRoot) { + const { auditUpdaterSource } = require("./patch-updater"); + const directory = path.join(asarRoot, ".vite", "build"); + const methods = []; + for (const name of fs.readdirSync(directory).filter((name) => name.endsWith(".js"))) { + const source = fs.readFileSync(path.join(directory, name), "utf8"); + if (!/shouldInclude(?:Sparkle|WindowsUpdater|WindowsMsixUpdater|Updater)/.test(source)) continue; + methods.push(...auditUpdaterSource(source).map((method) => ({ file: name, ...method }))); + } + const windowsMethods = methods.filter((method) => method.name !== "shouldIncludeSparkle"); + return { methods, disabled: windowsMethods.length > 0 && windowsMethods.every((method) => method.disabled) }; +} + +function saveCompatibilityEvidence(asarRoot, source) { + const destination = path.join(root, "patch-reports", "source-evidence"); + const signatures = ["shouldIncludeUpdater", "shouldIncludeWindowsUpdater", "shouldIncludeWindowsMsixUpdater", + "FlyoutSubmenuItem", "flyoutHeader", "data-model-picker-model-row", "data-model-picker-view", "modelListConfig"]; + const files = []; + for (const [label, directory] of [["main", ".vite/build"], ["webview", "webview/assets"]]) { + const sourceDirectory = path.join(asarRoot, directory); + for (const name of fs.readdirSync(sourceDirectory).filter((name) => /\.(?:js|css)$/.test(name))) { + const file = path.join(sourceDirectory, name); + const text = fs.readFileSync(file, "utf8"); + const matches = [...signatures, "settings.appearance.visualStyle", "--thread-content-expanded-max-width", "--markdown-wide-block-max-width"] + .filter((signature) => text.includes(signature)); + const startupEvidence = label === "main" && /^(?:early-bootstrap|startup-requirements|application-network-startup)/.test(name); + if (!matches.length && !startupEvidence) continue; + const copied = label === "main" ? require("./patch-updater").auditUpdaterSource(text).length > 0 + : matches.includes("flyoutHeader") || matches.includes("data-model-picker-model-row") + || matches.includes("data-model-picker-view") && matches.includes("modelListConfig"); + const readingEvidence = matches.includes("settings.appearance.visualStyle") || name.endsWith(".css") && matches.some(match => match.startsWith("--")); + if (copied || readingEvidence || startupEvidence) { + fs.mkdirSync(path.join(destination, label), { recursive: true }); + fs.copyFileSync(file, path.join(destination, label, name)); + } + files.push({ directory, name, matches, copied: copied || readingEvidence || startupEvidence, sha256: crypto.createHash("sha256").update(text).digest("hex") }); + } + } + writeJson(path.join(destination, "index.json"), { schemaVersion: 1, upstream: source, files, + note: "原始官方资源片段,不含用户配置;用于精确适配,不能代表 GUI 已验收" }); +} + +function releaseGate(check, apply, updater) { + const blocks = []; + for (const report of [check, apply]) { + if (!report.canBuild || report.errors.length) blocks.push(`${report.mode}: 补丁执行失败`); + for (const item of report.results) { + if (!item.required) continue; + if (item.status !== "passed" || item.noticeSummary?.some((notice) => notice.kind === "review")) { + blocks.push(`${report.mode}/${item.script}: 必要补丁失败或待核对`); + } + } + } + if (!updater.disabled) blocks.push("Windows 更新关闭状态尚未证实"); + return { canPromote: blocks.length === 0, blocks }; +} + +async function cliHandshake(cli, codexHome) { + return new Promise((resolve, reject) => { + const child = spawn(cli, ["app-server"], { + env: { ...process.env, CODEX_HOME: codexHome }, windowsHide: true, stdio: ["pipe", "pipe", "pipe"], + }); + let buffer = "", stderr = "", settled = false; + const finish = (error, result) => { + if (settled) return; + settled = true; + clearTimeout(timeout); + child.kill(); + if (error) reject(error); else resolve(result); + }; + const timeout = setTimeout(() => finish(new Error(`app-server 握手超时:${stderr.slice(-1000)}`)), 30000); + child.on("error", (error) => finish(error)); + child.stdin.on("error", (error) => finish(error)); + child.on("exit", (code) => { if (!settled) finish(new Error(`app-server 提前退出:${code}; ${stderr.slice(-1000)}`)); }); + child.stderr.on("data", (chunk) => { stderr = (stderr + chunk).slice(-8000); }); + child.stdout.on("data", (chunk) => { + buffer += chunk; + let newline; + while ((newline = buffer.indexOf("\n")) >= 0) { + const line = buffer.slice(0, newline); buffer = buffer.slice(newline + 1); + let message; + try { message = JSON.parse(line); } catch { continue; } + if (message.id !== 1) continue; + if (message.error || !message.result) finish(new Error(`app-server 初始化失败:${line}`)); + else { + child.stdin.write(JSON.stringify({ method: "initialized" }) + "\n"); + finish(null, { passed: true, result: message.result }); + } + } + }); + child.stdin.write(JSON.stringify({ id: 1, method: "initialize", params: { + clientInfo: { name: "codex-rebuild-smoke", version: "1.0.0" }, capabilities: { experimentalApi: true }, + } }) + "\n"); + }); +} + +async function inspectOutput(appDirectory, source, reports, directory) { + const { inspectComponents, inspectDesktop } = require("./windows-runtime-checks"); + const { findUpstreamCodex } = require("./codex-binary-policy"); + const { computeAsarHeaderHash } = require("./build-from-upstream"); + const resources = path.join(appDirectory, "resources"); + const asar = path.join(resources, "app.asar"); + const cli = findUpstreamCodex("win", resources, "codex.exe"); + if (!cli || !fs.existsSync(path.join(appDirectory, "Codex.exe"))) throw new Error("产物缺少 launcher 或官方 CLI"); + const cliSource = findUpstreamCodex("win", path.join(root, "src", "win"), "codex.exe"); + if (!cliSource || await sha256(cli) !== await sha256(cliSource)) throw new Error("官方 CLI 被替换或损坏"); + const codexHome = path.join(directory, "cli-smoke-home"); + fs.mkdirSync(codexHome, { recursive: true }); + const cliVersion = execFileSync(cli, ["--version"], { + env: { ...process.env, CODEX_HOME: codexHome }, encoding: "utf8", timeout: 30000, windowsHide: true, + }).trim(); + const handshake = await cliHandshake(cli, codexHome); + const headerHash = computeAsarHeaderHash(asar); + const executables = ["Codex.exe", "ChatGPT.exe"].filter((name) => fs.existsSync(path.join(appDirectory, name))); + const integrityHashEmbedded = executables.some((name) => fs.readFileSync(path.join(appDirectory, name)).includes(Buffer.from(headerHash))); + const signatures = JSON.parse(execFileSync("pwsh", ["-NoProfile", "-Command", + "$items=@(Get-ChildItem -LiteralPath $env:REBUILD_APP_PATH -Filter '*.exe' -File | ForEach-Object { $s=Get-AuthenticodeSignature -LiteralPath $_.FullName; [pscustomobject]@{file=$_.Name;status=[string]$s.Status} }); ConvertTo-Json -InputObject $items -Compress"], + { env: { ...process.env, REBUILD_APP_PATH: appDirectory }, encoding: "utf8" })); + const updater = inspectUpdater(path.join(root, "src", "win", "_asar")); + const gate = releaseGate(reports.check, reports.apply, updater); + let components, desktopSmoke; + try { + const originalApp = path.join(process.env.CODEX_SYNC_DIR, "win-extract", "app"); + components = await inspectComponents(appDirectory, originalApp, directory); + desktopSmoke = await inspectDesktop(appDirectory, directory); + writeJson(path.join(root, "patch-reports", "runtime-checks.json"), { components, desktopSmoke }); + } catch (error) { + writeJson(path.join(root, "patch-reports", "runtime-checks.json"), { components, desktopSmoke, passed: false, error: error.message, desktopDiagnostic: error.desktopDiagnostic }); + throw error; + } + // 缺少嵌入哈希可能是官方关闭校验,也可能是结构漂移;留诊断,禁止静默晋升。 + if (!integrityHashEmbedded) { gate.canPromote = false; gate.blocks.push("EXE 中未找到最终 ASAR 哈希,需要核对 runtime 完整性契约"); } + return { schemaVersion: 1, upstream: source, cliVersion, cliSha256: await sha256(cli), + cliInitialize: handshake, asarHeaderSha256: headerHash, integrityHashEmbedded, + signatures, updater, components, desktopSmoke, gate, guiValidated: false }; +} + +async function candidate(options) { + if (process.env.GITHUB_ACTIONS !== "true" || process.platform !== "win32") { + throw new Error("完整 Windows 候选构建只在 GitHub Actions Windows runner 执行"); + } + const directory = path.resolve(options.out || "artifacts/candidate"); + if (fs.existsSync(directory) && fs.readdirSync(directory).length) throw new Error("候选输出目录非空,不能覆盖已有产物"); + fs.mkdirSync(directory, { recursive: true }); + const sourceCommit = execFileSync("git", ["rev-parse", "HEAD"], { cwd: root, encoding: "utf8" }).trim(); + if (execFileSync("git", ["status", "--porcelain", "--untracked-files=no"], { cwd: root, encoding: "utf8" }).trim()) { + throw new Error("构建源码存在未提交修改,无法绑定候选提交"); + } + const source = await prepareSource(options, directory); + const syncDirectory = path.join(process.env.RUNNER_TEMP || os.tmpdir(), `codex-rebuild-${process.env.GITHUB_RUN_ID}-${process.env.GITHUB_RUN_ATTEMPT}`); + process.env.CODEX_SYNC_DIR = syncDirectory; + process.env.CODEX_REQUIRE_PINNED_SOURCE = "1"; + fs.mkdirSync(syncDirectory, { recursive: true }); + const { syncWin } = require("./sync-upstream"); + // 这个导入前 discovery 进程已经结束;当前进程的缓存路径在导入前明确固定。 + await syncWin(path.join(root, "src", "win"), { ...source, localPackage: path.join(directory, source.packageName) }); + saveCompatibilityEvidence(path.join(root, "src", "win", "_asar"), source); + const checkDirectory = path.join(root, "patch-reports", "windows-check"); + const applyDirectory = path.join(root, "patch-reports", "windows-apply"); + runScript("patch-all.js", ["win", "--check", "--report", checkDirectory]); + runScript("patch-all.js", ["win", "--report", applyDirectory]); + writeJson(path.join(root, "patch-reports", "frontend-source-checks.json"), require("./frontend-source-smoke").verifyFrontendSource(path.join(root, "src", "win", "_asar", "webview", "assets"))); + runScript("build-from-upstream.js", ["--platform", "win", "--defer-zip"]); + const reports = { check: readJson(path.join(checkDirectory, "report.json")), apply: readJson(path.join(applyDirectory, "report.json")) }; + const verified = await inspectOutput(path.join(root, "out", "win", "Codex-win32-x64"), source, reports, directory); + require("./build-from-upstream").createZip(path.join(root, "out", "Codex-verified.zip"), path.join(root, "out", "win", "Codex-win32-x64")); + const files = fs.readdirSync(path.join(root, "out")).filter((file) => file.endsWith(".zip")); + if (files.length !== 1) throw new Error("Windows ZIP 数量必须为 1"); + const revision = readJson(path.join(root, "package.json")).codexRebuildRevision; + if (!Number.isSafeInteger(revision) || revision < 1) throw new Error("维护修订号必须在源码中固定为正整数"); + const zipName = `Codex-win-x64-${source.version}-r${revision}-${sourceCommit.slice(0, 8)}.zip`; + fs.copyFileSync(path.join(root, "out", files[0]), path.join(directory, zipName)); + const zipHash = await sha256(path.join(directory, zipName)); + const metadata = { schemaVersion: 1, repository: process.env.GITHUB_REPOSITORY, sourceCommit, + runId: String(process.env.GITHUB_RUN_ID), runAttempt: String(process.env.GITHUB_RUN_ATTEMPT), + createdAt: new Date().toISOString(), upstream: source, zip: { name: zipName, sha256: zipHash, size: fs.statSync(path.join(directory, zipName)).size }, + revision, desktopVersion: reports.apply.upstream.win.version, gate: verified.gate }; + writeJson(path.join(directory, "candidate.json"), metadata); + writeJson(path.join(directory, "verify-report.json"), verified); + fs.writeFileSync(path.join(directory, "SHA256SUMS.txt"), `${zipHash} ${zipName}\n${source.sha256} ${source.packageName}\n`); + writeJson(path.join(directory, "acceptance-template.json"), { schemaVersion: 1, sourceCommit, + zipSha256: zipHash, runId: metadata.runId, tester: "", testedAt: "", + isolationEvidence: "", rollbackEvidence: "", checks: Object.fromEntries(requiredChecks.map((name) => [name, "pending"])), + notes: "填写实际结果;不能因脚本成功把 GUI 验收改为 passed。" }); + fs.rmSync(codexSmokeHome(directory), { recursive: true, force: true }); + for (const name of ["component-smoke", "desktop-smoke"]) fs.rmSync(path.join(directory, name), { recursive: true, force: true }); + output("zip_sha256", zipHash); + output("can_promote", String(metadata.gate.canPromote)); + if (process.env.GITHUB_STEP_SUMMARY) fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, + `\n## Windows 候选\n\n- MSIX: ${source.version}\n- CLI: ${verified.cliVersion}\n- ZIP SHA-256: \`${zipHash}\`\n- 自动发布门槛: ${metadata.gate.canPromote ? "通过,仍需 GUI 验收" : metadata.gate.blocks.join(";")}\n`); +} + +function codexSmokeHome(directory) { return path.join(directory, "cli-smoke-home"); } + +async function verifyRelease(options) { + const directory = path.resolve(options.dir || "artifacts/candidate"); + const metadata = readJson(path.join(directory, "candidate.json")); + const report = readJson(path.join(directory, "verify-report.json")); + const approval = readJson(path.resolve(options.acceptance || "acceptance.json")); + const hash = await sha256(confinedFile(directory, metadata.zip.name)); + if (metadata.schemaVersion !== 1 || !/^[a-f0-9]{40}$/.test(metadata.sourceCommit || "") + || !Number.isSafeInteger(metadata.revision) || metadata.revision < 1 + || !/^\d+$/.test(metadata.runId || "") || !/^\d+$/.test(metadata.runAttempt || "") + || metadata.zip.size !== fs.statSync(confinedFile(directory, metadata.zip.name)).size + || metadata.repository !== (options.repository || process.env.GITHUB_REPOSITORY) + || hash !== metadata.zip.sha256 || hash !== options["zip-sha256"] + || metadata.runId !== options["run-id"] + || options["source-commit"] && metadata.sourceCommit !== options["source-commit"] + || options["run-attempt"] && metadata.runAttempt !== options["run-attempt"]) throw new Error("候选源码、运行记录或 ZIP 哈希不一致"); + validateSource(metadata.upstream); + await verifySourceFile(metadata.upstream, confinedFile(directory, metadata.upstream.packageName)); + if (JSON.stringify(readJson(path.join(directory, "upstream.json"))) !== JSON.stringify(metadata.upstream) + || JSON.stringify(report.upstream) !== JSON.stringify(metadata.upstream)) throw new Error("来源记录不一致"); + if (!metadata.gate.canPromote || !report.gate.canPromote || metadata.gate.blocks.length || report.gate.blocks.length + || !report.cliInitialize.passed || !report.updater.disabled || !report.integrityHashEmbedded + || !report.components?.passed || !report.desktopSmoke?.passed) throw new Error("候选自动发布门槛未通过"); + if (approval.schemaVersion !== 1 || approval.sourceCommit !== metadata.sourceCommit + || approval.zipSha256 !== hash || approval.runId !== metadata.runId + || !approval.tester?.trim() || !Number.isFinite(Date.parse(approval.testedAt)) + || !approval.isolationEvidence?.trim() || !approval.rollbackEvidence?.trim() + || requiredChecks.some((name) => approval.checks?.[name] !== "passed")) throw new Error("GUI/隔离/回退验收缺失或仍未通过"); + fs.copyFileSync(path.resolve(options.acceptance || "acceptance.json"), path.join(directory, "acceptance.json")); + const tag = `win-${metadata.upstream.version}-r${metadata.revision}-${metadata.sourceCommit.slice(0, 8)}`; + output("tag", tag); + output("source_commit", metadata.sourceCommit); + output("zip_name", metadata.zip.name); + console.log("正式晋升校验通过:使用已验收原 ZIP,不重新构建"); +} + +async function main() { + const [command, ...args] = process.argv.slice(2); + const options = argsOf(args); + if (command === "discover") await discover(options); + else if (command === "candidate") await candidate(options); + else if (command === "verify-release") await verifyRelease(options); + else throw new Error("用法:windows-maintenance.js [--参数 值]"); +} +if (require.main === module) main().catch((error) => { console.error(`[error] ${error.message}`); process.exitCode = 1; }); +module.exports = { requiredChecks }; diff --git a/scripts/windows-runtime-checks.js b/scripts/windows-runtime-checks.js new file mode 100644 index 00000000..ac3c1ce6 --- /dev/null +++ b/scripts/windows-runtime-checks.js @@ -0,0 +1,145 @@ +/** Windows 真实产物检查:同包工具、原生组件及隔离桌面启动。 */ +const fs = require("node:fs"); +const path = require("node:path"); +const { execFileSync, spawn } = require("node:child_process"); +const { sha256 } = require("./windows-artifacts"); + +function peMachine(file) { + const fd = fs.openSync(file, "r"); + try { + const header = Buffer.alloc(64); + if (fs.readSync(fd, header, 0, 64, 0) !== 64 || header.readUInt16LE(0) !== 0x5a4d) throw new Error(`无效 MZ:${file}`); + const offset = header.readUInt32LE(60), pe = Buffer.alloc(6); + if (offset + 6 > fs.fstatSync(fd).size || fs.readSync(fd, pe, 0, 6, offset) !== 6 || pe.readUInt32LE(0) !== 0x4550) throw new Error(`无效 PE:${file}`); + return pe.readUInt16LE(4); + } finally { fs.closeSync(fd); } +} + +function isolatedEnvironment(root) { + const env = {}; + for (const key of ["SystemRoot", "SystemDrive", "WINDIR", "COMSPEC", "PATH", "PATHEXT"]) if (process.env[key]) env[key] = process.env[key]; + for (const [key, name] of Object.entries({ CODEX_HOME: "codex-home", USERPROFILE: "profile", APPDATA: "profile/AppData/Roaming", LOCALAPPDATA: "profile/AppData/Local", TEMP: "profile/AppData/Local/Temp", TMP: "profile/AppData/Local/Temp" })) { + env[key] = path.join(root, name); fs.mkdirSync(env[key], { recursive: true }); + } + for (const name of ["Desktop", "Documents", "Downloads", "AppData/LocalLow"]) fs.mkdirSync(path.join(env.USERPROFILE, name), { recursive: true }); + return env; +} + +function run(file, args, cwd, env) { + return execFileSync(file, args, { cwd, env, encoding: "utf8", windowsHide: true, timeout: 30000, maxBuffer: 1024 * 1024 }).trim(); +} + +function filesUnder(root, predicate) { + const results = []; + for (const entry of fs.readdirSync(root, { withFileTypes: true })) { + const file = path.join(root, entry.name); + if (entry.isSymbolicLink()) throw new Error(`运行组件路径不能经过链接:${file}`); + if (entry.isDirectory()) results.push(...filesUnder(file, predicate)); + else if (entry.isFile() && predicate(file)) results.push(file); + } + return results; +} + +async function inspectComponents(app, originalApp, output) { + const env = isolatedEnvironment(path.join(output, "component-smoke")); + const resources = path.join(app, "resources"), binaries = []; + const targets = ["Codex.exe", "resources/codex.exe", "resources/codex-code-mode-host.exe", "resources/rg.exe", "resources/cua_node/bin/node.exe"]; + const chrome = "resources/plugins/openai-bundled/plugins/chrome/extension-host/windows/x64/extension-host.exe"; + if (fs.existsSync(path.join(originalApp, chrome))) targets.push(chrome); + for (const relative of ["resources/cua_node/bin/node_repl.exe", + "resources/cua_node/bin/node_modules/@oai/cua/bin/windows/codex-computer-use.exe", + "resources/cua_node/bin/node_modules/@oai/sky/bin/windows/codex-computer-use.exe", + "resources/cua_node/bin/node_modules/@oai/sky/bin/windows/swift/x64/codex-computer-use-swift.exe"]) { + if (fs.existsSync(path.join(originalApp, relative))) targets.push(relative); + } + const nativeFiles = filesUnder(resources, file => file.endsWith(".node") + && !/(?:[\\/](?:android[^\\/]*|darwin[^\\/]*|linux[^\\/]*|win32-(?:arm64|ia32)[^\\/]*|windows[\\/](?:arm64|x86))(?:[\\/]|$)|-(?:darwin|linux|android|win32-arm64|win32-ia32))/i.test(file)); + if (!nativeFiles.length) throw new Error("候选没有 Windows 原生模块"); + targets.push(...nativeFiles.map(file => path.relative(app, file))); + for (const relative of targets) { + const file = path.join(app, relative), original = path.join(originalApp, relative); + if (!fs.existsSync(file) || fs.statSync(file).size === 0) throw new Error(`关键运行组件缺失:${relative}`); + if (peMachine(file) !== 0x8664) throw new Error(`关键运行组件不是 x64:${relative}`); + const hash = await sha256(file); + if (relative !== "Codex.exe") { + if (!fs.existsSync(original) || await sha256(original) !== hash) throw new Error(`同包运行组件被改动:${relative}`); + } + binaries.push({ file: relative.replaceAll("\\", "/"), size: fs.statSync(file).size, machine: "x64", sha256: hash, originalMatch: relative !== "Codex.exe" }); + } + const codeModeHelp = run(path.join(resources, "codex-code-mode-host.exe"), ["--help"], resources, env); + if (!codeModeHelp.includes("--listen")) throw new Error("code-mode-host 未返回预期帮助"); + const rgVersion = run(path.join(resources, "rg.exe"), ["--version"], resources, env); + const fixture = path.join(output, "component-smoke", "search.txt"); + fs.writeFileSync(fixture, "ordinary\n辅助工具验证\n", "utf8"); + const search = run(path.join(resources, "rg.exe"), ["--fixed-strings", "--line-number", "辅助工具验证", fixture], resources, env); + if (search !== "2:辅助工具验证") throw new Error("rg 中文搜索未通过"); + const cua = path.join(resources, "cua_node", "bin"); + const cuaImport = run(path.join(cua, "node.exe"), ["--input-type=module", "-e", 'await import("@oai/sky"); console.log("CUA_IMPORT_OK")'], cua, env); + if (!cuaImport.includes("CUA_IMPORT_OK")) throw new Error("CUA 原生组件加载未通过"); + return { passed: true, binaries, codeModeHelp, rgVersion, rgSearch: search, cuaImport, + note: "基础启动/加载检查通过,尚不代表实际代码模式任务或 GUI 业务验收通过" }; +} + +async function inspectDesktop(app, output) { + const root = path.join(output, "desktop-smoke"), env = isolatedEnvironment(root); + const executable = path.join(app, "Codex.exe"), cli = path.join(app, "resources", "codex.exe"); + Object.assign(env, { CODEX_REBUILD_TEST_ROOT: root, CODEX_REBUILD_SMOKE_EXIT: "1", CODEX_ELECTRON_USER_DATA_PATH: path.join(root, "electron-user-data"), CODEX_CLI_PATH: cli }); + const proofPath = path.join(root, "desktop-smoke.json"); + if (fs.existsSync(proofPath)) throw new Error("桌面冒烟目录存在旧证据"); + const child = spawn(executable, [`--user-data-dir=${env.CODEX_ELECTRON_USER_DATA_PATH}`, "--enable-logging=stderr"], { cwd: app, env, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }); + let stdout = "", stderr = ""; + child.stdout.on("data", chunk => { stdout = (stdout + chunk).slice(-64000); }); + child.stderr.on("data", chunk => { stderr = (stderr + chunk).slice(-64000); }); + let exited = false, exitCode, spawnError; + child.on("error", error => { spawnError = error; }); + child.on("exit", code => { exited = true; exitCode = code; }); + let proof; + try { + const deadline = Date.now() + 90000; + while (Date.now() < deadline) { + if (spawnError) throw spawnError; + if (fs.existsSync(proofPath)) { + proof = JSON.parse(fs.readFileSync(proofPath, "utf8")); + if (proof.failure) throw new Error(`桌面启动失败:${proof.failure}`); + if (proof.windowLoaded) break; + } + if (exited && !proof?.windowLoaded) throw new Error(`候选提前退出,未获得窗口加载证据;退出码 ${exitCode}`); + await new Promise(resolve => setTimeout(resolve, 500)); + } + const isolationFile = path.join(root, "isolation-runtime.json"); + if (!proof?.windowLoaded || !fs.existsSync(isolationFile)) throw new Error("桌面窗口/隔离 ready 证据缺失"); + const isolation = JSON.parse(fs.readFileSync(isolationFile, "utf8")); + if (path.resolve(isolation.codexHome) !== path.resolve(env.CODEX_HOME) + || path.resolve(isolation.userData) !== path.resolve(env.CODEX_ELECTRON_USER_DATA_PATH) + || path.resolve(isolation.sessionData) !== path.resolve(env.CODEX_ELECTRON_USER_DATA_PATH) + || ![executable, path.join(app, "ChatGPT.exe")].some(file => path.resolve(file).toLowerCase() === path.resolve(isolation.executable).toLowerCase()) + || isolation.pid !== proof.pid) throw new Error("桌面冒烟实际程序/数据路径不一致"); + const exitDeadline = Date.now() + 15000; + while (!exited && Date.now() < exitDeadline) await new Promise(resolve => setTimeout(resolve, 250)); + if (!exited || exitCode !== 0) throw new Error(`候选未正常退出:${exitCode}`); + return { passed: true, isolation, proof, note: "隔离空数据窗口启动检查,不代替登录、Provider、数据恢复等人工验收" }; + } catch (error) { + const records = {}; + for (const name of ["desktop-smoke.json", "isolation-runtime.json", "isolation-hook.json", "startup-error.json", "native-startup-error.json", "test-environment.json", "app-exit.json", "process-exit.json"]) { + const file = path.join(root, name); if (fs.existsSync(file)) records[name] = fs.readFileSync(file, "utf8"); + } + const priority = file => /CodexForensics|startup-error|isolation-hook/.test(file) ? 0 : /\.(?:log|jsonl)$/.test(file) ? 1 : 2; + const logs = filesUnder(root, file => /\.(?:log|jsonl)$/.test(file) && !/^\d+\.log$/.test(path.basename(file))).sort((a,b) => priority(a)-priority(b)); + for (const file of logs.slice(0, 12)) { + const size = fs.statSync(file).size, fd = fs.openSync(file, "r"); + try { + const tail = Buffer.alloc(Math.min(size, 64000)); fs.readSync(fd, tail, 0, tail.length, Math.max(0, size - tail.length)); + records[path.relative(root, file)] = tail.toString("utf8"); + } finally { fs.closeSync(fd); } + } + error.desktopDiagnostic = { executable, pid: child.pid, exitCode, stdout, stderr, records }; + throw error; + } finally { + // 仅清理由本次候选路径创建的进程,不能终止当前正式 Codex。 + if (!exited) child.kill(); + execFileSync("pwsh", ["-NoProfile", "-Command", "$prefix=$env:REBUILD_SMOKE_APP + [IO.Path]::DirectorySeparatorChar; $items=@(Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -and $_.ExecutablePath.StartsWith($prefix,[StringComparison]::OrdinalIgnoreCase) }); foreach($item in $items){ Stop-Process -Id $item.ProcessId -Force -ErrorAction SilentlyContinue }; Start-Sleep -Milliseconds 500; $remaining=@(Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -and $_.ExecutablePath.StartsWith($prefix,[StringComparison]::OrdinalIgnoreCase) }); if($remaining.Count){throw '候选进程残留'}"], + { env: { ...process.env, REBUILD_SMOKE_APP: path.resolve(app) }, windowsHide: true, timeout: 15000, stdio: "pipe" }); + } +} + +module.exports = { peMachine, isolatedEnvironment, inspectComponents, inspectDesktop }; From c934cf884709b586620213c267b571d31391c809 Mon Sep 17 00:00:00 2001 From: carptopus Date: Thu, 15 Oct 2026 19:47:35 +0800 Subject: [PATCH 02/51] Refine Windows UI patches and remove unsafe image auth --- .gitignore | 1 + .npmignore | 1 + README.md | 12 +- package.json | 1 - pnpm-lock.yaml | 9 - scripts/check-scripts.js | 2 +- scripts/frontend-source-smoke.js | 11 +- scripts/patch-accent-presets.js | 186 +++++++++++++ scripts/patch-accent-presets.test.js | 63 +++++ scripts/patch-hide-pet-menu.js | 149 ++++++++++ scripts/patch-hide-pet-menu.test.js | 45 +++ scripts/patch-image-generation-auth.js | 270 ------------------ scripts/patch-image-generation-auth.test.js | 289 -------------------- scripts/patch-policy.js | 3 +- scripts/patch-reading-layout.js | 41 ++- scripts/reading-layout-smoke.js | 30 +- scripts/runtime/image-generation-auth.cjs | 169 ------------ scripts/runtime/reading-width.mjs | 138 +++++++--- 18 files changed, 624 insertions(+), 796 deletions(-) create mode 100644 scripts/patch-accent-presets.js create mode 100644 scripts/patch-accent-presets.test.js create mode 100644 scripts/patch-hide-pet-menu.js create mode 100644 scripts/patch-hide-pet-menu.test.js delete mode 100644 scripts/patch-image-generation-auth.js delete mode 100644 scripts/patch-image-generation-auth.test.js delete mode 100644 scripts/runtime/image-generation-auth.cjs diff --git a/.gitignore b/.gitignore index 1434063a..c5fefc57 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ Codex.app/ node_modules/ # Build outputs +/build/ out/ out-*/ dist/ diff --git a/.npmignore b/.npmignore index 4809c672..13c8e6a7 100644 --- a/.npmignore +++ b/.npmignore @@ -1,2 +1,3 @@ # Not published to npm — this file silences the gitignore-fallback warning /local/ +/build/ diff --git a/README.md b/README.md index 22db9165..803f8fd7 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,17 @@ npm run build:all - `src//_asar` 是 ASAR 内资源的补丁目标。 - `src//plugins` 与 `src//cua_node` 是 Browser / Computer Use 等外置运行时的补丁目标;直打包流程会显式覆盖这两个目录,避免重新复制上游安装包缓存时丢失补丁。 - `patch-browser-auth.js` 兼容 API-key 登录:ChatGPT 身份与 request-header 策略可用时保持原行为;身份读取失败时仅关闭该可选请求头并继续本地浏览器通道,不会把 API key 伪装或发送为 ChatGPT token。 -- `patch-image-generation-auth.js` 兼容自定义 `base_url` 的 API-key 登录:仅对非 OpenAI/ChatGPT 官方地址为 app-server 注入 provider 认证、`image_gen` 能力参数,并在没有静态模型目录时启用远端模型发现;显式关闭项及已有 `model_catalog_json`/`model_catalog_url` 均优先,API key 只经子进程环境传递,不写入用户配置或命令行。 +- `patch-provider-quota.js` 按任务实际 Provider 和明确的 `base_url` 判断发送门槛,避免 ChatGPT 额度状态误阻断第三方 Provider,同时保留官方、云任务及第三方真实错误。 +- `patch-accent-presets.js` 允许没有 ChatGPT 账户主题的 API-key / 自定义 Provider 在本地选择官方强调色预设;账户主题仍在加载时保持禁用,账户可用时继续使用官方同步。 +- `patch-hide-pet-menu.js` 只隐藏账户菜单中的 Pet / Mini 入口,保留浮动面板实现、状态和全局快捷键。 +- `patch-reading-layout.js` 在外观主题卡片中加入默认、85%、100% 三档正文宽度,并同步代码块、表格和输入区宽度,扩宽适用对话框;Markdown 粗体颜色可跟随正文、强调色或使用自定义颜色。 +- `patch-test-isolation.js` 在官方设置 User Data 后、获取单实例锁前挂载 Windows 验收隔离,分别约束 `CODEX_HOME`、User Data 和 sessionData,并记录实际启动路径证据。 +- `patch-model-picker-submenu.js` 增加对新版原生 simple / advanced 内联模型列表的结构核验;官方实现完整时保持原样,旧结构继续适配,未知结构明确失败。 +- `patch-updater.js` 区分更新方法与调用 Bundle,并在补丁后核对更新方法确实返回禁用状态;缺少目标或结构未知不再误报为已关闭。 +- `sync-upstream.js`、`fetch-msstore.js` 和 `build-from-upstream.js` 强化 Windows x64 官方包选择与固定来源校验,支持精确版本和已验证原始 MSIX 重放;包身份、大小或 SHA-256 不符时拒绝构建,运行检查通过前不生成最终 ZIP。 +- `windows-artifacts.js` 与 `windows-maintenance.js` 记录官方来源和候选产物哈希,生成候选、验证发布门槛,并保证正式发布复用已经验收的同一 ZIP。 +- `windows-runtime-checks.js` 检查 Windows EXE / 原生模块架构及未修改组件哈希,实际加载 CUA、运行 code-mode host / rg 基础命令,并执行空白隔离桌面的启动、就绪和退出冒烟。 +- `check-scripts.js`、`frontend-source-smoke.js`、`reading-layout-smoke.js` 和 `maintenance-smoke.js` 覆盖脚本语法、真实补丁资源、阅读设置及候选/发布拒绝路径,避免只凭补丁脚本成功退出判断功能可用。 - `patch-realtime-voice-auth.js` 为 API-key 登录放行实时语音入口;实时会话仍由 app-server 使用当前 model provider 的 `base_url` 与认证创建,ChatGPT 工作区能力的认证限制保持不变。 - 上游更新后应先执行 `npm run patch -- --check` 或完整 `npm run patch`,再运行测试和构建。 diff --git a/package.json b/package.json index fda9f416..65230b25 100644 --- a/package.json +++ b/package.json @@ -66,7 +66,6 @@ "node-pty": "^1.1.0", "shell-env": "^4.0.1", "shlex": "^3.0.0", - "smol-toml": "^1.5.2", "tslib": "^2.8.1", "zod": "^4.1.13" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0d5a6e91..ecf560c4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -47,9 +47,6 @@ importers: shlex: specifier: ^3.0.0 version: 3.0.0 - smol-toml: - specifier: ^1.5.2 - version: 1.6.1 tslib: specifier: ^2.8.1 version: 2.8.1 @@ -2522,10 +2519,6 @@ packages: resolution: {integrity: sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==} engines: {node: '>= 6.0.0', npm: '>= 3.0.0'} - smol-toml@1.6.1: - resolution: {integrity: sha512-dWUG8F5sIIARXih1DTaQAX4SsiTXhInKf1buxdY9DIg4ZYPZK5nGM1VRIYmEbDbsHt7USo99xSLFu5Q1IqTmsg==} - engines: {node: '>= 18'} - socks-proxy-agent@7.0.0: resolution: {integrity: sha512-Fgl0YPZ902wEsAyiQ+idGd1A7rSFx/ayC1CQVMw5P+EQx2V0SgpGtf6OKFhVjPflPUl9YMmEOnmfjCdMUsygww==} engines: {node: '>= 10'} @@ -5913,8 +5906,6 @@ snapshots: smart-buffer@4.2.0: {} - smol-toml@1.6.1: {} - socks-proxy-agent@7.0.0: dependencies: agent-base: 6.0.2 diff --git a/scripts/check-scripts.js b/scripts/check-scripts.js index b8a11ea4..6cf935ae 100644 --- a/scripts/check-scripts.js +++ b/scripts/check-scripts.js @@ -4,7 +4,7 @@ const path = require("node:path"); const { execFileSync } = require("node:child_process"); const root = path.resolve(__dirname, ".."); const files = fs.readdirSync(__dirname).filter((name) => /\.(?:js|cjs)$/.test(name)); -files.push("../forge.config.js", "runtime/image-generation-auth.cjs"); +files.push("../forge.config.js"); files.push("runtime/rebuild-test-isolation.cjs"); files.push("runtime/rebuild-test-environment.cjs"); files.push("runtime/reading-width.mjs"); diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index 8c162c83..69c12611 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -64,7 +64,16 @@ function verifyFrontendSource(assets) { } const settings = files.filter(name => /^general-settings-/.test(name) && fs.readFileSync(path.join(assets, name), "utf8").includes("settings.appearance.visualStyle")); assert.equal(settings.length, 1); - assert.match(fs.readFileSync(path.join(assets, settings[0]), "utf8"), /jsx\)\(__CodexRebuildReadingWidth/); + const settingsSource = fs.readFileSync(path.join(assets, settings[0]), "utf8"); + assert.match(settingsSource, /jsx\)\(__CodexRebuildReadingWidth/); + assert.match(settingsSource, /codex-rebuild-reading-width:visual-card/); + assert.match(settingsSource, /codex-rebuild-local-accent-presets/); + assert.match(settingsSource, /__codexSelectAccent/); + const readingModule = fs.readFileSync(path.join(assets, "codex-rebuild-reading-width.js"), "utf8"); + assert.match(readingModule, /codex-rebuild:markdown-bold-color-mode:v1/); + assert.match(readingModule, /--app-color-text-accent/); + assert.doesNotMatch(readingModule, /--color-token-charts-green|--green-500|#00a240/); + assert.doesNotMatch(readingModule, /设置无效|请重新选择/); const shared = files.filter(name => /^app-shared-/.test(name) && fs.readFileSync(path.join(assets, name), "utf8").includes("codex-rebuild-dialog-default")); assert.equal(shared.length, 1); const dialogs = fs.readFileSync(path.join(assets, shared[0]), "utf8"); diff --git a/scripts/patch-accent-presets.js b/scripts/patch-accent-presets.js new file mode 100644 index 00000000..6576d90c --- /dev/null +++ b/scripts/patch-accent-presets.js @@ -0,0 +1,186 @@ +#!/usr/bin/env node +/** + * 允许没有 ChatGPT 账户主题状态的 API-key / 自定义 Provider 使用官方强调色预设。 + * 账户主题加载中仍保持禁用;账户可用时完整保留官方同步流程。 + */ +const fs = require("fs"); +const path = require("path"); +const { parse } = require("acorn"); +const { SRC_DIR, relPath } = require("./patch-util"); + +const MARKER = "/* codex-rebuild-local-accent-presets */"; +const STORAGE_KEY = "codex-rebuild:accent-preset:v1"; +const PLATFORMS = ["mac-arm64", "mac-x64", "win", "unix"]; +const HELPER = `${MARKER} +const __codexAccentPresetKey=${JSON.stringify(STORAGE_KEY)},__codexAccentPresets=new Set(["default","blue","green","yellow","pink","orange","purple","black"]); +function __codexStoredAccentPreset(){try{let e=globalThis.localStorage?.getItem(__codexAccentPresetKey);return __codexAccentPresets.has(e)?e:null}catch{return null}} +function __codexAccentSelection(e,t,n){return e===null?__codexStoredAccentPreset()??n:n} +function __codexResolveAccent(e,t,n){let r=e(t,n),i=/^var\\((--[^,\\s)]+)/.exec(r);if(i){let e=globalThis.getComputedStyle?.(globalThis.document?.documentElement)?.getPropertyValue(i[1]).trim();if(e)r=e}if(!/^#[0-9a-f]{6}$/i.test(r))throw Error("无法解析本地强调色预设");return r.toLowerCase()} +function __codexSelectAccent(e,t,n,r,i,a){return Promise.resolve().then(()=>{if(e!==null){globalThis.localStorage?.removeItem(__codexAccentPresetKey);return a()}globalThis.localStorage?.setItem(__codexAccentPresetKey,t);return i(__codexResolveAccent(r,t,n))})} +function __codexUseCustomAccent(e,t){globalThis.localStorage?.removeItem(__codexAccentPresetKey);return e(t)} +`; + +function walk(node, visit, parent = null) { + if (!node || typeof node !== "object" || !node.type) return; + visit(node, parent); + for (const [key, value] of Object.entries(node)) { + if (["type", "start", "end"].includes(key)) continue; + if (Array.isArray(value)) { + for (const child of value) if (child?.type) walk(child, visit, node); + } else if (value?.type) walk(value, visit, node); + } +} + +function nodes(root, predicate) { + const found = []; + walk(root, (node, parent) => { if (predicate(node, parent)) found.push(node); }); + return found; +} + +function literal(node) { + if (node?.type === "Literal") return node.value; + if (node?.type === "TemplateLiteral" && node.expressions.length === 0) return node.quasis[0].value.cooked; + return null; +} + +function key(node) { + if (!node) return null; + if (node.type === "Identifier") return node.name; + return literal(node); +} + +function unique(items, label) { + if (items.length !== 1) throw new Error(`${label} 数量异常(${items.length})`); + return items[0]; +} + +function objectBindings(pattern) { + return Object.fromEntries(pattern.properties.filter(property => property.type === "Property" && property.value?.type === "Identifier") + .map(property => [key(property.key), property.value.name])); +} + +function patchSource(source) { + if (!source.includes("chatgptAccentPicker.ChatGptAccentPicker.updateError") || !source.includes("accentSource")) { + return { status: "not-applicable", source }; + } + if (source.includes(MARKER)) { + parse(source, { ecmaVersion: "latest", sourceType: "module" }); + if (!["__codexAccentSelection(", "__codexSelectAccent(", "__codexUseCustomAccent("].every(value => source.includes(value))) { + return { status: "unexpected-shape", source, reason: "本地强调色标记不完整" }; + } + return { status: "already-patched", source }; + } + + try { + const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const component = unique(ast.body.filter(node => node.type === "FunctionDeclaration" && + source.slice(node.start, node.end).includes("chatgptAccentPicker.ChatGptAccentPicker.updateError") && + source.slice(node.start, node.end).includes("accentSource")), "强调色组件"); + const props = unique(nodes(component, node => node.type === "VariableDeclarator" && node.id?.type === "ObjectPattern") + .map(node => objectBindings(node.id)) + .filter(bindings => ["theme", "variant", "onSelect", "onCustomColorChange"].every(name => bindings[name])), "强调色属性"); + const theme = props.theme; + const variant = props.variant; + const selectAccount = props.onSelect; + const selectCustom = props.onCustomColorChange; + + const disabled = unique(nodes(component, node => node.type === "Property" && key(node.key) === "disabled" && + node.value?.type === "BinaryExpression" && ["==", "==="].includes(node.value.operator) && + node.value.left?.type === "Identifier" && literal(node.value.right) === null), "预设禁用条件"); + const accountTheme = disabled.value.left.name; + const selection = unique(nodes(component, node => node.type === "VariableDeclarator" && node.init?.type === "ConditionalExpression" && + source.slice(node.init.start, node.init.end).includes(`${theme}.accentSource`) && + source.slice(node.init.start, node.init.end).includes("`chatgpt`") && + source.slice(node.init.start, node.init.end).includes("`custom`")), "当前强调色来源"); + + const colorCalls = nodes(component, node => node.type === "CallExpression" && node.callee?.type === "Identifier" && + node.arguments.length === 2 && node.arguments[1]?.type === "Identifier" && node.arguments[1].name === variant && + source.slice(node.arguments[0].start, node.arguments[0].end).includes("effectiveTheme")); + const colorFunction = unique(colorCalls, "官方强调色函数").callee.name; + const accountCalls = nodes(component, node => node.type === "CallExpression" && node.callee?.type === "Identifier" && + node.callee.name === selectAccount); + const accountCall = unique(accountCalls, "账户强调色写入"); + const preset = accountCall.arguments[0]; + if (preset?.type !== "Identifier") throw new Error("强调色预设参数结构未知"); + + const customCalls = nodes(component, node => node.type === "CallExpression" && node.callee?.type === "Identifier" && + node.callee.name === selectCustom); + const customCall = unique(customCalls, "切换自定义强调色"); + if (customCall.arguments.length !== 1) throw new Error("自定义强调色调用结构未知"); + const onChange = unique(nodes(component, node => node.type === "Property" && key(node.key) === "onChange" && + node.value?.type === "Identifier" && node.value.name === selectCustom), "自定义颜色输入"); + + const imports = ast.body.filter(node => node.type === "ImportDeclaration"); + const insertAt = imports.length ? imports.at(-1).end : 0; + const edits = [ + { start: insertAt, end: insertAt, text: `\n${HELPER}` }, + { start: selection.init.start, end: selection.init.end, + text: `__codexAccentSelection(${accountTheme},${theme}.accentSource,${source.slice(selection.init.start, selection.init.end)})` }, + // undefined 表示账户主题仍在加载;null 才表示没有可用账户主题。 + { start: disabled.value.start, end: disabled.value.end, text: `${accountTheme}===void 0` }, + { start: accountCall.start, end: accountCall.end, + text: `__codexSelectAccent(${accountTheme},${preset.name},${variant},${colorFunction},${selectCustom},()=>${source.slice(accountCall.start, accountCall.end)})` }, + { start: customCall.start, end: customCall.end, + text: `__codexUseCustomAccent(${selectCustom},${source.slice(customCall.arguments[0].start, customCall.arguments[0].end)})` }, + { start: onChange.value.start, end: onChange.value.end, + text: `__codexColor=>__codexUseCustomAccent(${selectCustom},__codexColor)` }, + ]; + let next = source; + for (const edit of edits.sort((left, right) => right.start - left.start)) { + next = next.slice(0, edit.start) + edit.text + next.slice(edit.end); + } + parse(next, { ecmaVersion: "latest", sourceType: "module" }); + return { status: "patched", source: next }; + } catch (error) { + return { status: "unexpected-shape", source, reason: error.message }; + } +} + +function targetDirectories(platform) { + const directories = (platform ? [platform] : PLATFORMS) + .map(name => ({ platform: name, path: path.join(SRC_DIR, name, "_asar", "webview", "assets") })) + .filter(item => fs.existsSync(item.path)); + const legacy = path.join(SRC_DIR, "webview", "assets"); + if (!directories.length && fs.existsSync(legacy)) directories.push({ platform: "legacy", path: legacy }); + return directories; +} + +function main() { + const args = process.argv.slice(2); + const platform = args.find(arg => PLATFORMS.includes(arg)); + const check = args.includes("--check"); + const directories = targetDirectories(platform); + let failed = 0; + let patched = 0; + for (const directory of directories) { + const candidates = fs.readdirSync(directory.path).filter(name => /^general-settings-.*\.js$/.test(name)) + .map(name => ({ name, path: path.join(directory.path, name), source: fs.readFileSync(path.join(directory.path, name), "utf8") })) + .filter(file => file.source.includes("chatgptAccentPicker.ChatGptAccentPicker.updateError")); + if (candidates.length !== 1) { + console.error(` [x] ${directory.platform}: 强调色设置资源数量异常(${candidates.length})`); + failed++; + continue; + } + const target = candidates[0]; + const result = patchSource(target.source); + if (result.status === "unexpected-shape" || result.status === "not-applicable") { + console.error(` [x] ${directory.platform}: ${result.reason ?? "强调色设置结构未知"}`); + failed++; + continue; + } + console.log(` [${directory.platform}] ${relPath(target.path)}`); + if (result.status === "already-patched") console.log(" [ok] 本地强调色预设已启用"); + else if (check) console.log(" [?] 可启用本地强调色预设;dry-run 未写文件"); + else { + fs.writeFileSync(target.path, result.source, "utf8"); + patched++; + console.log(" * 无账户主题时本地应用预设;账户可用时保留官方同步"); + } + } + if (!directories.length) { console.error(" [x] 缺少目标平台界面资源"); failed++; } + if (failed) process.exitCode = 1; + else console.log(` [ok] ${patched} bundle(s) patched`); +} + +if (require.main === module) main(); +module.exports = { HELPER, MARKER, STORAGE_KEY, patchSource }; diff --git a/scripts/patch-accent-presets.test.js b/scripts/patch-accent-presets.test.js new file mode 100644 index 00000000..da161c69 --- /dev/null +++ b/scripts/patch-accent-presets.test.js @@ -0,0 +1,63 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { HELPER, MARKER, STORAGE_KEY, patchSource } = require("./patch-accent-presets"); + +function fixture() { + return 'import{palette as P,options as O}from"./app.js";' + + 'function Accent(e){let{theme:r,variant:i,onSelect:a,onCustomColorChange:o}=e,s=scope(),u=read(themeAtom),d=read(pendingAtom),' + + 'f=r.accentSource===`chatgpt`?u?.chatTheme??`default`:`custom`,v=f!==`custom`&&jsx(`span`,{style:{backgroundColor:P(u?.effectiveTheme??f,i)}}),' + + 'x=O.map(e=>jsx(RadioItem,{disabled:u==null,value:e,onSelect:()=>{let t=s.get(account),n=s.get(settings).data,r=t!=null&&n?.eligibleNowOrBefore===!0;' + + 'a(e,()=>{r&&sync({accentColor:e})}).catch(()=>{toast("chatgptAccentPicker.ChatGptAccentPicker.updateError")})},children:e},e)),' + + 'S=()=>o(r.accent),D=f===`custom`?jsx(ColorInput,{value:r.accent,onChange:o}):null;return [v,x,S,D]}' ; +} + +function helpers() { + return Function(`${HELPER};return {selection:__codexAccentSelection,select:__codexSelectAccent,custom:__codexUseCustomAccent}`)(); +} + +test("无账户主题时启用本地预设并保留加载态禁用", () => { + const result = patchSource(fixture()); + assert.equal(result.status, "patched", result.reason); + assert.match(result.source, new RegExp(MARKER.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))); + assert.match(result.source, /disabled:u===void 0/); + assert.match(result.source, /__codexSelectAccent\(u,e,i,P,o,\(\)=>a\(/); + assert.match(result.source, /onChange:__codexColor=>__codexUseCustomAccent\(o,__codexColor\)/); + assert.equal(patchSource(result.source).status, "already-patched"); +}); + +test("未知强调色结构明确失败", () => { + const result = patchSource('const x="chatgptAccentPicker.ChatGptAccentPicker.updateError accentSource"'); + assert.equal(result.status, "unexpected-shape"); +}); + +test("本地预设使用官方 CSS 色值,账户可用时仍调用官方同步", async () => { + const values = new Map(); + globalThis.localStorage = { + getItem: key => values.get(key) ?? null, + setItem: (key, value) => values.set(key, value), + removeItem: key => values.delete(key), + }; + globalThis.document = { documentElement: {} }; + globalThis.getComputedStyle = () => ({ getPropertyValue: name => name === "--brand-blue-400" ? "#3A83F7" : "" }); + const { selection, select, custom } = helpers(); + let local = null; + let synced = 0; + + await select(null, "blue", "light", () => "var(--brand-blue-400)", value => { local = value; }, () => { synced++; }); + assert.equal(local, "#3a83f7"); + assert.equal(synced, 0); + assert.equal(values.get(STORAGE_KEY), "blue"); + assert.equal(selection(null, "custom", "custom"), "blue"); + + await select({ chatTheme: "default" }, "green", "light", () => "#53b559", () => {}, () => { synced++; }); + assert.equal(synced, 1); + assert.equal(values.has(STORAGE_KEY), false); + + values.set(STORAGE_KEY, "blue"); + custom(value => { local = value; }, "#123456"); + assert.equal(local, "#123456"); + assert.equal(values.has(STORAGE_KEY), false); + delete globalThis.localStorage; + delete globalThis.document; + delete globalThis.getComputedStyle; +}); diff --git a/scripts/patch-hide-pet-menu.js b/scripts/patch-hide-pet-menu.js new file mode 100644 index 00000000..4612628a --- /dev/null +++ b/scripts/patch-hide-pet-menu.js @@ -0,0 +1,149 @@ +#!/usr/bin/env node +/** 隐藏账户菜单中的 Pet/Mini 入口;保留浮动面板及其全局快捷键。 */ +const fs = require("node:fs"); +const path = require("node:path"); +const { parse } = require("acorn"); +const { SRC_DIR, relPath } = require("./patch-util"); + +const MARKER = "/* codex-rebuild-hide-pet-menu */"; +const LABEL_IDS = [ + "codex.profileFooter.showPet", + "codex.profileFooter.hidePet", + "codex.profileFooter.showMini", + "codex.profileFooter.hideMini", +]; +const PLATFORMS = ["mac-arm64", "mac-x64", "win"]; + +function walk(node, visit) { + if (!node || typeof node !== "object") return; + if (node.type) visit(node); + for (const value of Object.values(node)) { + if (Array.isArray(value)) value.forEach((child) => walk(child, visit)); + else if (value?.type) walk(value, visit); + } +} + +function literal(node) { + if (node?.type === "Literal") return node.value; + if (node?.type === "TemplateLiteral" && node.expressions.length === 0) { + return node.quasis[0].value.cooked; + } + return null; +} + +function propertyName(property) { + if (property?.computed) return null; + if (property?.key?.type === "Identifier") return property.key.name; + return literal(property?.key); +} + +function patchSource(source) { + if (!LABEL_IDS.every((id) => source.includes(id))) { + return { status: "not-applicable", source }; + } + if (source.includes(MARKER)) { + const count = source.split(MARKER).length - 1; + if (count !== 1) return { status: "unexpected-shape", source, count }; + parse(source, { ecmaVersion: "latest", sourceType: "module" }); + return { status: "already-patched", source, count: 0 }; + } + + const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const petComponents = ast.body.filter( + (node) => + node.type === "FunctionDeclaration" && + node.id?.name && + LABEL_IDS.every((id) => source.slice(node.start, node.end).includes(id)), + ); + if (petComponents.length !== 1) { + return { + status: "unexpected-pet-component-count", + source, + count: petComponents.length, + }; + } + + const calls = []; + walk(ast, (node) => { + if ( + node.type !== "CallExpression" || + node.arguments[0]?.type !== "Identifier" || + node.arguments[0].name !== petComponents[0].id.name || + node.arguments[1]?.type !== "ObjectExpression" + ) { + return; + } + const names = new Set( + node.arguments[1].properties + .filter((property) => property.type === "Property") + .map(propertyName), + ); + if (["isOverlayOpen", "onTogglePet", "petShortcut"].every((name) => names.has(name))) { + calls.push(node); + } + }); + if (calls.length !== 1) { + return { + status: "unexpected-pet-menu-call-count", + source, + count: calls.length, + }; + } + + const call = calls[0]; + const patched = source.slice(0, call.start) + MARKER + "null" + source.slice(call.end); + parse(patched, { ecmaVersion: "latest", sourceType: "module" }); + return { status: "patched", source: patched, count: 1 }; +} + +function locateTargets(platform) { + const platforms = platform ? [platform] : PLATFORMS; + const targets = []; + for (const name of platforms) { + const directory = path.join(SRC_DIR, name, "_asar", "webview", "assets"); + if (!fs.existsSync(directory)) continue; + const matches = fs.readdirSync(directory) + .filter((file) => file.endsWith(".js")) + .map((file) => path.join(directory, file)) + .filter((file) => { + const source = fs.readFileSync(file, "utf8"); + return LABEL_IDS.every((id) => source.includes(id)); + }); + if (matches.length !== 1) { + throw new Error(`[${name}] Pet 菜单资源数量异常(${matches.length})`); + } + targets.push({ platform: name, path: matches[0] }); + } + return targets; +} + +function main() { + const args = process.argv.slice(2); + const platform = args.find((arg) => PLATFORMS.includes(arg)); + const check = args.includes("--check"); + const targets = locateTargets(platform); + if (targets.length === 0) { + console.log("[skip] Pet 菜单资源不适用于当前平台"); + return; + } + + for (const target of targets) { + const source = fs.readFileSync(target.path, "utf8"); + const result = patchSource(source); + const label = `[${target.platform}] ${relPath(target.path)}`; + if (result.status === "patched") { + if (check) console.log(`[?] ${label}: Pet 菜单入口可隐藏`); + else { + fs.writeFileSync(target.path, result.source, "utf8"); + console.log(`[ok] ${label}: 已隐藏 Pet 菜单入口,快捷键保持不变`); + } + } else if (result.status === "already-patched") { + console.log(`[ok] ${label}: Pet 菜单入口已隐藏`); + } else { + throw new Error(`${label}: Pet 菜单结构未知(${result.status})`); + } + } +} + +if (require.main === module) main(); +module.exports = { LABEL_IDS, MARKER, locateTargets, patchSource }; diff --git a/scripts/patch-hide-pet-menu.test.js b/scripts/patch-hide-pet-menu.test.js new file mode 100644 index 00000000..60dca14a --- /dev/null +++ b/scripts/patch-hide-pet-menu.test.js @@ -0,0 +1,45 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { MARKER, patchSource } = require("./patch-hide-pet-menu"); + +function fixture() { + return [ + "function Menu(e){", + "let {isOverlayOpen:a,onTogglePet:b,petShortcut:c}=e;", + "let item=b==null?null:(0,ui.jsx)(Pet,{isOverlayOpen:a,onTogglePet:b,petShortcut:c});", + "return (0,ui.jsx)(`div`,{children:[item,settings,help]})}", + "function Pet(e){", + "let a={id:`codex.profileFooter.showPet`};", + "let b={id:`codex.profileFooter.hidePet`};", + "let c={id:`codex.profileFooter.showMini`};", + "let d={id:`codex.profileFooter.hideMini`};", + "return (0,ui.jsx)(Item,{onClick:e.onTogglePet,children:[a,b,c,d]})}", + ].join(""); +} + +test("只隐藏账户菜单中的 Pet 入口", () => { + const result = patchSource(fixture()); + + assert.equal(result.status, "patched"); + assert.equal(result.count, 1); + assert.match(result.source, new RegExp(MARKER.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))); + assert.doesNotMatch(result.source, /jsx\)\(Pet,\{isOverlayOpen:/); + assert.match(result.source, /petShortcut:c/); + assert.match(result.source, /onTogglePet:b/); + assert.equal(patchSource(result.source).status, "already-patched"); +}); + +test("Pet 组件存在但菜单调用结构未知时明确失败", () => { + const source = fixture().replace( + "(Pet,{isOverlayOpen:a,onTogglePet:b,petShortcut:c})", + "(Pet,{isOverlayOpen:a,onTogglePet:b,shortcut:c})", + ); + const result = patchSource(source); + + assert.equal(result.status, "unexpected-pet-menu-call-count"); + assert.equal(result.count, 0); +}); + +test("没有 Pet 功能的资源不适用", () => { + assert.equal(patchSource("function menu(){return null}").status, "not-applicable"); +}); diff --git a/scripts/patch-image-generation-auth.js b/scripts/patch-image-generation-auth.js deleted file mode 100644 index bc508f83..00000000 --- a/scripts/patch-image-generation-auth.js +++ /dev/null @@ -1,270 +0,0 @@ -#!/usr/bin/env node -/** - * 为自定义 Responses provider 的 API-key 登录补齐受限能力。 - * - * 上游 CLI 会把 image_gen 限制为 ChatGPT backend 或 actor-authorization - * provider,并要求 API-key 模型发现显式配置目录地址与实验特性。桌面端启动 - * app-server 时,本补丁按用户配置识别自定义 base_url,将 API key 通过子进程 - * 环境传入 provider,并补齐 CLI 所需的能力标记。 - * 用户 config.toml 与 auth.json 均不会被修改,API key 也不会进入命令行。 - */ -const fs = require("node:fs"); -const path = require("node:path"); -const { parse } = require("acorn"); -const { SRC_DIR, relPath } = require("./patch-util"); - -const RUNTIME_FILENAME = "codex-image-generation-auth.cjs"; -const TOML_FILENAME = "codex-image-generation-toml.cjs"; -const RUNTIME_REQUIRE = `./${RUNTIME_FILENAME}`; -const FEATURE_CONFIG = "features.code_mode_host=true"; -const OPENAI_BASE_URL_ENV = "CODEX_APP_SERVER_OPENAI_BASE_URL"; -const APP_SERVER_FLAG = "--analytics-default-enabled"; - -function walk(node, visitor) { - if (!node || typeof node !== "object") return; - if (node.type) visitor(node); - for (const [key, child] of Object.entries(node)) { - if (key === "type" || key === "start" || key === "end") continue; - if (Array.isArray(child)) { - for (const item of child) walk(item, visitor); - } else { - walk(child, visitor); - } - } -} - -function staticString(node) { - if (node?.type === "Literal" && typeof node.value === "string") { - return node.value; - } - if ( - node?.type === "TemplateLiteral" && - node.expressions.length === 0 && - node.quasis.length === 1 - ) { - return node.quasis[0].value.cooked; - } - return null; -} - -function findBaseArgsNames(ast) { - const names = []; - walk(ast, (node) => { - if ( - node.type !== "VariableDeclarator" || - node.id?.type !== "Identifier" || - node.init?.type !== "ArrayExpression" - ) { - return; - } - const values = node.init.elements.map(staticString); - if (values.includes("-c") && values.includes(FEATURE_CONFIG)) { - names.push(node.id.name); - } - }); - return names; -} - -function findFactoryPatch(ast, source, baseArgsName) { - const candidates = []; - walk(ast, (node) => { - if (node.type !== "FunctionDeclaration" || node.body == null) return; - const bodySource = source.slice(node.body.start, node.body.end); - if (!bodySource.includes("app-server") || !bodySource.includes(APP_SERVER_FLAG)) { - return; - } - - const spreads = []; - walk(node.body, (child) => { - if ( - child.type === "SpreadElement" && - child.argument?.type === "Identifier" && - child.argument.name === baseArgsName - ) { - spreads.push(child.argument); - } - }); - if (spreads.length > 0) candidates.push({ node, spreads }); - }); - - if (candidates.length !== 1) { - return { - status: "unexpected-factory-count", - count: candidates.length, - }; - } - if (candidates[0].spreads.length !== 2) { - return { status: "unexpected-spread-count", count: candidates[0].spreads.length }; - } - return { status: "found", ...candidates[0] }; -} - -function patchSource(source) { - if (source.includes(RUNTIME_REQUIRE)) { - return { status: "already-patched", source, count: 0 }; - } - if ( - !source.includes(FEATURE_CONFIG) || - !source.includes(OPENAI_BASE_URL_ENV) || - !source.includes(APP_SERVER_FLAG) - ) { - return { status: "not-applicable", source, count: 0 }; - } - - const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); - const baseArgsNames = findBaseArgsNames(ast); - if (baseArgsNames.length !== 1) { - return { - status: "unexpected-base-args-count", - source, - count: baseArgsNames.length, - }; - } - - const match = findFactoryPatch(ast, source, baseArgsNames[0]); - if (match.status !== "found") { - return { ...match, source }; - } - - let next = source; - const replacement = `require(${JSON.stringify(RUNTIME_REQUIRE)}).withImageGenerationAuth(${baseArgsNames[0]})`; - for (const identifier of [...match.spreads].sort( - (left, right) => right.start - left.start, - )) { - next = - next.slice(0, identifier.start) + - replacement + - next.slice(identifier.end); - } - parse(next, { ecmaVersion: "latest", sourceType: "module" }); - return { status: "patched", source: next, count: match.spreads.length }; -} - -function platformNames(platform) { - return platform - ? [platform] - : ["mac-arm64", "mac-x64", "win"].filter((name) => - fs.existsSync(path.join(SRC_DIR, name, "_asar", ".vite", "build")), - ); -} - -function locateTargets(platform) { - const targets = []; - for (const name of platformNames(platform)) { - const buildDir = path.join(SRC_DIR, name, "_asar", ".vite", "build"); - if (!fs.existsSync(buildDir)) continue; - const matches = fs - .readdirSync(buildDir) - .filter((file) => file.endsWith(".js")) - .map((file) => path.join(buildDir, file)) - .filter((file) => { - const source = fs.readFileSync(file, "utf8"); - return ( - source.includes(FEATURE_CONFIG) && - source.includes(OPENAI_BASE_URL_ENV) && - source.includes(APP_SERVER_FLAG) - ); - }); - if (matches.length !== 1) { - throw new Error( - `[${name}] expected one app-server argument bundle, found ${matches.length}`, - ); - } - targets.push({ platform: name, path: matches[0], buildDir }); - } - return targets; -} - -function filesEqual(left, right) { - return fs.existsSync(right) && fs.readFileSync(left).equals(fs.readFileSync(right)); -} - -function runtimeFiles(buildDir) { - return [ - { - source: path.join(__dirname, "runtime", "image-generation-auth.cjs"), - destination: path.join(buildDir, RUNTIME_FILENAME), - }, - { - source: require.resolve("smol-toml"), - destination: path.join(buildDir, TOML_FILENAME), - }, - ]; -} - -function syncRuntimeFiles(buildDir, check) { - let changed = 0; - for (const file of runtimeFiles(buildDir)) { - if (filesEqual(file.source, file.destination)) continue; - changed++; - if (!check) fs.copyFileSync(file.source, file.destination); - } - return changed; -} - -function main() { - const args = process.argv.slice(2); - const check = args.includes("--check"); - const platform = args.find((arg) => - ["mac-arm64", "mac-x64", "win"].includes(arg), - ); - const targets = locateTargets(platform); - if (targets.length === 0) { - console.log("[ok] No generated app-server bundles found"); - return; - } - - let changed = 0; - for (const target of targets) { - const source = fs.readFileSync(target.path, "utf8"); - const result = patchSource(source); - const runtimeChanged = syncRuntimeFiles(target.buildDir, check); - const label = `[${target.platform}] ${relPath(target.path)}`; - - if (result.status === "patched") { - changed++; - if (check) { - console.log(`[?] ${label}: image-generation auth patch required`); - } else { - fs.writeFileSync(target.path, result.source, "utf8"); - console.log(`[*] ${label}: image-generation auth patched`); - } - } else if (result.status === "already-patched") { - console.log(`[ok] ${label}: already patched`); - } else { - throw new Error( - `${label}: unsupported app-server argument shape (${result.status})`, - ); - } - - if (runtimeChanged > 0) { - changed += runtimeChanged; - console.log( - check - ? `[?] ${label}: ${runtimeChanged} runtime file(s) need syncing` - : `[*] ${label}: ${runtimeChanged} runtime file(s) synced`, - ); - } - } - - console.log( - check - ? `[check] ${changed} image-generation patch item(s) need changes` - : `[done] ${changed} image-generation patch item(s) changed`, - ); -} - -if (require.main === module) main(); - -module.exports = { - APP_SERVER_FLAG, - FEATURE_CONFIG, - OPENAI_BASE_URL_ENV, - RUNTIME_FILENAME, - RUNTIME_REQUIRE, - findBaseArgsNames, - locateTargets, - patchSource, - runtimeFiles, - syncRuntimeFiles, -}; diff --git a/scripts/patch-image-generation-auth.test.js b/scripts/patch-image-generation-auth.test.js deleted file mode 100644 index 4c7c0713..00000000 --- a/scripts/patch-image-generation-auth.test.js +++ /dev/null @@ -1,289 +0,0 @@ -const test = require("node:test"); -const assert = require("node:assert/strict"); -const fs = require("node:fs"); -const os = require("node:os"); -const path = require("node:path"); -const { spawnSync } = require("node:child_process"); -const { parse } = require("smol-toml"); - -const { - patchSource, - RUNTIME_FILENAME, - RUNTIME_REQUIRE, - syncRuntimeFiles, -} = require("./patch-image-generation-auth"); -const { - ACTOR_HEADER, - API_KEY_ENV, - defaultModelCatalogUrl, - resolvePatch, - withImageGenerationAuth, -} = require("./runtime/image-generation-auth.cjs"); - -function createBundle() { - return [ - "const providerBase=[{configKey:`openai_base_url`,envVar:`CODEX_APP_SERVER_OPENAI_BASE_URL`}];", - "var base=[`-c`,`features.code_mode_host=true`];", - "function args(){let e=providerBase.flatMap(()=>[]);", - "return e.length===0?[...base,`app-server`,`--analytics-default-enabled`]:", - "[`app-server`,...base,...e,`--analytics-default-enabled`]} ", - ].join(""); -} - -function createRuntime(t, config, auth = null, env = {}) { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "codex-imagegen-auth-")); - t.after(() => fs.rmSync(home, { recursive: true, force: true })); - fs.writeFileSync(path.join(home, "config.toml"), config); - if (auth != null) { - fs.writeFileSync(path.join(home, "auth.json"), JSON.stringify(auth)); - } - return { - env: { CODEX_HOME: home, ...env }, - homedir: () => home, - join: (...parts) => path.join(...parts), - parseToml: parse, - readFile: (file) => fs.readFileSync(file, "utf8"), - }; -} - -test("app-server 参数工厂只补两处基础参数展开", () => { - const result = patchSource(createBundle()); - - assert.equal(result.status, "patched"); - assert.equal(result.count, 2); - assert.equal( - result.source.split(RUNTIME_REQUIRE).length - 1, - 2, - ); - assert.equal(patchSource(result.source).status, "already-patched"); -}); - -test("未知上游参数结构会明确失败", () => { - const source = createBundle().replace("...base,...e", "...e"); - assert.equal(patchSource(source).status, "unexpected-spread-count"); -}); - -test("自定义 base_url 的 API key 通过环境传递并启用受限能力", (t) => { - const runtime = createRuntime( - t, - [ - 'model_provider = "My.Provider"', - '[model_providers."My.Provider"]', - 'name = "OpenAI"', - 'base_url = "https://gateway.example.test/v1"', - 'wire_api = "responses"', - "requires_openai_auth = true", - ].join("\n"), - { auth_mode: "apikey", OPENAI_API_KEY: "test-secret" }, - { WSLENV: "EXISTING/u" }, - ); - const baseArgs = ["-c", "features.code_mode_host=true"]; - const result = withImageGenerationAuth(baseArgs, runtime); - - assert.deepEqual(baseArgs, ["-c", "features.code_mode_host=true"]); - assert.equal(runtime.env[API_KEY_ENV], "test-secret"); - assert.match(runtime.env.WSLENV, new RegExp(`(?:^|:)${API_KEY_ENV}(?::|$)`)); - assert.ok(result.includes("features.image_generation=true")); - assert.ok(result.includes("features.api_key_model_discovery=true")); - assert.ok( - result.includes( - 'model_providers."My.Provider".model_catalog_url="https://gateway.example.test/v1/models"', - ), - ); - assert.ok( - result.includes( - 'model_providers."My.Provider".requires_openai_auth=false', - ), - ); - assert.ok( - result.includes( - `model_providers."My.Provider".http_headers.${ACTOR_HEADER}="api-key"`, - ), - ); - assert.ok( - result.includes( - `model_providers."My.Provider".env_key="${API_KEY_ENV}"`, - ), - ); - assert.equal(result.some((arg) => arg.includes("test-secret")), false); -}); - -test("官方地址、非 API-key 认证和显式禁用全部能力时保持上游行为", (t) => { - const cases = [ - { - config: [ - 'model_provider = "OpenAI"', - "[model_providers.OpenAI]", - 'base_url = "https://api.openai.com/v1"', - "requires_openai_auth = true", - ].join("\n"), - auth: { auth_mode: "apikey", OPENAI_API_KEY: "unused" }, - }, - { - config: [ - 'model_provider = "OpenAI"', - "[model_providers.OpenAI]", - 'base_url = "https://gateway.example.test"', - "requires_openai_auth = true", - ].join("\n"), - auth: { auth_mode: "chatgpt", OPENAI_API_KEY: "unused" }, - }, - { - config: [ - 'model_provider = "OpenAI"', - "[features]", - "image_generation = false", - "api_key_model_discovery = false", - "[model_providers.OpenAI]", - 'base_url = "https://gateway.example.test"', - "requires_openai_auth = true", - ].join("\n"), - auth: { auth_mode: "apikey", OPENAI_API_KEY: "unused" }, - }, - ]; - - for (const entry of cases) { - const runtime = createRuntime(t, entry.config, entry.auth); - assert.equal(resolvePatch(runtime), null); - assert.equal(runtime.env[API_KEY_ENV], undefined); - } -}); - -test("静态模型目录优先,远端发现不会覆盖用户配置", (t) => { - const runtime = createRuntime( - t, - [ - 'model_provider = "proxy"', - 'model_catalog_json = "C:/configured/models.json"', - "[model_providers.proxy]", - 'base_url = "https://gateway.example.test/v1"', - 'wire_api = "responses"', - "requires_openai_auth = true", - ].join("\n"), - { auth_mode: "apikey", OPENAI_API_KEY: "test-secret" }, - ); - const patch = resolvePatch(runtime); - - assert.ok(patch); - assert.ok(patch.overrides.includes("features.image_generation=true")); - assert.equal( - patch.overrides.some((value) => value.includes("api_key_model_discovery")), - false, - ); - assert.equal( - patch.overrides.some((value) => value.includes("model_catalog_url")), - false, - ); -}); - -test("显式模型目录地址会被保留", (t) => { - const runtime = createRuntime( - t, - [ - 'model_provider = "proxy"', - "[features]", - "image_generation = false", - "[model_providers.proxy]", - 'base_url = "https://gateway.example.test/v1"', - 'model_catalog_url = "https://catalog.example.test/codex/models"', - "requires_openai_auth = true", - ].join("\n"), - { auth_mode: "apikey", OPENAI_API_KEY: "test-secret" }, - ); - const patch = resolvePatch(runtime); - - assert.ok(patch); - assert.deepEqual( - patch.overrides.filter((value) => value.includes("model_catalog_url")), - [], - ); - assert.ok(patch.overrides.includes("features.api_key_model_discovery=true")); - assert.equal( - patch.overrides.some((value) => value.includes(ACTOR_HEADER)), - false, - ); -}); - -test("默认模型目录地址跟随 provider base_url", () => { - assert.equal( - defaultModelCatalogUrl("https://gateway.example.test/v1/?ignored=yes#hash"), - "https://gateway.example.test/v1/models", - ); - assert.equal( - defaultModelCatalogUrl("http://127.0.0.1:8080"), - "http://127.0.0.1:8080/models", - ); -}); - -test("已有 provider 环境认证时只补能力标记", (t) => { - const runtime = createRuntime( - t, - [ - 'model_provider = "proxy"', - "[model_providers.proxy]", - 'base_url = "http://127.0.0.1:8080/v1"', - "requires_openai_auth = false", - 'env_key = "PROXY_TOKEN"', - ].join("\n"), - null, - { PROXY_TOKEN: "existing-secret" }, - ); - const patch = resolvePatch(runtime); - - assert.ok(patch); - assert.equal(runtime.env[API_KEY_ENV], undefined); - assert.equal(patch.overrides.some((value) => value.includes("env_key=")), false); -}); - -test("打包运行时在没有 node_modules 时使用随包 TOML 解析器", (t) => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), "codex-imagegen-isolated-")); - const home = path.join(root, "home"); - fs.mkdirSync(home); - t.after(() => fs.rmSync(root, { recursive: true, force: true })); - - fs.writeFileSync( - path.join(home, "config.toml"), - [ - 'model_provider = "OpenAI"', - "[model_providers.OpenAI]", - 'base_url = "https://gateway.example.test/v1"', - 'wire_api = "responses"', - "requires_openai_auth = true", - ].join("\n"), - ); - fs.writeFileSync( - path.join(home, "auth.json"), - JSON.stringify({ auth_mode: "api-key", OPENAI_API_KEY: "isolated-secret" }), - ); - assert.equal(syncRuntimeFiles(root, false), 2); - - const child = spawnSync( - process.execPath, - [ - "-e", - [ - `const m=require(${JSON.stringify(`./${RUNTIME_FILENAME}`)});`, - 'const args=m.withImageGenerationAuth(["app-server"]);', - "console.log(JSON.stringify({", - "envSet:Boolean(process.env[m.API_KEY_ENV]),", - 'hasFeature:args.includes("features.image_generation=true"),', - 'hasModelDiscovery:args.includes("features.api_key_model_discovery=true"),', - "secretInArgs:args.includes(process.env[m.API_KEY_ENV])", - "}));", - ].join(""), - ], - { - cwd: root, - encoding: "utf8", - env: { ...process.env, CODEX_HOME: home, NODE_PATH: "" }, - }, - ); - - assert.equal(child.status, 0, child.stderr); - assert.deepEqual(JSON.parse(child.stdout), { - envSet: true, - hasFeature: true, - hasModelDiscovery: true, - secretInArgs: false, - }); -}); diff --git a/scripts/patch-policy.js b/scripts/patch-policy.js index 317a4be5..72ff4b81 100644 --- a/scripts/patch-policy.js +++ b/scripts/patch-policy.js @@ -18,10 +18,11 @@ const PATCH_POLICY = [ { script: "patch-fast-mode.js", feature: "API-key Fast 模式" }, { script: "patch-realtime-voice-auth.js", feature: "API-key 实时语音" }, { script: "patch-codex-home-env.js", feature: "用户配置目录传递" }, - { script: "patch-image-generation-auth.js", feature: "API-key 图片生成" }, { script: "patch-windows-portable-runtime.js", feature: "Windows 便携运行时" }, { script: "patch-test-isolation.js", feature: "Windows 验收数据隔离" }, { script: "patch-provider-quota.js", feature: "真实 Provider 额度发送门槛" }, + { script: "patch-accent-presets.js", feature: "API-key 本地强调色预设" }, + { script: "patch-hide-pet-menu.js", feature: "隐藏 Pet 菜单入口" }, { script: "patch-reading-layout.js", feature: "可配置正文宽度与排版" }, { script: "patch-model-catalog-filter.js", feature: "模型目录过滤" }, { script: "patch-model-picker-submenu.js", feature: "模型选择器子菜单" }, diff --git a/scripts/patch-reading-layout.js b/scripts/patch-reading-layout.js index d6aaba1b..c2870d48 100644 --- a/scripts/patch-reading-layout.js +++ b/scripts/patch-reading-layout.js @@ -6,6 +6,7 @@ const { parse } = require("acorn"); const { SRC_DIR } = require("./patch-util"); const MODULE = "codex-rebuild-reading-width.js"; const MARKER = "__CodexRebuildReadingWidth"; +const PLACEMENT_MARKER = "/* codex-rebuild-reading-width:visual-card */"; function walk(node, visit) { if (!node || typeof node !== "object") return; @@ -47,7 +48,9 @@ function patchDialogs(source) { function patchSettings(source) { if (source.includes(MARKER)) { - if (!source.includes(MODULE) || !source.includes(`jsx)(${MARKER}`)) throw new Error("阅读布局标记不完整"); + if (!source.includes(MODULE) || !source.includes(`jsx)(${MARKER}`) || !source.includes(PLACEMENT_MARKER)) { + throw new Error("阅读布局标记不完整或仍使用旧版卡片外布局"); + } return source; } const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); @@ -65,6 +68,35 @@ function patchSettings(source) { if (arrays.length !== 1 || !states.length || new Set(states).size !== 1) throw new Error("外观设置 React/行结构未知"); const child = arrays[0].elements.find(element => element?.type === "CallExpression" && element.arguments[1]?.properties?.some(prop => key(prop.key) === "section" && literal(prop.value) === "visual")); const jsx = child.callee.expressions.at(-1).object.name; + const themeComponent = child.arguments[0]?.name; + const themeFunctions = ast.body.filter(node => node.type === "FunctionDeclaration" && node.id?.name === themeComponent); + if (themeFunctions.length !== 1) throw new Error("原生主题卡片列表结构未知"); + const variantCalls = []; + walk(themeFunctions[0], node => { + if (node.type !== "CallExpression" || node.arguments[0]?.type !== "Identifier" || node.arguments[1]?.type !== "ObjectExpression") return; + const names = node.arguments[1].properties.map(prop => key(prop.key)); + if (["section", "showVariantTitle", "variant"].every(name => names.includes(name))) variantCalls.push(node); + }); + if (variantCalls.length !== 1) throw new Error("原生主题变体组件结构未知"); + const variantComponent = variantCalls[0].arguments[0].name; + const variantFunctions = ast.body.filter(node => node.type === "FunctionDeclaration" && node.id?.name === variantComponent); + if (variantFunctions.length !== 1) throw new Error("原生主题设置卡片结构未知"); + let appearanceProps; + walk(variantFunctions[0], node => { + if (appearanceProps || node.type !== "VariableDeclarator" || node.id?.type !== "ObjectPattern") return; + const entries = Object.fromEntries(node.id.properties.filter(prop => prop.value?.type === "Identifier").map(prop => [key(prop.key), prop.value.name])); + if (["section", "showVariantTitle", "variant"].every(name => entries[name])) appearanceProps = entries; + }); + const cardCalls = []; + walk(variantFunctions[0], node => { + if (node.type !== "CallExpression" || node.arguments[1]?.type !== "ObjectExpression") return; + const properties = Object.fromEntries(node.arguments[1].properties.map(prop => [key(prop.key), prop])); + if (properties.headerControl && properties.children?.value?.type === "ArrayExpression") cardCalls.push({ node, children: properties.children.value }); + }); + if (!appearanceProps || cardCalls.length !== 1) throw new Error("原生主题设置卡片内容结构未知"); + const cardCallee = cardCalls[0].node.callee.expressions?.at(-1); + if (cardCallee?.type !== "MemberExpression" || cardCallee.object?.type !== "Identifier") throw new Error("原生主题设置 JSX 结构未知"); + const cardJsx = cardCallee.object.name; const fonts = ast.body.filter(node => node.type === "FunctionDeclaration" && source.slice(node.start, node.end).includes("settings.appearance.uiFontSize.description")); if (fonts.length !== 1) throw new Error("原生设置行结构未知"); let row; @@ -83,9 +115,10 @@ function patchSettings(source) { } }); if (!row || !intlCalls.length || new Set(intlCalls).size !== 1) throw new Error("原生设置行/语言上下文未知"); - const at = arrays[0].end - 1; + const at = cardCalls[0].children.end - 1; + const placement = `,${PLACEMENT_MARKER}${appearanceProps.section}===\`visual\`&&(!${appearanceProps.showVariantTitle}||${appearanceProps.variant}===\`dark\`)&&(0,${cardJsx}.jsx)(${MARKER},{})`; const result = `import {renderReadingWidth as __renderCodexReadingWidth} from "./${MODULE}";\n` - + source.slice(0, at) + `,(0,${jsx}.jsx)(${MARKER},{})` + source.slice(at) + + source.slice(0, at) + placement + source.slice(at) + `\nfunction ${MARKER}(){return __renderCodexReadingWidth(${states[0]},${jsx},${row},${intlCalls[0]}());}\n`; parse(result, { ecmaVersion: "latest", sourceType: "module" }); return result; @@ -110,7 +143,7 @@ function main() { if (dialogTargets.length !== 1) throw new Error("原生对话框资源缺失或不唯一"); const dialogPath = path.join(directory, dialogTargets[0]); const dialogPatched = patchDialogs(fs.readFileSync(dialogPath, "utf8")); - if (process.argv.includes("--check")) { console.log("[ok] 原生外观设置/响应式正文结构已核对,8 档宽度及排版样式可注入"); return; } + if (process.argv.includes("--check")) { console.log("[ok] 原生外观设置/响应式正文结构已核对,百分比扩宽档位可注入主题卡片"); return; } fs.writeFileSync(settingsPath, patched); fs.writeFileSync(entryPath, entryPatched); fs.writeFileSync(dialogPath, dialogPatched); diff --git a/scripts/reading-layout-smoke.js b/scripts/reading-layout-smoke.js index 83a52bd8..f09034cc 100644 --- a/scripts/reading-layout-smoke.js +++ b/scripts/reading-layout-smoke.js @@ -4,29 +4,37 @@ const http = require("node:http"); const fs = require("node:fs"); const path = require("node:path"); const html = `阅读布局功能验证 - +

阅读布局功能验证

模拟官方布局契约,执行真实阅读偏好模块;完整设置页面仍需候选 GUI 验收。

运行中
粗体内容
代码块
表格
输入区域
对话框
+ `; const server = http.createServer((req,res)=>{ diff --git a/scripts/runtime/image-generation-auth.cjs b/scripts/runtime/image-generation-auth.cjs deleted file mode 100644 index 5a689699..00000000 --- a/scripts/runtime/image-generation-auth.cjs +++ /dev/null @@ -1,169 +0,0 @@ -const API_KEY_ENV = "CODEX_REBUILD_IMAGE_GENERATION_API_KEY"; -const ACTOR_HEADER = "x-openai-actor-authorization"; -const ACTOR_HEADER_VALUE = "api-key"; - -function loadTomlParser() { - try { - return require("smol-toml").parse; - } catch { - return require("./codex-image-generation-toml.cjs").parse; - } -} - -function defaultRuntime() { - const fs = require("node:fs"); - const os = require("node:os"); - const path = require("node:path"); - return { - env: process.env, - homedir: () => os.homedir(), - join: (...parts) => path.join(...parts), - parseToml: loadTomlParser(), - readFile: (file) => fs.readFileSync(file, "utf8"), - }; -} - -function isNonEmptyString(value) { - return typeof value === "string" && value.trim().length > 0; -} - -function isCustomBaseUrl(value) { - if (!isNonEmptyString(value)) return false; - try { - const url = new URL(value); - if (url.protocol !== "http:" && url.protocol !== "https:") return false; - const hostname = url.hostname.toLowerCase(); - return !( - hostname === "openai.com" || - hostname.endsWith(".openai.com") || - hostname === "chatgpt.com" || - hostname.endsWith(".chatgpt.com") - ); - } catch { - return false; - } -} - -function defaultModelCatalogUrl(baseUrl) { - const url = new URL(baseUrl); - url.pathname = `${url.pathname.replace(/\/+$/, "")}/models`; - url.search = ""; - url.hash = ""; - return url.toString(); -} - -function dottedKeySegment(value) { - return /^[A-Za-z0-9_-]+$/.test(value) ? value : JSON.stringify(value); -} - -function readJson(runtime, file) { - return JSON.parse(runtime.readFile(file)); -} - -function hasConfiguredProviderAuth(provider, env) { - if (provider.requires_openai_auth !== false) return false; - if ( - isNonEmptyString(provider.env_key) && - isNonEmptyString(env[provider.env_key]) - ) { - return true; - } - if (isNonEmptyString(provider.experimental_bearer_token)) return true; - return provider.auth != null && typeof provider.auth === "object"; -} - -function addWslenvEntry(env, name) { - const entries = isNonEmptyString(env.WSLENV) - ? env.WSLENV.split(":").filter(Boolean) - : []; - const exists = entries.some( - (entry) => entry.split("/", 1)[0].toUpperCase() === name.toUpperCase(), - ); - if (!exists) env.WSLENV = [...entries, name].join(":"); -} - -function resolvePatch(runtime = defaultRuntime()) { - try { - const env = runtime.env; - const configuredHome = isNonEmptyString(env.CODEX_HOME) - ? env.CODEX_HOME.trim() - : runtime.join(runtime.homedir(), ".codex"); - const config = runtime.parseToml( - runtime.readFile(runtime.join(configuredHome, "config.toml")), - ); - - const providerId = config.model_provider; - const provider = config.model_providers?.[providerId]; - if (!isNonEmptyString(providerId) || provider == null) return null; - if (!isCustomBaseUrl(provider.base_url)) return null; - if (provider.wire_api != null && provider.wire_api !== "responses") { - return null; - } - - const imageGenerationEnabled = - config.features?.image_generation !== false; - const modelDiscoveryEnabled = - config.model_catalog_json == null && - config.features?.api_key_model_discovery !== false; - if (!imageGenerationEnabled && !modelDiscoveryEnabled) return null; - - let needsEnvOverride = !hasConfiguredProviderAuth(provider, env); - if (needsEnvOverride) { - const auth = readJson(runtime, runtime.join(configuredHome, "auth.json")); - const apiKey = auth.OPENAI_API_KEY; - const authMode = String(auth.auth_mode ?? "") - .trim() - .toLowerCase() - .replaceAll("_", "") - .replaceAll("-", ""); - if (!isNonEmptyString(apiKey)) return null; - if (authMode && authMode !== "apikey") return null; - env[API_KEY_ENV] = apiKey.trim(); - addWslenvEntry(env, API_KEY_ENV); - } - - const providerPath = `model_providers.${dottedKeySegment(providerId)}`; - const overrides = [`${providerPath}.requires_openai_auth=false`]; - if (imageGenerationEnabled) { - overrides.push( - "features.image_generation=true", - `${providerPath}.http_headers.${ACTOR_HEADER}=${JSON.stringify(ACTOR_HEADER_VALUE)}`, - ); - } - if (modelDiscoveryEnabled) { - overrides.push("features.api_key_model_discovery=true"); - if (!isNonEmptyString(provider.model_catalog_url)) { - overrides.push( - `${providerPath}.model_catalog_url=${JSON.stringify(defaultModelCatalogUrl(provider.base_url))}`, - ); - } - } - if (needsEnvOverride) { - overrides.push(`${providerPath}.env_key=${JSON.stringify(API_KEY_ENV)}`); - } - - return { overrides }; - } catch { - // 配置、认证或 TOML 解析失败时保持上游行为,避免阻断 app-server 启动。 - return null; - } -} - -function withImageGenerationAuth(baseArgs, runtime) { - const patch = resolvePatch(runtime); - if (patch == null) return baseArgs; - return [ - ...baseArgs, - ...patch.overrides.flatMap((override) => ["-c", override]), - ]; -} - -module.exports = { - ACTOR_HEADER, - ACTOR_HEADER_VALUE, - API_KEY_ENV, - defaultModelCatalogUrl, - isCustomBaseUrl, - resolvePatch, - withImageGenerationAuth, -}; diff --git a/scripts/runtime/reading-width.mjs b/scripts/runtime/reading-width.mjs index a5d84f9d..d2744c71 100644 --- a/scripts/runtime/reading-width.mjs +++ b/scripts/runtime/reading-width.mjs @@ -1,73 +1,133 @@ -// 只保存阅读布局偏好,认证、Provider 与任务配置由原程序管理。 -export const WIDTHS = ["default", "800", "960", "1120", "1280", "1440", "1600", "full"]; +// 只保存阅读布局与 Markdown 粗体样式偏好,认证、Provider 与任务配置由原程序管理。 +export const WIDTHS = ["default", "85", "100"]; export const STORAGE_KEY = "codex-rebuild:reading-width:v1"; +export const BOLD_COLOR_MODES = ["default", "accent", "custom"]; +export const BOLD_MODE_STORAGE_KEY = "codex-rebuild:markdown-bold-color-mode:v1"; +export const BOLD_CUSTOM_COLOR_STORAGE_KEY = "codex-rebuild:markdown-bold-custom-color:v1"; +export const DEFAULT_BOLD_CUSTOM_COLOR = "#7c3aed"; const STYLE_ID = "codex-rebuild-reading-style"; +const COLOR_PATTERN = /^#[0-9a-f]{6}$/i; let installed = false; -export function readingCss(value) { +export function readingCss(value, boldMode = "default", customColor = DEFAULT_BOLD_CUSTOM_COLOR) { if (!WIDTHS.includes(value)) throw new Error("未知的正文宽度档位"); - const width = value === "full" ? "100%" : `${value}px`; - const selected = value === "default" ? "" : `html[data-codex-rebuild-reading-width] body{--thread-content-max-width:${width};--thread-content-expanded-max-width:${width};--thread-content-compact-max-width:${width}}`; + if (!BOLD_COLOR_MODES.includes(boldMode)) throw new Error("未知的 Markdown 粗体颜色模式"); + if (boldMode === "custom" && !COLOR_PATTERN.test(customColor)) throw new Error("Markdown 粗体自定义颜色无效"); + const expanded = `min(100%,max(48rem,${value}%))`; + const compact = `min(100%,max(40rem,${value}%))`; + const selected = value === "default" ? "" : `html[data-codex-rebuild-reading-width] body{--thread-content-max-width:${expanded};--thread-content-expanded-max-width:${expanded};--thread-content-compact-max-width:${compact}}`; + const boldSelector = ":is([data-codex-window-type=browser],[data-codex-window-type=chrome-extension],[data-codex-window-type=electron]) [data-selected-text-overlay-target] strong"; + const bold = boldMode === "default" ? "" : `${boldSelector}{color:${boldMode === "accent" ? "var(--app-color-text-accent,var(--codex-base-accent,currentColor))" : customColor.toLowerCase()}}`; return `${selected} -[data-selected-text-overlay-target]{--markdown-wide-block-max-width:var(--thread-content-max-width,100%)} -:is([data-codex-window-type=browser],[data-codex-window-type=chrome-extension],[data-codex-window-type=electron]) [data-selected-text-overlay-target] strong{color:var(--color-token-charts-green,var(--green-500,#00a240))} +[data-selected-text-overlay-target]{--markdown-wide-block-max-width:100%} +${bold} ${Object.entries({ narrow: 520, feature: 600, compact: 640, wide: 800, xwide: 860, xxwide: 1040, editor: 800, default: 720 }).map(([name, size]) => `.codex-dialog.codex-rebuild-dialog-${name}{width:min(${size}px,calc(100vw / var(--codex-window-zoom,1) - 32px));max-width:calc(100vw / var(--codex-window-zoom,1) - 32px)}`).join("\n")} `; } -function preference() { +function widthPreference() { const value = localStorage.getItem(STORAGE_KEY) ?? "default"; - if (!WIDTHS.includes(value)) throw new Error("正文宽度设置无效,请重新选择"); - return value; + return WIDTHS.includes(value) ? value : "default"; } -function apply(value) { +function boldModePreference() { + const value = localStorage.getItem(BOLD_MODE_STORAGE_KEY) ?? "default"; + return BOLD_COLOR_MODES.includes(value) ? value : "default"; +} + +function boldCustomColorPreference() { + const value = localStorage.getItem(BOLD_CUSTOM_COLOR_STORAGE_KEY) ?? DEFAULT_BOLD_CUSTOM_COLOR; + return COLOR_PATTERN.test(value) ? value.toLowerCase() : DEFAULT_BOLD_CUSTOM_COLOR; +} + +function apply(width = widthPreference(), boldMode = boldModePreference(), customColor) { + const resolvedColor = customColor ?? (boldMode === "custom" ? boldCustomColorPreference() : DEFAULT_BOLD_CUSTOM_COLOR); let style = document.getElementById(STYLE_ID); if (!style) { style = document.createElement("style"); style.id = STYLE_ID; document.head.append(style); } - style.textContent = readingCss(value); - document.documentElement.dataset.codexRebuildReadingWidth = value; + style.textContent = readingCss(width, boldMode, resolvedColor); + document.documentElement.dataset.codexRebuildReadingWidth = width; + document.documentElement.dataset.codexRebuildBoldColor = boldMode; } export function installReadingStyle() { if (installed || typeof document === "undefined") return; installed = true; - try { apply(preference()); } catch (error) { console.error("[rebuild-reading]", error.message); apply("default"); } + apply(); window.addEventListener("storage", event => { - if (event.key !== STORAGE_KEY && event.key !== null) return; - try { apply(preference()); window.dispatchEvent(new Event("codex-rebuild-reading-change")); } - catch (error) { console.error("[rebuild-reading]", error.message); } + if (![STORAGE_KEY, BOLD_MODE_STORAGE_KEY, BOLD_CUSTOM_COLOR_STORAGE_KEY, null].includes(event.key)) return; + apply(); window.dispatchEvent(new Event("codex-rebuild-reading-change")); }); } export function renderReadingWidth(react, ui, Row, intl) { const chinese = String(intl.locale).startsWith("zh"); - const [value, setValue] = react.useState(() => { try { return preference(); } catch { return "default"; } }); - const [error, setError] = react.useState(() => { try { preference(); return ""; } catch (error) { return error.message; } }); + const [value, setValue] = react.useState(widthPreference); + const [boldMode, setBoldMode] = react.useState(boldModePreference); + const [boldColor, setBoldColor] = react.useState(boldCustomColorPreference); react.useEffect(() => { - const update = () => { try { setValue(preference()); setError(""); } catch (error) { setError(error.message); } }; + const update = () => { + const mode = boldModePreference(); + setValue(widthPreference()); setBoldMode(mode); + if (mode === "custom") setBoldColor(boldCustomColorPreference()); + }; window.addEventListener("codex-rebuild-reading-change", update); return () => window.removeEventListener("codex-rebuild-reading-change", update); }, []); - return ui.jsx(Row, { - label: chinese ? "聊天正文宽度" : "Chat content width", - description: error || (chinese ? "正文、输入区域及代码块/表格同步调整,窗口较窄时自动收缩。" : "Adjust chats, composer and wide blocks; shrink to fit smaller windows."), - control: ui.jsxs("select", { - "aria-label": chinese ? "聊天正文宽度" : "Chat content width", - "data-codex-rebuild-width-control": "true", - className: "rounded-md border border-default bg-surface px-3 py-1.5 text-sm text-default", - value, - onChange: event => { - const next = event.currentTarget.value; - try { - if (!WIDTHS.includes(next)) throw new Error("未知的正文宽度档位"); - localStorage.setItem(STORAGE_KEY, next); apply(next); setValue(next); setError(""); + const controlClass = "rounded-md border border-default bg-surface px-3 py-1.5 text-sm text-default"; + return ui.jsxs(react.Fragment, { children: [ + ui.jsx(Row, { + size: "compact", + label: chinese ? "聊天正文宽度" : "Chat content width", + control: ui.jsxs("select", { + "aria-label": chinese ? "聊天正文宽度" : "Chat content width", + "data-codex-rebuild-width-control": "true", + className: controlClass, + value, + onChange: event => { + const next = event.currentTarget.value; + localStorage.setItem(STORAGE_KEY, next); apply(next, boldModePreference()); setValue(next); window.dispatchEvent(new Event("codex-rebuild-reading-change")); - } catch (error) { setError(error.message); } - }, - children: WIDTHS.map(option => ui.jsx("option", { value: option, - children: option === "default" ? (chinese ? "默认" : "Default") : option === "full" ? (chinese ? "全宽" : "Full width") : `${option} ${chinese ? "像素" : "px"}` }, option)), - }), - }); + }, + children: WIDTHS.map(option => ui.jsx("option", { value: option, + children: option === "default" ? (chinese ? "默认" : "Default") : `${option}%` }, option)), + }), + }, "codex-rebuild-reading-width"), + ui.jsx(Row, { + size: "compact", + label: chinese ? "Markdown 粗体颜色" : "Markdown bold color", + control: ui.jsxs("div", { className: "flex items-center gap-2", children: [ + ui.jsxs("select", { + "aria-label": chinese ? "Markdown 粗体颜色" : "Markdown bold color", + "data-codex-rebuild-bold-color-control": "true", + className: controlClass, + value: boldMode, + onChange: event => { + const next = event.currentTarget.value; + localStorage.setItem(BOLD_MODE_STORAGE_KEY, next); apply(widthPreference(), next); setBoldMode(next); + window.dispatchEvent(new Event("codex-rebuild-reading-change")); + }, + children: BOLD_COLOR_MODES.map(option => ui.jsx("option", { value: option, children: ({ + default: chinese ? "跟随正文" : "Text color", + accent: chinese ? "跟随强调色" : "Accent color", + custom: chinese ? "自定义" : "Custom", + })[option] }, option)), + }), + boldMode === "custom" && ui.jsx("input", { + type: "color", + "aria-label": chinese ? "Markdown 粗体自定义颜色" : "Custom Markdown bold color", + "data-codex-rebuild-bold-custom-color": "true", + className: "h-8 w-10 cursor-pointer rounded border border-default bg-surface p-1", + value: boldColor, + onChange: event => { + const next = event.currentTarget.value.toLowerCase(); + localStorage.setItem(BOLD_CUSTOM_COLOR_STORAGE_KEY, next); localStorage.setItem(BOLD_MODE_STORAGE_KEY, "custom"); + apply(widthPreference(), "custom", next); setBoldColor(next); setBoldMode("custom"); + window.dispatchEvent(new Event("codex-rebuild-reading-change")); + }, + }), + ] }), + }, "codex-rebuild-markdown-bold-color"), + ] }); } installReadingStyle(); From 9d27b88d7ac3a5398e238c3188e3ade1c52f2c28 Mon Sep 17 00:00:00 2001 From: carptopus Date: Fri, 16 Oct 2026 00:19:50 +0800 Subject: [PATCH 03/51] Refine API-key appearance and home navigation --- README.md | 5 +- scripts/check-scripts.js | 1 + scripts/frontend-source-smoke.js | 26 ++- scripts/patch-accent-presets.js | 165 ++++++++------ scripts/patch-accent-presets.test.js | 172 +++++++++++---- scripts/patch-api-key-home-navigation.js | 204 ++++++++++++++++++ scripts/patch-api-key-home-navigation.test.js | 69 ++++++ scripts/patch-policy.js | 1 + scripts/reading-layout-smoke.js | 21 +- scripts/reading-width.test.js | 59 +++++ scripts/runtime/accent-presets.mjs | 56 +++++ scripts/runtime/reading-width.mjs | 50 +++-- 12 files changed, 695 insertions(+), 134 deletions(-) create mode 100644 scripts/patch-api-key-home-navigation.js create mode 100644 scripts/patch-api-key-home-navigation.test.js create mode 100644 scripts/reading-width.test.js create mode 100644 scripts/runtime/accent-presets.mjs diff --git a/README.md b/README.md index 803f8fd7..6648e483 100644 --- a/README.md +++ b/README.md @@ -40,9 +40,10 @@ npm run build:all - `src//plugins` 与 `src//cua_node` 是 Browser / Computer Use 等外置运行时的补丁目标;直打包流程会显式覆盖这两个目录,避免重新复制上游安装包缓存时丢失补丁。 - `patch-browser-auth.js` 兼容 API-key 登录:ChatGPT 身份与 request-header 策略可用时保持原行为;身份读取失败时仅关闭该可选请求头并继续本地浏览器通道,不会把 API key 伪装或发送为 ChatGPT token。 - `patch-provider-quota.js` 按任务实际 Provider 和明确的 `base_url` 判断发送门槛,避免 ChatGPT 额度状态误阻断第三方 Provider,同时保留官方、云任务及第三方真实错误。 -- `patch-accent-presets.js` 允许没有 ChatGPT 账户主题的 API-key / 自定义 Provider 在本地选择官方强调色预设;账户主题仍在加载时保持禁用,账户可用时继续使用官方同步。 +- `patch-api-key-home-navigation.js` 补齐 API-key 模式的当前会话导航记录,使首页入口按官方读取逻辑恢复当前会话;ChatGPT、无认证及其他认证方式保持原有条件。 +- `patch-accent-presets.js` 允许没有 ChatGPT 账户主题的 API-key / 自定义 Provider 在本地选择强调色,并复用官方完整预设渲染消息气泡等界面变量;账户主题仍在加载时保持禁用,账户可用时继续使用官方同步。 - `patch-hide-pet-menu.js` 只隐藏账户菜单中的 Pet / Mini 入口,保留浮动面板实现、状态和全局快捷键。 -- `patch-reading-layout.js` 在外观主题卡片中加入默认、85%、100% 三档正文宽度,并同步代码块、表格和输入区宽度,扩宽适用对话框;Markdown 粗体颜色可跟随正文、强调色或使用自定义颜色。 +- `patch-reading-layout.js` 在外观主题卡片中加入 50%–100%、步进 5% 的正文宽度滑杆,并同步代码块、表格和输入区宽度,扩宽适用对话框;百分比不低于官方宽度,Markdown 粗体颜色可跟随正文、强调色或使用自定义颜色。 - `patch-test-isolation.js` 在官方设置 User Data 后、获取单实例锁前挂载 Windows 验收隔离,分别约束 `CODEX_HOME`、User Data 和 sessionData,并记录实际启动路径证据。 - `patch-model-picker-submenu.js` 增加对新版原生 simple / advanced 内联模型列表的结构核验;官方实现完整时保持原样,旧结构继续适配,未知结构明确失败。 - `patch-updater.js` 区分更新方法与调用 Bundle,并在补丁后核对更新方法确实返回禁用状态;缺少目标或结构未知不再误报为已关闭。 diff --git a/scripts/check-scripts.js b/scripts/check-scripts.js index 6cf935ae..51b27eda 100644 --- a/scripts/check-scripts.js +++ b/scripts/check-scripts.js @@ -8,6 +8,7 @@ files.push("../forge.config.js"); files.push("runtime/rebuild-test-isolation.cjs"); files.push("runtime/rebuild-test-environment.cjs"); files.push("runtime/reading-width.mjs"); +files.push("runtime/accent-presets.mjs"); for (const file of files) execFileSync(process.execPath, ["--check", path.join(__dirname, file)], { stdio: "inherit" }); JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")); console.log(`脚本语法检查通过:${files.length} 个文件`); diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index 69c12611..96450926 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -67,9 +67,29 @@ function verifyFrontendSource(assets) { const settingsSource = fs.readFileSync(path.join(assets, settings[0]), "utf8"); assert.match(settingsSource, /jsx\)\(__CodexRebuildReadingWidth/); assert.match(settingsSource, /codex-rebuild-reading-width:visual-card/); - assert.match(settingsSource, /codex-rebuild-local-accent-presets/); - assert.match(settingsSource, /__codexSelectAccent/); + assert.match(settingsSource, /codex-rebuild-local-accent-presets:settings/); + assert.match(settingsSource, /codex-rebuild-accent-presets\.js/); + assert.match(settingsSource, /__codexSelectAccentPreset/); + const themeEntries = files.filter(name => /^app-initial-/.test(name) + && fs.readFileSync(path.join(assets, name), "utf8").includes("codex-rebuild-local-accent-presets:theme")); + assert.equal(themeEntries.length, 1); + const themeSource = fs.readFileSync(path.join(assets, themeEntries[0]), "utf8"); + assert.match(themeSource, /__codexResolveAccentPreset/); + assert.match(themeSource, /accentSource:`chatgpt`/); + const navigationEntries = files.filter(name => /^app-initial-/.test(name) + && fs.readFileSync(path.join(assets, name), "utf8").includes("Codex:API-key 首页恢复写入。")); + assert.equal(navigationEntries.length, 1); + const navigationSource = fs.readFileSync(path.join(assets, navigationEntries[0]), "utf8"); + assert.match(navigationSource, /\|\|\/\* Codex:API-key 首页恢复写入。 \*\/[A-Za-z_$][\w$]*===`apikey`/); + const accentModule = fs.readFileSync(path.join(assets, "codex-rebuild-accent-presets.js"), "utf8"); + assert.match(accentModule, /codex-rebuild:accent-preset:v1/); + assert.match(accentModule, /export function resolveAccentPreset/); + assert.doesNotMatch(accentModule, /getComputedStyle|#[0-9a-f]{6}/i); const readingModule = fs.readFileSync(path.join(assets, "codex-rebuild-reading-width.js"), "utf8"); + assert.match(readingModule, /MIN_WIDTH_PERCENT = 50/); + assert.match(readingModule, /MAX_WIDTH_PERCENT = 100/); + assert.match(readingModule, /WIDTH_STEP = 5/); + assert.match(readingModule, /type: "range"/); assert.match(readingModule, /codex-rebuild:markdown-bold-color-mode:v1/); assert.match(readingModule, /--app-color-text-accent/); assert.doesNotMatch(readingModule, /--color-token-charts-green|--green-500|#00a240/); @@ -78,7 +98,7 @@ function verifyFrontendSource(assets) { assert.equal(shared.length, 1); const dialogs = fs.readFileSync(path.join(assets, shared[0]), "utf8"); assert.match(dialogs, /codex-rebuild-dialog-editor h-\[720px\] max-w-full max-h-full/); - return { passed: true, quotaScenarios: results, nativeAppearanceRow: true, dialogHeightPreserved: true }; + return { passed: true, quotaScenarios: results, apiKeyHomeNavigation: true, nativeAppearanceRow: true, nativeAccentThemePipeline: true, dialogHeightPreserved: true }; } if (require.main === module) console.log(JSON.stringify(verifyFrontendSource(path.resolve(process.argv[2] || "src/win/_asar/webview/assets")), null, 2)); module.exports = { verifyFrontendSource }; diff --git a/scripts/patch-accent-presets.js b/scripts/patch-accent-presets.js index 6576d90c..b8dbf5a5 100644 --- a/scripts/patch-accent-presets.js +++ b/scripts/patch-accent-presets.js @@ -1,24 +1,17 @@ #!/usr/bin/env node /** * 允许没有 ChatGPT 账户主题状态的 API-key / 自定义 Provider 使用官方强调色预设。 - * 账户主题加载中仍保持禁用;账户可用时完整保留官方同步流程。 + * 本地只保存预设名,渲染继续复用官方预设生成器;账户主题可用时仍由账户状态优先。 */ const fs = require("fs"); const path = require("path"); const { parse } = require("acorn"); const { SRC_DIR, relPath } = require("./patch-util"); -const MARKER = "/* codex-rebuild-local-accent-presets */"; -const STORAGE_KEY = "codex-rebuild:accent-preset:v1"; +const MODULE = "codex-rebuild-accent-presets.js"; +const SETTINGS_MARKER = "/* codex-rebuild-local-accent-presets:settings */"; +const THEME_MARKER = "/* codex-rebuild-local-accent-presets:theme */"; const PLATFORMS = ["mac-arm64", "mac-x64", "win", "unix"]; -const HELPER = `${MARKER} -const __codexAccentPresetKey=${JSON.stringify(STORAGE_KEY)},__codexAccentPresets=new Set(["default","blue","green","yellow","pink","orange","purple","black"]); -function __codexStoredAccentPreset(){try{let e=globalThis.localStorage?.getItem(__codexAccentPresetKey);return __codexAccentPresets.has(e)?e:null}catch{return null}} -function __codexAccentSelection(e,t,n){return e===null?__codexStoredAccentPreset()??n:n} -function __codexResolveAccent(e,t,n){let r=e(t,n),i=/^var\\((--[^,\\s)]+)/.exec(r);if(i){let e=globalThis.getComputedStyle?.(globalThis.document?.documentElement)?.getPropertyValue(i[1]).trim();if(e)r=e}if(!/^#[0-9a-f]{6}$/i.test(r))throw Error("无法解析本地强调色预设");return r.toLowerCase()} -function __codexSelectAccent(e,t,n,r,i,a){return Promise.resolve().then(()=>{if(e!==null){globalThis.localStorage?.removeItem(__codexAccentPresetKey);return a()}globalThis.localStorage?.setItem(__codexAccentPresetKey,t);return i(__codexResolveAccent(r,t,n))})} -function __codexUseCustomAccent(e,t){globalThis.localStorage?.removeItem(__codexAccentPresetKey);return e(t)} -`; function walk(node, visit, parent = null) { if (!node || typeof node !== "object" || !node.type) return; @@ -59,14 +52,28 @@ function objectBindings(pattern) { .map(property => [key(property.key), property.value.name])); } -function patchSource(source) { +function importInsertion(ast) { + const imports = ast.body.filter(node => node.type === "ImportDeclaration"); + return imports.length ? imports.at(-1).end : 0; +} + +function applyEdits(source, edits) { + let next = source; + for (const edit of edits.sort((left, right) => right.start - left.start)) { + next = next.slice(0, edit.start) + edit.text + next.slice(edit.end); + } + parse(next, { ecmaVersion: "latest", sourceType: "module" }); + return next; +} + +function patchSettingsSource(source) { if (!source.includes("chatgptAccentPicker.ChatGptAccentPicker.updateError") || !source.includes("accentSource")) { return { status: "not-applicable", source }; } - if (source.includes(MARKER)) { + if (source.includes(SETTINGS_MARKER)) { parse(source, { ecmaVersion: "latest", sourceType: "module" }); - if (!["__codexAccentSelection(", "__codexSelectAccent(", "__codexUseCustomAccent("].every(value => source.includes(value))) { - return { status: "unexpected-shape", source, reason: "本地强调色标记不完整" }; + if (![MODULE, "__codexCurrentAccent=", "__codexAccentSelection(", "__codexSelectAccentPreset(", "__codexUseCustomAccent("].every(value => source.includes(value))) { + return { status: "unexpected-shape", source, reason: "本地强调色设置标记不完整" }; } return { status: "already-patched", source }; } @@ -80,7 +87,6 @@ function patchSource(source) { .map(node => objectBindings(node.id)) .filter(bindings => ["theme", "variant", "onSelect", "onCustomColorChange"].every(name => bindings[name])), "强调色属性"); const theme = props.theme; - const variant = props.variant; const selectAccount = props.onSelect; const selectCustom = props.onCustomColorChange; @@ -93,44 +99,71 @@ function patchSource(source) { source.slice(node.init.start, node.init.end).includes("`chatgpt`") && source.slice(node.init.start, node.init.end).includes("`custom`")), "当前强调色来源"); - const colorCalls = nodes(component, node => node.type === "CallExpression" && node.callee?.type === "Identifier" && - node.arguments.length === 2 && node.arguments[1]?.type === "Identifier" && node.arguments[1].name === variant && - source.slice(node.arguments[0].start, node.arguments[0].end).includes("effectiveTheme")); - const colorFunction = unique(colorCalls, "官方强调色函数").callee.name; - const accountCalls = nodes(component, node => node.type === "CallExpression" && node.callee?.type === "Identifier" && - node.callee.name === selectAccount); - const accountCall = unique(accountCalls, "账户强调色写入"); + const accountCall = unique(nodes(component, node => node.type === "CallExpression" && node.callee?.type === "Identifier" && + node.callee.name === selectAccount), "账户强调色写入"); const preset = accountCall.arguments[0]; if (preset?.type !== "Identifier") throw new Error("强调色预设参数结构未知"); - const customCalls = nodes(component, node => node.type === "CallExpression" && node.callee?.type === "Identifier" && - node.callee.name === selectCustom); - const customCall = unique(customCalls, "切换自定义强调色"); + const customCall = unique(nodes(component, node => node.type === "CallExpression" && node.callee?.type === "Identifier" && + node.callee.name === selectCustom), "切换自定义强调色"); if (customCall.arguments.length !== 1) throw new Error("自定义强调色调用结构未知"); const onChange = unique(nodes(component, node => node.type === "Property" && key(node.key) === "onChange" && node.value?.type === "Identifier" && node.value.name === selectCustom), "自定义颜色输入"); - const imports = ast.body.filter(node => node.type === "ImportDeclaration"); - const insertAt = imports.length ? imports.at(-1).end : 0; + const importAt = importInsertion(ast); + const originalSelection = source.slice(selection.init.start, selection.init.end); + const originalAccountCall = source.slice(accountCall.start, accountCall.end); + const customValue = source.slice(customCall.arguments[0].start, customCall.arguments[0].end); + const moduleImport = `\n${SETTINGS_MARKER}\nimport {accentPresetSelection as __codexAccentSelection,selectAccentPreset as __codexSelectAccentPreset,useCustomAccent as __codexUseCustomAccent} from "./${MODULE}";`; const edits = [ - { start: insertAt, end: insertAt, text: `\n${HELPER}` }, + { start: importAt, end: importAt, text: moduleImport }, + { start: component.body.start + 1, end: component.body.start + 1, + text: `const __codexCurrentAccent=${theme}.accent;` }, { start: selection.init.start, end: selection.init.end, - text: `__codexAccentSelection(${accountTheme},${theme}.accentSource,${source.slice(selection.init.start, selection.init.end)})` }, + text: `__codexAccentSelection(${accountTheme},${originalSelection})` }, // undefined 表示账户主题仍在加载;null 才表示没有可用账户主题。 { start: disabled.value.start, end: disabled.value.end, text: `${accountTheme}===void 0` }, { start: accountCall.start, end: accountCall.end, - text: `__codexSelectAccent(${accountTheme},${preset.name},${variant},${colorFunction},${selectCustom},()=>${source.slice(accountCall.start, accountCall.end)})` }, + text: `__codexSelectAccentPreset(${accountTheme},${preset.name},()=>${selectCustom}(__codexCurrentAccent),()=>${originalAccountCall})` }, { start: customCall.start, end: customCall.end, - text: `__codexUseCustomAccent(${selectCustom},${source.slice(customCall.arguments[0].start, customCall.arguments[0].end)})` }, + text: `__codexUseCustomAccent(${selectCustom},${customValue})` }, { start: onChange.value.start, end: onChange.value.end, text: `__codexColor=>__codexUseCustomAccent(${selectCustom},__codexColor)` }, ]; - let next = source; - for (const edit of edits.sort((left, right) => right.start - left.start)) { - next = next.slice(0, edit.start) + edit.text + next.slice(edit.end); + return { status: "patched", source: applyEdits(source, edits) }; + } catch (error) { + return { status: "unexpected-shape", source, reason: error.message }; + } +} + +function patchThemeSource(source) { + if (!["--color-background-user-message", "--color-image-generation-accent", "accentSource"].every(value => source.includes(value))) { + return { status: "not-applicable", source }; + } + if (source.includes(THEME_MARKER)) { + parse(source, { ecmaVersion: "latest", sourceType: "module" }); + if (![MODULE, "__codexResolveAccentPreset(", "accentSource:`chatgpt`"].every(value => source.includes(value))) { + return { status: "unexpected-shape", source, reason: "本地强调色主题标记不完整" }; + } + return { status: "already-patched", source }; + } + + try { + const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const renderer = unique(ast.body.filter(node => node.type === "FunctionDeclaration" && + ["--color-background-user-message", "--color-image-generation-accent", "accentSource"] + .every(value => source.slice(node.start, node.end).includes(value))), "官方强调色主题函数"); + const [theme, variant, accountPreset] = renderer.params; + if (![theme, variant, accountPreset].every(node => node?.type === "Identifier")) { + throw new Error("官方强调色主题参数结构未知"); } - parse(next, { ecmaVersion: "latest", sourceType: "module" }); - return { status: "patched", source: next }; + const importAt = importInsertion(ast); + const moduleImport = `\n${THEME_MARKER}\nimport {resolveAccentPreset as __codexResolveAccentPreset} from "./${MODULE}";`; + const injection = `const __codexAccentPreset=__codexResolveAccentPreset(${theme.name}.accentSource,${accountPreset.name});if(__codexAccentPreset!==null){${accountPreset.name}=__codexAccentPreset;${theme.name}={...${theme.name},accentSource:\`chatgpt\`}}`; + return { status: "patched", source: applyEdits(source, [ + { start: importAt, end: importAt, text: moduleImport }, + { start: renderer.body.start + 1, end: renderer.body.start + 1, text: injection }, + ]) }; } catch (error) { return { status: "unexpected-shape", source, reason: error.message }; } @@ -145,6 +178,14 @@ function targetDirectories(platform) { return directories; } +function findTarget(directory, pattern, content, label) { + const candidates = fs.readdirSync(directory).filter(name => pattern.test(name)) + .map(name => ({ name, path: path.join(directory, name), source: fs.readFileSync(path.join(directory, name), "utf8") })) + .filter(file => content.every(value => file.source.includes(value))); + if (candidates.length !== 1) throw new Error(`${label}资源数量异常(${candidates.length})`); + return candidates[0]; +} + function main() { const args = process.argv.slice(2); const platform = args.find(arg => PLATFORMS.includes(arg)); @@ -153,34 +194,38 @@ function main() { let failed = 0; let patched = 0; for (const directory of directories) { - const candidates = fs.readdirSync(directory.path).filter(name => /^general-settings-.*\.js$/.test(name)) - .map(name => ({ name, path: path.join(directory.path, name), source: fs.readFileSync(path.join(directory.path, name), "utf8") })) - .filter(file => file.source.includes("chatgptAccentPicker.ChatGptAccentPicker.updateError")); - if (candidates.length !== 1) { - console.error(` [x] ${directory.platform}: 强调色设置资源数量异常(${candidates.length})`); + try { + const settings = findTarget(directory.path, /^general-settings-.*\.js$/, + ["chatgptAccentPicker.ChatGptAccentPicker.updateError"], "强调色设置"); + const theme = findTarget(directory.path, /^app-initial-.*\.js$/, + ["--color-background-user-message", "--color-image-generation-accent", "accentSource"], "强调色主题"); + const settingsResult = patchSettingsSource(settings.source); + const themeResult = patchThemeSource(theme.source); + for (const [label, result] of [["强调色设置", settingsResult], ["强调色主题", themeResult]]) { + if (["unexpected-shape", "not-applicable"].includes(result.status)) { + throw new Error(`${label}:${result.reason ?? "结构未知"}`); + } + } + console.log(` [${directory.platform}] ${relPath(settings.path)}`); + console.log(` [${directory.platform}] ${relPath(theme.path)}`); + if (check) { + console.log(" [ok] 本地预设设置入口与官方主题生成器结构已核对;dry-run 未写文件"); + continue; + } + if (settingsResult.status === "patched") fs.writeFileSync(settings.path, settingsResult.source, "utf8"); + if (themeResult.status === "patched") fs.writeFileSync(theme.path, themeResult.source, "utf8"); + fs.copyFileSync(path.join(__dirname, "runtime", "accent-presets.mjs"), path.join(directory.path, MODULE)); + patched += Number(settingsResult.status === "patched" || themeResult.status === "patched"); + console.log(" [ok] 本地预设已接入官方完整主题渲染;账户主题仍优先"); + } catch (error) { + console.error(` [x] ${directory.platform}: ${error.message}`); failed++; - continue; - } - const target = candidates[0]; - const result = patchSource(target.source); - if (result.status === "unexpected-shape" || result.status === "not-applicable") { - console.error(` [x] ${directory.platform}: ${result.reason ?? "强调色设置结构未知"}`); - failed++; - continue; - } - console.log(` [${directory.platform}] ${relPath(target.path)}`); - if (result.status === "already-patched") console.log(" [ok] 本地强调色预设已启用"); - else if (check) console.log(" [?] 可启用本地强调色预设;dry-run 未写文件"); - else { - fs.writeFileSync(target.path, result.source, "utf8"); - patched++; - console.log(" * 无账户主题时本地应用预设;账户可用时保留官方同步"); } } if (!directories.length) { console.error(" [x] 缺少目标平台界面资源"); failed++; } if (failed) process.exitCode = 1; - else console.log(` [ok] ${patched} bundle(s) patched`); + else console.log(` [ok] ${patched} platform bundle set(s) patched`); } if (require.main === module) main(); -module.exports = { HELPER, MARKER, STORAGE_KEY, patchSource }; +module.exports = { MODULE, SETTINGS_MARKER, THEME_MARKER, patchSettingsSource, patchThemeSource }; diff --git a/scripts/patch-accent-presets.test.js b/scripts/patch-accent-presets.test.js index da161c69..af2340ee 100644 --- a/scripts/patch-accent-presets.test.js +++ b/scripts/patch-accent-presets.test.js @@ -1,63 +1,151 @@ const test = require("node:test"); const assert = require("node:assert/strict"); -const { HELPER, MARKER, STORAGE_KEY, patchSource } = require("./patch-accent-presets"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { pathToFileURL } = require("node:url"); +const { + MODULE, + SETTINGS_MARKER, + THEME_MARKER, + patchSettingsSource, + patchThemeSource, +} = require("./patch-accent-presets"); -function fixture() { +function settingsFixture() { return 'import{palette as P,options as O}from"./app.js";' + 'function Accent(e){let{theme:r,variant:i,onSelect:a,onCustomColorChange:o}=e,s=scope(),u=read(themeAtom),d=read(pendingAtom),' + 'f=r.accentSource===`chatgpt`?u?.chatTheme??`default`:`custom`,v=f!==`custom`&&jsx(`span`,{style:{backgroundColor:P(u?.effectiveTheme??f,i)}}),' + 'x=O.map(e=>jsx(RadioItem,{disabled:u==null,value:e,onSelect:()=>{let t=s.get(account),n=s.get(settings).data,r=t!=null&&n?.eligibleNowOrBefore===!0;' + 'a(e,()=>{r&&sync({accentColor:e})}).catch(()=>{toast("chatgptAccentPicker.ChatGptAccentPicker.updateError")})},children:e},e)),' + - 'S=()=>o(r.accent),D=f===`custom`?jsx(ColorInput,{value:r.accent,onChange:o}):null;return [v,x,S,D]}' ; + 'S=()=>o(r.accent),D=f===`custom`?jsx(ColorInput,{value:r.accent,onChange:o}):null;return [v,x,S,D]}'; } -function helpers() { - return Function(`${HELPER};return {selection:__codexAccentSelection,select:__codexSelectAccent,custom:__codexUseCustomAccent}`)(); +function themeFixture() { + return 'const presets={' + + 'default:{accent:`#default-accent`,userMessageBackground:`#default-bubble`,userMessageText:`#default-text`,soft:`#default-soft`},' + + 'blue:{accent:`#blue-accent`,userMessageBackground:`#blue-bubble`,userMessageText:`#blue-text`,soft:`#blue-soft`},' + + 'green:{accent:`#green-accent`,userMessageBackground:`#green-bubble`,userMessageText:`#green-text`,soft:`#green-soft`},' + + 'black:{accent:`#black-accent`,userMessageBackground:`#black-bubble`,userMessageText:`#black-text`,soft:`#black-soft`}};' + + 'function dba(e,t){return presets[e]}' + + 'function Tba(e,t,n,r=!0,i=!1){let a=e.accentSource===`chatgpt`&&n!=null?dba(n??`default`,t,r):null,' + + 'd={"--color-image-generation-accent":a!=null&&n===`black`?`black-image`:e.accent,"--color-background-user-message":`neutral-bubble`};' + + 'return a==null?d:{...d,"--color-background-user-message":a.userMessageBackground,"--color-text-user-message":a.userMessageText,"--app-color-background-accent":a.soft}}export{Tba}'; } +function fakeStorage(initial = {}) { + const values = new Map(Object.entries(initial)); + return { + values, + getItem: key => values.get(key) ?? null, + setItem: (key, value) => values.set(key, value), + removeItem: key => values.delete(key), + }; +} + +async function runtimeModule() { + return import(pathToFileURL(path.join(__dirname, "runtime", "accent-presets.mjs")).href); +} + +test.afterEach(() => { + delete globalThis.localStorage; +}); + test("无账户主题时启用本地预设并保留加载态禁用", () => { - const result = patchSource(fixture()); + const result = patchSettingsSource(settingsFixture()); assert.equal(result.status, "patched", result.reason); - assert.match(result.source, new RegExp(MARKER.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))); + assert.match(result.source, new RegExp(SETTINGS_MARKER.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))); + assert.match(result.source, new RegExp(MODULE.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))); + assert.match(result.source, /function Accent\(e\)\{const __codexCurrentAccent=r\.accent;/); assert.match(result.source, /disabled:u===void 0/); - assert.match(result.source, /__codexSelectAccent\(u,e,i,P,o,\(\)=>a\(/); + assert.match(result.source, /__codexSelectAccentPreset\(u,e,\(\)=>o\(__codexCurrentAccent\),\(\)=>a\(/); assert.match(result.source, /onChange:__codexColor=>__codexUseCustomAccent\(o,__codexColor\)/); - assert.equal(patchSource(result.source).status, "already-patched"); + assert.equal(patchSettingsSource(result.source).status, "already-patched"); }); -test("未知强调色结构明确失败", () => { - const result = patchSource('const x="chatgptAccentPicker.ChatGptAccentPicker.updateError accentSource"'); - assert.equal(result.status, "unexpected-shape"); +test("设置和主题未知结构均明确失败", () => { + const settings = patchSettingsSource('const x="chatgptAccentPicker.ChatGptAccentPicker.updateError accentSource"'); + assert.equal(settings.status, "unexpected-shape"); + const theme = patchThemeSource('const x="--color-background-user-message --color-image-generation-accent accentSource"'); + assert.equal(theme.status, "unexpected-shape"); }); -test("本地预设使用官方 CSS 色值,账户可用时仍调用官方同步", async () => { - const values = new Map(); - globalThis.localStorage = { - getItem: key => values.get(key) ?? null, - setItem: (key, value) => values.set(key, value), - removeItem: key => values.delete(key), - }; - globalThis.document = { documentElement: {} }; - globalThis.getComputedStyle = () => ({ getPropertyValue: name => name === "--brand-blue-400" ? "#3A83F7" : "" }); - const { selection, select, custom } = helpers(); - let local = null; - let synced = 0; - - await select(null, "blue", "light", () => "var(--brand-blue-400)", value => { local = value; }, () => { synced++; }); - assert.equal(local, "#3a83f7"); - assert.equal(synced, 0); - assert.equal(values.get(STORAGE_KEY), "blue"); - assert.equal(selection(null, "custom", "custom"), "blue"); - - await select({ chatTheme: "default" }, "green", "light", () => "#53b559", () => {}, () => { synced++; }); - assert.equal(synced, 1); - assert.equal(values.has(STORAGE_KEY), false); - - values.set(STORAGE_KEY, "blue"); - custom(value => { local = value; }, "#123456"); - assert.equal(local, "#123456"); - assert.equal(values.has(STORAGE_KEY), false); - delete globalThis.localStorage; - delete globalThis.document; - delete globalThis.getComputedStyle; +test("主题函数唯一注入本地预设解析器并保持幂等", () => { + const result = patchThemeSource(themeFixture()); + assert.equal(result.status, "patched", result.reason); + assert.match(result.source, new RegExp(THEME_MARKER.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))); + assert.match(result.source, /__codexResolveAccentPreset\(e\.accentSource,n\)/); + assert.match(result.source, /e=\{\.\.\.e,accentSource:`chatgpt`\}/); + assert.equal(patchThemeSource(result.source).status, "already-patched"); +}); + +test("本地设置、账户优先和自定义清理使用同一预设状态", async () => { + const runtime = await runtimeModule(); + const storage = fakeStorage(); + globalThis.localStorage = storage; + let localCalls = 0; + let accountCalls = 0; + let customValue = null; + + await runtime.selectAccentPreset(null, "blue", () => { localCalls++; }, () => { accountCalls++; }); + assert.equal(storage.values.get(runtime.ACCENT_PRESET_STORAGE_KEY), "blue"); + assert.equal(runtime.accentPresetSelection(null, "custom"), "blue"); + assert.equal(runtime.accentPresetSelection(undefined, "custom"), "custom"); + assert.equal(runtime.resolveAccentPreset("custom", null), "blue"); + assert.equal(localCalls, 1); + assert.equal(accountCalls, 0); + + await runtime.selectAccentPreset({ chatTheme: "green" }, "green", () => { localCalls++; }, () => { accountCalls++; }); + assert.equal(storage.values.has(runtime.ACCENT_PRESET_STORAGE_KEY), false); + assert.equal(accountCalls, 1); + + storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, "blue"); + runtime.useCustomAccent(value => { customValue = value; }, "#123456"); + assert.equal(customValue, "#123456"); + assert.equal(storage.values.has(runtime.ACCENT_PRESET_STORAGE_KEY), false); +}); + +test("预设解析保留名称语义并拒绝无效本地值", async () => { + const runtime = await runtimeModule(); + const storage = fakeStorage({ [runtime.ACCENT_PRESET_STORAGE_KEY]: "blue" }); + globalThis.localStorage = storage; + assert.equal(runtime.resolveAccentPreset("custom", null), "blue"); + assert.equal(runtime.resolveAccentPreset("chatgpt", "green"), "green"); + assert.equal(runtime.resolveAccentPreset("custom", "green"), null); + + for (const preset of ["default", "blue", "black"]) { + storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, preset); + assert.equal(runtime.resolveAccentPreset("custom", null), preset); + } + storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, "not-a-preset"); + assert.equal(runtime.resolveAccentPreset("custom", null), null); +}); + +test("完整主题链复用官方预设气泡且账户主题优先", async t => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "codex-accent-theme-")); + t.after(() => fs.rmSync(directory, { recursive: true, force: true })); + fs.copyFileSync(path.join(__dirname, "runtime", "accent-presets.mjs"), path.join(directory, MODULE)); + const result = patchThemeSource(themeFixture()); + assert.equal(result.status, "patched", result.reason); + const bundle = path.join(directory, "theme.mjs"); + fs.writeFileSync(bundle, result.source, "utf8"); + const theme = await import(`${pathToFileURL(bundle).href}?test=${Date.now()}`); + const runtime = await runtimeModule(); + const storage = fakeStorage({ [runtime.ACCENT_PRESET_STORAGE_KEY]: "blue" }); + globalThis.localStorage = storage; + + const localBlue = theme.Tba({ accentSource: "custom", accent: "#custom" }, "light", null); + assert.equal(localBlue["--color-background-user-message"], "#blue-bubble"); + assert.notEqual(localBlue["--color-background-user-message"], "neutral-bubble"); + + const accountGreen = theme.Tba({ accentSource: "chatgpt", accent: "#custom" }, "light", "green"); + assert.equal(accountGreen["--color-background-user-message"], "#green-bubble"); + const accountCustom = theme.Tba({ accentSource: "custom", accent: "#custom" }, "light", "green"); + assert.equal(accountCustom["--color-background-user-message"], "neutral-bubble"); + + for (const preset of ["default", "blue", "black"]) { + storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, preset); + const rendered = theme.Tba({ accentSource: "custom", accent: "#custom" }, "light", null); + assert.equal(rendered["--color-background-user-message"], `#${preset}-bubble`); + } }); diff --git a/scripts/patch-api-key-home-navigation.js b/scripts/patch-api-key-home-navigation.js new file mode 100644 index 00000000..38000356 --- /dev/null +++ b/scripts/patch-api-key-home-navigation.js @@ -0,0 +1,204 @@ +#!/usr/bin/env node +/** + * 补齐 API-key 模式的首页导航记录。 + * + * 上游的读取端会使用 auth:apikey 查找最近位置,但写入端同时受 + * ChatGPT capability 限制,导致 API-key 下从不写入、点击首页落到空路由。 + * 这里只放行 apikey 写入,不开启 ChatGPT capability,也不改变其他认证方式。 + */ +const fs = require("node:fs"); +const path = require("node:path"); +const { parse } = require("acorn"); +const { SRC_DIR, relPath } = require("./patch-util"); + +const MARKER = "/* Codex:API-key 首页恢复写入。 */"; +const PLATFORMS = ["mac-arm64", "mac-x64", "win", "unix"]; + +function walk(node, visit, root = node, ownScope = false) { + if (!node || typeof node !== "object" || !node.type) return; + if (ownScope && node !== root && /Function/.test(node.type)) return; + visit(node); + for (const value of Object.values(node)) { + if (Array.isArray(value)) { + for (const child of value) walk(child, visit, root, ownScope); + } else if (value?.type) { + walk(value, visit, root, ownScope); + } + } +} + +function nodes(root, predicate, ownScope = false) { + const found = []; + walk(root, node => { if (predicate(node)) found.push(node); }, root, ownScope); + return found; +} + +function literal(node) { + if (node?.type === "Literal") return node.value; + if (node?.type === "TemplateLiteral" && node.expressions.length === 0) { + return node.quasis[0].value.cooked; + } + return null; +} + +function propertyName(property) { + if (property?.type !== "Property") return null; + if (!property.computed && property.key.type === "Identifier") return property.key.name; + return literal(property.key); +} + +function templatePrefix(node, prefix, expressionName) { + return node?.type === "TemplateLiteral" && node.expressions.length === 1 && + node.quasis[0].value.cooked === prefix && node.quasis[1].value.cooked === "" && + node.expressions[0].type === "Identifier" && node.expressions[0].name === expressionName; +} + +function objectBinding(pattern, name) { + const property = pattern.properties.find(item => propertyName(item) === name); + return property?.value?.type === "Identifier" ? property.value.name : null; +} + +function unique(items, label) { + if (items.length !== 1) throw new Error(`${label} 数量异常(${items.length})`); + return items[0]; +} + +function findTracker(ast) { + const candidates = []; + for (const fn of ast.body.filter(node => node.type === "FunctionDeclaration")) { + const own = nodes(fn, () => true, true); + const all = nodes(fn, () => true); + const auth = own.filter(node => node.type === "VariableDeclarator" && + node.id?.type === "ObjectPattern" && node.init?.type === "CallExpression") + .map(node => ({ + accountId: objectBinding(node.id, "accountId"), + authMethod: objectBinding(node.id, "authMethod"), + })) + .filter(item => item.accountId && item.authMethod); + if (auth.length !== 1) continue; + + const navigationObjects = all.filter(node => node.type === "ObjectExpression").map(node => { + const properties = Object.fromEntries(node.properties + .filter(item => item.type === "Property") + .map(item => [propertyName(item), item.value])); + return { node, properties }; + }).filter(item => ["accountKey", "location", "productMode"].every(name => + item.properties[name]?.type === "Identifier")); + if (navigationObjects.length !== 1) continue; + + const accountKey = navigationObjects[0].properties.accountKey.name; + const authAssignment = own.filter(node => node.type === "AssignmentExpression" && + node.operator === "=" && node.left?.type === "Identifier" && + node.left.name === accountKey && + templatePrefix(node.right, "auth:", auth[0].authMethod)); + const accountAssignment = own.filter(node => node.type === "AssignmentExpression" && + node.operator === "=" && node.left?.type === "Identifier" && + node.left.name === accountKey && + templatePrefix(node.right, "chatgpt:", auth[0].accountId)); + if (authAssignment.length !== 1 || accountAssignment.length !== 1) continue; + + const guards = own.filter(node => node.type === "LogicalExpression" && node.operator === "&&" && + node.start <= authAssignment[0].start && node.end >= authAssignment[0].end && + node.start <= accountAssignment[0].start && node.end >= accountAssignment[0].end); + const outermost = guards.filter(node => !guards.some(other => other !== node && + other.start <= node.start && other.end >= node.end)); + if (outermost.length !== 1) continue; + const guard = outermost[0]; + if (guard.left?.type !== "LogicalExpression" || guard.left.operator !== "&&") continue; + + candidates.push({ authMethod: auth[0].authMethod, gate: guard.left.right }); + } + if (candidates.length > 1) throw new Error(`首页导航跟踪器 数量异常(${candidates.length})`); + return candidates[0] ?? null; +} + +function isApiKeyOverride(node, authMethod) { + if (node?.type !== "LogicalExpression" || node.operator !== "||") return false; + const comparison = node.right; + return comparison?.type === "BinaryExpression" && ["===", "=="].includes(comparison.operator) && + comparison.left?.type === "Identifier" && comparison.left.name === authMethod && + literal(comparison.right) === "apikey"; +} + +function patchSource(source) { + if (!["authMethod", "accountKey", "productMode", "auth:", "chatgpt:"].every(value => + source.includes(value))) { + return { status: "not-applicable", source }; + } + try { + const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const tracker = findTracker(ast); + if (tracker == null) { + if (source.includes(MARKER)) throw new Error("补丁标记存在但导航跟踪器结构未知"); + return { status: "not-applicable", source }; + } + if (isApiKeyOverride(tracker.gate, tracker.authMethod)) { + const gateSource = source.slice(tracker.gate.start, tracker.gate.end); + if (!gateSource.includes(MARKER)) throw new Error("API-key 放行逻辑存在但缺少本项目标记"); + return { status: "already-patched", source }; + } + if (tracker.gate.type !== "Identifier") { + throw new Error("ChatGPT capability 条件结构未知"); + } + const originalGate = source.slice(tracker.gate.start, tracker.gate.end); + const replacement = `(${originalGate}||${MARKER}${tracker.authMethod}===\`apikey\`)`; + const next = source.slice(0, tracker.gate.start) + replacement + source.slice(tracker.gate.end); + parse(next, { ecmaVersion: "latest", sourceType: "module" }); + return { status: "patched", source: next }; + } catch (error) { + return { status: "unexpected-shape", source, reason: error.message }; + } +} + +function targetDirectories(platform) { + const directories = (platform ? [platform] : PLATFORMS) + .map(name => ({ platform: name, path: path.join(SRC_DIR, name, "_asar", "webview", "assets") })) + .filter(item => fs.existsSync(item.path)); + const legacy = path.join(SRC_DIR, "webview", "assets"); + if (!directories.length && fs.existsSync(legacy)) directories.push({ platform: "legacy", path: legacy }); + return directories; +} + +function main() { + const args = process.argv.slice(2); + const platform = args.find(arg => PLATFORMS.includes(arg)); + const check = args.includes("--check"); + const directories = targetDirectories(platform); + let failed = 0; + let patched = 0; + for (const directory of directories) { + try { + const results = fs.readdirSync(directory.path).filter(name => name.endsWith(".js")) + .map(name => ({ name, path: path.join(directory.path, name) })) + .map(file => ({ ...file, source: fs.readFileSync(file.path, "utf8") })) + .filter(file => ["authMethod", "accountKey", "productMode", "auth:", "chatgpt:"] + .every(value => file.source.includes(value))) + .map(file => ({ file, result: patchSource(file.source) })) + .filter(item => item.result.status !== "not-applicable"); + const target = unique(results, "首页导航 Bundle"); + if (target.result.status === "unexpected-shape") throw new Error(target.result.reason); + console.log(` [${directory.platform}] ${relPath(target.file.path)}`); + if (target.result.status === "already-patched") { + console.log(" [ok] API-key 首页导航记录已启用"); + } else if (check) { + console.log(" [ok] API-key 首页导航写入锚点已核对;dry-run 未写文件"); + } else { + fs.writeFileSync(target.file.path, target.result.source, "utf8"); + patched++; + console.log(" [ok] API-key 将使用 auth:apikey 保存并恢复当前会话"); + } + } catch (error) { + console.error(` [x] ${directory.platform}: ${error.message}`); + failed++; + } + } + if (!directories.length) { + console.error(" [x] 缺少目标平台界面资源"); + failed++; + } + if (failed) process.exitCode = 1; + else console.log(` [ok] ${patched} platform bundle(s) patched`); +} + +if (require.main === module) main(); +module.exports = { MARKER, patchSource }; diff --git a/scripts/patch-api-key-home-navigation.test.js b/scripts/patch-api-key-home-navigation.test.js new file mode 100644 index 00000000..44b646a5 --- /dev/null +++ b/scripts/patch-api-key-home-navigation.test.js @@ -0,0 +1,69 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { MARKER, patchSource } = require("./patch-api-key-home-navigation"); + +function fixture() { + return [ + "function Lhc(){", + "let e=cache(),t=store(),n=location(),{accountId:r,authMethod:i}=mp(),", + "a=mode()!==`legacy`,o=capability(),s=productMode(),c=project(),l;", + "e[0]!==r||e[1]!==i||e[2]!==a||e[3]!==o?", + "(l=null,a&&o&&(i===`chatgpt`&&r!=null?l=`chatgpt:${r}`:i!=null&&(l=`auth:${i}`)),", + "e[0]=r,e[1]=i,e[2]=a,e[3]=o,e[4]=l):l=e[4];", + "yti(t,{accountKey:l,location:n,productMode:s});return l", + "}", + ].join(""); +} + +function load(source, auth, capability) { + return Function("auth", "capabilityValue", [ + "const cache=()=>[];const store=()=>({});const location=()=>({});", + "const mp=()=>auth;const mode=()=>`current`;const capability=()=>capabilityValue;", + "const productMode=()=>`codex`;const project=()=>null;const yti=()=>{};", + source, + "return Lhc();", + ].join(""))(auth, capability); +} + +test("API-key 在 ChatGPT capability 关闭时仍写入与读取端一致的 accountKey", () => { + const result = patchSource(fixture()); + + assert.equal(result.status, "patched"); + assert.ok(result.source.includes(MARKER)); + assert.equal(load(result.source, { accountId: null, authMethod: "apikey" }, false), "auth:apikey"); + assert.equal(patchSource(result.source).status, "already-patched"); +}); + +test("ChatGPT 登录继续遵守官方 capability 与账户条件", () => { + const result = patchSource(fixture()); + + assert.equal(load(result.source, { accountId: "account-1", authMethod: "chatgpt" }, true), "chatgpt:account-1"); + assert.equal(load(result.source, { accountId: "account-1", authMethod: "chatgpt" }, false), null); + assert.equal(load(result.source, { accountId: null, authMethod: "chatgpt" }, true), "auth:chatgpt"); +}); + +test("未认证及其他认证方式不会因补丁越过 capability", () => { + const result = patchSource(fixture()); + + assert.equal(load(result.source, { accountId: null, authMethod: null }, false), null); + assert.equal(load(result.source, { accountId: null, authMethod: "chatgptAuthTokens" }, false), null); + assert.equal(load(result.source, { accountId: null, authMethod: "chatgptAuthTokens" }, true), "auth:chatgptAuthTokens"); +}); + +test("导航跟踪器不唯一时明确失败", () => { + const source = fixture() + fixture().replaceAll("Lhc", "Mhc"); + const result = patchSource(source); + + assert.equal(result.status, "unexpected-shape"); + assert.match(result.reason, /首页导航跟踪器.*2/); + assert.equal(result.source, source); +}); + +test("无关 Bundle 保持不变", () => { + const source = "function unrelated(){return `home`}"; + const result = patchSource(source); + + assert.equal(result.status, "not-applicable"); + assert.equal(result.source, source); +}); diff --git a/scripts/patch-policy.js b/scripts/patch-policy.js index 72ff4b81..cf49375e 100644 --- a/scripts/patch-policy.js +++ b/scripts/patch-policy.js @@ -21,6 +21,7 @@ const PATCH_POLICY = [ { script: "patch-windows-portable-runtime.js", feature: "Windows 便携运行时" }, { script: "patch-test-isolation.js", feature: "Windows 验收数据隔离" }, { script: "patch-provider-quota.js", feature: "真实 Provider 额度发送门槛" }, + { script: "patch-api-key-home-navigation.js", feature: "API-key 首页会话恢复" }, { script: "patch-accent-presets.js", feature: "API-key 本地强调色预设" }, { script: "patch-hide-pet-menu.js", feature: "隐藏 Pet 菜单入口" }, { script: "patch-reading-layout.js", feature: "可配置正文宽度与排版" }, diff --git a/scripts/reading-layout-smoke.js b/scripts/reading-layout-smoke.js index f09034cc..6b7b922e 100644 --- a/scripts/reading-layout-smoke.js +++ b/scripts/reading-layout-smoke.js @@ -10,31 +10,32 @@ const html = `
粗体内容
代码块
表格
输入区域
对话框
`; const server = http.createServer((req,res)=>{ diff --git a/scripts/reading-width.test.js b/scripts/reading-width.test.js new file mode 100644 index 00000000..c24a4583 --- /dev/null +++ b/scripts/reading-width.test.js @@ -0,0 +1,59 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const path = require("node:path"); +const { pathToFileURL } = require("node:url"); + +async function readingModule() { + return import(pathToFileURL(path.join(__dirname, "runtime", "reading-width.mjs")).href); +} + +test.afterEach(() => { + delete globalThis.localStorage; +}); + +test("正文宽度提供 50% 到 100% 的 5% 步进", async () => { + const reading = await readingModule(); + assert.equal(reading.MIN_WIDTH_PERCENT, 50); + assert.equal(reading.MAX_WIDTH_PERCENT, 100); + assert.equal(reading.WIDTH_STEP, 5); + assert.deepEqual(reading.WIDTHS, ["50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"]); +}); + +test("所有百分比都保留官方宽度下限且不接受旧 default", async () => { + const { WIDTHS, readingCss } = await readingModule(); + for (const width of WIDTHS) { + const css = readingCss(width); + assert.match(css, new RegExp(`max\\(48rem,${width}%\\)`)); + assert.match(css, new RegExp(`max\\(40rem,${width}%\\)`)); + } + assert.throws(() => readingCss("default"), /未知的正文宽度档位/); +}); + +test("外观设置使用范围滑杆并将无效旧值回落到 50%", async () => { + const reading = await readingModule(); + const values = new Map([[reading.STORAGE_KEY, "default"]]); + globalThis.localStorage = { + getItem: key => values.get(key) ?? null, + setItem: (key, value) => values.set(key, value), + }; + const react = { + Fragment: Symbol("Fragment"), + useState: initial => [typeof initial === "function" ? initial() : initial, () => {}], + useEffect: () => {}, + }; + const ui = { + jsx: (type, props, key) => ({ type, props, key }), + jsxs: (type, props, key) => ({ type, props, key }), + }; + const Row = () => null; + const tree = reading.renderReadingWidth(react, ui, Row, { locale: "zh-CN" }); + const widthRow = tree.props.children[0]; + const [slider, output] = widthRow.props.control.props.children; + assert.equal(slider.type, "input"); + assert.equal(slider.props.type, "range"); + assert.equal(slider.props.min, 50); + assert.equal(slider.props.max, 100); + assert.equal(slider.props.step, 5); + assert.equal(slider.props.value, "50"); + assert.equal(output.props.children, "50%"); +}); diff --git a/scripts/runtime/accent-presets.mjs b/scripts/runtime/accent-presets.mjs new file mode 100644 index 00000000..f7ae5ee4 --- /dev/null +++ b/scripts/runtime/accent-presets.mjs @@ -0,0 +1,56 @@ +export const ACCENT_PRESET_STORAGE_KEY = "codex-rebuild:accent-preset:v1"; +export const ACCENT_PRESETS = new Set([ + "default", + "blue", + "green", + "yellow", + "pink", + "orange", + "purple", + "black", +]); + +function storage() { + return globalThis.localStorage; +} + +export function readLocalAccentPreset() { + try { + const value = storage()?.getItem(ACCENT_PRESET_STORAGE_KEY); + return ACCENT_PRESETS.has(value) ? value : null; + } catch { + return null; + } +} + +function clearLocalAccentPreset() { + try { + storage()?.removeItem(ACCENT_PRESET_STORAGE_KEY); + } catch {} +} + +export function accentPresetSelection(accountTheme, fallback) { + return accountTheme === null ? readLocalAccentPreset() ?? fallback : fallback; +} + +export function resolveAccentPreset(accentSource, accountPreset) { + if (accountPreset != null) return accentSource === "chatgpt" ? accountPreset : null; + return readLocalAccentPreset(); +} + +export function selectAccentPreset(accountTheme, preset, applyLocal, selectAccount) { + return Promise.resolve().then(() => { + if (accountTheme !== null) { + clearLocalAccentPreset(); + return selectAccount(); + } + if (!ACCENT_PRESETS.has(preset)) return; + storage()?.setItem(ACCENT_PRESET_STORAGE_KEY, preset); + return applyLocal(); + }); +} + +export function useCustomAccent(onChange, value) { + clearLocalAccentPreset(); + return onChange(value); +} diff --git a/scripts/runtime/reading-width.mjs b/scripts/runtime/reading-width.mjs index d2744c71..8abccc31 100644 --- a/scripts/runtime/reading-width.mjs +++ b/scripts/runtime/reading-width.mjs @@ -1,5 +1,11 @@ // 只保存阅读布局与 Markdown 粗体样式偏好,认证、Provider 与任务配置由原程序管理。 -export const WIDTHS = ["default", "85", "100"]; +export const MIN_WIDTH_PERCENT = 50; +export const MAX_WIDTH_PERCENT = 100; +export const WIDTH_STEP = 5; +export const WIDTHS = Array.from( + { length: (MAX_WIDTH_PERCENT - MIN_WIDTH_PERCENT) / WIDTH_STEP + 1 }, + (_, index) => String(MIN_WIDTH_PERCENT + index * WIDTH_STEP), +); export const STORAGE_KEY = "codex-rebuild:reading-width:v1"; export const BOLD_COLOR_MODES = ["default", "accent", "custom"]; export const BOLD_MODE_STORAGE_KEY = "codex-rebuild:markdown-bold-color-mode:v1"; @@ -15,7 +21,7 @@ export function readingCss(value, boldMode = "default", customColor = DEFAULT_BO if (boldMode === "custom" && !COLOR_PATTERN.test(customColor)) throw new Error("Markdown 粗体自定义颜色无效"); const expanded = `min(100%,max(48rem,${value}%))`; const compact = `min(100%,max(40rem,${value}%))`; - const selected = value === "default" ? "" : `html[data-codex-rebuild-reading-width] body{--thread-content-max-width:${expanded};--thread-content-expanded-max-width:${expanded};--thread-content-compact-max-width:${compact}}`; + const selected = `html[data-codex-rebuild-reading-width] body{--thread-content-max-width:${expanded};--thread-content-expanded-max-width:${expanded};--thread-content-compact-max-width:${compact}}`; const boldSelector = ":is([data-codex-window-type=browser],[data-codex-window-type=chrome-extension],[data-codex-window-type=electron]) [data-selected-text-overlay-target] strong"; const bold = boldMode === "default" ? "" : `${boldSelector}{color:${boldMode === "accent" ? "var(--app-color-text-accent,var(--codex-base-accent,currentColor))" : customColor.toLowerCase()}}`; return `${selected} @@ -26,8 +32,8 @@ ${Object.entries({ narrow: 520, feature: 600, compact: 640, wide: 800, xwide: 86 } function widthPreference() { - const value = localStorage.getItem(STORAGE_KEY) ?? "default"; - return WIDTHS.includes(value) ? value : "default"; + const value = localStorage.getItem(STORAGE_KEY) ?? String(MIN_WIDTH_PERCENT); + return WIDTHS.includes(value) ? value : String(MIN_WIDTH_PERCENT); } function boldModePreference() { @@ -78,19 +84,29 @@ export function renderReadingWidth(react, ui, Row, intl) { ui.jsx(Row, { size: "compact", label: chinese ? "聊天正文宽度" : "Chat content width", - control: ui.jsxs("select", { - "aria-label": chinese ? "聊天正文宽度" : "Chat content width", - "data-codex-rebuild-width-control": "true", - className: controlClass, - value, - onChange: event => { - const next = event.currentTarget.value; - localStorage.setItem(STORAGE_KEY, next); apply(next, boldModePreference()); setValue(next); - window.dispatchEvent(new Event("codex-rebuild-reading-change")); - }, - children: WIDTHS.map(option => ui.jsx("option", { value: option, - children: option === "default" ? (chinese ? "默认" : "Default") : `${option}%` }, option)), - }), + control: ui.jsxs("div", { className: "flex items-center gap-2", children: [ + ui.jsx("input", { + type: "range", + min: MIN_WIDTH_PERCENT, + max: MAX_WIDTH_PERCENT, + step: WIDTH_STEP, + "aria-label": chinese ? "聊天正文宽度" : "Chat content width", + "data-codex-rebuild-width-control": "true", + className: "w-36", + style: { accentColor: "var(--app-color-text-accent)" }, + value, + onChange: event => { + const next = event.currentTarget.value; + localStorage.setItem(STORAGE_KEY, next); apply(next, boldModePreference()); setValue(next); + window.dispatchEvent(new Event("codex-rebuild-reading-change")); + }, + }), + ui.jsx("output", { + "aria-hidden": "true", + className: "w-10 text-right text-sm tabular-nums text-secondary", + children: `${value}%`, + }), + ] }), }, "codex-rebuild-reading-width"), ui.jsx(Row, { size: "compact", From 005b2d33cb5f0a00f2a3914d688ef9bf43562eb5 Mon Sep 17 00:00:00 2001 From: carptopus Date: Fri, 16 Oct 2026 01:52:23 +0800 Subject: [PATCH 04/51] Fix appearance crash and API-key home restore --- scripts/patch-accent-presets.js | 6 +-- scripts/patch-accent-presets.test.js | 38 ++++++++++++++++++- scripts/patch-api-key-home-navigation.js | 13 ++++--- scripts/patch-api-key-home-navigation.test.js | 22 +++++++++-- 4 files changed, 63 insertions(+), 16 deletions(-) diff --git a/scripts/patch-accent-presets.js b/scripts/patch-accent-presets.js index b8dbf5a5..db5724c5 100644 --- a/scripts/patch-accent-presets.js +++ b/scripts/patch-accent-presets.js @@ -72,7 +72,7 @@ function patchSettingsSource(source) { } if (source.includes(SETTINGS_MARKER)) { parse(source, { ecmaVersion: "latest", sourceType: "module" }); - if (![MODULE, "__codexCurrentAccent=", "__codexAccentSelection(", "__codexSelectAccentPreset(", "__codexUseCustomAccent("].every(value => source.includes(value))) { + if (![MODULE, "__codexAccentSelection(", "__codexSelectAccentPreset(", "__codexUseCustomAccent("].every(value => source.includes(value)) || source.includes("__codexCurrentAccent=")) { return { status: "unexpected-shape", source, reason: "本地强调色设置标记不完整" }; } return { status: "already-patched", source }; @@ -117,14 +117,12 @@ function patchSettingsSource(source) { const moduleImport = `\n${SETTINGS_MARKER}\nimport {accentPresetSelection as __codexAccentSelection,selectAccentPreset as __codexSelectAccentPreset,useCustomAccent as __codexUseCustomAccent} from "./${MODULE}";`; const edits = [ { start: importAt, end: importAt, text: moduleImport }, - { start: component.body.start + 1, end: component.body.start + 1, - text: `const __codexCurrentAccent=${theme}.accent;` }, { start: selection.init.start, end: selection.init.end, text: `__codexAccentSelection(${accountTheme},${originalSelection})` }, // undefined 表示账户主题仍在加载;null 才表示没有可用账户主题。 { start: disabled.value.start, end: disabled.value.end, text: `${accountTheme}===void 0` }, { start: accountCall.start, end: accountCall.end, - text: `__codexSelectAccentPreset(${accountTheme},${preset.name},()=>${selectCustom}(__codexCurrentAccent),()=>${originalAccountCall})` }, + text: `__codexSelectAccentPreset(${accountTheme},${preset.name},()=>${selectCustom}(${theme}.accent),()=>${originalAccountCall})` }, { start: customCall.start, end: customCall.end, text: `__codexUseCustomAccent(${selectCustom},${customValue})` }, { start: onChange.value.start, end: onChange.value.end, diff --git a/scripts/patch-accent-presets.test.js b/scripts/patch-accent-presets.test.js index af2340ee..d9423c6d 100644 --- a/scripts/patch-accent-presets.test.js +++ b/scripts/patch-accent-presets.test.js @@ -56,13 +56,47 @@ test("无账户主题时启用本地预设并保留加载态禁用", () => { assert.equal(result.status, "patched", result.reason); assert.match(result.source, new RegExp(SETTINGS_MARKER.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))); assert.match(result.source, new RegExp(MODULE.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))); - assert.match(result.source, /function Accent\(e\)\{const __codexCurrentAccent=r\.accent;/); + assert.doesNotMatch(result.source, /__codexCurrentAccent/); assert.match(result.source, /disabled:u===void 0/); - assert.match(result.source, /__codexSelectAccentPreset\(u,e,\(\)=>o\(__codexCurrentAccent\),\(\)=>a\(/); + assert.match(result.source, /__codexSelectAccentPreset\(u,e,\(\)=>o\(r\.accent\),\(\)=>a\(/); assert.match(result.source, /onChange:__codexColor=>__codexUseCustomAccent\(o,__codexColor\)/); assert.equal(patchSettingsSource(result.source).status, "already-patched"); }); +test("设置组件在属性解构后才读取主题", () => { + const result = patchSettingsSource(settingsFixture()); + assert.equal(result.status, "patched", result.reason); + const executable = result.source.replace(/import[^;]+;/g, ""); + const Accent = Function( + "P", "O", "scope", "read", "themeAtom", "pendingAtom", "jsx", "RadioItem", "ColorInput", + "account", "settings", "sync", "toast", "__codexAccentSelection", "__codexSelectAccentPreset", "__codexUseCustomAccent", + `${executable};return Accent;`, + )( + () => "color", ["default", "blue"], () => ({ get: () => null }), () => null, {}, {}, + (_type, props) => props, "radio", "color", {}, {}, () => {}, () => {}, + (_accountTheme, fallback) => fallback, + () => Promise.resolve(), + (onChange, value) => onChange(value), + ); + + assert.doesNotThrow(() => Accent({ + theme: { accent: "#123456", accentSource: "custom" }, + variant: "light", + onSelect: () => Promise.resolve(), + onCustomColorChange: () => {}, + })); +}); + +test("旧版在属性解构前读取主题的崩溃补丁会被拒绝", () => { + const patched = patchSettingsSource(settingsFixture()); + assert.equal(patched.status, "patched", patched.reason); + const broken = patched.source.replace("function Accent(e){let", "function Accent(e){const __codexCurrentAccent=r.accent;let"); + const result = patchSettingsSource(broken); + + assert.equal(result.status, "unexpected-shape"); + assert.match(result.reason, /本地强调色设置标记不完整/); +}); + test("设置和主题未知结构均明确失败", () => { const settings = patchSettingsSource('const x="chatgptAccentPicker.ChatGptAccentPicker.updateError accentSource"'); assert.equal(settings.status, "unexpected-shape"); diff --git a/scripts/patch-api-key-home-navigation.js b/scripts/patch-api-key-home-navigation.js index 38000356..2fd70c50 100644 --- a/scripts/patch-api-key-home-navigation.js +++ b/scripts/patch-api-key-home-navigation.js @@ -3,8 +3,8 @@ * 补齐 API-key 模式的首页导航记录。 * * 上游的读取端会使用 auth:apikey 查找最近位置,但写入端同时受 - * ChatGPT capability 限制,导致 API-key 下从不写入、点击首页落到空路由。 - * 这里只放行 apikey 写入,不开启 ChatGPT capability,也不改变其他认证方式。 + * 新导航模式和 ChatGPT capability 限制,导致 API-key 下从不写入、点击首页落到空路由。 + * 这里只放行 apikey 写入,不开启这些 ChatGPT 账户能力,也不改变其他认证方式。 */ const fs = require("node:fs"); const path = require("node:path"); @@ -104,9 +104,9 @@ function findTracker(ast) { other.start <= node.start && other.end >= node.end)); if (outermost.length !== 1) continue; const guard = outermost[0]; - if (guard.left?.type !== "LogicalExpression" || guard.left.operator !== "&&") continue; + if (guard.left?.type !== "LogicalExpression") continue; - candidates.push({ authMethod: auth[0].authMethod, gate: guard.left.right }); + candidates.push({ authMethod: auth[0].authMethod, gate: guard.left }); } if (candidates.length > 1) throw new Error(`首页导航跟踪器 数量异常(${candidates.length})`); return candidates[0] ?? null; @@ -137,8 +137,9 @@ function patchSource(source) { if (!gateSource.includes(MARKER)) throw new Error("API-key 放行逻辑存在但缺少本项目标记"); return { status: "already-patched", source }; } - if (tracker.gate.type !== "Identifier") { - throw new Error("ChatGPT capability 条件结构未知"); + if (tracker.gate.type !== "LogicalExpression" || tracker.gate.operator !== "&&" || + tracker.gate.left?.type !== "Identifier" || tracker.gate.right?.type !== "Identifier") { + throw new Error("导航模式与 ChatGPT capability 条件结构未知"); } const originalGate = source.slice(tracker.gate.start, tracker.gate.end); const replacement = `(${originalGate}||${MARKER}${tracker.authMethod}===\`apikey\`)`; diff --git a/scripts/patch-api-key-home-navigation.test.js b/scripts/patch-api-key-home-navigation.test.js index 44b646a5..3a3891d8 100644 --- a/scripts/patch-api-key-home-navigation.test.js +++ b/scripts/patch-api-key-home-navigation.test.js @@ -16,14 +16,14 @@ function fixture() { ].join(""); } -function load(source, auth, capability) { - return Function("auth", "capabilityValue", [ +function load(source, auth, capability, modeValue = "current") { + return Function("auth", "capabilityValue", "modeValue", [ "const cache=()=>[];const store=()=>({});const location=()=>({});", - "const mp=()=>auth;const mode=()=>`current`;const capability=()=>capabilityValue;", + "const mp=()=>auth;const mode=()=>modeValue;const capability=()=>capabilityValue;", "const productMode=()=>`codex`;const project=()=>null;const yti=()=>{};", source, "return Lhc();", - ].join(""))(auth, capability); + ].join(""))(auth, capability, modeValue); } test("API-key 在 ChatGPT capability 关闭时仍写入与读取端一致的 accountKey", () => { @@ -31,7 +31,9 @@ test("API-key 在 ChatGPT capability 关闭时仍写入与读取端一致的 acc assert.equal(result.status, "patched"); assert.ok(result.source.includes(MARKER)); + assert.match(result.source, /\(a&&o\|\|\/\* Codex:API-key 首页恢复写入。 \*\/i===`apikey`\)&&/); assert.equal(load(result.source, { accountId: null, authMethod: "apikey" }, false), "auth:apikey"); + assert.equal(load(result.source, { accountId: null, authMethod: "apikey" }, false, "legacy"), "auth:apikey"); assert.equal(patchSource(result.source).status, "already-patched"); }); @@ -40,9 +42,21 @@ test("ChatGPT 登录继续遵守官方 capability 与账户条件", () => { assert.equal(load(result.source, { accountId: "account-1", authMethod: "chatgpt" }, true), "chatgpt:account-1"); assert.equal(load(result.source, { accountId: "account-1", authMethod: "chatgpt" }, false), null); + assert.equal(load(result.source, { accountId: "account-1", authMethod: "chatgpt" }, true, "legacy"), null); assert.equal(load(result.source, { accountId: null, authMethod: "chatgpt" }, true), "auth:chatgpt"); }); +test("旧版只绕过 capability 的不完整补丁会被拒绝", () => { + const incomplete = fixture().replace( + "a&&o&&", + `a&&(o||${MARKER}i===\`apikey\`)&&`, + ); + const result = patchSource(incomplete); + + assert.equal(result.status, "unexpected-shape"); + assert.match(result.reason, /导航模式与 ChatGPT capability/); +}); + test("未认证及其他认证方式不会因补丁越过 capability", () => { const result = patchSource(fixture()); From 664d017c5394683474ca9d922a77aa5069ff32f6 Mon Sep 17 00:00:00 2001 From: carptopus Date: Fri, 16 Oct 2026 02:43:28 +0800 Subject: [PATCH 05/51] Fix API-key home navigation and clarify width slider --- scripts/frontend-source-smoke.js | 2 + scripts/patch-api-key-home-navigation.js | 120 +++++++++++++++--- scripts/patch-api-key-home-navigation.test.js | 64 +++++++++- scripts/reading-layout-smoke.js | 3 +- scripts/reading-width.test.js | 12 ++ scripts/runtime/reading-width.mjs | 10 +- 6 files changed, 192 insertions(+), 19 deletions(-) diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index 96450926..7eaee379 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -81,6 +81,8 @@ function verifyFrontendSource(assets) { assert.equal(navigationEntries.length, 1); const navigationSource = fs.readFileSync(path.join(assets, navigationEntries[0]), "utf8"); assert.match(navigationSource, /\|\|\/\* Codex:API-key 首页恢复写入。 \*\/[A-Za-z_$][\w$]*===`apikey`/); + assert.match(navigationSource, + /\|\|\/\* Codex:API-key 当前首页保持会话。 \*\/[A-Za-z_$][\w$]*===`auth:apikey`/); const accentModule = fs.readFileSync(path.join(assets, "codex-rebuild-accent-presets.js"), "utf8"); assert.match(accentModule, /codex-rebuild:accent-preset:v1/); assert.match(accentModule, /export function resolveAccentPreset/); diff --git a/scripts/patch-api-key-home-navigation.js b/scripts/patch-api-key-home-navigation.js index 2fd70c50..62f61d25 100644 --- a/scripts/patch-api-key-home-navigation.js +++ b/scripts/patch-api-key-home-navigation.js @@ -3,8 +3,11 @@ * 补齐 API-key 模式的首页导航记录。 * * 上游的读取端会使用 auth:apikey 查找最近位置,但写入端同时受 - * 新导航模式和 ChatGPT capability 限制,导致 API-key 下从不写入、点击首页落到空路由。 - * 这里只放行 apikey 写入,不开启这些 ChatGPT 账户能力,也不改变其他认证方式。 + * 新导航模式和 ChatGPT capability 限制,导致 API-key 下从不写入。 + * 同时,旧导航模式不会把“当前会话已经属于首页”视为已到达目标,随后又拒绝 + * departedAt 为空的当前记录,最终让首页按钮落到空路由。 + * 这里只放行 apikey 的写入和当前首页短路,不开启这些 ChatGPT 账户能力, + * 也不改变其他认证方式。 */ const fs = require("node:fs"); const path = require("node:path"); @@ -12,6 +15,7 @@ const { parse } = require("acorn"); const { SRC_DIR, relPath } = require("./patch-util"); const MARKER = "/* Codex:API-key 首页恢复写入。 */"; +const CURRENT_HOME_MARKER = "/* Codex:API-key 当前首页保持会话。 */"; const PLATFORMS = ["mac-arm64", "mac-x64", "win", "unix"]; function walk(node, visit, root = node, ownScope = false) { @@ -112,6 +116,53 @@ function findTracker(ast) { return candidates[0] ?? null; } +function returnsTrue(statement) { + if (statement?.type !== "ReturnStatement") return false; + if (literal(statement.argument) === true) return true; + return statement.argument?.type === "UnaryExpression" && statement.argument.operator === "!" && + literal(statement.argument.argument) === 0; +} + +function memberName(node) { + if (node?.type !== "MemberExpression") return null; + if (!node.computed && node.property.type === "Identifier") return node.property.name; + return literal(node.property); +} + +function findCurrentHomeGuard(ast) { + const candidates = []; + for (const fn of ast.body.filter(node => node.type === "FunctionDeclaration")) { + const options = fn.params[1]; + if (options?.type !== "ObjectPattern") continue; + const accountKey = objectBinding(options, "accountKey"); + const area = objectBinding(options, "area"); + const productMode = objectBinding(options, "productMode"); + if (!accountKey || !area || !productMode) continue; + + const guards = nodes(fn, node => { + if (node.type !== "IfStatement" || !returnsTrue(node.consequent)) return false; + const own = nodes(node.test, () => true); + const identifiers = new Set(own.filter(item => item.type === "Identifier") + .map(item => item.name)); + return own.some(item => memberName(item) === "sidebarProductMode") && + identifiers.has(area) && identifiers.has(productMode); + }, true); + if (guards.length !== 1) continue; + + const modeChecks = nodes(guards[0].test, node => node.type === "LogicalExpression" && + node.operator === "&&" && + (node.left?.type === "Identifier" || isAccountKeyOverride(node.left, accountKey)) && + node.right?.type === "BinaryExpression" && ["!=", "!=="].includes(node.right.operator) && + literal(node.right.right) === null); + if (modeChecks.length !== 1) continue; + candidates.push({ accountKey, gate: modeChecks[0].left }); + } + if (candidates.length > 1) { + throw new Error(`当前首页短路 数量异常(${candidates.length})`); + } + return candidates[0] ?? null; +} + function isApiKeyOverride(node, authMethod) { if (node?.type !== "LogicalExpression" || node.operator !== "||") return false; const comparison = node.right; @@ -120,6 +171,14 @@ function isApiKeyOverride(node, authMethod) { literal(comparison.right) === "apikey"; } +function isAccountKeyOverride(node, accountKey) { + if (node?.type !== "LogicalExpression" || node.operator !== "||") return false; + const comparison = node.right; + return comparison?.type === "BinaryExpression" && ["===", "=="].includes(comparison.operator) && + comparison.left?.type === "Identifier" && comparison.left.name === accountKey && + literal(comparison.right) === "auth:apikey"; +} + function patchSource(source) { if (!["authMethod", "accountKey", "productMode", "auth:", "chatgpt:"].every(value => source.includes(value))) { @@ -128,22 +187,53 @@ function patchSource(source) { try { const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); const tracker = findTracker(ast); - if (tracker == null) { - if (source.includes(MARKER)) throw new Error("补丁标记存在但导航跟踪器结构未知"); + const currentHome = findCurrentHomeGuard(ast); + if (tracker == null || currentHome == null) { + if (source.includes(MARKER) || source.includes(CURRENT_HOME_MARKER)) { + throw new Error("补丁标记存在但首页导航结构未知"); + } return { status: "not-applicable", source }; } - if (isApiKeyOverride(tracker.gate, tracker.authMethod)) { + const trackerPatched = isApiKeyOverride(tracker.gate, tracker.authMethod); + const currentHomePatched = isAccountKeyOverride(currentHome.gate, currentHome.accountKey); + if (trackerPatched) { const gateSource = source.slice(tracker.gate.start, tracker.gate.end); if (!gateSource.includes(MARKER)) throw new Error("API-key 放行逻辑存在但缺少本项目标记"); - return { status: "already-patched", source }; - } - if (tracker.gate.type !== "LogicalExpression" || tracker.gate.operator !== "&&" || + } else if (tracker.gate.type !== "LogicalExpression" || tracker.gate.operator !== "&&" || tracker.gate.left?.type !== "Identifier" || tracker.gate.right?.type !== "Identifier") { throw new Error("导航模式与 ChatGPT capability 条件结构未知"); } - const originalGate = source.slice(tracker.gate.start, tracker.gate.end); - const replacement = `(${originalGate}||${MARKER}${tracker.authMethod}===\`apikey\`)`; - const next = source.slice(0, tracker.gate.start) + replacement + source.slice(tracker.gate.end); + if (currentHomePatched) { + const gateSource = source.slice(currentHome.gate.start, currentHome.gate.end); + if (!gateSource.includes(CURRENT_HOME_MARKER)) { + throw new Error("API-key 当前首页逻辑存在但缺少本项目标记"); + } + } else if (currentHome.gate.type !== "Identifier") { + throw new Error("当前首页导航模式条件结构未知"); + } + if (trackerPatched && currentHomePatched) return { status: "already-patched", source }; + + const edits = []; + if (!trackerPatched) { + const originalGate = source.slice(tracker.gate.start, tracker.gate.end); + edits.push({ + start: tracker.gate.start, + end: tracker.gate.end, + replacement: `(${originalGate}||${MARKER}${tracker.authMethod}===\`apikey\`)`, + }); + } + if (!currentHomePatched) { + const originalGate = source.slice(currentHome.gate.start, currentHome.gate.end); + edits.push({ + start: currentHome.gate.start, + end: currentHome.gate.end, + replacement: `(${originalGate}||${CURRENT_HOME_MARKER}${currentHome.accountKey}===\`auth:apikey\`)`, + }); + } + let next = source; + for (const edit of edits.sort((left, right) => right.start - left.start)) { + next = next.slice(0, edit.start) + edit.replacement + next.slice(edit.end); + } parse(next, { ecmaVersion: "latest", sourceType: "module" }); return { status: "patched", source: next }; } catch (error) { @@ -180,13 +270,13 @@ function main() { if (target.result.status === "unexpected-shape") throw new Error(target.result.reason); console.log(` [${directory.platform}] ${relPath(target.file.path)}`); if (target.result.status === "already-patched") { - console.log(" [ok] API-key 首页导航记录已启用"); + console.log(" [ok] API-key 首页导航记录和当前会话保持已启用"); } else if (check) { - console.log(" [ok] API-key 首页导航写入锚点已核对;dry-run 未写文件"); + console.log(" [ok] API-key 首页导航写入与当前会话锚点已核对;dry-run 未写文件"); } else { fs.writeFileSync(target.file.path, target.result.source, "utf8"); patched++; - console.log(" [ok] API-key 将使用 auth:apikey 保存并恢复当前会话"); + console.log(" [ok] API-key 将保存并恢复首页会话,当前会话点击首页保持不变"); } } catch (error) { console.error(` [x] ${directory.platform}: ${error.message}`); @@ -202,4 +292,4 @@ function main() { } if (require.main === module) main(); -module.exports = { MARKER, patchSource }; +module.exports = { CURRENT_HOME_MARKER, MARKER, patchSource }; diff --git a/scripts/patch-api-key-home-navigation.test.js b/scripts/patch-api-key-home-navigation.test.js index 3a3891d8..c1027d2f 100644 --- a/scripts/patch-api-key-home-navigation.test.js +++ b/scripts/patch-api-key-home-navigation.test.js @@ -1,7 +1,7 @@ const test = require("node:test"); const assert = require("node:assert/strict"); -const { MARKER, patchSource } = require("./patch-api-key-home-navigation"); +const { CURRENT_HOME_MARKER, MARKER, patchSource } = require("./patch-api-key-home-navigation"); function fixture() { return [ @@ -13,6 +13,12 @@ function fixture() { "e[0]=r,e[1]=i,e[2]=a,e[3]=o,e[4]=l):l=e[4];", "yti(t,{accountKey:l,location:n,productMode:s});return l", "}", + "function Sti(e,{accountKey:t,auth:n,area:r,navigate:i,productMode:a,state:o}){", + "let s=e.get(wc),c=e.get(Ug),u=bti(e,{accountKey:t,auth:n,area:r,productMode:a});", + "if(s&&c!=null&&sti(c,r).hash===c.hash&&Ati(e,c)===r&&e.get(lj)===a&&", + "(c.state?.sidebarProductMode==null||c.state.sidebarProductMode===a))return!0;", + "if(u==null||!s&&u.departedAt==null||Ati(e,u.location)!==r){i(`/`);return!0}", + "return i(ym(u.location)),!0}", ].join(""); } @@ -37,6 +43,60 @@ test("API-key 在 ChatGPT capability 关闭时仍写入与读取端一致的 acc assert.equal(patchSource(result.source).status, "already-patched"); }); +function restore(source, accountKey, { + currentPath = "/local/thread-1", + saved = { departedAt: null, location: { pathname: "/local/thread-1" } }, +} = {}) { + const navigations = []; + const current = { hash: "", pathname: currentPath, state: null }; + const store = { + get(key) { + if (key === "wc") return false; + if (key === "Ug") return current; + if (key === "lj") return "codex"; + return null; + }, + }; + const run = Function("store", "navigate", "accountKey", "saved", [ + "const wc=`wc`,Ug=`Ug`,lj=`lj`;", + "const bti=()=>saved;", + "const sti=location=>({hash:location.hash??``});", + "const Ati=(_store,location)=>location.pathname.startsWith(`/local/`)?`home`:null;", + "const ym=location=>location.pathname;", + source, + "return Sti(store,{accountKey,area:`home`,navigate,productMode:`codex`});", + ].join("")); + return { navigations, value: run(store, path => navigations.push(path), accountKey, saved) }; +} + +test("API-key 旧导航模式下点击首页保持当前会话", () => { + const result = patchSource(fixture()); + const restored = restore(result.source, "auth:apikey"); + + assert.ok(result.source.includes(CURRENT_HOME_MARKER)); + assert.equal(restored.value, true); + assert.deepEqual(restored.navigations, []); +}); + +test("ChatGPT 旧导航模式不获得当前首页短路", () => { + const result = patchSource(fixture()); + const restored = restore(result.source, "chatgpt:account-1"); + + assert.equal(restored.value, true); + assert.deepEqual(restored.navigations, ["/"]); +}); + +test("API-key 从设置页仍恢复已经离开的首页会话", () => { + const result = patchSource(fixture()); + const restored = restore(result.source, "auth:apikey", { + currentPath: "/settings/appearance", + saved: { departedAt: Date.now(), location: { pathname: "/local/thread-1" } }, + }); + + assert.equal(restored.value, true); + assert.deepEqual(restored.navigations, ["/local/thread-1"]); +}); + test("ChatGPT 登录继续遵守官方 capability 与账户条件", () => { const result = patchSource(fixture()); @@ -66,7 +126,7 @@ test("未认证及其他认证方式不会因补丁越过 capability", () => { }); test("导航跟踪器不唯一时明确失败", () => { - const source = fixture() + fixture().replaceAll("Lhc", "Mhc"); + const source = fixture() + fixture().replaceAll("Lhc", "Mhc").replaceAll("Sti", "Tti"); const result = patchSource(source); assert.equal(result.status, "unexpected-shape"); diff --git a/scripts/reading-layout-smoke.js b/scripts/reading-layout-smoke.js index 6b7b922e..802368c4 100644 --- a/scripts/reading-layout-smoke.js +++ b/scripts/reading-layout-smoke.js @@ -14,7 +14,7 @@ import {WIDTHS,MIN_WIDTH_PERCENT,MAX_WIDTH_PERCENT,WIDTH_STEP,STORAGE_KEY,BOLD_C const results=[], states=[];let cursor=0; const react={useState(init){const index=cursor++;states[index]??=typeof init==='function'?init():init;return [states[index],value=>states[index]=value]},useEffect(){}}; react.Fragment=Symbol('Fragment'); -const ui={jsx(type,props){const element=type===react.Fragment?document.createDocumentFragment():typeof type==='function'?type(props):document.createElement(type);if(type===react.Fragment||typeof type!=='function')for(const [key,value]of Object.entries(props)){if(key==='children'){for(const child of [value].flat())if(child!==false&&child!=null)element.append(child instanceof Node?child:document.createTextNode(String(child)));}else if(key==='onChange')element.addEventListener('change',event=>value({currentTarget:event.currentTarget}));else if(key==='className')element.className=value;else if(key==='style')Object.assign(element.style,value);else if(key==='disabled')element.disabled=value;else element.setAttribute(key,value);}if(props.value!==undefined&&'value'in element)element.value=props.value;return element},jsxs(type,props){return this.jsx(type,props)}}; +const ui={jsx(type,props){const element=type===react.Fragment?document.createDocumentFragment():typeof type==='function'?type(props):document.createElement(type);if(type===react.Fragment||typeof type!=='function')for(const [key,value]of Object.entries(props)){if(key==='children'){for(const child of [value].flat())if(child!==false&&child!=null)element.append(child instanceof Node?child:document.createTextNode(String(child)));}else if(key==='onChange')element.addEventListener('change',event=>value({currentTarget:event.currentTarget}));else if(key==='className')element.className=value;else if(key==='style')for(const [name,styleValue]of Object.entries(value))name.startsWith('--')?element.style.setProperty(name,styleValue):element.style[name]=styleValue;else if(key==='disabled')element.disabled=value;else element.setAttribute(key,value);}if(props.value!==undefined&&'value'in element)element.value=props.value;return element},jsxs(type,props){return this.jsx(type,props)}}; const Row=props=>ui.jsx('label',{children:[props.label,props.control]}); const control=renderReadingWidth(react,ui,Row,{locale:'zh-CN'});document.querySelector('#controls').append(control); const widthControl=document.querySelector('[data-codex-rebuild-width-control]'),widthOutput=widthControl.nextElementSibling,boldSelect=document.querySelector('[data-codex-rebuild-bold-color-control]'),boldPicker=document.querySelector('[data-codex-rebuild-bold-custom-color]'),stage=document.querySelector('.stage'),column=document.querySelector('.column'),composer=document.querySelector('.composer'); @@ -25,6 +25,7 @@ try{ check('当前百分比偏好直接读取',!location.search.includes('restored')?widthControl.value==='85':true); if(location.search.includes('restored')){check('刷新后保持 85%',widthControl.value==='85');check('启动时样式已恢复',document.documentElement.dataset.codexRebuildReadingWidth==='85');check('刷新后保持自定义粗体色并显示颜色选择器',boldSelect.value==='custom'&&boldPicker&&getComputedStyle(document.querySelector('strong')).color==='rgb(124, 58, 237)');} check('50% 到 100% 步进 5%',widthControl.type==='range'&&Number(widthControl.min)===MIN_WIDTH_PERCENT&&Number(widthControl.max)===MAX_WIDTH_PERCENT&&Number(widthControl.step)===WIDTH_STEP&&WIDTHS.length===11&&WIDTHS[0]==='50'&&WIDTHS.at(-1)==='100'); + check('滑杆轨道和当前位置可见',getComputedStyle(widthControl).getPropertyValue('--codex-rebuild-width-progress')==='70%'&&document.querySelector('#codex-rebuild-reading-style').textContent.includes('::-webkit-slider-runnable-track')); check('百分比读数可见',widthOutput?.textContent==='85%'); check('粗体颜色 3 档完整',boldSelect.options.length===3&&BOLD_COLOR_MODES.join(',')==='default,accent,custom'); if(!location.search.includes('restored'))check('正文色为默认且不显示自定义颜色选择器',getComputedStyle(document.querySelector('strong')).color==='rgb(17, 24, 39)'&&boldPicker===null); diff --git a/scripts/reading-width.test.js b/scripts/reading-width.test.js index c24a4583..7a27ee50 100644 --- a/scripts/reading-width.test.js +++ b/scripts/reading-width.test.js @@ -55,5 +55,17 @@ test("外观设置使用范围滑杆并将无效旧值回落到 50%", async () = assert.equal(slider.props.max, 100); assert.equal(slider.props.step, 5); assert.equal(slider.props.value, "50"); + assert.equal(slider.props.style["--codex-rebuild-width-progress"], "0%"); assert.equal(output.props.children, "50%"); }); + +test("宽度滑杆显示强调色进度、主题轨道和键盘焦点", async () => { + const { readingCss } = await readingModule(); + const css = readingCss("80"); + + assert.match(css, /\[data-codex-rebuild-width-control\]::\-webkit-slider-runnable-track/); + assert.match(css, /linear-gradient\(to right,var\(--app-color-text-accent/); + assert.match(css, /color-mix\(in srgb,currentColor 18%,transparent\)/); + assert.match(css, /\[data-codex-rebuild-width-control\]:focus-visible/); + assert.match(css, /\[data-codex-rebuild-width-control\]:disabled/); +}); diff --git a/scripts/runtime/reading-width.mjs b/scripts/runtime/reading-width.mjs index 8abccc31..f94c839f 100644 --- a/scripts/runtime/reading-width.mjs +++ b/scripts/runtime/reading-width.mjs @@ -26,6 +26,11 @@ export function readingCss(value, boldMode = "default", customColor = DEFAULT_BO const bold = boldMode === "default" ? "" : `${boldSelector}{color:${boldMode === "accent" ? "var(--app-color-text-accent,var(--codex-base-accent,currentColor))" : customColor.toLowerCase()}}`; return `${selected} [data-selected-text-overlay-target]{--markdown-wide-block-max-width:100%} +[data-codex-rebuild-width-control]{appearance:none;width:9rem;height:1.25rem;cursor:pointer;background:transparent;color:inherit} +[data-codex-rebuild-width-control]::-webkit-slider-runnable-track{height:.25rem;border-radius:9999px;background:linear-gradient(to right,var(--app-color-text-accent,var(--codex-base-accent,#2f6fda)) 0 var(--codex-rebuild-width-progress),color-mix(in srgb,currentColor 18%,transparent) var(--codex-rebuild-width-progress) 100%);box-shadow:inset 0 0 0 1px color-mix(in srgb,currentColor 12%,transparent)} +[data-codex-rebuild-width-control]::-webkit-slider-thumb{appearance:none;width:1rem;height:1rem;margin-top:-.375rem;border:2px solid var(--color-background-primary,var(--color-background-surface,Canvas));border-radius:9999px;background:var(--app-color-text-accent,var(--codex-base-accent,#2f6fda));box-shadow:0 0 0 1px color-mix(in srgb,currentColor 18%,transparent)} +[data-codex-rebuild-width-control]:focus-visible{outline:2px solid var(--app-color-text-accent,var(--codex-base-accent,#2f6fda));outline-offset:2px;border-radius:9999px} +[data-codex-rebuild-width-control]:disabled{cursor:not-allowed;opacity:.5} ${bold} ${Object.entries({ narrow: 520, feature: 600, compact: 640, wide: 800, xwide: 860, xxwide: 1040, editor: 800, default: 720 }).map(([name, size]) => `.codex-dialog.codex-rebuild-dialog-${name}{width:min(${size}px,calc(100vw / var(--codex-window-zoom,1) - 32px));max-width:calc(100vw / var(--codex-window-zoom,1) - 32px)}`).join("\n")} `; @@ -93,7 +98,10 @@ export function renderReadingWidth(react, ui, Row, intl) { "aria-label": chinese ? "聊天正文宽度" : "Chat content width", "data-codex-rebuild-width-control": "true", className: "w-36", - style: { accentColor: "var(--app-color-text-accent)" }, + style: { + accentColor: "var(--app-color-text-accent)", + "--codex-rebuild-width-progress": `${(Number(value) - MIN_WIDTH_PERCENT) / (MAX_WIDTH_PERCENT - MIN_WIDTH_PERCENT) * 100}%`, + }, value, onChange: event => { const next = event.currentTarget.value; From c61fe52b71f05690ba1002b28b0fc381b602475b Mon Sep 17 00:00:00 2001 From: carptopus Date: Fri, 16 Oct 2026 02:59:16 +0800 Subject: [PATCH 06/51] Keep API-key root navigation available --- scripts/frontend-source-smoke.js | 2 +- scripts/patch-api-key-home-navigation.js | 57 ++++++++++++++----- scripts/patch-api-key-home-navigation.test.js | 26 ++++++++- 3 files changed, 69 insertions(+), 16 deletions(-) diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index 7eaee379..c3ee9e3b 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -82,7 +82,7 @@ function verifyFrontendSource(assets) { const navigationSource = fs.readFileSync(path.join(assets, navigationEntries[0]), "utf8"); assert.match(navigationSource, /\|\|\/\* Codex:API-key 首页恢复写入。 \*\/[A-Za-z_$][\w$]*===`apikey`/); assert.match(navigationSource, - /\|\|\/\* Codex:API-key 当前首页保持会话。 \*\/[A-Za-z_$][\w$]*===`auth:apikey`/); + /\|\|\/\* Codex:API-key 当前首页保持会话。 \*\/[A-Za-z_$][\w$]*===`auth:apikey`&&[A-Za-z_$][\w$]*\?\.pathname!==`\/`/); const accentModule = fs.readFileSync(path.join(assets, "codex-rebuild-accent-presets.js"), "utf8"); assert.match(accentModule, /codex-rebuild:accent-preset:v1/); assert.match(accentModule, /export function resolveAccentPreset/); diff --git a/scripts/patch-api-key-home-navigation.js b/scripts/patch-api-key-home-navigation.js index 62f61d25..531b8d48 100644 --- a/scripts/patch-api-key-home-navigation.js +++ b/scripts/patch-api-key-home-navigation.js @@ -4,10 +4,10 @@ * * 上游的读取端会使用 auth:apikey 查找最近位置,但写入端同时受 * 新导航模式和 ChatGPT capability 限制,导致 API-key 下从不写入。 - * 同时,旧导航模式不会把“当前会话已经属于首页”视为已到达目标,随后又拒绝 - * departedAt 为空的当前记录,最终让首页按钮落到空路由。 - * 这里只放行 apikey 的写入和当前首页短路,不开启这些 ChatGPT 账户能力, - * 也不改变其他认证方式。 + * 同时,旧导航模式不会把“当前会话已经属于首页”视为已到达目标,最终让 + * 首页按钮落到空路由。这里只允许非根路径的 API-key 当前会话短路;根路径 + * 仍须继续执行官方落地页导航,避免空数据启动停在没有页面组件的 `/`。 + * 补丁不开启 ChatGPT 账户能力,也不改变其他认证方式。 */ const fs = require("node:fs"); const path = require("node:path"); @@ -124,11 +124,20 @@ function returnsTrue(statement) { } function memberName(node) { + if (node?.type === "ChainExpression") node = node.expression; if (node?.type !== "MemberExpression") return null; if (!node.computed && node.property.type === "Identifier") return node.property.name; return literal(node.property); } +function memberRoot(node) { + let current = node; + while (current?.type === "MemberExpression" || current?.type === "ChainExpression") { + current = current.type === "ChainExpression" ? current.expression : current.object; + } + return current?.type === "Identifier" ? current.name : null; +} + function findCurrentHomeGuard(ast) { const candidates = []; for (const fn of ast.body.filter(node => node.type === "FunctionDeclaration")) { @@ -149,13 +158,25 @@ function findCurrentHomeGuard(ast) { }, true); if (guards.length !== 1) continue; + const sidebarModeMembers = nodes(guards[0].test, + node => node.type === "MemberExpression" && memberName(node) === "sidebarProductMode"); + if (sidebarModeMembers.length !== 2) continue; + const currentLocations = new Set(sidebarModeMembers.map(memberRoot).filter(Boolean)); + if (currentLocations.size !== 1) continue; + const currentLocation = [...currentLocations][0]; + const modeChecks = nodes(guards[0].test, node => node.type === "LogicalExpression" && node.operator === "&&" && - (node.left?.type === "Identifier" || isAccountKeyOverride(node.left, accountKey)) && + (node.left?.type === "Identifier" || + isAccountKeyOverride(node.left, accountKey, currentLocation)) && node.right?.type === "BinaryExpression" && ["!=", "!=="].includes(node.right.operator) && literal(node.right.right) === null); if (modeChecks.length !== 1) continue; - candidates.push({ accountKey, gate: modeChecks[0].left }); + candidates.push({ + accountKey, + currentLocation, + gate: modeChecks[0].left, + }); } if (candidates.length > 1) { throw new Error(`当前首页短路 数量异常(${candidates.length})`); @@ -171,12 +192,18 @@ function isApiKeyOverride(node, authMethod) { literal(comparison.right) === "apikey"; } -function isAccountKeyOverride(node, accountKey) { +function isAccountKeyOverride(node, accountKey, currentLocation) { if (node?.type !== "LogicalExpression" || node.operator !== "||") return false; - const comparison = node.right; - return comparison?.type === "BinaryExpression" && ["===", "=="].includes(comparison.operator) && - comparison.left?.type === "Identifier" && comparison.left.name === accountKey && - literal(comparison.right) === "auth:apikey"; + const override = node.right; + if (override?.type !== "LogicalExpression" || override.operator !== "&&") return false; + const account = override.left; + const pathname = override.right; + return account?.type === "BinaryExpression" && ["===", "=="].includes(account.operator) && + account.left?.type === "Identifier" && account.left.name === accountKey && + literal(account.right) === "auth:apikey" && + pathname?.type === "BinaryExpression" && ["!==", "!=", "===", "=="].includes(pathname.operator) && + memberName(pathname.left) === "pathname" && memberRoot(pathname.left) === currentLocation && + literal(pathname.right) === "/" && ["!==", "!="].includes(pathname.operator); } function patchSource(source) { @@ -195,7 +222,11 @@ function patchSource(source) { return { status: "not-applicable", source }; } const trackerPatched = isApiKeyOverride(tracker.gate, tracker.authMethod); - const currentHomePatched = isAccountKeyOverride(currentHome.gate, currentHome.accountKey); + const currentHomePatched = isAccountKeyOverride( + currentHome.gate, + currentHome.accountKey, + currentHome.currentLocation, + ); if (trackerPatched) { const gateSource = source.slice(tracker.gate.start, tracker.gate.end); if (!gateSource.includes(MARKER)) throw new Error("API-key 放行逻辑存在但缺少本项目标记"); @@ -227,7 +258,7 @@ function patchSource(source) { edits.push({ start: currentHome.gate.start, end: currentHome.gate.end, - replacement: `(${originalGate}||${CURRENT_HOME_MARKER}${currentHome.accountKey}===\`auth:apikey\`)`, + replacement: `(${originalGate}||${CURRENT_HOME_MARKER}${currentHome.accountKey}===\`auth:apikey\`&&${currentHome.currentLocation}?.pathname!==\`/\`)`, }); } let next = source; diff --git a/scripts/patch-api-key-home-navigation.test.js b/scripts/patch-api-key-home-navigation.test.js index c1027d2f..cb83e4ec 100644 --- a/scripts/patch-api-key-home-navigation.test.js +++ b/scripts/patch-api-key-home-navigation.test.js @@ -48,7 +48,7 @@ function restore(source, accountKey, { saved = { departedAt: null, location: { pathname: "/local/thread-1" } }, } = {}) { const navigations = []; - const current = { hash: "", pathname: currentPath, state: null }; + const current = currentPath == null ? null : { hash: "", pathname: currentPath, state: null }; const store = { get(key) { if (key === "wc") return false; @@ -61,7 +61,7 @@ function restore(source, accountKey, { "const wc=`wc`,Ug=`Ug`,lj=`lj`;", "const bti=()=>saved;", "const sti=location=>({hash:location.hash??``});", - "const Ati=(_store,location)=>location.pathname.startsWith(`/local/`)?`home`:null;", + "const Ati=(_store,location)=>location.pathname===`/`||location.pathname.startsWith(`/local/`)?`home`:null;", "const ym=location=>location.pathname;", source, "return Sti(store,{accountKey,area:`home`,navigate,productMode:`codex`});", @@ -78,6 +78,28 @@ test("API-key 旧导航模式下点击首页保持当前会话", () => { assert.deepEqual(restored.navigations, []); }); +test("API-key 根路径不短路,保留官方空数据落地页导航", () => { + const result = patchSource(fixture()); + const restored = restore(result.source, "auth:apikey", { + currentPath: "/", + saved: null, + }); + + assert.equal(restored.value, true); + assert.deepEqual(restored.navigations, ["/"]); +}); + +test("API-key 尚无当前路由时不访问空对象", () => { + const result = patchSource(fixture()); + const restored = restore(result.source, "auth:apikey", { + currentPath: null, + saved: null, + }); + + assert.equal(restored.value, true); + assert.deepEqual(restored.navigations, ["/"]); +}); + test("ChatGPT 旧导航模式不获得当前首页短路", () => { const result = patchSource(fixture()); const restored = restore(result.source, "chatgpt:account-1"); From 950c229a15a3722fc45c39f6d8b7fa8ac1e28e4d Mon Sep 17 00:00:00 2001 From: carptopus Date: Fri, 16 Oct 2026 11:15:36 +0800 Subject: [PATCH 07/51] Fix API-key home navigation routing --- scripts/frontend-source-smoke.js | 2 +- scripts/patch-api-key-home-navigation.js | 73 ++++++++++++++----- scripts/patch-api-key-home-navigation.test.js | 57 +++++++++++++-- 3 files changed, 108 insertions(+), 24 deletions(-) diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index c3ee9e3b..480ceb8e 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -82,7 +82,7 @@ function verifyFrontendSource(assets) { const navigationSource = fs.readFileSync(path.join(assets, navigationEntries[0]), "utf8"); assert.match(navigationSource, /\|\|\/\* Codex:API-key 首页恢复写入。 \*\/[A-Za-z_$][\w$]*===`apikey`/); assert.match(navigationSource, - /\|\|\/\* Codex:API-key 当前首页保持会话。 \*\/[A-Za-z_$][\w$]*===`auth:apikey`&&[A-Za-z_$][\w$]*\?\.pathname!==`\/`/); + /\/\* Codex:API-key 当前首页保持会话。 \*\/[A-Za-z_$][\w$]*===`auth:apikey`&&[A-Za-z_$][\w$]*===`home`&&[A-Za-z_$][\w$]*!=null&&\([A-Za-z_$][\w$]*\.pathname\.startsWith\(`\/local\/`\)\|\|[A-Za-z_$][\w$]*\.pathname\.startsWith\(`\/remote\/`\)\)/); const accentModule = fs.readFileSync(path.join(assets, "codex-rebuild-accent-presets.js"), "utf8"); assert.match(accentModule, /codex-rebuild:accent-preset:v1/); assert.match(accentModule, /export function resolveAccentPreset/); diff --git a/scripts/patch-api-key-home-navigation.js b/scripts/patch-api-key-home-navigation.js index 531b8d48..dceb3482 100644 --- a/scripts/patch-api-key-home-navigation.js +++ b/scripts/patch-api-key-home-navigation.js @@ -5,8 +5,9 @@ * 上游的读取端会使用 auth:apikey 查找最近位置,但写入端同时受 * 新导航模式和 ChatGPT capability 限制,导致 API-key 下从不写入。 * 同时,旧导航模式不会把“当前会话已经属于首页”视为已到达目标,最终让 - * 首页按钮落到空路由。这里只允许非根路径的 API-key 当前会话短路;根路径 - * 仍须继续执行官方落地页导航,避免空数据启动停在没有页面组件的 `/`。 + * 首页按钮落到空路由。这里只对 API-key 下已经位于 `/local/` 或 + * `/remote/` 的首页会话直接短路,不再依赖新导航开关、hash、区域推断或 + * sidebarProductMode;根路径和非会话页面仍执行官方导航。 * 补丁不开启 ChatGPT 账户能力,也不改变其他认证方式。 */ const fs = require("node:fs"); @@ -138,6 +139,40 @@ function memberRoot(node) { return current?.type === "Identifier" ? current.name : null; } +function logicalTerms(node, operator) { + if (node?.type !== "LogicalExpression" || node.operator !== operator) return [node]; + return [...logicalTerms(node.left, operator), ...logicalTerms(node.right, operator)]; +} + +function isComparison(node, identifier, operator, value) { + return node?.type === "BinaryExpression" && node.operator === operator && + node.left?.type === "Identifier" && node.left.name === identifier && + (value === null ? node.right?.type === "Literal" && node.right.value === null : + literal(node.right) === value); +} + +function isPathPrefixCheck(node, currentLocation, prefix) { + return node?.type === "CallExpression" && node.arguments.length === 1 && + literal(node.arguments[0]) === prefix && memberName(node.callee) === "startsWith" && + node.callee.object?.type === "MemberExpression" && + memberName(node.callee.object) === "pathname" && + memberRoot(node.callee.object) === currentLocation; +} + +function isCurrentHomeOverride(node, accountKey, area, currentLocation) { + const terms = logicalTerms(node, "&&"); + if (terms.length !== 4) return false; + const paths = terms.find(item => item?.type === "LogicalExpression" && item.operator === "||"); + if (!paths) return false; + const pathTerms = logicalTerms(paths, "||"); + return terms.some(item => isComparison(item, accountKey, "===", "auth:apikey")) && + terms.some(item => isComparison(item, area, "===", "home")) && + terms.some(item => isComparison(item, currentLocation, "!=", null)) && + pathTerms.length === 2 && + pathTerms.some(item => isPathPrefixCheck(item, currentLocation, "/local/")) && + pathTerms.some(item => isPathPrefixCheck(item, currentLocation, "/remote/")); +} + function findCurrentHomeGuard(ast) { const candidates = []; for (const fn of ast.body.filter(node => node.type === "FunctionDeclaration")) { @@ -168,14 +203,23 @@ function findCurrentHomeGuard(ast) { const modeChecks = nodes(guards[0].test, node => node.type === "LogicalExpression" && node.operator === "&&" && (node.left?.type === "Identifier" || - isAccountKeyOverride(node.left, accountKey, currentLocation)) && + isLegacyCurrentHomeOverride(node.left, accountKey, currentLocation)) && node.right?.type === "BinaryExpression" && ["!=", "!=="].includes(node.right.operator) && literal(node.right.right) === null); if (modeChecks.length !== 1) continue; + const overrides = nodes(fn, node => node.type === "IfStatement" && + returnsTrue(node.consequent) && + isCurrentHomeOverride(node.test, accountKey, area, currentLocation), true); + if (overrides.length > 1) { + throw new Error(`API-key 当前首页短路 数量异常(${overrides.length})`); + } candidates.push({ accountKey, + area, currentLocation, gate: modeChecks[0].left, + statement: guards[0], + override: overrides[0] ?? null, }); } if (candidates.length > 1) { @@ -192,7 +236,7 @@ function isApiKeyOverride(node, authMethod) { literal(comparison.right) === "apikey"; } -function isAccountKeyOverride(node, accountKey, currentLocation) { +function isLegacyCurrentHomeOverride(node, accountKey, currentLocation) { if (node?.type !== "LogicalExpression" || node.operator !== "||") return false; const override = node.right; if (override?.type !== "LogicalExpression" || override.operator !== "&&") return false; @@ -201,9 +245,9 @@ function isAccountKeyOverride(node, accountKey, currentLocation) { return account?.type === "BinaryExpression" && ["===", "=="].includes(account.operator) && account.left?.type === "Identifier" && account.left.name === accountKey && literal(account.right) === "auth:apikey" && - pathname?.type === "BinaryExpression" && ["!==", "!=", "===", "=="].includes(pathname.operator) && + pathname?.type === "BinaryExpression" && ["!==", "!="].includes(pathname.operator) && memberName(pathname.left) === "pathname" && memberRoot(pathname.left) === currentLocation && - literal(pathname.right) === "/" && ["!==", "!="].includes(pathname.operator); + literal(pathname.right) === "/"; } function patchSource(source) { @@ -222,11 +266,7 @@ function patchSource(source) { return { status: "not-applicable", source }; } const trackerPatched = isApiKeyOverride(tracker.gate, tracker.authMethod); - const currentHomePatched = isAccountKeyOverride( - currentHome.gate, - currentHome.accountKey, - currentHome.currentLocation, - ); + const currentHomePatched = currentHome.override != null; if (trackerPatched) { const gateSource = source.slice(tracker.gate.start, tracker.gate.end); if (!gateSource.includes(MARKER)) throw new Error("API-key 放行逻辑存在但缺少本项目标记"); @@ -235,8 +275,8 @@ function patchSource(source) { throw new Error("导航模式与 ChatGPT capability 条件结构未知"); } if (currentHomePatched) { - const gateSource = source.slice(currentHome.gate.start, currentHome.gate.end); - if (!gateSource.includes(CURRENT_HOME_MARKER)) { + const overrideSource = source.slice(currentHome.override.start, currentHome.override.end); + if (!overrideSource.includes(CURRENT_HOME_MARKER)) { throw new Error("API-key 当前首页逻辑存在但缺少本项目标记"); } } else if (currentHome.gate.type !== "Identifier") { @@ -254,11 +294,10 @@ function patchSource(source) { }); } if (!currentHomePatched) { - const originalGate = source.slice(currentHome.gate.start, currentHome.gate.end); edits.push({ - start: currentHome.gate.start, - end: currentHome.gate.end, - replacement: `(${originalGate}||${CURRENT_HOME_MARKER}${currentHome.accountKey}===\`auth:apikey\`&&${currentHome.currentLocation}?.pathname!==\`/\`)`, + start: currentHome.statement.start, + end: currentHome.statement.start, + replacement: `if(${CURRENT_HOME_MARKER}${currentHome.accountKey}===\`auth:apikey\`&&${currentHome.area}===\`home\`&&${currentHome.currentLocation}!=null&&(${currentHome.currentLocation}.pathname.startsWith(\`/local/\`)||${currentHome.currentLocation}.pathname.startsWith(\`/remote/\`)))return!0;`, }); } let next = source; diff --git a/scripts/patch-api-key-home-navigation.test.js b/scripts/patch-api-key-home-navigation.test.js index cb83e4ec..a0441753 100644 --- a/scripts/patch-api-key-home-navigation.test.js +++ b/scripts/patch-api-key-home-navigation.test.js @@ -45,28 +45,39 @@ test("API-key 在 ChatGPT capability 关闭时仍写入与读取端一致的 acc function restore(source, accountKey, { currentPath = "/local/thread-1", + currentHash = "", + currentState = null, + newNavigation = false, + sanitizedHash = currentHash, saved = { departedAt: null, location: { pathname: "/local/thread-1" } }, } = {}) { const navigations = []; - const current = currentPath == null ? null : { hash: "", pathname: currentPath, state: null }; + const current = currentPath == null ? null : { + hash: currentHash, + pathname: currentPath, + state: currentState, + }; const store = { get(key) { - if (key === "wc") return false; + if (key === "wc") return newNavigation; if (key === "Ug") return current; if (key === "lj") return "codex"; return null; }, }; - const run = Function("store", "navigate", "accountKey", "saved", [ + const run = Function("store", "navigate", "accountKey", "saved", "sanitizedHash", [ "const wc=`wc`,Ug=`Ug`,lj=`lj`;", "const bti=()=>saved;", - "const sti=location=>({hash:location.hash??``});", - "const Ati=(_store,location)=>location.pathname===`/`||location.pathname.startsWith(`/local/`)?`home`:null;", + "const sti=()=>({hash:sanitizedHash});", + "const Ati=(_store,location)=>location.pathname===`/`||location.pathname.startsWith(`/local/`)||location.pathname.startsWith(`/remote/`)?`home`:null;", "const ym=location=>location.pathname;", source, "return Sti(store,{accountKey,area:`home`,navigate,productMode:`codex`});", ].join("")); - return { navigations, value: run(store, path => navigations.push(path), accountKey, saved) }; + return { + navigations, + value: run(store, path => navigations.push(path), accountKey, saved, sanitizedHash), + }; } test("API-key 旧导航模式下点击首页保持当前会话", () => { @@ -78,6 +89,29 @@ test("API-key 旧导航模式下点击首页保持当前会话", () => { assert.deepEqual(restored.navigations, []); }); +test("API-key 远程会话点击首页保持当前会话", () => { + const result = patchSource(fixture()); + const restored = restore(result.source, "auth:apikey", { + currentPath: "/remote/task-1", + }); + + assert.equal(restored.value, true); + assert.deepEqual(restored.navigations, []); +}); + +test("API-key 会话短路不依赖 hash 和 sidebarProductMode", () => { + const result = patchSource(fixture()); + const restored = restore(result.source, "auth:apikey", { + currentHash: "#panel=diff", + currentState: { sidebarProductMode: "other" }, + newNavigation: true, + sanitizedHash: "", + }); + + assert.equal(restored.value, true); + assert.deepEqual(restored.navigations, []); +}); + test("API-key 根路径不短路,保留官方空数据落地页导航", () => { const result = patchSource(fixture()); const restored = restore(result.source, "auth:apikey", { @@ -119,6 +153,17 @@ test("API-key 从设置页仍恢复已经离开的首页会话", () => { assert.deepEqual(restored.navigations, ["/local/thread-1"]); }); +test("API-key 非会话页面不获得当前首页短路", () => { + const result = patchSource(fixture()); + const restored = restore(result.source, "auth:apikey", { + currentPath: "/projects/example", + saved: { departedAt: Date.now(), location: { pathname: "/local/thread-1" } }, + }); + + assert.equal(restored.value, true); + assert.deepEqual(restored.navigations, ["/local/thread-1"]); +}); + test("ChatGPT 登录继续遵守官方 capability 与账户条件", () => { const result = patchSource(fixture()); From c2a176fdcc7de24086bdc48570565a5f5452ab56 Mon Sep 17 00:00:00 2001 From: carptopus Date: Fri, 16 Oct 2026 11:37:40 +0800 Subject: [PATCH 08/51] Adapt Windows patches to latest upstream --- scripts/patch-hide-pet-menu.js | 17 +++- scripts/patch-hide-pet-menu.test.js | 11 +++ scripts/patch-provider-quota.js | 143 ++++++++++----------------- scripts/patch-provider-quota.test.js | 52 ++++++++++ 4 files changed, 128 insertions(+), 95 deletions(-) create mode 100644 scripts/patch-provider-quota.test.js diff --git a/scripts/patch-hide-pet-menu.js b/scripts/patch-hide-pet-menu.js index 4612628a..62c05a12 100644 --- a/scripts/patch-hide-pet-menu.js +++ b/scripts/patch-hide-pet-menu.js @@ -55,6 +55,9 @@ function patchSource(source) { node.id?.name && LABEL_IDS.every((id) => source.slice(node.start, node.end).includes(id)), ); + if (petComponents.length === 0) { + return { status: "not-applicable", source }; + } if (petComponents.length !== 1) { return { status: "unexpected-pet-component-count", @@ -102,15 +105,25 @@ function locateTargets(platform) { for (const name of platforms) { const directory = path.join(SRC_DIR, name, "_asar", "webview", "assets"); if (!fs.existsSync(directory)) continue; - const matches = fs.readdirSync(directory) + const candidates = fs.readdirSync(directory) .filter((file) => file.endsWith(".js")) .map((file) => path.join(directory, file)) .filter((file) => { const source = fs.readFileSync(file, "utf8"); return LABEL_IDS.every((id) => source.includes(id)); }); + const diagnostics = []; + const matches = candidates.filter((file) => { + const result = patchSource(fs.readFileSync(file, "utf8")); + if (["patched", "already-patched"].includes(result.status)) return true; + if (result.status !== "not-applicable") { + diagnostics.push(`${path.basename(file)}: ${result.status}`); + } + return false; + }); if (matches.length !== 1) { - throw new Error(`[${name}] Pet 菜单资源数量异常(${matches.length})`); + const detail = diagnostics.length ? `;${diagnostics.join(";")}` : ""; + throw new Error(`[${name}] Pet 菜单资源数量异常(${matches.length})${detail}`); } targets.push({ platform: name, path: matches[0] }); } diff --git a/scripts/patch-hide-pet-menu.test.js b/scripts/patch-hide-pet-menu.test.js index 60dca14a..74ce434d 100644 --- a/scripts/patch-hide-pet-menu.test.js +++ b/scripts/patch-hide-pet-menu.test.js @@ -43,3 +43,14 @@ test("Pet 组件存在但菜单调用结构未知时明确失败", () => { test("没有 Pet 功能的资源不适用", () => { assert.equal(patchSource("function menu(){return null}").status, "not-applicable"); }); + +test("只包含 Pet 本地化文案的资源不构成菜单目标", () => { + const source = `const messages=${JSON.stringify(Object.fromEntries([ + "showPet", + "hidePet", + "showMini", + "hideMini", + ].map(name => [`codex.profileFooter.${name}`, name])))};`; + + assert.equal(patchSource(source).status, "not-applicable"); +}); diff --git a/scripts/patch-provider-quota.js b/scripts/patch-provider-quota.js index 36f4eaae..187dd1f0 100644 --- a/scripts/patch-provider-quota.js +++ b/scripts/patch-provider-quota.js @@ -80,61 +80,21 @@ function importFor(ast, localName) { return null; } -function exportFor(ast, localName) { - for (const declaration of ast.body) { - if (declaration.type !== "ExportNamedDeclaration") continue; - const specifier = declaration.specifiers.find(s => s.local.name === localName); - if (specifier) return specifier.exported.name; - } - return null; -} - -function getQuotaMetadata(source) { +function getProviderMetadata(source) { const ast = parseModule(source); - const hardBlockAtoms = nodes(ast, node => { - const item = binding(node); - if (item?.init?.type !== "CallExpression") return false; - return item.init.arguments.some(arg => arg.type === "ArrowFunctionExpression" && - property(arg.body) === "hardBlocked" && - unwrap(arg.body).object.type === "CallExpression"); - }).map(node => binding(node).name); - // Upstream's ordinary-model presets already resolve thread provider before - // config.model_provider. Reuse that exact thread-summary atom, not its name, - // the provider's display name, an auth flag, or a particular model slug. const providerReads = nodes(ast, node => node.type === "LogicalExpression" && node.operator === "??" && node.left.type === "CallExpression" && - node.left.arguments.length === 2 && property(node.right) === "model_provider"); - if (hardBlockAtoms.length !== 1 || providerReads.length !== 1) { - throw new Error("OpenAI quota atom or effective thread-provider lookup is ambiguous/missing"); - } - const hardBlockExport = exportFor(ast, hardBlockAtoms[0]); - const threadProviderImport = importFor(ast, providerReads[0].left.arguments[0].name); - if (!hardBlockExport || !threadProviderImport) { - throw new Error("OpenAI quota/thread-provider module bindings not found"); + node.left.arguments.length === 2 && node.left.arguments[0]?.type === "Identifier" && + property(node.right) === "model_provider"); + const providerAtoms = [...new Set(providerReads.map(node => node.left.arguments[0].name))]; + if (providerAtoms.length !== 1) { + throw new Error("Effective thread-provider lookup is ambiguous/missing"); } - return { hardBlockExport, threadProviderImport }; -} - -function importedLocal(ast, source, exportedName) { - for (const declaration of ast.body) { - if (declaration.type !== "ImportDeclaration" || declaration.source.value !== source) continue; - const specifier = declaration.specifiers.find(s => s.imported?.name === exportedName); - if (specifier) return specifier.local.name; + const threadProviderImport = importFor(ast, providerAtoms[0]); + if (!threadProviderImport) { + throw new Error("Effective thread-provider import not found"); } - return null; -} - -function quotaAtoms(ast, source) { - return new Set(nodes(ast, node => { - const item = binding(node); - if (item?.init?.type !== "CallExpression") return false; - return item.init.arguments.some(arg => { - if (arg.type !== "ArrowFunctionExpression") return false; - const text = source.slice(arg.start, arg.end); - return ["authMethod", "authenticatedAccountId", "rate_limit", "allowed", - "windowMinutes", "resetsAt"].every(key => text.includes(key)); - }); - }).map(node => binding(node).name)); + return { threadProviderAtom: providerAtoms[0], threadProviderImport }; } function unique(items, label) { @@ -159,19 +119,15 @@ function hasExternalBaseUrl(provider) { } } -function patchSource(source, metadata, initialImport) { +function patchSource(source) { try { const updating = source.includes(MARKER); const ast = parseModule(source); - const hardBlockAtom = importedLocal(ast, initialImport, metadata.hardBlockExport); - const threadProviderAtom = importedLocal(ast, metadata.threadProviderImport.source, - metadata.threadProviderImport.name); - if (!hardBlockAtom || !threadProviderAtom) throw new Error("Composer quota/provider imports not found"); + const { threadProviderAtom } = getProviderMetadata(source); if (!updating && [CUSTOM, PROVIDER, THREAD_PROVIDER, PROVIDER_CONFIG] .some(name => source.includes(name))) { throw new Error("Custom-provider patch binding already exists without its marker"); } - const nativeQuotaAtoms = quotaAtoms(ast, source); const composer = unique(ast.body.filter(node => node.type === "FunctionDeclaration" && nodes(node, child => property(child) === "submitDisabled", true).length > 0 && nodes(node, child => property(child) === "resolvedConfig").length > 0), @@ -186,41 +142,43 @@ function patchSource(source, metadata, initialImport) { const disabled = unique(declarations.filter(node => node.id.name === submit.value.name && node.init), "Submit-disabled expression"); const referenced = new Set(nodes(disabled.init, node => node.type === "Identifier").map(node => node.name)); - const hardBlock = unique(declarations.filter(node => referenced.has(node.id.name) && - node.init?.type === "CallExpression" && node.init.arguments[0]?.name === hardBlockAtom && - node.init.arguments.length === 2), "Host quota gate"); - const baseBlock = unique(declarations.filter(node => referenced.has(node.id.name) && node.init && - nodes(node.init, child => child.type === "CallExpression" && child.arguments.length === 1 && - nativeQuotaAtoms.has(child.arguments[0].name)).length > 0), "Account quota gate"); const configNames = new Set(memberReads.filter(node => property(node) === "resolvedConfig") .map(node => unwrap(node).object.name)); const pendingNames = new Set(memberReads.filter(node => property(node) === "isConfigDataPending") .map(node => unwrap(node).object.name)); const config = unique(declarations.filter(node => configNames.has(node.id.name) && pendingNames.has(node.id.name) && node.init?.type === "CallExpression"), "Resolved composer config"); - const target = config.init.arguments[0]; - const targets = target?.type === "ObjectExpression" ? [target] : ownNodes - .map(binding).filter(item => item?.name === target?.name && item.init?.type === "ObjectExpression") - .map(item => item.init); - const targetObject = unique(targets, "Composer config target"); + const contextGates = []; + for (const gate of declarations.filter(node => referenced.has(node.id.name) && + node.init?.type === "CallExpression")) { + for (const argument of gate.init.arguments.filter(arg => arg.type === "Identifier")) { + const assignments = ownNodes.map(binding).filter(item => item?.name === argument.name && item.init); + for (const assignment of assignments) { + const contexts = nodes(assignment.init, node => node.type === "ObjectExpression" && + ["conversationId", "hostId"].every(name => + node.properties.some(prop => property(prop) === name))); + for (const context of contexts) { + contextGates.push({ gate, context, contextName: argument.name }); + } + } + } + } + const contextGate = unique(contextGates, "Composer conversation/host quota gate"); + const targetObject = contextGate.context; const conversation = targetObject.properties.find(prop => property(prop) === "conversationId")?.value; const host = targetObject.properties.find(prop => property(prop) === "hostId")?.value; if (conversation?.type !== "Identifier" || host?.type !== "Identifier") { throw new Error("Composer config target lacks conversation/host identifiers"); } - function resolveAlias(name) { - const seen = new Set(); - while (!seen.has(name)) { - seen.add(name); - const alias = declarations.find(node => node.id.name === name && node.init?.type === "Identifier"); - if (!alias) break; - name = alias.init.name; - } - return name; - } - if (resolveAlias(host.name) !== resolveAlias(hardBlock.init.arguments[1].name)) { - throw new Error("Composer config and quota hosts differ"); - } + const baseBlock = contextGate.gate; + const hardBlock = unique(declarations.filter(node => { + if (!referenced.has(node.id.name) || node.init?.type !== "CallExpression" || + node.init.arguments.length !== 1) return false; + const terms = nodes(node.init.arguments[0], child => child.type === "BinaryExpression" && + ["===", "=="].includes(child.operator) && child.left?.type === "Identifier" && + child.left.name === host.name && value(child.right) === "local"); + return terms.length === 1; + }), "Host quota gate"); const scopes = [...new Set(ownNodes.filter(node => property(node) === "kind" && property(unwrap(node).object) === "value") .map(node => unwrap(unwrap(node).object).object.name))]; @@ -228,7 +186,7 @@ function patchSource(source, metadata, initialImport) { const statement = unique(composer.body.body.filter(node => node.type === "VariableDeclaration" && node.declarations.includes(disabled)), "Submit-disabled declaration"); if (config.end > statement.start) throw new Error("Composer config is resolved after submission gating"); - const guard = `${MARKER}\nconst ${THREAD_PROVIDER}=${source.slice(hardBlock.init.callee.start, hardBlock.init.callee.end)}(${threadProviderAtom},${conversation.name}),` + + const guard = `${MARKER}\nconst ${THREAD_PROVIDER}=${source.slice(baseBlock.init.callee.start, baseBlock.init.callee.end)}(${threadProviderAtom},${conversation.name}),` + `${PROVIDER}=${THREAD_PROVIDER}??(${config.id.name}.isConfigDataPending?null:${config.id.name}.resolvedConfig?.model_provider),` + `${PROVIDER_CONFIG}=${config.id.name}.isConfigDataPending?null:${config.id.name}.resolvedConfig?.model_providers?.[${PROVIDER}],` + `${CUSTOM}=(${scope}.value.kind===\`local\`||${scope}.value.kind===\`new\`&&!${scope}.value.cloudThreadPrototype)` + @@ -300,19 +258,18 @@ function main() { .map(name => ({ name, source: fs.readFileSync(path.join(directory.path, name), "utf8") })); const candidates = []; const diagnostics = []; - for (const file of files.filter(file => file.source.includes("hardBlocked") && - file.source.includes("model_provider") && file.source.includes("additional_rate_limits"))) { - try { candidates.push({ file, metadata: getQuotaMetadata(file.source) }); } + for (const file of files.filter(file => file.source.includes("submitDisabled") && + file.source.includes("model_provider") && file.source.includes("resolvedConfig") && + file.source.includes("isConfigDataPending"))) { + try { + const result = patchSource(file.source); + if (result.status === "error") throw new Error(result.reason); + candidates.push({ file, result }); + } catch (error) { diagnostics.push(`${file.name}: ${error.message}`); } } - if (!candidates.length) throw new Error(`OpenAI quota metadata not found; ${diagnostics.join("; ")}`); - const { file: initial, metadata } = unique(candidates, "OpenAI quota metadata bundle"); - const primary = unique(files.filter(file => file.name !== initial.name && - file.source.includes(`./${initial.name}`) && file.source.includes("submitDisabled") && - file.source.includes("resolvedConfig") && file.source.includes("isConfigDataPending")), - "Composer bundle"); - const result = patchSource(primary.source, metadata, `./${initial.name}`); - if (result.status === "error") throw new Error(result.reason); + if (!candidates.length) throw new Error(`Provider-aware composer not found; ${diagnostics.join("; ")}`); + const { file: primary, result } = unique(candidates, "Provider-aware composer bundle"); const filePath = path.join(directory.path, primary.name); console.log(` [${directory.platform}] ${relPath(filePath)}`); if (result.status === "already") { @@ -334,4 +291,4 @@ function main() { } if (require.main === module) main(); -module.exports = { MARKER, getQuotaMetadata, patchSource }; +module.exports = { MARKER, getProviderMetadata, patchSource }; diff --git a/scripts/patch-provider-quota.test.js b/scripts/patch-provider-quota.test.js new file mode 100644 index 00000000..c4ef1c57 --- /dev/null +++ b/scripts/patch-provider-quota.test.js @@ -0,0 +1,52 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { MARKER, getProviderMetadata, patchSource } = require("./patch-provider-quota"); + +function fixture() { + return [ + "import{provider as threadProvider,quota as quotaAtom,hard as hardBlockAtom,host as hostAtom}from'./initial.js';", + "function providerFor(store,id,config){return store.get(threadProvider,id)??config.model_provider}", + "function Composer(props){", + "let{submitDisabled:external}=props,scope=useScope(),conversation=currentConversation(),host=read(hostAtom,conversation),context;", + "cacheMiss()?(context=conversation==null?null:{conversationId:conversation,hostId:host}):context=cached();", + "let accountQuota=read(quotaAtom,context),config=useConfig(target),hardQuota=value(host===`local`&&hardBlockAtom);", + "let disabled=external||accountQuota||config.isLoading||hardQuota;", + "save(config.isConfigDataPending?null:config.resolvedConfig,scope.value.kind);", + "return jsx(Editor,{submitDisabled:disabled})", + "}", + ].join(""); +} + +test("按新版 Composer 数据流隔离第三方 Provider 的官方额度门槛", () => { + const result = patchSource(fixture()); + + assert.equal(result.status, "patched", result.reason); + assert.ok(result.code.includes(MARKER)); + assert.match(result.code, /const __codexQuotaThreadProvider=read\(threadProvider,conversation\)/); + assert.match(result.code, /\(!__codexUsesCustomProvider&&accountQuota\)/); + assert.match(result.code, /\(!__codexUsesCustomProvider&&hardQuota\)/); + assert.equal(patchSource(result.code).status, "already"); +}); + +test("多个 Provider 读取仍要求指向同一个会话 Provider atom", () => { + const source = fixture().replace( + "function Composer(props){", + "function another(get,id,config){return get(threadProvider,id)??config.model_provider}function Composer(props){", + ); + + assert.equal(getProviderMetadata(source).threadProviderAtom, "threadProvider"); + const result = patchSource(source); + assert.equal(result.status, "patched", result.reason); +}); + +test("会话 Provider atom 不唯一时拒绝补丁", () => { + const source = fixture().replace( + "function Composer(props){", + "function other(get,id,config){return get(otherProvider,id)??config.model_provider}function Composer(props){", + ); + const result = patchSource(source); + + assert.equal(result.status, "error"); + assert.match(result.reason, /thread-provider lookup is ambiguous/); +}); From 95fd9b63680c322dd2e383bcb01edff1c9798a7e Mon Sep 17 00:00:00 2001 From: carptopus Date: Sat, 17 Oct 2026 01:40:39 +0800 Subject: [PATCH 09/51] feat: update Windows candidate patches for current upstream --- .gitignore | 1 + README.md | 5 +- package.json | 2 + scripts/build-from-upstream.js | 4 +- scripts/frontend-source-smoke.js | 13 +- scripts/maintenance-smoke.js | 124 ++++- scripts/patch-accent-presets.test.js | 12 +- scripts/patch-api-key-home-navigation.js | 221 ++++---- scripts/patch-api-key-home-navigation.test.js | 110 ++-- scripts/patch-archive-delete.js | 183 ++++++- scripts/patch-archive-delete.test.js | 81 +++ scripts/patch-browser-auth.js | 39 +- scripts/patch-browser-auth.test.js | 25 +- scripts/patch-crash-forensics.js | 37 +- scripts/patch-fast-mode.js | 472 +++++++++--------- scripts/patch-fast-mode.test.js | 121 ++++- scripts/patch-policy.js | 2 +- scripts/patch-provider-quota.js | 11 +- scripts/patch-provider-quota.test.js | 15 + scripts/patch-worker-forensics.js | 32 +- scripts/prepare-src.js | 3 +- scripts/runtime/accent-presets.mjs | 5 +- scripts/storage-governance.js | 228 +++++++++ scripts/sync-upstream.js | 20 +- scripts/windows-maintenance.js | 62 ++- 25 files changed, 1333 insertions(+), 495 deletions(-) create mode 100644 scripts/patch-archive-delete.test.js create mode 100644 scripts/storage-governance.js diff --git a/.gitignore b/.gitignore index c5fefc57..708b991c 100644 --- a/.gitignore +++ b/.gitignore @@ -52,6 +52,7 @@ resources/codex.exe .cache/ artifacts/ /acceptance/ +/release/archive/ # Private maintenance documents and machine-local tools; never commit /local/ diff --git a/README.md b/README.md index 6648e483..c4e8a681 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,8 @@ npm run build:all - `src//_asar` 是 ASAR 内资源的补丁目标。 - `src//plugins` 与 `src//cua_node` 是 Browser / Computer Use 等外置运行时的补丁目标;直打包流程会显式覆盖这两个目录,避免重新复制上游安装包缓存时丢失补丁。 -- `patch-browser-auth.js` 兼容 API-key 登录:ChatGPT 身份与 request-header 策略可用时保持原行为;身份读取失败时仅关闭该可选请求头并继续本地浏览器通道,不会把 API key 伪装或发送为 ChatGPT token。 +- `patch-browser-auth.js` 兼容 API-key 登录:旧版在 ChatGPT 身份读取失败时仅关闭可选 request-header 并继续本地浏览器通道;新版原生托管请求头不再依赖 ChatGPT 身份时验证该完整链路并保持原样,不会把 API key 伪装或发送为 ChatGPT token。 +- `patch-fast-mode.js` 为 API-key / 自定义 Provider 补齐新版 `serviceTierAccess`:跳过不可用的 ChatGPT 账户权限查询,但仍由当前模型返回的 `serviceTierOptions` 决定是否显示和发送 Fast / Ultrafast 档位。 - `patch-provider-quota.js` 按任务实际 Provider 和明确的 `base_url` 判断发送门槛,避免 ChatGPT 额度状态误阻断第三方 Provider,同时保留官方、云任务及第三方真实错误。 - `patch-api-key-home-navigation.js` 补齐 API-key 模式的当前会话导航记录,使首页入口按官方读取逻辑恢复当前会话;ChatGPT、无认证及其他认证方式保持原有条件。 - `patch-accent-presets.js` 允许没有 ChatGPT 账户主题的 API-key / 自定义 Provider 在本地选择强调色,并复用官方完整预设渲染消息气泡等界面变量;账户主题仍在加载时保持禁用,账户可用时继续使用官方同步。 @@ -46,11 +47,13 @@ npm run build:all - `patch-reading-layout.js` 在外观主题卡片中加入 50%–100%、步进 5% 的正文宽度滑杆,并同步代码块、表格和输入区宽度,扩宽适用对话框;百分比不低于官方宽度,Markdown 粗体颜色可跟随正文、强调色或使用自定义颜色。 - `patch-test-isolation.js` 在官方设置 User Data 后、获取单实例锁前挂载 Windows 验收隔离,分别约束 `CODEX_HOME`、User Data 和 sessionData,并记录实际启动路径证据。 - `patch-model-picker-submenu.js` 增加对新版原生 simple / advanced 内联模型列表的结构核验;官方实现完整时保持原样,旧结构继续适配,未知结构明确失败。 +- `patch-archive-delete.js` 让归档列表明确查询全部 Provider,避免切换 Provider 后旧归档被隐藏;新版上游已有原生删除链路时保持原样,旧版才补充永久删除入口。 - `patch-updater.js` 区分更新方法与调用 Bundle,并在补丁后核对更新方法确实返回禁用状态;缺少目标或结构未知不再误报为已关闭。 - `sync-upstream.js`、`fetch-msstore.js` 和 `build-from-upstream.js` 强化 Windows x64 官方包选择与固定来源校验,支持精确版本和已验证原始 MSIX 重放;包身份、大小或 SHA-256 不符时拒绝构建,运行检查通过前不生成最终 ZIP。 - `windows-artifacts.js` 与 `windows-maintenance.js` 记录官方来源和候选产物哈希,生成候选、验证发布门槛,并保证正式发布复用已经验收的同一 ZIP。 - `windows-runtime-checks.js` 检查 Windows EXE / 原生模块架构及未修改组件哈希,实际加载 CUA、运行 code-mode host / rg 基础命令,并执行空白隔离桌面的启动、就绪和退出冒烟。 - `check-scripts.js`、`frontend-source-smoke.js`、`reading-layout-smoke.js` 和 `maintenance-smoke.js` 覆盖脚本语法、真实补丁资源、阅读设置及候选/发布拒绝路径,避免只凭补丁脚本成功退出判断功能可用。 +- `storage-governance.js` 审计本地缓存、构建目录和取证日志;清理模式只处理可重建缓存/构建中间结果、旧隔离验收数据和确认中断的临时目录,下载与验收运行各保留最近两次、取证日志保留最近 7 天并限制单文件大小,正式制品及当前与上一版程序不参与清理。 - `patch-realtime-voice-auth.js` 为 API-key 登录放行实时语音入口;实时会话仍由 app-server 使用当前 model provider 的 `base_url` 与认证创建,ChatGPT 工作区能力的认证限制保持不变。 - 上游更新后应先执行 `npm run patch -- --check` 或完整 `npm run patch`,再运行测试和构建。 diff --git a/package.json b/package.json index 65230b25..cf3e6f7e 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,8 @@ "test": "node --test scripts/*.test.js", "check": "node scripts/check-scripts.js", "test:maintenance": "node scripts/maintenance-smoke.js", + "storage:audit": "node scripts/storage-governance.js audit", + "storage:clean": "node scripts/storage-governance.js clean", "windows:check-update": "node scripts/windows-maintenance.js discover", "windows:candidate": "node scripts/windows-maintenance.js candidate", "windows:verify-release": "node scripts/windows-maintenance.js verify-release", diff --git a/scripts/build-from-upstream.js b/scripts/build-from-upstream.js index 9a7c6a78..2e71b09d 100644 --- a/scripts/build-from-upstream.js +++ b/scripts/build-from-upstream.js @@ -235,7 +235,7 @@ function buildMac(platform) { // 1. Find the .app in the ZIP extract cache const tempDir = process.env.CODEX_SYNC_DIR ? path.resolve(process.env.CODEX_SYNC_DIR) - : path.join(require("os").tmpdir(), "codex-sync"); + : path.join(PROJECT_ROOT, ".cache", "upstream-sync"); const variant = platform === "mac-arm64" ? "arm64" : "x64"; const extractDir = path.join(tempDir, `${variant}-extract`); @@ -319,7 +319,7 @@ function buildWin(platform, { deferZip = false } = {}) { // Windows: use the MSIX extract cache const tempDir = process.env.CODEX_SYNC_DIR ? path.resolve(process.env.CODEX_SYNC_DIR) - : path.join(require("os").tmpdir(), "codex-sync"); + : path.join(PROJECT_ROOT, ".cache", "upstream-sync"); const extractDir = path.join(tempDir, "win-extract"); const appDir = path.join(extractDir, "app"); diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index 480ceb8e..c0b18cb2 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -81,11 +81,20 @@ function verifyFrontendSource(assets) { assert.equal(navigationEntries.length, 1); const navigationSource = fs.readFileSync(path.join(assets, navigationEntries[0]), "utf8"); assert.match(navigationSource, /\|\|\/\* Codex:API-key 首页恢复写入。 \*\/[A-Za-z_$][\w$]*===`apikey`/); + assert.match(navigationSource, /authMethod:__codexAuthMethod/); assert.match(navigationSource, - /\/\* Codex:API-key 当前首页保持会话。 \*\/[A-Za-z_$][\w$]*===`auth:apikey`&&[A-Za-z_$][\w$]*===`home`&&[A-Za-z_$][\w$]*!=null&&\([A-Za-z_$][\w$]*\.pathname\.startsWith\(`\/local\/`\)\|\|[A-Za-z_$][\w$]*\.pathname\.startsWith\(`\/remote\/`\)\)/); + /\/\* Codex:API-key 当前首页保持会话。 \*\/__codexAuthMethod===`apikey`&&[A-Za-z_$][\w$]*!=null&&\([A-Za-z_$][\w$]*\.pathname\.startsWith\(`\/local\/`\)\|\|[A-Za-z_$][\w$]*\.pathname\.startsWith\(`\/remote\/`\)\)/); + const serviceTierEntries = files.filter(name => /^app-initial-/.test(name) + && fs.readFileSync(path.join(assets, name), "utf8").includes("CodexRebuildServiceTierApiKeyRequest")); + assert.equal(serviceTierEntries.length, 1); + const serviceTierSource = fs.readFileSync(path.join(assets, serviceTierEntries[0]), "utf8"); + assert.match(serviceTierSource, /CodexRebuildServiceTierApiKeyAuth/); + assert.match(serviceTierSource, /CodexRebuildServiceTierApiKeyAccess/); + assert.match(serviceTierSource, /\{fast:!0,ultrafast:!0\}\/\* CodexRebuildServiceTierApiKeyRequest \*\//); const accentModule = fs.readFileSync(path.join(assets, "codex-rebuild-accent-presets.js"), "utf8"); assert.match(accentModule, /codex-rebuild:accent-preset:v1/); assert.match(accentModule, /export function resolveAccentPreset/); + assert.match(accentModule, /preset === "default" \? "blue" : preset/); assert.doesNotMatch(accentModule, /getComputedStyle|#[0-9a-f]{6}/i); const readingModule = fs.readFileSync(path.join(assets, "codex-rebuild-reading-width.js"), "utf8"); assert.match(readingModule, /MIN_WIDTH_PERCENT = 50/); @@ -100,7 +109,7 @@ function verifyFrontendSource(assets) { assert.equal(shared.length, 1); const dialogs = fs.readFileSync(path.join(assets, shared[0]), "utf8"); assert.match(dialogs, /codex-rebuild-dialog-editor h-\[720px\] max-w-full max-h-full/); - return { passed: true, quotaScenarios: results, apiKeyHomeNavigation: true, nativeAppearanceRow: true, nativeAccentThemePipeline: true, dialogHeightPreserved: true }; + return { passed: true, quotaScenarios: results, apiKeyHomeNavigation: true, apiKeyServiceTiers: true, nativeAppearanceRow: true, nativeAccentThemePipeline: true, dialogHeightPreserved: true }; } if (require.main === module) console.log(JSON.stringify(verifyFrontendSource(path.resolve(process.argv[2] || "src/win/_asar/webview/assets")), null, 2)); module.exports = { verifyFrontendSource }; diff --git a/scripts/maintenance-smoke.js b/scripts/maintenance-smoke.js index d2ba74ff..fe8e94dc 100644 --- a/scripts/maintenance-smoke.js +++ b/scripts/maintenance-smoke.js @@ -6,7 +6,7 @@ const os = require("node:os"); const crypto = require("node:crypto"); const assert = require("node:assert/strict"); const { spawnSync } = require("node:child_process"); -const { requiredChecks } = require("./windows-maintenance"); +const { requiredChecks, saveCompatibilityEvidence } = require("./windows-maintenance"); const temporary = fs.mkdtempSync(path.join(os.tmpdir(), "codex-maintenance-smoke-")); const scriptRoot = __dirname; const hash = (value) => crypto.createHash("sha256").update(value).digest("hex"); @@ -88,6 +88,50 @@ try { write(path.join(updaterSource, "gates.js"), "const changed=true;"); assert.match(run("patch-updater.js", ["win"], 0, { CODEX_PATCH_SOURCE_DIR: path.join(temporary, "updater") }).stdout, /\[!\]/); + const evidencePlatform = path.join(temporary, "evidence", "win"); + const evidenceAsar = path.join(evidencePlatform, "_asar"); + const evidenceOutput = path.join(temporary, "evidence-output"); + write(path.join(evidenceAsar, ".vite", "build", "early-bootstrap.js"), "const startup=true;"); + write(path.join(evidenceAsar, "webview", "assets", "app.js"), "const app=true;"); + const browserService = [ + 'const gate="codex_browser_use_agent_request_header";', + "async function read(){try{return await feature(gate)}catch{return!1}}", + ].join(""); + for (const plugin of ["browser", "chrome"]) { + write( + path.join( + evidencePlatform, + "plugins", + "openai-bundled", + "plugins", + plugin, + "scripts", + "browser-service.mjs", + ), + browserService, + ); + } + saveCompatibilityEvidence(evidenceAsar, { version: "fixture" }, evidenceOutput); + const evidenceIndex = JSON.parse(fs.readFileSync(path.join(evidenceOutput, "index.json"), "utf8")); + const browserEvidence = evidenceIndex.files.filter((item) => item.name === "browser-service.mjs"); + assert.equal(browserEvidence.length, 2); + assert(browserEvidence.every((item) => item.copied)); + assert(browserEvidence.every((item) => item.matches.includes("codex_browser_use_agent_request_header"))); + assert.equal( + fs.existsSync(path.join( + evidenceOutput, + "external", + "plugins", + "openai-bundled", + "plugins", + "browser", + "scripts", + "browser-service.mjs", + )), + true, + ); + checks++; + const pickerRoot = path.join(temporary, "picker"); const pickerFile = path.join(pickerRoot, "win", "_asar", "webview", "assets", "model-picker.js"); const nativePicker = 'function picker(input){const {modelListConfig:list,menuView:view,onToggleMenuView:toggle}=input;const items=list.options.map(option=>ui.jsx(menu.Item,{"data-model-selected":option.selected,role:`menuitemradio`,onSelect:event=>{event.preventDefault();option.onSelect();toggle(`simple`)}}));return ui.jsx("div",{"data-model-picker-view":view,children:items});}'; @@ -143,6 +187,84 @@ try { json(path.join(candidate, "candidate.json"), metadata); run("windows-maintenance.js", arguments.map((value) => value === "123" ? "999" : value), 1); run("windows-maintenance.js", arguments.map((value) => value === sha ? "2".repeat(40) : value), 1); + + const storageRoot = path.join(temporary, "storage-project"); + const storageTemp = path.join(temporary, "storage-temp"); + const storageForensics = path.join(temporary, "storage-forensics"); + const old = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000); + for (const name of ["100", "200", "300"]) { + write(path.join(storageRoot, ".cache", "downloads", name, "payload.bin"), name); + fs.utimesSync(path.join(storageRoot, ".cache", "downloads", name), old, new Date(old.getTime() + Number(name))); + write(path.join(storageRoot, ".cache", "gh-downloads", name, "payload.bin"), name); + fs.utimesSync(path.join(storageRoot, ".cache", "gh-downloads", name), old, new Date(old.getTime() + Number(name))); + write(path.join(storageRoot, ".cache", "acceptance", name, "profile.bin"), name); + fs.utimesSync(path.join(storageRoot, ".cache", "acceptance", name), old, new Date(old.getTime() + Number(name))); + } + write(path.join(storageRoot, ".cache", "downloads", "300", "payload.zip"), "done"); + write(path.join(storageRoot, ".cache", "downloads", "300", "payload.zip.parts", "0.part"), "duplicate"); + write(path.join(storageRoot, "build", "Codex", "Codex.exe"), "protected"); + write(path.join(storageRoot, "build", "previous", "Codex.exe"), "protected previous"); + for (const directory of ["src", "out", "out-win", "patch-reports"]) write(path.join(storageRoot, directory, "generated.bin"), "generated"); + for (const name of [".next-preparing-123", ".previous-retired-123"]) { + write(path.join(storageRoot, "build", name, "Codex.exe"), "interrupted"); + fs.utimesSync(path.join(storageRoot, "build", name), old, old); + } + for (let day = 1; day <= 9; day++) write(path.join(storageForensics, `forensics-2026-10-${String(day).padStart(2, "0")}.log`), String(day)); + write(path.join(storageForensics, "chrome-debug.log"), "x".repeat(64)); + write(path.join(storageForensics, "forensics-2026-10-09.log"), "x".repeat(64)); + write(path.join(storageTemp, "codex-forensics-fatal.log"), "x".repeat(64)); + write(path.join(storageTemp, "codex-main-test-old", "fixture"), "old"); + fs.utimesSync(path.join(storageTemp, "codex-main-test-old"), old, old); + write(path.join(storageTemp, "codex-rebuild-old", "fixture"), "old"); + fs.utimesSync(path.join(storageTemp, "codex-rebuild-old"), old, old); + const storageEnv = { CODEX_STORAGE_TEST_MODE: "1", CODEX_STORAGE_TEST_ROOT: storageRoot, + CODEX_STORAGE_TEST_TEMP: storageTemp, CODEX_STORAGE_TEST_FORENSICS: storageForensics, + CODEX_STORAGE_TEST_LOG_LIMIT: "32", CODEX_STORAGE_TEST_FATAL_LOG_LIMIT: "16" }; + run("storage-governance.js", ["clean"], 0, storageEnv); + assert.equal(fs.existsSync(path.join(storageRoot, ".cache", "downloads", "100")), false); + assert.equal(fs.existsSync(path.join(storageRoot, ".cache", "downloads", "200")), true); + assert.equal(fs.existsSync(path.join(storageRoot, ".cache", "gh-downloads", "100")), false); + assert.equal(fs.existsSync(path.join(storageRoot, ".cache", "acceptance", "100")), false); + assert.equal(fs.existsSync(path.join(storageRoot, ".cache", "downloads", "300", "payload.zip.parts")), false); + assert.equal(fs.readFileSync(path.join(storageRoot, "build", "Codex", "Codex.exe"), "utf8"), "protected"); + assert.equal(fs.readFileSync(path.join(storageRoot, "build", "previous", "Codex.exe"), "utf8"), "protected previous"); + assert.equal(fs.existsSync(path.join(storageRoot, "build", ".next-preparing-123")), false); + assert.equal(fs.existsSync(path.join(storageRoot, "build", ".previous-retired-123")), false); + for (const directory of ["src", "out", "out-win", "patch-reports"]) assert.equal(fs.existsSync(path.join(storageRoot, directory)), false); + assert.equal(fs.existsSync(path.join(storageTemp, "codex-main-test-old")), false); + assert.equal(fs.existsSync(path.join(storageTemp, "codex-rebuild-old")), false); + assert.equal(fs.readdirSync(storageForensics).filter(name => /^forensics-\d{4}-\d{2}-\d{2}\.log$/.test(name)).length, 7); + assert.equal(fs.statSync(path.join(storageForensics, "chrome-debug.log")).size, 32); + assert.equal(fs.statSync(path.join(storageForensics, "forensics-2026-10-09.log")).size, 32); + assert.equal(fs.statSync(path.join(storageTemp, "codex-forensics-fatal.log")).size, 16); + checks++; + + if (process.platform === "win32") { + const archiveProject = path.join(temporary, "archive-project"); + const archiveScript = path.join(archiveProject, "local", "scripts", "Archive-Candidate.ps1"); + fs.mkdirSync(path.dirname(archiveScript), { recursive: true }); + fs.copyFileSync(path.join(scriptRoot, "..", "local", "scripts", "Archive-Candidate.ps1"), archiveScript); + for (let index = 1; index <= 3; index++) { + const candidateDirectory = path.join(archiveProject, `candidate-${index}`); + const zipName = `candidate-${index}.zip`, packageName = `source-${index}.msix`; + const zipPayload = `zip-${index}`, packagePayload = `msix-${index}`; + write(path.join(candidateDirectory, zipName), zipPayload); + write(path.join(candidateDirectory, packageName), packagePayload); + json(path.join(candidateDirectory, "candidate.json"), { + schemaVersion: 1, repository: "Carptopus/CodexDesktop-Rebuild", + sourceCommit: String(index).repeat(40), + upstream: { version: `1.0.0.${index}`, packageName, sha256: hash(packagePayload) }, + zip: { name: zipName, sha256: hash(zipPayload) }, + }); + const archived = spawnSync("pwsh", ["-NoProfile", "-File", archiveScript, "-CandidateDirectory", candidateDirectory, "-Keep", "2"], { encoding: "utf8" }); + assert.equal(archived.status, 0, archived.stdout + archived.stderr); + const destination = path.join(archiveProject, "release", "archive", `1.0.0.${index}-${String(index).repeat(40)}`); + fs.utimesSync(destination, new Date(2020, 0, index), new Date(2020, 0, index)); + } + const kept = fs.readdirSync(path.join(archiveProject, "release", "archive")).sort(); + assert.deepEqual(kept, [`1.0.0.2-${"2".repeat(40)}`, `1.0.0.3-${"3".repeat(40)}`]); + checks++; + } console.log(`维护链功能测试通过:${checks} 个 CLI 场景;实际 GUI、原始 MSIX 和签名由候选验收覆盖。`); } finally { fs.rmSync(temporary, { recursive: true, force: true }); diff --git a/scripts/patch-accent-presets.test.js b/scripts/patch-accent-presets.test.js index d9423c6d..3d652669 100644 --- a/scripts/patch-accent-presets.test.js +++ b/scripts/patch-accent-presets.test.js @@ -139,7 +139,7 @@ test("本地设置、账户优先和自定义清理使用同一预设状态", as assert.equal(storage.values.has(runtime.ACCENT_PRESET_STORAGE_KEY), false); }); -test("预设解析保留名称语义并拒绝无效本地值", async () => { +test("预设解析补齐官方默认有效色并拒绝无效本地值", async () => { const runtime = await runtimeModule(); const storage = fakeStorage({ [runtime.ACCENT_PRESET_STORAGE_KEY]: "blue" }); globalThis.localStorage = storage; @@ -147,10 +147,13 @@ test("预设解析保留名称语义并拒绝无效本地值", async () => { assert.equal(runtime.resolveAccentPreset("chatgpt", "green"), "green"); assert.equal(runtime.resolveAccentPreset("custom", "green"), null); - for (const preset of ["default", "blue", "black"]) { + for (const preset of ["blue", "black"]) { storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, preset); assert.equal(runtime.resolveAccentPreset("custom", null), preset); } + storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, "default"); + assert.equal(runtime.accentPresetSelection(null, "custom"), "default"); + assert.equal(runtime.resolveAccentPreset("custom", null), "blue"); storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, "not-a-preset"); assert.equal(runtime.resolveAccentPreset("custom", null), null); }); @@ -177,9 +180,12 @@ test("完整主题链复用官方预设气泡且账户主题优先", async t => const accountCustom = theme.Tba({ accentSource: "custom", accent: "#custom" }, "light", "green"); assert.equal(accountCustom["--color-background-user-message"], "neutral-bubble"); - for (const preset of ["default", "blue", "black"]) { + for (const preset of ["blue", "black"]) { storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, preset); const rendered = theme.Tba({ accentSource: "custom", accent: "#custom" }, "light", null); assert.equal(rendered["--color-background-user-message"], `#${preset}-bubble`); } + storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, "default"); + const localDefault = theme.Tba({ accentSource: "custom", accent: "#custom" }, "light", null); + assert.equal(localDefault["--color-background-user-message"], "#blue-bubble"); }); diff --git a/scripts/patch-api-key-home-navigation.js b/scripts/patch-api-key-home-navigation.js index dceb3482..72412713 100644 --- a/scripts/patch-api-key-home-navigation.js +++ b/scripts/patch-api-key-home-navigation.js @@ -4,10 +4,10 @@ * * 上游的读取端会使用 auth:apikey 查找最近位置,但写入端同时受 * 新导航模式和 ChatGPT capability 限制,导致 API-key 下从不写入。 - * 同时,旧导航模式不会把“当前会话已经属于首页”视为已到达目标,最终让 - * 首页按钮落到空路由。这里只对 API-key 下已经位于 `/local/` 或 - * `/remote/` 的首页会话直接短路,不再依赖新导航开关、hash、区域推断或 - * sidebarProductMode;根路径和非会话页面仍执行官方导航。 + * 同时,侧栏房子按钮使用独立的 openHome 分支直接导航到 `/`,不会进入 + * 上述首页恢复函数。这里只给该按钮传入真实 authMethod,并在 API-key 已经 + * 位于 `/local/` 或 `/remote/` 时短路;根路径和非会话页面仍执行 + * 官方导航。 * 补丁不开启 ChatGPT 账户能力,也不改变其他认证方式。 */ const fs = require("node:fs"); @@ -63,6 +63,13 @@ function objectBinding(pattern, name) { return property?.value?.type === "Identifier" ? property.value.name : null; } +function optionBinding(pattern, name) { + const property = pattern.properties.find(item => propertyName(item) === name); + if (property?.value?.type === "Identifier") return property.value.name; + return property?.value?.type === "AssignmentPattern" && property.value.left?.type === "Identifier" + ? property.value.left.name : null; +} + function unique(items, label) { if (items.length !== 1) throw new Error(`${label} 数量异常(${items.length})`); return items[0]; @@ -117,11 +124,9 @@ function findTracker(ast) { return candidates[0] ?? null; } -function returnsTrue(statement) { - if (statement?.type !== "ReturnStatement") return false; - if (literal(statement.argument) === true) return true; - return statement.argument?.type === "UnaryExpression" && statement.argument.operator === "!" && - literal(statement.argument.argument) === 0; +function isTrue(node) { + return literal(node) === true || node?.type === "UnaryExpression" && + node.operator === "!" && literal(node.argument) === 0; } function memberName(node) { @@ -131,6 +136,11 @@ function memberName(node) { return literal(node.property); } +function memberObject(node) { + if (node?.type === "ChainExpression") node = node.expression; + return node?.type === "MemberExpression" ? node.object : null; +} + function memberRoot(node) { let current = node; while (current?.type === "MemberExpression" || current?.type === "ChainExpression") { @@ -139,93 +149,80 @@ function memberRoot(node) { return current?.type === "Identifier" ? current.name : null; } -function logicalTerms(node, operator) { - if (node?.type !== "LogicalExpression" || node.operator !== operator) return [node]; - return [...logicalTerms(node.left, operator), ...logicalTerms(node.right, operator)]; -} - -function isComparison(node, identifier, operator, value) { - return node?.type === "BinaryExpression" && node.operator === operator && - node.left?.type === "Identifier" && node.left.name === identifier && - (value === null ? node.right?.type === "Literal" && node.right.value === null : - literal(node.right) === value); -} - -function isPathPrefixCheck(node, currentLocation, prefix) { - return node?.type === "CallExpression" && node.arguments.length === 1 && - literal(node.arguments[0]) === prefix && memberName(node.callee) === "startsWith" && - node.callee.object?.type === "MemberExpression" && - memberName(node.callee.object) === "pathname" && - memberRoot(node.callee.object) === currentLocation; +function objectProperty(node, name) { + return node?.properties?.find(property => propertyName(property) === name) ?? null; } -function isCurrentHomeOverride(node, accountKey, area, currentLocation) { - const terms = logicalTerms(node, "&&"); - if (terms.length !== 4) return false; - const paths = terms.find(item => item?.type === "LogicalExpression" && item.operator === "||"); - if (!paths) return false; - const pathTerms = logicalTerms(paths, "||"); - return terms.some(item => isComparison(item, accountKey, "===", "auth:apikey")) && - terms.some(item => isComparison(item, area, "===", "home")) && - terms.some(item => isComparison(item, currentLocation, "!=", null)) && - pathTerms.length === 2 && - pathTerms.some(item => isPathPrefixCheck(item, currentLocation, "/local/")) && - pathTerms.some(item => isPathPrefixCheck(item, currentLocation, "/remote/")); -} - -function findCurrentHomeGuard(ast) { - const candidates = []; +function findOpenHomeRoute(ast, source) { + const routes = []; for (const fn of ast.body.filter(node => node.type === "FunctionDeclaration")) { const options = fn.params[1]; if (options?.type !== "ObjectPattern") continue; - const accountKey = objectBinding(options, "accountKey"); - const area = objectBinding(options, "area"); - const productMode = objectBinding(options, "productMode"); - if (!accountKey || !area || !productMode) continue; + const bindings = Object.fromEntries([ + "codexLocalAccessStatus", "currentMode", "navigate", "nextMode", "openHome", + "restoreNavigation", "startNewConversation", "authMethod", + ].map(name => [name, optionBinding(options, name)])); + if (["codexLocalAccessStatus", "currentMode", "navigate", "nextMode", "openHome", + "restoreNavigation", "startNewConversation"].some(name => !bindings[name])) continue; - const guards = nodes(fn, node => { - if (node.type !== "IfStatement" || !returnsTrue(node.consequent)) return false; - const own = nodes(node.test, () => true); - const identifiers = new Set(own.filter(item => item.type === "Identifier") - .map(item => item.name)); - return own.some(item => memberName(item) === "sidebarProductMode") && - identifiers.has(area) && identifiers.has(productMode); + const branches = nodes(fn, node => { + if (node.type !== "IfStatement") return false; + const testIdentifiers = nodes(node.test, item => item.type === "Identifier") + .map(item => item.name); + if (!testIdentifiers.includes(bindings.openHome)) return false; + const body = nodes(node.consequent, () => true); + return body.some(item => item.type === "ReturnStatement") && + body.some(item => item.type === "CallExpression" && + item.callee?.type === "Identifier" && item.callee.name === bindings.navigate && + literal(item.arguments[0]) === "/" && + item.arguments[1]?.type === "ObjectExpression" && + objectProperty(objectProperty(item.arguments[1], "state")?.value, "sidebarProductMode")?.value?.name === bindings.nextMode); }, true); - if (guards.length !== 1) continue; - - const sidebarModeMembers = nodes(guards[0].test, - node => node.type === "MemberExpression" && memberName(node) === "sidebarProductMode"); - if (sidebarModeMembers.length !== 2) continue; - const currentLocations = new Set(sidebarModeMembers.map(memberRoot).filter(Boolean)); - if (currentLocations.size !== 1) continue; - const currentLocation = [...currentLocations][0]; + if (branches.length !== 1) continue; - const modeChecks = nodes(guards[0].test, node => node.type === "LogicalExpression" && - node.operator === "&&" && - (node.left?.type === "Identifier" || - isLegacyCurrentHomeOverride(node.left, accountKey, currentLocation)) && - node.right?.type === "BinaryExpression" && ["!=", "!=="].includes(node.right.operator) && - literal(node.right.right) === null); - if (modeChecks.length !== 1) continue; - const overrides = nodes(fn, node => node.type === "IfStatement" && - returnsTrue(node.consequent) && - isCurrentHomeOverride(node.test, accountKey, area, currentLocation), true); - if (overrides.length > 1) { - throw new Error(`API-key 当前首页短路 数量异常(${overrides.length})`); - } - candidates.push({ - accountKey, - area, - currentLocation, - gate: modeChecks[0].left, - statement: guards[0], - override: overrides[0] ?? null, + const libraryRoots = new Set(nodes(fn, node => node.type === "CallExpression" && + memberName(node.callee) === "startsWith" && literal(node.arguments[0]) === "/library/" && + memberName(memberObject(node.callee)) === "pathname") + .map(node => memberRoot(memberObject(node.callee))).filter(Boolean)); + const exactLibraryRoots = new Set(nodes(fn, node => node.type === "BinaryExpression" && + ["===", "=="].includes(node.operator) && literal(node.right) === "/library" && + memberName(node.left) === "pathname") + .map(node => memberRoot(node.left)).filter(Boolean)); + const currentLocations = [...libraryRoots].filter(name => exactLibraryRoots.has(name)); + if (currentLocations.length !== 1) continue; + routes.push({ + authMethod: bindings.authMethod, + branch: branches[0], + currentLocation: currentLocations[0], + fn, + options, + name: fn.id?.name, }); } - if (candidates.length > 1) { - throw new Error(`当前首页短路 数量异常(${candidates.length})`); + const route = unique(routes, "房子按钮 openHome 路由"); + const callers = []; + for (const fn of ast.body.filter(node => node.type === "FunctionDeclaration")) { + const authBindings = nodes(fn, node => node.type === "VariableDeclarator" && + node.id?.type === "ObjectPattern", true) + .map(node => objectBinding(node.id, "authMethod")).filter(Boolean); + if (authBindings.length !== 1) continue; + for (const call of nodes(fn, node => node.type === "CallExpression" && + node.callee?.type === "Identifier" && node.callee.name === route.name)) { + const options = call.arguments[1]; + if (options?.type !== "ObjectExpression" || + !isTrue(objectProperty(options, "openHome")?.value) || + literal(objectProperty(options, "nextMode")?.value) !== "codex") continue; + callers.push({ + authMethod: authBindings[0], + call, + options, + passedAuthMethod: objectProperty(options, "authMethod")?.value, + }); + } } - return candidates[0] ?? null; + const caller = unique(callers, "房子按钮调用点"); + const markerPresent = source.slice(route.fn.start, route.fn.end).includes(CURRENT_HOME_MARKER); + return { ...route, caller, markerPresent }; } function isApiKeyOverride(node, authMethod) { @@ -236,20 +233,6 @@ function isApiKeyOverride(node, authMethod) { literal(comparison.right) === "apikey"; } -function isLegacyCurrentHomeOverride(node, accountKey, currentLocation) { - if (node?.type !== "LogicalExpression" || node.operator !== "||") return false; - const override = node.right; - if (override?.type !== "LogicalExpression" || override.operator !== "&&") return false; - const account = override.left; - const pathname = override.right; - return account?.type === "BinaryExpression" && ["===", "=="].includes(account.operator) && - account.left?.type === "Identifier" && account.left.name === accountKey && - literal(account.right) === "auth:apikey" && - pathname?.type === "BinaryExpression" && ["!==", "!="].includes(pathname.operator) && - memberName(pathname.left) === "pathname" && memberRoot(pathname.left) === currentLocation && - literal(pathname.right) === "/"; -} - function patchSource(source) { if (!["authMethod", "accountKey", "productMode", "auth:", "chatgpt:"].every(value => source.includes(value))) { @@ -258,15 +241,18 @@ function patchSource(source) { try { const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); const tracker = findTracker(ast); - const currentHome = findCurrentHomeGuard(ast); - if (tracker == null || currentHome == null) { + const openHome = findOpenHomeRoute(ast, source); + if (tracker == null || openHome == null) { if (source.includes(MARKER) || source.includes(CURRENT_HOME_MARKER)) { throw new Error("补丁标记存在但首页导航结构未知"); } return { status: "not-applicable", source }; } const trackerPatched = isApiKeyOverride(tracker.gate, tracker.authMethod); - const currentHomePatched = currentHome.override != null; + const openHomePatched = openHome.markerPresent && + openHome.authMethod === "__codexAuthMethod" && + openHome.caller.passedAuthMethod?.type === "Identifier" && + openHome.caller.passedAuthMethod.name === openHome.caller.authMethod; if (trackerPatched) { const gateSource = source.slice(tracker.gate.start, tracker.gate.end); if (!gateSource.includes(MARKER)) throw new Error("API-key 放行逻辑存在但缺少本项目标记"); @@ -274,15 +260,12 @@ function patchSource(source) { tracker.gate.left?.type !== "Identifier" || tracker.gate.right?.type !== "Identifier") { throw new Error("导航模式与 ChatGPT capability 条件结构未知"); } - if (currentHomePatched) { - const overrideSource = source.slice(currentHome.override.start, currentHome.override.end); - if (!overrideSource.includes(CURRENT_HOME_MARKER)) { - throw new Error("API-key 当前首页逻辑存在但缺少本项目标记"); - } - } else if (currentHome.gate.type !== "Identifier") { - throw new Error("当前首页导航模式条件结构未知"); + const openHomePartiallyPatched = openHome.markerPresent || openHome.authMethod != null || + openHome.caller.passedAuthMethod != null; + if (!openHomePatched && openHomePartiallyPatched) { + throw new Error("房子按钮 API-key 保持逻辑不完整"); } - if (trackerPatched && currentHomePatched) return { status: "already-patched", source }; + if (trackerPatched && openHomePatched) return { status: "already-patched", source }; const edits = []; if (!trackerPatched) { @@ -293,11 +276,21 @@ function patchSource(source) { replacement: `(${originalGate}||${MARKER}${tracker.authMethod}===\`apikey\`)`, }); } - if (!currentHomePatched) { + if (!openHomePatched) { + edits.push({ + start: openHome.options.start + 1, + end: openHome.options.start + 1, + replacement: "authMethod:__codexAuthMethod,", + }); + edits.push({ + start: openHome.caller.options.start + 1, + end: openHome.caller.options.start + 1, + replacement: `authMethod:${openHome.caller.authMethod},`, + }); edits.push({ - start: currentHome.statement.start, - end: currentHome.statement.start, - replacement: `if(${CURRENT_HOME_MARKER}${currentHome.accountKey}===\`auth:apikey\`&&${currentHome.area}===\`home\`&&${currentHome.currentLocation}!=null&&(${currentHome.currentLocation}.pathname.startsWith(\`/local/\`)||${currentHome.currentLocation}.pathname.startsWith(\`/remote/\`)))return!0;`, + start: openHome.branch.start, + end: openHome.branch.start, + replacement: `if(${CURRENT_HOME_MARKER}__codexAuthMethod===\`apikey\`&&${openHome.currentLocation}!=null&&(${openHome.currentLocation}.pathname.startsWith(\`/local/\`)||${openHome.currentLocation}.pathname.startsWith(\`/remote/\`)))return;`, }); } let next = source; diff --git a/scripts/patch-api-key-home-navigation.test.js b/scripts/patch-api-key-home-navigation.test.js index a0441753..1fd2c248 100644 --- a/scripts/patch-api-key-home-navigation.test.js +++ b/scripts/patch-api-key-home-navigation.test.js @@ -19,6 +19,13 @@ function fixture() { "(c.state?.sidebarProductMode==null||c.state.sidebarProductMode===a))return!0;", "if(u==null||!s&&u.departedAt==null||Ati(e,u.location)!==r){i(`/`);return!0}", "return i(ym(u.location)),!0}", + "function wti(e,{codexLocalAccessStatus:t,currentMode:n,navigate:r,nextMode:i,openHome:a=!1,restoreNavigation:o=!0,startNewConversation:s}){", + "let c=e.get(wc);if(i===n&&!a)return;dei(e);let l=e.get(Pti,i),u=e.get(Ug),d=e.get(ye),", + "f=u?.pathname===`/library`||u?.pathname.startsWith(`/library/`);", + "if(u!=null&&!f&&e.set(Pti,n,{location:u,selectedProject:d}),SFe(e,i),a){r(`/`,{state:{sidebarProductMode:i}});return}", + "if(!o)return;if(l==null){s();return}r(l.location)}", + "function Pjo(){let i=store(),h=navigate(),a=start(),{accountId:O,authMethod:k}=mp(),", + "c=()=>{wti(i,{codexLocalAccessStatus:`allowed`,currentMode:`codex`,navigate:h,nextMode:`codex`,openHome:!0,startNewConversation:a})};return c}", ].join(""); } @@ -43,125 +50,80 @@ test("API-key 在 ChatGPT capability 关闭时仍写入与读取端一致的 acc assert.equal(patchSource(result.source).status, "already-patched"); }); -function restore(source, accountKey, { +function clickHome(source, authMethod, { currentPath = "/local/thread-1", - currentHash = "", - currentState = null, - newNavigation = false, - sanitizedHash = currentHash, - saved = { departedAt: null, location: { pathname: "/local/thread-1" } }, } = {}) { const navigations = []; - const current = currentPath == null ? null : { - hash: currentHash, - pathname: currentPath, - state: currentState, - }; + const current = currentPath == null ? null : { pathname: currentPath }; const store = { get(key) { - if (key === "wc") return newNavigation; + if (key === "wc") return false; if (key === "Ug") return current; - if (key === "lj") return "codex"; return null; }, + set() {}, }; - const run = Function("store", "navigate", "accountKey", "saved", "sanitizedHash", [ - "const wc=`wc`,Ug=`Ug`,lj=`lj`;", - "const bti=()=>saved;", - "const sti=()=>({hash:sanitizedHash});", - "const Ati=(_store,location)=>location.pathname===`/`||location.pathname.startsWith(`/local/`)||location.pathname.startsWith(`/remote/`)?`home`:null;", - "const ym=location=>location.pathname;", + const run = Function("activeStore", "recordNavigation", "authMethod", [ + "const wc=`wc`,Ug=`Ug`,Pti=`Pti`,ye=`ye`;", + "const store=()=>activeStore,navigate=()=>path=>recordNavigation(path),start=()=>()=>{};", + "const mp=()=>({accountId:null,authMethod});const dei=()=>{},SFe=()=>{};", source, - "return Sti(store,{accountKey,area:`home`,navigate,productMode:`codex`});", + "return Pjo()();", ].join("")); - return { - navigations, - value: run(store, path => navigations.push(path), accountKey, saved, sanitizedHash), - }; + run(store, path => navigations.push(path), authMethod); + return navigations; } -test("API-key 旧导航模式下点击首页保持当前会话", () => { +test("API-key 点击真实侧栏房子按钮保持当前本地会话", () => { const result = patchSource(fixture()); - const restored = restore(result.source, "auth:apikey"); assert.ok(result.source.includes(CURRENT_HOME_MARKER)); - assert.equal(restored.value, true); - assert.deepEqual(restored.navigations, []); + assert.match(result.source, /authMethod:__codexAuthMethod/); + assert.match(result.source, /authMethod:k/); + assert.deepEqual(clickHome(result.source, "apikey"), []); }); test("API-key 远程会话点击首页保持当前会话", () => { const result = patchSource(fixture()); - const restored = restore(result.source, "auth:apikey", { + const navigations = clickHome(result.source, "apikey", { currentPath: "/remote/task-1", }); - assert.equal(restored.value, true); - assert.deepEqual(restored.navigations, []); -}); - -test("API-key 会话短路不依赖 hash 和 sidebarProductMode", () => { - const result = patchSource(fixture()); - const restored = restore(result.source, "auth:apikey", { - currentHash: "#panel=diff", - currentState: { sidebarProductMode: "other" }, - newNavigation: true, - sanitizedHash: "", - }); - - assert.equal(restored.value, true); - assert.deepEqual(restored.navigations, []); + assert.deepEqual(navigations, []); }); test("API-key 根路径不短路,保留官方空数据落地页导航", () => { const result = patchSource(fixture()); - const restored = restore(result.source, "auth:apikey", { + const navigations = clickHome(result.source, "apikey", { currentPath: "/", - saved: null, }); - assert.equal(restored.value, true); - assert.deepEqual(restored.navigations, ["/"]); + assert.deepEqual(navigations, ["/"]); }); test("API-key 尚无当前路由时不访问空对象", () => { const result = patchSource(fixture()); - const restored = restore(result.source, "auth:apikey", { + const navigations = clickHome(result.source, "apikey", { currentPath: null, - saved: null, }); - assert.equal(restored.value, true); - assert.deepEqual(restored.navigations, ["/"]); + assert.deepEqual(navigations, ["/"]); }); -test("ChatGPT 旧导航模式不获得当前首页短路", () => { +test("ChatGPT 登录不获得 API-key 房子按钮短路", () => { const result = patchSource(fixture()); - const restored = restore(result.source, "chatgpt:account-1"); + const navigations = clickHome(result.source, "chatgpt"); - assert.equal(restored.value, true); - assert.deepEqual(restored.navigations, ["/"]); + assert.deepEqual(navigations, ["/"]); }); -test("API-key 从设置页仍恢复已经离开的首页会话", () => { +test("API-key 从设置页点击房子仍执行官方首页导航", () => { const result = patchSource(fixture()); - const restored = restore(result.source, "auth:apikey", { + const navigations = clickHome(result.source, "apikey", { currentPath: "/settings/appearance", - saved: { departedAt: Date.now(), location: { pathname: "/local/thread-1" } }, - }); - - assert.equal(restored.value, true); - assert.deepEqual(restored.navigations, ["/local/thread-1"]); -}); - -test("API-key 非会话页面不获得当前首页短路", () => { - const result = patchSource(fixture()); - const restored = restore(result.source, "auth:apikey", { - currentPath: "/projects/example", - saved: { departedAt: Date.now(), location: { pathname: "/local/thread-1" } }, }); - assert.equal(restored.value, true); - assert.deepEqual(restored.navigations, ["/local/thread-1"]); + assert.deepEqual(navigations, ["/"]); }); test("ChatGPT 登录继续遵守官方 capability 与账户条件", () => { @@ -193,7 +155,9 @@ test("未认证及其他认证方式不会因补丁越过 capability", () => { }); test("导航跟踪器不唯一时明确失败", () => { - const source = fixture() + fixture().replaceAll("Lhc", "Mhc").replaceAll("Sti", "Tti"); + const source = fixture() + fixture() + .replaceAll("Lhc", "Mhc").replaceAll("Sti", "Tti") + .replaceAll("wti", "xti").replaceAll("Pjo", "Qjo"); const result = patchSource(source); assert.equal(result.status, "unexpected-shape"); diff --git a/scripts/patch-archive-delete.js b/scripts/patch-archive-delete.js index 69569412..53700d2d 100644 --- a/scripts/patch-archive-delete.js +++ b/scripts/patch-archive-delete.js @@ -1,8 +1,9 @@ #!/usr/bin/env node /** - * patch-archive-delete.js — 为旧版归档会话列表补充删除能力。 + * patch-archive-delete.js — 补齐跨 Provider 归档列表与旧版删除能力。 * - * Two-layer patch: + * Three-layer patch: + * 0. archived thread queries: use [] to explicitly query all model providers * 1. app-main chunk: inject "delete-conversation" route into the message router * 2. data-controls chunk: inject a red "Delete" button next to "Unarchive" * @@ -13,8 +14,166 @@ * 26.803 起上游已提供单条、按项目及全部删除;检测到完整原生链路时不再注入。 */ const fs = require("fs"); +const path = require("path"); const acorn = require("acorn"); -const { locateBundles, relPath } = require("./patch-util"); +const { locateBundles, relPath, SRC_DIR } = require("./patch-util"); + +function walkArchive(node, visitor) { + if (!node || typeof node !== "object") return; + if (node.type) visitor(node); + for (const [key, child] of Object.entries(node)) { + if (key === "type" || key === "start" || key === "end") continue; + if (Array.isArray(child)) { + for (const item of child) { + if (item && typeof item === "object" && item.type) { + walkArchive(item, visitor); + } + } + } else if (child && typeof child === "object" && child.type) { + walkArchive(child, visitor); + } + } +} + +function archiveLiteral(node) { + if (node?.type === "Literal") return node.value; + if ( + node?.type === "TemplateLiteral" && + node.expressions.length === 0 && + node.quasis.length === 1 + ) { + return node.quasis[0].value.cooked; + } + return undefined; +} + +function archiveObjectProperty(node, name) { + if (node?.type !== "ObjectExpression") return null; + return node.properties.find((property) => { + if (property.type !== "Property" || property.kind !== "init") return false; + const key = property.computed + ? archiveLiteral(property.key) + : property.key.type === "Identifier" + ? property.key.name + : archiveLiteral(property.key); + return key === name; + }) ?? null; +} + +function archiveStaticBoolean(node) { + if (node?.type === "Literal" && typeof node.value === "boolean") { + return node.value; + } + if ( + node?.type === "UnaryExpression" && + node.operator === "!" && + node.argument?.type === "Literal" && + (node.argument.value === 0 || node.argument.value === 1) + ) { + return node.argument.value === 0; + } + return null; +} + +function analyzeArchivedListProviders(source) { + const ast = acorn.parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const edits = []; + let alreadyAllProviders = 0; + + walkArchive(ast, (node) => { + if (node.type !== "CallExpression" || node.callee.type !== "MemberExpression") { + return; + } + const method = node.callee.computed + ? archiveLiteral(node.callee.property) + : node.callee.property.name; + const options = method === "listAllThreads" + ? node.arguments[0] + : method === "sendRequest" && archiveLiteral(node.arguments[0]) === "thread/list" + ? node.arguments[1] + : null; + if (archiveStaticBoolean(archiveObjectProperty(options, "archived")?.value) !== true) { + return; + } + + const providers = archiveObjectProperty(options, "modelProviders")?.value; + if (providers?.type === "Literal" && providers.value === null) { + edits.push(providers); + } else if (providers?.type === "ArrayExpression" && providers.elements.length === 0) { + alreadyAllProviders++; + } + }); + + let code = source; + for (const edit of edits.sort((left, right) => right.start - left.start)) { + code = code.slice(0, edit.start) + "[]" + code.slice(edit.end); + } + return { code, edits: edits.length, alreadyAllProviders }; +} + +function patchArchivedListProviders(source) { + return analyzeArchivedListProviders(source).code; +} + +function locateArchivedProviderBundles(platform) { + const platforms = platform + ? [platform] + : ["mac-arm64", "mac-x64", "win"].filter((name) => + fs.existsSync(path.join(SRC_DIR, name)), + ); + const roots = platforms.length > 0 + ? platforms.map((name) => ({ + platform: name, + dir: path.join(SRC_DIR, name, "_asar", "webview", "assets"), + })) + : [{ platform: "legacy", dir: path.join(SRC_DIR, "webview", "assets") }]; + const bundles = []; + + for (const root of roots) { + if (!fs.existsSync(root.dir)) continue; + for (const name of fs.readdirSync(root.dir)) { + if (!name.endsWith(".js")) continue; + const filePath = path.join(root.dir, name); + const source = fs.readFileSync(filePath, "utf-8"); + if ( + source.includes("modelProviders") && + (source.includes("listAllThreads") || source.includes("thread/list")) + ) { + bundles.push({ platform: root.platform, path: filePath }); + } + } + } + return bundles.sort((left, right) => left.path.localeCompare(right.path)); +} + +function patchArchivedProviderQueries(bundles, isCheck) { + let patched = 0; + let already = 0; + for (const bundle of bundles) { + const source = fs.readFileSync(bundle.path, "utf-8"); + const result = analyzeArchivedListProviders(source); + if (result.edits > 0) { + console.log( + ` [${isCheck ? "?" : "ok"}] ${relPath(bundle.path)}: ` + + `${isCheck ? "would query" : "queries"} all providers for ` + + `${result.edits} archived list call(s)`, + ); + if (!isCheck) fs.writeFileSync(bundle.path, result.code, "utf-8"); + patched += result.edits; + } + if (result.alreadyAllProviders > 0) { + console.log( + ` [ok] ${relPath(bundle.path)}: ${result.alreadyAllProviders} archived list ` + + "call(s) already query all providers", + ); + already += result.alreadyAllProviders; + } + } + if (patched === 0 && already === 0) { + throw new Error("archived list provider query target not found"); + } + return { patched, already }; +} function hasNativeArchiveDelete(code) { const legacyMarkers = [ @@ -315,6 +474,12 @@ function main() { ["mac-arm64", "mac-x64", "win"].includes(a), ); + console.log(" [layer 0] archived lists: query all model providers"); + const providerResult = patchArchivedProviderQueries( + locateArchivedProviderBundles(platform), + isCheck, + ); + const dataControlsBundles = locateBundles({ dir: "assets", pattern: /^data-controls-.*\.js$/, @@ -347,10 +512,18 @@ function main() { ); console.log( - ` [done] native: ${nativeBundles.length}, routes: ${routePatched}, buttons: ${btnPatched}`, + ` [done] providers: ${providerResult.patched} patched/${providerResult.already} already, ` + + `native: ${nativeBundles.length}, routes: ${routePatched}, buttons: ${btnPatched}`, ); } if (require.main === module) main(); -module.exports = { hasNativeArchiveDelete, patchAppMain, patchDataControls }; +module.exports = { + analyzeArchivedListProviders, + hasNativeArchiveDelete, + patchAppMain, + patchArchivedListProviders, + patchArchivedProviderQueries, + patchDataControls, +}; diff --git a/scripts/patch-archive-delete.test.js b/scripts/patch-archive-delete.test.js new file mode 100644 index 00000000..db216910 --- /dev/null +++ b/scripts/patch-archive-delete.test.js @@ -0,0 +1,81 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { + analyzeArchivedListProviders, + patchArchivedListProviders, +} = require("./patch-archive-delete"); + +test("归档分页会返回其他 Provider 的历史会话", async () => { + const source = "async function list(client,cursor){return client.sendRequest(`thread/list`,{archived:!0,cursor,limit:100,modelProviders:null,sourceKinds:[`vscode`],useStateDbOnly:!0})}"; + const threads = [ + { id: "old", provider: "local" }, + { id: "new", provider: "custom" }, + ]; + const calls = []; + const client = { + async sendRequest(method, options) { + calls.push({ method, options }); + const providers = options.modelProviders ?? ["custom"]; + return { + data: threads.filter( + (thread) => providers.length === 0 || providers.includes(thread.provider), + ), + }; + }, + }; + + const original = new Function(`${source};return list`)(); + assert.deepEqual( + (await original(client, "next")).data.map((thread) => thread.id), + ["new"], + ); + + const patchedSource = patchArchivedListProviders(source); + const patched = new Function(`${patchedSource};return list`)(); + assert.deepEqual( + (await patched(client, "next")).data.map((thread) => thread.id), + ["old", "new"], + ); + assert.deepEqual(calls[1], { + method: "thread/list", + options: { + archived: true, + cursor: "next", + limit: 100, + modelProviders: [], + sourceKinds: ["vscode"], + useStateDbOnly: true, + }, + }); + assert.equal(patchArchivedListProviders(patchedSource), patchedSource); +}); + +test("归档 Provider 修复不改变活动列表、显式过滤和其他调用", () => { + const unchanged = [ + 'client.sendRequest("thread/list",{archived:false,modelProviders:null});', + 'client.sendRequest("thread/list",{modelProviders:null});', + 'client.sendRequest("thread/list",{archived:true,modelProviders:["custom"]});', + 'client.sendRequest("thread/delete",{archived:true,modelProviders:null});', + 'client.unrelated({archived:true,modelProviders:null});', + 'const text="modelProviders:null,archived:!0";', + ].join(""); + const queries = [ + "client.listAllThreads({modelProviders:null,archived:!0});", + 'client["sendRequest"]("thread/list",{"archived":true,"modelProviders":null});', + ].join(""); + const expected = unchanged + [ + "client.listAllThreads({modelProviders:[],archived:!0});", + 'client["sendRequest"]("thread/list",{"archived":true,"modelProviders":[]});', + ].join(""); + + const result = analyzeArchivedListProviders(unchanged + queries); + assert.equal(result.code, expected); + assert.equal(result.edits, 2); + assert.equal(result.alreadyAllProviders, 0); + + const repeated = analyzeArchivedListProviders(result.code); + assert.equal(repeated.code, expected); + assert.equal(repeated.edits, 0); + assert.equal(repeated.alreadyAllProviders, 2); +}); diff --git a/scripts/patch-browser-auth.js b/scripts/patch-browser-auth.js index 4f99614c..03208aa7 100644 --- a/scripts/patch-browser-auth.js +++ b/scripts/patch-browser-auth.js @@ -11,6 +11,8 @@ * 将 request-header 能力降级为关闭,恢复旧版可继续建立本地浏览器通道的行为。 * 26.1007 将读取改为调用通用 feature-gate 函数;仅包装 request-header * 回调,不改变其他 feature gate 的身份要求或超时逻辑。 + * 26.1013 改为从本地 requirements 读取托管请求头,不再经过 ChatGPT + * 身份 gate;检测到这条原生链路时只验证并保持上游实现。 * 不会把 API key 当作 ChatGPT token 发送到 chatgpt.com。 */ const fs = require("fs"); @@ -22,6 +24,19 @@ const IDENTITY_ERROR = "Browser request-header policy requires caller identity."; const FEATURE_GATE_IDENTITY_ERROR = "Browser feature gates require caller identity."; const REQUEST_HEADER_GATE = "codex_browser_use_agent_request_header"; +const MANAGED_REQUEST_HEADER_MARKERS = [ + "getExtensionRequestHeaders", + "readRequirements", + "requestHeadersVersion", + "request_headers", +]; + +function hasNativeManagedRequestHeaders(source) { + return ( + !source.includes(REQUEST_HEADER_GATE) && + MANAGED_REQUEST_HEADER_MARKERS.every((marker) => source.includes(marker)) + ); +} function walk(node, visitor) { if (!node || typeof node !== "object") return; @@ -216,10 +231,7 @@ function locateTargets(platform) { ]; for (const root of roots) { for (const filePath of findBrowserServices(root)) { - const source = fs.readFileSync(filePath, "utf8"); - if (source.includes(REQUEST_HEADER_GATE)) { - targets.push({ platform: name, path: filePath }); - } + targets.push({ platform: name, path: filePath }); } } } @@ -236,16 +248,24 @@ function main() { const targets = locateTargets(platform); if (targets.length === 0) { - console.log("[ok] No browser request-header auth targets found"); - return; + throw new Error("browser-service.mjs not found in external plugin resources"); } let patched = 0; let alreadyPatched = 0; + let native = 0; for (const target of targets) { const source = fs.readFileSync(target.path, "utf8"); - const result = patchSource(source); const label = `[${target.platform}] ${relPath(target.path)}`; + if (hasNativeManagedRequestHeaders(source)) { + console.log( + `[ok] ${label}: upstream reads managed request headers without ChatGPT identity`, + ); + native++; + continue; + } + + const result = patchSource(source); if (result.status === "patched") { if (check) { @@ -267,7 +287,8 @@ function main() { } console.log( - `[ok] Browser auth targets: ${targets.length}, patched: ${patched}, already: ${alreadyPatched}`, + `[ok] Browser auth targets: ${targets.length}, native: ${native}, ` + + `patched: ${patched}, already: ${alreadyPatched}`, ); } @@ -275,8 +296,10 @@ if (require.main === module) main(); module.exports = { IDENTITY_ERROR, + MANAGED_REQUEST_HEADER_MARKERS, REQUEST_HEADER_GATE, findRequestHeaderAuthPatches, + hasNativeManagedRequestHeaders, locateTargets, patchSource, }; diff --git a/scripts/patch-browser-auth.test.js b/scripts/patch-browser-auth.test.js index da378cca..5c695578 100644 --- a/scripts/patch-browser-auth.test.js +++ b/scripts/patch-browser-auth.test.js @@ -1,7 +1,10 @@ const test = require("node:test"); const assert = require("node:assert/strict"); -const { patchSource } = require("./patch-browser-auth"); +const { + hasNativeManagedRequestHeaders, + patchSource, +} = require("./patch-browser-auth"); function createService(identityPromise, gateValue = true) { return [ @@ -99,3 +102,23 @@ test("未知上游结构会明确失败而不是静默漏补", () => { assert.equal(patchSource(source).status, "unexpected-shape"); }); + +test("26.1013 原生托管请求头不再依赖 ChatGPT 身份 gate", () => { + const source = [ + "class Preferences{async getExtensionRequestHeaders(){", + "return(await this.config.readRequirements())?.requirements?.browserUse?.extension?.requestHeaders", + "}}", + "class BrowserTransport{async sendSessionRequest(){", + "const headers=await this.preferences.getExtensionRequestHeaders();", + "if(this.clientInfo.requestHeadersVersion===1)this.params.request_headers=headers;", + "}}", + 'async function readBrowserFeatureGate(){throw new Error("Browser feature gates require caller identity.")}', + ].join(""); + + assert.equal(hasNativeManagedRequestHeaders(source), true); + assert.equal(patchSource(source).status, "not-applicable"); + assert.equal( + hasNativeManagedRequestHeaders(source.replace("readRequirements", "readAccountIdentity")), + false, + ); +}); diff --git a/scripts/patch-crash-forensics.js b/scripts/patch-crash-forensics.js index 4df4ec66..9d468d94 100644 --- a/scripts/patch-crash-forensics.js +++ b/scripts/patch-crash-forensics.js @@ -31,8 +31,9 @@ const { SRC_DIR, relPath } = require("./patch-util"); const LEGACY_MARKERS = [ "__CODEX_CRASH_FORENSICS__", "__CODEX_CRASH_FORENSICS_V2__", + "__CODEX_CRASH_FORENSICS_V3__", ]; -const MARKER = "__CODEX_CRASH_FORENSICS_V3__"; +const MARKER = "__CODEX_CRASH_FORENSICS_V4__"; // ────────────────────────────────────────────── // 注入体:以真实函数形式书写,保证语法正确。 @@ -61,9 +62,31 @@ function __codexForensics() { "forensics-" + new Date().toISOString().slice(0, 10) + ".log", ); var chromeLog = path.join(earlyDir, "chrome-debug.log"); + var MAX_LOG_BYTES = 16 * 1024 * 1024; + var MAX_LOG_FILES = 7; + + // 取证是辅助数据:只保留最近 7 天,每个日志最多 16MB。 + try { + var oldLogs = fs + .readdirSync(earlyDir) + .filter(function (name) { + return /^forensics-\d{4}-\d{2}-\d{2}\.log$/.test(name); + }) + .sort() + .reverse(); + for (var oldIndex = MAX_LOG_FILES; oldIndex < oldLogs.length; oldIndex++) { + try { + fs.unlinkSync(path.join(earlyDir, oldLogs[oldIndex])); + } catch (e) {} + } + if (fs.existsSync(chromeLog) && fs.statSync(chromeLog).size >= MAX_LOG_BYTES) { + fs.writeFileSync(chromeLog, ""); + } + } catch (e) {} function write(line) { try { + if (fs.existsSync(logFile) && fs.statSync(logFile).size >= MAX_LOG_BYTES) return; fs.appendFileSync( logFile, "[" + new Date().toISOString() + "] " + line + "\n", @@ -462,13 +485,11 @@ function __codexForensics() { } catch (err) { // 取证代码自身绝不能拖垮应用 try { - require("node:fs").appendFileSync( - require("node:path").join( - require("node:os").tmpdir(), - "codex-forensics-fatal.log", - ), - String((err && err.stack) || err) + "\n", - ); + var fatalFs = require("node:fs"); + var fatalFile = require("node:path").join(require("node:os").tmpdir(), "codex-forensics-fatal.log"); + if (!fatalFs.existsSync(fatalFile) || fatalFs.statSync(fatalFile).size < 1024 * 1024) { + fatalFs.appendFileSync(fatalFile, String((err && err.stack) || err) + "\n"); + } } catch (e) {} } } diff --git a/scripts/patch-fast-mode.js b/scripts/patch-fast-mode.js index af604b23..42af6d6f 100644 --- a/scripts/patch-fast-mode.js +++ b/scripts/patch-fast-mode.js @@ -1,280 +1,294 @@ #!/usr/bin/env node /** - * 构建后补丁:为 API key 登录启用 Fast mode(速度选择器)。 + * 为 API-key / 自定义 Provider 接入新版 serviceTierAccess。 * - * 上游会用 authMethod 或保存认证结果的局部变量限制速度选择器及 - * service_tier 读取。补丁覆盖以下两类判断,并且只额外放行 apikey: - * X !== "chatgpt" -> X !== "chatgpt" && X !== "apikey" - * X === "chatgpt" -> X === "chatgpt" || X === "apikey" - * - * 目标:同时包含 "fast_mode" 与 "chatgpt" 的渲染进程代码块。 + * 官方账户会从 ChatGPT requirements 读取 Fast / Ultrafast 权限;API-key + * 没有这份账户数据,因此 UI 和请求层都会得到 null。这里仅为 apikey + * 跳过账户查询,模型是否显示具体档位仍由官方 model/list 返回的 + * serviceTierOptions 决定。 */ const fs = require("fs"); const path = require("path"); const { parse } = require("acorn"); -const { locateBundles, relPath, SRC_DIR } = require("./patch-util"); +const { relPath, SRC_DIR } = require("./patch-util"); + +const PLATFORMS = ["mac-arm64", "mac-x64", "win"]; +const SETTINGS_AUTH_MARKER = "/* CodexRebuildServiceTierApiKeyAuth */"; +const SETTINGS_ACCESS_MARKER = "/* CodexRebuildServiceTierApiKeyAccess */"; +const REQUEST_ACCESS_MARKER = "/* CodexRebuildServiceTierApiKeyRequest */"; -function walk(node, visitor, parent = null) { - if (!node || typeof node !== "object") return; - if (node.type) visitor(node, parent); - for (const key of Object.keys(node)) { - if (key === "type" || key === "start" || key === "end") continue; - const child = node[key]; - if (Array.isArray(child)) { - for (const item of child) { - if (item && typeof item === "object" && item.type) - walk(item, visitor, node); +function isFunctionNode(node) { + return node?.type === "FunctionDeclaration" || + node?.type === "FunctionExpression" || + node?.type === "ArrowFunctionExpression"; +} + +function nodes(root, predicate, { skipNestedFunctions = false } = {}) { + const found = []; + function visit(node, parent = null) { + if (!node || typeof node !== "object") return; + if (node !== root && skipNestedFunctions && isFunctionNode(node)) return; + if (node.type && predicate(node, parent)) found.push(node); + for (const [key, child] of Object.entries(node)) { + if (["type", "start", "end"].includes(key)) continue; + if (Array.isArray(child)) { + for (const item of child) visit(item, node); + } else { + visit(child, node); } - } else if (child && typeof child === "object" && child.type) { - walk(child, visitor, node); } } + visit(root); + return found; } -function isChatGptLiteral(node) { - return ( - (node.type === "Literal" && node.value === "chatgpt") || - (node.type === "TemplateLiteral" && - node.expressions.length === 0 && - node.quasis.length === 1 && - node.quasis[0].value.cooked === "chatgpt") - ); +function literal(node) { + if (node?.type === "Literal") return node.value; + if (node?.type === "TemplateLiteral" && node.expressions.length === 0 && node.quasis.length === 1) { + return node.quasis[0].value.cooked; + } + return undefined; } -function expressionSourceForApiKeySide(binary, source) { - if (isChatGptLiteral(binary.right)) return source.slice(binary.left.start, binary.left.end); - if (isChatGptLiteral(binary.left)) return source.slice(binary.right.start, binary.right.end); - return null; +function flattenLogical(node, operator) { + if (node?.type !== "LogicalExpression" || node.operator !== operator) return [node]; + return [...flattenLogical(node.left, operator), ...flattenLogical(node.right, operator)]; } -function isAlreadyExpandedToApiKey(parent, source) { - if (!parent || parent.type !== "LogicalExpression") return false; - return source.slice(parent.start, parent.end).includes("apikey"); +function comparisonOperand(node, source, operator, value) { + if (node?.type !== "BinaryExpression" || node.operator !== operator) return null; + if (literal(node.right) === value) return source.slice(node.left.start, node.left.end); + if (literal(node.left) === value) return source.slice(node.right.start, node.right.end); + return null; } -function collectPatches(ast, source) { - const patches = []; - - walk(ast, (node) => { - // 只在同时包含认证判断和 fast_mode 的函数内改写,避免误伤普通字符串比较。 - const isFn = - node.type === "FunctionDeclaration" || - node.type === "FunctionExpression" || - node.type === "ArrowFunctionExpression"; - if (!isFn) return; - - const fnSrc = source.slice(node.start, node.end); - if (!fnSrc.includes("fast_mode") || !fnSrc.includes("chatgpt")) return; - - walk(node, (child, parent) => { - if (child.type !== "BinaryExpression") return; - - const childSrc = source.slice(child.start, child.end); - - // 旧版和新版都可能先把 authMethod 保存到局部变量再进行排除判断。 - if (child.operator === "!==") { - const apiKeySide = expressionSourceForApiKeySide(child, source); - if (apiKeySide == null) return; - if (isAlreadyExpandedToApiKey(parent, source)) return; - - // 同一函数可能被外层函数再次遍历,按偏移去重。 - if (patches.some((p) => p.start === child.start)) return; +function exactAuthPair(node, source, logicalOperator, comparisonOperator) { + if (node?.type !== "LogicalExpression" || node.operator !== logicalOperator) return null; + const terms = flattenLogical(node, logicalOperator); + if (terms.length !== 2) return null; + const chatGpt = terms.map((term) => + comparisonOperand(term, source, comparisonOperator, "chatgpt")).find(Boolean); + const token = terms.map((term) => + comparisonOperand(term, source, comparisonOperator, "personalAccessToken")).find(Boolean); + return chatGpt != null && chatGpt === token ? chatGpt : null; +} - patches.push({ - id: "fast_mode_auth_gate", - start: child.start, - end: child.end, - replacement: `${childSrc}&&${apiKeySide}!==\`apikey\``, - original: childSrc, - }); - return; - } +function count(source, value) { + return source.split(value).length - 1; +} - // 肯定判断同样只额外允许 API key 登录。 - if (child.operator === "===") { - const apiKeySide = expressionSourceForApiKeySide(child, source); - if (apiKeySide == null) return; - if (isAlreadyExpandedToApiKey(parent, source)) return; +function returnsNull(statement) { + return statement?.type === "ReturnStatement" && literal(statement.argument) === null; +} - // 同一函数可能被外层函数再次遍历,按偏移去重。 - if (patches.some((p) => p.start === child.start)) return; +function findSettingsTarget(ast, source) { + const candidates = []; + for (const fn of nodes(ast, isFunctionNode)) { + const fnSource = source.slice(fn.start, fn.end); + if (!["serviceTierAccess", "isLoading", "chatgpt", "personalAccessToken", "authMethod"] + .every((value) => fnSource.includes(value))) continue; - patches.push({ - id: "fast_mode_api_auth_gate", - start: child.start, - end: child.end, - replacement: `${childSrc}||${apiKeySide}===\`apikey\``, - original: childSrc, - }); - } + const declarations = nodes(fn, (node) => node.type === "VariableDeclarator", { + skipNestedFunctions: true, }); - }); - - return patches; + const authDeclarations = declarations.filter((node) => + node.id?.type === "Identifier" && + exactAuthPair(node.init, source, "||", "===") != null); + if (authDeclarations.length !== 1) continue; + const authDeclaration = authDeclarations[0]; + const gate = authDeclaration.id.name; + const authExpression = exactAuthPair(authDeclaration.init, source, "||", "==="); + + const pendingTerms = nodes(fn, (node) => + node.type === "LogicalExpression" && node.operator === "&&" && + node.left?.type === "Identifier" && node.left.name === gate && + node.right?.type === "Identifier", { skipNestedFunctions: true }); + const accessConditions = nodes(fn, (node) => { + if (node.type !== "ConditionalExpression" || literal(node.alternate) !== null || + node.consequent?.type !== "CallExpression") return false; + const identifiers = nodes(node.test, (item) => item.type === "Identifier") + .map((item) => item.name); + return identifiers.includes(gate) && source.slice(node.test.start, node.test.end).includes("!=null"); + }, { skipNestedFunctions: true }); + if (pendingTerms.length !== 1 || accessConditions.length !== 1) continue; + candidates.push({ + authDeclaration, + authExpression, + gate, + pending: pendingTerms[0], + access: accessConditions[0], + }); + } + if (candidates.length !== 1) { + throw new Error(`serviceTierAccess 设置门槛数量异常(${candidates.length})`); + } + return candidates[0]; } -function hasPatchedFastModeGate(ast, source) { - let found = false; - walk(ast, (node) => { - if (found) return; - const isFn = - node.type === "FunctionDeclaration" || - node.type === "FunctionExpression" || - node.type === "ArrowFunctionExpression"; - if (!isFn) return; - - const fnSource = source.slice(node.start, node.end); - if (!fnSource.includes("fast_mode") || !fnSource.includes("chatgpt")) return; - walk(node, (child, parent) => { - if ( - child.type === "BinaryExpression" && - expressionSourceForApiKeySide(child, source) != null && - isAlreadyExpandedToApiKey(parent, source) - ) { - found = true; - } +function findRequestTarget(ast, source) { + const declarations = new Map(nodes(ast, (node) => node.type === "FunctionDeclaration") + .filter((node) => node.id?.name) + .map((node) => [node.id.name, node])); + const callers = nodes(ast, (node) => isFunctionNode(node) && + source.slice(node.start, node.end).includes("Failed to read service tier for request")); + if (callers.length !== 1) { + throw new Error(`service tier 请求读取器数量异常(${callers.length})`); + } + const awaitedNames = nodes(callers[0], (node) => + node.type === "AwaitExpression" && + node.argument?.type === "CallExpression" && + node.argument.callee?.type === "Identifier", { skipNestedFunctions: true }) + .map((node) => node.argument.callee.name); + const candidates = []; + for (const name of awaitedNames) { + const fn = declarations.get(name); + if (!fn?.async) continue; + const guards = nodes(fn, (node) => + node.type === "IfStatement" && + returnsNull(node.consequent) && + exactAuthPair(node.test, source, "&&", "!==") != null, + { skipNestedFunctions: true }); + if (guards.length !== 1) continue; + candidates.push({ + authExpression: exactAuthPair(guards[0].test, source, "&&", "!=="), + guard: guards[0], }); - }); - return found; + } + if (candidates.length !== 1) { + throw new Error(`serviceTierAccess 请求门槛数量异常(${candidates.length})`); + } + return candidates[0]; } -function patchSource(source) { - if (!source.includes("fast_mode") || !source.includes("chatgpt")) { - return { status: "not-applicable", source, patches: [] }; +function validatePatchedSource(source) { + for (const marker of [SETTINGS_AUTH_MARKER, SETTINGS_ACCESS_MARKER, REQUEST_ACCESS_MARKER]) { + if (count(source, marker) !== 1) throw new Error(`${marker} 数量异常`); } - - let ast; - try { - ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); - } catch (error) { - return { status: "parse-error", source, error }; + const escapedMarker = SETTINGS_AUTH_MARKER.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + if (!new RegExp(`===\`apikey\`\\?${escapedMarker}\`apikey\`:`).test(source)) { + throw new Error("API-key serviceTierAccess 认证标记结构异常"); } - - const patches = collectPatches(ast, source).sort((a, b) => b.start - a.start); - if (patches.length === 0) { - return { - status: hasPatchedFastModeGate(ast, source) - ? "already-patched" - : "not-applicable", - source, - patches: [], - }; + if (!source.includes(`{fast:!0,ultrafast:!0}${SETTINGS_ACCESS_MARKER}`) || + !source.includes(`{fast:!0,ultrafast:!0}${REQUEST_ACCESS_MARKER}`)) { + throw new Error("API-key Fast/Ultrafast 权限标记结构异常"); } + parse(source, { ecmaVersion: "latest", sourceType: "module" }); +} - let code = source; - for (const patch of patches) { - code = code.slice(0, patch.start) + patch.replacement + code.slice(patch.end); +function patchSource(source) { + const markerCount = [SETTINGS_AUTH_MARKER, SETTINGS_ACCESS_MARKER, REQUEST_ACCESS_MARKER] + .reduce((total, marker) => total + count(source, marker), 0); + if (markerCount > 0) { + try { + validatePatchedSource(source); + return { status: "already-patched", source, patches: [] }; + } catch (error) { + return { status: "unexpected-shape", source, patches: [], reason: error.message }; + } + } + if (!["serviceTierAccess", "personalAccessToken", "Failed to read service tier for request"] + .every((value) => source.includes(value))) { + return { status: "not-applicable", source, patches: [] }; } - // 写回前重新解析,避免生成损坏的压缩代码。 try { - parse(code, { ecmaVersion: "latest", sourceType: "module" }); + const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const settings = findSettingsTarget(ast, source); + const request = findRequestTarget(ast, source); + const originalAuth = source.slice(settings.authDeclaration.init.start, settings.authDeclaration.init.end); + const originalPending = source.slice(settings.pending.start, settings.pending.end); + const originalAccess = source.slice(settings.access.start, settings.access.end); + const edits = [ + { + id: "service_tier_settings_auth", + start: settings.authDeclaration.init.start, + end: settings.authDeclaration.init.end, + replacement: `${settings.authExpression}===\`apikey\`?${SETTINGS_AUTH_MARKER}\`apikey\`:(${originalAuth})`, + }, + { + id: "service_tier_settings_pending", + start: settings.pending.start, + end: settings.pending.end, + replacement: `${settings.gate}!==\`apikey\`&&(${originalPending})`, + }, + { + id: "service_tier_settings_access", + start: settings.access.start, + end: settings.access.end, + replacement: `${settings.gate}===\`apikey\`?{fast:!0,ultrafast:!0}${SETTINGS_ACCESS_MARKER}:(${originalAccess})`, + }, + { + id: "service_tier_request_access", + start: request.guard.start, + end: request.guard.start, + replacement: `if(${request.authExpression}===\`apikey\`)return{fast:!0,ultrafast:!0}${REQUEST_ACCESS_MARKER};`, + }, + ].sort((a, b) => b.start - a.start); + let next = source; + for (const edit of edits) { + next = next.slice(0, edit.start) + edit.replacement + next.slice(edit.end); + } + validatePatchedSource(next); + return { status: "patched", source: next, patches: edits }; } catch (error) { - return { status: "invalid-output", source, patches, error }; + return { status: "unexpected-shape", source, patches: [], reason: error.message }; } +} - return { status: "patched", source: code, patches }; +function targetDirectories(platform) { + const requested = platform ? [platform] : PLATFORMS; + return requested.map((item) => ({ + platform: item, + path: path.join(SRC_DIR, item, "_asar", "webview", "assets"), + })).filter((item) => fs.existsSync(item.path)); } function main() { const args = process.argv.slice(2); - const isCheck = args.includes("--check"); - const platform = args.find((a) => - ["mac-arm64", "mac-x64", "win"].includes(a), - ); - - const platforms = platform - ? [platform] - : ["mac-arm64", "mac-x64", "win"].filter((p) => - fs.existsSync(path.join(SRC_DIR, p, "_asar", "webview", "assets")), - ); - - const targets = []; - for (const plat of platforms) { - const assetsDir = path.join(SRC_DIR, plat, "_asar", "webview", "assets"); - if (!fs.existsSync(assetsDir)) continue; - for (const f of fs.readdirSync(assetsDir)) { - if (!f.endsWith(".js")) continue; - const fp = path.join(assetsDir, f); - const src = fs.readFileSync(fp, "utf-8"); - if (src.includes("chatgpt") && src.includes("fast_mode")) { - targets.push({ platform: plat, path: fp }); - } - } - } - - if (targets.length === 0) { - console.log(" [skip] No chunk contains fast_mode gate logic"); - return; - } - - let totalPatched = 0; - let totalFound = 0; + const platform = args.find((arg) => PLATFORMS.includes(arg)); + const check = args.includes("--check"); + const directories = targetDirectories(platform); let failed = 0; - const relevantPlatforms = new Set(); - - for (const bundle of targets) { - const source = fs.readFileSync(bundle.path, "utf-8"); - - const t0 = Date.now(); - const result = patchSource(source); - if (result.status === "parse-error") { - console.log(` [x] ${relPath(bundle.path)}: parse failed`); - failed++; - continue; - } - if (result.status === "already-patched") { - relevantPlatforms.add(bundle.platform); - continue; - } - if (result.status === "invalid-output") { - console.log(` [x] ${relPath(bundle.path)}: patched output is invalid`); - failed++; - continue; - } - - const patches = result.patches; - - if (patches.length === 0) continue; - relevantPlatforms.add(bundle.platform); - totalFound += patches.length; - - console.log( - ` [${bundle.platform}] ${relPath(bundle.path)} (parse ${Date.now() - t0}ms)`, - ); - - if (isCheck) { - for (const p of patches) { - console.log(` [?] offset ${p.start}: ${p.original} -> ${p.replacement}`); + let patched = 0; + for (const directory of directories) { + try { + const results = fs.readdirSync(directory.path).filter((name) => name.endsWith(".js")) + .map((name) => ({ name, path: path.join(directory.path, name) })) + .map((file) => ({ ...file, source: fs.readFileSync(file.path, "utf8") })) + .filter((file) => file.source.includes("serviceTierAccess") || + file.source.includes(REQUEST_ACCESS_MARKER)) + .map((file) => ({ file, result: patchSource(file.source) })) + .filter((item) => item.result.status !== "not-applicable"); + if (results.length !== 1) throw new Error(`Fast/Ultrafast Bundle 数量异常(${results.length})`); + const target = results[0]; + if (target.result.status === "unexpected-shape") throw new Error(target.result.reason); + console.log(` [${directory.platform}] ${relPath(target.file.path)}`); + if (target.result.status === "already-patched") { + console.log(" [ok] API-key Fast/Ultrafast serviceTierAccess 已接入"); + } else if (check) { + console.log(" [ok] API-key serviceTierAccess 设置与请求门槛已核对;dry-run 未写文件"); + } else { + fs.writeFileSync(target.file.path, target.result.source, "utf8"); + patched++; + console.log(" [ok] API-key 跳过账户权限查询;显示档位仍由模型 serviceTierOptions 决定"); } - continue; - } - - for (const p of patches) { - console.log(` * ${p.original} -> ${p.replacement}`); - } - - fs.writeFileSync(bundle.path, result.source, "utf-8"); - totalPatched += patches.length; - } - - if (totalPatched > 0) { - console.log(` [ok] ${totalPatched} auth gate(s) removed`); - } else if (isCheck && totalFound > 0) { - console.log(` [check] ${totalFound} auth gate(s) would be patched`); - } else { - console.log(" [ok] fast_mode auth gates already patched or absent"); - } - - for (const currentPlatform of platforms) { - if (!relevantPlatforms.has(currentPlatform)) { - console.log(` [x] [${currentPlatform}] no recognized fast_mode auth gate`); + } catch (error) { + console.error(` [x] ${directory.platform}: ${error.message}`); failed++; } } - if (failed > 0) process.exitCode = 1; + if (!directories.length) { + console.error(" [x] 缺少目标平台界面资源"); + failed++; + } + if (failed) process.exitCode = 1; + else console.log(` [ok] ${patched} platform bundle(s) patched`); } if (require.main === module) main(); - -module.exports = { collectPatches, patchSource }; +module.exports = { + REQUEST_ACCESS_MARKER, + SETTINGS_ACCESS_MARKER, + SETTINGS_AUTH_MARKER, + patchSource, +}; diff --git a/scripts/patch-fast-mode.test.js b/scripts/patch-fast-mode.test.js index 9cb481f5..03992ca7 100644 --- a/scripts/patch-fast-mode.test.js +++ b/scripts/patch-fast-mode.test.js @@ -1,43 +1,112 @@ const test = require("node:test"); const assert = require("node:assert/strict"); -const { patchSource } = require("./patch-fast-mode"); - -test("局部变量形式的排除判断只额外放行 apikey", () => { - const source = [ - `async function fastModeEnabled(){`, - `let n=await getAuthMethod();`, - `if(n!==\`chatgpt\`)return!1;`, - `return requirements.fast_mode!==!1`, - `}`, +const { + REQUEST_ACCESS_MARKER, + SETTINGS_ACCESS_MARKER, + SETTINGS_AUTH_MARKER, + patchSource, +} = require("./patch-fast-mode"); + +function fixture() { + return [ + "function mapRequirements(value){return value.access}", + "function useTierAccess(auth,result,pending){", + "let accountAuth=auth?.authMethod===`chatgpt`||auth?.authMethod===`personalAccessToken`,", + "method=auth?.authMethod??null,loading=!!auth?.isLoading||accountAuth&&pending,access;", + "access=accountAuth&&!loading&&result!=null?mapRequirements(result):null;", + "return{serviceTierAccess:access,isLoading:loading,method}}", + "async function readTierAccess(context,host){let auth=await context.getAuth(host);", + "if(auth!==`chatgpt`&&auth!==`personalAccessToken`)return null;", + "let requirements=await context.getRequirements(host);return mapRequirements(requirements)}", + "async function readTierForRequest(context,host){try{let access=await readTierAccess(context,host);", + "return access}catch(error){console.error(`Failed to read service tier for request`,error);return null}}", ].join(""); +} - const result = patchSource(source); +function load(source) { + return Function(`${source};return {useTierAccess,readTierForRequest}`)(); +} - assert.equal(result.status, "patched"); - assert.match(result.source, /n!==`chatgpt`&&n!==`apikey`/); - assert.equal(patchSource(result.source).status, "already-patched"); -}); +test("API-key 设置和请求绕过账户 requirements,同时保持模型档位门槛", async () => { + const first = patchSource(fixture()); -test("肯定判断同时允许 chatgpt 与 apikey", () => { - const source = - "function canUseFastMode(auth){return auth.authMethod===`chatgpt`&&requirements.fast_mode!==!1}"; + assert.equal(first.status, "patched"); + assert.ok(first.source.includes(SETTINGS_AUTH_MARKER)); + assert.ok(first.source.includes(SETTINGS_ACCESS_MARKER)); + assert.ok(first.source.includes(REQUEST_ACCESS_MARKER)); + assert.equal(patchSource(first.source).status, "already-patched"); - const result = patchSource(source); + const runtime = load(first.source); + assert.deepEqual(runtime.useTierAccess({ authMethod: "apikey" }, null, true), { + serviceTierAccess: { fast: true, ultrafast: true }, + isLoading: false, + method: "apikey", + }); + assert.deepEqual(runtime.useTierAccess({ authMethod: "chatgpt" }, { + access: { fast: false, ultrafast: true }, + }, false).serviceTierAccess, { fast: false, ultrafast: true }); + assert.equal(runtime.useTierAccess({ authMethod: "copilot" }, null, false).serviceTierAccess, null); - assert.equal(result.status, "patched"); - assert.match( - result.source, - /auth\.authMethod===`chatgpt`\|\|auth\.authMethod===`apikey`/, - ); - assert.equal(patchSource(result.source).status, "already-patched"); + let accountRequests = 0; + const context = { + async getAuth() { return "apikey"; }, + async getRequirements() { accountRequests++; return { access: { fast: false } }; }, + }; + assert.deepEqual(await runtime.readTierForRequest(context, "local"), { + fast: true, + ultrafast: true, + }); + assert.equal(accountRequests, 0); + + const access = runtime.useTierAccess({ authMethod: "apikey" }, null, false).serviceTierAccess; + const availableOptions = [ + { value: null }, + { value: "fast" }, + ].filter((option) => option.value == null || access[option.value]); + assert.deepEqual(availableOptions.map((option) => option.value), [null, "fast"]); + assert.deepEqual([{ value: null }].map((option) => option.value), [null], + "补丁不为没有 serviceTierOptions 的模型创造 Fast 档位"); }); -test("fast_mode 函数之外的认证判断保持不变", () => { - const source = "function unrelated(n){return n!==`chatgpt`}"; +test("ChatGPT 与 personalAccessToken 继续读取官方账户权限", async () => { + const runtime = load(patchSource(fixture()).source); + for (const authMethod of ["chatgpt", "personalAccessToken"]) { + let accountRequests = 0; + const context = { + async getAuth() { return authMethod; }, + async getRequirements() { + accountRequests++; + return { access: { fast: false, ultrafast: false } }; + }, + }; + assert.deepEqual(await runtime.readTierForRequest(context, "local"), { + fast: false, + ultrafast: false, + }); + assert.equal(accountRequests, 1); + } +}); +test("无关 fast_mode 字符串不再被误判为速度入口", () => { + const source = "function homeBeacon(auth){return auth===`chatgpt`&&flags.fast_mode}"; const result = patchSource(source); assert.equal(result.status, "not-applicable"); assert.equal(result.source, source); }); + +test("未知 serviceTierAccess 结构明确失败", () => { + const source = fixture().replace("accountAuth&&pending", "pending"); + const result = patchSource(source); + + assert.equal(result.status, "unexpected-shape"); + assert.match(result.reason, /设置门槛/); +}); + +test("残缺补丁标记明确失败", () => { + const result = patchSource(fixture() + SETTINGS_AUTH_MARKER); + + assert.equal(result.status, "unexpected-shape"); + assert.match(result.reason, /数量异常/); +}); diff --git a/scripts/patch-policy.js b/scripts/patch-policy.js index cf49375e..a821be42 100644 --- a/scripts/patch-policy.js +++ b/scripts/patch-policy.js @@ -33,7 +33,7 @@ const PATCH_POLICY = [ { script: "patch-remote-control.js", feature: "远程控制" }, { script: "patch-composer-workspace-root.js", feature: "会话工作目录传递" }, { script: "patch-updater.js", feature: "禁用上游自动更新" }, - { script: "patch-archive-delete.js", feature: "归档会话删除" }, + { script: "patch-archive-delete.js", feature: "跨 Provider 归档列表与归档删除" }, { script: "patch-crash-forensics.js", feature: "主进程崩溃诊断" }, { script: "patch-worker-forensics.js", feature: "Worker 崩溃诊断" }, { script: "patch-worker-limits.js", feature: "Worker 内存限制" }, diff --git a/scripts/patch-provider-quota.js b/scripts/patch-provider-quota.js index 187dd1f0..76221a7e 100644 --- a/scripts/patch-provider-quota.js +++ b/scripts/patch-provider-quota.js @@ -172,12 +172,15 @@ function patchSource(source) { } const baseBlock = contextGate.gate; const hardBlock = unique(declarations.filter(node => { - if (!referenced.has(node.id.name) || node.init?.type !== "CallExpression" || - node.init.arguments.length !== 1) return false; - const terms = nodes(node.init.arguments[0], child => child.type === "BinaryExpression" && + if (!referenced.has(node.id.name) || node.init == null) return false; + const terms = nodes(node.init, child => child.type === "BinaryExpression" && ["===", "=="].includes(child.operator) && child.left?.type === "Identifier" && child.left.name === host.name && value(child.right) === "local"); - return terms.length === 1; + // 26.1007 使用 read(hardBlockAtom) && host === "local";后续版本 + // 改成 value(host === "local" && hardBlockAtom)。两者都必须同时包含 + // 唯一的本地主机门槛和真实读取调用,避免按变量名猜测。 + return terms.length === 1 && nodes(node.init, + child => child.type === "CallExpression").length === 1; }), "Host quota gate"); const scopes = [...new Set(ownNodes.filter(node => property(node) === "kind" && property(unwrap(node).object) === "value") diff --git a/scripts/patch-provider-quota.test.js b/scripts/patch-provider-quota.test.js index c4ef1c57..85655c0b 100644 --- a/scripts/patch-provider-quota.test.js +++ b/scripts/patch-provider-quota.test.js @@ -18,6 +18,13 @@ function fixture() { ].join(""); } +function legacyFixture() { + return fixture().replace( + "hardQuota=value(host===`local`&&hardBlockAtom)", + "hardQuota=value(hardBlockAtom)&&host===`local`", + ); +} + test("按新版 Composer 数据流隔离第三方 Provider 的官方额度门槛", () => { const result = patchSource(fixture()); @@ -40,6 +47,14 @@ test("多个 Provider 读取仍要求指向同一个会话 Provider atom", () => assert.equal(result.status, "patched", result.reason); }); +test("兼容 26.1007 的独立本地主机额度门槛", () => { + const result = patchSource(legacyFixture()); + + assert.equal(result.status, "patched", result.reason); + assert.match(result.code, /\(!__codexUsesCustomProvider&&hardQuota\)/); + assert.equal(patchSource(result.code).status, "already"); +}); + test("会话 Provider atom 不唯一时拒绝补丁", () => { const source = fixture().replace( "function Composer(props){", diff --git a/scripts/patch-worker-forensics.js b/scripts/patch-worker-forensics.js index 1a66f236..f01336da 100644 --- a/scripts/patch-worker-forensics.js +++ b/scripts/patch-worker-forensics.js @@ -53,10 +53,11 @@ const fs = require("fs"); const acorn = require("acorn"); const { locateBundles, relPath } = require("./patch-util"); -const MARKER = "__CODEX_WORKER_FORENSICS_V3__"; +const MARKER = "__CODEX_WORKER_FORENSICS_V4__"; const LEGACY_MARKERS = [ "__CODEX_WORKER_FORENSICS__", "__CODEX_WORKER_FORENSICS_V2__", + "__CODEX_WORKER_FORENSICS_V3__", ]; // 注入体:自包含 CJS,不依赖 electron(worker/utility 进程无 app)。 @@ -75,6 +76,22 @@ function __codexWorkerForensics() { dir, "forensics-" + new Date().toISOString().slice(0, 10) + ".log", ); + var MAX_LOG_BYTES = 16 * 1024 * 1024; + var MAX_LOG_FILES = 7; + try { + var oldLogs = fs + .readdirSync(dir) + .filter(function (name) { + return /^forensics-\d{4}-\d{2}-\d{2}\.log$/.test(name); + }) + .sort() + .reverse(); + for (var oldIndex = MAX_LOG_FILES; oldIndex < oldLogs.length; oldIndex++) { + try { + fs.unlinkSync(path.join(dir, oldLogs[oldIndex])); + } catch (e) {} + } + } catch (e) {} // 标注进程角色:worker_threads 主线程 / 工作线程 / 独立进程 var role = "worker"; @@ -85,6 +102,7 @@ function __codexWorkerForensics() { function write(line) { try { + if (fs.existsSync(logFile) && fs.statSync(logFile).size >= MAX_LOG_BYTES) return; fs.appendFileSync( logFile, "[" + @@ -294,13 +312,11 @@ function __codexWorkerForensics() { } catch (e) {} } catch (e) { try { - require("node:fs").appendFileSync( - require("node:path").join( - require("node:os").tmpdir(), - "codex-forensics-fatal.log", - ), - "worker-forensics: " + String((e && e.stack) || e) + "\n", - ); + var fatalFs = require("node:fs"); + var fatalFile = require("node:path").join(require("node:os").tmpdir(), "codex-forensics-fatal.log"); + if (!fatalFs.existsSync(fatalFile) || fatalFs.statSync(fatalFile).size < 1024 * 1024) { + fatalFs.appendFileSync(fatalFile, "worker-forensics: " + String((e && e.stack) || e) + "\n"); + } } catch (e2) {} } } diff --git a/scripts/prepare-src.js b/scripts/prepare-src.js index 0563a9ff..fcaf2477 100644 --- a/scripts/prepare-src.js +++ b/scripts/prepare-src.js @@ -147,7 +147,8 @@ function ensureVendorExtracted(platform) { } console.log(` [vendor] fetching ${spec} via npm pack...`); - const tmpDir = path.join(require("os").tmpdir(), "cometix-codex-pack"); + const tmpDir = path.join(PROJECT_ROOT, ".cache", "vendor-pack"); + if (fs.existsSync(tmpDir)) fs.rmSync(tmpDir, { recursive: true, force: true }); fs.mkdirSync(tmpDir, { recursive: true }); try { diff --git a/scripts/runtime/accent-presets.mjs b/scripts/runtime/accent-presets.mjs index f7ae5ee4..32463822 100644 --- a/scripts/runtime/accent-presets.mjs +++ b/scripts/runtime/accent-presets.mjs @@ -35,7 +35,10 @@ export function accentPresetSelection(accountTheme, fallback) { export function resolveAccentPreset(accentSource, accountPreset) { if (accountPreset != null) return accentSource === "chatgpt" ? accountPreset : null; - return readLocalAccentPreset(); + const preset = readLocalAccentPreset(); + // 官方账户的“默认”会先解析成 effectiveTheme;未登录时没有这层账户数据。 + // Windows 官方当前的有效默认色是 blue,本地模式在渲染阶段补齐同一语义。 + return preset === "default" ? "blue" : preset; } export function selectAccentPreset(accountTheme, preset, applyLocal, selectAccount) { diff --git a/scripts/storage-governance.js b/scripts/storage-governance.js new file mode 100644 index 00000000..da044b09 --- /dev/null +++ b/scripts/storage-governance.js @@ -0,0 +1,228 @@ +#!/usr/bin/env node +/** 本地存储治理:审计固定输出,清理可重建缓存,不触碰当前/上一版程序与正式验收记录。 */ +const fs = require("node:fs"); +const path = require("node:path"); +const os = require("node:os"); + +const testMode = process.env.CODEX_STORAGE_TEST_MODE === "1"; +const root = testMode + ? path.resolve(process.env.CODEX_STORAGE_TEST_ROOT || "") + : path.resolve(__dirname, ".."); +const tempRoot = testMode + ? path.resolve(process.env.CODEX_STORAGE_TEST_TEMP || "") + : os.tmpdir(); +const forensicsRoot = testMode + ? path.resolve(process.env.CODEX_STORAGE_TEST_FORENSICS || "") + : path.join(process.env.LOCALAPPDATA || process.env.APPDATA || os.tmpdir(), "CodexForensics"); +const cacheRoot = path.join(root, ".cache"); +const mode = process.argv[2] || "audit"; +const DAY = 24 * 60 * 60 * 1000; +const LOG_LIMIT = testMode + ? Number(process.env.CODEX_STORAGE_TEST_LOG_LIMIT || 16 * 1024 * 1024) + : 16 * 1024 * 1024; +const FATAL_LOG_LIMIT = testMode + ? Number(process.env.CODEX_STORAGE_TEST_FATAL_LOG_LIMIT || 1024 * 1024) + : 1024 * 1024; +const OWNED_TEMP_PREFIXES = [ + "codex-accent-probe-", "codex-accent-theme-", "codex-cli-policy-test-", + "codex-dmg-test-", "codex-external-overlay-test-", "codex-home-nav-", + "codex-main-test-", "codex-maintenance-smoke-", "codex-msix-test-", + "codex-nested-cli-test-", "codex-owl-integrity-test-", "codex-owl-launcher-test-", + "codex-owl-manifest-test-", "codex-owl-test-", "codex-patch-report-", + "codex-preview-smoke-", "codex-readonly-overlay-test-", "codex-sentry-test-", + "codex-rebuild-", "rebuild-download-smoke-", +]; + +if (!root || !tempRoot || !forensicsRoot || !["audit", "clean"].includes(mode)) { + throw new Error("用法:node scripts/storage-governance.js audit|clean"); +} + +function assertChild(target, parent, label) { + const resolved = path.resolve(target); + const boundary = path.resolve(parent); + if (resolved !== boundary && !resolved.startsWith(boundary + path.sep)) { + throw new Error(`${label} 越界:${resolved}`); + } + return resolved; +} + +function removeOwned(target, parent, removed) { + const resolved = assertChild(target, parent, "清理目标"); + if (resolved === path.resolve(parent)) throw new Error(`禁止删除治理根目录:${resolved}`); + if (!fs.existsSync(resolved)) return; + const item = fs.lstatSync(resolved); + if (item.isSymbolicLink()) throw new Error(`禁止删除链接目标:${resolved}`); + fs.rmSync(resolved, { recursive: item.isDirectory(), force: true }); + removed.push(resolved); +} + +function directorySize(directory) { + if (!fs.existsSync(directory)) return { files: 0, bytes: 0 }; + const pending = [directory]; + let files = 0, bytes = 0; + while (pending.length) { + const current = pending.pop(); + for (const entry of fs.readdirSync(current, { withFileTypes: true })) { + const file = path.join(current, entry.name); + if (entry.isSymbolicLink()) continue; + if (entry.isDirectory()) pending.push(file); + else { files++; bytes += fs.statSync(file).size; } + } + } + return { files, bytes }; +} + +function pruneCompletedAndExpiredParts(removed) { + if (!fs.existsSync(cacheRoot)) return; + const pending = [cacheRoot], now = Date.now(); + while (pending.length) { + const current = pending.pop(); + for (const entry of fs.readdirSync(current, { withFileTypes: true })) { + const item = path.join(current, entry.name); + if (entry.isSymbolicLink() || !entry.isDirectory()) continue; + if (entry.name.endsWith(".parts")) { + const completed = item.slice(0, -".parts".length); + if (fs.existsSync(completed) || now - fs.statSync(item).mtimeMs > 2 * DAY) { + removeOwned(item, cacheRoot, removed); + } + } else pending.push(item); + } + } +} + +function pruneRunDirectories(directory, removed, keep = 2, protectedNames = []) { + if (!fs.existsSync(directory)) return; + const protectedSet = new Set(protectedNames.map(name => name.toLowerCase())); + const directories = fs.readdirSync(directory, { withFileTypes: true }) + .filter(entry => entry.isDirectory() && !entry.isSymbolicLink() && !protectedSet.has(entry.name.toLowerCase())) + .map(entry => { + const full = path.join(directory, entry.name); + return { full, modified: fs.statSync(full).mtimeMs }; + }) + .sort((left, right) => right.modified - left.modified); + for (const entry of directories.slice(keep)) removeOwned(entry.full, directory, removed); +} + +function pruneDownloadRuns(removed, keep = 2) { + pruneRunDirectories(path.join(cacheRoot, "downloads"), removed, keep); + // 早期下载脚本和手工 gh 下载使用此目录;继续纳入同一保留规则。 + pruneRunDirectories(path.join(cacheRoot, "gh-downloads"), removed, keep); +} + +function pruneAcceptanceRuns(removed, keep = 2) { + pruneRunDirectories(path.join(cacheRoot, "acceptance"), removed, keep, ["staged-candidate"]); + pruneRunDirectories(path.join(root, "acceptance"), removed, keep, ["staged-candidate"]); +} + +function pruneOwnedTemp(removed) { + if (!fs.existsSync(tempRoot)) return; + const now = Date.now(); + for (const entry of fs.readdirSync(tempRoot, { withFileTypes: true })) { + if (!entry.isDirectory() || entry.isSymbolicLink() || !OWNED_TEMP_PREFIXES.some(prefix => entry.name.startsWith(prefix))) continue; + const full = path.join(tempRoot, entry.name); + if (now - fs.statSync(full).mtimeMs > DAY) removeOwned(full, tempRoot, removed); + } +} + +function compactFile(file, maximum, compacted) { + if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return; + const size = fs.statSync(file).size; + if (size <= maximum) return; + const buffer = Buffer.alloc(maximum); + const handle = fs.openSync(file, "r"); + try { fs.readSync(handle, buffer, 0, maximum, size - maximum); } + finally { fs.closeSync(handle); } + fs.writeFileSync(file, buffer); + compacted.push(file); +} + +function pruneForensics(removed, compacted, keep = 7) { + if (!fs.existsSync(forensicsRoot)) return; + const logs = fs.readdirSync(forensicsRoot, { withFileTypes: true }) + .filter(entry => entry.isFile() && /^forensics-\d{4}-\d{2}-\d{2}\.log$/.test(entry.name)) + .map(entry => path.join(forensicsRoot, entry.name)) + .sort((left, right) => path.basename(right).localeCompare(path.basename(left))); + for (const file of logs.slice(keep)) removeOwned(file, forensicsRoot, removed); + for (const file of logs.slice(0, keep)) compactFile(file, LOG_LIMIT, compacted); + compactFile(path.join(forensicsRoot, "chrome-debug.log"), LOG_LIMIT, compacted); + compactFile(path.join(tempRoot, "codex-forensics-fatal.log"), FATAL_LOG_LIMIT, compacted); +} + +function hasNestedLink(directory) { + const pending = [directory]; + while (pending.length) { + const current = pending.pop(); + for (const entry of fs.readdirSync(current, { withFileTypes: true })) { + if (entry.isSymbolicLink()) return true; + if (entry.isDirectory()) pending.push(path.join(current, entry.name)); + } + } + return false; +} + +function pruneInterruptedBuilds(removed) { + const buildRoot = path.join(root, "build"); + if (!fs.existsSync(buildRoot) || fs.existsSync(path.join(buildRoot, ".candidate-switch.lock"))) return; + const hasProtectedVersions = ["Codex", "previous"].every(name => + fs.existsSync(path.join(buildRoot, name, "Codex.exe"))); + const now = Date.now(); + for (const entry of fs.readdirSync(buildRoot, { withFileTypes: true })) { + if (!entry.isDirectory() || entry.isSymbolicLink()) continue; + const preparing = /^\.next-preparing-\d+$/.test(entry.name); + const retired = /^\.previous-retired-\d+$/.test(entry.name); + if (!preparing && !(retired && hasProtectedVersions)) continue; + const full = path.join(buildRoot, entry.name); + if (now - fs.statSync(full).mtimeMs <= DAY || hasNestedLink(full)) continue; + removeOwned(full, buildRoot, removed); + } +} + +function pruneGeneratedOutputs(removed) { + for (const name of ["src", "out", "patch-reports"]) { + const target = path.join(root, name); + if (fs.existsSync(target)) removeOwned(target, root, removed); + } + for (const entry of fs.readdirSync(root, { withFileTypes: true })) { + if (!entry.isDirectory() || entry.isSymbolicLink() || !/^out-.+/.test(entry.name)) continue; + removeOwned(path.join(root, entry.name), root, removed); + } +} + +function audit() { + const paths = [ + cacheRoot, + path.join(root, "build"), + path.join(root, "src"), + path.join(root, "out"), + path.join(root, "patch-reports"), + path.join(root, "artifacts"), + path.join(root, "acceptance"), + path.join(root, "release", "archive"), + forensicsRoot, + ]; + return paths.filter(file => fs.existsSync(file)).map(file => { + const size = directorySize(file); + return { path: file, files: size.files, mib: Number((size.bytes / 1048576).toFixed(1)) }; + }); +} + +const removed = [], compacted = []; +if (mode === "clean") { + pruneCompletedAndExpiredParts(removed); + pruneDownloadRuns(removed); + pruneAcceptanceRuns(removed); + pruneOwnedTemp(removed); + pruneForensics(removed, compacted); + pruneInterruptedBuilds(removed); + pruneGeneratedOutputs(removed); +} +console.log(JSON.stringify({ + mode, + policy: { + downloadRuns: 2, acceptanceRuns: 2, incompletePartsDays: 2, + forensicsLogs: 7, forensicsLogMiB: 16, fatalLogMiB: 1, + ownedTempHours: 24, interruptedBuildHours: 24, + generatedOutputs: ["src", "out", "out-*", "patch-reports"], + }, + removed, compacted, usage: audit(), +}, null, 2)); diff --git a/scripts/sync-upstream.js b/scripts/sync-upstream.js index f5763659..e669caae 100644 --- a/scripts/sync-upstream.js +++ b/scripts/sync-upstream.js @@ -37,7 +37,7 @@ const PROJECT_ROOT = path.resolve(__dirname, ".."); const SRC_DIR = path.join(PROJECT_ROOT, "src"); const TEMP_DIR = process.env.CODEX_SYNC_DIR ? path.resolve(process.env.CODEX_SYNC_DIR) - : path.join(require("os").tmpdir(), "codex-sync"); + : path.join(PROJECT_ROOT, ".cache", "upstream-sync"); const VERSION_FILE = path.join(__dirname, ".versions.json"); const APPCAST_ARM64 = "https://persistent.oaistatic.com/codex-app-prod/appcast.xml"; @@ -212,6 +212,20 @@ function clearDir(dir) { fs.mkdirSync(dir, { recursive: true }); } +function removeObsoletePackages(currentFile, pattern) { + if (!fs.existsSync(TEMP_DIR)) return []; + const keep = path.resolve(currentFile); + const removed = []; + for (const entry of fs.readdirSync(TEMP_DIR, { withFileTypes: true })) { + if (!entry.isFile() || !pattern.test(entry.name)) continue; + const file = path.join(TEMP_DIR, entry.name); + if (path.resolve(file) === keep) continue; + fs.rmSync(file, { force: true }); + removed.push(entry.name); + } + return removed; +} + function countFiles(dir) { let n = 0; for (const e of fs.readdirSync(dir, { withFileTypes: true })) { @@ -436,6 +450,8 @@ async function syncMac(variant, appcastUrl, destDir) { const zipPath = path.join(TEMP_DIR, `Codex-${variant}-${info.version}.zip`); const extractDir = path.join(TEMP_DIR, `${variant}-extract`); + const variantPattern = new RegExp(`^Codex-${variant.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}-.*\\.zip$`, "i"); + removeObsoletePackages(zipPath, variantPattern); if (!fs.existsSync(zipPath)) { curlDownload(info.url, zipPath, label); @@ -463,6 +479,7 @@ async function syncWin(destDir, info) { const msixPath = path.join(TEMP_DIR, info.packageName || `codex-win-${info.version}.msix`); const extractDir = path.join(TEMP_DIR, "win-extract"); + removeObsoletePackages(msixPath, /^OpenAI\.Codex_.*_x64__.*\.msix$/i); if (info.localPackage) { await verifySourceFile(info, info.localPackage); @@ -611,6 +628,7 @@ module.exports = { readWindowsPackageIdentity, selectWindowsPackage, validateWindowsPackage, + removeObsoletePackages, }; if (require.main === module) { diff --git a/scripts/windows-maintenance.js b/scripts/windows-maintenance.js index 58273809..88cb85ba 100644 --- a/scripts/windows-maintenance.js +++ b/scripts/windows-maintenance.js @@ -107,10 +107,29 @@ function inspectUpdater(asarRoot) { return { methods, disabled: windowsMethods.length > 0 && windowsMethods.every((method) => method.disabled) }; } -function saveCompatibilityEvidence(asarRoot, source) { - const destination = path.join(root, "patch-reports", "source-evidence"); +function findFilesNamed(directory, expectedName) { + if (!fs.existsSync(directory)) return []; + const files = []; + const pending = [directory]; + while (pending.length > 0) { + const current = pending.pop(); + for (const entry of fs.readdirSync(current, { withFileTypes: true })) { + const fullPath = path.join(current, entry.name); + if (entry.isDirectory()) pending.push(fullPath); + else if (entry.isFile() && entry.name === expectedName) files.push(fullPath); + } + } + return files.sort(); +} + +function saveCompatibilityEvidence( + asarRoot, + source, + destination = path.join(root, "patch-reports", "source-evidence"), +) { const signatures = ["shouldIncludeUpdater", "shouldIncludeWindowsUpdater", "shouldIncludeWindowsMsixUpdater", - "FlyoutSubmenuItem", "flyoutHeader", "data-model-picker-model-row", "data-model-picker-view", "modelListConfig"]; + "FlyoutSubmenuItem", "flyoutHeader", "data-model-picker-model-row", "data-model-picker-view", "modelListConfig", + "serviceTierAccess", "Failed to read service tier for request"]; const files = []; for (const [label, directory] of [["main", ".vite/build"], ["webview", "webview/assets"]]) { const sourceDirectory = path.join(asarRoot, directory); @@ -124,12 +143,43 @@ function saveCompatibilityEvidence(asarRoot, source) { const copied = label === "main" ? require("./patch-updater").auditUpdaterSource(text).length > 0 : matches.includes("flyoutHeader") || matches.includes("data-model-picker-model-row") || matches.includes("data-model-picker-view") && matches.includes("modelListConfig"); + const serviceTierEvidence = matches.includes("serviceTierAccess") && + matches.includes("Failed to read service tier for request"); const readingEvidence = matches.includes("settings.appearance.visualStyle") || name.endsWith(".css") && matches.some(match => match.startsWith("--")); - if (copied || readingEvidence || startupEvidence) { + if (copied || serviceTierEvidence || readingEvidence || startupEvidence) { fs.mkdirSync(path.join(destination, label), { recursive: true }); fs.copyFileSync(file, path.join(destination, label, name)); } - files.push({ directory, name, matches, copied: copied || readingEvidence || startupEvidence, sha256: crypto.createHash("sha256").update(text).digest("hex") }); + files.push({ directory, name, matches, copied: copied || serviceTierEvidence || readingEvidence || startupEvidence, sha256: crypto.createHash("sha256").update(text).digest("hex") }); + } + } + + const platformRoot = path.dirname(asarRoot); + const browserSignatures = [ + "codex_browser_use_agent_request_header", + "Browser request-header policy requires caller identity.", + "Browser feature gates require caller identity.", + "agentRequestHeaderEnabled", + "getExtensionRequestHeaders", + "readRequirements", + "requestHeadersVersion", + "request_headers", + ]; + for (const resourceName of ["plugins", "cua_node"]) { + const resourceRoot = path.join(platformRoot, resourceName); + for (const file of findFilesNamed(resourceRoot, "browser-service.mjs")) { + const text = fs.readFileSync(file, "utf8"); + const relative = path.relative(platformRoot, file); + const copiedFile = path.join(destination, "external", relative); + fs.mkdirSync(path.dirname(copiedFile), { recursive: true }); + fs.copyFileSync(file, copiedFile); + files.push({ + directory: path.dirname(relative).replaceAll("\\", "/"), + name: path.basename(file), + matches: browserSignatures.filter((signature) => text.includes(signature)), + copied: true, + sha256: crypto.createHash("sha256").update(text).digest("hex"), + }); } } writeJson(path.join(destination, "index.json"), { schemaVersion: 1, upstream: source, files, @@ -332,4 +382,4 @@ async function main() { else throw new Error("用法:windows-maintenance.js [--参数 值]"); } if (require.main === module) main().catch((error) => { console.error(`[error] ${error.message}`); process.exitCode = 1; }); -module.exports = { requiredChecks }; +module.exports = { findFilesNamed, requiredChecks, saveCompatibilityEvidence }; From 361611c6d6ba6ec8632921689293fe2a00365bbb Mon Sep 17 00:00:00 2001 From: carptopus Date: Sat, 17 Oct 2026 01:43:10 +0800 Subject: [PATCH 10/51] fix: keep public maintenance tests self-contained --- scripts/maintenance-smoke.js | 26 -------------------------- 1 file changed, 26 deletions(-) diff --git a/scripts/maintenance-smoke.js b/scripts/maintenance-smoke.js index fe8e94dc..0ade7331 100644 --- a/scripts/maintenance-smoke.js +++ b/scripts/maintenance-smoke.js @@ -239,32 +239,6 @@ try { assert.equal(fs.statSync(path.join(storageTemp, "codex-forensics-fatal.log")).size, 16); checks++; - if (process.platform === "win32") { - const archiveProject = path.join(temporary, "archive-project"); - const archiveScript = path.join(archiveProject, "local", "scripts", "Archive-Candidate.ps1"); - fs.mkdirSync(path.dirname(archiveScript), { recursive: true }); - fs.copyFileSync(path.join(scriptRoot, "..", "local", "scripts", "Archive-Candidate.ps1"), archiveScript); - for (let index = 1; index <= 3; index++) { - const candidateDirectory = path.join(archiveProject, `candidate-${index}`); - const zipName = `candidate-${index}.zip`, packageName = `source-${index}.msix`; - const zipPayload = `zip-${index}`, packagePayload = `msix-${index}`; - write(path.join(candidateDirectory, zipName), zipPayload); - write(path.join(candidateDirectory, packageName), packagePayload); - json(path.join(candidateDirectory, "candidate.json"), { - schemaVersion: 1, repository: "Carptopus/CodexDesktop-Rebuild", - sourceCommit: String(index).repeat(40), - upstream: { version: `1.0.0.${index}`, packageName, sha256: hash(packagePayload) }, - zip: { name: zipName, sha256: hash(zipPayload) }, - }); - const archived = spawnSync("pwsh", ["-NoProfile", "-File", archiveScript, "-CandidateDirectory", candidateDirectory, "-Keep", "2"], { encoding: "utf8" }); - assert.equal(archived.status, 0, archived.stdout + archived.stderr); - const destination = path.join(archiveProject, "release", "archive", `1.0.0.${index}-${String(index).repeat(40)}`); - fs.utimesSync(destination, new Date(2020, 0, index), new Date(2020, 0, index)); - } - const kept = fs.readdirSync(path.join(archiveProject, "release", "archive")).sort(); - assert.deepEqual(kept, [`1.0.0.2-${"2".repeat(40)}`, `1.0.0.3-${"3".repeat(40)}`]); - checks++; - } console.log(`维护链功能测试通过:${checks} 个 CLI 场景;实际 GUI、原始 MSIX 和签名由候选验收覆盖。`); } finally { fs.rmSync(temporary, { recursive: true, force: true }); From 540078605487c234849443276f494711a1a01448 Mon Sep 17 00:00:00 2001 From: carptopus Date: Sun, 18 Oct 2026 02:15:40 +0800 Subject: [PATCH 11/51] feat: restore home session and enable thread timeline --- README.md | 4 +- package.json | 2 - scripts/frontend-source-smoke.js | 10 +- scripts/maintenance-smoke.js | 51 ---- scripts/patch-api-key-home-navigation.js | 84 ++++++- scripts/patch-api-key-home-navigation.test.js | 58 ++++- scripts/patch-policy.js | 1 + scripts/patch-thread-timeline.js | 186 ++++++++++++++ scripts/patch-thread-timeline.test.js | 63 +++++ scripts/storage-governance.js | 228 ------------------ 10 files changed, 395 insertions(+), 292 deletions(-) create mode 100644 scripts/patch-thread-timeline.js create mode 100644 scripts/patch-thread-timeline.test.js delete mode 100644 scripts/storage-governance.js diff --git a/README.md b/README.md index c4e8a681..93d9fb50 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,8 @@ npm run build:all - `patch-browser-auth.js` 兼容 API-key 登录:旧版在 ChatGPT 身份读取失败时仅关闭可选 request-header 并继续本地浏览器通道;新版原生托管请求头不再依赖 ChatGPT 身份时验证该完整链路并保持原样,不会把 API key 伪装或发送为 ChatGPT token。 - `patch-fast-mode.js` 为 API-key / 自定义 Provider 补齐新版 `serviceTierAccess`:跳过不可用的 ChatGPT 账户权限查询,但仍由当前模型返回的 `serviceTierOptions` 决定是否显示和发送 Fast / Ultrafast 档位。 - `patch-provider-quota.js` 按任务实际 Provider 和明确的 `base_url` 判断发送门槛,避免 ChatGPT 额度状态误阻断第三方 Provider,同时保留官方、云任务及第三方真实错误。 -- `patch-api-key-home-navigation.js` 补齐 API-key 模式的当前会话导航记录,使首页入口按官方读取逻辑恢复当前会话;ChatGPT、无认证及其他认证方式保持原有条件。 +- `patch-api-key-home-navigation.js` 补齐 API-key 模式的当前会话导航记录,并让功能导航栏的首页重选分支使用该记录恢复最近会话,而不是直达空首页;ChatGPT、无认证及其他认证方式保持原有条件。 +- `patch-thread-timeline.js` 在当前 host 与 App Server 版本支持时启用官方 `thread/timeline/list` 历史路径,移除 API-key / 自定义 Provider 无法获得的远端灰度条件;版本兼容判断仍由官方逻辑负责。 - `patch-accent-presets.js` 允许没有 ChatGPT 账户主题的 API-key / 自定义 Provider 在本地选择强调色,并复用官方完整预设渲染消息气泡等界面变量;账户主题仍在加载时保持禁用,账户可用时继续使用官方同步。 - `patch-hide-pet-menu.js` 只隐藏账户菜单中的 Pet / Mini 入口,保留浮动面板实现、状态和全局快捷键。 - `patch-reading-layout.js` 在外观主题卡片中加入 50%–100%、步进 5% 的正文宽度滑杆,并同步代码块、表格和输入区宽度,扩宽适用对话框;百分比不低于官方宽度,Markdown 粗体颜色可跟随正文、强调色或使用自定义颜色。 @@ -53,7 +54,6 @@ npm run build:all - `windows-artifacts.js` 与 `windows-maintenance.js` 记录官方来源和候选产物哈希,生成候选、验证发布门槛,并保证正式发布复用已经验收的同一 ZIP。 - `windows-runtime-checks.js` 检查 Windows EXE / 原生模块架构及未修改组件哈希,实际加载 CUA、运行 code-mode host / rg 基础命令,并执行空白隔离桌面的启动、就绪和退出冒烟。 - `check-scripts.js`、`frontend-source-smoke.js`、`reading-layout-smoke.js` 和 `maintenance-smoke.js` 覆盖脚本语法、真实补丁资源、阅读设置及候选/发布拒绝路径,避免只凭补丁脚本成功退出判断功能可用。 -- `storage-governance.js` 审计本地缓存、构建目录和取证日志;清理模式只处理可重建缓存/构建中间结果、旧隔离验收数据和确认中断的临时目录,下载与验收运行各保留最近两次、取证日志保留最近 7 天并限制单文件大小,正式制品及当前与上一版程序不参与清理。 - `patch-realtime-voice-auth.js` 为 API-key 登录放行实时语音入口;实时会话仍由 app-server 使用当前 model provider 的 `base_url` 与认证创建,ChatGPT 工作区能力的认证限制保持不变。 - 上游更新后应先执行 `npm run patch -- --check` 或完整 `npm run patch`,再运行测试和构建。 diff --git a/package.json b/package.json index cf3e6f7e..65230b25 100644 --- a/package.json +++ b/package.json @@ -28,8 +28,6 @@ "test": "node --test scripts/*.test.js", "check": "node scripts/check-scripts.js", "test:maintenance": "node scripts/maintenance-smoke.js", - "storage:audit": "node scripts/storage-governance.js audit", - "storage:clean": "node scripts/storage-governance.js clean", "windows:check-update": "node scripts/windows-maintenance.js discover", "windows:candidate": "node scripts/windows-maintenance.js candidate", "windows:verify-release": "node scripts/windows-maintenance.js verify-release", diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index c0b18cb2..145e8cae 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -84,6 +84,14 @@ function verifyFrontendSource(assets) { assert.match(navigationSource, /authMethod:__codexAuthMethod/); assert.match(navigationSource, /\/\* Codex:API-key 当前首页保持会话。 \*\/__codexAuthMethod===`apikey`&&[A-Za-z_$][\w$]*!=null&&\([A-Za-z_$][\w$]*\.pathname\.startsWith\(`\/local\/`\)\|\|[A-Za-z_$][\w$]*\.pathname\.startsWith\(`\/remote\/`\)\)/); + assert.match(navigationSource, + /\/\* Codex:API-key 首页恢复最近会话。 \*\/[A-Za-z_$][\w$]*\.authMethod!==`apikey`/); + const timelineEntries = files.filter(name => /^app-initial-/.test(name) + && fs.readFileSync(path.join(assets, name), "utf8").includes("CodexRebuildThreadTimeline")); + assert.equal(timelineEntries.length, 1); + const timelineSource = fs.readFileSync(path.join(assets, timelineEntries[0]), "utf8"); + assert.match(timelineSource, + /supportsThreadTimeline\(\)\{return\s*[A-Za-z_$][\w$]*\(this\.hostId,this\.requestClient\.getAppServerVersion\(\)\)\/\* CodexRebuildThreadTimeline \*\//); const serviceTierEntries = files.filter(name => /^app-initial-/.test(name) && fs.readFileSync(path.join(assets, name), "utf8").includes("CodexRebuildServiceTierApiKeyRequest")); assert.equal(serviceTierEntries.length, 1); @@ -109,7 +117,7 @@ function verifyFrontendSource(assets) { assert.equal(shared.length, 1); const dialogs = fs.readFileSync(path.join(assets, shared[0]), "utf8"); assert.match(dialogs, /codex-rebuild-dialog-editor h-\[720px\] max-w-full max-h-full/); - return { passed: true, quotaScenarios: results, apiKeyHomeNavigation: true, apiKeyServiceTiers: true, nativeAppearanceRow: true, nativeAccentThemePipeline: true, dialogHeightPreserved: true }; + return { passed: true, quotaScenarios: results, apiKeyHomeNavigation: true, threadTimelineEnabled: true, apiKeyServiceTiers: true, nativeAppearanceRow: true, nativeAccentThemePipeline: true, dialogHeightPreserved: true }; } if (require.main === module) console.log(JSON.stringify(verifyFrontendSource(path.resolve(process.argv[2] || "src/win/_asar/webview/assets")), null, 2)); module.exports = { verifyFrontendSource }; diff --git a/scripts/maintenance-smoke.js b/scripts/maintenance-smoke.js index 0ade7331..5cd01fe1 100644 --- a/scripts/maintenance-smoke.js +++ b/scripts/maintenance-smoke.js @@ -188,57 +188,6 @@ try { run("windows-maintenance.js", arguments.map((value) => value === "123" ? "999" : value), 1); run("windows-maintenance.js", arguments.map((value) => value === sha ? "2".repeat(40) : value), 1); - const storageRoot = path.join(temporary, "storage-project"); - const storageTemp = path.join(temporary, "storage-temp"); - const storageForensics = path.join(temporary, "storage-forensics"); - const old = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000); - for (const name of ["100", "200", "300"]) { - write(path.join(storageRoot, ".cache", "downloads", name, "payload.bin"), name); - fs.utimesSync(path.join(storageRoot, ".cache", "downloads", name), old, new Date(old.getTime() + Number(name))); - write(path.join(storageRoot, ".cache", "gh-downloads", name, "payload.bin"), name); - fs.utimesSync(path.join(storageRoot, ".cache", "gh-downloads", name), old, new Date(old.getTime() + Number(name))); - write(path.join(storageRoot, ".cache", "acceptance", name, "profile.bin"), name); - fs.utimesSync(path.join(storageRoot, ".cache", "acceptance", name), old, new Date(old.getTime() + Number(name))); - } - write(path.join(storageRoot, ".cache", "downloads", "300", "payload.zip"), "done"); - write(path.join(storageRoot, ".cache", "downloads", "300", "payload.zip.parts", "0.part"), "duplicate"); - write(path.join(storageRoot, "build", "Codex", "Codex.exe"), "protected"); - write(path.join(storageRoot, "build", "previous", "Codex.exe"), "protected previous"); - for (const directory of ["src", "out", "out-win", "patch-reports"]) write(path.join(storageRoot, directory, "generated.bin"), "generated"); - for (const name of [".next-preparing-123", ".previous-retired-123"]) { - write(path.join(storageRoot, "build", name, "Codex.exe"), "interrupted"); - fs.utimesSync(path.join(storageRoot, "build", name), old, old); - } - for (let day = 1; day <= 9; day++) write(path.join(storageForensics, `forensics-2026-10-${String(day).padStart(2, "0")}.log`), String(day)); - write(path.join(storageForensics, "chrome-debug.log"), "x".repeat(64)); - write(path.join(storageForensics, "forensics-2026-10-09.log"), "x".repeat(64)); - write(path.join(storageTemp, "codex-forensics-fatal.log"), "x".repeat(64)); - write(path.join(storageTemp, "codex-main-test-old", "fixture"), "old"); - fs.utimesSync(path.join(storageTemp, "codex-main-test-old"), old, old); - write(path.join(storageTemp, "codex-rebuild-old", "fixture"), "old"); - fs.utimesSync(path.join(storageTemp, "codex-rebuild-old"), old, old); - const storageEnv = { CODEX_STORAGE_TEST_MODE: "1", CODEX_STORAGE_TEST_ROOT: storageRoot, - CODEX_STORAGE_TEST_TEMP: storageTemp, CODEX_STORAGE_TEST_FORENSICS: storageForensics, - CODEX_STORAGE_TEST_LOG_LIMIT: "32", CODEX_STORAGE_TEST_FATAL_LOG_LIMIT: "16" }; - run("storage-governance.js", ["clean"], 0, storageEnv); - assert.equal(fs.existsSync(path.join(storageRoot, ".cache", "downloads", "100")), false); - assert.equal(fs.existsSync(path.join(storageRoot, ".cache", "downloads", "200")), true); - assert.equal(fs.existsSync(path.join(storageRoot, ".cache", "gh-downloads", "100")), false); - assert.equal(fs.existsSync(path.join(storageRoot, ".cache", "acceptance", "100")), false); - assert.equal(fs.existsSync(path.join(storageRoot, ".cache", "downloads", "300", "payload.zip.parts")), false); - assert.equal(fs.readFileSync(path.join(storageRoot, "build", "Codex", "Codex.exe"), "utf8"), "protected"); - assert.equal(fs.readFileSync(path.join(storageRoot, "build", "previous", "Codex.exe"), "utf8"), "protected previous"); - assert.equal(fs.existsSync(path.join(storageRoot, "build", ".next-preparing-123")), false); - assert.equal(fs.existsSync(path.join(storageRoot, "build", ".previous-retired-123")), false); - for (const directory of ["src", "out", "out-win", "patch-reports"]) assert.equal(fs.existsSync(path.join(storageRoot, directory)), false); - assert.equal(fs.existsSync(path.join(storageTemp, "codex-main-test-old")), false); - assert.equal(fs.existsSync(path.join(storageTemp, "codex-rebuild-old")), false); - assert.equal(fs.readdirSync(storageForensics).filter(name => /^forensics-\d{4}-\d{2}-\d{2}\.log$/.test(name)).length, 7); - assert.equal(fs.statSync(path.join(storageForensics, "chrome-debug.log")).size, 32); - assert.equal(fs.statSync(path.join(storageForensics, "forensics-2026-10-09.log")).size, 32); - assert.equal(fs.statSync(path.join(storageTemp, "codex-forensics-fatal.log")).size, 16); - checks++; - console.log(`维护链功能测试通过:${checks} 个 CLI 场景;实际 GUI、原始 MSIX 和签名由候选验收覆盖。`); } finally { fs.rmSync(temporary, { recursive: true, force: true }); diff --git a/scripts/patch-api-key-home-navigation.js b/scripts/patch-api-key-home-navigation.js index 72412713..783176f2 100644 --- a/scripts/patch-api-key-home-navigation.js +++ b/scripts/patch-api-key-home-navigation.js @@ -6,8 +6,9 @@ * 新导航模式和 ChatGPT capability 限制,导致 API-key 下从不写入。 * 同时,侧栏房子按钮使用独立的 openHome 分支直接导航到 `/`,不会进入 * 上述首页恢复函数。这里只给该按钮传入真实 authMethod,并在 API-key 已经 - * 位于 `/local/` 或 `/remote/` 时短路;根路径和非会话页面仍执行 - * 官方导航。 + * 位于 `/local/` 或 `/remote/` 时短路。新版功能导航栏还有一条 + * “当前已经选中首页时再次点击”的直达 `/` 分支;API-key 必须跳过该分支, + * 交回官方首页位置记录器,才能从设置等页面恢复最近会话。 * 补丁不开启 ChatGPT 账户能力,也不改变其他认证方式。 */ const fs = require("node:fs"); @@ -17,6 +18,7 @@ const { SRC_DIR, relPath } = require("./patch-util"); const MARKER = "/* Codex:API-key 首页恢复写入。 */"; const CURRENT_HOME_MARKER = "/* Codex:API-key 当前首页保持会话。 */"; +const HOME_RESELECT_MARKER = "/* Codex:API-key 首页恢复最近会话。 */"; const PLATFORMS = ["mac-arm64", "mac-x64", "win", "unix"]; function walk(node, visit, root = node, ownScope = false) { @@ -225,6 +227,52 @@ function findOpenHomeRoute(ast, source) { return { ...route, caller, markerPresent }; } +function findHomeRailReselect(ast, source) { + const candidates = []; + for (const fn of ast.body.filter(node => node.type === "FunctionDeclaration")) { + const authBindings = nodes(fn, node => node.type === "VariableDeclarator" && + node.id?.type === "ObjectPattern" && node.init?.type === "Identifier", true) + .map(node => ({ + authMethod: objectBinding(node.id, "authMethod"), + authState: node.init.name, + })) + .filter(item => item.authMethod); + if (authBindings.length !== 1) continue; + + for (const arrow of nodes(fn, node => node.type === "ArrowFunctionExpression")) { + const restoreCalls = nodes(arrow, node => { + if (node.type !== "CallExpression" || node.arguments[1]?.type !== "ObjectExpression") return false; + const options = node.arguments[1]; + return ["accountKey", "area", "navigate", "productMode", "state"].every(name => + objectProperty(options, name)?.value?.type === "Identifier"); + }, true); + if (restoreCalls.length !== 1) continue; + const restoreCall = restoreCalls[0]; + const options = restoreCall.arguments[1]; + const area = objectProperty(options, "area").value.name; + const productMode = objectProperty(options, "productMode").value.name; + const branches = nodes(arrow, node => { + if (node.type !== "IfStatement" || node.start >= restoreCall.start) return false; + const testNames = new Set(nodes(node.test, item => item.type === "Identifier") + .map(item => item.name)); + if (!testNames.has(area) || !testNames.has(productMode)) return false; + const body = nodes(node.consequent, () => true); + return body.some(item => item.type === "ReturnStatement") && + body.some(item => memberName(item) === "path"); + }, true); + if (branches.length !== 1) continue; + candidates.push({ + authMethod: authBindings[0].authMethod, + authState: authBindings[0].authState, + branch: branches[0], + markerPresent: source.slice(branches[0].start, restoreCall.start) + .includes(HOME_RESELECT_MARKER), + }); + } + } + return unique(candidates, "功能导航栏首页重选分支"); +} + function isApiKeyOverride(node, authMethod) { if (node?.type !== "LogicalExpression" || node.operator !== "||") return false; const comparison = node.right; @@ -233,6 +281,13 @@ function isApiKeyOverride(node, authMethod) { literal(comparison.right) === "apikey"; } +function isApiKeyRailGuard(node, authState) { + return nodes(node, item => item.type === "BinaryExpression" && + ["!==", "!="].includes(item.operator) && + memberName(item.left) === "authMethod" && memberRoot(item.left) === authState && + literal(item.right) === "apikey").length === 1; +} + function patchSource(source) { if (!["authMethod", "accountKey", "productMode", "auth:", "chatgpt:"].every(value => source.includes(value))) { @@ -242,8 +297,10 @@ function patchSource(source) { const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); const tracker = findTracker(ast); const openHome = findOpenHomeRoute(ast, source); - if (tracker == null || openHome == null) { - if (source.includes(MARKER) || source.includes(CURRENT_HOME_MARKER)) { + const homeRail = findHomeRailReselect(ast, source); + if (tracker == null || openHome == null || homeRail == null) { + if (source.includes(MARKER) || source.includes(CURRENT_HOME_MARKER) || + source.includes(HOME_RESELECT_MARKER)) { throw new Error("补丁标记存在但首页导航结构未知"); } return { status: "not-applicable", source }; @@ -253,6 +310,8 @@ function patchSource(source) { openHome.authMethod === "__codexAuthMethod" && openHome.caller.passedAuthMethod?.type === "Identifier" && openHome.caller.passedAuthMethod.name === openHome.caller.authMethod; + const homeRailPatched = homeRail.markerPresent && + isApiKeyRailGuard(homeRail.branch.test, homeRail.authState); if (trackerPatched) { const gateSource = source.slice(tracker.gate.start, tracker.gate.end); if (!gateSource.includes(MARKER)) throw new Error("API-key 放行逻辑存在但缺少本项目标记"); @@ -265,7 +324,12 @@ function patchSource(source) { if (!openHomePatched && openHomePartiallyPatched) { throw new Error("房子按钮 API-key 保持逻辑不完整"); } - if (trackerPatched && openHomePatched) return { status: "already-patched", source }; + if (homeRail.markerPresent && !homeRailPatched) { + throw new Error("功能导航栏首页恢复逻辑不完整"); + } + if (trackerPatched && openHomePatched && homeRailPatched) { + return { status: "already-patched", source }; + } const edits = []; if (!trackerPatched) { @@ -293,6 +357,14 @@ function patchSource(source) { replacement: `if(${CURRENT_HOME_MARKER}__codexAuthMethod===\`apikey\`&&${openHome.currentLocation}!=null&&(${openHome.currentLocation}.pathname.startsWith(\`/local/\`)||${openHome.currentLocation}.pathname.startsWith(\`/remote/\`)))return;`, }); } + if (!homeRailPatched) { + const originalTest = source.slice(homeRail.branch.test.start, homeRail.branch.test.end); + edits.push({ + start: homeRail.branch.test.start, + end: homeRail.branch.test.end, + replacement: `(${HOME_RESELECT_MARKER}${homeRail.authState}.authMethod!==\`apikey\`&&(${originalTest}))`, + }); + } let next = source; for (const edit of edits.sort((left, right) => right.start - left.start)) { next = next.slice(0, edit.start) + edit.replacement + next.slice(edit.end); @@ -355,4 +427,4 @@ function main() { } if (require.main === module) main(); -module.exports = { CURRENT_HOME_MARKER, MARKER, patchSource }; +module.exports = { CURRENT_HOME_MARKER, HOME_RESELECT_MARKER, MARKER, patchSource }; diff --git a/scripts/patch-api-key-home-navigation.test.js b/scripts/patch-api-key-home-navigation.test.js index 1fd2c248..3c665548 100644 --- a/scripts/patch-api-key-home-navigation.test.js +++ b/scripts/patch-api-key-home-navigation.test.js @@ -1,7 +1,12 @@ const test = require("node:test"); const assert = require("node:assert/strict"); -const { CURRENT_HOME_MARKER, MARKER, patchSource } = require("./patch-api-key-home-navigation"); +const { + CURRENT_HOME_MARKER, + HOME_RESELECT_MARKER, + MARKER, + patchSource, +} = require("./patch-api-key-home-navigation"); function fixture() { return [ @@ -26,6 +31,11 @@ function fixture() { "if(!o)return;if(l==null){s();return}r(l.location)}", "function Pjo(){let i=store(),h=navigate(),a=start(),{accountId:O,authMethod:k}=mp(),", "c=()=>{wti(i,{codexLocalAccessStatus:`allowed`,currentMode:`codex`,navigate:h,nextMode:`codex`,openHome:!0,startNewConversation:a})};return c}", + "function Rail({selectedArea:A}){let P=scope(),N=productMode(),C=auth(),", + "{accountId:w,authMethod:T,userId:E,isLoading:D}=C,O=`auth:${T}`,", + "M=(e,t)=>{let n=N,r=P.get(currentMode),a=destinations[e];run(a,t=>{", + "if(A===e&&r===n){let n=destinations[e];if(n==null)return;let r=P.get(currentLocation),i=r!=null&&belongs(r,n);(!i)&&navigate(n.path,{state:t});return}", + "restoreHome(P,{accountKey:O,auth:C,area:e,navigate:navigate,productMode:n,state:t})})};return M}", ].join(""); } @@ -126,6 +136,49 @@ test("API-key 从设置页点击房子仍执行官方首页导航", () => { assert.deepEqual(navigations, ["/"]); }); +function clickFeatureHome(source, authMethod) { + const navigations = []; + const restores = []; + const scopeValue = { + get(key) { + if (key === "currentMode") return "codex"; + if (key === "currentLocation") return { pathname: "/settings/appearance" }; + return null; + }, + }; + const run = Function("authMethod", "scopeValue", "recordNavigation", "recordRestore", [ + "const scope=()=>scopeValue,productMode=()=>`codex`;", + "const auth=()=>({accountId:null,authMethod,userId:null,isLoading:false});", + "const currentMode=`currentMode`,currentLocation=`currentLocation`;", + "const destinations={home:{path:`/`}},run=(_destination,callback)=>callback({});", + "const belongs=()=>false,navigate=path=>recordNavigation(path);", + "const restoreHome=(_scope,options)=>recordRestore(options.area);", + source, + "return Rail({selectedArea:`home`})(`home`,{});", + ].join("")); + run(authMethod, scopeValue, path => navigations.push(path), area => restores.push(area)); + return { navigations, restores }; +} + +test("API-key 重选功能导航栏首页时恢复记录的最近会话", () => { + const result = patchSource(fixture()); + + assert.ok(result.source.includes(HOME_RESELECT_MARKER)); + assert.deepEqual(clickFeatureHome(result.source, "apikey"), { + navigations: [], + restores: ["home"], + }); +}); + +test("ChatGPT 重选功能导航栏首页时保持官方直达行为", () => { + const result = patchSource(fixture()); + + assert.deepEqual(clickFeatureHome(result.source, "chatgpt"), { + navigations: ["/"], + restores: [], + }); +}); + test("ChatGPT 登录继续遵守官方 capability 与账户条件", () => { const result = patchSource(fixture()); @@ -157,7 +210,8 @@ test("未认证及其他认证方式不会因补丁越过 capability", () => { test("导航跟踪器不唯一时明确失败", () => { const source = fixture() + fixture() .replaceAll("Lhc", "Mhc").replaceAll("Sti", "Tti") - .replaceAll("wti", "xti").replaceAll("Pjo", "Qjo"); + .replaceAll("wti", "xti").replaceAll("Pjo", "Qjo") + .replaceAll("Rail", "Sail"); const result = patchSource(source); assert.equal(result.status, "unexpected-shape"); diff --git a/scripts/patch-policy.js b/scripts/patch-policy.js index a821be42..76157d3d 100644 --- a/scripts/patch-policy.js +++ b/scripts/patch-policy.js @@ -22,6 +22,7 @@ const PATCH_POLICY = [ { script: "patch-test-isolation.js", feature: "Windows 验收数据隔离" }, { script: "patch-provider-quota.js", feature: "真实 Provider 额度发送门槛" }, { script: "patch-api-key-home-navigation.js", feature: "API-key 首页会话恢复" }, + { script: "patch-thread-timeline.js", feature: "按版本能力启用官方会话时间线" }, { script: "patch-accent-presets.js", feature: "API-key 本地强调色预设" }, { script: "patch-hide-pet-menu.js", feature: "隐藏 Pet 菜单入口" }, { script: "patch-reading-layout.js", feature: "可配置正文宽度与排版" }, diff --git a/scripts/patch-thread-timeline.js b/scripts/patch-thread-timeline.js new file mode 100644 index 00000000..f9655061 --- /dev/null +++ b/scripts/patch-thread-timeline.js @@ -0,0 +1,186 @@ +#!/usr/bin/env node +/** + * 在本地 App Server 版本支持时启用官方 thread/timeline/list 路径。 + * + * 上游同时使用本地版本兼容判断和远端 readThreadTimelineEnabled 灰度开关。 + * API-key / 自定义 Provider 没有该远端开关,因而继续走逐 turn 的 + * thread/items/list 旧路径。这里只移除远端灰度条件,保留 host 与 App + * Server 版本判断;未知结构必须失败,不能把不兼容 CLI 强行切到 timeline。 + */ +const fs = require("node:fs"); +const path = require("node:path"); +const { parse } = require("acorn"); +const { relPath, SRC_DIR } = require("./patch-util"); + +const MARKER = "/* CodexRebuildThreadTimeline */"; +const PLATFORMS = ["mac-arm64", "mac-x64", "win"]; + +function propertyName(member) { + if (member?.type !== "MemberExpression") return null; + if (!member.computed && member.property.type === "Identifier") return member.property.name; + return member.property?.type === "Literal" ? member.property.value : null; +} + +function isThisMember(node, name) { + return node?.type === "MemberExpression" && node.object?.type === "ThisExpression" && + propertyName(node) === name; +} + +function isCompatibilityCall(node) { + if (node?.type !== "CallExpression" || node.arguments.length !== 2) return false; + if (!isThisMember(node.arguments[0], "hostId")) return false; + const version = node.arguments[1]; + return version?.type === "CallExpression" && version.arguments.length === 0 && + propertyName(version.callee) === "getAppServerVersion" && + isThisMember(version.callee.object, "requestClient"); +} + +function isTimelineGate(node) { + if (node?.type !== "CallExpression" || node.arguments.length !== 0 || + propertyName(node.callee) !== "readThreadTimelineEnabled") return false; + const history = node.callee.object; + return propertyName(history) === "history" && isThisMember(history.object, "settings"); +} + +function methodName(node) { + if (node?.type !== "MethodDefinition" || node.computed) return null; + return node.key?.type === "Identifier" ? node.key.name : node.key?.value; +} + +function findMethod(ast) { + const methods = []; + for (const statement of ast.body) walk(statement, (node) => { + if (methodName(node) === "supportsThreadTimeline" && node.kind === "method" && !node.static) { + methods.push(node); + } + }); + if (methods.length !== 1) { + throw new Error(`supportsThreadTimeline 方法数量异常(${methods.length})`); + } + return methods[0]; +} + +function walk(node, visit) { + if (!node || typeof node !== "object") return; + if (node.type) visit(node); + for (const [key, value] of Object.entries(node)) { + if (["type", "start", "end"].includes(key)) continue; + if (Array.isArray(value)) { + for (const child of value) walk(child, visit); + } else { + walk(value, visit); + } + } +} + +function methodReturn(method) { + const body = method.value?.body?.body; + if (!Array.isArray(body) || body.length !== 1 || body[0].type !== "ReturnStatement" || + body[0].argument == null) { + throw new Error("supportsThreadTimeline 返回结构异常"); + } + return body[0]; +} + +function count(source, value) { + return source.split(value).length - 1; +} + +function validatePatchedSource(source) { + if (count(source, MARKER) !== 1) throw new Error(`${MARKER} 数量异常`); + const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const method = findMethod(ast); + const returned = methodReturn(method); + if (!isCompatibilityCall(returned.argument)) { + throw new Error("补丁后未保留 App Server 版本兼容判断"); + } + if (!source.slice(method.start, method.end).includes(MARKER)) { + throw new Error("timeline 标记不在 supportsThreadTimeline 方法内"); + } +} + +function patchSource(source) { + if (source.includes(MARKER)) { + try { + validatePatchedSource(source); + return { status: "already-patched", source }; + } catch (error) { + return { status: "unexpected-shape", source, reason: error.message }; + } + } + if (!source.includes("supportsThreadTimeline") || + !source.includes("readThreadTimelineEnabled") || + !source.includes("getAppServerVersion")) { + return { status: "not-applicable", source }; + } + + try { + const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const method = findMethod(ast); + const returned = methodReturn(method); + const gate = returned.argument; + if (gate.type !== "LogicalExpression" || gate.operator !== "&&" || + !isCompatibilityCall(gate.left) || !isTimelineGate(gate.right)) { + throw new Error("supportsThreadTimeline 灰度门槛结构异常"); + } + const compatibility = source.slice(gate.left.start, gate.left.end); + const next = source.slice(0, gate.start) + compatibility + MARKER + source.slice(gate.end); + validatePatchedSource(next); + return { status: "patched", source: next }; + } catch (error) { + return { status: "unexpected-shape", source, reason: error.message }; + } +} + +function targetDirectories(platform) { + const requested = platform ? [platform] : PLATFORMS; + return requested.map((item) => ({ + platform: item, + path: path.join(SRC_DIR, item, "_asar", "webview", "assets"), + })).filter((item) => fs.existsSync(item.path)); +} + +function main() { + const args = process.argv.slice(2); + const platform = args.find((arg) => PLATFORMS.includes(arg)); + const check = args.includes("--check"); + const directories = targetDirectories(platform); + let failed = 0; + let patched = 0; + + for (const directory of directories) { + try { + const results = fs.readdirSync(directory.path) + .filter((name) => /^app-initial-.*\.js$/.test(name)) + .map((name) => ({ name, path: path.join(directory.path, name) })) + .map((file) => ({ ...file, source: fs.readFileSync(file.path, "utf8") })) + .map((file) => ({ file, result: patchSource(file.source) })) + .filter((item) => item.result.status !== "not-applicable"); + if (results.length !== 1) throw new Error(`timeline Bundle 数量异常(${results.length})`); + const target = results[0]; + if (target.result.status === "unexpected-shape") throw new Error(target.result.reason); + console.log(` [${directory.platform}] ${relPath(target.file.path)}`); + if (target.result.status === "already-patched") { + console.log(" [ok] 官方 thread timeline 已按版本能力启用"); + } else if (check) { + console.log(" [ok] timeline 版本门槛与远端灰度结构已核对;dry-run 未写文件"); + } else { + fs.writeFileSync(target.file.path, target.result.source, "utf8"); + patched++; + console.log(" [ok] 已移除远端灰度门槛并保留 App Server 版本兼容判断"); + } + } catch (error) { + console.error(` [x] ${directory.platform}: ${error.message}`); + failed++; + } + } + if (!directories.length) { + console.error(" [x] 缺少目标平台界面资源"); + failed++; + } + if (failed) process.exitCode = 1; + else console.log(` [ok] ${patched} platform bundle(s) patched`); +} + +if (require.main === module) main(); +module.exports = { MARKER, patchSource }; diff --git a/scripts/patch-thread-timeline.test.js b/scripts/patch-thread-timeline.test.js new file mode 100644 index 00000000..96626299 --- /dev/null +++ b/scripts/patch-thread-timeline.test.js @@ -0,0 +1,63 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { MARKER, patchSource } = require("./patch-thread-timeline"); + +function fixture() { + return [ + "function compatible(host,version){return host===`local`&&version>=150}", + "class Store{constructor(host,version,gate){this.hostId=host;this.requestClient={getAppServerVersion:()=>version};", + "this.settings={history:{readThreadTimelineEnabled:gate}}}", + "get supportsThreadTimelineProxy(){return()=>this.supportsThreadTimeline()}", + "supportsThreadTimeline(){return compatible(this.hostId,this.requestClient.getAppServerVersion())&&this.settings.history.readThreadTimelineEnabled()}}", + ].join(""); +} + +function load(source) { + return Function(`${source};return Store`)(); +} + +test("支持 timeline 的本地 CLI 不再依赖远端灰度开关", () => { + const result = patchSource(fixture()); + assert.equal(result.status, "patched"); + assert.equal(result.source.split(MARKER).length - 1, 1); + assert.equal(patchSource(result.source).status, "already-patched"); + + let gateReads = 0; + const Store = load(result.source); + const supported = new Store("local", 163, () => { gateReads++; return false; }); + const unsupported = new Store("local", 149, () => { gateReads++; return true; }); + assert.equal(supported.supportsThreadTimeline(), true); + assert.equal(unsupported.supportsThreadTimeline(), false); + assert.equal(gateReads, 0, "补丁后不应读取远端灰度开关"); +}); + +test("兼容判断变化时明确失败,不强行启用 timeline", () => { + const source = fixture().replace( + "compatible(this.hostId,this.requestClient.getAppServerVersion())", + "compatible(this.requestClient.getAppServerVersion())", + ); + const result = patchSource(source); + assert.equal(result.status, "unexpected-shape"); + assert.match(result.reason, /灰度门槛结构异常/); +}); + +test("灰度条件变化时明确失败", () => { + const source = fixture().replace("&&this.settings.history.readThreadTimelineEnabled()", "||this.settings.history.readThreadTimelineEnabled()"); + const result = patchSource(source); + assert.equal(result.status, "unexpected-shape"); + assert.match(result.reason, /灰度门槛结构异常/); +}); + +test("残缺标记明确失败", () => { + const result = patchSource(fixture() + MARKER); + assert.equal(result.status, "unexpected-shape"); + assert.match(result.reason, /版本兼容判断|方法内/); +}); + +test("无关 Bundle 不适用", () => { + const source = "class Other{supportsSomethingElse(){return true}}"; + const result = patchSource(source); + assert.equal(result.status, "not-applicable"); + assert.equal(result.source, source); +}); diff --git a/scripts/storage-governance.js b/scripts/storage-governance.js deleted file mode 100644 index da044b09..00000000 --- a/scripts/storage-governance.js +++ /dev/null @@ -1,228 +0,0 @@ -#!/usr/bin/env node -/** 本地存储治理:审计固定输出,清理可重建缓存,不触碰当前/上一版程序与正式验收记录。 */ -const fs = require("node:fs"); -const path = require("node:path"); -const os = require("node:os"); - -const testMode = process.env.CODEX_STORAGE_TEST_MODE === "1"; -const root = testMode - ? path.resolve(process.env.CODEX_STORAGE_TEST_ROOT || "") - : path.resolve(__dirname, ".."); -const tempRoot = testMode - ? path.resolve(process.env.CODEX_STORAGE_TEST_TEMP || "") - : os.tmpdir(); -const forensicsRoot = testMode - ? path.resolve(process.env.CODEX_STORAGE_TEST_FORENSICS || "") - : path.join(process.env.LOCALAPPDATA || process.env.APPDATA || os.tmpdir(), "CodexForensics"); -const cacheRoot = path.join(root, ".cache"); -const mode = process.argv[2] || "audit"; -const DAY = 24 * 60 * 60 * 1000; -const LOG_LIMIT = testMode - ? Number(process.env.CODEX_STORAGE_TEST_LOG_LIMIT || 16 * 1024 * 1024) - : 16 * 1024 * 1024; -const FATAL_LOG_LIMIT = testMode - ? Number(process.env.CODEX_STORAGE_TEST_FATAL_LOG_LIMIT || 1024 * 1024) - : 1024 * 1024; -const OWNED_TEMP_PREFIXES = [ - "codex-accent-probe-", "codex-accent-theme-", "codex-cli-policy-test-", - "codex-dmg-test-", "codex-external-overlay-test-", "codex-home-nav-", - "codex-main-test-", "codex-maintenance-smoke-", "codex-msix-test-", - "codex-nested-cli-test-", "codex-owl-integrity-test-", "codex-owl-launcher-test-", - "codex-owl-manifest-test-", "codex-owl-test-", "codex-patch-report-", - "codex-preview-smoke-", "codex-readonly-overlay-test-", "codex-sentry-test-", - "codex-rebuild-", "rebuild-download-smoke-", -]; - -if (!root || !tempRoot || !forensicsRoot || !["audit", "clean"].includes(mode)) { - throw new Error("用法:node scripts/storage-governance.js audit|clean"); -} - -function assertChild(target, parent, label) { - const resolved = path.resolve(target); - const boundary = path.resolve(parent); - if (resolved !== boundary && !resolved.startsWith(boundary + path.sep)) { - throw new Error(`${label} 越界:${resolved}`); - } - return resolved; -} - -function removeOwned(target, parent, removed) { - const resolved = assertChild(target, parent, "清理目标"); - if (resolved === path.resolve(parent)) throw new Error(`禁止删除治理根目录:${resolved}`); - if (!fs.existsSync(resolved)) return; - const item = fs.lstatSync(resolved); - if (item.isSymbolicLink()) throw new Error(`禁止删除链接目标:${resolved}`); - fs.rmSync(resolved, { recursive: item.isDirectory(), force: true }); - removed.push(resolved); -} - -function directorySize(directory) { - if (!fs.existsSync(directory)) return { files: 0, bytes: 0 }; - const pending = [directory]; - let files = 0, bytes = 0; - while (pending.length) { - const current = pending.pop(); - for (const entry of fs.readdirSync(current, { withFileTypes: true })) { - const file = path.join(current, entry.name); - if (entry.isSymbolicLink()) continue; - if (entry.isDirectory()) pending.push(file); - else { files++; bytes += fs.statSync(file).size; } - } - } - return { files, bytes }; -} - -function pruneCompletedAndExpiredParts(removed) { - if (!fs.existsSync(cacheRoot)) return; - const pending = [cacheRoot], now = Date.now(); - while (pending.length) { - const current = pending.pop(); - for (const entry of fs.readdirSync(current, { withFileTypes: true })) { - const item = path.join(current, entry.name); - if (entry.isSymbolicLink() || !entry.isDirectory()) continue; - if (entry.name.endsWith(".parts")) { - const completed = item.slice(0, -".parts".length); - if (fs.existsSync(completed) || now - fs.statSync(item).mtimeMs > 2 * DAY) { - removeOwned(item, cacheRoot, removed); - } - } else pending.push(item); - } - } -} - -function pruneRunDirectories(directory, removed, keep = 2, protectedNames = []) { - if (!fs.existsSync(directory)) return; - const protectedSet = new Set(protectedNames.map(name => name.toLowerCase())); - const directories = fs.readdirSync(directory, { withFileTypes: true }) - .filter(entry => entry.isDirectory() && !entry.isSymbolicLink() && !protectedSet.has(entry.name.toLowerCase())) - .map(entry => { - const full = path.join(directory, entry.name); - return { full, modified: fs.statSync(full).mtimeMs }; - }) - .sort((left, right) => right.modified - left.modified); - for (const entry of directories.slice(keep)) removeOwned(entry.full, directory, removed); -} - -function pruneDownloadRuns(removed, keep = 2) { - pruneRunDirectories(path.join(cacheRoot, "downloads"), removed, keep); - // 早期下载脚本和手工 gh 下载使用此目录;继续纳入同一保留规则。 - pruneRunDirectories(path.join(cacheRoot, "gh-downloads"), removed, keep); -} - -function pruneAcceptanceRuns(removed, keep = 2) { - pruneRunDirectories(path.join(cacheRoot, "acceptance"), removed, keep, ["staged-candidate"]); - pruneRunDirectories(path.join(root, "acceptance"), removed, keep, ["staged-candidate"]); -} - -function pruneOwnedTemp(removed) { - if (!fs.existsSync(tempRoot)) return; - const now = Date.now(); - for (const entry of fs.readdirSync(tempRoot, { withFileTypes: true })) { - if (!entry.isDirectory() || entry.isSymbolicLink() || !OWNED_TEMP_PREFIXES.some(prefix => entry.name.startsWith(prefix))) continue; - const full = path.join(tempRoot, entry.name); - if (now - fs.statSync(full).mtimeMs > DAY) removeOwned(full, tempRoot, removed); - } -} - -function compactFile(file, maximum, compacted) { - if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return; - const size = fs.statSync(file).size; - if (size <= maximum) return; - const buffer = Buffer.alloc(maximum); - const handle = fs.openSync(file, "r"); - try { fs.readSync(handle, buffer, 0, maximum, size - maximum); } - finally { fs.closeSync(handle); } - fs.writeFileSync(file, buffer); - compacted.push(file); -} - -function pruneForensics(removed, compacted, keep = 7) { - if (!fs.existsSync(forensicsRoot)) return; - const logs = fs.readdirSync(forensicsRoot, { withFileTypes: true }) - .filter(entry => entry.isFile() && /^forensics-\d{4}-\d{2}-\d{2}\.log$/.test(entry.name)) - .map(entry => path.join(forensicsRoot, entry.name)) - .sort((left, right) => path.basename(right).localeCompare(path.basename(left))); - for (const file of logs.slice(keep)) removeOwned(file, forensicsRoot, removed); - for (const file of logs.slice(0, keep)) compactFile(file, LOG_LIMIT, compacted); - compactFile(path.join(forensicsRoot, "chrome-debug.log"), LOG_LIMIT, compacted); - compactFile(path.join(tempRoot, "codex-forensics-fatal.log"), FATAL_LOG_LIMIT, compacted); -} - -function hasNestedLink(directory) { - const pending = [directory]; - while (pending.length) { - const current = pending.pop(); - for (const entry of fs.readdirSync(current, { withFileTypes: true })) { - if (entry.isSymbolicLink()) return true; - if (entry.isDirectory()) pending.push(path.join(current, entry.name)); - } - } - return false; -} - -function pruneInterruptedBuilds(removed) { - const buildRoot = path.join(root, "build"); - if (!fs.existsSync(buildRoot) || fs.existsSync(path.join(buildRoot, ".candidate-switch.lock"))) return; - const hasProtectedVersions = ["Codex", "previous"].every(name => - fs.existsSync(path.join(buildRoot, name, "Codex.exe"))); - const now = Date.now(); - for (const entry of fs.readdirSync(buildRoot, { withFileTypes: true })) { - if (!entry.isDirectory() || entry.isSymbolicLink()) continue; - const preparing = /^\.next-preparing-\d+$/.test(entry.name); - const retired = /^\.previous-retired-\d+$/.test(entry.name); - if (!preparing && !(retired && hasProtectedVersions)) continue; - const full = path.join(buildRoot, entry.name); - if (now - fs.statSync(full).mtimeMs <= DAY || hasNestedLink(full)) continue; - removeOwned(full, buildRoot, removed); - } -} - -function pruneGeneratedOutputs(removed) { - for (const name of ["src", "out", "patch-reports"]) { - const target = path.join(root, name); - if (fs.existsSync(target)) removeOwned(target, root, removed); - } - for (const entry of fs.readdirSync(root, { withFileTypes: true })) { - if (!entry.isDirectory() || entry.isSymbolicLink() || !/^out-.+/.test(entry.name)) continue; - removeOwned(path.join(root, entry.name), root, removed); - } -} - -function audit() { - const paths = [ - cacheRoot, - path.join(root, "build"), - path.join(root, "src"), - path.join(root, "out"), - path.join(root, "patch-reports"), - path.join(root, "artifacts"), - path.join(root, "acceptance"), - path.join(root, "release", "archive"), - forensicsRoot, - ]; - return paths.filter(file => fs.existsSync(file)).map(file => { - const size = directorySize(file); - return { path: file, files: size.files, mib: Number((size.bytes / 1048576).toFixed(1)) }; - }); -} - -const removed = [], compacted = []; -if (mode === "clean") { - pruneCompletedAndExpiredParts(removed); - pruneDownloadRuns(removed); - pruneAcceptanceRuns(removed); - pruneOwnedTemp(removed); - pruneForensics(removed, compacted); - pruneInterruptedBuilds(removed); - pruneGeneratedOutputs(removed); -} -console.log(JSON.stringify({ - mode, - policy: { - downloadRuns: 2, acceptanceRuns: 2, incompletePartsDays: 2, - forensicsLogs: 7, forensicsLogMiB: 16, fatalLogMiB: 1, - ownedTempHours: 24, interruptedBuildHours: 24, - generatedOutputs: ["src", "out", "out-*", "patch-reports"], - }, - removed, compacted, usage: audit(), -}, null, 2)); From dddcfe3be801c43f74ca77497df3dfc6459d30ac Mon Sep 17 00:00:00 2001 From: carptopus Date: Sun, 18 Oct 2026 04:15:01 +0800 Subject: [PATCH 12/51] fix: reduce MCP refreshes and gate remote control --- README.md | 2 + scripts/STATSIG_GATES.md | 4 +- scripts/frontend-source-smoke.js | 11 +- scripts/patch-mcp-status-refresh.js | 273 +++++++++++++++++++++++ scripts/patch-mcp-status-refresh.test.js | 100 +++++++++ scripts/patch-policy.js | 3 +- scripts/patch-remote-control.js | 18 +- scripts/patch-remote-control.test.js | 33 +++ 8 files changed, 431 insertions(+), 13 deletions(-) create mode 100644 scripts/patch-mcp-status-refresh.js create mode 100644 scripts/patch-mcp-status-refresh.test.js create mode 100644 scripts/patch-remote-control.test.js diff --git a/README.md b/README.md index 93d9fb50..4347850c 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,8 @@ npm run build:all - `patch-provider-quota.js` 按任务实际 Provider 和明确的 `base_url` 判断发送门槛,避免 ChatGPT 额度状态误阻断第三方 Provider,同时保留官方、云任务及第三方真实错误。 - `patch-api-key-home-navigation.js` 补齐 API-key 模式的当前会话导航记录,并让功能导航栏的首页重选分支使用该记录恢复最近会话,而不是直达空首页;ChatGPT、无认证及其他认证方式保持原有条件。 - `patch-thread-timeline.js` 在当前 host 与 App Server 版本支持时启用官方 `thread/timeline/list` 历史路径,移除 API-key / 自定义 Provider 无法获得的远端灰度条件;版本兼容判断仍由官方逻辑负责。 +- `patch-mcp-status-refresh.js` 将短时间内的 MCP 启动状态通知合并为一次轻量目录刷新;Full 目录只标记为 stale、不在后台立即重拉,详细 MCP 页面后续仍按官方 Full 查询取得资源与模板。 +- `patch-remote-control.js` 只开放 Connections 设置入口;需要 ChatGPT 账户与 workspace routing 的 Remote Control 数据链继续遵守官方 gate,避免 API-key 模式反复建立无凭据的 Durable 连接。 - `patch-accent-presets.js` 允许没有 ChatGPT 账户主题的 API-key / 自定义 Provider 在本地选择强调色,并复用官方完整预设渲染消息气泡等界面变量;账户主题仍在加载时保持禁用,账户可用时继续使用官方同步。 - `patch-hide-pet-menu.js` 只隐藏账户菜单中的 Pet / Mini 入口,保留浮动面板实现、状态和全局快捷键。 - `patch-reading-layout.js` 在外观主题卡片中加入 50%–100%、步进 5% 的正文宽度滑杆,并同步代码块、表格和输入区宽度,扩宽适用对话框;百分比不低于官方宽度,Markdown 粗体颜色可跟随正文、强调色或使用自定义颜色。 diff --git a/scripts/STATSIG_GATES.md b/scripts/STATSIG_GATES.md index ba92c9b1..e8fc7799 100644 --- a/scripts/STATSIG_GATES.md +++ b/scripts/STATSIG_GATES.md @@ -85,14 +85,14 @@ gate 2307253562 → codex_git_commit | `patch-devtools.js` | `allowInspectElement` / `devTools` | 属性值 → `!0` | | `patch-copyright.js` | About Dialog / setAboutPanelOptions 或自定义 HTML | 替换版权文本 | | `patch-process-polyfill.js` | Windows `process` polyfill | 注入 `process.env`/`process.platform` | -| `patch-remote-control.js` | gate `4114442250` / `1042620455` | 开启 Connections 入口与 Remote Control 数据加载;保留服务端权限状态判断 | +| `patch-remote-control.js` | gate `4114442250` | 开启 Connections 入口;Remote Control 数据加载 gate 保持上游判断,避免 API-key 模式建立无凭据的 durable 连接 | ### Remote Control 已确认 gate | ID | 功能 | 影响范围 | |---|---|---| | `4114442250` | Remote Connections 可见性 | Settings 中的 Connections 项、相关远程标识 | -| `1042620455` | Remote Control / Slingshot | 手机控制分区、远程设备加载、主进程 gate bridge | +| `1042620455` | Remote Control / Slingshot | 手机控制分区、远程设备加载、主进程 gate bridge;不得强制开启 | ## 备注 diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index 145e8cae..c1988ae9 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -92,6 +92,15 @@ function verifyFrontendSource(assets) { const timelineSource = fs.readFileSync(path.join(assets, timelineEntries[0]), "utf8"); assert.match(timelineSource, /supportsThreadTimeline\(\)\{return\s*[A-Za-z_$][\w$]*\(this\.hostId,this\.requestClient\.getAppServerVersion\(\)\)\/\* CodexRebuildThreadTimeline \*\//); + const mcpRefreshEntries = files.filter(name => /^app-initial-/.test(name) + && fs.readFileSync(path.join(assets, name), "utf8").includes("CodexRebuildMcpStatusRefresh")); + assert.equal(mcpRefreshEntries.length, 1); + const mcpRefreshSource = fs.readFileSync(path.join(assets, mcpRefreshEntries[0]), "utf8"); + assert.match(mcpRefreshSource, /toolsAndAuthOnly/); + assert.match(mcpRefreshSource, /mention-discovery/); + assert.match(mcpRefreshSource, /refetchType:`none`/); + assert.match(mcpRefreshSource, /===`full`/); + assert.match(mcpRefreshSource, /CodexRebuildMcpStatusRefresh \*\/\)\},250\)/); const serviceTierEntries = files.filter(name => /^app-initial-/.test(name) && fs.readFileSync(path.join(assets, name), "utf8").includes("CodexRebuildServiceTierApiKeyRequest")); assert.equal(serviceTierEntries.length, 1); @@ -117,7 +126,7 @@ function verifyFrontendSource(assets) { assert.equal(shared.length, 1); const dialogs = fs.readFileSync(path.join(assets, shared[0]), "utf8"); assert.match(dialogs, /codex-rebuild-dialog-editor h-\[720px\] max-w-full max-h-full/); - return { passed: true, quotaScenarios: results, apiKeyHomeNavigation: true, threadTimelineEnabled: true, apiKeyServiceTiers: true, nativeAppearanceRow: true, nativeAccentThemePipeline: true, dialogHeightPreserved: true }; + return { passed: true, quotaScenarios: results, apiKeyHomeNavigation: true, threadTimelineEnabled: true, mcpStatusRefreshGoverned: true, apiKeyServiceTiers: true, nativeAppearanceRow: true, nativeAccentThemePipeline: true, dialogHeightPreserved: true }; } if (require.main === module) console.log(JSON.stringify(verifyFrontendSource(path.resolve(process.argv[2] || "src/win/_asar/webview/assets")), null, 2)); module.exports = { verifyFrontendSource }; diff --git a/scripts/patch-mcp-status-refresh.js b/scripts/patch-mcp-status-refresh.js new file mode 100644 index 00000000..deccee43 --- /dev/null +++ b/scripts/patch-mcp-status-refresh.js @@ -0,0 +1,273 @@ +#!/usr/bin/env node +/** + * 合并 MCP 启动状态通知带来的目录刷新,并避免后台通知立即重拉 Full 目录。 + * + * 上游已经提供 toolsAndAuthOnly 查询和请求级 coalescing;本补丁不改变 Full + * 查询的内容,只把短时间内的启动通知合并为一次轻量刷新,并把 Full 查询 + * 标记为 stale、但不在后台立即 refetch。目标结构漂移时必须失败。 + */ +const fs = require("node:fs"); +const path = require("node:path"); +const { parse } = require("acorn"); +const { relPath, SRC_DIR } = require("./patch-util"); + +const MARKER = "/* CodexRebuildMcpStatusRefresh */"; +const REFRESH_DELAY_MS = 250; +const PLATFORMS = ["mac-arm64", "mac-x64", "win"]; + +function walk(node, visit) { + if (!node || typeof node !== "object") return; + if (node.type) visit(node); + for (const [key, value] of Object.entries(node)) { + if (["type", "start", "end"].includes(key)) continue; + if (Array.isArray(value)) value.forEach((child) => walk(child, visit)); + else if (value?.type) walk(value, visit); + } +} + +function staticValue(node) { + if (node?.type === "Literal") return node.value; + if (node?.type === "TemplateLiteral" && node.expressions.length === 0) { + return node.quasis[0].value.cooked; + } + return undefined; +} + +function propertyName(member) { + if (member?.type !== "MemberExpression") return null; + if (!member.computed && member.property.type === "Identifier") return member.property.name; + return staticValue(member.property); +} + +function objectProperty(object, name) { + return object?.type === "ObjectExpression" + ? object.properties.find((item) => item.type === "Property" && propertyName({ + type: "MemberExpression", + computed: item.computed, + property: item.key, + }) === name) + : undefined; +} + +function targetCase(ast) { + const matches = []; + walk(ast, (node) => { + if (node.type === "SwitchCase" && staticValue(node.test) === "mcpServer/startupStatus/updated" && + node.consequent[0]?.type === "ExpressionStatement") { + matches.push(node); + } + }); + if (matches.length !== 1) { + throw new Error(`MCP 启动状态刷新分支数量异常(${matches.length})`); + } + const branch = matches[0]; + if (branch.consequent.length !== 2 || branch.consequent[1].type !== "BreakStatement") { + throw new Error("MCP 启动状态刷新分支结构异常"); + } + return branch; +} + +function analyzeOriginal(source, branch) { + const expression = branch.consequent[0].expression; + if (expression.type !== "SequenceExpression" || expression.expressions.length !== 2) { + throw new Error("MCP 启动状态刷新表达式结构异常"); + } + const [readyRefresh, scopedRefresh] = expression.expressions; + if (readyRefresh.type !== "ConditionalExpression" || scopedRefresh.type !== "ConditionalExpression") { + throw new Error("MCP 启动状态刷新条件结构异常"); + } + + const readyText = source.slice(readyRefresh.test.start, readyRefresh.test.end); + const readyMatch = readyText.match(/^([A-Za-z_$][\w$]*)\.params\.status===`ready`&&\1\.params\.threadId!=null$/); + if (!readyMatch) throw new Error("MCP thread ready 条件结构异常"); + const notification = readyMatch[1]; + const globalText = source.slice(scopedRefresh.test.start, scopedRefresh.test.end); + if (globalText !== `${notification}.params.threadId==null&&${notification}.params.status!==\`starting\``) { + throw new Error("MCP global 状态条件结构异常"); + } + + const scheduled = readyRefresh.consequent; + if (scheduled.type !== "AssignmentExpression" || scheduled.operator !== "??=" || + scheduled.left.type !== "Identifier" || scheduled.right.type !== "CallExpression" || + scheduled.right.callee.type !== "Identifier" || scheduled.right.callee.name !== "setTimeout" || + scheduled.right.arguments.length !== 2 || staticValue(scheduled.right.arguments[1]) !== 0) { + throw new Error("MCP 轻量刷新定时器结构异常"); + } + const timer = scheduled.left.name; + const callback = scheduled.right.arguments[0]; + const bodyExpression = callback?.type === "ArrowFunctionExpression" && + callback.body.type === "BlockStatement" && callback.body.body.length === 1 && + callback.body.body[0].type === "ExpressionStatement" + ? callback.body.body[0].expression + : null; + if (bodyExpression?.type !== "SequenceExpression" || bodyExpression.expressions.length !== 2) { + throw new Error("MCP 轻量刷新回调结构异常"); + } + const reset = bodyExpression.expressions[0]; + const guarded = bodyExpression.expressions[1]; + if (reset.type !== "AssignmentExpression" || reset.left?.name !== timer || + guarded.type !== "LogicalExpression" || guarded.operator !== "&&" || + guarded.left?.type !== "LogicalExpression" || guarded.left.operator !== "&&" || + guarded.left.left?.type !== "Identifier" || guarded.right?.type !== "SequenceExpression" || + guarded.right.expressions.length !== 2) { + throw new Error("MCP 轻量刷新守卫结构异常"); + } + const active = guarded.left.left.name; + const guard = source.slice(guarded.left.right.start, guarded.left.right.end); + const [toolsCall, mentionCall] = guarded.right.expressions; + const toolsText = source.slice(toolsCall.start, toolsCall.end); + const mentionText = source.slice(mentionCall.start, mentionCall.end); + if (!toolsText.includes("toolsAndAuthOnly") || !mentionText.includes("mention-discovery")) { + throw new Error("MCP 轻量目录刷新调用结构异常"); + } + + const queryClient = source.slice(toolsCall.arguments[0].start, toolsCall.arguments[0].end); + if (!queryClient.endsWith(".queryClient")) throw new Error("MCP queryClient 结构异常"); + const queryKey = objectProperty(toolsCall.arguments[1], "queryKey")?.value; + if (queryKey?.type !== "ArrayExpression" || queryKey.elements.length !== 3 || + queryKey.elements[0]?.type !== "SpreadElement" || + queryKey.elements[0].argument.type !== "Identifier" || + queryKey.elements[1]?.type !== "Identifier" || staticValue(queryKey.elements[2]) !== "toolsAndAuthOnly") { + throw new Error("MCP toolsAndAuthOnly query key 结构异常"); + } + const queryBase = queryKey.elements[0].argument.name; + const host = queryKey.elements[1].name; + + const installedText = source.slice(readyRefresh.alternate.start, readyRefresh.alternate.end); + if (!installedText.includes("installed-inventory") || !installedText.includes("installed")) { + throw new Error("MCP installed inventory 刷新结构异常"); + } + const blanket = source.slice(scopedRefresh.consequent.start, scopedRefresh.consequent.end); + if (!blanket.includes(`queryKey:[...${queryBase},${host}]`) || blanket.includes("refetchType")) { + throw new Error("MCP Full blanket 刷新结构异常"); + } + const threadRefresh = source.slice(scopedRefresh.alternate.start, scopedRefresh.alternate.end); + if (!threadRefresh.includes(`${notification}.params.threadId`) || !threadRefresh.includes("`thread`")) { + throw new Error("MCP thread 范围刷新结构异常"); + } + + return { + expression, + notification, + timer, + active, + guard, + toolsText, + mentionText, + queryClient, + queryBase, + host, + readyText, + globalText, + installedText, + threadRefresh, + }; +} + +function count(source, value) { + return source.split(value).length - 1; +} + +function validatePatchedSource(source) { + if (count(source, MARKER) !== 1) throw new Error(`${MARKER} 数量异常`); + const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const branch = targetCase(ast); + const branchText = source.slice(branch.start, branch.end); + if (!branchText.includes(MARKER) || !branchText.includes(`},${REFRESH_DELAY_MS})`)) { + throw new Error("MCP 刷新合并标记或时间窗口缺失"); + } + if (!branchText.includes("toolsAndAuthOnly") || !branchText.includes("mention-discovery") || + !branchText.includes("refetchType:`none`") || !branchText.includes("===`full`")) { + throw new Error("MCP 轻量刷新或 Full stale 规则缺失"); + } + const calls = []; + walk(branch, (node) => { + if (node.type === "CallExpression" && propertyName(node.callee) === "invalidateQueries") calls.push(node); + }); + const staleOnly = calls.filter((call) => { + const options = call.arguments[0]; + return staticValue(objectProperty(options, "refetchType")?.value) === "none"; + }); + if (staleOnly.length !== 1) throw new Error("MCP Full stale-only 调用数量异常"); +} + +function patchSource(source) { + if (source.includes(MARKER)) { + try { + validatePatchedSource(source); + return { status: "already-patched", source }; + } catch (error) { + return { status: "unexpected-shape", source, reason: error.message }; + } + } + if (!source.includes("mcpServer/startupStatus/updated") || + !source.includes("toolsAndAuthOnly") || !source.includes("mention-discovery")) { + return { status: "not-applicable", source }; + } + try { + const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const branch = targetCase(ast); + const shape = analyzeOriginal(source, branch); + const fullStale = `${shape.queryClient}.invalidateQueries({queryKey:[...${shape.queryBase},${shape.host}],predicate:({queryKey:e})=>e.length===${shape.queryBase}.length+2&&e[${shape.queryBase}.length+1]===\`full\`,refetchType:\`none\`})${MARKER}`; + const schedule = `${shape.timer}??=setTimeout(()=>{${shape.timer}=void 0,${shape.active}&&(${shape.guard})&&(${shape.toolsText},${shape.mentionText},${fullStale})},${REFRESH_DELAY_MS})`; + const globalOnly = `${shape.notification}.params.threadId==null&&(${shape.installedText})`; + const replacement = `(${shape.readyText}||${shape.globalText})&&(${schedule}),${globalOnly},${shape.threadRefresh}`; + const next = source.slice(0, shape.expression.start) + replacement + source.slice(shape.expression.end); + validatePatchedSource(next); + return { status: "patched", source: next }; + } catch (error) { + return { status: "unexpected-shape", source, reason: error.message }; + } +} + +function targetDirectories(platform) { + const requested = platform ? [platform] : PLATFORMS; + return requested.map((item) => ({ + platform: item, + path: path.join(SRC_DIR, item, "_asar", "webview", "assets"), + })).filter((item) => fs.existsSync(item.path)); +} + +function main() { + const args = process.argv.slice(2); + const platform = args.find((arg) => PLATFORMS.includes(arg)); + const check = args.includes("--check"); + const directories = targetDirectories(platform); + let failed = 0; + let patched = 0; + for (const directory of directories) { + try { + const results = fs.readdirSync(directory.path) + .filter((name) => /^app-initial-.*\.js$/.test(name)) + .map((name) => ({ name, path: path.join(directory.path, name) })) + .map((file) => ({ ...file, source: fs.readFileSync(file.path, "utf8") })) + .map((file) => ({ file, result: patchSource(file.source) })) + .filter((item) => item.result.status !== "not-applicable"); + if (results.length !== 1) throw new Error(`MCP 状态 Bundle 数量异常(${results.length})`); + const target = results[0]; + if (target.result.status === "unexpected-shape") throw new Error(target.result.reason); + console.log(` [${directory.platform}] ${relPath(target.file.path)}`); + if (target.result.status === "already-patched") { + console.log(" [ok] MCP 启动状态刷新已治理"); + } else if (check) { + console.log(" [ok] MCP 启动状态刷新结构已核对;dry-run 未写文件"); + } else { + fs.writeFileSync(target.file.path, target.result.source, "utf8"); + patched++; + console.log(" [ok] 已合并轻量刷新并阻止后台 Full 目录立即重拉"); + } + } catch (error) { + console.error(` [x] ${directory.platform}: ${error.message}`); + failed++; + } + } + if (!directories.length) { + console.error(" [x] 缺少目标平台界面资源"); + failed++; + } + if (failed) process.exitCode = 1; + else console.log(` [ok] ${patched} platform bundle(s) patched`); +} + +if (require.main === module) main(); +module.exports = { MARKER, REFRESH_DELAY_MS, patchSource }; diff --git a/scripts/patch-mcp-status-refresh.test.js b/scripts/patch-mcp-status-refresh.test.js new file mode 100644 index 00000000..705275bc --- /dev/null +++ b/scripts/patch-mcp-status-refresh.test.js @@ -0,0 +1,100 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { MARKER, REFRESH_DELAY_MS, patchSource } = require("./patch-mcp-status-refresh"); + +function fixture() { + return "function createHandler(e,t,r){let i=!0,C,S=new Set,x;return n=>{switch(n.method){case`mcpServer/startupStatus/updated`:n.params.status===`ready`&&n.params.threadId!=null?C??=setTimeout(()=>{C=void 0,i&&(r?.()??!0)&&(GE(e.queryClient,{queryKey:[...eC,t,`toolsAndAuthOnly`],exact:!0},{cancelRefetch:!1}),GE(e.queryClient,{queryKey:[...eC,t,`mention-discovery`],refetchType:`active`},{cancelRefetch:!1}))},0):n.params.status===`ready`&&GE(e.queryClient,{queryKey:WT,predicate:({queryKey:e})=>(e[1]===`installed-inventory`||e[1]===`installed`&&K_(n.params.name))&&e[2]===t},{cancelRefetch:!1}),n.params.threadId==null&&n.params.status!==`starting`?GE(e.queryClient,{queryKey:[...eC,t]},{cancelRefetch:!1}):n.params.threadId!=null&&n.params.status!==`starting`&&(S.add(n.params.threadId),x??=setTimeout(()=>{x=void 0;let n=S;S=new Set,i&&(r?.()??!0)&&e.queryClient.invalidateQueries({queryKey:[...eC,t,`thread`],predicate:({queryKey:e})=>{let t=e[eC.length+2];return typeof t==`string`&&n.has(t)}})},0));break;default:break}}}"; +} + +function load(source, calls, timers) { + const GE = (client, filters, options) => calls.push({ kind: "GE", client, filters, options }); + const setTimeout = (callback, delay) => { + const timer = { callback, delay }; + timers.push(timer); + return timer; + }; + const factory = Function("GE", "eC", "WT", "K_", "setTimeout", `${source};return createHandler`)( + GE, + ["mcp"], + ["plugins"], + () => true, + setTimeout, + ); + const queryClient = { + invalidateQueries(filters) { + calls.push({ kind: "invalidate", filters }); + }, + }; + return factory({ queryClient }, "local", () => true); +} + +test("启动通知在短窗口内只刷新一次轻量目录并让 Full 仅失效", () => { + const result = patchSource(fixture()); + assert.equal(result.status, "patched"); + assert.equal(result.source.split(MARKER).length - 1, 1); + assert.equal(patchSource(result.source).status, "already-patched"); + + const calls = []; + const timers = []; + const listener = load(result.source, calls, timers); + const notification = { method: "mcpServer/startupStatus/updated", params: { name: "server-a", status: "ready", threadId: null } }; + listener(notification); + listener(notification); + + assert.equal(timers.length, 1, "同一窗口内的 global 通知应共享一个轻量刷新定时器"); + assert.equal(timers[0].delay, REFRESH_DELAY_MS); + assert.equal(calls.filter((item) => item.filters?.queryKey === undefined || item.filters.queryKey?.[0] === "plugins").length, 2, + "installed inventory 刷新保持上游行为,不属于 Full MCP 目录"); + + timers.shift().callback(); + const tools = calls.filter((item) => item.filters?.queryKey?.at(-1) === "toolsAndAuthOnly"); + const mentions = calls.filter((item) => item.filters?.queryKey?.includes("mention-discovery")); + const full = calls.filter((item) => item.kind === "invalidate" && item.filters?.refetchType === "none"); + assert.equal(tools.length, 1); + assert.equal(mentions.length, 1); + assert.equal(full.length, 1); + assert.deepEqual(full[0].filters.queryKey, ["mcp", "local"]); + assert.equal(full[0].filters.predicate({ queryKey: ["mcp", "local", "full"] }), true); + assert.equal(full[0].filters.predicate({ queryKey: ["mcp", "local", "thread", "thread-a", "full"] }), false); + assert.equal(calls.some((item) => item.filters?.queryKey?.length === 2 && item.options?.cancelRefetch === false), false, + "不能保留按 host 全量立即 refetch 的 blanket invalidation"); +}); + +test("thread 范围通知仍只失效对应 thread,并与轻量刷新分离", () => { + const result = patchSource(fixture()); + const calls = []; + const timers = []; + const listener = load(result.source, calls, timers); + listener({ method: "mcpServer/startupStatus/updated", params: { name: "server-a", status: "ready", threadId: "thread-a" } }); + + assert.deepEqual(timers.map((item) => item.delay).sort((a, b) => a - b), [0, REFRESH_DELAY_MS]); + for (const timer of [...timers].sort((a, b) => a.delay - b.delay)) timer.callback(); + const threadInvalidation = calls.find((item) => item.kind === "invalidate" && item.filters?.queryKey?.includes("thread")); + assert.ok(threadInvalidation); + assert.equal(threadInvalidation.filters.predicate({ queryKey: ["mcp", "local", "thread", "thread-a", "full"] }), true); + assert.equal(threadInvalidation.filters.predicate({ queryKey: ["mcp", "local", "thread", "thread-b", "full"] }), false); +}); + +test("上游刷新结构漂移时明确失败", () => { + const changed = fixture().replace( + "GE(e.queryClient,{queryKey:[...eC,t]},{cancelRefetch:!1})", + "GE(e.queryClient,{queryKey:[...eC,t],refetchType:`active`},{cancelRefetch:!1})", + ); + const result = patchSource(changed); + assert.equal(result.status, "unexpected-shape"); + assert.match(result.reason, /blanket/); +}); + +test("残缺标记明确失败", () => { + const result = patchSource(fixture() + MARKER); + assert.equal(result.status, "unexpected-shape"); + assert.match(result.reason, /数量异常|缺失|分支/); +}); + +test("无关 Bundle 不适用", () => { + const source = "function unrelated(){return true}"; + const result = patchSource(source); + assert.equal(result.status, "not-applicable"); + assert.equal(result.source, source); +}); diff --git a/scripts/patch-policy.js b/scripts/patch-policy.js index 76157d3d..30d8b77a 100644 --- a/scripts/patch-policy.js +++ b/scripts/patch-policy.js @@ -23,6 +23,7 @@ const PATCH_POLICY = [ { script: "patch-provider-quota.js", feature: "真实 Provider 额度发送门槛" }, { script: "patch-api-key-home-navigation.js", feature: "API-key 首页会话恢复" }, { script: "patch-thread-timeline.js", feature: "按版本能力启用官方会话时间线" }, + { script: "patch-mcp-status-refresh.js", feature: "MCP 启动状态刷新治理" }, { script: "patch-accent-presets.js", feature: "API-key 本地强调色预设" }, { script: "patch-hide-pet-menu.js", feature: "隐藏 Pet 菜单入口" }, { script: "patch-reading-layout.js", feature: "可配置正文宽度与排版" }, @@ -31,7 +32,7 @@ const PATCH_POLICY = [ { script: "patch-thread-file-manager-action.js", feature: "会话文件管理器入口" }, { script: "patch-browser-auth.js", feature: "API-key 浏览器认证" }, { script: "patch-plugin-auth.js", feature: "插件认证与功能开关" }, - { script: "patch-remote-control.js", feature: "远程控制" }, + { script: "patch-remote-control.js", feature: "Connections 入口" }, { script: "patch-composer-workspace-root.js", feature: "会话工作目录传递" }, { script: "patch-updater.js", feature: "禁用上游自动更新" }, { script: "patch-archive-delete.js", feature: "跨 Provider 归档列表与归档删除" }, diff --git a/scripts/patch-remote-control.js b/scripts/patch-remote-control.js index 9a0e6aae..9647a526 100644 --- a/scripts/patch-remote-control.js +++ b/scripts/patch-remote-control.js @@ -1,14 +1,13 @@ #!/usr/bin/env node /** - * 构建后补丁:开启“连接 / 手机远程控制”入口。 + * 构建后补丁:开启“连接”入口。 * - * 上游当前使用两个 Statsig gate 控制入口: - * - 4114442250:显示 Connections 设置项与路由 - * - 1042620455:启用 Remote Control(Slingshot)数据加载与设置分区 + * 上游当前使用 4114442250 控制 Connections 设置项与路由。 * - * 这里只绕过客户端 rollout gate,不修改服务端返回的 available、 - * accessRequired、authRequired 等能力状态。这样账号没有服务端权限时, - * 仍会保留真实错误,而不是显示一个必然失败的伪可用状态。 + * 1042620455 会启动需要 ChatGPT 账户与 workspace routing 的 Remote Control + *(Slingshot)数据链。API-key Provider 没有这类账户状态;强制开启会反复 + * 建立 durable 连接并触发“无法加载组织设置”。因此该 gate 保持上游判断, + * 这里只开放 Connections 入口,不伪造 Remote Control 的账户能力。 */ const fs = require("fs"); const path = require("path"); @@ -17,7 +16,6 @@ const { SRC_DIR, relPath } = require("./patch-util"); const GATES = new Map([ ["4114442250", "remote_connections_visibility"], - ["1042620455", "remote_control_slingshot"], ]); function walk(node, visitor) { @@ -160,4 +158,6 @@ function main() { ); } -main(); +if (require.main === module) main(); + +module.exports = { GATES, findPatches, marker }; diff --git a/scripts/patch-remote-control.test.js b/scripts/patch-remote-control.test.js new file mode 100644 index 00000000..9df31412 --- /dev/null +++ b/scripts/patch-remote-control.test.js @@ -0,0 +1,33 @@ +const assert = require("node:assert/strict"); +const test = require("node:test"); + +const { findPatches, marker } = require("./patch-remote-control"); + +function applyPatches(source, patches) { + let result = source; + for (const patch of [...patches].sort((a, b) => b.start - a.start)) { + result = result.slice(0, patch.start) + patch.replacement + result.slice(patch.end); + } + return result; +} + +test("only opens Connections visibility and keeps Remote Control on its upstream gate", () => { + const source = [ + "function connections(){return checkGate(`4114442250`)}", + "function remoteControl(){return checkGate(`1042620455`)}", + ].join("\n"); + + const patches = findPatches(source); + assert.equal(patches.length, 1); + assert.equal(patches[0].gateId, "4114442250"); + + const result = applyPatches(source, patches); + assert.match(result, new RegExp(marker("4114442250").replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))); + assert.match(result, /remoteControl\(\)\{return checkGate\(`1042620455`\)\}/); + assert.doesNotMatch(result, /codex-remote-gate:1042620455/); + assert.equal(findPatches(result).length, 0); +}); + +test("does not patch a bundle that only contains the Remote Control data gate", () => { + assert.deepEqual(findPatches("const enabled=checkGate(`1042620455`);"), []); +}); From 35cb9573ae8667b8f11bbdf8832a6ea6eda9805c Mon Sep 17 00:00:00 2001 From: carptopus Date: Sun, 18 Oct 2026 04:44:19 +0800 Subject: [PATCH 13/51] fix: preserve state-based home sessions --- README.md | 2 +- scripts/frontend-source-smoke.js | 4 +- scripts/patch-api-key-home-navigation.js | 72 ++++++++++++++++--- scripts/patch-api-key-home-navigation.test.js | 69 ++++++++++++++++-- 4 files changed, 130 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 4347850c..76b41317 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ npm run build:all - `patch-browser-auth.js` 兼容 API-key 登录:旧版在 ChatGPT 身份读取失败时仅关闭可选 request-header 并继续本地浏览器通道;新版原生托管请求头不再依赖 ChatGPT 身份时验证该完整链路并保持原样,不会把 API key 伪装或发送为 ChatGPT token。 - `patch-fast-mode.js` 为 API-key / 自定义 Provider 补齐新版 `serviceTierAccess`:跳过不可用的 ChatGPT 账户权限查询,但仍由当前模型返回的 `serviceTierOptions` 决定是否显示和发送 Fast / Ultrafast 档位。 - `patch-provider-quota.js` 按任务实际 Provider 和明确的 `base_url` 判断发送门槛,避免 ChatGPT 额度状态误阻断第三方 Provider,同时保留官方、云任务及第三方真实错误。 -- `patch-api-key-home-navigation.js` 补齐 API-key 模式的当前会话导航记录,并让功能导航栏的首页重选分支使用该记录恢复最近会话,而不是直达空首页;ChatGPT、无认证及其他认证方式保持原有条件。 +- `patch-api-key-home-navigation.js` 补齐 API-key 模式的当前会话导航记录,并识别新版保存在路由 state 中的会话位置;当前会话点击首页保持不变,从设置等页面点击首页则恢复最近会话,避免直达空首页。ChatGPT、无认证及其他认证方式保持原有条件。 - `patch-thread-timeline.js` 在当前 host 与 App Server 版本支持时启用官方 `thread/timeline/list` 历史路径,移除 API-key / 自定义 Provider 无法获得的远端灰度条件;版本兼容判断仍由官方逻辑负责。 - `patch-mcp-status-refresh.js` 将短时间内的 MCP 启动状态通知合并为一次轻量目录刷新;Full 目录只标记为 stale、不在后台立即重拉,详细 MCP 页面后续仍按官方 Full 查询取得资源与模板。 - `patch-remote-control.js` 只开放 Connections 设置入口;需要 ChatGPT 账户与 workspace routing 的 Remote Control 数据链继续遵守官方 gate,避免 API-key 模式反复建立无凭据的 Durable 连接。 diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index c1988ae9..46d9a03c 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -83,7 +83,9 @@ function verifyFrontendSource(assets) { assert.match(navigationSource, /\|\|\/\* Codex:API-key 首页恢复写入。 \*\/[A-Za-z_$][\w$]*===`apikey`/); assert.match(navigationSource, /authMethod:__codexAuthMethod/); assert.match(navigationSource, - /\/\* Codex:API-key 当前首页保持会话。 \*\/__codexAuthMethod===`apikey`&&[A-Za-z_$][\w$]*!=null&&\([A-Za-z_$][\w$]*\.pathname\.startsWith\(`\/local\/`\)\|\|[A-Za-z_$][\w$]*\.pathname\.startsWith\(`\/remote\/`\)\)/); + /\/\* Codex:API-key 当前首页保持会话。 \*\/__codexAuthMethod===`apikey`&&([A-Za-z_$][\w$]*)!=null&&\(\1\.pathname\.startsWith\(`\/local\/`\)\|\|\1\.pathname\.startsWith\(`\/remote\/`\)\|\|\1\.state\?\.sidebarThreadLocationId!=null\)/); + assert.match(navigationSource, + /\/\* Codex:API-key 首页保持状态会话。 \*\/[A-Za-z_$][\w$]*\.authMethod===`apikey`&&[A-Za-z_$][\w$]*\?\.state\?\.sidebarThreadLocationId!=null/); assert.match(navigationSource, /\/\* Codex:API-key 首页恢复最近会话。 \*\/[A-Za-z_$][\w$]*\.authMethod!==`apikey`/); const timelineEntries = files.filter(name => /^app-initial-/.test(name) diff --git a/scripts/patch-api-key-home-navigation.js b/scripts/patch-api-key-home-navigation.js index 783176f2..009b89fe 100644 --- a/scripts/patch-api-key-home-navigation.js +++ b/scripts/patch-api-key-home-navigation.js @@ -6,7 +6,7 @@ * 新导航模式和 ChatGPT capability 限制,导致 API-key 下从不写入。 * 同时,侧栏房子按钮使用独立的 openHome 分支直接导航到 `/`,不会进入 * 上述首页恢复函数。这里只给该按钮传入真实 authMethod,并在 API-key 已经 - * 位于 `/local/` 或 `/remote/` 时短路。新版功能导航栏还有一条 + * 位于 `/local/`、`/remote/`,或根路径仍携带会话位置状态时短路。新版功能导航栏还有一条 * “当前已经选中首页时再次点击”的直达 `/` 分支;API-key 必须跳过该分支, * 交回官方首页位置记录器,才能从设置等页面恢复最近会话。 * 补丁不开启 ChatGPT 账户能力,也不改变其他认证方式。 @@ -19,6 +19,7 @@ const { SRC_DIR, relPath } = require("./patch-util"); const MARKER = "/* Codex:API-key 首页恢复写入。 */"; const CURRENT_HOME_MARKER = "/* Codex:API-key 当前首页保持会话。 */"; const HOME_RESELECT_MARKER = "/* Codex:API-key 首页恢复最近会话。 */"; +const HOME_STATE_MARKER = "/* Codex:API-key 首页保持状态会话。 */"; const PLATFORMS = ["mac-arm64", "mac-x64", "win", "unix"]; function walk(node, visit, root = node, ownScope = false) { @@ -223,8 +224,19 @@ function findOpenHomeRoute(ast, source) { } } const caller = unique(callers, "房子按钮调用点"); - const markerPresent = source.slice(route.fn.start, route.fn.end).includes(CURRENT_HOME_MARKER); - return { ...route, caller, markerPresent }; + const markedGuards = nodes(route.fn, node => node.type === "IfStatement" && + source.slice(node.start, node.consequent.start).includes(CURRENT_HOME_MARKER), true); + if (markedGuards.length > 1) { + throw new Error(`房子按钮当前会话守卫 数量异常(${markedGuards.length})`); + } + const markerPresent = markedGuards.length === 1; + const guardSource = markerPresent + ? source.slice(markedGuards[0].test.start, markedGuards[0].test.end) + : ""; + const stateGuardPresent = guardSource.includes( + `${route.currentLocation}.state?.sidebarThreadLocationId!=null`, + ); + return { ...route, caller, markerPresent, stateGuardPresent }; } function findHomeRailReselect(ast, source) { @@ -261,12 +273,39 @@ function findHomeRailReselect(ast, source) { body.some(item => memberName(item) === "path"); }, true); if (branches.length !== 1) continue; + const branch = branches[0]; + const store = restoreCall.arguments[0]; + if (store?.type !== "Identifier") continue; + const currentLocationReads = nodes(branch.consequent, node => + node.type === "VariableDeclarator" && node.id?.type === "Identifier" && + node.init?.type === "CallExpression" && node.init.arguments.length === 1 && + memberName(node.init.callee) === "get" && + memberRoot(node.init.callee) === store.name && + node.init.arguments[0]?.type === "Identifier"); + if (currentLocationReads.length !== 1) continue; + const currentLocationAtom = currentLocationReads[0].init.arguments[0].name; + const parentFunctions = nodes(fn, node => /Function/.test(node.type)) + .filter(node => node !== arrow && node.start < arrow.start && node.end > arrow.end) + .sort((left, right) => (left.end - left.start) - (right.end - right.start)); + const parentFunction = parentFunctions[0]; + if (parentFunction == null) continue; + const visibleLocationReads = nodes(parentFunction, node => + node.type === "VariableDeclarator" && node.id?.type === "Identifier" && + node.init?.type === "CallExpression" && node.init.arguments.length === 1 && + memberName(node.init.callee) === "get" && + memberRoot(node.init.callee) === store.name && + node.init.arguments[0]?.type === "Identifier" && + node.init.arguments[0].name === currentLocationAtom, true); + if (visibleLocationReads.length !== 1) continue; candidates.push({ authMethod: authBindings[0].authMethod, authState: authBindings[0].authState, - branch: branches[0], - markerPresent: source.slice(branches[0].start, restoreCall.start) + branch, + currentLocation: visibleLocationReads[0].id.name, + markerPresent: source.slice(branch.start, restoreCall.start) .includes(HOME_RESELECT_MARKER), + stateMarkerPresent: source.slice(arrow.start, restoreCall.start) + .includes(HOME_STATE_MARKER), }); } } @@ -300,17 +339,17 @@ function patchSource(source) { const homeRail = findHomeRailReselect(ast, source); if (tracker == null || openHome == null || homeRail == null) { if (source.includes(MARKER) || source.includes(CURRENT_HOME_MARKER) || - source.includes(HOME_RESELECT_MARKER)) { + source.includes(HOME_RESELECT_MARKER) || source.includes(HOME_STATE_MARKER)) { throw new Error("补丁标记存在但首页导航结构未知"); } return { status: "not-applicable", source }; } const trackerPatched = isApiKeyOverride(tracker.gate, tracker.authMethod); - const openHomePatched = openHome.markerPresent && + const openHomePatched = openHome.markerPresent && openHome.stateGuardPresent && openHome.authMethod === "__codexAuthMethod" && openHome.caller.passedAuthMethod?.type === "Identifier" && openHome.caller.passedAuthMethod.name === openHome.caller.authMethod; - const homeRailPatched = homeRail.markerPresent && + const homeRailPatched = homeRail.markerPresent && homeRail.stateMarkerPresent && isApiKeyRailGuard(homeRail.branch.test, homeRail.authState); if (trackerPatched) { const gateSource = source.slice(tracker.gate.start, tracker.gate.end); @@ -324,7 +363,7 @@ function patchSource(source) { if (!openHomePatched && openHomePartiallyPatched) { throw new Error("房子按钮 API-key 保持逻辑不完整"); } - if (homeRail.markerPresent && !homeRailPatched) { + if ((homeRail.markerPresent || homeRail.stateMarkerPresent) && !homeRailPatched) { throw new Error("功能导航栏首页恢复逻辑不完整"); } if (trackerPatched && openHomePatched && homeRailPatched) { @@ -354,11 +393,16 @@ function patchSource(source) { edits.push({ start: openHome.branch.start, end: openHome.branch.start, - replacement: `if(${CURRENT_HOME_MARKER}__codexAuthMethod===\`apikey\`&&${openHome.currentLocation}!=null&&(${openHome.currentLocation}.pathname.startsWith(\`/local/\`)||${openHome.currentLocation}.pathname.startsWith(\`/remote/\`)))return;`, + replacement: `if(${CURRENT_HOME_MARKER}__codexAuthMethod===\`apikey\`&&${openHome.currentLocation}!=null&&(${openHome.currentLocation}.pathname.startsWith(\`/local/\`)||${openHome.currentLocation}.pathname.startsWith(\`/remote/\`)||${openHome.currentLocation}.state?.sidebarThreadLocationId!=null))return;`, }); } if (!homeRailPatched) { const originalTest = source.slice(homeRail.branch.test.start, homeRail.branch.test.end); + edits.push({ + start: homeRail.branch.start, + end: homeRail.branch.start, + replacement: `if(${HOME_STATE_MARKER}${homeRail.authState}.authMethod===\`apikey\`&&${homeRail.currentLocation}?.state?.sidebarThreadLocationId!=null)return;`, + }); edits.push({ start: homeRail.branch.test.start, end: homeRail.branch.test.end, @@ -427,4 +471,10 @@ function main() { } if (require.main === module) main(); -module.exports = { CURRENT_HOME_MARKER, HOME_RESELECT_MARKER, MARKER, patchSource }; +module.exports = { + CURRENT_HOME_MARKER, + HOME_RESELECT_MARKER, + HOME_STATE_MARKER, + MARKER, + patchSource, +}; diff --git a/scripts/patch-api-key-home-navigation.test.js b/scripts/patch-api-key-home-navigation.test.js index 3c665548..1eb1bf76 100644 --- a/scripts/patch-api-key-home-navigation.test.js +++ b/scripts/patch-api-key-home-navigation.test.js @@ -4,6 +4,7 @@ const assert = require("node:assert/strict"); const { CURRENT_HOME_MARKER, HOME_RESELECT_MARKER, + HOME_STATE_MARKER, MARKER, patchSource, } = require("./patch-api-key-home-navigation"); @@ -33,7 +34,7 @@ function fixture() { "c=()=>{wti(i,{codexLocalAccessStatus:`allowed`,currentMode:`codex`,navigate:h,nextMode:`codex`,openHome:!0,startNewConversation:a})};return c}", "function Rail({selectedArea:A}){let P=scope(),N=productMode(),C=auth(),", "{accountId:w,authMethod:T,userId:E,isLoading:D}=C,O=`auth:${T}`,", - "M=(e,t)=>{let n=N,r=P.get(currentMode),a=destinations[e];run(a,t=>{", + "M=(e,t)=>{let n=N,r=P.get(currentMode),a=destinations[e],o=P.get(currentLocation);run(a,t=>{", "if(A===e&&r===n){let n=destinations[e];if(n==null)return;let r=P.get(currentLocation),i=r!=null&&belongs(r,n);(!i)&&navigate(n.path,{state:t});return}", "restoreHome(P,{accountKey:O,auth:C,area:e,navigate:navigate,productMode:n,state:t})})};return M}", ].join(""); @@ -62,9 +63,10 @@ test("API-key 在 ChatGPT capability 关闭时仍写入与读取端一致的 acc function clickHome(source, authMethod, { currentPath = "/local/thread-1", + currentState, } = {}) { const navigations = []; - const current = currentPath == null ? null : { pathname: currentPath }; + const current = currentPath == null ? null : { pathname: currentPath, state: currentState }; const store = { get(key) { if (key === "wc") return false; @@ -111,6 +113,26 @@ test("API-key 根路径不短路,保留官方空数据落地页导航", () => assert.deepEqual(navigations, ["/"]); }); +test("API-key 根路径携带会话位置状态时保持当前会话", () => { + const result = patchSource(fixture()); + const navigations = clickHome(result.source, "apikey", { + currentPath: "/", + currentState: { sidebarThreadLocationId: "chats" }, + }); + + assert.deepEqual(navigations, []); +}); + +test("ChatGPT 根路径携带会话位置状态时保持官方首页行为", () => { + const result = patchSource(fixture()); + const navigations = clickHome(result.source, "chatgpt", { + currentPath: "/", + currentState: { sidebarThreadLocationId: "chats" }, + }); + + assert.deepEqual(navigations, ["/"]); +}); + test("API-key 尚无当前路由时不访问空对象", () => { const result = patchSource(fixture()); const navigations = clickHome(result.source, "apikey", { @@ -136,13 +158,16 @@ test("API-key 从设置页点击房子仍执行官方首页导航", () => { assert.deepEqual(navigations, ["/"]); }); -function clickFeatureHome(source, authMethod) { +function clickFeatureHome(source, authMethod, { + currentPath = "/settings/appearance", + currentState, +} = {}) { const navigations = []; const restores = []; const scopeValue = { get(key) { if (key === "currentMode") return "codex"; - if (key === "currentLocation") return { pathname: "/settings/appearance" }; + if (key === "currentLocation") return { pathname: currentPath, state: currentState }; return null; }, }; @@ -170,6 +195,19 @@ test("API-key 重选功能导航栏首页时恢复记录的最近会话", () => }); }); +test("API-key 重选功能导航栏首页时保持根路径中的当前状态会话", () => { + const result = patchSource(fixture()); + + assert.ok(result.source.includes(HOME_STATE_MARKER)); + assert.deepEqual(clickFeatureHome(result.source, "apikey", { + currentPath: "/", + currentState: { sidebarThreadLocationId: "chats" }, + }), { + navigations: [], + restores: [], + }); +}); + test("ChatGPT 重选功能导航栏首页时保持官方直达行为", () => { const result = patchSource(fixture()); @@ -179,6 +217,29 @@ test("ChatGPT 重选功能导航栏首页时保持官方直达行为", () => { }); }); +test("ChatGPT 重选功能导航栏首页时不获得 API-key 状态会话短路", () => { + const result = patchSource(fixture()); + + assert.deepEqual(clickFeatureHome(result.source, "chatgpt", { + currentPath: "/", + currentState: { sidebarThreadLocationId: "chats" }, + }), { + navigations: ["/"], + restores: [], + }); +}); + +test("旧版缺少状态会话判断的首页补丁会被拒绝", () => { + const patched = patchSource(fixture()); + const incomplete = patched.source + .replace("||u.state?.sidebarThreadLocationId!=null", "") + .replace(new RegExp(`if\\(\\/\\* Codex:API-key 首页保持状态会话。 \\*\\/[\\s\\S]*?return;`), ""); + const result = patchSource(incomplete); + + assert.equal(result.status, "unexpected-shape"); + assert.match(result.reason, /保持逻辑不完整/); +}); + test("ChatGPT 登录继续遵守官方 capability 与账户条件", () => { const result = patchSource(fixture()); From 1cbc8cf982911cc2dee034ba7389a49136c1d633 Mon Sep 17 00:00:00 2001 From: carptopus Date: Sun, 18 Oct 2026 13:10:54 +0800 Subject: [PATCH 14/51] fix: harden desktop compatibility patches --- README.md | 42 +- package.json | 12 +- scripts/build-current.js | 8 +- scripts/build-from-upstream.js | 10 +- scripts/build-from-upstream.test.js | 36 ++ scripts/maintenance-smoke.js | 22 + scripts/patch-accent-presets.js | 46 +- scripts/patch-accent-presets.test.js | 36 +- scripts/patch-all.test.js | 12 +- scripts/patch-api-key-home-navigation.js | 90 ++-- scripts/patch-api-key-home-navigation.test.js | 12 +- scripts/patch-archive-delete.js | 392 ++++++++++++++++-- scripts/patch-ast-util.js | 60 +++ scripts/patch-browser-auth.js | 183 +++++++- scripts/patch-browser-auth.test.js | 41 +- scripts/patch-hide-pet-menu.js | 1 + scripts/patch-mcp-status-refresh.js | 19 +- scripts/patch-model-picker-submenu.js | 5 + scripts/patch-upstream-compat.test.js | 84 +++- scripts/prepare-src.js | 85 ++-- scripts/runtime/accent-presets.mjs | 21 +- scripts/sync-upstream.js | 34 +- scripts/sync-upstream.test.js | 23 + scripts/windows-maintenance.js | 13 +- 24 files changed, 999 insertions(+), 288 deletions(-) create mode 100644 scripts/patch-ast-util.js diff --git a/README.md b/README.md index 76b41317..6d741422 100644 --- a/README.md +++ b/README.md @@ -13,25 +13,29 @@ Cross-platform Electron build for OpenAI Codex Desktop App. ## Build ```bash -# Install dependencies -npm install +# Install locked dependencies without native install scripts +pnpm install --frozen-lockfile --ignore-scripts + +# Point downloads/extraction at an explicit disposable cache directory. +# PowerShell: $env:CODEX_SYNC_DIR = Join-Path $env:TEMP "codex-rebuild" +export CODEX_SYNC_DIR="${RUNNER_TEMP:-/tmp}/codex-rebuild" # Sync upstream resources, then apply all patches -npm run sync -npm run patch +pnpm run sync +pnpm run patch # Build for current platform -npm run build +pnpm run build # Build for specific platform -npm run build:mac-x64 -npm run build:mac-arm64 -npm run build:win-x64 -npm run build:linux-x64 -npm run build:linux-arm64 +pnpm run build:mac-x64 +pnpm run build:mac-arm64 +pnpm run build:win-x64 +pnpm run build:linux-x64 +pnpm run build:linux-arm64 # Build all platforms -npm run build:all +pnpm run build:all ``` ## 补丁链路 @@ -41,7 +45,7 @@ npm run build:all - `patch-browser-auth.js` 兼容 API-key 登录:旧版在 ChatGPT 身份读取失败时仅关闭可选 request-header 并继续本地浏览器通道;新版原生托管请求头不再依赖 ChatGPT 身份时验证该完整链路并保持原样,不会把 API key 伪装或发送为 ChatGPT token。 - `patch-fast-mode.js` 为 API-key / 自定义 Provider 补齐新版 `serviceTierAccess`:跳过不可用的 ChatGPT 账户权限查询,但仍由当前模型返回的 `serviceTierOptions` 决定是否显示和发送 Fast / Ultrafast 档位。 - `patch-provider-quota.js` 按任务实际 Provider 和明确的 `base_url` 判断发送门槛,避免 ChatGPT 额度状态误阻断第三方 Provider,同时保留官方、云任务及第三方真实错误。 -- `patch-api-key-home-navigation.js` 补齐 API-key 模式的当前会话导航记录,并识别新版保存在路由 state 中的会话位置;当前会话点击首页保持不变,从设置等页面点击首页则恢复最近会话,避免直达空首页。ChatGPT、无认证及其他认证方式保持原有条件。 +- `patch-api-key-home-navigation.js` 补齐 API-key 模式的当前会话导航记录,并复用官方首页区域分类器识别当前会话;当前会话点击首页保持不变,从设置等页面点击首页则恢复最近会话,避免直达空首页。ChatGPT、无认证及其他认证方式保持原有条件。 - `patch-thread-timeline.js` 在当前 host 与 App Server 版本支持时启用官方 `thread/timeline/list` 历史路径,移除 API-key / 自定义 Provider 无法获得的远端灰度条件;版本兼容判断仍由官方逻辑负责。 - `patch-mcp-status-refresh.js` 将短时间内的 MCP 启动状态通知合并为一次轻量目录刷新;Full 目录只标记为 stale、不在后台立即重拉,详细 MCP 页面后续仍按官方 Full 查询取得资源与模板。 - `patch-remote-control.js` 只开放 Connections 设置入口;需要 ChatGPT 账户与 workspace routing 的 Remote Control 数据链继续遵守官方 gate,避免 API-key 模式反复建立无凭据的 Durable 连接。 @@ -55,14 +59,14 @@ npm run build:all - `sync-upstream.js`、`fetch-msstore.js` 和 `build-from-upstream.js` 强化 Windows x64 官方包选择与固定来源校验,支持精确版本和已验证原始 MSIX 重放;包身份、大小或 SHA-256 不符时拒绝构建,运行检查通过前不生成最终 ZIP。 - `windows-artifacts.js` 与 `windows-maintenance.js` 记录官方来源和候选产物哈希,生成候选、验证发布门槛,并保证正式发布复用已经验收的同一 ZIP。 - `windows-runtime-checks.js` 检查 Windows EXE / 原生模块架构及未修改组件哈希,实际加载 CUA、运行 code-mode host / rg 基础命令,并执行空白隔离桌面的启动、就绪和退出冒烟。 -- `check-scripts.js`、`frontend-source-smoke.js`、`reading-layout-smoke.js` 和 `maintenance-smoke.js` 覆盖脚本语法、真实补丁资源、阅读设置及候选/发布拒绝路径,避免只凭补丁脚本成功退出判断功能可用。 +- `check-scripts.js`、`frontend-source-smoke.js`、`reading-layout-smoke.js` 和 `maintenance-smoke.js` 覆盖脚本语法、真实补丁资源、阅读设置及候选/发布拒绝路径。这些属于补丁结构回归,只证明补丁仍能安全命中和拒绝未知结构;首页、主题、MCP 等运行效果仍以独立 GUI 验收项为准。 - `patch-realtime-voice-auth.js` 为 API-key 登录放行实时语音入口;实时会话仍由 app-server 使用当前 model provider 的 `base_url` 与认证创建,ChatGPT 工作区能力的认证限制保持不变。 -- 上游更新后应先执行 `npm run patch -- --check` 或完整 `npm run patch`,再运行测试和构建。 +- 上游更新后应先执行 `pnpm run patch -- --check` 或完整 `pnpm run patch`,再运行测试和构建。 ## Development ```bash -npm run dev +pnpm run dev ``` ## Project Structure @@ -85,9 +89,9 @@ npm run dev ## CI/CD -GitHub Actions automatically builds on: -- Push to `master` / `main` and tag `v*` → build artifacts -- 每日上游同步工作流:逐平台比较已保存的版本;仅在任一平台版本变化时下载上游、重新应用补丁、构建并更新 Release +`Windows Candidate` 在面向 `master` 的 PR 上只运行语法、补丁和维护链回归检查,不下载或构建候选。推送到 `master`、`maintenance/**`、`candidate/**`,每日定时检查或手动触发时才构建候选 artifact;定时运行只有发现新的 Windows x64 官方版本时才构建。候选不会自动发布。 + +候选完成真实 GUI 验收后,将审查过的验收 JSON 合入 `master`,再手动触发 `Promote Verified Windows Candidate`。晋升工作流下载并核对原候选 run 的同一 ZIP、源码提交、来源和全部必过验收项,然后创建 Release;不会重新打包替代已验收 ZIP。 ### 上游补丁兼容检查 @@ -107,7 +111,7 @@ node scripts/patch-all.js mac-arm64 --check --report patch-reports/mac-arm64-che # 应用补丁,再构建 node scripts/patch-all.js mac-arm64 --report patch-reports/mac-arm64-apply -npm run build:mac-arm64 +pnpm run build:mac-arm64 # 调试历史或单独解压的资源,可指定 src 根目录 node scripts/patch-all.js win --check --source-dir /path/to/extracted/src --report patch-reports/win-check diff --git a/package.json b/package.json index 65230b25..8ac92a05 100644 --- a/package.json +++ b/package.json @@ -18,13 +18,13 @@ "build": "node scripts/build-current.js", "build:mac-arm64": "node scripts/build-from-upstream.js --platform mac-arm64", "build:mac-x64": "node scripts/build-from-upstream.js --platform mac-x64", - "build:mac": "npm run build:mac-arm64 && npm run build:mac-x64", + "build:mac": "pnpm run build:mac-arm64 && pnpm run build:mac-x64", "build:win-x64": "node scripts/build-from-upstream.js --platform win", - "build:win": "npm run build:win-x64", - "build:linux-x64": "node scripts/prepare-src.js --platform linux-x64 && npm run rebuild:native && node scripts/sync-native-modules.js --platform linux-x64 && rm -rf out && electron-forge make --platform=linux --arch=x64", - "build:linux-arm64": "node scripts/prepare-src.js --platform linux-arm64 && npm run rebuild:native && node scripts/sync-native-modules.js --platform linux-arm64 && rm -rf out && electron-forge make --platform=linux --arch=arm64", - "build:linux": "npm run build:linux-x64 && npm run build:linux-arm64", - "build:all": "npm run build:mac && npm run build:win && npm run build:linux", + "build:win": "pnpm run build:win-x64", + "build:linux-x64": "node scripts/prepare-src.js --platform linux-x64 && pnpm run rebuild:native && node scripts/sync-native-modules.js --platform linux-x64 && rm -rf out && electron-forge make --platform=linux --arch=x64", + "build:linux-arm64": "node scripts/prepare-src.js --platform linux-arm64 && pnpm run rebuild:native && node scripts/sync-native-modules.js --platform linux-arm64 && rm -rf out && electron-forge make --platform=linux --arch=arm64", + "build:linux": "pnpm run build:linux-x64 && pnpm run build:linux-arm64", + "build:all": "pnpm run build:mac && pnpm run build:win && pnpm run build:linux", "test": "node --test scripts/*.test.js", "check": "node scripts/check-scripts.js", "test:maintenance": "node scripts/maintenance-smoke.js", diff --git a/scripts/build-current.js b/scripts/build-current.js index be59b1b1..76ce7dcd 100644 --- a/scripts/build-current.js +++ b/scripts/build-current.js @@ -20,16 +20,16 @@ if (!TARGET_SCRIPT) { process.exit(1); } -console.log(`[build] current platform ${process.platform}-${process.arch} -> npm run ${TARGET_SCRIPT}`); +console.log(`[build] current platform ${process.platform}-${process.arch} -> pnpm run ${TARGET_SCRIPT}`); -const npmBin = process.platform === "win32" ? "npm.cmd" : "npm"; -const result = spawnSync(npmBin, ["run", TARGET_SCRIPT], { +const pnpmBin = process.platform === "win32" ? "pnpm.cmd" : "pnpm"; +const result = spawnSync(pnpmBin, ["run", TARGET_SCRIPT], { stdio: "inherit", shell: false, }); if (result.error) { - console.error(`[x] Failed to run npm: ${result.error.message}`); + console.error(`[x] Failed to run pnpm: ${result.error.message}`); process.exit(1); } diff --git a/scripts/build-from-upstream.js b/scripts/build-from-upstream.js index 2e71b09d..85bfe8b9 100644 --- a/scripts/build-from-upstream.js +++ b/scripts/build-from-upstream.js @@ -16,7 +16,7 @@ const fs = require("fs"); const path = require("path"); const { execSync, execFileSync } = require("child_process"); const { findUpstreamCodex, getCodexBinarySource } = require("./codex-binary-policy"); -const { validateWindowsPackage } = require("./sync-upstream"); +const { resolveSyncDirectory, validateWindowsPackage } = require("./sync-upstream"); const { validateSource } = require("./windows-artifacts"); const PROJECT_ROOT = path.resolve(__dirname, ".."); @@ -233,9 +233,7 @@ function buildMac(platform) { } // 1. Find the .app in the ZIP extract cache - const tempDir = process.env.CODEX_SYNC_DIR - ? path.resolve(process.env.CODEX_SYNC_DIR) - : path.join(PROJECT_ROOT, ".cache", "upstream-sync"); + const tempDir = resolveSyncDirectory(); const variant = platform === "mac-arm64" ? "arm64" : "x64"; const extractDir = path.join(tempDir, `${variant}-extract`); @@ -317,9 +315,7 @@ function buildWin(platform, { deferZip = false } = {}) { } // Windows: use the MSIX extract cache - const tempDir = process.env.CODEX_SYNC_DIR - ? path.resolve(process.env.CODEX_SYNC_DIR) - : path.join(PROJECT_ROOT, ".cache", "upstream-sync"); + const tempDir = resolveSyncDirectory(); const extractDir = path.join(tempDir, "win-extract"); const appDir = path.join(extractDir, "app"); diff --git a/scripts/build-from-upstream.test.js b/scripts/build-from-upstream.test.js index 309d49c9..c5f13b37 100644 --- a/scripts/build-from-upstream.test.js +++ b/scripts/build-from-upstream.test.js @@ -17,6 +17,7 @@ const { getCodexBinarySource, getCometixCodexPackageSpec, } = require("./codex-binary-policy"); +const { registryCurlArgs, resolveCometixRegistryEntry } = require("./prepare-src"); function createTemporaryOutput(t) { const directory = fs.mkdtempSync(path.join(os.tmpdir(), "codex-dmg-test-")); @@ -163,6 +164,41 @@ test("Cometix 平台包使用架构 dist-tag 而不是拼接主包版本", () => ); }); +test("Cometix registry 元数据固定架构版本、HTTPS tarball 与完整性摘要", () => { + const integrity = `sha512-${Buffer.alloc(64, 7).toString("base64")}`; + const metadata = { + "dist-tags": { "linux-x64": "1.2.3" }, + versions: { "1.2.3": { dist: { integrity, tarball: "https://registry.example/codex.tgz" } } }, + }; + assert.deepEqual(resolveCometixRegistryEntry("linux-x64", metadata), { + integrity, + spec: "@cometix/codex@1.2.3", + tarball: "https://registry.example/codex.tgz", + version: "1.2.3", + }); + assert.throws( + () => resolveCometixRegistryEntry("linux-x64", { + ...metadata, + versions: { "1.2.3": { dist: { tarball: "https://registry.example/codex.tgz" } } }, + }), + /缺少可验证的 registry tarball/, + ); + assert.throws( + () => resolveCometixRegistryEntry("linux-x64", { + ...metadata, + versions: { "1.2.3": { dist: { integrity, tarball: "http://registry.example/codex.tgz" } } }, + }), + /必须使用 HTTPS/, + ); +}); + +test("Cometix registry 下载禁止 HTTP 输入与降级重定向", () => { + const args = registryCurlArgs("https://registry.example/codex.tgz", "package.tgz"); + assert.deepEqual(args.slice(0, 6), [ + "--fail", "--location", "--proto", "=https", "--proto-redir", "=https", + ]); +}); + test("保留上游 CLI 时不会改写二进制", (t) => { const directory = fs.mkdtempSync(path.join(os.tmpdir(), "codex-cli-policy-test-")); t.after(() => fs.rmSync(directory, { recursive: true, force: true })); diff --git a/scripts/maintenance-smoke.js b/scripts/maintenance-smoke.js index 5cd01fe1..2373444d 100644 --- a/scripts/maintenance-smoke.js +++ b/scripts/maintenance-smoke.js @@ -36,6 +36,7 @@ try { const discoveryPreload = path.join(temporary, "discovery-preload.cjs"); write(discoveryPreload, `const target=require.resolve(${JSON.stringify(path.join(scriptRoot, "fetch-msstore.js"))}); require.cache[target]={id:target,filename:target,loaded:true,exports:{getCookie:async()=>"cookie",getAppInfo:async()=>({categoryId:"fixture"}),getFileList:async()=>["26.1007.9446.0","26.917.71314.0","26.1007.2314.0"].map(v=>({name:"OpenAI.Codex_"+v+"_x64__2p2nqsd0c76g0.msix",size:"10",digest:Buffer.alloc(20).toString("base64"),updateID:v,revisionNumber:"1"})),getDownloadUrl:async()=>"https://tlu.dl.delivery.mp.microsoft.com/fixture.msix"}};`); const discoveryOutput = path.join(temporary, "discovery.json"); + const discoveryCache = path.join(temporary, "discovery-cache"); const observed = path.join(temporary, "observed.json"); json(observed, { schemaVersion: 1, upstream: { version: "26.1007.9446.0" } }); const discovered = spawnSync(process.execPath, ["--require", discoveryPreload, path.join(scriptRoot, "windows-maintenance.js"), "discover", "--out", discoveryOutput, "--stable-manifest", observed], { encoding: "utf8", env: { ...process.env, GITHUB_OUTPUT: "" } }); @@ -43,6 +44,17 @@ try { assert.match(discovered.stdout, /has_update=false/); assert.equal(JSON.parse(fs.readFileSync(discoveryOutput)).version, "26.1007.9446.0"); checks++; + const missingDiscoveryCache = spawnSync(process.execPath, ["--require", discoveryPreload, path.join(scriptRoot, "windows-maintenance.js"), "discover"], { + encoding: "utf8", env: { ...process.env, CODEX_SYNC_DIR: "", GITHUB_OUTPUT: "" }, + }); + assert.notEqual(missingDiscoveryCache.status, 0); + assert.match(missingDiscoveryCache.stderr, /缺少 CODEX_SYNC_DIR/); + const cachedDiscovery = spawnSync(process.execPath, ["--require", discoveryPreload, path.join(scriptRoot, "windows-maintenance.js"), "discover"], { + encoding: "utf8", env: { ...process.env, CODEX_SYNC_DIR: discoveryCache, GITHUB_OUTPUT: "" }, + }); + assert.equal(cachedDiscovery.status, 0, cachedDiscovery.stderr); + assert.equal(JSON.parse(fs.readFileSync(path.join(discoveryCache, "windows-discovery.json"))).version, "26.1007.9446.0"); + checks += 2; json(observed, { schemaVersion: 1, upstream: { version: "26.1007.2314.0" } }); const changed = spawnSync(process.execPath, ["--require", discoveryPreload, path.join(scriptRoot, "windows-maintenance.js"), "discover", "--out", discoveryOutput, "--stable-manifest", observed], { encoding: "utf8", env: { ...process.env, GITHUB_OUTPUT: "" } }); assert.equal(changed.status, 0, changed.stderr); @@ -132,6 +144,16 @@ try { ); checks++; + const missingRequiredRoot = path.join(temporary, "missing-required-targets"); + fs.mkdirSync(path.join(missingRequiredRoot, "win", "_asar", "webview", "assets"), { recursive: true }); + run("patch-hide-pet-menu.js", ["win", "--check"], 1, { CODEX_PATCH_SOURCE_DIR: missingRequiredRoot }); + run("patch-model-picker-submenu.js", ["win", "--check"], 1, { CODEX_PATCH_SOURCE_DIR: missingRequiredRoot }); + fs.writeFileSync( + path.join(missingRequiredRoot, "win", "_asar", "webview", "assets", "archived-list.js"), + "client.sendRequest(`thread/list`,{archived:!0,modelProviders:null});", + ); + run("patch-archive-delete.js", ["win", "--check"], 1, { CODEX_PATCH_SOURCE_DIR: missingRequiredRoot }); + const pickerRoot = path.join(temporary, "picker"); const pickerFile = path.join(pickerRoot, "win", "_asar", "webview", "assets", "model-picker.js"); const nativePicker = 'function picker(input){const {modelListConfig:list,menuView:view,onToggleMenuView:toggle}=input;const items=list.options.map(option=>ui.jsx(menu.Item,{"data-model-selected":option.selected,role:`menuitemradio`,onSelect:event=>{event.preventDefault();option.onSelect();toggle(`simple`)}}));return ui.jsx("div",{"data-model-picker-view":view,children:items});}'; diff --git a/scripts/patch-accent-presets.js b/scripts/patch-accent-presets.js index db5724c5..4b53766a 100644 --- a/scripts/patch-accent-presets.js +++ b/scripts/patch-accent-presets.js @@ -6,6 +6,7 @@ const fs = require("fs"); const path = require("path"); const { parse } = require("acorn"); +const { applyEdits, key, literal, nodes, unique } = require("./patch-ast-util"); const { SRC_DIR, relPath } = require("./patch-util"); const MODULE = "codex-rebuild-accent-presets.js"; @@ -13,40 +14,6 @@ const SETTINGS_MARKER = "/* codex-rebuild-local-accent-presets:settings */"; const THEME_MARKER = "/* codex-rebuild-local-accent-presets:theme */"; const PLATFORMS = ["mac-arm64", "mac-x64", "win", "unix"]; -function walk(node, visit, parent = null) { - if (!node || typeof node !== "object" || !node.type) return; - visit(node, parent); - for (const [key, value] of Object.entries(node)) { - if (["type", "start", "end"].includes(key)) continue; - if (Array.isArray(value)) { - for (const child of value) if (child?.type) walk(child, visit, node); - } else if (value?.type) walk(value, visit, node); - } -} - -function nodes(root, predicate) { - const found = []; - walk(root, (node, parent) => { if (predicate(node, parent)) found.push(node); }); - return found; -} - -function literal(node) { - if (node?.type === "Literal") return node.value; - if (node?.type === "TemplateLiteral" && node.expressions.length === 0) return node.quasis[0].value.cooked; - return null; -} - -function key(node) { - if (!node) return null; - if (node.type === "Identifier") return node.name; - return literal(node); -} - -function unique(items, label) { - if (items.length !== 1) throw new Error(`${label} 数量异常(${items.length})`); - return items[0]; -} - function objectBindings(pattern) { return Object.fromEntries(pattern.properties.filter(property => property.type === "Property" && property.value?.type === "Identifier") .map(property => [key(property.key), property.value.name])); @@ -57,15 +24,6 @@ function importInsertion(ast) { return imports.length ? imports.at(-1).end : 0; } -function applyEdits(source, edits) { - let next = source; - for (const edit of edits.sort((left, right) => right.start - left.start)) { - next = next.slice(0, edit.start) + edit.text + next.slice(edit.end); - } - parse(next, { ecmaVersion: "latest", sourceType: "module" }); - return next; -} - function patchSettingsSource(source) { if (!source.includes("chatgptAccentPicker.ChatGptAccentPicker.updateError") || !source.includes("accentSource")) { return { status: "not-applicable", source }; @@ -118,7 +76,7 @@ function patchSettingsSource(source) { const edits = [ { start: importAt, end: importAt, text: moduleImport }, { start: selection.init.start, end: selection.init.end, - text: `__codexAccentSelection(${accountTheme},${originalSelection})` }, + text: `__codexAccentSelection(${accountTheme},${theme}.accentSource,${originalSelection})` }, // undefined 表示账户主题仍在加载;null 才表示没有可用账户主题。 { start: disabled.value.start, end: disabled.value.end, text: `${accountTheme}===void 0` }, { start: accountCall.start, end: accountCall.end, diff --git a/scripts/patch-accent-presets.test.js b/scripts/patch-accent-presets.test.js index 3d652669..a71bb3d4 100644 --- a/scripts/patch-accent-presets.test.js +++ b/scripts/patch-accent-presets.test.js @@ -58,6 +58,7 @@ test("无账户主题时启用本地预设并保留加载态禁用", () => { assert.match(result.source, new RegExp(MODULE.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))); assert.doesNotMatch(result.source, /__codexCurrentAccent/); assert.match(result.source, /disabled:u===void 0/); + assert.match(result.source, /__codexAccentSelection\(u,r\.accentSource,/); assert.match(result.source, /__codexSelectAccentPreset\(u,e,\(\)=>o\(r\.accent\),\(\)=>a\(/); assert.match(result.source, /onChange:__codexColor=>__codexUseCustomAccent\(o,__codexColor\)/); assert.equal(patchSettingsSource(result.source).status, "already-patched"); @@ -74,7 +75,7 @@ test("设置组件在属性解构后才读取主题", () => { )( () => "color", ["default", "blue"], () => ({ get: () => null }), () => null, {}, {}, (_type, props) => props, "radio", "color", {}, {}, () => {}, () => {}, - (_accountTheme, fallback) => fallback, + (_accountTheme, _accentSource, fallback) => fallback, () => Promise.resolve(), (onChange, value) => onChange(value), ); @@ -113,7 +114,7 @@ test("主题函数唯一注入本地预设解析器并保持幂等", () => { assert.equal(patchThemeSource(result.source).status, "already-patched"); }); -test("本地设置、账户优先和自定义清理使用同一预设状态", async () => { +test("本地设置、账户同步和自定义清理使用同一预设状态", async () => { const runtime = await runtimeModule(); const storage = fakeStorage(); globalThis.localStorage = storage; @@ -123,16 +124,35 @@ test("本地设置、账户优先和自定义清理使用同一预设状态", as await runtime.selectAccentPreset(null, "blue", () => { localCalls++; }, () => { accountCalls++; }); assert.equal(storage.values.get(runtime.ACCENT_PRESET_STORAGE_KEY), "blue"); - assert.equal(runtime.accentPresetSelection(null, "custom"), "blue"); - assert.equal(runtime.accentPresetSelection(undefined, "custom"), "custom"); + assert.equal(runtime.accentPresetSelection(null, "custom", "custom"), "blue"); + assert.equal(runtime.accentPresetSelection({ chatTheme: "green" }, "custom", "custom"), "blue"); + assert.equal(runtime.accentPresetSelection(undefined, "custom", "custom"), "custom"); + assert.equal(runtime.accentPresetSelection({ chatTheme: "green" }, "chatgpt", "green"), "green"); assert.equal(runtime.resolveAccentPreset("custom", null), "blue"); assert.equal(localCalls, 1); assert.equal(accountCalls, 0); await runtime.selectAccentPreset({ chatTheme: "green" }, "green", () => { localCalls++; }, () => { accountCalls++; }); - assert.equal(storage.values.has(runtime.ACCENT_PRESET_STORAGE_KEY), false); + assert.equal(storage.values.get(runtime.ACCENT_PRESET_STORAGE_KEY), "green"); assert.equal(accountCalls, 1); + globalThis.localStorage = { + getItem: () => null, + setItem: () => { throw new Error("storage unavailable"); }, + removeItem: () => {}, + }; + await runtime.selectAccentPreset({ chatTheme: "purple" }, "purple", () => { localCalls++; }, () => { accountCalls++; }); + assert.equal(accountCalls, 2); + + await runtime.selectAccentPreset({ chatTheme: "future" }, "future-preset", () => { localCalls++; }, () => { accountCalls++; }); + assert.equal(accountCalls, 3); + assert.equal(storage.values.get(runtime.ACCENT_PRESET_STORAGE_KEY), "green"); + + await runtime.selectAccentPreset(null, "future-preset", () => { localCalls++; }, () => { accountCalls++; }); + assert.equal(accountCalls, 4); + assert.equal(localCalls, 1); + + globalThis.localStorage = storage; storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, "blue"); runtime.useCustomAccent(value => { customValue = value; }, "#123456"); assert.equal(customValue, "#123456"); @@ -145,7 +165,7 @@ test("预设解析补齐官方默认有效色并拒绝无效本地值", async () globalThis.localStorage = storage; assert.equal(runtime.resolveAccentPreset("custom", null), "blue"); assert.equal(runtime.resolveAccentPreset("chatgpt", "green"), "green"); - assert.equal(runtime.resolveAccentPreset("custom", "green"), null); + assert.equal(runtime.resolveAccentPreset("custom", "green"), "blue"); for (const preset of ["blue", "black"]) { storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, preset); @@ -177,8 +197,8 @@ test("完整主题链复用官方预设气泡且账户主题优先", async t => const accountGreen = theme.Tba({ accentSource: "chatgpt", accent: "#custom" }, "light", "green"); assert.equal(accountGreen["--color-background-user-message"], "#green-bubble"); - const accountCustom = theme.Tba({ accentSource: "custom", accent: "#custom" }, "light", "green"); - assert.equal(accountCustom["--color-background-user-message"], "neutral-bubble"); + const localWithAccountData = theme.Tba({ accentSource: "custom", accent: "#custom" }, "light", "green"); + assert.equal(localWithAccountData["--color-background-user-message"], "#blue-bubble"); for (const preset of ["blue", "black"]) { storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, preset); diff --git a/scripts/patch-all.test.js b/scripts/patch-all.test.js index ec64ad28..565f0d08 100644 --- a/scripts/patch-all.test.js +++ b/scripts/patch-all.test.js @@ -123,7 +123,7 @@ test("CLI 缺少同步资源时返回失败并生成可读报告", (t) => { assert.match(report.errors[0], /mac-arm64/); }); -test("报告合并正常扫描提示,并把缺少目标与平台不适用分开", (t) => { +test("报告合并正常扫描提示,并阻止缺少必要补丁目标", (t) => { const root = fixture(t); const asar = path.join(root, "mac-arm64", "_asar"); const assets = path.join(asar, "webview", "assets"); @@ -140,19 +140,19 @@ test("报告合并正常扫描提示,并把缺少目标与平台不适用分 log: () => {}, }); - assert.equal(report.canBuild, true); - assert.equal(report.reviewCount, 1); + assert.equal(report.canBuild, false); + assert.equal(report.reviewCount, 0); const scanner = report.results.find((item) => item.script === "patch-plugin-auth.js"); assert.equal(scanner.noticeSummary.length, 1); assert.equal(scanner.noticeSummary[0].kind, "info"); assert.equal(scanner.noticeSummary[0].count, 2); assert.equal(report.results.find((item) => item.script === "patch-windows-portable-runtime.js").noticeSummary[0].kind, "info"); - assert.equal(report.results.find((item) => item.script === "patch-model-picker-submenu.js").noticeSummary[0].kind, "review"); + assert.equal(report.results.find((item) => item.script === "patch-model-picker-submenu.js").status, "failed"); const markdown = fs.readFileSync(path.join(reportDir, "report.md"), "utf8"); - // The table must not claim a missing submenu patch was applied. + // A required patch with no verifiable target must block the build. const submenuRow = markdown.split("\n").find((line) => line.startsWith("|") && line.includes("patch-model-picker-submenu.js")); - assert.match(submenuRow, /待核对/); + assert.match(submenuRow, /失败,阻止构建/); const infoLines = markdown.split("\n").filter((line) => line.startsWith("- ") && line.includes("patch-plugin-auth.js")); assert.equal(infoLines.length, 1); assert.equal(renderReport(report, { linkLogs: false }).includes("]("), false); diff --git a/scripts/patch-api-key-home-navigation.js b/scripts/patch-api-key-home-navigation.js index 009b89fe..389cde89 100644 --- a/scripts/patch-api-key-home-navigation.js +++ b/scripts/patch-api-key-home-navigation.js @@ -5,8 +5,8 @@ * 上游的读取端会使用 auth:apikey 查找最近位置,但写入端同时受 * 新导航模式和 ChatGPT capability 限制,导致 API-key 下从不写入。 * 同时,侧栏房子按钮使用独立的 openHome 分支直接导航到 `/`,不会进入 - * 上述首页恢复函数。这里只给该按钮传入真实 authMethod,并在 API-key 已经 - * 位于 `/local/`、`/remote/`,或根路径仍携带会话位置状态时短路。新版功能导航栏还有一条 + * 上述首页恢复函数。这里只给该按钮传入真实 authMethod,并复用官方的 + * 首页区域分类器判断当前是否已经位于会话/首页区域。新版功能导航栏还有一条 * “当前已经选中首页时再次点击”的直达 `/` 分支;API-key 必须跳过该分支, * 交回官方首页位置记录器,才能从设置等页面恢复最近会话。 * 补丁不开启 ChatGPT 账户能力,也不改变其他认证方式。 @@ -14,6 +14,7 @@ const fs = require("node:fs"); const path = require("node:path"); const { parse } = require("acorn"); +const { applyEdits, literal, nodes, unique } = require("./patch-ast-util"); const { SRC_DIR, relPath } = require("./patch-util"); const MARKER = "/* Codex:API-key 首页恢复写入。 */"; @@ -22,33 +23,6 @@ const HOME_RESELECT_MARKER = "/* Codex:API-key 首页恢复最近会话。 */" const HOME_STATE_MARKER = "/* Codex:API-key 首页保持状态会话。 */"; const PLATFORMS = ["mac-arm64", "mac-x64", "win", "unix"]; -function walk(node, visit, root = node, ownScope = false) { - if (!node || typeof node !== "object" || !node.type) return; - if (ownScope && node !== root && /Function/.test(node.type)) return; - visit(node); - for (const value of Object.values(node)) { - if (Array.isArray(value)) { - for (const child of value) walk(child, visit, root, ownScope); - } else if (value?.type) { - walk(value, visit, root, ownScope); - } - } -} - -function nodes(root, predicate, ownScope = false) { - const found = []; - walk(root, node => { if (predicate(node)) found.push(node); }, root, ownScope); - return found; -} - -function literal(node) { - if (node?.type === "Literal") return node.value; - if (node?.type === "TemplateLiteral" && node.expressions.length === 0) { - return node.quasis[0].value.cooked; - } - return null; -} - function propertyName(property) { if (property?.type !== "Property") return null; if (!property.computed && property.key.type === "Identifier") return property.key.name; @@ -73,15 +47,10 @@ function optionBinding(pattern, name) { ? property.value.left.name : null; } -function unique(items, label) { - if (items.length !== 1) throw new Error(`${label} 数量异常(${items.length})`); - return items[0]; -} - function findTracker(ast) { const candidates = []; for (const fn of ast.body.filter(node => node.type === "FunctionDeclaration")) { - const own = nodes(fn, () => true, true); + const own = nodes(fn, () => true, { ownScope: true }); const all = nodes(fn, () => true); const auth = own.filter(node => node.type === "VariableDeclarator" && node.id?.type === "ObjectPattern" && node.init?.type === "CallExpression") @@ -180,7 +149,7 @@ function findOpenHomeRoute(ast, source) { literal(item.arguments[0]) === "/" && item.arguments[1]?.type === "ObjectExpression" && objectProperty(objectProperty(item.arguments[1], "state")?.value, "sidebarProductMode")?.value?.name === bindings.nextMode); - }, true); + }, { ownScope: true }); if (branches.length !== 1) continue; const libraryRoots = new Set(nodes(fn, node => node.type === "CallExpression" && @@ -215,9 +184,15 @@ function findOpenHomeRoute(ast, source) { if (options?.type !== "ObjectExpression" || !isTrue(objectProperty(options, "openHome")?.value) || literal(objectProperty(options, "nextMode")?.value) !== "codex") continue; + const homeClassifiers = nodes(fn, node => node.type === "BinaryExpression" && + ["===", "=="].includes(node.operator) && literal(node.right) === "home" && + node.left?.type === "CallExpression" && node.left.callee?.type === "Identifier" && + node.left.arguments.length === 1, { ownScope: true }); + if (homeClassifiers.length !== 1) continue; callers.push({ authMethod: authBindings[0], call, + homeClassifier: homeClassifiers[0].left.callee.name, options, passedAuthMethod: objectProperty(options, "authMethod")?.value, }); @@ -225,7 +200,7 @@ function findOpenHomeRoute(ast, source) { } const caller = unique(callers, "房子按钮调用点"); const markedGuards = nodes(route.fn, node => node.type === "IfStatement" && - source.slice(node.start, node.consequent.start).includes(CURRENT_HOME_MARKER), true); + source.slice(node.start, node.consequent.start).includes(CURRENT_HOME_MARKER), { ownScope: true }); if (markedGuards.length > 1) { throw new Error(`房子按钮当前会话守卫 数量异常(${markedGuards.length})`); } @@ -233,10 +208,10 @@ function findOpenHomeRoute(ast, source) { const guardSource = markerPresent ? source.slice(markedGuards[0].test.start, markedGuards[0].test.end) : ""; - const stateGuardPresent = guardSource.includes( - `${route.currentLocation}.state?.sidebarThreadLocationId!=null`, + const currentAreaGuardPresent = guardSource.includes( + `${caller.homeClassifier}(${route.currentLocation})===\`home\``, ); - return { ...route, caller, markerPresent, stateGuardPresent }; + return { ...route, caller, currentAreaGuardPresent, markerPresent }; } function findHomeRailReselect(ast, source) { @@ -257,7 +232,7 @@ function findHomeRailReselect(ast, source) { const options = node.arguments[1]; return ["accountKey", "area", "navigate", "productMode", "state"].every(name => objectProperty(options, name)?.value?.type === "Identifier"); - }, true); + }, { ownScope: true }); if (restoreCalls.length !== 1) continue; const restoreCall = restoreCalls[0]; const options = restoreCall.arguments[1]; @@ -271,7 +246,7 @@ function findHomeRailReselect(ast, source) { const body = nodes(node.consequent, () => true); return body.some(item => item.type === "ReturnStatement") && body.some(item => memberName(item) === "path"); - }, true); + }, { ownScope: true }); if (branches.length !== 1) continue; const branch = branches[0]; const store = restoreCall.arguments[0]; @@ -295,8 +270,15 @@ function findHomeRailReselect(ast, source) { memberName(node.init.callee) === "get" && memberRoot(node.init.callee) === store.name && node.init.arguments[0]?.type === "Identifier" && - node.init.arguments[0].name === currentLocationAtom, true); + node.init.arguments[0].name === currentLocationAtom, { ownScope: true }); if (visibleLocationReads.length !== 1) continue; + const markedStateGuards = nodes(arrow, node => node.type === "IfStatement" && + node.start < restoreCall.start && + source.slice(node.start, node.consequent.start).includes(HOME_STATE_MARKER), + { ownScope: true }); + if (markedStateGuards.length > 1) { + throw new Error(`功能导航栏当前首页守卫 数量异常(${markedStateGuards.length})`); + } candidates.push({ authMethod: authBindings[0].authMethod, authState: authBindings[0].authState, @@ -304,8 +286,10 @@ function findHomeRailReselect(ast, source) { currentLocation: visibleLocationReads[0].id.name, markerPresent: source.slice(branch.start, restoreCall.start) .includes(HOME_RESELECT_MARKER), - stateMarkerPresent: source.slice(arrow.start, restoreCall.start) - .includes(HOME_STATE_MARKER), + stateGuardSource: markedStateGuards.length === 1 + ? source.slice(markedStateGuards[0].test.start, markedStateGuards[0].test.end) + : "", + stateMarkerPresent: markedStateGuards.length === 1, }); } } @@ -345,12 +329,14 @@ function patchSource(source) { return { status: "not-applicable", source }; } const trackerPatched = isApiKeyOverride(tracker.gate, tracker.authMethod); - const openHomePatched = openHome.markerPresent && openHome.stateGuardPresent && + const openHomePatched = openHome.markerPresent && openHome.currentAreaGuardPresent && openHome.authMethod === "__codexAuthMethod" && openHome.caller.passedAuthMethod?.type === "Identifier" && openHome.caller.passedAuthMethod.name === openHome.caller.authMethod; const homeRailPatched = homeRail.markerPresent && homeRail.stateMarkerPresent && - isApiKeyRailGuard(homeRail.branch.test, homeRail.authState); + homeRail.stateGuardSource.includes( + `${openHome.caller.homeClassifier}(${homeRail.currentLocation})===\`home\``, + ) && isApiKeyRailGuard(homeRail.branch.test, homeRail.authState); if (trackerPatched) { const gateSource = source.slice(tracker.gate.start, tracker.gate.end); if (!gateSource.includes(MARKER)) throw new Error("API-key 放行逻辑存在但缺少本项目标记"); @@ -393,7 +379,7 @@ function patchSource(source) { edits.push({ start: openHome.branch.start, end: openHome.branch.start, - replacement: `if(${CURRENT_HOME_MARKER}__codexAuthMethod===\`apikey\`&&${openHome.currentLocation}!=null&&(${openHome.currentLocation}.pathname.startsWith(\`/local/\`)||${openHome.currentLocation}.pathname.startsWith(\`/remote/\`)||${openHome.currentLocation}.state?.sidebarThreadLocationId!=null))return;`, + replacement: `if(${CURRENT_HOME_MARKER}__codexAuthMethod===\`apikey\`&&${openHome.currentLocation}!=null&&${openHome.caller.homeClassifier}(${openHome.currentLocation})===\`home\`)return;`, }); } if (!homeRailPatched) { @@ -401,7 +387,7 @@ function patchSource(source) { edits.push({ start: homeRail.branch.start, end: homeRail.branch.start, - replacement: `if(${HOME_STATE_MARKER}${homeRail.authState}.authMethod===\`apikey\`&&${homeRail.currentLocation}?.state?.sidebarThreadLocationId!=null)return;`, + replacement: `if(${HOME_STATE_MARKER}${homeRail.authState}.authMethod===\`apikey\`&&${homeRail.currentLocation}!=null&&${openHome.caller.homeClassifier}(${homeRail.currentLocation})===\`home\`)return;`, }); edits.push({ start: homeRail.branch.test.start, @@ -409,11 +395,7 @@ function patchSource(source) { replacement: `(${HOME_RESELECT_MARKER}${homeRail.authState}.authMethod!==\`apikey\`&&(${originalTest}))`, }); } - let next = source; - for (const edit of edits.sort((left, right) => right.start - left.start)) { - next = next.slice(0, edit.start) + edit.replacement + next.slice(edit.end); - } - parse(next, { ecmaVersion: "latest", sourceType: "module" }); + const next = applyEdits(source, edits); return { status: "patched", source: next }; } catch (error) { return { status: "unexpected-shape", source, reason: error.message }; diff --git a/scripts/patch-api-key-home-navigation.test.js b/scripts/patch-api-key-home-navigation.test.js index 1eb1bf76..186746ae 100644 --- a/scripts/patch-api-key-home-navigation.test.js +++ b/scripts/patch-api-key-home-navigation.test.js @@ -30,7 +30,9 @@ function fixture() { "f=u?.pathname===`/library`||u?.pathname.startsWith(`/library/`);", "if(u!=null&&!f&&e.set(Pti,n,{location:u,selectedProject:d}),SFe(e,i),a){r(`/`,{state:{sidebarProductMode:i}});return}", "if(!o)return;if(l==null){s();return}r(l.location)}", + "function homeArea(e){return e?.pathname.startsWith(`/settings/`)?null:`home`}", "function Pjo(){let i=store(),h=navigate(),a=start(),{accountId:O,authMethod:k}=mp(),", + "p=location(),selected=homeArea(p)===`home`&&mode()===`codex`,", "c=()=>{wti(i,{codexLocalAccessStatus:`allowed`,currentMode:`codex`,navigate:h,nextMode:`codex`,openHome:!0,startNewConversation:a})};return c}", "function Rail({selectedArea:A}){let P=scope(),N=productMode(),C=auth(),", "{accountId:w,authMethod:T,userId:E,isLoading:D}=C,O=`auth:${T}`,", @@ -77,7 +79,7 @@ function clickHome(source, authMethod, { }; const run = Function("activeStore", "recordNavigation", "authMethod", [ "const wc=`wc`,Ug=`Ug`,Pti=`Pti`,ye=`ye`;", - "const store=()=>activeStore,navigate=()=>path=>recordNavigation(path),start=()=>()=>{};", + "const store=()=>activeStore,location=()=>activeStore.get(Ug),mode=()=>`codex`,navigate=()=>path=>recordNavigation(path),start=()=>()=>{};", "const mp=()=>({accountId:null,authMethod});const dei=()=>{},SFe=()=>{};", source, "return Pjo()();", @@ -104,13 +106,13 @@ test("API-key 远程会话点击首页保持当前会话", () => { assert.deepEqual(navigations, []); }); -test("API-key 根路径不短路,保留官方空数据落地页导航", () => { +test("API-key 根路径已属于首页区域时不再导航到空路由", () => { const result = patchSource(fixture()); const navigations = clickHome(result.source, "apikey", { currentPath: "/", }); - assert.deepEqual(navigations, ["/"]); + assert.deepEqual(navigations, []); }); test("API-key 根路径携带会话位置状态时保持当前会话", () => { @@ -232,7 +234,7 @@ test("ChatGPT 重选功能导航栏首页时不获得 API-key 状态会话短路 test("旧版缺少状态会话判断的首页补丁会被拒绝", () => { const patched = patchSource(fixture()); const incomplete = patched.source - .replace("||u.state?.sidebarThreadLocationId!=null", "") + .replace("&&homeArea(u)===`home`", "") .replace(new RegExp(`if\\(\\/\\* Codex:API-key 首页保持状态会话。 \\*\\/[\\s\\S]*?return;`), ""); const result = patchSource(incomplete); @@ -272,7 +274,7 @@ test("导航跟踪器不唯一时明确失败", () => { const source = fixture() + fixture() .replaceAll("Lhc", "Mhc").replaceAll("Sti", "Tti") .replaceAll("wti", "xti").replaceAll("Pjo", "Qjo") - .replaceAll("Rail", "Sail"); + .replaceAll("Rail", "Sail").replaceAll("homeArea", "awayArea"); const result = patchSource(source); assert.equal(result.status, "unexpected-shape"); diff --git a/scripts/patch-archive-delete.js b/scripts/patch-archive-delete.js index 53700d2d..b8602feb 100644 --- a/scripts/patch-archive-delete.js +++ b/scripts/patch-archive-delete.js @@ -16,6 +16,7 @@ const fs = require("fs"); const path = require("path"); const acorn = require("acorn"); +const { key, literal, nodes } = require("./patch-ast-util"); const { locateBundles, relPath, SRC_DIR } = require("./patch-util"); function walkArchive(node, visitor) { @@ -175,25 +176,325 @@ function patchArchivedProviderQueries(bundles, isCheck) { return { patched, already }; } -function hasNativeArchiveDelete(code) { - const legacyMarkers = [ - "delete-archived-conversation", - "delete-all-archived-conversations", - "showDeleteButton", - "settings.dataControls.archivedChats.deleteConfirm.title", - "thread/delete", - ]; - const currentMarkers = [ - "delete-archived-conversation", - "delete-archived-conversations", - "deleteArchivedConversation", - "deleteAllArchivedConversations", - "showDeleteButton", - "thread/delete", - ]; - return [legacyMarkers, currentMarkers].some((markers) => - markers.every((marker) => code.includes(marker)), +function memberName(node) { + if (node?.type === "ChainExpression") node = node.expression; + if (node?.type !== "MemberExpression") return null; + return !node.computed && node.property.type === "Identifier" + ? node.property.name : key(node.property); +} + +function bindingNames(root, value) { + return nodes(root, (node) => + (node.type === "VariableDeclarator" && node.init === value && node.id?.type === "Identifier") || + (node.type === "AssignmentExpression" && node.right === value && node.left?.type === "Identifier")) + .map(owner => owner.type === "VariableDeclarator" ? owner.id.name : owner.left.name); +} + +function objectProperty(node, name) { + return node?.type === "ObjectExpression" + ? node.properties.find(property => property.type === "Property" && key(property.key) === name) ?? null + : null; +} + +function receiverSource(source, call) { + const callee = call.callee?.type === "ChainExpression" ? call.callee.expression : call.callee; + return callee?.type === "MemberExpression" + ? source.slice(callee.object.start, callee.object.end) + : null; +} + +function inspectMutationChain(ast, source) { + return nodes(ast, node => node.type === "FunctionDeclaration").filter(fn => { + const deleteCallbacks = nodes(fn, (node, parent) => { + if (node.type !== "ArrowFunctionExpression" && node.type !== "FunctionExpression") return false; + if (!((parent?.type === "AssignmentExpression" && parent.left?.type === "Identifier") || + (parent?.type === "VariableDeclarator" && parent.id?.type === "Identifier"))) return false; + const calls = nodes(node, item => item.type === "CallExpression" && + ["deleteArchivedConversation", "deleteAllArchivedConversations"].includes(memberName(item.callee))); + const receivers = new Map(); + for (const call of calls) { + const receiver = receiverSource(source, call); + if (receiver == null) continue; + if (!receivers.has(receiver)) receivers.set(receiver, new Set()); + receivers.get(receiver).add(memberName(call.callee)); + } + return [...receivers.values()].some(methods => methods.has("deleteArchivedConversation") && + methods.has("deleteAllArchivedConversations")); + }); + if (deleteCallbacks.length !== 1) return false; + const callbackBindings = new Set(bindingNames(fn, deleteCallbacks[0])); + if (callbackBindings.size !== 1) return false; + + const mutationConfigs = nodes(fn, node => node.type === "ObjectExpression" && + objectProperty(node, "mutationFn")?.value?.type === "Identifier" && + callbackBindings.has(objectProperty(node, "mutationFn").value.name)); + const configBindings = new Set(mutationConfigs.flatMap(config => bindingNames(fn, config))); + if (configBindings.size !== 1) return false; + + const mutationHandles = new Set(nodes(fn, node => node.type === "CallExpression" && + node.arguments.some(argument => argument?.type === "Identifier" && + configBindings.has(argument.name))).flatMap(call => bindingNames(fn, call))); + if (mutationHandles.size !== 1) return false; + + const confirmCallbacks = nodes(fn, node => + (node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression") && + nodes(node, call => call.type === "CallExpression" && memberName(call.callee) === "mutate" && + call.callee.object?.type === "Identifier" && mutationHandles.has(call.callee.object.name)).length > 0); + const confirmBindings = new Set(confirmCallbacks.flatMap(callback => bindingNames(fn, callback))); + if (confirmBindings.size < 1) return false; + return nodes(fn, node => node.type === "Property" && key(node.key) === "onConfirm" && + node.value?.type === "Identifier" && confirmBindings.has(node.value.name)).length === 1; + }); +} + +function inspectManagerDeleteChain(protocolAst) { + const helperFunctions = new Map(nodes(protocolAst, node => node.type === "FunctionDeclaration" && + node.id?.type === "Identifier").map(fn => [fn.id.name, fn])); + return nodes(protocolAst, node => node.type === "ClassDeclaration" || node.type === "ClassExpression") + .filter(classNode => { + const methods = new Map(classNode.body.body.filter(item => item.type === "MethodDefinition") + .map(method => [key(method.key), method])); + const names = ["deleteArchivedConversation", "deleteAllArchivedConversations"]; + if (names.some(name => !methods.has(name))) return false; + const helperNames = names.map(name => new Set(nodes(methods.get(name).value.body, + call => call.type === "CallExpression" && call.callee?.type === "Identifier") + .map(call => call.callee.name))); + const sharedHelpers = [...helperNames[0]].filter(name => helperNames[1].has(name)); + const helperLinked = sharedHelpers.some(name => { + const helper = helperFunctions.get(name); + const context = helper?.params[0]?.type === "Identifier" ? helper.params[0].name : null; + if (context == null) return false; + const runtimeCalls = nodes(helper, call => call.type === "CallExpression" && + memberName(call.callee) === "deleteArchivedThreads" && + call.callee.object?.type === "MemberExpression" && + memberName(call.callee.object) === "runtime" && + call.callee.object.object?.type === "Identifier" && + call.callee.object.object.name === context); + if (runtimeCalls.length !== 1) return false; + return names.every(methodName => nodes(methods.get(methodName).value.body, call => + call.type === "CallExpression" && call.callee?.type === "Identifier" && + call.callee.name === name && call.arguments.some(argument => + argument?.type === "ObjectExpression" && + objectProperty(argument, "runtime")?.value?.type === "MemberExpression" && + objectProperty(argument, "runtime").value.object?.type === "ThisExpression" && + memberName(objectProperty(argument, "runtime").value) === "runtime")).length === 1); + }); + const directLinked = names.every(name => nodes(methods.get(name).value.body, + call => call.type === "CallExpression" && + memberName(call.callee) === "deleteArchivedThreads" && + call.callee.object?.type === "MemberExpression" && + call.callee.object.object?.type === "ThisExpression" && + memberName(call.callee.object) === "runtime").length === 1); + return helperLinked || directLinked; + }); +} + +function functionForBinding(root, name) { + const functions = nodes(root, (node, parent) => + (node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression") && + ((parent?.type === "VariableDeclarator" && parent.id?.type === "Identifier" && + parent.id.name === name) || + (parent?.type === "AssignmentExpression" && parent.left?.type === "Identifier" && + parent.left.name === name))); + return functions.length === 1 ? functions[0] : null; +} + +function componentNameForProps(ast, props) { + const calls = nodes(ast, call => call.type === "CallExpression" && + call.arguments[0]?.type === "Identifier" && call.arguments[1] === props); + return calls.length === 1 ? calls[0].arguments[0].name : null; +} + +function destructuredPropertyBinding(fn, propertyName) { + const bindings = nodes(fn, node => node.type === "ObjectPattern").flatMap(pattern => + pattern.properties.filter(property => property.type === "Property" && + key(property.key) === propertyName && property.value?.type === "Identifier") + .map(property => property.value.name)); + return bindings.length === 1 ? bindings[0] : null; +} + +function inspectRowMutationLink(ast, mutationFunction, rowFunctions, deleteProps) { + const statePairs = nodes(mutationFunction, node => node.type === "VariableDeclarator" && + node.id?.type === "ArrayPattern" && node.id.elements.length >= 2 && + node.id.elements[0]?.type === "Identifier" && node.id.elements[1]?.type === "Identifier" && + node.init?.type === "CallExpression" && literal(node.init.arguments[0]) === null) + .map(node => ({ value: node.id.elements[0].name, setter: node.id.elements[1].name })); + const confirmProps = nodes(mutationFunction, node => node.type === "Property" && + key(node.key) === "onConfirm" && node.value?.type === "Identifier"); + const linked = []; + + for (const confirmProp of confirmProps) { + const confirm = functionForBinding(mutationFunction, confirmProp.value.name); + if (confirm == null) continue; + for (const state of statePairs) { + const clearsState = nodes(confirm, call => call.type === "CallExpression" && + call.callee?.type === "Identifier" && call.callee.name === state.setter && + call.arguments.length === 1 && literal(call.arguments[0]) === null).length > 0; + const mutatesState = nodes(confirm, call => call.type === "CallExpression" && + memberName(call.callee) === "mutate" && + nodes({ type: "Arguments", values: call.arguments }, node => + node.type === "Identifier" && node.name === state.value).length > 0).length > 0; + if (!mutatesState || !clearsState) continue; + + const openDeleteProps = nodes(mutationFunction, node => node.type === "ObjectExpression" && + objectProperty(node, "onDelete")?.value != null && + nodes(objectProperty(node, "onDelete").value, call => call.type === "CallExpression" && + call.callee?.type === "Identifier" && call.callee.name === state.setter && + nodes(call, item => item.type === "Property" && key(item.key) === "kind" && + literal(item.value) === "single").length === 1).length === 1); + for (const props of openDeleteProps) { + const groupName = componentNameForProps(ast, props); + const groupFunction = nodes(ast, node => node.type === "FunctionDeclaration" && + node.id?.name === groupName)[0]; + if (groupFunction == null) continue; + const groupDelete = destructuredPropertyBinding(groupFunction, "onDelete"); + if (groupDelete == null) continue; + for (const rowProps of deleteProps) { + const rowName = componentNameForProps(ast, rowProps); + if (!rowFunctions.some(fn => fn.id?.name === rowName)) continue; + const rowDelete = objectProperty(rowProps, "onDelete")?.value; + if (rowDelete != null && nodes(rowDelete, call => call.type === "CallExpression" && + call.callee?.type === "Identifier" && call.callee.name === groupDelete).length === 1) { + linked.push(rowProps); + } + } + } + } + } + return [...new Set(linked)]; +} + +function rootIdentifier(node) { + if (node?.type === "ChainExpression") node = node.expression; + while (node?.type === "MemberExpression") node = node.object; + return node?.type === "Identifier" ? node.name : null; +} + +function hasDeletionHandlerForRoot(root, scope) { + return nodes(scope, call => call.type === "CallExpression" && + memberName(call.callee) === "handleThreadDeletion" && + call.arguments.some(argument => nodes(argument, item => item.type === "MemberExpression" && + memberName(item) === "threadId" && rootIdentifier(item) === root).length > 0)).length > 0; +} + +function deletedComparisonRoot(node) { + if (node?.type !== "BinaryExpression" || !["===", "=="].includes(node.operator)) return null; + const method = literal(node.left) === "thread/deleted" + ? node.right + : literal(node.right) === "thread/deleted" + ? node.left + : null; + return memberName(method) === "method" ? rootIdentifier(method) : null; +} + +function handlesDeletedNotification(fn) { + const switches = nodes(fn, node => node.type === "SwitchStatement" && + memberName(node.discriminant) === "method"); + for (const statement of switches) { + const root = rootIdentifier(statement.discriminant); + if (root == null) continue; + for (const branch of statement.cases) { + if (literal(branch.test) !== "thread/deleted") continue; + if (hasDeletionHandlerForRoot(root, { type: "CaseBody", body: branch.consequent })) return true; + } + } + + const conditionals = nodes(fn, node => + node.type === "IfStatement" || node.type === "ConditionalExpression"); + for (const conditional of conditionals) { + const root = deletedComparisonRoot(conditional.test); + if (root != null && hasDeletionHandlerForRoot(root, conditional.consequent)) return true; + } + + const logicalBranches = nodes(fn, node => node.type === "LogicalExpression" && node.operator === "&&"); + for (const branch of logicalBranches) { + const root = deletedComparisonRoot(branch.left); + if (root != null && hasDeletionHandlerForRoot(root, branch.right)) return true; + } + return false; +} + +function inspectNativeArchiveDelete(code, protocolCode) { + const ast = acorn.parse(code, { ecmaVersion: "latest", sourceType: "module" }); + const protocolAst = acorn.parse(protocolCode, { ecmaVersion: "latest", sourceType: "module" }); + + const mutationFunctions = inspectMutationChain(ast, code); + if (mutationFunctions.length !== 1) return null; + + const deleteProps = nodes(ast, node => node.type === "ObjectExpression").filter(object => { + const names = new Set(object.properties.filter(property => property.type === "Property") + .map(property => key(property.key))); + return names.has("showDeleteButton") && names.has("onDelete"); + }); + if (deleteProps.length < 1) return null; + + const rowFunctions = nodes(ast, node => node.type === "FunctionDeclaration").filter(fn => { + const patterns = [fn.params, ...nodes(fn.body, node => node.type === "ObjectPattern")].flat(); + const bindings = patterns.filter(pattern => pattern?.type === "ObjectPattern").map(pattern => + Object.fromEntries(pattern.properties.filter(property => property.type === "Property" && + property.value?.type === "Identifier").map(property => [key(property.key), property.value.name]))); + const props = bindings.find(item => item.showDeleteButton && item.onDelete); + if (props == null) return false; + const usesDeleteGuard = nodes(fn.body, node => node.type === "Identifier" && + node.name === props.showDeleteButton).length > 1; + const invokesDelete = nodes(fn.body, node => + (node.type === "CallExpression" && node.callee?.type === "Identifier" && + node.callee.name === props.onDelete) || + (node.type === "Property" && key(node.key) === "onClick" && + node.value?.type === "Identifier" && node.value.name === props.onDelete)).length > 0; + return usesDeleteGuard && invokesDelete; + }); + if (rowFunctions.length !== 1) return null; + const linkedDeleteProps = inspectRowMutationLink( + ast, + mutationFunctions[0], + rowFunctions, + deleteProps, ); + if (linkedDeleteProps.length < 1) return null; + + const managerChains = inspectManagerDeleteChain(protocolAst); + if (managerChains.length !== 1) return null; + const runtimeDeletes = nodes(protocolAst, node => + (node.type === "Property" || node.type === "MethodDefinition") && + key(node.key) === "deleteArchivedThreads"); + if (runtimeDeletes.length !== 1) return null; + const runtimeCalls = nodes(runtimeDeletes[0], node => node.type === "CallExpression" && + ["deleteArchivedThread", "deleteAllArchivedThreads"].includes(memberName(node.callee))); + const runtimeReceivers = new Map(); + for (const call of runtimeCalls) { + const receiver = receiverSource(protocolCode, call); + if (receiver == null) continue; + if (!runtimeReceivers.has(receiver)) runtimeReceivers.set(receiver, new Set()); + runtimeReceivers.get(receiver).add(memberName(call.callee)); + } + if (![...runtimeReceivers.values()].some(methods => methods.has("deleteArchivedThread") && + methods.has("deleteAllArchivedThreads"))) return null; + const protocolMethods = nodes(protocolAst, node => + (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || + node.type === "ArrowFunctionExpression") && + nodes(node, call => call.type === "CallExpression" && + ["sendRequest", "sendAppServerRequest", "sendAppServerExtensionRequest"] + .includes(memberName(call.callee)) && literal(call.arguments[0]) === "thread/delete").length > 0); + const deleteNotifications = nodes(protocolAst, node => + (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || + node.type === "ArrowFunctionExpression") && + handlesDeletedNotification(node)); + if (protocolMethods.length < 1 || deleteNotifications.length < 1) return null; + + return { + deleteProps: linkedDeleteProps.length, + mutationFunction: mutationFunctions[0].id?.name ?? null, + rowFunction: rowFunctions[0].id?.name ?? null, + }; +} + +function hasNativeArchiveDelete(code, protocolCode = code) { + try { + return inspectNativeArchiveDelete(code, protocolCode) != null; + } catch { + return false; + } } // ─── Layer 1: app-main route injection ────────────────────────── @@ -216,8 +517,7 @@ function patchAppMain(bundles, isCheck) { const routeRe = /(["`])unarchive-conversation\1:(\w+)\(async\((\w+),\{conversationId:(\w+)\}\)=>\{\s*await \3\.unarchiveConversation\(\4\)\s*\}\)/; const routeMatch = code.match(routeRe); if (!routeMatch) { - console.log(` [!] ${relPath(bundle.path)}: unarchive-conversation route not found`); - continue; + throw new Error(`${relPath(bundle.path)}: unarchive-conversation route not found`); } const q = routeMatch[1]; // quote style @@ -260,8 +560,7 @@ function patchDataControls(bundles, isCheck) { try { ast = acorn.parse(code, { ecmaVersion: 2022, sourceType: "module" }); } catch (e) { - console.log(` [!] ${relPath(bundle.path)}: parse failed: ${e.message}`); - continue; + throw new Error(`${relPath(bundle.path)}: parse failed: ${e.message}`); } // ── Step 1: Extract import variable names via AST ImportDeclarations ── @@ -343,8 +642,7 @@ function patchDataControls(bundles, isCheck) { ]); if (!rowFunc) { - console.log(` [!] ${relPath(bundle.path)}: row function not found`); - continue; + throw new Error(`${relPath(bundle.path)}: row function not found`); } // Inside the row function, find: @@ -410,13 +708,12 @@ function patchDataControls(bundles, isCheck) { !threadVar || !hostIdVar || !queryClientVar || !contentVar || !unarchiveBtnVar || childrenArrayStart < 0 ) { - console.log(` [!] ${relPath(bundle.path)}: could not resolve all variables`); - console.log( - ` msgFn=${msgFnName} btn=${btnComponent} jsx=${jsxRuntime}` + + throw new Error( + `${relPath(bundle.path)}: could not resolve all delete-button variables ` + + `(msgFn=${msgFnName} btn=${btnComponent} jsx=${jsxRuntime}` + ` thread=${threadVar} host=${hostIdVar} qc=${queryClientVar}` + - ` content=${contentVar} unarchiveBtn=${unarchiveBtnVar}`, + ` content=${contentVar} unarchiveBtn=${unarchiveBtnVar})`, ); - continue; } // ── Step 4: Build delete button and splice into children array ── @@ -485,9 +782,24 @@ function main() { pattern: /^data-controls-.*\.js$/, ...(platform ? { platform } : {}), }); - const nativeBundles = dataControlsBundles.filter((bundle) => - hasNativeArchiveDelete(fs.readFileSync(bundle.path, "utf-8")), - ); + const protocolBundles = locateBundles({ + dir: "assets", + pattern: /^app-initial-.*\.js$/, + ...(platform ? { platform } : {}), + }); + const protocolByPlatform = new Map(); + for (const bundle of protocolBundles) { + if (protocolByPlatform.has(bundle.platform)) { + throw new Error(`[${bundle.platform}] app-initial protocol bundle 数量异常`); + } + protocolByPlatform.set(bundle.platform, fs.readFileSync(bundle.path, "utf-8")); + } + const nativeBundles = dataControlsBundles.filter((bundle) => { + const protocolCode = protocolByPlatform.get(bundle.platform); + return protocolCode != null && hasNativeArchiveDelete( + fs.readFileSync(bundle.path, "utf-8"), protocolCode, + ); + }); const nativePlatforms = new Set(nativeBundles.map((bundle) => bundle.platform)); for (const bundle of nativeBundles) { @@ -500,6 +812,21 @@ function main() { pattern: /^app-main-.*\.js$/, ...(platform ? { platform } : {}), }); + const expectedPlatforms = platform + ? [platform] + : ["mac-arm64", "mac-x64", "win"].filter(name => + fs.existsSync(path.join(SRC_DIR, name, "_asar"))); + for (const name of expectedPlatforms) { + if (nativePlatforms.has(name)) continue; + const appMainCount = appMainBundles.filter(bundle => bundle.platform === name).length; + const dataControlsCount = dataControlsBundles.filter(bundle => bundle.platform === name).length; + if (appMainCount !== 1 || dataControlsCount !== 1) { + throw new Error( + `[${name}] 归档删除链路不完整:原生实现未通过验证,` + + `fallback app-main=${appMainCount}, data-controls=${dataControlsCount}`, + ); + } + } const routePatched = patchAppMain( appMainBundles.filter((bundle) => !nativePlatforms.has(bundle.platform)), isCheck, @@ -522,6 +849,7 @@ if (require.main === module) main(); module.exports = { analyzeArchivedListProviders, hasNativeArchiveDelete, + inspectNativeArchiveDelete, patchAppMain, patchArchivedListProviders, patchArchivedProviderQueries, diff --git a/scripts/patch-ast-util.js b/scripts/patch-ast-util.js new file mode 100644 index 00000000..bcc60fa8 --- /dev/null +++ b/scripts/patch-ast-util.js @@ -0,0 +1,60 @@ +"use strict"; + +const { parse } = require("acorn"); + +function walk(root, visit, { ownScope = false } = {}) { + function visitNode(node, parent) { + if (!node || typeof node !== "object" || !node.type) return; + if (ownScope && node !== root && /Function/.test(node.type)) return; + visit(node, parent); + for (const [key, value] of Object.entries(node)) { + if (["type", "start", "end"].includes(key)) continue; + if (Array.isArray(value)) { + for (const child of value) if (child?.type) visitNode(child, node); + } else if (value?.type) { + visitNode(value, node); + } + } + } + visitNode(root, null); +} + +function nodes(root, predicate, options) { + const found = []; + walk(root, (node, parent) => { + if (predicate(node, parent)) found.push(node); + }, options); + return found; +} + +function literal(node) { + if (node?.type === "Literal") return node.value; + if (node?.type === "TemplateLiteral" && node.expressions.length === 0) { + return node.quasis[0].value.cooked; + } + return undefined; +} + +function key(node) { + if (!node) return null; + if (node.type === "Identifier") return node.name; + return literal(node) ?? null; +} + +function unique(items, label) { + if (items.length !== 1) throw new Error(`${label} 数量异常(${items.length})`); + return items[0]; +} + +function applyEdits(source, edits) { + let next = source; + for (const edit of [...edits].sort((left, right) => right.start - left.start)) { + const replacement = edit.text ?? edit.replacement; + if (typeof replacement !== "string") throw new Error("AST edit 缺少替换文本"); + next = next.slice(0, edit.start) + replacement + next.slice(edit.end); + } + parse(next, { ecmaVersion: "latest", sourceType: "module" }); + return next; +} + +module.exports = { applyEdits, key, literal, nodes, unique, walk }; diff --git a/scripts/patch-browser-auth.js b/scripts/patch-browser-auth.js index 03208aa7..dc280750 100644 --- a/scripts/patch-browser-auth.js +++ b/scripts/patch-browser-auth.js @@ -18,6 +18,7 @@ const fs = require("fs"); const path = require("path"); const { parse } = require("acorn"); +const { key, nodes, walk } = require("./patch-ast-util"); const { SRC_DIR, relPath } = require("./patch-util"); const IDENTITY_ERROR = @@ -31,25 +32,176 @@ const MANAGED_REQUEST_HEADER_MARKERS = [ "request_headers", ]; -function hasNativeManagedRequestHeaders(source) { - return ( - !source.includes(REQUEST_HEADER_GATE) && - MANAGED_REQUEST_HEADER_MARKERS.every((marker) => source.includes(marker)) - ); +function memberName(node) { + if (node?.type === "ChainExpression") node = node.expression; + if (node?.type !== "MemberExpression") return null; + return !node.computed && node.property.type === "Identifier" + ? node.property.name : key(node.property); +} + +function classBinding(node, parent) { + if (node.type === "ClassDeclaration") return node.id?.name ?? null; + return parent?.type === "VariableDeclarator" && parent.id?.type === "Identifier" + ? parent.id.name : null; +} + +function unwrapChain(node) { + return node?.type === "ChainExpression" ? node.expression : node; +} + +function constructedClass(node) { + node = unwrapChain(node); + return node?.type === "NewExpression" && node.callee?.type === "Identifier" + ? node.callee.name : null; +} + +function thisProperty(node) { + node = unwrapChain(node); + if (node?.type !== "MemberExpression" || unwrapChain(node.object)?.type !== "ThisExpression") { + return null; + } + return memberName(node); +} + +function constructorPropertySources(classNode, property) { + const constructors = classNode.body.body.filter(method => + method.type === "MethodDefinition" && method.kind === "constructor"); + if (constructors.length !== 1) return []; + const constructor = constructors[0]; + return nodes(constructor.value.body, item => item.type === "AssignmentExpression" && + thisProperty(item.left) === property).map(assignment => { + const directClass = constructedClass(assignment.right); + if (directClass != null) return { directClass }; + if (assignment.right?.type !== "Identifier") return null; + const parameterIndex = constructor.value.params.findIndex(parameter => + parameter.type === "Identifier" && parameter.name === assignment.right.name); + return parameterIndex < 0 ? null : { parameterIndex }; + }).filter(Boolean); +} + +function hasConstructedReceiver(ast, ownerClass, ownerNode, receiver, targetClass) { + receiver = unwrapChain(receiver); + if (receiver?.type === "Identifier") { + return nodes(ast, node => node.type === "VariableDeclarator" && + node.id?.type === "Identifier" && node.id.name === receiver.name && + constructedClass(node.init) === targetClass).length === 1; + } + + const property = thisProperty(receiver); + if (property == null) return false; + const sources = constructorPropertySources(ownerNode, property); + if (sources.some(source => source.directClass === targetClass)) return true; + return sources.some(source => source.parameterIndex != null && + nodes(ast, node => node.type === "NewExpression" && + node.callee?.type === "Identifier" && node.callee.name === ownerClass && + constructedClass(node.arguments[source.parameterIndex]) === targetClass).length >= 1); } -function walk(node, visitor) { - if (!node || typeof node !== "object") return; - if (node.type) visitor(node); - for (const [key, child] of Object.entries(node)) { - if (key === "type" || key === "start" || key === "end") continue; - if (Array.isArray(child)) { - for (const item of child) { - if (item && typeof item === "object" && item.type) walk(item, visitor); +function inspectNativeManagedRequestHeaders(source) { + if (source.includes(REQUEST_HEADER_GATE)) return null; + const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const definitions = []; + walk(ast, (node, parent) => { + if (node.type !== "ClassDeclaration" && node.type !== "ClassExpression") return; + const owner = classBinding(node, parent); + if (owner == null) return; + const methods = node.body.body.filter(method => method.type === "MethodDefinition" && + key(method.key) === "getExtensionRequestHeaders").filter(method => { + const body = method.value?.body; + if (body == null) return false; + const requirementCalls = nodes(body, node => node.type === "CallExpression" && + memberName(node.callee) === "readRequirements"); + const requestHeaders = nodes(body, node => node.type === "MemberExpression" && + memberName(node) === "requestHeaders"); + return requirementCalls.length === 1 && requestHeaders.length === 1 && + source.slice(method.start, method.end).includes("requirements") && + source.slice(method.start, method.end).includes("browserUse") && + source.slice(method.start, method.end).includes("extension"); + }); + for (const method of methods) definitions.push({ method, owner }); + }); + if (definitions.length !== 1) return null; + + const transports = []; + walk(ast, (node, parent) => { + if (node.type !== "ClassDeclaration" && node.type !== "ClassExpression") return; + const binding = classBinding(node, parent); + if (binding == null) return; + const methods = node.body.body.filter(item => item.type === "MethodDefinition"); + const send = methods.filter(method => key(method.key) === "sendSessionRequest"); + const constructor = methods.filter(method => method.kind === "constructor"); + if (send.length !== 1 || constructor.length !== 1) return; + const assignments = nodes(send[0].value.body, item => item.type === "AssignmentExpression" && + memberName(item.left) === "request_headers"); + // 新版同时把请求头写入本次请求和 lastSessionParams;两处写入都属于 + // 同一条传输链,不能再假设 request_headers 只赋值一次。 + if (assignments.length < 1) return; + const callbackCalls = nodes(send[0].value.body, item => item.type === "CallExpression" && + item.callee?.type === "MemberExpression" && item.callee.object?.type === "ThisExpression"); + for (const call of callbackCalls) { + const callback = memberName(call.callee); + const headerBindings = new Set(nodes(send[0].value.body, item => + item.type === "VariableDeclarator" && item.id?.type === "Identifier" && + item.init != null && nodes(item.init, nested => nested === call).length === 1) + .map(item => item.id.name)); + const flowsToRequestHeaders = assignments.some(assignment => + nodes(assignment.right, item => item.type === "Identifier" && + headerBindings.has(item.name)).length > 0); + if (!flowsToRequestHeaders) continue; + const wiring = nodes(constructor[0].value.body, item => item.type === "AssignmentExpression" && + item.left?.type === "MemberExpression" && item.left.object?.type === "ThisExpression" && + memberName(item.left) === callback && item.right?.type === "Identifier"); + if (wiring.length !== 1) continue; + const parameterIndex = constructor[0].value.params.findIndex(parameter => + parameter.type === "Identifier" && parameter.name === wiring[0].right.name); + if (parameterIndex < 0) continue; + transports.push({ binding, callback, parameterIndex }); + } + }); + if (transports.length !== 1) return null; + + const transport = transports[0]; + const consumers = []; + walk(ast, (node, parent) => { + if (node.type !== "ClassDeclaration" && node.type !== "ClassExpression") return; + const owner = classBinding(node, parent); + if (owner == null) return; + const transportCalls = nodes(node, item => item.type === "NewExpression" && + item.callee?.type === "Identifier" && item.callee.name === transport.binding && + item.arguments[transport.parameterIndex] != null); + for (const transportCall of transportCalls) { + const callbacks = nodes(transportCall.arguments[transport.parameterIndex], item => + item.type === "CallExpression" && + memberName(item.callee) === "getExtensionRequestHeaders"); + if (callbacks.length !== 1) continue; + const callee = unwrapChain(callbacks[0].callee); + if (hasConstructedReceiver(ast, owner, node, callee.object, definitions[0].owner)) { + consumers.push(transportCall); } - } else if (child && typeof child === "object" && child.type) { - walk(child, visitor); } + }); + + // 兼容未包在宿主类中的简单初始化,但同样要求调用接收者确实由目标类创建。 + for (const transportCall of nodes(ast, (node, parent) => node.type === "NewExpression" && + node.callee?.type === "Identifier" && node.callee.name === transport.binding && + parent?.type !== "MethodDefinition" && node.arguments[transport.parameterIndex] != null)) { + const callbacks = nodes(transportCall.arguments[transport.parameterIndex], item => + item.type === "CallExpression" && memberName(item.callee) === "getExtensionRequestHeaders"); + if (callbacks.length !== 1) continue; + const callee = unwrapChain(callbacks[0].callee); + if (hasConstructedReceiver(ast, null, { body: { body: [] } }, callee.object, definitions[0].owner)) { + consumers.push(transportCall); + } + } + if (consumers.length < 1) return null; + return { consumers: consumers.length, transport: transport.binding }; +} + +function hasNativeManagedRequestHeaders(source) { + try { + return inspectNativeManagedRequestHeaders(source) != null; + } catch { + return false; } } @@ -300,6 +452,7 @@ module.exports = { REQUEST_HEADER_GATE, findRequestHeaderAuthPatches, hasNativeManagedRequestHeaders, + inspectNativeManagedRequestHeaders, locateTargets, patchSource, }; diff --git a/scripts/patch-browser-auth.test.js b/scripts/patch-browser-auth.test.js index 5c695578..a5853788 100644 --- a/scripts/patch-browser-auth.test.js +++ b/scripts/patch-browser-auth.test.js @@ -108,10 +108,13 @@ test("26.1013 原生托管请求头不再依赖 ChatGPT 身份 gate", () => { "class Preferences{async getExtensionRequestHeaders(){", "return(await this.config.readRequirements())?.requirements?.browserUse?.extension?.requestHeaders", "}}", - "class BrowserTransport{async sendSessionRequest(){", - "const headers=await this.preferences.getExtensionRequestHeaders();", + "class BrowserTransport{constructor(readRequestHeaders){this.readRequestHeaders=readRequestHeaders}", + "async sendSessionRequest(){", + "const headers=await this.readRequestHeaders();", "if(this.clientInfo.requestHeadersVersion===1)this.params.request_headers=headers;", "}}", + "const preferences=new Preferences();", + "const browser=new BrowserTransport(async()=>preferences.getExtensionRequestHeaders());", 'async function readBrowserFeatureGate(){throw new Error("Browser feature gates require caller identity.")}', ].join(""); @@ -121,4 +124,38 @@ test("26.1013 原生托管请求头不再依赖 ChatGPT 身份 gate", () => { hasNativeManagedRequestHeaders(source.replace("readRequirements", "readAccountIdentity")), false, ); + assert.equal( + hasNativeManagedRequestHeaders(source.replace("this.readRequestHeaders=readRequestHeaders", "this.other=readRequestHeaders")), + false, + ); + assert.equal( + hasNativeManagedRequestHeaders(source.replace("request_headers=headers", "request_headers=[]")), + false, + ); + assert.equal( + hasNativeManagedRequestHeaders(source.replace( + "class Preferences{", + "class OtherPreferences{async getExtensionRequestHeaders(){return []}}class Preferences{", + ).replace("new Preferences()", "new OtherPreferences()")), + false, + ); +}); + +test("26.1013 原生托管请求头绑定宿主属性、传输回调与真实配置类", () => { + const source = [ + "class Preferences{async getExtensionRequestHeaders(){", + "return(await this.config.readRequirements())?.requirements?.browserUse?.extension?.requestHeaders", + "}}", + "class BrowserTransport{constructor(api,readRequestHeaders){this.api=api;this.readRequestHeaders=readRequestHeaders}", + "async sendSessionRequest(){const headers=await this.readRequestHeaders();this.params.request_headers=headers}}", + "class Browsers{constructor(runtime,preferences){this.runtime=runtime;this.preferences=preferences}", + "refresh(){return new BrowserTransport(this.runtime,async()=>this.preferences?.getExtensionRequestHeaders())}}", + "new Browsers(runtime,new Preferences(config,runtime));", + ].join(""); + + assert.equal(hasNativeManagedRequestHeaders(source), true); + assert.equal( + hasNativeManagedRequestHeaders(source.replace("new Preferences(config,runtime)", "new OtherPreferences()")), + false, + ); }); diff --git a/scripts/patch-hide-pet-menu.js b/scripts/patch-hide-pet-menu.js index 62c05a12..40cb92fe 100644 --- a/scripts/patch-hide-pet-menu.js +++ b/scripts/patch-hide-pet-menu.js @@ -136,6 +136,7 @@ function main() { const check = args.includes("--check"); const targets = locateTargets(platform); if (targets.length === 0) { + if (platform) throw new Error(`[${platform}] 缺少 Pet 菜单目标资源,不能跳过必要补丁`); console.log("[skip] Pet 菜单资源不适用于当前平台"); return; } diff --git a/scripts/patch-mcp-status-refresh.js b/scripts/patch-mcp-status-refresh.js index deccee43..30354455 100644 --- a/scripts/patch-mcp-status-refresh.js +++ b/scripts/patch-mcp-status-refresh.js @@ -9,30 +9,13 @@ const fs = require("node:fs"); const path = require("node:path"); const { parse } = require("acorn"); +const { literal: staticValue, walk } = require("./patch-ast-util"); const { relPath, SRC_DIR } = require("./patch-util"); const MARKER = "/* CodexRebuildMcpStatusRefresh */"; const REFRESH_DELAY_MS = 250; const PLATFORMS = ["mac-arm64", "mac-x64", "win"]; -function walk(node, visit) { - if (!node || typeof node !== "object") return; - if (node.type) visit(node); - for (const [key, value] of Object.entries(node)) { - if (["type", "start", "end"].includes(key)) continue; - if (Array.isArray(value)) value.forEach((child) => walk(child, visit)); - else if (value?.type) walk(value, visit); - } -} - -function staticValue(node) { - if (node?.type === "Literal") return node.value; - if (node?.type === "TemplateLiteral" && node.expressions.length === 0) { - return node.quasis[0].value.cooked; - } - return undefined; -} - function propertyName(member) { if (member?.type !== "MemberExpression") return null; if (!member.computed && member.property.type === "Identifier") return member.property.name; diff --git a/scripts/patch-model-picker-submenu.js b/scripts/patch-model-picker-submenu.js index 9ad308fb..f2109553 100644 --- a/scripts/patch-model-picker-submenu.js +++ b/scripts/patch-model-picker-submenu.js @@ -193,6 +193,11 @@ function main() { const targets = findTargets(platform); if (targets.length === 0) { + const hasAssets = getPlatforms(platform).some((name) => + fs.existsSync(path.join(SRC_DIR, name, "_asar", "webview", "assets"))); + if (platform || hasAssets) { + throw new Error(`[${platform ?? "all"}] 模型选择器资源未知,不能跳过必要补丁`); + } console.log(" [skip] No model picker submenu bundle found"); return; } diff --git a/scripts/patch-upstream-compat.test.js b/scripts/patch-upstream-compat.test.js index da3bee15..ab80fc68 100644 --- a/scripts/patch-upstream-compat.test.js +++ b/scripts/patch-upstream-compat.test.js @@ -70,26 +70,70 @@ test("识别上游原生工作区根目录传递链路", () => { }); test("识别上游原生归档会话删除功能", () => { - const source = [ - "delete-archived-conversation", - "delete-all-archived-conversations", - "showDeleteButton", - "settings.dataControls.archivedChats.deleteConfirm.title", - "thread/delete", - ].join("|"); - - assert.equal(hasNativeArchiveDelete(source), true); - assert.equal(hasNativeArchiveDelete(source.replace("thread/delete", "thread/archive")), false); - - const currentSource = [ - "delete-archived-conversation", - "delete-archived-conversations", - "deleteArchivedConversation", - "deleteAllArchivedConversations", - "showDeleteButton", - "thread/delete", - ].join("|"); - assert.equal(hasNativeArchiveDelete(currentSource), true); + const dataControls = [ + "function DataControls(manager,ui){", + "const [pending,setPending]=useState(null);", + "const run=async target=>target.kind===`all`?manager.deleteAllArchivedConversations():manager.deleteArchivedConversation(target.thread.id);", + "const mutationConfig={mutationKey:[`delete-archived-conversations`],mutationFn:run};", + "const mutation=useMutation(mutationConfig);const confirm=()=>{if(pending){setPending(null);mutation.mutate(pending)}};", + "return ui(Dialog,{onConfirm:confirm,children:ui(Group,{onDelete:thread=>setPending({kind:`single`,thread})})});}", + "function Group(input){const {onDelete:openDelete}=input;", + "return ui(Row,{showDeleteButton:!0,onDelete:()=>openDelete(thread)})}", + "function Row(input){const {showDeleteButton:show,onDelete:remove}=input;", + "return show?button({onClick:()=>remove()}):null}", + ].join(""); + const protocol = [ + "class Manager{deleteArchivedConversation(id){return this.runtime.deleteArchivedThreads(`local`,id)}", + "deleteAllArchivedConversations(){return this.runtime.deleteArchivedThreads(`local`)}}", + "const runtime={async deleteArchivedThreads(host,id){let service=this.threadArchive;", + "return id==null?await service.deleteAllArchivedThreads({hostId:host}):await service.deleteArchivedThread({hostId:host,threadId:id})}};", + "async function deleteOne(appServer,id){return appServer.sendAppServerRequest(`thread/delete`,{threadId:id})}", + "function notification(event,manager){if(event.method===`thread/deleted`)manager.handleThreadDeletion([event.params.threadId])}", + ].join(""); + + assert.equal(hasNativeArchiveDelete(dataControls, protocol), true); + assert.equal( + hasNativeArchiveDelete(dataControls.replace("onDelete:thread=>setPending", "onDelete:thread=>noop"), protocol), + false, + ); + assert.equal( + hasNativeArchiveDelete(dataControls, protocol.replace("thread/delete", "thread/archive")), + false, + ); + assert.equal( + hasNativeArchiveDelete(dataControls.replace("onConfirm:confirm", "onCancel:confirm"), protocol), + false, + ); + assert.equal( + hasNativeArchiveDelete(dataControls.replace("onDelete:()=>openDelete(thread)", "onDelete:noop"), protocol), + false, + ); + assert.equal( + hasNativeArchiveDelete(dataControls.replace("mutation.mutate(pending)", "mutation.mutate(other);void pending"), protocol), + false, + ); + assert.equal( + hasNativeArchiveDelete(dataControls, protocol.replaceAll("this.runtime.deleteArchivedThreads", "this.runtime.archiveThreads")), + false, + ); + assert.equal( + hasNativeArchiveDelete(dataControls, protocol.replaceAll("this.runtime.deleteArchivedThreads", "this.dead.deleteArchivedThreads")), + false, + ); + assert.equal( + hasNativeArchiveDelete(dataControls, protocol.replace( + "return appServer.sendAppServerRequest(`thread/delete`,{threadId:id})", + "void `thread/delete`;return appServer.sendAppServerRequest(`thread/archive`,{threadId:id})", + )), + false, + ); + assert.equal( + hasNativeArchiveDelete(dataControls, protocol.replace( + "if(event.method===`thread/deleted`)manager.handleThreadDeletion([event.params.threadId])", + "if(event.method===`thread/deleted`){noop()}else{manager.handleThreadDeletion([event.params.threadId])}", + )), + false, + ); }); test("主进程入口兼容 bootstrap 与哈希 main 文件", () => { diff --git a/scripts/prepare-src.js b/scripts/prepare-src.js index fcaf2477..c8f712cd 100644 --- a/scripts/prepare-src.js +++ b/scripts/prepare-src.js @@ -17,12 +17,14 @@ */ const fs = require("fs"); const path = require("path"); -const { execSync, execFileSync } = require("child_process"); +const crypto = require("crypto"); +const { execFileSync } = require("child_process"); const { findUpstreamCodex, getCodexBinarySource, getCometixCodexPackageSpec, } = require("./codex-binary-policy"); +const { resolveSyncDirectory } = require("./sync-upstream"); const SRC = path.join(__dirname, "..", "src"); const PROJECT_ROOT = path.join(__dirname, ".."); @@ -107,9 +109,41 @@ function copyRecursive(src, dest, skipFiles, skipDirs) { /** * Ensure the @cometix/codex platform package is extracted to a temp dir. * Returns the vendor root path (e.g. .../vendor/{triple}/) or null. - * Caches the result so npm pack runs at most once per build. + * Caches the result so the registry package is fetched at most once per build. */ let _vendorRootCache = null; + +function resolveCometixRegistryEntry(platform, metadata) { + const spec = getCometixCodexPackageSpec(platform, metadata?.["dist-tags"]); + const version = spec.slice(spec.lastIndexOf("@") + 1); + const dist = metadata?.versions?.[version]?.dist; + if (typeof dist?.tarball !== "string" || !/^sha512-[A-Za-z0-9+/]+={0,2}$/.test(dist.integrity || "")) { + throw new Error(`@cometix/codex ${version} 缺少可验证的 registry tarball`); + } + const tarball = new URL(dist.tarball); + if (tarball.protocol !== "https:") throw new Error("@cometix/codex tarball 必须使用 HTTPS"); + return { integrity: dist.integrity, spec, tarball: tarball.href, version }; +} + +function registryCurlArgs(url, destination) { + return ["--fail", "--location", "--proto", "=https", "--proto-redir", "=https", + "--retry", "3", "--retry-delay", "2", + "--connect-timeout", "30", "--output", destination, url]; +} + +function downloadRegistryFile(url, destination) { + const curl = process.platform === "win32" ? "curl.exe" : "curl"; + execFileSync(curl, registryCurlArgs(url, destination), { stdio: "inherit" }); +} + +function verifyRegistryIntegrity(file, integrity) { + const expected = Buffer.from(integrity.slice("sha512-".length), "base64"); + const actual = crypto.createHash("sha512").update(fs.readFileSync(file)).digest(); + if (expected.length !== actual.length || !crypto.timingSafeEqual(expected, actual)) { + throw new Error("@cometix/codex registry tarball 完整性校验失败"); + } +} + function ensureVendorExtracted(platform) { if (_vendorRootCache !== undefined && _vendorRootCache !== null) return _vendorRootCache; @@ -131,40 +165,35 @@ function ensureVendorExtracted(platform) { const oldPath = path.join(PROJECT_ROOT, "node_modules", "@cometix", "codex", "vendor", triple); if (fs.existsSync(oldPath)) { _vendorRootCache = oldPath; return oldPath; } - // 3. npm pack platform package - let spec; - try { - const distTags = JSON.parse( - execSync("npm view @cometix/codex dist-tags --json", { - encoding: "utf-8", - stdio: ["pipe", "pipe", "pipe"], - }), - ); - spec = getCometixCodexPackageSpec(platform, distTags); - } catch (error) { - console.log(` [!] unable to resolve @cometix/codex package: ${error.message}`); - return null; - } - - console.log(` [vendor] fetching ${spec} via npm pack...`); - const tmpDir = path.join(PROJECT_ROOT, ".cache", "vendor-pack"); + // 3. 从 pnpm 配置的 registry 直接取得并校验包,避免生成额外全局缓存。 + const tmpDir = path.join(resolveSyncDirectory(), "vendor-pack"); if (fs.existsSync(tmpDir)) fs.rmSync(tmpDir, { recursive: true, force: true }); fs.mkdirSync(tmpDir, { recursive: true }); try { - const tgzName = execSync(`npm pack ${spec} --pack-destination "${tmpDir}"`, { - cwd: tmpDir, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"], - }).trim().split("\n").pop(); + const pnpm = process.platform === "win32" ? "pnpm.cmd" : "pnpm"; + const registryText = execFileSync(pnpm, ["config", "get", "registry"], { + cwd: PROJECT_ROOT, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"], + }).trim() || "https://registry.npmjs.org/"; + const registry = new URL(registryText.endsWith("/") ? registryText : `${registryText}/`); + if (registry.protocol !== "https:") throw new Error("pnpm registry 必须使用 HTTPS"); + const metadataUrl = new URL("@cometix%2Fcodex", registry).href; + const metadataFile = path.join(tmpDir, "metadata.json"); + downloadRegistryFile(metadataUrl, metadataFile); + const entry = resolveCometixRegistryEntry(platform, JSON.parse(fs.readFileSync(metadataFile, "utf-8"))); + console.log(` [vendor] fetching ${entry.spec} from pnpm registry...`); + const tarballFile = path.join(tmpDir, "package.tgz"); + downloadRegistryFile(entry.tarball, tarballFile); + verifyRegistryIntegrity(tarballFile, entry.integrity); const extractDir = path.join(tmpDir, "extracted"); - if (fs.existsSync(extractDir)) fs.rmSync(extractDir, { recursive: true }); fs.mkdirSync(extractDir, { recursive: true }); - execSync(`tar xzf "${path.join(tmpDir, tgzName)}" -C "${extractDir}"`, { stdio: "pipe" }); + execFileSync("tar", ["xzf", tarballFile, "-C", extractDir], { stdio: "pipe" }); const vendorRoot = path.join(extractDir, "package", "vendor", triple); if (fs.existsSync(vendorRoot)) { _vendorRootCache = vendorRoot; return vendorRoot; } - } catch (e) { - console.log(` [!] npm pack failed: ${e.message}`); + } catch (error) { + console.log(` [!] unable to fetch @cometix/codex package: ${error.message}`); } return null; @@ -337,4 +366,6 @@ function main() { console.log(` [ok] src/ ready for ${platform} build`); } -main(); +if (require.main === module) main(); + +module.exports = { registryCurlArgs, resolveCometixRegistryEntry, verifyRegistryIntegrity }; diff --git a/scripts/runtime/accent-presets.mjs b/scripts/runtime/accent-presets.mjs index 32463822..72b0d8c1 100644 --- a/scripts/runtime/accent-presets.mjs +++ b/scripts/runtime/accent-presets.mjs @@ -29,12 +29,19 @@ function clearLocalAccentPreset() { } catch {} } -export function accentPresetSelection(accountTheme, fallback) { - return accountTheme === null ? readLocalAccentPreset() ?? fallback : fallback; +function saveLocalAccentPreset(preset) { + try { + storage()?.setItem(ACCENT_PRESET_STORAGE_KEY, preset); + } catch {} +} + +export function accentPresetSelection(accountTheme, accentSource, fallback) { + if (accountTheme === undefined || accentSource === "chatgpt") return fallback; + return readLocalAccentPreset() ?? fallback; } export function resolveAccentPreset(accentSource, accountPreset) { - if (accountPreset != null) return accentSource === "chatgpt" ? accountPreset : null; + if (accentSource === "chatgpt") return accountPreset; const preset = readLocalAccentPreset(); // 官方账户的“默认”会先解析成 effectiveTheme;未登录时没有这层账户数据。 // Windows 官方当前的有效默认色是 blue,本地模式在渲染阶段补齐同一语义。 @@ -43,12 +50,14 @@ export function resolveAccentPreset(accentSource, accountPreset) { export function selectAccentPreset(accountTheme, preset, applyLocal, selectAccount) { return Promise.resolve().then(() => { + // 上游可能新增预设;本模块不认识时不保存本地值,也不吞掉官方选择动作。 + if (!ACCENT_PRESETS.has(preset)) return selectAccount(); + // 无论当前是否能同步到 ChatGPT 账户,都保留一份本地预设。 + // 自定义 Provider 重启后可能拿不到账户主题;此时仍应恢复用户上次选择的官方预设。 + saveLocalAccentPreset(preset); if (accountTheme !== null) { - clearLocalAccentPreset(); return selectAccount(); } - if (!ACCENT_PRESETS.has(preset)) return; - storage()?.setItem(ACCENT_PRESET_STORAGE_KEY, preset); return applyLocal(); }); } diff --git a/scripts/sync-upstream.js b/scripts/sync-upstream.js index e669caae..1ed7bdc2 100644 --- a/scripts/sync-upstream.js +++ b/scripts/sync-upstream.js @@ -35,9 +35,6 @@ https.globalAgent.options.ca = extraCAs; const PROJECT_ROOT = path.resolve(__dirname, ".."); const SRC_DIR = path.join(PROJECT_ROOT, "src"); -const TEMP_DIR = process.env.CODEX_SYNC_DIR - ? path.resolve(process.env.CODEX_SYNC_DIR) - : path.join(PROJECT_ROOT, ".cache", "upstream-sync"); const VERSION_FILE = path.join(__dirname, ".versions.json"); const APPCAST_ARM64 = "https://persistent.oaistatic.com/codex-app-prod/appcast.xml"; @@ -51,6 +48,16 @@ const CHECK_ONLY = args.includes("--check-only"); const SKIP_MAC = args.includes("--skip-mac"); const SKIP_WIN = args.includes("--skip-win"); +function resolveSyncDirectory() { + const configured = process.env.CODEX_SYNC_DIR?.trim(); + if (!configured) { + throw new Error( + "缺少 CODEX_SYNC_DIR;请由维护入口显式提供可丢弃缓存目录,禁止回退到仓库 .cache", + ); + } + return path.resolve(configured); +} + // ─── Helpers ──────────────────────────────────────────────────── function httpGet(url) { @@ -213,12 +220,13 @@ function clearDir(dir) { } function removeObsoletePackages(currentFile, pattern) { - if (!fs.existsSync(TEMP_DIR)) return []; const keep = path.resolve(currentFile); + const directory = path.dirname(keep); + if (!fs.existsSync(directory)) return []; const removed = []; - for (const entry of fs.readdirSync(TEMP_DIR, { withFileTypes: true })) { + for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { if (!entry.isFile() || !pattern.test(entry.name)) continue; - const file = path.join(TEMP_DIR, entry.name); + const file = path.join(directory, entry.name); if (path.resolve(file) === keep) continue; fs.rmSync(file, { force: true }); removed.push(entry.name); @@ -442,14 +450,16 @@ function validateWindowsPackage(extractDir, expected) { // ─── Extract macOS ────────────────────────────────────────────── async function syncMac(variant, appcastUrl, destDir) { + const tempDir = resolveSyncDirectory(); + fs.mkdirSync(tempDir, { recursive: true }); const label = `macOS-${variant}`; console.log(`\n-- ${label}`); const info = await getAppcastVersion(appcastUrl); console.log(` version: ${info.version} (build ${info.build})`); - const zipPath = path.join(TEMP_DIR, `Codex-${variant}-${info.version}.zip`); - const extractDir = path.join(TEMP_DIR, `${variant}-extract`); + const zipPath = path.join(tempDir, `Codex-${variant}-${info.version}.zip`); + const extractDir = path.join(tempDir, `${variant}-extract`); const variantPattern = new RegExp(`^Codex-${variant.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}-.*\\.zip$`, "i"); removeObsoletePackages(zipPath, variantPattern); @@ -473,12 +483,14 @@ async function syncMac(variant, appcastUrl, destDir) { // ─── Extract Windows ──────────────────────────────────────────── async function syncWin(destDir, info) { + const tempDir = resolveSyncDirectory(); + fs.mkdirSync(tempDir, { recursive: true }); console.log("\n-- Windows"); console.log(` package: ${info.packageName}`); console.log(` version: ${info.version} (${info.architecture})`); - const msixPath = path.join(TEMP_DIR, info.packageName || `codex-win-${info.version}.msix`); - const extractDir = path.join(TEMP_DIR, "win-extract"); + const msixPath = path.join(tempDir, info.packageName || `codex-win-${info.version}.msix`); + const extractDir = path.join(tempDir, "win-extract"); removeObsoletePackages(msixPath, /^OpenAI\.Codex_.*_x64__.*\.msix$/i); if (info.localPackage) { @@ -565,7 +577,6 @@ function saveVersions(v) { async function main() { console.log("== Codex upstream sync ==\n"); - fs.mkdirSync(TEMP_DIR, { recursive: true }); const results = {}; @@ -629,6 +640,7 @@ module.exports = { selectWindowsPackage, validateWindowsPackage, removeObsoletePackages, + resolveSyncDirectory, }; if (require.main === module) { diff --git a/scripts/sync-upstream.test.js b/scripts/sync-upstream.test.js index 5bb7f072..eab77da3 100644 --- a/scripts/sync-upstream.test.js +++ b/scripts/sync-upstream.test.js @@ -5,6 +5,7 @@ const os = require("os"); const path = require("path"); const { + resolveSyncDirectory, selectWindowsPackage, validateWindowsPackage, } = require("./sync-upstream"); @@ -16,6 +17,28 @@ const X64_PACKAGE = { name: "OpenAI.Codex_26.715.10079.0_x64__2p2nqsd0c76g0.msix", }; +test("同步缓存目录必须由维护入口显式提供", () => { + const previous = process.env.CODEX_SYNC_DIR; + delete process.env.CODEX_SYNC_DIR; + try { + assert.throws(() => resolveSyncDirectory(), /缺少 CODEX_SYNC_DIR/); + } finally { + if (previous == null) delete process.env.CODEX_SYNC_DIR; + else process.env.CODEX_SYNC_DIR = previous; + } +}); + +test("同步缓存目录解析显式环境变量", () => { + const previous = process.env.CODEX_SYNC_DIR; + process.env.CODEX_SYNC_DIR = ".cache-explicit-test"; + try { + assert.equal(resolveSyncDirectory(), path.resolve(".cache-explicit-test")); + } finally { + if (previous == null) delete process.env.CODEX_SYNC_DIR; + else process.env.CODEX_SYNC_DIR = previous; + } +}); + function createExtractDir(t, architecture, version = "26.715.10079.0") { const extractDir = fs.mkdtempSync(path.join(os.tmpdir(), "codex-msix-test-")); t.after(() => fs.rmSync(extractDir, { recursive: true, force: true })); diff --git a/scripts/windows-maintenance.js b/scripts/windows-maintenance.js index 88cb85ba..5bc951f8 100644 --- a/scripts/windows-maintenance.js +++ b/scripts/windows-maintenance.js @@ -9,8 +9,10 @@ const { writeJson, sha256, validateSource, verifySourceFile, confinedFile } = re const root = path.resolve(__dirname, ".."); const requiredChecks = [ "isolation", "start-exit", "authentication", "thread-history", "provider-switch", - "model-catalog", "compaction", "archive-delete", "browser-auth", "plugins-skills", - "worker-config", "updater-disabled", "program-rollback", "data-restore", "reading-layout", + "model-catalog", "home-navigation", "provider-quota", "service-tier", "thread-timeline", + "mcp-refresh", "pet-menu", "remote-control", "compaction", "archive-delete", "browser-auth", + "plugins-skills", "worker-config", "updater-disabled", "program-rollback", "data-restore", + "reading-layout", ]; function readJson(file) { return JSON.parse(fs.readFileSync(file, "utf8")); } @@ -37,12 +39,15 @@ function output(name, value) { } async function discover(options) { - const { getWindowsVersion } = require("./sync-upstream"); + const { getWindowsVersion, resolveSyncDirectory } = require("./sync-upstream"); const info = await getWindowsVersion(options.version); if (!Number.isSafeInteger(info.size) || info.size <= 0 || !info.storeDigest) { throw new Error("Store 没有提供可验证的包大小或摘要"); } - writeJson(path.resolve(options.out || ".cache/windows-discovery.json"), { + const discoveryFile = options.out + ? path.resolve(options.out) + : path.join(resolveSyncDirectory(), "windows-discovery.json"); + writeJson(discoveryFile, { schemaVersion: 1, ...info, checkedAt: new Date().toISOString(), }); let approvedVersion = ""; From 02f50b55a2c8d9ac5d894a1e964f3b3a6152cc68 Mon Sep 17 00:00:00 2001 From: carptopus Date: Sun, 18 Oct 2026 13:20:13 +0800 Subject: [PATCH 15/51] fix: align home navigation bundle smoke --- scripts/frontend-source-smoke.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index 46d9a03c..af05e2e1 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -83,9 +83,9 @@ function verifyFrontendSource(assets) { assert.match(navigationSource, /\|\|\/\* Codex:API-key 首页恢复写入。 \*\/[A-Za-z_$][\w$]*===`apikey`/); assert.match(navigationSource, /authMethod:__codexAuthMethod/); assert.match(navigationSource, - /\/\* Codex:API-key 当前首页保持会话。 \*\/__codexAuthMethod===`apikey`&&([A-Za-z_$][\w$]*)!=null&&\(\1\.pathname\.startsWith\(`\/local\/`\)\|\|\1\.pathname\.startsWith\(`\/remote\/`\)\|\|\1\.state\?\.sidebarThreadLocationId!=null\)/); + /\/\* Codex:API-key 当前首页保持会话。 \*\/__codexAuthMethod===`apikey`&&([A-Za-z_$][\w$]*)!=null&&([A-Za-z_$][\w$]*)\(\1\)===`home`/); assert.match(navigationSource, - /\/\* Codex:API-key 首页保持状态会话。 \*\/[A-Za-z_$][\w$]*\.authMethod===`apikey`&&[A-Za-z_$][\w$]*\?\.state\?\.sidebarThreadLocationId!=null/); + /\/\* Codex:API-key 首页保持状态会话。 \*\/[A-Za-z_$][\w$]*\.authMethod===`apikey`&&([A-Za-z_$][\w$]*)!=null&&([A-Za-z_$][\w$]*)\(\1\)===`home`/); assert.match(navigationSource, /\/\* Codex:API-key 首页恢复最近会话。 \*\/[A-Za-z_$][\w$]*\.authMethod!==`apikey`/); const timelineEntries = files.filter(name => /^app-initial-/.test(name) From 7abbf7ac116f80b7dbff0a47433be0bf4a62b6f5 Mon Sep 17 00:00:00 2001 From: carptopus Date: Sun, 18 Oct 2026 15:19:26 +0800 Subject: [PATCH 16/51] fix: restore local UI state and isolate remote control --- README.md | 2 +- scripts/STATSIG_GATES.md | 4 +- scripts/frontend-source-smoke.js | 12 +- scripts/patch-accent-presets.test.js | 23 +- scripts/patch-api-key-home-navigation.js | 8 +- scripts/patch-api-key-home-navigation.test.js | 10 +- scripts/patch-policy.js | 2 +- scripts/patch-remote-control.js | 365 ++++++++++++------ scripts/patch-remote-control.test.js | 57 +-- scripts/runtime/accent-presets.mjs | 16 +- 10 files changed, 323 insertions(+), 176 deletions(-) diff --git a/README.md b/README.md index 6d741422..f4497e99 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ pnpm run build:all - `patch-api-key-home-navigation.js` 补齐 API-key 模式的当前会话导航记录,并复用官方首页区域分类器识别当前会话;当前会话点击首页保持不变,从设置等页面点击首页则恢复最近会话,避免直达空首页。ChatGPT、无认证及其他认证方式保持原有条件。 - `patch-thread-timeline.js` 在当前 host 与 App Server 版本支持时启用官方 `thread/timeline/list` 历史路径,移除 API-key / 自定义 Provider 无法获得的远端灰度条件;版本兼容判断仍由官方逻辑负责。 - `patch-mcp-status-refresh.js` 将短时间内的 MCP 启动状态通知合并为一次轻量目录刷新;Full 目录只标记为 stale、不在后台立即重拉,详细 MCP 页面后续仍按官方 Full 查询取得资源与模板。 -- `patch-remote-control.js` 只开放 Connections 设置入口;需要 ChatGPT 账户与 workspace routing 的 Remote Control 数据链继续遵守官方 gate,避免 API-key 模式反复建立无凭据的 Durable 连接。 +- `patch-remote-control.js` 不强开 Connections 或 Remote Control gate;只有真实 ChatGPT 认证才同步官方 Remote Control 本地状态,API-key 等其他认证会清除旧启用值并禁用当前 app-server 的 Remote Control。 - `patch-accent-presets.js` 允许没有 ChatGPT 账户主题的 API-key / 自定义 Provider 在本地选择强调色,并复用官方完整预设渲染消息气泡等界面变量;账户主题仍在加载时保持禁用,账户可用时继续使用官方同步。 - `patch-hide-pet-menu.js` 只隐藏账户菜单中的 Pet / Mini 入口,保留浮动面板实现、状态和全局快捷键。 - `patch-reading-layout.js` 在外观主题卡片中加入 50%–100%、步进 5% 的正文宽度滑杆,并同步代码块、表格和输入区宽度,扩宽适用对话框;百分比不低于官方宽度,Markdown 粗体颜色可跟随正文、强调色或使用自定义颜色。 diff --git a/scripts/STATSIG_GATES.md b/scripts/STATSIG_GATES.md index e8fc7799..5c8625fe 100644 --- a/scripts/STATSIG_GATES.md +++ b/scripts/STATSIG_GATES.md @@ -85,13 +85,13 @@ gate 2307253562 → codex_git_commit | `patch-devtools.js` | `allowInspectElement` / `devTools` | 属性值 → `!0` | | `patch-copyright.js` | About Dialog / setAboutPanelOptions 或自定义 HTML | 替换版权文本 | | `patch-process-polyfill.js` | Windows `process` polyfill | 注入 `process.env`/`process.platform` | -| `patch-remote-control.js` | gate `4114442250` | 开启 Connections 入口;Remote Control 数据加载 gate 保持上游判断,避免 API-key 模式建立无凭据的 durable 连接 | +| `patch-remote-control.js` | `local_remote_control_enabled` 同步组件 | 不覆盖任何 gate;ChatGPT 保持官方同步,API-key 等其他认证清除旧启用值并禁用当前 app-server 的 Remote Control | ### Remote Control 已确认 gate | ID | 功能 | 影响范围 | |---|---|---| -| `4114442250` | Remote Connections 可见性 | Settings 中的 Connections 项、相关远程标识 | +| `4114442250` | Remote Connections 可见性 | Settings 中的 Connections 项、相关远程标识;不得强制开启 | | `1042620455` | Remote Control / Slingshot | 手机控制分区、远程设备加载、主进程 gate bridge;不得强制开启 | ## 备注 diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index af05e2e1..18c6336b 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -103,6 +103,13 @@ function verifyFrontendSource(assets) { assert.match(mcpRefreshSource, /refetchType:`none`/); assert.match(mcpRefreshSource, /===`full`/); assert.match(mcpRefreshSource, /CodexRebuildMcpStatusRefresh \*\/\)\},250\)/); + const remoteControlEntries = files.filter(name => /^app-initial-/.test(name) + && fs.readFileSync(path.join(assets, name), "utf8").includes("CodexRebuildRemoteControlAuthIsolation")); + assert.equal(remoteControlEntries.length, 1); + const remoteControlSource = fs.readFileSync(path.join(assets, remoteControlEntries[0]), "utf8"); + assert.match(remoteControlSource, /__codexRemoteAuth\?\.authMethod!==`chatgpt`/); + assert.match(remoteControlSource, /__codexSetRemoteEnabled\(!1\)/); + assert.doesNotMatch(remoteControlSource, /codex-remote-gate:/); const serviceTierEntries = files.filter(name => /^app-initial-/.test(name) && fs.readFileSync(path.join(assets, name), "utf8").includes("CodexRebuildServiceTierApiKeyRequest")); assert.equal(serviceTierEntries.length, 1); @@ -113,7 +120,8 @@ function verifyFrontendSource(assets) { const accentModule = fs.readFileSync(path.join(assets, "codex-rebuild-accent-presets.js"), "utf8"); assert.match(accentModule, /codex-rebuild:accent-preset:v1/); assert.match(accentModule, /export function resolveAccentPreset/); - assert.match(accentModule, /preset === "default" \? "blue" : preset/); + assert.match(accentModule, /preset == null \|\| preset === "default" \? "blue" : preset/); + assert.match(accentModule, /CUSTOM_ACCENT_PRESET = "custom"/); assert.doesNotMatch(accentModule, /getComputedStyle|#[0-9a-f]{6}/i); const readingModule = fs.readFileSync(path.join(assets, "codex-rebuild-reading-width.js"), "utf8"); assert.match(readingModule, /MIN_WIDTH_PERCENT = 50/); @@ -128,7 +136,7 @@ function verifyFrontendSource(assets) { assert.equal(shared.length, 1); const dialogs = fs.readFileSync(path.join(assets, shared[0]), "utf8"); assert.match(dialogs, /codex-rebuild-dialog-editor h-\[720px\] max-w-full max-h-full/); - return { passed: true, quotaScenarios: results, apiKeyHomeNavigation: true, threadTimelineEnabled: true, mcpStatusRefreshGoverned: true, apiKeyServiceTiers: true, nativeAppearanceRow: true, nativeAccentThemePipeline: true, dialogHeightPreserved: true }; + return { passed: true, quotaScenarios: results, apiKeyHomeNavigation: true, threadTimelineEnabled: true, mcpStatusRefreshGoverned: true, remoteControlAuthIsolated: true, apiKeyServiceTiers: true, nativeAppearanceRow: true, nativeAccentThemePipeline: true, dialogHeightPreserved: true }; } if (require.main === module) console.log(JSON.stringify(verifyFrontendSource(path.resolve(process.argv[2] || "src/win/_asar/webview/assets")), null, 2)); module.exports = { verifyFrontendSource }; diff --git a/scripts/patch-accent-presets.test.js b/scripts/patch-accent-presets.test.js index a71bb3d4..5ac4f344 100644 --- a/scripts/patch-accent-presets.test.js +++ b/scripts/patch-accent-presets.test.js @@ -114,7 +114,7 @@ test("主题函数唯一注入本地预设解析器并保持幂等", () => { assert.equal(patchThemeSource(result.source).status, "already-patched"); }); -test("本地设置、账户同步和自定义清理使用同一预设状态", async () => { +test("本地设置、账户同步和显式自定义使用同一预设状态", async () => { const runtime = await runtimeModule(); const storage = fakeStorage(); globalThis.localStorage = storage; @@ -156,13 +156,18 @@ test("本地设置、账户同步和自定义清理使用同一预设状态", as storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, "blue"); runtime.useCustomAccent(value => { customValue = value; }, "#123456"); assert.equal(customValue, "#123456"); - assert.equal(storage.values.has(runtime.ACCENT_PRESET_STORAGE_KEY), false); + assert.equal(storage.values.get(runtime.ACCENT_PRESET_STORAGE_KEY), "custom"); + assert.equal(runtime.accentPresetSelection(null, "custom", "custom"), "custom"); + assert.equal(runtime.resolveAccentPreset("custom", null), null); }); test("预设解析补齐官方默认有效色并拒绝无效本地值", async () => { const runtime = await runtimeModule(); - const storage = fakeStorage({ [runtime.ACCENT_PRESET_STORAGE_KEY]: "blue" }); + const storage = fakeStorage(); globalThis.localStorage = storage; + assert.equal(runtime.accentPresetSelection(null, "custom", "custom"), "default"); + assert.equal(runtime.resolveAccentPreset("custom", null), "blue"); + storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, "blue"); assert.equal(runtime.resolveAccentPreset("custom", null), "blue"); assert.equal(runtime.resolveAccentPreset("chatgpt", "green"), "green"); assert.equal(runtime.resolveAccentPreset("custom", "green"), "blue"); @@ -175,7 +180,7 @@ test("预设解析补齐官方默认有效色并拒绝无效本地值", async () assert.equal(runtime.accentPresetSelection(null, "custom"), "default"); assert.equal(runtime.resolveAccentPreset("custom", null), "blue"); storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, "not-a-preset"); - assert.equal(runtime.resolveAccentPreset("custom", null), null); + assert.equal(runtime.resolveAccentPreset("custom", null), "blue"); }); test("完整主题链复用官方预设气泡且账户主题优先", async t => { @@ -188,9 +193,13 @@ test("完整主题链复用官方预设气泡且账户主题优先", async t => fs.writeFileSync(bundle, result.source, "utf8"); const theme = await import(`${pathToFileURL(bundle).href}?test=${Date.now()}`); const runtime = await runtimeModule(); - const storage = fakeStorage({ [runtime.ACCENT_PRESET_STORAGE_KEY]: "blue" }); + const storage = fakeStorage(); globalThis.localStorage = storage; + const localImplicitDefault = theme.Tba({ accentSource: "custom", accent: "#custom" }, "light", null); + assert.equal(localImplicitDefault["--color-background-user-message"], "#blue-bubble"); + + storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, "blue"); const localBlue = theme.Tba({ accentSource: "custom", accent: "#custom" }, "light", null); assert.equal(localBlue["--color-background-user-message"], "#blue-bubble"); assert.notEqual(localBlue["--color-background-user-message"], "neutral-bubble"); @@ -208,4 +217,8 @@ test("完整主题链复用官方预设气泡且账户主题优先", async t => storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, "default"); const localDefault = theme.Tba({ accentSource: "custom", accent: "#custom" }, "light", null); assert.equal(localDefault["--color-background-user-message"], "#blue-bubble"); + + storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, "custom"); + const localCustom = theme.Tba({ accentSource: "custom", accent: "#custom" }, "light", null); + assert.equal(localCustom["--color-background-user-message"], "neutral-bubble"); }); diff --git a/scripts/patch-api-key-home-navigation.js b/scripts/patch-api-key-home-navigation.js index 389cde89..6f59e52a 100644 --- a/scripts/patch-api-key-home-navigation.js +++ b/scripts/patch-api-key-home-navigation.js @@ -209,7 +209,7 @@ function findOpenHomeRoute(ast, source) { ? source.slice(markedGuards[0].test.start, markedGuards[0].test.end) : ""; const currentAreaGuardPresent = guardSource.includes( - `${caller.homeClassifier}(${route.currentLocation})===\`home\``, + `${route.currentLocation}.pathname===\`/\`||${caller.homeClassifier}(${route.currentLocation})===\`home\``, ); return { ...route, caller, currentAreaGuardPresent, markerPresent }; } @@ -335,7 +335,7 @@ function patchSource(source) { openHome.caller.passedAuthMethod.name === openHome.caller.authMethod; const homeRailPatched = homeRail.markerPresent && homeRail.stateMarkerPresent && homeRail.stateGuardSource.includes( - `${openHome.caller.homeClassifier}(${homeRail.currentLocation})===\`home\``, + `${homeRail.currentLocation}.pathname===\`/\`||${openHome.caller.homeClassifier}(${homeRail.currentLocation})===\`home\``, ) && isApiKeyRailGuard(homeRail.branch.test, homeRail.authState); if (trackerPatched) { const gateSource = source.slice(tracker.gate.start, tracker.gate.end); @@ -379,7 +379,7 @@ function patchSource(source) { edits.push({ start: openHome.branch.start, end: openHome.branch.start, - replacement: `if(${CURRENT_HOME_MARKER}__codexAuthMethod===\`apikey\`&&${openHome.currentLocation}!=null&&${openHome.caller.homeClassifier}(${openHome.currentLocation})===\`home\`)return;`, + replacement: `if(${CURRENT_HOME_MARKER}__codexAuthMethod===\`apikey\`&&${openHome.currentLocation}!=null&&(${openHome.currentLocation}.pathname===\`/\`||${openHome.caller.homeClassifier}(${openHome.currentLocation})===\`home\`))return;`, }); } if (!homeRailPatched) { @@ -387,7 +387,7 @@ function patchSource(source) { edits.push({ start: homeRail.branch.start, end: homeRail.branch.start, - replacement: `if(${HOME_STATE_MARKER}${homeRail.authState}.authMethod===\`apikey\`&&${homeRail.currentLocation}!=null&&${openHome.caller.homeClassifier}(${homeRail.currentLocation})===\`home\`)return;`, + replacement: `if(${HOME_STATE_MARKER}${homeRail.authState}.authMethod===\`apikey\`&&${homeRail.currentLocation}!=null&&(${homeRail.currentLocation}.pathname===\`/\`||${openHome.caller.homeClassifier}(${homeRail.currentLocation})===\`home\`))return;`, }); edits.push({ start: homeRail.branch.test.start, diff --git a/scripts/patch-api-key-home-navigation.test.js b/scripts/patch-api-key-home-navigation.test.js index 186746ae..26cc3a0b 100644 --- a/scripts/patch-api-key-home-navigation.test.js +++ b/scripts/patch-api-key-home-navigation.test.js @@ -30,7 +30,7 @@ function fixture() { "f=u?.pathname===`/library`||u?.pathname.startsWith(`/library/`);", "if(u!=null&&!f&&e.set(Pti,n,{location:u,selectedProject:d}),SFe(e,i),a){r(`/`,{state:{sidebarProductMode:i}});return}", "if(!o)return;if(l==null){s();return}r(l.location)}", - "function homeArea(e){return e?.pathname.startsWith(`/settings/`)?null:`home`}", + "function homeArea(e){return e?.pathname===`/`||e?.pathname.startsWith(`/settings/`)?null:`home`}", "function Pjo(){let i=store(),h=navigate(),a=start(),{accountId:O,authMethod:k}=mp(),", "p=location(),selected=homeArea(p)===`home`&&mode()===`codex`,", "c=()=>{wti(i,{codexLocalAccessStatus:`allowed`,currentMode:`codex`,navigate:h,nextMode:`codex`,openHome:!0,startNewConversation:a})};return c}", @@ -115,6 +115,12 @@ test("API-key 根路径已属于首页区域时不再导航到空路由", () => assert.deepEqual(navigations, []); }); +test("测试夹具保持真实 Bundle 的裸根路由分类行为", () => { + assert.match(fixture(), /pathname===`\/`\|\|e\?\.pathname\.startsWith/); + const result = patchSource(fixture()); + assert.match(result.source, /u\.pathname===`\/`\|\|homeArea\(u\)===`home`/); +}); + test("API-key 根路径携带会话位置状态时保持当前会话", () => { const result = patchSource(fixture()); const navigations = clickHome(result.source, "apikey", { @@ -234,7 +240,7 @@ test("ChatGPT 重选功能导航栏首页时不获得 API-key 状态会话短路 test("旧版缺少状态会话判断的首页补丁会被拒绝", () => { const patched = patchSource(fixture()); const incomplete = patched.source - .replace("&&homeArea(u)===`home`", "") + .replace("&&(u.pathname===`/`||homeArea(u)===`home`)", "") .replace(new RegExp(`if\\(\\/\\* Codex:API-key 首页保持状态会话。 \\*\\/[\\s\\S]*?return;`), ""); const result = patchSource(incomplete); diff --git a/scripts/patch-policy.js b/scripts/patch-policy.js index 30d8b77a..d4328352 100644 --- a/scripts/patch-policy.js +++ b/scripts/patch-policy.js @@ -32,7 +32,7 @@ const PATCH_POLICY = [ { script: "patch-thread-file-manager-action.js", feature: "会话文件管理器入口" }, { script: "patch-browser-auth.js", feature: "API-key 浏览器认证" }, { script: "patch-plugin-auth.js", feature: "插件认证与功能开关" }, - { script: "patch-remote-control.js", feature: "Connections 入口" }, + { script: "patch-remote-control.js", feature: "Remote Control 认证隔离" }, { script: "patch-composer-workspace-root.js", feature: "会话工作目录传递" }, { script: "patch-updater.js", feature: "禁用上游自动更新" }, { script: "patch-archive-delete.js", feature: "跨 Provider 归档列表与归档删除" }, diff --git a/scripts/patch-remote-control.js b/scripts/patch-remote-control.js index 9647a526..9ad95452 100644 --- a/scripts/patch-remote-control.js +++ b/scripts/patch-remote-control.js @@ -1,163 +1,272 @@ #!/usr/bin/env node /** - * 构建后补丁:开启“连接”入口。 + * 将 Remote Control 的本地状态同步限制在真实 ChatGPT 认证下。 * - * 上游当前使用 4114442250 控制 Connections 设置项与路由。 + * 上游同步组件会在应用启动时无条件读取 local_remote_control_enabled;旧版 + * 本项目曾强开 Remote Control gate,因此可能留下 true。API-key Provider + * 无法建立该连接,继续同步会反复触发 remoteControl/enable 和认证失败。 * - * 1042620455 会启动需要 ChatGPT 账户与 workspace routing 的 Remote Control - *(Slingshot)数据链。API-key Provider 没有这类账户状态;强制开启会反复 - * 建立 durable 连接并触发“无法加载组织设置”。因此该 gate 保持上游判断, - * 这里只开放 Connections 入口,不伪造 Remote Control 的账户能力。 + * 本补丁不再强开任何 Remote Control / Connections gate。ChatGPT 认证保持 + * 官方行为;其他认证方式清除遗留启用值,并向当前 app-server 发送一次 + * disable,确保切换认证方式时不会遗留已启动的 Remote Control。 */ -const fs = require("fs"); -const path = require("path"); +const fs = require("node:fs"); +const path = require("node:path"); const { parse } = require("acorn"); -const { SRC_DIR, relPath } = require("./patch-util"); - -const GATES = new Map([ - ["4114442250", "remote_connections_visibility"], -]); - -function walk(node, visitor) { - if (!node || typeof node !== "object") return; - if (node.type) visitor(node); - for (const key of Object.keys(node)) { - const child = node[key]; - if (Array.isArray(child)) { - for (const item of child) { - if (item && typeof item === "object" && item.type) walk(item, visitor); - } - } else if (child && typeof child === "object" && child.type) { - walk(child, visitor); - } - } -} +const { literal, walk } = require("./patch-ast-util"); +const { relPath, SRC_DIR } = require("./patch-util"); -function getLiteralValue(node) { - if (!node) return null; - if (node.type === "Literal") return node.value; - if ( - node.type === "TemplateLiteral" && - node.expressions.length === 0 && - node.quasis.length === 1 - ) { - return node.quasis[0].value.cooked; - } - return null; -} +const PLATFORMS = ["mac-arm64", "mac-x64", "win"]; +const STORAGE_KEY = "local_remote_control_enabled"; +const MARKER = "/* CodexRebuildRemoteControlAuthIsolation */"; -function marker(gateId) { - return `/*codex-remote-gate:${gateId}*/`; +function propertyName(member) { + if (member?.type !== "MemberExpression") return null; + if (!member.computed && member.property.type === "Identifier") return member.property.name; + return literal(member.property); } -function findPatches(source) { - const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); - const patches = []; - - walk(ast, (node) => { - if (node.type !== "CallExpression") return; - if (node.callee?.type !== "Identifier") return; - - const gateId = node.arguments - ?.map((argument) => String(getLiteralValue(argument) ?? "")) - .find((value) => GATES.has(value)); - if (!gateId) return; - const gateName = GATES.get(gateId); - if (!gateName) return; - - patches.push({ - id: gateName, - gateId, - start: node.start, - end: node.end, - original: source.slice(node.start, node.end), - replacement: `!0${marker(gateId)}`, - }); - }); +function memberCallee(call) { + let callee = call?.callee; + if (callee?.type === "SequenceExpression") callee = callee.expressions.at(-1); + return callee?.type === "MemberExpression" ? callee : null; +} - return patches; +function functions(ast) { + return ast.body.filter((node) => node.type === "FunctionDeclaration" && node.id?.name); } -function locatePlatforms(platform) { - if (platform) return [platform]; - return ["mac-arm64", "mac-x64", "win"].filter((name) => - fs.existsSync(path.join(SRC_DIR, name, "_asar", "webview", "assets")), - ); +function descendants(root, predicate, { skipNestedFunctions = false } = {}) { + const found = []; + walk(root, (node) => { + if (node === root) return; + if (predicate(node)) found.push(node); + }, { ownScope: skipNestedFunctions }); + return found; } -function main() { - const args = process.argv.slice(2); - const isCheck = args.includes("--check"); - const platform = args.find((arg) => ["mac-arm64", "mac-x64", "win"].includes(arg)); - const platforms = locatePlatforms(platform); +function nextInitializer(allFunctions, target, source) { + const following = allFunctions.filter((node) => node.start > target.end).sort((a, b) => a.start - b.start); + const initializer = following[0]; + if (initializer == null || initializer.start - target.end > 200) { + throw new Error(`${target.id.name} 的模块初始化器未找到`); + } + const arrows = descendants(initializer, (node) => + node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement"); + if (arrows.length !== 1 || !source.slice(initializer.start, initializer.end).includes("return")) { + throw new Error(`${target.id.name} 的模块初始化器结构异常`); + } + return { function: initializer, body: arrows[0].body }; +} - if (platforms.length === 0) { - console.log("[skip] No generated platform assets found"); - return; +function findRemoteSync(allFunctions, source) { + const candidates = allFunctions.filter((node) => { + const text = source.slice(node.start, node.end); + return text.includes(STORAGE_KEY) && text.includes("Failed to sync local remote control enablement"); + }); + if (candidates.length !== 1) { + throw new Error(`Remote Control 本地状态同步组件数量异常(${candidates.length})`); } + const fn = candidates[0]; + const declarations = descendants(fn, (node) => node.type === "VariableDeclarator", { + skipNestedFunctions: true, + }); + const storage = declarations.filter((node) => + node.id?.type === "ArrayPattern" && + node.id.elements[0]?.type === "Identifier" && + node.init?.type === "CallExpression" && + node.init.callee.type === "Identifier" && + node.init.arguments.some((argument) => literal(argument) === STORAGE_KEY)); + if (storage.length !== 1) throw new Error("Remote Control 本地状态 Hook 结构异常"); + const storedValue = storage[0].id.elements[0].name; + const storageHook = storage[0].init.callee.name; - let changedFiles = 0; - let pendingFiles = 0; + const catches = descendants(fn, (node) => + node.type === "CallExpression" && + propertyName(node.callee) === "catch" && + node.callee.object?.type === "CallExpression" && + node.callee.object.callee?.type === "Identifier" && + node.callee.object.arguments[1]?.type === "Identifier" && + node.callee.object.arguments[1].name === storedValue); + if (catches.length !== 1 || catches[0].arguments.length !== 1) { + throw new Error("Remote Control 同步及错误处理结构异常"); + } + const syncCall = catches[0].callee.object; + const syncFunction = syncCall.callee.name; + const container = syncCall.arguments[0]; + if (container?.type !== "Identifier") throw new Error("Remote Control 容器参数结构异常"); + const containerDeclaration = declarations.find((node) => node.id?.name === container.name); + if (containerDeclaration?.init == null) throw new Error("Remote Control 容器初始化结构异常"); - for (const targetPlatform of platforms) { - const assetsDir = path.join(SRC_DIR, targetPlatform, "_asar", "webview", "assets"); - const counts = new Map([...GATES.keys()].map((gateId) => [gateId, { patched: 0, marked: 0 }])); + const effects = descendants(fn, (node) => + node.type === "CallExpression" && propertyName(memberCallee(node)) === "useEffect"); + const effectCallee = effects.length === 1 ? memberCallee(effects[0]) : null; + if (effectCallee?.object.type !== "Identifier") { + throw new Error("Remote Control useEffect 结构异常"); + } - for (const name of fs.readdirSync(assetsDir)) { - if (!name.endsWith(".js")) continue; - const file = path.join(assetsDir, name); - const source = fs.readFileSync(file, "utf8"); - const relevant = [...GATES.keys()].some( - (gateId) => source.includes(gateId) || source.includes(marker(gateId)), - ); - if (!relevant) continue; + return { + fn, + container: container.name, + containerExpression: source.slice(containerDeclaration.init.start, containerDeclaration.init.end), + storedValue, + storageHook, + syncFunction, + catchHandler: source.slice(catches[0].arguments[0].start, catches[0].arguments[0].end), + react: effectCallee.object.name, + }; +} - for (const gateId of GATES.keys()) { - counts.get(gateId).marked += source.split(marker(gateId)).length - 1; - } +function findHostAuth(allFunctions, source) { + const candidates = []; + for (const fn of allFunctions) { + const text = source.slice(fn.start, fn.end); + if (!["serviceTierAccess", "authMethod", "hostId", "isLoading", "apikey"] + .every((value) => text.includes(value))) continue; + const declarations = descendants(fn, (node) => node.type === "VariableDeclarator", { + skipNestedFunctions: true, + }); + for (const host of declarations) { + if (host.id?.type !== "Identifier" || host.init?.type !== "CallExpression" || + host.init.callee.type !== "Identifier" || host.init.arguments.length !== 1 || + host.init.arguments[0].type !== "Identifier") continue; + const selected = declarations.find((node) => + node.id?.type === "Identifier" && node.init?.type === "LogicalExpression" && + node.init.operator === "??" && node.init.right?.type === "Identifier" && + node.init.right.name === host.id.name); + if (selected == null) continue; + const auth = declarations.find((node) => + node.id?.type === "Identifier" && node.init?.type === "CallExpression" && + node.init.callee.type === "Identifier" && node.init.arguments.length === 1 && + node.init.arguments[0]?.type === "Identifier" && + node.init.arguments[0].name === selected.id.name && + text.includes(`${node.id.name}?.authMethod`)); + if (auth == null) continue; + candidates.push({ + fn, + hostHook: host.init.callee.name, + defaultHost: host.init.arguments[0].name, + authHook: auth.init.callee.name, + }); + } + } + if (candidates.length !== 1) { + throw new Error(`当前 Host 认证 Hook 数量异常(${candidates.length})`); + } + return candidates[0]; +} - const patches = findPatches(source); - if (patches.length === 0) continue; +function count(source, value) { + return source.split(value).length - 1; +} - console.log(`\n-- [${targetPlatform}] ${relPath(file)}`); - for (const patch of patches) { - counts.get(patch.gateId).patched++; - console.log( - ` ${isCheck ? "[?]" : "*"} [${patch.id}] ${patch.original} -> ${patch.replacement}`, - ); - } +function validatePatchedSource(source) { + if (count(source, MARKER) !== 1) throw new Error(`${MARKER} 数量异常`); + if (source.includes("codex-remote-gate:")) throw new Error("仍存在强制开启 Remote Control gate 的旧标记"); + if (!source.includes("__codexRemoteAuth?.authMethod!==`chatgpt`") || + !source.includes("__codexSetRemoteEnabled(!1)") || + !source.includes("__codexRemoteAuth?.isLoading")) { + throw new Error("Remote Control 认证隔离或遗留状态清理不完整"); + } + parse(source, { ecmaVersion: "latest", sourceType: "module" }); +} - if (isCheck) { - pendingFiles++; - continue; - } +function patchSource(source) { + if (source.includes(MARKER)) { + try { + validatePatchedSource(source); + return { status: "already-patched", source }; + } catch (error) { + return { status: "unexpected-shape", source, reason: error.message }; + } + } + if (!source.includes(STORAGE_KEY) || + !source.includes("Failed to sync local remote control enablement")) { + return { status: "not-applicable", source }; + } + if (source.includes("codex-remote-gate:")) { + return { + status: "unexpected-shape", + source, + reason: "输入 Bundle 已包含旧 Remote Control gate 补丁,必须从官方资源重新生成", + }; + } - patches.sort((a, b) => b.start - a.start); - let code = source; - for (const patch of patches) { - code = code.slice(0, patch.start) + patch.replacement + code.slice(patch.end); - } - fs.writeFileSync(file, code, "utf8"); - changedFiles++; + try { + const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const allFunctions = functions(ast); + const remote = findRemoteSync(allFunctions, source); + const hostAuth = findHostAuth(allFunctions, source); + const remoteInitializer = nextInitializer(allFunctions, remote.fn, source); + const hostInitializer = nextInitializer(allFunctions, hostAuth.fn, source); + const replacement = `function ${remote.fn.id.name}(){let ${remote.container}=${remote.containerExpression},[${remote.storedValue},__codexSetRemoteEnabled]=${remote.storageHook}(\`${STORAGE_KEY}\`),__codexRemoteHostId=${hostAuth.hostHook}(${hostAuth.defaultHost}),__codexRemoteAuth=${hostAuth.authHook}(__codexRemoteHostId);${remote.react}.useEffect(()=>{if(__codexRemoteAuth?.isLoading)return;if(__codexRemoteAuth?.authMethod!==\`chatgpt\`){${remote.storedValue}===!0&&__codexSetRemoteEnabled(!1),${remote.syncFunction}(${remote.container},!1).catch(${remote.catchHandler});return}${remote.storedValue}!=null&&${remote.syncFunction}(${remote.container},${remote.storedValue}).catch(${remote.catchHandler})},[__codexRemoteAuth?.authMethod,__codexRemoteAuth?.isLoading,${remote.storedValue},__codexSetRemoteEnabled,${remote.container}]);return null}${MARKER}`; + const edits = [ + { start: remote.fn.start, end: remote.fn.end, replacement }, + { + start: remoteInitializer.body.start + 1, + end: remoteInitializer.body.start + 1, + replacement: `${hostInitializer.function.id.name}(),`, + }, + ].sort((a, b) => b.start - a.start); + let next = source; + for (const edit of edits) { + next = next.slice(0, edit.start) + edit.replacement + next.slice(edit.end); } + validatePatchedSource(next); + return { status: "patched", source: next }; + } catch (error) { + return { status: "unexpected-shape", source, reason: error.message }; + } +} + +function targetDirectories(platform) { + const requested = platform ? [platform] : PLATFORMS; + return requested.map((item) => ({ + platform: item, + path: path.join(SRC_DIR, item, "_asar", "webview", "assets"), + })).filter((item) => fs.existsSync(item.path)); +} + +function main() { + const args = process.argv.slice(2); + const platform = args.find((arg) => PLATFORMS.includes(arg)); + const check = args.includes("--check"); + const directories = targetDirectories(platform); + let failed = 0; + let patched = 0; - for (const [gateId, gateName] of GATES) { - const count = counts.get(gateId); - if (count.patched === 0 && count.marked === 0) { - throw new Error(`[${targetPlatform}] Remote-control gate not found: ${gateName} (${gateId})`); + for (const directory of directories) { + try { + const results = fs.readdirSync(directory.path) + .filter((name) => /^app-initial-.*\.js$/.test(name)) + .map((name) => ({ name, path: path.join(directory.path, name) })) + .map((file) => ({ ...file, source: fs.readFileSync(file.path, "utf8") })) + .map((file) => ({ file, result: patchSource(file.source) })) + .filter((item) => item.result.status !== "not-applicable"); + if (results.length !== 1) throw new Error(`Remote Control Bundle 数量异常(${results.length})`); + const target = results[0]; + if (target.result.status === "unexpected-shape") throw new Error(target.result.reason); + console.log(` [${directory.platform}] ${relPath(target.file.path)}`); + if (target.result.status === "already-patched") { + console.log(" [ok] Remote Control 已按认证方式隔离"); + } else if (check) { + console.log(" [ok] Remote Control 认证隔离结构已核对;dry-run 未写文件"); + } else { + fs.writeFileSync(target.file.path, target.result.source, "utf8"); + patched++; + console.log(" [ok] API-key 已清理并禁用 Remote Control;ChatGPT 保持官方行为"); } - const state = count.patched > 0 ? `${count.patched} match(es)` : `${count.marked} marker(s)`; - console.log(` [ok] [${targetPlatform}] ${gateName}: ${state}`); + } catch (error) { + failed++; + console.error(` [fail] ${directory.platform}: ${error.message}`); } } - console.log( - isCheck - ? `[check] ${pendingFiles} file(s) would be changed` - : `[done] ${changedFiles} file(s) patched`, - ); + if (directories.length === 0) console.log("[skip] No generated platform assets found"); + if (failed > 0) process.exitCode = 1; + else console.log(check ? "[check] Remote Control patch verified" : `[done] ${patched} file(s) patched`); } if (require.main === module) main(); -module.exports = { GATES, findPatches, marker }; +module.exports = { MARKER, patchSource, validatePatchedSource }; diff --git a/scripts/patch-remote-control.test.js b/scripts/patch-remote-control.test.js index 9df31412..1335e42b 100644 --- a/scripts/patch-remote-control.test.js +++ b/scripts/patch-remote-control.test.js @@ -1,33 +1,46 @@ const assert = require("node:assert/strict"); const test = require("node:test"); -const { findPatches, marker } = require("./patch-remote-control"); +const { MARKER, patchSource, validatePatchedSource } = require("./patch-remote-control"); -function applyPatches(source, patches) { - let result = source; - for (const patch of [...patches].sort((a, b) => b.start - a.start)) { - result = result.slice(0, patch.start) + patch.replacement + result.slice(patch.end); - } - return result; +function fixture() { + return [ + "function remoteSync(){let e=(0,cache.c)(4),t=get(Container),[n]=shared(`local_remote_control_enabled`),r,i;return e[0]!==n||e[1]!==t?(r=()=>{n!=null&&sync(t,n).catch(e=>{handle(t,e),log.error(`Failed to sync local remote control enablement`,{error:e})})},i=[n,t],e[0]=n,e[1]=t,e[2]=r,e[3]=i):(r=e[2],i=e[3]),react.useEffect(r,i),null}", + "var cache,react;", + "function remoteInit(){return(remoteInit=once((()=>{cache=compiled(),base(),react=reactModule(),sharedInit(),syncInit()})))()}", + "function serviceTier(e){let t=(0,serviceCache.c)(10),n=useAtom(defaultHost),r=e?.hostId??n,i=useHostAuth(r),a=i?.authMethod===`apikey`?`apikey`:(i?.authMethod===`chatgpt`||i?.authMethod===`personalAccessToken`),o=i?.authMethod??null,s={authMethod:o,hostId:r},c={serviceTierAccess:a,isLoading:!!i?.isLoading};return c}", + "var serviceCache;", + "function serviceInit(){return(serviceInit=once((()=>{serviceCache=compiled(),atomInit(),hostInit(),authInit()})))()}", + ].join(""); } -test("only opens Connections visibility and keeps Remote Control on its upstream gate", () => { - const source = [ - "function connections(){return checkGate(`4114442250`)}", - "function remoteControl(){return checkGate(`1042620455`)}", - ].join("\n"); +test("API-key 清除旧启用值并禁用 Remote Control,ChatGPT 保留官方同步", () => { + const result = patchSource(fixture()); + assert.equal(result.status, "patched", result.reason); + validatePatchedSource(result.source); + assert.equal(result.source.split(MARKER).length - 1, 1); + assert.match(result.source, /__codexRemoteAuth\?\.authMethod!==`chatgpt`/); + assert.match(result.source, /n===!0&&__codexSetRemoteEnabled\(!1\),sync\(t,!1\)/); + assert.match(result.source, /n!=null&&sync\(t,n\)/); + assert.match(result.source, /function remoteInit\(\).*serviceInit\(\),/); + assert.doesNotMatch(result.source, /codex-remote-gate:/); +}); - const patches = findPatches(source); - assert.equal(patches.length, 1); - assert.equal(patches[0].gateId, "4114442250"); +test("重复应用保持幂等", () => { + const first = patchSource(fixture()); + assert.equal(first.status, "patched", first.reason); + const second = patchSource(first.source); + assert.equal(second.status, "already-patched", second.reason); + assert.equal(second.source, first.source); +}); - const result = applyPatches(source, patches); - assert.match(result, new RegExp(marker("4114442250").replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))); - assert.match(result, /remoteControl\(\)\{return checkGate\(`1042620455`\)\}/); - assert.doesNotMatch(result, /codex-remote-gate:1042620455/); - assert.equal(findPatches(result).length, 0); +test("拒绝继续处理曾经强开 gate 的污染 Bundle", () => { + const source = `${fixture()}const enabled=!0/*codex-remote-gate:1042620455*/;`; + const result = patchSource(source); + assert.equal(result.status, "unexpected-shape"); + assert.match(result.reason, /官方资源重新生成/); }); -test("does not patch a bundle that only contains the Remote Control data gate", () => { - assert.deepEqual(findPatches("const enabled=checkGate(`1042620455`);"), []); +test("没有 Remote Control 同步组件时不适用", () => { + assert.equal(patchSource("const value=1;").status, "not-applicable"); }); diff --git a/scripts/runtime/accent-presets.mjs b/scripts/runtime/accent-presets.mjs index 72b0d8c1..2dc9c36f 100644 --- a/scripts/runtime/accent-presets.mjs +++ b/scripts/runtime/accent-presets.mjs @@ -1,4 +1,5 @@ export const ACCENT_PRESET_STORAGE_KEY = "codex-rebuild:accent-preset:v1"; +export const CUSTOM_ACCENT_PRESET = "custom"; export const ACCENT_PRESETS = new Set([ "default", "blue", @@ -8,6 +9,7 @@ export const ACCENT_PRESETS = new Set([ "orange", "purple", "black", + CUSTOM_ACCENT_PRESET, ]); function storage() { @@ -23,12 +25,6 @@ export function readLocalAccentPreset() { } } -function clearLocalAccentPreset() { - try { - storage()?.removeItem(ACCENT_PRESET_STORAGE_KEY); - } catch {} -} - function saveLocalAccentPreset(preset) { try { storage()?.setItem(ACCENT_PRESET_STORAGE_KEY, preset); @@ -37,15 +33,16 @@ function saveLocalAccentPreset(preset) { export function accentPresetSelection(accountTheme, accentSource, fallback) { if (accountTheme === undefined || accentSource === "chatgpt") return fallback; - return readLocalAccentPreset() ?? fallback; + return readLocalAccentPreset() ?? "default"; } export function resolveAccentPreset(accentSource, accountPreset) { if (accentSource === "chatgpt") return accountPreset; const preset = readLocalAccentPreset(); + if (preset === CUSTOM_ACCENT_PRESET) return null; // 官方账户的“默认”会先解析成 effectiveTheme;未登录时没有这层账户数据。 // Windows 官方当前的有效默认色是 blue,本地模式在渲染阶段补齐同一语义。 - return preset === "default" ? "blue" : preset; + return preset == null || preset === "default" ? "blue" : preset; } export function selectAccentPreset(accountTheme, preset, applyLocal, selectAccount) { @@ -63,6 +60,7 @@ export function selectAccentPreset(accountTheme, preset, applyLocal, selectAccou } export function useCustomAccent(onChange, value) { - clearLocalAccentPreset(); + // 缺少键表示从未设置,本地模式会采用官方默认蓝色;显式 custom 才表示用户选择自定义色。 + saveLocalAccentPreset(CUSTOM_ACCENT_PRESET); return onChange(value); } From 6f80e89b4d3922ae469b37c89bb026211f9643c3 Mon Sep 17 00:00:00 2001 From: carptopus Date: Sun, 18 Oct 2026 15:29:05 +0800 Subject: [PATCH 17/51] fix: decouple remote control auth detection --- scripts/patch-remote-control.js | 2 +- scripts/patch-remote-control.test.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/patch-remote-control.js b/scripts/patch-remote-control.js index 9ad95452..871fdfa5 100644 --- a/scripts/patch-remote-control.js +++ b/scripts/patch-remote-control.js @@ -121,7 +121,7 @@ function findHostAuth(allFunctions, source) { const candidates = []; for (const fn of allFunctions) { const text = source.slice(fn.start, fn.end); - if (!["serviceTierAccess", "authMethod", "hostId", "isLoading", "apikey"] + if (!["serviceTierAccess", "authMethod", "hostId", "isLoading"] .every((value) => text.includes(value))) continue; const declarations = descendants(fn, (node) => node.type === "VariableDeclarator", { skipNestedFunctions: true, diff --git a/scripts/patch-remote-control.test.js b/scripts/patch-remote-control.test.js index 1335e42b..55f2d933 100644 --- a/scripts/patch-remote-control.test.js +++ b/scripts/patch-remote-control.test.js @@ -8,7 +8,7 @@ function fixture() { "function remoteSync(){let e=(0,cache.c)(4),t=get(Container),[n]=shared(`local_remote_control_enabled`),r,i;return e[0]!==n||e[1]!==t?(r=()=>{n!=null&&sync(t,n).catch(e=>{handle(t,e),log.error(`Failed to sync local remote control enablement`,{error:e})})},i=[n,t],e[0]=n,e[1]=t,e[2]=r,e[3]=i):(r=e[2],i=e[3]),react.useEffect(r,i),null}", "var cache,react;", "function remoteInit(){return(remoteInit=once((()=>{cache=compiled(),base(),react=reactModule(),sharedInit(),syncInit()})))()}", - "function serviceTier(e){let t=(0,serviceCache.c)(10),n=useAtom(defaultHost),r=e?.hostId??n,i=useHostAuth(r),a=i?.authMethod===`apikey`?`apikey`:(i?.authMethod===`chatgpt`||i?.authMethod===`personalAccessToken`),o=i?.authMethod??null,s={authMethod:o,hostId:r},c={serviceTierAccess:a,isLoading:!!i?.isLoading};return c}", + "function serviceTier(e){let t=(0,serviceCache.c)(10),n=useAtom(defaultHost),r=e?.hostId??n,i=useHostAuth(r),a=i?.authMethod===`chatgpt`||i?.authMethod===`personalAccessToken`,o=i?.authMethod??null,s={authMethod:o,hostId:r},c={serviceTierAccess:a,isLoading:!!i?.isLoading};return c}", "var serviceCache;", "function serviceInit(){return(serviceInit=once((()=>{serviceCache=compiled(),atomInit(),hostInit(),authInit()})))()}", ].join(""); From b5168ea5257342dbcfd2c10c0633c2e7cd5b3ce1 Mon Sep 17 00:00:00 2001 From: carptopus Date: Sun, 18 Oct 2026 15:42:13 +0800 Subject: [PATCH 18/51] test: align home navigation candidate smoke --- scripts/frontend-source-smoke.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index 18c6336b..29ecefce 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -83,9 +83,9 @@ function verifyFrontendSource(assets) { assert.match(navigationSource, /\|\|\/\* Codex:API-key 首页恢复写入。 \*\/[A-Za-z_$][\w$]*===`apikey`/); assert.match(navigationSource, /authMethod:__codexAuthMethod/); assert.match(navigationSource, - /\/\* Codex:API-key 当前首页保持会话。 \*\/__codexAuthMethod===`apikey`&&([A-Za-z_$][\w$]*)!=null&&([A-Za-z_$][\w$]*)\(\1\)===`home`/); + /\/\* Codex:API-key 当前首页保持会话。 \*\/__codexAuthMethod===`apikey`&&([A-Za-z_$][\w$]*)!=null&&\(\1\.pathname===`\/`\|\|([A-Za-z_$][\w$]*)\(\1\)===`home`\)/); assert.match(navigationSource, - /\/\* Codex:API-key 首页保持状态会话。 \*\/[A-Za-z_$][\w$]*\.authMethod===`apikey`&&([A-Za-z_$][\w$]*)!=null&&([A-Za-z_$][\w$]*)\(\1\)===`home`/); + /\/\* Codex:API-key 首页保持状态会话。 \*\/[A-Za-z_$][\w$]*\.authMethod===`apikey`&&([A-Za-z_$][\w$]*)!=null&&\(\1\.pathname===`\/`\|\|([A-Za-z_$][\w$]*)\(\1\)===`home`\)/); assert.match(navigationSource, /\/\* Codex:API-key 首页恢复最近会话。 \*\/[A-Za-z_$][\w$]*\.authMethod!==`apikey`/); const timelineEntries = files.filter(name => /^app-initial-/.test(name) From ef58e079d3aacbd1bd5659f420639211c8e2f31b Mon Sep 17 00:00:00 2001 From: carptopus Date: Sun, 18 Oct 2026 17:17:48 +0800 Subject: [PATCH 19/51] fix: restore API key home navigation --- README.md | 2 +- scripts/frontend-source-smoke.js | 11 +- scripts/patch-api-key-home-navigation.js | 438 +++++++----------- scripts/patch-api-key-home-navigation.test.js | 339 ++++++-------- 4 files changed, 316 insertions(+), 474 deletions(-) diff --git a/README.md b/README.md index f4497e99..39a13f0f 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ pnpm run build:all - `patch-browser-auth.js` 兼容 API-key 登录:旧版在 ChatGPT 身份读取失败时仅关闭可选 request-header 并继续本地浏览器通道;新版原生托管请求头不再依赖 ChatGPT 身份时验证该完整链路并保持原样,不会把 API key 伪装或发送为 ChatGPT token。 - `patch-fast-mode.js` 为 API-key / 自定义 Provider 补齐新版 `serviceTierAccess`:跳过不可用的 ChatGPT 账户权限查询,但仍由当前模型返回的 `serviceTierOptions` 决定是否显示和发送 Fast / Ultrafast 档位。 - `patch-provider-quota.js` 按任务实际 Provider 和明确的 `base_url` 判断发送门槛,避免 ChatGPT 额度状态误阻断第三方 Provider,同时保留官方、云任务及第三方真实错误。 -- `patch-api-key-home-navigation.js` 补齐 API-key 模式的当前会话导航记录,并复用官方首页区域分类器识别当前会话;当前会话点击首页保持不变,从设置等页面点击首页则恢复最近会话,避免直达空首页。ChatGPT、无认证及其他认证方式保持原有条件。 +- `patch-api-key-home-navigation.js` 补齐 API-key 模式的当前会话导航记录,并在官方公共首页恢复函数中复用当前位置短路;当前会话点击首页保持不变,从设置等页面点击首页则恢复最近会话,避免直达空首页。ChatGPT、无认证、其他认证方式及非首页区域保持原有条件。 - `patch-thread-timeline.js` 在当前 host 与 App Server 版本支持时启用官方 `thread/timeline/list` 历史路径,移除 API-key / 自定义 Provider 无法获得的远端灰度条件;版本兼容判断仍由官方逻辑负责。 - `patch-mcp-status-refresh.js` 将短时间内的 MCP 启动状态通知合并为一次轻量目录刷新;Full 目录只标记为 stale、不在后台立即重拉,详细 MCP 页面后续仍按官方 Full 查询取得资源与模板。 - `patch-remote-control.js` 不强开 Connections 或 Remote Control gate;只有真实 ChatGPT 认证才同步官方 Remote Control 本地状态,API-key 等其他认证会清除旧启用值并禁用当前 app-server 的 Remote Control。 diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index 29ecefce..e896adfd 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -81,13 +81,12 @@ function verifyFrontendSource(assets) { assert.equal(navigationEntries.length, 1); const navigationSource = fs.readFileSync(path.join(assets, navigationEntries[0]), "utf8"); assert.match(navigationSource, /\|\|\/\* Codex:API-key 首页恢复写入。 \*\/[A-Za-z_$][\w$]*===`apikey`/); - assert.match(navigationSource, /authMethod:__codexAuthMethod/); assert.match(navigationSource, - /\/\* Codex:API-key 当前首页保持会话。 \*\/__codexAuthMethod===`apikey`&&([A-Za-z_$][\w$]*)!=null&&\(\1\.pathname===`\/`\|\|([A-Za-z_$][\w$]*)\(\1\)===`home`\)/); - assert.match(navigationSource, - /\/\* Codex:API-key 首页保持状态会话。 \*\/[A-Za-z_$][\w$]*\.authMethod===`apikey`&&([A-Za-z_$][\w$]*)!=null&&\(\1\.pathname===`\/`\|\|([A-Za-z_$][\w$]*)\(\1\)===`home`\)/); - assert.match(navigationSource, - /\/\* Codex:API-key 首页恢复最近会话。 \*\/[A-Za-z_$][\w$]*\.authMethod!==`apikey`/); + /\([A-Za-z_$][\w$]*\|\|\/\* Codex:API-key 首页保持当前位置。 \*\/[A-Za-z_$][\w$]*===`auth:apikey`&&[A-Za-z_$][\w$]*===`home`\)&&[A-Za-z_$][\w$]*!=null/); + assert.doesNotMatch(navigationSource, /Codex:API-key 当前首页保持会话/); + assert.doesNotMatch(navigationSource, /Codex:API-key 首页保持状态会话/); + assert.doesNotMatch(navigationSource, /Codex:API-key 首页恢复最近会话/); + assert.doesNotMatch(navigationSource, /authMethod:__codexAuthMethod/); const timelineEntries = files.filter(name => /^app-initial-/.test(name) && fs.readFileSync(path.join(assets, name), "utf8").includes("CodexRebuildThreadTimeline")); assert.equal(timelineEntries.length, 1); diff --git a/scripts/patch-api-key-home-navigation.js b/scripts/patch-api-key-home-navigation.js index 6f59e52a..7d75f4b5 100644 --- a/scripts/patch-api-key-home-navigation.js +++ b/scripts/patch-api-key-home-navigation.js @@ -4,12 +4,11 @@ * * 上游的读取端会使用 auth:apikey 查找最近位置,但写入端同时受 * 新导航模式和 ChatGPT capability 限制,导致 API-key 下从不写入。 - * 同时,侧栏房子按钮使用独立的 openHome 分支直接导航到 `/`,不会进入 - * 上述首页恢复函数。这里只给该按钮传入真实 authMethod,并复用官方的 - * 首页区域分类器判断当前是否已经位于会话/首页区域。新版功能导航栏还有一条 - * “当前已经选中首页时再次点击”的直达 `/` 分支;API-key 必须跳过该分支, - * 交回官方首页位置记录器,才能从设置等页面恢复最近会话。 - * 补丁不开启 ChatGPT 账户能力,也不改变其他认证方式。 + * 官方公共首页恢复函数也只在 ChatGPT capability 可用时保持当前首页位置; + * API-key 因而会把仍在使用的当前会话判为不可恢复并回退到空的 `/` 路由。 + * 这里让 auth:apikey 仅在请求 home 且当前位置仍属于 home 时复用官方短路, + * 离开首页后仍由官方记录恢复逻辑处理,不再逐个修改具体按钮入口。 + * 补丁不开启 ChatGPT 账户能力,也不改变其他认证方式或其他导航区域。 */ const fs = require("node:fs"); const path = require("node:path"); @@ -18,9 +17,12 @@ const { applyEdits, literal, nodes, unique } = require("./patch-ast-util"); const { SRC_DIR, relPath } = require("./patch-util"); const MARKER = "/* Codex:API-key 首页恢复写入。 */"; -const CURRENT_HOME_MARKER = "/* Codex:API-key 当前首页保持会话。 */"; -const HOME_RESELECT_MARKER = "/* Codex:API-key 首页恢复最近会话。 */"; -const HOME_STATE_MARKER = "/* Codex:API-key 首页保持状态会话。 */"; +const HOME_CURRENT_MARKER = "/* Codex:API-key 首页保持当前位置。 */"; +const LEGACY_MARKERS = [ + "/* Codex:API-key 当前首页保持会话。 */", + "/* Codex:API-key 首页恢复最近会话。 */", + "/* Codex:API-key 首页保持状态会话。 */", +]; const PLATFORMS = ["mac-arm64", "mac-x64", "win", "unix"]; function propertyName(property) { @@ -47,6 +49,21 @@ function optionBinding(pattern, name) { ? property.value.left.name : null; } +function memberName(node) { + if (node?.type === "ChainExpression") node = node.expression; + if (node?.type !== "MemberExpression") return null; + if (!node.computed && node.property.type === "Identifier") return node.property.name; + return literal(node.property); +} + +function memberRoot(node) { + let current = node; + while (current?.type === "MemberExpression" || current?.type === "ChainExpression") { + current = current.type === "ChainExpression" ? current.expression : current.object; + } + return current?.type === "Identifier" ? current.name : null; +} + function findTracker(ast) { const candidates = []; for (const fn of ast.body.filter(node => node.type === "FunctionDeclaration")) { @@ -86,11 +103,9 @@ function findTracker(ast) { node.start <= accountAssignment[0].start && node.end >= accountAssignment[0].end); const outermost = guards.filter(node => !guards.some(other => other !== node && other.start <= node.start && other.end >= node.end)); - if (outermost.length !== 1) continue; - const guard = outermost[0]; - if (guard.left?.type !== "LogicalExpression") continue; + if (outermost.length !== 1 || outermost[0].left?.type !== "LogicalExpression") continue; - candidates.push({ authMethod: auth[0].authMethod, gate: guard.left }); + candidates.push({ authMethod: auth[0].authMethod, gate: outermost[0].left }); } if (candidates.length > 1) throw new Error(`首页导航跟踪器 数量异常(${candidates.length})`); return candidates[0] ?? null; @@ -101,301 +116,183 @@ function isTrue(node) { node.operator === "!" && literal(node.argument) === 0; } -function memberName(node) { - if (node?.type === "ChainExpression") node = node.expression; - if (node?.type !== "MemberExpression") return null; - if (!node.computed && node.property.type === "Identifier") return node.property.name; - return literal(node.property); +function returnsTrue(node) { + if (node?.type === "ReturnStatement") return isTrue(node.argument); + return node?.type === "BlockStatement" && node.body.length === 1 && + node.body[0].type === "ReturnStatement" && isTrue(node.body[0].argument); } -function memberObject(node) { - if (node?.type === "ChainExpression") node = node.expression; - return node?.type === "MemberExpression" ? node.object : null; +function equalityWithIdentifier(node, identifier) { + if (node?.type !== "BinaryExpression" || !["===", "=="].includes(node.operator)) return null; + if (node.left?.type === "Identifier" && node.left.name === identifier) return node.right; + if (node.right?.type === "Identifier" && node.right.name === identifier) return node.left; + return null; } -function memberRoot(node) { +function isNotNullComparison(node, identifier) { + if (node?.type !== "BinaryExpression" || !["!=", "!=="].includes(node.operator)) return false; + return (node.left?.type === "Identifier" && node.left.name === identifier && + literal(node.right) === null) || + (node.right?.type === "Identifier" && node.right.name === identifier && + literal(node.left) === null); +} + +function firstAndOperand(node) { let current = node; - while (current?.type === "MemberExpression" || current?.type === "ChainExpression") { - current = current.type === "ChainExpression" ? current.expression : current.object; - } - return current?.type === "Identifier" ? current.name : null; + while (current?.type === "LogicalExpression" && current.operator === "&&") current = current.left; + return current; } -function objectProperty(node, name) { - return node?.properties?.find(property => propertyName(property) === name) ?? null; +function logicalOperands(node, operator) { + if (node?.type !== "LogicalExpression" || node.operator !== operator) return [node]; + return [...logicalOperands(node.left, operator), ...logicalOperands(node.right, operator)]; } -function findOpenHomeRoute(ast, source) { - const routes = []; - for (const fn of ast.body.filter(node => node.type === "FunctionDeclaration")) { - const options = fn.params[1]; - if (options?.type !== "ObjectPattern") continue; - const bindings = Object.fromEntries([ - "codexLocalAccessStatus", "currentMode", "navigate", "nextMode", "openHome", - "restoreNavigation", "startNewConversation", "authMethod", - ].map(name => [name, optionBinding(options, name)])); - if (["codexLocalAccessStatus", "currentMode", "navigate", "nextMode", "openHome", - "restoreNavigation", "startNewConversation"].some(name => !bindings[name])) continue; - - const branches = nodes(fn, node => { - if (node.type !== "IfStatement") return false; - const testIdentifiers = nodes(node.test, item => item.type === "Identifier") - .map(item => item.name); - if (!testIdentifiers.includes(bindings.openHome)) return false; - const body = nodes(node.consequent, () => true); - return body.some(item => item.type === "ReturnStatement") && - body.some(item => item.type === "CallExpression" && - item.callee?.type === "Identifier" && item.callee.name === bindings.navigate && - literal(item.arguments[0]) === "/" && - item.arguments[1]?.type === "ObjectExpression" && - objectProperty(objectProperty(item.arguments[1], "state")?.value, "sidebarProductMode")?.value?.name === bindings.nextMode); - }, { ownScope: true }); - if (branches.length !== 1) continue; - - const libraryRoots = new Set(nodes(fn, node => node.type === "CallExpression" && - memberName(node.callee) === "startsWith" && literal(node.arguments[0]) === "/library/" && - memberName(memberObject(node.callee)) === "pathname") - .map(node => memberRoot(memberObject(node.callee))).filter(Boolean)); - const exactLibraryRoots = new Set(nodes(fn, node => node.type === "BinaryExpression" && - ["===", "=="].includes(node.operator) && literal(node.right) === "/library" && - memberName(node.left) === "pathname") - .map(node => memberRoot(node.left)).filter(Boolean)); - const currentLocations = [...libraryRoots].filter(name => exactLibraryRoots.has(name)); - if (currentLocations.length !== 1) continue; - routes.push({ - authMethod: bindings.authMethod, - branch: branches[0], - currentLocation: currentLocations[0], - fn, - options, - name: fn.id?.name, - }); - } - const route = unique(routes, "房子按钮 openHome 路由"); - const callers = []; - for (const fn of ast.body.filter(node => node.type === "FunctionDeclaration")) { - const authBindings = nodes(fn, node => node.type === "VariableDeclarator" && - node.id?.type === "ObjectPattern", true) - .map(node => objectBinding(node.id, "authMethod")).filter(Boolean); - if (authBindings.length !== 1) continue; - for (const call of nodes(fn, node => node.type === "CallExpression" && - node.callee?.type === "Identifier" && node.callee.name === route.name)) { - const options = call.arguments[1]; - if (options?.type !== "ObjectExpression" || - !isTrue(objectProperty(options, "openHome")?.value) || - literal(objectProperty(options, "nextMode")?.value) !== "codex") continue; - const homeClassifiers = nodes(fn, node => node.type === "BinaryExpression" && - ["===", "=="].includes(node.operator) && literal(node.right) === "home" && - node.left?.type === "CallExpression" && node.left.callee?.type === "Identifier" && - node.left.arguments.length === 1, { ownScope: true }); - if (homeClassifiers.length !== 1) continue; - callers.push({ - authMethod: authBindings[0], - call, - homeClassifier: homeClassifiers[0].left.callee.name, - options, - passedAuthMethod: objectProperty(options, "authMethod")?.value, - }); - } - } - const caller = unique(callers, "房子按钮调用点"); - const markedGuards = nodes(route.fn, node => node.type === "IfStatement" && - source.slice(node.start, node.consequent.start).includes(CURRENT_HOME_MARKER), { ownScope: true }); - if (markedGuards.length > 1) { - throw new Error(`房子按钮当前会话守卫 数量异常(${markedGuards.length})`); - } - const markerPresent = markedGuards.length === 1; - const guardSource = markerPresent - ? source.slice(markedGuards[0].test.start, markedGuards[0].test.end) - : ""; - const currentAreaGuardPresent = guardSource.includes( - `${route.currentLocation}.pathname===\`/\`||${caller.homeClassifier}(${route.currentLocation})===\`home\``, - ); - return { ...route, caller, currentAreaGuardPresent, markerPresent }; +function comparison(node, identifier, value) { + if (node?.type !== "BinaryExpression" || !["===", "=="].includes(node.operator)) return false; + return (node.left?.type === "Identifier" && node.left.name === identifier && + literal(node.right) === value) || + (node.right?.type === "Identifier" && node.right.name === identifier && + literal(node.left) === value); +} + +function isApiKeyHomeGate(node, capability, accountKey, area) { + if (node?.type !== "LogicalExpression" || node.operator !== "||" || + node.left?.type !== "Identifier" || node.left.name !== capability) return false; + const conditions = logicalOperands(node.right, "&&"); + return conditions.length === 2 && + conditions.some(item => comparison(item, accountKey, "auth:apikey")) && + conditions.some(item => comparison(item, area, "home")); } -function findHomeRailReselect(ast, source) { +function findHomeRestore(ast, source) { const candidates = []; for (const fn of ast.body.filter(node => node.type === "FunctionDeclaration")) { - const authBindings = nodes(fn, node => node.type === "VariableDeclarator" && - node.id?.type === "ObjectPattern" && node.init?.type === "Identifier", true) - .map(node => ({ - authMethod: objectBinding(node.id, "authMethod"), - authState: node.init.name, - })) - .filter(item => item.authMethod); - if (authBindings.length !== 1) continue; - - for (const arrow of nodes(fn, node => node.type === "ArrowFunctionExpression")) { - const restoreCalls = nodes(arrow, node => { - if (node.type !== "CallExpression" || node.arguments[1]?.type !== "ObjectExpression") return false; - const options = node.arguments[1]; - return ["accountKey", "area", "navigate", "productMode", "state"].every(name => - objectProperty(options, name)?.value?.type === "Identifier"); - }, { ownScope: true }); - if (restoreCalls.length !== 1) continue; - const restoreCall = restoreCalls[0]; - const options = restoreCall.arguments[1]; - const area = objectProperty(options, "area").value.name; - const productMode = objectProperty(options, "productMode").value.name; - const branches = nodes(arrow, node => { - if (node.type !== "IfStatement" || node.start >= restoreCall.start) return false; - const testNames = new Set(nodes(node.test, item => item.type === "Identifier") - .map(item => item.name)); - if (!testNames.has(area) || !testNames.has(productMode)) return false; - const body = nodes(node.consequent, () => true); - return body.some(item => item.type === "ReturnStatement") && - body.some(item => memberName(item) === "path"); - }, { ownScope: true }); - if (branches.length !== 1) continue; - const branch = branches[0]; - const store = restoreCall.arguments[0]; - if (store?.type !== "Identifier") continue; - const currentLocationReads = nodes(branch.consequent, node => - node.type === "VariableDeclarator" && node.id?.type === "Identifier" && - node.init?.type === "CallExpression" && node.init.arguments.length === 1 && - memberName(node.init.callee) === "get" && - memberRoot(node.init.callee) === store.name && - node.init.arguments[0]?.type === "Identifier"); - if (currentLocationReads.length !== 1) continue; - const currentLocationAtom = currentLocationReads[0].init.arguments[0].name; - const parentFunctions = nodes(fn, node => /Function/.test(node.type)) - .filter(node => node !== arrow && node.start < arrow.start && node.end > arrow.end) - .sort((left, right) => (left.end - left.start) - (right.end - right.start)); - const parentFunction = parentFunctions[0]; - if (parentFunction == null) continue; - const visibleLocationReads = nodes(parentFunction, node => - node.type === "VariableDeclarator" && node.id?.type === "Identifier" && - node.init?.type === "CallExpression" && node.init.arguments.length === 1 && - memberName(node.init.callee) === "get" && - memberRoot(node.init.callee) === store.name && - node.init.arguments[0]?.type === "Identifier" && - node.init.arguments[0].name === currentLocationAtom, { ownScope: true }); - if (visibleLocationReads.length !== 1) continue; - const markedStateGuards = nodes(arrow, node => node.type === "IfStatement" && - node.start < restoreCall.start && - source.slice(node.start, node.consequent.start).includes(HOME_STATE_MARKER), - { ownScope: true }); - if (markedStateGuards.length > 1) { - throw new Error(`功能导航栏当前首页守卫 数量异常(${markedStateGuards.length})`); - } + if (fn.params.length < 2 || fn.params[0]?.type !== "Identifier" || + fn.params[1]?.type !== "ObjectPattern") continue; + const store = fn.params[0].name; + const options = fn.params[1]; + const bindings = Object.fromEntries(["accountKey", "auth", "area", "navigate", "productMode", "state"] + .map(name => [name, optionBinding(options, name)])); + if (Object.values(bindings).some(value => value == null)) continue; + + for (const branch of nodes(fn, node => node.type === "IfStatement" && returnsTrue(node.consequent), + { ownScope: true })) { + const areaCalls = nodes(branch.test, node => { + const other = equalityWithIdentifier(node, bindings.area); + return other?.type === "CallExpression"; + }).map(node => equalityWithIdentifier(node, bindings.area)); + const currentNames = areaCalls.flatMap(call => call.arguments + .filter(argument => argument?.type === "Identifier" && argument.name !== store) + .map(argument => argument.name)); + const current = [...new Set(currentNames)].find(name => + nodes(branch.test, node => isNotNullComparison(node, name)).length === 1); + if (current == null) continue; + + const productChecks = nodes(branch.test, + node => equalityWithIdentifier(node, bindings.productMode)?.type === "CallExpression"); + if (productChecks.length !== 1) continue; + + const gate = firstAndOperand(branch.test); + const capability = gate?.type === "Identifier" ? gate.name : + gate?.type === "LogicalExpression" && gate.operator === "||" && + gate.left?.type === "Identifier" ? gate.left.name : null; + if (capability == null) continue; + const capabilityDeclarations = fn.body.body + .filter(node => node.type === "VariableDeclaration") + .flatMap(node => node.declarations) + .filter(node => node.id?.type === "Identifier" && node.id.name === capability && + node.init?.type === "CallExpression" && memberName(node.init.callee) === "get" && + memberRoot(node.init.callee) === store); + if (capabilityDeclarations.length !== 1) continue; + candidates.push({ - authMethod: authBindings[0].authMethod, - authState: authBindings[0].authState, - branch, - currentLocation: visibleLocationReads[0].id.name, - markerPresent: source.slice(branch.start, restoreCall.start) - .includes(HOME_RESELECT_MARKER), - stateGuardSource: markedStateGuards.length === 1 - ? source.slice(markedStateGuards[0].test.start, markedStateGuards[0].test.end) - : "", - stateMarkerPresent: markedStateGuards.length === 1, + accountKey: bindings.accountKey, + area: bindings.area, + capability, + current, + gate, + markerPresent: source.slice(gate.start, gate.end).includes(HOME_CURRENT_MARKER), }); } } - return unique(candidates, "功能导航栏首页重选分支"); + if (candidates.length > 1) throw new Error(`公共首页恢复当前位置分支 数量异常(${candidates.length})`); + return candidates[0] ?? null; } function isApiKeyOverride(node, authMethod) { if (node?.type !== "LogicalExpression" || node.operator !== "||") return false; - const comparison = node.right; - return comparison?.type === "BinaryExpression" && ["===", "=="].includes(comparison.operator) && - comparison.left?.type === "Identifier" && comparison.left.name === authMethod && - literal(comparison.right) === "apikey"; -} - -function isApiKeyRailGuard(node, authState) { - return nodes(node, item => item.type === "BinaryExpression" && - ["!==", "!="].includes(item.operator) && - memberName(item.left) === "authMethod" && memberRoot(item.left) === authState && - literal(item.right) === "apikey").length === 1; + const comparisonNode = node.right; + return comparisonNode?.type === "BinaryExpression" && + ["===", "=="].includes(comparisonNode.operator) && + comparisonNode.left?.type === "Identifier" && comparisonNode.left.name === authMethod && + literal(comparisonNode.right) === "apikey"; } function patchSource(source) { + const legacyMarker = LEGACY_MARKERS.find(marker => source.includes(marker)); + if (legacyMarker != null) { + return { + status: "unexpected-shape", + source, + reason: "检测到旧入口级首页补丁;必须从未应用旧补丁的上游 Bundle 重新构建", + }; + } if (!["authMethod", "accountKey", "productMode", "auth:", "chatgpt:"].every(value => source.includes(value))) { + if (source.includes(MARKER) || source.includes(HOME_CURRENT_MARKER)) { + return { status: "unexpected-shape", source, reason: "补丁标记存在但首页导航结构未知" }; + } return { status: "not-applicable", source }; } try { const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); const tracker = findTracker(ast); - const openHome = findOpenHomeRoute(ast, source); - const homeRail = findHomeRailReselect(ast, source); - if (tracker == null || openHome == null || homeRail == null) { - if (source.includes(MARKER) || source.includes(CURRENT_HOME_MARKER) || - source.includes(HOME_RESELECT_MARKER) || source.includes(HOME_STATE_MARKER)) { + const homeRestore = findHomeRestore(ast, source); + if (tracker == null || homeRestore == null) { + if (source.includes(MARKER) || source.includes(HOME_CURRENT_MARKER)) { throw new Error("补丁标记存在但首页导航结构未知"); } return { status: "not-applicable", source }; } + const trackerPatched = isApiKeyOverride(tracker.gate, tracker.authMethod); - const openHomePatched = openHome.markerPresent && openHome.currentAreaGuardPresent && - openHome.authMethod === "__codexAuthMethod" && - openHome.caller.passedAuthMethod?.type === "Identifier" && - openHome.caller.passedAuthMethod.name === openHome.caller.authMethod; - const homeRailPatched = homeRail.markerPresent && homeRail.stateMarkerPresent && - homeRail.stateGuardSource.includes( - `${homeRail.currentLocation}.pathname===\`/\`||${openHome.caller.homeClassifier}(${homeRail.currentLocation})===\`home\``, - ) && isApiKeyRailGuard(homeRail.branch.test, homeRail.authState); - if (trackerPatched) { - const gateSource = source.slice(tracker.gate.start, tracker.gate.end); - if (!gateSource.includes(MARKER)) throw new Error("API-key 放行逻辑存在但缺少本项目标记"); - } else if (tracker.gate.type !== "LogicalExpression" || tracker.gate.operator !== "&&" || - tracker.gate.left?.type !== "Identifier" || tracker.gate.right?.type !== "Identifier") { - throw new Error("导航模式与 ChatGPT capability 条件结构未知"); + const homePatched = isApiKeyHomeGate(homeRestore.gate, homeRestore.capability, + homeRestore.accountKey, homeRestore.area); + if (trackerPatched && !source.slice(tracker.gate.start, tracker.gate.end).includes(MARKER)) { + throw new Error("API-key 放行逻辑存在但缺少本项目标记"); + } + if (homePatched && !homeRestore.markerPresent) { + throw new Error("API-key 首页当前位置逻辑存在但缺少本项目标记"); } - const openHomePartiallyPatched = openHome.markerPresent || openHome.authMethod != null || - openHome.caller.passedAuthMethod != null; - if (!openHomePatched && openHomePartiallyPatched) { - throw new Error("房子按钮 API-key 保持逻辑不完整"); + if (!trackerPatched && (source.includes(MARKER) || + tracker.gate.type !== "LogicalExpression" || tracker.gate.operator !== "&&" || + tracker.gate.left?.type !== "Identifier" || tracker.gate.right?.type !== "Identifier")) { + throw new Error("导航模式与 ChatGPT capability 条件结构未知"); } - if ((homeRail.markerPresent || homeRail.stateMarkerPresent) && !homeRailPatched) { - throw new Error("功能导航栏首页恢复逻辑不完整"); + if (!homePatched && (source.includes(HOME_CURRENT_MARKER) || + homeRestore.gate.type !== "Identifier")) { + throw new Error("公共首页恢复当前位置逻辑不完整"); } - if (trackerPatched && openHomePatched && homeRailPatched) { - return { status: "already-patched", source }; + if (trackerPatched !== homePatched) { + throw new Error("API-key 首页补丁只完成了一部分"); } + if (trackerPatched) return { status: "already-patched", source }; - const edits = []; - if (!trackerPatched) { - const originalGate = source.slice(tracker.gate.start, tracker.gate.end); - edits.push({ + const originalTrackerGate = source.slice(tracker.gate.start, tracker.gate.end); + const next = applyEdits(source, [ + { start: tracker.gate.start, end: tracker.gate.end, - replacement: `(${originalGate}||${MARKER}${tracker.authMethod}===\`apikey\`)`, - }); - } - if (!openHomePatched) { - edits.push({ - start: openHome.options.start + 1, - end: openHome.options.start + 1, - replacement: "authMethod:__codexAuthMethod,", - }); - edits.push({ - start: openHome.caller.options.start + 1, - end: openHome.caller.options.start + 1, - replacement: `authMethod:${openHome.caller.authMethod},`, - }); - edits.push({ - start: openHome.branch.start, - end: openHome.branch.start, - replacement: `if(${CURRENT_HOME_MARKER}__codexAuthMethod===\`apikey\`&&${openHome.currentLocation}!=null&&(${openHome.currentLocation}.pathname===\`/\`||${openHome.caller.homeClassifier}(${openHome.currentLocation})===\`home\`))return;`, - }); - } - if (!homeRailPatched) { - const originalTest = source.slice(homeRail.branch.test.start, homeRail.branch.test.end); - edits.push({ - start: homeRail.branch.start, - end: homeRail.branch.start, - replacement: `if(${HOME_STATE_MARKER}${homeRail.authState}.authMethod===\`apikey\`&&${homeRail.currentLocation}!=null&&(${homeRail.currentLocation}.pathname===\`/\`||${openHome.caller.homeClassifier}(${homeRail.currentLocation})===\`home\`))return;`, - }); - edits.push({ - start: homeRail.branch.test.start, - end: homeRail.branch.test.end, - replacement: `(${HOME_RESELECT_MARKER}${homeRail.authState}.authMethod!==\`apikey\`&&(${originalTest}))`, - }); - } - const next = applyEdits(source, edits); + replacement: `(${originalTrackerGate}||${MARKER}${tracker.authMethod}===\`apikey\`)`, + }, + { + start: homeRestore.gate.start, + end: homeRestore.gate.end, + replacement: `(${homeRestore.capability}||${HOME_CURRENT_MARKER}` + + `${homeRestore.accountKey}===\`auth:apikey\`&&${homeRestore.area}===\`home\`)`, + }, + ]); return { status: "patched", source: next }; } catch (error) { return { status: "unexpected-shape", source, reason: error.message }; @@ -431,13 +328,13 @@ function main() { if (target.result.status === "unexpected-shape") throw new Error(target.result.reason); console.log(` [${directory.platform}] ${relPath(target.file.path)}`); if (target.result.status === "already-patched") { - console.log(" [ok] API-key 首页导航记录和当前会话保持已启用"); + console.log(" [ok] API-key 首页导航记录和公共当前位置保持已启用"); } else if (check) { - console.log(" [ok] API-key 首页导航写入与当前会话锚点已核对;dry-run 未写文件"); + console.log(" [ok] API-key 首页导航写入与公共恢复分支已核对;dry-run 未写文件"); } else { fs.writeFileSync(target.file.path, target.result.source, "utf8"); patched++; - console.log(" [ok] API-key 将保存并恢复首页会话,当前会话点击首页保持不变"); + console.log(" [ok] API-key 将保存并恢复首页会话,当前首页会话保持不变"); } } catch (error) { console.error(` [x] ${directory.platform}: ${error.message}`); @@ -454,9 +351,8 @@ function main() { if (require.main === module) main(); module.exports = { - CURRENT_HOME_MARKER, - HOME_RESELECT_MARKER, - HOME_STATE_MARKER, + HOME_CURRENT_MARKER, + LEGACY_MARKERS, MARKER, patchSource, }; diff --git a/scripts/patch-api-key-home-navigation.test.js b/scripts/patch-api-key-home-navigation.test.js index 26cc3a0b..a1111f10 100644 --- a/scripts/patch-api-key-home-navigation.test.js +++ b/scripts/patch-api-key-home-navigation.test.js @@ -2,289 +2,236 @@ const test = require("node:test"); const assert = require("node:assert/strict"); const { - CURRENT_HOME_MARKER, - HOME_RESELECT_MARKER, - HOME_STATE_MARKER, + HOME_CURRENT_MARKER, + LEGACY_MARKERS, MARKER, patchSource, } = require("./patch-api-key-home-navigation"); function fixture() { return [ - "function Lhc(){", - "let e=cache(),t=store(),n=location(),{accountId:r,authMethod:i}=mp(),", - "a=mode()!==`legacy`,o=capability(),s=productMode(),c=project(),l;", + "function Track(){", + "let e=cache(),t=store(),n=location(),{accountId:r,authMethod:i}=auth(),", + "a=mode()!==`legacy`,o=capability(),s=productMode(),l;", "e[0]!==r||e[1]!==i||e[2]!==a||e[3]!==o?", "(l=null,a&&o&&(i===`chatgpt`&&r!=null?l=`chatgpt:${r}`:i!=null&&(l=`auth:${i}`)),", "e[0]=r,e[1]=i,e[2]=a,e[3]=o,e[4]=l):l=e[4];", - "yti(t,{accountKey:l,location:n,productMode:s});return l", + "track(t,{accountKey:l,location:n,productMode:s});return l", "}", - "function Sti(e,{accountKey:t,auth:n,area:r,navigate:i,productMode:a,state:o}){", - "let s=e.get(wc),c=e.get(Ug),u=bti(e,{accountKey:t,auth:n,area:r,productMode:a});", - "if(s&&c!=null&&sti(c,r).hash===c.hash&&Ati(e,c)===r&&e.get(lj)===a&&", + "function restore(e,{accountKey:t,auth:n,area:r,navigate:i,productMode:a,state:o}){", + "let s=e.get(AE),c=e.get(CH),u=remembered(e,{accountKey:t,auth:n,area:r,productMode:a});", + "if(s&&c!=null&&same(c,r).hash===c.hash&&areaOf(e,c)===r&&e.get(PM)===a&&", "(c.state?.sidebarProductMode==null||c.state.sidebarProductMode===a))return!0;", - "if(u==null||!s&&u.departedAt==null||Ati(e,u.location)!==r){i(`/`);return!0}", - "return i(ym(u.location)),!0}", - "function wti(e,{codexLocalAccessStatus:t,currentMode:n,navigate:r,nextMode:i,openHome:a=!1,restoreNavigation:o=!0,startNewConversation:s}){", - "let c=e.get(wc);if(i===n&&!a)return;dei(e);let l=e.get(Pti,i),u=e.get(Ug),d=e.get(ye),", - "f=u?.pathname===`/library`||u?.pathname.startsWith(`/library/`);", - "if(u!=null&&!f&&e.set(Pti,n,{location:u,selectedProject:d}),SFe(e,i),a){r(`/`,{state:{sidebarProductMode:i}});return}", - "if(!o)return;if(l==null){s();return}r(l.location)}", - "function homeArea(e){return e?.pathname===`/`||e?.pathname.startsWith(`/settings/`)?null:`home`}", - "function Pjo(){let i=store(),h=navigate(),a=start(),{accountId:O,authMethod:k}=mp(),", - "p=location(),selected=homeArea(p)===`home`&&mode()===`codex`,", - "c=()=>{wti(i,{codexLocalAccessStatus:`allowed`,currentMode:`codex`,navigate:h,nextMode:`codex`,openHome:!0,startNewConversation:a})};return c}", - "function Rail({selectedArea:A}){let P=scope(),N=productMode(),C=auth(),", - "{accountId:w,authMethod:T,userId:E,isLoading:D}=C,O=`auth:${T}`,", - "M=(e,t)=>{let n=N,r=P.get(currentMode),a=destinations[e],o=P.get(currentLocation);run(a,t=>{", - "if(A===e&&r===n){let n=destinations[e];if(n==null)return;let r=P.get(currentLocation),i=r!=null&&belongs(r,n);(!i)&&navigate(n.path,{state:t});return}", - "restoreHome(P,{accountKey:O,auth:C,area:e,navigate:navigate,productMode:n,state:t})})};return M}", + "if(u==null||!s&&u.departedAt==null||areaOf(e,u.location)!==r){i(`/`);return!0}", + "return s?nativeRestore(e,u,o):(i(u.location.pathname,{state:o}),!0)", + "}", + "function Rail(e,o){let d={id:`builtin:home`};return()=>restore(e,{...o,area:`home`})}", ].join(""); } -function load(source, auth, capability, modeValue = "current") { - return Function("auth", "capabilityValue", "modeValue", [ +function loadTracker(source, authValue, capabilityValue, modeValue = "current") { + return Function("authValue", "capabilityValue", "modeValue", [ "const cache=()=>[];const store=()=>({});const location=()=>({});", - "const mp=()=>auth;const mode=()=>modeValue;const capability=()=>capabilityValue;", - "const productMode=()=>`codex`;const project=()=>null;const yti=()=>{};", + "const auth=()=>authValue;const mode=()=>modeValue;const capability=()=>capabilityValue;", + "const productMode=()=>`codex`;const track=()=>{};", source, - "return Lhc();", - ].join(""))(auth, capability, modeValue); + "return Track();", + ].join(""))(authValue, capabilityValue, modeValue); } -test("API-key 在 ChatGPT capability 关闭时仍写入与读取端一致的 accountKey", () => { - const result = patchSource(fixture()); - - assert.equal(result.status, "patched"); - assert.ok(result.source.includes(MARKER)); - assert.match(result.source, /\(a&&o\|\|\/\* Codex:API-key 首页恢复写入。 \*\/i===`apikey`\)&&/); - assert.equal(load(result.source, { accountId: null, authMethod: "apikey" }, false), "auth:apikey"); - assert.equal(load(result.source, { accountId: null, authMethod: "apikey" }, false, "legacy"), "auth:apikey"); - assert.equal(patchSource(result.source).status, "already-patched"); -}); - -function clickHome(source, authMethod, { - currentPath = "/local/thread-1", - currentState, +function clickHome(source, { + accountKey = "auth:apikey", + capability = false, + currentArea = "home", + rememberedArea = "home", + rememberedDepartedAt = 1, + rememberedPath = "/thread/remembered", + hasRemembered = true, } = {}) { const navigations = []; - const current = currentPath == null ? null : { pathname: currentPath, state: currentState }; - const store = { + const current = currentArea == null ? null : { + area: currentArea, + hash: `same`, + state: { sidebarProductMode: "codex" }, + }; + const rememberedValue = hasRemembered ? { + departedAt: rememberedDepartedAt, + location: { area: rememberedArea, pathname: rememberedPath }, + } : null; + const activeStore = { get(key) { - if (key === "wc") return false; - if (key === "Ug") return current; + if (key === "AE") return capability; + if (key === "CH") return current; + if (key === "PM") return "codex"; return null; }, - set() {}, }; - const run = Function("activeStore", "recordNavigation", "authMethod", [ - "const wc=`wc`,Ug=`Ug`,Pti=`Pti`,ye=`ye`;", - "const store=()=>activeStore,location=()=>activeStore.get(Ug),mode=()=>`codex`,navigate=()=>path=>recordNavigation(path),start=()=>()=>{};", - "const mp=()=>({accountId:null,authMethod});const dei=()=>{},SFe=()=>{};", + const invoke = Function("activeStore", "accountKey", "rememberedValue", "recordNavigation", [ + "const AE=`AE`,CH=`CH`,PM=`PM`;", + "const cache=()=>[];const store=()=>({});const location=()=>({});", + "const auth=()=>({accountId:null,authMethod:`apikey`});const mode=()=>`current`;", + "const capability=()=>false,productMode=()=>`codex`,track=()=>{};", + "const remembered=()=>rememberedValue;const same=()=>({hash:`same`});", + "const areaOf=(_store,value)=>value.area;const nativeRestore=()=>true;", source, - "return Pjo()();", + "return Rail(activeStore,{accountKey,auth:{},navigate:path=>recordNavigation(path),", + "productMode:`codex`,state:{}})();", ].join("")); - run(store, path => navigations.push(path), authMethod); + invoke(activeStore, accountKey, rememberedValue, path => navigations.push(path)); return navigations; } -test("API-key 点击真实侧栏房子按钮保持当前本地会话", () => { +test("API-key 在 ChatGPT capability 关闭时仍写入与读取端一致的 accountKey", () => { const result = patchSource(fixture()); - assert.ok(result.source.includes(CURRENT_HOME_MARKER)); - assert.match(result.source, /authMethod:__codexAuthMethod/); - assert.match(result.source, /authMethod:k/); - assert.deepEqual(clickHome(result.source, "apikey"), []); -}); - -test("API-key 远程会话点击首页保持当前会话", () => { - const result = patchSource(fixture()); - const navigations = clickHome(result.source, "apikey", { - currentPath: "/remote/task-1", - }); - - assert.deepEqual(navigations, []); + assert.equal(result.status, "patched"); + assert.ok(result.source.includes(MARKER)); + assert.match(result.source, /\(a&&o\|\|\/\* Codex:API-key 首页恢复写入。 \*\/i===`apikey`\)&&/); + assert.equal(loadTracker(result.source, { accountId: null, authMethod: "apikey" }, false), + "auth:apikey"); + assert.equal(loadTracker(result.source, { accountId: null, authMethod: "apikey" }, false, "legacy"), + "auth:apikey"); }); -test("API-key 根路径已属于首页区域时不再导航到空路由", () => { +test("builtin:home 通过公共恢复函数保持 API-key 当前首页会话", () => { const result = patchSource(fixture()); - const navigations = clickHome(result.source, "apikey", { - currentPath: "/", - }); - - assert.deepEqual(navigations, []); -}); -test("测试夹具保持真实 Bundle 的裸根路由分类行为", () => { - assert.match(fixture(), /pathname===`\/`\|\|e\?\.pathname\.startsWith/); - const result = patchSource(fixture()); - assert.match(result.source, /u\.pathname===`\/`\|\|homeArea\(u\)===`home`/); + assert.equal(result.status, "patched"); + assert.ok(result.source.includes("builtin:home")); + assert.ok(result.source.includes(HOME_CURRENT_MARKER)); + assert.match(result.source, + /\(s\|\|\/\* Codex:API-key 首页保持当前位置。 \*\/t===`auth:apikey`&&r===`home`\)&&c!=null/); + assert.deepEqual(clickHome(result.source), []); }); -test("API-key 根路径携带会话位置状态时保持当前会话", () => { +test("API-key 从设置页进入首页时恢复已记录的会话", () => { const result = patchSource(fixture()); - const navigations = clickHome(result.source, "apikey", { - currentPath: "/", - currentState: { sidebarThreadLocationId: "chats" }, - }); - assert.deepEqual(navigations, []); + assert.deepEqual(clickHome(result.source, { currentArea: "settings" }), ["/thread/remembered"]); }); -test("ChatGPT 根路径携带会话位置状态时保持官方首页行为", () => { +test("API-key 没有首页记录时保留官方根路由 fallback", () => { const result = patchSource(fixture()); - const navigations = clickHome(result.source, "chatgpt", { - currentPath: "/", - currentState: { sidebarThreadLocationId: "chats" }, - }); - assert.deepEqual(navigations, ["/"]); + assert.deepEqual(clickHome(result.source, { currentArea: "settings", hasRemembered: false }), ["/"]); }); -test("API-key 尚无当前路由时不访问空对象", () => { +test("ChatGPT capability 可用时保持官方当前首页短路", () => { const result = patchSource(fixture()); - const navigations = clickHome(result.source, "apikey", { - currentPath: null, - }); - assert.deepEqual(navigations, ["/"]); + assert.deepEqual(clickHome(result.source, { + accountKey: "chatgpt:account-1", + capability: true, + }), []); }); -test("ChatGPT 登录不获得 API-key 房子按钮短路", () => { +test("ChatGPT capability 不可用时不会获得 API-key 特例", () => { const result = patchSource(fixture()); - const navigations = clickHome(result.source, "chatgpt"); - assert.deepEqual(navigations, ["/"]); + assert.deepEqual(clickHome(result.source, { + accountKey: "chatgpt:account-1", + capability: false, + rememberedDepartedAt: null, + }), ["/"]); }); -test("API-key 从设置页点击房子仍执行官方首页导航", () => { +test("其他认证方式不会获得 API-key 特例", () => { const result = patchSource(fixture()); - const navigations = clickHome(result.source, "apikey", { - currentPath: "/settings/appearance", - }); - assert.deepEqual(navigations, ["/"]); + assert.deepEqual(clickHome(result.source, { + accountKey: "auth:chatgptAuthTokens", + rememberedDepartedAt: null, + }), ["/"]); }); -function clickFeatureHome(source, authMethod, { - currentPath = "/settings/appearance", - currentState, -} = {}) { - const navigations = []; - const restores = []; - const scopeValue = { - get(key) { - if (key === "currentMode") return "codex"; - if (key === "currentLocation") return { pathname: currentPath, state: currentState }; - return null; - }, - }; - const run = Function("authMethod", "scopeValue", "recordNavigation", "recordRestore", [ - "const scope=()=>scopeValue,productMode=()=>`codex`;", - "const auth=()=>({accountId:null,authMethod,userId:null,isLoading:false});", - "const currentMode=`currentMode`,currentLocation=`currentLocation`;", - "const destinations={home:{path:`/`}},run=(_destination,callback)=>callback({});", - "const belongs=()=>false,navigate=path=>recordNavigation(path);", - "const restoreHome=(_scope,options)=>recordRestore(options.area);", - source, - "return Rail({selectedArea:`home`})(`home`,{});", - ].join("")); - run(authMethod, scopeValue, path => navigations.push(path), area => restores.push(area)); - return { navigations, restores }; -} - -test("API-key 重选功能导航栏首页时恢复记录的最近会话", () => { +test("API-key 的非首页区域不会获得首页当前位置特例", () => { const result = patchSource(fixture()); + const direct = result.source.replace("area:`home`", "area:`scheduled`"); - assert.ok(result.source.includes(HOME_RESELECT_MARKER)); - assert.deepEqual(clickFeatureHome(result.source, "apikey"), { - navigations: [], - restores: ["home"], - }); + assert.deepEqual(clickHome(direct, { + currentArea: "scheduled", + rememberedArea: "scheduled", + rememberedDepartedAt: null, + }), ["/"]); }); -test("API-key 重选功能导航栏首页时保持根路径中的当前状态会话", () => { - const result = patchSource(fixture()); +test("补丁可重复执行且不重复修改", () => { + const patched = patchSource(fixture()); + const repeated = patchSource(patched.source); - assert.ok(result.source.includes(HOME_STATE_MARKER)); - assert.deepEqual(clickFeatureHome(result.source, "apikey", { - currentPath: "/", - currentState: { sidebarThreadLocationId: "chats" }, - }), { - navigations: [], - restores: [], - }); + assert.equal(repeated.status, "already-patched"); + assert.equal(repeated.source, patched.source); + assert.equal(repeated.source.split(MARKER).length - 1, 1); + assert.equal(repeated.source.split(HOME_CURRENT_MARKER).length - 1, 1); }); -test("ChatGPT 重选功能导航栏首页时保持官方直达行为", () => { - const result = patchSource(fixture()); +test("只有写入端改动的不完整补丁会被拒绝", () => { + const incomplete = fixture().replace("a&&o&&", + `(a&&o||${MARKER}i===\`apikey\`)&&`); + const result = patchSource(incomplete); - assert.deepEqual(clickFeatureHome(result.source, "chatgpt"), { - navigations: ["/"], - restores: [], - }); + assert.equal(result.status, "unexpected-shape"); + assert.match(result.reason, /只完成了一部分/); }); -test("ChatGPT 重选功能导航栏首页时不获得 API-key 状态会话短路", () => { - const result = patchSource(fixture()); +test("公共恢复条件缺失 home 限定时会被拒绝", () => { + const patched = patchSource(fixture()); + const incomplete = patched.source.replace("&&r===`home`", ""); + const result = patchSource(incomplete); - assert.deepEqual(clickFeatureHome(result.source, "chatgpt", { - currentPath: "/", - currentState: { sidebarThreadLocationId: "chats" }, - }), { - navigations: ["/"], - restores: [], - }); + assert.equal(result.status, "unexpected-shape"); + assert.match(result.reason, /当前位置逻辑不完整/); }); -test("旧版缺少状态会话判断的首页补丁会被拒绝", () => { +test("没有本项目标记的同形逻辑会被拒绝", () => { const patched = patchSource(fixture()); - const incomplete = patched.source - .replace("&&(u.pathname===`/`||homeArea(u)===`home`)", "") - .replace(new RegExp(`if\\(\\/\\* Codex:API-key 首页保持状态会话。 \\*\\/[\\s\\S]*?return;`), ""); - const result = patchSource(incomplete); + const unmarked = patched.source.replace(HOME_CURRENT_MARKER, ""); + const result = patchSource(unmarked); assert.equal(result.status, "unexpected-shape"); - assert.match(result.reason, /保持逻辑不完整/); + assert.match(result.reason, /缺少本项目标记/); }); -test("ChatGPT 登录继续遵守官方 capability 与账户条件", () => { - const result = patchSource(fixture()); +for (const marker of LEGACY_MARKERS) { + test(`检测并拒绝旧入口级补丁:${marker}`, () => { + const source = fixture().replace("function Rail", `${marker}function Rail`); + const result = patchSource(source); - assert.equal(load(result.source, { accountId: "account-1", authMethod: "chatgpt" }, true), "chatgpt:account-1"); - assert.equal(load(result.source, { accountId: "account-1", authMethod: "chatgpt" }, false), null); - assert.equal(load(result.source, { accountId: "account-1", authMethod: "chatgpt" }, true, "legacy"), null); - assert.equal(load(result.source, { accountId: null, authMethod: "chatgpt" }, true), "auth:chatgpt"); -}); + assert.equal(result.status, "unexpected-shape"); + assert.match(result.reason, /旧入口级首页补丁/); + assert.equal(result.source, source); + }); +} -test("旧版只绕过 capability 的不完整补丁会被拒绝", () => { - const incomplete = fixture().replace( - "a&&o&&", - `a&&(o||${MARKER}i===\`apikey\`)&&`, - ); - const result = patchSource(incomplete); +test("ChatGPT 登录继续遵守官方 capability 与账户条件", () => { + const result = patchSource(fixture()); - assert.equal(result.status, "unexpected-shape"); - assert.match(result.reason, /导航模式与 ChatGPT capability/); + assert.equal(loadTracker(result.source, + { accountId: "account-1", authMethod: "chatgpt" }, true), "chatgpt:account-1"); + assert.equal(loadTracker(result.source, + { accountId: "account-1", authMethod: "chatgpt" }, false), null); + assert.equal(loadTracker(result.source, + { accountId: "account-1", authMethod: "chatgpt" }, true, "legacy"), null); }); -test("未认证及其他认证方式不会因补丁越过 capability", () => { +test("未认证及其他认证方式不会因写入补丁越过 capability", () => { const result = patchSource(fixture()); - assert.equal(load(result.source, { accountId: null, authMethod: null }, false), null); - assert.equal(load(result.source, { accountId: null, authMethod: "chatgptAuthTokens" }, false), null); - assert.equal(load(result.source, { accountId: null, authMethod: "chatgptAuthTokens" }, true), "auth:chatgptAuthTokens"); + assert.equal(loadTracker(result.source, { accountId: null, authMethod: null }, false), null); + assert.equal(loadTracker(result.source, + { accountId: null, authMethod: "chatgptAuthTokens" }, false), null); + assert.equal(loadTracker(result.source, + { accountId: null, authMethod: "chatgptAuthTokens" }, true), "auth:chatgptAuthTokens"); }); -test("导航跟踪器不唯一时明确失败", () => { - const source = fixture() + fixture() - .replaceAll("Lhc", "Mhc").replaceAll("Sti", "Tti") - .replaceAll("wti", "xti").replaceAll("Pjo", "Qjo") - .replaceAll("Rail", "Sail").replaceAll("homeArea", "awayArea"); +test("首页导航目标不唯一时明确失败", () => { + const duplicate = fixture().replaceAll("Track", "Track2") + .replaceAll("restore", "restore2").replaceAll("Rail", "Rail2"); + const source = fixture() + duplicate; const result = patchSource(source); assert.equal(result.status, "unexpected-shape"); - assert.match(result.reason, /首页导航跟踪器.*2/); + assert.match(result.reason, /首页导航跟踪器.*2|公共首页恢复当前位置分支.*2/); assert.equal(result.source, source); }); From 84e7e5c7be9b81b56b6017493225c820268f33f0 Mon Sep 17 00:00:00 2001 From: carptopus Date: Sun, 18 Oct 2026 19:21:46 +0800 Subject: [PATCH 20/51] fix: isolate remote control by app server auth --- scripts/patch-remote-control.js | 158 ++++++++++++++++++++------- scripts/patch-remote-control.test.js | 17 ++- 2 files changed, 133 insertions(+), 42 deletions(-) diff --git a/scripts/patch-remote-control.js b/scripts/patch-remote-control.js index 871fdfa5..f2ec2d05 100644 --- a/scripts/patch-remote-control.js +++ b/scripts/patch-remote-control.js @@ -2,9 +2,9 @@ /** * 将 Remote Control 的本地状态同步限制在真实 ChatGPT 认证下。 * - * 上游同步组件会在应用启动时无条件读取 local_remote_control_enabled;旧版 - * 本项目曾强开 Remote Control gate,因此可能留下 true。API-key Provider - * 无法建立该连接,继续同步会反复触发 remoteControl/enable 和认证失败。 + * 上游本地状态同步组件和 gate bridge 会分别触发 Remote Control 状态更新; + * 旧版本项目还曾强开相关 gate,因此可能留下 true。API-key Provider 无法 + * 建立该连接,任一入口继续发送 enable 都会反复触发认证失败。 * * 本补丁不再强开任何 Remote Control / Connections gate。ChatGPT 认证保持 * 官方行为;其他认证方式清除遗留启用值,并向当前 app-server 发送一次 @@ -19,6 +19,7 @@ const { relPath, SRC_DIR } = require("./patch-util"); const PLATFORMS = ["mac-arm64", "mac-x64", "win"]; const STORAGE_KEY = "local_remote_control_enabled"; const MARKER = "/* CodexRebuildRemoteControlAuthIsolation */"; +const GATE_MARKER = "/* CodexRebuildRemoteControlGateAuthIsolation */"; function propertyName(member) { if (member?.type !== "MemberExpression") return null; @@ -117,62 +118,136 @@ function findRemoteSync(allFunctions, source) { }; } -function findHostAuth(allFunctions, source) { +function findCurrentAuth(allFunctions, source) { const candidates = []; for (const fn of allFunctions) { const text = source.slice(fn.start, fn.end); - if (!["serviceTierAccess", "authMethod", "hostId", "isLoading"] + if (!["accountLoading", "authLoading", "authMethod", "authenticatedAccountId", + "hasChatGptToken", "requiresAuth", "supportedSurface"] .every((value) => text.includes(value))) continue; - const declarations = descendants(fn, (node) => node.type === "VariableDeclarator", { - skipNestedFunctions: true, + const assignments = descendants(fn, (node) => + node.type === "AssignmentExpression" && node.operator === "=" && + node.left?.type === "Identifier" && node.right?.type === "CallExpression"); + const account = assignments.filter((node) => { + if (node.left.name === fn.id.name) return false; + const assignmentText = source.slice(node.start, node.end); + return ["accountLoading", "authLoading", "authMethod", "authenticatedAccountId", + "hasChatGptToken", "requiresAuth", "supportedSurface"] + .every((value) => assignmentText.includes(value)); }); - for (const host of declarations) { - if (host.id?.type !== "Identifier" || host.init?.type !== "CallExpression" || - host.init.callee.type !== "Identifier" || host.init.arguments.length !== 1 || - host.init.arguments[0].type !== "Identifier") continue; - const selected = declarations.find((node) => - node.id?.type === "Identifier" && node.init?.type === "LogicalExpression" && - node.init.operator === "??" && node.init.right?.type === "Identifier" && - node.init.right.name === host.id.name); - if (selected == null) continue; - const auth = declarations.find((node) => - node.id?.type === "Identifier" && node.init?.type === "CallExpression" && - node.init.callee.type === "Identifier" && node.init.arguments.length === 1 && - node.init.arguments[0]?.type === "Identifier" && - node.init.arguments[0].name === selected.id.name && - text.includes(`${node.id.name}?.authMethod`)); - if (auth == null) continue; - candidates.push({ - fn, - hostHook: host.init.callee.name, - defaultHost: host.init.arguments[0].name, - authHook: auth.init.callee.name, - }); + if (account.length !== 1) continue; + const assigned = new Set(assignments.map((node) => node.left.name)); + const hooks = new Set(); + for (const hookFn of allFunctions) { + const statements = hookFn.body?.body; + if (statements?.length !== 1 || statements[0].type !== "ReturnStatement") continue; + const call = statements[0].argument; + if (call?.type !== "CallExpression" || call.callee?.type !== "Identifier" || + call.arguments.length !== 1 || call.arguments[0]?.type !== "Identifier" || + !assigned.has(call.arguments[0].name)) continue; + hooks.add(call.callee.name); } + if (hooks.size !== 1) continue; + candidates.push({ + initializer: fn, + atom: account[0].left.name, + hook: [...hooks][0], + }); } if (candidates.length !== 1) { - throw new Error(`当前 Host 认证 Hook 数量异常(${candidates.length})`); + throw new Error(`当前 App Server 认证状态数量异常(${candidates.length})`); } return candidates[0]; } +function findGateBridge(allFunctions, source) { + const candidates = allFunctions.filter((node) => { + const text = source.slice(node.start, node.end); + return text.includes("set-remote-control-connections-enabled") && + text.includes("remote-connections/gate-bridge") && text.includes("1042620455"); + }); + if (candidates.length !== 1) { + throw new Error(`Remote Control gate bridge 数量异常(${candidates.length})`); + } + const fn = candidates[0]; + const declarations = descendants(fn, (node) => node.type === "VariableDeclarator", { + skipNestedFunctions: true, + }); + const gateState = declarations.filter((node) => { + if (node.id?.type !== "ObjectPattern" || node.init?.type !== "CallExpression" || + node.init.callee?.type !== "Identifier") return false; + const properties = new Map(node.id.properties.map((property) => [ + property.key?.name ?? literal(property.key), + property.value?.name, + ])); + return properties.has("checkGate") && properties.has("isLoading"); + }); + if (gateState.length !== 1) throw new Error("Remote Control gate 状态 Hook 结构异常"); + const gateProperties = new Map(gateState[0].id.properties.map((property) => [ + property.key?.name ?? literal(property.key), + property.value?.name, + ])); + const checkGate = gateProperties.get("checkGate"); + const gateLoading = gateProperties.get("isLoading"); + const gateCalls = descendants(fn, (node) => + node.type === "CallExpression" && node.callee?.type === "Identifier" && + node.callee.name === checkGate, { + skipNestedFunctions: true, + }); + const remoteGate = gateCalls.filter((node) => + node.arguments.some((argument) => literal(argument) === "1042620455")); + const oneToOneGate = gateCalls.filter((node) => + node.arguments.length === 1 && node.arguments[0]?.type === "Identifier"); + if (remoteGate.length !== 1 || oneToOneGate.length !== 1) { + throw new Error("Remote Control gate 调用结构异常"); + } + const catches = descendants(fn, (node) => + node.type === "CallExpression" && propertyName(node.callee) === "catch" && + node.callee.object?.type === "CallExpression" && + node.callee.object.arguments.some((argument) => + literal(argument) === "set-remote-control-connections-enabled")); + if (catches.length !== 1 || catches[0].callee.object.callee?.type !== "Identifier" || + catches[0].arguments.length !== 1) { + throw new Error("Remote Control gate bridge IPC 结构异常"); + } + const effects = descendants(fn, (node) => + node.type === "CallExpression" && propertyName(memberCallee(node)) === "useEffect"); + const effectCallee = effects.length === 1 ? memberCallee(effects[0]) : null; + if (effectCallee?.object.type !== "Identifier") { + throw new Error("Remote Control gate bridge useEffect 结构异常"); + } + return { + fn, + gateHook: gateState[0].init.callee.name, + checkGate, + gateLoading, + oneToOneGate: oneToOneGate[0].arguments[0].name, + ipc: catches[0].callee.object.callee.name, + catchHandler: source.slice(catches[0].arguments[0].start, catches[0].arguments[0].end), + react: effectCallee.object.name, + }; +} + function count(source, value) { return source.split(value).length - 1; } function validatePatchedSource(source) { if (count(source, MARKER) !== 1) throw new Error(`${MARKER} 数量异常`); + if (count(source, GATE_MARKER) !== 1) throw new Error(`${GATE_MARKER} 数量异常`); if (source.includes("codex-remote-gate:")) throw new Error("仍存在强制开启 Remote Control gate 的旧标记"); - if (!source.includes("__codexRemoteAuth?.authMethod!==`chatgpt`") || + if (!source.includes("__codexRemoteAccount?.authMethod!==`chatgpt`") || !source.includes("__codexSetRemoteEnabled(!1)") || - !source.includes("__codexRemoteAuth?.isLoading")) { + !source.includes("__codexRemoteAccount?.authLoading") || + !source.includes("__codexRemoteGateAccount?.authMethod===`chatgpt`") || + !source.includes("__codexRemoteGateAccount?.authLoading")) { throw new Error("Remote Control 认证隔离或遗留状态清理不完整"); } parse(source, { ecmaVersion: "latest", sourceType: "module" }); } function patchSource(source) { - if (source.includes(MARKER)) { + if (source.includes(MARKER) || source.includes(GATE_MARKER)) { try { validatePatchedSource(source); return { status: "already-patched", source }; @@ -196,16 +271,25 @@ function patchSource(source) { const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); const allFunctions = functions(ast); const remote = findRemoteSync(allFunctions, source); - const hostAuth = findHostAuth(allFunctions, source); + const currentAuth = findCurrentAuth(allFunctions, source); + const gate = findGateBridge(allFunctions, source); const remoteInitializer = nextInitializer(allFunctions, remote.fn, source); - const hostInitializer = nextInitializer(allFunctions, hostAuth.fn, source); - const replacement = `function ${remote.fn.id.name}(){let ${remote.container}=${remote.containerExpression},[${remote.storedValue},__codexSetRemoteEnabled]=${remote.storageHook}(\`${STORAGE_KEY}\`),__codexRemoteHostId=${hostAuth.hostHook}(${hostAuth.defaultHost}),__codexRemoteAuth=${hostAuth.authHook}(__codexRemoteHostId);${remote.react}.useEffect(()=>{if(__codexRemoteAuth?.isLoading)return;if(__codexRemoteAuth?.authMethod!==\`chatgpt\`){${remote.storedValue}===!0&&__codexSetRemoteEnabled(!1),${remote.syncFunction}(${remote.container},!1).catch(${remote.catchHandler});return}${remote.storedValue}!=null&&${remote.syncFunction}(${remote.container},${remote.storedValue}).catch(${remote.catchHandler})},[__codexRemoteAuth?.authMethod,__codexRemoteAuth?.isLoading,${remote.storedValue},__codexSetRemoteEnabled,${remote.container}]);return null}${MARKER}`; + const gateInitializer = nextInitializer(allFunctions, gate.fn, source); + const replacement = `function ${remote.fn.id.name}(){let ${remote.container}=${remote.containerExpression},[${remote.storedValue},__codexSetRemoteEnabled]=${remote.storageHook}(\`${STORAGE_KEY}\`),__codexRemoteAccount=${currentAuth.hook}(${currentAuth.atom});${remote.react}.useEffect(()=>{if(__codexRemoteAccount?.authLoading)return;if(__codexRemoteAccount?.authMethod!==\`chatgpt\`){${remote.storedValue}===!0&&__codexSetRemoteEnabled(!1),${remote.syncFunction}(${remote.container},!1).catch(${remote.catchHandler});return}${remote.storedValue}!=null&&${remote.syncFunction}(${remote.container},${remote.storedValue}).catch(${remote.catchHandler})},[__codexRemoteAccount?.authMethod,__codexRemoteAccount?.authLoading,${remote.storedValue},__codexSetRemoteEnabled,${remote.container}]);return null}${MARKER}`; + const gateReplacement = `function ${gate.fn.id.name}(){let{checkGate:${gate.checkGate},isLoading:${gate.gateLoading}}=${gate.gateHook}(),__codexRemoteGateAccount=${currentAuth.hook}(${currentAuth.atom}),i=__codexRemoteGateAccount?.authMethod===\`chatgpt\`&&${gate.checkGate}(${gate.oneToOneGate}),o=__codexRemoteGateAccount?.authMethod===\`chatgpt\`&&(${gate.checkGate}(\`1042620455\`)||i);${gate.react}.useEffect(()=>{if(${gate.gateLoading}||__codexRemoteGateAccount?.authLoading)return;${gate.ipc}(\`set-remote-control-connections-enabled\`,{params:{enabled:o,oneToOnePairingInAppEnabled:i}}).catch(${gate.catchHandler})},[${gate.gateLoading},i,o,__codexRemoteGateAccount?.authLoading,__codexRemoteGateAccount?.authMethod]);return null}${GATE_MARKER}`; + const currentAuthInit = `${currentAuth.initializer.id.name}(),`; const edits = [ { start: remote.fn.start, end: remote.fn.end, replacement }, + { start: gate.fn.start, end: gate.fn.end, replacement: gateReplacement }, { start: remoteInitializer.body.start + 1, end: remoteInitializer.body.start + 1, - replacement: `${hostInitializer.function.id.name}(),`, + replacement: currentAuthInit, + }, + { + start: gateInitializer.body.start + 1, + end: gateInitializer.body.start + 1, + replacement: currentAuthInit, }, ].sort((a, b) => b.start - a.start); let next = source; diff --git a/scripts/patch-remote-control.test.js b/scripts/patch-remote-control.test.js index 55f2d933..0b15ae29 100644 --- a/scripts/patch-remote-control.test.js +++ b/scripts/patch-remote-control.test.js @@ -8,9 +8,12 @@ function fixture() { "function remoteSync(){let e=(0,cache.c)(4),t=get(Container),[n]=shared(`local_remote_control_enabled`),r,i;return e[0]!==n||e[1]!==t?(r=()=>{n!=null&&sync(t,n).catch(e=>{handle(t,e),log.error(`Failed to sync local remote control enablement`,{error:e})})},i=[n,t],e[0]=n,e[1]=t,e[2]=r,e[3]=i):(r=e[2],i=e[3]),react.useEffect(r,i),null}", "var cache,react;", "function remoteInit(){return(remoteInit=once((()=>{cache=compiled(),base(),react=reactModule(),sharedInit(),syncInit()})))()}", - "function serviceTier(e){let t=(0,serviceCache.c)(10),n=useAtom(defaultHost),r=e?.hostId??n,i=useHostAuth(r),a=i?.authMethod===`chatgpt`||i?.authMethod===`personalAccessToken`,o=i?.authMethod??null,s={authMethod:o,hostId:r},c={serviceTierAccess:a,isLoading:!!i?.isLoading};return c}", - "var serviceCache;", - "function serviceInit(){return(serviceInit=once((()=>{serviceCache=compiled(),atomInit(),hostInit(),authInit()})))()}", + "function currentAccess(){return useAtom(accountAccess)}", + "var accountAtom,accountAccess;", + "function accountInit(){return(accountInit=once((()=>{accountAtom=atom(Store,()=>({accountId:null,accountLoading:!0,authLoading:!0,authMethod:null,authenticatedAccountId:null,hasChatGptToken:void 0,requiresAuth:!0,supportedSurface:null})),accountAccess=selector(Store,({get:e})=>e(accountAtom).authMethod)})))()}", + "function gateBridge(){let e=(0,gateCache.c)(10),{checkGate:t,isLoading:n}=useGates(),r;e[0]===t?r=e[1]:(r=t(oneToOneGate),e[0]=t,e[1]=r);let i=r,a;e[2]!==t||e[3]!==i?(a=t(`1042620455`)||i,e[2]=t,e[3]=i,e[4]=a):a=e[4];let o=a,s,c;return e[5]!==n||e[6]!==i||e[7]!==o?(s=()=>{n||ipc(`set-remote-control-connections-enabled`,{params:{enabled:o,oneToOnePairingInAppEnabled:i}}).catch(e=>{log.warning(`[remote-connections/gate-bridge] sync_failed`,{error:e})})},c=[n,i,o],e[5]=n,e[6]=i,e[7]=o,e[8]=s,e[9]=c):(s=e[8],c=e[9]),react.useEffect(s,c),null}", + "var gateCache;", + "function gateInit(){return(gateInit=once((()=>{gateCache=compiled(),gateDeps()})))()}", ].join(""); } @@ -19,10 +22,14 @@ test("API-key 清除旧启用值并禁用 Remote Control,ChatGPT 保留官方 assert.equal(result.status, "patched", result.reason); validatePatchedSource(result.source); assert.equal(result.source.split(MARKER).length - 1, 1); - assert.match(result.source, /__codexRemoteAuth\?\.authMethod!==`chatgpt`/); + assert.match(result.source, /__codexRemoteAccount\?\.authMethod!==`chatgpt`/); assert.match(result.source, /n===!0&&__codexSetRemoteEnabled\(!1\),sync\(t,!1\)/); assert.match(result.source, /n!=null&&sync\(t,n\)/); - assert.match(result.source, /function remoteInit\(\).*serviceInit\(\),/); + assert.match(result.source, /function remoteInit\(\).*accountInit\(\),/); + assert.match(result.source, /function gateInit\(\).*accountInit\(\),/); + assert.match(result.source, /__codexRemoteGateAccount\?\.authMethod===`chatgpt`/); + assert.match(result.source, /if\(n\|\|__codexRemoteGateAccount\?\.authLoading\)return/); + assert.match(result.source, /enabled:o,oneToOnePairingInAppEnabled:i/); assert.doesNotMatch(result.source, /codex-remote-gate:/); }); From 0cb6b71c49a137a9b5c3d1e38ffc8b231eb127c6 Mon Sep 17 00:00:00 2001 From: carptopus Date: Sun, 18 Oct 2026 19:32:59 +0800 Subject: [PATCH 21/51] test: update remote control bundle smoke --- scripts/frontend-source-smoke.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index e896adfd..98c5e47c 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -106,8 +106,11 @@ function verifyFrontendSource(assets) { && fs.readFileSync(path.join(assets, name), "utf8").includes("CodexRebuildRemoteControlAuthIsolation")); assert.equal(remoteControlEntries.length, 1); const remoteControlSource = fs.readFileSync(path.join(assets, remoteControlEntries[0]), "utf8"); - assert.match(remoteControlSource, /__codexRemoteAuth\?\.authMethod!==`chatgpt`/); + assert.match(remoteControlSource, /__codexRemoteAccount\?\.authMethod!==`chatgpt`/); assert.match(remoteControlSource, /__codexSetRemoteEnabled\(!1\)/); + assert.match(remoteControlSource, /CodexRebuildRemoteControlGateAuthIsolation/); + assert.match(remoteControlSource, /__codexRemoteGateAccount\?\.authMethod===`chatgpt`/); + assert.match(remoteControlSource, /__codexRemoteGateAccount\?\.authLoading/); assert.doesNotMatch(remoteControlSource, /codex-remote-gate:/); const serviceTierEntries = files.filter(name => /^app-initial-/.test(name) && fs.readFileSync(path.join(assets, name), "utf8").includes("CodexRebuildServiceTierApiKeyRequest")); From 877620afee13275db8628411496cfc5e83e295a4 Mon Sep 17 00:00:00 2001 From: zhangbohun Date: Sun, 18 Oct 2026 21:38:54 +0800 Subject: [PATCH 22/51] fix: preserve API key home thread state --- scripts/frontend-source-smoke.js | 2 + scripts/patch-api-key-home-navigation.js | 128 ++++++++++++++++-- scripts/patch-api-key-home-navigation.test.js | 68 ++++++++-- 3 files changed, 179 insertions(+), 19 deletions(-) diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index 98c5e47c..8b6d1a14 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -83,6 +83,8 @@ function verifyFrontendSource(assets) { assert.match(navigationSource, /\|\|\/\* Codex:API-key 首页恢复写入。 \*\/[A-Za-z_$][\w$]*===`apikey`/); assert.match(navigationSource, /\([A-Za-z_$][\w$]*\|\|\/\* Codex:API-key 首页保持当前位置。 \*\/[A-Za-z_$][\w$]*===`auth:apikey`&&[A-Za-z_$][\w$]*===`home`\)&&[A-Za-z_$][\w$]*!=null/); + assert.match(navigationSource, + /&&\([A-Za-z_$][\w$]*\([^)]*\)===[A-Za-z_$][\w$]*\|\|\/\* Codex:API-key 首页保持当前。 \*\/[A-Za-z_$][\w$]*\.state\?\.sidebarThreadLocationId!=null\)/); assert.doesNotMatch(navigationSource, /Codex:API-key 当前首页保持会话/); assert.doesNotMatch(navigationSource, /Codex:API-key 首页保持状态会话/); assert.doesNotMatch(navigationSource, /Codex:API-key 首页恢复最近会话/); diff --git a/scripts/patch-api-key-home-navigation.js b/scripts/patch-api-key-home-navigation.js index 7d75f4b5..be6fd78e 100644 --- a/scripts/patch-api-key-home-navigation.js +++ b/scripts/patch-api-key-home-navigation.js @@ -18,6 +18,7 @@ const { SRC_DIR, relPath } = require("./patch-util"); const MARKER = "/* Codex:API-key 首页恢复写入。 */"; const HOME_CURRENT_MARKER = "/* Codex:API-key 首页保持当前位置。 */"; +const HOME_STATE_MARKER = "/* Codex:API-key 首页保持当前。 */"; const LEGACY_MARKERS = [ "/* Codex:API-key 当前首页保持会话。 */", "/* Codex:API-key 首页恢复最近会话。 */", @@ -165,6 +166,87 @@ function isApiKeyHomeGate(node, capability, accountKey, area) { conditions.some(item => comparison(item, area, "home")); } +function currentHomeMatch(node, current, area) { + if (node?.type !== "BinaryExpression" || !["===", "=="].includes(node.operator)) return null; + const left = node.left; + if (left?.type !== "CallExpression" || left.arguments.length !== 2 || + left.callee?.type !== "Identifier" || left.arguments[1]?.type !== "Identifier" || + left.arguments[1].name !== current || node.right?.type !== "Identifier" || + node.right.name !== area) return null; + return left.callee.name; +} + +function sidebarThreadMember(node, current) { + const member = node?.type === "ChainExpression" ? node.expression : node; + return member?.type === "MemberExpression" && member.optional === true && + member.object?.type === "MemberExpression" && member.object.optional !== true && + member.object.object?.type === "Identifier" && member.object.object.name === current && + member.object.property?.type === "Identifier" && member.object.property.name === "state" && + member.property?.type === "Identifier" && member.property.name === "sidebarThreadLocationId" + ? member : null; +} + +function isSidebarThreadLocationMember(node, current) { + return sidebarThreadMember(node, current) != null; +} + +function sidebarThreadLocationPresence(node, current) { + if (node?.type !== "BinaryExpression" || !["!=", "!=="].includes(node.operator)) return null; + return isSidebarThreadLocationMember(node.left, current) && literal(node.right) === null ? node : null; +} + +function currentHomeDirect(node, current, area) { + const classifier = currentHomeMatch(node, current, area); + return classifier == null ? null : { classifier, home: node, state: null }; +} + +function findCurrentHomeCheck(fn, current, area, source) { + const candidates = []; + // 当前首页判断所在分支的文本范围用于核对 marker;结构判定仍只认官方条件本身。 + const branchRange = nodes(fn, + item => item.type === "IfStatement" && item.consequent.type === "ReturnStatement" && + item.test?.type === "LogicalExpression" && item.test.operator === "&&", + { ownScope: true }) + .map(item => item.test) + .find(item => nodes(item, node => currentHomeDirect(node, current, area) != null).length >= 1) ?? null; + const orExpressions = nodes(fn, + item => item.type === "LogicalExpression" && item.operator === "||", + { ownScope: true }); + for (const node of nodes(fn, item => item.type === "BinaryExpression" && + ["===", "=="].includes(item.operator), { ownScope: true })) { + const direct = currentHomeDirect(node, current, area); + if (direct == null) continue; + const alternatives = orExpressions + .filter(item => item.start <= node.start && item.end >= node.end) + .map(item => ({ item, parts: logicalOperands(item, "||") })) + .filter(({ parts }) => parts.length === 2 && parts.includes(node)) + .map(({ item, parts }) => { + const state = parts.find(part => part !== node); + return sidebarThreadLocationPresence(state, current) == null + ? null : { item, state }; + }) + .filter(Boolean) + .sort((left, right) => left.item.end - left.item.start - (right.item.end - right.item.start)); + const alternative = alternatives[0] ?? null; + // 无状态条件时扫描整个分支,避免残留 marker 被误判为已完成。 + const patchedRange = alternative?.item ?? node; + const markerRange = branchRange == null ? patchedRange : { + start: Math.min(patchedRange.start, branchRange.start), + end: Math.max(patchedRange.end, branchRange.end), + }; + const markerPresent = source.slice(markerRange.start, markerRange.end).includes(HOME_STATE_MARKER); + const statePatched = alternative?.state != null && markerPresent; + candidates.push({ + ...direct, + state: statePatched ? alternative.state : null, + node: patchedRange, + markerPresent, + }); + } + if (candidates.length !== 1) throw new Error(`首页当前位置判定 数量异常(${candidates.length})`); + return candidates[0]; +} + function findHomeRestore(ast, source) { const candidates = []; for (const fn of ast.body.filter(node => node.type === "FunctionDeclaration")) { @@ -205,14 +287,21 @@ function findHomeRestore(ast, source) { node.init?.type === "CallExpression" && memberName(node.init.callee) === "get" && memberRoot(node.init.callee) === store); if (capabilityDeclarations.length !== 1) continue; + let currentHome; + try { + currentHome = findCurrentHomeCheck(fn, current, bindings.area, source); + } catch { + continue; + } candidates.push({ accountKey: bindings.accountKey, area: bindings.area, capability, current, + currentHome, gate, - markerPresent: source.slice(gate.start, gate.end).includes(HOME_CURRENT_MARKER), + markerPresent: currentHome.markerPresent, }); } } @@ -257,41 +346,61 @@ function patchSource(source) { } const trackerPatched = isApiKeyOverride(tracker.gate, tracker.authMethod); - const homePatched = isApiKeyHomeGate(homeRestore.gate, homeRestore.capability, + const gatePatched = isApiKeyHomeGate(homeRestore.gate, homeRestore.capability, homeRestore.accountKey, homeRestore.area); + const currentHomePatched = homeRestore.currentHome.state != null; if (trackerPatched && !source.slice(tracker.gate.start, tracker.gate.end).includes(MARKER)) { throw new Error("API-key 放行逻辑存在但缺少本项目标记"); } - if (homePatched && !homeRestore.markerPresent) { + if (gatePatched && !source.slice(homeRestore.gate.start, homeRestore.gate.end) + .includes(HOME_CURRENT_MARKER)) { + throw new Error("API-key 首页放行逻辑存在但缺少本项目标记"); + } + if (currentHomePatched && !homeRestore.currentHome.markerPresent) { throw new Error("API-key 首页当前位置逻辑存在但缺少本项目标记"); } + if (!currentHomePatched && homeRestore.currentHome.markerPresent) { + throw new Error("API-key 首页当前状态逻辑不完整"); + } if (!trackerPatched && (source.includes(MARKER) || tracker.gate.type !== "LogicalExpression" || tracker.gate.operator !== "&&" || tracker.gate.left?.type !== "Identifier" || tracker.gate.right?.type !== "Identifier")) { throw new Error("导航模式与 ChatGPT capability 条件结构未知"); } - if (!homePatched && (source.includes(HOME_CURRENT_MARKER) || + if (!gatePatched && (source.includes(HOME_CURRENT_MARKER) || homeRestore.gate.type !== "Identifier")) { throw new Error("公共首页恢复当前位置逻辑不完整"); } - if (trackerPatched !== homePatched) { - throw new Error("API-key 首页补丁只完成了一部分"); + if (!currentHomePatched && source.includes(HOME_STATE_MARKER)) { + throw new Error("API-key 首页当前状态逻辑不完整"); + } + if (trackerPatched && gatePatched && currentHomePatched) { + return { status: "already-patched", source }; } - if (trackerPatched) return { status: "already-patched", source }; const originalTrackerGate = source.slice(tracker.gate.start, tracker.gate.end); + const home = homeRestore.currentHome; const next = applyEdits(source, [ { start: tracker.gate.start, end: tracker.gate.end, - replacement: `(${originalTrackerGate}||${MARKER}${tracker.authMethod}===\`apikey\`)`, + replacement: trackerPatched ? originalTrackerGate : + `(${originalTrackerGate}||${MARKER}${tracker.authMethod}===\`apikey\`)`, }, { start: homeRestore.gate.start, end: homeRestore.gate.end, - replacement: `(${homeRestore.capability}||${HOME_CURRENT_MARKER}` + + replacement: gatePatched ? source.slice(homeRestore.gate.start, homeRestore.gate.end) : + `(${homeRestore.capability}||${HOME_CURRENT_MARKER}` + `${homeRestore.accountKey}===\`auth:apikey\`&&${homeRestore.area}===\`home\`)`, }, + { + start: home.node.start, + end: home.node.end, + replacement: currentHomePatched ? source.slice(home.node.start, home.node.end) : + `(${source.slice(home.home.start, home.home.end)}||` + + `${HOME_STATE_MARKER}${homeRestore.current}.state?.sidebarThreadLocationId!=null)`, + }, ]); return { status: "patched", source: next }; } catch (error) { @@ -352,6 +461,7 @@ function main() { if (require.main === module) main(); module.exports = { HOME_CURRENT_MARKER, + HOME_STATE_MARKER, LEGACY_MARKERS, MARKER, patchSource, diff --git a/scripts/patch-api-key-home-navigation.test.js b/scripts/patch-api-key-home-navigation.test.js index a1111f10..48dc0348 100644 --- a/scripts/patch-api-key-home-navigation.test.js +++ b/scripts/patch-api-key-home-navigation.test.js @@ -3,6 +3,7 @@ const assert = require("node:assert/strict"); const { HOME_CURRENT_MARKER, + HOME_STATE_MARKER, LEGACY_MARKERS, MARKER, patchSource, @@ -43,6 +44,7 @@ function clickHome(source, { accountKey = "auth:apikey", capability = false, currentArea = "home", + sidebarThreadLocationId = "chats", rememberedArea = "home", rememberedDepartedAt = 1, rememberedPath = "/thread/remembered", @@ -50,9 +52,9 @@ function clickHome(source, { } = {}) { const navigations = []; const current = currentArea == null ? null : { - area: currentArea, + area: currentArea === "home" ? null : currentArea, hash: `same`, - state: { sidebarProductMode: "codex" }, + state: { sidebarProductMode: "codex", sidebarThreadLocationId }, }; const rememberedValue = hasRemembered ? { departedAt: rememberedDepartedAt, @@ -99,21 +101,43 @@ test("builtin:home 通过公共恢复函数保持 API-key 当前首页会话", ( assert.equal(result.status, "patched"); assert.ok(result.source.includes("builtin:home")); assert.ok(result.source.includes(HOME_CURRENT_MARKER)); + assert.ok(result.source.includes(HOME_STATE_MARKER)); assert.match(result.source, - /\(s\|\|\/\* Codex:API-key 首页保持当前位置。 \*\/t===`auth:apikey`&&r===`home`\)&&c!=null/); + /same\(c,r\)\.hash===c\.hash&&\(areaOf\(e,c\)===r\|\|\/\* Codex:API-key 首页保持当前。 \*\/c\.state\?\.sidebarThreadLocationId!=null\)/); assert.deepEqual(clickHome(result.source), []); }); +test("API-key 当前会话位于真实空首页分类时仍保持当前位置", () => { + const result = patchSource(fixture()); + + assert.deepEqual(clickHome(result.source, { + currentArea: "home", + sidebarThreadLocationId: "chats", + }), []); + assert.deepEqual(clickHome(result.source, { + currentArea: "home", + sidebarThreadLocationId: null, + rememberedDepartedAt: null, + }), ["/"]); +}); + test("API-key 从设置页进入首页时恢复已记录的会话", () => { const result = patchSource(fixture()); - assert.deepEqual(clickHome(result.source, { currentArea: "settings" }), ["/thread/remembered"]); + assert.deepEqual(clickHome(result.source, { + currentArea: "settings", + sidebarThreadLocationId: null, + }), ["/thread/remembered"]); }); test("API-key 没有首页记录时保留官方根路由 fallback", () => { const result = patchSource(fixture()); - assert.deepEqual(clickHome(result.source, { currentArea: "settings", hasRemembered: false }), ["/"]); + assert.deepEqual(clickHome(result.source, { + currentArea: "settings", + sidebarThreadLocationId: null, + hasRemembered: false, + }), ["/"]); }); test("ChatGPT capability 可用时保持官方当前首页短路", () => { @@ -163,24 +187,48 @@ test("补丁可重复执行且不重复修改", () => { assert.equal(repeated.source, patched.source); assert.equal(repeated.source.split(MARKER).length - 1, 1); assert.equal(repeated.source.split(HOME_CURRENT_MARKER).length - 1, 1); + assert.equal(repeated.source.split(HOME_STATE_MARKER).length - 1, 1); }); -test("只有写入端改动的不完整补丁会被拒绝", () => { +test("只完成写入端的旧补丁会补齐缺少的两段", () => { const incomplete = fixture().replace("a&&o&&", `(a&&o||${MARKER}i===\`apikey\`)&&`); const result = patchSource(incomplete); - assert.equal(result.status, "unexpected-shape"); - assert.match(result.reason, /只完成了一部分/); + assert.equal(result.status, "patched"); + assert.ok(result.source.includes(HOME_CURRENT_MARKER)); + assert.ok(result.source.includes(HOME_STATE_MARKER)); + assert.match(result.source, /areaOf\(e,c\)===r\|\|\/\* Codex:API-key 首页保持当前。 \*\/c\.state\?\.sidebarThreadLocationId!=null/); +}); + +test("只完成公共放行的旧补丁会补齐缺少的两段", () => { + const incomplete = fixture().replace("if(s&&c!=null&&", + `if((s||${HOME_CURRENT_MARKER}t===\`auth:apikey\`&&r===\`home\`)&&c!=null&&`); + const result = patchSource(incomplete); + + assert.equal(result.status, "patched"); + assert.ok(result.source.includes(MARKER)); + assert.ok(result.source.includes(HOME_STATE_MARKER)); }); test("公共恢复条件缺失 home 限定时会被拒绝", () => { const patched = patchSource(fixture()); - const incomplete = patched.source.replace("&&r===`home`", ""); + const incomplete = patched.source.replace("areaOf(e,c)===r||", + "/* Codex:缺少当前位置 */"); + const result = patchSource(incomplete); + + assert.equal(result.status, "unexpected-shape"); + assert.match(result.reason, /当前位置逻辑不完整|补丁标记存在但首页导航结构未知/); +}); + +test("公共恢复条件缺少真实会话状态判据时会被拒绝", () => { + const patched = patchSource(fixture()); + const incomplete = patched.source.replace( + `||${HOME_STATE_MARKER}c.state?.sidebarThreadLocationId!=null`, HOME_STATE_MARKER); const result = patchSource(incomplete); assert.equal(result.status, "unexpected-shape"); - assert.match(result.reason, /当前位置逻辑不完整/); + assert.match(result.reason, /当前状态逻辑不完整/); }); test("没有本项目标记的同形逻辑会被拒绝", () => { From f928e3572053b6f6929b08572a8ec0877bf215e6 Mon Sep 17 00:00:00 2001 From: zhangbohun Date: Mon, 19 Oct 2026 02:28:16 +0800 Subject: [PATCH 23/51] fix: restore API key home thread from other pages --- scripts/frontend-source-smoke.js | 2 + scripts/patch-api-key-home-navigation.js | 57 ++++++++++++++++++- scripts/patch-api-key-home-navigation.test.js | 6 +- 3 files changed, 63 insertions(+), 2 deletions(-) diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index 8b6d1a14..99aec4f1 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -85,6 +85,8 @@ function verifyFrontendSource(assets) { /\([A-Za-z_$][\w$]*\|\|\/\* Codex:API-key 首页保持当前位置。 \*\/[A-Za-z_$][\w$]*===`auth:apikey`&&[A-Za-z_$][\w$]*===`home`\)&&[A-Za-z_$][\w$]*!=null/); assert.match(navigationSource, /&&\([A-Za-z_$][\w$]*\([^)]*\)===[A-Za-z_$][\w$]*\|\|\/\* Codex:API-key 首页保持当前。 \*\/[A-Za-z_$][\w$]*\.state\?\.sidebarThreadLocationId!=null\)/); + assert.match(navigationSource, + /\(\s*[A-Za-z_$][\w$]*\|\|\/\* Codex:API-key 首页从其他页面恢复会话。 \*\/[A-Za-z_$][\w$]*===`auth:apikey`&&[A-Za-z_$][\w$]*===`home`\s*\)\?/); assert.doesNotMatch(navigationSource, /Codex:API-key 当前首页保持会话/); assert.doesNotMatch(navigationSource, /Codex:API-key 首页保持状态会话/); assert.doesNotMatch(navigationSource, /Codex:API-key 首页恢复最近会话/); diff --git a/scripts/patch-api-key-home-navigation.js b/scripts/patch-api-key-home-navigation.js index be6fd78e..55c781d5 100644 --- a/scripts/patch-api-key-home-navigation.js +++ b/scripts/patch-api-key-home-navigation.js @@ -19,6 +19,7 @@ const { SRC_DIR, relPath } = require("./patch-util"); const MARKER = "/* Codex:API-key 首页恢复写入。 */"; const HOME_CURRENT_MARKER = "/* Codex:API-key 首页保持当前位置。 */"; const HOME_STATE_MARKER = "/* Codex:API-key 首页保持当前。 */"; +const HOME_RESTORE_MARKER = "/* Codex:API-key 首页从其他页面恢复会话。 */"; const LEGACY_MARKERS = [ "/* Codex:API-key 当前首页保持会话。 */", "/* Codex:API-key 首页恢复最近会话。 */", @@ -301,6 +302,7 @@ function findHomeRestore(ast, source) { current, currentHome, gate, + preparedRestore: findPreparedRestoreCheck(fn, store, capability), markerPresent: currentHome.markerPresent, }); } @@ -309,6 +311,28 @@ function findHomeRestore(ast, source) { return candidates[0] ?? null; } +function findPreparedRestoreCheck(fn, store, capability) { + const candidates = []; + for (const conditional of nodes(fn, + item => item.type === "ConditionalExpression", { ownScope: true })) { + const prepared = conditional.consequent; + const direct = conditional.alternate; + const testPatched = isApiKeyRestoreOverride(conditional.test); + if (!testPatched && + (conditional.test?.type !== "Identifier" || conditional.test.name !== capability)) continue; + if ( + prepared?.type !== "CallExpression" || + prepared.arguments[0]?.type !== "Identifier" || prepared.arguments[0].name !== store || + prepared.arguments[1]?.type !== "Identifier" || + direct?.type !== "SequenceExpression") continue; + candidates.push({ node: conditional.test }); + } + if (candidates.length !== 1) { + throw new Error(`首页完整恢复分支 数量异常(${candidates.length})`); + } + return candidates[0]; +} + function isApiKeyOverride(node, authMethod) { if (node?.type !== "LogicalExpression" || node.operator !== "||") return false; const comparisonNode = node.right; @@ -318,6 +342,20 @@ function isApiKeyOverride(node, authMethod) { literal(comparisonNode.right) === "apikey"; } +function isApiKeyRestoreOverride(node) { + if (node?.type !== "LogicalExpression" || node.operator !== "||" || + node.left?.type !== "Identifier") return false; + const conditions = logicalOperands(node.right, "&&"); + return conditions.length === 2 && + conditions.some(item => item.type === "BinaryExpression" && + ["===", "=="].includes(item.operator) && + item.left?.type === "Identifier" && + literal(item.right) === "auth:apikey") && + conditions.some(item => item.type === "BinaryExpression" && + ["===", "=="].includes(item.operator) && + literal(item.right) === "home"); +} + function patchSource(source) { const legacyMarker = LEGACY_MARKERS.find(marker => source.includes(marker)); if (legacyMarker != null) { @@ -349,6 +387,7 @@ function patchSource(source) { const gatePatched = isApiKeyHomeGate(homeRestore.gate, homeRestore.capability, homeRestore.accountKey, homeRestore.area); const currentHomePatched = homeRestore.currentHome.state != null; + const preparedRestorePatched = isApiKeyRestoreOverride(homeRestore.preparedRestore.node); if (trackerPatched && !source.slice(tracker.gate.start, tracker.gate.end).includes(MARKER)) { throw new Error("API-key 放行逻辑存在但缺少本项目标记"); } @@ -359,6 +398,10 @@ function patchSource(source) { if (currentHomePatched && !homeRestore.currentHome.markerPresent) { throw new Error("API-key 首页当前位置逻辑存在但缺少本项目标记"); } + if (preparedRestorePatched && !source.slice(homeRestore.preparedRestore.node.start, + homeRestore.preparedRestore.node.end).includes(HOME_RESTORE_MARKER)) { + throw new Error("API-key 首页完整恢复逻辑存在但缺少本项目标记"); + } if (!currentHomePatched && homeRestore.currentHome.markerPresent) { throw new Error("API-key 首页当前状态逻辑不完整"); } @@ -374,7 +417,10 @@ function patchSource(source) { if (!currentHomePatched && source.includes(HOME_STATE_MARKER)) { throw new Error("API-key 首页当前状态逻辑不完整"); } - if (trackerPatched && gatePatched && currentHomePatched) { + if (!preparedRestorePatched && source.includes(HOME_RESTORE_MARKER)) { + throw new Error("API-key 首页完整恢复逻辑不完整"); + } + if (trackerPatched && gatePatched && currentHomePatched && preparedRestorePatched) { return { status: "already-patched", source }; } @@ -401,6 +447,14 @@ function patchSource(source) { `(${source.slice(home.home.start, home.home.end)}||` + `${HOME_STATE_MARKER}${homeRestore.current}.state?.sidebarThreadLocationId!=null)`, }, + { + start: homeRestore.preparedRestore.node.start, + end: homeRestore.preparedRestore.node.end, + replacement: preparedRestorePatched ? source.slice(homeRestore.preparedRestore.node.start, + homeRestore.preparedRestore.node.end) : + `(${homeRestore.capability}||${HOME_RESTORE_MARKER}` + + `${homeRestore.accountKey}===\`auth:apikey\`&&${homeRestore.area}===\`home\`)`, + }, ]); return { status: "patched", source: next }; } catch (error) { @@ -461,6 +515,7 @@ function main() { if (require.main === module) main(); module.exports = { HOME_CURRENT_MARKER, + HOME_RESTORE_MARKER, HOME_STATE_MARKER, LEGACY_MARKERS, MARKER, diff --git a/scripts/patch-api-key-home-navigation.test.js b/scripts/patch-api-key-home-navigation.test.js index 48dc0348..797a5ab7 100644 --- a/scripts/patch-api-key-home-navigation.test.js +++ b/scripts/patch-api-key-home-navigation.test.js @@ -3,6 +3,7 @@ const assert = require("node:assert/strict"); const { HOME_CURRENT_MARKER, + HOME_RESTORE_MARKER, HOME_STATE_MARKER, LEGACY_MARKERS, MARKER, @@ -74,7 +75,8 @@ function clickHome(source, { "const auth=()=>({accountId:null,authMethod:`apikey`});const mode=()=>`current`;", "const capability=()=>false,productMode=()=>`codex`,track=()=>{};", "const remembered=()=>rememberedValue;const same=()=>({hash:`same`});", - "const areaOf=(_store,value)=>value.area;const nativeRestore=()=>true;", + "const areaOf=(_store,value)=>value.area;", + "const nativeRestore=(_store,record)=>{recordNavigation(record.location.pathname);return true};", source, "return Rail(activeStore,{accountKey,auth:{},navigate:path=>recordNavigation(path),", "productMode:`codex`,state:{}})();", @@ -102,6 +104,7 @@ test("builtin:home 通过公共恢复函数保持 API-key 当前首页会话", ( assert.ok(result.source.includes("builtin:home")); assert.ok(result.source.includes(HOME_CURRENT_MARKER)); assert.ok(result.source.includes(HOME_STATE_MARKER)); + assert.ok(result.source.includes(HOME_RESTORE_MARKER)); assert.match(result.source, /same\(c,r\)\.hash===c\.hash&&\(areaOf\(e,c\)===r\|\|\/\* Codex:API-key 首页保持当前。 \*\/c\.state\?\.sidebarThreadLocationId!=null\)/); assert.deepEqual(clickHome(result.source), []); @@ -188,6 +191,7 @@ test("补丁可重复执行且不重复修改", () => { assert.equal(repeated.source.split(MARKER).length - 1, 1); assert.equal(repeated.source.split(HOME_CURRENT_MARKER).length - 1, 1); assert.equal(repeated.source.split(HOME_STATE_MARKER).length - 1, 1); + assert.equal(repeated.source.split(HOME_RESTORE_MARKER).length - 1, 1); }); test("只完成写入端的旧补丁会补齐缺少的两段", () => { From a39d0fa2830708e3ad7be1da93714a517c9ed8da Mon Sep 17 00:00:00 2001 From: carptopus Date: Mon, 19 Oct 2026 14:52:19 +0800 Subject: [PATCH 24/51] diag: instrument home restore pipeline for api key --- scripts/patch-home-restore-diagnostics.js | 123 ++++++++++++++++++ .../patch-home-restore-diagnostics.test.js | 43 ++++++ scripts/patch-policy.js | 1 + 3 files changed, 167 insertions(+) create mode 100644 scripts/patch-home-restore-diagnostics.js create mode 100644 scripts/patch-home-restore-diagnostics.test.js diff --git a/scripts/patch-home-restore-diagnostics.js b/scripts/patch-home-restore-diagnostics.js new file mode 100644 index 00000000..f8b9cc7d --- /dev/null +++ b/scripts/patch-home-restore-diagnostics.js @@ -0,0 +1,123 @@ +#!/usr/bin/env node +/** + * 首页恢复诊断日志(临时补丁,确诊后移除)。 + * 只注入只读日志,不改变任何业务行为;锚点漂移必须失败。 + */ +const fs = require('node:fs'); +const path = require('node:path'); +const { parse } = require('acorn'); +const { relPath, SRC_DIR } = require('./patch-util'); +const MARKER = '/* CodexRebuildHomeRestoreDiag */'; +const PLATFORMS = ['mac-arm64', 'mac-x64', 'win']; +const PREFIX = '__codexHomeRestoreDiag'; +function targetDirectories(platform) { + const requested = platform ? [platform] : PLATFORMS; + return requested.map((item) => ({ + platform: item, + path: path.join(SRC_DIR, item, '_asar', 'webview', 'assets'), + })).filter((item) => fs.existsSync(item.path)); +} +function stmt(tag, expression) { return '(window.' + PREFIX + '??=[]).push({tag:' + JSON.stringify(tag) + ',at:Date.now(),data:' + expression + '});' } +function logCall(tag, expression) { + return '(window.' + PREFIX + '??=[]).push({tag:' + JSON.stringify(tag) + ',at:Date.now(),data:' + expression + '}),'; +} +function patchSource(source) { + if (source.includes(MARKER)) return { status: 'already-patched', source }; + if (!source.includes('Codex:API-key 首页恢复写入。') || + !source.includes('Codex:API-key 首页从其他页面恢复会话。')) { + return { status: 'not-applicable', source }; + } + try { + parse(source, { ecmaVersion: 'latest', sourceType: 'module' }); + let next = source; + const edits = []; + const writerAnchor = 'u=()=>{QBa(t,{accountKey:l,location:n,productMode:s})}'; + if (next.split(writerAnchor).length - 1 !== 1) throw new Error('首页写入端锚点缺失'); + edits.push({ + anchor: writerAnchor, + replacement: 'u=()=>{' + + logCall('cuu.write', '{accountKey:l,pathname:n?.pathname,state:n?.state}') + + 'QBa(t,{accountKey:l,location:n,productMode:s})}', + }); + const tVaHead='function tVa(e,{accountKey:t,auth:n,area:r,navigate:i,productMode:a,state:o}){let s=e.get(AE),c=e.get(ch);'; + if (next.split(tVaHead).length - 1 !== 1) throw new Error('tVa head anchor missing'); + edits.push({ + anchor: tVaHead, + replacement: tVaHead + stmt('tVa.enter', '{accountKey:t,area:r,current:c?.pathname,currentState:c?.state}'), + }); + + const consumerAnchor = ',gO=Y(U,({get:e})=>{let t=e(ch)?.state?.sidebarThreadLocationId;'; + if (next.split(consumerAnchor).length - 1 !== 1) throw new Error('首页消费端锚点缺失'); + edits.push({ + anchor: consumerAnchor, + replacement: ',gO=Y(U,({get:e})=>{' + + stmt('gO.read', '{pathname:e(ch)?.pathname,state:e(ch)?.state}') + + 'let t=e(ch)?.state?.sidebarThreadLocationId;', + }); + const navAnchor = 'function nVa(e,t,n){let r=e.get(eh).prepareNavigation(gc(t.location),{state:{...t.location.state,...n}});return r!=null&&'; + if (next.split(navAnchor).length - 1 !== 1) throw new Error('首页跳转端锚点缺失'); + edits.push({ + anchor: navAnchor, + replacement: 'function nVa(e,t,n){' + + stmt('nVa.enter', '{target:t.location?.pathname,mergedState:{...t.location?.state,...n}}') + + 'let r=e.get(eh).prepareNavigation(gc(t.location),{state:{...t.location.state,...n}});' + + stmt('nVa.prepared', '{prepared:r!=null}') + + 'return r!=null&&', + }); + for (const edit of edits) { + if (!next.includes(edit.anchor)) throw new Error('e1'); + next = next.replace(edit.anchor, edit.replacement); + } + if (!next.includes(MARKER)) { + const q = String.fromCharCode(34); + const boot = 'import ' + q + './codex-rebuild-reading-width.js' + q + ';'; + if (!next.includes(boot)) throw new Error('e2'); + next = next.replace(boot, boot + MARKER); + } + parse(next, { ecmaVersion: 'latest', sourceType: 'module' }); + return { status: 'patched', source: next }; + } catch (error) { + return { status: 'unexpected-shape', source, reason: error.message }; + } +} +function main() { + const args = process.argv.slice(2); + const platform = args.find((arg) => PLATFORMS.includes(arg)); + const check = args.includes('--check'); + const directories = targetDirectories(platform); + let failed = 0; + let patched = 0; + for (const directory of directories) { + try { + const results = fs.readdirSync(directory.path) + .filter((name) => /^app-initial-.*\.js$/.test(name)) + .map((name) => ({ name, path: path.join(directory.path, name) })) + .map((file) => ({ file, result: patchSource(fs.readFileSync(file.path, 'utf8')) })) + .filter((item) => item.result.status !== 'not-applicable'); + if (results.length !== 1) throw new Error('bundle-count ' + results.length); + const target = results[0]; + if (target.result.status === 'unexpected-shape') throw new Error(target.result.reason); + console.log(' [' + directory.platform + '] ' + relPath(target.file.path)); + if (target.result.status === 'already-patched') { + console.log(' [ok] already patched'); + } else if (check) { + console.log(' [ok] anchors verified; dry-run'); + } else { + fs.writeFileSync(target.file.path, target.result.source, 'utf8'); + patched++; + console.log(' [ok] diagnostics injected'); + } + } catch (error) { + console.error(' [x] ' + directory.platform + ': ' + error.message); + failed++; + } + } + if (!directories.length) { + console.error(' [x] missing platform assets'); + failed++; + } + if (failed) process.exitCode = 1; + else console.log(' [ok] ' + patched + ' platform bundle(s) patched'); +} +if (require.main === module) main(); +module.exports = { MARKER, PREFIX, patchSource }; diff --git a/scripts/patch-home-restore-diagnostics.test.js b/scripts/patch-home-restore-diagnostics.test.js new file mode 100644 index 00000000..1ac443b0 --- /dev/null +++ b/scripts/patch-home-restore-diagnostics.test.js @@ -0,0 +1,43 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { MARKER, PREFIX, patchSource } = require('./patch-home-restore-diagnostics'); + +function fixture() { + return [ + 'import ' + String.fromCharCode(34) + './codex-rebuild-reading-width.js' + String.fromCharCode(34) + ';', + 'function restore(e,{accountKey:t,auth:n,area:r,navigate:i,productMode:a,state:o}){', + 'let s=e.get(AE),c=e.get(CH),u=remembered(e,{accountKey:t,auth:n,area:r,productMode:a});', + 'if(u==null||!s&&u.departedAt==null||areaOf(e,u.location)!==r){i(`/`);return!0}', + 'function tVa(e,{accountKey:t,auth:n,area:r,navigate:i,productMode:a,state:o}){let s=e.get(AE),c=e.get(ch);let u2=1}', + 'return (s||/* Codex:API-key 首页从其他页面恢复会话。 */t===`auth:apikey`&&r===`home`)?nVa(e,u,o):(i(u.location.pathname,{state:o}),!0)', + '}', + 'function cuu(){let l=e[4];', + 'let u;', + '/* Codex:API-key 首页恢复写入。 */u=()=>{QBa(t,{accountKey:l,location:n,productMode:s})};', + 'return u}', + 'let zChain=1', + ',gO=Y(U,({get:e})=>{let t=e(ch)?.state?.sidebarThreadLocationId;return typeof t==`string`?t:null}),', + '_O=cs(U,new Map);', + 'function nVa(e,t,n){let r=e.get(eh).prepareNavigation(gc(t.location),{state:{...t.location.state,...n}});return r!=null&&r()!=!0}', + ].join(''); +} + +test('diagnostics inject anchors and are idempotent', () => { + const result = patchSource(fixture()); + assert.equal(result.status, 'patched'); + assert.ok(result.source.includes(MARKER)); + assert.ok(result.source.includes(PREFIX)); + assert.match(result.source, /cuu\.write/); + assert.match(result.source, /tVa.enter/); + assert.match(result.source, /gO\.read/); + assert.match(result.source, /nVa\.enter/); + assert.match(result.source, /nVa\.prepared/); + const repeated = patchSource(result.source); + assert.equal(repeated.status, 'already-patched'); + assert.equal(repeated.source, result.source); +}); + +test('unrelated bundle stays not-applicable', () => { + const result = patchSource('function unrelated(){return 1}'); + assert.equal(result.status, 'not-applicable'); +}); diff --git a/scripts/patch-policy.js b/scripts/patch-policy.js index d4328352..64e08725 100644 --- a/scripts/patch-policy.js +++ b/scripts/patch-policy.js @@ -22,6 +22,7 @@ const PATCH_POLICY = [ { script: "patch-test-isolation.js", feature: "Windows 验收数据隔离" }, { script: "patch-provider-quota.js", feature: "真实 Provider 额度发送门槛" }, { script: "patch-api-key-home-navigation.js", feature: "API-key 首页会话恢复" }, + { script: "patch-home-restore-diagnostics.js", feature: "首页恢复诊断日志(临时)" }, { script: "patch-thread-timeline.js", feature: "按版本能力启用官方会话时间线" }, { script: "patch-mcp-status-refresh.js", feature: "MCP 启动状态刷新治理" }, { script: "patch-accent-presets.js", feature: "API-key 本地强调色预设" }, From 5b0f47a18cb314ce261fcb8b7a3fb2d3ec94721c Mon Sep 17 00:00:00 2001 From: carptopus Date: Mon, 19 Oct 2026 15:38:28 +0800 Subject: [PATCH 25/51] diag: skip diagnostics when home patch not applied in check mode --- scripts/patch-home-restore-diagnostics.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/scripts/patch-home-restore-diagnostics.js b/scripts/patch-home-restore-diagnostics.js index f8b9cc7d..b4010b6e 100644 --- a/scripts/patch-home-restore-diagnostics.js +++ b/scripts/patch-home-restore-diagnostics.js @@ -94,7 +94,11 @@ function main() { .map((name) => ({ name, path: path.join(directory.path, name) })) .map((file) => ({ file, result: patchSource(fs.readFileSync(file.path, 'utf8')) })) .filter((item) => item.result.status !== 'not-applicable'); - if (results.length !== 1) throw new Error('bundle-count ' + results.length); + if (results.length > 1) throw new Error('bundle-count ' + results.length); + if (!results.length) { + console.log(' [skip] api-key home patch not applied yet; diagnostics not applicable'); + continue; + } const target = results[0]; if (target.result.status === 'unexpected-shape') throw new Error(target.result.reason); console.log(' [' + directory.platform + '] ' + relPath(target.file.path)); From 64fe6472351149e00b03606b453dd5fc78dfb98c Mon Sep 17 00:00:00 2001 From: carptopus Date: Mon, 19 Oct 2026 16:04:40 +0800 Subject: [PATCH 26/51] diag: prepend marker without relying on reading-width import --- scripts/diag-replay-test.js | 13 +++++++++++++ scripts/patch-home-restore-diagnostics.js | 5 +---- 2 files changed, 14 insertions(+), 4 deletions(-) create mode 100644 scripts/diag-replay-test.js diff --git a/scripts/diag-replay-test.js b/scripts/diag-replay-test.js new file mode 100644 index 00000000..ae8303c9 --- /dev/null +++ b/scripts/diag-replay-test.js @@ -0,0 +1,13 @@ +const fs=require('fs'); +const acorn=require('acorn'); +const src=fs.readFileSync('Z:/TEMP/diag-reports/source-evidence/webview/app-initial-5851df3f6cb1.js','utf8'); +const { patchSource: homePatch }=require('./patch-api-key-home-navigation.js'); +const home=homePatch(src).source; +const { patchSource: diagPatch }=require('./patch-home-restore-diagnostics.js'); +const diag=diagPatch(home); +if(diag.status!=='patched'){console.log('diag failed:',diag.reason);process.exit(1);} +acorn.parse(diag.source,{ecmaVersion:'latest',sourceType:'module'}); +console.log('parsed-ok'); +const again=diagPatch(diag.source); +console.log('second:',again.status); +console.log('marker-at-start:', diag.source.startsWith('/* CodexRebuildHomeRestoreDiag */')); diff --git a/scripts/patch-home-restore-diagnostics.js b/scripts/patch-home-restore-diagnostics.js index b4010b6e..2abcb680 100644 --- a/scripts/patch-home-restore-diagnostics.js +++ b/scripts/patch-home-restore-diagnostics.js @@ -69,10 +69,7 @@ function patchSource(source) { next = next.replace(edit.anchor, edit.replacement); } if (!next.includes(MARKER)) { - const q = String.fromCharCode(34); - const boot = 'import ' + q + './codex-rebuild-reading-width.js' + q + ';'; - if (!next.includes(boot)) throw new Error('e2'); - next = next.replace(boot, boot + MARKER); + next = MARKER + next; } parse(next, { ecmaVersion: 'latest', sourceType: 'module' }); return { status: 'patched', source: next }; From c320e431794b40f0633373e641ebe6829a699e0a Mon Sep 17 00:00:00 2001 From: carptopus Date: Mon, 19 Oct 2026 17:43:55 +0800 Subject: [PATCH 27/51] diag: forward restore diagnostics to main-process file via console-message --- scripts/patch-home-restore-collector.js | 45 +++++++++++++++++++++++ scripts/patch-home-restore-diagnostics.js | 4 +- 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 scripts/patch-home-restore-collector.js diff --git a/scripts/patch-home-restore-collector.js b/scripts/patch-home-restore-collector.js new file mode 100644 index 00000000..55ae4967 --- /dev/null +++ b/scripts/patch-home-restore-collector.js @@ -0,0 +1,45 @@ +#!/usr/bin/env node +/** 主进程落盘采集器:捕获渲染进程 __codexHomeRestoreDiag 日志并追加写 JSONL。 */ +const fs = require('node:fs'); +const path = require('node:path'); +const { relPath } = require('./patch-util'); +const MARKER = '/* CodexRebuildHomeRestoreDiagCollector */'; +const PLATFORMS = ['mac-arm64', 'mac-x64', 'win']; +const ANCHOR = 'O.default.app.on(rowser-window-created,a)'; +const INJECT = [ + 'O.default.app.on(rowser-window-created,a),', + 'O.default.app.on(rowser-window-created,(q3e,w3e)=>{try{w3e.webContents.on(console-message,(q4e,r4e,m4e)=>{try{if(typeof m4e===string&&m4e.includes(__codexHomeRestoreDiag)){const t4e=m4e.slice(m4e.indexOf(__codexHomeRestoreDiag));fs.appendFileSync(process.env.CODEX_HOME_RESTORE_DIAG_LOG||Z:\\TEMP\\CodexRebuild\\cache\\home-restore-diag.jsonl,t4e+\n)}}catch(x4e){}})}catch(x4e){}}),', +].join(''); +function patchSource(source) { + if (source.includes(MARKER)) return { status: 'already-patched', source }; + if (!source.includes('browser-window-created')) return { status: 'not-applicable', source }; + try { + if (source.split(ANCHOR).length - 1 !== 1) throw new Error('主窗口锚点数量异常'); + const next = source.replace(ANCHOR, INJECT) + MARKER; + require('acorn').parse(next, { ecmaVersion: 'latest', sourceType: 'module' }); + return { status: 'patched', source: next }; + } catch (error) { return { status: 'unexpected-shape', source, reason: error.message }; } +} +function main() { + const args = process.argv.slice(2); + const platform = args.find(a => PLATFORMS.includes(a)); + const check = args.includes('--check'); + const dirs = PLATFORMS.map(item => ({ platform: item, path: path.join(require('./patch-util').SRC_DIR, item, '_asar', '.vite', 'build') })).filter(i => fs.existsSync(i.path)); + let failed = 0, patched = 0; + for (const d of dirs) { + try { + const files = fs.readdirSync(d.path).filter(n => /^main-.*\.js$/.test(n)); + const results = files.map(n => ({ n, s: fs.readFileSync(path.join(d.path, n), 'utf8') })).map(x => ({ n: x.n, r: patchSource(x.s) })).filter(x => x.r.status !== 'not-applicable'); + if (results.length !== 1) throw new Error('main bundle count ' + results.length); + const t = results[0]; + if (t.r.status === 'unexpected-shape') throw new Error(t.r.reason); + console.log(' [' + d.platform + '] ' + relPath(path.join(d.path, t.n))); + if (t.r.status === 'already-patched') { console.log(' [ok] already patched'); } + else if (check) { console.log(' [ok] anchors verified; dry-run'); } + else { fs.writeFileSync(path.join(d.path, t.n), t.r.source, 'utf8'); patched++; console.log(' [ok] collector injected'); } + } catch (e) { console.error(' [x] ' + d.platform + ': ' + e.message); failed++; } + } + if (failed) process.exitCode = 1; +} +if (require.main === module) main(); +module.exports = { MARKER, patchSource }; diff --git a/scripts/patch-home-restore-diagnostics.js b/scripts/patch-home-restore-diagnostics.js index 2abcb680..b5428be9 100644 --- a/scripts/patch-home-restore-diagnostics.js +++ b/scripts/patch-home-restore-diagnostics.js @@ -19,7 +19,9 @@ function targetDirectories(platform) { } function stmt(tag, expression) { return '(window.' + PREFIX + '??=[]).push({tag:' + JSON.stringify(tag) + ',at:Date.now(),data:' + expression + '});' } function logCall(tag, expression) { - return '(window.' + PREFIX + '??=[]).push({tag:' + JSON.stringify(tag) + ',at:Date.now(),data:' + expression + '}),'; + const entry = '({tag:' + JSON.stringify(tag) + ',at:Date.now(),data:' + expression + '})'; + const report = JSON.stringify('DIAG ' + tag + ' ' + expression); + return '(window.' + PREFIX + '??=[]).push(' + entry + '),console.log(' + report + '),'; } function patchSource(source) { if (source.includes(MARKER)) return { status: 'already-patched', source }; From d6719cda9fcee3aa61160efeb9146ee6018b0ac1 Mon Sep 17 00:00:00 2001 From: carptopus Date: Mon, 19 Oct 2026 20:31:21 +0800 Subject: [PATCH 28/51] diag: capture home restore chain in main process --- scripts/diag-replay-test.js | 13 ---- scripts/patch-home-restore-collector.js | 73 +++++++++++++------ scripts/patch-home-restore-collector.test.js | 48 ++++++++++++ scripts/patch-home-restore-diagnostics.js | 9 ++- .../patch-home-restore-diagnostics.test.js | 1 + scripts/patch-policy.js | 1 + scripts/verify-home-restore-chain.js | 42 +++++++++++ 7 files changed, 149 insertions(+), 38 deletions(-) delete mode 100644 scripts/diag-replay-test.js create mode 100644 scripts/patch-home-restore-collector.test.js create mode 100644 scripts/verify-home-restore-chain.js diff --git a/scripts/diag-replay-test.js b/scripts/diag-replay-test.js deleted file mode 100644 index ae8303c9..00000000 --- a/scripts/diag-replay-test.js +++ /dev/null @@ -1,13 +0,0 @@ -const fs=require('fs'); -const acorn=require('acorn'); -const src=fs.readFileSync('Z:/TEMP/diag-reports/source-evidence/webview/app-initial-5851df3f6cb1.js','utf8'); -const { patchSource: homePatch }=require('./patch-api-key-home-navigation.js'); -const home=homePatch(src).source; -const { patchSource: diagPatch }=require('./patch-home-restore-diagnostics.js'); -const diag=diagPatch(home); -if(diag.status!=='patched'){console.log('diag failed:',diag.reason);process.exit(1);} -acorn.parse(diag.source,{ecmaVersion:'latest',sourceType:'module'}); -console.log('parsed-ok'); -const again=diagPatch(diag.source); -console.log('second:',again.status); -console.log('marker-at-start:', diag.source.startsWith('/* CodexRebuildHomeRestoreDiag */')); diff --git a/scripts/patch-home-restore-collector.js b/scripts/patch-home-restore-collector.js index 55ae4967..6b14ce2e 100644 --- a/scripts/patch-home-restore-collector.js +++ b/scripts/patch-home-restore-collector.js @@ -1,45 +1,74 @@ #!/usr/bin/env node -/** 主进程落盘采集器:捕获渲染进程 __codexHomeRestoreDiag 日志并追加写 JSONL。 */ +/** 临时诊断采集器:把首页恢复链路的 console 调用结果追加到专用 JSONL。 */ const fs = require('node:fs'); const path = require('node:path'); -const { relPath } = require('./patch-util'); +const { relPath, SRC_DIR } = require('./patch-util'); const MARKER = '/* CodexRebuildHomeRestoreDiagCollector */'; const PLATFORMS = ['mac-arm64', 'mac-x64', 'win']; -const ANCHOR = 'O.default.app.on(rowser-window-created,a)'; -const INJECT = [ - 'O.default.app.on(rowser-window-created,a),', - 'O.default.app.on(rowser-window-created,(q3e,w3e)=>{try{w3e.webContents.on(console-message,(q4e,r4e,m4e)=>{try{if(typeof m4e===string&&m4e.includes(__codexHomeRestoreDiag)){const t4e=m4e.slice(m4e.indexOf(__codexHomeRestoreDiag));fs.appendFileSync(process.env.CODEX_HOME_RESTORE_DIAG_LOG||Z:\\TEMP\\CodexRebuild\\cache\\home-restore-diag.jsonl,t4e+\n)}}catch(x4e){}})}catch(x4e){}}),', +const ANCHOR = 'O.default.app.on(' + String.fromCharCode(96) + 'browser-window-created' + String.fromCharCode(96) + ',a),'; +const COLLECTOR = [ + 'O.default.app.on(' + String.fromCharCode(96) + 'browser-window-created' + String.fromCharCode(96) + ',(ce,we)=>{try{', + 'we.webContents.on(' + String.fromCharCode(96) + 'console-message' + String.fromCharCode(96) + ',(Ee,Se,Ie)=>{try{', + 'const De=typeof Ie===' + String.fromCharCode(39) + 'string' + String.fromCharCode(39) + '?Ie:typeof Se===' + String.fromCharCode(39) + 'string' + String.fromCharCode(39) + '?Se:Ee?.message;', + 'if(typeof De===' + String.fromCharCode(39) + 'string' + String.fromCharCode(39) + '&&De.includes(' + String.fromCharCode(39) + '__codexHomeRestoreDiag' + String.fromCharCode(39) + '))', + 'fs.appendFileSync(' + String.fromCharCode(39) + 'Z:\\TEMP\\CodexRebuild\\cache\\home-restore-diag.jsonl' + String.fromCharCode(39) + ',De.slice(De.indexOf(' + String.fromCharCode(39) + '__codexHomeRestoreDiag' + String.fromCharCode(39) + '))+' + String.fromCharCode(39) + '\\n' + String.fromCharCode(39) + ')', + '}catch(xe){}})}catch(xe){}}),', ].join(''); + function patchSource(source) { if (source.includes(MARKER)) return { status: 'already-patched', source }; if (!source.includes('browser-window-created')) return { status: 'not-applicable', source }; try { - if (source.split(ANCHOR).length - 1 !== 1) throw new Error('主窗口锚点数量异常'); - const next = source.replace(ANCHOR, INJECT) + MARKER; + if (source.split(ANCHOR).length - 1 !== 1) throw new Error('main listener anchor count ' + (source.split(ANCHOR).length - 1)); + const next = source.replace(ANCHOR, ANCHOR + COLLECTOR) + MARKER; require('acorn').parse(next, { ecmaVersion: 'latest', sourceType: 'module' }); return { status: 'patched', source: next }; - } catch (error) { return { status: 'unexpected-shape', source, reason: error.message }; } + } catch (error) { + return { status: 'unexpected-shape', source, reason: error.message }; + } } + function main() { const args = process.argv.slice(2); - const platform = args.find(a => PLATFORMS.includes(a)); + const platform = args.find((arg) => PLATFORMS.includes(arg)); const check = args.includes('--check'); - const dirs = PLATFORMS.map(item => ({ platform: item, path: path.join(require('./patch-util').SRC_DIR, item, '_asar', '.vite', 'build') })).filter(i => fs.existsSync(i.path)); - let failed = 0, patched = 0; - for (const d of dirs) { + const dirs = PLATFORMS.map((item) => ({ + platform: item, + path: path.join(SRC_DIR, item, '_asar', '.vite', 'build'), + })).filter((item) => fs.existsSync(item.path)); + let failed = 0; + let patched = 0; + for (const directory of dirs) { try { - const files = fs.readdirSync(d.path).filter(n => /^main-.*\.js$/.test(n)); - const results = files.map(n => ({ n, s: fs.readFileSync(path.join(d.path, n), 'utf8') })).map(x => ({ n: x.n, r: patchSource(x.s) })).filter(x => x.r.status !== 'not-applicable'); + const results = fs.readdirSync(directory.path) + .filter((name) => /^main-.*\.js$/.test(name)) + .map((name) => ({ name, source: fs.readFileSync(path.join(directory.path, name), 'utf8') })) + .map((item) => ({ ...item, result: patchSource(item.source) })) + .filter((item) => item.result.status !== 'not-applicable'); if (results.length !== 1) throw new Error('main bundle count ' + results.length); - const t = results[0]; - if (t.r.status === 'unexpected-shape') throw new Error(t.r.reason); - console.log(' [' + d.platform + '] ' + relPath(path.join(d.path, t.n))); - if (t.r.status === 'already-patched') { console.log(' [ok] already patched'); } - else if (check) { console.log(' [ok] anchors verified; dry-run'); } - else { fs.writeFileSync(path.join(d.path, t.n), t.r.source, 'utf8'); patched++; console.log(' [ok] collector injected'); } - } catch (e) { console.error(' [x] ' + d.platform + ': ' + e.message); failed++; } + const target = results[0]; + if (target.result.status === 'unexpected-shape') throw new Error(target.result.reason); + console.log(' [' + directory.platform + '] ' + relPath(path.join(directory.path, target.name))); + if (target.result.status === 'already-patched') { + console.log(' [ok] already patched'); + } else if (check) { + console.log(' [ok] anchors verified; dry-run'); + } else { + fs.writeFileSync(path.join(directory.path, target.name), target.result.source, 'utf8'); + patched++; + console.log(' [ok] collector injected'); + } + } catch (error) { + console.error(' [x] ' + directory.platform + ': ' + error.message); + failed++; + } + } + if (!dirs.length) { + console.error(' [x] missing platform assets'); + failed++; } if (failed) process.exitCode = 1; } + if (require.main === module) main(); module.exports = { MARKER, patchSource }; diff --git a/scripts/patch-home-restore-collector.test.js b/scripts/patch-home-restore-collector.test.js new file mode 100644 index 00000000..7f401836 --- /dev/null +++ b/scripts/patch-home-restore-collector.test.js @@ -0,0 +1,48 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const vm = require('node:vm'); +const { MARKER, patchSource } = require('./patch-home-restore-collector'); + +function fixture() { + const tick = String.fromCharCode(96); + return 'const e=require(' + JSON.stringify('node:events') + '),O=e.a(require(' + JSON.stringify('electron') + '),1);function attach(n,r){let a=(e,t)=>{},i=()=>{};return O.default.app.on(' + tick + 'browser-window-created' + tick + ',a),n.push(()=>{O.default.app.removeListener(' + tick + 'browser-window-created' + tick + ',a)}),i}'; +} + +function captureConsole(source, options, legacy) { + const tick = String.fromCharCode(96); + const first = 'O.default.app.on(' + tick + 'browser-window-created' + tick + ',a),'; + const start = source.indexOf(first) + first.length; + const end = source.indexOf(',n.push(', start); + let appHandler; + let consoleHandler; + let written; + const fs = { appendFileSync: (_file, data) => { written = data; } }; + const app = { on: (_event, callback) => { appHandler = callback; } }; + const webContents = { on: (_event, callback) => { consoleHandler = callback; } }; + const we = { webContents }; + vm.runInNewContext(source.slice(start, end), { O: { default: { app } }, app, fs, we }); + appHandler({}, we); + consoleHandler(...(legacy ? ['old-api', options.level, options.message] : [options])); + return written; +} + +test('collector patches actual main-process listener and forwards both Electron signatures', () => { + const patched = patchSource(fixture()); + assert.equal(patched.status, 'patched'); + assert.ok(patched.source.includes(MARKER)); + assert.ok(patched.source.includes('app.on(' + String.fromCharCode(96) + 'browser-window-created' + String.fromCharCode(96))); + assert.equal(patchSource(patched.source).status, 'already-patched'); + assert.equal( + captureConsole(patched.source, { level: 3, message: 'DIAG __codexHomeRestoreDiag new' }), + '__codexHomeRestoreDiag new\n', + ); + assert.equal( + captureConsole(patched.source, { level: 3, message: 'DIAG __codexHomeRestoreDiag old' }, true), + '__codexHomeRestoreDiag old\n', + ); +}); + +test('collector needs the evaluated main-process window listener', () => { + assert.equal(patchSource('unrelated').status, 'not-applicable'); + assert.equal(patchSource('browser-window-created O.default.app.on(' + String.fromCharCode(96) + 'browser-window-created' + String.fromCharCode(96) + ',a),').status, 'unexpected-shape'); +}); diff --git a/scripts/patch-home-restore-diagnostics.js b/scripts/patch-home-restore-diagnostics.js index b5428be9..093cc1cb 100644 --- a/scripts/patch-home-restore-diagnostics.js +++ b/scripts/patch-home-restore-diagnostics.js @@ -17,11 +17,14 @@ function targetDirectories(platform) { path: path.join(SRC_DIR, item, '_asar', 'webview', 'assets'), })).filter((item) => fs.existsSync(item.path)); } -function stmt(tag, expression) { return '(window.' + PREFIX + '??=[]).push({tag:' + JSON.stringify(tag) + ',at:Date.now(),data:' + expression + '});' } -function logCall(tag, expression) { +function stmt(tag, expression) { const entry = '({tag:' + JSON.stringify(tag) + ',at:Date.now(),data:' + expression + '})'; + const report = JSON.stringify('DIAG ' + tag); + return '(window.' + PREFIX + '??=[]).push(' + entry + '),globalThis.console.log(' + report + ');'; +} +function logCall(tag, expression) { const report = JSON.stringify('DIAG ' + tag + ' ' + expression); - return '(window.' + PREFIX + '??=[]).push(' + entry + '),console.log(' + report + '),'; + return '(window.' + PREFIX + '??=[]).push({tag:' + JSON.stringify(tag) + ',at:Date.now(),data:' + expression + '}),globalThis.console.log(' + report + ');'; } function patchSource(source) { if (source.includes(MARKER)) return { status: 'already-patched', source }; diff --git a/scripts/patch-home-restore-diagnostics.test.js b/scripts/patch-home-restore-diagnostics.test.js index 1ac443b0..b060fbb3 100644 --- a/scripts/patch-home-restore-diagnostics.test.js +++ b/scripts/patch-home-restore-diagnostics.test.js @@ -32,6 +32,7 @@ test('diagnostics inject anchors and are idempotent', () => { assert.match(result.source, /gO\.read/); assert.match(result.source, /nVa\.enter/); assert.match(result.source, /nVa\.prepared/); + assert.match(result.source, /globalThis\.console\.log\("DIAG gO\.read"\)/); const repeated = patchSource(result.source); assert.equal(repeated.status, 'already-patched'); assert.equal(repeated.source, result.source); diff --git a/scripts/patch-policy.js b/scripts/patch-policy.js index 64e08725..78e85909 100644 --- a/scripts/patch-policy.js +++ b/scripts/patch-policy.js @@ -23,6 +23,7 @@ const PATCH_POLICY = [ { script: "patch-provider-quota.js", feature: "真实 Provider 额度发送门槛" }, { script: "patch-api-key-home-navigation.js", feature: "API-key 首页会话恢复" }, { script: "patch-home-restore-diagnostics.js", feature: "首页恢复诊断日志(临时)" }, + { script: "patch-home-restore-collector.js", feature: "首页恢复诊断落盘采集(临时)" }, { script: "patch-thread-timeline.js", feature: "按版本能力启用官方会话时间线" }, { script: "patch-mcp-status-refresh.js", feature: "MCP 启动状态刷新治理" }, { script: "patch-accent-presets.js", feature: "API-key 本地强调色预设" }, diff --git a/scripts/verify-home-restore-chain.js b/scripts/verify-home-restore-chain.js new file mode 100644 index 00000000..ca5a8a1a --- /dev/null +++ b/scripts/verify-home-restore-chain.js @@ -0,0 +1,42 @@ +const fs = require('node:fs'); +const { parse } = require('acorn'); +const home = require('./patch-api-key-home-navigation'); +const diagnostics = require('./patch-home-restore-diagnostics'); +const collector = require('./patch-home-restore-collector'); + +const rendererPath = process.argv[2]; +const mainPath = process.argv[3]; +if (!rendererPath || !mainPath) throw new Error('usage: node scripts/verify-home-restore-chain.js '); + +function stripPriorDiagnostics(source) { + const marker = '/* CodexRebuildHomeRestoreDiag */'; + if (!source.startsWith(marker)) return source; + const call = ',console.log("DIAG cuu.write {accountKey:l,pathname:n?.pathname,state:n?.state}")'; + if (!source.includes(call)) throw new Error('instrumented writer log missing'); + return source.slice(marker.length).replace(call, '').replace('window.__codexHomeRestoreDiag??=[])).push(({', 'window.__codexHomeRestoreDiag??=[]).push({'); +} + +function validateRenderer(source) { + const navigation = home.patchSource(source); + if (navigation.status === 'unexpected-shape') throw new Error('home navigation ' + navigation.reason); + if (navigation.status === 'not-applicable') throw new Error('home navigation missing'); + const observed = diagnostics.patchSource(navigation.source); + if (observed.status === 'unexpected-shape') throw new Error('diagnostics ' + observed.reason); + if (observed.status !== 'patched' && observed.status !== 'already-patched') throw new Error('diagnostics missing'); + parse(observed.source, { ecmaVersion: 'latest', sourceType: 'module' }); + return { navigation: navigation.status, diagnostics: observed.status, source: observed.source }; +} + +const original = fs.readFileSync(rendererPath, 'utf8'); +validateRenderer(original); +const cleanRenderer = stripPriorDiagnostics(original); +const observedRenderer = validateRenderer(cleanRenderer); +const observedMain = collector.patchSource(fs.readFileSync(mainPath, 'utf8')); +if (observedMain.status === 'unexpected-shape') throw new Error('collector ' + observedMain.reason); +if (observedMain.status === 'patched') parse(observedMain.source, { ecmaVersion: 'latest', sourceType: 'module' }); +console.log(JSON.stringify({ + cleanNavigation: home.patchSource(cleanRenderer).status, + diagnostics: observedRenderer.diagnostics, + collector: observedMain.status, + diagCalls: observedRenderer.source.split('globalThis.console.log').length - 1, +})); From ed3f2f590526e95f82a5582b0ba890900fecb4d3 Mon Sep 17 00:00:00 2001 From: carptopus Date: Mon, 19 Oct 2026 21:17:00 +0800 Subject: [PATCH 29/51] diag: handle Electron console details object --- scripts/patch-home-restore-collector.js | 6 +++--- scripts/patch-home-restore-collector.test.js | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/scripts/patch-home-restore-collector.js b/scripts/patch-home-restore-collector.js index 6b14ce2e..98989a38 100644 --- a/scripts/patch-home-restore-collector.js +++ b/scripts/patch-home-restore-collector.js @@ -9,9 +9,9 @@ const ANCHOR = 'O.default.app.on(' + String.fromCharCode(96) + 'browser-window-c const COLLECTOR = [ 'O.default.app.on(' + String.fromCharCode(96) + 'browser-window-created' + String.fromCharCode(96) + ',(ce,we)=>{try{', 'we.webContents.on(' + String.fromCharCode(96) + 'console-message' + String.fromCharCode(96) + ',(Ee,Se,Ie)=>{try{', - 'const De=typeof Ie===' + String.fromCharCode(39) + 'string' + String.fromCharCode(39) + '?Ie:typeof Se===' + String.fromCharCode(39) + 'string' + String.fromCharCode(39) + '?Se:Ee?.message;', - 'if(typeof De===' + String.fromCharCode(39) + 'string' + String.fromCharCode(39) + '&&De.includes(' + String.fromCharCode(39) + '__codexHomeRestoreDiag' + String.fromCharCode(39) + '))', - 'fs.appendFileSync(' + String.fromCharCode(39) + 'Z:\\TEMP\\CodexRebuild\\cache\\home-restore-diag.jsonl' + String.fromCharCode(39) + ',De.slice(De.indexOf(' + String.fromCharCode(39) + '__codexHomeRestoreDiag' + String.fromCharCode(39) + '))+' + String.fromCharCode(39) + '\\n' + String.fromCharCode(39) + ')', + 'const De=[Ee?.message,Se?.message,typeof Se===' + String.fromCharCode(39) + 'string' + String.fromCharCode(39) + '?Se:null,Ie?.message,typeof Ie===' + String.fromCharCode(39) + 'string' + String.fromCharCode(39) + '?Ie:null].find(xe=>typeof xe===' + String.fromCharCode(39) + 'string' + String.fromCharCode(39) + '&&xe.includes(' + String.fromCharCode(39) + '__codexHomeRestoreDiag' + String.fromCharCode(39) + '));', + 'if(De!=null){const xe=De.slice(De.indexOf(' + String.fromCharCode(39) + '__codexHomeRestoreDiag' + String.fromCharCode(39) + '));', + 'fs.appendFileSync(' + String.fromCharCode(39) + 'Z:\\TEMP\\CodexRebuild\\cache\\home-restore-diag.jsonl' + String.fromCharCode(39) + ',xe+' + String.fromCharCode(39) + '\\n' + String.fromCharCode(39) + ')}', '}catch(xe){}})}catch(xe){}}),', ].join(''); diff --git a/scripts/patch-home-restore-collector.test.js b/scripts/patch-home-restore-collector.test.js index 7f401836..06a98064 100644 --- a/scripts/patch-home-restore-collector.test.js +++ b/scripts/patch-home-restore-collector.test.js @@ -22,7 +22,7 @@ function captureConsole(source, options, legacy) { const we = { webContents }; vm.runInNewContext(source.slice(start, end), { O: { default: { app } }, app, fs, we }); appHandler({}, we); - consoleHandler(...(legacy ? ['old-api', options.level, options.message] : [options])); + consoleHandler(...(legacy ? ['old-api', options.level, options.message] : ['new-api', options])); return written; } From 521ab5a4fd26faccb375ca027334a8f8d36f9c6b Mon Sep 17 00:00:00 2001 From: carptopus Date: Mon, 19 Oct 2026 21:41:53 +0800 Subject: [PATCH 30/51] diag: hook renderer web contents payloads --- scripts/patch-home-restore-collector.js | 9 ++++++-- scripts/patch-home-restore-collector.test.js | 22 ++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/scripts/patch-home-restore-collector.js b/scripts/patch-home-restore-collector.js index 98989a38..66c18463 100644 --- a/scripts/patch-home-restore-collector.js +++ b/scripts/patch-home-restore-collector.js @@ -8,11 +8,16 @@ const PLATFORMS = ['mac-arm64', 'mac-x64', 'win']; const ANCHOR = 'O.default.app.on(' + String.fromCharCode(96) + 'browser-window-created' + String.fromCharCode(96) + ',a),'; const COLLECTOR = [ 'O.default.app.on(' + String.fromCharCode(96) + 'browser-window-created' + String.fromCharCode(96) + ',(ce,we)=>{try{', - 'we.webContents.on(' + String.fromCharCode(96) + 'console-message' + String.fromCharCode(96) + ',(Ee,Se,Ie)=>{try{', + 'const webContents=we?.webContents??we;', + 'if(webContents?.isDestroyed?.())return;', + 'const hookMessage=(Ee,Se,Ie)=>{try{', 'const De=[Ee?.message,Se?.message,typeof Se===' + String.fromCharCode(39) + 'string' + String.fromCharCode(39) + '?Se:null,Ie?.message,typeof Ie===' + String.fromCharCode(39) + 'string' + String.fromCharCode(39) + '?Ie:null].find(xe=>typeof xe===' + String.fromCharCode(39) + 'string' + String.fromCharCode(39) + '&&xe.includes(' + String.fromCharCode(39) + '__codexHomeRestoreDiag' + String.fromCharCode(39) + '));', 'if(De!=null){const xe=De.slice(De.indexOf(' + String.fromCharCode(39) + '__codexHomeRestoreDiag' + String.fromCharCode(39) + '));', 'fs.appendFileSync(' + String.fromCharCode(39) + 'Z:\\TEMP\\CodexRebuild\\cache\\home-restore-diag.jsonl' + String.fromCharCode(39) + ',xe+' + String.fromCharCode(39) + '\\n' + String.fromCharCode(39) + ')}', - '}catch(xe){}})}catch(xe){}}),', + '}catch(xe){}};', + 'webContents?.on?.(' + String.fromCharCode(96) + 'console-message' + String.fromCharCode(96) + ',hookMessage);', + 'if(webContents?.isDestroyed?.())return;', + '}catch(xe){}}),', ].join(''); function patchSource(source) { diff --git a/scripts/patch-home-restore-collector.test.js b/scripts/patch-home-restore-collector.test.js index 06a98064..3d7f0b31 100644 --- a/scripts/patch-home-restore-collector.test.js +++ b/scripts/patch-home-restore-collector.test.js @@ -42,6 +42,28 @@ test('collector patches actual main-process listener and forwards both Electron ); }); +test('collector also accepts a webContents payload', () => { + const patched = patchSource(fixture()); + const tick = String.fromCharCode(96); + const first = 'O.default.app.on(' + tick + 'browser-window-created' + tick + ',a),'; + const start = patched.source.indexOf(first) + first.length; + const end = patched.source.indexOf(',n.push(', start); + let appHandler; + let messageHandler; + let written; + const fs = { appendFileSync: (_file, data) => { written = data; } }; + const app = { on: (_event, callback) => { appHandler = callback; } }; + const webContents = { + isDestroyed: () => false, + on: (_event, callback) => { messageHandler = callback; }, + }; + vm.runInNewContext(patched.source.slice(start, end), { O: { default: { app } }, app, fs }); + appHandler({}, webContents); + assert.equal(typeof messageHandler, 'function'); + messageHandler('legacy', 3, 'DIAG __codexHomeRestoreDiag payload'); + assert.equal(written, '__codexHomeRestoreDiag payload\n'); +}); + test('collector needs the evaluated main-process window listener', () => { assert.equal(patchSource('unrelated').status, 'not-applicable'); assert.equal(patchSource('browser-window-created O.default.app.on(' + String.fromCharCode(96) + 'browser-window-created' + String.fromCharCode(96) + ',a),').status, 'unexpected-shape'); From ac1f3719cbdc594cb50975ba21d171b8836e3b9e Mon Sep 17 00:00:00 2001 From: carptopus Date: Mon, 19 Oct 2026 23:19:03 +0800 Subject: [PATCH 31/51] diag: start collector from main entry --- scripts/patch-home-restore-collector.js | 33 ++--- scripts/patch-home-restore-collector.test.js | 132 +++++++++++-------- 2 files changed, 90 insertions(+), 75 deletions(-) diff --git a/scripts/patch-home-restore-collector.js b/scripts/patch-home-restore-collector.js index 66c18463..3aea2d44 100644 --- a/scripts/patch-home-restore-collector.js +++ b/scripts/patch-home-restore-collector.js @@ -1,31 +1,27 @@ #!/usr/bin/env node -/** 临时诊断采集器:把首页恢复链路的 console 调用结果追加到专用 JSONL。 */ +/** 临时诊断采集器:在主进程入口顶部订阅所有窗口的 console 消息并追加到专用 JSONL。 */ const fs = require('node:fs'); const path = require('node:path'); const { relPath, SRC_DIR } = require('./patch-util'); const MARKER = '/* CodexRebuildHomeRestoreDiagCollector */'; const PLATFORMS = ['mac-arm64', 'mac-x64', 'win']; -const ANCHOR = 'O.default.app.on(' + String.fromCharCode(96) + 'browser-window-created' + String.fromCharCode(96) + ',a),'; -const COLLECTOR = [ - 'O.default.app.on(' + String.fromCharCode(96) + 'browser-window-created' + String.fromCharCode(96) + ',(ce,we)=>{try{', - 'const webContents=we?.webContents??we;', - 'if(webContents?.isDestroyed?.())return;', - 'const hookMessage=(Ee,Se,Ie)=>{try{', - 'const De=[Ee?.message,Se?.message,typeof Se===' + String.fromCharCode(39) + 'string' + String.fromCharCode(39) + '?Se:null,Ie?.message,typeof Ie===' + String.fromCharCode(39) + 'string' + String.fromCharCode(39) + '?Ie:null].find(xe=>typeof xe===' + String.fromCharCode(39) + 'string' + String.fromCharCode(39) + '&&xe.includes(' + String.fromCharCode(39) + '__codexHomeRestoreDiag' + String.fromCharCode(39) + '));', - 'if(De!=null){const xe=De.slice(De.indexOf(' + String.fromCharCode(39) + '__codexHomeRestoreDiag' + String.fromCharCode(39) + '));', - 'fs.appendFileSync(' + String.fromCharCode(39) + 'Z:\\TEMP\\CodexRebuild\\cache\\home-restore-diag.jsonl' + String.fromCharCode(39) + ',xe+' + String.fromCharCode(39) + '\\n' + String.fromCharCode(39) + ')}', - '}catch(xe){}};', - 'webContents?.on?.(' + String.fromCharCode(96) + 'console-message' + String.fromCharCode(96) + ',hookMessage);', - 'if(webContents?.isDestroyed?.())return;', - '}catch(xe){}}),', +const INJECT = [ + '/* CodexRebuildHomeRestoreDiagCollector */', + '(()=>{try{const electron=require(' + JSON.stringify('electron') + '),fs=require(' + JSON.stringify('node:fs') + '),app=electron.app;', + 'const output=' + JSON.stringify('Z:\\TEMP\\CodexRebuild\\cache\\home-restore-diag.jsonl') + ';', + 'const write=(value)=>{if(typeof value!==' + JSON.stringify('string') + '||!value.includes(' + JSON.stringify('__codexHomeRestoreDiag') + '))return;try{fs.appendFileSync(output,value.slice(value.indexOf(' + JSON.stringify('__codexHomeRestoreDiag') + '))+' + JSON.stringify('\n') + ')}catch{}};', + 'const hook=(webContents)=>{try{if(webContents==null||webContents.isDestroyed?.())return;webContents.on(' + JSON.stringify('console-message') + ',(event,level,message,line,sourceId)=>write([event?.message,level?.message,typeof level===' + JSON.stringify('string') + '?level:null,message?.message,typeof message===' + JSON.stringify('string') + '?message:null].find(value=>typeof value===' + JSON.stringify('string') + '&&value.includes(' + JSON.stringify('__codexHomeRestoreDiag') + '))))}catch{}};', + 'app.on(' + JSON.stringify('web-contents-created') + ',(event,webContents)=>hook(webContents));', + 'app.on(' + JSON.stringify('browser-window-created') + ',(event,window)=>hook(window?.webContents??window));', + 'for(const window of electron.BrowserWindow.getAllWindows())hook(window.webContents);', + 'write(' + JSON.stringify('__codexHomeRestoreDiag collector-ready') + ');', + '}catch{}})();', ].join(''); function patchSource(source) { if (source.includes(MARKER)) return { status: 'already-patched', source }; - if (!source.includes('browser-window-created')) return { status: 'not-applicable', source }; try { - if (source.split(ANCHOR).length - 1 !== 1) throw new Error('main listener anchor count ' + (source.split(ANCHOR).length - 1)); - const next = source.replace(ANCHOR, ANCHOR + COLLECTOR) + MARKER; + const next = INJECT + source; require('acorn').parse(next, { ecmaVersion: 'latest', sourceType: 'module' }); return { status: 'patched', source: next }; } catch (error) { @@ -48,8 +44,7 @@ function main() { const results = fs.readdirSync(directory.path) .filter((name) => /^main-.*\.js$/.test(name)) .map((name) => ({ name, source: fs.readFileSync(path.join(directory.path, name), 'utf8') })) - .map((item) => ({ ...item, result: patchSource(item.source) })) - .filter((item) => item.result.status !== 'not-applicable'); + .map((item) => ({ ...item, result: patchSource(item.source) })); if (results.length !== 1) throw new Error('main bundle count ' + results.length); const target = results[0]; if (target.result.status === 'unexpected-shape') throw new Error(target.result.reason); diff --git a/scripts/patch-home-restore-collector.test.js b/scripts/patch-home-restore-collector.test.js index 3d7f0b31..81fb9e83 100644 --- a/scripts/patch-home-restore-collector.test.js +++ b/scripts/patch-home-restore-collector.test.js @@ -1,70 +1,90 @@ const test = require('node:test'); const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); const vm = require('node:vm'); const { MARKER, patchSource } = require('./patch-home-restore-collector'); -function fixture() { - const tick = String.fromCharCode(96); - return 'const e=require(' + JSON.stringify('node:events') + '),O=e.a(require(' + JSON.stringify('electron') + '),1);function attach(n,r){let a=(e,t)=>{},i=()=>{};return O.default.app.on(' + tick + 'browser-window-created' + tick + ',a),n.push(()=>{O.default.app.removeListener(' + tick + 'browser-window-created' + tick + ',a)}),i}'; -} - -function captureConsole(source, options, legacy) { - const tick = String.fromCharCode(96); - const first = 'O.default.app.on(' + tick + 'browser-window-created' + tick + ',a),'; - const start = source.indexOf(first) + first.length; - const end = source.indexOf(',n.push(', start); - let appHandler; - let consoleHandler; - let written; - const fs = { appendFileSync: (_file, data) => { written = data; } }; - const app = { on: (_event, callback) => { appHandler = callback; } }; - const webContents = { on: (_event, callback) => { consoleHandler = callback; } }; - const we = { webContents }; - vm.runInNewContext(source.slice(start, end), { O: { default: { app } }, app, fs, we }); - appHandler({}, we); - consoleHandler(...(legacy ? ['old-api', options.level, options.message] : ['new-api', options])); - return written; -} - -test('collector patches actual main-process listener and forwards both Electron signatures', () => { - const patched = patchSource(fixture()); +test('collector runs at main entry and captures both console payloads', (t) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-collector-test-')); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const original = 'const electron=require(' + JSON.stringify('electron') + ');globalThis.entryExecuted=true;'; + const patched = patchSource(original); assert.equal(patched.status, 'patched'); - assert.ok(patched.source.includes(MARKER)); - assert.ok(patched.source.includes('app.on(' + String.fromCharCode(96) + 'browser-window-created' + String.fromCharCode(96))); + assert.ok(patched.source.startsWith(MARKER)); assert.equal(patchSource(patched.source).status, 'already-patched'); - assert.equal( - captureConsole(patched.source, { level: 3, message: 'DIAG __codexHomeRestoreDiag new' }), - '__codexHomeRestoreDiag new\n', - ); - assert.equal( - captureConsole(patched.source, { level: 3, message: 'DIAG __codexHomeRestoreDiag old' }, true), - '__codexHomeRestoreDiag old\n', + + const appHandlers = new Map(); + const consoleHandlers = []; + const mainWindow = { + webContents: { + isDestroyed: () => false, + on: (event, callback) => { + assert.equal(event, 'console-message'); + consoleHandlers.push(callback); + }, + }, + }; + const app = { on: (event, callback) => appHandlers.set(event, callback) }; + const fakeRequire = (name) => { + if (name === 'electron') return { app, BrowserWindow: { getAllWindows: () => [mainWindow] } }; + return require(name); + }; + const context = { + require: fakeRequire, + console: { warn: (value) => { throw new Error(value); } }, + }; + vm.runInNewContext(patched.source, context); + assert.equal(context.entryExecuted, true); + assert.equal(consoleHandlers.length, 1); + + const replacement = patched.source.replace( + JSON.stringify('Z:\\TEMP\\CodexRebuild\\cache\\home-restore-diag.jsonl'), + JSON.stringify(path.join(root, 'diag.jsonl')), ); + assert.notEqual(replacement, patched.source); + const isolatedConsoleHandlers = []; + const isolatedMain = { + webContents: { + isDestroyed: () => false, + on: (_event, callback) => isolatedConsoleHandlers.push(callback), + }, + }; + const isolatedApp = { on: () => {} }; + vm.runInNewContext(replacement, { + require: (name) => name === 'electron' + ? { app: isolatedApp, BrowserWindow: { getAllWindows: () => [isolatedMain] } } + : require(name), + }); + const log = path.join(root, 'diag.jsonl'); + assert.match(fs.readFileSync(log, 'utf8'), /collector-ready/); + isolatedConsoleHandlers[0]({ message: 'DIAG __codexHomeRestoreDiag details' }); + isolatedConsoleHandlers[0]('old', 3, 'DIAG __codexHomeRestoreDiag old'); + assert.match(fs.readFileSync(log, 'utf8'), /__codexHomeRestoreDiag details/); + assert.match(fs.readFileSync(log, 'utf8'), /__codexHomeRestoreDiag old/); }); -test('collector also accepts a webContents payload', () => { - const patched = patchSource(fixture()); - const tick = String.fromCharCode(96); - const first = 'O.default.app.on(' + tick + 'browser-window-created' + tick + ',a),'; - const start = patched.source.indexOf(first) + first.length; - const end = patched.source.indexOf(',n.push(', start); - let appHandler; - let messageHandler; - let written; - const fs = { appendFileSync: (_file, data) => { written = data; } }; - const app = { on: (_event, callback) => { appHandler = callback; } }; +test('renderer console events use the same listener', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-collector-payload-')); + const source = patchSource('const e=require(' + JSON.stringify('electron') + ');').source.replace( + JSON.stringify('Z:\\TEMP\\CodexRebuild\\cache\\home-restore-diag.jsonl'), + JSON.stringify(path.join(root, 'diag.jsonl')), + ); + let webContentsHandler; + let rendererHandler; + const app = { on: (event, callback) => { if (event === 'web-contents-created') webContentsHandler = callback; } }; const webContents = { isDestroyed: () => false, - on: (_event, callback) => { messageHandler = callback; }, + on: (_event, callback) => { rendererHandler = callback; }, }; - vm.runInNewContext(patched.source.slice(start, end), { O: { default: { app } }, app, fs }); - appHandler({}, webContents); - assert.equal(typeof messageHandler, 'function'); - messageHandler('legacy', 3, 'DIAG __codexHomeRestoreDiag payload'); - assert.equal(written, '__codexHomeRestoreDiag payload\n'); -}); - -test('collector needs the evaluated main-process window listener', () => { - assert.equal(patchSource('unrelated').status, 'not-applicable'); - assert.equal(patchSource('browser-window-created O.default.app.on(' + String.fromCharCode(96) + 'browser-window-created' + String.fromCharCode(96) + ',a),').status, 'unexpected-shape'); + vm.runInNewContext(source, { + require: (name) => name === 'electron' + ? { app, BrowserWindow: { getAllWindows: () => [] } } + : require(name), + }); + webContentsHandler({}, webContents); + rendererHandler({ level: 3 }, { message: 'DIAG __codexHomeRestoreDiag payload' }); + assert.match(fs.readFileSync(path.join(root, 'diag.jsonl'), 'utf8'), /__codexHomeRestoreDiag payload/); + fs.rmSync(root, { recursive: true, force: true }); }); From 513d7e154f19fa7f5b24f65debe45142f0363cd8 Mon Sep 17 00:00:00 2001 From: carptopus Date: Mon, 19 Oct 2026 23:50:36 +0800 Subject: [PATCH 32/51] ci: rerun candidate after stalled build From e5698bbebba387de03260fb2b5cc9ab66bc964e4 Mon Sep 17 00:00:00 2001 From: carptopus Date: Mon, 19 Oct 2026 23:53:46 +0800 Subject: [PATCH 33/51] diag: capture home restore diagnostic lines --- scripts/patch-home-restore-collector.js | 4 ++-- scripts/patch-home-restore-collector.test.js | 24 ++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/scripts/patch-home-restore-collector.js b/scripts/patch-home-restore-collector.js index 3aea2d44..ea7206e4 100644 --- a/scripts/patch-home-restore-collector.js +++ b/scripts/patch-home-restore-collector.js @@ -9,8 +9,8 @@ const INJECT = [ '/* CodexRebuildHomeRestoreDiagCollector */', '(()=>{try{const electron=require(' + JSON.stringify('electron') + '),fs=require(' + JSON.stringify('node:fs') + '),app=electron.app;', 'const output=' + JSON.stringify('Z:\\TEMP\\CodexRebuild\\cache\\home-restore-diag.jsonl') + ';', - 'const write=(value)=>{if(typeof value!==' + JSON.stringify('string') + '||!value.includes(' + JSON.stringify('__codexHomeRestoreDiag') + '))return;try{fs.appendFileSync(output,value.slice(value.indexOf(' + JSON.stringify('__codexHomeRestoreDiag') + '))+' + JSON.stringify('\n') + ')}catch{}};', - 'const hook=(webContents)=>{try{if(webContents==null||webContents.isDestroyed?.())return;webContents.on(' + JSON.stringify('console-message') + ',(event,level,message,line,sourceId)=>write([event?.message,level?.message,typeof level===' + JSON.stringify('string') + '?level:null,message?.message,typeof message===' + JSON.stringify('string') + '?message:null].find(value=>typeof value===' + JSON.stringify('string') + '&&value.includes(' + JSON.stringify('__codexHomeRestoreDiag') + '))))}catch{}};', + 'const write=(value)=>{if(typeof value!==' + JSON.stringify('string') + ')return;const marker=value.includes(' + JSON.stringify('__codexHomeRestoreDiag') + ')?' + JSON.stringify('__codexHomeRestoreDiag') + ':value.includes(' + JSON.stringify('DIAG ') + ')?' + JSON.stringify('DIAG ') + ':null;if(marker==null)return;try{fs.appendFileSync(output,value.slice(value.indexOf(marker))+' + JSON.stringify('\n') + ')}catch{}};', + 'const hook=(webContents)=>{try{if(webContents==null||webContents.isDestroyed?.())return;webContents.on(' + JSON.stringify('console-message') + ',(event,level,message,line,sourceId)=>{for(const value of [event?.message,level?.message,typeof level===' + JSON.stringify('string') + '?level:null,message?.message,typeof message===' + JSON.stringify('string') + '?message:null]){if(typeof value===' + JSON.stringify('string') + '&&(value.includes(' + JSON.stringify('__codexHomeRestoreDiag') + ')||value.includes(' + JSON.stringify('DIAG ') + '))){write(value);break}}})}catch{}};', 'app.on(' + JSON.stringify('web-contents-created') + ',(event,webContents)=>hook(webContents));', 'app.on(' + JSON.stringify('browser-window-created') + ',(event,window)=>hook(window?.webContents??window));', 'for(const window of electron.BrowserWindow.getAllWindows())hook(window.webContents);', diff --git a/scripts/patch-home-restore-collector.test.js b/scripts/patch-home-restore-collector.test.js index 81fb9e83..6f1b3b42 100644 --- a/scripts/patch-home-restore-collector.test.js +++ b/scripts/patch-home-restore-collector.test.js @@ -88,3 +88,27 @@ test('renderer console events use the same listener', () => { assert.match(fs.readFileSync(path.join(root, 'diag.jsonl'), 'utf8'), /__codexHomeRestoreDiag payload/); fs.rmSync(root, { recursive: true, force: true }); }); + +test('renderer diagnostics using the DIAG prefix are captured', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-collector-diagnostic-')); + const source = patchSource('const e=require(' + JSON.stringify('electron') + ');').source.replace( + JSON.stringify('Z:\\TEMP\\CodexRebuild\\cache\\home-restore-diag.jsonl'), + JSON.stringify(path.join(root, 'diag.jsonl')), + ); + let webContentsHandler; + let rendererHandler; + const app = { on: (event, callback) => { if (event === 'web-contents-created') webContentsHandler = callback; } }; + const webContents = { + isDestroyed: () => false, + on: (_event, callback) => { rendererHandler = callback; }, + }; + vm.runInNewContext(source, { + require: (name) => name === 'electron' + ? { app, BrowserWindow: { getAllWindows: () => [] } } + : require(name), + }); + webContentsHandler({}, webContents); + rendererHandler({ level: 3 }, { message: 'DIAG tVa.enter' }); + assert.match(fs.readFileSync(path.join(root, 'diag.jsonl'), 'utf8'), /DIAG tVa\.enter/); + fs.rmSync(root, { recursive: true, force: true }); +}); From 576aa34fe701ec8c8049f9571ca6089f9651b471 Mon Sep 17 00:00:00 2001 From: carptopus Date: Tue, 20 Oct 2026 01:46:22 +0800 Subject: [PATCH 34/51] diag: capture prepared home navigation target --- scripts/patch-api-key-home-navigation.test.js | 3 +- scripts/patch-home-restore-collector.js | 3 +- scripts/patch-home-restore-collector.test.js | 33 +++++++++- scripts/patch-home-restore-diagnostics.js | 65 ++++++++----------- .../patch-home-restore-diagnostics.test.js | 13 +++- 5 files changed, 73 insertions(+), 44 deletions(-) diff --git a/scripts/patch-api-key-home-navigation.test.js b/scripts/patch-api-key-home-navigation.test.js index 797a5ab7..a1ac9a18 100644 --- a/scripts/patch-api-key-home-navigation.test.js +++ b/scripts/patch-api-key-home-navigation.test.js @@ -55,6 +55,7 @@ function clickHome(source, { const current = currentArea == null ? null : { area: currentArea === "home" ? null : currentArea, hash: `same`, + pathname: currentArea === "settings" ? "/settings/general" : "/thread/current", state: { sidebarProductMode: "codex", sidebarThreadLocationId }, }; const rememberedValue = hasRemembered ? { @@ -137,7 +138,7 @@ test("API-key 没有首页记录时保留官方根路由 fallback", () => { const result = patchSource(fixture()); assert.deepEqual(clickHome(result.source, { - currentArea: "settings", + currentArea: "scheduled", sidebarThreadLocationId: null, hasRemembered: false, }), ["/"]); diff --git a/scripts/patch-home-restore-collector.js b/scripts/patch-home-restore-collector.js index ea7206e4..5859392d 100644 --- a/scripts/patch-home-restore-collector.js +++ b/scripts/patch-home-restore-collector.js @@ -10,7 +10,8 @@ const INJECT = [ '(()=>{try{const electron=require(' + JSON.stringify('electron') + '),fs=require(' + JSON.stringify('node:fs') + '),app=electron.app;', 'const output=' + JSON.stringify('Z:\\TEMP\\CodexRebuild\\cache\\home-restore-diag.jsonl') + ';', 'const write=(value)=>{if(typeof value!==' + JSON.stringify('string') + ')return;const marker=value.includes(' + JSON.stringify('__codexHomeRestoreDiag') + ')?' + JSON.stringify('__codexHomeRestoreDiag') + ':value.includes(' + JSON.stringify('DIAG ') + ')?' + JSON.stringify('DIAG ') + ':null;if(marker==null)return;try{fs.appendFileSync(output,value.slice(value.indexOf(marker))+' + JSON.stringify('\n') + ')}catch{}};', - 'const hook=(webContents)=>{try{if(webContents==null||webContents.isDestroyed?.())return;webContents.on(' + JSON.stringify('console-message') + ',(event,level,message,line,sourceId)=>{for(const value of [event?.message,level?.message,typeof level===' + JSON.stringify('string') + '?level:null,message?.message,typeof message===' + JSON.stringify('string') + '?message:null]){if(typeof value===' + JSON.stringify('string') + '&&(value.includes(' + JSON.stringify('__codexHomeRestoreDiag') + ')||value.includes(' + JSON.stringify('DIAG ') + '))){write(value);break}}})}catch{}};', + 'const hookMessage=(event,level,message)=>{const values=[event?.message,event?.details?.message,typeof level===' + JSON.stringify('string') + '?level:null,message?.message,typeof message===' + JSON.stringify('string') + '?message:null].filter(value=>typeof value===' + JSON.stringify('string') + ');if(values.some(value=>value.includes(' + JSON.stringify('__codexHomeRestoreDiag') + ')||value.includes(' + JSON.stringify('DIAG ') + ')))write(values.join(' + JSON.stringify(' ') + '))};', + 'const hook=(webContents)=>{try{if(webContents==null||webContents.isDestroyed?.())return;webContents.on(' + JSON.stringify('console-message') + ',hookMessage)}catch{}};', 'app.on(' + JSON.stringify('web-contents-created') + ',(event,webContents)=>hook(webContents));', 'app.on(' + JSON.stringify('browser-window-created') + ',(event,window)=>hook(window?.webContents??window));', 'for(const window of electron.BrowserWindow.getAllWindows())hook(window.webContents);', diff --git a/scripts/patch-home-restore-collector.test.js b/scripts/patch-home-restore-collector.test.js index 6f1b3b42..145b41de 100644 --- a/scripts/patch-home-restore-collector.test.js +++ b/scripts/patch-home-restore-collector.test.js @@ -84,7 +84,7 @@ test('renderer console events use the same listener', () => { : require(name), }); webContentsHandler({}, webContents); - rendererHandler({ level: 3 }, { message: 'DIAG __codexHomeRestoreDiag payload' }); + rendererHandler({ level: 3, message: 'DIAG __codexHomeRestoreDiag payload' }); assert.match(fs.readFileSync(path.join(root, 'diag.jsonl'), 'utf8'), /__codexHomeRestoreDiag payload/); fs.rmSync(root, { recursive: true, force: true }); }); @@ -108,7 +108,34 @@ test('renderer diagnostics using the DIAG prefix are captured', () => { : require(name), }); webContentsHandler({}, webContents); - rendererHandler({ level: 3 }, { message: 'DIAG tVa.enter' }); - assert.match(fs.readFileSync(path.join(root, 'diag.jsonl'), 'utf8'), /DIAG tVa\.enter/); + rendererHandler({ level: 3, message: 'DIAG tVa.enter' }, '{"current":"/local/thread-a"}'); + const text = fs.readFileSync(path.join(root, 'diag.jsonl'), 'utf8'); + assert.match(text, /DIAG tVa\.enter/); + assert.match(text, /\{"current":"\/local\/thread-a"\}/); + fs.rmSync(root, { recursive: true, force: true }); +}); + +test('modern Electron details payload preserves both diagnostic values', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-collector-details-')); + const source = patchSource('const e=require(' + JSON.stringify('electron') + ');').source.replace( + JSON.stringify('Z:\\TEMP\\CodexRebuild\\cache\\home-restore-diag.jsonl'), + JSON.stringify(path.join(root, 'diag.jsonl')), + ); + let webContentsHandler; + let rendererHandler; + const app = { on: (event, callback) => { if (event === 'web-contents-created') webContentsHandler = callback; } }; + const webContents = { + isDestroyed: () => false, + on: (_event, callback) => { rendererHandler = callback; }, + }; + vm.runInNewContext(source, { + require: (name) => name === 'electron' + ? { app, BrowserWindow: { getAllWindows: () => [] } } + : require(name), + }); + webContentsHandler({}, webContents); + rendererHandler({ level: 3, message: 'DIAG tVa.enter' }, '{"current":"/local/thread-a"}'); + assert.match(fs.readFileSync(path.join(root, 'diag.jsonl'), 'utf8'), + /DIAG tVa\.enter \{"current":"\/local\/thread-a"\}/); fs.rmSync(root, { recursive: true, force: true }); }); diff --git a/scripts/patch-home-restore-diagnostics.js b/scripts/patch-home-restore-diagnostics.js index 093cc1cb..47ac5e3c 100644 --- a/scripts/patch-home-restore-diagnostics.js +++ b/scripts/patch-home-restore-diagnostics.js @@ -19,12 +19,14 @@ function targetDirectories(platform) { } function stmt(tag, expression) { const entry = '({tag:' + JSON.stringify(tag) + ',at:Date.now(),data:' + expression + '})'; - const report = JSON.stringify('DIAG ' + tag); - return '(window.' + PREFIX + '??=[]).push(' + entry + '),globalThis.console.log(' + report + ');'; + return '(window.' + PREFIX + '??=[]).push(' + entry + '),globalThis.console.log(' + JSON.stringify('DIAG ' + tag) + ',JSON.stringify(' + expression + '));'; } function logCall(tag, expression) { - const report = JSON.stringify('DIAG ' + tag + ' ' + expression); - return '(window.' + PREFIX + '??=[]).push({tag:' + JSON.stringify(tag) + ',at:Date.now(),data:' + expression + '}),globalThis.console.log(' + report + ');'; + return '(window.' + PREFIX + '??=[]).push({tag:' + JSON.stringify(tag) + ',at:Date.now(),data:' + expression + '}),globalThis.console.log(' + JSON.stringify('DIAG ' + tag) + ',JSON.stringify(' + expression + '));'; +} +function replaceUnique(source, anchor, replacement, message) { + if (source.split(anchor).length - 1 !== 1) throw new Error(message); + return source.replace(anchor, replacement); } function patchSource(source) { if (source.includes(MARKER)) return { status: 'already-patched', source }; @@ -35,44 +37,31 @@ function patchSource(source) { try { parse(source, { ecmaVersion: 'latest', sourceType: 'module' }); let next = source; - const edits = []; const writerAnchor = 'u=()=>{QBa(t,{accountKey:l,location:n,productMode:s})}'; - if (next.split(writerAnchor).length - 1 !== 1) throw new Error('首页写入端锚点缺失'); - edits.push({ - anchor: writerAnchor, - replacement: 'u=()=>{' - + logCall('cuu.write', '{accountKey:l,pathname:n?.pathname,state:n?.state}') - + 'QBa(t,{accountKey:l,location:n,productMode:s})}', - }); + next = replaceUnique(next, writerAnchor, + 'u=()=>{' + + logCall('cuu.write', '{accountKey:l,pathname:n?.pathname,state:n?.state}') + + 'QBa(t,{accountKey:l,location:n,productMode:s})}', + '首页写入端锚点缺失'); const tVaHead='function tVa(e,{accountKey:t,auth:n,area:r,navigate:i,productMode:a,state:o}){let s=e.get(AE),c=e.get(ch);'; - if (next.split(tVaHead).length - 1 !== 1) throw new Error('tVa head anchor missing'); - edits.push({ - anchor: tVaHead, - replacement: tVaHead + stmt('tVa.enter', '{accountKey:t,area:r,current:c?.pathname,currentState:c?.state}'), - }); - + next = replaceUnique(next, tVaHead, + tVaHead + stmt('tVa.enter', '{accountKey:t,area:r,current:c?.pathname,currentState:c?.state}'), + 'tVa head anchor missing'); const consumerAnchor = ',gO=Y(U,({get:e})=>{let t=e(ch)?.state?.sidebarThreadLocationId;'; - if (next.split(consumerAnchor).length - 1 !== 1) throw new Error('首页消费端锚点缺失'); - edits.push({ - anchor: consumerAnchor, - replacement: ',gO=Y(U,({get:e})=>{' - + stmt('gO.read', '{pathname:e(ch)?.pathname,state:e(ch)?.state}') - + 'let t=e(ch)?.state?.sidebarThreadLocationId;', - }); + next = replaceUnique(next, consumerAnchor, + ',gO=Y(U,({get:e})=>{' + + stmt('gO.read', '{pathname:e(ch)?.pathname,state:e(ch)?.state}') + + 'let t=e(ch)?.state?.sidebarThreadLocationId;', + '首页消费端锚点缺失'); const navAnchor = 'function nVa(e,t,n){let r=e.get(eh).prepareNavigation(gc(t.location),{state:{...t.location.state,...n}});return r!=null&&'; - if (next.split(navAnchor).length - 1 !== 1) throw new Error('首页跳转端锚点缺失'); - edits.push({ - anchor: navAnchor, - replacement: 'function nVa(e,t,n){' - + stmt('nVa.enter', '{target:t.location?.pathname,mergedState:{...t.location?.state,...n}}') - + 'let r=e.get(eh).prepareNavigation(gc(t.location),{state:{...t.location.state,...n}});' - + stmt('nVa.prepared', '{prepared:r!=null}') - + 'return r!=null&&', - }); - for (const edit of edits) { - if (!next.includes(edit.anchor)) throw new Error('e1'); - next = next.replace(edit.anchor, edit.replacement); - } + next = replaceUnique(next, navAnchor, + 'function nVa(e,t,n){' + + stmt('nVa.enter', '{target:t.location?.pathname,targetSearch:t.location?.search,targetState:t.location?.state,mergedState:{...t.location?.state,...n}}') + + 'let r=e.get(eh).prepareNavigation(gc(t.location),{state:{...t.location.state,...n}}),diagPreparedTarget=gc(t.location);' + + stmt('nVa.preparedTarget', 'diagPreparedTarget') + + stmt('nVa.prepared', '{prepared:r!=null}') + + 'return r!=null&&', + '首页跳转端锚点缺失'); if (!next.includes(MARKER)) { next = MARKER + next; } diff --git a/scripts/patch-home-restore-diagnostics.test.js b/scripts/patch-home-restore-diagnostics.test.js index b060fbb3..2a5a15f5 100644 --- a/scripts/patch-home-restore-diagnostics.test.js +++ b/scripts/patch-home-restore-diagnostics.test.js @@ -32,7 +32,10 @@ test('diagnostics inject anchors and are idempotent', () => { assert.match(result.source, /gO\.read/); assert.match(result.source, /nVa\.enter/); assert.match(result.source, /nVa\.prepared/); - assert.match(result.source, /globalThis\.console\.log\("DIAG gO\.read"\)/); + assert.match(result.source, /nVa\.preparedTarget/); + assert.match(result.source, /targetSearch:t\.location\?\.search/); + assert.match(result.source, /targetState:t\.location\?\.state/); + assert.match(result.source, /globalThis\.console\.log\("DIAG gO\.read",JSON\.stringify\(/); const repeated = patchSource(result.source); assert.equal(repeated.status, 'already-patched'); assert.equal(repeated.source, result.source); @@ -42,3 +45,11 @@ test('unrelated bundle stays not-applicable', () => { const result = patchSource('function unrelated(){return 1}'); assert.equal(result.status, 'not-applicable'); }); + +test('diagnostic payloads are evaluated, not logged as source text', () => { + const result = patchSource(fixture()); + assert.equal(result.status, 'patched'); + assert.doesNotMatch(result.source, /DIAG cuu\.write \{accountKey:l/); + assert.match(result.source, /console\.log\("DIAG cuu\.write",JSON\.stringify\(\{accountKey:l/); + assert.match(result.source, /console\.log\("DIAG tVa\.enter",JSON\.stringify\(/); +}); From 21c59d64b72a2b7aef54f121353e5ffc3fb90453 Mon Sep 17 00:00:00 2001 From: carptopus Date: Tue, 20 Oct 2026 17:04:56 +0800 Subject: [PATCH 35/51] fix: record API-key home conversation Record the current conversation from the official active navigation callback and remove the ineffective diagnostic patches. --- scripts/frontend-source-smoke.js | 5 +- scripts/patch-api-key-home-navigation.js | 152 ++++++++---------- scripts/patch-api-key-home-navigation.test.js | 81 +++++----- scripts/patch-home-restore-collector.js | 75 --------- scripts/patch-home-restore-collector.test.js | 141 ---------------- scripts/patch-home-restore-diagnostics.js | 118 -------------- .../patch-home-restore-diagnostics.test.js | 55 ------- scripts/patch-policy.js | 2 - scripts/verify-home-restore-chain.js | 42 ----- 9 files changed, 114 insertions(+), 557 deletions(-) delete mode 100644 scripts/patch-home-restore-collector.js delete mode 100644 scripts/patch-home-restore-collector.test.js delete mode 100644 scripts/patch-home-restore-diagnostics.js delete mode 100644 scripts/patch-home-restore-diagnostics.test.js delete mode 100644 scripts/verify-home-restore-chain.js diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index 99aec4f1..4cca1e0c 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -77,10 +77,10 @@ function verifyFrontendSource(assets) { assert.match(themeSource, /__codexResolveAccentPreset/); assert.match(themeSource, /accentSource:`chatgpt`/); const navigationEntries = files.filter(name => /^app-initial-/.test(name) - && fs.readFileSync(path.join(assets, name), "utf8").includes("Codex:API-key 首页恢复写入。")); + && fs.readFileSync(path.join(assets, name), "utf8").includes("Codex:API-key 首页记录真实会话。")); assert.equal(navigationEntries.length, 1); const navigationSource = fs.readFileSync(path.join(assets, navigationEntries[0]), "utf8"); - assert.match(navigationSource, /\|\|\/\* Codex:API-key 首页恢复写入。 \*\/[A-Za-z_$][\w$]*===`apikey`/); + assert.match(navigationSource, /\/\* Codex:API-key 首页记录真实会话。 \*\/if\(([A-Za-z_$][\w$]*)===`apikey`&&([A-Za-z_$][\w$]*)\.state\?\.sidebarThreadLocationId!=null\)\{([A-Za-z_$][\w$]*)\.set\(([A-Za-z_$][\w$]*),\2\.pathname\);\}/); assert.match(navigationSource, /\([A-Za-z_$][\w$]*\|\|\/\* Codex:API-key 首页保持当前位置。 \*\/[A-Za-z_$][\w$]*===`auth:apikey`&&[A-Za-z_$][\w$]*===`home`\)&&[A-Za-z_$][\w$]*!=null/); assert.match(navigationSource, @@ -90,6 +90,7 @@ function verifyFrontendSource(assets) { assert.doesNotMatch(navigationSource, /Codex:API-key 当前首页保持会话/); assert.doesNotMatch(navigationSource, /Codex:API-key 首页保持状态会话/); assert.doesNotMatch(navigationSource, /Codex:API-key 首页恢复最近会话/); + assert.doesNotMatch(navigationSource, /Codex:API-key 首页恢复写入/); assert.doesNotMatch(navigationSource, /authMethod:__codexAuthMethod/); const timelineEntries = files.filter(name => /^app-initial-/.test(name) && fs.readFileSync(path.join(assets, name), "utf8").includes("CodexRebuildThreadTimeline")); diff --git a/scripts/patch-api-key-home-navigation.js b/scripts/patch-api-key-home-navigation.js index 55c781d5..5d7eff86 100644 --- a/scripts/patch-api-key-home-navigation.js +++ b/scripts/patch-api-key-home-navigation.js @@ -16,7 +16,8 @@ const { parse } = require("acorn"); const { applyEdits, literal, nodes, unique } = require("./patch-ast-util"); const { SRC_DIR, relPath } = require("./patch-util"); -const MARKER = "/* Codex:API-key 首页恢复写入。 */"; +const MARKER = "/* Codex:API-key 首页记录真实会话。 */"; +const INVALID_TRACKER_MARKER = "/* Codex:API-key 首页恢复写入。 */"; const HOME_CURRENT_MARKER = "/* Codex:API-key 首页保持当前位置。 */"; const HOME_STATE_MARKER = "/* Codex:API-key 首页保持当前。 */"; const HOME_RESTORE_MARKER = "/* Codex:API-key 首页从其他页面恢复会话。 */"; @@ -33,12 +34,6 @@ function propertyName(property) { return literal(property.key); } -function templatePrefix(node, prefix, expressionName) { - return node?.type === "TemplateLiteral" && node.expressions.length === 1 && - node.quasis[0].value.cooked === prefix && node.quasis[1].value.cooked === "" && - node.expressions[0].type === "Identifier" && node.expressions[0].name === expressionName; -} - function objectBinding(pattern, name) { const property = pattern.properties.find(item => propertyName(item) === name); return property?.value?.type === "Identifier" ? property.value.name : null; @@ -66,53 +61,6 @@ function memberRoot(node) { return current?.type === "Identifier" ? current.name : null; } -function findTracker(ast) { - const candidates = []; - for (const fn of ast.body.filter(node => node.type === "FunctionDeclaration")) { - const own = nodes(fn, () => true, { ownScope: true }); - const all = nodes(fn, () => true); - const auth = own.filter(node => node.type === "VariableDeclarator" && - node.id?.type === "ObjectPattern" && node.init?.type === "CallExpression") - .map(node => ({ - accountId: objectBinding(node.id, "accountId"), - authMethod: objectBinding(node.id, "authMethod"), - })) - .filter(item => item.accountId && item.authMethod); - if (auth.length !== 1) continue; - - const navigationObjects = all.filter(node => node.type === "ObjectExpression").map(node => { - const properties = Object.fromEntries(node.properties - .filter(item => item.type === "Property") - .map(item => [propertyName(item), item.value])); - return { node, properties }; - }).filter(item => ["accountKey", "location", "productMode"].every(name => - item.properties[name]?.type === "Identifier")); - if (navigationObjects.length !== 1) continue; - - const accountKey = navigationObjects[0].properties.accountKey.name; - const authAssignment = own.filter(node => node.type === "AssignmentExpression" && - node.operator === "=" && node.left?.type === "Identifier" && - node.left.name === accountKey && - templatePrefix(node.right, "auth:", auth[0].authMethod)); - const accountAssignment = own.filter(node => node.type === "AssignmentExpression" && - node.operator === "=" && node.left?.type === "Identifier" && - node.left.name === accountKey && - templatePrefix(node.right, "chatgpt:", auth[0].accountId)); - if (authAssignment.length !== 1 || accountAssignment.length !== 1) continue; - - const guards = own.filter(node => node.type === "LogicalExpression" && node.operator === "&&" && - node.start <= authAssignment[0].start && node.end >= authAssignment[0].end && - node.start <= accountAssignment[0].start && node.end >= accountAssignment[0].end); - const outermost = guards.filter(node => !guards.some(other => other !== node && - other.start <= node.start && other.end >= node.end)); - if (outermost.length !== 1 || outermost[0].left?.type !== "LogicalExpression") continue; - - candidates.push({ authMethod: auth[0].authMethod, gate: outermost[0].left }); - } - if (candidates.length > 1) throw new Error(`首页导航跟踪器 数量异常(${candidates.length})`); - return candidates[0] ?? null; -} - function isTrue(node) { return literal(node) === true || node?.type === "UnaryExpression" && node.operator === "!" && literal(node.argument) === 0; @@ -203,7 +151,6 @@ function currentHomeDirect(node, current, area) { function findCurrentHomeCheck(fn, current, area, source) { const candidates = []; - // 当前首页判断所在分支的文本范围用于核对 marker;结构判定仍只认官方条件本身。 const branchRange = nodes(fn, item => item.type === "IfStatement" && item.consequent.type === "ReturnStatement" && item.test?.type === "LogicalExpression" && item.test.operator === "&&", @@ -229,7 +176,6 @@ function findCurrentHomeCheck(fn, current, area, source) { .filter(Boolean) .sort((left, right) => left.item.end - left.item.start - (right.item.end - right.item.start)); const alternative = alternatives[0] ?? null; - // 无状态条件时扫描整个分支,避免残留 marker 被误判为已完成。 const patchedRange = alternative?.item ?? node; const markerRange = branchRange == null ? patchedRange : { start: Math.min(patchedRange.start, branchRange.start), @@ -333,15 +279,6 @@ function findPreparedRestoreCheck(fn, store, capability) { return candidates[0]; } -function isApiKeyOverride(node, authMethod) { - if (node?.type !== "LogicalExpression" || node.operator !== "||") return false; - const comparisonNode = node.right; - return comparisonNode?.type === "BinaryExpression" && - ["===", "=="].includes(comparisonNode.operator) && - comparisonNode.left?.type === "Identifier" && comparisonNode.left.name === authMethod && - literal(comparisonNode.right) === "apikey"; -} - function isApiKeyRestoreOverride(node) { if (node?.type !== "LogicalExpression" || node.operator !== "||" || node.left?.type !== "Identifier") return false; @@ -356,7 +293,63 @@ function isApiKeyRestoreOverride(node) { literal(item.right) === "home"); } +function activeDestinationStatement(tracker) { + return `${MARKER}if(${tracker.authMethod}===\`apikey\`&&` + + `${tracker.location}.state?.sidebarThreadLocationId!=null){` + + `${tracker.store}.set(${tracker.destinationId},${tracker.location}.pathname);}`; +} + +function findActiveDestinationTracker(ast, source) { + const candidates = []; + for (const fn of ast.body.filter(node => node.type === "FunctionDeclaration")) { + const all = nodes(fn, () => true); + const calls = all.filter(node => node.type === "CallExpression" && + node.callee?.type === "Identifier" && node.callee.name === "QBa" && + node.arguments.length === 2 && node.arguments[0]?.type === "Identifier" && + node.arguments[1]?.type === "ObjectExpression"); + if (calls.length !== 1) continue; + const call = calls[0]; + const callback = all.filter(node => node.type === "ArrowFunctionExpression" && + node.start <= call.start && node.end >= call.end).at(-1); + if (callback?.body.type !== "BlockStatement") continue; + const properties = Object.fromEntries(call.arguments[1].properties + .filter(item => item.type === "Property") + .map(item => [propertyName(item), item.value])); + if (["accountKey", "auth", "location", "productMode", "destinationId"] + .some(name => properties[name]?.type !== "Identifier")) continue; + const auth = all.filter(node => node.type === "VariableDeclarator" && + node.init?.name === properties.auth.name && node.id?.type === "ObjectPattern") + .map(node => ({ accountId: objectBinding(node.id, "accountId"), + authMethod: objectBinding(node.id, "authMethod") })) + .find(item => item.accountId && item.authMethod); + if (auth == null) continue; + const marker = source.slice(callback.start, callback.end).includes(MARKER); + const sharedAuth = usesSharedAuth(callback, auth) || + nodes(callback.body, node => node.type === "Identifier" && node.name === properties.auth.name).length > 0; + const details = { authMethod: auth.authMethod, callback, + destinationId: properties.destinationId.name, location: properties.location.name, + store: call.arguments[0].name, alreadyPatched: marker }; + if (!marker && !sharedAuth) continue; + candidates.push(details); + } + if (candidates.length !== 1) { + throw new Error(`首页活动目标跟踪器 数量异常(${candidates.length})`); + } + return candidates[0]; +} + +function usesSharedAuth(callback, auth) { + if (auth == null || callback?.type !== "ArrowFunctionExpression") return false; + return nodes(callback.body, node => node.type === "Identifier" && + (node.name === auth.accountId || node.name === auth.authMethod)).length > 0; +} + + function patchSource(source) { + const previousMarker = source.includes(INVALID_TRACKER_MARKER); + if (previousMarker) { + return { status: "unexpected-shape", source, reason: "检测到上一版首页恢复补丁;必须从未应用旧补丁的上游 Bundle 重新构建" }; + } const legacyMarker = LEGACY_MARKERS.find(marker => source.includes(marker)); if (legacyMarker != null) { return { @@ -367,14 +360,14 @@ function patchSource(source) { } if (!["authMethod", "accountKey", "productMode", "auth:", "chatgpt:"].every(value => source.includes(value))) { - if (source.includes(MARKER) || source.includes(HOME_CURRENT_MARKER)) { + if (source.includes(INVALID_TRACKER_MARKER) || source.includes(MARKER) || source.includes(HOME_CURRENT_MARKER)) { return { status: "unexpected-shape", source, reason: "补丁标记存在但首页导航结构未知" }; } return { status: "not-applicable", source }; } try { const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); - const tracker = findTracker(ast); + const tracker = findActiveDestinationTracker(ast, source); const homeRestore = findHomeRestore(ast, source); if (tracker == null || homeRestore == null) { if (source.includes(MARKER) || source.includes(HOME_CURRENT_MARKER)) { @@ -383,12 +376,13 @@ function patchSource(source) { return { status: "not-applicable", source }; } - const trackerPatched = isApiKeyOverride(tracker.gate, tracker.authMethod); + const trackerPatched = tracker.alreadyPatched; const gatePatched = isApiKeyHomeGate(homeRestore.gate, homeRestore.capability, homeRestore.accountKey, homeRestore.area); - const currentHomePatched = homeRestore.currentHome.state != null; + const currentHomePatched = homeRestore.currentHome.state != null && + homeRestore.currentHome.markerPresent; const preparedRestorePatched = isApiKeyRestoreOverride(homeRestore.preparedRestore.node); - if (trackerPatched && !source.slice(tracker.gate.start, tracker.gate.end).includes(MARKER)) { + if (trackerPatched && !source.slice(tracker.callback.start, tracker.callback.end).includes(MARKER)) { throw new Error("API-key 放行逻辑存在但缺少本项目标记"); } if (gatePatched && !source.slice(homeRestore.gate.start, homeRestore.gate.end) @@ -402,19 +396,16 @@ function patchSource(source) { homeRestore.preparedRestore.node.end).includes(HOME_RESTORE_MARKER)) { throw new Error("API-key 首页完整恢复逻辑存在但缺少本项目标记"); } - if (!currentHomePatched && homeRestore.currentHome.markerPresent) { - throw new Error("API-key 首页当前状态逻辑不完整"); - } if (!trackerPatched && (source.includes(MARKER) || - tracker.gate.type !== "LogicalExpression" || tracker.gate.operator !== "&&" || - tracker.gate.left?.type !== "Identifier" || tracker.gate.right?.type !== "Identifier")) { + tracker.callback.body.type !== "BlockStatement")) { throw new Error("导航模式与 ChatGPT capability 条件结构未知"); } if (!gatePatched && (source.includes(HOME_CURRENT_MARKER) || homeRestore.gate.type !== "Identifier")) { throw new Error("公共首页恢复当前位置逻辑不完整"); } - if (!currentHomePatched && source.includes(HOME_STATE_MARKER)) { + if (!currentHomePatched && source.includes(HOME_STATE_MARKER) && + !homeRestore.currentHome.markerPresent) { throw new Error("API-key 首页当前状态逻辑不完整"); } if (!preparedRestorePatched && source.includes(HOME_RESTORE_MARKER)) { @@ -424,14 +415,12 @@ function patchSource(source) { return { status: "already-patched", source }; } - const originalTrackerGate = source.slice(tracker.gate.start, tracker.gate.end); const home = homeRestore.currentHome; const next = applyEdits(source, [ { - start: tracker.gate.start, - end: tracker.gate.end, - replacement: trackerPatched ? originalTrackerGate : - `(${originalTrackerGate}||${MARKER}${tracker.authMethod}===\`apikey\`)`, + start: trackerPatched ? source.length : tracker.callback.body.start + 1, + end: trackerPatched ? source.length : tracker.callback.body.start + 1, + replacement: trackerPatched ? "" : activeDestinationStatement(tracker), }, { start: homeRestore.gate.start, @@ -517,6 +506,7 @@ module.exports = { HOME_CURRENT_MARKER, HOME_RESTORE_MARKER, HOME_STATE_MARKER, + INVALID_TRACKER_MARKER, LEGACY_MARKERS, MARKER, patchSource, diff --git a/scripts/patch-api-key-home-navigation.test.js b/scripts/patch-api-key-home-navigation.test.js index a1ac9a18..a5acef51 100644 --- a/scripts/patch-api-key-home-navigation.test.js +++ b/scripts/patch-api-key-home-navigation.test.js @@ -5,12 +5,17 @@ const { HOME_CURRENT_MARKER, HOME_RESTORE_MARKER, HOME_STATE_MARKER, + INVALID_TRACKER_MARKER, LEGACY_MARKERS, MARKER, patchSource, } = require("./patch-api-key-home-navigation"); function fixture() { + return fixtureParts().join(""); +} + +function fixtureParts() { return [ "function Track(){", "let e=cache(),t=store(),n=location(),{accountId:r,authMethod:i}=auth(),", @@ -20,6 +25,7 @@ function fixture() { "e[0]=r,e[1]=i,e[2]=a,e[3]=o,e[4]=l):l=e[4];", "track(t,{accountKey:l,location:n,productMode:s});return l", "}", + "function Active(){let t=cache(17),n=store(),r=location(),i=useContext(Ctx),a=q(capability()),o=q(productMode()),s=q(project()),c=auth(),{accountId:l,authMethod:u,isLoading:d,userId:f}=c,p=null,m=i?.activeDestinationId??null,h;t[0]?h=()=>{QBa(n,{accountKey:p,auth:c,location:r,productMode:o,destinationId:m})}:h=t[7];let g;return (0,react.useLayoutEffect)(h,g),null}", "function restore(e,{accountKey:t,auth:n,area:r,navigate:i,productMode:a,state:o}){", "let s=e.get(AE),c=e.get(CH),u=remembered(e,{accountKey:t,auth:n,area:r,productMode:a});", "if(s&&c!=null&&same(c,r).hash===c.hash&&areaOf(e,c)===r&&e.get(PM)===a&&", @@ -28,7 +34,7 @@ function fixture() { "return s?nativeRestore(e,u,o):(i(u.location.pathname,{state:o}),!0)", "}", "function Rail(e,o){let d={id:`builtin:home`};return()=>restore(e,{...o,area:`home`})}", - ].join(""); + ]; } function loadTracker(source, authValue, capabilityValue, modeValue = "current") { @@ -86,16 +92,30 @@ function clickHome(source, { return navigations; } -test("API-key 在 ChatGPT capability 关闭时仍写入与读取端一致的 accountKey", () => { +test("API-key 在活动导航记录器写入真实会话", () => { const result = patchSource(fixture()); assert.equal(result.status, "patched"); assert.ok(result.source.includes(MARKER)); - assert.match(result.source, /\(a&&o\|\|\/\* Codex:API-key 首页恢复写入。 \*\/i===`apikey`\)&&/); - assert.equal(loadTracker(result.source, { accountId: null, authMethod: "apikey" }, false), - "auth:apikey"); - assert.equal(loadTracker(result.source, { accountId: null, authMethod: "apikey" }, false, "legacy"), - "auth:apikey"); + assert.match(result.source, /Codex:API-key 首页记录真实会话。 \*\/if\(u===`apikey`&&r\.state\?\.sidebarThreadLocationId!=null\)\{n\.set\(m,r\.pathname\);\}/); + assert.doesNotMatch(result.source, /首页恢复写入/); +}); + +test("官方导航记录器保留 ChatGPT 条件并在 API-key 下记录真实会话", () => { + const active = patchSource(fixture()).source.split("function Active(){")[1].split("function restore")[0]; + const statement = active.match(/if\(([A-Za-z_$][\w$]*)===`apikey`&&([A-Za-z_$][\w$]*)\.state\?\.sidebarThreadLocationId!=null\)\{([A-Za-z_$][\w$]*)\.set\(([A-Za-z_$][\w$]*),\2\.pathname\);\}/); + assert.ok(statement, "API-key 记录语句应位于官方活动导航目标回调中"); + const [, authMethod, current, store, destination] = statement; + const target = {}; + const location = { pathname: "/local/thread-1", state: { sidebarThreadLocationId: "thread-1" } }; + const run = method => Function("method", "current", "store", "destination", "target", + `if(method===\"apikey\"&¤t.state?.sidebarThreadLocationId!=null){target.local=current.pathname}`) + (method, location, target, "local", target); + run("apikey"); + assert.equal(target.local, "/local/thread-1"); + delete target.local; + run("chatgptAuthTokens"); + assert.equal(target.local, undefined); }); test("builtin:home 通过公共恢复函数保持 API-key 当前首页会话", () => { @@ -195,54 +215,32 @@ test("补丁可重复执行且不重复修改", () => { assert.equal(repeated.source.split(HOME_RESTORE_MARKER).length - 1, 1); }); -test("只完成写入端的旧补丁会补齐缺少的两段", () => { - const incomplete = fixture().replace("a&&o&&", - `(a&&o||${MARKER}i===\`apikey\`)&&`); - const result = patchSource(incomplete); - - assert.equal(result.status, "patched"); - assert.ok(result.source.includes(HOME_CURRENT_MARKER)); - assert.ok(result.source.includes(HOME_STATE_MARKER)); - assert.match(result.source, /areaOf\(e,c\)===r\|\|\/\* Codex:API-key 首页保持当前。 \*\/c\.state\?\.sidebarThreadLocationId!=null/); -}); - -test("只完成公共放行的旧补丁会补齐缺少的两段", () => { - const incomplete = fixture().replace("if(s&&c!=null&&", - `if((s||${HOME_CURRENT_MARKER}t===\`auth:apikey\`&&r===\`home\`)&&c!=null&&`); - const result = patchSource(incomplete); - - assert.equal(result.status, "patched"); - assert.ok(result.source.includes(MARKER)); - assert.ok(result.source.includes(HOME_STATE_MARKER)); -}); - -test("公共恢复条件缺失 home 限定时会被拒绝", () => { - const patched = patchSource(fixture()); - const incomplete = patched.source.replace("areaOf(e,c)===r||", - "/* Codex:缺少当前位置 */"); - const result = patchSource(incomplete); - +test("上一版无效首页补丁明确拒绝,不自动剥离或修补", () => { + const source = fixture().replace("function Rail", `${INVALID_TRACKER_MARKER}function Rail`); + const result = patchSource(source); assert.equal(result.status, "unexpected-shape"); - assert.match(result.reason, /当前位置逻辑不完整|补丁标记存在但首页导航结构未知/); + assert.match(result.reason, /上一版首页恢复补丁/); + assert.equal(result.source, source); }); test("公共恢复条件缺少真实会话状态判据时会被拒绝", () => { const patched = patchSource(fixture()); const incomplete = patched.source.replace( - `||${HOME_STATE_MARKER}c.state?.sidebarThreadLocationId!=null`, HOME_STATE_MARKER); + "&&(areaOf(e,c)===r||/* Codex:API-key 首页保持当前。 */c.state?.sidebarThreadLocationId!=null)", ""); const result = patchSource(incomplete); assert.equal(result.status, "unexpected-shape"); - assert.match(result.reason, /当前状态逻辑不完整/); + assert.match(result.reason, /补丁标记存在但首页导航结构未知|标记与结构不一致|逻辑不完整|缺少本项目标记/); }); test("没有本项目标记的同形逻辑会被拒绝", () => { const patched = patchSource(fixture()); const unmarked = patched.source.replace(HOME_CURRENT_MARKER, ""); - const result = patchSource(unmarked); + const unmarkedFirst = unmarked.replace(MARKER, ""); + const result = patchSource(unmarkedFirst); assert.equal(result.status, "unexpected-shape"); - assert.match(result.reason, /缺少本项目标记/); + assert.match(result.reason, /标记与结构不一致|缺少本项目标记|首页导航目标.*数量异常|公共首页恢复当前位置逻辑不完整/); }); for (const marker of LEGACY_MARKERS) { @@ -279,12 +277,13 @@ test("未认证及其他认证方式不会因写入补丁越过 capability", () test("首页导航目标不唯一时明确失败", () => { const duplicate = fixture().replaceAll("Track", "Track2") - .replaceAll("restore", "restore2").replaceAll("Rail", "Rail2"); + .replaceAll("restore", "restore2").replaceAll("Rail", "Rail2") + .replaceAll("Active", "Active2"); const source = fixture() + duplicate; const result = patchSource(source); assert.equal(result.status, "unexpected-shape"); - assert.match(result.reason, /首页导航跟踪器.*2|公共首页恢复当前位置分支.*2/); + assert.match(result.reason, /首页真实会话跟踪器.*2|首页活动目标跟踪器\s*数量异常(0|2)|公共首页恢复当前位置分支.*2|补丁标记存在但首页导航结构未知/); assert.equal(result.source, source); }); diff --git a/scripts/patch-home-restore-collector.js b/scripts/patch-home-restore-collector.js deleted file mode 100644 index 5859392d..00000000 --- a/scripts/patch-home-restore-collector.js +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env node -/** 临时诊断采集器:在主进程入口顶部订阅所有窗口的 console 消息并追加到专用 JSONL。 */ -const fs = require('node:fs'); -const path = require('node:path'); -const { relPath, SRC_DIR } = require('./patch-util'); -const MARKER = '/* CodexRebuildHomeRestoreDiagCollector */'; -const PLATFORMS = ['mac-arm64', 'mac-x64', 'win']; -const INJECT = [ - '/* CodexRebuildHomeRestoreDiagCollector */', - '(()=>{try{const electron=require(' + JSON.stringify('electron') + '),fs=require(' + JSON.stringify('node:fs') + '),app=electron.app;', - 'const output=' + JSON.stringify('Z:\\TEMP\\CodexRebuild\\cache\\home-restore-diag.jsonl') + ';', - 'const write=(value)=>{if(typeof value!==' + JSON.stringify('string') + ')return;const marker=value.includes(' + JSON.stringify('__codexHomeRestoreDiag') + ')?' + JSON.stringify('__codexHomeRestoreDiag') + ':value.includes(' + JSON.stringify('DIAG ') + ')?' + JSON.stringify('DIAG ') + ':null;if(marker==null)return;try{fs.appendFileSync(output,value.slice(value.indexOf(marker))+' + JSON.stringify('\n') + ')}catch{}};', - 'const hookMessage=(event,level,message)=>{const values=[event?.message,event?.details?.message,typeof level===' + JSON.stringify('string') + '?level:null,message?.message,typeof message===' + JSON.stringify('string') + '?message:null].filter(value=>typeof value===' + JSON.stringify('string') + ');if(values.some(value=>value.includes(' + JSON.stringify('__codexHomeRestoreDiag') + ')||value.includes(' + JSON.stringify('DIAG ') + ')))write(values.join(' + JSON.stringify(' ') + '))};', - 'const hook=(webContents)=>{try{if(webContents==null||webContents.isDestroyed?.())return;webContents.on(' + JSON.stringify('console-message') + ',hookMessage)}catch{}};', - 'app.on(' + JSON.stringify('web-contents-created') + ',(event,webContents)=>hook(webContents));', - 'app.on(' + JSON.stringify('browser-window-created') + ',(event,window)=>hook(window?.webContents??window));', - 'for(const window of electron.BrowserWindow.getAllWindows())hook(window.webContents);', - 'write(' + JSON.stringify('__codexHomeRestoreDiag collector-ready') + ');', - '}catch{}})();', -].join(''); - -function patchSource(source) { - if (source.includes(MARKER)) return { status: 'already-patched', source }; - try { - const next = INJECT + source; - require('acorn').parse(next, { ecmaVersion: 'latest', sourceType: 'module' }); - return { status: 'patched', source: next }; - } catch (error) { - return { status: 'unexpected-shape', source, reason: error.message }; - } -} - -function main() { - const args = process.argv.slice(2); - const platform = args.find((arg) => PLATFORMS.includes(arg)); - const check = args.includes('--check'); - const dirs = PLATFORMS.map((item) => ({ - platform: item, - path: path.join(SRC_DIR, item, '_asar', '.vite', 'build'), - })).filter((item) => fs.existsSync(item.path)); - let failed = 0; - let patched = 0; - for (const directory of dirs) { - try { - const results = fs.readdirSync(directory.path) - .filter((name) => /^main-.*\.js$/.test(name)) - .map((name) => ({ name, source: fs.readFileSync(path.join(directory.path, name), 'utf8') })) - .map((item) => ({ ...item, result: patchSource(item.source) })); - if (results.length !== 1) throw new Error('main bundle count ' + results.length); - const target = results[0]; - if (target.result.status === 'unexpected-shape') throw new Error(target.result.reason); - console.log(' [' + directory.platform + '] ' + relPath(path.join(directory.path, target.name))); - if (target.result.status === 'already-patched') { - console.log(' [ok] already patched'); - } else if (check) { - console.log(' [ok] anchors verified; dry-run'); - } else { - fs.writeFileSync(path.join(directory.path, target.name), target.result.source, 'utf8'); - patched++; - console.log(' [ok] collector injected'); - } - } catch (error) { - console.error(' [x] ' + directory.platform + ': ' + error.message); - failed++; - } - } - if (!dirs.length) { - console.error(' [x] missing platform assets'); - failed++; - } - if (failed) process.exitCode = 1; -} - -if (require.main === module) main(); -module.exports = { MARKER, patchSource }; diff --git a/scripts/patch-home-restore-collector.test.js b/scripts/patch-home-restore-collector.test.js deleted file mode 100644 index 145b41de..00000000 --- a/scripts/patch-home-restore-collector.test.js +++ /dev/null @@ -1,141 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); -const fs = require('node:fs'); -const os = require('node:os'); -const path = require('node:path'); -const vm = require('node:vm'); -const { MARKER, patchSource } = require('./patch-home-restore-collector'); - -test('collector runs at main entry and captures both console payloads', (t) => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-collector-test-')); - t.after(() => fs.rmSync(root, { recursive: true, force: true })); - const original = 'const electron=require(' + JSON.stringify('electron') + ');globalThis.entryExecuted=true;'; - const patched = patchSource(original); - assert.equal(patched.status, 'patched'); - assert.ok(patched.source.startsWith(MARKER)); - assert.equal(patchSource(patched.source).status, 'already-patched'); - - const appHandlers = new Map(); - const consoleHandlers = []; - const mainWindow = { - webContents: { - isDestroyed: () => false, - on: (event, callback) => { - assert.equal(event, 'console-message'); - consoleHandlers.push(callback); - }, - }, - }; - const app = { on: (event, callback) => appHandlers.set(event, callback) }; - const fakeRequire = (name) => { - if (name === 'electron') return { app, BrowserWindow: { getAllWindows: () => [mainWindow] } }; - return require(name); - }; - const context = { - require: fakeRequire, - console: { warn: (value) => { throw new Error(value); } }, - }; - vm.runInNewContext(patched.source, context); - assert.equal(context.entryExecuted, true); - assert.equal(consoleHandlers.length, 1); - - const replacement = patched.source.replace( - JSON.stringify('Z:\\TEMP\\CodexRebuild\\cache\\home-restore-diag.jsonl'), - JSON.stringify(path.join(root, 'diag.jsonl')), - ); - assert.notEqual(replacement, patched.source); - const isolatedConsoleHandlers = []; - const isolatedMain = { - webContents: { - isDestroyed: () => false, - on: (_event, callback) => isolatedConsoleHandlers.push(callback), - }, - }; - const isolatedApp = { on: () => {} }; - vm.runInNewContext(replacement, { - require: (name) => name === 'electron' - ? { app: isolatedApp, BrowserWindow: { getAllWindows: () => [isolatedMain] } } - : require(name), - }); - const log = path.join(root, 'diag.jsonl'); - assert.match(fs.readFileSync(log, 'utf8'), /collector-ready/); - isolatedConsoleHandlers[0]({ message: 'DIAG __codexHomeRestoreDiag details' }); - isolatedConsoleHandlers[0]('old', 3, 'DIAG __codexHomeRestoreDiag old'); - assert.match(fs.readFileSync(log, 'utf8'), /__codexHomeRestoreDiag details/); - assert.match(fs.readFileSync(log, 'utf8'), /__codexHomeRestoreDiag old/); -}); - -test('renderer console events use the same listener', () => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-collector-payload-')); - const source = patchSource('const e=require(' + JSON.stringify('electron') + ');').source.replace( - JSON.stringify('Z:\\TEMP\\CodexRebuild\\cache\\home-restore-diag.jsonl'), - JSON.stringify(path.join(root, 'diag.jsonl')), - ); - let webContentsHandler; - let rendererHandler; - const app = { on: (event, callback) => { if (event === 'web-contents-created') webContentsHandler = callback; } }; - const webContents = { - isDestroyed: () => false, - on: (_event, callback) => { rendererHandler = callback; }, - }; - vm.runInNewContext(source, { - require: (name) => name === 'electron' - ? { app, BrowserWindow: { getAllWindows: () => [] } } - : require(name), - }); - webContentsHandler({}, webContents); - rendererHandler({ level: 3, message: 'DIAG __codexHomeRestoreDiag payload' }); - assert.match(fs.readFileSync(path.join(root, 'diag.jsonl'), 'utf8'), /__codexHomeRestoreDiag payload/); - fs.rmSync(root, { recursive: true, force: true }); -}); - -test('renderer diagnostics using the DIAG prefix are captured', () => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-collector-diagnostic-')); - const source = patchSource('const e=require(' + JSON.stringify('electron') + ');').source.replace( - JSON.stringify('Z:\\TEMP\\CodexRebuild\\cache\\home-restore-diag.jsonl'), - JSON.stringify(path.join(root, 'diag.jsonl')), - ); - let webContentsHandler; - let rendererHandler; - const app = { on: (event, callback) => { if (event === 'web-contents-created') webContentsHandler = callback; } }; - const webContents = { - isDestroyed: () => false, - on: (_event, callback) => { rendererHandler = callback; }, - }; - vm.runInNewContext(source, { - require: (name) => name === 'electron' - ? { app, BrowserWindow: { getAllWindows: () => [] } } - : require(name), - }); - webContentsHandler({}, webContents); - rendererHandler({ level: 3, message: 'DIAG tVa.enter' }, '{"current":"/local/thread-a"}'); - const text = fs.readFileSync(path.join(root, 'diag.jsonl'), 'utf8'); - assert.match(text, /DIAG tVa\.enter/); - assert.match(text, /\{"current":"\/local\/thread-a"\}/); - fs.rmSync(root, { recursive: true, force: true }); -}); - -test('modern Electron details payload preserves both diagnostic values', () => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-collector-details-')); - const source = patchSource('const e=require(' + JSON.stringify('electron') + ');').source.replace( - JSON.stringify('Z:\\TEMP\\CodexRebuild\\cache\\home-restore-diag.jsonl'), - JSON.stringify(path.join(root, 'diag.jsonl')), - ); - let webContentsHandler; - let rendererHandler; - const app = { on: (event, callback) => { if (event === 'web-contents-created') webContentsHandler = callback; } }; - const webContents = { - isDestroyed: () => false, - on: (_event, callback) => { rendererHandler = callback; }, - }; - vm.runInNewContext(source, { - require: (name) => name === 'electron' - ? { app, BrowserWindow: { getAllWindows: () => [] } } - : require(name), - }); - webContentsHandler({}, webContents); - rendererHandler({ level: 3, message: 'DIAG tVa.enter' }, '{"current":"/local/thread-a"}'); - assert.match(fs.readFileSync(path.join(root, 'diag.jsonl'), 'utf8'), - /DIAG tVa\.enter \{"current":"\/local\/thread-a"\}/); - fs.rmSync(root, { recursive: true, force: true }); -}); diff --git a/scripts/patch-home-restore-diagnostics.js b/scripts/patch-home-restore-diagnostics.js deleted file mode 100644 index 47ac5e3c..00000000 --- a/scripts/patch-home-restore-diagnostics.js +++ /dev/null @@ -1,118 +0,0 @@ -#!/usr/bin/env node -/** - * 首页恢复诊断日志(临时补丁,确诊后移除)。 - * 只注入只读日志,不改变任何业务行为;锚点漂移必须失败。 - */ -const fs = require('node:fs'); -const path = require('node:path'); -const { parse } = require('acorn'); -const { relPath, SRC_DIR } = require('./patch-util'); -const MARKER = '/* CodexRebuildHomeRestoreDiag */'; -const PLATFORMS = ['mac-arm64', 'mac-x64', 'win']; -const PREFIX = '__codexHomeRestoreDiag'; -function targetDirectories(platform) { - const requested = platform ? [platform] : PLATFORMS; - return requested.map((item) => ({ - platform: item, - path: path.join(SRC_DIR, item, '_asar', 'webview', 'assets'), - })).filter((item) => fs.existsSync(item.path)); -} -function stmt(tag, expression) { - const entry = '({tag:' + JSON.stringify(tag) + ',at:Date.now(),data:' + expression + '})'; - return '(window.' + PREFIX + '??=[]).push(' + entry + '),globalThis.console.log(' + JSON.stringify('DIAG ' + tag) + ',JSON.stringify(' + expression + '));'; -} -function logCall(tag, expression) { - return '(window.' + PREFIX + '??=[]).push({tag:' + JSON.stringify(tag) + ',at:Date.now(),data:' + expression + '}),globalThis.console.log(' + JSON.stringify('DIAG ' + tag) + ',JSON.stringify(' + expression + '));'; -} -function replaceUnique(source, anchor, replacement, message) { - if (source.split(anchor).length - 1 !== 1) throw new Error(message); - return source.replace(anchor, replacement); -} -function patchSource(source) { - if (source.includes(MARKER)) return { status: 'already-patched', source }; - if (!source.includes('Codex:API-key 首页恢复写入。') || - !source.includes('Codex:API-key 首页从其他页面恢复会话。')) { - return { status: 'not-applicable', source }; - } - try { - parse(source, { ecmaVersion: 'latest', sourceType: 'module' }); - let next = source; - const writerAnchor = 'u=()=>{QBa(t,{accountKey:l,location:n,productMode:s})}'; - next = replaceUnique(next, writerAnchor, - 'u=()=>{' - + logCall('cuu.write', '{accountKey:l,pathname:n?.pathname,state:n?.state}') - + 'QBa(t,{accountKey:l,location:n,productMode:s})}', - '首页写入端锚点缺失'); - const tVaHead='function tVa(e,{accountKey:t,auth:n,area:r,navigate:i,productMode:a,state:o}){let s=e.get(AE),c=e.get(ch);'; - next = replaceUnique(next, tVaHead, - tVaHead + stmt('tVa.enter', '{accountKey:t,area:r,current:c?.pathname,currentState:c?.state}'), - 'tVa head anchor missing'); - const consumerAnchor = ',gO=Y(U,({get:e})=>{let t=e(ch)?.state?.sidebarThreadLocationId;'; - next = replaceUnique(next, consumerAnchor, - ',gO=Y(U,({get:e})=>{' - + stmt('gO.read', '{pathname:e(ch)?.pathname,state:e(ch)?.state}') - + 'let t=e(ch)?.state?.sidebarThreadLocationId;', - '首页消费端锚点缺失'); - const navAnchor = 'function nVa(e,t,n){let r=e.get(eh).prepareNavigation(gc(t.location),{state:{...t.location.state,...n}});return r!=null&&'; - next = replaceUnique(next, navAnchor, - 'function nVa(e,t,n){' - + stmt('nVa.enter', '{target:t.location?.pathname,targetSearch:t.location?.search,targetState:t.location?.state,mergedState:{...t.location?.state,...n}}') - + 'let r=e.get(eh).prepareNavigation(gc(t.location),{state:{...t.location.state,...n}}),diagPreparedTarget=gc(t.location);' - + stmt('nVa.preparedTarget', 'diagPreparedTarget') - + stmt('nVa.prepared', '{prepared:r!=null}') - + 'return r!=null&&', - '首页跳转端锚点缺失'); - if (!next.includes(MARKER)) { - next = MARKER + next; - } - parse(next, { ecmaVersion: 'latest', sourceType: 'module' }); - return { status: 'patched', source: next }; - } catch (error) { - return { status: 'unexpected-shape', source, reason: error.message }; - } -} -function main() { - const args = process.argv.slice(2); - const platform = args.find((arg) => PLATFORMS.includes(arg)); - const check = args.includes('--check'); - const directories = targetDirectories(platform); - let failed = 0; - let patched = 0; - for (const directory of directories) { - try { - const results = fs.readdirSync(directory.path) - .filter((name) => /^app-initial-.*\.js$/.test(name)) - .map((name) => ({ name, path: path.join(directory.path, name) })) - .map((file) => ({ file, result: patchSource(fs.readFileSync(file.path, 'utf8')) })) - .filter((item) => item.result.status !== 'not-applicable'); - if (results.length > 1) throw new Error('bundle-count ' + results.length); - if (!results.length) { - console.log(' [skip] api-key home patch not applied yet; diagnostics not applicable'); - continue; - } - const target = results[0]; - if (target.result.status === 'unexpected-shape') throw new Error(target.result.reason); - console.log(' [' + directory.platform + '] ' + relPath(target.file.path)); - if (target.result.status === 'already-patched') { - console.log(' [ok] already patched'); - } else if (check) { - console.log(' [ok] anchors verified; dry-run'); - } else { - fs.writeFileSync(target.file.path, target.result.source, 'utf8'); - patched++; - console.log(' [ok] diagnostics injected'); - } - } catch (error) { - console.error(' [x] ' + directory.platform + ': ' + error.message); - failed++; - } - } - if (!directories.length) { - console.error(' [x] missing platform assets'); - failed++; - } - if (failed) process.exitCode = 1; - else console.log(' [ok] ' + patched + ' platform bundle(s) patched'); -} -if (require.main === module) main(); -module.exports = { MARKER, PREFIX, patchSource }; diff --git a/scripts/patch-home-restore-diagnostics.test.js b/scripts/patch-home-restore-diagnostics.test.js deleted file mode 100644 index 2a5a15f5..00000000 --- a/scripts/patch-home-restore-diagnostics.test.js +++ /dev/null @@ -1,55 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); -const { MARKER, PREFIX, patchSource } = require('./patch-home-restore-diagnostics'); - -function fixture() { - return [ - 'import ' + String.fromCharCode(34) + './codex-rebuild-reading-width.js' + String.fromCharCode(34) + ';', - 'function restore(e,{accountKey:t,auth:n,area:r,navigate:i,productMode:a,state:o}){', - 'let s=e.get(AE),c=e.get(CH),u=remembered(e,{accountKey:t,auth:n,area:r,productMode:a});', - 'if(u==null||!s&&u.departedAt==null||areaOf(e,u.location)!==r){i(`/`);return!0}', - 'function tVa(e,{accountKey:t,auth:n,area:r,navigate:i,productMode:a,state:o}){let s=e.get(AE),c=e.get(ch);let u2=1}', - 'return (s||/* Codex:API-key 首页从其他页面恢复会话。 */t===`auth:apikey`&&r===`home`)?nVa(e,u,o):(i(u.location.pathname,{state:o}),!0)', - '}', - 'function cuu(){let l=e[4];', - 'let u;', - '/* Codex:API-key 首页恢复写入。 */u=()=>{QBa(t,{accountKey:l,location:n,productMode:s})};', - 'return u}', - 'let zChain=1', - ',gO=Y(U,({get:e})=>{let t=e(ch)?.state?.sidebarThreadLocationId;return typeof t==`string`?t:null}),', - '_O=cs(U,new Map);', - 'function nVa(e,t,n){let r=e.get(eh).prepareNavigation(gc(t.location),{state:{...t.location.state,...n}});return r!=null&&r()!=!0}', - ].join(''); -} - -test('diagnostics inject anchors and are idempotent', () => { - const result = patchSource(fixture()); - assert.equal(result.status, 'patched'); - assert.ok(result.source.includes(MARKER)); - assert.ok(result.source.includes(PREFIX)); - assert.match(result.source, /cuu\.write/); - assert.match(result.source, /tVa.enter/); - assert.match(result.source, /gO\.read/); - assert.match(result.source, /nVa\.enter/); - assert.match(result.source, /nVa\.prepared/); - assert.match(result.source, /nVa\.preparedTarget/); - assert.match(result.source, /targetSearch:t\.location\?\.search/); - assert.match(result.source, /targetState:t\.location\?\.state/); - assert.match(result.source, /globalThis\.console\.log\("DIAG gO\.read",JSON\.stringify\(/); - const repeated = patchSource(result.source); - assert.equal(repeated.status, 'already-patched'); - assert.equal(repeated.source, result.source); -}); - -test('unrelated bundle stays not-applicable', () => { - const result = patchSource('function unrelated(){return 1}'); - assert.equal(result.status, 'not-applicable'); -}); - -test('diagnostic payloads are evaluated, not logged as source text', () => { - const result = patchSource(fixture()); - assert.equal(result.status, 'patched'); - assert.doesNotMatch(result.source, /DIAG cuu\.write \{accountKey:l/); - assert.match(result.source, /console\.log\("DIAG cuu\.write",JSON\.stringify\(\{accountKey:l/); - assert.match(result.source, /console\.log\("DIAG tVa\.enter",JSON\.stringify\(/); -}); diff --git a/scripts/patch-policy.js b/scripts/patch-policy.js index 78e85909..d4328352 100644 --- a/scripts/patch-policy.js +++ b/scripts/patch-policy.js @@ -22,8 +22,6 @@ const PATCH_POLICY = [ { script: "patch-test-isolation.js", feature: "Windows 验收数据隔离" }, { script: "patch-provider-quota.js", feature: "真实 Provider 额度发送门槛" }, { script: "patch-api-key-home-navigation.js", feature: "API-key 首页会话恢复" }, - { script: "patch-home-restore-diagnostics.js", feature: "首页恢复诊断日志(临时)" }, - { script: "patch-home-restore-collector.js", feature: "首页恢复诊断落盘采集(临时)" }, { script: "patch-thread-timeline.js", feature: "按版本能力启用官方会话时间线" }, { script: "patch-mcp-status-refresh.js", feature: "MCP 启动状态刷新治理" }, { script: "patch-accent-presets.js", feature: "API-key 本地强调色预设" }, diff --git a/scripts/verify-home-restore-chain.js b/scripts/verify-home-restore-chain.js deleted file mode 100644 index ca5a8a1a..00000000 --- a/scripts/verify-home-restore-chain.js +++ /dev/null @@ -1,42 +0,0 @@ -const fs = require('node:fs'); -const { parse } = require('acorn'); -const home = require('./patch-api-key-home-navigation'); -const diagnostics = require('./patch-home-restore-diagnostics'); -const collector = require('./patch-home-restore-collector'); - -const rendererPath = process.argv[2]; -const mainPath = process.argv[3]; -if (!rendererPath || !mainPath) throw new Error('usage: node scripts/verify-home-restore-chain.js '); - -function stripPriorDiagnostics(source) { - const marker = '/* CodexRebuildHomeRestoreDiag */'; - if (!source.startsWith(marker)) return source; - const call = ',console.log("DIAG cuu.write {accountKey:l,pathname:n?.pathname,state:n?.state}")'; - if (!source.includes(call)) throw new Error('instrumented writer log missing'); - return source.slice(marker.length).replace(call, '').replace('window.__codexHomeRestoreDiag??=[])).push(({', 'window.__codexHomeRestoreDiag??=[]).push({'); -} - -function validateRenderer(source) { - const navigation = home.patchSource(source); - if (navigation.status === 'unexpected-shape') throw new Error('home navigation ' + navigation.reason); - if (navigation.status === 'not-applicable') throw new Error('home navigation missing'); - const observed = diagnostics.patchSource(navigation.source); - if (observed.status === 'unexpected-shape') throw new Error('diagnostics ' + observed.reason); - if (observed.status !== 'patched' && observed.status !== 'already-patched') throw new Error('diagnostics missing'); - parse(observed.source, { ecmaVersion: 'latest', sourceType: 'module' }); - return { navigation: navigation.status, diagnostics: observed.status, source: observed.source }; -} - -const original = fs.readFileSync(rendererPath, 'utf8'); -validateRenderer(original); -const cleanRenderer = stripPriorDiagnostics(original); -const observedRenderer = validateRenderer(cleanRenderer); -const observedMain = collector.patchSource(fs.readFileSync(mainPath, 'utf8')); -if (observedMain.status === 'unexpected-shape') throw new Error('collector ' + observedMain.reason); -if (observedMain.status === 'patched') parse(observedMain.source, { ecmaVersion: 'latest', sourceType: 'module' }); -console.log(JSON.stringify({ - cleanNavigation: home.patchSource(cleanRenderer).status, - diagnostics: observedRenderer.diagnostics, - collector: observedMain.status, - diagCalls: observedRenderer.source.split('globalThis.console.log').length - 1, -})); From e4c619100fa500d4dffc5c6f12a6970d2c7c6ead Mon Sep 17 00:00:00 2001 From: carptopus Date: Tue, 20 Oct 2026 18:05:12 +0800 Subject: [PATCH 36/51] fix: use official API-key home recorder --- scripts/frontend-source-smoke.js | 5 +- scripts/patch-api-key-home-navigation.js | 22 +++++--- scripts/patch-api-key-home-navigation.test.js | 52 +++++++++++++------ 3 files changed, 55 insertions(+), 24 deletions(-) diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index 4cca1e0c..695d0fff 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -77,10 +77,11 @@ function verifyFrontendSource(assets) { assert.match(themeSource, /__codexResolveAccentPreset/); assert.match(themeSource, /accentSource:`chatgpt`/); const navigationEntries = files.filter(name => /^app-initial-/.test(name) - && fs.readFileSync(path.join(assets, name), "utf8").includes("Codex:API-key 首页记录真实会话。")); + && fs.readFileSync(path.join(assets, name), "utf8").includes("Codex:API-key 首页使用官方记录器。")); assert.equal(navigationEntries.length, 1); const navigationSource = fs.readFileSync(path.join(assets, navigationEntries[0]), "utf8"); - assert.match(navigationSource, /\/\* Codex:API-key 首页记录真实会话。 \*\/if\(([A-Za-z_$][\w$]*)===`apikey`&&([A-Za-z_$][\w$]*)\.state\?\.sidebarThreadLocationId!=null\)\{([A-Za-z_$][\w$]*)\.set\(([A-Za-z_$][\w$]*),\2\.pathname\);\}/); + assert.match(navigationSource, /\/\* Codex:API-key 首页使用官方记录器。 \*\/if\([A-Za-z_$][\w$]*===`apikey`\)\{QBa\([A-Za-z_$][\w$]*,\{accountKey:`auth:apikey`,auth:[A-Za-z_$][\w$]*,location:[A-Za-z_$][\w$]*,productMode:[A-Za-z_$][\w$]*\}\);return;\}/); + assert.doesNotMatch(navigationSource, /Codex:API-key 首页记录真实会话。/); assert.match(navigationSource, /\([A-Za-z_$][\w$]*\|\|\/\* Codex:API-key 首页保持当前位置。 \*\/[A-Za-z_$][\w$]*===`auth:apikey`&&[A-Za-z_$][\w$]*===`home`\)&&[A-Za-z_$][\w$]*!=null/); assert.match(navigationSource, diff --git a/scripts/patch-api-key-home-navigation.js b/scripts/patch-api-key-home-navigation.js index 5d7eff86..d0f1b248 100644 --- a/scripts/patch-api-key-home-navigation.js +++ b/scripts/patch-api-key-home-navigation.js @@ -16,7 +16,8 @@ const { parse } = require("acorn"); const { applyEdits, literal, nodes, unique } = require("./patch-ast-util"); const { SRC_DIR, relPath } = require("./patch-util"); -const MARKER = "/* Codex:API-key 首页记录真实会话。 */"; +const MARKER = "/* Codex:API-key 首页使用官方记录器。 */"; +const BROKEN_TRACKER_MARKER = "/* Codex:API-key 首页记录真实会话。 */"; const INVALID_TRACKER_MARKER = "/* Codex:API-key 首页恢复写入。 */"; const HOME_CURRENT_MARKER = "/* Codex:API-key 首页保持当前位置。 */"; const HOME_STATE_MARKER = "/* Codex:API-key 首页保持当前。 */"; @@ -294,9 +295,10 @@ function isApiKeyRestoreOverride(node) { } function activeDestinationStatement(tracker) { - return `${MARKER}if(${tracker.authMethod}===\`apikey\`&&` + - `${tracker.location}.state?.sidebarThreadLocationId!=null){` + - `${tracker.store}.set(${tracker.destinationId},${tracker.location}.pathname);}`; + // 交给官方记录器处理 atom、路由分类及离开时间;空 destinationId 会阻止记录。 + return `${MARKER}if(${tracker.authMethod}===\`apikey\`){` + + `${tracker.recorder}(${tracker.store},{accountKey:\`auth:apikey\`,` + + `auth:${tracker.auth},location:${tracker.location},productMode:${tracker.productMode}});return;}`; } function findActiveDestinationTracker(ast, source) { @@ -307,8 +309,11 @@ function findActiveDestinationTracker(ast, source) { node.callee?.type === "Identifier" && node.callee.name === "QBa" && node.arguments.length === 2 && node.arguments[0]?.type === "Identifier" && node.arguments[1]?.type === "ObjectExpression"); - if (calls.length !== 1) continue; - const call = calls[0]; + // 已补丁的回调会多一个 API-key 调用;以官方包含 destinationId 的调用为锚点。 + const officialCalls = calls.filter(node => node.arguments[1].properties + .some(item => propertyName(item) === "destinationId")); + if (officialCalls.length !== 1) continue; + const call = officialCalls[0]; const callback = all.filter(node => node.type === "ArrowFunctionExpression" && node.start <= call.start && node.end >= call.end).at(-1); if (callback?.body.type !== "BlockStatement") continue; @@ -327,6 +332,7 @@ function findActiveDestinationTracker(ast, source) { const sharedAuth = usesSharedAuth(callback, auth) || nodes(callback.body, node => node.type === "Identifier" && node.name === properties.auth.name).length > 0; const details = { authMethod: auth.authMethod, callback, + recorder: call.callee.name, auth: properties.auth.name, productMode: properties.productMode.name, destinationId: properties.destinationId.name, location: properties.location.name, store: call.arguments[0].name, alreadyPatched: marker }; if (!marker && !sharedAuth) continue; @@ -346,6 +352,10 @@ function usesSharedAuth(callback, auth) { function patchSource(source) { + if (source.includes(BROKEN_TRACKER_MARKER)) { + return { status: "unexpected-shape", source, + reason: "检测到错误的状态仓库写入补丁;必须从干净的上游 Bundle 重新构建" }; + } const previousMarker = source.includes(INVALID_TRACKER_MARKER); if (previousMarker) { return { status: "unexpected-shape", source, reason: "检测到上一版首页恢复补丁;必须从未应用旧补丁的上游 Bundle 重新构建" }; diff --git a/scripts/patch-api-key-home-navigation.test.js b/scripts/patch-api-key-home-navigation.test.js index a5acef51..10a3edab 100644 --- a/scripts/patch-api-key-home-navigation.test.js +++ b/scripts/patch-api-key-home-navigation.test.js @@ -97,25 +97,45 @@ test("API-key 在活动导航记录器写入真实会话", () => { assert.equal(result.status, "patched"); assert.ok(result.source.includes(MARKER)); - assert.match(result.source, /Codex:API-key 首页记录真实会话。 \*\/if\(u===`apikey`&&r\.state\?\.sidebarThreadLocationId!=null\)\{n\.set\(m,r\.pathname\);\}/); + assert.match(result.source, /QBa\(n,\{accountKey:`auth:apikey`,auth:c,location:r,productMode:o\}\);return;/); + assert.doesNotMatch(result.source, /n\.set\(m,r\.pathname\)/); assert.doesNotMatch(result.source, /首页恢复写入/); }); -test("官方导航记录器保留 ChatGPT 条件并在 API-key 下记录真实会话", () => { - const active = patchSource(fixture()).source.split("function Active(){")[1].split("function restore")[0]; - const statement = active.match(/if\(([A-Za-z_$][\w$]*)===`apikey`&&([A-Za-z_$][\w$]*)\.state\?\.sidebarThreadLocationId!=null\)\{([A-Za-z_$][\w$]*)\.set\(([A-Za-z_$][\w$]*),\2\.pathname\);\}/); - assert.ok(statement, "API-key 记录语句应位于官方活动导航目标回调中"); - const [, authMethod, current, store, destination] = statement; - const target = {}; - const location = { pathname: "/local/thread-1", state: { sidebarThreadLocationId: "thread-1" } }; - const run = method => Function("method", "current", "store", "destination", "target", - `if(method===\"apikey\"&¤t.state?.sidebarThreadLocationId!=null){target.local=current.pathname}`) - (method, location, target, "local", target); - run("apikey"); - assert.equal(target.local, "/local/thread-1"); - delete target.local; - run("chatgptAuthTokens"); - assert.equal(target.local, undefined); +test("活动回调在会话和设置页都委托官方记录器,且不向仓库传入导航 ID", () => { + const source = patchSource(fixture()).source; + const calls = []; + const activeStore = { set() { assert.fail("不能将导航 ID 当作 atom 写入仓库"); } }; + const invoke = Function("current", "method", "activeStore", "record", [ + "const cache=()=>[true],store=()=>activeStore,location=()=>current;", + "const useContext=()=>({activeDestinationId:null}),Ctx={},q=x=>x;", + "const capability=()=>false,productMode=()=>`codex`,project=()=>null;", + "const auth=()=>({authMethod:method}),QBa=record;", + "const react={useLayoutEffect:callback=>callback()};", + source, + "Active();", + ].join("")); + for (const current of [ + { pathname: "/local/thread-1", state: { sidebarThreadLocationId: "chats" } }, + { pathname: "/settings/general", state: null }, + ]) { + invoke(current, "apikey", activeStore, (store, options) => calls.push({ store, options })); + const call = calls.at(-1); + assert.equal(call.store, activeStore); + assert.equal(call.options.accountKey, "auth:apikey"); + assert.equal(call.options.auth.authMethod, "apikey"); + assert.equal(call.options.location, current); + assert.equal(call.options.productMode, "codex"); + assert.equal(Object.hasOwn(call.options, "destinationId"), false); + } + assert.equal(calls.length, 2, "每次路由变化只调用一次官方记录器"); +}); + +test("拒绝曾导致真实 API-key 页面崩溃的旧写入补丁", () => { + const broken = fixture().replace("function Rail", "/* Codex:API-key 首页记录真实会话。 */function Rail"); + const result = patchSource(broken); + assert.equal(result.status, "unexpected-shape"); + assert.match(result.reason, /错误的状态仓库写入/); }); test("builtin:home 通过公共恢复函数保持 API-key 当前首页会话", () => { From 38ebf931da2be40ab51966efba395c6f97345da3 Mon Sep 17 00:00:00 2001 From: carptopus Date: Tue, 20 Oct 2026 23:33:06 +0800 Subject: [PATCH 37/51] Hide invite entries in account menu --- README.md | 1 + scripts/frontend-source-smoke.js | 4 ++ scripts/maintenance-smoke.js | 20 +++++++++ scripts/patch-hide-invite-menu.js | 67 +++++++++++++++++++++++++++++++ scripts/patch-policy.js | 1 + 5 files changed, 93 insertions(+) create mode 100644 scripts/patch-hide-invite-menu.js diff --git a/README.md b/README.md index 39a13f0f..a13c487f 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,7 @@ pnpm run build:all - `patch-remote-control.js` 不强开 Connections 或 Remote Control gate;只有真实 ChatGPT 认证才同步官方 Remote Control 本地状态,API-key 等其他认证会清除旧启用值并禁用当前 app-server 的 Remote Control。 - `patch-accent-presets.js` 允许没有 ChatGPT 账户主题的 API-key / 自定义 Provider 在本地选择强调色,并复用官方完整预设渲染消息气泡等界面变量;账户主题仍在加载时保持禁用,账户可用时继续使用官方同步。 - `patch-hide-pet-menu.js` 只隐藏账户菜单中的 Pet / Mini 入口,保留浮动面板实现、状态和全局快捷键。 +- `patch-hide-invite-menu.js` 隐藏账户菜单中的“邀请好友 / 邀请同事”入口。 - `patch-reading-layout.js` 在外观主题卡片中加入 50%–100%、步进 5% 的正文宽度滑杆,并同步代码块、表格和输入区宽度,扩宽适用对话框;百分比不低于官方宽度,Markdown 粗体颜色可跟随正文、强调色或使用自定义颜色。 - `patch-test-isolation.js` 在官方设置 User Data 后、获取单实例锁前挂载 Windows 验收隔离,分别约束 `CODEX_HOME`、User Data 和 sessionData,并记录实际启动路径证据。 - `patch-model-picker-submenu.js` 增加对新版原生 simple / advanced 内联模型列表的结构核验;官方实现完整时保持原样,旧结构继续适配,未知结构明确失败。 diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index 695d0fff..3fdb4693 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -143,6 +143,10 @@ function verifyFrontendSource(assets) { const shared = files.filter(name => /^app-shared-/.test(name) && fs.readFileSync(path.join(assets, name), "utf8").includes("codex-rebuild-dialog-default")); assert.equal(shared.length, 1); const dialogs = fs.readFileSync(path.join(assets, shared[0]), "utf8"); + const inviteMenus = files.filter(name => /^profile-dropdown-items-.*\.js$/.test(name)); + assert.equal(inviteMenus.length, 1); + assert.equal(require("./patch-hide-invite-menu").patchSource( + fs.readFileSync(path.join(assets, inviteMenus[0]), "utf8")).status, "already-patched"); assert.match(dialogs, /codex-rebuild-dialog-editor h-\[720px\] max-w-full max-h-full/); return { passed: true, quotaScenarios: results, apiKeyHomeNavigation: true, threadTimelineEnabled: true, mcpStatusRefreshGoverned: true, remoteControlAuthIsolated: true, apiKeyServiceTiers: true, nativeAppearanceRow: true, nativeAccentThemePipeline: true, dialogHeightPreserved: true }; } diff --git a/scripts/maintenance-smoke.js b/scripts/maintenance-smoke.js index 2373444d..9b05b99e 100644 --- a/scripts/maintenance-smoke.js +++ b/scripts/maintenance-smoke.js @@ -147,6 +147,7 @@ try { const missingRequiredRoot = path.join(temporary, "missing-required-targets"); fs.mkdirSync(path.join(missingRequiredRoot, "win", "_asar", "webview", "assets"), { recursive: true }); run("patch-hide-pet-menu.js", ["win", "--check"], 1, { CODEX_PATCH_SOURCE_DIR: missingRequiredRoot }); + run("patch-hide-invite-menu.js", ["win", "--check"], 1, { CODEX_PATCH_SOURCE_DIR: missingRequiredRoot }); run("patch-model-picker-submenu.js", ["win", "--check"], 1, { CODEX_PATCH_SOURCE_DIR: missingRequiredRoot }); fs.writeFileSync( path.join(missingRequiredRoot, "win", "_asar", "webview", "assets", "archived-list.js"), @@ -154,6 +155,25 @@ try { ); run("patch-archive-delete.js", ["win", "--check"], 1, { CODEX_PATCH_SOURCE_DIR: missingRequiredRoot }); + const inviteRoot = path.join(temporary, "invite-menu"); + const inviteFile = path.join(inviteRoot, "win", "_asar", "webview", "assets", "profile-dropdown-items-fixture.js"); + const inviteSource = 'function Invite(){return {id:`codex.profileDropdown.inviteFriend`,other:`codex.profileDropdown.inviteCoworker`}};function menu(){return [ui.jsx(Invite,{context:context,onSelect:close}),usage,settings,help]};'; + write(inviteFile, inviteSource); + const inviteEnv = { CODEX_PATCH_SOURCE_DIR: inviteRoot }; + run("patch-hide-invite-menu.js", ["win", "--check"], 0, inviteEnv); + assert.equal(fs.readFileSync(inviteFile, "utf8"), inviteSource); + run("patch-hide-invite-menu.js", ["win"], 0, inviteEnv); + const hiddenInvite = fs.readFileSync(inviteFile, "utf8"); + const renderMenu = source => Function("ui", "context", "close", "usage", "settings", "help", source + "return menu();")( + { jsx: () => "invite" }, {}, () => {}, "usage", "settings", "help"); + assert.deepEqual(renderMenu(inviteSource), ["invite", "usage", "settings", "help"]); + assert.deepEqual(renderMenu(hiddenInvite), [null, "usage", "settings", "help"]); + run("patch-hide-invite-menu.js", ["win"], 0, inviteEnv); + assert.equal(fs.readFileSync(inviteFile, "utf8"), hiddenInvite); + write(inviteFile, inviteSource.replace("onSelect:close", "changed:close")); + run("patch-hide-invite-menu.js", ["win"], 1, inviteEnv); + assert.equal(fs.readFileSync(inviteFile, "utf8"), inviteSource.replace("onSelect:close", "changed:close")); + const pickerRoot = path.join(temporary, "picker"); const pickerFile = path.join(pickerRoot, "win", "_asar", "webview", "assets", "model-picker.js"); const nativePicker = 'function picker(input){const {modelListConfig:list,menuView:view,onToggleMenuView:toggle}=input;const items=list.options.map(option=>ui.jsx(menu.Item,{"data-model-selected":option.selected,role:`menuitemradio`,onSelect:event=>{event.preventDefault();option.onSelect();toggle(`simple`)}}));return ui.jsx("div",{"data-model-picker-view":view,children:items});}'; diff --git a/scripts/patch-hide-invite-menu.js b/scripts/patch-hide-invite-menu.js new file mode 100644 index 00000000..66e92cc2 --- /dev/null +++ b/scripts/patch-hide-invite-menu.js @@ -0,0 +1,67 @@ +#!/usr/bin/env node +/** 只隐藏账户菜单中的邀请入口,保留官方邀请功能的其他路径。 */ +const fs = require("node:fs"); +const path = require("node:path"); +const { parse } = require("acorn"); +const { applyEdits, key, literal, nodes } = require("./patch-ast-util"); +const { SRC_DIR, relPath } = require("./patch-util"); + +const MARKER = "/* codex-rebuild-hide-invite-menu */"; +const LABEL_IDS = [ + "codex.profileDropdown.inviteFriend", + "codex.profileDropdown.inviteCoworker", +]; + +function patchSource(source) { + if (!LABEL_IDS.every(id => source.includes(id))) return { status: "not-applicable", source }; + const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const components = ast.body.filter(node => node.type === "FunctionDeclaration" && + LABEL_IDS.every(id => nodes(node, child => literal(child) === id).length > 0)); + if (components.length !== 1) return { status: "unexpected-component-count", source }; + const calls = nodes(ast, node => { + if (node.type !== "CallExpression" || node.arguments[0]?.type !== "Identifier" || + node.arguments[0].name !== components[0].id.name || + node.arguments[1]?.type !== "ObjectExpression") return false; + const names = node.arguments[1].properties.filter(p => p.type === "Property").map(p => key(p.key)); + return names.length === 2 && names.includes("context") && names.includes("onSelect"); + }); + const markers = source.split(MARKER).length - 1; + if (markers) { + return { status: markers === 1 && calls.length === 0 && source.includes(MARKER + "null") + ? "already-patched" : "unexpected-patched-shape", source }; + } + if (calls.length !== 1) return { status: "unexpected-menu-call-count", source }; + const call = calls[0]; + return { status: "patched", source: applyEdits(source, [ + { start: call.start, end: call.end, text: MARKER + "null" }, + ]) }; +} + +function main() { + const args = process.argv.slice(2); + const platform = args.find(arg => ["mac-arm64", "mac-x64", "win"].includes(arg)); + const check = args.includes("--check"); + const targets = []; + for (const name of platform ? [platform] : ["mac-arm64", "mac-x64", "win"]) { + const directory = path.join(SRC_DIR, name, "_asar", "webview", "assets"); + if (!platform && !fs.existsSync(directory)) continue; + const files = fs.existsSync(directory) + ? fs.readdirSync(directory).filter(file => /^profile-dropdown-items-.*\.js$/.test(file)) : []; + if (files.length !== 1) { + throw new Error(`[${name}] 邀请菜单资源必须唯一`); + } + targets.push({ path: path.join(directory, files[0]) }); + } + if (!targets.length) throw new Error("缺少邀请菜单目标资源,不能跳过补丁"); + for (const target of targets) { + const result = patchSource(fs.readFileSync(target.path, "utf8")); + if (!["patched", "already-patched"].includes(result.status)) { + throw new Error(`${relPath(target.path)}: 邀请菜单结构未知(${result.status})`); + } + if (result.status === "patched" && !check) fs.writeFileSync(target.path, result.source, "utf8"); + console.log(`[ok] ${relPath(target.path)}: ${check ? "邀请菜单隐藏检查通过,未写文件" : "邀请菜单入口已隐藏"}`); + } +} + +if (require.main === module) main(); +module.exports = { MARKER, patchSource }; diff --git a/scripts/patch-policy.js b/scripts/patch-policy.js index d4328352..357203fa 100644 --- a/scripts/patch-policy.js +++ b/scripts/patch-policy.js @@ -26,6 +26,7 @@ const PATCH_POLICY = [ { script: "patch-mcp-status-refresh.js", feature: "MCP 启动状态刷新治理" }, { script: "patch-accent-presets.js", feature: "API-key 本地强调色预设" }, { script: "patch-hide-pet-menu.js", feature: "隐藏 Pet 菜单入口" }, + { script: "patch-hide-invite-menu.js", feature: "隐藏账户菜单邀请入口" }, { script: "patch-reading-layout.js", feature: "可配置正文宽度与排版" }, { script: "patch-model-catalog-filter.js", feature: "模型目录过滤" }, { script: "patch-model-picker-submenu.js", feature: "模型选择器子菜单" }, From bc5a516aa65b6c788e4e98ed684eacb55e4af92b Mon Sep 17 00:00:00 2001 From: carptopus Date: Wed, 21 Oct 2026 00:23:09 +0800 Subject: [PATCH 38/51] Replace sidebar avatar with usage ring --- README.md | 1 + package.json | 1 + scripts/check-scripts.js | 1 + scripts/frontend-source-smoke.js | 4 + scripts/maintenance-smoke.js | 2 + scripts/patch-policy.js | 1 + scripts/patch-sidebar-usage.js | 135 ++++++++++++++++++++++++++++ scripts/runtime/sidebar-usage.mjs | 46 ++++++++++ scripts/sidebar-usage-smoke.js | 141 ++++++++++++++++++++++++++++++ 9 files changed, 332 insertions(+) create mode 100644 scripts/patch-sidebar-usage.js create mode 100644 scripts/runtime/sidebar-usage.mjs create mode 100644 scripts/sidebar-usage-smoke.js diff --git a/README.md b/README.md index a13c487f..d54a3855 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,7 @@ pnpm run build:all - `patch-accent-presets.js` 允许没有 ChatGPT 账户主题的 API-key / 自定义 Provider 在本地选择强调色,并复用官方完整预设渲染消息气泡等界面变量;账户主题仍在加载时保持禁用,账户可用时继续使用官方同步。 - `patch-hide-pet-menu.js` 只隐藏账户菜单中的 Pet / Mini 入口,保留浮动面板实现、状态和全局快捷键。 - `patch-hide-invite-menu.js` 隐藏账户菜单中的“邀请好友 / 邀请同事”入口。 +- `patch-sidebar-usage.js` 在 ChatGPT 登录时以剩余额度圆环和百分比替换侧栏头像,复用官方额度查询和刷新机制,点击仍打开原账户菜单。 - `patch-reading-layout.js` 在外观主题卡片中加入 50%–100%、步进 5% 的正文宽度滑杆,并同步代码块、表格和输入区宽度,扩宽适用对话框;百分比不低于官方宽度,Markdown 粗体颜色可跟随正文、强调色或使用自定义颜色。 - `patch-test-isolation.js` 在官方设置 User Data 后、获取单实例锁前挂载 Windows 验收隔离,分别约束 `CODEX_HOME`、User Data 和 sessionData,并记录实际启动路径证据。 - `patch-model-picker-submenu.js` 增加对新版原生 simple / advanced 内联模型列表的结构核验;官方实现完整时保持原样,旧结构继续适配,未知结构明确失败。 diff --git a/package.json b/package.json index 8ac92a05..a3f67b55 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "test": "node --test scripts/*.test.js", "check": "node scripts/check-scripts.js", "test:maintenance": "node scripts/maintenance-smoke.js", + "test:sidebar-usage": "node scripts/sidebar-usage-smoke.js", "windows:check-update": "node scripts/windows-maintenance.js discover", "windows:candidate": "node scripts/windows-maintenance.js candidate", "windows:verify-release": "node scripts/windows-maintenance.js verify-release", diff --git a/scripts/check-scripts.js b/scripts/check-scripts.js index 51b27eda..699470bf 100644 --- a/scripts/check-scripts.js +++ b/scripts/check-scripts.js @@ -9,6 +9,7 @@ files.push("runtime/rebuild-test-isolation.cjs"); files.push("runtime/rebuild-test-environment.cjs"); files.push("runtime/reading-width.mjs"); files.push("runtime/accent-presets.mjs"); +files.push("runtime/sidebar-usage.mjs"); for (const file of files) execFileSync(process.execPath, ["--check", path.join(__dirname, file)], { stdio: "inherit" }); JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")); console.log(`脚本语法检查通过:${files.length} 个文件`); diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index 3fdb4693..3396c8bd 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -147,6 +147,10 @@ function verifyFrontendSource(assets) { assert.equal(inviteMenus.length, 1); assert.equal(require("./patch-hide-invite-menu").patchSource( fs.readFileSync(path.join(assets, inviteMenus[0]), "utf8")).status, "already-patched"); + const usagePatch = require("./patch-sidebar-usage"); + assert.equal(usagePatch.patchSource(mcpRefreshSource).status, "already-patched"); + assert.equal(fs.readFileSync(path.join(assets, usagePatch.MODULE), "utf8"), + fs.readFileSync(path.join(__dirname, "runtime", "sidebar-usage.mjs"), "utf8")); assert.match(dialogs, /codex-rebuild-dialog-editor h-\[720px\] max-w-full max-h-full/); return { passed: true, quotaScenarios: results, apiKeyHomeNavigation: true, threadTimelineEnabled: true, mcpStatusRefreshGoverned: true, remoteControlAuthIsolated: true, apiKeyServiceTiers: true, nativeAppearanceRow: true, nativeAccentThemePipeline: true, dialogHeightPreserved: true }; } diff --git a/scripts/maintenance-smoke.js b/scripts/maintenance-smoke.js index 9b05b99e..ebb1c56d 100644 --- a/scripts/maintenance-smoke.js +++ b/scripts/maintenance-smoke.js @@ -148,6 +148,8 @@ try { fs.mkdirSync(path.join(missingRequiredRoot, "win", "_asar", "webview", "assets"), { recursive: true }); run("patch-hide-pet-menu.js", ["win", "--check"], 1, { CODEX_PATCH_SOURCE_DIR: missingRequiredRoot }); run("patch-hide-invite-menu.js", ["win", "--check"], 1, { CODEX_PATCH_SOURCE_DIR: missingRequiredRoot }); + run("patch-sidebar-usage.js", ["win", "--check"], 1, { CODEX_PATCH_SOURCE_DIR: missingRequiredRoot }); + run("sidebar-usage-smoke.js", []); run("patch-model-picker-submenu.js", ["win", "--check"], 1, { CODEX_PATCH_SOURCE_DIR: missingRequiredRoot }); fs.writeFileSync( path.join(missingRequiredRoot, "win", "_asar", "webview", "assets", "archived-list.js"), diff --git a/scripts/patch-policy.js b/scripts/patch-policy.js index 357203fa..544b35dd 100644 --- a/scripts/patch-policy.js +++ b/scripts/patch-policy.js @@ -27,6 +27,7 @@ const PATCH_POLICY = [ { script: "patch-accent-presets.js", feature: "API-key 本地强调色预设" }, { script: "patch-hide-pet-menu.js", feature: "隐藏 Pet 菜单入口" }, { script: "patch-hide-invite-menu.js", feature: "隐藏账户菜单邀请入口" }, + { script: "patch-sidebar-usage.js", feature: "侧栏常驻剩余额度圆环" }, { script: "patch-reading-layout.js", feature: "可配置正文宽度与排版" }, { script: "patch-model-catalog-filter.js", feature: "模型目录过滤" }, { script: "patch-model-picker-submenu.js", feature: "模型选择器子菜单" }, diff --git a/scripts/patch-sidebar-usage.js b/scripts/patch-sidebar-usage.js new file mode 100644 index 00000000..30196df2 --- /dev/null +++ b/scripts/patch-sidebar-usage.js @@ -0,0 +1,135 @@ +#!/usr/bin/env node +/** 复用官方额度查询,用剩余额度圆环替换侧栏头像。 */ +const fs = require("node:fs"); +const path = require("node:path"); +const { parse } = require("acorn"); +const { applyEdits, key, literal, nodes, unique } = require("./patch-ast-util"); +const { SRC_DIR, relPath } = require("./patch-util"); +const MODULE = "codex-rebuild-sidebar-usage.js"; +const MARKER = "/* CodexRebuildSidebarUsage */"; +const COMPONENT = "__CodexSidebarUsage"; +const ACCOUNT_COMPONENT = "__CodexAccountSidebarUsage"; +const RENDER = "__codexRenderSidebarUsage"; +const contains = (source, node, value) => source.slice(node.start, node.end).includes(value); +const props = node => Object.fromEntries((node?.properties ?? []) + .filter(property => property.type === "Property" && !property.computed) + .map(property => [key(property.key), property.value])); + +function analyze(source, ast) { + const footer = unique(ast.body.filter(node => node.type === "FunctionDeclaration" && + contains(source, node, "codex.profileFooter.settingsFallback") && + contains(source, node, "codex.profileFooter.loadingProfile")), "原生头像侧栏组件"); + const declarations = nodes(footer, node => node.type === "VariableDeclarator", { ownScope: true }); + const hookFor = name => { + const declaration = unique(declarations.filter(node => node.id?.name === name), `侧栏变量 ${name}`); + if (declaration.init?.type !== "CallExpression" || declaration.init.callee.type !== "Identifier" || + declaration.init.arguments.length !== 0) throw new Error(`侧栏 Hook ${name} 结构未知`); + return declaration.init.callee.name; + }; + const authBinding = unique(declarations.filter(node => node.id.type === "ObjectPattern" && + ["accountId", "authMethod", "userId"].every(name => props(node.id)[name])), "账户身份解构"); + if (authBinding.init?.type !== "Identifier") throw new Error("账户身份来源未知"); + const authHook = hookFor(authBinding.init.name); + const profileCall = unique(nodes(footer, node => node.type === "CallExpression" && + node.arguments[1]?.type === "ObjectExpression" && + ["sidebarFooter", "hideUsage", "triggerButton"].every(name => props(node.arguments[1])[name])), "头像菜单调用"); + const profileProps = props(profileCall.arguments[1]); + const width = props(profileProps.sidebarFooter).width; + if (width?.type !== "ConditionalExpression" || width.test.type !== "Identifier" || + width.alternate.type !== "Identifier" || profileProps.hideUsage.type !== "Identifier") { + throw new Error("侧栏宽度和额度可见性结构未知"); + } + const widthRead = unique(declarations.filter(node => node.id?.name === width.alternate.name), "侧栏宽度读取"); + if (widthRead.init?.type !== "CallExpression" || widthRead.init.callee.type !== "Identifier") { + throw new Error("原生状态订阅读取结构未知"); + } + const readHook = widthRead.init.callee.name; + const intlCall = unique(nodes(footer, node => node.type === "CallExpression" && + node.callee.type === "MemberExpression" && key(node.callee.property) === "formatMessage" && + node.arguments[0]?.type === "ObjectExpression" && + literal(props(node.arguments[0]).id) === "codex.profileFooter.settingsFallback"), "侧栏国际化"); + const intlHook = hookFor(intlCall.callee.object.name); + const jsx = profileCall.callee.type === "SequenceExpression" ? profileCall.callee.expressions.at(-1) : profileCall.callee; + if (jsx?.type !== "MemberExpression" || jsx.object.type !== "Identifier" || key(jsx.property) !== "jsx") { + throw new Error("原生侧栏 JSX 结构未知"); + } + const usageFetch = unique(ast.body.filter(node => node.type === "FunctionDeclaration" && + nodes(node, child => literal(child) === "/wham/usage").length > 0), "官方额度请求"); + const usageAtom = unique(nodes(ast, node => node.type === "AssignmentExpression" && + node.operator === "=" && node.left.type === "Identifier" && node.right.type === "CallExpression" && + node.right.arguments.some(argument => { + if (argument.type !== "ArrowFunctionExpression") return false; + const returned = argument.body.type === "BlockStatement" ? argument.body.body.at(-1) : null; + const options = props(returned?.type === "ReturnStatement" ? returned.argument : argument.body); + return options.refetchInterval && options.queryFn && nodes(options.queryFn, call => + call.type === "CallExpression" && call.callee.type === "Identifier" && + call.callee.name === usageFetch.id.name).length > 0; + })), "共享额度查询"); + const initialize = unique(ast.body.filter(node => node.type === "FunctionDeclaration" && + node.start < usageAtom.start && node.end > usageAtom.end), "额度查询初始化器"); + const avatar = unique(nodes(footer, node => node.type === "CallExpression" && + node.arguments[1]?.type === "ObjectExpression" && + ["colorKey", "name", "size", "src", "fallback", "loadingFallback"].every(name => props(node.arguments[1])[name])), "原生头像"); + const avatarAssignment = unique(nodes(footer, node => node.type === "AssignmentExpression" && + node.left.type === "Identifier" && node.right.type === "ConditionalExpression" && + node.right.start < avatar.start && node.right.end > avatar.end), "头像渲染分支"); + const avatarSlot = unique(declarations.filter(node => node.init?.type === "Identifier" && + node.init.name === avatarAssignment.left.name), "账户按钮头像插槽"); + if (!nodes(footer, node => node.type === "Property" && key(node.key) === "icon" && + node.value?.type === "Identifier" && node.value.name === avatarSlot.id.name).length) { + throw new Error("原生账户按钮头像引用未知"); + } + return { footer, avatarSlot, authHook, readHook, + intlHook, jsx: jsx.object.name, compact: width.test.name, hidden: profileProps.hideUsage.name, + usageAtom: usageAtom.left.name, initialize: initialize.id.name }; +} + +function patchSource(source) { + if (!source.includes("codex.profileFooter.settingsFallback")) return { status: "not-applicable", source }; + try { + const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + if (source.includes(MARKER)) { + if (source.split(MARKER).length !== 2 || !source.includes(MODULE) || + !source.includes(`jsx)(${COMPONENT},{fallback:`) || + !ast.body.some(node => node.type === "FunctionDeclaration" && node.id?.name === ACCOUNT_COMPONENT)) { + throw new Error("侧栏额度补丁标记不完整"); + } + return { status: "already-patched", source }; + } + if ([COMPONENT, ACCOUNT_COMPONENT, RENDER, MODULE].some(value => source.includes(value))) { + throw new Error("侧栏额度注入名称已占用"); + } + const shape = analyze(source, ast); + const call = `(0,${shape.jsx}.jsx)(${COMPONENT},{fallback:${shape.avatarSlot.init.name},compact:${shape.compact},hidden:${shape.hidden}})`; + const bridges = `\n${MARKER}\nfunction ${COMPONENT}(props){const auth=${shape.authHook}();return props.hidden||auth.authMethod!==\`chatgpt\`?props.fallback:(0,${shape.jsx}.jsx)(${ACCOUNT_COMPONENT},props);}\n` + + `function ${ACCOUNT_COMPONENT}(props){${shape.initialize}();const auth=${shape.authHook}(),usage=${shape.readHook}(${shape.usageAtom}),intl=${shape.intlHook}();return ${RENDER}({...props,auth,usage:usage.data,intl,jsx:${shape.jsx}});}\n`; + const patched = applyEdits(source, [{ start: shape.avatarSlot.init.start, end: shape.avatarSlot.init.end, text: call }]); + const result = `import {renderSidebarUsage as ${RENDER}} from "./${MODULE}";\n` + patched + bridges; + parse(result, { ecmaVersion: "latest", sourceType: "module" }); + return { status: "patched", source: result }; + } catch (error) { + return { status: "unexpected-shape", source, reason: error.message }; + } +} + +function main() { + const args = process.argv.slice(2), platform = args.find(arg => ["win", "mac-arm64", "mac-x64"].includes(arg)); + const check = args.includes("--check"); + let count = 0; + for (const name of platform ? [platform] : ["win", "mac-arm64", "mac-x64"]) { + const directory = path.join(SRC_DIR, name, "_asar", "webview", "assets"); + if (!platform && !fs.existsSync(directory)) continue; + const file = unique(fs.readdirSync(directory).filter(file => /^app-initial-.*\.js$/.test(file)), "侧栏资源"); + const target = path.join(directory, file), result = patchSource(fs.readFileSync(target, "utf8")); + if (!["patched", "already-patched"].includes(result.status)) throw new Error(result.reason ?? result.status); + if (!check) { + if (result.status === "patched") fs.writeFileSync(target, result.source, "utf8"); + fs.copyFileSync(path.join(__dirname, "runtime", "sidebar-usage.mjs"), path.join(directory, MODULE)); + } + console.log(`[ok] ${relPath(target)}: 侧栏额度圆环${check ? "结构检查通过,未写文件" : "已加入"}`); + count++; + } + if (!count) throw new Error("缺少侧栏额度目标资源"); +} +if (require.main === module) main(); +module.exports = { MODULE, MARKER, COMPONENT, ACCOUNT_COMPONENT, RENDER, patchSource }; diff --git a/scripts/runtime/sidebar-usage.mjs b/scripts/runtime/sidebar-usage.mjs new file mode 100644 index 00000000..42974529 --- /dev/null +++ b/scripts/runtime/sidebar-usage.mjs @@ -0,0 +1,46 @@ +/** 侧栏额度展示;数据与刷新由官方账户查询维护。 */ +export function renderSidebarUsage({ compact, auth, usage, intl, jsx }) { + const zh = intl.locale.toLowerCase().startsWith("zh"); + const label = zh ? "剩余额度" : "Usage remaining"; + const valid = !auth.isLoading && !auth.authLoading && !auth.accountLoading && + auth.accountId != null && auth.userId != null && + usage?.account_id === auth.accountId && usage?.user_id === auth.userId; + const windows = valid ? [usage.rate_limit?.primary_window, usage.rate_limit?.secondary_window] + .filter(window => Number.isFinite(window?.used_percent)) : []; + // 多窗口取最紧张的一项;不能用缺失数据推算出 100%。 + const remaining = windows.length ? Math.min(...windows.map(window => + Math.max(0, Math.min(100, 100 - window.used_percent)))) : null; + const percent = remaining == null ? "—" : intl.formatNumber(remaining, { maximumFractionDigits: 0 }) + "%"; + const accent = "var(--app-color-text-accent,var(--codex-base-accent,currentColor))"; + const color = remaining == null ? "currentColor" : remaining <= 10 ? "#dc503f" : remaining <= 25 ? "#bd7b16" : accent; + const details = windows.map(window => { + const hours = window.limit_window_seconds / 3600; + const period = hours === 168 ? (zh ? "每周" : "Weekly") + : Number.isFinite(hours) && hours > 0 ? (zh ? `${hours} 小时` : `${hours} hours`) : label; + const left = intl.formatNumber(Math.max(0, Math.min(100, 100 - window.used_percent)), { maximumFractionDigits: 0 }); + const reset = Number.isFinite(window.reset_at) ? new Date(window.reset_at * 1000) : null; + const resetText = reset && Number.isFinite(reset.getTime()) + ? new Intl.DateTimeFormat(intl.locale, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" }).format(reset) : null; + return `${period}: ${left}%${resetText ? (zh ? `,${resetText} 重置` : `; resets ${resetText}`) : ""}`; + }); + const title = details.length ? details.join("\n") : (zh ? "额度数据暂不可用" : "Usage data unavailable"); + const size = compact ? 32 : 24; + return jsx.jsxs("span", { + "data-codex-sidebar-usage": true, role: "img", "aria-label": `${label}: ${percent}`, title, + style: { position: "relative", display: "inline-flex", width: size, height: size, flexShrink: 0, alignItems: "center", justifyContent: "center" }, + children: [jsx.jsxs("svg", { + width: size, height: size, viewBox: "0 0 36 36", "aria-hidden": true, + style: { position: "absolute", inset: 0, overflow: "visible" }, + children: [jsx.jsx("circle", { + cx: 18, cy: 18, r: 15, fill: "none", stroke: "currentColor", strokeWidth: 2.5, opacity: 0.14, + }), remaining == null ? null : jsx.jsx("circle", { + cx: 18, cy: 18, r: 15, fill: "none", stroke: color, strokeWidth: 2.5, + pathLength: 100, strokeDasharray: `${remaining} 100`, transform: "rotate(-90 18 18)", + })], + }), jsx.jsx("span", { + "data-codex-sidebar-usage-value": true, + style: { position: "relative", fontSize: compact ? 9 : 7.5, fontWeight: 600, fontVariantNumeric: "tabular-nums", lineHeight: 1 }, + children: percent, + })], + }); +} diff --git a/scripts/sidebar-usage-smoke.js b/scripts/sidebar-usage-smoke.js new file mode 100644 index 00000000..7dc57225 --- /dev/null +++ b/scripts/sidebar-usage-smoke.js @@ -0,0 +1,141 @@ +#!/usr/bin/env node +/** 执行补丁生成的组件和额度渲染链;--asar 可核验真实候选,不启动或修改 GUI。 */ +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const vm = require("node:vm"); +const { pathToFileURL } = require("node:url"); +const { parse } = require("acorn"); +const { nodes, unique } = require("./patch-ast-util"); +const { MODULE, MARKER, COMPONENT, ACCOUNT_COMPONENT, RENDER, patchSource } = require("./patch-sidebar-usage"); + +const fixture = `let usageAtom; +async function fetchUsage(){return http("/wham/usage")} +function initialize(){usageAtom=query(null,()=>{return{queryFn:()=>fetchUsage(),refetchInterval:()=>30000}})} +function Profile(input){ + const {compact,hideUsage}=input,auth=useAuth(); + const {accountId,authMethod,userId}=auth,width=read(widthAtom),intl=useIntl(); + const label=intl.formatMessage({id:"codex.profileFooter.settingsFallback"}); + const loading=intl.formatMessage({id:"codex.profileFooter.loadingProfile"}); + let picture;picture=authMethod==="chatgpt"?(0,ui.jsx)("span",{children:(0,ui.jsx)(Avatar,{colorKey:userId,name:label,size:"sm",src:null,fallback:null,loadingFallback:null})}):null; + const icon=picture;let slot;slot=measuring?null:icon; + const button=(0,ui.jsx)(Button,{compact,uniform:compact,iconSize:"lg","aria-label":label,onClick:openMenu,children:[loading,slot,label]}); + const alternate=(0,ui.jsx)(Alternate,{icon}); + const footer=(0,ui.jsx)(Menu,{sidebarFooter:{width:compact?null:width},hideUsage,triggerButton:button}); + let result;return result=(0,ui.jsx)("footer",{children:footer}),result; +}`; + +async function main() { + const args = process.argv.slice(2); + let source = fixture, rendererPath = path.join(__dirname, "runtime/sidebar-usage.mjs"), origin = "内置功能样本"; + if (args[0] === "--asar" && args.length === 2) { + const asar = await import("@electron/asar"); + const files = asar.listPackage(args[1]); + const entry = unique(files.filter(name => /app-initial-[^/\\]+\.js$/.test(name)), "真实侧栏 Bundle"); + source = asar.extractFile(args[1], entry.replace(/^[/\\]/, "")).toString(); + origin = `${args[1]}:${entry}`; + if (source.includes(MARKER)) { + const embedded = asar.extractFile(args[1], path.join(path.dirname(entry), MODULE).replace(/^[/\\]/, "")).toString(); + assert.equal(embedded, fs.readFileSync(rendererPath, "utf8"), "候选渲染模块与当前源码不一致"); + } + } else assert.equal(args.length, 0, "用法:node scripts/sidebar-usage-smoke.js [--asar PATH]"); + const result = patchSource(source); + assert.ok(["patched", "already-patched"].includes(result.status), result.reason); + assert.equal(patchSource(result.source).source, result.source, "重复应用必须幂等"); + const ast = parse(result.source, { ecmaVersion: "latest", sourceType: "module" }); + const outer = unique(ast.body.filter(node => node.id?.name === COMPONENT), "账号门槛组件"); + const account = unique(ast.body.filter(node => node.id?.name === ACCOUNT_COMPONENT), "额度组件"); + const declarations = nodes(account, node => node.type === "VariableDeclarator"); + const binding = name => unique(declarations.filter(node => node.id.name === name), name).init; + const authHook = binding("auth").callee.name, readHook = binding("usage").callee.name; + const intlHook = binding("intl").callee.name; + const jsxCall = unique(nodes(outer, node => node.type === "CallExpression" && node.callee.type === "SequenceExpression"), "组件 JSX"); + const jsxName = jsxCall.callee.expressions.at(-1).object.name; + const atom = {}, fallback = { type: "native-avatar", props: {} }, state = {}; + const jsx = { jsx: (type, props) => typeof type === "function" ? type(props) : { type, props } }; + jsx.jsxs = jsx.jsx; + const { renderSidebarUsage } = await import(pathToFileURL(rendererPath)); + const context = { + [authHook]: () => state.auth, + [readHook]: value => { assert.equal(value, atom); state.reads++; return { data: state.usage }; }, + [binding("usage").arguments[0].name]: atom, + [intlHook]: () => ({ locale: state.locale, formatNumber: (number, options) => new Intl.NumberFormat(state.locale, options).format(number) }), + [account.body.body[0].expression.callee.name]: () => {}, + [jsxName]: jsx, [RENDER]: renderSidebarUsage, + }; + const bridgeSource = [outer, account].map(node => result.source.slice(node.start, node.end)).join("\n"); + vm.createContext(context); + vm.runInContext(bridgeSource, context, { timeout: 2000 }); + const mount = unique(nodes(ast, node => node.type === "CallExpression" && + node.arguments[0]?.name === COMPONENT), "真实头像插槽中的额度组件调用"); + const host = unique(ast.body.filter(node => node.type === "FunctionDeclaration" && + node.start < mount.start && node.end > mount.end), "侧栏组件宿主"); + const avatarSlot = unique(nodes(host, node => node.type === "VariableDeclarator" && node.init === mount), "头像插槽初始化"); + const nativeButton = unique(nodes(host, node => node.type === "CallExpression" && + node.arguments[1]?.type === "ObjectExpression" && ["compact", "uniform", "children"].every(name => + node.arguments[1].properties.some(property => property.key?.name === name))), "原生账户菜单按钮"); + const buttonProps = Object.fromEntries(nativeButton.arguments[1].properties.map(property => [property.key.name ?? property.key.value, property.value])); + const iconAlias = buttonProps.children.elements[1].name; + const iconForward = unique(nodes(host, node => node.type === "AssignmentExpression" && + node.left?.name === iconAlias && node.right.type === "ConditionalExpression" && + node.right.alternate?.name === avatarSlot.id.name), "原生按钮继续使用头像插槽"); + assert.ok(iconForward); + const mountProps = Object.fromEntries(mount.arguments[1].properties.map(property => [property.key.name, property.value.name])); + const mountSource = result.source.slice(mount.start, mount.end); + const all = tree => !tree || typeof tree !== "object" ? [] : [tree, ...[tree.props?.children].flat(Infinity).flatMap(all)]; + const render = (compact = true, hidden = false) => { + state.reads = 0; + context[mountProps.fallback] = fallback; + context[mountProps.compact] = compact; + context[mountProps.hidden] = hidden; + return vm.runInContext(mountSource, context, { timeout: 2000 }); + }; + const value = tree => all(tree).find(node => node.props?.["data-codex-sidebar-usage-value"])?.props.children; + const baseAuth = { authMethod: "chatgpt", accountId: "account", userId: "user" }; + const usage = used => ({ account_id: "account", user_id: "user", rate_limit: { + primary_window: { used_percent: used, limit_window_seconds: 604800, reset_at: 1793000000 }, + } }); + state.auth = baseAuth; state.usage = usage(19); state.locale = "zh-CN"; + let tree = render(); + assert.equal(value(tree), "81%"); assert.equal(state.reads, 1); + assert.equal(tree.type, "span"); assert.equal(tree.props.style.width, 32); + assert.equal(all(tree).filter(node => node.type === "button").length, 0, "不能在原按钮里嵌套新按钮"); + const ring = all(tree).find(node => node.type === "circle" && node.props.pathLength === 100); + assert.equal(ring.props.strokeDasharray, "81 100"); + assert.match(tree.props.title, /每周: 81%/); + for (const node of nodes(nativeButton.arguments[1], node => node.type === "Identifier")) { + if (!(node.name in context)) context[node.name] = null; + } + context[iconAlias] = tree; + context[nativeButton.arguments[0].name] = props => jsx.jsx("button", props); + context[buttonProps.onClick.name] = () => { state.menuOpened = true; }; + const button = vm.runInContext(result.source.slice(nativeButton.start, nativeButton.end), context, { timeout: 2000 }); + assert.equal(button.props.children[1], tree); + button.props.onClick(); assert.equal(state.menuOpened, true, "点击仍走原生账户菜单事件"); + state.usage = usage(28); assert.equal(value(render()), "72%", "不打开菜单也应读取最新共享状态"); + tree = render(false); assert.equal(value(tree), "72%"); + assert.equal(tree.props.style.width, 24); + state.usage.rate_limit.secondary_window = { used_percent: 80, limit_window_seconds: 18000 }; + assert.equal(value(render()), "20%", "多窗口取最紧张的额度"); + for (const [used, expected] of [[0, "100%"], [100, "0%"], [150, "0%"], [-1, "100%"], [null, "—"]]) { + state.usage = usage(used); assert.equal(value(render()), expected); + } + state.usage = usage(19); state.auth = { ...baseAuth, accountId: "other" }; + assert.equal(value(render()), "—", "切换账号时不能显示旧账号额度"); + state.usage.account_id = "other"; state.usage.rate_limit.primary_window.used_percent = 46; + assert.equal(value(render()), "54%"); + state.auth = { ...baseAuth, isLoading: true }; assert.equal(value(render()), "—"); + state.auth = baseAuth; state.usage = null; assert.equal(value(render()), "—"); + state.usage = usage(19); state.locale = "en-US"; + assert.match(render().props.title, /Weekly: 81%/); + state.auth = { ...baseAuth, authMethod: "apikey" }; + assert.equal(render(), fallback); assert.equal(state.reads, 0, "API 模式不挂载官方额度订阅"); + state.auth = baseAuth; assert.equal(render(true, true), fallback); assert.equal(state.reads, 0); + if (source === fixture) { + const invalid = fixture.replace('"/wham/usage"', '"/changed/usage"'); + assert.equal(patchSource(invalid).status, "unexpected-shape"); + assert.equal(patchSource(invalid).source, invalid); + } + console.log(`侧栏额度功能验证通过:${origin};头像插槽替换、原生菜单点击、常驻更新、未知/边界、双窗口、身份切换。未启动或修改 GUI。`); +} +main().catch(error => { console.error(error); process.exitCode = 1; }); From b57cb43e1d5ea18c4fee9af3ef5bbe8da230e43e Mon Sep 17 00:00:00 2001 From: carptopus Date: Wed, 21 Oct 2026 01:02:28 +0800 Subject: [PATCH 39/51] Improve sidebar usage ring readability --- scripts/runtime/sidebar-usage.mjs | 18 ++++++++++-------- scripts/sidebar-usage-smoke.js | 19 +++++++++++++++++-- 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/scripts/runtime/sidebar-usage.mjs b/scripts/runtime/sidebar-usage.mjs index 42974529..8f9379fb 100644 --- a/scripts/runtime/sidebar-usage.mjs +++ b/scripts/runtime/sidebar-usage.mjs @@ -27,20 +27,22 @@ export function renderSidebarUsage({ compact, auth, usage, intl, jsx }) { const size = compact ? 32 : 24; return jsx.jsxs("span", { "data-codex-sidebar-usage": true, role: "img", "aria-label": `${label}: ${percent}`, title, - style: { position: "relative", display: "inline-flex", width: size, height: size, flexShrink: 0, alignItems: "center", justifyContent: "center" }, + style: { display: "inline-flex", width: size, height: size, flexShrink: 0, alignItems: "center", justifyContent: "center", color: "var(--color-text)", lineHeight: 0 }, children: [jsx.jsxs("svg", { - width: size, height: size, viewBox: "0 0 36 36", "aria-hidden": true, - style: { position: "absolute", inset: 0, overflow: "visible" }, + width: size, height: size, viewBox: "0 0 36 36", "aria-hidden": true, "data-no-autosize": true, + // 官方按钮会自动缩放内部 SVG;使用其原生豁免,并把数字置于同一坐标系。 + style: { display: "block", width: size, height: size, flex: "none", margin: 0, overflow: "visible" }, children: [jsx.jsx("circle", { - cx: 18, cy: 18, r: 15, fill: "none", stroke: "currentColor", strokeWidth: 2.5, opacity: 0.14, + cx: 18, cy: 18, r: 15, fill: "none", stroke: "currentColor", strokeWidth: 2.5, opacity: 0.2, }), remaining == null ? null : jsx.jsx("circle", { cx: 18, cy: 18, r: 15, fill: "none", stroke: color, strokeWidth: 2.5, pathLength: 100, strokeDasharray: `${remaining} 100`, transform: "rotate(-90 18 18)", + }), jsx.jsx("text", { + "data-codex-sidebar-usage-value": true, x: 18, y: 18, textAnchor: "middle", dominantBaseline: "central", + textLength: percent.length >= 4 ? 26 : undefined, lengthAdjust: "spacingAndGlyphs", + style: { fill: "var(--color-text)", opacity: 1, fontSize: compact ? 13 : 15, fontWeight: 700, fontFamily: "inherit", fontVariantNumeric: "tabular-nums" }, + children: percent, })], - }), jsx.jsx("span", { - "data-codex-sidebar-usage-value": true, - style: { position: "relative", fontSize: compact ? 9 : 7.5, fontWeight: 600, fontVariantNumeric: "tabular-nums", lineHeight: 1 }, - children: percent, })], }); } diff --git a/scripts/sidebar-usage-smoke.js b/scripts/sidebar-usage-smoke.js index 7dc57225..fdc48ad8 100644 --- a/scripts/sidebar-usage-smoke.js +++ b/scripts/sidebar-usage-smoke.js @@ -28,6 +28,7 @@ function Profile(input){ async function main() { const args = process.argv.slice(2); let source = fixture, rendererPath = path.join(__dirname, "runtime/sidebar-usage.mjs"), origin = "内置功能样本"; + let rendererUrl = pathToFileURL(rendererPath).href; if (args[0] === "--asar" && args.length === 2) { const asar = await import("@electron/asar"); const files = asar.listPackage(args[1]); @@ -36,7 +37,9 @@ async function main() { origin = `${args[1]}:${entry}`; if (source.includes(MARKER)) { const embedded = asar.extractFile(args[1], path.join(path.dirname(entry), MODULE).replace(/^[/\\]/, "")).toString(); - assert.equal(embedded, fs.readFileSync(rendererPath, "utf8"), "候选渲染模块与当前源码不一致"); + // Git 在 Windows 构建机可能检出 CRLF;校验源码内容后直接执行成品模块。 + assert.equal(embedded.replace(/\r\n/g, "\n"), fs.readFileSync(rendererPath, "utf8").replace(/\r\n/g, "\n"), "候选渲染模块与当前源码不一致"); + rendererUrl = `data:text/javascript;base64,${Buffer.from(embedded).toString("base64")}`; } } else assert.equal(args.length, 0, "用法:node scripts/sidebar-usage-smoke.js [--asar PATH]"); const result = patchSource(source); @@ -54,7 +57,7 @@ async function main() { const atom = {}, fallback = { type: "native-avatar", props: {} }, state = {}; const jsx = { jsx: (type, props) => typeof type === "function" ? type(props) : { type, props } }; jsx.jsxs = jsx.jsx; - const { renderSidebarUsage } = await import(pathToFileURL(rendererPath)); + const { renderSidebarUsage } = await import(rendererUrl); const context = { [authHook]: () => state.auth, [readHook]: value => { assert.equal(value, atom); state.reads++; return { data: state.usage }; }, @@ -102,6 +105,18 @@ async function main() { assert.equal(all(tree).filter(node => node.type === "button").length, 0, "不能在原按钮里嵌套新按钮"); const ring = all(tree).find(node => node.type === "circle" && node.props.pathLength === 100); assert.equal(ring.props.strokeDasharray, "81 100"); + const svg = all(tree).find(node => node.type === "svg"); + assert.equal(svg.props["data-no-autosize"], true, "必须避开官方按钮 SVG 自动缩放"); + assert.equal(svg.props.style.width, tree.props.style.width); + assert.equal(svg.props.style.height, tree.props.style.height); + const percentage = all(svg).find(node => node.props?.["data-codex-sidebar-usage-value"]); + assert.equal(percentage.type, "text", "数字和圆环必须共用 SVG 坐标系"); + assert.equal(percentage.props.x, ring.props.cx); + assert.equal(percentage.props.y, ring.props.cy); + assert.equal(percentage.props.textAnchor, "middle"); + assert.equal(percentage.props.dominantBaseline, "central"); + assert.equal(percentage.props.style.fill, "var(--color-text)"); + assert.ok(percentage.props.style.fontSize >= 13); assert.match(tree.props.title, /每周: 81%/); for (const node of nodes(nativeButton.arguments[1], node => node.type === "Identifier")) { if (!(node.name in context)) context[node.name] = null; From dc88098249adf57d02c4b2dbe5540ba2c0613aaf Mon Sep 17 00:00:00 2001 From: carptopus Date: Wed, 21 Oct 2026 02:24:51 +0800 Subject: [PATCH 40/51] Refine sidebar usage ring appearance --- scripts/runtime/sidebar-usage.mjs | 15 ++++++++------- scripts/sidebar-usage-smoke.js | 22 ++++++++++++++++------ 2 files changed, 24 insertions(+), 13 deletions(-) diff --git a/scripts/runtime/sidebar-usage.mjs b/scripts/runtime/sidebar-usage.mjs index 8f9379fb..7bec8c76 100644 --- a/scripts/runtime/sidebar-usage.mjs +++ b/scripts/runtime/sidebar-usage.mjs @@ -10,9 +10,11 @@ export function renderSidebarUsage({ compact, auth, usage, intl, jsx }) { // 多窗口取最紧张的一项;不能用缺失数据推算出 100%。 const remaining = windows.length ? Math.min(...windows.map(window => Math.max(0, Math.min(100, 100 - window.used_percent)))) : null; - const percent = remaining == null ? "—" : intl.formatNumber(remaining, { maximumFractionDigits: 0 }) + "%"; + const displayValue = remaining == null ? "—" : intl.formatNumber(remaining, { maximumFractionDigits: 0 }); + const percent = remaining == null ? displayValue : `${displayValue}%`; const accent = "var(--app-color-text-accent,var(--codex-base-accent,currentColor))"; - const color = remaining == null ? "currentColor" : remaining <= 10 ? "#dc503f" : remaining <= 25 ? "#bd7b16" : accent; + const color = remaining == null ? "currentColor" : remaining <= 10 ? "#dc503f" : remaining <= 25 ? "#bd7b16" + : `color-mix(in srgb, ${accent} 75%, var(--color-text))`; const details = windows.map(window => { const hours = window.limit_window_seconds / 3600; const period = hours === 168 ? (zh ? "每周" : "Weekly") @@ -33,15 +35,14 @@ export function renderSidebarUsage({ compact, auth, usage, intl, jsx }) { // 官方按钮会自动缩放内部 SVG;使用其原生豁免,并把数字置于同一坐标系。 style: { display: "block", width: size, height: size, flex: "none", margin: 0, overflow: "visible" }, children: [jsx.jsx("circle", { - cx: 18, cy: 18, r: 15, fill: "none", stroke: "currentColor", strokeWidth: 2.5, opacity: 0.2, + cx: 18, cy: 18, r: 15, fill: "none", stroke: "currentColor", strokeWidth: 2, opacity: 0.1, }), remaining == null ? null : jsx.jsx("circle", { - cx: 18, cy: 18, r: 15, fill: "none", stroke: color, strokeWidth: 2.5, + cx: 18, cy: 18, r: 15, fill: "none", stroke: color, strokeWidth: 2, pathLength: 100, strokeDasharray: `${remaining} 100`, transform: "rotate(-90 18 18)", }), jsx.jsx("text", { "data-codex-sidebar-usage-value": true, x: 18, y: 18, textAnchor: "middle", dominantBaseline: "central", - textLength: percent.length >= 4 ? 26 : undefined, lengthAdjust: "spacingAndGlyphs", - style: { fill: "var(--color-text)", opacity: 1, fontSize: compact ? 13 : 15, fontWeight: 700, fontFamily: "inherit", fontVariantNumeric: "tabular-nums" }, - children: percent, + style: { fill: "var(--color-text)", opacity: 1, fontSize: compact ? 13 : 15, fontWeight: 500, fontFamily: "inherit", fontVariantNumeric: "tabular-nums" }, + children: displayValue, })], })], }); diff --git a/scripts/sidebar-usage-smoke.js b/scripts/sidebar-usage-smoke.js index fdc48ad8..ff47ca49 100644 --- a/scripts/sidebar-usage-smoke.js +++ b/scripts/sidebar-usage-smoke.js @@ -100,11 +100,17 @@ async function main() { } }); state.auth = baseAuth; state.usage = usage(19); state.locale = "zh-CN"; let tree = render(); - assert.equal(value(tree), "81%"); assert.equal(state.reads, 1); + assert.equal(value(tree), "81"); assert.equal(state.reads, 1); + assert.equal(tree.props["aria-label"], "剩余额度: 81%"); assert.equal(tree.type, "span"); assert.equal(tree.props.style.width, 32); assert.equal(all(tree).filter(node => node.type === "button").length, 0, "不能在原按钮里嵌套新按钮"); const ring = all(tree).find(node => node.type === "circle" && node.props.pathLength === 100); assert.equal(ring.props.strokeDasharray, "81 100"); + assert.equal(ring.props.strokeWidth, 2); + assert.match(ring.props.stroke, /^color-mix\(/); + const track = all(tree).find(node => node.type === "circle" && node.props.pathLength == null); + assert.equal(track.props.strokeWidth, 2); + assert.equal(track.props.opacity, 0.1); const svg = all(tree).find(node => node.type === "svg"); assert.equal(svg.props["data-no-autosize"], true, "必须避开官方按钮 SVG 自动缩放"); assert.equal(svg.props.style.width, tree.props.style.width); @@ -116,6 +122,7 @@ async function main() { assert.equal(percentage.props.textAnchor, "middle"); assert.equal(percentage.props.dominantBaseline, "central"); assert.equal(percentage.props.style.fill, "var(--color-text)"); + assert.equal(percentage.props.style.fontWeight, 500); assert.ok(percentage.props.style.fontSize >= 13); assert.match(tree.props.title, /每周: 81%/); for (const node of nodes(nativeButton.arguments[1], node => node.type === "Identifier")) { @@ -127,18 +134,21 @@ async function main() { const button = vm.runInContext(result.source.slice(nativeButton.start, nativeButton.end), context, { timeout: 2000 }); assert.equal(button.props.children[1], tree); button.props.onClick(); assert.equal(state.menuOpened, true, "点击仍走原生账户菜单事件"); - state.usage = usage(28); assert.equal(value(render()), "72%", "不打开菜单也应读取最新共享状态"); - tree = render(false); assert.equal(value(tree), "72%"); + state.usage = usage(28); assert.equal(value(render()), "72", "不打开菜单也应读取最新共享状态"); + tree = render(false); assert.equal(value(tree), "72"); assert.equal(tree.props.style.width, 24); state.usage.rate_limit.secondary_window = { used_percent: 80, limit_window_seconds: 18000 }; - assert.equal(value(render()), "20%", "多窗口取最紧张的额度"); - for (const [used, expected] of [[0, "100%"], [100, "0%"], [150, "0%"], [-1, "100%"], [null, "—"]]) { + tree = render(); assert.equal(value(tree), "20", "多窗口取最紧张的额度"); + assert.equal(all(tree).find(node => node.type === "circle" && node.props.pathLength === 100).props.stroke, "#bd7b16"); + state.usage = usage(90); + assert.equal(all(render()).find(node => node.type === "circle" && node.props.pathLength === 100).props.stroke, "#dc503f"); + for (const [used, expected] of [[0, "100"], [100, "0"], [150, "0"], [-1, "100"], [null, "—"]]) { state.usage = usage(used); assert.equal(value(render()), expected); } state.usage = usage(19); state.auth = { ...baseAuth, accountId: "other" }; assert.equal(value(render()), "—", "切换账号时不能显示旧账号额度"); state.usage.account_id = "other"; state.usage.rate_limit.primary_window.used_percent = 46; - assert.equal(value(render()), "54%"); + assert.equal(value(render()), "54"); state.auth = { ...baseAuth, isLoading: true }; assert.equal(value(render()), "—"); state.auth = baseAuth; state.usage = null; assert.equal(value(render()), "—"); state.usage = usage(19); state.locale = "en-US"; From e1f61c0ef825e9c76aa934133bea7fd6e6654102 Mon Sep 17 00:00:00 2001 From: carptopus Date: Fri, 23 Oct 2026 01:14:17 +0800 Subject: [PATCH 41/51] fix: adapt patches for Windows 26.1016 --- scripts/patch-api-key-home-navigation.js | 12 +++- scripts/patch-api-key-home-navigation.test.js | 53 +++++++++++++++++ scripts/patch-fast-mode.js | 15 +++-- scripts/patch-fast-mode.test.js | 37 ++++++++++++ scripts/patch-remote-control.js | 14 +++++ scripts/patch-remote-control.test.js | 43 ++++++++++++++ scripts/patch-thread-file-manager-action.js | 39 ++++++++++++- .../patch-thread-file-manager-action.test.js | 57 +++++++++++++++++++ 8 files changed, 259 insertions(+), 11 deletions(-) diff --git a/scripts/patch-api-key-home-navigation.js b/scripts/patch-api-key-home-navigation.js index d0f1b248..4108d9e0 100644 --- a/scripts/patch-api-key-home-navigation.js +++ b/scripts/patch-api-key-home-navigation.js @@ -306,12 +306,18 @@ function findActiveDestinationTracker(ast, source) { for (const fn of ast.body.filter(node => node.type === "FunctionDeclaration")) { const all = nodes(fn, () => true); const calls = all.filter(node => node.type === "CallExpression" && - node.callee?.type === "Identifier" && node.callee.name === "QBa" && + node.callee?.type === "Identifier" && node.arguments.length === 2 && node.arguments[0]?.type === "Identifier" && node.arguments[1]?.type === "ObjectExpression"); // 已补丁的回调会多一个 API-key 调用;以官方包含 destinationId 的调用为锚点。 - const officialCalls = calls.filter(node => node.arguments[1].properties - .some(item => propertyName(item) === "destinationId")); + // 压缩器会重命名记录器;以完整官方调用契约定位,不能绑定 QBa 等临时名。 + const officialCalls = calls.filter(node => { + const properties = node.arguments[1].properties; + return properties.length === 5 && + ["accountKey", "auth", "location", "productMode", "destinationId"] + .every(name => properties.filter(item => propertyName(item) === name && + item.value?.type === "Identifier").length === 1); + }); if (officialCalls.length !== 1) continue; const call = officialCalls[0]; const callback = all.filter(node => node.type === "ArrowFunctionExpression" && diff --git a/scripts/patch-api-key-home-navigation.test.js b/scripts/patch-api-key-home-navigation.test.js index 10a3edab..4849bc31 100644 --- a/scripts/patch-api-key-home-navigation.test.js +++ b/scripts/patch-api-key-home-navigation.test.js @@ -1,5 +1,7 @@ const test = require("node:test"); const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const acorn = require("acorn"); const { HOME_CURRENT_MARKER, @@ -11,6 +13,57 @@ const { patchSource, } = require("./patch-api-key-home-navigation"); +// 可选的官方资源功能验收;输入只读,直接执行已补丁的真实函数。 +test("26.1016 真实 Bundle:首页记录、离开及完整状态恢复", { + skip: !process.env.CODEX_PATCH_REAL_BUNDLE, +}, () => { + const source = fs.readFileSync(process.env.CODEX_PATCH_REAL_BUNDLE, "utf8"); + const result = patchSource(source); + assert.equal(result.status, "patched", result.reason); + const again = patchSource(result.source); + assert.equal(again.status, "already-patched", again.reason); + assert.equal(again.source, result.source); + const ast = acorn.parse(result.source, { ecmaVersion: "latest", sourceType: "module" }); + const functions = ["mEc", "uKa", "CKa", "xKa", "SKa", "$Ga", "eKa", "dKa", "pKa", "mKa", "bKa"] + .map(name => { + const matches = ast.body.filter(node => node.type === "FunctionDeclaration" && node.id.name === name); + assert.equal(matches.length, 1, `真实函数 ${name} 必须唯一`); + return result.source.slice(matches[0].start, matches[0].end); + }).join("\n"); + const harness = Function("assert", ` + const atoms=Object.fromEntries(["jE","HE","EL","hC","sC","DKa","EKa","CD","OL","tg","Gy","kw","Aw","Ow","fEc"].map(id=>[id,{id}])); + const {jE,HE,EL,hC,sC,DKa,EKa,CD,OL,tg,Gy,kw,Aw,Ow,fEc}=atoms; + const values=new Map([[jE,false],[EL,"codex"],[hC,{projectId:"sample"}],[sC,{}]]),records=new Map(); + const store={get(atom,partition){assert.ok(atom?.id,"get 必须使用 atom");return atom===EKa?(records.get(partition)||{}):values.get(atom)}, + set(atom,...args){assert.ok(atom?.id,"set 必须使用 atom");if(atom===EKa)records.set(args[0],args[1]);else values.set(atom,args[0])}}; + let current,navigated=null;const auth={authMethod:"apikey"}; + values.set(CD,{prepareNavigation:(pathname,options)=>()=>{navigated={pathname,...options}}}); + const J={},uEc={},hEc={c:()=>[]},gEc={useContext:()=>null,useLayoutEffect:fn=>fn()}; + const E=()=>store,Wa=()=>current,DT=()=>auth,Z=atom=>store.get(atom); + const gL={home:{destinationId:"builtin:home"}},Ty="/",wKa=480000; + const qke={},Ewe={},BI="/review",ia=()=>null,no=()=>false,nOe=()=>null; + const eb=({pathname})=>({routeKind:pathname.startsWith("/settings")?"other":"home"}); + const Me=location=>location.pathname,Cwn=()=>{}; + ${functions} + return {visit(location){current=location;values.set(HE,location);mEc()}, + click(){navigated=null;pKa(store,{accountKey:"auth:apikey",auth,area:"home",navigate:pathname=>{navigated={pathname}},productMode:"codex",state:{}});return navigated}, + record(){return records.get("auth:apikey:codex")?.["builtin:home"]}}; + `)(assert); + const thread = { pathname: "/local/sample-thread", key: "thread", search: "", hash: "", + state: { sidebarThreadLocationId: "chats", sidebarProductMode: "codex", sidebarProductModeAccountKey: "auth:apikey" } }; + harness.visit(thread); + assert.equal(harness.record().location.pathname, thread.pathname); + assert.equal(harness.record().departedAt, null); + assert.equal(harness.click(), null); + harness.visit({ pathname: "/settings/general", key: "settings", search: "", hash: "", state: null }); + assert.equal(harness.record().location.pathname, thread.pathname); + assert.ok(harness.record().departedAt > 0); + const restored = harness.click(); + assert.equal(restored.pathname, thread.pathname); + assert.equal(restored.state.sidebarThreadLocationId, "chats"); + assert.equal(restored.state.sidebarProductModeAccountKey, "auth:apikey"); +}); + function fixture() { return fixtureParts().join(""); } diff --git a/scripts/patch-fast-mode.js b/scripts/patch-fast-mode.js index 42af6d6f..b4ca91ef 100644 --- a/scripts/patch-fast-mode.js +++ b/scripts/patch-fast-mode.js @@ -65,12 +65,15 @@ function comparisonOperand(node, source, operator, value) { function exactAuthPair(node, source, logicalOperator, comparisonOperator) { if (node?.type !== "LogicalExpression" || node.operator !== logicalOperator) return null; const terms = flattenLogical(node, logicalOperator); - if (terms.length !== 2) return null; - const chatGpt = terms.map((term) => - comparisonOperand(term, source, comparisonOperator, "chatgpt")).find(Boolean); - const token = terms.map((term) => - comparisonOperand(term, source, comparisonOperator, "personalAccessToken")).find(Boolean); - return chatGpt != null && chatGpt === token ? chatGpt : null; + // 新版在账户 requirements 白名单中加入 Bedrock;只接受这两种已核实的完整集合。 + const methods = ["chatgpt", "personalAccessToken"]; + if (terms.length === 3) methods.push("amazonBedrock"); + if (terms.length !== methods.length) return null; + const operands = methods.map((method) => terms.map((term) => + comparisonOperand(term, source, comparisonOperator, method)).filter(Boolean)); + if (operands.some((items) => items.length !== 1) || + operands.some((items) => items[0] !== operands[0][0])) return null; + return operands[0][0]; } function count(source, value) { diff --git a/scripts/patch-fast-mode.test.js b/scripts/patch-fast-mode.test.js index 03992ca7..8c984cb3 100644 --- a/scripts/patch-fast-mode.test.js +++ b/scripts/patch-fast-mode.test.js @@ -110,3 +110,40 @@ test("残缺补丁标记明确失败", () => { assert.equal(result.status, "unexpected-shape"); assert.match(result.reason, /数量异常/); }); + +// 明确指定未修改的 26.1016.8120.0 证据;不把大型官方 Bundle 放进公开仓库。 +test("26.1016 真实 Bundle 的设置与请求行为", { skip: !process.env.CODEX_REBUILD_1016_BUNDLE }, async () => { + const fs = require("node:fs"); + const vm = require("node:vm"); + const { parse } = require("acorn"); + const source = fs.readFileSync(process.env.CODEX_REBUILD_1016_BUNDLE, "utf8"); + const result = patchSource(source); + assert.equal(result.status, "patched", result.reason); + assert.equal(patchSource(result.source).status, "already-patched"); + const functions = parse(result.source, { ecmaVersion: "latest", sourceType: "module" }).body + .filter((node) => node.type === "FunctionDeclaration"); + const extract = (name) => { + const matches = functions.filter((node) => node.id.name === name); + assert.equal(matches.length, 1); + return result.source.slice(matches[0].start, matches[0].end); + }; + let authMethod, pending, requests = 0; + const access = { fast: false, ultrafast: true }; + const context = vm.createContext({ + vLo: { c: () => [] }, Z: () => "local", vk: {}, OT: () => ({ authMethod, isLoading: false }), + Nc: () => ({ data: { access }, isPending: pending }), xC: {}, fCe: (value) => value.access, + Z6s: async () => authMethod, Hwn: async () => { requests++; return { access }; }, + }); + vm.runInContext(`${extract("_Lo")};${extract("t8s")}`, context); + for (authMethod of ["apikey", "chatgpt", "personalAccessToken", "amazonBedrock", "copilot"]) { + pending = false; + const ui = context._Lo(); + const request = await context.t8s({ query: { setData() {} } }, "local"); + const expected = authMethod === "apikey" ? { fast: true, ultrafast: true } : authMethod === "copilot" ? null : access; + assert.equal(JSON.stringify(ui.serviceTierAccess), JSON.stringify(expected)); + assert.equal(JSON.stringify(request), JSON.stringify(expected)); + pending = true; + assert.equal(context._Lo().isLoading, ["chatgpt", "personalAccessToken", "amazonBedrock"].includes(authMethod)); + } + assert.equal(requests, 3, "API-key 与不支持的认证都不读取 requirements"); +}); diff --git a/scripts/patch-remote-control.js b/scripts/patch-remote-control.js index f2ec2d05..f687d19a 100644 --- a/scripts/patch-remote-control.js +++ b/scripts/patch-remote-control.js @@ -147,6 +147,20 @@ function findCurrentAuth(allFunctions, source) { !assigned.has(call.arguments[0].name)) continue; hooks.add(call.callee.name); } + if (hooks.size === 0) { + // 新版移除了认证 selector 的单句 Hook 包装;从实际使用完整认证 atom + // 且含 React effect 的组件中定位 Hook,避免把 selector 的 get 当成 Hook。 + for (const component of allFunctions) { + const effects = descendants(component, (node) => node.type === "CallExpression" && + propertyName(memberCallee(node)) === "useEffect", { skipNestedFunctions: true }); + if (effects.length === 0) continue; + const calls = descendants(component, (node) => node.type === "CallExpression" && + node.callee?.type === "Identifier" && node.arguments.length === 1 && + node.arguments[0]?.type === "Identifier" && + node.arguments[0].name === account[0].left.name, { skipNestedFunctions: true }); + for (const call of calls) hooks.add(call.callee.name); + } + } if (hooks.size !== 1) continue; candidates.push({ initializer: fn, diff --git a/scripts/patch-remote-control.test.js b/scripts/patch-remote-control.test.js index 0b15ae29..774fe688 100644 --- a/scripts/patch-remote-control.test.js +++ b/scripts/patch-remote-control.test.js @@ -51,3 +51,46 @@ test("拒绝继续处理曾经强开 gate 的污染 Bundle", () => { test("没有 Remote Control 同步组件时不适用", () => { assert.equal(patchSource("const value=1;").status, "not-applicable"); }); + +test("26.1016 真实 Bundle 的 Remote Control 认证切换行为", { skip: !process.env.CODEX_REBUILD_1016_BUNDLE }, async () => { + const fs = require("node:fs"); + const vm = require("node:vm"); + const { parse } = require("acorn"); + const source = fs.readFileSync(process.env.CODEX_REBUILD_1016_BUNDLE, "utf8"); + const result = patchSource(source); + assert.equal(result.status, "patched", result.reason); + assert.equal(patchSource(result.source).status, "already-patched"); + const functions = parse(result.source, { ecmaVersion: "latest", sourceType: "module" }).body + .filter((node) => node.type === "FunctionDeclaration"); + const extract = (name) => { + const matches = functions.filter((node) => node.id.name === name); + assert.equal(matches.length, 1); + return result.source.slice(matches[0].start, matches[0].end); + }; + const events = [], container = {}; + let account, enabled = true; + const context = vm.createContext({ + E: () => container, J: {}, Czl: () => [enabled, (value) => { events.push(["storage", value]); enabled = value; }], + Z: () => account, $h: {}, rvu: async (target, value) => { assert.equal(target, container); events.push(["sync", value]); }, + gvu: { useEffect: (effect) => effect() }, xvu: { useEffect: (effect) => effect() }, + $v: () => ({ checkGate: () => true, isLoading: false }), F_i: "pairing", + tu: async (method, value) => events.push([method, JSON.parse(JSON.stringify(value.params))]), + }); + vm.runInContext(`${extract("mvu")};${extract("yvu")}`, context); + for (const authMethod of ["apikey", "chatgpt", "copilot"]) { + enabled = true; + events.length = 0; + account = { authMethod, authLoading: true }; + context.mvu(); context.yvu(); + assert.deepEqual(events, [], "认证加载期间不触发同步或状态清理"); + account = { authMethod, authLoading: false }; + context.mvu(); context.yvu(); + await Promise.resolve(); + const chatgpt = authMethod === "chatgpt"; + assert.deepEqual(events, [ + ...chatgpt ? [] : [["storage", false]], + ["sync", chatgpt], + ["set-remote-control-connections-enabled", { enabled: chatgpt, oneToOnePairingInAppEnabled: chatgpt }], + ]); + } +}); diff --git a/scripts/patch-thread-file-manager-action.js b/scripts/patch-thread-file-manager-action.js index 3c41b3a6..17a86b23 100644 --- a/scripts/patch-thread-file-manager-action.js +++ b/scripts/patch-thread-file-manager-action.js @@ -248,6 +248,24 @@ function findPatchContext(ast, source) { function findSidebarPatchContexts(ast, source) { const selectorGitGates = new Map(); const contexts = []; + const remoteControlAtoms = new Set(); + + // 26.1016 将远程连接读取封装成派生 atom,确认读取 .remoteControl 的真实定义。 + walk(ast, (node) => { + const name = node.type === "AssignmentExpression" && node.left?.type === "Identifier" + ? node.left.name : node.type === "VariableDeclarator" && node.id?.type === "Identifier" + ? node.id.name : null; + const call = node.type === "AssignmentExpression" ? node.right : node.init; + if (name == null || call?.type !== "CallExpression") return; + const selector = call.arguments[1]; + const get = objectPatternBindings(selector?.params?.[0]).get("get"); + const body = selector?.body?.type === "ChainExpression" ? selector.body.expression : selector?.body; + if (get != null && memberName(body) === "remoteControl" && + body.object?.type === "CallExpression" && body.object.callee?.name === get && + body.object.arguments.length === 1 && body.object.arguments[0].type === "Identifier") { + remoteControlAtoms.add(name); + } + }); // 26.908 起,Git 仓库限制位于派生选择器中,而不是菜单 push 表达式中。 walkWithAncestors(ast, (node, ancestors) => { @@ -278,12 +296,29 @@ function findSidebarPatchContexts(ast, source) { if ( conversationId == null || hostId == null || - get == null || - !code.includes("remote_control_connections") + get == null ) { return; } + let derivedRemoteExclusion = false; + walk(node.body, (candidate) => { + if (candidate.type !== "UnaryExpression" || candidate.operator !== "!") return; + const some = candidate.argument?.type === "ChainExpression" + ? candidate.argument.expression : candidate.argument; + const read = some?.callee?.object; + const predicate = some?.arguments?.[0]; + if (some?.type === "CallExpression" && memberName(some.callee) === "some" && + read?.type === "CallExpression" && read.callee?.name === get && + read.arguments.length === 1 && remoteControlAtoms.has(read.arguments[0]?.name) && + predicate?.type === "ArrowFunctionExpression" && predicate.params[0]?.type === "Identifier" && + predicate.body?.type === "BinaryExpression" && predicate.body.operator === "===" && + memberName(predicate.body.left) === "hostId" && + predicate.body.left.object?.name === predicate.params[0].name && + predicate.body.right?.name === hostId) derivedRemoteExclusion = true; + }); + if (!code.includes("remote_control_connections") && !derivedRemoteExclusion) return; + const gitGates = []; walk(node.body, (candidate) => { if ( diff --git a/scripts/patch-thread-file-manager-action.test.js b/scripts/patch-thread-file-manager-action.test.js index 3d8ee1cd..c44cfc40 100644 --- a/scripts/patch-thread-file-manager-action.test.js +++ b/scripts/patch-thread-file-manager-action.test.js @@ -2,6 +2,8 @@ const test = require("node:test"); const assert = require("node:assert/strict"); const acorn = require("acorn"); const vm = require("node:vm"); +const fs = require("node:fs"); +const { nodes } = require("./patch-ast-util"); const { DIRECT_ACTION_ID, @@ -13,6 +15,61 @@ const { patchSource, } = require("./patch-thread-file-manager-action"); +test("26.1016 真实 Bundle:普通目录入口、远程排除和原打开链路", { + skip: !process.env.CODEX_PATCH_REAL_BUNDLE, +}, async () => { + const original = fs.readFileSync(process.env.CODEX_PATCH_REAL_BUNDLE, "utf8"); + const menu = patchSource(original); + assert.equal(menu.status, "patched"); + const result = patchSidebarSource(menu.source); + assert.equal(result.status, "patched"); + assert.equal(patchSource(result.source).source, result.source); + assert.equal(patchSidebarSource(result.source).source, result.source); + const ast = acorn.parse(result.source, { ecmaVersion: "latest", sourceType: "module" }); + const selectors = nodes(ast, node => node.type === "AssignmentExpression" && + node.left?.name === "VUc"); + assert.equal(selectors.length, 1); + const selector = selectors[0].right.arguments[1]; + const select = vm.runInNewContext(`(${result.source.slice(selector.start, selector.end)})`, { ah: "remote" }); + for (const connections of [[], [{ hostId: "local" }], [{ hostId: "other" }]]) { + assert.equal(select({ conversationId: "thread", hostId: "local" }, { + get: atom => { assert.equal(atom, "remote"); return connections; }, + }), !connections.some(item => item.hostId === "local")); + } + const callers = nodes(ast, node => node.type === "LogicalExpression" && + node.right?.type === "CallExpression" && node.right.callee?.property?.name === "push" && + result.source.slice(node.start, node.end).includes("...LUc(")); + assert.equal(callers.length, 1); + const expression = result.source.slice(callers[0].start, callers[0].end); + for (const cwd of [null, "C:\\plain-folder"]) { + const context = { v: cwd, e: { get: () => true }, VUc: {}, g: "thread", _: "local", + L: [], is: value => value, LUc: () => [{ id: DIRECT_ACTION_ID }] }; + vm.runInNewContext(expression, context); + assert.equal(context.L.length, cwd == null ? 0 : 1); + } + const builder = ast.body.find(node => node.type === "FunctionDeclaration" && node.id.name === "LUc"); + assert.ok(builder); + const builderSource = result.source.slice(builder.start, builder.end); + const openName = /onSelect:\(\)=>([\w$]+)\(/.exec(builderSource)?.[1]; + assert.ok(openName); + let opened; + const scope = { get: () => null, + query: { getData: () => ({ targets: [{ target: "fileManager", available: true, resolvedIcon: "folder-icon" }] }), + getOptions: () => ({ queryKey: [] }), fetch: async () => ({}) }, + queryClient: { getQueryState: () => ({ status: "success" }) } }; + const context = { navigator: { platform: "Win32" }, Iq: {}, DJt: {}, ay: {}, + scope, RUc: () => [{ id: "open-workspace-in", icon: "icon" }], + [openName]: params => { opened = params; } }; + vm.runInNewContext(`${builderSource};items=LUc({scope,cwd:'C:/plain-folder',hostId:'local'})`, context); + assert.equal(context.items[0].id, DIRECT_ACTION_ID); + assert.equal(context.items[0].message.id, "sidebarElectron.openWorkspaceRootInExplorer"); + context.items[0].onSelect(); + assert.equal(opened.target, "fileManager"); + assert.equal(opened.cwd, "C:/plain-folder"); + assert.equal(opened.hostId, "local"); + assert.equal(Object.hasOwn(opened, "persistPreferredTargetPath"), false); +}); + function createGroupedMenuBundle(options = {}) { const openHelper = options.includeOpenHelper === false ? "" From 0ab12e4199bdfe6d0bdc282afa2930ac61d93140 Mon Sep 17 00:00:00 2001 From: carptopus Date: Fri, 23 Oct 2026 01:32:56 +0800 Subject: [PATCH 42/51] fix: validate home recorder by call contract --- scripts/frontend-source-smoke.js | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index 3396c8bd..12d927a7 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -80,7 +80,23 @@ function verifyFrontendSource(assets) { && fs.readFileSync(path.join(assets, name), "utf8").includes("Codex:API-key 首页使用官方记录器。")); assert.equal(navigationEntries.length, 1); const navigationSource = fs.readFileSync(path.join(assets, navigationEntries[0]), "utf8"); - assert.match(navigationSource, /\/\* Codex:API-key 首页使用官方记录器。 \*\/if\([A-Za-z_$][\w$]*===`apikey`\)\{QBa\([A-Za-z_$][\w$]*,\{accountKey:`auth:apikey`,auth:[A-Za-z_$][\w$]*,location:[A-Za-z_$][\w$]*,productMode:[A-Za-z_$][\w$]*\}\);return;\}/); + const recorder = /\/\* Codex:API-key 首页使用官方记录器。 \*\/if\([A-Za-z_$][\w$]*===`apikey`\)\{([A-Za-z_$][\w$]*)\([A-Za-z_$][\w$]*,\{accountKey:`auth:apikey`,auth:[A-Za-z_$][\w$]*,location:[A-Za-z_$][\w$]*,productMode:[A-Za-z_$][\w$]*\}\);return;\}/.exec(navigationSource); + assert.ok(recorder, "API-key 首页必须调用结构完整的官方记录器"); + // 校验实际调用契约,不绑定压缩函数名;仍要求与原生五字段调用共用唯一记录器。 + const navigationAst = parse(navigationSource, { ecmaVersion: "latest", sourceType: "module" }); + let recorderDefinitions = 0, officialRecorderCalls = 0; + walk(navigationAst, node => { + if (node.type === "FunctionDeclaration" && node.id?.name === recorder[1]) recorderDefinitions++; + if (node.type !== "CallExpression" || node.callee?.name !== recorder[1] || + node.arguments.length !== 2 || node.arguments[0]?.type !== "Identifier" || + node.arguments[1]?.type !== "ObjectExpression") return; + const properties = node.arguments[1].properties; + if (properties.length === 5 && ["accountKey", "auth", "location", "productMode", "destinationId"] + .every(name => properties.filter(property => property.key?.name === name && + property.value?.type === "Identifier").length === 1)) officialRecorderCalls++; + }); + assert.equal(recorderDefinitions, 1, "官方首页记录器定义必须唯一"); + assert.equal(officialRecorderCalls, 1, "官方首页五字段记录调用必须唯一"); assert.doesNotMatch(navigationSource, /Codex:API-key 首页记录真实会话。/); assert.match(navigationSource, /\([A-Za-z_$][\w$]*\|\|\/\* Codex:API-key 首页保持当前位置。 \*\/[A-Za-z_$][\w$]*===`auth:apikey`&&[A-Za-z_$][\w$]*===`home`\)&&[A-Za-z_$][\w$]*!=null/); From d2eaa6cfd001db20b13c8c7200c6f12bb8f62ba6 Mon Sep 17 00:00:00 2001 From: carptopus Date: Sun, 25 Oct 2026 12:37:11 +0800 Subject: [PATCH 43/51] fix: absorb thread actions and update retries --- README.md | 3 + scripts/check-update.js | 56 ++-- scripts/check-update.test.js | 44 ++- scripts/fetch-msstore.js | 57 ++-- scripts/fetch-msstore.test.js | 36 ++- scripts/patch-policy.js | 1 + scripts/patch-thread-copy-markdown.js | 208 ++++++++++++++ scripts/patch-thread-copy-markdown.test.js | 264 ++++++++++++++++++ scripts/patch-thread-file-manager-action.js | 172 ++++++++---- .../patch-thread-file-manager-action.test.js | 254 +++++++++++++++-- 10 files changed, 964 insertions(+), 131 deletions(-) create mode 100644 scripts/patch-thread-copy-markdown.js create mode 100644 scripts/patch-thread-copy-markdown.test.js diff --git a/README.md b/README.md index d54a3855..8c637ad5 100644 --- a/README.md +++ b/README.md @@ -56,9 +56,12 @@ pnpm run build:all - `patch-reading-layout.js` 在外观主题卡片中加入 50%–100%、步进 5% 的正文宽度滑杆,并同步代码块、表格和输入区宽度,扩宽适用对话框;百分比不低于官方宽度,Markdown 粗体颜色可跟随正文、强调色或使用自定义颜色。 - `patch-test-isolation.js` 在官方设置 User Data 后、获取单实例锁前挂载 Windows 验收隔离,分别约束 `CODEX_HOME`、User Data 和 sessionData,并记录实际启动路径证据。 - `patch-model-picker-submenu.js` 增加对新版原生 simple / advanced 内联模型列表的结构核验;官方实现完整时保持原样,旧结构继续适配,未知结构明确失败。 +- `patch-thread-file-manager-action.js` 将系统文件管理器入口提升到会话菜单顶层,复用官方工作区打开回调,保留最新工作树解析及失败提示,不覆盖默认编辑器偏好;按菜单内容识别所在 Bundle,支持新版菜单迁移。 +- `patch-thread-copy-markdown.js` 修复未打开会话时 Markdown 复制可能为空的问题,仅在复制操作中加载完整历史,并在需要时复用官方快照及渲染器;不改变日常会话恢复和分页。 - `patch-archive-delete.js` 让归档列表明确查询全部 Provider,避免切换 Provider 后旧归档被隐藏;新版上游已有原生删除链路时保持原样,旧版才补充永久删除入口。 - `patch-updater.js` 区分更新方法与调用 Bundle,并在补丁后核对更新方法确实返回禁用状态;缺少目标或结构未知不再误报为已关闭。 - `sync-upstream.js`、`fetch-msstore.js` 和 `build-from-upstream.js` 强化 Windows x64 官方包选择与固定来源校验,支持精确版本和已验证原始 MSIX 重放;包身份、大小或 SHA-256 不符时拒绝构建,运行检查通过前不生成最终 ZIP。 +- `check-update.js` 在平台检测失败时输出对应错误并以退出码 2 标记检测不完整,不保存部分结果;`fetch-msstore.js` 先筛选目标包,再对同一包摘要的下载地址查询执行有限重试。 - `windows-artifacts.js` 与 `windows-maintenance.js` 记录官方来源和候选产物哈希,生成候选、验证发布门槛,并保证正式发布复用已经验收的同一 ZIP。 - `windows-runtime-checks.js` 检查 Windows EXE / 原生模块架构及未修改组件哈希,实际加载 CUA、运行 code-mode host / rg 基础命令,并执行空白隔离桌面的启动、就绪和退出冒烟。 - `check-scripts.js`、`frontend-source-smoke.js`、`reading-layout-smoke.js` 和 `maintenance-smoke.js` 覆盖脚本语法、真实补丁资源、阅读设置及候选/发布拒绝路径。这些属于补丁结构回归,只证明补丁仍能安全命中和拒绝未知结构;首页、主题、MCP 等运行效果仍以独立 GUI 验收项为准。 diff --git a/scripts/check-update.js b/scripts/check-update.js index 2903171f..e1646a85 100644 --- a/scripts/check-update.js +++ b/scripts/check-update.js @@ -181,9 +181,20 @@ function formatSize(bytes) { return (bytes / (1024 * 1024 * 1024)).toFixed(2) + " GB"; } +function summarizeChecks(checks) { + const platforms = ["macOS-arm64", "macOS-x64", "Windows"]; + const results = []; + const errors = {}; + checks.forEach((check, index) => { + if (check.status === "fulfilled") results.push(check.value); + else errors[platforms[index]] = check.reason?.message || String(check.reason); + }); + return { results, errors }; +} + // ─── 主流程 ────────────────────────────────────────────────────── -async function main() { - const args = process.argv.slice(2); +async function main(options = {}) { + const args = options.args || process.argv.slice(2); const force = args.includes("--force"); const jsonOutput = args.includes("--json"); const doSave = args.includes("--save"); @@ -191,20 +202,17 @@ async function main() { const versionFile = resolveVersionFile(args); const saved = loadVersions(versionFile); - const results = []; - - const checks = await Promise.allSettled([ - checkMacArm64Version(), - checkMacX64Version(), - checkWindowsVersion(), - ]); - - for (const r of checks) { - if (r.status === "fulfilled") { - const info = r.value; - results.push(info); - } else if (!quiet) { - console.error(` [!] ${r.reason.message}`); + const checkers = options.checkers || [ + checkMacArm64Version, + checkMacX64Version, + checkWindowsVersion, + ]; + const checks = await Promise.allSettled(checkers.map((check) => check())); + const { results, errors } = summarizeChecks(checks); + const hasErrors = Object.keys(errors).length > 0; + if (!quiet) { + for (const [platform, error] of Object.entries(errors)) { + console.error(` [!] ${platform}: ${error}`); } } @@ -214,8 +222,9 @@ async function main() { if (jsonOutput) { const output = { timestamp: new Date().toISOString(), - hasUpdates: updates.length > 0, + hasUpdates: hasErrors ? null : updates.length > 0, platforms: Object.fromEntries(results.map((r) => [r.platform, r])), + errors, previous: saved, }; console.log(JSON.stringify(output, null, 2)); @@ -224,7 +233,7 @@ async function main() { const toShow = force ? results : updates; if (toShow.length === 0 && !force) { - if (!quiet) console.log("✅ 没有新版本。"); + if (!quiet && !hasErrors) console.log("✅ 没有新版本。"); } else { for (const info of toShow) { const isUpdate = updates.includes(info); @@ -248,7 +257,7 @@ async function main() { } // 保存版本记录 - if (doSave && results.length > 0) { + if (doSave && !hasErrors && results.length > 0) { const newSaved = { ...saved }; for (const r of results) { newSaved[r.platform] = { @@ -261,10 +270,11 @@ async function main() { if (!quiet) console.log(`💾 版本记录已保存到 ${versionFile}`); } - // 退出码: 0=有更新, 1=无更新(方便 CI 使用) - if (!force && updates.length === 0) process.exitCode = 1; + // 退出码: 0=有更新或强制成功,1=无更新,2=检测不完整。 + if (hasErrors) process.exitCode = 2; + else if (!force && updates.length === 0) process.exitCode = 1; - return { results, updates }; + return { results, updates, errors, exitCode: hasErrors ? 2 : (!force && updates.length === 0 ? 1 : 0) }; } module.exports = { @@ -273,6 +283,8 @@ module.exports = { checkWindowsVersion, findUpdates, resolveVersionFile, + summarizeChecks, + main, }; if (require.main === module) { diff --git a/scripts/check-update.test.js b/scripts/check-update.test.js index 46138a31..dbc540b2 100644 --- a/scripts/check-update.test.js +++ b/scripts/check-update.test.js @@ -1,8 +1,11 @@ const test = require("node:test"); const assert = require("node:assert/strict"); const path = require("path"); +const fs = require("fs"); +const os = require("os"); +const { randomUUID } = require("crypto"); -const { findUpdates, resolveVersionFile } = require("./check-update"); +const { findUpdates, resolveVersionFile, main } = require("./check-update"); const CURRENT_PLATFORMS = [ { platform: "macOS-arm64", version: "26.721.41059", build: "5848" }, @@ -54,3 +57,42 @@ test("缺少状态文件路径时直接失败", () => { /需要提供文件路径/ ); }); + +test("检测不完整时 JSON 报错、退出码为 2 且不保存部分结果", async () => { + const testRoot = process.env.CODEX_REBUILD_TEST_ROOT || os.tmpdir(); + const dir = path.join(testRoot, `check-update-${randomUUID()}`); + const stateFile = path.join(dir, "versions.json"); + const saved = { Windows: { version: "26.721.4979.0" } }; + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(stateFile, JSON.stringify(saved)); + const output = []; + const previousExitCode = process.exitCode; + const previousLog = console.log; + const previousError = console.error; + + try { + process.exitCode = 0; + console.log = (line) => output.push(line); + console.error = () => {}; + const result = await main({ + args: ["--json", "--save", "--state-file", stateFile], + checkers: [ + async () => CURRENT_PLATFORMS[0], + async () => CURRENT_PLATFORMS[1], + async () => { throw new Error("Store unavailable"); }, + ], + }); + + const json = JSON.parse(output[0]); + assert.equal(json.hasUpdates, null); + assert.deepEqual(json.errors, { Windows: "Store unavailable" }); + assert.equal(result.errors.Windows, "Store unavailable"); + assert.equal(process.exitCode, 2); + assert.deepEqual(JSON.parse(fs.readFileSync(stateFile, "utf-8")), saved); + } finally { + process.exitCode = previousExitCode; + console.log = previousLog; + console.error = previousError; + fs.rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/scripts/fetch-msstore.js b/scripts/fetch-msstore.js index 9def1d97..6d5dc313 100644 --- a/scripts/fetch-msstore.js +++ b/scripts/fetch-msstore.js @@ -386,26 +386,37 @@ async function getFileList(cookie, categoryId, ring) { return updates; } -async function getDownloadUrl(updateID, revisionNumber, ring, digest) { +async function getDownloadUrl(updateID, revisionNumber, ring, digest, options = {}) { const soap = makeGetUrlSoap(updateID, revisionNumber, ring); - const res = await soapPost( - "https://fe3.delivery.mp.microsoft.com/ClientWebService/client.asmx/secured", - soap - ); - - if (res.status !== 200) return ""; - - const parsed = parseXml(res.body); - const locations = deepFindAll(parsed, "FileLocation"); + const request = options.request || ((url, body) => httpsRequestOnce(url, { + method: "POST", + headers: { + "Content-Type": "application/soap+xml; charset=utf-8", + "Content-Length": Buffer.byteLength(body, "utf-8"), + }, + body, + })); + // 商店灰度发布时可能 HTTP 200 但暂时没有匹配文件;重试同一更新且不放宽摘要校验。 + return withRetry(async () => { + const res = await request( + "https://fe3.delivery.mp.microsoft.com/ClientWebService/client.asmx/secured", + soap + ); + if (res.status !== 200) { + throw new Error(`GetExtendedUpdateInfo2 失败: HTTP ${res.status}`); + } - for (const loc of locations) { - const fileDigest = deepFind(loc, "FileDigest"); - const url = deepFind(loc, "Url"); - if (fileDigest === digest && url) return url; - } + const locations = deepFindAll(parseXml(res.body), "FileLocation"); + for (const loc of locations) { + const fileDigest = deepFind(loc, "FileDigest"); + const url = deepFind(loc, "Url"); + if (digest && fileDigest === digest && typeof url === "string" && /^https?:\/\//.test(url)) { + return url; + } + } - // 不得将其他包的 URL 作为主包下载地址。 - return ""; + throw new Error(`微软未返回与包摘要匹配的下载链接 (${updateID})`); + }, options); } // ─── 深度搜索辅助 ──────────────────────────────────────────────── @@ -590,9 +601,13 @@ async function main() { // Step 4: Get URLs console.log(` [4/4] 获取下载链接...`); + const selected = filter + ? packages.filter((pkg) => pkg.name.toLowerCase().includes(filter)) + : packages; const results = []; - for (const pkg of packages) { + // 先筛选目标包,避免无关架构或依赖包的链接失败阻断目标包处理。 + for (const pkg of selected) { const url = await getDownloadUrl( pkg.updateID, pkg.revisionNumber, @@ -602,11 +617,7 @@ async function main() { results.push({ ...pkg, url }); } - // 过滤 - let filtered = results; - if (filter) { - filtered = results.filter((r) => r.name.toLowerCase().includes(filter)); - } + const filtered = results; // 输出结果 console.log(`\n${"─".repeat(80)}`); diff --git a/scripts/fetch-msstore.test.js b/scripts/fetch-msstore.test.js index 5e88a5f3..80502fec 100644 --- a/scripts/fetch-msstore.test.js +++ b/scripts/fetch-msstore.test.js @@ -1,7 +1,7 @@ const test = require("node:test"); const assert = require("node:assert/strict"); -const { withRetry } = require("./fetch-msstore"); +const { getDownloadUrl, withRetry } = require("./fetch-msstore"); test("临时请求失败后会重试并返回结果", async () => { let attempts = 0; @@ -35,3 +35,37 @@ test("请求持续失败时达到次数上限后抛出最后一个错误", async assert.equal(attempts, 3); }); + +test("商店暂时未返回文件位置时有限重试同一更新", async () => { + let calls = 0; + const url = await getDownloadUrl("update-1", "1", "Retail", "expected", { + retryDelayMs: 0, + request: async (_url, body) => { + assert.match(body, /update-1<\/UpdateID>/); + calls++; + return { + status: 200, + body: calls === 1 + ? "" + : "expectedhttps://example.com/app.msix", + }; + }, + }); + + assert.equal(url, "https://example.com/app.msix"); + assert.equal(calls, 2); +}); + +test("摘要不匹配时不返回其他包的 URL", async () => { + await assert.rejects( + getDownloadUrl("update-1", "1", "Retail", "expected", { + maxAttempts: 1, + retryDelayMs: 0, + request: async () => ({ + status: 200, + body: "differenthttps://example.com/other.msix", + }), + }), + /摘要匹配/ + ); +}); diff --git a/scripts/patch-policy.js b/scripts/patch-policy.js index 544b35dd..da2f743a 100644 --- a/scripts/patch-policy.js +++ b/scripts/patch-policy.js @@ -32,6 +32,7 @@ const PATCH_POLICY = [ { script: "patch-model-catalog-filter.js", feature: "模型目录过滤" }, { script: "patch-model-picker-submenu.js", feature: "模型选择器子菜单" }, { script: "patch-thread-file-manager-action.js", feature: "会话文件管理器入口" }, + { script: "patch-thread-copy-markdown.js", feature: "未打开会话的完整 Markdown 复制" }, { script: "patch-browser-auth.js", feature: "API-key 浏览器认证" }, { script: "patch-plugin-auth.js", feature: "插件认证与功能开关" }, { script: "patch-remote-control.js", feature: "Remote Control 认证隔离" }, diff --git a/scripts/patch-thread-copy-markdown.js b/scripts/patch-thread-copy-markdown.js new file mode 100644 index 00000000..c1153394 --- /dev/null +++ b/scripts/patch-thread-copy-markdown.js @@ -0,0 +1,208 @@ +#!/usr/bin/env node +/** 修复未打开会话时“复制为 Markdown”取不到完整历史的问题。 */ +const fs = require("node:fs"); +const path = require("node:path"); +const { parse } = require("acorn"); +const { SRC_DIR, relPath } = require("./patch-util"); + +const MARKER = "/* CodexRebuild: copy complete conversation Markdown */"; +const ERROR_ID = "threadActions.copyConversationMarkdown.copyConversationMarkdownError"; +const PLATFORMS = ["mac-arm64", "mac-x64", "win"]; + +function walk(node, visit) { + if (!node || typeof node !== "object") return; + if (node.type) visit(node); + for (const value of Object.values(node)) { + if (Array.isArray(value)) value.forEach((child) => walk(child, visit)); + else if (value?.type) walk(value, visit); + } +} + +function name(node) { return node?.name ?? node?.value ?? null; } + +function operands(node) { + return node?.type === "LogicalExpression" && node.operator === "&&" + ? [...operands(node.left), ...operands(node.right)] + : [node]; +} + +function findHelpers(ast, source) { + const found = { complete: [], render: [], visible: [], excluded: [] }; + walk(ast, (node) => { + if (node.type !== "FunctionDeclaration" || !node.id) return; + const body = source.slice(node.start, node.end); + const keys = node.params[0]?.type === "ObjectPattern" + ? node.params[0].properties.map((property) => name(property.key)) : []; + if (["visibleTurnEntries", "title", "cwd"].every((key) => keys.includes(key)) && + body.includes("renderConversationMarkdown")) found.render.push(node.id.name); + if (["conversationRequests", "conversationTurns", "hasConversation", "parentConversationTurns", "subagentParentThreadId"] + .every((key) => keys.includes(key))) found.visible.push(node.id.name); + if (body.includes("Conversation must be resumed before loading history")) { + walk(node.body, (child) => { + if (child.type !== "VariableDeclarator") return; + const call = child.init; + if (call?.type === "CallExpression" && call.callee.type === "Identifier" && + call.arguments.length === 1 && name(call.arguments[0]?.callee?.property) === "getConversation") { + found.complete.push(call.callee.name); + } + }); + } + const options = node.params[1]; + const optionKeys = options?.type === "ObjectPattern" + ? options.properties.map((property) => name(property.key)) : []; + if (["conversationId", "isBackgroundSubagentsEnabled", "markdownLimit"].every((key) => optionKeys.includes(key)) && + body.includes("visibleTurnEntries")) { + const first = node.body.body[0]; + if (first?.type === "IfStatement" && first.test.type === "CallExpression" && + first.test.callee.type === "Identifier" && first.consequent.type === "ReturnStatement" && + first.consequent.argument?.type === "Literal" && first.consequent.argument.value === null) { + found.excluded.push(first.test.callee.name); + } + } + }); + if (Object.values(found).some((matches) => matches.length !== 1)) return null; + return Object.fromEntries(Object.entries(found).map(([key, matches]) => [key, matches[0]])); +} + +function validatePatched(source) { + if (source.split(MARKER).length !== 2) throw new Error("补丁标记数量异常"); + const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const marked = []; + walk(ast, (node) => { + if (node.type === "FunctionDeclaration" && source.slice(node.start, node.end).includes(MARKER)) marked.push(node); + }); + if (marked.length !== 1) throw new Error("补丁标记未唯一位于复制动作中"); + const body = source.slice(marked[0].start, marked[0].end); + if (!body.includes("force:!0") || !body.includes("getConversation") || + !body.includes("会话历史不完整") || !body.includes("无法写入剪贴板")) { + throw new Error("补丁完整历史或失败保护结构异常"); + } +} + +function patchSource(source) { + if (source.includes(MARKER)) { + try { validatePatched(source); return { status: "already-patched", source }; } + catch (error) { return { status: "unexpected-shape", source, reason: error.message }; } + } + if (!source.includes(ERROR_ID)) return { status: "signature-missing", source }; + let ast; + try { ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); } + catch (error) { return { status: "parse-error", source, reason: error.message }; } + + const candidates = []; + walk(ast, (node) => { + if (node.type !== "FunctionDeclaration" || node.params.length !== 1 || node.params[0].type !== "ObjectPattern") return; + const bindings = new Map(node.params[0].properties.map((property) => [name(property.key), name(property.value)])); + if (["scope", "conversationId", "parentConversationId", "getMarkdown", "intl"] + .every((key) => bindings.has(key)) && source.slice(node.start, node.end).includes(ERROR_ID)) { + candidates.push({ node, bindings }); + } + }); + if (candidates.length !== 1) return { status: "ambiguous-copy-action", source, count: candidates.length }; + + const { node, bindings } = candidates[0]; + const statements = node.body.body; + const chain = statements[0]?.expression; + const iife = chain?.callee?.object?.callee; + const body = iife?.body?.body; + const ensure = body?.[0]?.expression?.argument; + const markdown = body?.[1]?.declarations?.[0]; + const parts = operands(body?.[2]?.expression); + const copy = parts[2]; + const success = parts[3]; + const text = (item) => item ? source.slice(item.start, item.end) : ""; + if (statements.length !== 1 || statements[0].type !== "ExpressionStatement" || + name(chain?.callee?.property) !== "catch" || chain.arguments.length !== 1 || + iife?.type !== "ArrowFunctionExpression" || !iife.async || body?.length !== 3 || + body[0].expression?.type !== "AwaitExpression" || ensure?.type !== "CallExpression" || + name(ensure.callee?.property) !== "ensureConversationHistoryLoaded" || ensure.arguments.length !== 2 || + name(ensure.arguments[0]) !== bindings.get("conversationId") || body[1].declarations?.length !== 1 || + markdown?.id?.type !== "Identifier" || markdown.init?.type !== "AwaitExpression" || + name(markdown.init.argument?.callee) !== bindings.get("getMarkdown") || + body[2].type !== "ExpressionStatement" || parts.length !== 4 || + copy?.type !== "AwaitExpression" || copy.argument?.type !== "CallExpression" || + copy.argument.arguments.length !== 1 || name(copy.argument.arguments[0]) !== markdown.id.name || + success?.type !== "CallExpression" || name(success.callee?.property) !== "success" || + !text(success).includes("copyConversationMarkdownSuccess")) { + return { status: "unsupported-copy-structure", source }; + } + const helpers = findHelpers(ast, source); + if (!helpers) return { status: "unsupported-history-renderer", source }; + const nonempty = `${text(parts[0])}&&${text(parts[1])}`; + const id = bindings.get("conversationId"); + const parent = bindings.get("parentConversationId"); + const value = markdown.id.name; + const fallback = `if(!(${nonempty})){` + + `const __crClient=${text(ensure.callee.object)};` + + `const __crConversation=await __crClient.getConversation(${id});` + + `const __crParent=${parent}==null?null:await __crClient.getConversation(${parent});` + + `if(__crConversation==null||(${parent}!=null&&__crParent==null)||${helpers.excluded}(__crConversation.threadSource))throw new Error("会话不可导出");` + + `const __crTurns=${helpers.complete}(__crConversation);` + + `const __crParentTurns=${parent}==null?[]:${helpers.complete}(__crParent);` + + `if(__crTurns==null||__crParentTurns==null)throw new Error("会话历史不完整");` + + `const {visibleTurnEntries:__crEntries}=${helpers.visible}({conversationRequests:__crConversation.requests,conversationTurns:__crTurns,hasConversation:!0,isBackgroundSubagentsEnabled:!0,parentConversationTurns:__crParentTurns,subagentParentThreadId:${parent}});` + + `${value}=await ${helpers.render}({cwd:__crConversation.cwd,title:__crConversation.title,projectlessOutputDirectory:__crConversation.projectlessOutputDirectory,isBackgroundSubagentsEnabled:!0,visibleTurnEntries:__crEntries});}`; + const guards = `if(!(${nonempty}))throw new Error("会话没有可复制的内容");` + + `if(!(${text(copy)}))throw new Error("无法写入剪贴板");${text(success)};`; + const edits = [ + { start: ensure.end - 1, replacement: ",{force:!0}" }, + { start: body[2].start, end: body[2].end, replacement: fallback + guards }, + { start: node.body.start + 1, replacement: `${MARKER}return ` }, + ].sort((a, b) => b.start - a.start); + let result = source; + for (const edit of edits) result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end ?? edit.start); + try { validatePatched(result); } + catch (error) { return { status: "invalid-patch-result", source, reason: error.message }; } + return { status: "patched", source: result }; +} + +function findTargets(platform) { + const requested = platform ? [platform] : PLATFORMS; + const targets = []; + const errors = []; + for (const current of requested) { + const assets = path.join(SRC_DIR, current, "_asar", "webview", "assets"); + if (!fs.existsSync(assets)) continue; + const files = fs.readdirSync(assets).filter((file) => /^app-(?:initial|primary)-.*\.js$/.test(file)); + const candidates = files.map((name) => { + const file = path.join(assets, name); + return { path: file, source: fs.readFileSync(file, "utf8") }; + }).filter(({ source }) => source.includes(ERROR_ID) || source.includes(MARKER)); + if (candidates.length !== 1) { + errors.push(`${current}: 复制动作源码签名 ${ERROR_ID} 数量异常(${candidates.length})`); + continue; + } + targets.push({ platform: current, ...candidates[0] }); + } + return { targets, errors }; +} + +function main() { + const args = process.argv.slice(2); + const unknown = args.filter((arg) => arg !== "--check" && !PLATFORMS.includes(arg)); + if (unknown.length) throw new Error(`未知参数:${unknown.join(", ")}`); + const platforms = args.filter((arg) => PLATFORMS.includes(arg)); + if (platforms.length > 1) throw new Error("只能指定一个平台"); + const check = args.includes("--check"); + const { targets, errors } = findTargets(platforms[0]); + for (const error of errors) { console.error(` [x] ${error}`); process.exitCode = 1; } + if (!targets.length && !errors.length) { console.error(" [x] 缺少目标平台界面资源"); process.exitCode = 1; } + for (const target of targets) { + const result = patchSource(target.source); + if (result.status === "already-patched") console.log(` [ok] ${relPath(target.path)}: already patched`); + else if (result.status === "patched") { + if (!check) fs.writeFileSync(target.path, result.source, "utf8"); + console.log(` [ok] ${relPath(target.path)}: ${check ? "check only; no write" : "patched"}`); + } else { + console.error(` [x] ${target.platform}: ${result.status}${result.reason ? `: ${result.reason}` : ""}`); + process.exitCode = 1; + } + } +} + +if (require.main === module) { + try { main(); } + catch (error) { console.error(` [x] ${error.message}`); process.exitCode = 1; } +} + +module.exports = { ERROR_ID, MARKER, patchSource, findTargets, validatePatched }; diff --git a/scripts/patch-thread-copy-markdown.test.js b/scripts/patch-thread-copy-markdown.test.js new file mode 100644 index 00000000..6e124701 --- /dev/null +++ b/scripts/patch-thread-copy-markdown.test.js @@ -0,0 +1,264 @@ +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { spawnSync } = require("node:child_process"); +const test = require("node:test"); +const vm = require("node:vm"); +const { parse } = require("acorn"); +const { ERROR_ID, MARKER, patchSource, validatePatched } = require("./patch-thread-copy-markdown"); + +const nativeFixture = "async function getComplete(client,id){if(!client)throw Error('Conversation must be resumed before loading history');let result=complete(client.getConversation(id));return result}" + + "async function renderNative({visibleTurnEntries,cwd,title}){return renderConversationMarkdown(visibleTurnEntries,cwd,title)}" + + "function visibleNative({conversationRequests,conversationTurns,hasConversation,parentConversationTurns,subagentParentThreadId}){return{visibleTurnEntries:conversationTurns}}" + + "async function readView(scope,{conversationId,isBackgroundSubagentsEnabled,markdownLimit}){if(excluded(scope.source))return null;let {visibleTurnEntries}=scope.get(conversationId);return renderNative({visibleTurnEntries})}"; +const fixture = nativeFixture + "function copy({scope:s,conversationId:id,parentConversationId:parent,getMarkdown:render,intl:i}){" + + "(async()=>{await manager(s,s.get(host,id)).ensureConversationHistoryLoaded(id,parent==null?[]:[parent]);" + + "let markdown=await render();markdown!=null&&markdown.trim().length!==0&&await write(markdown)&&" + + "s.get(toasts).success(i.formatMessage(messages.copyConversationMarkdownSuccess))})().catch(()=>{" + + `s.get(toasts).danger(i.formatMessage(messages.copyConversationMarkdownError),{errorAnalytics:{toastId:'${ERROR_ID}'}})})}`; + +function compile({ content = "# 会话\n实际历史", clipboard = true, failure, viewLoaded = false, source = "user", parentMissing = false } = {}) { + const result = patchSource(fixture); + assert.equal(result.status, "patched"); + const calls = []; + const written = []; + const notices = []; + let loaded = false; + const client = { + async getConversation(id) { + if (parentMissing && id === "parent-thread") return null; + return { content, threadSource: source, requests: [], complete: loaded && failure !== "incomplete" }; + }, + async ensureConversationHistoryLoaded(id, parents, options) { + calls.push({ id, parents, options }); + if (failure === "history") throw Error("读取历史失败"); + if (options?.force) loaded = true; + }, + }; + const notify = { success: (value) => notices.push(["success", value]), danger: (value) => notices.push(["danger", value]) }; + const scope = { get: (token) => token === "toasts" ? notify : "local" }; + const copy = vm.runInNewContext(`${result.source};copy`, { + host: "host", toasts: "toasts", manager: () => client, + messages: { copyConversationMarkdownSuccess: "复制成功", copyConversationMarkdownError: "复制失败" }, + write: async (text) => { + if (failure === "clipboard") throw Error("剪贴板占用"); + if (clipboard) written.push(text); + return clipboard; + }, + complete: (conversation) => conversation?.complete ? [conversation.content] : null, + excluded: (value) => value === "unsupported", + renderConversationMarkdown: (entries) => entries[0], + }); + const run = (parent) => copy({ scope, conversationId: "thread", parentConversationId: parent, + getMarkdown: async () => { + if (failure === "render") throw Error("格式化失败"); + return loaded && viewLoaded ? content : null; + }, intl: { formatMessage: (value) => value } }); + return { run, calls, written, notices }; +} + +test("冷会话复制强制加载完整历史,再写入内容并提示成功", async () => { + const h = compile(); + await h.run(); + assert.equal(h.calls[0].options.force, true); + assert.equal(h.calls[0].id, "thread"); + assert.deepEqual(h.written, ["# 会话\n实际历史"]); + assert.deepEqual(h.notices, [["success", "复制成功"]]); +}); + +test("子代理复制保留父会话加载并读取", async () => { + const h = compile(); + await h.run("parent-thread"); + assert.deepEqual([...h.calls[0].parents], ["parent-thread"]); + assert.deepEqual(h.notices, [["success", "复制成功"]]); +}); + +test("已打开页面继续使用官方 Markdown 回调", async () => { + const h = compile({ viewLoaded: true }); + await h.run(); + assert.deepEqual(h.written, ["# 会话\n实际历史"]); +}); + +test("后台历史不完整或父会话快照缺失时拒绝复制", async () => { + const incomplete = compile({ failure: "incomplete" }); + await incomplete.run(); + assert.deepEqual(incomplete.written, []); + assert.deepEqual(incomplete.notices, [["danger", "复制失败"]]); + + const missing = compile({ parentMissing: true }); + await missing.run("parent-thread"); + assert.deepEqual(missing.written, []); + assert.deepEqual(missing.notices, [["danger", "复制失败"]]); +}); + +test("不支持的会话类型走原生错误提示", async () => { + const h = compile({ source: "unsupported" }); + await h.run(); + assert.deepEqual(h.written, []); + assert.deepEqual(h.notices, [["danger", "复制失败"]]); +}); + +for (const content of [null, "", " \n "]) { + test(`空 Markdown ${JSON.stringify(content)} 不写剪贴板并提示失败`, async () => { + const h = compile({ content }); + await h.run(); + assert.deepEqual(h.written, []); + assert.deepEqual(h.notices, [["danger", "复制失败"]]); + }); +} + +for (const failure of ["history", "render", "clipboard"]) { + test(`${failure} 失败沿用原生错误提示`, async () => { + const h = compile({ failure }); + await h.run(); + assert.deepEqual(h.written, []); + assert.deepEqual(h.notices, [["danger", "复制失败"]]); + }); +} + +test("剪贴板写入返回 false 时提示失败", async () => { + const h = compile({ clipboard: false }); + await h.run(); + assert.deepEqual(h.written, []); + assert.deepEqual(h.notices, [["danger", "复制失败"]]); +}); + +test("补丁幂等且保留复制动作之外的加载调用", () => { + const unrelated = "function unrelated(){return client.ensureConversationHistoryLoaded(id,[])}"; + const first = patchSource(fixture + unrelated); + const second = patchSource(first.source); + assert.equal(second.status, "already-patched"); + assert.equal(second.source, first.source); + assert.ok(first.source.endsWith(unrelated)); +}); + +test("结构漂移、重复复制动作和缺少原生 helper 均 fail-closed", () => { + const changed = fixture.replace("ensureConversationHistoryLoaded(id,", "differentHistoryLoader(id,"); + assert.equal(patchSource(changed).status, "unsupported-copy-structure"); + const duplicate = fixture + fixture.slice(nativeFixture.length).replace("function copy(", "function duplicateCopy("); + assert.equal(patchSource(duplicate).status, "ambiguous-copy-action"); + assert.equal(patchSource(fixture.replace("renderConversationMarkdown(visibleTurnEntries", "changedRenderer(visibleTurnEntries")).status, + "unsupported-history-renderer"); + assert.equal(patchSource(fixture.replace(ERROR_ID, "missing.error.signature")).status, "signature-missing"); +}); + +test("已有标记必须通过补丁后结构验证", () => { + const damaged = fixture.replace("function copy(", `function copy(){${MARKER};function copy(`); + assert.equal(patchSource(damaged).status, "unexpected-shape"); + assert.throws(() => validatePatched(`${MARKER} broken`)); +}); + +test("check 模式定位单一原生入口,未改变输入内容", () => { + const before = fixture; + const result = patchSource(before); + assert.equal(result.status, "patched"); + assert.equal(fixture, before); + assert.equal(patchSource(result.source).status, "already-patched"); +}); + +test("CLI 按 check、apply、check 执行且拒绝重复源码签名", (t) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "codex-copy-markdown-")); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const assets = path.join(root, "win", "_asar", "webview", "assets"); + fs.mkdirSync(assets, { recursive: true }); + const target = path.join(assets, "app-primary-test.js"); + fs.writeFileSync(target, fixture); + const script = path.join(__dirname, "patch-thread-copy-markdown.js"); + const check = spawnSync(process.execPath, [script, "win", "--check"], { + encoding: "utf8", env: { ...process.env, CODEX_PATCH_SOURCE_DIR: root }, + }); + assert.equal(check.status, 0, check.stderr); + assert.match(check.stdout, /check only; no write/); + assert.equal(fs.readFileSync(target, "utf8"), fixture); + + const apply = spawnSync(process.execPath, [script, "win"], { + encoding: "utf8", env: { ...process.env, CODEX_PATCH_SOURCE_DIR: root }, + }); + assert.equal(apply.status, 0, apply.stderr); + const applied = fs.readFileSync(target, "utf8"); + assert.notEqual(applied, fixture); + assert.equal(patchSource(applied).status, "already-patched"); + + const secondCheck = spawnSync(process.execPath, [script, "win", "--check"], { + encoding: "utf8", env: { ...process.env, CODEX_PATCH_SOURCE_DIR: root }, + }); + assert.equal(secondCheck.status, 0, secondCheck.stderr); + assert.equal(fs.readFileSync(target, "utf8"), applied); + + fs.writeFileSync(path.join(assets, "app-initial-duplicate.js"), fixture); + const duplicate = spawnSync(process.execPath, [script, "win", "--check"], { + encoding: "utf8", env: { ...process.env, CODEX_PATCH_SOURCE_DIR: root }, + }); + assert.equal(duplicate.status, 1); + assert.match(duplicate.stderr, /复制动作源码签名.*数量异常(2)/); +}); + +// 本场景固定验证 26.1016 的真实 renderer/helper 名称;ASAR 版本变化时需重新适配 fixture。 +test("26.1016 真实 ASAR 的复制函数执行冷快照与失败路径", { skip: !process.env.CODEX_PATCH_REAL_ASAR }, async () => { + const asar = require("@electron/asar"); + const crypto = require("node:crypto"); + const archive = path.resolve(process.env.CODEX_PATCH_REAL_ASAR); + assert.equal(crypto.createHash("sha256").update(fs.readFileSync(archive)).digest("hex"), + "8563a16801cccb9b3feb02a9a18052f4e6d1b2eb271827a44228d22deae99700"); + const entry = asar.listPackage(archive).find((file) => file.includes("app-initial-") && file.endsWith(".js")); + assert.ok(entry, "ASAR 缺少 app-initial JavaScript"); + const source = asar.extractFile(archive, entry.slice(1)).toString("utf8"); + const patched = patchSource(source); + assert.ok(["patched", "already-patched"].includes(patched.status), patched.reason || patched.status); + validatePatched(patched.source); + + const ast = parse(patched.source, { ecmaVersion: "latest", sourceType: "module" }); + const functions = []; + const visit = (node) => { + if (!node || typeof node !== "object") return; + if (node.type === "FunctionDeclaration" && patched.source.slice(node.start, node.end).includes(MARKER)) functions.push(node); + for (const value of Object.values(node)) { + if (Array.isArray(value)) value.forEach(visit); + else if (value?.type) visit(value); + } + }; + visit(ast); + assert.equal(functions.length, 1); + const fnNode = functions[0]; + const fnSource = patched.source.slice(fnNode.start, fnNode.end); + const parameters = Object.fromEntries(fnNode.params[0].properties.map((property) => [property.key.name, property.value.name])); + const execute = async ({ incomplete = false, empty = false, writeFails = false, parent = null } = {}) => { + let loaded = false; const reads = []; const writes = []; const notices = []; + const client = { + async ensureConversationHistoryLoaded(id, parents, options) { assert.equal(options.force, true); loaded = true; reads.push(...parents); }, + async getConversation(id) { + reads.push(id); + return id === parent && parent ? { threadSource: "user", turns: ["parent"] } : + { threadSource: "user", requests: [], turns: incomplete ? null : ["cold session"], cwd: "C:\\repo", title: "Cold", projectlessOutputDirectory: null }; + }, + }; + const scope = { get: (token) => token === "toasts" ? { success: (value) => notices.push(["success", value]), danger: (value) => notices.push(["danger", value]) } : client }; + const context = { + yk: "host", nl: "toasts", mY: { copyConversationMarkdownSuccess: "ok", copyConversationMarkdownError: "error" }, + gh: (_scope, value) => value, VSo: () => false, + _4t: (snapshot) => snapshot?.turns ?? null, + vCo: ({ conversationTurns, parentConversationTurns }) => ({ visibleTurnEntries: [...parentConversationTurns, ...conversationTurns] }), + HCo: async ({ visibleTurnEntries }) => empty ? " " : visibleTurnEntries.join("\n"), + Vi: async (value) => { if (writeFails) return false; writes.push(value); return true; }, + }; + const run = vm.runInNewContext(`(${fnSource})`, context); + await run({ scope, conversationId: "thread", parentConversationId: parent, + getMarkdown: async () => null, intl: { formatMessage: (value) => value } }); + return { loaded, reads, writes, notices }; + }; + const cold = await execute(); + assert.equal(cold.loaded, true); + assert.deepEqual(cold.writes, ["cold session"]); + assert.deepEqual(cold.notices, [["success", "ok"]]); + const parentResult = await execute({ parent: "parent-thread" }); + assert.ok(parentResult.reads.includes("parent-thread")); + const incomplete = await execute({ incomplete: true }); + assert.deepEqual(incomplete.writes, []); + assert.deepEqual(incomplete.notices, [["danger", "error"]]); + const emptyResult = await execute({ empty: true }); + assert.deepEqual(emptyResult.writes, []); + assert.deepEqual(emptyResult.notices, [["danger", "error"]]); + const writeFailure = await execute({ writeFails: true }); + assert.deepEqual(writeFailure.notices, [["danger", "error"]]); +}); diff --git a/scripts/patch-thread-file-manager-action.js b/scripts/patch-thread-file-manager-action.js index 17a86b23..f9cb19da 100644 --- a/scripts/patch-thread-file-manager-action.js +++ b/scripts/patch-thread-file-manager-action.js @@ -4,7 +4,10 @@ * * 26.825 起,上游把工作区的所有打开目标统一收进“打开方式”子菜单; * 26.901 又把侧边栏会话菜单拆到 app-primary,并仅为 Git 会话调用该菜单; - * 26.908 将该限制移入派生选择器;26.911 又将菜单构造器移回 app-initial。 + * 26.908 将该限制移入派生选择器;26.911 又将菜单构造器移回 app-initial; + * 26.1021 将两类菜单移回 app-primary,因此按菜单内容而非固定 chunk 定位。 + * 顶层入口复用工作区菜单回调,保留工作树解析和错误提示,避免调用要求 + * ThreadScope 的通用文件预览函数而在全局侧边栏抛 Missing scope instance。 * 本补丁先复用打开链路增加顶层入口,再按内容定位侧边栏菜单并放宽两种 * 结构中的 Git 限制,使所有有工作目录的本地会话都能显示入口。旧版若已 * 提供 open-thread-folder,则安全跳过。 @@ -18,7 +21,8 @@ const acorn = require("acorn"); const { locateBundles, relPath } = require("./patch-util"); const PLATFORMS = ["mac-arm64", "mac-x64", "win"]; -const MARKER = "/* Codex:对话菜单直接显示系统文件管理器入口。 */"; +const LEGACY_MARKER = "/* Codex:对话菜单直接显示系统文件管理器入口。 */"; +const MARKER = "/* Codex:对话菜单通过工作区打开链路显示系统文件管理器入口(v2)。 */"; const SIDEBAR_MARKER = "/* Codex:侧边栏会话菜单对普通目录显示打开入口。 */"; const DIRECT_ACTION_ID = "open-workspace-file-manager-direct"; @@ -32,15 +36,8 @@ const SIDEBAR_PATCHABLE_SIGNATURES = [ "id:`archive-thread`", "id:`open-in-new-window`", ]; -const SIDEBAR_BUNDLE_SIGNATURES = [ - "rename-thread", - "archive-thread", - "open-in-new-window", - "remote_control_connections", -]; - function hasSidebarMenuSignatures(source) { - return SIDEBAR_BUNDLE_SIGNATURES.every((signature) => + return SIDEBAR_PATCHABLE_SIGNATURES.every((signature) => source.includes(signature), ); } @@ -174,7 +171,6 @@ function parse(source) { function findPatchContext(ast, source) { const menuBuilders = []; - const openHelpers = []; walk(ast, (node) => { if (node.type !== "FunctionDeclaration" || node.id?.type !== "Identifier") { @@ -185,15 +181,7 @@ function findPatchContext(ast, source) { const mayBuildMenu = ["scope", "cwd", "hostId"].every((key) => bindings.has(key), ); - const mayOpenItem = [ - "scope", - "cwd", - "hostId", - "path", - "target", - "openMode", - ].every((key) => bindings.has(key)); - if (!mayBuildMenu && !mayOpenItem) return; + if (!mayBuildMenu) return; const code = source.slice(node.start, node.end); if ( @@ -233,16 +221,67 @@ function findPatchContext(ast, source) { menuBuilders.push({ bindings, returns, targetsVariables }); } - if ( - mayOpenItem && - code.includes("persistPreferredTargetPath") && - code.includes("openInSidePanel") - ) { - openHelpers.push(node.id.name); + }); + + return { menuBuilders }; +} + +function workspaceOpenCallback(call, source, scope) { + const callback = objectExpressionProperties(call.arguments[0]).get("onOpenInTarget"); + if (!callback || !["ArrowFunctionExpression", "FunctionExpression"].includes(callback.type)) { + return null; + } + const edits = []; + let openMutations = 0; + walk(callback, (node) => { + if (node.type === "Property" && propertyName(node) === "persistPreferredTargetPath") { + // 顶层单次打开不能改写原生子菜单保存的默认编辑器或终端。 + edits.push({ start: node.value.start, end: node.value.end, text: "void 0" }); + } + if (node.type !== "CallExpression") return; + const properties = objectExpressionProperties(node.arguments[0]); + if (["mutate", "mutateAsync"].includes(memberName(node.callee)) && + ["path", "cwd", "hostId", "target", "openMode"].every((key) => properties.has(key))) { + openMutations++; + } + const owner = node.callee?.object; + if (memberName(node.callee) === "setData" && memberName(owner) === "query" && + owner.object?.name === scope && source.slice(node.start, node.end).includes("preferredTarget")) { + edits.push({ start: node.start, end: node.end, text: "void 0" }); } }); + if (openMutations !== 1) return null; + let code = source.slice(callback.start, callback.end); + for (const edit of edits.sort((a, b) => b.start - a.start)) { + code = code.slice(0, edit.start - callback.start) + edit.text + code.slice(edit.end - callback.start); + } + return code; +} - return { menuBuilders, openHelpers }; +function restoreLegacyMenu(ast, source) { + const contexts = []; + walk(ast, (node) => { + if (node.type !== "FunctionDeclaration") return; + const statements = node.body.body; + const start = statements.findIndex((statement) => statement.type === "VariableDeclaration" && + statement.declarations.length === 1 && + statement.declarations[0].id?.name === "__codexOpenWorkspaceItems" && + statement.declarations[0].init?.type === "CallExpression"); + const end = statements.findIndex((statement) => statement.type === "ReturnStatement" && + statement.argument?.type === "ArrayExpression" && + source.slice(statement.start, statement.end).includes(LEGACY_MARKER)); + if (start < 0 || end <= start) return; + // 只剥离旧补丁生成的语句,遇到夹杂的新逻辑不能整段删除。 + if (!statements.slice(start + 1, end).every((statement) => + statement.type === "VariableDeclaration" && statement.declarations.length === 1 && + ["__codexFileManagerTarget", "__codexDesktopPlatform"].includes(statement.declarations[0].id?.name))) return; + contexts.push({ declaration: statements[start], returnNode: statements[end] }); + }); + if (contexts.length !== 1) return null; + const { declaration, returnNode } = contexts[0]; + const original = declaration.declarations[0].init; + return source.slice(0, declaration.start) + `return ${source.slice(original.start, original.end)};` + + source.slice(returnNode.end); } function findSidebarPatchContexts(ast, source) { @@ -492,7 +531,14 @@ function patchSource(source) { return { status: "parse-failed", phase: "before", error, source }; } - const { menuBuilders, openHelpers } = findPatchContext(ast, source); + if (source.includes(LEGACY_MARKER)) { + const restored = restoreLegacyMenu(ast, source); + if (restored == null) return { status: "unexpected-legacy-menu", source }; + const result = patchSource(restored); + return result.status === "patched" ? result : { ...result, source }; + } + + const { menuBuilders } = findPatchContext(ast, source); if (menuBuilders.length === 0 && hasNativeAction) { return { status: "native", source }; } @@ -503,14 +549,6 @@ function patchSource(source) { source, }; } - if (openHelpers.length !== 1) { - return { - status: "unexpected-open-helper-count", - count: openHelpers.length, - source, - }; - } - const [{ bindings, returns, targetsVariables }] = menuBuilders; if (returns.length !== 1) { return { @@ -522,8 +560,8 @@ function patchSource(source) { const [returnNode] = returns; const scope = bindings.get("scope"); - const cwd = bindings.get("cwd"); - const hostId = bindings.get("hostId"); + const callback = workspaceOpenCallback(returnNode.argument, source, scope); + if (callback == null) return { status: "missing-workspace-open-callback", source }; const originalItems = source.slice( returnNode.argument.start, returnNode.argument.end, @@ -531,8 +569,10 @@ function patchSource(source) { const itemsVariable = "__codexOpenWorkspaceItems"; const targetVariable = "__codexFileManagerTarget"; const platformVariable = "__codexDesktopPlatform"; + const callbackVariable = "__codexOpenWorkspaceInTarget"; const replacement = [ `let ${itemsVariable}=${originalItems};`, + `let ${callbackVariable}=${callback};`, ...(targetsVariables.length === 1 ? [ `let ${targetVariable}=${targetsVariables[0]}?.targets.find(` + @@ -551,10 +591,7 @@ function patchSource(source) { ? `${targetVariable}?.resolvedIcon??${targetVariable}?.icon??` : "" }${itemsVariable}[0]?.icon,`, - `onSelect:()=>${openHelpers[0]}({`, - `scope:${scope},path:${cwd},cwd:${cwd},hostId:${hostId},`, - "target:`fileManager`,openMode:`workspace`", - "})},", + `onSelect:()=>${callbackVariable}(\`fileManager\`)},`, `...${itemsVariable}]`, ].join(""); const next = @@ -622,6 +659,28 @@ function patchSidebarSource(source) { return { status: "patched", source: next }; } +function selectTargets(bundles) { + const platforms = [...new Set(bundles.map((bundle) => bundle.platform))]; + return platforms.flatMap((platform) => { + const candidates = bundles.filter((bundle) => bundle.platform === platform); + const patchable = candidates.filter(({ source }) => + source.includes(MARKER) || source.includes(LEGACY_MARKER) || + PATCHABLE_SIGNATURES.every((signature) => source.includes(signature)), + ); + const native = candidates.filter(({ source }) => hasNativeDirectAction(source)); + // 无法识别时仍进入核心检查,不能把 chunk 迁移误报为无需修补。 + const openMenus = patchable.length > 0 ? patchable + : native.length > 0 ? native : candidates.slice(0, 1); + const sidebars = candidates.filter(({ source }) => + source.includes(SIDEBAR_MARKER) || hasSidebarMenuSignatures(source), + ); + return [ + ...openMenus.map((target) => ({ ...target, patchKind: "open-menu" })), + ...sidebars.map((target) => ({ ...target, patchKind: "sidebar" })), + ]; + }); +} + function findTargets(platform) { const appInitialTargets = locateBundles({ dir: "assets", @@ -642,18 +701,7 @@ function findTargets(platform) { source: fs.readFileSync(target.path, "utf-8"), })); - const openMenuTargets = appInitialTargets.map((target) => ({ - ...target, - patchKind: "open-menu", - })); - const sidebarTargets = [...appInitialTargets, ...appPrimaryTargets] - .filter( - ({ source }) => - source.includes(SIDEBAR_MARKER) || hasSidebarMenuSignatures(source), - ) - .map((target) => ({ ...target, patchKind: "sidebar" })); - - return [...openMenuTargets, ...sidebarTargets]; + return selectTargets([...appInitialTargets, ...appPrimaryTargets]); } function main() { @@ -663,10 +711,22 @@ function main() { const targets = findTargets(platform); if (targets.length === 0) { - console.log(" [skip] No matching thread action bundle found"); + console.error(" [x] No matching thread action bundle found"); + process.exitCode = 1; return; } + for (const current of new Set(targets.map(target => target.platform))) { + for (const kind of ["open-menu", "sidebar"]) { + const matches = targets.filter(target => target.platform === current && target.patchKind === kind); + if (matches.length > 1) { + console.error(` [x] ${current}: ambiguous ${kind} bundles (${matches.length})`); + process.exitCode = 1; + return; + } + } + } + let patched = 0; let failed = 0; for (const target of targets) { @@ -721,6 +781,7 @@ if (require.main === module) main(); module.exports = { DIRECT_ACTION_ID, + LEGACY_MARKER, MARKER, SIDEBAR_MARKER, findTargets, @@ -728,4 +789,5 @@ module.exports = { hasNativeDirectAction, patchSidebarSource, patchSource, + selectTargets, }; diff --git a/scripts/patch-thread-file-manager-action.test.js b/scripts/patch-thread-file-manager-action.test.js index c44cfc40..5da17a09 100644 --- a/scripts/patch-thread-file-manager-action.test.js +++ b/scripts/patch-thread-file-manager-action.test.js @@ -3,26 +3,44 @@ const assert = require("node:assert/strict"); const acorn = require("acorn"); const vm = require("node:vm"); const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { spawnSync } = require("node:child_process"); const { nodes } = require("./patch-ast-util"); const { DIRECT_ACTION_ID, + LEGACY_MARKER, MARKER, SIDEBAR_MARKER, hasSidebarMenuSignatures, hasNativeDirectAction, patchSidebarSource, patchSource, + selectTargets, } = require("./patch-thread-file-manager-action"); -test("26.1016 真实 Bundle:普通目录入口、远程排除和原打开链路", { - skip: !process.env.CODEX_PATCH_REAL_BUNDLE, +test("26.1016 真实 Bundle:普通目录入口、远程排除和工作区原生打开链路", { + skip: !process.env.CODEX_PATCH_REAL_BUNDLE && !process.env.CODEX_PATCH_REAL_ASAR, }, async () => { - const original = fs.readFileSync(process.env.CODEX_PATCH_REAL_BUNDLE, "utf8"); + let original; + if (process.env.CODEX_PATCH_REAL_BUNDLE) { + original = fs.readFileSync(process.env.CODEX_PATCH_REAL_BUNDLE, "utf8"); + } else { + const asar = require("@electron/asar"); + const archive = process.env.CODEX_PATCH_REAL_ASAR; + const entries = asar.listPackage(archive).filter(name => /app-(initial|primary)-[^/\\]+\.js$/.test(name)); + const sources = entries.map(name => asar.extractFile(archive, name.replace(/^[/\\]/, "")).toString()); + const matches = sources.filter(source => source.includes(LEGACY_MARKER)); + assert.equal(matches.length, 1, "当前成品应唯一包含待替换的旧入口"); + [original] = matches; + } const menu = patchSource(original); assert.equal(menu.status, "patched"); - const result = patchSidebarSource(menu.source); - assert.equal(result.status, "patched"); + const copy = require("./patch-thread-copy-markdown").patchSource(menu.source); + assert.equal(copy.status, "patched", "同一真实 Bundle 还须能够组合应用 Markdown 复制修复"); + const result = patchSidebarSource(copy.source); + assert.ok(["patched", "already-patched"].includes(result.status)); assert.equal(patchSource(result.source).source, result.source); assert.equal(patchSidebarSource(result.source).source, result.source); const ast = acorn.parse(result.source, { ecmaVersion: "latest", sourceType: "module" }); @@ -50,24 +68,44 @@ test("26.1016 真实 Bundle:普通目录入口、远程排除和原打开链 const builder = ast.body.find(node => node.type === "FunctionDeclaration" && node.id.name === "LUc"); assert.ok(builder); const builderSource = result.source.slice(builder.start, builder.end); - const openName = /onSelect:\(\)=>([\w$]+)\(/.exec(builderSource)?.[1]; - assert.ok(openName); - let opened; - const scope = { get: () => null, + assert.doesNotMatch(builderSource, /onSelect:\(\)=>Bq\(/); + let opened, preferredWrites = 0, errors = 0, failure = false; + const context = { navigator: { platform: "Win32" }, Iq: {}, DJt: {}, ay: {}, + GE: {}, QZn: {}, KE: {}, i$a: {}, nl: {}, y_: {}, + GZn: async () => { context.latestWorkspace = "C:/最新工作树"; }, + RUc: input => [{ id: "open-workspace-in", icon: "icon", onOpenInTarget: input.onOpenInTarget }] }; + const scope = { get: atom => { + if (atom === context.GE) return true; + if (atom === context.QZn) return { data: { latestWorktree: { workspaceRoot: context.latestWorkspace } } }; + if (atom === context.i$a) return { mutateAsync: async params => { opened = params; return { success: !failure }; } }; + if (atom === context.nl) return { danger: () => errors++ }; + if (atom === context.y_) return { formatMessage: message => message.defaultMessage }; + return null; + }, + getOwnValue() { throw new Error("Missing scope instance"); }, query: { getData: () => ({ targets: [{ target: "fileManager", available: true, resolvedIcon: "folder-icon" }] }), - getOptions: () => ({ queryKey: [] }), fetch: async () => ({}) }, + getOptions: () => ({ queryKey: [] }), fetch: async () => ({}), setData: () => preferredWrites++ }, queryClient: { getQueryState: () => ({ status: "success" }) } }; - const context = { navigator: { platform: "Win32" }, Iq: {}, DJt: {}, ay: {}, - scope, RUc: () => [{ id: "open-workspace-in", icon: "icon" }], - [openName]: params => { opened = params; } }; - vm.runInNewContext(`${builderSource};items=LUc({scope,cwd:'C:/plain-folder',hostId:'local'})`, context); + context.scope = scope; + vm.runInNewContext(`${builderSource};items=LUc({scope,conversationId:'thread',cwd:'C:/plain-folder',hostId:'local'})`, context); assert.equal(context.items[0].id, DIRECT_ACTION_ID); assert.equal(context.items[0].message.id, "sidebarElectron.openWorkspaceRootInExplorer"); context.items[0].onSelect(); + await new Promise(resolve => setImmediate(resolve)); assert.equal(opened.target, "fileManager"); - assert.equal(opened.cwd, "C:/plain-folder"); + assert.equal(opened.cwd, "C:/最新工作树"); assert.equal(opened.hostId, "local"); - assert.equal(Object.hasOwn(opened, "persistPreferredTargetPath"), false); + assert.equal(opened.persistPreferredTargetPath, undefined); + assert.equal(preferredWrites, 0); + context.items[1].onOpenInTarget("vscode", "C:/Code.exe"); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(opened.target, "vscode"); + assert.equal(opened.persistPreferredTargetPath, "C:/最新工作树"); + assert.equal(preferredWrites, 1); + failure = true; + context.items[0].onSelect(); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(errors, 1, "真实系统打开失败仍走原生提示"); }); function createGroupedMenuBundle(options = {}) { @@ -104,26 +142,38 @@ function createGroupedMenuBundle(options = {}) { return openHelper + menuBuilder; } -function evaluatePatchedMenu(source, platform) { +function evaluatePatchedMenu(source, platform, options = {}) { const context = { navigator: { userAgentData: { platform } }, targets: {}, openMutation: {}, + store: {}, + derive: (_store, selector) => selector, opened: null, - makeOpenMenu: () => [{ id: "open-workspace-in", icon: "open-icon" }], + makeOpenMenu: input => [{ id: "open-workspace-in", icon: "open-icon", onOpenInTarget: input.onOpenInTarget }], }; context.scope = { - get: () => ({ mutate() {} }), - open: (params) => { - context.opened = params; - }, + get: () => ({ + mutate(params) { context.opened = params; }, + async mutateAsync(params) { + if (options.reject) throw new Error("测试打开失败"); + context.opened = params; + return { success: options.success !== false }; + }, + }), + getOwnValue() { throw new Error("Missing scope instance"); }, + open() { throw new Error("不能从全局侧栏调用文件预览函数"); }, query: { fetch: () => Promise.resolve(), + setData() { context.preferredTargetChanged = true; }, getData: () => ({ targets: [{ target: "fileManager", resolvedIcon: "folder-icon" }], }), }, }; + context.ensureWorkspace = async () => { context.resolvedWorkspace = "C:\\最新工作树"; }; + context.resolveWorkspace = fallback => context.resolvedWorkspace ?? fallback; + context.reportError = () => { context.reportedErrors = (context.reportedErrors ?? 0) + 1; }; vm.runInNewContext( `${source};result=buildOpenItems({scope,cwd:\`C:\\\\repo\`,hostId:\`local\`})`, context, @@ -194,7 +244,7 @@ test("新版对话菜单增加顶层文件管理器入口并保留打开方式 assert.ok(result.source.includes(`id:\`${DIRECT_ACTION_ID}\``)); assert.match( result.source, - /onSelect:\(\)=>openItem\(\{scope:s,path:c,cwd:c,hostId:h,target:`fileManager`,openMode:`workspace`\}\)/, + /onSelect:\(\)=>__codexOpenWorkspaceInTarget\(`fileManager`\)/, ); assert.match( result.source, @@ -343,7 +393,8 @@ test("顶层入口按系统显示文案并复用 fileManager 打开链路", () = context.result[0].onSelect(); assert.equal(context.opened.target, "fileManager"); assert.equal(context.opened.cwd, "C:\\repo"); - assert.equal("persistPreferredTargetPath" in context.opened, false); + assert.equal(context.opened.persistPreferredTargetPath, undefined); + assert.equal(context.preferredTargetChanged, undefined); } }); @@ -365,11 +416,156 @@ test("新旧菜单实现共存时优先修补新版动作聚合器", () => { assert.ok(result.source.includes(MARKER)); }); -test("打开链路缺失时拒绝生成不完整补丁", () => { - const result = patchSource( - createGroupedMenuBundle({ includeOpenHelper: false }), +test("工作区菜单不依赖要求 ThreadScope 的文件预览函数", () => { + const result = patchSource(createGroupedMenuBundle({ includeOpenHelper: false })); + assert.equal(result.status, "patched"); + const context = evaluatePatchedMenu(result.source, "Windows"); + context.result[0].onSelect(); + assert.equal(context.opened.path, "C:\\repo"); +}); + +test("原生工作区打开回调缺失时保留原文并报错", () => { + const original = createGroupedMenuBundle().replace("onOpenInTarget:", "changedOpenHandler:"); + const result = patchSource(original); + assert.equal(result.status, "missing-workspace-open-callback"); + assert.equal(result.source, original); +}); + +function createCurrentWorkspaceBundle() { + return createGroupedMenuBundle().replace( + "onOpenInTarget:(target,appPath)=>{s.get(openMutation).mutate({path:c,cwd:c,hostId:h,target,appPath,openMode:`workspace`,persistPreferredTargetPath:c},{onError:report})}", + "onOpenInTarget:async(target,appPath)=>{try{await ensureWorkspace();let cwd=resolveWorkspace(c);s.query.setData(targets,request,data=>({...data,preferredTarget:target}));let result=await s.get(openMutation).mutateAsync({path:cwd,cwd,hostId:h,target,appPath,openMode:`workspace`,persistPreferredTargetPath:cwd});if(!result.success)reportError()}catch(error){reportError()}}", ); +} - assert.equal(result.status, "unexpected-open-helper-count"); - assert.equal(result.count, 0); +test("打开最新工作树且不改变默认编辑器,原生子菜单仍保存偏好", async () => { + const result = patchSource(createCurrentWorkspaceBundle()); + assert.equal(result.status, "patched"); + const context = evaluatePatchedMenu(result.source, "Windows"); + await context.result[0].onSelect(); + assert.equal(context.opened.path, "C:\\最新工作树"); + assert.equal(context.opened.cwd, "C:\\最新工作树"); + assert.equal(context.opened.target, "fileManager"); + assert.equal(context.opened.persistPreferredTargetPath, undefined); + assert.equal(context.preferredTargetChanged, undefined); + await context.result[1].onOpenInTarget("vscode", "C:\\Code.exe"); + assert.equal(context.preferredTargetChanged, true); + assert.equal(context.opened.persistPreferredTargetPath, "C:\\最新工作树"); + assert.equal(context.opened.target, "vscode"); +}); + +test("系统打开返回失败或异常仍显示原生错误提示", async () => { + const result = patchSource(createCurrentWorkspaceBundle()); + for (const options of [{ success: false }, { reject: true }]) { + const context = evaluatePatchedMenu(result.source, "Windows", options); + await context.result[0].onSelect(); + assert.equal(context.reportedErrors, 1); + } +}); + +test("只替换已知旧注入并保持原生菜单,未知旧改动不被删除", () => { + const source = createGroupedMenuBundle(); + const old = source.replace("return makeOpenMenu({", "let __codexOpenWorkspaceItems=makeOpenMenu({") + .replace("})}const copyMessage", `});let __codexDesktopPlatform=\`win\`;return[{${LEGACY_MARKER}id:\`${DIRECT_ACTION_ID}\`,onSelect:()=>openItem({scope:s,path:c,cwd:c,hostId:h,target:\`fileManager\`,openMode:\`workspace\`})},...__codexOpenWorkspaceItems]}const copyMessage`); + const result = patchSource(old); + assert.equal(result.status, "patched"); + assert.equal(result.source.includes(LEGACY_MARKER), false); + assert.equal(result.source.split(DIRECT_ACTION_ID).length - 1, 1); + const context = evaluatePatchedMenu(result.source, "Windows"); + context.result[0].onSelect(); + assert.equal(context.opened.target, "fileManager"); + assert.equal(patchSource(result.source).status, "already-patched"); + const unknown = old.replace(`return[{${LEGACY_MARKER}`, `changed();return[{${LEGACY_MARKER}`); + assert.equal(patchSource(unknown).status, "unexpected-legacy-menu"); + assert.equal(patchSource(unknown).source, unknown); +}); + +test("菜单迁移到 app-primary 且无远程配置名时仍定位两类补丁", () => { + const sidebar = "const remoteConnections=derive(store,({get})=>get(config).remoteControl);" + + createSelectorSidebarMenuBundle().replace("getState(g,`remote_control_connections`)", "g(remoteConnections)"); + const source = createCurrentWorkspaceBundle() + sidebar; + assert.equal(source.includes("remote_control_connections"), false); + const targets = selectTargets([ + { platform: "win", path: "app-initial-new.js", source: "const initial=true;" }, + { platform: "win", path: "app-primary-new.js", source }, + ]); + assert.deepEqual(targets.map(({ path, patchKind }) => [path, patchKind]), [ + ["app-primary-new.js", "open-menu"], ["app-primary-new.js", "sidebar"], + ]); + let patched = source; + for (const target of targets) { + const result = (target.patchKind === "sidebar" ? patchSidebarSource : patchSource)(patched); + assert.equal(result.status, "patched"); + patched = result.source; + } + const context = { store: {}, config: {}, gitBacked: {}, derive: (_store, selector) => selector }; + const gate = vm.runInNewContext(`${patched};sidebarGate`, context); + for (const connections of [[], [{ hostId: "local" }], [{ hostId: "other" }]]) { + assert.equal(gate({ conversationId: "thread", hostId: "local" }, { get: () => connections }), + !connections.some(connection => connection.hostId === "local")); + } +}); + +test("按平台独立选择实际菜单,支持旧版分离 chunk 与原生入口", () => { + const targets = selectTargets([ + { platform: "mac-arm64", path: "mac/app-initial.js", source: createGroupedMenuBundle() }, + { platform: "win", path: "win/app-initial.js", source: "const initial=true;" }, + { platform: "mac-arm64", path: "mac/app-primary.js", source: createSidebarMenuBundle() }, + { platform: "win", path: "win/app-primary.js", source: createGroupedMenuBundle() + createSidebarMenuBundle() }, + ]); + assert.deepEqual(targets.map(({ path, patchKind }) => [path, patchKind]), [ + ["mac/app-initial.js", "open-menu"], ["mac/app-primary.js", "sidebar"], + ["win/app-primary.js", "open-menu"], ["win/app-primary.js", "sidebar"], + ]); + const native = selectTargets([ + { platform: "win", path: "app-initial.js", source: "const initial=true;" }, + { platform: "win", path: "app-primary.js", source: "const items=[{id:`open-thread-folder`}];" }, + ]); + assert.equal(native.length, 1); + assert.equal(native[0].path, "app-primary.js"); + assert.equal(patchSource(native[0].source).status, "native"); +}); + +test("菜单未知时仍进入检查并失败,不因 chunk 变化静默跳过", () => { + const targets = selectTargets([ + { platform: "win", path: "app-initial.js", source: "const changedMenu=true;" }, + { platform: "win", path: "app-primary.js", source: "const primary=true;" }, + ]); + assert.equal(targets.length, 1); + assert.equal(patchSource(targets[0].source).status, "unexpected-menu-builder-count"); +}); + +test("CLI 在实际资源目录执行 check → apply → check,重复目标在写入前被拒绝", t => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "codex-file-manager-")); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const assets = path.join(root, "win", "_asar", "webview", "assets"); + fs.mkdirSync(assets, { recursive: true }); + const initial = path.join(assets, "app-initial-test.js"); + const primary = path.join(assets, "app-primary-test.js"); + const source = createCurrentWorkspaceBundle() + createSelectorSidebarMenuBundle(); + fs.writeFileSync(initial, "const initial=true;"); + fs.writeFileSync(primary, source); + const run = check => spawnSync(process.execPath, + [path.join(__dirname, "patch-thread-file-manager-action.js"), "win", ...(check ? ["--check"] : [])], + { encoding: "utf8", env: { ...process.env, CODEX_PATCH_SOURCE_DIR: root } }); + const checked = run(true); + assert.equal(checked.status, 0, checked.stdout + checked.stderr); + assert.equal(fs.readFileSync(primary, "utf8"), source); + const applied = run(false); + assert.equal(applied.status, 0, applied.stdout + applied.stderr); + const patched = fs.readFileSync(primary, "utf8"); + assert.ok(patched.includes(MARKER) && patched.includes(SIDEBAR_MARKER)); + assert.equal(run(true).status, 0); + assert.equal(fs.readFileSync(primary, "utf8"), patched); + const menu = evaluatePatchedMenu(patched, "Windows"); + return menu.result[0].onSelect().then(() => { + assert.equal(menu.opened.target, "fileManager"); + fs.writeFileSync(initial, source); + fs.writeFileSync(primary, source); + const ambiguous = run(false); + assert.equal(ambiguous.status, 1); + assert.match(ambiguous.stderr, /ambiguous open-menu bundles/); + assert.equal(fs.readFileSync(initial, "utf8"), source); + assert.equal(fs.readFileSync(primary, "utf8"), source); + }); }); From e8ea2d1a7288cf95cae34df0a2d16bfe6974be2d Mon Sep 17 00:00:00 2001 From: carptopus Date: Sun, 25 Oct 2026 13:26:52 +0800 Subject: [PATCH 44/51] Adapt patches for Windows 26.1021 resources --- scripts/frontend-source-smoke.js | 84 ++++++----- scripts/maintenance-smoke.js | 31 +++- scripts/patch-accent-presets.js | 14 +- scripts/patch-accent-presets.test.js | 39 +++++ scripts/patch-api-key-home-navigation.js | 10 +- scripts/patch-api-key-home-navigation.test.js | 80 ++++++++++ scripts/patch-crash-forensics.js | 38 +++-- scripts/patch-mcp-status-refresh.js | 97 ++++++++++-- scripts/patch-mcp-status-refresh.test.js | 85 +++++++++++ scripts/patch-provider-quota.js | 67 +++++++-- scripts/patch-provider-quota.test.js | 104 +++++++++++++ scripts/patch-remote-control.js | 139 ++++++++++++++++-- scripts/patch-remote-control.test.js | 108 ++++++++++++++ scripts/patch-sidebar-usage.js | 99 ++++++++++--- scripts/patch-thread-file-manager-action.js | 53 ++++++- .../patch-thread-file-manager-action.test.js | 101 ++++++++++++- scripts/sidebar-usage-smoke.js | 43 ++++-- scripts/windows-maintenance.js | 16 +- 18 files changed, 1082 insertions(+), 126 deletions(-) diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index 12d927a7..a2816c27 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -15,9 +15,22 @@ function walk(node, visit) { } function verifyFrontendSource(assets) { const files = fs.readdirSync(assets).filter(name => name.endsWith(".js")); - const primary = files.filter(name => /^app-primary-/.test(name) && fs.readFileSync(path.join(assets, name), "utf8").includes("const __codexQuotaThreadProvider=")); - assert.equal(primary.length, 1); - const source = fs.readFileSync(path.join(assets, primary[0]), "utf8"), ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const markers = ["const __codexQuotaThreadProvider=", "codex-rebuild-local-accent-presets:theme", + "Codex:API-key 首页使用官方记录器。", "CodexRebuildThreadTimeline", "CodexRebuildMcpStatusRefresh", + "CodexRebuildRemoteControlAuthIsolation", "CodexRebuildRemoteControlGateAuthIsolation", + "CodexRebuildServiceTierApiKeyRequest", "CodexRebuildSidebarUsage"]; + const markedSources = new Map(); + for (const name of files) { + const text = fs.readFileSync(path.join(assets, name), "utf8"); + if (markers.some(marker => text.includes(marker))) markedSources.set(name, text); + } + const markedSource = marker => { + const matches = [...markedSources.values()].filter(source => source.includes(marker)); + assert.equal(matches.length, 1, `补丁标记必须唯一:${marker}`); + return matches[0]; + }; + // 编译器会移动组件;实际补丁标记和后续契约检查共同定位,不绑定 chunk 名称。 + const source = markedSource("const __codexQuotaThreadProvider="), ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); let guard, disabled, config, scope, quota = [], loading; walk(ast, node => { if (node.type === "VariableDeclaration" && node.declarations.some(d => d.id.name === "__codexUsesCustomProvider")) guard = node; @@ -36,6 +49,17 @@ function verifyFrontendSource(assets) { }); assert.equal(quota.length, 2); assert.ok(config && scope && loading); const lookup = guard.declarations[0].init; + // 新 Composer 通过导出初始化器读取跨模块会话 atom;执行生成表达式,保留初始化调用。 + const providerRead = lookup.type === "SequenceExpression" ? lookup.expressions.at(-1) : lookup; + assert.equal(providerRead.type, "CallExpression"); + assert.equal(providerRead.callee.type, "Identifier"); + assert.equal(providerRead.arguments.length, 2); + const providerInitializers = lookup.type === "SequenceExpression" ? lookup.expressions.slice(0, -1) : []; + for (const initializer of providerInitializers) { + assert.equal(initializer.type, "CallExpression"); + assert.equal(initializer.callee.type, "Identifier"); + assert.equal(initializer.arguments.length, 0); + } const external = { base_url: "https://provider.example/v1", requires_openai_auth: true }; const scenarios = [ { name: "第三方服务不受官方额度禁发", provider: "local", endpoint: external, expected: false }, @@ -55,9 +79,12 @@ function verifyFrontendSource(assets) { const results = []; for (const scenario of scenarios) { const context = Object.fromEntries([...names].map(name => [name, false])); + let initialized = providerInitializers.length === 0; + for (const initializer of providerInitializers) context[initializer.callee.name] = () => { initialized = true; }; Object.assign(context, { URL, [config]: { isConfigDataPending: !!scenario.pending, resolvedConfig: { model_provider: scenario.provider, model_providers: { local: scenario.endpoint } } }, [scope]: { value: { kind: scenario.kind || "local", cloudThreadPrototype: scenario.cloud } }, [loading]: { isLoading: !!scenario.loading }, - [lookup.callee.name]: () => scenario.saved, [lookup.arguments[0].name]: null, [lookup.arguments[1].name]: "fixture-thread" }); + [providerRead.callee.name]: () => { assert.ok(initialized, "会话 Provider atom 必须先初始化"); return scenario.saved; }, + [providerRead.arguments[0].name]: null, [providerRead.arguments[1].name]: "fixture-thread" }); for (const name of quota) context[name] = true; const actual = vm.runInNewContext(source.slice(guard.start, guard.end) + `\nBoolean(${source.slice(disabled.init.start, disabled.init.end)})`, context, { timeout: 1000 }); assert.equal(actual, scenario.expected, scenario.name); results.push(scenario.name); @@ -70,16 +97,10 @@ function verifyFrontendSource(assets) { assert.match(settingsSource, /codex-rebuild-local-accent-presets:settings/); assert.match(settingsSource, /codex-rebuild-accent-presets\.js/); assert.match(settingsSource, /__codexSelectAccentPreset/); - const themeEntries = files.filter(name => /^app-initial-/.test(name) - && fs.readFileSync(path.join(assets, name), "utf8").includes("codex-rebuild-local-accent-presets:theme")); - assert.equal(themeEntries.length, 1); - const themeSource = fs.readFileSync(path.join(assets, themeEntries[0]), "utf8"); + const themeSource = markedSource("codex-rebuild-local-accent-presets:theme"); assert.match(themeSource, /__codexResolveAccentPreset/); assert.match(themeSource, /accentSource:`chatgpt`/); - const navigationEntries = files.filter(name => /^app-initial-/.test(name) - && fs.readFileSync(path.join(assets, name), "utf8").includes("Codex:API-key 首页使用官方记录器。")); - assert.equal(navigationEntries.length, 1); - const navigationSource = fs.readFileSync(path.join(assets, navigationEntries[0]), "utf8"); + const navigationSource = markedSource("Codex:API-key 首页使用官方记录器。"); const recorder = /\/\* Codex:API-key 首页使用官方记录器。 \*\/if\([A-Za-z_$][\w$]*===`apikey`\)\{([A-Za-z_$][\w$]*)\([A-Za-z_$][\w$]*,\{accountKey:`auth:apikey`,auth:[A-Za-z_$][\w$]*,location:[A-Za-z_$][\w$]*,productMode:[A-Za-z_$][\w$]*\}\);return;\}/.exec(navigationSource); assert.ok(recorder, "API-key 首页必须调用结构完整的官方记录器"); // 校验实际调用契约,不绑定压缩函数名;仍要求与原生五字段调用共用唯一记录器。 @@ -109,35 +130,28 @@ function verifyFrontendSource(assets) { assert.doesNotMatch(navigationSource, /Codex:API-key 首页恢复最近会话/); assert.doesNotMatch(navigationSource, /Codex:API-key 首页恢复写入/); assert.doesNotMatch(navigationSource, /authMethod:__codexAuthMethod/); - const timelineEntries = files.filter(name => /^app-initial-/.test(name) - && fs.readFileSync(path.join(assets, name), "utf8").includes("CodexRebuildThreadTimeline")); - assert.equal(timelineEntries.length, 1); - const timelineSource = fs.readFileSync(path.join(assets, timelineEntries[0]), "utf8"); + const timelineSource = markedSource("CodexRebuildThreadTimeline"); assert.match(timelineSource, /supportsThreadTimeline\(\)\{return\s*[A-Za-z_$][\w$]*\(this\.hostId,this\.requestClient\.getAppServerVersion\(\)\)\/\* CodexRebuildThreadTimeline \*\//); - const mcpRefreshEntries = files.filter(name => /^app-initial-/.test(name) - && fs.readFileSync(path.join(assets, name), "utf8").includes("CodexRebuildMcpStatusRefresh")); - assert.equal(mcpRefreshEntries.length, 1); - const mcpRefreshSource = fs.readFileSync(path.join(assets, mcpRefreshEntries[0]), "utf8"); + const mcpRefreshSource = markedSource("CodexRebuildMcpStatusRefresh"); assert.match(mcpRefreshSource, /toolsAndAuthOnly/); assert.match(mcpRefreshSource, /mention-discovery/); assert.match(mcpRefreshSource, /refetchType:`none`/); assert.match(mcpRefreshSource, /===`full`/); assert.match(mcpRefreshSource, /CodexRebuildMcpStatusRefresh \*\/\)\},250\)/); - const remoteControlEntries = files.filter(name => /^app-initial-/.test(name) - && fs.readFileSync(path.join(assets, name), "utf8").includes("CodexRebuildRemoteControlAuthIsolation")); - assert.equal(remoteControlEntries.length, 1); - const remoteControlSource = fs.readFileSync(path.join(assets, remoteControlEntries[0]), "utf8"); + const remoteControlSource = markedSource("CodexRebuildRemoteControlAuthIsolation"); + const remoteGateSource = markedSource("CodexRebuildRemoteControlGateAuthIsolation"); assert.match(remoteControlSource, /__codexRemoteAccount\?\.authMethod!==`chatgpt`/); - assert.match(remoteControlSource, /__codexSetRemoteEnabled\(!1\)/); - assert.match(remoteControlSource, /CodexRebuildRemoteControlGateAuthIsolation/); - assert.match(remoteControlSource, /__codexRemoteGateAccount\?\.authMethod===`chatgpt`/); - assert.match(remoteControlSource, /__codexRemoteGateAccount\?\.authLoading/); + // 新版官方目录 atom 为只读派生值;旧版仍需清理可写存储,二者均校验认证隔离。 + assert.equal(require("./patch-remote-control").patchSource(remoteControlSource).status, "already-patched"); + if (!remoteControlSource.includes("CodexRebuildRemoteControlCatalog")) { + assert.match(remoteControlSource, /__codexSetRemoteEnabled\(!1\)/); + } + assert.match(remoteGateSource, /__codexRemoteGateAccount\?\.authMethod===`chatgpt`/); + assert.match(remoteGateSource, /__codexRemoteGateAccount\?\.authLoading/); assert.doesNotMatch(remoteControlSource, /codex-remote-gate:/); - const serviceTierEntries = files.filter(name => /^app-initial-/.test(name) - && fs.readFileSync(path.join(assets, name), "utf8").includes("CodexRebuildServiceTierApiKeyRequest")); - assert.equal(serviceTierEntries.length, 1); - const serviceTierSource = fs.readFileSync(path.join(assets, serviceTierEntries[0]), "utf8"); + assert.doesNotMatch(remoteGateSource, /codex-remote-gate:/); + const serviceTierSource = markedSource("CodexRebuildServiceTierApiKeyRequest"); assert.match(serviceTierSource, /CodexRebuildServiceTierApiKeyAuth/); assert.match(serviceTierSource, /CodexRebuildServiceTierApiKeyAccess/); assert.match(serviceTierSource, /\{fast:!0,ultrafast:!0\}\/\* CodexRebuildServiceTierApiKeyRequest \*\//); @@ -164,7 +178,11 @@ function verifyFrontendSource(assets) { assert.equal(require("./patch-hide-invite-menu").patchSource( fs.readFileSync(path.join(assets, inviteMenus[0]), "utf8")).status, "already-patched"); const usagePatch = require("./patch-sidebar-usage"); - assert.equal(usagePatch.patchSource(mcpRefreshSource).status, "already-patched"); + const usageDependencies = files.filter(name => /^app-initial-.*\.js$/.test(name)) + .map(name => ({ name, source: fs.readFileSync(path.join(assets, name), "utf8") })); + assert.equal(usagePatch.patchSource(markedSource("CodexRebuildSidebarUsage"), { + relatedSources: usageDependencies, + }).status, "already-patched"); assert.equal(fs.readFileSync(path.join(assets, usagePatch.MODULE), "utf8"), fs.readFileSync(path.join(__dirname, "runtime", "sidebar-usage.mjs"), "utf8")); assert.match(dialogs, /codex-rebuild-dialog-editor h-\[720px\] max-w-full max-h-full/); diff --git a/scripts/maintenance-smoke.js b/scripts/maintenance-smoke.js index ebb1c56d..eccbe8c5 100644 --- a/scripts/maintenance-smoke.js +++ b/scripts/maintenance-smoke.js @@ -78,7 +78,19 @@ try { const patched = fs.readFileSync(entry); run("patch-test-isolation.js", ["win"], 0, { CODEX_PATCH_SOURCE_DIR: source }); assert.deepEqual(fs.readFileSync(entry), patched); - const started = spawnSync(process.execPath, [entry], { encoding: "utf8", env: { ...process.env, CODEX_REBUILD_TEST_ROOT: testRoot } }); + if (mode === "commonjs") { + run("patch-crash-forensics.js", ["win", "--check"], 0, { CODEX_PATCH_SOURCE_DIR: source }); + assert.deepEqual(fs.readFileSync(entry), patched); + run("patch-crash-forensics.js", ["win"], 0, { CODEX_PATCH_SOURCE_DIR: source }); + const combined = fs.readFileSync(entry); + assert.ok(combined.indexOf('require("./codex-rebuild-test-environment.cjs")') < combined.indexOf("__CODEX_CRASH_FORENSICS_V4__")); + run("patch-test-isolation.js", ["win", "--check"], 0, { CODEX_PATCH_SOURCE_DIR: source }); + run("patch-crash-forensics.js", ["win"], 0, { CODEX_PATCH_SOURCE_DIR: source }); + assert.deepEqual(fs.readFileSync(entry), combined, "隔离与诊断组合重复应用不能继续改写入口"); + checks++; + } + const started = spawnSync(process.execPath, [entry], { encoding: "utf8", env: { ...process.env, CODEX_REBUILD_TEST_ROOT: testRoot, + LOCALAPPDATA: path.join(testRoot, "diagnostics") } }); assert.equal(started.status, 0, started.stderr); const proof = JSON.parse(fs.readFileSync(path.join(testRoot, "isolation-runtime.json"))); assert.equal(proof.codexHome, path.join(testRoot, "codex-home")); @@ -105,6 +117,15 @@ try { const evidenceOutput = path.join(temporary, "evidence-output"); write(path.join(evidenceAsar, ".vite", "build", "early-bootstrap.js"), "const startup=true;"); write(path.join(evidenceAsar, "webview", "assets", "app.js"), "const app=true;"); + const frontendEvidence = [ + ["app-shared-fixture.js", "const sharedDefinitions=true;"], + ["composer-content-fixture.js", "const composer={isConfigDataPending:false};"], + ["remote-control-fixture.js", "const event='set-remote-control-connections-enabled';"], + ["app-theme-fixture.js", "const theme={'--color-image-generation-accent':'blue'};"], + ]; + for (const [name, source] of frontendEvidence) { + write(path.join(evidenceAsar, "webview", "assets", name), source); + } const browserService = [ 'const gate="codex_browser_use_agent_request_header";', "async function read(){try{return await feature(gate)}catch{return!1}}", @@ -125,6 +146,14 @@ try { } saveCompatibilityEvidence(evidenceAsar, { version: "fixture" }, evidenceOutput); const evidenceIndex = JSON.parse(fs.readFileSync(path.join(evidenceOutput, "index.json"), "utf8")); + for (const [name, source] of frontendEvidence) { + const entry = evidenceIndex.files.find(file => file.name === name); + assert.equal(entry?.copied, true, `缺少新版独立功能块取证:${name}`); + const copied = fs.readFileSync(path.join(evidenceOutput, "webview", name), "utf8"); + assert.equal(copied, source); + assert.equal(entry.sha256, hash(copied)); + } + checks++; const browserEvidence = evidenceIndex.files.filter((item) => item.name === "browser-service.mjs"); assert.equal(browserEvidence.length, 2); assert(browserEvidence.every((item) => item.copied)); diff --git a/scripts/patch-accent-presets.js b/scripts/patch-accent-presets.js index 4b53766a..ca5b5c3a 100644 --- a/scripts/patch-accent-presets.js +++ b/scripts/patch-accent-presets.js @@ -142,6 +142,15 @@ function findTarget(directory, pattern, content, label) { return candidates[0]; } +function findThemeTarget(directory) { + const signature = ["--color-background-user-message", "--color-image-generation-accent", "accentSource"]; + const candidates = fs.readdirSync(directory).filter(name => name.endsWith(".js")) + .map(name => ({ name, path: path.join(directory, name), source: fs.readFileSync(path.join(directory, name), "utf8") })) + .filter(file => signature.every(value => file.source.includes(value))); + if (candidates.length !== 1) throw new Error(`强调色主题资源数量异常(${candidates.length})`); + return candidates[0]; +} + function main() { const args = process.argv.slice(2); const platform = args.find(arg => PLATFORMS.includes(arg)); @@ -153,8 +162,7 @@ function main() { try { const settings = findTarget(directory.path, /^general-settings-.*\.js$/, ["chatgptAccentPicker.ChatGptAccentPicker.updateError"], "强调色设置"); - const theme = findTarget(directory.path, /^app-initial-.*\.js$/, - ["--color-background-user-message", "--color-image-generation-accent", "accentSource"], "强调色主题"); + const theme = findThemeTarget(directory.path); const settingsResult = patchSettingsSource(settings.source); const themeResult = patchThemeSource(theme.source); for (const [label, result] of [["强调色设置", settingsResult], ["强调色主题", themeResult]]) { @@ -184,4 +192,4 @@ function main() { } if (require.main === module) main(); -module.exports = { MODULE, SETTINGS_MARKER, THEME_MARKER, patchSettingsSource, patchThemeSource }; +module.exports = { MODULE, SETTINGS_MARKER, THEME_MARKER, findThemeTarget, patchSettingsSource, patchThemeSource }; diff --git a/scripts/patch-accent-presets.test.js b/scripts/patch-accent-presets.test.js index 5ac4f344..1f3e17d2 100644 --- a/scripts/patch-accent-presets.test.js +++ b/scripts/patch-accent-presets.test.js @@ -3,11 +3,13 @@ const assert = require("node:assert/strict"); const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); +const { execFileSync } = require("node:child_process"); const { pathToFileURL } = require("node:url"); const { MODULE, SETTINGS_MARKER, THEME_MARKER, + findThemeTarget, patchSettingsSource, patchThemeSource, } = require("./patch-accent-presets"); @@ -114,6 +116,43 @@ test("主题函数唯一注入本地预设解析器并保持幂等", () => { assert.equal(patchThemeSource(result.source).status, "already-patched"); }); +test("CLI 按主题签名定位旧新 chunk,并拒绝重复目标", t => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "codex-accent-locator-")); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const assets = path.join(root, "webview", "assets"); + fs.mkdirSync(assets, { recursive: true }); + fs.writeFileSync(path.join(assets, "general-settings-fixture.js"), settingsFixture()); + const env = { ...process.env, CODEX_PATCH_SOURCE_DIR: root }; + for (const name of ["app-initial-legacy.js", "app-theme-current.js"]) { + fs.writeFileSync(path.join(assets, name), themeFixture()); + assert.equal(findThemeTarget(assets).name, name); + assert.match(execFileSync(process.execPath, [path.join(__dirname, "patch-accent-presets.js"), "--check"], { env, encoding: "utf8" }), /主题生成器结构已核对/); + fs.unlinkSync(path.join(assets, name)); + } + fs.writeFileSync(path.join(assets, "app-initial-a.js"), themeFixture()); + fs.writeFileSync(path.join(assets, "app-theme-b.js"), themeFixture()); + assert.throws(() => findThemeTarget(assets), /主题资源数量异常(2)/); + assert.throws(() => execFileSync(process.execPath, [path.join(__dirname, "patch-accent-presets.js"), "--check"], { env, encoding: "utf8" }), /强调色主题资源数量异常(2)/); +}); + +test("真实资源路径可核对 26.1021 设置与主题 Bundle", { skip: !process.env.CODEX_REBUILD_ACCENT_ASSETS }, () => { + const assets = process.env.CODEX_REBUILD_ACCENT_ASSETS; + const settingsFiles = fs.readdirSync(assets).filter(name => /^general-settings-.*\.js$/.test(name) && + fs.readFileSync(path.join(assets, name), "utf8").includes("chatgptAccentPicker.ChatGptAccentPicker.updateError")); + const themeFiles = fs.readdirSync(assets).filter(name => /^app-theme-.*\.js$/.test(name) && + ["--color-background-user-message", "--color-image-generation-accent", "accentSource"] + .every(value => fs.readFileSync(path.join(assets, name), "utf8").includes(value))); + assert.equal(settingsFiles.length, 1, "设置组件应唯一定位"); + assert.equal(themeFiles.length, 1, "主题生成器应唯一定位"); + const settings = patchSettingsSource(fs.readFileSync(path.join(assets, settingsFiles[0]), "utf8")); + const theme = patchThemeSource(fs.readFileSync(path.join(assets, themeFiles[0]), "utf8")); + assert.equal(settings.status, "patched", settings.reason); + assert.equal(theme.status, "patched", theme.reason); + assert.match(settings.source, /disabled:[^,}]*===void 0/); + assert.match(theme.source, /__codexResolveAccentPreset\(/); + assert.equal(patchThemeSource(theme.source).status, "already-patched"); +}); + test("本地设置、账户同步和显式自定义使用同一预设状态", async () => { const runtime = await runtimeModule(); const storage = fakeStorage(); diff --git a/scripts/patch-api-key-home-navigation.js b/scripts/patch-api-key-home-navigation.js index 4108d9e0..cb33d2e8 100644 --- a/scripts/patch-api-key-home-navigation.js +++ b/scripts/patch-api-key-home-navigation.js @@ -344,10 +344,10 @@ function findActiveDestinationTracker(ast, source) { if (!marker && !sharedAuth) continue; candidates.push(details); } - if (candidates.length !== 1) { + if (candidates.length > 1) { throw new Error(`首页活动目标跟踪器 数量异常(${candidates.length})`); } - return candidates[0]; + return candidates[0] ?? null; } function usesSharedAuth(callback, auth) { @@ -384,6 +384,12 @@ function patchSource(source) { try { const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); const tracker = findActiveDestinationTracker(ast, source); + if (tracker == null) { + if ([MARKER, HOME_CURRENT_MARKER, HOME_STATE_MARKER, HOME_RESTORE_MARKER] + .some(marker => source.includes(marker))) throw new Error("补丁标记存在但首页活动目标跟踪器缺失"); + // 多个 chunk 会共享账户字段;只有完整原生记录调用所在文件才是补丁目标。 + return { status: "not-applicable", source }; + } const homeRestore = findHomeRestore(ast, source); if (tracker == null || homeRestore == null) { if (source.includes(MARKER) || source.includes(HOME_CURRENT_MARKER)) { diff --git a/scripts/patch-api-key-home-navigation.test.js b/scripts/patch-api-key-home-navigation.test.js index 4849bc31..2dbd4d74 100644 --- a/scripts/patch-api-key-home-navigation.test.js +++ b/scripts/patch-api-key-home-navigation.test.js @@ -2,6 +2,9 @@ const test = require("node:test"); const assert = require("node:assert/strict"); const fs = require("node:fs"); const acorn = require("acorn"); +const os = require("node:os"); +const path = require("node:path"); +const { spawnSync } = require("node:child_process"); const { HOME_CURRENT_MARKER, @@ -367,3 +370,80 @@ test("无关 Bundle 保持不变", () => { assert.equal(result.status, "not-applicable"); assert.equal(result.source, source); }); + +test("CLI 从共享账户字段的多个 chunk 中选择唯一完整首页链路", t => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "codex-home-chunks-")); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const assets = path.join(root, "win", "_asar", "webview", "assets"); + fs.mkdirSync(assets, { recursive: true }); + const unrelated = "const account={authMethod:`apikey`,accountKey:`auth:apikey`,productMode:`codex`,auth:`chatgpt:`};"; + const shared = path.join(assets, "app-shared-test.js"); + const primary = path.join(assets, "app-primary-test.js"); + fs.writeFileSync(shared, unrelated); + fs.writeFileSync(primary, fixture()); + const run = check => spawnSync(process.execPath, + [path.join(__dirname, "patch-api-key-home-navigation.js"), "win", ...(check ? ["--check"] : [])], + { encoding: "utf8", env: { ...process.env, CODEX_PATCH_SOURCE_DIR: root } }); + const checked = run(true); + assert.equal(checked.status, 0, checked.stdout + checked.stderr); + assert.equal(fs.readFileSync(primary, "utf8"), fixture()); + const applied = run(false); + assert.equal(applied.status, 0, applied.stdout + applied.stderr); + const patched = fs.readFileSync(primary, "utf8"); + assert.ok(patched.includes(MARKER)); + assert.equal(fs.readFileSync(shared, "utf8"), unrelated); + assert.equal(run(true).status, 0); + assert.equal(fs.readFileSync(primary, "utf8"), patched); + fs.writeFileSync(shared, unrelated + MARKER); + assert.equal(run(true).status, 1, "无跟踪器却包含残缺补丁时仍须拒绝"); +}); + +test("26.1021 真实资源:首页记录、离开和设置页完整恢复", { + skip: !process.env.CODEX_REBUILD_1021_ASSETS, +}, () => { + const directory = process.env.CODEX_REBUILD_1021_ASSETS; + const input = fs.readFileSync(path.join(directory, "app-primary-844e405f2b90.js"), "utf8"); + assert.equal(require("node:crypto").createHash("sha256").update(input).digest("hex"), + "298f4c7bafe278563aa82ef8d8d4c1afe3f581d54915917849065085f7f621d2"); + const result = patchSource(input); + assert.equal(result.status, "patched", result.reason); + const ast = acorn.parse(result.source, { ecmaVersion: "latest", sourceType: "module" }); + const functions = ["oNn", "HOt", "ekt", "jOt", "MOt", "ZOt", "$Ot", "QOt", "UOt", "KOt", "GOt"] + .map(name => { + const found = ast.body.filter(node => node.type === "FunctionDeclaration" && node.id.name === name); + assert.equal(found.length, 1, `真实函数 ${name} 必须唯一`); + return result.source.slice(found[0].start, found[0].end); + }).join("\n"); + const harness = Function("assert", ` + const atoms=Object.fromEntries(["PS","Wy","BD","vE","uP","lP","kS","iKe","xZe","xG"].map(id=>[id,{id}])); + const {PS,Wy,BD,vE,uP,lP,kS,iKe,xZe,xG}=atoms; + const values=new Map([[PS,false],[BD,"codex"],[vE,{projectId:"sample"}]]),records=new Map(); + const store={get(atom,partition){assert.ok(atom?.id,"get 必须使用 atom");return atom===lP?(records.get(partition)||{}):values.get(atom)}, + set(atom,...args){assert.ok(atom?.id,"set 必须使用 atom");if(atom===lP)records.set(args[0],args[1]);else values.set(atom,args[0])}}; + let current,navigated=null;const auth={authMethod:"apikey"}; + values.set(kS,{prepareNavigation:(pathname,options)=>()=>{navigated={pathname,...options}}}); + const q={},yG={},sNn={c:()=>[]},cNn={useContext:()=>null,useLayoutEffect:fn=>fn()}; + const Jd=()=>store,_n=()=>current,rw=()=>auth,X=atom=>store.get(atom); + const Fm={home:{destinationId:"builtin:home"}},sm="/orbit",tkt=480000; + const Sne="/site",Nte="/review",Co=()=>null,Ys=()=>null,jo=()=>false; + const sD=({pathname})=>({routeKind:pathname.startsWith("/settings")?"other":"home"}); + const Ga=location=>location.pathname,m0e=(target,project)=>target.set(vE,project); + ${functions} + return {visit(location){current=location;values.set(Wy,location);oNn()}, + click(){navigated=null;GOt(store,{accountKey:"auth:apikey",auth,area:"home",navigate:pathname=>{navigated={pathname}},productMode:"codex",state:{}});return navigated}, + record(){return records.get("auth:apikey:codex")?.["builtin:home"]}}; + `)(assert); + const thread = { pathname: "/local/sample-thread", key: "thread", search: "", hash: "", + state: { sidebarThreadLocationId: "chats", sidebarProductMode: "codex", sidebarProductModeAccountKey: "auth:apikey" } }; + harness.visit(thread); + assert.equal(harness.record().location.pathname, thread.pathname); + assert.equal(harness.click(), null); + harness.visit({ pathname: "/settings/general", key: "settings", search: "", hash: "", state: null }); + assert.equal(harness.record().location.pathname, thread.pathname); + assert.ok(harness.record().departedAt > 0); + const restored = harness.click(); + assert.equal(restored.pathname, thread.pathname); + assert.equal(restored.state.sidebarThreadLocationId, "chats"); + assert.equal(restored.state.sidebarProductModeAccountKey, "auth:apikey"); + assert.equal(patchSource(result.source).status, "already-patched"); +}); diff --git a/scripts/patch-crash-forensics.js b/scripts/patch-crash-forensics.js index 9d468d94..53bc83ef 100644 --- a/scripts/patch-crash-forensics.js +++ b/scripts/patch-crash-forensics.js @@ -540,6 +540,20 @@ function stripKnownInjections(code) { return { code: next, stripped }; } +// 隔离环境必须先于 Electron 初始化;诊断代码不能抢到环境加载器之前。 +function splitStartupPrefix(code) { + const ast = acorn.parse(code, { ecmaVersion: 2022, sourceType: "script", allowHashBang: true }); + let offset = code.startsWith("#!") ? code.indexOf("\n") + 1 : 0; + for (const node of ast.body) { + if (node.directive) { offset = node.end; continue; } + if (node.type === "ExpressionStatement" && node.expression.type === "CallExpression" && + node.expression.callee.name === "require" && node.expression.arguments.length === 1 && + node.expression.arguments[0].value === "./codex-rebuild-test-environment.cjs") offset = node.end; + break; + } + return { prefix: code.slice(0, offset), code: code.slice(offset).trimStart() }; +} + function isElectronBootstrap(code) { let ast; try { @@ -661,15 +675,17 @@ function main() { for (const bundle of bundles) { const code = fs.readFileSync(bundle.path, "utf-8"); - if (code.includes(MARKER)) { - const afterCurrent = stripLeadingForensicsInjection(code).code; - if (!startsWithForensicsInjection(afterCurrent)) { - console.log(` [ok] ${relPath(bundle.path)}: already patched`); - continue; - } + const leading = splitStartupPrefix(code); + const strippedResult = stripKnownInjections(leading.code); + // 旧组合把诊断放在环境前;移除已知诊断后再提取环境入口,原生代码不变。 + const remaining = splitStartupPrefix(strippedResult.code); + const prefix = leading.prefix + remaining.prefix; + const baseCode = remaining.code, stripped = strippedResult.stripped; + if ([MARKER, ...LEGACY_MARKERS].some(marker => baseCode.includes(marker))) { + console.log(` [x] ${relPath(bundle.path)}: unexpected nested forensics injection`); + failed++; + continue; } - - const { code: baseCode, stripped } = stripKnownInjections(code); if (!bundle.declared && !isElectronBootstrap(baseCode)) { console.log( ` [x] ${relPath(bundle.path)}: not an Electron main entry, skipping`, @@ -678,7 +694,11 @@ function main() { continue; } - const next = INJECT + baseCode; + const next = (prefix ? prefix + "\n" : "") + INJECT + baseCode; + if (next === code) { + console.log(` [ok] ${relPath(bundle.path)}: already patched`); + continue; + } // 写入前对最终结果做语法校验,解析失败则中止不写 try { diff --git a/scripts/patch-mcp-status-refresh.js b/scripts/patch-mcp-status-refresh.js index 30354455..5f18548b 100644 --- a/scripts/patch-mcp-status-refresh.js +++ b/scripts/patch-mcp-status-refresh.js @@ -50,7 +50,7 @@ function targetCase(ast) { return branch; } -function analyzeOriginal(source, branch) { +function analyzeOriginal(source, branch, ast) { const expression = branch.consequent[0].expression; if (expression.type !== "SequenceExpression" || expression.expressions.length !== 2) { throw new Error("MCP 启动状态刷新表达式结构异常"); @@ -69,7 +69,21 @@ function analyzeOriginal(source, branch) { throw new Error("MCP global 状态条件结构异常"); } - const scheduled = readyRefresh.consequent; + let scheduled = readyRefresh.consequent; + let pending = ""; + let callbackPrefix = ""; + let inventoryRefresh = ""; + let inventoryOwner; + if (scheduled.type === "SequenceExpression" && scheduled.expressions.length === 2) { + const accumulation = scheduled.expressions[0]; + if (accumulation.type !== "AssignmentExpression" || accumulation.operator !== "||=" || + accumulation.left.type !== "Identifier" || accumulation.right.type !== "CallExpression" || + source.slice(accumulation.right.arguments[0]?.start, accumulation.right.arguments[0]?.end) !== `${notification}.params.name`) { + throw new Error("MCP inventory 累积结构异常"); + } + pending = source.slice(accumulation.start, accumulation.end); + scheduled = scheduled.expressions[1]; + } if (scheduled.type !== "AssignmentExpression" || scheduled.operator !== "??=" || scheduled.left.type !== "Identifier" || scheduled.right.type !== "CallExpression" || scheduled.right.callee.type !== "Identifier" || scheduled.right.callee.name !== "setTimeout" || @@ -78,11 +92,34 @@ function analyzeOriginal(source, branch) { } const timer = scheduled.left.name; const callback = scheduled.right.arguments[0]; - const bodyExpression = callback?.type === "ArrowFunctionExpression" && + let bodyExpression = callback?.type === "ArrowFunctionExpression" && callback.body.type === "BlockStatement" && callback.body.body.length === 1 && callback.body.body[0].type === "ExpressionStatement" ? callback.body.body[0].expression : null; + if (pending && callback?.body?.body.length === 3) { + const [resetTimer, capture, work] = callback.body.body; + const captured = capture.type === "VariableDeclaration" && capture.declarations.length === 1 + ? capture.declarations[0] : null; + const sequence = work.type === "ExpressionStatement" ? work.expression : null; + const clear = sequence?.type === "SequenceExpression" && sequence.expressions.length === 2 + ? sequence.expressions[0] : null; + if (resetTimer.type !== "ExpressionStatement" || captured?.id.type !== "Identifier" || + captured.init?.type !== "Identifier" || !pending.startsWith(`${captured.init.name}||=`) || + clear?.type !== "AssignmentExpression" || clear.left.name !== captured.init.name || + source.slice(clear.right.start, clear.right.end) !== "!1") { + throw new Error("MCP inventory 回调捕获结构异常"); + } + callbackPrefix = `${source.slice(capture.start, capture.end)}${source.slice(clear.start, clear.end)},`; + bodyExpression = { type: "SequenceExpression", expressions: [resetTimer.expression, sequence.expressions[1]] }; + const calls = sequence.expressions[1]?.right?.expressions; + const inventory = calls?.length === 3 ? calls[1] : null; + if (inventory?.type !== "CallExpression" || inventory.arguments.length !== 1 || + inventory.arguments[0].name !== captured.id.name) { + throw new Error("MCP inventory 回调调用结构异常"); + } + inventoryRefresh = source.slice(inventory.start, inventory.end); + } if (bodyExpression?.type !== "SequenceExpression" || bodyExpression.expressions.length !== 2) { throw new Error("MCP 轻量刷新回调结构异常"); } @@ -92,12 +129,13 @@ function analyzeOriginal(source, branch) { guarded.type !== "LogicalExpression" || guarded.operator !== "&&" || guarded.left?.type !== "LogicalExpression" || guarded.left.operator !== "&&" || guarded.left.left?.type !== "Identifier" || guarded.right?.type !== "SequenceExpression" || - guarded.right.expressions.length !== 2) { + guarded.right.expressions.length !== (pending ? 3 : 2)) { throw new Error("MCP 轻量刷新守卫结构异常"); } const active = guarded.left.left.name; const guard = source.slice(guarded.left.right.start, guarded.left.right.end); - const [toolsCall, mentionCall] = guarded.right.expressions; + const toolsCall = guarded.right.expressions[0]; + const mentionCall = guarded.right.expressions.at(-1); const toolsText = source.slice(toolsCall.start, toolsCall.end); const mentionText = source.slice(mentionCall.start, mentionCall.end); if (!toolsText.includes("toolsAndAuthOnly") || !mentionText.includes("mention-discovery")) { @@ -117,9 +155,36 @@ function analyzeOriginal(source, branch) { const host = queryKey.elements[1].name; const installedText = source.slice(readyRefresh.alternate.start, readyRefresh.alternate.end); - if (!installedText.includes("installed-inventory") || !installedText.includes("installed")) { + if (!pending && (!installedText.includes("installed-inventory") || !installedText.includes("installed"))) { throw new Error("MCP installed inventory 刷新结构异常"); } + if (pending) { + const original = readyRefresh.alternate; + const installedCall = original.type === "LogicalExpression" ? original.right : null; + const pendingCall = readyRefresh.consequent.expressions[0].right; + if (installedCall?.type !== "CallExpression" || installedCall.callee.name !== + guarded.right.expressions[1].callee.name || installedCall.arguments.length !== 1 || + source.slice(installedCall.arguments[0].start, installedCall.arguments[0].end) !== + source.slice(pendingCall.start, pendingCall.end)) { + throw new Error("MCP installed inventory helper 调用结构异常"); + } + const enclosing = []; + walk(ast, node => { + if (node.type === "FunctionDeclaration" && node.start < branch.start && node.end > branch.end) enclosing.push(node); + }); + const owner = enclosing.sort((a, b) => (a.end - a.start) - (b.end - b.start))[0]; + inventoryOwner = owner; + const helpers = []; + if (owner) walk(owner, node => { + if (node.type === "VariableDeclarator" && node.id.name === installedCall.callee.name && + node.init?.type === "ArrowFunctionExpression") helpers.push(node); + }, { ownScope: true }); + const helperText = helpers.length === 1 ? source.slice(helpers[0].start, helpers[0].end) : ""; + if (!["installed-inventory", "installed", `${queryClient}`].every(term => helperText.includes(term)) || + !helperText.includes(`[2]===${host}`)) { + throw new Error("MCP installed inventory helper 定义结构异常"); + } + } const blanket = source.slice(scopedRefresh.consequent.start, scopedRefresh.consequent.end); if (!blanket.includes(`queryKey:[...${queryBase},${host}]`) || blanket.includes("refetchType")) { throw new Error("MCP Full blanket 刷新结构异常"); @@ -144,6 +209,10 @@ function analyzeOriginal(source, branch) { globalText, installedText, threadRefresh, + pending, + callbackPrefix, + inventoryRefresh, + inventoryOwner, }; } @@ -190,12 +259,20 @@ function patchSource(source) { try { const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); const branch = targetCase(ast); - const shape = analyzeOriginal(source, branch); + const shape = analyzeOriginal(source, branch, ast); + if (shape.pending && source.includes("__codexMcpThreadReadyPending")) { + throw new Error("MCP thread-ready pending binding 已存在但缺少补丁标记"); + } const fullStale = `${shape.queryClient}.invalidateQueries({queryKey:[...${shape.queryBase},${shape.host}],predicate:({queryKey:e})=>e.length===${shape.queryBase}.length+2&&e[${shape.queryBase}.length+1]===\`full\`,refetchType:\`none\`})${MARKER}`; - const schedule = `${shape.timer}??=setTimeout(()=>{${shape.timer}=void 0,${shape.active}&&(${shape.guard})&&(${shape.toolsText},${shape.mentionText},${fullStale})},${REFRESH_DELAY_MS})`; + const inventoryCapture = shape.pending ? "let __codexMcpRefreshInventory=__codexMcpThreadReadyPending;__codexMcpThreadReadyPending=!1;" : ""; + const schedule = `${shape.pending ? `${shape.readyText}&&(__codexMcpThreadReadyPending=!0,${shape.pending}),` : ""}${shape.timer}??=setTimeout(()=>{${shape.timer}=void 0;${inventoryCapture}${shape.callbackPrefix}${shape.active}&&(${shape.guard})&&(${shape.toolsText},${shape.inventoryRefresh ? `__codexMcpRefreshInventory&&${shape.inventoryRefresh},` : ""}${shape.mentionText},${fullStale})},${REFRESH_DELAY_MS})`; const globalOnly = `${shape.notification}.params.threadId==null&&(${shape.installedText})`; const replacement = `(${shape.readyText}||${shape.globalText})&&(${schedule}),${globalOnly},${shape.threadRefresh}`; - const next = source.slice(0, shape.expression.start) + replacement + source.slice(shape.expression.end); + let next = source.slice(0, shape.expression.start) + replacement + source.slice(shape.expression.end); + if (shape.inventoryOwner) { + const start = shape.inventoryOwner.body.start + 1; + next = next.slice(0, start) + "let __codexMcpThreadReadyPending=!1;" + next.slice(start); + } validatePatchedSource(next); return { status: "patched", source: next }; } catch (error) { @@ -221,7 +298,7 @@ function main() { for (const directory of directories) { try { const results = fs.readdirSync(directory.path) - .filter((name) => /^app-initial-.*\.js$/.test(name)) + .filter((name) => name.endsWith(".js")) .map((name) => ({ name, path: path.join(directory.path, name) })) .map((file) => ({ ...file, source: fs.readFileSync(file.path, "utf8") })) .map((file) => ({ file, result: patchSource(file.source) })) diff --git a/scripts/patch-mcp-status-refresh.test.js b/scripts/patch-mcp-status-refresh.test.js index 705275bc..f404cdc8 100644 --- a/scripts/patch-mcp-status-refresh.test.js +++ b/scripts/patch-mcp-status-refresh.test.js @@ -92,9 +92,94 @@ test("残缺标记明确失败", () => { assert.match(result.reason, /数量异常|缺失|分支/); }); +test("拆分后的 inventory helper 保持线程累计刷新且不重复刷新 global 库存", () => { + const source = fixture() + .replace("let i=!0,C,S=new Set,x;", "let i=!0,C,S=new Set,x,D=!1,O=n=>{GE(e.queryClient,{queryKey:WT,predicate:({queryKey:e})=>(e[1]===`installed-inventory`||e[1]===`installed`&&n)&&e[2]===t},{cancelRefetch:!1})};") + .replace("?C??=setTimeout(()=>{C=void 0,", "?(D||=K_(n.params.name),C??=setTimeout(()=>{C=void 0;let n=D;D=!1,") + .replace("exact:!0},{cancelRefetch:!1}),GE", "exact:!0},{cancelRefetch:!1}),O(n),GE") + .replace("},0):n.params.status===`ready`&&GE(e.queryClient,{queryKey:WT,predicate:({queryKey:e})=>(e[1]===`installed-inventory`||e[1]===`installed`&&K_(n.params.name))&&e[2]===t},{cancelRefetch:!1})", + "},0)):n.params.status===`ready`&&O(K_(n.params.name))"); + const result = patchSource(source); + assert.equal(result.status, "patched", result.reason); + assert.equal(patchSource(result.source).status, "already-patched"); + const calls = [], timers = [], listener = load(result.source, calls, timers); + const notify = threadId => listener({ method: "mcpServer/startupStatus/updated", params: { threadId, status: "ready", name: "plugin-a" } }); + notify(null); notify(null); + assert.equal(calls.length, 2); + timers.shift().callback(); + assert.equal(calls.filter(call => call.filters.queryKey?.[0] === "plugins").length, 2); + calls.length = 0; notify("thread-a"); notify("thread-b"); + for (const timer of timers.splice(0)) timer.callback(); + assert.equal(calls.filter(call => call.filters.queryKey?.[0] === "plugins").length, 1); + assert.equal(calls.filter(call => call.filters.queryKey?.at(-1) === "toolsAndAuthOnly").length, 1); +}); + test("无关 Bundle 不适用", () => { const source = "function unrelated(){return true}"; const result = patchSource(source); assert.equal(result.status, "not-applicable"); assert.equal(result.source, source); }); + +test("26.1021 真实通知函数保留 inventory 并合并轻量目录刷新", { skip: !process.env.CODEX_REBUILD_1021_BUNDLE }, () => { + const fs = require("node:fs"), path = require("node:path"), vm = require("node:vm"); + const { parse } = require("acorn"); + const { walk, literal } = require("./patch-ast-util"); + let file = process.env.CODEX_REBUILD_1021_BUNDLE; + if (fs.statSync(file).isDirectory()) { + const names = fs.readdirSync(file).filter(name => /^initialize-app-host-services-.*\.js$/.test(name) && + fs.readFileSync(path.join(file, name), "utf8").includes("toolsAndAuthOnly")); + assert.equal(names.length, 1); file = path.join(file, names[0]); + } + const source = fs.readFileSync(file, "utf8"), result = patchSource(source); + assert.equal(result.status, "patched", result.reason); + assert.equal(patchSource(result.source).status, "already-patched"); + const ast = parse(result.source, { ecmaVersion: "latest", sourceType: "module" }); + const branches = [], arrows = [], helpers = []; + walk(ast, node => { + if (node.type === "SwitchCase" && literal(node.test) === "mcpServer/startupStatus/updated" && + result.source.slice(node.start, node.end).includes(MARKER)) branches.push(node); + if (node.type === "ArrowFunctionExpression") arrows.push(node); + if (node.type === "VariableDeclarator" && node.id.name === "O" && + result.source.slice(node.start, node.end).includes("installed-inventory")) helpers.push(node); + }); + assert.equal(branches.length, 1); assert.equal(helpers.length, 1); + const branch = branches[0]; + const listener = arrows.filter(node => node.start < branch.start && node.end > branch.end) + .sort((a, b) => (a.end - a.start) - (b.end - b.start))[0]; + const calls = [], timers = []; + const context = vm.createContext({ + e: { queryClient: { invalidateQueries: filters => calls.push({ kind: "invalidate", filters }) } }, + t: "local", r: () => true, lh: ["mcp"], Xh: ["plugins"], ea: name => name === "plugin-a", + eg: (client, filters, options) => calls.push({ kind: "refresh", filters, options }), + setTimeout: (callback, delay) => { const timer = { callback, delay }; timers.push(timer); return timer; }, + }); + vm.runInContext(`let i=true,E,D=false,T=new Set,w,__codexMcpThreadReadyPending=false;let ${result.source.slice(helpers[0].start, helpers[0].end)};globalThis.listener=${result.source.slice(listener.start, listener.end)}`, context); + const notify = (threadId, status = "ready") => context.listener({ method: "mcpServer/startupStatus/updated", params: { threadId, status, name: "plugin-a" } }); + notify(null); notify(null); + assert.deepEqual(timers.map(timer => timer.delay), [REFRESH_DELAY_MS]); + assert.equal(calls.filter(call => call.filters.queryKey?.[0] === "plugins").length, 2); + timers.shift().callback(); + assert.equal(calls.filter(call => call.filters.queryKey?.[0] === "plugins").length, 2, + "global 通知不应在延迟回调再次刷新 inventory"); + assert.equal(calls.filter(call => call.filters.queryKey?.at(-1) === "toolsAndAuthOnly").length, 1); + assert.equal(calls.filter(call => call.filters.queryKey?.at(-1) === "mention-discovery").length, 1); + const full = calls.find(call => call.filters.refetchType === "none"); + assert.ok(full); assert.equal(full.filters.predicate({ queryKey: ["mcp", "local", "full"] }), true); + assert.equal(full.filters.predicate({ queryKey: ["mcp", "local", "thread", "thread-a", "full"] }), false); + calls.length = 0; + notify("thread-a"); notify("thread-b"); + assert.deepEqual(timers.map(timer => timer.delay).sort((a, b) => a - b), [0, REFRESH_DELAY_MS]); + for (const timer of timers.splice(0)) timer.callback(); + const inventory = calls.find(call => call.filters.queryKey?.[0] === "plugins"); + assert.ok(inventory); assert.equal(inventory.filters.predicate({ queryKey: ["plugins", "installed", "local"] }), true); + const thread = calls.find(call => call.kind === "invalidate" && call.filters.queryKey?.includes("thread")); + assert.ok(thread); assert.equal(thread.filters.predicate({ queryKey: ["mcp", "local", "thread", "thread-a", "full"] }), true); + assert.equal(thread.filters.predicate({ queryKey: ["mcp", "local", "thread", "other", "full"] }), false); + calls.length = 0; notify(null, "starting"); assert.equal(timers.length, 0); assert.deepEqual(calls, []); + notify(null); vm.runInContext("i=false", context); calls.length = 0; + for (const timer of timers.splice(0)) timer.callback(); + assert.deepEqual(calls, [], "已释放 handler 不继续刷新目录"); + assert.equal(patchSource(source.replace("`installed-inventory`", "`unexpected-inventory`")).status, + "unexpected-shape", "inventory helper 漂移不能绕过校验"); +}); diff --git a/scripts/patch-provider-quota.js b/scripts/patch-provider-quota.js index 76221a7e..e121d5f5 100644 --- a/scripts/patch-provider-quota.js +++ b/scripts/patch-provider-quota.js @@ -80,13 +80,58 @@ function importFor(ast, localName) { return null; } -function getProviderMetadata(source) { - const ast = parseModule(source); - const providerReads = nodes(ast, node => node.type === "LogicalExpression" && +function providerReads(ast) { + return nodes(ast, node => node.type === "LogicalExpression" && node.operator === "??" && node.left.type === "CallExpression" && node.left.arguments.length === 2 && node.left.arguments[0]?.type === "Identifier" && property(node.right) === "model_provider"); - const providerAtoms = [...new Set(providerReads.map(node => node.left.arguments[0].name))]; +} + +function getProviderMetadata(source, { resolveModule } = {}) { + const ast = parseModule(source); + const providerAtoms = [...new Set(providerReads(ast).map(node => node.left.arguments[0].name))]; + if (providerAtoms.length === 0 && resolveModule) { + // 26.1021 将 Composer 拆成独立模块。只从它真实导入的 initial 模块 + // 追踪会话 Provider atom,核对 summary.modelProvider 定义及导出初始化器。 + const imports = ast.body.filter(node => node.type === "ImportDeclaration" && + /^\.\/app-initial-[^/]+\.js$/.test(node.source.value)); + const dependencyName = unique([...new Set(imports.map(node => node.source.value))], "Composer initial dependency"); + const dependency = { source: { value: dependencyName }, specifiers: imports.flatMap(node => node.specifiers) }; + const dependencySource = resolveModule(dependency.source.value); + const dependencyAst = parseModule(dependencySource); + const name = unique([...new Set(providerReads(dependencyAst) + .map(node => node.left.arguments[0].name))], "Effective thread-provider dependency"); + const initializer = unique(dependencyAst.body.filter(node => node.type === "FunctionDeclaration" && + nodes(node, child => child.type === "AssignmentExpression" && child.left?.name === name && + nodes(child.right, term => property(term) === "modelProvider").length === 1).length === 1), + "Thread-provider initializer"); + const definition = unique(nodes(initializer, node => node.type === "AssignmentExpression" && + node.left?.name === name), "Thread-provider definition"); + if (!/\(\{summary:/.test(dependencySource.slice(definition.start, definition.end)) || + !/\.modelProvider\|\|null/.test(dependencySource.slice(definition.start, definition.end))) { + throw new Error("Thread-provider summary definition changed"); + } + const exports = dependencyAst.body.filter(node => node.type === "ExportNamedDeclaration") + .flatMap(node => node.specifiers); + const atomExport = unique(exports.filter(item => item.local.name === name), "Thread-provider export").exported.name; + const initExport = unique(exports.filter(item => item.local.name === initializer.id.name), + "Thread-provider initializer export").exported.name; + const aliases = [[atomExport, "__codexQuotaThreadProviderAtom"], [initExport, "__codexQuotaThreadProviderInit"]] + .map(([exported, fallback]) => { + const imported = dependency.specifiers.filter(item => item.imported?.name === exported); + if (imported.length > 1 || !imported.length && source.includes(fallback)) { + throw new Error("Thread-provider import binding is ambiguous/already occupied"); + } + return imported[0]?.local.name ?? fallback; + }); + const [atomAlias, initAlias] = aliases; + const missing = [[atomExport, atomAlias], [initExport, initAlias]] + .filter(([exported]) => !dependency.specifiers.some(item => item.imported?.name === exported)); + return { threadProviderAtom: atomAlias, + threadProviderImport: { source: dependency.source.value, name: atomExport }, + initialize: `${initAlias}(),`, + importText: missing.length ? `import{${missing.map(([exported, local]) => `${exported} as ${local}`).join(",")}}from${JSON.stringify(dependency.source.value)};` : "" }; + } if (providerAtoms.length !== 1) { throw new Error("Effective thread-provider lookup is ambiguous/missing"); } @@ -119,11 +164,12 @@ function hasExternalBaseUrl(provider) { } } -function patchSource(source) { +function patchSource(source, options) { try { const updating = source.includes(MARKER); const ast = parseModule(source); - const { threadProviderAtom } = getProviderMetadata(source); + const metadata = getProviderMetadata(source, options); + const { threadProviderAtom } = metadata; if (!updating && [CUSTOM, PROVIDER, THREAD_PROVIDER, PROVIDER_CONFIG] .some(name => source.includes(name))) { throw new Error("Custom-provider patch binding already exists without its marker"); @@ -189,13 +235,15 @@ function patchSource(source) { const statement = unique(composer.body.body.filter(node => node.type === "VariableDeclaration" && node.declarations.includes(disabled)), "Submit-disabled declaration"); if (config.end > statement.start) throw new Error("Composer config is resolved after submission gating"); - const guard = `${MARKER}\nconst ${THREAD_PROVIDER}=${source.slice(baseBlock.init.callee.start, baseBlock.init.callee.end)}(${threadProviderAtom},${conversation.name}),` + + const providerRead = `${source.slice(baseBlock.init.callee.start, baseBlock.init.callee.end)}(${threadProviderAtom},${conversation.name})`; + const guard = `${MARKER}\nconst ${THREAD_PROVIDER}=${metadata.initialize ? `(${metadata.initialize}${providerRead})` : providerRead},` + `${PROVIDER}=${THREAD_PROVIDER}??(${config.id.name}.isConfigDataPending?null:${config.id.name}.resolvedConfig?.model_provider),` + `${PROVIDER_CONFIG}=${config.id.name}.isConfigDataPending?null:${config.id.name}.resolvedConfig?.model_providers?.[${PROVIDER}],` + `${CUSTOM}=(${scope}.value.kind===\`local\`||${scope}.value.kind===\`new\`&&!${scope}.value.cloudThreadPrototype)` + `&&typeof ${PROVIDER}===\`string\`&&${PROVIDER}.trim().length>0&&${PROVIDER}!==\`openai\`` + `&&(${hasExternalBaseUrl.toString()})(${PROVIDER_CONFIG});`; const edits = []; + if (metadata.importText) edits.push({ start: 0, end: 0, text: metadata.importText }); if (updating) { // Upgrade the previous provider-ID-only guard as well as fresh sources. // Keep the existing hook and quota-gate reads in their original positions. @@ -262,10 +310,11 @@ function main() { const candidates = []; const diagnostics = []; for (const file of files.filter(file => file.source.includes("submitDisabled") && - file.source.includes("model_provider") && file.source.includes("resolvedConfig") && + file.source.includes("resolvedConfig") && file.source.includes("isConfigDataPending"))) { try { - const result = patchSource(file.source); + const result = patchSource(file.source, { resolveModule: name => + fs.readFileSync(path.join(directory.path, name), "utf8") }); if (result.status === "error") throw new Error(result.reason); candidates.push({ file, result }); } diff --git a/scripts/patch-provider-quota.test.js b/scripts/patch-provider-quota.test.js index 85655c0b..cf61f9d0 100644 --- a/scripts/patch-provider-quota.test.js +++ b/scripts/patch-provider-quota.test.js @@ -65,3 +65,107 @@ test("会话 Provider atom 不唯一时拒绝补丁", () => { assert.equal(result.status, "error"); assert.match(result.reason, /thread-provider lookup is ambiguous/); }); + +test("拆分 Composer 只沿真实初始模块导出识别 Provider atom", () => { + const source = fixture().replace(/import[^;]+;/, + 'import{quota as quotaAtom,hard as hardBlockAtom,host as hostAtom}from"./app-initial-fixture.js";') + .replace("function providerFor(store,id,config){return store.get(threadProvider,id)??config.model_provider}", ""); + const dependency = "var atom;function init(){atom=cj(({summary:e})=>e.modelProvider||null)}function providerFor(get,id,config){return get(atom,id)??config.model_provider}export{atom as provider,init as initialize};"; + const options = { resolveModule: name => { assert.equal(name, "./app-initial-fixture.js"); return dependency; } }; + const result = patchSource(source, options); + assert.equal(result.status, "patched", result.reason); + assert.match(result.code, /provider as __codexQuotaThreadProviderAtom/); + assert.match(result.code, /initialize as __codexQuotaThreadProviderInit/); + assert.match(result.code, /__codexQuotaThreadProviderInit\(\),read\(__codexQuotaThreadProviderAtom,conversation\)/); + assert.equal(patchSource(result.code, options).status, "already"); + assert.equal(patchSource(source).status, "error"); + assert.equal(patchSource(source, { resolveModule: () => dependency.replace("modelProvider", "otherProvider") }).status, "error"); + assert.equal(patchSource(source, { resolveModule: () => dependency.replace("atom as provider", "other as provider") }).status, "error"); +}); + +test("实际生成的发送门槛只忽略明确第三方端点的官方额度", () => { + const result = patchSource(fixture()); + assert.equal(result.status, "patched", result.reason); + const { parse } = require("acorn"); + const composer = parse(result.code, { ecmaVersion: "latest", sourceType: "module" }).body + .find(node => node.type === "FunctionDeclaration" && node.id.name === "Composer"); + const source = result.code.slice(composer.start, composer.end); + const vm = require("node:vm"); + let state; + const context = vm.createContext({ + URL, threadProvider: "provider", quotaAtom: "quota", hardBlockAtom: "hard", hostAtom: "host", + target: {}, Editor: {}, cacheMiss: () => true, currentConversation: () => "thread-a", + useScope: () => ({ value: state.scope ?? { kind: "local" } }), + useConfig: () => ({ isLoading: false, isConfigDataPending: state.pending ?? false, + resolvedConfig: { model_provider: "custom", model_providers: state.providers } }), + read: atom => atom === "provider" ? state.threadProvider : atom === "host" ? "local" : true, + value: () => true, save: () => {}, jsx: (_, props) => props, + }); + vm.runInContext(source, context); + for (const endpoint of ["https://proxy.example/v1", "http://127.0.0.1:8080/v1"]) { + state = { providers: { custom: { base_url: endpoint, requires_openai_auth: true } } }; + assert.equal(context.Composer({}).submitDisabled, false, endpoint); + assert.equal(context.Composer({ submitDisabled: true }).submitDisabled, true, + "外部禁用条件不能因自定义 Provider 被忽略"); + } + for (const endpoint of [undefined, "", "https://chatgpt.com/backend-api/codex", + "https://sub.chatgpt.com./codex", "https://chat.openai.com/codex", "file:///tmp/api", "invalid"]) { + state = { providers: { custom: { base_url: endpoint } } }; + assert.equal(context.Composer({}).submitDisabled, true, String(endpoint)); + } + state = { providers: { custom: { base_url: "https://proxy.example/v1" } }, pending: true }; + assert.equal(context.Composer({}).submitDisabled, true, "待解析配置不能绕过额度"); + state = { providers: { custom: { base_url: "https://proxy.example/v1" } }, threadProvider: "openai" }; + assert.equal(context.Composer({}).submitDisabled, true, "已保存会话 Provider 优先于当前配置"); + state = { providers: { custom: { base_url: "https://proxy.example/v1" } }, scope: { kind: "cloud" } }; + assert.equal(context.Composer({}).submitDisabled, true, "云会话不能绕过官方额度"); +}); + +test("26.1021 真实 adapter 的 Provider 依赖与发送门槛", { skip: !process.env.CODEX_REBUILD_1021_BUNDLE }, () => { + const fs = require("node:fs"), path = require("node:path"), vm = require("node:vm"); + const { parse } = require("acorn"); + const { walk } = require("./patch-ast-util"); + let file = process.env.CODEX_REBUILD_1021_BUNDLE; + if (fs.statSync(file).isDirectory()) { + const names = fs.readdirSync(file).filter(name => /^codex-composer-adapter-.*\.js$/.test(name) && + fs.readFileSync(path.join(file, name), "utf8").includes("isConfigDataPending")); + assert.equal(names.length, 1); file = path.join(file, names[0]); + } + const source = fs.readFileSync(file, "utf8"); + const options = { resolveModule: name => fs.readFileSync(path.join(path.dirname(file), name), "utf8") }; + const result = patchSource(source, options); + assert.equal(result.status, "patched", result.reason); + assert.equal(patchSource(result.code, options).status, "already"); + assert.equal(patchSource(source).status, "error", "缺少真实依赖时不能推测 Provider atom"); + const ast = parse(result.code, { ecmaVersion: "latest", sourceType: "module" }); + const composer = ast.body.find(node => node.type === "FunctionDeclaration" && + result.code.slice(node.start, node.end).includes("const __codexQuotaThreadProvider=")); + const guardIndex = composer.body.body.findIndex(node => node.type === "VariableDeclaration" && + node.declarations[0].id.name === "__codexQuotaThreadProvider"); + const guard = composer.body.body[guardIndex], disabled = composer.body.body[guardIndex + 1].declarations[0]; + const names = new Set(); + walk(disabled.init, node => { if (node.type === "Identifier") names.add(node.name); }); + const context = vm.createContext(Object.fromEntries([...names].map(name => [name, false]))); + let state; + Object.assign(context, { URL, H: "thread-a", __codexQuotaThreadProviderAtom: {}, sn: () => {}, + A: () => state.savedProvider, R: { value: { kind: "local" } }, + Fr: { isConfigDataPending: false, resolvedConfig: { model_provider: "custom", model_providers: {} } }, + Pn: true, Ur: true }); + vm.runInContext(`function evaluate(){${result.code.slice(guard.start, guard.end)}return ${result.code.slice(disabled.init.start, disabled.init.end)}}`, context); + for (const endpoint of ["https://proxy.example/v1", "http://localhost:8000/v1", "https://chatgpt.com", undefined]) { + state = {}; + context.Fr.resolvedConfig.model_providers.custom = { base_url: endpoint, requires_openai_auth: true }; + assert.equal(context.evaluate(), endpoint == null || endpoint === "https://chatgpt.com", String(endpoint)); + } + context.Fr.resolvedConfig.model_providers.custom = { base_url: "https://proxy.example/v1" }; + state.savedProvider = "openai"; + assert.equal(context.evaluate(), true, "会话已保存 Provider 优先于当前配置"); + state.savedProvider = null; + context.Fr.isConfigDataPending = true; + assert.equal(context.evaluate(), true); + context.Fr.isConfigDataPending = false; + context.R.value = { kind: "new", cloudThreadPrototype: true }; + assert.equal(context.evaluate(), true); + context.R.value = { kind: "local" }; context.yt = true; + assert.equal(context.evaluate(), true, "外部 submitDisabled 不被绕过"); +}); diff --git a/scripts/patch-remote-control.js b/scripts/patch-remote-control.js index f687d19a..a0d3c240 100644 --- a/scripts/patch-remote-control.js +++ b/scripts/patch-remote-control.js @@ -20,6 +20,7 @@ const PLATFORMS = ["mac-arm64", "mac-x64", "win"]; const STORAGE_KEY = "local_remote_control_enabled"; const MARKER = "/* CodexRebuildRemoteControlAuthIsolation */"; const GATE_MARKER = "/* CodexRebuildRemoteControlGateAuthIsolation */"; +const CATALOG_MARKER = "/* CodexRebuildRemoteControlCatalog */"; function propertyName(member) { if (member?.type !== "MemberExpression") return null; @@ -177,7 +178,7 @@ function findCurrentAuth(allFunctions, source) { function findGateBridge(allFunctions, source) { const candidates = allFunctions.filter((node) => { const text = source.slice(node.start, node.end); - return text.includes("set-remote-control-connections-enabled") && + return (text.includes("set-remote-control-connections-enabled") || text.includes("setRemoteControlEnabled")) && text.includes("remote-connections/gate-bridge") && text.includes("1042620455"); }); if (candidates.length !== 1) { @@ -218,9 +219,10 @@ function findGateBridge(allFunctions, source) { const catches = descendants(fn, (node) => node.type === "CallExpression" && propertyName(node.callee) === "catch" && node.callee.object?.type === "CallExpression" && - node.callee.object.arguments.some((argument) => - literal(argument) === "set-remote-control-connections-enabled")); - if (catches.length !== 1 || catches[0].callee.object.callee?.type !== "Identifier" || + (node.callee.object.arguments.some((argument) => + literal(argument) === "set-remote-control-connections-enabled") || + propertyName(node.callee.object.callee) === "setRemoteControlEnabled")); + if (catches.length !== 1 || catches[0].arguments.length !== 1) { throw new Error("Remote Control gate bridge IPC 结构异常"); } @@ -230,6 +232,21 @@ function findGateBridge(allFunctions, source) { if (effectCallee?.object.type !== "Identifier") { throw new Error("Remote Control gate bridge useEffect 结构异常"); } + const sync = catches[0].callee.object; + let nativeService; + if (propertyName(sync.callee) === "setRemoteControlEnabled") { + const service = descendants(fn, node => node.type === "VariableDeclarator" && + node.id.name === sync.callee.object?.name && propertyName(node.init) === "remoteConnections"); + if (service.length !== 1 || sync.arguments.length !== 1 || + sync.arguments[0].type !== "ObjectExpression" || + !["enabled", "oneToOnePairingInAppEnabled"].every(name => + sync.arguments[0].properties.some(node => node.key?.name === name))) { + throw new Error("Remote Control native bridge 结构异常"); + } + nativeService = source.slice(service[0].init.start, service[0].init.end); + } else if (sync.callee.type !== "Identifier") { + throw new Error("Remote Control gate bridge IPC 结构异常"); + } return { fn, gateHook: gateState[0].init.callee.name, @@ -239,6 +256,7 @@ function findGateBridge(allFunctions, source) { ipc: catches[0].callee.object.callee.name, catchHandler: source.slice(catches[0].arguments[0].start, catches[0].arguments[0].end), react: effectCallee.object.name, + nativeService, }; } @@ -251,16 +269,97 @@ function validatePatchedSource(source) { if (count(source, GATE_MARKER) !== 1) throw new Error(`${GATE_MARKER} 数量异常`); if (source.includes("codex-remote-gate:")) throw new Error("仍存在强制开启 Remote Control gate 的旧标记"); if (!source.includes("__codexRemoteAccount?.authMethod!==`chatgpt`") || - !source.includes("__codexSetRemoteEnabled(!1)") || + !(source.includes("__codexSetRemoteEnabled(!1)") || source.includes(CATALOG_MARKER)) || !source.includes("__codexRemoteAccount?.authLoading") || !source.includes("__codexRemoteGateAccount?.authMethod===`chatgpt`") || !source.includes("__codexRemoteGateAccount?.authLoading")) { throw new Error("Remote Control 认证隔离或遗留状态清理不完整"); } - parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const isolated = descendants(ast, node => node.type === "IfStatement" && + source.slice(node.test.start, node.test.end) === "__codexRemoteAccount?.authMethod!==`chatgpt`"); + if (isolated.length !== 1 || isolated[0].consequent.type !== "BlockStatement" || + isolated[0].consequent.body.at(-1)?.type !== "ReturnStatement") { + throw new Error("Remote Control 非 ChatGPT disable 分支缺失"); + } + const disableCalls = descendants(isolated[0].consequent, node => node.type === "CallExpression" && + propertyName(node.callee) === "catch" && node.callee.object?.type === "CallExpression" && + node.callee.object.callee.type === "Identifier" && node.callee.object.arguments.length === 2 && + node.callee.object.arguments[0].type === "Identifier" && + source.slice(node.callee.object.arguments[1].start, node.callee.object.arguments[1].end) === "!1"); + if (disableCalls.length !== 1) throw new Error("Remote Control 非 ChatGPT 未强制同步 disable"); +} + +function catalogContext(ast, allFunctions, source, resolveModule) { + if (!resolveModule) throw new Error("Remote Control catalog 需要真实 import/export 依赖资源"); + const remote = allFunctions.filter(fn => source.slice(fn.start, fn.end) + .includes("Failed to sync local remote control enablement")); + if (remote.length !== 1) throw new Error("Remote Control catalog 同步组件数量异常"); + const fn = remote[0]; + const declarations = descendants(fn, node => node.type === "VariableDeclarator", { skipNestedFunctions: true }); + const catches = descendants(fn, node => node.type === "CallExpression" && + propertyName(node.callee) === "catch" && node.callee.object?.type === "CallExpression" && + node.callee.object.callee.type === "Identifier" && node.callee.object.arguments.length === 2); + if (catches.length !== 1) throw new Error("Remote Control catalog 同步调用结构异常"); + const sync = catches[0].callee.object; + const [container, stored] = sync.arguments; + const state = declarations.find(node => node.id.name === stored?.name); + const containerDeclaration = declarations.find(node => node.id.name === container?.name); + if (state?.init?.type !== "CallExpression" || state.init.callee.type !== "Identifier" || + state.init.arguments.length !== 1 || state.init.arguments[0].type !== "Identifier" || + containerDeclaration?.init == null) throw new Error("Remote Control catalog atom 读取结构异常"); + const imports = ast.body.filter(node => node.type === "ImportDeclaration"); + const dependency = imports.find(node => node.specifiers.some(item => item.local.name === state.init.arguments[0].name)); + if (!dependency || !/^\.\/app-initial-[^/]+\.js$/.test(dependency.source.value)) { + throw new Error("Remote Control catalog atom 来源异常"); + } + const dependencySource = resolveModule(dependency.source.value); + const dependencyAst = parse(dependencySource, { ecmaVersion: "latest", sourceType: "module" }); + const exports = dependencyAst.body.filter(node => node.type === "ExportNamedDeclaration").flatMap(node => node.specifiers); + const imported = dependency.specifiers.find(item => item.local.name === state.init.arguments[0].name); + const catalogExport = exports.find(item => item.exported.name === imported.imported.name); + const catalog = descendants(dependencyAst, node => node.type === "AssignmentExpression" && + node.left.name === catalogExport?.local.name && descendants(node.right, + member => propertyName(member) === "localRemoteControlEnabled").length === 1); + if (catalog.length !== 1) throw new Error("Remote Control catalog enabled selector 定义异常"); + const fields = ["accountLoading", "authLoading", "authMethod", "authenticatedAccountId", + "hasChatGptToken", "requiresAuth", "supportedSurface"]; + const accounts = []; + for (const initializer of functions(dependencyAst)) { + for (const assignment of descendants(initializer, node => node.type === "AssignmentExpression" && + node.left.type === "Identifier" && node.left.name !== initializer.id.name && node.right.type === "CallExpression")) { + const text = dependencySource.slice(assignment.start, assignment.end); + if (fields.every(field => text.includes(field))) accounts.push({ assignment, initializer }); + } + } + if (accounts.length !== 1) throw new Error(`当前 catalog App Server 认证 atom 数量异常(${accounts.length})`); + const account = accounts[0]; + let importText = ""; + const names = [account.assignment.left.name, account.initializer.id.name].map((name, index) => { + const exported = exports.filter(item => item.local.name === name); + if (exported.length !== 1) throw new Error("当前认证 atom 或初始化器未唯一导出"); + const local = dependency.specifiers.filter(item => item.imported?.name === exported[0].exported.name); + if (local.length === 0 && index === 1 && !source.includes("__codexRemoteAuthInit")) { + importText = `import{${exported[0].exported.name} as __codexRemoteAuthInit}from${JSON.stringify(dependency.source.value)};`; + return "__codexRemoteAuthInit"; + } + if (local.length !== 1) throw new Error("当前认证 atom 或初始化器未真实导入 runtime"); + return local[0].local.name; + }); + const effect = descendants(fn, node => node.type === "CallExpression" && + propertyName(memberCallee(node)) === "useEffect"); + if (effect.length !== 1) throw new Error("Remote Control catalog effect 结构异常"); + return { + remote: { fn, container: container.name, storedValue: stored.name, + containerExpression: source.slice(containerDeclaration.init.start, containerDeclaration.init.end), + catalogRead: source.slice(state.init.start, state.init.end), syncFunction: sync.callee.name, + catchHandler: source.slice(catches[0].arguments[0].start, catches[0].arguments[0].end), + react: memberCallee(effect[0]).object.name }, + currentAuth: { atom: names[0], hook: state.init.callee.name, initializer: { id: { name: names[1] } }, importText }, + }; } -function patchSource(source) { +function patchSource(source, { resolveModule } = {}) { if (source.includes(MARKER) || source.includes(GATE_MARKER)) { try { validatePatchedSource(source); @@ -269,8 +368,7 @@ function patchSource(source) { return { status: "unexpected-shape", source, reason: error.message }; } } - if (!source.includes(STORAGE_KEY) || - !source.includes("Failed to sync local remote control enablement")) { + if (!source.includes("Failed to sync local remote control enablement")) { return { status: "not-applicable", source }; } if (source.includes("codex-remote-gate:")) { @@ -284,13 +382,20 @@ function patchSource(source) { try { const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); const allFunctions = functions(ast); - const remote = findRemoteSync(allFunctions, source); - const currentAuth = findCurrentAuth(allFunctions, source); + // 26.1021 改读 host catalog,没有旧本地开关 setter;仍通过原同步函数 + // 发送 app-server disable,并通过 native bridge 同步 false,不能伪造 ChatGPT。 + const catalog = !source.includes(STORAGE_KEY) ? catalogContext(ast, allFunctions, source, resolveModule) : null; + const remote = catalog?.remote ?? findRemoteSync(allFunctions, source); + const currentAuth = catalog?.currentAuth ?? findCurrentAuth(allFunctions, source); const gate = findGateBridge(allFunctions, source); const remoteInitializer = nextInitializer(allFunctions, remote.fn, source); const gateInitializer = nextInitializer(allFunctions, gate.fn, source); - const replacement = `function ${remote.fn.id.name}(){let ${remote.container}=${remote.containerExpression},[${remote.storedValue},__codexSetRemoteEnabled]=${remote.storageHook}(\`${STORAGE_KEY}\`),__codexRemoteAccount=${currentAuth.hook}(${currentAuth.atom});${remote.react}.useEffect(()=>{if(__codexRemoteAccount?.authLoading)return;if(__codexRemoteAccount?.authMethod!==\`chatgpt\`){${remote.storedValue}===!0&&__codexSetRemoteEnabled(!1),${remote.syncFunction}(${remote.container},!1).catch(${remote.catchHandler});return}${remote.storedValue}!=null&&${remote.syncFunction}(${remote.container},${remote.storedValue}).catch(${remote.catchHandler})},[__codexRemoteAccount?.authMethod,__codexRemoteAccount?.authLoading,${remote.storedValue},__codexSetRemoteEnabled,${remote.container}]);return null}${MARKER}`; - const gateReplacement = `function ${gate.fn.id.name}(){let{checkGate:${gate.checkGate},isLoading:${gate.gateLoading}}=${gate.gateHook}(),__codexRemoteGateAccount=${currentAuth.hook}(${currentAuth.atom}),i=__codexRemoteGateAccount?.authMethod===\`chatgpt\`&&${gate.checkGate}(${gate.oneToOneGate}),o=__codexRemoteGateAccount?.authMethod===\`chatgpt\`&&(${gate.checkGate}(\`1042620455\`)||i);${gate.react}.useEffect(()=>{if(${gate.gateLoading}||__codexRemoteGateAccount?.authLoading)return;${gate.ipc}(\`set-remote-control-connections-enabled\`,{params:{enabled:o,oneToOnePairingInAppEnabled:i}}).catch(${gate.catchHandler})},[${gate.gateLoading},i,o,__codexRemoteGateAccount?.authLoading,__codexRemoteGateAccount?.authMethod]);return null}${GATE_MARKER}`; + const stateRead = catalog ? `${remote.storedValue}=${remote.catalogRead}` : + `[${remote.storedValue},__codexSetRemoteEnabled]=${remote.storageHook}(\`${STORAGE_KEY}\`)`; + const clearLegacy = catalog ? "" : `${remote.storedValue}===!0&&__codexSetRemoteEnabled(!1),`; + const replacement = `function ${remote.fn.id.name}(){let ${remote.container}=${remote.containerExpression},${stateRead},__codexRemoteAccount=${currentAuth.hook}(${currentAuth.atom});${remote.react}.useEffect(()=>{if(__codexRemoteAccount?.authLoading)return;if(__codexRemoteAccount?.authMethod!==\`chatgpt\`){${clearLegacy}${remote.syncFunction}(${remote.container},!1).catch(${remote.catchHandler});return}${remote.storedValue}!=null&&${remote.syncFunction}(${remote.container},${remote.storedValue}).catch(${remote.catchHandler})},[__codexRemoteAccount?.authMethod,__codexRemoteAccount?.authLoading,${remote.storedValue},${catalog ? "" : "__codexSetRemoteEnabled,"}${remote.container}]);return null}${MARKER}${catalog ? CATALOG_MARKER : ""}`; + const syncGate = gate.nativeService ? `let __codexRemoteConnections=${gate.nativeService};__codexRemoteConnections!=null&&__codexRemoteConnections.setRemoteControlEnabled({enabled:o,oneToOnePairingInAppEnabled:i}).catch(${gate.catchHandler})` : `${gate.ipc}(\`set-remote-control-connections-enabled\`,{params:{enabled:o,oneToOnePairingInAppEnabled:i}}).catch(${gate.catchHandler})`; + const gateReplacement = `function ${gate.fn.id.name}(){let{checkGate:${gate.checkGate},isLoading:${gate.gateLoading}}=${gate.gateHook}(),__codexRemoteGateAccount=${currentAuth.hook}(${currentAuth.atom}),i=__codexRemoteGateAccount?.authMethod===\`chatgpt\`&&${gate.checkGate}(${gate.oneToOneGate}),o=__codexRemoteGateAccount?.authMethod===\`chatgpt\`&&(${gate.checkGate}(\`1042620455\`)||i);${gate.react}.useEffect(()=>{if(${gate.gateLoading}||__codexRemoteGateAccount?.authLoading)return;${syncGate}},[${gate.gateLoading},i,o,__codexRemoteGateAccount?.authLoading,__codexRemoteGateAccount?.authMethod]);return null}${GATE_MARKER}`; const currentAuthInit = `${currentAuth.initializer.id.name}(),`; const edits = [ { start: remote.fn.start, end: remote.fn.end, replacement }, @@ -306,6 +411,7 @@ function patchSource(source) { replacement: currentAuthInit, }, ].sort((a, b) => b.start - a.start); + if (currentAuth.importText) edits.push({ start: 0, end: 0, replacement: currentAuth.importText }); let next = source; for (const edit of edits) { next = next.slice(0, edit.start) + edit.replacement + next.slice(edit.end); @@ -336,10 +442,11 @@ function main() { for (const directory of directories) { try { const results = fs.readdirSync(directory.path) - .filter((name) => /^app-initial-.*\.js$/.test(name)) + .filter((name) => name.endsWith(".js")) .map((name) => ({ name, path: path.join(directory.path, name) })) .map((file) => ({ ...file, source: fs.readFileSync(file.path, "utf8") })) - .map((file) => ({ file, result: patchSource(file.source) })) + .map((file) => ({ file, result: patchSource(file.source, { resolveModule: name => + fs.readFileSync(path.join(directory.path, name), "utf8") }) })) .filter((item) => item.result.status !== "not-applicable"); if (results.length !== 1) throw new Error(`Remote Control Bundle 数量异常(${results.length})`); const target = results[0]; @@ -352,7 +459,7 @@ function main() { } else { fs.writeFileSync(target.file.path, target.result.source, "utf8"); patched++; - console.log(" [ok] API-key 已清理并禁用 Remote Control;ChatGPT 保持官方行为"); + console.log(" [ok] 非 ChatGPT 已同步禁用 Remote Control;ChatGPT 保持官方行为"); } } catch (error) { failed++; diff --git a/scripts/patch-remote-control.test.js b/scripts/patch-remote-control.test.js index 774fe688..201467a6 100644 --- a/scripts/patch-remote-control.test.js +++ b/scripts/patch-remote-control.test.js @@ -52,6 +52,65 @@ test("没有 Remote Control 同步组件时不适用", () => { assert.equal(patchSource("const value=1;").status, "not-applicable"); }); +test("catalog 模式要求 enabled selector、完整认证 atom 及初始化器的真实导入", () => { + const source = 'import{catalog as enabledAtom,account as currentAccount,initialize as initAuth}from"./app-initial-fixture.js";' + + fixture().replace('[n]=shared(`local_remote_control_enabled`)', 'n=useAtom(enabledAtom)'); + const dependency = "var enabled,account;function init(){enabled=select(({get:e})=>e(catalog)?.localRemoteControlEnabled),account=atom(()=>({accountLoading:true,authLoading:true,authMethod:null,authenticatedAccountId:null,hasChatGptToken:null,requiresAuth:true,supportedSurface:null}))}export{enabled as catalog,account,init as initialize};"; + const result = patchSource(source, { resolveModule: () => dependency }); + assert.equal(result.status, "patched", result.reason); + assert.equal(patchSource(result.source).status, "already-patched"); + assert.equal(patchSource(source).status, "unexpected-shape"); + assert.equal(patchSource(source, { resolveModule: () => dependency.replace("localRemoteControlEnabled", "otherEnabled") }).status, "unexpected-shape"); + assert.equal(patchSource(source, { resolveModule: () => dependency.replace("account,init as", "other as account,init as") }).status, "unexpected-shape"); +}); + +test("执行生成组件验证认证加载、存储清理及两个 Remote Control 同步入口", async () => { + const result = patchSource(fixture()); + assert.equal(result.status, "patched", result.reason); + const { parse } = require("acorn"); + const vm = require("node:vm"); + const functions = parse(result.source, { ecmaVersion: "latest", sourceType: "module" }).body + .filter(node => node.type === "FunctionDeclaration" && ["remoteSync", "gateBridge"].includes(node.id.name)); + assert.equal(functions.length, 2); + const events = [], container = {}; + let account, enabled, gateLoading = false, remoteGate = true, pairingGate = true; + const context = vm.createContext({ + get: () => container, Container: {}, accountAtom: {}, useAtom: () => account, + shared: () => [enabled, value => { enabled = value; events.push(["storage", value]); }], + sync: async (target, value) => { assert.equal(target, container); events.push(["sync", value]); }, + react: { useEffect: effect => effect() }, oneToOneGate: "pairing", + useGates: () => ({ isLoading: gateLoading, checkGate: gate => gate === "pairing" ? pairingGate : remoteGate }), + ipc: async (method, value) => events.push([method, JSON.parse(JSON.stringify(value.params))]), + }); + vm.runInContext(functions.map(node => result.source.slice(node.start, node.end)).join(";"), context); + for (const authMethod of ["apikey", "chatgpt", "copilot"]) { + enabled = true; + events.length = 0; + account = { authMethod, authLoading: true }; + context.remoteSync(); context.gateBridge(); + assert.deepEqual(events, [], "认证加载期间不能同步或清理存储"); + account.authLoading = false; + context.remoteSync(); context.gateBridge(); + await Promise.resolve(); + const chatgpt = authMethod === "chatgpt"; + assert.deepEqual(events, [ + ...chatgpt ? [] : [["storage", false]], ["sync", chatgpt], + ["set-remote-control-connections-enabled", { enabled: chatgpt, oneToOnePairingInAppEnabled: chatgpt }], + ]); + } + events.length = 0; + account = { authMethod: "chatgpt", authLoading: false }; + remoteGate = false; pairingGate = false; + context.gateBridge(); + assert.deepEqual(events.at(-1), ["set-remote-control-connections-enabled", { + enabled: false, oneToOnePairingInAppEnabled: false, + }], "ChatGPT 仍遵循官方 gate,不能被强制开启"); + events.length = 0; + gateLoading = true; + context.gateBridge(); + assert.deepEqual(events, [], "gate 加载期间不提前发送状态"); +}); + test("26.1016 真实 Bundle 的 Remote Control 认证切换行为", { skip: !process.env.CODEX_REBUILD_1016_BUNDLE }, async () => { const fs = require("node:fs"); const vm = require("node:vm"); @@ -94,3 +153,52 @@ test("26.1016 真实 Bundle 的 Remote Control 认证切换行为", { skip: !pro ]); } }); + +test("26.1021 真实 catalog 与 native Remote Control 认证切换", { skip: !process.env.CODEX_REBUILD_1021_BUNDLE }, async () => { + const fs = require("node:fs"), path = require("node:path"), vm = require("node:vm"); + const { parse } = require("acorn"); + let file = process.env.CODEX_REBUILD_1021_BUNDLE; + if (fs.statSync(file).isDirectory()) { + const names = fs.readdirSync(file).filter(name => /^app-runtime-.*\.js$/.test(name)); + assert.equal(names.length, 1); file = path.join(file, names[0]); + } + const source = fs.readFileSync(file, "utf8"); + const options = { resolveModule: name => fs.readFileSync(path.join(path.dirname(file), name), "utf8") }; + const result = patchSource(source, options); + assert.equal(result.status, "patched", result.reason); + assert.equal(patchSource(result.source).status, "already-patched"); + assert.equal(patchSource(source).status, "unexpected-shape", "缺少依赖必须拒绝认证推断"); + assert.match(result.source, /CodexRebuildRemoteControlCatalog/); + assert.match(result.source, /function TU\(\).*__codexRemoteAuthInit\(\),/); + assert.match(result.source, /function jU\(\).*__codexRemoteAuthInit\(\),/); + assert.doesNotMatch(result.source, /__codexSetRemoteEnabled/); + assert.equal(patchSource(result.source.replace("WE(t,!1)", "WE(t,!0)")).status, + "unexpected-shape", "已有 catalog 标记不能掩盖非 ChatGPT enable 污染"); + const functions = parse(result.source, { ecmaVersion: "latest", sourceType: "module" }).body + .filter(node => node.type === "FunctionDeclaration" && ["SU", "DU"].includes(node.id.name)); + assert.equal(functions.length, 2); + const events = [], container = {}, catalogAtom = {}, accountAtom = {}; + let account, enabled = true, nativeAvailable = true; + const context = vm.createContext({ K: () => container, f: {}, Uc: catalogAtom, Jd: accountAtom, + H: atom => atom === catalogAtom ? enabled : account, + WE: async (target, value) => { assert.equal(target, container); events.push(["sync", value]); }, + wU: { useEffect: effect => effect() }, kU: { useEffect: effect => effect() }, + xa: () => ({ checkGate: () => true, isLoading: false }), al: "pairing", + I: { get remoteConnections() { return nativeAvailable ? { setRemoteControlEnabled: async params => + events.push(["native", JSON.parse(JSON.stringify(params))]) } : null; } }, + }); + vm.runInContext(functions.map(node => result.source.slice(node.start, node.end)).join(";"), context); + for (const authMethod of ["apikey", "chatgpt", "copilot"]) { + events.length = 0; account = { authMethod, authLoading: true }; + context.SU(); context.DU(); assert.deepEqual(events, []); + account.authLoading = false; context.SU(); context.DU(); await Promise.resolve(); + const chatgpt = authMethod === "chatgpt"; + assert.deepEqual(events, [["sync", chatgpt], ["native", { + enabled: chatgpt, oneToOnePairingInAppEnabled: chatgpt, + }]]); + } + nativeAvailable = false; events.length = 0; context.DU(); assert.deepEqual(events, []); + enabled = false; events.length = 0; context.SU(); assert.deepEqual(events, [["sync", false]]); + const changed = { resolveModule: name => options.resolveModule(name).replace("?.localRemoteControlEnabled", "?.unexpectedEnabled") }; + assert.equal(patchSource(source, changed).status, "unexpected-shape", "catalog selector 漂移必须拒绝"); +}); diff --git a/scripts/patch-sidebar-usage.js b/scripts/patch-sidebar-usage.js index 30196df2..a03b7659 100644 --- a/scripts/patch-sidebar-usage.js +++ b/scripts/patch-sidebar-usage.js @@ -15,7 +15,22 @@ const props = node => Object.fromEntries((node?.properties ?? []) .filter(property => property.type === "Property" && !property.computed) .map(property => [key(property.key), property.value])); -function analyze(source, ast) { +function isSidebarSignature(source) { + const markers = ["codex.profileFooter.settingsFallback", "codex.profileFooter.loadingProfile", "sidebarFooter", "hideUsage"]; + if (!markers.every(marker => source.includes(marker))) return false; + const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + return ast.body.some(node => node.type === "FunctionDeclaration" && markers.every(marker => + source.slice(node.start, node.end).includes(marker))); +} + +function findSidebarTarget(directory) { + const candidates = fs.readdirSync(directory).filter(name => name.endsWith(".js")) + .map(name => ({ name, path: path.join(directory, name), source: fs.readFileSync(path.join(directory, name), "utf8") })) + .filter(file => isSidebarSignature(file.source)); + return unique(candidates, "原生头像侧栏资源"); +} + +function analyze(source, ast, relatedSources = []) { const footer = unique(ast.body.filter(node => node.type === "FunctionDeclaration" && contains(source, node, "codex.profileFooter.settingsFallback") && contains(source, node, "codex.profileFooter.loadingProfile")), "原生头像侧栏组件"); @@ -53,20 +68,58 @@ function analyze(source, ast) { if (jsx?.type !== "MemberExpression" || jsx.object.type !== "Identifier" || key(jsx.property) !== "jsx") { throw new Error("原生侧栏 JSX 结构未知"); } - const usageFetch = unique(ast.body.filter(node => node.type === "FunctionDeclaration" && - nodes(node, child => literal(child) === "/wham/usage").length > 0), "官方额度请求"); - const usageAtom = unique(nodes(ast, node => node.type === "AssignmentExpression" && - node.operator === "=" && node.left.type === "Identifier" && node.right.type === "CallExpression" && - node.right.arguments.some(argument => { - if (argument.type !== "ArrowFunctionExpression") return false; - const returned = argument.body.type === "BlockStatement" ? argument.body.body.at(-1) : null; - const options = props(returned?.type === "ReturnStatement" ? returned.argument : argument.body); - return options.refetchInterval && options.queryFn && nodes(options.queryFn, call => - call.type === "CallExpression" && call.callee.type === "Identifier" && - call.callee.name === usageFetch.id.name).length > 0; - })), "共享额度查询"); - const initialize = unique(ast.body.filter(node => node.type === "FunctionDeclaration" && - node.start < usageAtom.start && node.end > usageAtom.end), "额度查询初始化器"); + let usageAtom, initialize; + const usageFetch = ast.body.filter(node => node.type === "FunctionDeclaration" && + nodes(node, child => literal(child) === "/wham/usage").length > 0); + if (usageFetch.length) { + const fetch = unique(usageFetch, "官方额度请求"); + usageAtom = unique(nodes(ast, node => node.type === "AssignmentExpression" && + node.operator === "=" && node.left.type === "Identifier" && node.right.type === "CallExpression" && + node.right.arguments.some(argument => { + if (argument.type !== "ArrowFunctionExpression") return false; + const returned = argument.body.type === "BlockStatement" ? argument.body.body.at(-1) : null; + const options = props(returned?.type === "ReturnStatement" ? returned.argument : argument.body); + return options.refetchInterval && options.queryFn && nodes(options.queryFn, call => + call.type === "CallExpression" && call.callee.type === "Identifier" && + call.callee.name === fetch.id.name).length > 0; + })), "共享额度查询"); + initialize = unique(ast.body.filter(node => node.type === "FunctionDeclaration" && + node.start < usageAtom.start && node.end > usageAtom.end), "额度查询初始化器"); + } else { + const linked = relatedSources.map(related => { + const relatedAst = parse(related.source, { ecmaVersion: "latest", sourceType: "module" }); + const fetch = unique(relatedAst.body.filter(node => node.type === "FunctionDeclaration" && + nodes(node, child => literal(child) === "/wham/usage").length > 0), "共享官方额度请求"); + const assignments = nodes(relatedAst, node => node.type === "AssignmentExpression" && + node.operator === "=" && node.left.type === "Identifier" && node.right.type === "CallExpression" && + node.right.arguments.some(argument => { + if (argument.type !== "ArrowFunctionExpression") return false; + const returned = argument.body.type === "BlockStatement" ? argument.body.body.at(-1) : null; + const options = props(returned?.type === "ReturnStatement" ? returned.argument : argument.body); + return options.refetchInterval && options.queryFn && nodes(options.queryFn, call => + call.type === "CallExpression" && call.callee.type === "Identifier" && + call.callee.name === fetch.id.name).length > 0; + })); + const atom = unique(assignments, "共享账户额度 Atom"); + const initializer = unique(relatedAst.body.filter(node => node.type === "FunctionDeclaration" && + node.start < atom.start && node.end > atom.end), "共享账户额度初始化器"); + const exported = name => unique(relatedAst.body.flatMap(node => node.type === "ExportNamedDeclaration" + ? (node.specifiers ?? []).filter(specifier => specifier.local.name === name).map(specifier => specifier.exported.name) : []), + `额度导出 ${name}`); + const atomExport = exported(atom.left.name), initExport = exported(initializer.id.name); + const filename = path.basename(related.name); + const importDeclaration = unique(ast.body.filter(node => node.type === "ImportDeclaration" && + path.basename(node.source.value) === filename && + node.specifiers.some(specifier => specifier.imported?.name === atomExport) && + node.specifiers.some(specifier => specifier.imported?.name === initExport)), "账户额度导入链"); + const importedLocal = name => unique(importDeclaration.specifiers.filter(specifier => + specifier.imported?.name === name).map(specifier => specifier.local.name), `账户额度本地绑定 ${name}`); + return { atom: importedLocal(atomExport), initialize: importedLocal(initExport) }; + }); + const binding = unique(linked, "共享账户额度来源"); + usageAtom = { left: { name: binding.atom } }; + initialize = { id: { name: binding.initialize } }; + } const avatar = unique(nodes(footer, node => node.type === "CallExpression" && node.arguments[1]?.type === "ObjectExpression" && ["colorKey", "name", "size", "src", "fallback", "loadingFallback"].every(name => props(node.arguments[1])[name])), "原生头像"); @@ -84,7 +137,7 @@ function analyze(source, ast) { usageAtom: usageAtom.left.name, initialize: initialize.id.name }; } -function patchSource(source) { +function patchSource(source, { relatedSources = [] } = {}) { if (!source.includes("codex.profileFooter.settingsFallback")) return { status: "not-applicable", source }; try { const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); @@ -99,7 +152,7 @@ function patchSource(source) { if ([COMPONENT, ACCOUNT_COMPONENT, RENDER, MODULE].some(value => source.includes(value))) { throw new Error("侧栏额度注入名称已占用"); } - const shape = analyze(source, ast); + const shape = analyze(source, ast, relatedSources); const call = `(0,${shape.jsx}.jsx)(${COMPONENT},{fallback:${shape.avatarSlot.init.name},compact:${shape.compact},hidden:${shape.hidden}})`; const bridges = `\n${MARKER}\nfunction ${COMPONENT}(props){const auth=${shape.authHook}();return props.hidden||auth.authMethod!==\`chatgpt\`?props.fallback:(0,${shape.jsx}.jsx)(${ACCOUNT_COMPONENT},props);}\n` + `function ${ACCOUNT_COMPONENT}(props){${shape.initialize}();const auth=${shape.authHook}(),usage=${shape.readHook}(${shape.usageAtom}),intl=${shape.intlHook}();return ${RENDER}({...props,auth,usage:usage.data,intl,jsx:${shape.jsx}});}\n`; @@ -119,8 +172,14 @@ function main() { for (const name of platform ? [platform] : ["win", "mac-arm64", "mac-x64"]) { const directory = path.join(SRC_DIR, name, "_asar", "webview", "assets"); if (!platform && !fs.existsSync(directory)) continue; - const file = unique(fs.readdirSync(directory).filter(file => /^app-initial-.*\.js$/.test(file)), "侧栏资源"); - const target = path.join(directory, file), result = patchSource(fs.readFileSync(target, "utf8")); + const targetFile = findSidebarTarget(directory); + const target = targetFile.path; + let relatedSources = []; + if (!targetFile.source.includes("/wham/usage")) { + const initial = unique(fs.readdirSync(directory).filter(file => /^app-initial-.*\.js$/.test(file)), "官方账户额度资源"); + relatedSources = [{ name: initial, source: fs.readFileSync(path.join(directory, initial), "utf8") }]; + } + const result = patchSource(targetFile.source, { relatedSources }); if (!["patched", "already-patched"].includes(result.status)) throw new Error(result.reason ?? result.status); if (!check) { if (result.status === "patched") fs.writeFileSync(target, result.source, "utf8"); @@ -132,4 +191,4 @@ function main() { if (!count) throw new Error("缺少侧栏额度目标资源"); } if (require.main === module) main(); -module.exports = { MODULE, MARKER, COMPONENT, ACCOUNT_COMPONENT, RENDER, patchSource }; +module.exports = { MODULE, MARKER, COMPONENT, ACCOUNT_COMPONENT, RENDER, findSidebarTarget, isSidebarSignature, patchSource }; diff --git a/scripts/patch-thread-file-manager-action.js b/scripts/patch-thread-file-manager-action.js index f9cb19da..814bc4d0 100644 --- a/scripts/patch-thread-file-manager-action.js +++ b/scripts/patch-thread-file-manager-action.js @@ -17,6 +17,7 @@ * node scripts/patch-thread-file-manager-action.js --check */ const fs = require("fs"); +const path = require("path"); const acorn = require("acorn"); const { locateBundles, relPath } = require("./patch-util"); @@ -284,13 +285,16 @@ function restoreLegacyMenu(ast, source) { source.slice(returnNode.end); } -function findSidebarPatchContexts(ast, source) { +function findSidebarPatchContexts(ast, source, relatedSources = []) { const selectorGitGates = new Map(); const contexts = []; const remoteControlAtoms = new Set(); + const remoteControlExports = new Map(); // 26.1016 将远程连接读取封装成派生 atom,确认读取 .remoteControl 的真实定义。 - walk(ast, (node) => { + const collectRemoteControlAtoms = (moduleAst) => { + const atoms = new Set(); + walk(moduleAst, (node) => { const name = node.type === "AssignmentExpression" && node.left?.type === "Identifier" ? node.left.name : node.type === "VariableDeclarator" && node.id?.type === "Identifier" ? node.id.name : null; @@ -302,7 +306,35 @@ function findSidebarPatchContexts(ast, source) { if (get != null && memberName(body) === "remoteControl" && body.object?.type === "CallExpression" && body.object.callee?.name === get && body.object.arguments.length === 1 && body.object.arguments[0].type === "Identifier") { - remoteControlAtoms.add(name); + atoms.add(name); + } + }); + return atoms; + }; + for (const atom of collectRemoteControlAtoms(ast)) remoteControlAtoms.add(atom); + + // app-primary 可能从 app-initial 导入 remoteControl 派生 atom;只按实际 ESM 导出/导入链解析。 + for (const related of relatedSources) { + if (!related?.source || !related.path) continue; + let relatedAst; + try { relatedAst = parse(related.source); } + catch { continue; } + const atoms = collectRemoteControlAtoms(relatedAst); + const exported = new Set(); + for (const statement of relatedAst.body) { + if (statement.type !== "ExportNamedDeclaration" || statement.source != null) continue; + for (const specifier of statement.specifiers) { + if (atoms.has(specifier.local?.name)) exported.add(specifier.exported?.name); + } + } + if (exported.size > 0) remoteControlExports.set(path.basename(related.path), exported); + } + walk(ast, (node) => { + if (node.type !== "ImportDeclaration") return; + const exported = remoteControlExports.get(path.basename(node.source.value)); + if (!exported) return; + for (const specifier of node.specifiers) { + if (exported.has(specifier.imported?.name)) remoteControlAtoms.add(specifier.local.name); } }); @@ -608,7 +640,7 @@ function patchSource(source) { return { status: "patched", source: next }; } -function patchSidebarSource(source) { +function patchSidebarSource(source, relatedSources = []) { if (source.includes(SIDEBAR_MARKER)) { return { status: "already-patched", source }; } @@ -623,7 +655,7 @@ function patchSidebarSource(source) { return { status: "parse-failed", phase: "before", error, source }; } - const contexts = findSidebarPatchContexts(ast, source); + const contexts = findSidebarPatchContexts(ast, source, relatedSources); if (contexts.length !== 1) { return { status: "unexpected-sidebar-menu-gate-count", @@ -701,7 +733,14 @@ function findTargets(platform) { source: fs.readFileSync(target.path, "utf-8"), })); - return selectTargets([...appInitialTargets, ...appPrimaryTargets]); + const bundles = [...appInitialTargets, ...appPrimaryTargets]; + const targets = selectTargets(bundles); + return targets.map((target) => ({ + ...target, + relatedSources: bundles.filter((bundle) => + bundle.platform === target.platform && bundle.path !== target.path, + ), + })); } function main() { @@ -735,7 +774,7 @@ function main() { const source = fs.readFileSync(target.path, "utf-8"); const result = target.patchKind === "sidebar" - ? patchSidebarSource(source) + ? patchSidebarSource(source, target.relatedSources) : patchSource(source); if (result.status === "native") { diff --git a/scripts/patch-thread-file-manager-action.test.js b/scripts/patch-thread-file-manager-action.test.js index 5da17a09..421a7413 100644 --- a/scripts/patch-thread-file-manager-action.test.js +++ b/scripts/patch-thread-file-manager-action.test.js @@ -108,6 +108,83 @@ test("26.1016 真实 Bundle:普通目录入口、远程排除和工作区原 assert.equal(errors, 1, "真实系统打开失败仍走原生提示"); }); +test("26.1021 app-primary 通过真实 ESM atom 链保留同 host 排除", { + skip: !process.env.CODEX_PATCH_1021_PRIMARY_BUNDLE || !process.env.CODEX_PATCH_1021_INITIAL_BUNDLE, +}, async () => { + const primaryPath = process.env.CODEX_PATCH_1021_PRIMARY_BUNDLE; + const initialPath = process.env.CODEX_PATCH_1021_INITIAL_BUNDLE; + assert.equal(path.basename(primaryPath), "app-primary-844e405f2b90.js"); + assert.equal(path.basename(initialPath), "app-initial-438d1df57f70.js"); + const primary = fs.readFileSync(primaryPath, "utf8"); + const initial = fs.readFileSync(initialPath, "utf8"); + const openMenu = patchSource(primary); + assert.equal(openMenu.status, "patched"); + const result = patchSidebarSource(openMenu.source, [{ path: initialPath, source: initial }]); + assert.equal(result.status, "patched", `${result.status} (${result.count})`); + + const ast = acorn.parse(result.source, { ecmaVersion: "latest", sourceType: "module" }); + const selector = nodes(ast, node => node.type === "ArrowFunctionExpression" && + result.source.slice(node.start, node.end).includes(SIDEBAR_MARKER) && + node.params[1]?.type === "ObjectPattern" && + node.params[1].properties.some(property => property.key?.name === "get")); + assert.equal(selector.length, 1); + const [gate] = selector; + const getName = gate.params[1].properties.find(property => property.key.name === "get").value.name; + const remoteAtom = nodes(gate, node => node.type === "CallExpression" && node.callee.name === getName && + node.arguments[0]?.type === "Identifier")[0].arguments[0].name; + const select = vm.runInNewContext(`(${result.source.slice(gate.start, gate.end)})`, { [remoteAtom]: "remote-control" }); + for (const [connections, expected] of [[[], true], [[{ hostId: "local" }], false], [[{ hostId: "other" }], true]]) { + assert.equal(select({ conversationId: "thread", hostId: "local" }, { + get: atom => atom === "remote-control" ? connections : true, + }), expected); + } + + const caller = nodes(ast, node => node.type === "LogicalExpression" && + node.right?.type === "CallExpression" && node.right.callee?.property?.name === "push" && + result.source.slice(node.start, node.end).includes("...JYn(")); + assert.equal(caller.length, 1); + const expression = result.source.slice(caller[0].start, caller[0].end); + for (const cwd of [null, "C:/plain-folder"]) { + const context = { y: cwd, e: { get: () => true }, QYn: {}, _: "thread", v: "local", R: [], + uu: value => value, JYn: () => [{ id: "latest-worktree-entry" }] }; + vm.runInNewContext(expression, context); + assert.equal(context.R.length, cwd == null ? 0 : 1); + if (cwd != null) assert.equal(context.R[0].id, "latest-worktree-entry"); + } + const currentRootLookup = nodes(ast, node => node.type === "FunctionDeclaration" && node.id.name === "JYn"); + assert.equal(currentRootLookup.length, 1); + const context = { + navigator: { userAgentData: { platform: "Windows" } }, + Ewe: {}, om: {}, rAe: {}, d9e: {}, ka: {}, ES: {}, FRe: {}, pw: {}, oce: {}, + latestWorkspace: "C:/最新工作树", opened: null, + YYn: input => [{ id: "open-workspace-in", onOpenInTarget: input.onOpenInTarget }], + epe: async () => {}, + }; + context.scope = { + get: atom => atom === context.Ewe ? true : atom === context.rAe + ? { data: { latestWorktree: { workspaceRoot: context.latestWorkspace } } } + : atom === context.FRe ? context.pw : atom === context.oce + ? { mutateAsync: async input => { context.opened = input; return { success: true }; } } + : null, + query: { + getData: atom => atom === context.d9e + ? { targets: [{ target: "fileManager", available: true }], availableTargets: ["fileManager"] } + : undefined, + fetch: async () => ({}), + setData: () => {}, + getOptions: () => ({ queryKey: [] }), + }, + queryClient: { getQueryState: () => ({ status: "success" }) }, + }; + const builderSource = result.source.slice(currentRootLookup[0].start, currentRootLookup[0].end); + vm.runInNewContext(`${builderSource};items=JYn({scope,conversationId:'thread',cwd:'C:/plain-folder',hostId:'local'})`, context); + context.items[1].onOpenInTarget("vscode", "C:/Code.exe"); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(context.opened.cwd, "C:/最新工作树"); + assert.equal(context.opened.target, "vscode"); + assert.equal(context.opened.hostId, "local"); +}); + function createGroupedMenuBundle(options = {}) { const openHelper = options.includeOpenHelper === false ? "" @@ -542,8 +619,12 @@ test("CLI 在实际资源目录执行 check → apply → check,重复目标 fs.mkdirSync(assets, { recursive: true }); const initial = path.join(assets, "app-initial-test.js"); const primary = path.join(assets, "app-primary-test.js"); - const source = createCurrentWorkspaceBundle() + createSelectorSidebarMenuBundle(); - fs.writeFileSync(initial, "const initial=true;"); + const initialSource = "const remoteConnections=derive(store,({get})=>get(config).remoteControl);" + + "export {remoteConnections as remoteConnectionsExport};"; + const source = "import {remoteConnectionsExport as remoteConnections} from './app-initial-test.js';" + + createCurrentWorkspaceBundle() + createSelectorSidebarMenuBundle() + .replace("getState(g,`remote_control_connections`)", "g(remoteConnections)"); + fs.writeFileSync(initial, initialSource); fs.writeFileSync(primary, source); const run = check => spawnSync(process.execPath, [path.join(__dirname, "patch-thread-file-manager-action.js"), "win", ...(check ? ["--check"] : [])], @@ -551,13 +632,27 @@ test("CLI 在实际资源目录执行 check → apply → check,重复目标 const checked = run(true); assert.equal(checked.status, 0, checked.stdout + checked.stderr); assert.equal(fs.readFileSync(primary, "utf8"), source); + fs.writeFileSync(initial, "const remoteConnections=true;"); + const missingExport = run(true); + assert.equal(missingExport.status, 1); + assert.match(missingExport.stdout + missingExport.stderr, /unexpected-sidebar-menu-gate-count/); + assert.equal(fs.readFileSync(primary, "utf8"), source); + fs.writeFileSync(initial, initialSource.replace(".remoteControl", ".otherConfig")); + const unrelatedAtom = run(true); + assert.equal(unrelatedAtom.status, 1); + assert.match(unrelatedAtom.stdout + unrelatedAtom.stderr, /unexpected-sidebar-menu-gate-count/); + assert.equal(fs.readFileSync(primary, "utf8"), source); + fs.writeFileSync(initial, initialSource); const applied = run(false); assert.equal(applied.status, 0, applied.stdout + applied.stderr); const patched = fs.readFileSync(primary, "utf8"); assert.ok(patched.includes(MARKER) && patched.includes(SIDEBAR_MARKER)); assert.equal(run(true).status, 0); assert.equal(fs.readFileSync(primary, "utf8"), patched); - const menu = evaluatePatchedMenu(patched, "Windows"); + const menu = evaluatePatchedMenu(patched.replace( + "import {remoteConnectionsExport as remoteConnections} from './app-initial-test.js';", + "", + ), "Windows"); return menu.result[0].onSelect().then(() => { assert.equal(menu.opened.target, "fileManager"); fs.writeFileSync(initial, source); diff --git a/scripts/sidebar-usage-smoke.js b/scripts/sidebar-usage-smoke.js index ff47ca49..b124ce85 100644 --- a/scripts/sidebar-usage-smoke.js +++ b/scripts/sidebar-usage-smoke.js @@ -7,7 +7,7 @@ const vm = require("node:vm"); const { pathToFileURL } = require("node:url"); const { parse } = require("acorn"); const { nodes, unique } = require("./patch-ast-util"); -const { MODULE, MARKER, COMPONENT, ACCOUNT_COMPONENT, RENDER, patchSource } = require("./patch-sidebar-usage"); +const { MODULE, MARKER, COMPONENT, ACCOUNT_COMPONENT, RENDER, findSidebarTarget, isSidebarSignature, patchSource } = require("./patch-sidebar-usage"); const fixture = `let usageAtom; async function fetchUsage(){return http("/wham/usage")} @@ -27,22 +27,47 @@ function Profile(input){ async function main() { const args = process.argv.slice(2); - let source = fixture, rendererPath = path.join(__dirname, "runtime/sidebar-usage.mjs"), origin = "内置功能样本"; + let source = fixture, relatedSources = [], rendererPath = path.join(__dirname, "runtime/sidebar-usage.mjs"), origin = "内置功能样本"; let rendererUrl = pathToFileURL(rendererPath).href; - if (args[0] === "--asar" && args.length === 2) { + if (args[0] === "--assets" && args.length === 2) { + const assets = path.resolve(args[1]); + const target = findSidebarTarget(assets); + source = target.source; + if (!source.includes("/wham/usage")) { + const initial = unique(fs.readdirSync(assets).filter(name => /^app-initial-[^/\\]+\.js$/.test(name)), "共享账户额度 Bundle"); + relatedSources = [{ name: initial, source: fs.readFileSync(path.join(assets, initial), "utf8") }]; + } + origin = `${assets}:${target.name}`; + } else if (args[0] === "--asar" && args.length === 2) { const asar = await import("@electron/asar"); const files = asar.listPackage(args[1]); - const entry = unique(files.filter(name => /app-initial-[^/\\]+\.js$/.test(name)), "真实侧栏 Bundle"); - source = asar.extractFile(args[1], entry.replace(/^[/\\]/, "")).toString(); - origin = `${args[1]}:${entry}`; + const candidates = files.filter(name => /app-(?:primary|initial)-[^/\\]+\.js$/.test(name)); + const matches = candidates.map(name => ({ name, source: asar.extractFile(args[1], name.replace(/^[/\\]/, "")).toString() })) + .filter(file => isSidebarSignature(file.source)); + const entry = unique(matches, "真实侧栏 Bundle"); + source = entry.source; + if (!source.includes("/wham/usage")) { + const initial = unique(files.filter(name => /app-initial-[^/\\]+\.js$/.test(name)), "共享账户额度 Bundle"); + relatedSources = [{ name: path.basename(initial), source: asar.extractFile(args[1], initial.replace(/^[/\\]/, "")).toString() }]; + } + origin = `${args[1]}:${entry.name}`; if (source.includes(MARKER)) { - const embedded = asar.extractFile(args[1], path.join(path.dirname(entry), MODULE).replace(/^[/\\]/, "")).toString(); + const embedded = asar.extractFile(args[1], path.join(path.dirname(entry.name), MODULE).replace(/^[/\\]/, "")).toString(); // Git 在 Windows 构建机可能检出 CRLF;校验源码内容后直接执行成品模块。 assert.equal(embedded.replace(/\r\n/g, "\n"), fs.readFileSync(rendererPath, "utf8").replace(/\r\n/g, "\n"), "候选渲染模块与当前源码不一致"); rendererUrl = `data:text/javascript;base64,${Buffer.from(embedded).toString("base64")}`; } - } else assert.equal(args.length, 0, "用法:node scripts/sidebar-usage-smoke.js [--asar PATH]"); - const result = patchSource(source); + } else assert.equal(args.length, 0, "用法:node scripts/sidebar-usage-smoke.js [--assets PATH | --asar PATH]"); + if (relatedSources.length && !source.includes(MARKER)) { + const sourceAst = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const linkedImport = unique(sourceAst.body.filter(node => node.type === "ImportDeclaration" && + path.basename(node.source.value) === path.basename(relatedSources[0].name)), "测试账户额度导入链"); + const broken = source.slice(0, linkedImport.source.start) + JSON.stringify("./missing-account-usage.js") + source.slice(linkedImport.source.end); + const rejected = patchSource(broken, { relatedSources }); + assert.equal(rejected.status, "unexpected-shape"); + assert.match(rejected.reason, /账户额度导入链/); + } + const result = patchSource(source, { relatedSources }); assert.ok(["patched", "already-patched"].includes(result.status), result.reason); assert.equal(patchSource(result.source).source, result.source, "重复应用必须幂等"); const ast = parse(result.source, { ecmaVersion: "latest", sourceType: "module" }); diff --git a/scripts/windows-maintenance.js b/scripts/windows-maintenance.js index 5bc951f8..aaa940c7 100644 --- a/scripts/windows-maintenance.js +++ b/scripts/windows-maintenance.js @@ -135,27 +135,35 @@ function saveCompatibilityEvidence( const signatures = ["shouldIncludeUpdater", "shouldIncludeWindowsUpdater", "shouldIncludeWindowsMsixUpdater", "FlyoutSubmenuItem", "flyoutHeader", "data-model-picker-model-row", "data-model-picker-view", "modelListConfig", "serviceTierAccess", "Failed to read service tier for request"]; + const functionalSignatures = ["mcpServer/startupStatus/updated", "mention-discovery", + "Failed to sync local remote control enablement", "set-remote-control-connections-enabled", + "remote-connections/gate-bridge", "isConfigDataPending", "codex.profileFooter.settingsFallback", + "chatgptAccentPicker.ChatGptAccentPicker.updateError", "--color-image-generation-accent"]; const files = []; for (const [label, directory] of [["main", ".vite/build"], ["webview", "webview/assets"]]) { const sourceDirectory = path.join(asarRoot, directory); for (const name of fs.readdirSync(sourceDirectory).filter((name) => /\.(?:js|css)$/.test(name))) { const file = path.join(sourceDirectory, name); const text = fs.readFileSync(file, "utf8"); - const matches = [...signatures, "settings.appearance.visualStyle", "--thread-content-expanded-max-width", "--markdown-wide-block-max-width"] + const matches = [...signatures, ...functionalSignatures, "settings.appearance.visualStyle", "--thread-content-expanded-max-width", "--markdown-wide-block-max-width"] .filter((signature) => text.includes(signature)); const startupEvidence = label === "main" && /^(?:early-bootstrap|startup-requirements|application-network-startup)/.test(name); - if (!matches.length && !startupEvidence) continue; + // 新版会在三个入口 chunk 之间移动实现;诊断必须包含共享定义与实际功能块。 + const frontendEvidence = label === "webview" && + (/^app-(?:initial|primary|shared)-.*\.js$/.test(name) || + name.endsWith(".js") && matches.some(match => functionalSignatures.includes(match))); + if (!matches.length && !startupEvidence && !frontendEvidence) continue; const copied = label === "main" ? require("./patch-updater").auditUpdaterSource(text).length > 0 : matches.includes("flyoutHeader") || matches.includes("data-model-picker-model-row") || matches.includes("data-model-picker-view") && matches.includes("modelListConfig"); const serviceTierEvidence = matches.includes("serviceTierAccess") && matches.includes("Failed to read service tier for request"); const readingEvidence = matches.includes("settings.appearance.visualStyle") || name.endsWith(".css") && matches.some(match => match.startsWith("--")); - if (copied || serviceTierEvidence || readingEvidence || startupEvidence) { + if (copied || serviceTierEvidence || readingEvidence || startupEvidence || frontendEvidence) { fs.mkdirSync(path.join(destination, label), { recursive: true }); fs.copyFileSync(file, path.join(destination, label, name)); } - files.push({ directory, name, matches, copied: copied || serviceTierEvidence || readingEvidence || startupEvidence, sha256: crypto.createHash("sha256").update(text).digest("hex") }); + files.push({ directory, name, matches, copied: copied || serviceTierEvidence || readingEvidence || startupEvidence || frontendEvidence, sha256: crypto.createHash("sha256").update(text).digest("hex") }); } } From e2ade169989e9da78c6f69d256ae447907732141 Mon Sep 17 00:00:00 2001 From: carptopus Date: Wed, 28 Oct 2026 11:13:19 +0800 Subject: [PATCH 45/51] Persist rebuild appearance settings outside browser storage --- README.md | 1 + package.json | 1 + scripts/check-scripts.js | 2 + scripts/frontend-source-smoke.js | 14 ++- scripts/maintenance-smoke.js | 13 ++ scripts/patch-accent-presets.test.js | 77 ++++++------ scripts/patch-policy.js | 1 + scripts/patch-rebuild-settings.js | 114 +++++++++++++++++ scripts/reading-layout-smoke.js | 26 ++-- scripts/reading-width.test.js | 28 +++-- scripts/runtime/accent-presets.mjs | 30 ++--- scripts/runtime/reading-width.mjs | 29 ++--- scripts/runtime/rebuild-settings.cjs | 98 +++++++++++++++ scripts/runtime/rebuild-settings.mjs | 55 +++++++++ scripts/settings-persistence-smoke.js | 170 ++++++++++++++++++++++++++ scripts/windows-maintenance.js | 10 +- 16 files changed, 576 insertions(+), 93 deletions(-) create mode 100644 scripts/patch-rebuild-settings.js create mode 100644 scripts/runtime/rebuild-settings.cjs create mode 100644 scripts/runtime/rebuild-settings.mjs create mode 100644 scripts/settings-persistence-smoke.js diff --git a/README.md b/README.md index 8c637ad5..231dc76c 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ pnpm run build:all - `patch-hide-invite-menu.js` 隐藏账户菜单中的“邀请好友 / 邀请同事”入口。 - `patch-sidebar-usage.js` 在 ChatGPT 登录时以剩余额度圆环和百分比替换侧栏头像,复用官方额度查询和刷新机制,点击仍打开原账户菜单。 - `patch-reading-layout.js` 在外观主题卡片中加入 50%–100%、步进 5% 的正文宽度滑杆,并同步代码块、表格和输入区宽度,扩宽适用对话框;百分比不低于官方宽度,Markdown 粗体颜色可跟随正文、强调色或使用自定义颜色。 +- `patch-rebuild-settings.js` 将正文宽度、Markdown 粗体颜色和本地强调色预设保存到 `CODEX_HOME/codex-rebuild-settings.json`,独立于程序目录与浏览器 User Data;通过限定的可信 IPC 读取和保存,不读取或迁移旧 localStorage。官方账户主题仍由官方管理。 - `patch-test-isolation.js` 在官方设置 User Data 后、获取单实例锁前挂载 Windows 验收隔离,分别约束 `CODEX_HOME`、User Data 和 sessionData,并记录实际启动路径证据。 - `patch-model-picker-submenu.js` 增加对新版原生 simple / advanced 内联模型列表的结构核验;官方实现完整时保持原样,旧结构继续适配,未知结构明确失败。 - `patch-thread-file-manager-action.js` 将系统文件管理器入口提升到会话菜单顶层,复用官方工作区打开回调,保留最新工作树解析及失败提示,不覆盖默认编辑器偏好;按菜单内容识别所在 Bundle,支持新版菜单迁移。 diff --git a/package.json b/package.json index a3f67b55..bd26f479 100644 --- a/package.json +++ b/package.json @@ -29,6 +29,7 @@ "check": "node scripts/check-scripts.js", "test:maintenance": "node scripts/maintenance-smoke.js", "test:sidebar-usage": "node scripts/sidebar-usage-smoke.js", + "test:settings-persistence": "node scripts/settings-persistence-smoke.js", "windows:check-update": "node scripts/windows-maintenance.js discover", "windows:candidate": "node scripts/windows-maintenance.js candidate", "windows:verify-release": "node scripts/windows-maintenance.js verify-release", diff --git a/scripts/check-scripts.js b/scripts/check-scripts.js index 699470bf..61df480c 100644 --- a/scripts/check-scripts.js +++ b/scripts/check-scripts.js @@ -10,6 +10,8 @@ files.push("runtime/rebuild-test-environment.cjs"); files.push("runtime/reading-width.mjs"); files.push("runtime/accent-presets.mjs"); files.push("runtime/sidebar-usage.mjs"); +files.push("runtime/rebuild-settings.cjs"); +files.push("runtime/rebuild-settings.mjs"); for (const file of files) execFileSync(process.execPath, ["--check", path.join(__dirname, file)], { stdio: "inherit" }); JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")); console.log(`脚本语法检查通过:${files.length} 个文件`); diff --git a/scripts/frontend-source-smoke.js b/scripts/frontend-source-smoke.js index a2816c27..030c432c 100644 --- a/scripts/frontend-source-smoke.js +++ b/scripts/frontend-source-smoke.js @@ -156,7 +156,10 @@ function verifyFrontendSource(assets) { assert.match(serviceTierSource, /CodexRebuildServiceTierApiKeyAccess/); assert.match(serviceTierSource, /\{fast:!0,ultrafast:!0\}\/\* CodexRebuildServiceTierApiKeyRequest \*\//); const accentModule = fs.readFileSync(path.join(assets, "codex-rebuild-accent-presets.js"), "utf8"); - assert.match(accentModule, /codex-rebuild:accent-preset:v1/); + assert.match(accentModule, /ACCENT_PRESET_STORAGE_KEY = "accentPreset"/); + assert.match(accentModule, /readSettings/); + assert.match(accentModule, /writeSettings/); + assert.doesNotMatch(accentModule, /localStorage/); assert.match(accentModule, /export function resolveAccentPreset/); assert.match(accentModule, /preset == null \|\| preset === "default" \? "blue" : preset/); assert.match(accentModule, /CUSTOM_ACCENT_PRESET = "custom"/); @@ -166,7 +169,14 @@ function verifyFrontendSource(assets) { assert.match(readingModule, /MAX_WIDTH_PERCENT = 100/); assert.match(readingModule, /WIDTH_STEP = 5/); assert.match(readingModule, /type: "range"/); - assert.match(readingModule, /codex-rebuild:markdown-bold-color-mode:v1/); + assert.match(readingModule, /markdownBoldColorMode/); + assert.match(readingModule, /\.\/rebuild-settings\.mjs/); + assert.doesNotMatch(readingModule, /localStorage/); + const settingsClient = fs.readFileSync(path.join(assets, "rebuild-settings.mjs"), "utf8"); + assert.match(settingsClient, /electronBridge\?\.rebuildSettings/); + assert.match(settingsClient, /bridge\.read\(\)/); + assert.match(settingsClient, /bridge\.write\(patch\)/); + assert.doesNotMatch(settingsClient, /localStorage/); assert.match(readingModule, /--app-color-text-accent/); assert.doesNotMatch(readingModule, /--color-token-charts-green|--green-500|#00a240/); assert.doesNotMatch(readingModule, /设置无效|请重新选择/); diff --git a/scripts/maintenance-smoke.js b/scripts/maintenance-smoke.js index eccbe8c5..395dead3 100644 --- a/scripts/maintenance-smoke.js +++ b/scripts/maintenance-smoke.js @@ -123,6 +123,13 @@ try { ["remote-control-fixture.js", "const event='set-remote-control-connections-enabled';"], ["app-theme-fixture.js", "const theme={'--color-image-generation-accent':'blue'};"], ]; + const settingsBridgeEvidence = [ + ["main-settings-fixture.js", "const options={isTrustedIpcEvent:trust,getContextForWebContents:getContext};"], + ["preload.js", "contextBridge.exposeInMainWorld('electronBridge',{});"], + ]; + for (const [name, source] of settingsBridgeEvidence) { + write(path.join(evidenceAsar, ".vite", "build", name), source); + } for (const [name, source] of frontendEvidence) { write(path.join(evidenceAsar, "webview", "assets", name), source); } @@ -146,6 +153,12 @@ try { } saveCompatibilityEvidence(evidenceAsar, { version: "fixture" }, evidenceOutput); const evidenceIndex = JSON.parse(fs.readFileSync(path.join(evidenceOutput, "index.json"), "utf8")); + for (const [name, source] of settingsBridgeEvidence) { + const entry = evidenceIndex.files.find(file => file.name === name); + assert.equal(entry?.copied, true, `缺少外观配置桥取证:${name}`); + assert.equal(fs.readFileSync(path.join(evidenceOutput, "main", name), "utf8"), source); + assert.equal(entry.sha256, hash(source)); + } for (const [name, source] of frontendEvidence) { const entry = evidenceIndex.files.find(file => file.name === name); assert.equal(entry?.copied, true, `缺少新版独立功能块取证:${name}`); diff --git a/scripts/patch-accent-presets.test.js b/scripts/patch-accent-presets.test.js index 1f3e17d2..ecfe64c6 100644 --- a/scripts/patch-accent-presets.test.js +++ b/scripts/patch-accent-presets.test.js @@ -35,22 +35,37 @@ function themeFixture() { 'return a==null?d:{...d,"--color-background-user-message":a.userMessageBackground,"--color-text-user-message":a.userMessageText,"--app-color-background-accent":a.soft}}export{Tba}'; } -function fakeStorage(initial = {}) { - const values = new Map(Object.entries(initial)); - return { - values, - getItem: key => values.get(key) ?? null, - setItem: (key, value) => values.set(key, value), - removeItem: key => values.delete(key), - }; +const defaults = { + readingWidthPercent: 50, + markdownBoldColorMode: "default", + markdownBoldCustomColor: "#7c3aed", + accentPreset: null, +}; +let snapshot = { ...defaults }; +let failWrites = false; +const listeners = new Set(); +function replaceSnapshot(next) { + snapshot = { ...next }; + for (const listener of listeners) listener({ ...snapshot }); } +globalThis.electronBridge = { rebuildSettings: { + read: () => ({ ...snapshot }), + async write(patch) { + if (failWrites) throw new Error("settings unavailable"); + snapshot = { ...snapshot, ...patch }; + for (const listener of listeners) listener({ ...snapshot }); + return { ...snapshot }; + }, + onChange(listener) { listeners.add(listener); return () => listeners.delete(listener); }, +} }; async function runtimeModule() { return import(pathToFileURL(path.join(__dirname, "runtime", "accent-presets.mjs")).href); } test.afterEach(() => { - delete globalThis.localStorage; + failWrites = false; + replaceSnapshot(defaults); }); test("无账户主题时启用本地预设并保留加载态禁用", () => { @@ -155,14 +170,12 @@ test("真实资源路径可核对 26.1021 设置与主题 Bundle", { skip: !proc test("本地设置、账户同步和显式自定义使用同一预设状态", async () => { const runtime = await runtimeModule(); - const storage = fakeStorage(); - globalThis.localStorage = storage; let localCalls = 0; let accountCalls = 0; let customValue = null; await runtime.selectAccentPreset(null, "blue", () => { localCalls++; }, () => { accountCalls++; }); - assert.equal(storage.values.get(runtime.ACCENT_PRESET_STORAGE_KEY), "blue"); + assert.equal(snapshot.accentPreset, "blue"); assert.equal(runtime.accentPresetSelection(null, "custom", "custom"), "blue"); assert.equal(runtime.accentPresetSelection({ chatTheme: "green" }, "custom", "custom"), "blue"); assert.equal(runtime.accentPresetSelection(undefined, "custom", "custom"), "custom"); @@ -172,53 +185,47 @@ test("本地设置、账户同步和显式自定义使用同一预设状态", as assert.equal(accountCalls, 0); await runtime.selectAccentPreset({ chatTheme: "green" }, "green", () => { localCalls++; }, () => { accountCalls++; }); - assert.equal(storage.values.get(runtime.ACCENT_PRESET_STORAGE_KEY), "green"); + assert.equal(snapshot.accentPreset, "green"); assert.equal(accountCalls, 1); - globalThis.localStorage = { - getItem: () => null, - setItem: () => { throw new Error("storage unavailable"); }, - removeItem: () => {}, - }; + failWrites = true; await runtime.selectAccentPreset({ chatTheme: "purple" }, "purple", () => { localCalls++; }, () => { accountCalls++; }); assert.equal(accountCalls, 2); await runtime.selectAccentPreset({ chatTheme: "future" }, "future-preset", () => { localCalls++; }, () => { accountCalls++; }); assert.equal(accountCalls, 3); - assert.equal(storage.values.get(runtime.ACCENT_PRESET_STORAGE_KEY), "green"); + assert.equal(snapshot.accentPreset, "green"); await runtime.selectAccentPreset(null, "future-preset", () => { localCalls++; }, () => { accountCalls++; }); assert.equal(accountCalls, 4); assert.equal(localCalls, 1); - globalThis.localStorage = storage; - storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, "blue"); - runtime.useCustomAccent(value => { customValue = value; }, "#123456"); + failWrites = false; + replaceSnapshot({ ...snapshot, accentPreset: "blue" }); + await runtime.useCustomAccent(value => { customValue = value; }, "#123456"); assert.equal(customValue, "#123456"); - assert.equal(storage.values.get(runtime.ACCENT_PRESET_STORAGE_KEY), "custom"); + assert.equal(snapshot.accentPreset, "custom"); assert.equal(runtime.accentPresetSelection(null, "custom", "custom"), "custom"); assert.equal(runtime.resolveAccentPreset("custom", null), null); }); test("预设解析补齐官方默认有效色并拒绝无效本地值", async () => { const runtime = await runtimeModule(); - const storage = fakeStorage(); - globalThis.localStorage = storage; assert.equal(runtime.accentPresetSelection(null, "custom", "custom"), "default"); assert.equal(runtime.resolveAccentPreset("custom", null), "blue"); - storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, "blue"); + replaceSnapshot({ ...snapshot, accentPreset: "blue" }); assert.equal(runtime.resolveAccentPreset("custom", null), "blue"); assert.equal(runtime.resolveAccentPreset("chatgpt", "green"), "green"); assert.equal(runtime.resolveAccentPreset("custom", "green"), "blue"); for (const preset of ["blue", "black"]) { - storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, preset); + replaceSnapshot({ ...snapshot, accentPreset: preset }); assert.equal(runtime.resolveAccentPreset("custom", null), preset); } - storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, "default"); + replaceSnapshot({ ...snapshot, accentPreset: "default" }); assert.equal(runtime.accentPresetSelection(null, "custom"), "default"); assert.equal(runtime.resolveAccentPreset("custom", null), "blue"); - storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, "not-a-preset"); + replaceSnapshot({ ...snapshot, accentPreset: "not-a-preset" }); assert.equal(runtime.resolveAccentPreset("custom", null), "blue"); }); @@ -226,19 +233,19 @@ test("完整主题链复用官方预设气泡且账户主题优先", async t => const directory = fs.mkdtempSync(path.join(os.tmpdir(), "codex-accent-theme-")); t.after(() => fs.rmSync(directory, { recursive: true, force: true })); fs.copyFileSync(path.join(__dirname, "runtime", "accent-presets.mjs"), path.join(directory, MODULE)); + fs.copyFileSync(path.join(__dirname, "runtime", "rebuild-settings.mjs"), path.join(directory, "rebuild-settings.mjs")); const result = patchThemeSource(themeFixture()); assert.equal(result.status, "patched", result.reason); const bundle = path.join(directory, "theme.mjs"); fs.writeFileSync(bundle, result.source, "utf8"); const theme = await import(`${pathToFileURL(bundle).href}?test=${Date.now()}`); const runtime = await runtimeModule(); - const storage = fakeStorage(); - globalThis.localStorage = storage; + replaceSnapshot({ ...snapshot, accentPreset: null }); const localImplicitDefault = theme.Tba({ accentSource: "custom", accent: "#custom" }, "light", null); assert.equal(localImplicitDefault["--color-background-user-message"], "#blue-bubble"); - storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, "blue"); + replaceSnapshot({ ...snapshot, accentPreset: "blue" }); const localBlue = theme.Tba({ accentSource: "custom", accent: "#custom" }, "light", null); assert.equal(localBlue["--color-background-user-message"], "#blue-bubble"); assert.notEqual(localBlue["--color-background-user-message"], "neutral-bubble"); @@ -249,15 +256,15 @@ test("完整主题链复用官方预设气泡且账户主题优先", async t => assert.equal(localWithAccountData["--color-background-user-message"], "#blue-bubble"); for (const preset of ["blue", "black"]) { - storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, preset); + replaceSnapshot({ ...snapshot, accentPreset: preset }); const rendered = theme.Tba({ accentSource: "custom", accent: "#custom" }, "light", null); assert.equal(rendered["--color-background-user-message"], `#${preset}-bubble`); } - storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, "default"); + replaceSnapshot({ ...snapshot, accentPreset: "default" }); const localDefault = theme.Tba({ accentSource: "custom", accent: "#custom" }, "light", null); assert.equal(localDefault["--color-background-user-message"], "#blue-bubble"); - storage.values.set(runtime.ACCENT_PRESET_STORAGE_KEY, "custom"); + replaceSnapshot({ ...snapshot, accentPreset: "custom" }); const localCustom = theme.Tba({ accentSource: "custom", accent: "#custom" }, "light", null); assert.equal(localCustom["--color-background-user-message"], "neutral-bubble"); }); diff --git a/scripts/patch-policy.js b/scripts/patch-policy.js index da2f743a..a606c061 100644 --- a/scripts/patch-policy.js +++ b/scripts/patch-policy.js @@ -20,6 +20,7 @@ const PATCH_POLICY = [ { script: "patch-codex-home-env.js", feature: "用户配置目录传递" }, { script: "patch-windows-portable-runtime.js", feature: "Windows 便携运行时" }, { script: "patch-test-isolation.js", feature: "Windows 验收数据隔离" }, + { script: "patch-rebuild-settings.js", feature: "独立文件持久化外观偏好" }, { script: "patch-provider-quota.js", feature: "真实 Provider 额度发送门槛" }, { script: "patch-api-key-home-navigation.js", feature: "API-key 首页会话恢复" }, { script: "patch-thread-timeline.js", feature: "按版本能力启用官方会话时间线" }, diff --git a/scripts/patch-rebuild-settings.js b/scripts/patch-rebuild-settings.js new file mode 100644 index 00000000..b9b49640 --- /dev/null +++ b/scripts/patch-rebuild-settings.js @@ -0,0 +1,114 @@ +#!/usr/bin/env node +/** 在官方启动配置/可信 IPC 就绪后挂载独立外观 JSON,并扩展原有 preload 桥。 */ +const fs = require("node:fs"); +const path = require("node:path"); +const { parse } = require("acorn"); +const { SRC_DIR } = require("./patch-util"); +const { CHANNELS } = require("./runtime/rebuild-settings.cjs"); +const MAIN_MARKER = "/* codex-rebuild-settings:main */"; +const PRELOAD_MARKER = "/* codex-rebuild-settings:preload */"; +const MODULE = "codex-rebuild-settings.cjs"; +function walk(node, visit, ancestors = []) { + if (!node || typeof node !== "object") return; + if (node.type) visit(node, ancestors); + const parents = node.type ? [...ancestors, node] : ancestors; + for (const value of Object.values(node)) { + if (Array.isArray(value)) value.forEach(child => walk(child, visit, parents)); + else if (value?.type) walk(value, visit, parents); + } +} +const key = node => node?.name ?? node?.value; +const literal = node => node?.type === "Literal" ? node.value : node?.type === "TemplateLiteral" && !node.expressions.length ? node.quasis[0].value.cooked : undefined; +const ast = source => parse(source, { ecmaVersion: "latest", sourceType: "script" }); +function properties(node) { + return node?.type === "ObjectExpression" ? Object.fromEntries(node.properties.filter(prop => prop.type === "Property").map(prop => [key(prop.key), prop.value])) : {}; +} +function patchMain(source) { + const matches = []; + walk(ast(source), (node, parents) => { + if (node.type !== "CallExpression" || node.callee.type !== "Identifier" || node.arguments.length !== 1) return; + const props = properties(node.arguments[0]); + if (!["buildFlavor", "getContextForWebContents", "isTrustedIpcEvent"].every(name => props[name])) return; + if (props.isTrustedIpcEvent.type !== "Identifier" || props.getContextForWebContents.type !== "MemberExpression") throw new Error("官方可信 IPC 注册参数结构未知"); + const owner = parents.findLast(parent => ["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"].includes(parent.type)); + if (!owner) throw new Error("官方可信 IPC 注册不在真实启动函数内"); + const homes = []; + walk(owner.body, child => { + if (child.type !== "VariableDeclarator" || child.id.type !== "Identifier" || child.init?.type !== "AwaitExpression" || child.init.argument.type !== "CallExpression") return; + const initProps = properties(child.init.argument.arguments[0]); + if (initProps.moduleDir?.type === "Identifier" && initProps.moduleDir.name === "__dirname" && child.end < node.start) homes.push(child.id.name); + }); + if (homes.length !== 1 || !source.slice(owner.start, owner.end).includes(`${homes[0]}.codexHome`)) throw new Error("官方真实启动 codexHome 解析结构未知"); + matches.push({ node, home: homes[0], trusted: props.isTrustedIpcEvent.name }); + }); + if (matches.length !== 1) throw new Error("官方可信 IPC 注册挂载点缺失或不唯一"); + const { node, home, trusted } = matches[0]; + const injection = `,${MAIN_MARKER}require("./${MODULE}").install({codexHome:${home}.codexHome,isTrustedIpcEvent:${trusted}})`; + if (source.includes(MAIN_MARKER)) { + if (source.split(MAIN_MARKER).length !== 2 || !source.slice(node.end).startsWith(injection)) throw new Error("本地外观配置 main 标记位置或契约异常"); + return source; + } + if (source.includes(MODULE)) throw new Error("本地外观配置 main 存在无标记注入"); + const result = source.slice(0, node.end) + injection + source.slice(node.end); + ast(result); return result; +} +function patchPreload(source) { + const tree = ast(source), exposures = [], declarations = []; + walk(tree, node => { + if (node.type === "VariableDeclarator") declarations.push(node); + if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && key(node.callee.property) === "exposeInMainWorld" && literal(node.arguments[0]) === "electronBridge") exposures.push(node); + }); + if (exposures.length !== 1) throw new Error("官方 electronBridge 暴露点缺失或不唯一"); + const exposure = exposures[0], bridge = exposure.arguments[1]; + const electron = exposure.callee.object; + if (bridge?.type !== "Identifier" || electron?.type !== "MemberExpression" || key(electron.property) !== "contextBridge" || electron.object.type !== "Identifier") throw new Error("官方 preload contextBridge 结构未知"); + const symbol = electron.object.name; + const imports = declarations.filter(node => node.id.name === symbol && node.init?.type === "CallExpression" && node.init.callee.name === "require" && literal(node.init.arguments[0]) === "electron"); + const objects = declarations.filter(node => node.id.name === bridge.name && node.init?.type === "ObjectExpression"); + if (imports.length !== 1 || objects.length !== 1) throw new Error("官方 preload Electron 依赖或桥对象缺失"); + const object = objects[0].init, props = properties(object); + if (!["sendMessageFromView", "getSystemThemeVariant", "getSharedObjectSnapshotValue"].every(name => props[name])) throw new Error("官方 preload 桥缺少必要通信契约"); + const ipc = `${symbol}.ipcRenderer`; + const injection = `,${PRELOAD_MARKER}rebuildSettings:{read:()=>${ipc}.sendSync(${JSON.stringify(CHANNELS.read)}),write:patch=>${ipc}.invoke(${JSON.stringify(CHANNELS.write)},patch),onChange:fn=>{if(typeof fn!=="function")throw new TypeError("本地外观配置监听器必须是函数");const listener=(_event,value)=>fn(value);${ipc}.on(${JSON.stringify(CHANNELS.changed)},listener);return()=>${ipc}.removeListener(${JSON.stringify(CHANNELS.changed)},listener)}}`; + if (source.includes(PRELOAD_MARKER)) { + if (source.split(PRELOAD_MARKER).length !== 2 || !source.slice(object.start, object.end).endsWith(injection + "}")) throw new Error("本地外观配置 preload 标记位置或契约异常"); + return source; + } + if (props.rebuildSettings || source.includes(CHANNELS.read)) throw new Error("本地外观配置 preload 存在无标记注入"); + const at = object.end - 1, result = source.slice(0, at) + injection + source.slice(at); + ast(result); return result; +} +function main() { + const platforms = ["mac-arm64", "mac-x64", "win", "unix"], args = process.argv.slice(2); + const selected = args.filter(arg => platforms.includes(arg)); + if (selected.length > 1 || args.some(arg => !platforms.includes(arg) && arg !== "--check")) throw new Error("本地外观配置补丁参数无效"); + let targets = (selected.length ? selected : platforms.filter(platform => fs.existsSync(path.join(SRC_DIR, platform, "_asar")))) + .map(platform => ({ platform, root: path.join(SRC_DIR, platform, "_asar") })); + if (!targets.length && !selected.length && fs.existsSync(path.join(SRC_DIR, "package.json"))) targets = [{ platform: "legacy", root: SRC_DIR }]; + if (!targets.length) throw new Error("本地外观配置补丁缺少平台资源"); + const runtime = path.join(__dirname, "runtime", "rebuild-settings.cjs"), client = path.join(__dirname, "runtime", "rebuild-settings.mjs"); + for (const file of [runtime, client]) if (!fs.statSync(file).isFile()) throw new Error(`本地外观配置依赖缺失:${file}`); + const prepared = targets.map(({ platform, root }) => { + const manifest = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")); + if (typeof manifest.main !== "string" || !manifest.main) throw new Error(`[${platform}] 官方 package.main 缺失`); + const entry = path.resolve(root, manifest.main), relative = path.relative(root, entry); + if (!relative || relative === ".." || relative.startsWith(".." + path.sep) || path.isAbsolute(relative) || !fs.statSync(entry).isFile()) throw new Error(`[${platform}] 官方 package.main 不存在或逃出 ASAR`); + const actualRelative = path.relative(fs.realpathSync(root), fs.realpathSync(entry)); + if (actualRelative === ".." || actualRelative.startsWith(".." + path.sep) || path.isAbsolute(actualRelative)) throw new Error(`[${platform}] 官方 package.main 实际目标逃出 ASAR`); + const build = path.dirname(entry), assets = path.join(root, "webview", "assets"); + if (!fs.statSync(assets).isDirectory()) throw new Error(`[${platform}] 官方 webview 资源缺失`); + const names = fs.readdirSync(build).filter(name => name.endsWith(".js") && fs.readFileSync(path.join(build, name), "utf8").includes("exports.runMainAppStartup=")); + if (names.length !== 1) throw new Error(`[${platform}] 官方 main 启动资源缺失或不唯一`); + const mainFile = path.join(build, names[0]), preloadFile = path.join(build, "preload.js"); + return { platform, build, assets, mainFile, preloadFile, mainSource: patchMain(fs.readFileSync(mainFile, "utf8")), preloadSource: patchPreload(fs.readFileSync(preloadFile, "utf8")) }; + }); + for (const target of prepared) { + if (args.includes("--check")) { console.log(`[ok] [${target.platform}] 本地外观 JSON、官方可信 IPC 与 preload 扩展挂载点已核对`); continue; } + fs.writeFileSync(target.mainFile, target.mainSource); fs.writeFileSync(target.preloadFile, target.preloadSource); + fs.copyFileSync(runtime, path.join(target.build, MODULE)); + fs.copyFileSync(client, path.join(target.assets, "rebuild-settings.mjs")); + console.log(`[ok] [${target.platform}] 已接入 CODEX_HOME 独立外观 JSON 与限定 preload 桥`); + } +} +if (require.main === module) main(); +module.exports = { patchMain, patchPreload, MAIN_MARKER, PRELOAD_MARKER, MODULE }; diff --git a/scripts/reading-layout-smoke.js b/scripts/reading-layout-smoke.js index 802368c4..48e4bbe5 100644 --- a/scripts/reading-layout-smoke.js +++ b/scripts/reading-layout-smoke.js @@ -8,19 +8,20 @@ const html = `:is([data-codex-window-type=browser],[data-codex-window-type=chrome-extension],[data-codex-window-type=electron]) body{--thread-content-max-width:48rem}

阅读布局功能验证

模拟官方布局契约,执行真实阅读偏好模块;完整设置页面仍需候选 GUI 验收。

运行中
粗体内容
代码块
表格
输入区域
对话框
- + `; const server = http.createServer((req,res)=>{ res.setHeader("Cache-Control", "no-store"); if(req.url === "/reading-width.mjs"){res.setHeader("Content-Type","text/javascript; charset=utf-8");res.end(fs.readFileSync(path.join(__dirname,"runtime","reading-width.mjs")));} - else{res.setHeader("Content-Type","text/html; charset=utf-8");res.end(html);} + else if(req.url === "/rebuild-settings.mjs"){res.setHeader("Content-Type","text/javascript; charset=utf-8");res.end(fs.readFileSync(path.join(__dirname,"runtime","rebuild-settings.mjs")));} + else if(req.url === "/settings"&&req.method==="POST"){let body="";req.on("data",chunk=>body+=chunk);req.on("end",()=>{try{settings={...settings,...JSON.parse(body)};res.setHeader("Content-Type","application/json; charset=utf-8");res.end(JSON.stringify(settings));}catch(error){res.statusCode=400;res.end(JSON.stringify({error:error.message}));}});} + else{res.setHeader("Content-Type","text/html; charset=utf-8");res.end(html.replace("__SETTINGS_JSON__",JSON.stringify(settings)));} }); +let settings={readingWidthPercent:85,markdownBoldColorMode:"default",markdownBoldCustomColor:"#7c3aed",accentPreset:null}; server.listen(Number(process.env.REBUILD_SMOKE_PORT || 0),"127.0.0.1",()=>console.log(`Reading smoke: http://127.0.0.1:${server.address().port}/`)); diff --git a/scripts/reading-width.test.js b/scripts/reading-width.test.js index 7a27ee50..f44b0ab6 100644 --- a/scripts/reading-width.test.js +++ b/scripts/reading-width.test.js @@ -7,8 +7,27 @@ async function readingModule() { return import(pathToFileURL(path.join(__dirname, "runtime", "reading-width.mjs")).href); } +const defaults = { + readingWidthPercent: 50, + markdownBoldColorMode: "default", + markdownBoldCustomColor: "#7c3aed", + accentPreset: null, +}; +let snapshot = { ...defaults }; +const listeners = new Set(); +globalThis.electronBridge = { rebuildSettings: { + read: () => ({ ...snapshot }), + async write(patch) { + snapshot = { ...snapshot, ...patch }; + for (const listener of listeners) listener({ ...snapshot }); + return { ...snapshot }; + }, + onChange(listener) { listeners.add(listener); return () => listeners.delete(listener); }, +} }; + test.afterEach(() => { - delete globalThis.localStorage; + snapshot = { ...defaults }; + for (const listener of listeners) listener({ ...snapshot }); }); test("正文宽度提供 50% 到 100% 的 5% 步进", async () => { @@ -29,13 +48,8 @@ test("所有百分比都保留官方宽度下限且不接受旧 default", async assert.throws(() => readingCss("default"), /未知的正文宽度档位/); }); -test("外观设置使用范围滑杆并将无效旧值回落到 50%", async () => { +test("外观设置使用范围滑杆并读取独立配置默认值", async () => { const reading = await readingModule(); - const values = new Map([[reading.STORAGE_KEY, "default"]]); - globalThis.localStorage = { - getItem: key => values.get(key) ?? null, - setItem: (key, value) => values.set(key, value), - }; const react = { Fragment: Symbol("Fragment"), useState: initial => [typeof initial === "function" ? initial() : initial, () => {}], diff --git a/scripts/runtime/accent-presets.mjs b/scripts/runtime/accent-presets.mjs index 2dc9c36f..0f9fdc13 100644 --- a/scripts/runtime/accent-presets.mjs +++ b/scripts/runtime/accent-presets.mjs @@ -1,4 +1,5 @@ -export const ACCENT_PRESET_STORAGE_KEY = "codex-rebuild:accent-preset:v1"; +import { readSettings, writeSettings, reportSettingsError } from "./rebuild-settings.mjs"; +export const ACCENT_PRESET_STORAGE_KEY = "accentPreset"; export const CUSTOM_ACCENT_PRESET = "custom"; export const ACCENT_PRESETS = new Set([ "default", @@ -12,23 +13,14 @@ export const ACCENT_PRESETS = new Set([ CUSTOM_ACCENT_PRESET, ]); -function storage() { - return globalThis.localStorage; -} - export function readLocalAccentPreset() { - try { - const value = storage()?.getItem(ACCENT_PRESET_STORAGE_KEY); - return ACCENT_PRESETS.has(value) ? value : null; - } catch { - return null; - } + const value = readSettings()[ACCENT_PRESET_STORAGE_KEY]; + return ACCENT_PRESETS.has(value) ? value : null; } -function saveLocalAccentPreset(preset) { - try { - storage()?.setItem(ACCENT_PRESET_STORAGE_KEY, preset); - } catch {} +async function saveLocalAccentPreset(preset) { + try { await writeSettings({ [ACCENT_PRESET_STORAGE_KEY]: preset }); } + catch (error) { reportSettingsError(error); } } export function accentPresetSelection(accountTheme, accentSource, fallback) { @@ -46,12 +38,12 @@ export function resolveAccentPreset(accentSource, accountPreset) { } export function selectAccentPreset(accountTheme, preset, applyLocal, selectAccount) { - return Promise.resolve().then(() => { + return Promise.resolve().then(async () => { // 上游可能新增预设;本模块不认识时不保存本地值,也不吞掉官方选择动作。 if (!ACCENT_PRESETS.has(preset)) return selectAccount(); // 无论当前是否能同步到 ChatGPT 账户,都保留一份本地预设。 // 自定义 Provider 重启后可能拿不到账户主题;此时仍应恢复用户上次选择的官方预设。 - saveLocalAccentPreset(preset); + await saveLocalAccentPreset(preset); if (accountTheme !== null) { return selectAccount(); } @@ -59,8 +51,8 @@ export function selectAccentPreset(accountTheme, preset, applyLocal, selectAccou }); } -export function useCustomAccent(onChange, value) { +export async function useCustomAccent(onChange, value) { // 缺少键表示从未设置,本地模式会采用官方默认蓝色;显式 custom 才表示用户选择自定义色。 - saveLocalAccentPreset(CUSTOM_ACCENT_PRESET); + await saveLocalAccentPreset(CUSTOM_ACCENT_PRESET); return onChange(value); } diff --git a/scripts/runtime/reading-width.mjs b/scripts/runtime/reading-width.mjs index f94c839f..b4d3388f 100644 --- a/scripts/runtime/reading-width.mjs +++ b/scripts/runtime/reading-width.mjs @@ -1,4 +1,5 @@ // 只保存阅读布局与 Markdown 粗体样式偏好,认证、Provider 与任务配置由原程序管理。 +import { readSettings, writeSettings, reportSettingsError, SETTINGS_CHANGED } from "./rebuild-settings.mjs"; export const MIN_WIDTH_PERCENT = 50; export const MAX_WIDTH_PERCENT = 100; export const WIDTH_STEP = 5; @@ -6,10 +7,10 @@ export const WIDTHS = Array.from( { length: (MAX_WIDTH_PERCENT - MIN_WIDTH_PERCENT) / WIDTH_STEP + 1 }, (_, index) => String(MIN_WIDTH_PERCENT + index * WIDTH_STEP), ); -export const STORAGE_KEY = "codex-rebuild:reading-width:v1"; +export const STORAGE_KEY = "readingWidthPercent"; export const BOLD_COLOR_MODES = ["default", "accent", "custom"]; -export const BOLD_MODE_STORAGE_KEY = "codex-rebuild:markdown-bold-color-mode:v1"; -export const BOLD_CUSTOM_COLOR_STORAGE_KEY = "codex-rebuild:markdown-bold-custom-color:v1"; +export const BOLD_MODE_STORAGE_KEY = "markdownBoldColorMode"; +export const BOLD_CUSTOM_COLOR_STORAGE_KEY = "markdownBoldCustomColor"; export const DEFAULT_BOLD_CUSTOM_COLOR = "#7c3aed"; const STYLE_ID = "codex-rebuild-reading-style"; const COLOR_PATTERN = /^#[0-9a-f]{6}$/i; @@ -37,17 +38,17 @@ ${Object.entries({ narrow: 520, feature: 600, compact: 640, wide: 800, xwide: 86 } function widthPreference() { - const value = localStorage.getItem(STORAGE_KEY) ?? String(MIN_WIDTH_PERCENT); + const value = String(readSettings()[STORAGE_KEY]); return WIDTHS.includes(value) ? value : String(MIN_WIDTH_PERCENT); } function boldModePreference() { - const value = localStorage.getItem(BOLD_MODE_STORAGE_KEY) ?? "default"; + const value = readSettings()[BOLD_MODE_STORAGE_KEY]; return BOLD_COLOR_MODES.includes(value) ? value : "default"; } function boldCustomColorPreference() { - const value = localStorage.getItem(BOLD_CUSTOM_COLOR_STORAGE_KEY) ?? DEFAULT_BOLD_CUSTOM_COLOR; + const value = readSettings()[BOLD_CUSTOM_COLOR_STORAGE_KEY]; return COLOR_PATTERN.test(value) ? value.toLowerCase() : DEFAULT_BOLD_CUSTOM_COLOR; } @@ -64,8 +65,7 @@ export function installReadingStyle() { if (installed || typeof document === "undefined") return; installed = true; apply(); - window.addEventListener("storage", event => { - if (![STORAGE_KEY, BOLD_MODE_STORAGE_KEY, BOLD_CUSTOM_COLOR_STORAGE_KEY, null].includes(event.key)) return; + window.addEventListener(SETTINGS_CHANGED, () => { apply(); window.dispatchEvent(new Event("codex-rebuild-reading-change")); }); } @@ -104,9 +104,8 @@ export function renderReadingWidth(react, ui, Row, intl) { }, value, onChange: event => { - const next = event.currentTarget.value; - localStorage.setItem(STORAGE_KEY, next); apply(next, boldModePreference()); setValue(next); - window.dispatchEvent(new Event("codex-rebuild-reading-change")); + const next = Number(event.currentTarget.value); + return writeSettings({ [STORAGE_KEY]: next }).catch(reportSettingsError); }, }), ui.jsx("output", { @@ -127,8 +126,7 @@ export function renderReadingWidth(react, ui, Row, intl) { value: boldMode, onChange: event => { const next = event.currentTarget.value; - localStorage.setItem(BOLD_MODE_STORAGE_KEY, next); apply(widthPreference(), next); setBoldMode(next); - window.dispatchEvent(new Event("codex-rebuild-reading-change")); + return writeSettings({ [BOLD_MODE_STORAGE_KEY]: next }).catch(reportSettingsError); }, children: BOLD_COLOR_MODES.map(option => ui.jsx("option", { value: option, children: ({ default: chinese ? "跟随正文" : "Text color", @@ -144,9 +142,8 @@ export function renderReadingWidth(react, ui, Row, intl) { value: boldColor, onChange: event => { const next = event.currentTarget.value.toLowerCase(); - localStorage.setItem(BOLD_CUSTOM_COLOR_STORAGE_KEY, next); localStorage.setItem(BOLD_MODE_STORAGE_KEY, "custom"); - apply(widthPreference(), "custom", next); setBoldColor(next); setBoldMode("custom"); - window.dispatchEvent(new Event("codex-rebuild-reading-change")); + return writeSettings({ [BOLD_CUSTOM_COLOR_STORAGE_KEY]: next, [BOLD_MODE_STORAGE_KEY]: "custom" }) + .catch(reportSettingsError); }, }), ] }), diff --git a/scripts/runtime/rebuild-settings.cjs b/scripts/runtime/rebuild-settings.cjs new file mode 100644 index 00000000..1e4504a8 --- /dev/null +++ b/scripts/runtime/rebuild-settings.cjs @@ -0,0 +1,98 @@ +// 本地外观偏好只读写真实 CODEX_HOME 下的固定文件,不接入官方会话或浏览器存储。 +const fs = require("node:fs"); +const path = require("node:path"); +const { randomUUID } = require("node:crypto"); +const CHANNELS = Object.freeze({ read: "codex_rebuild:settings-read", write: "codex_rebuild:settings-write", changed: "codex_rebuild:settings-changed" }); +const DEFAULTS = Object.freeze({ readingWidthPercent: 50, markdownBoldColorMode: "default", markdownBoldCustomColor: "#7c3aed", accentPreset: null }); +const KEYS = Object.keys(DEFAULTS); +const PRESETS = new Set(["default", "blue", "green", "yellow", "pink", "orange", "purple", "black", "custom"]); +const MAX_BYTES = 64 * 1024; + +function validate(value, partial = false) { + if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("本地外观配置必须是 JSON 对象"); + const keys = Reflect.ownKeys(value); + if (keys.some(key => !KEYS.includes(key)) || !partial && KEYS.some(key => !Object.hasOwn(value, key))) throw new Error("本地外观配置字段无效"); + if (Object.hasOwn(value, "readingWidthPercent") && (!Number.isInteger(value.readingWidthPercent) || value.readingWidthPercent < 50 || value.readingWidthPercent > 100 || value.readingWidthPercent % 5 !== 0)) throw new Error("正文宽度必须是 50 到 100 的 5% 档位"); + if (Object.hasOwn(value, "markdownBoldColorMode") && !["default", "accent", "custom"].includes(value.markdownBoldColorMode)) throw new Error("Markdown 粗体颜色模式无效"); + if (Object.hasOwn(value, "markdownBoldCustomColor") && (typeof value.markdownBoldCustomColor !== "string" || !/^#[0-9a-f]{6}$/.test(value.markdownBoldCustomColor))) throw new Error("Markdown 粗体自定义颜色必须是小写六位十六进制色值"); + if (Object.hasOwn(value, "accentPreset") && value.accentPreset !== null && !PRESETS.has(value.accentPreset)) throw new Error("本地强调色预设无效"); + return value; +} + +function snapshot(value) { return Object.fromEntries(KEYS.map(key => [key, value[key]])); } + +function install({ codexHome, isTrustedIpcEvent, electron = require("electron") }) { + if (typeof codexHome !== "string" || !path.isAbsolute(codexHome) || typeof isTrustedIpcEvent !== "function") throw new Error("本地外观配置缺少真实启动目录或官方 IPC 校验"); + const { ipcMain } = electron; + const file = path.join(codexHome, "codex-rebuild-settings.json"); + const subscribers = new Map(); + let pending = Promise.resolve(); + const read = () => { + let bytes; + try { + if (fs.statSync(file).size > MAX_BYTES) throw new Error("本地外观配置文件超过大小限制"); + bytes = fs.readFileSync(file); + } catch (error) { if (error.code === "ENOENT") return snapshot(DEFAULTS); throw error; } + if (bytes.length > MAX_BYTES) throw new Error("本地外观配置文件超过大小限制"); + return snapshot(validate(JSON.parse(bytes.toString("utf8")))); + }; + const forget = sender => { + const stop = subscribers.get(sender); + if (stop) sender.removeListener("destroyed", stop); + subscribers.delete(sender); + }; + const remember = sender => { + if (subscribers.has(sender) || sender.isDestroyed()) return; + const stop = () => forget(sender); + subscribers.set(sender, stop); sender.once("destroyed", stop); + }; + const broadcast = value => { + for (const sender of subscribers.keys()) { + try { + if (sender.isDestroyed() || !isTrustedIpcEvent({ sender, senderFrame: sender.mainFrame })) { forget(sender); continue; } + sender.send(CHANNELS.changed, snapshot(value)); + } catch { forget(sender); } + } + }; + const onRead = event => { + // 同步 IPC 的所有拒绝/读取异常分支都必须设置 returnValue,避免 renderer 挂起。 + try { + if (!isTrustedIpcEvent(event)) throw new Error("拒绝未受信任的本地外观配置读取"); + remember(event.sender); event.returnValue = read(); + } catch (error) { event.returnValue = { error: error.message || String(error) }; } + }; + const onWrite = (event, patch) => { + if (!isTrustedIpcEvent(event)) return Promise.reject(new Error("拒绝未受信任的本地外观配置写入")); + let update; + try { update = { ...validate(patch, true) }; } catch (error) { return Promise.reject(error); } + remember(event.sender); + const operation = pending.then(() => { + // 排队后重新读取完整磁盘值,保留其他窗口刚写入的字段;无效文件禁止覆盖。 + const value = snapshot(validate({ ...read(), ...update })); + const temporary = path.join(codexHome, `.codex-rebuild-settings.${process.pid}.${randomUUID()}.tmp`); + let created = false, descriptor; + try { + fs.mkdirSync(codexHome, { recursive: true }); + descriptor = fs.openSync(temporary, "wx", 0o600); created = true; + fs.writeFileSync(descriptor, JSON.stringify(value, null, 2) + "\n", { encoding: "utf8" }); + fs.fsyncSync(descriptor); + const closing = descriptor; descriptor = undefined; fs.closeSync(closing); + fs.renameSync(temporary, file); created = false; + } finally { + try { if (descriptor !== undefined) fs.closeSync(descriptor); } + finally { if (created) fs.rmSync(temporary, { force: true }); } + } + broadcast(value); return value; + }); + pending = operation.catch(() => {}); + return operation; + }; + ipcMain.on(CHANNELS.read, onRead); + ipcMain.handle(CHANNELS.write, onWrite); + return () => { + ipcMain.removeListener(CHANNELS.read, onRead); ipcMain.removeHandler(CHANNELS.write); + for (const sender of subscribers.keys()) forget(sender); + }; +} + +module.exports = { install, CHANNELS }; diff --git a/scripts/runtime/rebuild-settings.mjs b/scripts/runtime/rebuild-settings.mjs new file mode 100644 index 00000000..14fbdd31 --- /dev/null +++ b/scripts/runtime/rebuild-settings.mjs @@ -0,0 +1,55 @@ +// 主进程负责独立 JSON 文件;渲染层仅保留已确认的快照,不读写浏览器存储。 +export const DEFAULT_SETTINGS = Object.freeze({ + readingWidthPercent: 50, + markdownBoldColorMode: "default", + markdownBoldCustomColor: "#7c3aed", + accentPreset: null, +}); +export const SETTINGS_CHANGED = "codex-rebuild-settings-change"; +let current; +let bridge; + +export function reportSettingsError(error) { + console.error("[CodexRebuild] 外观配置读写失败", error); +} + +function accept(snapshot) { + if (!snapshot || snapshot.error) throw new Error(snapshot?.error ?? "外观配置快照缺失"); + current = Object.freeze({ ...snapshot }); +} + +function notify() { + if (typeof window !== "undefined") window.dispatchEvent(new Event(SETTINGS_CHANGED)); +} + +function initialize() { + if (current) return; + bridge = globalThis.electronBridge?.rebuildSettings; + try { + if (!bridge) throw new Error("外观配置桥未加载"); + accept(bridge.read()); + } catch (error) { + current = DEFAULT_SETTINGS; + reportSettingsError(error); + } + bridge?.onChange(snapshot => { + try { accept(snapshot); notify(); } + catch (error) { reportSettingsError(error); } + }); +} + +export function readSettings() { + initialize(); + return current; +} + +export async function writeSettings(patch) { + initialize(); + if (!bridge) throw new Error("外观配置桥未加载,未保存"); + // 只有主进程确认落盘成功后才更新界面,避免显示已保存却实际丢失。 + const observed = current; + const snapshot = await bridge.write(patch); + // 广播可能已经送来更新的快照,较早请求的回复不能将它覆盖回去。 + if (current === observed) { accept(snapshot); notify(); } + return current; +} diff --git a/scripts/settings-persistence-smoke.js b/scripts/settings-persistence-smoke.js new file mode 100644 index 00000000..02f1de03 --- /dev/null +++ b/scripts/settings-persistence-smoke.js @@ -0,0 +1,170 @@ +#!/usr/bin/env node +/** 用真实生成 main/preload 资源贯通 IPC 与磁盘;不启动 GUI,不冒充候选原生验收。 */ +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const os = require("node:os"); +const vm = require("node:vm"); +const { pathToFileURL } = require("node:url"); +const { EventEmitter } = require("node:events"); +const { execFileSync } = require("node:child_process"); +const { parse } = require("acorn"); +const { SRC_DIR } = require("./patch-util"); +const { CHANNELS } = require("./runtime/rebuild-settings.cjs"); +const raw = path.resolve(process.env.RAW_ASAR_DIR || path.join(SRC_DIR, "win", "_asar")); +const parent = path.resolve(process.env.REBUILD_SETTINGS_SMOKE_ROOT || os.tmpdir()); +fs.mkdirSync(parent, { recursive: true }); +const root = fs.mkdtempSync(path.join(parent, "settings-persistence-")); +const generated = path.join(root, "source", "win", "_asar"), build = path.join(generated, ".vite", "build"); +function walk(node, visit) { + if (!node || typeof node !== "object") return; + if (node.type) visit(node); + for (const value of Object.values(node)) { + if (Array.isArray(value)) value.forEach(child => walk(child, visit)); + else if (value?.type) walk(value, visit); + } +} +async function main() { + fs.mkdirSync(build, { recursive: true }); fs.mkdirSync(path.join(generated, "webview", "assets"), { recursive: true }); + fs.copyFileSync(path.join(raw, "package.json"), path.join(generated, "package.json")); + const originalBuild = path.join(raw, ".vite", "build"); + const names = fs.readdirSync(originalBuild).filter(name => /^main-.*\.js$/.test(name) && fs.readFileSync(path.join(originalBuild, name), "utf8").includes("exports.runMainAppStartup=")); + assert.equal(names.length, 1, "需要唯一的真实官方 main 资源"); + for (const name of [names[0], "early-bootstrap.js", "preload.js"]) fs.copyFileSync(path.join(originalBuild, name), path.join(build, name)); + const patch = (flags, platform = "win") => execFileSync(process.execPath, [path.join(__dirname, "patch-rebuild-settings.js"), ...(platform ? [platform] : []), ...flags], { env: { ...process.env, CODEX_PATCH_SOURCE_DIR: path.join(root, "source") }, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); + const sourceBefore = fs.readFileSync(path.join(build, names[0])); + patch(["--check"], null); assert.deepEqual(fs.readFileSync(path.join(build, names[0])), sourceBefore, "自动选择现有 Windows 平台且 --check 不写入"); + patch(["--check"]); assert.deepEqual(fs.readFileSync(path.join(build, names[0])), sourceBefore, "--check 不改 main"); + assert.equal(fs.existsSync(path.join(build, "codex-rebuild-settings.cjs")), false, "--check 不复制模块"); + patch([], null); + const patchedMain = fs.readFileSync(path.join(build, names[0]), "utf8"), patchedPreload = fs.readFileSync(path.join(build, "preload.js"), "utf8"); + patch([]); assert.equal(fs.readFileSync(path.join(build, names[0]), "utf8"), patchedMain); assert.equal(fs.readFileSync(path.join(build, "preload.js"), "utf8"), patchedPreload); + assert.deepEqual(fs.readFileSync(path.join(generated, "webview", "assets", "rebuild-settings.mjs")), fs.readFileSync(path.join(__dirname, "runtime", "rebuild-settings.mjs"))); + const handlers = new Map(), ipcMain = new EventEmitter(); + ipcMain.handle = (channel, handler) => { assert.equal(handlers.has(channel), false); handlers.set(channel, handler); }; + ipcMain.removeHandler = channel => handlers.delete(channel); + const codexHome = path.join(root, "isolated-codex-home"), file = path.join(codexHome, "codex-rebuild-settings.json"); + const senders = [], trusted = event => senders.includes(event.sender) && !event.sender.destroyed && event.senderFrame === event.sender.mainFrame && event.sender.mainFrame.url === "app://-/index.html"; + let dispose; + const tree = parse(patchedMain, { ecmaVersion: "latest", sourceType: "script" }), installs = []; + walk(tree, node => { + if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && node.callee.property.name === "install" && node.callee.object.type === "CallExpression" && node.callee.object.callee.name === "require" && node.callee.object.arguments[0]?.value === "./codex-rebuild-settings.cjs") installs.push(node); + }); + assert.equal(installs.length, 1); + const install = installs[0], args = Object.fromEntries(install.arguments[0].properties.map(prop => [prop.key.name, prop.value])); + const context = { + require(name) { assert.equal(name, "./codex-rebuild-settings.cjs"); return { install(options) { dispose = require(path.join(build, "codex-rebuild-settings.cjs")).install({ ...options, electron: { ipcMain } }); } }; }, + [args.codexHome.object.name]: { codexHome }, [args.isTrustedIpcEvent.name]: trusted, + }; + vm.runInNewContext(patchedMain.slice(install.start, install.end), context); + function renderer({ allowed = true, frame = true } = {}) { + const sender = new EventEmitter(), ipcRenderer = new EventEmitter(); + sender.destroyed = false; sender.isDestroyed = () => sender.destroyed; sender.mainFrame = { url: "app://-/index.html" }; + sender.send = (channel, value) => ipcRenderer.emit(channel, {}, value); + if (allowed) senders.push(sender); + const event = () => ({ sender, senderFrame: frame ? sender.mainFrame : { url: sender.mainFrame.url } }); + ipcRenderer.send = () => {}; + ipcRenderer.sendSync = channel => { + if (channel === CHANNELS.read) { const request = event(); ipcMain.emit(channel, request); assert.ok(Object.hasOwn(request, "returnValue"), "同步请求必须返回明确结果"); return request.returnValue; } + if (channel.endsWith("get-sentry-init-options")) return { appVersion: "fixture", codexAppSessionId: "fixture" }; + if (channel.endsWith("get-shared-object-snapshot")) return {}; + return "light"; + }; + ipcRenderer.invoke = (channel, value) => { assert.equal(channel, CHANNELS.write); return handlers.get(channel)(event(), value); }; + const exposed = {}, win = { addEventListener() {}, dispatchEvent() {}, location: { origin: "app://-" } }; + vm.runInNewContext(patchedPreload, { require(name) { assert.equal(name, "electron"); return { ipcRenderer, contextBridge: { exposeInMainWorld(name, value) { exposed[name] = value; } }, webUtils: {} }; }, window: win, document: { documentElement: { dataset: {} } }, performance: { timeOrigin: 0 }, process: { platform: "win32", arch: "x64" }, console }); + return { bridge: exposed.electronBridge.rebuildSettings, sender, destroy() { sender.destroyed = true; sender.emit("destroyed"); } }; + } + const a = renderer(), b = renderer(), outsider = renderer({ allowed: false }), subframe = renderer({ frame: false }); + const clean = value => JSON.parse(JSON.stringify(value)); + const defaults = { readingWidthPercent: 50, markdownBoldColorMode: "default", markdownBoldCustomColor: "#7c3aed", accentPreset: null }; + assert.deepEqual(clean(a.bridge.read()), defaults); assert.equal(fs.existsSync(file), false, "缺文件读取不落盘"); + assert.deepEqual(clean(b.bridge.read()), defaults); + assert.equal(typeof outsider.bridge.read().error, "string"); assert.equal(typeof subframe.bridge.read().error, "string"); + await assert.rejects(outsider.bridge.write({ readingWidthPercent: 70 }), /未受信任/); + await assert.rejects(subframe.bridge.write({ readingWidthPercent: 70 }), /未受信任/); + let changes = 0, outsiderChanges = 0, latest; + const stop = b.bridge.onChange(value => { changes++; latest = value; }); outsider.bridge.onChange(() => outsiderChanges++); + const saved = await a.bridge.write({ readingWidthPercent: 70, markdownBoldColorMode: "custom", markdownBoldCustomColor: "#407aed" }); + assert.deepEqual(saved, { ...defaults, readingWidthPercent: 70, markdownBoldColorMode: "custom", markdownBoldCustomColor: "#407aed" }); + assert.equal(changes, 1); assert.deepEqual(latest, saved); assert.equal(outsiderChanges, 0); + assert.deepEqual(JSON.parse(fs.readFileSync(file, "utf8")), saved); + const globalKeys = ["electronBridge", "window", "document", "localStorage"], originalGlobals = new Map(globalKeys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])); + const effects = []; + try { + const styles = new Map(), widthsAtApply = [], dataset = new Proxy({}, { set(target, key, value) { if (key === "codexRebuildReadingWidth") widthsAtApply.push(value); target[key] = value; return true; } }); + globalThis.electronBridge = { rebuildSettings: a.bridge }; + globalThis.window = new EventTarget(); + globalThis.document = { documentElement: { dataset }, getElementById: id => styles.get(id), createElement(tag) { assert.equal(tag, "style"); return { id: "", textContent: "" }; }, head: { append(style) { styles.set(style.id, style); } } }; + Object.defineProperty(globalThis, "localStorage", { configurable: true, get() { throw new Error("独立配置流程禁止读取 localStorage"); } }); + const reading = await import(pathToFileURL(path.join(__dirname, "runtime", "reading-width.mjs")).href); + const accent = await import(pathToFileURL(path.join(__dirname, "runtime", "accent-presets.mjs")).href); + const style = styles.get("codex-rebuild-reading-style"); + assert.deepEqual(widthsAtApply, ["70"], "首次样式直接使用持久值,没有先应用默认宽度"); + assert.equal(dataset.codexRebuildReadingWidth, "70"); assert.ok(style.textContent.includes("#407aed")); + const controls = [], react = { Fragment: Symbol("Fragment"), useState(initial) { return [typeof initial === "function" ? initial() : initial, () => {}]; }, useEffect(effect) { effects.push(effect()); } }; + const ui = { jsx(type, props) { if (props["data-codex-rebuild-width-control"]) controls.push(props); return { type, props }; }, jsxs(type, props) { return this.jsx(type, props); } }; + reading.renderReadingWidth(react, ui, function Row() {}, { locale: "zh-CN" }); + assert.equal(controls.length, 1); assert.equal(controls[0].value, "70"); + await controls[0].onChange({ currentTarget: { value: "85" } }); + const fromSlider = JSON.parse(fs.readFileSync(file, "utf8")); + assert.deepEqual(fromSlider, { ...saved, readingWidthPercent: 85 }); + assert.equal(dataset.codexRebuildReadingWidth, "85"); assert.ok(style.textContent.includes("max(48rem,85%)") && style.textContent.includes("#407aed")); + let localApplied = false; + await accent.selectAccentPreset(null, "green", () => { localApplied = true; }, () => { throw new Error("本地强调色不应选择账户预设"); }); + assert.equal(localApplied, true); assert.equal(accent.readLocalAccentPreset(), "green"); + assert.deepEqual(JSON.parse(fs.readFileSync(file, "utf8")), { ...fromSlider, accentPreset: "green" }); + } finally { + for (const cleanup of effects) cleanup?.(); + for (const key of globalKeys) { const descriptor = originalGlobals.get(key); if (descriptor) Object.defineProperty(globalThis, key, descriptor); else delete globalThis[key]; } + } + await Promise.all([a.bridge.write({ readingWidthPercent: 85 }), b.bridge.write({ accentPreset: "blue" })]); + assert.deepEqual(clean(renderer().bridge.read()), { ...saved, readingWidthPercent: 85, accentPreset: "blue" }); + const external = { ...saved, readingWidthPercent: 100, accentPreset: "green" }; + fs.writeFileSync(file, JSON.stringify(external)); + assert.deepEqual(await a.bridge.write({ markdownBoldColorMode: "accent" }), { ...external, markdownBoldColorMode: "accent" }, "写入前读取最新磁盘,保留外部修改"); + for (const bad of [{ arbitraryPath: "ignored" }, { readingWidthPercent: 71 }, { accentPreset: "unknown" }, { markdownBoldColorMode: "invalid" }, { markdownBoldCustomColor: "red" }, { readingWidthPercent: null }]) await assert.rejects(a.bridge.write(bad)); + const previous = fs.readFileSync(file, "utf8"), notifications = changes; + const writeFile = fs.writeFileSync; + let partialDescriptor; + try { + // 文件已创建且写入部分字节后故障,仍需关闭句柄并删除本次临时文件。 + fs.writeFileSync = (target, ...options) => { + if (typeof target === "number") { partialDescriptor = target; fs.writeSync(target, "{partial"); throw new Error("模拟磁盘写入中断"); } + return writeFile(target, ...options); + }; + await assert.rejects(a.bridge.write({ readingWidthPercent: 75 }), /磁盘写入中断/); + assert.equal(typeof partialDescriptor, "number"); assert.throws(() => fs.fstatSync(partialDescriptor), /EBADF/); + assert.equal(fs.readFileSync(file, "utf8"), previous); assert.equal(changes, notifications); + assert.deepEqual(fs.readdirSync(codexHome), ["codex-rebuild-settings.json"], "部分写入故障不残留临时文件"); + } finally { fs.writeFileSync = writeFile; } + const rename = fs.renameSync; + try { + // 在完整桥调用内模拟最终磁盘提交失败,确认 UI 不收到已保存通知且原文件保留。 + fs.renameSync = (source, target) => { if (target === file) throw Object.assign(new Error("模拟磁盘提交失败"), { code: "EACCES" }); return rename(source, target); }; + await assert.rejects(a.bridge.write({ readingWidthPercent: 75 }), /磁盘提交失败/); + assert.equal(fs.readFileSync(file, "utf8"), previous); assert.equal(changes, notifications); + assert.deepEqual(fs.readdirSync(codexHome), ["codex-rebuild-settings.json"]); + } finally { fs.renameSync = rename; } + for (const invalid of ["{bad-json", JSON.stringify({ readingWidthPercent: 70 }), JSON.stringify({ ...defaults, extra: 1 }), " ".repeat(65537)]) { + fs.writeFileSync(file, invalid); assert.equal(typeof a.bridge.read().error, "string"); + await assert.rejects(a.bridge.write({ readingWidthPercent: 75 })); assert.equal(fs.readFileSync(file, "utf8"), invalid, "损坏文件不被写入覆盖"); + } + assert.equal(changes, notifications, "失败写入不广播"); fs.writeFileSync(file, previous); + stop(); await a.bridge.write({ accentPreset: null }); assert.equal(changes, notifications, "取消监听后不再回调"); + b.sender.mainFrame.url = "https://example.invalid"; + await a.bridge.write({ accentPreset: "pink" }); assert.equal(b.sender.listenerCount("destroyed"), 0, "导航离开可信页面后清除订阅"); + a.destroy(); assert.equal(a.sender.listenerCount("destroyed"), 0); + assert.deepEqual(fs.readdirSync(codexHome), ["codex-rebuild-settings.json"], "成功与失败后无临时文件残留"); + dispose(); assert.equal(ipcMain.listenerCount(CHANNELS.read), 0); assert.equal(handlers.size, 0); + vm.runInNewContext(patchedMain.slice(install.start, install.end), context); + assert.deepEqual(clean(renderer().bridge.read()), JSON.parse(fs.readFileSync(file, "utf8")), "main 重新安装后从磁盘恢复"); dispose(); + const drifted = fs.readFileSync(path.join(originalBuild, "preload.js"), "utf8").replaceAll("exposeInMainWorld", "driftedExposeInMainWorld"); + fs.writeFileSync(path.join(build, "preload.js"), drifted); + assert.throws(() => patch(["--check"]), /electronBridge/); assert.equal(fs.readFileSync(path.join(build, "preload.js"), "utf8"), drifted, "锚点漂移失败不写入"); + console.log("[ok] 真实 main/preload 与生产外观模块贯通:首屏持久值、滑杆/强调色保存、重载、并发补丁、部分写入/落盘失败、可信广播及锚点漂移拒绝"); +} +main().catch(error => { console.error(error); process.exitCode = 1; }).finally(() => { + // 只清理本脚本刚创建的随机目录,不处理调用者提供的父目录。 + if (path.dirname(root) === parent && path.basename(root).startsWith("settings-persistence-")) fs.rmSync(root, { recursive: true, force: true }); +}); diff --git a/scripts/windows-maintenance.js b/scripts/windows-maintenance.js index aaa940c7..d3fcf2b3 100644 --- a/scripts/windows-maintenance.js +++ b/scripts/windows-maintenance.js @@ -148,22 +148,25 @@ function saveCompatibilityEvidence( const matches = [...signatures, ...functionalSignatures, "settings.appearance.visualStyle", "--thread-content-expanded-max-width", "--markdown-wide-block-max-width"] .filter((signature) => text.includes(signature)); const startupEvidence = label === "main" && /^(?:early-bootstrap|startup-requirements|application-network-startup)/.test(name); + const settingsBridgeEvidence = label === "main" && + (text.includes("isTrustedIpcEvent") && text.includes("getContextForWebContents") || + name === "preload.js" && text.includes("electronBridge") && text.includes("exposeInMainWorld")); // 新版会在三个入口 chunk 之间移动实现;诊断必须包含共享定义与实际功能块。 const frontendEvidence = label === "webview" && (/^app-(?:initial|primary|shared)-.*\.js$/.test(name) || name.endsWith(".js") && matches.some(match => functionalSignatures.includes(match))); - if (!matches.length && !startupEvidence && !frontendEvidence) continue; + if (!matches.length && !startupEvidence && !frontendEvidence && !settingsBridgeEvidence) continue; const copied = label === "main" ? require("./patch-updater").auditUpdaterSource(text).length > 0 : matches.includes("flyoutHeader") || matches.includes("data-model-picker-model-row") || matches.includes("data-model-picker-view") && matches.includes("modelListConfig"); const serviceTierEvidence = matches.includes("serviceTierAccess") && matches.includes("Failed to read service tier for request"); const readingEvidence = matches.includes("settings.appearance.visualStyle") || name.endsWith(".css") && matches.some(match => match.startsWith("--")); - if (copied || serviceTierEvidence || readingEvidence || startupEvidence || frontendEvidence) { + if (copied || serviceTierEvidence || readingEvidence || startupEvidence || frontendEvidence || settingsBridgeEvidence) { fs.mkdirSync(path.join(destination, label), { recursive: true }); fs.copyFileSync(file, path.join(destination, label, name)); } - files.push({ directory, name, matches, copied: copied || serviceTierEvidence || readingEvidence || startupEvidence || frontendEvidence, sha256: crypto.createHash("sha256").update(text).digest("hex") }); + files.push({ directory, name, matches, copied: copied || serviceTierEvidence || readingEvidence || startupEvidence || frontendEvidence || settingsBridgeEvidence, sha256: crypto.createHash("sha256").update(text).digest("hex") }); } } @@ -318,6 +321,7 @@ async function candidate(options) { const applyDirectory = path.join(root, "patch-reports", "windows-apply"); runScript("patch-all.js", ["win", "--check", "--report", checkDirectory]); runScript("patch-all.js", ["win", "--report", applyDirectory]); + runScript("settings-persistence-smoke.js", []); writeJson(path.join(root, "patch-reports", "frontend-source-checks.json"), require("./frontend-source-smoke").verifyFrontendSource(path.join(root, "src", "win", "_asar", "webview", "assets"))); runScript("build-from-upstream.js", ["--platform", "win", "--defer-zip"]); const reports = { check: readJson(path.join(checkDirectory, "report.json")), apply: readJson(path.join(applyDirectory, "report.json")) }; From d55307c0714bcceb7eb96198c80fc0c1128367d2 Mon Sep 17 00:00:00 2001 From: carptopus Date: Wed, 28 Oct 2026 16:28:05 +0800 Subject: [PATCH 46/51] fix quota patch composer import shadowing --- scripts/patch-provider-quota.js | 15 ++++-- scripts/patch-provider-quota.test.js | 78 +++++++++++++++++++++++++++- 2 files changed, 87 insertions(+), 6 deletions(-) diff --git a/scripts/patch-provider-quota.js b/scripts/patch-provider-quota.js index e121d5f5..f1c0e082 100644 --- a/scripts/patch-provider-quota.js +++ b/scripts/patch-provider-quota.js @@ -116,17 +116,22 @@ function getProviderMetadata(source, { resolveModule } = {}) { const atomExport = unique(exports.filter(item => item.local.name === name), "Thread-provider export").exported.name; const initExport = unique(exports.filter(item => item.local.name === initializer.id.name), "Thread-provider initializer export").exported.name; + // 官方压缩导入名可能被 Composer 参数解构遮蔽(26.1023 的 Ie)。 + // 使用专用导入名;重复应用时只复用本补丁自己的同名导入。 const aliases = [[atomExport, "__codexQuotaThreadProviderAtom"], [initExport, "__codexQuotaThreadProviderInit"]] - .map(([exported, fallback]) => { - const imported = dependency.specifiers.filter(item => item.imported?.name === exported); - if (imported.length > 1 || !imported.length && source.includes(fallback)) { + .map(([exported, local]) => { + const imported = dependency.specifiers.filter(item => item.local.name === local); + const occurrences = nodes(ast, node => node.type === "Identifier" && node.name === local); + if (imported.length > 1 || imported.length && imported[0].imported?.name !== exported || + !imported.length && occurrences.length) { throw new Error("Thread-provider import binding is ambiguous/already occupied"); } - return imported[0]?.local.name ?? fallback; + return local; }); const [atomAlias, initAlias] = aliases; const missing = [[atomExport, atomAlias], [initExport, initAlias]] - .filter(([exported]) => !dependency.specifiers.some(item => item.imported?.name === exported)); + .filter(([exported, local]) => !dependency.specifiers.some(item => + item.imported?.name === exported && item.local.name === local)); return { threadProviderAtom: atomAlias, threadProviderImport: { source: dependency.source.value, name: atomExport }, initialize: `${initAlias}(),`, diff --git a/scripts/patch-provider-quota.test.js b/scripts/patch-provider-quota.test.js index cf61f9d0..9ffd53a6 100644 --- a/scripts/patch-provider-quota.test.js +++ b/scripts/patch-provider-quota.test.js @@ -83,6 +83,38 @@ test("拆分 Composer 只沿真实初始模块导出识别 Provider atom", () => assert.equal(patchSource(source, { resolveModule: () => dependency.replace("atom as provider", "other as provider") }).status, "error"); }); +test("拆分 Composer 执行时不调用被参数遮蔽的官方导入名", () => { + const source = fixture().replace(/import[^;]+;/, + 'import{provider as p,initialize as Ie,quota as quotaAtom,hard as hardBlockAtom,host as hostAtom}from"./app-initial-fixture.js";') + .replace("function providerFor(store,id,config){return store.get(threadProvider,id)??config.model_provider}", "") + .replace("let{submitDisabled:external}=props", "let{submitDisabled:external,composerController:Ie,provider:p}=props"); + const dependency = "var atom;function init(){atom=cj(({summary:e})=>e.modelProvider||null)}function providerFor(get,id,config){return get(atom,id)??config.model_provider}export{atom as provider,init as initialize};"; + const options = { resolveModule: () => dependency }; + const result = patchSource(source, options); + assert.equal(result.status, "patched", result.reason); + assert.equal(patchSource(result.code, options).status, "already"); + const { parse } = require("acorn"), vm = require("node:vm"); + const ast = parse(result.code, { ecmaVersion: "latest", sourceType: "module" }); + const composer = ast.body.find(node => node.type === "FunctionDeclaration" && node.id.name === "Composer"); + const atom = {}, context = vm.createContext({ URL, target: {}, Editor: {}, + __codexQuotaThreadProviderAtom: atom, + __codexQuotaThreadProviderInit: () => { context.initialized = true; }, + quotaAtom: "quota", hardBlockAtom: "hard", hostAtom: "host", + cacheMiss: () => true, currentConversation: () => "thread-a", + useScope: () => ({ value: { kind: "local" } }), + useConfig: () => ({ isConfigDataPending: false, resolvedConfig: { + model_provider: "custom", model_providers: { custom: { base_url: "https://proxy.example/v1" } } } }), + read: item => { + if (item === atom) { assert.equal(context.initialized, true); return context.savedProvider; } + return item === "host" ? "local" : true; + }, value: () => true, save: () => {}, jsx: (_, props) => props }); + vm.runInContext(result.code.slice(composer.start, composer.end), context); + assert.equal(context.Composer({ composerController: {}, provider: "shadow" }).submitDisabled, false); + assert.equal(context.Composer({ submitDisabled: true }).submitDisabled, true); + context.savedProvider = "openai"; + assert.equal(context.Composer({}).submitDisabled, true, "官方会话额度门槛保留"); +}); + test("实际生成的发送门槛只忽略明确第三方端点的官方额度", () => { const result = patchSource(fixture()); assert.equal(result.status, "patched", result.reason); @@ -121,6 +153,50 @@ test("实际生成的发送门槛只忽略明确第三方端点的官方额度", assert.equal(context.Composer({}).submitDisabled, true, "云会话不能绕过官方额度"); }); +test("真实 ASAR 的 Composer 参数作用域内执行额度补丁", { skip: !process.env.CODEX_REBUILD_QUOTA_ASAR }, () => { + const asar = require("@electron/asar"), vm = require("node:vm"); + const { parse } = require("acorn"), { walk } = require("./patch-ast-util"); + const file = process.env.CODEX_REBUILD_QUOTA_ASAR; + const candidates = asar.listPackage(file).filter(name => /codex-composer-adapter-.*\.js$/.test(name)) + .map(name => asar.extractFile(file, name.slice(1)).toString()) + .filter(source => source.includes("isConfigDataPending")); + assert.equal(candidates.length, 1); + const options = { resolveModule: name => asar.extractFile(file, + `webview\\assets\\${name.replace("./", "")}`).toString() }; + const result = patchSource(candidates[0], options); + assert.notEqual(result.status, "error", result.reason); + assert.equal(patchSource(result.code, options).status, "already"); + const ast = parse(result.code, { ecmaVersion: "latest", sourceType: "module" }); + const composer = ast.body.find(node => node.type === "FunctionDeclaration" && + node.body.body.some(statement => statement.declarations?.[0]?.id.name === "__codexQuotaThreadProvider")); + assert.ok(composer); + const guard = composer.body.body.find(node => node.declarations?.[0]?.id.name === "__codexQuotaThreadProvider"); + const lookup = guard.declarations[0].init; + assert.equal(lookup.type, "SequenceExpression"); + const read = lookup.expressions.at(-1); + let config, scope; + walk(guard, node => { + if (node.type === "MemberExpression" && node.property.name === "isConfigDataPending") config = node.object.name; + if (node.type === "MemberExpression" && node.property.name === "kind") scope = node.object.object.name; + }); + // 保留真实参数解构,不能在全局伪造 Ie 函数后单独执行 guard 掩盖遮蔽。 + const pattern = composer.body.body.flatMap(node => node.declarations ?? []) + .find(node => node.id.type === "ObjectPattern" && node.id.properties.some(prop => prop.key?.name === "composerController"))?.id; + assert.ok(pattern); + let savedProvider = null, initialized = false; + const atom = {}, context = vm.createContext({ URL, props: { composerController: {} }, + __codexQuotaThreadProviderAtom: atom, + __codexQuotaThreadProviderInit: () => { initialized = true; }, + [read.callee.name]: value => { assert.equal(value, atom); assert.ok(initialized); return savedProvider; }, + [read.arguments[1].name]: "thread-a", [scope]: { value: { kind: "local" } }, + [config]: { isConfigDataPending: false, resolvedConfig: { + model_provider: "custom", model_providers: { custom: { base_url: "https://proxy.example/v1" } } } } }); + vm.runInContext(`function evaluate(){let ${result.code.slice(pattern.start, pattern.end)}=props;${result.code.slice(guard.start, guard.end)}return __codexUsesCustomProvider}`, context); + assert.equal(context.evaluate(), true); + savedProvider = "openai"; + assert.equal(context.evaluate(), false); +}); + test("26.1021 真实 adapter 的 Provider 依赖与发送门槛", { skip: !process.env.CODEX_REBUILD_1021_BUNDLE }, () => { const fs = require("node:fs"), path = require("node:path"), vm = require("node:vm"); const { parse } = require("acorn"); @@ -147,7 +223,7 @@ test("26.1021 真实 adapter 的 Provider 依赖与发送门槛", { skip: !proce walk(disabled.init, node => { if (node.type === "Identifier") names.add(node.name); }); const context = vm.createContext(Object.fromEntries([...names].map(name => [name, false]))); let state; - Object.assign(context, { URL, H: "thread-a", __codexQuotaThreadProviderAtom: {}, sn: () => {}, + Object.assign(context, { URL, H: "thread-a", __codexQuotaThreadProviderAtom: {}, __codexQuotaThreadProviderInit: () => {}, A: () => state.savedProvider, R: { value: { kind: "local" } }, Fr: { isConfigDataPending: false, resolvedConfig: { model_provider: "custom", model_providers: {} } }, Pn: true, Ur: true }); From ac908f328498a7da9500301ac1608fab8e869ca1 Mon Sep 17 00:00:00 2001 From: carptopus Date: Wed, 4 Nov 2026 00:57:45 +0800 Subject: [PATCH 47/51] Add compact sidebar usage indicator --- README.md | 2 +- scripts/patch-sidebar-usage.js | 43 +++++++++++++++++++++++++++++-- scripts/runtime/sidebar-usage.mjs | 9 ++++--- scripts/sidebar-usage-smoke.js | 40 +++++++++++++++++++++++----- 4 files changed, 80 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 231dc76c..fb930865 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ pnpm run build:all - `patch-accent-presets.js` 允许没有 ChatGPT 账户主题的 API-key / 自定义 Provider 在本地选择强调色,并复用官方完整预设渲染消息气泡等界面变量;账户主题仍在加载时保持禁用,账户可用时继续使用官方同步。 - `patch-hide-pet-menu.js` 只隐藏账户菜单中的 Pet / Mini 入口,保留浮动面板实现、状态和全局快捷键。 - `patch-hide-invite-menu.js` 隐藏账户菜单中的“邀请好友 / 邀请同事”入口。 -- `patch-sidebar-usage.js` 在 ChatGPT 登录时以剩余额度圆环和百分比替换侧栏头像,复用官方额度查询和刷新机制,点击仍打开原账户菜单。 +- `patch-sidebar-usage.js` 在 ChatGPT 登录时以剩余额度圆环和数字替换侧栏头像,隐藏官方独立额度入口,使用官方圆环主题配色;复用官方额度查询和刷新机制,点击仍打开原账户菜单。 - `patch-reading-layout.js` 在外观主题卡片中加入 50%–100%、步进 5% 的正文宽度滑杆,并同步代码块、表格和输入区宽度,扩宽适用对话框;百分比不低于官方宽度,Markdown 粗体颜色可跟随正文、强调色或使用自定义颜色。 - `patch-rebuild-settings.js` 将正文宽度、Markdown 粗体颜色和本地强调色预设保存到 `CODEX_HOME/codex-rebuild-settings.json`,独立于程序目录与浏览器 User Data;通过限定的可信 IPC 读取和保存,不读取或迁移旧 localStorage。官方账户主题仍由官方管理。 - `patch-test-isolation.js` 在官方设置 User Data 后、获取单实例锁前挂载 Windows 验收隔离,分别约束 `CODEX_HOME`、User Data 和 sessionData,并记录实际启动路径证据。 diff --git a/scripts/patch-sidebar-usage.js b/scripts/patch-sidebar-usage.js index a03b7659..a1bd18b5 100644 --- a/scripts/patch-sidebar-usage.js +++ b/scripts/patch-sidebar-usage.js @@ -7,6 +7,7 @@ const { applyEdits, key, literal, nodes, unique } = require("./patch-ast-util"); const { SRC_DIR, relPath } = require("./patch-util"); const MODULE = "codex-rebuild-sidebar-usage.js"; const MARKER = "/* CodexRebuildSidebarUsage */"; +const RAIL_MARKER = "/* CodexRebuildSidebarUsageRail */"; const COMPONENT = "__CodexSidebarUsage"; const ACCOUNT_COMPONENT = "__CodexAccountSidebarUsage"; const RENDER = "__codexRenderSidebarUsage"; @@ -137,6 +138,40 @@ function analyze(source, ast, relatedSources = []) { usageAtom: usageAtom.left.name, initialize: initialize.id.name }; } +// 独立额度入口启用后,官方会隐藏头像处额度;只调整导航栏宿主。 +function patchRail(source, footerName) { + const ast = parse(source, { ecmaVersion: "latest", sourceType: "module" }); + const avatars = nodes(ast, node => node.type === "CallExpression" && + node.arguments[0]?.name === footerName && node.arguments[1]?.type === "ObjectExpression" && + (literal(props(node.arguments[1]).compact) === true || + props(node.arguments[1]).compact?.type === "UnaryExpression" && + props(node.arguments[1]).compact.operator === "!" && literal(props(node.arguments[1]).compact.argument) === 0) && + props(node.arguments[1]).hideUsage); + if (!avatars.length && !source.includes("AmbientUsageRailMenu")) return source; + const avatar = unique(avatars, "导航栏紧凑头像调用"); + const host = unique(ast.body.filter(node => node.type === "FunctionDeclaration" && + node.start < avatar.start && node.end > avatar.end), "导航栏头像宿主"); + const menus = nodes(host, node => node.type === "CallExpression" && + node.arguments[1]?.type === "ObjectExpression" && + ["currentAccount", "usage", "fallback", "children"].every(name => props(node.arguments[1])[name]) && + nodes(props(node.arguments[1]).children, child => child.type === "ObjectExpression" && + ["menu", "source", "usage", "actions"].every(name => props(child)[name])).length === 1); + const hidden = props(avatar.arguments[1]).hideUsage; + if (source.includes(RAIL_MARKER)) { + if (source.split(RAIL_MARKER).length !== 2 || literal(hidden) !== false || menus.length) { + throw new Error("导航栏额度替换标记不完整"); + } + return source; + } + const menu = unique(menus, "官方独立额度入口"); + if (hidden.type !== "Identifier") throw new Error("导航栏额度隐藏条件未知"); + return applyEdits(source, [ + { start: host.start, end: host.start, text: `${RAIL_MARKER}\n` }, + { start: hidden.start, end: hidden.end, text: "false" }, + { start: menu.start, end: menu.end, text: "null" }, + ]); +} + function patchSource(source, { relatedSources = [] } = {}) { if (!source.includes("codex.profileFooter.settingsFallback")) return { status: "not-applicable", source }; try { @@ -147,7 +182,10 @@ function patchSource(source, { relatedSources = [] } = {}) { !ast.body.some(node => node.type === "FunctionDeclaration" && node.id?.name === ACCOUNT_COMPONENT)) { throw new Error("侧栏额度补丁标记不完整"); } - return { status: "already-patched", source }; + const footer = unique(ast.body.filter(node => node.type === "FunctionDeclaration" && + contains(source, node, "codex.profileFooter.settingsFallback")), "已补丁头像组件"); + const updated = patchRail(source, footer.id.name); + return { status: updated === source ? "already-patched" : "patched", source: updated }; } if ([COMPONENT, ACCOUNT_COMPONENT, RENDER, MODULE].some(value => source.includes(value))) { throw new Error("侧栏额度注入名称已占用"); @@ -157,7 +195,8 @@ function patchSource(source, { relatedSources = [] } = {}) { const bridges = `\n${MARKER}\nfunction ${COMPONENT}(props){const auth=${shape.authHook}();return props.hidden||auth.authMethod!==\`chatgpt\`?props.fallback:(0,${shape.jsx}.jsx)(${ACCOUNT_COMPONENT},props);}\n` + `function ${ACCOUNT_COMPONENT}(props){${shape.initialize}();const auth=${shape.authHook}(),usage=${shape.readHook}(${shape.usageAtom}),intl=${shape.intlHook}();return ${RENDER}({...props,auth,usage:usage.data,intl,jsx:${shape.jsx}});}\n`; const patched = applyEdits(source, [{ start: shape.avatarSlot.init.start, end: shape.avatarSlot.init.end, text: call }]); - const result = `import {renderSidebarUsage as ${RENDER}} from "./${MODULE}";\n` + patched + bridges; + const result = patchRail(`import {renderSidebarUsage as ${RENDER}} from "./${MODULE}";\n` + patched + bridges, + shape.footer.id.name); parse(result, { ecmaVersion: "latest", sourceType: "module" }); return { status: "patched", source: result }; } catch (error) { diff --git a/scripts/runtime/sidebar-usage.mjs b/scripts/runtime/sidebar-usage.mjs index 7bec8c76..2c6fceb3 100644 --- a/scripts/runtime/sidebar-usage.mjs +++ b/scripts/runtime/sidebar-usage.mjs @@ -12,9 +12,9 @@ export function renderSidebarUsage({ compact, auth, usage, intl, jsx }) { Math.max(0, Math.min(100, 100 - window.used_percent)))) : null; const displayValue = remaining == null ? "—" : intl.formatNumber(remaining, { maximumFractionDigits: 0 }); const percent = remaining == null ? displayValue : `${displayValue}%`; - const accent = "var(--app-color-text-accent,var(--codex-base-accent,currentColor))"; - const color = remaining == null ? "currentColor" : remaining <= 10 ? "#dc503f" : remaining <= 25 ? "#bd7b16" - : `color-mix(in srgb, ${accent} 75%, var(--color-text))`; + const color = remaining != null && remaining < 15 + ? "var(--color-usage-meter-warning,#dc503f)" + : "var(--color-usage-meter-fill,var(--color-text-secondary,currentColor))"; const details = windows.map(window => { const hours = window.limit_window_seconds / 3600; const period = hours === 168 ? (zh ? "每周" : "Weekly") @@ -35,7 +35,8 @@ export function renderSidebarUsage({ compact, auth, usage, intl, jsx }) { // 官方按钮会自动缩放内部 SVG;使用其原生豁免,并把数字置于同一坐标系。 style: { display: "block", width: size, height: size, flex: "none", margin: 0, overflow: "visible" }, children: [jsx.jsx("circle", { - cx: 18, cy: 18, r: 15, fill: "none", stroke: "currentColor", strokeWidth: 2, opacity: 0.1, + cx: 18, cy: 18, r: 15, fill: "none", + stroke: "var(--color-usage-meter-track,var(--color-border-strong))", strokeWidth: 2, }), remaining == null ? null : jsx.jsx("circle", { cx: 18, cy: 18, r: 15, fill: "none", stroke: color, strokeWidth: 2, pathLength: 100, strokeDasharray: `${remaining} 100`, transform: "rotate(-90 18 18)", diff --git a/scripts/sidebar-usage-smoke.js b/scripts/sidebar-usage-smoke.js index b124ce85..904fbd46 100644 --- a/scripts/sidebar-usage-smoke.js +++ b/scripts/sidebar-usage-smoke.js @@ -38,7 +38,7 @@ async function main() { relatedSources = [{ name: initial, source: fs.readFileSync(path.join(assets, initial), "utf8") }]; } origin = `${assets}:${target.name}`; - } else if (args[0] === "--asar" && args.length === 2) { + } else if (["--asar", "--source-asar"].includes(args[0]) && args.length === 2) { const asar = await import("@electron/asar"); const files = asar.listPackage(args[1]); const candidates = files.filter(name => /app-(?:primary|initial)-[^/\\]+\.js$/.test(name)); @@ -51,13 +51,13 @@ async function main() { relatedSources = [{ name: path.basename(initial), source: asar.extractFile(args[1], initial.replace(/^[/\\]/, "")).toString() }]; } origin = `${args[1]}:${entry.name}`; - if (source.includes(MARKER)) { + if (args[0] === "--asar" && source.includes(MARKER)) { const embedded = asar.extractFile(args[1], path.join(path.dirname(entry.name), MODULE).replace(/^[/\\]/, "")).toString(); // Git 在 Windows 构建机可能检出 CRLF;校验源码内容后直接执行成品模块。 assert.equal(embedded.replace(/\r\n/g, "\n"), fs.readFileSync(rendererPath, "utf8").replace(/\r\n/g, "\n"), "候选渲染模块与当前源码不一致"); rendererUrl = `data:text/javascript;base64,${Buffer.from(embedded).toString("base64")}`; } - } else assert.equal(args.length, 0, "用法:node scripts/sidebar-usage-smoke.js [--assets PATH | --asar PATH]"); + } else assert.equal(args.length, 0, "用法:node scripts/sidebar-usage-smoke.js [--assets PATH | --asar PATH | --source-asar PATH]"); if (relatedSources.length && !source.includes(MARKER)) { const sourceAst = parse(source, { ecmaVersion: "latest", sourceType: "module" }); const linkedImport = unique(sourceAst.body.filter(node => node.type === "ImportDeclaration" && @@ -71,6 +71,15 @@ async function main() { assert.ok(["patched", "already-patched"].includes(result.status), result.reason); assert.equal(patchSource(result.source).source, result.source, "重复应用必须幂等"); const ast = parse(result.source, { ecmaVersion: "latest", sourceType: "module" }); + if (source.includes("AmbientUsageRailMenu")) { + assert.ok(result.source.includes("/* CodexRebuildSidebarUsageRail */")); + const footer = unique(ast.body.filter(node => node.type === "FunctionDeclaration" && + result.source.slice(node.start, node.end).includes("codex.profileFooter.settingsFallback")), "真实头像组件"); + const call = unique(nodes(ast, node => node.type === "CallExpression" && node.arguments[0]?.name === footer.id.name && + node.arguments[1]?.properties?.some(prop => prop.key?.name === "hideUsage")), "真实导航栏头像调用"); + const hidden = call.arguments[1].properties.find(prop => prop.key?.name === "hideUsage").value; + assert.equal(hidden.value, false, "官方独立额度启用后也不能隐藏头像数字"); + } const outer = unique(ast.body.filter(node => node.id?.name === COMPONENT), "账号门槛组件"); const account = unique(ast.body.filter(node => node.id?.name === ACCOUNT_COMPONENT), "额度组件"); const declarations = nodes(account, node => node.type === "VariableDeclarator"); @@ -132,10 +141,10 @@ async function main() { const ring = all(tree).find(node => node.type === "circle" && node.props.pathLength === 100); assert.equal(ring.props.strokeDasharray, "81 100"); assert.equal(ring.props.strokeWidth, 2); - assert.match(ring.props.stroke, /^color-mix\(/); + assert.match(ring.props.stroke, /--color-usage-meter-fill/); const track = all(tree).find(node => node.type === "circle" && node.props.pathLength == null); assert.equal(track.props.strokeWidth, 2); - assert.equal(track.props.opacity, 0.1); + assert.match(track.props.stroke, /--color-usage-meter-track/); const svg = all(tree).find(node => node.type === "svg"); assert.equal(svg.props["data-no-autosize"], true, "必须避开官方按钮 SVG 自动缩放"); assert.equal(svg.props.style.width, tree.props.style.width); @@ -164,9 +173,9 @@ async function main() { assert.equal(tree.props.style.width, 24); state.usage.rate_limit.secondary_window = { used_percent: 80, limit_window_seconds: 18000 }; tree = render(); assert.equal(value(tree), "20", "多窗口取最紧张的额度"); - assert.equal(all(tree).find(node => node.type === "circle" && node.props.pathLength === 100).props.stroke, "#bd7b16"); + assert.match(all(tree).find(node => node.type === "circle" && node.props.pathLength === 100).props.stroke, /--color-usage-meter-fill/); state.usage = usage(90); - assert.equal(all(render()).find(node => node.type === "circle" && node.props.pathLength === 100).props.stroke, "#dc503f"); + assert.match(all(render()).find(node => node.type === "circle" && node.props.pathLength === 100).props.stroke, /--color-usage-meter-warning/); for (const [used, expected] of [[0, "100"], [100, "0"], [150, "0"], [-1, "100"], [null, "—"]]) { state.usage = usage(used); assert.equal(value(render()), expected); } @@ -182,6 +191,23 @@ async function main() { assert.equal(render(), fallback); assert.equal(state.reads, 0, "API 模式不挂载官方额度订阅"); state.auth = baseAuth; assert.equal(render(true, true), fallback); assert.equal(state.reads, 0); if (source === fixture) { + const rail = `function Rail(){const profile=jsx(Profile,{compact:true,hideUsage:enabled});const entry=enabled&&jsx(UsageMenu,{currentAccount:account,usage:usage,fallback:null,children:(data,actions)=>jsx(LazyUsage,{menu:data.menu,source:data.source,usage:usage,actions:actions})});return jsx(Layout,{leading:profile,trailing:entry})}`; + const patched = patchSource(fixture + rail); + assert.equal(patched.status, "patched", patched.reason); + assert.equal(patchSource(patched.source).source, patched.source); + const railAst = parse(patched.source, { ecmaVersion: "latest", sourceType: "module" }); + const railFunction = railAst.body.find(node => node.id?.name === "Rail"); + const railContext = vm.createContext({ enabled: true, account: {}, usage: {}, + Profile: input => render(input.compact, input.hideUsage), Layout: input => input, + UsageMenu: () => { throw new Error("独立额度入口不应挂载"); }, + jsx: (component, input) => component(input) }); + vm.runInContext(patched.source.slice(railFunction.start, railFunction.end), railContext); + assert.equal(value(railContext.Rail().leading), "81"); + assert.equal(railContext.Rail().trailing, null); + railContext.enabled = false; + assert.equal(value(railContext.Rail().leading), "81"); + const drift = patchSource(fixture + rail.replace("hideUsage:enabled", "hideUsage:true")); + assert.equal(drift.status, "unexpected-shape"); const invalid = fixture.replace('"/wham/usage"', '"/changed/usage"'); assert.equal(patchSource(invalid).status, "unexpected-shape"); assert.equal(patchSource(invalid).source, invalid); From 7e3cf429620f1c0f091c4a5f4a26aadcd6c409af Mon Sep 17 00:00:00 2001 From: carptopus Date: Wed, 4 Nov 2026 02:39:25 +0800 Subject: [PATCH 48/51] Adapt patches to October Windows release --- scripts/1027-main-features.test.js | 112 ++++++++++++++++++ scripts/patch-all.js | 3 +- scripts/patch-all.test.js | 20 +++- scripts/patch-archive-delete.js | 106 ++++++++++++++--- scripts/patch-archive-delete.test.js | 46 ++++++++ scripts/patch-cdp-screenshot.js | 59 ++++++---- scripts/patch-codex-home-env.js | 40 ++++--- scripts/patch-copyright.js | 27 +++-- scripts/patch-devtools.js | 17 ++- scripts/patch-diff-limits.js | 86 ++++++++++++-- scripts/patch-diff-limits.test.js | 17 +++ scripts/patch-rebuild-settings.js | 33 +++++- scripts/patch-sentry-scope.js | 145 +++++++++++++++--------- scripts/patch-sidebar-usage.js | 40 +++---- scripts/patch-test-isolation.js | 32 ++++-- scripts/patch-updater.js | 19 ++-- scripts/patch-util.js | 25 +++- scripts/patch-worker-limits.js | 8 +- scripts/settings-persistence-smoke.js | 30 ++++- scripts/sidebar-usage-smoke.js | 9 ++ scripts/startup-1027.test.js | 157 ++++++++++++++++++++++++++ 21 files changed, 839 insertions(+), 192 deletions(-) create mode 100644 scripts/1027-main-features.test.js create mode 100644 scripts/patch-diff-limits.test.js create mode 100644 scripts/startup-1027.test.js diff --git a/scripts/1027-main-features.test.js b/scripts/1027-main-features.test.js new file mode 100644 index 00000000..f548a0ac --- /dev/null +++ b/scripts/1027-main-features.test.js @@ -0,0 +1,112 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const os = require("node:os"); +const vm = require("node:vm"); +const { spawnSync } = require("node:child_process"); +const acorn = require("acorn"); +const worker = require("./patch-worker-limits"); +const cdp = require("./patch-cdp-screenshot"); +const sentry = require("./patch-sentry-scope"); + +// 26.1027.6604.0 early-bootstrap-499 的真实 Worker 构造表达式。 +const workerExpression = "new eMg.Worker(r,{name:this.id,workerData:{...a,sentryRpcPort:n.port2,mainRpcPort:i?.port2??null},transferList:[n.port2,...null==i?[]:[i.port2]]})"; +test("1027 Worker 限额保留名称、RPC 端口和 transferList", () => { + const result = worker.patchSource("function create(){return " + workerExpression + "}"); + assert.equal(result.status, "patched"); + const run = vm.runInNewContext("(" + result.source + ")", { eMg: { Worker: class { constructor(file, options) { this.file = file; this.options = options; } } }, r: "worker.js", a: { task: "git" }, n: { port2: "sentry" }, i: { port2: "main" } }); + const instance = run.call({ id: "git-worker" }); + assert.equal(instance.file, "worker.js"); + assert.deepEqual(JSON.parse(JSON.stringify(instance.options)), { name: "git-worker", workerData: { task: "git", sentryRpcPort: "sentry", mainRpcPort: "main" }, transferList: ["sentry", "main"], resourceLimits: { maxOldGenerationSizeMb: 1024, maxYoungGenerationSizeMb: 128 } }); + assert.equal(worker.patchSource(result.source).status, "already-patched"); + assert.equal(worker.patchSource("function absent(){}").status, "unexpected-anchor-count"); + assert.equal(worker.patchSource(result.source + result.source).status, "unexpected-anchor-count"); +}); + +// 同一 chunk 的真实 sendDebuggerCommand,包含新增的结果包装器。 +const forwarder = 'async sendDebuggerCommand(e,t,r,n={},i=this.cdpCommandTimeoutMs){let s=n.sessionId??(null==n.targetId?void 0:this.debuggerSessionIdForTarget(e,n.targetId)??void 0);if(null!=n.targetId&&n.targetId!==eeY(e)&&null==s)throw Error(`No in-app browser debugger session is attached for target ${n.targetId}`);return(0,ea.LcI)(t,await ets(e.webContents.debugger.sendCommand(t,r,s),i,`Timed out running CDP command "${t}" for tab ${e.cdpTabId}`))}'; +test("1027 CDP 包装返回值和超时语义保留,仅修改整页截图副本", async () => { + const result = cdp.patchSource("class BrowserHost{" + forwarder + "}"); + assert.equal(result.status, "patched"); + let sent, timeout, wrapped; + const BrowserHost = vm.runInNewContext(result.source + ";BrowserHost", { ets: async (promise, ms) => { timeout = ms; return promise; }, ea: { LcI: (method, value) => { wrapped = method; return { value }; } } }); + const host = new BrowserHost(); + host.cdpCommandTimeoutMs = 456; + const tab = { webContents: { debugger: { sendCommand: async (...args) => { sent = args; return "response"; } } } }; + const params = { captureBeyondViewport: true, clip: { width: 10000, height: 10000 }, format: "png", other: 9 }; + const response = await host.sendDebuggerCommand(tab, "Page.captureScreenshot", params, { sessionId: "session" }); + assert.equal(response.value, "response"); + assert.equal(wrapped, "Page.captureScreenshot"); + assert.equal(timeout, 456); + assert.equal(sent[2], "session"); + assert.deepEqual(JSON.parse(JSON.stringify(sent[1])), { captureBeyondViewport: false, format: "jpeg", quality: 60, other: 9 }); + assert.equal(params.captureBeyondViewport, true); + assert.ok(params.clip); + const viewport = { captureBeyondViewport: false, clip: { width: 10, height: 10 }, format: "png" }; + await host.sendDebuggerCommand(tab, "Page.captureScreenshot", viewport); + assert.equal(sent[1], viewport); + await host.sendDebuggerCommand(tab, "Page.navigate", params); + assert.equal(sent[1], params); + const jpeg = { captureBeyondViewport: true, format: "jpeg", quality: 85 }; + await host.sendDebuggerCommand(tab, "Page.captureScreenshot", jpeg); + assert.equal(sent[1].quality, 85); + assert.equal(cdp.patchSource(result.source).status, "already-patched"); + assert.equal(cdp.patchSource("class X{" + forwarder + forwarder + "}").status, "unexpected-shape"); +}); + +const evidenceDir = process.env.CODEX_1027_SOURCE_EVIDENCE; +test("1027 完整真实源:五项补丁两次运行、缺失和歧义拒绝", { skip: !evidenceDir }, () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "codex-1027-main-features-")); + const build = path.join(root, "win", "_asar", ".vite", "build"); + fs.mkdirSync(build, { recursive: true }); + fs.cpSync(evidenceDir, build, { recursive: true }); + function run(name) { + return spawnSync(process.execPath, [path.join(__dirname, "patch-" + name + ".js"), "win"], { env: { ...process.env, CODEX_PATCH_SOURCE_DIR: root }, encoding: "utf8" }); + } + try { + const sources = fs.readdirSync(build).filter((f) => f.endsWith(".js")).map((f) => fs.readFileSync(path.join(build, f), "utf8")); + assert.deepEqual(sentry.inspectNativeScopeProtection(sources), [{ moduleId: 72629, sanitizerModuleId: 39092, sanitizerName: "r7" }]); + assert.equal(sentry.inspectNativeScopeProtection(sources.map((source) => source.replace("beforeBreadcrumb:o.SKH", "beforeBreadcrumb:o.wrong"))).length, 0); + assert.equal(sentry.inspectNativeScopeProtection(sources.map((source) => source.replace("byteLength<=2048", "byteLength<=9999"))).length, 0); + const sanitizerSource = sources.find((source) => source.includes("codex_truncated_breadcrumb_data") && source.includes("SKH:()=>r7")); + const sanitizerAst = acorn.parse(sanitizerSource, { ecmaVersion: "latest" }); + const functions = new Map(); + function collect(node, inSanitizerModule = false) { + if (!node || typeof node !== "object") return; + if (node.type === "Property" && node.key?.value === 39092) inSanitizerModule = true; + if (inSanitizerModule && node.type === "FunctionDeclaration" && ["r7", "ot", "on"].includes(node.id.name)) functions.set(node.id.name, sanitizerSource.slice(node.start, node.end)); + for (const value of Object.values(node)) { + if (Array.isArray(value)) value.forEach((child) => collect(child, inSanitizerModule)); + else if (value?.type) collect(value, inSanitizerModule); + } + } + collect(sanitizerAst); + assert.equal(functions.size, 3); + const truncate = vm.runInNewContext([...functions.values()].join(";") + ";r7", { TextEncoder, r8: "[Truncated: breadcrumb data exceeded 2 KiB]" }); + const small = { data: { message: "small" } }; + assert.equal(truncate(small), small); + const large = { data: { arguments: "汉".repeat(5000), payload: "x".repeat(9000) } }; + const trimmed = truncate(large); + assert.ok(new TextEncoder().encode(JSON.stringify(trimmed.data)).byteLength <= 2048); + assert.equal(trimmed.data.codex_truncated_breadcrumb_data, true); + assert.equal(large.data.payload.length, 9000); + for (const name of ["devtools", "worker-limits", "sentry-scope", "cdp-screenshot", "copyright"]) { + for (let pass = 0; pass < 2; pass++) { + const result = run(name); + assert.equal(result.status, 0, name + " " + result.stdout + result.stderr); + } + } + const main = fs.readdirSync(build).find((f) => f.startsWith("early-bootstrap-499-")); + const mainPath = path.join(build, main); + const patched = fs.readFileSync(mainPath, "utf8"); + acorn.parse(patched, { ecmaVersion: "latest", sourceType: "module" }); + fs.copyFileSync(mainPath, path.join(build, "decoy.js")); + assert.notEqual(run("worker-limits").status, 0); + fs.unlinkSync(path.join(build, "decoy.js")); + fs.unlinkSync(mainPath); + for (const name of ["devtools", "worker-limits", "cdp-screenshot", "copyright"]) assert.notEqual(run(name).status, 0, name); + } finally { + fs.rmSync(root, { recursive: true }); + } +}); diff --git a/scripts/patch-all.js b/scripts/patch-all.js index ae13e91d..42f10240 100644 --- a/scripts/patch-all.js +++ b/scripts/patch-all.js @@ -45,7 +45,8 @@ function snapshotOptionalTargets(patch, sourceDir, platform) { ? path.join(sourceDir, platform, "_asar", "webview", "assets") : path.join(sourceDir, platform, "_asar", ".vite", "build"); if (!fs.existsSync(directory)) return []; - const pattern = patch.rollback === "translations" ? /^zh-CN-.*\.js$/ : /^main(?:-[^.]+)?\.js$/; + const pattern = patch.rollback === "translations" ? /^zh-CN-.*\.js$/ + : /^(?:main|early-bootstrap)(?:-[^.]+)?\.js$/; return fs.readdirSync(directory).filter((name) => pattern.test(name)).map((name) => { const file = path.join(directory, name); return { file, contents: fs.readFileSync(file) }; diff --git a/scripts/patch-all.test.js b/scripts/patch-all.test.js index 565f0d08..53fd63d0 100644 --- a/scripts/patch-all.test.js +++ b/scripts/patch-all.test.js @@ -44,7 +44,7 @@ test("真实 updater 补丁的预检查不修改资源,应用后关闭更新", test("可选版权补丁失败时保留上游文件,严格模式阻止继续", (t) => { const root = fixture(t); - const first = "const broken=;"; + const first = 'const about={copyright:"© OpenAI"};const broken=;'; const firstFile = write(root, ".vite/build/main-a.js", first); const reportDir = path.join(root, "report"); const options = { platform: "win", sourceDir: root, reportDir, policy: policy("patch-copyright.js"), log: () => {} }; @@ -68,10 +68,26 @@ test("可选版权补丁失败时保留上游文件,严格模式阻止继续", assert.equal(updater.shouldIncludeUpdater(), false); }); +test("新版箭头 updater 门槛在真实 CLI 应用后关闭且审计通过", t => { + const root = fixture(t); + const source = 'const updater={shouldIncludeWindowsUpdater:(plan,host)=>host==="win32",shouldIncludeWindowsMsixUpdater:()=>true,shouldIncludeUpdater:()=>true};'; + const file = write(root, ".vite/build/early-bootstrap.js", source); + const options = { platform: "win", sourceDir: root, policy: policy("patch-updater.js"), log: () => {} }; + assert.equal(runPatches(options).canBuild, true); + const updated = fs.readFileSync(file, "utf8"); + const updater = Function(`${updated};return updater`)(); + assert.equal(updater.shouldIncludeWindowsUpdater("pro", "win32"), false); + assert.equal(updater.shouldIncludeWindowsMsixUpdater(), false); + assert.equal(updater.shouldIncludeUpdater(), false); + assert.ok(require("./patch-updater").auditUpdaterSource(updated).every(item => item.disabled)); + assert.equal(runPatches(options).canBuild, true); + assert.equal(fs.readFileSync(file, "utf8"), updated); +}); + test("可选补丁已写文件但报告写入失败时回滚并阻止构建", (t) => { const root = fixture(t); const source = "const about={copyright:'© OpenAI'};"; - const file = write(root, ".vite/build/main-test.js", source); + const file = write(root, ".vite/build/early-bootstrap-499-test.js", source); const reportDir = path.join(root, "report"); fs.mkdirSync(path.join(reportDir, "logs", "win-patch-copyright.js.log"), { recursive: true }); diff --git a/scripts/patch-archive-delete.js b/scripts/patch-archive-delete.js index b8602feb..0e65487c 100644 --- a/scripts/patch-archive-delete.js +++ b/scripts/patch-archive-delete.js @@ -17,7 +17,7 @@ const fs = require("fs"); const path = require("path"); const acorn = require("acorn"); const { key, literal, nodes } = require("./patch-ast-util"); -const { locateBundles, relPath, SRC_DIR } = require("./patch-util"); +const { locateBundles, listBuildBundles, relPath, SRC_DIR } = require("./patch-util"); function walkArchive(node, visitor) { if (!node || typeof node !== "object") return; @@ -147,6 +147,23 @@ function locateArchivedProviderBundles(platform) { return bundles.sort((left, right) => left.path.localeCompare(right.path)); } +function locateDataControlsBundles(platform) { + const platforms = platform ? [platform] : ["mac-arm64", "mac-x64", "win"].filter(name => + fs.existsSync(path.join(SRC_DIR, name, "_asar", "webview", "assets"))); + const roots = platforms.length ? platforms.map(name => ({ platform: name, + dir: path.join(SRC_DIR, name, "_asar", "webview", "assets") })) : + [{ platform: "legacy", dir: path.join(SRC_DIR, "webview", "assets") }]; + return roots.flatMap(root => { + if (!fs.existsSync(root.dir)) return []; + const matches = fs.readdirSync(root.dir).filter(name => /^data-controls-.*\.js$/.test(name)) + .map(name => ({ platform: root.platform, path: path.join(root.dir, name) })) + .filter(bundle => { const source = fs.readFileSync(bundle.path, "utf-8"); + return source.includes("archivedThread") && source.includes("archived-threads"); }); + if (matches.length !== 1) throw new Error(`[${root.platform}] expected exactly 1 archived data-controls bundle, found ${matches.length}`); + return matches; + }); +} + function patchArchivedProviderQueries(bundles, isCheck) { let patched = 0; let already = 0; @@ -313,7 +330,7 @@ function destructuredPropertyBinding(fn, propertyName) { return bindings.length === 1 ? bindings[0] : null; } -function inspectRowMutationLink(ast, mutationFunction, rowFunctions, deleteProps) { +function inspectRowMutationLink(ast, mutationFunction, rowFunctions, deleteProps, requireBulk = false) { const statePairs = nodes(mutationFunction, node => node.type === "VariableDeclarator" && node.id?.type === "ArrayPattern" && node.id.elements.length >= 2 && node.id.elements[0]?.type === "Identifier" && node.id.elements[1]?.type === "Identifier" && @@ -335,6 +352,11 @@ function inspectRowMutationLink(ast, mutationFunction, rowFunctions, deleteProps nodes({ type: "Arguments", values: call.arguments }, node => node.type === "Identifier" && node.name === state.value).length > 0).length > 0; if (!mutatesState || !clearsState) continue; + if (requireBulk && !nodes(mutationFunction, node => node.type === "Property" && + key(node.key) === "onClick" && nodes(node.value, call => call.type === "CallExpression" && + call.callee?.type === "Identifier" && call.callee.name === state.setter && + nodes(call, item => item.type === "Property" && key(item.key) === "kind" && + literal(item.value) === "all").length === 1).length === 1).length) continue; const openDeleteProps = nodes(mutationFunction, node => node.type === "ObjectExpression" && objectProperty(node, "onDelete")?.value != null && @@ -414,9 +436,45 @@ function handlesDeletedNotification(fn) { return false; } -function inspectNativeArchiveDelete(code, protocolCode) { +// Verify both archived-thread service methods reach the exported deletion path. +function hasSplitMainDeleteChain(mainAst, serviceAst) { + const functions = nodes(mainAst, node => node.type === "FunctionDeclaration" && node.id); + const callsName = (fn, name) => nodes(fn.body, call => call.type === "CallExpression" && + call.callee?.type === "Identifier" && call.callee.name === name).length > 0; + const deleteFns = functions.filter(fn => nodes(fn.body, call => call.type === "CallExpression" && + memberName(call.callee) === "sendAppServerRequest" && literal(call.arguments[0]) === "thread/delete").length > 0); + if (deleteFns.length !== 1) return false; + const batchFns = functions.filter(fn => callsName(fn, deleteFns[0].id.name)); + if (batchFns.length !== 1) return false; + const entryFns = functions.filter(fn => callsName(fn, batchFns[0].id.name)); + if (entryFns.length !== 2) return false; + const exports = new Map(); + for (const fn of entryFns) { + const properties = nodes(mainAst, node => node.type === "Property" && + node.value?.type === "ArrowFunctionExpression" && node.value.body?.type === "Identifier" && + node.value.body.name === fn.id.name); + if (properties.length !== 1) return false; + exports.set(fn.id.name, key(properties[0].key)); + } + const serviceMethods = nodes(serviceAst, node => node.type === "MethodDefinition" && + ["deleteArchivedThread", "deleteAllArchivedThreads"].includes(key(node.key))); + if (serviceMethods.length !== 2) return false; + const used = new Set(); + for (const method of serviceMethods) { + const hits = [...exports.values()].filter(name => nodes(method.value.body, call => + call.type === "CallExpression" && nodes(call.callee, member => + member.type === "MemberExpression" && memberName(member) === name).length > 0).length > 0); + if (hits.length !== 1 || used.has(hits[0])) return false; + used.add(hits[0]); + } + return true; +} + +function inspectNativeArchiveDelete(code, protocolCode, runtimeCode = protocolCode, mainCode = protocolCode, serviceCode = null) { const ast = acorn.parse(code, { ecmaVersion: "latest", sourceType: "module" }); const protocolAst = acorn.parse(protocolCode, { ecmaVersion: "latest", sourceType: "module" }); + const runtimeAst = runtimeCode === protocolCode ? protocolAst : acorn.parse(runtimeCode, { ecmaVersion: "latest", sourceType: "module" }); + const mainAst = mainCode === protocolCode ? protocolAst : acorn.parse(mainCode, { ecmaVersion: "latest", sourceType: "module" }); const mutationFunctions = inspectMutationChain(ast, code); if (mutationFunctions.length !== 1) return null; @@ -450,12 +508,13 @@ function inspectNativeArchiveDelete(code, protocolCode) { mutationFunctions[0], rowFunctions, deleteProps, + serviceCode != null, ); if (linkedDeleteProps.length < 1) return null; const managerChains = inspectManagerDeleteChain(protocolAst); if (managerChains.length !== 1) return null; - const runtimeDeletes = nodes(protocolAst, node => + const runtimeDeletes = nodes(runtimeAst, node => (node.type === "Property" || node.type === "MethodDefinition") && key(node.key) === "deleteArchivedThreads"); if (runtimeDeletes.length !== 1) return null; @@ -463,14 +522,14 @@ function inspectNativeArchiveDelete(code, protocolCode) { ["deleteArchivedThread", "deleteAllArchivedThreads"].includes(memberName(node.callee))); const runtimeReceivers = new Map(); for (const call of runtimeCalls) { - const receiver = receiverSource(protocolCode, call); + const receiver = receiverSource(runtimeCode, call); if (receiver == null) continue; if (!runtimeReceivers.has(receiver)) runtimeReceivers.set(receiver, new Set()); runtimeReceivers.get(receiver).add(memberName(call.callee)); } if (![...runtimeReceivers.values()].some(methods => methods.has("deleteArchivedThread") && methods.has("deleteAllArchivedThreads"))) return null; - const protocolMethods = nodes(protocolAst, node => + const protocolMethods = nodes(mainAst, node => (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") && nodes(node, call => call.type === "CallExpression" && @@ -481,6 +540,8 @@ function inspectNativeArchiveDelete(code, protocolCode) { node.type === "ArrowFunctionExpression") && handlesDeletedNotification(node)); if (protocolMethods.length < 1 || deleteNotifications.length < 1) return null; + if (serviceCode != null && !hasSplitMainDeleteChain(mainAst, + acorn.parse(serviceCode, { ecmaVersion: "latest", sourceType: "module" }))) return null; return { deleteProps: linkedDeleteProps.length, @@ -489,9 +550,9 @@ function inspectNativeArchiveDelete(code, protocolCode) { }; } -function hasNativeArchiveDelete(code, protocolCode = code) { +function hasNativeArchiveDelete(code, protocolCode = code, runtimeCode = protocolCode, mainCode = protocolCode, serviceCode = null) { try { - return inspectNativeArchiveDelete(code, protocolCode) != null; + return inspectNativeArchiveDelete(code, protocolCode, runtimeCode, mainCode, serviceCode) != null; } catch { return false; } @@ -777,11 +838,7 @@ function main() { isCheck, ); - const dataControlsBundles = locateBundles({ - dir: "assets", - pattern: /^data-controls-.*\.js$/, - ...(platform ? { platform } : {}), - }); + const dataControlsBundles = locateDataControlsBundles(platform); const protocolBundles = locateBundles({ dir: "assets", pattern: /^app-initial-.*\.js$/, @@ -794,11 +851,26 @@ function main() { } protocolByPlatform.set(bundle.platform, fs.readFileSync(bundle.path, "utf-8")); } + const runtimeBundles = locateBundles({ + dir: "assets", pattern: /^renderer-app-server-managers-.*\.js$/, + ...(platform ? { platform } : {}), + }); + const buildBundles = listBuildBundles(platform); const nativeBundles = dataControlsBundles.filter((bundle) => { const protocolCode = protocolByPlatform.get(bundle.platform); - return protocolCode != null && hasNativeArchiveDelete( - fs.readFileSync(bundle.path, "utf-8"), protocolCode, - ); + if (protocolCode == null) return false; + const uiCode = fs.readFileSync(bundle.path, "utf-8"); + if (hasNativeArchiveDelete(uiCode, protocolCode)) return true; + const runtimes = runtimeBundles.filter(item => item.platform === bundle.platform); + const mains = buildBundles.filter(item => item.platform === bundle.platform && + fs.readFileSync(item.path, "utf-8").includes('sendAppServerRequest("thread/delete"')); + const services = buildBundles.filter(item => item.platform === bundle.platform && + (() => { const source = fs.readFileSync(item.path, "utf-8"); + return source.includes("deleteArchivedThread(") && source.includes("deleteAllArchivedThreads("); })()); + if (runtimes.length !== 1 || mains.length !== 1 || services.length !== 1) return false; + return hasNativeArchiveDelete(uiCode, protocolCode, + fs.readFileSync(runtimes[0].path, "utf-8"), fs.readFileSync(mains[0].path, "utf-8"), + fs.readFileSync(services[0].path, "utf-8")); }); const nativePlatforms = new Set(nativeBundles.map((bundle) => bundle.platform)); @@ -850,6 +922,8 @@ module.exports = { analyzeArchivedListProviders, hasNativeArchiveDelete, inspectNativeArchiveDelete, + hasSplitMainDeleteChain, + inspectRowMutationLink, patchAppMain, patchArchivedListProviders, patchArchivedProviderQueries, diff --git a/scripts/patch-archive-delete.test.js b/scripts/patch-archive-delete.test.js index db216910..37ba7060 100644 --- a/scripts/patch-archive-delete.test.js +++ b/scripts/patch-archive-delete.test.js @@ -79,3 +79,49 @@ test("归档 Provider 修复不改变活动列表、显式过滤和其他调用" assert.equal(repeated.edits, 0); assert.equal(repeated.alreadyAllProviders, 2); }); + +test("新版主进程拆包后单条和批量归档删除均须连接协议", () => { + const acorn = require("acorn"); + const { hasSplitMainDeleteChain } = require("./patch-archive-delete"); + const main = [ + 'async function remove(server,id){return server.sendAppServerRequest("thread/delete",{threadId:id})}', + 'async function batch(server,ids){for(const id of ids)await guard(()=>remove(server,id))}', + 'async function one(server,id){return batch(server,[id])}', + 'async function all(server){return batch(server,await server.listThreads())}', + 'const exported={a:()=>one,b:()=>all};', + ].join(""); + const service = 'class Archive{async deleteArchivedThread(x){return module.a(x)}async deleteAllArchivedThreads(x){return module.b(x)}}'; + const parse = source => acorn.parse(source, { ecmaVersion: "latest" }); + assert.equal(hasSplitMainDeleteChain(parse(main), parse(service)), true); + assert.equal(hasSplitMainDeleteChain(parse(main.replace('"thread/delete"', '"thread/archive"')), parse(service)), false); + assert.equal(hasSplitMainDeleteChain(parse(main), parse(service.replace('module.b(x)', 'module.a(x)'))), false); + assert.equal(hasSplitMainDeleteChain(parse(main.replace('batch(server,await server.listThreads())', 'noop()')), parse(service)), false); +}); + + +test("新版批量按钮和单条行共用待确认状态", () => { + const acorn = require("acorn"); + const { inspectRowMutationLink } = require("./patch-archive-delete"); + const source = [ + 'function Screen(){const [pending,setPending]=useState(null);', + 'const confirm=()=>{if(pending){setPending(null);mutation.mutate(pending)}};', + 'return ui(Dialog,{onConfirm:confirm,children:[ui(Button,{onClick:()=>setPending({kind:"all"})}),', + 'ui(Group,{onDelete:thread=>setPending({kind:"single",thread})})]})}', + 'function Group(input){const {onDelete:openDelete}=input;return ui(Row,{showDeleteButton:true,onDelete:()=>openDelete(thread)})}', + 'function Row(input){const {showDeleteButton:show,onDelete:remove}=input;if(show)remove()}', + ].join(""); + function check(text) { + const ast = acorn.parse(text, { ecmaVersion: "latest" }); + const [screen, , row] = ast.body; + let props; + function walk(node) { + if (!node || typeof node !== "object") return; + if (node.type === "ObjectExpression" && node.properties.some(p => p.key?.name === "showDeleteButton")) props = node; + for (const value of Object.values(node)) if (Array.isArray(value)) value.forEach(walk); else if (value?.type) walk(value); + } + walk(ast); + return inspectRowMutationLink(ast, screen, [row], [props], true).length; + } + assert.equal(check(source), 1); + assert.equal(check(source.replace('setPending({kind:"all"})', 'noop({kind:"all"})')), 0); +}); diff --git a/scripts/patch-cdp-screenshot.js b/scripts/patch-cdp-screenshot.js index ec7356f1..0df334a4 100644 --- a/scripts/patch-cdp-screenshot.js +++ b/scripts/patch-cdp-screenshot.js @@ -30,7 +30,7 @@ */ const fs = require("fs"); const acorn = require("acorn"); -const { locateBundles, relPath } = require("./patch-util"); +const { locateBuildFeatureBundles, relPath } = require("./patch-util"); const MARKER = "__codexCdpGuard"; @@ -41,13 +41,7 @@ const GUARD_DEF = MARKER + "=function(m,p){try{if(m===`Page.captureScreenshot`&&p&&typeof p==`object`&&p.captureBeyondViewport===!0){var q={};for(var k in p)q[k]=p[k];q.captureBeyondViewport=!1;delete q.clip;(q.format==null||q.format===`png`)&&(q.format=`jpeg`,q.quality=60);return q}}catch(e){}return p};\n"; -// CDP 统一转发点(sendDebuggerCommand 内部)——main bundle 中唯一 -const ANCHOR = - "return await hY(e.webContents.debugger.sendCommand(t,n,i),this.cdpCommandTimeoutMs,"; -const REPLACEMENT = - "return await hY(e.webContents.debugger.sendCommand(t,globalThis." + - MARKER + - "(t,n),i),this.cdpCommandTimeoutMs,"; +// 保留给已有诊断调用者的旧形态识别式;实际修改使用 AST 方法上下文。 const DYNAMIC_ANCHOR_RE = /return await ([A-Z_$a-z][\w$]*)\(([A-Z_$a-z][\w$]*)\.webContents\.debugger\.sendCommand\(([A-Z_$a-z][\w$]*),([A-Z_$a-z][\w$]*),([A-Z_$a-z][\w$]*)\),(this\.cdpCommandTimeoutMs|[A-Z_$a-z][\w$]*),/; @@ -66,21 +60,38 @@ function parseOk(code) { } function patchSource(code) { - if (code.includes(MARKER)) { - return { status: "already-patched", source: code }; + // 新版对返回结果再包装,直接定位 sendDebuggerCommand 方法内的真实调用。 + let ast; + try { ast = acorn.parse(code, { ecmaVersion: "latest", sourceType: "module" }); } + catch { return { status: "invalid-output", source: code }; } + const matches = []; + const guarded = []; + function walk(node, inForwarder = false) { + if (!node || typeof node !== "object") return; + if (node.type === "MethodDefinition") inForwarder = node.key?.name === "sendDebuggerCommand"; + if (inForwarder && node.type === "CallExpression" && node.arguments.length === 3 && + /\.webContents\.debugger\.sendCommand$/.test(code.slice(node.callee.start, node.callee.end))) { + if (node.arguments.every((arg) => arg.type === "Identifier")) matches.push(node); + else { + const [method, params, session] = node.arguments; + if (method.type === "Identifier" && session.type === "Identifier" && params.type === "CallExpression" && + code.slice(params.callee.start, params.callee.end) === `globalThis.${MARKER}` && + params.arguments.length === 2 && params.arguments[0].name === method.name && params.arguments[1].type === "Identifier") guarded.push(node); + } + } + for (const value of Object.values(node)) { + if (Array.isArray(value)) value.forEach((child) => walk(child, inForwarder)); + else if (value?.type) walk(value, inForwarder); + } } - + walk(ast); + if (code.includes(MARKER)) return { status: code.includes(GUARD_DEF) && guarded.length === 1 && matches.length === 0 ? "already-patched" : "unexpected-shape", source: code }; + if (matches.length > 1) return { status: "unexpected-shape", source: code }; let forwarded = null; - if (code.includes(ANCHOR)) { - forwarded = code.replace(ANCHOR, REPLACEMENT); - } else { - forwarded = code.replace( - DYNAMIC_ANCHOR_RE, - (match, timeoutFn, webContents, method, params, sessionId, timeout) => - `return await ${timeoutFn}(${webContents}.webContents.debugger.sendCommand(` + - `${method},globalThis.${MARKER}(${method},${params}),${sessionId}),${timeout},`, - ); - if (forwarded === code) forwarded = null; + if (matches.length === 1) { + const [method, params] = matches[0].arguments; + const replacement = `globalThis.${MARKER}(${code.slice(method.start, method.end)},${code.slice(params.start, params.end)})`; + forwarded = code.slice(0, params.start) + replacement + code.slice(params.end); } if (forwarded == null) { @@ -108,10 +119,10 @@ function main() { ["mac-arm64", "mac-x64", "win"].includes(a), ); - const bundles = locateBundles({ - dir: "build", - pattern: /^main-.*\.js$/, + const bundles = locateBuildFeatureBundles({ platform, + label: "CDP screenshot", + match: code => code.includes("sendDebuggerCommand") && code.includes("Page.captureScreenshot") && code.includes("captureBeyondViewport"), }); if (bundles.length === 0) { diff --git a/scripts/patch-codex-home-env.js b/scripts/patch-codex-home-env.js index c16c2508..28023fb6 100644 --- a/scripts/patch-codex-home-env.js +++ b/scripts/patch-codex-home-env.js @@ -10,6 +10,7 @@ */ const fs = require("fs"); const path = require("path"); +const { parse } = require("acorn"); const { SRC_DIR } = require("./patch-util"); const args = process.argv.slice(2); @@ -28,10 +29,6 @@ const LEGACY_NEW = // 新版上游会把 resolved Codex home 作为 codexHome 参数传入启动函数。 // 函数体一开始补写 process.env.CODEX_HOME,后续 spawn/import 的子进程即可继承。 -const NATIVE_PIPE_START_RE = - /(function\s+\w+\(\{codexHome:([A-Za-z_$][\w$]*)=[\s\S]{0,500}?startServer:[A-Za-z_$][\w$]*=[A-Za-z_$][\w$]*\}\)\{)(?!process\.env\.CODEX_HOME\?\?=)/g; -const NATIVE_PIPE_PATCHED_RE = - /function\s+\w+\(\{codexHome:([A-Za-z_$][\w$]*)=[\s\S]{0,500}?startServer:[A-Za-z_$][\w$]*=[A-Za-z_$][\w$]*\}\)\{process\.env\.CODEX_HOME\?\?=\1;/; function countLiteral(src, needle) { return src.split(needle).length - 1; @@ -41,10 +38,6 @@ function patchSource(src, file) { if (src.includes(LEGACY_NEW)) { return { matched: true, changed: false, source: src, label: "legacy bootstrap already patched" }; } - if (NATIVE_PIPE_PATCHED_RE.test(src)) { - return { matched: true, changed: false, source: src, label: "native-pipe bootstrap already patched" }; - } - const legacyCount = countLiteral(src, LEGACY_OLD); if (legacyCount > 0) { if (legacyCount !== 1) { @@ -58,18 +51,36 @@ function patchSource(src, file) { }; } - const matches = [...src.matchAll(NATIVE_PIPE_START_RE)]; + // 新版 Webpack 会将工厂内联为匿名函数;按参数契约识别,不能依赖压缩后的函数名。 + const matches = []; + function visit(node) { + if (!node || typeof node !== "object") return; + if (["FunctionDeclaration", "FunctionExpression"].includes(node.type) && node.params.length === 1 && node.params[0].type === "ObjectPattern") { + const props = Object.fromEntries(node.params[0].properties.filter(p => p.type === "Property").map(p => [p.key.name, p.value])); + const home = props.codexHome; + if (home?.type === "AssignmentPattern" && home.left.type === "Identifier" && ["codexCliPath", "platform", "startServer"].every(key => props[key])) { + const body = src.slice(node.body.start + 1, node.body.end - 1); + if (!body.includes("windowsHelperPath") || !body.includes("windowsHelperTransportModulePath") || !body.includes("codexHome:")) throw new Error(`Unknown native-pipe startup contract in ${file}`); + matches.push({ node, home: home.left.name }); + } + } + for (const value of Object.values(node)) { + if (Array.isArray(value)) value.forEach(visit); + else if (value?.type) visit(value); + } + } + visit(parse(src, { ecmaVersion: "latest", sourceType: "module" })); if (matches.length > 0) { if (matches.length !== 1) { throw new Error(`Expected one native-pipe Codex home startup marker in ${file}, found ${matches.length}`); } - NATIVE_PIPE_START_RE.lastIndex = 0; + const { node, home } = matches[0]; + const injection = `process.env.CODEX_HOME??=${home};`; + if (src.slice(node.body.start + 1).startsWith(injection)) return { matched: true, changed: false, source: src, label: "native-pipe bootstrap already patched" }; return { matched: true, changed: true, - source: src.replace(NATIVE_PIPE_START_RE, (_match, prefix, codexHomeVar) => { - return `${prefix}process.env.CODEX_HOME??=${codexHomeVar};`; - }), + source: src.slice(0, node.body.start + 1) + injection + src.slice(node.body.start + 1), label: "native-pipe bootstrap", }; } @@ -115,4 +126,5 @@ function main() { console.log(check ? `[check] ${changed} file(s) need patching` : `[done] ${changed} file(s) patched`); } -main(); +if (require.main === module) main(); +module.exports = { patchSource }; diff --git a/scripts/patch-copyright.js b/scripts/patch-copyright.js index 9b21287c..827fe385 100644 --- a/scripts/patch-copyright.js +++ b/scripts/patch-copyright.js @@ -11,7 +11,7 @@ const fs = require("fs"); const path = require("path"); const { parse } = require("acorn"); -const { locateBundles, relPath } = require("./patch-util"); +const { locateBuildFeatureBundles, relPath } = require("./patch-util"); // ────────────────────────────────────────────── // Config @@ -88,15 +88,16 @@ function collectPatches(ast, source) { }); // 26.803 起 About 面板改成自定义 HTML,不再调用 setAboutPanelOptions。 - let offset = 0; - while ((offset = source.indexOf(OLD_COPYRIGHT_HTML, offset)) !== -1) { + const htmlPattern = /