Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(desktop): split app.asar into a shell + signed OTA-able core (reload / relaunch / rollback) (#19501)

Innei070c7f8aba1b
diff --git a/.github/actions/desktop-cleanup-s3/action.yml b/.github/actions/desktop-cleanup-s3/action.yml
index c5e6f4f3c1a..60a34d76d5d 100644
--- a/.github/actions/desktop-cleanup-s3/action.yml
+++ b/.github/actions/desktop-cleanup-s3/action.yml
@@ -60,6 +60,7 @@ runs:
| grep 'PRE ' \
| awk '{print $2}' \
| sed 's|/$||' \
+ | { grep -vx 'core' || true; } \
| sort -V)
if [ -z "$all_versions" ]; then
diff --git a/.github/actions/desktop-core-seq/action.yml b/.github/actions/desktop-core-seq/action.yml
new file mode 100644
index 00000000000..5be2adf6b26
--- /dev/null
+++ b/.github/actions/desktop-core-seq/action.yml
@@ -0,0 +1,52 @@
+name: Desktop Core Seq
+description: Resolve the next core seq (max over every platform's published latest.json + 1) so a new core always outranks published ones
+
+inputs:
+ channel:
+ description: 'Update channel'
+ required: true
+ update-server-url:
+ description: 'Update server URL (with or without channel suffix)'
+ required: true
+
+outputs:
+ seq:
+ description: 'Next core seq'
+ value: ${{ steps.seq.outputs.seq }}
+ feed-base-url:
+ description: 'Update server URL without the channel suffix'
+ value: ${{ steps.seq.outputs.feed_base_url }}
+
+runs:
+ using: composite
+ steps:
+ - name: Resolve next core seq
+ id: seq
+ shell: bash
+ env:
+ CHANNEL: ${{ inputs.channel }}
+ UPDATE_SERVER_URL: ${{ inputs.update-server-url }}
+ run: |
+ set -euo pipefail
+ BASE="${UPDATE_SERVER_URL%/}"
+ case "$BASE" in
+ */stable|*/nightly|*/canary|*/beta) BASE="${BASE%/*}" ;;
+ esac
+ MAX_SEQ=-1
+ for p in darwin win32 linux; do
+ HTTP_STATUS=$(curl -sS --connect-timeout 10 --max-time 30 \
+ -o "$RUNNER_TEMP/latest-$p.json" -w '%{http_code}' "$BASE/$CHANNEL/core/$p/latest.json")
+ case "$HTTP_STATUS" in
+ 200) SEQ=$(jq -er '.seq | select(type == "number")' "$RUNNER_TEMP/latest-$p.json") ;;
+ 404) SEQ=-1 ;;
+ *) echo "::error::$p latest.json fetch failed: HTTP $HTTP_STATUS"; exit 1 ;;
+ esac
+ echo "$p latest seq: $SEQ"
+ if [ "$SEQ" -gt "$MAX_SEQ" ]; then MAX_SEQ=$SEQ; fi
+ done
+ NEXT=$((MAX_SEQ + 1))
+ echo "Next core seq: $NEXT"
+ {
+ echo "seq=$NEXT"
+ echo "feed_base_url=$BASE"
+ } >> "$GITHUB_OUTPUT"
diff --git a/.github/actions/desktop-ota-diagnostics/action.yml b/.github/actions/desktop-ota-diagnostics/action.yml
index 3f471493dc7..ea2033b4e12 100644
--- a/.github/actions/desktop-ota-diagnostics/action.yml
+++ b/.github/actions/desktop-ota-diagnostics/action.yml
@@ -2,8 +2,8 @@ name: Desktop OTA Diagnostics
description: Preserve compatibility inputs and explicit build/publication outcomes, including failures
inputs:
kind:
- description: patch, build or release
- default: patch
+ description: gate, core-build, core-publish, build or release
+ default: gate
channel:
description: Desktop update channel
required: true
@@ -13,9 +13,13 @@ inputs:
job-status:
description: Caller job status before diagnostics
required: true
+ suffix:
+ description: Extra artifact-name segment for matrix legs sharing job id, os and arch
+ required: false
+ default: ''
outputs:
published:
- description: Whether the renderer patch was published
+ description: Whether a core release was published
value: ${{ steps.report.outputs.published }}
reason:
description: Publication or skip reason
@@ -24,7 +28,7 @@ outputs:
description: Whether compatibility requires a full release
value: ${{ steps.report.outputs.requires_full_release }}
version:
- description: Published renderer patch version
+ description: Published core version
value: ${{ steps.report.outputs.version }}
runs:
using: composite
@@ -43,17 +47,13 @@ runs:
if: always()
uses: actions/upload-artifact@v6
with:
- name: renderer-ota-diagnostics-${{ github.job }}-${{ runner.os }}-${{ runner.arch }}-${{ github.run_attempt }}
+ name: desktop-ota-diagnostics-${{ github.job }}-${{ runner.os }}-${{ runner.arch }}${{ inputs.suffix && format('-{0}', inputs.suffix) || '' }}-${{ github.run_attempt }}
if-no-files-found: warn
retention-days: 14
path: |
- renderer-ota-diagnostics/
- apps/desktop/release/renderer-mainhash-inputs.json
- apps/desktop/release/renderer-mainhash.txt
- apps/desktop/release/renderer-mainhash/
- release/renderer-mainhash-inputs.json
- release/renderer-mainhash.txt
- release/renderer-mainhash/
- ${{ runner.temp }}/renderer-base.json
- ${{ runner.temp }}/base-mainhash-inputs.json
- ${{ runner.temp }}/renderer-mainhash-diff.txt
+ desktop-ota-diagnostics/
+ apps/desktop/release/core-ota/core/*/latest.json
+ release/core-ota/core/*/latest.json
+ release/shell.json
+ ${{ runner.temp }}/shell.json
+ ${{ runner.temp }}/previous-core.json
diff --git a/.github/actions/desktop-publish-core-ota/action.yml b/.github/actions/desktop-publish-core-ota/action.yml
new file mode 100644
index 00000000000..ed5dd50381a
--- /dev/null
+++ b/.github/actions/desktop-publish-core-ota/action.yml
@@ -0,0 +1,135 @@
+name: Desktop Publish Core OTA
+description: Upload a buildCore.mjs output tree (cas + core/<platform>) to the update server
+
+inputs:
+ channel:
+ description: 'Update channel (stable, beta, canary)'
+ required: true
+ release-dir:
+ description: 'Directory produced by buildCore.mjs --out'
+ required: true
+ shell-json:
+ description: 'Optional path to a shell.json to publish as <channel>/shell.json before latest.json'
+ required: false
+ default: ''
+ aws-access-key-id:
+ description: 'AWS access key ID'
+ required: true
+ aws-secret-access-key:
+ description: 'AWS secret access key'
+ required: true
+ s3-bucket:
+ description: 'S3 bucket name'
+ required: true
+ s3-region:
+ description: 'S3 region (defaults to us-east-1)'
+ required: false
+ default: 'us-east-1'
+ s3-endpoint:
+ description: 'Custom S3 endpoint (for R2/MinIO etc.)'
+ required: false
+ default: ''
+
+outputs:
+ published:
+ description: 'Whether latest.json was uploaded for at least one platform'
+ value: ${{ steps.upload.outputs.published }}
+ platforms:
+ description: 'Space-separated platforms published'
+ value: ${{ steps.upload.outputs.platforms }}
+
+runs:
+ using: composite
+ steps:
+ - name: Upload core release to S3
+ id: upload
+ shell: bash
+ env:
+ AWS_ACCESS_KEY_ID: ${{ inputs.aws-access-key-id }}
+ AWS_SECRET_ACCESS_KEY: ${{ inputs.aws-secret-access-key }}
+ AWS_REGION: ${{ inputs.s3-region }}
+ S3_BUCKET: ${{ inputs.s3-bucket }}
+ S3_ENDPOINT: ${{ inputs.s3-endpoint }}
+ CHANNEL: ${{ inputs.channel }}
+ RELEASE_DIR: ${{ inputs.release-dir }}
+ SHELL_JSON: ${{ inputs.shell-json }}
+ run: |
+ set -euo pipefail
+ echo "published=false" >> "$GITHUB_OUTPUT"
+ echo "platforms=" >> "$GITHUB_OUTPUT"
+ if [ -z "$S3_BUCKET" ]; then
+ echo "⚠️ S3 bucket is not configured, skipping core OTA upload"
+ exit 0
+ fi
+ ENDPOINT_ARGS=()
+ if [ -n "$S3_ENDPOINT" ]; then
+ ENDPOINT_ARGS=(--endpoint-url "$S3_ENDPOINT")
+ fi
+ IMMUTABLE=(--cache-control "public,max-age=31536000,immutable")
+
+ # seq is allocated as max(published)+1 without a lock, so a concurrent publisher for the
+ # same channel may have landed first. Same seq + same version is a re-run and allowed.
+ assert_not_behind() {
+ local platform=$1
+ local key="$CHANNEL/core/$platform/latest.json"
+ aws s3 ls "s3://$S3_BUCKET/$key" "${ENDPOINT_ARGS[@]}" >/dev/null 2>&1 || return 0
+ local remote local_json remote_seq remote_version local_seq local_version
+ remote=$(aws s3 cp "s3://$S3_BUCKET/$key" - "${ENDPOINT_ARGS[@]}")
+ local_json="$RELEASE_DIR/core/$platform/latest.json"
+ remote_seq=$(jq -r '.seq // -1' <<<"$remote")
+ remote_version=$(jq -r '.version' <<<"$remote")
+ local_seq=$(jq -r '.seq' "$local_json")
+ local_version=$(jq -r '.version' "$local_json")
+ if [ "$remote_seq" -gt "$local_seq" ] || { [ "$remote_seq" -eq "$local_seq" ] && [ "$remote_version" != "$local_version" ]; }; then
+ echo "::error::$key already at seq $remote_seq ($remote_version); refusing to publish seq $local_seq ($local_version)"
+ exit 1
+ fi
+ }
+
+ for platform_dir in "$RELEASE_DIR"/core/*/; do
+ [ -d "$platform_dir" ] || continue
+ assert_not_behind "$(basename "$platform_dir")"
+ done
+
+ # Order matters for clients mid-download: objects → packs → snapshot → shell.json → latest.json.
+ if [ -d "$RELEASE_DIR/cas" ]; then
+ echo "📦 Syncing CAS objects"
+ aws s3 sync "$RELEASE_DIR/cas" "s3://$S3_BUCKET/cas" --size-only \
+ --content-type application/zstd "${IMMUTABLE[@]}" "${ENDPOINT_ARGS[@]}"
+ fi
+
+ PLATFORMS=""
+ for platform_dir in "$RELEASE_DIR"/core/*/; do
+ [ -d "$platform_dir" ] || continue
+ platform=$(basename "$platform_dir")
+ target="s3://$S3_BUCKET/$CHANNEL/core/$platform"
+ version=$(jq -r '.version' "$platform_dir/latest.json")
+ echo "🚀 $platform: core $version → $target"
+ if [ -d "$platform_dir/packs" ]; then
+ aws s3 sync "$platform_dir/packs" "$target/packs" --size-only \
+ --content-type application/zip "${IMMUTABLE[@]}" "${ENDPOINT_ARGS[@]}"
+ fi
+ aws s3 cp "$platform_dir/versions/$version.json" "$target/versions/$version.json" \
+ --content-type application/json --cache-control no-store "${ENDPOINT_ARGS[@]}"
+ PLATFORMS="$PLATFORMS $platform"
+ done
+
+ if [ -n "$SHELL_JSON" ]; then
+ echo "📋 Publishing $CHANNEL/shell.json: $(cat "$SHELL_JSON")"
+ aws s3 cp "$SHELL_JSON" "s3://$S3_BUCKET/$CHANNEL/shell.json" \
+ --content-type application/json --cache-control no-store "${ENDPOINT_ARGS[@]}"
+ fi
+
+ for platform in $PLATFORMS; do
+ assert_not_behind "$platform"
+ aws s3 cp "$RELEASE_DIR/core/$platform/latest.json" "s3://$S3_BUCKET/$CHANNEL/core/$platform/latest.json" \
+ --content-type application/json --cache-control no-store "${ENDPOINT_ARGS[@]}"
+ done
+
+ if [ -n "$PLATFORMS" ]; then
+ echo "published=true" >> "$GITHUB_OUTPUT"
+ echo "platforms=${PLATFORMS# }" >> "$GITHUB_OUTPUT"
+ echo "✅ Published core for:$PLATFORMS"
+ else
+ echo "⚠️ No core/<platform> directories found under $RELEASE_DIR"
+ fi
diff --git a/.github/actions/desktop-publish-s3/action.yml b/.github/actions/desktop-publish-s3/action.yml
index 83e7ec424ac..edd77d71a30 100644
--- a/.github/actions/desktop-publish-s3/action.yml
+++ b/.github/actions/desktop-publish-s3/action.yml
@@ -53,20 +53,58 @@ runs:
echo ""
echo "📋 Version: ${{ inputs.version }}, Channel: ${{ inputs.channel }}"
- - name: Setup Node.js for renderer validation
- id: setup
- uses: actions/setup-node@v6
+ - name: Download r0 core releases
+ uses: actions/download-artifact@v7
with:
- node-version: ${{ env.NODE_VERSION }}
- package-manager-cache: false
+ path: release/core-r0
+ pattern: core-r0-*
- - name: Validate renderer OTA baseline before publishing
- id: validate
+ - name: Merge r0 cores and compose shell.json
+ id: shell
shell: bash
env:
- CHANNEL: ${{ inputs.channel }}
VERSION: ${{ inputs.version }}
- run: node apps/desktop/scripts/validateMainHash.mjs --base release "$CHANNEL" "$VERSION"
+ run: |
+ set -euo pipefail
+ ls release/core-r0
+ mkdir -p release/core-ota
+ SHELL_ABI=""
+ # Same-platform builds from different runners (mac arm64/x64) must produce identical trees.
+ for dir in release/core-r0/*/; do
+ for latest in "$dir"core/*/latest.json; do
+ platform=$(basename "$(dirname "$latest")")
+ [ "$(jq -r '.version' "$latest")" = "$VERSION" ] || { echo "::error::core version in $latest is not $VERSION"; exit 1; }
+ abi=$(jq -er '.shellAbi' "$latest")
+ [ -z "$SHELL_ABI" ] && SHELL_ABI="$abi"
+ [ "$abi" = "$SHELL_ABI" ] || { echo "::error::shellAbi differs across platforms ($latest)"; exit 1; }
+ if [ -f "release/core-ota/core/$platform/latest.json" ]; then
+ # A mismatch only costs delta efficiency for some clients (they fall back to objects/full pack); keep the first tree.
+ diff <(jq -S '.tree' "release/core-ota/core/$platform/latest.json") <(jq -S '.tree' "$latest") \
+ || echo "::warning::$platform core trees differ between runners; keeping the first"
+ continue
+ fi
+ mkdir -p release/core-ota/cas release/core-ota/core
+ if [ -d "$dir"cas ]; then cp -R "$dir"cas/. release/core-ota/cas/; fi
+ cp -R "$dir"core/"$platform" release/core-ota/core/
+ done
+ done
+ [ -n "$SHELL_ABI" ] || { echo "::error::no r0 core artifacts found"; exit 1; }
+ jq -n --arg shellAbi "$SHELL_ABI" --arg shellVersion "$VERSION" --arg publishedAt "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
+ '{shellAbi: $shellAbi, shellVersion: $shellVersion, publishedAt: $publishedAt}' > release/shell.json
+ cat release/shell.json
+
+ - name: Publish shell.json and r0 core
+ id: base
+ uses: ./.github/actions/desktop-publish-core-ota
+ with:
+ channel: ${{ inputs.channel }}
+ release-dir: release/core-ota
+ shell-json: release/shell.json
+ aws-access-key-id: ${{ inputs.aws-access-key-id }}
+ aws-secret-access-key: ${{ inputs.aws-secret-access-key }}
+ s3-bucket: ${{ inputs.s3-bucket }}
+ s3-region: ${{ inputs.s3-region }}
+ s3-endpoint: ${{ inputs.s3-endpoint }}
- name: Upload to S3
id: installers
@@ -158,71 +196,6 @@ runs:
echo "📋 Files in s3://$S3_BUCKET/$CHANNEL/$VERSION/:"
aws s3 ls "s3://$S3_BUCKET/$CHANNEL/$VERSION/" $ENDPOINT_ARG || true
- - name: Publish renderer OTA base marker
- id: base
- shell: bash
- env:
- AWS_ACCESS_KEY_ID: ${{ inputs.aws-access-key-id }}
- AWS_SECRET_ACCESS_KEY: ${{ inputs.aws-secret-access-key }}
- AWS_REGION: ${{ inputs.s3-region }}
- S3_BUCKET: ${{ inputs.s3-bucket }}
- S3_ENDPOINT: ${{ inputs.s3-endpoint }}
- CHANNEL: ${{ inputs.channel }}
- CLOUD_REF: ${{ inputs.cloud-ref }}
- VERSION: ${{ inputs.version }}
- run: |
- set -euo pipefail
-
- if [ -z "$S3_BUCKET" ]; then
- echo "S3 bucket not configured, skipping renderer OTA marker"
- echo "reason=upload-not-configured" >> "$GITHUB_OUTPUT"
- exit 0
- fi
-
- ENDPOINT_ARG=""
- if [ -n "$S3_ENDPOINT" ]; then
- ENDPOINT_ARG="--endpoint-url $S3_ENDPOINT"
- fi
-
- MAIN_HASH=$(cat release/renderer-mainhash.txt)
- if [[ ! "$MAIN_HASH" =~ ^[0-9a-f]{64}$ ]] || [[ ! "$CLOUD_REF" =~ ^[0-9a-f]{40}$ ]]; then
- echo "Invalid renderer OTA base metadata"
- exit 1
- fi
-
- echo "renderer OTA base mainHash: $MAIN_HASH"
- jq -n \
- --arg cloudRef "$CLOUD_REF" \
- --arg mainHash "$MAIN_HASH" \
- --arg version "$VERSION" \
- '{ cloudRef: $cloudRef, mainHash: $mainHash, rendererProtocol: 2, version: $version }' \
- > /tmp/renderer-ota-base.json
-
- RENDERER_ROOT="release/renderer-ota/$CHANNEL/$VERSION/renderer/v2"
- LATEST="$RENDERER_ROOT/latest.json"
- SNAPSHOT="$RENDERER_ROOT/versions/r0.json"
- if [ ! -d "$RENDERER_ROOT/packs" ] || [ ! -f "$LATEST" ] || [ ! -f "$SNAPSHOT" ]; then
- echo "Renderer OTA r0 artifacts are incomplete"
- exit 1
- fi
-
- S3_RENDERER_ROOT="s3://$S3_BUCKET/$CHANNEL/$VERSION/renderer/v2"
- aws s3 sync "$RENDERER_ROOT/packs" "$S3_RENDERER_ROOT/packs" \
- --size-only \
- --content-type application/zip \
- --cache-control public,max-age=31536000,immutable \
- $ENDPOINT_ARG
- aws s3 cp "$SNAPSHOT" "$S3_RENDERER_ROOT/versions/r0.json" \
- --cache-control no-store $ENDPOINT_ARG
- aws s3 cp "$LATEST" "$S3_RENDERER_ROOT/latest.json" \
- --cache-control no-store $ENDPOINT_ARG
- aws s3 cp release/renderer-mainhash-inputs.json "$S3_RENDERER_ROOT/mainhash-inputs.json" \
- --cache-control no-store $ENDPOINT_ARG
- aws s3 cp /tmp/renderer-ota-base.json "s3://$S3_BUCKET/$CHANNEL/base.json" \
- --cache-control no-store $ENDPOINT_ARG
- echo "Published renderer OTA r0 for $CHANNEL/$VERSION"
- echo "published=true" >> "$GITHUB_OUTPUT"
-
- name: Preserve release publication diagnostics
if: always()
uses: ./.github/actions/desktop-ota-diagnostics
diff --git a/.github/actions/desktop-upload-artifacts/action.yml b/.github/actions/desktop-upload-artifacts/action.yml
index f1a9bd0f289..b56f14360ed 100644
--- a/.github/actions/desktop-upload-artifacts/action.yml
+++ b/.github/actions/desktop-upload-artifacts/action.yml
@@ -9,60 +9,18 @@ inputs:
description: Number of days to retain artifacts
required: false
default: '5'
- renderer-ota-public-key:
- description: Public key embedded in the packaged binary
- required: true
- renderer-ota-private-key:
- description: Private key used to sign the r0 renderer OTA baseline
+ update-server-url:
+ description: Update server URL; with core-signing-key, also builds the r0 core release from core-dist
required: false
default: ''
- update-channel:
- description: Desktop update channel (canary, beta, stable)
+ core-signing-key:
+ description: Ed25519 private key PEM used to sign the r0 core manifest
required: false
default: ''
runs:
using: composite
steps:
- - name: Validate renderer OTA base hash
- shell: bash
- run: |
- set -euo pipefail
- MAIN_HASH=$(cat apps/desktop/release/renderer-mainhash.txt)
- if [[ ! "$MAIN_HASH" =~ ^[0-9a-f]{64}$ ]]; then
- echo "Invalid renderer OTA main bundle hash"
- exit 1
- fi
- node --input-type=module <<'NODE'
- import { readFile, mkdir, writeFile } from 'node:fs/promises';
- import { validateInputManifest } from './apps/desktop/scripts/validateMainHash.mjs';
- const release = 'apps/desktop/release';
- const manifest = JSON.parse(await readFile(`${release}/renderer-mainhash-inputs.json`, 'utf8'));
- validateInputManifest(manifest);
- const embedded = (await readFile(`${release}/renderer-mainhash.txt`, 'utf8')).trim();
- if (embedded !== manifest.mainHash) throw new Error('Packaged hash differs from source inputs');
- await mkdir(`${release}/renderer-mainhash`, { recursive: true });
- await writeFile(`${release}/renderer-mainhash/${process.env.ARTIFACT_NAME}.json`, JSON.stringify(manifest, null, 2));
- NODE
- env:
- ARTIFACT_NAME: ${{ inputs.artifact-name }}
-
- - name: Sign renderer OTA r0 baseline
- if: runner.os == 'Linux' && inputs.renderer-ota-private-key != '' && inputs.update-channel != ''
- shell: bash
- env:
- RENDERER_OTA_PRIVATE_KEY: ${{ inputs.renderer-ota-private-key }}
- RENDERER_OTA_PUBLIC_KEY: ${{ inputs.renderer-ota-public-key }}
- run: |
- set -euo pipefail
- MAIN_HASH=$(cat apps/desktop/release/renderer-mainhash.txt)
- node apps/desktop/scripts/buildRendererManifest.mjs \
- --renderer=apps/desktop/dist/renderer \
- --out=apps/desktop/release/renderer-ota \
- --channel=${{ inputs.update-channel }} \
- --version=r0 \
- --mainHash="$MAIN_HASH"
-
- name: Rename macOS *-mac.yml for multi-architecture support
if: runner.os == 'macOS'
shell: bash
@@ -103,6 +61,38 @@ runs:
apps/desktop/release/*.snap*
apps/desktop/release/*.rpm*
apps/desktop/release/*.tar.gz*
- apps/desktop/release/renderer-mainhash/
- apps/desktop/release/renderer-ota
+ retention-days: ${{ inputs.retention-days }}
+
+ - name: Build r0 core release
+ id: core
+ if: inputs.update-server-url != '' && inputs.core-signing-key != ''
+ shell: bash
+ working-directory: apps/desktop
+ env:
+ RENDERER_OTA_PRIVATE_KEY: ${{ inputs.core-signing-key }}
+ UPDATE_SERVER_URL: ${{ inputs.update-server-url }}
+ run: |
+ set -euo pipefail
+ BASE="${UPDATE_SERVER_URL%/}"
+ case "$BASE" in
+ */stable|*/nightly|*/canary|*/beta) BASE="${BASE%/*}" ;;
+ esac
+ read -r PLATFORM CHANNEL VERSION SEQ SHELL_ABI < <(node -p "const m=require('./core-dist/manifest.json');[m.platform,m.channel,m.version,m.seq,m.shellAbi].join(' ')")
+ node scripts/buildCore.mjs \
+ --core=core-dist \
+ --platform="$PLATFORM" \
+ --channel="$CHANNEL" \
+ --version="$VERSION" \
+ --seq="$SEQ" \
+ --shell-abi="$SHELL_ABI" \
+ --objects-base-url="$BASE/cas" \
+ --out=release/core-ota
+ echo "platform=$PLATFORM" >> "$GITHUB_OUTPUT"
+
+ - name: Upload r0 core release
+ if: steps.core.outputs.platform != ''
+ uses: actions/upload-artifact@v6
+ with:
+ name: core-r0-${{ steps.core.outputs.platform }}-${{ runner.arch }}
+ path: apps/desktop/release/core-ota
retention-days: ${{ inputs.retention-days }}
diff --git a/.github/workflows/desktop-core-dry-run.yml b/.github/workflows/desktop-core-dry-run.yml
new file mode 100644
index 00000000000..01e8439880d
--- /dev/null
+++ b/.github/workflows/desktop-core-dry-run.yml
@@ -0,0 +1,62 @@
+name: Desktop Core Dry Run
+
+on:
+ workflow_dispatch:
+ inputs:
+ channel:
+ description: 'Update channel'
+ required: false
+ type: choice
+ options:
+ - canary
+ - beta
+ - stable
+ default: canary
+
+permissions: read-all
+
+env:
+ NODE_VERSION: '24.11.1'
+
+jobs:
+ build-core:
+ name: Build core (darwin)
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v6
+
+ - name: Setup environment
+ uses: ./.github/actions/setup-env
+ with:
+ node-version: ${{ env.NODE_VERSION }}
+
+ - name: Install deps
+ run: pnpm install
+
+ - name: Build core
+ run: npm_config_platform=darwin pnpm -C apps/desktop run build:main
+ env:
+ UPDATE_CHANNEL: ${{ inputs.channel }}
+ UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
+ RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
+ APP_URL: http://localhost:3015
+ DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
+ KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
+
+ - name: Build unsigned core manifest
+ working-directory: apps/desktop
+ env:
+ RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
+ UPDATE_CHANNEL: ${{ inputs.channel }}
+ run: |
+ set -euo pipefail
+ SHELL_ABI=$(node scripts/shellAbi.mjs)
+ VERSION=$(node -p "require('./package.json').version")
+ node scripts/buildCoreManifest.mjs --core=core-dist --platform=darwin --channel="$UPDATE_CHANNEL" --version="$VERSION" --seq=0 --shell-abi="$SHELL_ABI"
+
+ - name: Upload core
+ uses: actions/upload-artifact@v6
+ with:
+ name: core-darwin-dryrun
+ path: apps/desktop/core-dist
+ retention-days: 7
diff --git a/.github/workflows/release-desktop-beta.yml b/.github/workflows/release-desktop-beta.yml
index f888948b654..eed18cee9ba 100644
--- a/.github/workflows/release-desktop-beta.yml
+++ b/.github/workflows/release-desktop-beta.yml
@@ -71,15 +71,6 @@ jobs:
fi
echo "cloud_ref=$cloud_ref" >> "$GITHUB_OUTPUT"
- renderer-ota:
- name: Publish Renderer OTA
- needs: [check-beta]
- if: needs.check-beta.outputs.is_beta == 'true'
- uses: ./.github/workflows/release-desktop-renderer-ota.yml
- with:
- channel: beta
- secrets: inherit
-
test:
name: Code quality check
needs: [check-beta]
@@ -120,6 +111,13 @@ jobs:
cloud-token: ${{ secrets.LOBEHUB_CLOUD_TOKEN }}
node-version: ${{ env.NODE_VERSION }}
+ - name: Resolve core seq
+ id: core_seq
+ uses: ./.github/actions/desktop-core-seq
+ with:
+ channel: beta
+ update-server-url: ${{ secrets.UPDATE_SERVER_URL }}
+
- name: Set package version
id: app_version
run: npm run workflow:set-desktop-version ${{ needs.check-beta.outputs.version }} beta
@@ -143,6 +141,7 @@ jobs:
UPDATE_CHANNEL: beta
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
+ CORE_SEQ: ${{ steps.core_seq.outputs.seq }}
APP_URL: http://localhost:3015
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
@@ -164,6 +163,7 @@ jobs:
UPDATE_CHANNEL: beta
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
+ CORE_SEQ: ${{ steps.core_seq.outputs.seq }}
APP_URL: http://localhost:3015
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
@@ -181,6 +181,7 @@ jobs:
UPDATE_CHANNEL: beta
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
+ CORE_SEQ: ${{ steps.core_seq.outputs.seq }}
APP_URL: http://localhost:3015
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
@@ -192,9 +193,8 @@ jobs:
uses: ./.github/actions/desktop-upload-artifacts
with:
artifact-name: release-${{ matrix.os }}
- renderer-ota-private-key: ${{ secrets.RENDERER_OTA_PRIVATE_KEY }}
- renderer-ota-public-key: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
- update-channel: beta
+ update-server-url: ${{ secrets.UPDATE_SERVER_URL }}
+ core-signing-key: ${{ secrets.RENDERER_OTA_PRIVATE_KEY }}
- name: Preserve desktop build diagnostics
if: always()
@@ -239,9 +239,6 @@ jobs:
pattern: release-*
merge-multiple: true
- - name: Validate platform renderer hashes
- run: node apps/desktop/scripts/validateMainHash.mjs release release-macos-latest release-macos-15-intel release-windows-2025 release-ubuntu-latest
-
# 列出下载的构建产物
- name: List downloaded artifacts
run: ls -R release
@@ -309,9 +306,9 @@ jobs:
env:
GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
- publish-renderer-base:
+ publish-core-base:
needs: [check-beta, merge-mac-files]
- name: Publish Beta Renderer Base
+ name: Publish Beta Shell and Core r0
runs-on: ubuntu-latest
steps:
- uses: actions/create-github-app-token@v2
diff --git a/.github/workflows/release-desktop-canary.yml b/.github/workflows/release-desktop-canary.yml
index c1ec2a4997b..8db7fb95217 100644
--- a/.github/workflows/release-desktop-canary.yml
+++ b/.github/workflows/release-desktop-canary.yml
@@ -8,6 +8,10 @@ name: Release Desktop Canary
# (可带任意 gitmoji)
# 2. 手动触发 (workflow_dispatch)
#
+# core-only 优先:
+# 先跑 release-desktop-core-ota.yml;只有 shellAbi 变了 (requires_full_release)
+# 或 core 没有变化 (skipped) 或手动 force_full 时才走全量打包。
+#
# 并发策略:
# 运行中的发布不会被后续 push 取消;等待队列仅保留最新一次运行
#
@@ -28,6 +32,11 @@ on:
required: false
type: boolean
default: false
+ force_full:
+ description: 'Skip the core-only path and publish a full release'
+ required: false
+ type: boolean
+ default: false
concurrency:
group: ${{ github.workflow }}
@@ -83,22 +92,27 @@ jobs:
echo "⏭️ Commit type is not style/feat/fix/perf/refactor/release, skipping: $commit_msg"
fi
- renderer-ota:
- name: Publish Renderer OTA
+ # ============================================
+ # core-only 发布(壳未变时不打全量包)
+ # ============================================
+ core-ota:
+ name: Core OTA
needs: [check-trigger]
- if: needs.check-trigger.outputs.should_build == 'true'
- uses: ./.github/workflows/release-desktop-renderer-ota.yml
+ if: needs.check-trigger.outputs.should_build == 'true' && !inputs.force_full
+ uses: ./.github/workflows/release-desktop-core-ota.yml
+ secrets: inherit
with:
channel: canary
- secrets: inherit
# ============================================
- # OTA 无法覆盖当前 main 时,计算完整发布版本
+ # 计算版本号
# ============================================
calculate-version:
name: Calculate Canary Version
- needs: [check-trigger, renderer-ota]
- if: needs.check-trigger.outputs.should_build == 'true' && (github.event_name == 'workflow_dispatch' || needs.renderer-ota.outputs.requires_full_release == 'true')
+ needs: [check-trigger, core-ota]
+ if: |
+ always() && needs.check-trigger.outputs.should_build == 'true' &&
+ (inputs.force_full || needs.core-ota.outputs.requires_full_release == 'true' || needs.core-ota.outputs.skipped == 'true')
runs-on: ubuntu-latest
outputs:
cloud_ref: ${{ steps.cloud-ref.outputs.cloud_ref }}
@@ -267,6 +281,13 @@ jobs:
cloud-token: ${{ secrets.LOBEHUB_CLOUD_TOKEN }}
node-version: ${{ env.NODE_VERSION }}
+ - name: Resolve core seq
+ id: core_seq
+ uses: ./.github/actions/desktop-core-seq
+ with:
+ channel: canary
+ update-server-url: ${{ secrets.UPDATE_SERVER_URL }}
+
- name: Set package version
id: app_version
run: npm run workflow:set-desktop-version ${{ needs.calculate-version.outputs.version }} canary
@@ -298,6 +319,7 @@ jobs:
UPDATE_CHANNEL: canary
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
+ CORE_SEQ: ${{ steps.core_seq.outputs.seq }}
RELEASE_NOTES: ${{ needs.calculate-version.outputs.release_notes }}
APP_URL: http://localhost:3015
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
@@ -320,6 +342,7 @@ jobs:
UPDATE_CHANNEL: canary
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
+ CORE_SEQ: ${{ steps.core_seq.outputs.seq }}
RELEASE_NOTES: ${{ needs.calculate-version.outputs.release_notes }}
APP_URL: http://localhost:3015
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
@@ -338,6 +361,7 @@ jobs:
UPDATE_CHANNEL: canary
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
+ CORE_SEQ: ${{ steps.core_seq.outputs.seq }}
RELEASE_NOTES: ${{ needs.calculate-version.outputs.release_notes }}
APP_URL: http://localhost:3015
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
@@ -367,10 +391,9 @@ jobs:
uses: ./.github/actions/desktop-upload-artifacts
with:
artifact-name: release-${{ matrix.os }}
- renderer-ota-private-key: ${{ secrets.RENDERER_OTA_PRIVATE_KEY }}
- renderer-ota-public-key: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
+ update-server-url: ${{ secrets.UPDATE_SERVER_URL }}
+ core-signing-key: ${{ secrets.RENDERER_OTA_PRIVATE_KEY }}
retention-days: 3
- update-channel: canary
- name: Preserve desktop build diagnostics
if: always()
@@ -406,9 +429,6 @@ jobs:
pattern: release-*
merge-multiple: true
- - name: Validate platform renderer hashes
- run: node apps/desktop/scripts/validateMainHash.mjs release release-macos-15 release-macos-15-intel release-windows-2025 release-ubuntu-latest
-
- name: List downloaded artifacts
run: ls -R release
diff --git a/.github/workflows/release-desktop-core-ota.yml b/.github/workflows/release-desktop-core-ota.yml
new file mode 100644
index 00000000000..597ab69b109
--- /dev/null
+++ b/.github/workflows/release-desktop-core-ota.yml
@@ -0,0 +1,360 @@
+name: Release Desktop Core OTA
+
+# ============================================
+# core-only 发布(壳不变,只发 main/preload/renderer/cli)
+# ============================================
+# 门禁: HEAD 的 shellAbi 必须等于 <channel>/shell.json 的 shellAbi,
+# 否则 requires_full_release=true,由调用方走全量发版。
+# 产物: cas/objects/<sha>.zst, cas/patches/<from>-<to>.zst 跨平台共享,immutable
+# <channel>/core/<platform>/packs/<sha>.zip 全量 zip(fallback)
+# <channel>/core/<platform>/versions/<version>.json 签名快照
+# <channel>/core/<platform>/latest.json 签名 manifest(no-store)
+# ============================================
+
+on:
+ workflow_call:
+ inputs:
+ channel:
+ description: 'Update channel'
+ required: true
+ type: string
+ rollout:
+ description: 'Rollout ratio 0-1'
+ required: false
+ type: string
+ default: '1'
+ outputs:
+ requires_full_release:
+ description: 'Whether the caller must publish a full desktop release'
+ value: ${{ jobs.gate.outputs.requires_full_release }}
+ skipped:
+ description: 'Whether every platform produced an empty release'
+ value: ${{ jobs.publish.outputs.skipped }}
+ published:
+ description: 'Whether a core release was uploaded'
+ value: ${{ jobs.publish.outputs.published }}
+ version:
+ description: 'Published core version'
+ value: ${{ jobs.gate.outputs.version }}
+ workflow_dispatch:
+ inputs:
+ channel:
+ description: 'Update channel'
+ required: true
+ type: choice
+ options:
+ - canary
+ - beta
+ - stable
+ default: canary
+ rollout:
+ description: 'Rollout ratio 0-1'
+ required: false
+ type: string
+ default: '1'
+
+concurrency:
+ group: desktop-core-ota-${{ inputs.channel }}
+ cancel-in-progress: false
+
+permissions: read-all
+
+env:
+ NODE_VERSION: '24.11.1'
+
+jobs:
+ gate:
+ name: Shell ABI gate (${{ inputs.channel }})
+ runs-on: ubuntu-latest
+ outputs:
+ app_version: ${{ steps.base.outputs.app_version }}
+ cloud_ref: ${{ steps.cloud-ref.outputs.cloud_ref }}
+ feed_base_url: ${{ steps.server.outputs.feed_base_url }}
+ requires_full_release: ${{ steps.gate.outputs.requires_full_release }}
+ seq: ${{ steps.version.outputs.seq }}
+ shell_abi: ${{ steps.gate.outputs.shell_abi }}
+ version: ${{ steps.version.outputs.version }}
+ steps:
+ - uses: actions/checkout@v7
+ id: checkout
+
+ - name: Resolve update server base URL
+ id: server
+ env:
+ UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
+ run: |
+ set -euo pipefail
+ BASE="${UPDATE_SERVER_URL%/}"
+ case "$BASE" in
+ */stable|*/nightly|*/canary|*/beta) BASE="${BASE%/*}" ;;
+ esac
+ echo "feed_base_url=$BASE" >> "$GITHUB_OUTPUT"
+
+ - name: Load shipped shell
+ id: base
+ env:
+ CHANNEL: ${{ inputs.channel }}
+ FEED_BASE_URL: ${{ steps.server.outputs.feed_base_url }}
+ run: |
+ set -euo pipefail
+ HTTP_STATUS=$(curl -sS --connect-timeout 10 --max-time 30 \
+ -o "$RUNNER_TEMP/shell.json" -w '%{http_code}' "$FEED_BASE_URL/$CHANNEL/shell.json")
+ echo "shell.json HTTP status: $HTTP_STATUS"
+ if [ "$HTTP_STATUS" = "404" ]; then
+ echo "::warning::no shell.json for $CHANNEL; run a full release first"
+ echo "found=false" >> "$GITHUB_OUTPUT"
+ echo "reason=base-missing" >> "$GITHUB_OUTPUT"
+ exit 0
+ fi
+ if [ "$HTTP_STATUS" != "200" ]; then
+ echo "::error::shell.json fetch failed: HTTP $HTTP_STATUS"
+ echo "reason=base-invalid" >> "$GITHUB_OUTPUT"
+ exit 1
+ fi
+ SHELL_ABI=$(jq -er '.shellAbi | select(type == "string" and test("^[0-9a-f]{64}$"))' "$RUNNER_TEMP/shell.json")
+ APP_VERSION=$(jq -er '.shellVersion | select(type == "string" and test("^[0-9A-Za-z.+-]+$"))' "$RUNNER_TEMP/shell.json")
+ {
+ echo "found=true"
+ echo "reason=base-found"
+ echo "shell_abi=$SHELL_ABI"
+ echo "app_version=$APP_VERSION"
+ } >> "$GITHUB_OUTPUT"
+
+ - name: Gate on shellAbi
+ id: gate
+ env:
+ BASE_SHELL_ABI: ${{ steps.base.outputs.shell_abi }}
+ FOUND: ${{ steps.base.outputs.found }}
+ RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
+ run: |
+ set -euo pipefail
+ SHELL_ABI=$(node apps/desktop/scripts/shellAbi.mjs)
+ echo "shell_abi=$SHELL_ABI" >> "$GITHUB_OUTPUT"
+ echo "HEAD shellAbi: $SHELL_ABI"
+ echo "Shipped shellAbi: ${BASE_SHELL_ABI:-<none>}"
+ if [ "$FOUND" != "true" ] || [ "$SHELL_ABI" != "$BASE_SHELL_ABI" ]; then
+ echo "::warning::shell changed since last full release — core-only release is not allowed"
+ echo "allowed=false" >> "$GITHUB_OUTPUT"
+ echo "reason=abi-changed" >> "$GITHUB_OUTPUT"
+ echo "requires_full_release=true" >> "$GITHUB_OUTPUT"
+ else
+ echo "allowed=true" >> "$GITHUB_OUTPUT"
+ echo "requires_full_release=false" >> "$GITHUB_OUTPUT"
+ fi
+
+ - name: Resolve next core seq
+ id: seq
+ if: steps.gate.outputs.allowed == 'true'
+ uses: ./.github/actions/desktop-core-seq
+ with:
+ channel: ${{ inputs.channel }}
+ update-server-url: ${{ secrets.UPDATE_SERVER_URL }}
+
+ - name: Determine core version
+ id: version
+ if: steps.gate.outputs.allowed == 'true'
+ env:
+ APP_VERSION: ${{ steps.base.outputs.app_version }}
+ SEQ: ${{ steps.seq.outputs.seq }}
+ run: |
+ set -euo pipefail
+ echo "seq=$SEQ" >> "$GITHUB_OUTPUT"
+ echo "version=$APP_VERSION-core.$SEQ" >> "$GITHUB_OUTPUT"
+ echo "Next core: $APP_VERSION-core.$SEQ (seq $SEQ)"
+
+ - name: Resolve Cloud revision
+ id: cloud-ref
+ if: steps.gate.outputs.allowed == 'true'
+ env:
+ CLOUD_REPOSITORY: ${{ vars.OVERLAY_REPOSITORY }}
+ CLOUD_TOKEN: ${{ secrets.LOBEHUB_CLOUD_TOKEN }}
+ run: |
+ set -euo pipefail
+ : "${CLOUD_REPOSITORY:?OVERLAY_REPOSITORY repository variable is not set}"
+ cloud_ref=$(git -c http.https://github.com/.extraheader= ls-remote "https://x-access-token:${CLOUD_TOKEN}@github.com/${CLOUD_REPOSITORY}.git" HEAD | cut -f1)
+ if [[ ! "$cloud_ref" =~ ^[0-9a-f]{40}$ ]]; then
+ echo "Unable to resolve Cloud revision"
+ exit 1
+ fi
+ echo "cloud_ref=$cloud_ref" >> "$GITHUB_OUTPUT"
+
+ - name: Report gate result
+ if: always()
+ uses: ./.github/actions/desktop-ota-diagnostics
+ with:
+ kind: gate
+ channel: ${{ inputs.channel }}
+ steps-json: ${{ toJSON(steps) }}
+ job-status: ${{ job.status }}
+
+ build-core:
+ name: Build core (${{ matrix.platform }})
+ needs: [gate]
+ if: needs.gate.outputs.requires_full_release == 'false'
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ platform: [darwin, win32, linux]
+ steps:
+ - uses: actions/checkout@v7
+
+ - name: Setup build environment
+ id: setup
+ uses: ./.github/actions/desktop-build-setup
+ with:
+ cloud-ref: ${{ needs.gate.outputs.cloud_ref }}
+ cloud-repository: ${{ vars.OVERLAY_REPOSITORY }}
+ cloud-token: ${{ secrets.LOBEHUB_CLOUD_TOKEN }}
+ node-version: ${{ env.NODE_VERSION }}
+
+ - name: Set package version
+ id: app_version
+ run: npm run workflow:set-desktop-version ${{ needs.gate.outputs.app_version }} ${{ inputs.channel }}
+
+ # ponytail: renderer is platform-independent but rebuilt per platform; share one renderer build if this queue gets slow.
+ - name: Build core
+ id: build
+ run: npm_config_platform=${{ matrix.platform }} pnpm -C apps/desktop run build:main
+ env:
+ UPDATE_CHANNEL: ${{ inputs.channel }}
+ UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
+ RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
+ APP_URL: http://localhost:3015
+ DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
+ KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
+ NEXT_PUBLIC_DESKTOP_PROJECT_ID: ${{ inputs.channel == 'stable' && secrets.UMAMI_STABLE_DESKTOP_PROJECT_ID || secrets.UMAMI_BETA_DESKTOP_PROJECT_ID }}
+ NEXT_PUBLIC_DESKTOP_UMAMI_BASE_URL: ${{ inputs.channel == 'stable' && secrets.UMAMI_STABLE_DESKTOP_BASE_URL || secrets.UMAMI_BETA_DESKTOP_BASE_URL }}
+
+ - name: Load previous core manifest
+ id: previous
+ env:
+ CHANNEL: ${{ inputs.channel }}
+ FEED_BASE_URL: ${{ needs.gate.outputs.feed_base_url }}
+ PLATFORM: ${{ matrix.platform }}
+ run: |
+ set -euo pipefail
+ HTTP_STATUS=$(curl -sS --connect-timeout 10 --max-time 30 \
+ -o "$RUNNER_TEMP/previous-core.json" -w '%{http_code}' "$FEED_BASE_URL/$CHANNEL/core/$PLATFORM/latest.json")
+ case "$HTTP_STATUS" in
+ 200)
+ echo "Previous core: $(jq -er '.version' "$RUNNER_TEMP/previous-core.json")"
+ echo "args=--previous-manifest=$RUNNER_TEMP/previous-core.json" >> "$GITHUB_OUTPUT"
+ ;;
+ 404)
+ echo "::warning::no previous core manifest for $PLATFORM; publishing without patches"
+ echo "args=" >> "$GITHUB_OUTPUT"
+ ;;
+ *) echo "::error::previous latest.json fetch failed: HTTP $HTTP_STATUS"; exit 1 ;;
+ esac
+
+ - name: Build core release
+ id: core
+ working-directory: apps/desktop
+ env:
+ RENDERER_OTA_PRIVATE_KEY: ${{ secrets.RENDERER_OTA_PRIVATE_KEY }}
+ CHANNEL: ${{ inputs.channel }}
+ FEED_BASE_URL: ${{ needs.gate.outputs.feed_base_url }}
+ PLATFORM: ${{ matrix.platform }}
+ PREVIOUS_ARGS: ${{ steps.previous.outputs.args }}
+ ROLLOUT: ${{ inputs.rollout }}
+ SEQ: ${{ needs.gate.outputs.seq }}
+ SHELL_ABI: ${{ needs.gate.outputs.shell_abi }}
+ VERSION: ${{ needs.gate.outputs.version }}
+ run: |
+ set -euo pipefail
+ set +e
+ # shellcheck disable=SC2086
+ node scripts/buildCore.mjs \
+ --core=core-dist \
+ --platform="$PLATFORM" \
+ --channel="$CHANNEL" \
+ --version="$VERSION" \
+ --seq="$SEQ" \
+ --rollout="$ROLLOUT" \
+ --shell-abi="$SHELL_ABI" \
+ --objects-base-url="$FEED_BASE_URL/cas" \
+ --out=release/core-ota \
+ $PREVIOUS_ARGS
+ STATUS=$?
+ set -e
+ if [ "$STATUS" = "3" ]; then
+ echo "::notice::core for $PLATFORM is unchanged; nothing to publish"
+ echo "skipped=true" >> "$GITHUB_OUTPUT"
+ exit 0
+ fi
+ [ "$STATUS" = "0" ] || exit "$STATUS"
+ echo "skipped=false" >> "$GITHUB_OUTPUT"
+
+ - name: Upload core release
+ id: upload
+ if: steps.core.outputs.skipped == 'false'
+ uses: actions/upload-artifact@v6
+ with:
+ name: core-ota-${{ matrix.platform }}
+ path: apps/desktop/release/core-ota
+ retention-days: 3
+
+ - name: Report core build result
+ if: always()
+ uses: ./.github/actions/desktop-ota-diagnostics
+ with:
+ kind: core-build
+ channel: ${{ inputs.channel }}
+ suffix: ${{ matrix.platform }}
+ steps-json: ${{ toJSON(steps) }}
+ job-status: ${{ job.status }}
+
+ publish:
+ name: Publish core (${{ inputs.channel }})
+ needs: [gate, build-core]
+ if: needs.gate.outputs.requires_full_release == 'false'
+ runs-on: ubuntu-latest
+ outputs:
+ published: ${{ steps.publish.outputs.published }}
+ skipped: ${{ steps.collect.outputs.skipped }}
+ steps:
+ - uses: actions/checkout@v7
+
+ - name: Download core releases
+ uses: actions/download-artifact@v7
+ with:
+ path: release/core-ota
+ pattern: core-ota-*
+ merge-multiple: true
+
+ - name: Collect platforms
+ id: collect
+ run: |
+ set -euo pipefail
+ if [ -d release/core-ota/core ] && [ -n "$(ls -A release/core-ota/core)" ]; then
+ echo "Platforms: $(ls release/core-ota/core | tr '\n' ' ')"
+ echo "skipped=false" >> "$GITHUB_OUTPUT"
+ else
+ echo "::notice::every platform was unchanged; nothing to publish"
+ echo "skipped=true" >> "$GITHUB_OUTPUT"
+ fi
+
+ - name: Upload to S3
+ id: publish
+ if: steps.collect.outputs.skipped == 'false'
+ uses: ./.github/actions/desktop-publish-core-ota
+ with:
+ channel: ${{ inputs.channel }}
+ release-dir: release/core-ota
+ aws-access-key-id: ${{ secrets.UPDATE_AWS_ACCESS_KEY_ID }}
+ aws-secret-access-key: ${{ secrets.UPDATE_AWS_SECRET_ACCESS_KEY }}
+ s3-bucket: ${{ secrets.UPDATE_S3_BUCKET }}
+ s3-region: ${{ secrets.UPDATE_S3_REGION }}
+ s3-endpoint: ${{ secrets.UPDATE_S3_ENDPOINT }}
+
+ - name: Report core publish result
+ if: always()
+ uses: ./.github/actions/desktop-ota-diagnostics
+ env:
+ APP_VERSION: ${{ needs.gate.outputs.version }}
+ with:
+ kind: core-publish
+ channel: ${{ inputs.channel }}
+ steps-json: ${{ toJSON(steps) }}
+ job-status: ${{ job.status }}
diff --git a/.github/workflows/release-desktop-renderer-ota.yml b/.github/workflows/release-desktop-renderer-ota.yml
deleted file mode 100644
index c6edd131f4d..00000000000
--- a/.github/workflows/release-desktop-renderer-ota.yml
+++ /dev/null
@@ -1,262 +0,0 @@
-name: Release Desktop Renderer OTA
-
-# ============================================
-# Renderer 热更 patch 发布
-# ============================================
-# 前提: <channel>/base.json 由全量发版流程写入 (desktop-publish-s3)。
-# 门禁: HEAD 的 mainHash 必须等于该 marker —— main 变了只能走全量发版,
-# 此工作流会直接跳过。
-# 产物: <channel>/<appVersion>/renderer/v2/latest.json (签名 manifest)
-# <channel>/<appVersion>/renderer/v2/versions/rN.json (签名快照)
-# <channel>/<appVersion>/renderer/v2/packs/<sha256>.zip (聚合 full/delta pack)
-# delta: r0 + 最近 2 个 rN,客户端一次只下载一份对得上的 pack
-# ============================================
-
-on:
- workflow_call:
- inputs:
- channel:
- description: 'Update channel'
- required: true
- type: string
- outputs:
- published:
- description: 'Whether a renderer patch was uploaded'
- value: ${{ jobs.publish-renderer-patch.outputs.published }}
- reason:
- description: 'Renderer OTA publication or skip reason'
- value: ${{ jobs.publish-renderer-patch.outputs.reason }}
- requires_full_release:
- description: 'Whether the caller must publish a full desktop release'
- value: ${{ jobs.publish-renderer-patch.outputs.requires_full_release }}
- version:
- description: 'Published renderer patch version'
- value: ${{ jobs.publish-renderer-patch.outputs.version }}
- workflow_dispatch:
- inputs:
- channel:
- description: 'Update channel'
- required: true
- type: choice
- options:
- - canary
- - stable
- - beta
- default: canary
-
-concurrency:
- group: desktop-renderer-ota-${{ inputs.channel }}
- cancel-in-progress: true
-
-permissions: read-all
-
-env:
- NODE_VERSION: '24.11.1'
-
-jobs:
- publish-renderer-patch:
- name: Publish Renderer Patch (${{ inputs.channel }})
- runs-on: ubuntu-latest
- outputs:
- published: ${{ steps.result.outputs.published }}
- reason: ${{ steps.result.outputs.reason }}
- requires_full_release: ${{ steps.result.outputs.requires_full_release }}
- version: ${{ steps.result.outputs.version }}
- steps:
- - uses: actions/checkout@v7
- id: checkout
-
- - name: Resolve update server base URL
- id: server
- env:
- UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
- run: |
- set -euo pipefail
- UPDATE_SERVER_BASE_URL="${UPDATE_SERVER_URL%/}"
- case "$UPDATE_SERVER_BASE_URL" in
- */stable|*/nightly|*/canary|*/beta) UPDATE_SERVER_BASE_URL="${UPDATE_SERVER_BASE_URL%/*}" ;;
- esac
- echo "UPDATE_SERVER_BASE_URL=$UPDATE_SERVER_BASE_URL" >> "$GITHUB_ENV"
-
- - name: Load shipped base
- id: base
- env:
- CHANNEL: ${{ inputs.channel }}
- run: |
- set -euo pipefail
- HTTP_STATUS=$(curl -sS --connect-timeout 10 --max-time 30 \
- -o "$RUNNER_TEMP/renderer-base.json" -w '%{http_code}' \
- "$UPDATE_SERVER_BASE_URL/$CHANNEL/base.json")
- echo "Renderer base HTTP status: $HTTP_STATUS"
- if [ "$HTTP_STATUS" = "404" ]; then
- echo "::warning::no renderer OTA base metadata found; run a full release first"
- echo "found=false" >> "$GITHUB_OUTPUT"
- echo "reason=base-missing" >> "$GITHUB_OUTPUT"
- exit 0
- fi
-
- if [ "$HTTP_STATUS" != "200" ]; then
- echo "::error::Renderer base fetch failed: HTTP $HTTP_STATUS"
- exit 1
- fi
- echo "reason=base-invalid" >> "$GITHUB_OUTPUT"
- BASE=$(cat "$RUNNER_TEMP/renderer-base.json")
- if [ "$(jq -r '.rendererProtocol // 0' <<< "$BASE")" != "2" ]; then
- echo "::warning::renderer OTA base is not V2; run a full release first"
- echo "found=false" >> "$GITHUB_OUTPUT"
- echo "reason=unsupported-base" >> "$GITHUB_OUTPUT"
- exit 0
- fi
-
- MAIN_HASH=$(jq -er '.mainHash | select(type == "string" and test("^[0-9a-f]{64}$"))' <<< "$BASE")
- CLOUD_REF=$(jq -er '.cloudRef | select(type == "string" and test("^[0-9a-f]{40}$"))' <<< "$BASE")
- APP_VERSION=$(jq -er '.version | select(type == "string" and test("^[0-9A-Za-z.+-]+$"))' <<< "$BASE")
- {
- echo "app_version=$APP_VERSION"
- echo "cloud_ref=$CLOUD_REF"
- echo "found=true"
- echo "reason=base-found"
- echo "main_hash=$MAIN_HASH"
- } >> "$GITHUB_OUTPUT"
-
- - name: Setup build environment
- id: setup
- if: steps.base.outputs.found == 'true'
- uses: ./.github/actions/desktop-build-setup
- with:
- cloud-ref: ${{ steps.base.outputs.cloud_ref }}
- cloud-repository: ${{ vars.OVERLAY_REPOSITORY }}
- cloud-token: ${{ secrets.LOBEHUB_CLOUD_TOKEN }}
- node-version: ${{ env.NODE_VERSION }}
-
- - name: Set package version
- id: app_version
- if: steps.base.outputs.found == 'true'
- run: npm run workflow:set-desktop-version ${{ steps.base.outputs.app_version }} ${{ inputs.channel }}
-
- - name: Gate on mainHash
- id: gate
- if: steps.base.outputs.found == 'true'
- env:
- APP_VERSION: ${{ steps.base.outputs.app_version }}
- CHANNEL: ${{ inputs.channel }}
- BASE_MAIN_HASH: ${{ steps.base.outputs.main_hash }}
- RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
- UPDATE_CHANNEL: ${{ inputs.channel }}
- UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
- run: |
- set -euo pipefail
- MAIN_HASH=$(node apps/desktop/scripts/mainHash.mjs)
- echo "main_hash=$MAIN_HASH" >> "$GITHUB_OUTPUT"
- echo "HEAD mainHash: $MAIN_HASH"
- echo "Shipped base mainHash: $BASE_MAIN_HASH"
-
- if [ "$MAIN_HASH" != "$BASE_MAIN_HASH" ]; then
- echo "::warning::main changed since last full release — renderer patch is not allowed, run a full release instead"
- echo "allowed=false" >> "$GITHUB_OUTPUT"
- echo "reason=main-changed" >> "$GITHUB_OUTPUT"
- if curl -fsS --connect-timeout 10 --max-time 30 "$UPDATE_SERVER_BASE_URL/$CHANNEL/$APP_VERSION/renderer/v2/mainhash-inputs.json" -o "$RUNNER_TEMP/base-mainhash-inputs.json"; then
- node --input-type=module > "$RUNNER_TEMP/renderer-mainhash-diff.txt" <<'NODE' || echo "::warning::Input manifest diff unavailable"
- import { readFile } from 'node:fs/promises';
- import { diffInputs } from './apps/desktop/scripts/validateMainHash.mjs';
- const base = JSON.parse(await readFile(`${process.env.RUNNER_TEMP}/base-mainhash-inputs.json`, 'utf8'));
- const head = JSON.parse(await readFile('apps/desktop/release/renderer-mainhash-inputs.json', 'utf8'));
- console.log(diffInputs(base, head).join('\n'));
- NODE
- cat "$RUNNER_TEMP/renderer-mainhash-diff.txt"
- else
- echo "Baseline has no source input manifest; a full release will establish one"
- fi
- else
- echo "allowed=true" >> "$GITHUB_OUTPUT"
- fi
-
- - name: Determine patch version
- id: version
- if: steps.gate.outputs.allowed == 'true'
- env:
- APP_VERSION: ${{ steps.base.outputs.app_version }}
- CHANNEL: ${{ inputs.channel }}
- run: |
- CURRENT=$(curl -sf "$UPDATE_SERVER_BASE_URL/$CHANNEL/$APP_VERSION/renderer/v2/latest.json" | node -e "
- let d='';process.stdin.on('data',c=>d+=c).on('end',()=>{
- try { console.log(JSON.parse(d).version) } catch { console.log('r0') }
- })" || echo "r0")
- NEXT="r$(( ${CURRENT#r} + 1 ))"
- echo "Current patch: $CURRENT -> next: $NEXT"
- echo "version=$NEXT" >> "$GITHUB_OUTPUT"
-
- - name: Build renderer
- id: renderer
- if: steps.gate.outputs.allowed == 'true'
- run: npm run build:renderer --prefix=./apps/desktop
- env:
- UPDATE_CHANNEL: ${{ inputs.channel }}
- UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
- APP_URL: http://localhost:3015
- DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
- KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
- NEXT_PUBLIC_DESKTOP_PROJECT_ID: ${{ inputs.channel == 'stable' && secrets.UMAMI_STABLE_DESKTOP_PROJECT_ID || secrets.UMAMI_BETA_DESKTOP_PROJECT_ID }}
- NEXT_PUBLIC_DESKTOP_UMAMI_BASE_URL: ${{ inputs.channel == 'stable' && secrets.UMAMI_STABLE_DESKTOP_BASE_URL || secrets.UMAMI_BETA_DESKTOP_BASE_URL }}
-
- - name: Build and sign manifest
- id: sign
- if: steps.gate.outputs.allowed == 'true'
- env:
- RENDERER_OTA_PRIVATE_KEY: ${{ secrets.RENDERER_OTA_PRIVATE_KEY }}
- APP_VERSION: ${{ steps.base.outputs.app_version }}
- CHANNEL: ${{ inputs.channel }}
- MAIN_HASH: ${{ steps.gate.outputs.main_hash }}
- run: |
- set -euo pipefail
- node apps/desktop/scripts/buildRendererManifest.mjs \
- --renderer=apps/desktop/dist/renderer \
- --out=renderer-ota-out \
- --channel=${{ inputs.channel }} \
- --version=${{ steps.version.outputs.version }} \
- --mainHash=${{ steps.gate.outputs.main_hash }} \
- --feed-url="$UPDATE_SERVER_BASE_URL/$CHANNEL/$APP_VERSION/renderer/v2"
-
- - name: Upload to S3
- id: publish
- if: steps.gate.outputs.allowed == 'true'
- env:
- AWS_ACCESS_KEY_ID: ${{ secrets.UPDATE_AWS_ACCESS_KEY_ID }}
- AWS_SECRET_ACCESS_KEY: ${{ secrets.UPDATE_AWS_SECRET_ACCESS_KEY }}
- AWS_REGION: ${{ secrets.UPDATE_S3_REGION }}
- S3_BUCKET: ${{ secrets.UPDATE_S3_BUCKET }}
- S3_ENDPOINT: ${{ secrets.UPDATE_S3_ENDPOINT }}
- APP_VERSION: ${{ steps.base.outputs.app_version }}
- CHANNEL: ${{ inputs.channel }}
- run: |
- set -euo pipefail
- ENDPOINT_ARGS=()
- if [ -n "$S3_ENDPOINT" ]; then
- ENDPOINT_ARGS=(--endpoint-url "$S3_ENDPOINT")
- fi
-
- # Immutable packs first, then the version snapshot, latest.json last.
- RENDERER_ROOT="renderer-ota-out/$CHANNEL/$APP_VERSION/renderer/v2"
- S3_RENDERER_ROOT="s3://$S3_BUCKET/$CHANNEL/$APP_VERSION/renderer/v2"
- aws s3 sync "$RENDERER_ROOT/packs" "$S3_RENDERER_ROOT/packs" \
- --size-only \
- --content-type application/zip \
- --cache-control public,max-age=31536000,immutable \
- "${ENDPOINT_ARGS[@]}"
- aws s3 cp "$RENDERER_ROOT/versions/${{ steps.version.outputs.version }}.json" \
- "$S3_RENDERER_ROOT/versions/${{ steps.version.outputs.version }}.json" \
- --cache-control no-store "${ENDPOINT_ARGS[@]}"
- aws s3 cp "$RENDERER_ROOT/latest.json" \
- "$S3_RENDERER_ROOT/latest.json" \
- --cache-control no-store "${ENDPOINT_ARGS[@]}"
-
- echo "✅ Published renderer patch ${{ steps.version.outputs.version }} for $CHANNEL/$APP_VERSION"
-
- - name: Report renderer OTA result
- id: result
- if: always()
- uses: ./.github/actions/desktop-ota-diagnostics
- with:
- channel: ${{ inputs.channel }}
- steps-json: ${{ toJSON(steps) }}
- job-status: ${{ job.status }}
diff --git a/.github/workflows/release-desktop-stable.yml b/.github/workflows/release-desktop-stable.yml
index f1f1becc4f0..23563bda6f3 100644
--- a/.github/workflows/release-desktop-stable.yml
+++ b/.github/workflows/release-desktop-stable.yml
@@ -137,15 +137,6 @@ jobs:
fi
echo "cloud_ref=$cloud_ref" >> "$GITHUB_OUTPUT"
- renderer-ota:
- name: Publish Renderer OTA
- needs: [check-stable]
- if: ${{ needs.check-stable.outputs.is_stable == 'true' && (github.event_name != 'workflow_dispatch' || !inputs.skip_s3_upload) }}
- uses: ./.github/workflows/release-desktop-renderer-ota.yml
- with:
- channel: stable
- secrets: inherit
-
# ============================================
# 配置构建矩阵 (检查自托管 Runner)
# ============================================
@@ -213,6 +204,13 @@ jobs:
cloud-token: ${{ secrets.LOBEHUB_CLOUD_TOKEN }}
node-version: ${{ env.NODE_VERSION }}
+ - name: Resolve core seq
+ id: core_seq
+ uses: ./.github/actions/desktop-core-seq
+ with:
+ channel: stable
+ update-server-url: ${{ secrets.UPDATE_SERVER_URL }}
+
- name: Set package version
id: app_version
run: npm run workflow:set-desktop-version ${{ needs.check-stable.outputs.version }} stable
@@ -244,6 +242,7 @@ jobs:
UPDATE_CHANNEL: stable
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
+ CORE_SEQ: ${{ steps.core_seq.outputs.seq }}
RELEASE_NOTES: ${{ needs.check-stable.outputs.release_notes }}
APP_URL: http://localhost:3015
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
@@ -268,6 +267,7 @@ jobs:
UPDATE_CHANNEL: stable
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
+ CORE_SEQ: ${{ steps.core_seq.outputs.seq }}
RELEASE_NOTES: ${{ needs.check-stable.outputs.release_notes }}
APP_URL: http://localhost:3015
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
@@ -286,6 +286,7 @@ jobs:
UPDATE_CHANNEL: stable
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
+ CORE_SEQ: ${{ steps.core_seq.outputs.seq }}
RELEASE_NOTES: ${{ needs.check-stable.outputs.release_notes }}
APP_URL: http://localhost:3015
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
@@ -298,9 +299,8 @@ jobs:
uses: ./.github/actions/desktop-upload-artifacts
with:
artifact-name: release-${{ matrix.name }}
- renderer-ota-private-key: ${{ secrets.RENDERER_OTA_PRIVATE_KEY }}
- renderer-ota-public-key: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}
- update-channel: stable
+ update-server-url: ${{ secrets.UPDATE_SERVER_URL }}
+ core-signing-key: ${{ secrets.RENDERER_OTA_PRIVATE_KEY }}
- name: Preserve desktop build diagnostics
if: always()
@@ -336,17 +336,6 @@ jobs:
pattern: release-*
merge-multiple: true
- - name: Validate platform renderer hashes
- env:
- BUILD_MATRIX: ${{ needs.configure-build.outputs.matrix }}
- run: |
- node --input-type=module <<'NODE'
- import { validateReleaseInputs } from './apps/desktop/scripts/validateMainHash.mjs';
- const expected = JSON.parse(process.env.BUILD_MATRIX).include.map(({ name }) => `release-${name}`);
- const manifest = await validateReleaseInputs('release', expected);
- console.log(`Validated ${expected.length} platform hashes: ${manifest.mainHash}`);
- NODE
-
- name: List downloaded artifacts
run: ls -R release
diff --git a/.gitignore b/.gitignore
index 176e4168fb2..c4e9d5a6933 100644
--- a/.gitignore
+++ b/.gitignore
@@ -174,6 +174,10 @@ docs/superpowers/
public/sounds/
apps/desktop/resources/sounds/
+# Generated by apps/desktop/scripts/shellAbi.mjs --write
+apps/desktop/shell/abi.json
+apps/desktop/core-dist
+
# alint: local provider setup (holds the API key) and result cache
.alint/
.alintcache
diff --git a/.prettierignore b/.prettierignore
index 03eaf0bf9ad..267cb62e380 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -72,3 +72,6 @@ packages/heterogeneous-agents/src/codex/protocol/generated.ts
# Generated from lobehub/acceptance releases; preserve the upstream bytes.
.agents/skills/acceptance/**
+
+# generated files (regenerate with `bun run shell:vendor` in apps/desktop)
+apps/desktop/shell/rescue/electron-updater.cjs
diff --git a/apps/desktop/electron-builder.mjs b/apps/desktop/electron-builder.mjs
index d81d99afd3c..37e75c599df 100644
--- a/apps/desktop/electron-builder.mjs
+++ b/apps/desktop/electron-builder.mjs
@@ -6,10 +6,8 @@ import { fileURLToPath } from 'node:url';
import dotenv from 'dotenv';
-import {
- copyExternalRuntimeModulesToSource,
- getExternalRuntimeModulesFilesConfig,
-} from './external-runtime-deps.config.mjs';
+import { copyExternalRuntimeModulesToSource } from './external-runtime-deps.config.mjs';
+import { getModuleFilesConfig } from './module-deps.config.mjs';
import {
buildFirstPartyNativeAddons,
copyNativeModulesToSource,
@@ -145,7 +143,7 @@ const config = {
* BeforePack hook to resolve pnpm symlinks for native modules.
* This ensures native modules are properly included in the asar archive.
*/
- beforePack: async () => {
+ beforePack: async (context) => {
buildFirstPartyNativeAddons();
await copyNativeModulesToSource();
@@ -166,26 +164,20 @@ const config = {
// lazily downloads it on first use into the per-user cache dir. See
// apps/desktop/src/main/modules/binaries/agentBrowserBinaries.ts.
- // Build and copy CLI bundle for embedding
console.info('📦 Building CLI for embedding...');
execSync('npm run build:cli', { stdio: 'inherit', cwd: __dirname });
- const cliSrc = path.resolve(__dirname, '../cli/dist/index.js');
- const cliDest = path.resolve(__dirname, 'resources/bin/lobe-cli.js');
- await fs.mkdir(path.dirname(cliDest), { recursive: true });
- await fs.copyFile(cliSrc, cliDest);
-
- // Write a minimal package.json next to the CLI bundle so that
- // createRequire('../package.json') resolves correctly in the packaged app.
- // The CLI script lives at Resources/bin/lobe-cli.js, so '../package.json'
- // resolves to Resources/package.json.
- const cliPkg = JSON.parse(
- await fs.readFile(path.resolve(__dirname, '../cli/package.json'), 'utf8'),
+
+ execSync('node scripts/shellAbi.mjs --write', { stdio: 'inherit', cwd: __dirname });
+ const { shellAbi } = JSON.parse(
+ await fs.readFile(path.join(__dirname, 'shell/abi.json'), 'utf8'),
);
- await fs.writeFile(
- path.resolve(__dirname, 'resources/cli-package.json'),
- JSON.stringify({ name: cliPkg.name, type: 'module', version: cliPkg.version }),
+ const corePlatform =
+ context.electronPlatformName === 'mas' ? 'darwin' : context.electronPlatformName;
+ execSync('node scripts/assembleCore.mjs', { stdio: 'inherit', cwd: __dirname });
+ execSync(
+ `node scripts/buildCoreManifest.mjs --core=core-dist --platform=${corePlatform} --channel=${channel || 'stable'} --version=${packageJSON.version} --seq=${process.env.CORE_SEQ || 0} --shell-abi=${shellAbi}`,
+ { stdio: 'inherit', cwd: __dirname },
);
- console.info('✅ CLI bundle copied to resources/bin/lobe-cli.js');
},
/**
* AfterPack hook for copying Liquid Glass Assets.car on macOS 26+.
@@ -263,24 +255,15 @@ const config = {
electronLanguages: ['en', 'en_GB', 'en_US', 'en-GB', 'en-US'],
files: [
- 'dist',
- 'resources',
- 'dist/renderer/**/*',
- '!resources/locales',
- '!resources/dmg.png',
- // NOTICE:
- // AUV must execute from the external bin directory, so its ASAR copy is unnecessary.
- // The resources glob otherwise duplicates the binary copied by extraResources below.
- // Source: PR #19051 ASAR Size Gate; resources/bin is staged in beforePack above.
- // Remove these exclusions only if AUV no longer ships through extraResources.
- '!resources/bin/auv',
- '!resources/bin/auv.exe',
+ 'shell/**',
+ '!shell/__tests__',
+ 'package.json',
// Exclude all node_modules first
'!node_modules',
// Then explicitly include native modules using object form (handles pnpm symlinks)
...getNativeModulesFilesConfig(),
- // Include non-native runtime modules that are intentionally externalized from Vite.
- ...getExternalRuntimeModulesFilesConfig(),
+ // electron-log ships in the core (assembleCore), a shell copy would shadow it via the resolver shim
+ ...getModuleFilesConfig(['font-list']),
],
generateUpdatesFilesForAllChannels: true,
linux: {
@@ -360,7 +343,9 @@ const config = {
extraResources: [
{ from: 'resources/bin', to: 'bin' },
- { from: 'resources/cli-package.json', to: 'package.json' },
+ { from: 'core-dist', to: 'core' },
+ // electron-builder's copy filter drops a top-level `node_modules` dir from any `from`, so it needs its own entry
+ { from: 'core-dist/node_modules', to: 'core/node_modules' },
// Local Sandbox helper binaries. The sandbox spawns these by path, so they
// must be real files — not entries inside app.asar, and not something the
// user is expected to install separately.
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 6ca0bd63f29..d740c2be26e 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -9,11 +9,11 @@
"url": "https://github.com/lobehub/lobehub.git"
},
"author": "LobeHub",
- "main": "./dist/main/index.js",
+ "main": "./shell/main.js",
"scripts": {
"build:cli": "cd ../cli && cross-env MINIFY=1 bun run build",
"build:main": "cross-env NODE_OPTIONS=--max-old-space-size=8192 npm run build:main:raw",
- "build:main:raw": "vite build --config vite.main.config.ts && vite build --config vite.preload.config.ts && vite build --config vite.renderer.config.ts",
+ "build:main:raw": "vite build --config vite.main.config.ts && vite build --config vite.preload.config.ts && vite build --config vite.renderer.config.ts && npm run build:cli && node scripts/assembleCore.mjs",
"build:renderer": "cross-env NODE_OPTIONS=--max-old-space-size=8192 vite build --config vite.renderer.config.ts",
"build:run-unpack": "electron .",
"db:generate:local": "drizzle-kit generate --config drizzle.local.config.ts",
@@ -39,6 +39,8 @@
"package:mac:local": "npm run build:main && cross-env UPDATE_CHANNEL=nightly electron-builder --mac --config electron-builder.mjs --publish never --c.mac.notarize=false -c.mac.identity=null",
"package:win": "npm run build:main && electron-builder --win --config electron-builder.mjs --publish never",
"react-devtools": "bunx react-devtools@7",
+ "shell:abi": "node scripts/shellAbi.mjs --write",
+ "shell:vendor": "node scripts/vendorShellUpdater.mjs",
"start": "npm run build:main && electron .",
"start:reuse": "electron .",
"stylelint": "stylelint \"src/**/*.{js,jsx,ts,tsx}\" --fix",
diff --git a/apps/desktop/scripts/__tests__/assembleCore.test.mjs b/apps/desktop/scripts/__tests__/assembleCore.test.mjs
new file mode 100644
index 00000000000..16b72fad462
--- /dev/null
+++ b/apps/desktop/scripts/__tests__/assembleCore.test.mjs
@@ -0,0 +1,99 @@
+import { mkdir, mkdtemp, readdir, readFile, rm, symlink, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { assembleCore } from '../assembleCore.mjs';
+
+let root;
+
+const write = async (file, content = file) => {
+ const abs = path.join(root, file);
+ await mkdir(path.dirname(abs), { recursive: true });
+ await writeFile(abs, content);
+};
+
+const listFiles = async (dir, prefix = '') => {
+ const out = [];
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
+ if (entry.isDirectory()) out.push(...(await listFiles(path.join(dir, entry.name), rel)));
+ else out.push(rel);
+ }
+ return out.sort();
+};
+
+const setup = async () => {
+ root = await mkdtemp(path.join(tmpdir(), 'assemble-core-'));
+ await write('desktop/dist/main/index.js');
+ await write('desktop/dist/main/chunk.js');
+ await write('desktop/dist/preload/index.js');
+ await write('desktop/dist/renderer/index.html');
+ await write('desktop/dist/renderer/assets/app.js');
+ await write('desktop/resources/tray.png');
+ await write('desktop/resources/sounds/ping.mp3');
+ await write('desktop/resources/bin/auv');
+ await write('desktop/resources/bin/lobe-cli.js');
+ await write('desktop/resources/dmg.png');
+ await write('desktop/resources/cli-package.json');
+ await write('desktop/resources/locales/en-US.json');
+ await write('desktop/node_modules/.pnpm/electron-log@5/node_modules/electron-log/package.json');
+ await write('desktop/node_modules/.pnpm/electron-log@5/node_modules/electron-log/main.js');
+ await symlink(
+ path.join(root, 'desktop/node_modules/.pnpm/electron-log@5/node_modules/electron-log'),
+ path.join(root, 'desktop/node_modules/electron-log'),
+ );
+ await write('cli/dist/index.js', 'cli');
+ await write(
+ 'cli/package.json',
+ JSON.stringify({ name: '@lobehub/cli', version: '1.2.3', bin: {} }),
+ );
+ return {
+ cliDir: path.join(root, 'cli'),
+ desktopDir: path.join(root, 'desktop'),
+ out: path.join(root, 'out'),
+ };
+};
+
+afterEach(async () => {
+ if (root) await rm(root, { force: true, recursive: true });
+});
+
+describe('assembleCore', () => {
+ it('produces the core layout with resources exclusions and dereferenced electron-log', async () => {
+ const options = await setup();
+ await write('out/stale.txt');
+ assembleCore(options);
+
+ expect(await listFiles(options.out)).toEqual([
+ 'cli/lobe-cli.js',
+ 'cli/package.json',
+ 'dist/main/chunk.js',
+ 'dist/main/index.js',
+ 'dist/preload/index.js',
+ 'dist/renderer/assets/app.js',
+ 'dist/renderer/index.html',
+ 'node_modules/electron-log/main.js',
+ 'node_modules/electron-log/package.json',
+ 'package.json',
+ 'resources/sounds/ping.mp3',
+ 'resources/tray.png',
+ ]);
+ expect(await readFile(path.join(options.out, 'cli/lobe-cli.js'), 'utf8')).toBe('cli');
+ expect(JSON.parse(await readFile(path.join(options.out, 'package.json'), 'utf8'))).toEqual({
+ type: 'commonjs',
+ });
+ expect(JSON.parse(await readFile(path.join(options.out, 'cli/package.json'), 'utf8'))).toEqual({
+ name: '@lobehub/cli',
+ type: 'module',
+ version: '1.2.3',
+ });
+ });
+
+ it('throws when dist/main is missing', async () => {
+ const options = await setup();
+ await rm(path.join(options.desktopDir, 'dist/main'), { recursive: true });
+ expect(() => assembleCore(options)).toThrow(/dist\/main/);
+ });
+});
diff --git a/apps/desktop/scripts/__tests__/buildCore.test.mjs b/apps/desktop/scripts/__tests__/buildCore.test.mjs
new file mode 100644
index 00000000000..e3120d2f3f0
--- /dev/null
+++ b/apps/desktop/scripts/__tests__/buildCore.test.mjs
@@ -0,0 +1,283 @@
+import { spawnSync } from 'node:child_process';
+import { createHash, generateKeyPairSync } from 'node:crypto';
+import { existsSync, readdirSync } from 'node:fs';
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { zstdCompressSync, zstdDecompressSync } from 'node:zlib';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import {
+ coreManifestSchema,
+ verifyManifestSignature,
+} from '../../src/main/core/infrastructure/coreOta/manifest';
+import { applyZstdPatch } from '../../src/main/core/infrastructure/coreOta/zstdPatch';
+import { buildCore, EmptyReleaseError } from '../buildCore.mjs';
+import { decodePack } from '../buildRendererManifest.mjs';
+
+const SCRIPT = fileURLToPath(new URL('../buildCore.mjs', import.meta.url));
+
+const sha256 = (content) => createHash('sha256').update(content).digest('hex');
+
+const bigText = (seed) =>
+ Array.from({ length: 1024 }, (_, i) => `${seed} line ${i} ${'x'.repeat(20)}\n`).join('');
+
+const baseFiles = () => ({
+ 'cli/lobe-cli.js': bigText('cli'),
+ 'dist/main/index.js': 'main v1',
+ 'dist/renderer/es-AAAAAAAA.js': bigText('renderer'),
+ 'package.json': '{"type":"commonjs"}',
+});
+
+const { privateKey, publicKey } = generateKeyPairSync('ed25519');
+const privateKeyPem = privateKey.export({ format: 'pem', type: 'pkcs8' }).toString();
+const publicKeyPem = publicKey.export({ format: 'pem', type: 'spki' }).toString();
+
+let root;
+let outDir;
+
+const writeCore = async (name, files) => {
+ const dir = path.join(root, name);
+ for (const [file, content] of Object.entries(files)) {
+ await mkdir(path.join(dir, path.dirname(file)), { recursive: true });
+ await writeFile(path.join(dir, file), content);
+ }
+ return dir;
+};
+
+const options = (coreDir, extra) => ({
+ channel: 'canary',
+ coreDir,
+ objectsBaseUrl: 'https://cdn.example.com/cas',
+ outDir,
+ platform: 'darwin',
+ privateKeyPem,
+ seq: 1,
+ shellAbi: 'a'.repeat(64),
+ version: '1.0.0',
+ ...extra,
+});
+
+const objectCount = () => readdirSync(path.join(outDir, 'cas/objects')).length;
+const readJson = async (file) => JSON.parse(await readFile(path.join(outDir, file), 'utf8'));
+
+beforeEach(async () => {
+ root = await mkdtemp(path.join(tmpdir(), 'build-core-'));
+ outDir = path.join(root, 'out');
+});
+
+afterEach(async () => {
+ await rm(root, { force: true, recursive: true });
+});
+
+describe('buildCore', () => {
+ it('publishes objects, full pack and identical manifest snapshots for a first release', async () => {
+ const files = baseFiles();
+ const coreDir = await writeCore('v1', files);
+ const { manifest } = await buildCore(options(coreDir));
+
+ expect(manifest).toMatchObject({
+ applyMode: null,
+ channel: 'canary',
+ objectsBaseUrl: 'https://cdn.example.com/cas',
+ patches: [],
+ platform: 'darwin',
+ previous: null,
+ rollout: 1,
+ schemaVersion: 3,
+ seq: 1,
+ version: '1.0.0',
+ });
+ expect(manifest.tree.map((file) => file.path)).toEqual(Object.keys(files).sort());
+ expect(coreManifestSchema.safeParse(manifest).success).toBe(true);
+ expect(verifyManifestSignature(manifest, publicKeyPem)).toBe(true);
+
+ expect(objectCount()).toBe(Object.keys(files).length);
+ for (const file of manifest.tree) {
+ const zst = await readFile(path.join(outDir, 'cas/objects', `${file.sha256}.zst`));
+ expect(sha256(zstdDecompressSync(zst))).toBe(file.sha256);
+ }
+
+ const pack = await readFile(path.join(outDir, 'core/darwin', manifest.full.path));
+ expect(manifest.full).toEqual({
+ path: `packs/${sha256(pack)}.zip`,
+ sha256: sha256(pack),
+ size: pack.byteLength,
+ });
+ const entries = decodePack(pack);
+ expect([...entries.keys()].sort()).toEqual(
+ manifest.tree.map((file) => `objects/${file.sha256}`).sort(),
+ );
+ for (const file of manifest.tree) {
+ expect(sha256(entries.get(`objects/${file.sha256}`))).toBe(file.sha256);
+ }
+
+ const latest = await readFile(path.join(outDir, 'core/darwin/latest.json'), 'utf8');
+ expect(await readFile(path.join(outDir, 'core/darwin/versions/1.0.0.json'), 'utf8')).toBe(
+ latest,
+ );
+ expect(await readFile(path.join(coreDir, 'manifest.json'), 'utf8')).toBe(latest);
+ expect(JSON.parse(latest)).toEqual(manifest);
+ });
+
+ it('emits one new object and a round-trippable patch for a renderer-only change', async () => {
+ const v1 = await writeCore('v1', baseFiles());
+ await buildCore(options(v1));
+ const previousManifest = await readJson('core/darwin/latest.json');
+
+ const v2Files = { ...baseFiles() };
+ delete v2Files['dist/renderer/es-AAAAAAAA.js'];
+ v2Files['dist/renderer/es-BBBBBBBB.js'] = bigText('renderer').replace('line 7 ', 'line 7! ');
+ const v2 = await writeCore('v2', v2Files);
+ const { manifest } = await buildCore(
+ options(v2, { previousManifest, seq: 2, version: '1.0.1' }),
+ );
+
+ expect(manifest).toMatchObject({ applyMode: 'reload', previous: '1.0.0', seq: 2 });
+ expect(objectCount()).toBe(5);
+ expect(manifest.patches).toHaveLength(1);
+ const [patch] = manifest.patches;
+ expect(patch.fromSha256).toBe(sha256(baseFiles()['dist/renderer/es-AAAAAAAA.js']));
+ expect(patch.toSha256).toBe(sha256(v2Files['dist/renderer/es-BBBBBBBB.js']));
+
+ const patchFile = path.join(outDir, 'cas/patches', `${patch.fromSha256}-${patch.toSha256}.zst`);
+ const patchContent = await readFile(patchFile);
+ expect(patchContent.byteLength).toBe(patch.size);
+ const restored = await applyZstdPatch(
+ Buffer.from(baseFiles()['dist/renderer/es-AAAAAAAA.js']),
+ patchContent,
+ );
+ expect(restored.toString()).toBe(v2Files['dist/renderer/es-BBBBBBBB.js']);
+
+ expect(coreManifestSchema.safeParse(await readJson('core/darwin/latest.json')).success).toBe(
+ true,
+ );
+ expect(verifyManifestSignature(manifest, publicKeyPem)).toBe(true);
+ expect(existsSync(path.join(outDir, 'core/darwin/versions/1.0.0.json'))).toBe(true);
+ });
+
+ it('marks relaunch when main changes and patches cli by path', async () => {
+ const v1 = await writeCore('v1', baseFiles());
+ await buildCore(options(v1));
+ const previousManifest = await readJson('core/darwin/latest.json');
+
+ const v3Files = {
+ ...baseFiles(),
+ 'cli/lobe-cli.js': bigText('cli').replace('line 3 ', 'line 3? '),
+ 'dist/main/index.js': 'main v3',
+ };
+ const v3 = await writeCore('v3', v3Files);
+ const { manifest } = await buildCore(
+ options(v3, { previousManifest, seq: 2, version: '1.1.0' }),
+ );
+
+ expect(manifest.applyMode).toBe('relaunch');
+ expect(manifest.patches).toHaveLength(1);
+ expect(manifest.patches[0].toSha256).toBe(sha256(v3Files['cli/lobe-cli.js']));
+ });
+
+ it('rejects an empty release or a package.json-only diff', async () => {
+ const v1 = await writeCore('v1', baseFiles());
+ await buildCore(options(v1));
+ const previousManifest = await readJson('core/darwin/latest.json');
+
+ const same = await writeCore('same', baseFiles());
+ await expect(
+ buildCore(options(same, { previousManifest, seq: 2, version: '1.0.1' })),
+ ).rejects.toThrow(EmptyReleaseError);
+
+ const pkgOnly = await writeCore('pkg', { ...baseFiles(), 'package.json': '{"v":2}' });
+ await expect(
+ buildCore(options(pkgOnly, { previousManifest, seq: 2, version: '1.0.1' })),
+ ).rejects.toThrow(EmptyReleaseError);
+ });
+
+ describe('previous base resolved through fetchImpl', () => {
+ const oldContent = baseFiles()['dist/renderer/es-AAAAAAAA.js'];
+ const v2Files = () => {
+ const files = { ...baseFiles() };
+ delete files['dist/renderer/es-AAAAAAAA.js'];
+ files['dist/renderer/es-BBBBBBBB.js'] = oldContent.replace('line 7 ', 'line 7! ');
+ return files;
+ };
+ const response = (body, ok = true) => ({
+ arrayBuffer: async () => body,
+ ok,
+ status: ok ? 200 : 404,
+ });
+
+ const run = async (fetchImpl) => {
+ const v1 = await writeCore('v1', baseFiles());
+ await buildCore(options(v1, { outDir: path.join(root, 'out-v1') }));
+ const previousManifest = JSON.parse(
+ await readFile(path.join(root, 'out-v1/core/darwin/latest.json'), 'utf8'),
+ );
+ const v2 = await writeCore('v2', v2Files());
+ const urls = [];
+ const { manifest } = await buildCore(
+ options(v2, {
+ fetchImpl: async (url) => {
+ urls.push(url);
+ return fetchImpl(url);
+ },
+ previousManifest,
+ seq: 2,
+ version: '1.0.1',
+ }),
+ );
+ return { manifest, urls };
+ };
+
+ it('patches when the object is served', async () => {
+ const { manifest, urls } = await run(async () => response(zstdCompressSync(oldContent)));
+ expect(urls).toEqual([`https://cdn.example.com/cas/objects/${sha256(oldContent)}.zst`]);
+ expect(manifest.patches).toHaveLength(1);
+ });
+
+ it('skips the patch on non-ok, thrown fetch, or sha mismatch', async () => {
+ for (const fetchImpl of [
+ async () => response(null, false),
+ async () => {
+ throw new Error('network');
+ },
+ async () => response(zstdCompressSync(Buffer.from(`${oldContent}tampered`))),
+ ]) {
+ const { manifest } = await run(fetchImpl);
+ expect(manifest.patches).toEqual([]);
+ expect(manifest.applyMode).toBe('reload');
+ await rm(root, { force: true, recursive: true });
+ root = await mkdtemp(path.join(tmpdir(), 'build-core-'));
+ outDir = path.join(root, 'out');
+ }
+ });
+ });
+
+ it('exits 3 with "empty release" from the CLI', async () => {
+ const v1 = await writeCore('v1', baseFiles());
+ await buildCore(options(v1));
+ const keyFile = path.join(root, 'key.pem');
+ await writeFile(keyFile, privateKeyPem);
+
+ const result = spawnSync(
+ process.execPath,
+ [
+ SCRIPT,
+ `--core=${v1}`,
+ '--platform=darwin',
+ '--channel=canary',
+ '--version=1.0.1',
+ '--seq=2',
+ `--shell-abi=${'a'.repeat(64)}`,
+ '--objects-base-url=https://cdn.example.com/cas',
+ `--out=${outDir}`,
+ `--previous-manifest=${path.join(outDir, 'core/darwin/latest.json')}`,
+ `--private-key-file=${keyFile}`,
+ ],
+ { encoding: 'utf8' },
+ );
+ expect(result.status).toBe(3);
+ expect(result.stderr).toContain('empty release');
+ });
+});
diff --git a/apps/desktop/scripts/__tests__/buildCoreManifest.test.mjs b/apps/desktop/scripts/__tests__/buildCoreManifest.test.mjs
new file mode 100644
index 00000000000..40e097075b0
--- /dev/null
+++ b/apps/desktop/scripts/__tests__/buildCoreManifest.test.mjs
@@ -0,0 +1,143 @@
+import { createHash, generateKeyPairSync } from 'node:crypto';
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import {
+ coreManifestSchema,
+ verifyManifestSignature,
+} from '../../src/main/core/infrastructure/coreOta/manifest';
+import {
+ buildCoreManifest,
+ createCoreManifest,
+ PLACEHOLDER_FULL,
+ PLACEHOLDER_OBJECTS_BASE_URL,
+} from '../buildCoreManifest.mjs';
+
+const shellLoader = createRequire(import.meta.url)('../../shell/core-loader.js');
+
+let root;
+
+const sha256 = (content) => createHash('sha256').update(content).digest('hex');
+
+const files = {
+ 'dist/main/index.js': 'main',
+ 'dist/preload/index.js': 'preload',
+ 'dist/renderer/index.html': '<html></html>',
+ 'resources/tray.png': 'png',
+};
+
+const setup = async () => {
+ root = await mkdtemp(path.join(tmpdir(), 'core-manifest-'));
+ for (const [file, content] of Object.entries(files)) {
+ await mkdir(path.join(root, path.dirname(file)), { recursive: true });
+ await writeFile(path.join(root, file), content);
+ }
+ await writeFile(path.join(root, 'manifest.json'), '{}');
+};
+
+const keys = () => {
+ const { privateKey, publicKey } = generateKeyPairSync('ed25519');
+ return {
+ privateKeyPem: privateKey.export({ format: 'pem', type: 'pkcs8' }).toString(),
+ publicKeyPem: publicKey.export({ format: 'pem', type: 'spki' }).toString(),
+ };
+};
+
+const options = (extra) => ({
+ channel: 'canary',
+ coreDir: root,
+ platform: 'darwin',
+ seq: 7,
+ shellAbi: 'a'.repeat(64),
+ version: '2.3.0',
+ ...extra,
+});
+
+afterEach(async () => {
+ if (root) await rm(root, { force: true, recursive: true });
+});
+
+describe('buildCoreManifest', () => {
+ it('covers every file with correct hashes and validates against the core schema', async () => {
+ await setup();
+ const { privateKeyPem } = keys();
+ const manifest = await buildCoreManifest(
+ options({ objectsBaseUrl: 'https://cdn.example.com/cas', privateKeyPem }),
+ );
+
+ expect(manifest.tree).toEqual(
+ Object.entries(files).map(([file, content]) => ({
+ path: file,
+ sha256: sha256(content),
+ size: Buffer.byteLength(content),
+ })),
+ );
+ expect(manifest).toMatchObject({
+ applyMode: null,
+ channel: 'canary',
+ objectsBaseUrl: 'https://cdn.example.com/cas',
+ patches: [],
+ platform: 'darwin',
+ previous: null,
+ rollout: 1,
+ schemaVersion: 3,
+ seq: 7,
+ shellAbi: 'a'.repeat(64),
+ version: '2.3.0',
+ });
+ expect(manifest.full).toEqual(PLACEHOLDER_FULL);
+ expect(coreManifestSchema.safeParse(manifest).success).toBe(true);
+ expect(JSON.parse(await readFile(path.join(root, 'manifest.json'), 'utf8'))).toEqual(manifest);
+ });
+
+ it('signs so the shell loader verifies, and rejects a tampered byte', async () => {
+ await setup();
+ const { privateKeyPem, publicKeyPem } = keys();
+ const manifest = await buildCoreManifest(options({ privateKeyPem }));
+ expect(verifyManifestSignature(manifest, publicKeyPem)).toBe(true);
+ expect(shellLoader.verifyManifestSignature(manifest, publicKeyPem)).toBe(true);
+
+ const tampered = structuredClone(manifest);
+ tampered.tree[0].sha256 = `b${tampered.tree[0].sha256.slice(1)}`;
+ expect(verifyManifestSignature(tampered, publicKeyPem)).toBe(false);
+ expect(shellLoader.verifyManifestSignature(tampered, publicKeyPem)).toBe(false);
+ });
+
+ it('writes an empty signature without a private key', async () => {
+ await setup();
+ const manifest = await buildCoreManifest(options());
+ expect(manifest.signature).toBe('');
+ expect(manifest.objectsBaseUrl).toBe(PLACEHOLDER_OBJECTS_BASE_URL);
+ });
+
+ it('rejects a manifest whose shellAbi is not a sha256', async () => {
+ await setup();
+ await expect(buildCoreManifest(options({ shellAbi: 'dev' }))).rejects.toThrow(/shellAbi/);
+ });
+
+ it('leaves .DS_Store out of the tree since electron-builder does not package it', async () => {
+ await setup();
+ await writeFile(path.join(root, 'dist/renderer/.DS_Store'), 'finder');
+ await writeFile(path.join(root, '.DS_Store'), 'finder');
+
+ const manifest = await buildCoreManifest(options());
+
+ expect(manifest.tree.map((file) => file.path)).toEqual(Object.keys(files));
+ });
+
+ it('rejects a non-numeric rollout', () => {
+ const tree = [{ path: 'dist/main/index.js', sha256: 'b'.repeat(64), size: 1 }];
+ expect(() =>
+ createCoreManifest({
+ ...options({ rollout: Number('50%') }),
+ full: PLACEHOLDER_FULL,
+ objectsBaseUrl: PLACEHOLDER_OBJECTS_BASE_URL,
+ tree,
+ }),
+ ).toThrow(/rollout/);
+ });
+});
diff --git a/apps/desktop/scripts/__tests__/mainHash.test.mjs b/apps/desktop/scripts/__tests__/mainHash.test.mjs
deleted file mode 100644
index 0c98955fc87..00000000000
--- a/apps/desktop/scripts/__tests__/mainHash.test.mjs
+++ /dev/null
@@ -1,582 +0,0 @@
-import { execFile } from 'node:child_process';
-import { cp, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
-import path from 'node:path';
-import { pathToFileURL } from 'node:url';
-import { promisify } from 'node:util';
-
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-
-import { viteOsPlatformResolve } from '../../../../plugins/vite/osPlatformResolve';
-import { collectSourceInputs, collectViteGraph } from '../mainHash.mjs';
-import {
- diffInputs,
- validateInputManifest,
- validateReleaseInputs,
- validateRendererBase,
-} from '../validateMainHash.mjs';
-
-let root;
-const put = async (file, content = '') => {
- const target = path.join(root, file);
- await mkdir(path.dirname(target), { recursive: true });
- await writeFile(target, content);
- return target;
-};
-const collect = (entry, resolve) =>
- collectViteGraph({
- configFile: false,
- root,
- resolve,
- build: { lib: { entry, formats: ['es'] }, ssr: true },
- });
-const hash = async (options = {}) =>
- collectSourceInputs({
- repoRoot: root,
- publicKey: 'test-key',
- sourcePackages: [],
- graph:
- options.graph ??
- (await Promise.all(
- ['main', 'preload'].map((target) =>
- collect(path.join(options.repoRoot ?? root, `apps/desktop/src/${target}/index.ts`)),
- ),
- )),
- ...options,
- });
-
-beforeEach(async () => {
- root = await mkdtemp(path.join(tmpdir(), 'main hash '));
- await put('apps/desktop/package.json', JSON.stringify({ version: '1.0.0' }));
- await put('apps/desktop/pnpm-lock.yaml', 'lockfileVersion: 9\n');
- await put('apps/desktop/pnpm-workspace.yaml', 'packages: []\n');
- await put('apps/desktop/tsconfig.json', '{}');
- for (const file of [
- 'vite.main.config.ts',
- 'vite.preload.config.ts',
- 'vite.shared.ts',
- 'native-deps.config.mjs',
- 'external-runtime-deps.config.mjs',
- 'module-deps.config.mjs',
- 'scripts/mainHash.mjs',
- 'scripts/mainHashGraph.mjs',
- ])
- await put(`apps/desktop/${file}`, 'export {};\n');
- for (const dir of ['main', 'preload', 'common'])
- await put(`apps/desktop/src/${dir}/index.ts`, 'export {};\n');
- await put('apps/desktop/src/main/index.ts', "export * from '../common/index';\n");
- await put('apps/desktop/resources/error.html', '<html>error</html>\n');
- await put('plugins/vite/platform.ts', 'export {};\n');
- await put('packages/native/binding.gyp', '{}');
- await put('packages/native/native/addon.mm', '// native v1\n');
-});
-
-afterEach(async () => {
- await rm(root, { force: true, recursive: true });
-});
-
-describe('source main hash', () => {
- it.each([
- ['apps/desktop/src/main/index.ts', 'export const changed = true;'],
- ['apps/desktop/src/preload/index.ts', 'export const changed = true;'],
- ['apps/desktop/src/common/index.ts', 'export const changed = true;'],
- ['packages/native/native/addon.mm', '// native v2'],
- ['packages/native/binding.gyp', '{"targets":[]}'],
- ['apps/desktop/pnpm-lock.yaml', 'lockfileVersion: 9\npackages: {changed: true}\n'],
- ['apps/desktop/package.json', '{"version":"1.0.1"}'],
- ['apps/desktop/vite.shared.ts', 'export const target = "node24";'],
- ['apps/desktop/resources/error.html', '<html>new error</html>'],
- ])('invalidates all platforms for %s', async (file, content) => {
- const before = await hash();
- await put(file, content);
- const after = await hash();
- expect(after.mainHash).not.toBe(before.mainHash);
- expect(diffInputs(before, after).some((line) => line.includes(`oss/${file}:`))).toBe(true);
- expect(() => validateInputManifest(after)).not.toThrow();
- });
-
- it('ignores installed native variants, generated output, renderer, docs and tests', async () => {
- const before = await hash();
- for (const file of [
- 'apps/desktop/node_modules/native-darwin/package.json',
- 'apps/desktop/node_modules/native-linux/package.json',
- 'apps/desktop/dist/main/index.js',
- 'apps/desktop/src/overlay/entry.tsx',
- 'apps/desktop/src/main/__tests__/foo.test.ts',
- 'apps/desktop/src/main/README.md',
- 'apps/desktop/resources/bin/lobe-cli.js',
- 'apps/desktop/resources/cli-package.json',
- 'packages/native/build/Release/addon.node',
- 'packages/native/dist/index.js',
- ])
- await put(file, '{}');
- expect((await hash()).mainHash).toBe(before.mainHash);
- });
-
- it('normalizes text line endings, but preserves JSON key order and binary resource bytes', async () => {
- await put('apps/desktop/package.json', '{"version":"1.0.0","name":"desktop"}\n');
- const before = await hash();
- await put('apps/desktop/package.json', '{"version":"1.0.0","name":"desktop"}\r\n');
- await put('apps/desktop/src/main/index.ts', "export * from '../common/index';\r\n");
- expect((await hash()).mainHash).toBe(before.mainHash);
- await put('apps/desktop/package.json', '{"name":"desktop","version":"1.0.0"}\n');
- expect((await hash()).mainHash).not.toBe(before.mainHash);
- await put('apps/desktop/resources/icon.png', Buffer.from([0, 13, 10, 255]));
- const withBinary = await hash();
- await put('apps/desktop/resources/icon.png', Buffer.from([0, 10, 255]));
- expect((await hash()).mainHash).not.toBe(withBinary.mainHash);
- });
-
- it('is independent of checkout location and symlinked roots', async () => {
- const copy = `${root}-copy`;
- const link = `${root}-link`;
- try {
- await cp(root, copy, { recursive: true });
- await symlink(copy, link, process.platform === 'win32' ? 'junction' : 'dir');
- expect((await hash({ repoRoot: copy })).mainHash).toBe((await hash()).mainHash);
- expect((await hash({ repoRoot: link })).mainHash).toBe((await hash()).mainHash);
- } finally {
- await rm(link, { force: true });
- await rm(copy, { recursive: true, force: true });
- }
- });
-
- it('canonicalizes graph paths before walking package boundaries', async () => {
- await put('package.json', '{"private":true}');
- const node = (id) => ({
- configFiles: [],
- defines: {},
- nodes: new Map([
- [
- id,
- {
- ast: undefined,
- dynamicImports: [],
- entry: false,
- external: false,
- id,
- imports: [],
- retained: false,
- },
- ],
- ]),
- });
- const canonical = await hash({ graph: [node(path.join(root, 'package.json'))] });
- const relative = `${root}/apps/desktop/src/main/../../../../package.json`;
-
- expect((await hash({ graph: [node(relative)] })).mainHash).toBe(canonical.mainHash);
- });
-
- it('tracks Cloud runtime sources and dependency declarations without the whole Cloud revision', async () => {
- const cloud = `${root}-cloud`;
- try {
- await mkdir(path.join(cloud, 'scripts/cloud-desktop'), { recursive: true });
- await writeFile(path.join(cloud, 'package.json'), '{"dependencies":{"sentry":"1.0.0"}}');
- const source = path.join(cloud, 'runtime.ts');
- await writeFile(source, 'export const value = 1;');
- const cloudHash = async () => hash({ cloudRoot: cloud, graph: [await collect(source)] });
- const before = await cloudHash();
- await writeFile(path.join(cloud, 'renderer.ts'), 'renderer-only change');
- expect((await cloudHash()).mainHash).toBe(before.mainHash);
- await writeFile(source, 'export const value = 2;');
- const changed = await cloudHash();
- expect(changed.mainHash).not.toBe(before.mainHash);
- await writeFile(path.join(cloud, 'package.json'), '{"dependencies":{"sentry":"2.0.0"}}');
- expect((await cloudHash()).mainHash).not.toBe(changed.mainHash);
- } finally {
- await rm(cloud, { force: true, recursive: true });
- }
- });
-
- it('does not hide deleted sources, missing locks or changed keys', async () => {
- const before = await hash();
- expect((await hash({ publicKey: 'another-key' })).mainHash).not.toBe(before.mainHash);
- await rm(path.join(root, 'packages/native/native/addon.mm'));
- expect((await hash()).mainHash).not.toBe(before.mainHash);
- await rm(path.join(root, 'apps/desktop/pnpm-lock.yaml'));
- await expect(hash()).rejects.toThrow();
- });
-});
-
-describe('workspace Vite graph', () => {
- const collect = async () =>
- collectViteGraph({
- configFile: false,
- root,
- build: {
- lib: { entry: path.join(root, 'apps/desktop/src/main/index.ts'), formats: ['es'] },
- ssr: true,
- },
- resolve: { alias: { '@workspace': path.join(root, 'packages/shared/src') } },
- });
-
- it('follows runtime, side-effect and dynamic imports but not type-only or unused files', async () => {
- await put('packages/shared/src/runtime.ts', 'export const value = 1;');
- await put('packages/shared/src/types.ts', 'export interface Value { value: number }');
- await put('packages/shared/src/unused.ts', 'export const unused = 1;');
- await put('packages/shared/src/effect.ts', 'globalThis.effect = true;');
- await put('packages/shared/src/lazy.ts', 'export const lazy = 1;');
- await put('packages/shared/src/data.json', '{"label":"v1"}');
- await put(
- 'apps/desktop/src/main/index.ts',
- `
- import type { Value } from '@workspace/types';
- import { value } from '@workspace/runtime';
- import '@workspace/effect';
- import data from '@workspace/data.json';
- export const result: Value = { value };
- export const label = data.label;
- export const load = () => import('@workspace/lazy');
- `,
- );
- await put('packages/shared/package.json', '{"type":"module"}');
- const graph = await collect();
- const before = await hash({ graph: [graph] });
- const paths = [
- ...before.inputs.map((input) => input.path.replace(/^\$graph\/main\//, '')),
- ...before.graph.flatMap((target) => target.modules.flatMap((node) => node.inlined)),
- ];
- expect(paths).toContain('oss/packages/shared/src/runtime.ts');
- expect(paths).toContain('oss/packages/shared/src/effect.ts');
- expect(paths).toContain('oss/packages/shared/src/lazy.ts');
- expect(paths).toContain('oss/packages/shared/src/data.json');
- expect(paths).not.toContain('oss/packages/shared/src/types.ts');
- expect(paths).not.toContain('oss/packages/shared/src/unused.ts');
- await put('packages/shared/src/types.ts', 'export interface Value { other: string }');
- await put('packages/shared/src/unused.ts', 'export const unused = 2;');
- expect((await hash({ graph: [await collect()] })).mainHash).toBe(before.mainHash);
- await put('packages/shared/package.json', '{"type":"module","sideEffects":false}');
- expect((await hash({ graph: [await collect()] })).mainHash).not.toBe(before.mainHash);
- await put('packages/shared/package.json', '{"type":"module"}');
- await put('packages/shared/src/runtime.ts', 'export const value = 2;');
- expect((await hash({ graph: [await collect()] })).mainHash).not.toBe(before.mainHash);
- });
-
- it('ignores types, comments and unused forwarding exports, but detects a live binding swap', async () => {
- await put('apps/desktop/src/main/a.ts', 'export const a = 11;');
- await put('apps/desktop/src/main/b.ts', 'export const b = 22;');
- await put('apps/desktop/src/main/forward.ts', "export { a } from './a';");
- await put('apps/desktop/src/main/types.ts', 'export interface Value { name: string }');
- const barrel = 'apps/desktop/src/main/barrel.ts';
- await put(barrel, "export { a as selected } from './a';");
- await put(
- 'apps/desktop/src/main/index.ts',
- `
- import { selected } from './barrel';
- import { a } from './a';
- import { b } from './b';
- export const result = [selected, a, b];
- `,
- );
- const capture = async () => {
- let code;
- const graph = await collectViteGraph({
- configFile: false,
- root,
- build: {
- lib: { entry: path.join(root, 'apps/desktop/src/main/index.ts'), formats: ['es'] },
- },
- plugins: [
- {
- name: 'capture-result',
- generateBundle(_options, bundle) {
- code = Object.values(bundle).find((item) => item.type === 'chunk').code;
- },
- },
- ],
- });
- const output = await import(
- `data:text/javascript;base64,${Buffer.from(code).toString('base64')}`
- );
- return { manifest: await hash({ graph: [graph] }), result: output.result };
- };
- const before = await capture();
- expect(before.result).toEqual([11, 11, 22]);
- for (const source of [
- "// another comment\nexport { a as selected } from './a'; export type { Value } from './types';",
- "export { a as selected } from './a'; export * from './types';",
- "export { a as selected } from './a'; export { b as unused } from './b';",
- "export { a as selected } from './forward';",
- ]) {
- await put(barrel, source);
- const after = await capture();
- expect(after.result).toEqual(before.result);
- expect(after.manifest.mainHash).toBe(before.manifest.mainHash);
- }
- await put(barrel, "export { b as selected } from './b';");
- const swapped = await capture();
- expect(swapped.result).toEqual([22, 11, 22]);
- expect(swapped.manifest.mainHash).not.toBe(before.manifest.mainHash);
- });
-
- it.each([
- [
- "import { selected } from './barrel'; export const result = selected;",
- "export { a as selected } from './a';",
- "export { b as selected } from './b';",
- ],
- [
- "import selected from './barrel'; export const result = selected;",
- "export { a as default } from './a';",
- "export { b as default } from './b';",
- ],
- [
- "import * as value from './barrel'; export const result = value.selected;",
- "export { a as selected } from './a';",
- "export { b as selected } from './b';",
- ],
- [
- "export const load = () => import('./barrel');",
- "export { a as selected } from './a';",
- "export { b as selected } from './b';",
- ],
- ])(
- 'tracks named, default, namespace and dynamic bindings: %s',
- async (entry, beforeSource, afterSource) => {
- await put('apps/desktop/src/main/a.ts', 'export const a = 11;');
- await put('apps/desktop/src/main/b.ts', 'export const b = 22;');
- await put(
- 'apps/desktop/src/main/index.ts',
- `${entry}\nexport { a } from './a'; export { b } from './b';`,
- );
- await put('apps/desktop/src/main/barrel.ts', beforeSource);
- const before = await hash();
- await put('apps/desktop/src/main/barrel.ts', afterSource);
- expect((await hash()).mainHash).not.toBe(before.mainHash);
- },
- );
-
- it('preserves side-effect order through omitted forwarding modules', async () => {
- await put('apps/desktop/src/main/a.ts', 'globalThis.order = "a";');
- await put('apps/desktop/src/main/b.ts', 'globalThis.order += "b";');
- await put(
- 'apps/desktop/src/main/index.ts',
- "import './barrel'; export const result = globalThis.order;",
- );
- await put('apps/desktop/src/main/barrel.ts', "import './a'; import './b';");
- const before = await hash();
- await put('apps/desktop/src/main/barrel.ts', "import './b'; import './a';");
- expect((await hash()).mainHash).not.toBe(before.mainHash);
- });
-
- it('ignores ordinary comments while preserving tree-shaking annotations', async () => {
- await put('apps/desktop/src/main/index.ts', 'export const result = 1; globalThis.effect();');
- const before = await hash();
- await put(
- 'apps/desktop/src/main/index.ts',
- '// comment\nexport const result = 1; /* another */ globalThis.effect();',
- );
- expect((await hash()).mainHash).toBe(before.mainHash);
- await put(
- 'apps/desktop/src/main/index.ts',
- 'export const result = 1; /* @__PURE__ */ globalThis.effect();',
- );
- expect((await hash()).mainHash).not.toBe(before.mainHash);
- });
-
- it('keeps transitive definitions used by constant folding', async () => {
- await put('apps/desktop/src/main/a.ts', 'export const a = 11;');
- await put('apps/desktop/src/main/barrel.ts', "export { a } from './a';");
- await put(
- 'apps/desktop/src/main/b.ts',
- "import { a } from './barrel'; export const b = a + 1;",
- );
- await put(
- 'apps/desktop/src/main/index.ts',
- "import { b } from './b'; export const result = b + 1;",
- );
- const before = await hash();
- await put('apps/desktop/src/main/a.ts', 'export const a = 22;');
- expect((await hash()).mainHash).not.toBe(before.mainHash);
- });
-
- it('ignores unread namespace exports, but includes the namespace receiver of method calls', async () => {
- await put(
- 'apps/desktop/src/main/a.ts',
- 'export const a = 11; export function read() { return this.spare; }',
- );
- await put('apps/desktop/src/main/b.ts', 'export const b = 22;');
- const barrel = 'apps/desktop/src/main/barrel.ts';
- const entry = 'apps/desktop/src/main/index.ts';
- await put(barrel, "export { a as selected, a as spare, read } from './a';");
- await put(
- entry,
- "import * as ns from './barrel'; export const result = ns.selected; export { a } from './a'; export { b } from './b';",
- );
- const before = await hash();
- await put(
- barrel,
- "export { a as selected, read } from './a'; export { b as spare } from './b';",
- );
- expect((await hash()).mainHash).toBe(before.mainHash);
- await put(
- entry,
- "import * as ns from './barrel'; export const result = ns.read(); export { a } from './a'; export { b } from './b';",
- );
- const call = await hash();
- await put(barrel, "export { a as selected, a as spare, read } from './a';");
- expect((await hash()).mainHash).not.toBe(call.mainHash);
- });
-
- it('requires bundled npm code to be pinned by the Desktop lockfile', async () => {
- await mkdir(path.join(root, 'apps/desktop/node_modules'), { recursive: true });
- await put(
- 'node_modules/floating/package.json',
- '{"name":"floating","version":"1.0.0","type":"module","main":"index.js"}',
- );
- await put('node_modules/floating/index.js', 'export const value = 1;');
- await put(
- 'apps/desktop/src/main/index.ts',
- "import { value } from 'floating'; export const result = value;",
- );
- const graph = await collectViteGraph({
- configFile: false,
- root,
- build: {
- lib: { entry: path.join(root, 'apps/desktop/src/main/index.ts'), formats: ['es'] },
- ssr: true,
- },
- ssr: { noExternal: true },
- });
- await expect(hash({ graph: [graph] })).rejects.toThrow(
- 'not pinned by apps/desktop/pnpm-lock.yaml: [email protected]',
- );
- await put('apps/desktop/pnpm-lock.yaml', 'lockfileVersion: 9\npackages:\n [email protected]:\n');
- expect((await hash({ graph: [graph] })).mainHash).toMatch(/^[0-9a-f]{64}$/);
- });
-
- it('tracks star forwarding, cycles and CommonJS without dropping runtime dependencies', async () => {
- await put('apps/desktop/src/main/a.ts', 'export const selected = 11;');
- await put('apps/desktop/src/main/b.ts', 'export const selected = 22;');
- await put('apps/desktop/src/main/barrel.ts', "export * from './forward';");
- await put('apps/desktop/src/main/forward.ts', "export * from './barrel'; export * from './a';");
- await put(
- 'apps/desktop/src/main/index.ts',
- "export { selected } from './barrel'; export { selected as a } from './a'; export { selected as b } from './b';",
- );
- const before = await hash();
- await put('apps/desktop/src/main/forward.ts', "export * from './barrel'; export * from './b';");
- expect((await hash()).mainHash).not.toBe(before.mainHash);
- await put('apps/desktop/src/main/legacy.cjs', 'module.exports = { value: 11 };');
- await put(
- 'apps/desktop/src/main/index.ts',
- "import value from './legacy.cjs'; export const result = value.value;",
- );
- const legacy = await hash();
- await put('apps/desktop/src/main/legacy.cjs', 'module.exports = { value: 22 };');
- expect((await hash()).mainHash).not.toBe(legacy.mainHash);
- });
-
- it('covers unselected platform branches and keeps shared descendants in the runtime graph', async () => {
- await put(
- 'apps/desktop/src/main/index.ts',
- "export { platform } from './platform'; export { shared } from './shared';",
- );
- await put('apps/desktop/src/main/platform.ts', "export const platform = 'default';");
- await put(
- 'apps/desktop/src/main/platform.mac.ts',
- "import { shared } from './shared'; import { mac } from './mac-only'; export const platform = shared + mac;",
- );
- await put('apps/desktop/src/main/shared.ts', 'export const shared = 1;');
- await put('apps/desktop/src/main/mac-only.ts', 'export const mac = 2;');
- const platformHash = async () => {
- const graph = [];
- for (const os of ['mac', 'linux', 'windows']) {
- graph.push({
- ...(await collectViteGraph({
- configFile: false,
- root,
- build: {
- lib: { entry: path.join(root, 'apps/desktop/src/main/index.ts'), formats: ['es'] },
- },
- plugins: [viteOsPlatformResolve(os)],
- })),
- label: `main/${os}`,
- });
- }
- return hash({ graph });
- };
- const before = await platformHash();
- expect(
- before.inputs.some((item) => item.path.endsWith('/mac-only.ts') && item.group === 'platform'),
- ).toBe(true);
- await put('apps/desktop/src/main/mac-only.ts', 'export const mac = 3;');
- const platformChange = await platformHash();
- expect(platformChange.mainHash).not.toBe(before.mainHash);
- await put('apps/desktop/src/main/shared.ts', 'export const shared = 4;');
- expect((await platformHash()).mainHash).not.toBe(platformChange.mainHash);
- });
-});
-
-describe('release hash validation', () => {
- it('validates release manifests without installing Vite in the publishing job', async () => {
- const directory = path.join(root, 'validator');
- await mkdir(directory);
- for (const file of ['mainHash.mjs', 'mainHashGraph.mjs', 'validateMainHash.mjs']) {
- await cp(new URL(`../${file}`, import.meta.url), path.join(directory, file));
- }
- const manifest = await hash();
- const module = pathToFileURL(path.join(directory, 'validateMainHash.mjs')).href;
- await expect(
- promisify(execFile)(process.execPath, [
- '--input-type=module',
- '-e',
- `import { validateInputManifest } from ${JSON.stringify(module)}; validateInputManifest(${JSON.stringify(manifest)});`,
- ]),
- ).resolves.toMatchObject({ stdout: '', stderr: '' });
- });
-
- it('requires r0, the source manifest and the packaged hash to agree', async () => {
- const inputs = await hash();
- const release = path.join(root, 'release');
- await put('release/renderer-mainhash-inputs.json', JSON.stringify(inputs));
- await put('release/renderer-mainhash.txt', inputs.mainHash);
- const feed = 'release/renderer-ota/canary/1.0.0/renderer/v2';
- const pack = `packs/${'a'.repeat(64)}.zip`;
- const r0 = {
- appVersion: '1.0.0',
- version: 'r0',
- schemaVersion: 2,
- mainHash: inputs.mainHash,
- full: { path: pack },
- };
- await put(`${feed}/latest.json`, JSON.stringify(r0));
- await put(`${feed}/versions/r0.json`, JSON.stringify(r0));
- await put(`${feed}/${pack}`, 'pack');
- await expect(validateRendererBase(release, 'canary', '1.0.0')).resolves.toMatchObject({
- mainHash: inputs.mainHash,
- });
- await put(`${feed}/latest.json`, JSON.stringify({ ...r0, mainHash: 'b'.repeat(64) }));
- await expect(validateRendererBase(release, 'canary', '1.0.0')).rejects.toThrow(
- 'does not match',
- );
- await put(`${feed}/latest.json`, JSON.stringify(r0));
- await rm(path.join(root, feed, pack));
- await expect(validateRendererBase(release, 'canary', '1.0.0')).rejects.toThrow();
- });
-
- it('blocks missing platforms and changed contents before writing a canonical base', async () => {
- const before = await hash();
- const release = path.join(root, 'release');
- await put('release/renderer-mainhash/mac.json', JSON.stringify(before));
- await expect(validateReleaseInputs(release, ['mac', 'linux'])).rejects.toThrow('expected');
- await put('apps/desktop/src/main/index.ts', 'export const changed = true;');
- const after = await hash();
- await put('release/renderer-mainhash/linux.json', JSON.stringify(after));
- await expect(validateReleaseInputs(release, ['mac', 'linux'])).rejects.toThrow(
- 'oss/apps/desktop/src/main/index.ts',
- );
- await expect(readFile(path.join(release, 'renderer-mainhash.txt'))).rejects.toThrow();
- await put('release/renderer-mainhash/linux.json', JSON.stringify(before));
- await validateReleaseInputs(release, ['mac', 'linux']);
- expect((await readFile(path.join(release, 'renderer-mainhash.txt'), 'utf8')).trim()).toBe(
- before.mainHash,
- );
- expect(() => validateInputManifest({ ...before, mainHash: after.mainHash })).toThrow(
- 'does not match',
- );
- expect(() => validateInputManifest({ ...before, algorithm: 'old-bundle' })).toThrow(
- 'full release required',
- );
- });
-});
diff --git a/apps/desktop/scripts/__tests__/reportRendererOta.test.mjs b/apps/desktop/scripts/__tests__/reportRendererOta.test.mjs
index 6ec8838e0b1..0ddaef14939 100644
--- a/apps/desktop/scripts/__tests__/reportRendererOta.test.mjs
+++ b/apps/desktop/scripts/__tests__/reportRendererOta.test.mjs
@@ -15,20 +15,20 @@ let root;
afterEach(async () => {
if (root) await rm(root, { recursive: true, force: true });
});
-const base = { outcome: 'success', outputs: { found: 'true', main_hash: 'a'.repeat(64) } };
-const gate = { outcome: 'success', outputs: { allowed: 'true', main_hash: 'a'.repeat(64) } };
+const base = { outcome: 'success', outputs: { found: 'true', shell_abi: 'a'.repeat(64) } };
+const gate = { outcome: 'success', outputs: { allowed: 'true', shell_abi: 'a'.repeat(64) } };
+const version = { outcome: 'success', outputs: { seq: '4', version: '1.0.0-core.4' } };
-describe('renderer OTA diagnostic outcomes', () => {
+describe('classifyResult', () => {
it('requests a full release only for a successfully evaluated compatibility decision', () => {
expect(
classifyResult({
base,
- gate: { outcome: 'success', outputs: { allowed: 'false', reason: 'main-changed' } },
+ gate: { outcome: 'success', outputs: { allowed: 'false', reason: 'abi-changed' } },
}),
- ).toMatchObject({ outcome: 'skipped', reason: 'main-changed', requiresFullRelease: true });
+ ).toMatchObject({ outcome: 'skipped', reason: 'abi-changed', requiresFullRelease: true });
expect(classifyResult({ base, gate: { outcome: 'failure' } })).toMatchObject({
- outcome: 'failed',
- reason: 'hash-compute-failed',
+ reason: 'abi-compute-failed',
requiresFullRelease: false,
});
expect(classifyResult({ base: { outcome: 'failure' } })).toMatchObject({
@@ -41,29 +41,47 @@ describe('renderer OTA diagnostic outcomes', () => {
expect(
classifyResult({
base: { outcome: 'success', outputs: { found: 'false', reason: 'base-missing' } },
+ gate: { outcome: 'success', outputs: { allowed: 'false', reason: 'abi-changed' } },
}),
).toMatchObject({ reason: 'base-missing', requiresFullRelease: true });
+ expect(classifyResult({ base, gate, version })).toMatchObject({
+ outcome: 'gated',
+ reason: 'core-allowed',
+ requiresFullRelease: false,
+ });
});
it.each([
['setup', 'environment-setup-failed'],
- ['renderer', 'renderer-build-failed'],
- ['sign', 'manifest-sign-failed'],
- ['publish', 'upload-failed'],
- ])(
- 'retains %s failure instead of reporting an incompatible or published patch',
- (stage, reason) => {
- expect(classifyResult({ base, gate, [stage]: { outcome: 'failure' } })).toMatchObject({
- reason,
- outcome: 'failed',
- published: false,
- requiresFullRelease: false,
- });
- },
- );
+ ['build', 'core-build-failed'],
+ ['core', 'core-release-failed'],
+ ['upload', 'artifact-upload-failed'],
+ ])('retains core-build %s failure', (stage, reason) => {
+ expect(classifyResult({ [stage]: { outcome: 'failure' } }, 'core-build')).toMatchObject({
+ reason,
+ outcome: 'failed',
+ published: false,
+ requiresFullRelease: false,
+ });
+ });
+
+ it('reports unchanged cores as skipped and uploaded cores as built', () => {
+ expect(
+ classifyResult({ core: { outcome: 'success', outputs: { skipped: 'true' } } }, 'core-build'),
+ ).toMatchObject({ outcome: 'skipped', reason: 'core-unchanged' });
+ expect(
+ classifyResult(
+ {
+ core: { outcome: 'success', outputs: { skipped: 'false' } },
+ upload: { outcome: 'success' },
+ },
+ 'core-build',
+ ),
+ ).toMatchObject({ outcome: 'built', reason: 'core-ready' });
+ });
it('distinguishes cancellation, prepared artifacts and actual publication', () => {
- expect(classifyResult({ base, gate, renderer: { outcome: 'cancelled' } })).toMatchObject({
+ expect(classifyResult({ base, gate, version: { outcome: 'cancelled' } })).toMatchObject({
reason: 'cancelled',
published: false,
requiresFullRelease: false,
@@ -83,11 +101,23 @@ describe('renderer OTA diagnostic outcomes', () => {
).toMatchObject({ published: true });
expect(
classifyResult(
- { base, gate, version: { outputs: { version: 'r2' } }, publish: { outcome: 'success' } },
- 'patch',
- 'cancelled',
+ {
+ collect: { outcome: 'success', outputs: { skipped: 'false' } },
+ publish: { outcome: 'success', outputs: { published: 'true' } },
+ },
+ 'core-publish',
),
- ).toMatchObject({ published: true, version: 'r2', reason: 'published' });
+ ).toMatchObject({ published: true, reason: 'published' });
+ expect(
+ classifyResult(
+ { collect: { outcome: 'success', outputs: { skipped: 'true' } } },
+ 'core-publish',
+ ),
+ ).toMatchObject({ outcome: 'skipped', reason: 'core-unchanged' });
+ expect(classifyResult({ publish: { outcome: 'failure' } }, 'core-publish')).toMatchObject({
+ outcome: 'failed',
+ reason: 'upload-failed',
+ });
});
it('writes CLI evidence after setup failure without exposing unrelated outputs or secrets', async () => {
@@ -101,7 +131,7 @@ describe('renderer OTA diagnostic outcomes', () => {
cwd: root,
env: {
...process.env,
- DIAGNOSTIC_KIND: 'patch',
+ DIAGNOSTIC_KIND: 'core-build',
CHANNEL: 'canary',
GITHUB_SHA: 'fixture-commit',
GITHUB_RUN_ID: '123',
@@ -110,17 +140,15 @@ describe('renderer OTA diagnostic outcomes', () => {
GITHUB_STEP_SUMMARY: summary,
RENDERER_OTA_PRIVATE_KEY: 'NEVER-LOG-THIS-PRIVATE-KEY',
STEPS_JSON: JSON.stringify({
- base,
setup: { outcome: 'failure', outputs: { token: 'NEVER-LOG-THIS-TOKEN' } },
}),
},
});
- const data = await readFile(path.join(root, 'renderer-ota-diagnostics/result.json'), 'utf8');
+ const data = await readFile(path.join(root, 'desktop-ota-diagnostics/result.json'), 'utf8');
expect(JSON.parse(data)).toMatchObject({
reason: 'environment-setup-failed',
commit: 'fixture-commit',
runId: '123',
- inputManifestStatus: 'missing',
lockSha256: expect.stringMatching(/^[a-f0-9]{64}$/),
});
expect(data).not.toContain('NEVER-LOG');
diff --git a/apps/desktop/scripts/__tests__/shellAbi.test.mjs b/apps/desktop/scripts/__tests__/shellAbi.test.mjs
new file mode 100644
index 00000000000..41491af2c58
--- /dev/null
+++ b/apps/desktop/scripts/__tests__/shellAbi.test.mjs
@@ -0,0 +1,124 @@
+import { execFileSync } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { computeShellAbi } from '../shellAbi.mjs';
+
+const LOCK = `lockfileVersion: '9.0'
+
+importers:
+
+ .:
+ dependencies:
+ foo:
+ specifier: ^1.0.0
+ version: 1.0.0
+
+packages:
+
+ '@scope/[email protected]':
+ resolution: {integrity: sha512-bar}
+
+ resolution: {integrity: sha512-foo}
+ engines: {node: '>=14'}
+
+ resolution: {integrity: sha512-unrelated}
+
+snapshots:
+
+`;
+
+let root;
+const write = (file, content) => {
+ const abs = path.join(root, file);
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
+ fs.writeFileSync(abs, content);
+};
+const git = (...args) => execFileSync('git', args, { cwd: root, stdio: 'pipe' });
+const abi = (publicKey = 'KEY') => computeShellAbi({ publicKey, root });
+
+beforeEach(() => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'shell-abi-'));
+ write(
+ 'apps/desktop/package.json',
+ JSON.stringify({
+ dependencies: { '@scope/bar': '^2.0.0', 'foo': '^1.0.0' },
+ devDependencies: { '@anthropic-ai/sandbox-runtime': '0.0.1', 'electron': '40.0.0' },
+ version: '1.2.3',
+ }),
+ );
+ write('apps/desktop/pnpm-lock.yaml', LOCK);
+ write('apps/desktop/shell/main.js', 'require("./core-loader")');
+ write('apps/desktop/shell/abi.json', '{"shellAbi":"x"}');
+ write('apps/desktop/shell/__tests__/x.test.mjs', 'test');
+ write('apps/desktop/build/icon.png', 'png');
+ write('apps/desktop/build/icon-beta.png', 'beta-png');
+ write('apps/desktop/build/Icon.Assets.car', 'car');
+ write('apps/desktop/electron-builder.mjs', 'export default {}');
+ write('packages/native/binding.gyp', '{}');
+ write('packages/native/src/a.cc', 'int main() {}');
+ write('packages/pure/index.js', 'pure');
+ git('init', '-q');
+ git('add', '-A');
+});
+
+afterEach(() => fs.rmSync(root, { force: true, recursive: true }));
+
+describe('computeShellAbi', () => {
+ it('returns a stable 64-hex hash for the same inputs', () => {
+ const first = abi();
+ expect(first).toMatch(/^[a-f0-9]{64}$/);
+ expect(abi()).toBe(first);
+ });
+
+ it('changes when a shell file, native package, lock entry or public key changes', () => {
+ const base = abi();
+
+ write('apps/desktop/shell/main.js', 'changed');
+ const afterShell = abi();
+ expect(afterShell).not.toBe(base);
+
+ write('packages/native/src/a.cc', 'changed');
+ const afterNative = abi();
+ expect(afterNative).not.toBe(afterShell);
+
+ write('apps/desktop/pnpm-lock.yaml', LOCK.replace('sha512-foo', 'sha512-foo2'));
+ const afterLock = abi();
+ expect(afterLock).not.toBe(afterNative);
+
+ expect(abi('OTHER')).not.toBe(afterLock);
+ });
+
+ it('ignores abi.json, shell tests, untracked files, non-native packages and unrelated lock entries', () => {
+ const base = abi();
+ write('apps/desktop/shell/abi.json', '{"shellAbi":"y"}');
+ write('apps/desktop/shell/__tests__/x.test.mjs', 'changed');
+ write('apps/desktop/shell/untracked.js', 'new');
+ write('packages/pure/index.js', 'changed');
+ write('apps/desktop/pnpm-lock.yaml', LOCK.replace('sha512-unrelated', 'sha512-unrelated2'));
+ expect(abi()).toBe(base);
+ });
+
+ it('ignores the channel-swapped icon targets but not their variants', () => {
+ const base = abi();
+ write('apps/desktop/build/icon.png', 'beta-png');
+ write('apps/desktop/build/Icon.icns', 'beta-icns');
+ write('apps/desktop/build/icon.ico', 'beta-ico');
+ expect(abi()).toBe(base);
+ write('apps/desktop/build/icon-beta.png', 'changed');
+ expect(abi()).not.toBe(base);
+ write('apps/desktop/build/icon-beta.png', 'beta-png');
+ write('apps/desktop/build/Icon.Assets.car', 'changed');
+ expect(abi()).not.toBe(base);
+ });
+
+ it('normalizes CRLF and whitespace in the public key', () => {
+ expect(abi('KEY\r\n')).toBe(abi('KEY'));
+ });
+});
diff --git a/apps/desktop/scripts/assembleCore.mjs b/apps/desktop/scripts/assembleCore.mjs
new file mode 100644
index 00000000000..4a4651848f4
--- /dev/null
+++ b/apps/desktop/scripts/assembleCore.mjs
@@ -0,0 +1,56 @@
+import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const DESKTOP_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const CLI_DIR = path.resolve(DESKTOP_DIR, '../cli');
+const RESOURCES_EXCLUDED = new Set(['bin', 'cli-package.json', 'dmg.png', 'locales']);
+
+export function assembleCore({
+ cliDir = CLI_DIR,
+ desktopDir = DESKTOP_DIR,
+ out = path.join(DESKTOP_DIR, 'core-dist'),
+} = {}) {
+ const inputs = {
+ 'apps/cli/dist/index.js': path.join(cliDir, 'dist/index.js'),
+ 'dist/main': path.join(desktopDir, 'dist/main'),
+ 'dist/preload': path.join(desktopDir, 'dist/preload'),
+ 'dist/renderer': path.join(desktopDir, 'dist/renderer'),
+ 'node_modules/electron-log': path.join(desktopDir, 'node_modules/electron-log'),
+ 'resources': path.join(desktopDir, 'resources'),
+ };
+ const missing = Object.entries(inputs)
+ .filter(([, abs]) => !existsSync(abs))
+ .map(([label]) => label);
+ if (missing.length) throw new Error(`assembleCore: missing inputs: ${missing.join(', ')}`);
+
+ rmSync(out, { force: true, recursive: true });
+ const copy = (from, to, filter) =>
+ cpSync(from, path.join(out, to), { dereference: true, filter, recursive: true });
+
+ copy(inputs['dist/main'], 'dist/main');
+ copy(inputs['dist/preload'], 'dist/preload');
+ copy(inputs['dist/renderer'], 'dist/renderer');
+ copy(
+ inputs.resources,
+ 'resources',
+ (src) => !RESOURCES_EXCLUDED.has(path.relative(inputs.resources, src).split(path.sep)[0]),
+ );
+ copy(inputs['node_modules/electron-log'], 'node_modules/electron-log');
+ writeFileSync(path.join(out, 'package.json'), JSON.stringify({ type: 'commonjs' }));
+
+ mkdirSync(path.join(out, 'cli'), { recursive: true });
+ cpSync(inputs['apps/cli/dist/index.js'], path.join(out, 'cli/lobe-cli.js'));
+ const { name, version } = JSON.parse(readFileSync(path.join(cliDir, 'package.json'), 'utf8'));
+ writeFileSync(
+ path.join(out, 'cli/package.json'),
+ JSON.stringify({ name, type: 'module', version }),
+ );
+ return out;
+}
+
+if (process.argv[1] === fileURLToPath(import.meta.url)) {
+ const outArg = process.argv.find((arg) => arg.startsWith('--out='))?.slice(6);
+ const out = assembleCore(outArg ? { out: path.resolve(outArg) } : {});
+ console.log(`core assembled at ${out}`);
+}
diff --git a/apps/desktop/scripts/buildCore.mjs b/apps/desktop/scripts/buildCore.mjs
new file mode 100644
index 00000000000..be342e5f467
--- /dev/null
+++ b/apps/desktop/scripts/buildCore.mjs
@@ -0,0 +1,206 @@
+import { createHash } from 'node:crypto';
+import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { constants, zstdCompressSync, zstdDecompressSync } from 'node:zlib';
+
+import {
+ createCoreManifest,
+ parseArgs,
+ readCoreTree,
+ readPrivateKey,
+ writeCoreManifest,
+} from './buildCoreManifest.mjs';
+import { encodePack } from './buildRendererManifest.mjs';
+import { generateZstdPatch, pairRendererFiles } from './rendererDelta.mjs';
+
+const PATCH_SCOPE = /^(?:dist\/renderer|cli)\//;
+const RELOAD_SCOPE = 'dist/renderer/';
+const ZSTD_LEVEL = { params: { [constants.ZSTD_c_compressionLevel]: 19 } };
+
+export class EmptyReleaseError extends Error {
+ constructor() {
+ super('empty release');
+ }
+}
+
+const sha256Of = (content) => createHash('sha256').update(content).digest('hex');
+
+const writeIfMissing = (file, content) => {
+ if (existsSync(file)) return false;
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, content);
+ return true;
+};
+
+const changedPaths = (fromTree, toTree) => {
+ const from = new Map(fromTree.map((file) => [file.path, file.sha256]));
+ const to = new Map(toTree.map((file) => [file.path, file.sha256]));
+ return [...new Set([...from.keys(), ...to.keys()])].filter(
+ (filePath) => from.get(filePath) !== to.get(filePath),
+ );
+};
+
+const previousObject = async (sha256, outDir, objectsBaseUrl, fetchImpl) => {
+ try {
+ const local = path.join(outDir, 'cas/objects', `${sha256}.zst`);
+ let content;
+ if (existsSync(local)) {
+ content = zstdDecompressSync(readFileSync(local));
+ } else {
+ const response = await fetchImpl(`${objectsBaseUrl}/objects/${sha256}.zst`);
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ content = zstdDecompressSync(Buffer.from(await response.arrayBuffer()));
+ }
+ if (sha256Of(content) !== sha256) throw new Error('sha256 mismatch');
+ return content;
+ } catch (error) {
+ console.error(`patch skipped ${sha256}: ${error.message}`);
+ return null;
+ }
+};
+
+const buildPatches = async ({ fetchImpl, objects, objectsBaseUrl, outDir, previousTree, tree }) => {
+ const patches = new Map();
+ const pairings = pairRendererFiles(
+ previousTree.filter((file) => PATCH_SCOPE.test(file.path)),
+ tree.filter((file) => PATCH_SCOPE.test(file.path)),
+ );
+ for (const pairing of pairings) {
+ if (pairing.kind !== 'patch') continue;
+ const key = `${pairing.from.sha256}-${pairing.to.sha256}`;
+ if (patches.has(key)) continue;
+ const oldContent = await previousObject(pairing.from.sha256, outDir, objectsBaseUrl, fetchImpl);
+ if (!oldContent) continue;
+ const patch = await generateZstdPatch(oldContent, objects.get(pairing.to.sha256));
+ if (!patch) continue;
+ writeIfMissing(path.join(outDir, 'cas/patches', `${key}.zst`), patch);
+ patches.set(key, {
+ fromSha256: pairing.from.sha256,
+ size: patch.byteLength,
+ toSha256: pairing.to.sha256,
+ });
+ }
+ return [...patches.values()].sort((a, b) => a.toSha256.localeCompare(b.toSha256));
+};
+
+export async function buildCore({
+ channel,
+ coreDir,
+ fetchImpl = fetch,
+ objectsBaseUrl,
+ outDir,
+ platform,
+ previousManifest = null,
+ privateKeyPem,
+ rollout = 1,
+ seq,
+ shellAbi,
+ version,
+}) {
+ if (!privateKeyPem) throw new Error('private key required (--private-key-file or env)');
+ const { objects, tree } = readCoreTree(coreDir);
+
+ let applyMode = null;
+ let patches = [];
+ if (previousManifest) {
+ const changed = changedPaths(previousManifest.tree, tree);
+ if (changed.every((filePath) => filePath === 'package.json')) throw new EmptyReleaseError();
+ applyMode = changed.every((filePath) => filePath.startsWith(RELOAD_SCOPE))
+ ? 'reload'
+ : 'relaunch';
+ }
+
+ let objectsWritten = 0;
+ let objectBytes = 0;
+ for (const [sha256, content] of objects) {
+ const file = path.join(outDir, 'cas/objects', `${sha256}.zst`);
+ if (existsSync(file)) {
+ objectBytes += statSync(file).size;
+ continue;
+ }
+ const zst = zstdCompressSync(content, ZSTD_LEVEL);
+ objectBytes += zst.byteLength;
+ writeIfMissing(file, zst);
+ objectsWritten += 1;
+ }
+
+ if (previousManifest) {
+ patches = await buildPatches({
+ fetchImpl,
+ objects,
+ objectsBaseUrl,
+ outDir,
+ previousTree: previousManifest.tree,
+ tree,
+ });
+ }
+
+ const pack = encodePack(
+ new Map([...objects].map(([sha256, content]) => [`objects/${sha256}`, { content }])),
+ );
+ const packSha256 = sha256Of(pack);
+ const full = { path: `packs/${packSha256}.zip`, sha256: packSha256, size: pack.byteLength };
+ const platformDir = path.join(outDir, 'core', platform);
+ writeIfMissing(path.join(platformDir, full.path), pack);
+
+ const manifest = createCoreManifest({
+ applyMode,
+ channel,
+ full,
+ objectsBaseUrl,
+ patches,
+ platform,
+ previous: previousManifest?.version ?? null,
+ privateKeyPem,
+ rollout,
+ seq,
+ shellAbi,
+ tree,
+ version,
+ });
+ const json = JSON.stringify(manifest, null, 2);
+ mkdirSync(path.join(platformDir, 'versions'), { recursive: true });
+ writeFileSync(path.join(platformDir, 'versions', `${version}.json`), json);
+ writeFileSync(path.join(platformDir, 'latest.json'), json);
+ writeCoreManifest(coreDir, manifest);
+
+ return {
+ manifest,
+ stats: { objectBytes, objects: objects.size, objectsWritten, patches: patches.length },
+ };
+}
+
+if (process.argv[1] === fileURLToPath(import.meta.url)) {
+ const args = parseArgs(process.argv.slice(2));
+ const started = Date.now();
+ try {
+ const { manifest, stats } = await buildCore({
+ channel: args.channel,
+ coreDir: path.resolve(args.core ?? 'core-dist'),
+ objectsBaseUrl: args['objects-base-url'],
+ outDir: path.resolve(args.out ?? 'release/core-ota'),
+ platform: args.platform,
+ previousManifest: args['previous-manifest']
+ ? JSON.parse(readFileSync(args['previous-manifest'], 'utf8'))
+ : null,
+ privateKeyPem: readPrivateKey(args),
+ rollout: args.rollout === undefined ? 1 : Number(args.rollout),
+ seq: Number(args.seq),
+ shellAbi: args['shell-abi'],
+ version: args.version,
+ });
+ console.log(
+ `core ${manifest.channel}/${manifest.platform} ${manifest.version} seq ${manifest.seq}: ` +
+ `${manifest.tree.length} files, ${stats.objects} objects (${stats.objectsWritten} new, ${(stats.objectBytes / 1048576).toFixed(2)} MB zst), ` +
+ `${stats.patches} patches, full ${(manifest.full.size / 1048576).toFixed(2)} MB, ` +
+ `applyMode ${manifest.applyMode}, previous ${manifest.previous}, ${((Date.now() - started) / 1000).toFixed(1)}s`,
+ );
+ } catch (error) {
+ if (error instanceof EmptyReleaseError) {
+ console.error('empty release');
+ process.exit(3);
+ }
+ throw error;
+ }
+}
diff --git a/apps/desktop/scripts/buildCoreManifest.mjs b/apps/desktop/scripts/buildCoreManifest.mjs
new file mode 100644
index 00000000000..71e380b85b6
--- /dev/null
+++ b/apps/desktop/scripts/buildCoreManifest.mjs
@@ -0,0 +1,137 @@
+import { readFileSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { readRendererTree, signManifest } from './buildRendererManifest.mjs';
+
+const SHA256 = /^[0-9a-f]{64}$/;
+const CHANNELS = new Set(['stable', 'beta', 'canary', 'nightly']);
+const PLATFORMS = new Set(['darwin', 'win32', 'linux']);
+
+export const PLACEHOLDER_OBJECTS_BASE_URL = 'https://core-ota.invalid/cas';
+export const PLACEHOLDER_FULL = {
+ path: `packs/${'0'.repeat(64)}.zip`,
+ sha256: '0'.repeat(64),
+ size: 1,
+};
+
+const assertManifest = (manifest) => {
+ const problems = [];
+ if (!CHANNELS.has(manifest.channel)) problems.push(`channel ${manifest.channel}`);
+ if (!PLATFORMS.has(manifest.platform)) problems.push(`platform ${manifest.platform}`);
+ if (!manifest.version) problems.push('version');
+ if (!Number.isInteger(manifest.seq) || manifest.seq < 0) problems.push(`seq ${manifest.seq}`);
+ if (!SHA256.test(manifest.shellAbi)) problems.push(`shellAbi ${manifest.shellAbi}`);
+ if (manifest.tree.length === 0) problems.push('tree empty');
+ if (manifest.tree.some((file) => !SHA256.test(file.sha256))) problems.push('tree sha256');
+ if (!URL.canParse(manifest.objectsBaseUrl)) problems.push('objectsBaseUrl');
+ if (manifest.full?.path !== `packs/${manifest.full?.sha256}.zip`) problems.push('full');
+ if (!Number.isFinite(manifest.rollout) || manifest.rollout < 0 || manifest.rollout > 1)
+ problems.push(`rollout ${manifest.rollout}`);
+ if (problems.length) throw new Error(`core manifest invalid: ${problems.join(', ')}`);
+};
+
+export const readCoreTree = (coreDir) => {
+ const { objects, tree: allFiles } = readRendererTree(coreDir);
+ const tree = allFiles.filter(
+ (file) => file.path !== 'manifest.json' && path.posix.basename(file.path) !== '.DS_Store',
+ );
+ const referenced = new Set(tree.map((file) => file.sha256));
+ for (const sha256 of objects.keys()) if (!referenced.has(sha256)) objects.delete(sha256);
+ return { objects, tree };
+};
+
+export function createCoreManifest({
+ applyMode = null,
+ channel,
+ full,
+ objectsBaseUrl,
+ patches = [],
+ platform,
+ previous = null,
+ privateKeyPem,
+ rollout = 1,
+ seq,
+ shellAbi,
+ tree,
+ version,
+}) {
+ const unsigned = {
+ applyMode,
+ channel,
+ full,
+ objectsBaseUrl,
+ patches,
+ platform,
+ previous,
+ rollout,
+ schemaVersion: 3,
+ seq,
+ shellAbi,
+ tree,
+ version,
+ };
+ assertManifest(unsigned);
+ if (privateKeyPem) return signManifest(unsigned, privateKeyPem);
+ console.info(
+ 'core manifest: no private key, writing unsigned manifest (builtin cores need no signature)',
+ );
+ return { ...unsigned, signature: '' };
+}
+
+export const writeCoreManifest = (coreDir, manifest) =>
+ writeFileSync(path.join(coreDir, 'manifest.json'), JSON.stringify(manifest, null, 2));
+
+export async function buildCoreManifest({
+ channel,
+ coreDir,
+ objectsBaseUrl = PLACEHOLDER_OBJECTS_BASE_URL,
+ platform,
+ privateKeyPem,
+ seq,
+ shellAbi,
+ version,
+}) {
+ const manifest = createCoreManifest({
+ channel,
+ full: PLACEHOLDER_FULL,
+ objectsBaseUrl,
+ platform,
+ privateKeyPem,
+ seq,
+ shellAbi,
+ tree: readCoreTree(coreDir).tree,
+ version,
+ });
+ writeCoreManifest(coreDir, manifest);
+ return manifest;
+}
+
+export const parseArgs = (argv) =>
+ Object.fromEntries(
+ argv
+ .filter((arg) => arg.startsWith('--'))
+ .map((arg) => arg.slice(2).split(/=(.*)/s).slice(0, 2)),
+ );
+
+export const readPrivateKey = (args) =>
+ args['private-key-file']
+ ? readFileSync(args['private-key-file'], 'utf8')
+ : process.env.RENDERER_OTA_PRIVATE_KEY;
+
+if (process.argv[1] === fileURLToPath(import.meta.url)) {
+ const args = parseArgs(process.argv.slice(2));
+ const manifest = await buildCoreManifest({
+ channel: args.channel,
+ coreDir: path.resolve(args.core ?? 'core-dist'),
+ objectsBaseUrl: args['objects-base-url'],
+ platform: args.platform,
+ privateKeyPem: readPrivateKey(args),
+ seq: Number(args.seq),
+ shellAbi: args['shell-abi'],
+ version: args.version,
+ });
+ console.log(
+ `core manifest: ${manifest.channel}/${manifest.platform} ${manifest.version} seq ${manifest.seq} (${manifest.tree.length} files, ${manifest.signature ? 'signed' : 'UNSIGNED'})`,
+ );
+}
diff --git a/apps/desktop/scripts/buildRendererManifest.mjs b/apps/desktop/scripts/buildRendererManifest.mjs
index 7ccb2bc0903..18e18d5b733 100644
--- a/apps/desktop/scripts/buildRendererManifest.mjs
+++ b/apps/desktop/scripts/buildRendererManifest.mjs
@@ -12,7 +12,6 @@ import { fileURLToPath } from 'node:url';
import { unzipSync, zipSync } from 'fflate';
-import { computeMainHash } from './mainHash.mjs';
import { candidateDeltaVersions, generateZstdPatch, pairRendererFiles } from './rendererDelta.mjs';
const PACK_COMPRESSION_LEVEL = 9;
@@ -352,7 +351,8 @@ async function main() {
.export({ format: 'pem', type: 'spki' })
.toString();
const feedDir = path.join(outDir, channel, appVersion, 'renderer', 'v2');
- const mainHash = args.mainHash ?? (await computeMainHash());
+ const mainHash = args.mainHash;
+ if (!/^[0-9a-f]{64}$/.test(mainHash ?? '')) throw new Error('--mainHash=<sha256> is required');
const { objects, tree } = readRendererTree(rendererDir);
const fullMetadata = { kind: 'full', packVersion: 1, tree, version };
const fullPack = encodePack(fullPackEntries(objects, fullMetadata));
diff --git a/apps/desktop/scripts/core-ota-test/README.md b/apps/desktop/scripts/core-ota-test/README.md
new file mode 100644
index 00000000000..7e46b22b74b
--- /dev/null
+++ b/apps/desktop/scripts/core-ota-test/README.md
@@ -0,0 +1,93 @@
+# Core OTA 本地 E2E(打包态)
+
+在本机打一个 arm64 的壳 + 内置 core(v1),再用本地 feed 依次发布 renderer-only(v2,reload)
+和 main 变更(v3,relaunch),最后验证篡改拒绝和 boot 回滚。所有命令在 `apps/desktop/` 下执行。
+
+产物都在 `release/core-ota-e2e/`:`priv.pem`/`pub.pem`、`app/`(打包结果)、`core-v1..v3/`、`feed/`。
+app 名固定为 `lobehub-core-ota-e2e`,userData 在 `~/Library/Application Support/lobehub-core-ota-e2e`,
+日志在 `~/Library/Logs/lobehub-core-ota-e2e/main.log`,与开发实例互不干扰。
+
+## 1. 构建 v1(一次,约 10 分钟)
+
+```bash
+node scripts/core-ota-test/run.mjs keys
+node scripts/core-ota-test/run.mjs build # dist/ 已存在则跳过 build:main;打包用 --dir,不签名不公证
+```
+
+`build` 会把 `package.json` 的 name/version 临时改成 `lobehub-core-ota-e2e`/`1.0.0`(Electron 用 name 决定 userData),结束后 `run.mjs restore` 还原。
+壳的 `abi.json`、内置 core 的签名 manifest(seq 0)由 `electron-builder.mjs` 的 `beforePack` 生成;
+`feed/` 里的 r0 与内置 core 字节一致。
+
+## 2. renderer-only 更新(reload)
+
+```bash
+node scripts/core-ota-test/run.mjs v2 # index.html 加一个红色 "CORE V2" 角标,seq 1
+node scripts/core-ota-test/run.mjs serve & # http://127.0.0.1:8787
+node scripts/core-ota-test/run.mjs reset # 清 userData/日志
+node scripts/core-ota-test/run.mjs launch # RENDERER_OTA_CHECK_DELAY=3000
+```
+
+期望:日志 `Core OTA staged {"applyMode":"reload",...}`;toast 点「刷新」或等 5 分钟空闲后窗口右上角出现 `CORE V2`;
+`run.mjs state` 显示 `current: "1.0.0-core.1"`。
+
+## 3. main 变更(relaunch)
+
+```bash
+node scripts/core-ota-test/run.mjs v3 # dist/main/index.js 追加 console.log('core v3'),seq 2
+```
+
+app 内触发检查(或等 60 分钟定时)→ 日志 `applyMode":"relaunch"` → toast「立即重启」→
+重启后日志开头出现 `core v3`,`state` 显示 `current: "1.0.0-core.2"`,壳日志 `source: external`。
+
+## 4. 篡改拒绝
+
+```bash
+node scripts/core-ota-test/run.mjs kill
+node scripts/core-ota-test/run.mjs tamper # 改 cores/1.0.0-core.2/dist/main/index.js
+node scripts/core-ota-test/run.mjs launch
+```
+
+期望:壳日志 `core 1.0.0-core.2 rejected: ... hash mismatch`,回退到 `previous`(1.0.0-core.1)。
+
+## 5. boot 失败回滚
+
+直接改 `cores/<v>/` 里的文件会被壳的 hash 校验拦下(等于第 4 步),所以发布一个签名有效但 renderer 永远不 mount 的 v4:
+
+```bash
+node scripts/core-ota-test/run.mjs v4 # index.html 只引一个 js 资源并 throw,seq 3,reload
+node scripts/core-ota-test/run.mjs eval "window.electronAPI.invoke('rendererOta.checkNow')"
+node scripts/core-ota-test/run.mjs eval "window.electronAPI.invoke('rendererOta.applyNow')"
+```
+
+期望:3 s 内 `Core OTA rolled back {coldBoot: false, reason: 'load-timeout'}`,pointer `blacklist` 含 `1.0.0-core.3`,
+窗口回到 v3 的 renderer。冷启动检查:把 `pointer.current` 手动指回 `1.0.0-core.3`、删掉 `boot.json` 再 `launch`,
+60 s 后 `Core OTA rolled back {coldBoot: true}` 并自动 relaunch 到上一版本。
+
+## 6. 壳救援(内置 core 坏掉)
+
+```bash
+R=release/core-ota-e2e/app/mac-arm64/lobehub-core-ota-e2e.app/Contents/Resources
+cp $R/core/dist/main/index.js /tmp/core-main.js # 结束后拷回
+sed -i '' '1s/^/throw new Error("e2e builtin boom");/' $R/core/dist/main/index.js
+# --dir 打包没有 app-update.yml,救援靠它拿 feed 地址
+printf 'provider: generic\nurl: http://127.0.0.1:8787/stable\n' > $R/app-update.yml
+```
+
+在 `feed/` 放一个 `stable-mac.yml`(`version: 1.0.0` 走「已是最新」,更高版本走下载 → `quitAndInstall`)。
+
+期望:`launch` 后出现救援窗口和对话框,`userData/logs/shell-rescue.log` 记录原始错误和检查结果;
+`boot.json` 为 `[email protected]` failures 3,下一次启动不再加载 core 直接进救援;「重试启动」清掉计数并真正重新加载 core。
+假 zip 会让 Squirrel.Mac 报 `Could not locate update bundle`,此时应回到失败对话框而不是卡在「正在安装」。
+
+## 辅助
+
+`launch` 带 `--remote-debugging-port=9333`,`run.mjs eval "<js>"` 在主窗口里求值(`window.electronAPI.invoke('rendererOta.<applyNow|checkNow|getStatus>')`),
+`run.mjs eval --shot <file.png>` 截主窗口。`tamper` 改 `cores/1.0.0-core.2/dist/main/index.js` 一行。
+onboarding 页不挂 UpdateNotification,toast 要登录后才看得到;用 `eval` 触发 IPC 即可。
+
+## 收尾
+
+```bash
+node scripts/core-ota-test/run.mjs kill
+node scripts/core-ota-test/run.mjs restore
+```
diff --git a/apps/desktop/scripts/core-ota-test/run.mjs b/apps/desktop/scripts/core-ota-test/run.mjs
new file mode 100644
index 00000000000..50da53038f9
--- /dev/null
+++ b/apps/desktop/scripts/core-ota-test/run.mjs
@@ -0,0 +1,245 @@
+import { execSync, spawn } from 'node:child_process';
+import { generateKeyPairSync } from 'node:crypto';
+import {
+ appendFileSync,
+ cpSync,
+ existsSync,
+ mkdirSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const DESKTOP_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
+const WORK = path.join(DESKTOP_DIR, 'release/core-ota-e2e');
+const FEED = path.join(WORK, 'feed');
+const PORT = 8787;
+const CDP_PORT = 9333;
+const PRODUCT = 'lobehub-core-ota-e2e';
+const CHANNEL = 'stable';
+const APP_VERSION = '1.0.0';
+const PLATFORM = 'darwin';
+const APP = path.join(WORK, 'app', 'mac-arm64', `${PRODUCT}.app`, 'Contents', 'MacOS', PRODUCT);
+const USER_DATA = path.join(os.homedir(), 'Library/Application Support', PRODUCT);
+const LOG = path.join(os.homedir(), 'Library/Logs', PRODUCT, 'main.log');
+
+const keys = () => ({
+ privateKey: readFileSync(path.join(WORK, 'priv.pem'), 'utf8'),
+ publicKey: readFileSync(path.join(WORK, 'pub.pem'), 'utf8'),
+});
+
+const sh = (cmd, env = {}) =>
+ execSync(cmd, { cwd: DESKTOP_DIR, env: { ...process.env, ...env }, stdio: 'inherit' });
+
+const coreDir = (tag) => path.join(WORK, `core-${tag}`);
+const manifestOf = (tag) =>
+ JSON.parse(readFileSync(path.join(coreDir(tag), 'manifest.json'), 'utf8'));
+
+const publish = (tag, { version, seq, previous }) => {
+ const { shellAbi } = manifestOf(previous ?? tag);
+ const previousArg = previous
+ ? `--previous-manifest=${path.join(FEED, 'core', PLATFORM, 'versions', `${manifestOf(previous).version}.json`)}`
+ : '';
+ sh(
+ `node scripts/buildCore.mjs --core=${coreDir(tag)} --platform=${PLATFORM} --channel=${CHANNEL} ` +
+ `--version=${version} --seq=${seq} --shell-abi=${shellAbi} ` +
+ `--objects-base-url=http://127.0.0.1:${PORT}/cas --out=${FEED} ${previousArg}`,
+ { RENDERER_OTA_PRIVATE_KEY: keys().privateKey },
+ );
+};
+
+const steps = {
+ keys() {
+ mkdirSync(WORK, { recursive: true });
+ const pair = generateKeyPairSync('ed25519');
+ writeFileSync(
+ path.join(WORK, 'priv.pem'),
+ pair.privateKey.export({ format: 'pem', type: 'pkcs8' }),
+ );
+ writeFileSync(
+ path.join(WORK, 'pub.pem'),
+ pair.publicKey.export({ format: 'pem', type: 'spki' }),
+ );
+ console.log(`keys written to ${WORK}`);
+ },
+
+ build() {
+ const { publicKey } = keys();
+ const env = {
+ RENDERER_OTA_PUBLIC_KEY: publicKey,
+ UPDATE_CHANNEL: CHANNEL,
+ UPDATE_SERVER_URL: `http://127.0.0.1:${PORT}/${CHANNEL}`,
+ APP_URL: 'http://localhost:3015',
+ DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres',
+ KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE=',
+ };
+ // Electron derives userData from package.json name; productName alone would share the dev instance's data.
+ sh(`npm pkg set name=${PRODUCT} version=${APP_VERSION}`);
+ if (!existsSync(path.join(DESKTOP_DIR, 'dist/renderer/apps/desktop/index.html'))) {
+ sh('npm run build:main', env);
+ } else {
+ console.log('dist/ present, skipping build:main');
+ }
+ rmSync(path.join(WORK, 'app'), { force: true, recursive: true });
+ sh(
+ `npx electron-builder --dir --mac --arm64 --config electron-builder.mjs ` +
+ `-c.mac.notarize=false -c.mac.identity=null -c.productName=${PRODUCT} -c.directories.output=${path.join(WORK, 'app')}`,
+ env,
+ );
+ rmSync(coreDir('v1'), { force: true, recursive: true });
+ cpSync(path.join(DESKTOP_DIR, 'core-dist'), coreDir('v1'), { recursive: true });
+ rmSync(FEED, { force: true, recursive: true });
+ publish('v1', { seq: manifestOf('v1').seq, version: manifestOf('v1').version });
+ // buildCore writes core/<platform>; the client reads <channel>/core/<platform> (S3 adds the channel prefix).
+ symlinkSync('.', path.join(FEED, CHANNEL));
+ console.log(`v1 app: ${APP}`);
+ },
+
+ v2() {
+ rmSync(coreDir('v2'), { force: true, recursive: true });
+ cpSync(coreDir('v1'), coreDir('v2'), { recursive: true });
+ const html = path.join(coreDir('v2'), 'dist/renderer/apps/desktop/index.html');
+ writeFileSync(
+ html,
+ readFileSync(html, 'utf8').replace(
+ /<body[^>]*>/,
+ '$&<div id="core-ota-e2e" style="position:fixed;top:8px;right:8px;z-index:99999;background:#e11;color:#fff;padding:6px 10px;font:bold 14px sans-serif">CORE V2</div>',
+ ),
+ );
+ publish('v2', { previous: 'v1', seq: 1, version: `${APP_VERSION}-core.1` });
+ },
+
+ v3() {
+ rmSync(coreDir('v3'), { force: true, recursive: true });
+ cpSync(coreDir('v2'), coreDir('v3'), { recursive: true });
+ appendFileSync(path.join(coreDir('v3'), 'dist/main/index.js'), "\nconsole.log('core v3');\n");
+ publish('v3', { previous: 'v2', seq: 2, version: `${APP_VERSION}-core.2` });
+ },
+
+ v4() {
+ rmSync(coreDir('v4'), { force: true, recursive: true });
+ cpSync(coreDir('v3'), coreDir('v4'), { recursive: true });
+ const rendererDir = path.join(coreDir('v4'), 'dist/renderer');
+ const asset = readdirSync(path.join(rendererDir, 'assets')).find((name) =>
+ name.endsWith('.js'),
+ );
+ writeFileSync(
+ path.join(rendererDir, 'apps/desktop/index.html'),
+ `<html><body><script src="/assets/${asset}"></script><script>throw new Error("boot failure e2e")</script></body></html>`,
+ );
+ publish('v4', { previous: 'v3', seq: 3, version: `${APP_VERSION}-core.3` });
+ },
+
+ v5() {
+ rmSync(coreDir('v5'), { force: true, recursive: true });
+ cpSync(coreDir('v3'), coreDir('v5'), { recursive: true });
+ appendFileSync(path.join(coreDir('v5'), 'dist/main/index.js'), '\nprocess.exit(1);\n');
+ publish('v5', { previous: 'v4', seq: 4, version: `${APP_VERSION}-core.4` });
+ },
+
+ serve() {
+ spawn('node', ['scripts/core-ota-test/serve.mjs', FEED, String(PORT)], {
+ cwd: DESKTOP_DIR,
+ stdio: 'inherit',
+ });
+ },
+
+ launch() {
+ const child = spawn(APP, [`--remote-debugging-port=${CDP_PORT}`], {
+ detached: true,
+ env: { ...process.env, RENDERER_OTA_CHECK_DELAY: '3000' },
+ stdio: 'ignore',
+ });
+ child.unref();
+ console.log(`launched pid ${child.pid}; log: ${LOG}`);
+ },
+
+ kill() {
+ try {
+ execSync(`pkill -f "${PRODUCT}.app/Contents/MacOS/${PRODUCT}"`);
+ } catch (error) {
+ // pkill exits 1 when no process matched; anything else is a real failure
+ if (error.status !== 1) throw error;
+ }
+ },
+
+ tamper() {
+ const file = path.join(
+ USER_DATA,
+ 'core-ota/cores',
+ `${APP_VERSION}-core.2`,
+ 'dist/main/index.js',
+ );
+ appendFileSync(file, '\n// tampered\n');
+ console.log(`tampered ${file}`);
+ },
+
+ async eval() {
+ const expression = process.argv[3];
+ const targets = await (await fetch(`http://127.0.0.1:${CDP_PORT}/json`)).json();
+ const page = targets.find(
+ (t) => t.type === 'page' && !t.url.includes('overlay') && !t.url.includes('popup'),
+ );
+ const ws = new WebSocket(page.webSocketDebuggerUrl);
+ await new Promise((r) => (ws.onopen = r));
+ const send = (method, params) =>
+ new Promise((resolve) => {
+ const id = Math.floor(Math.random() * 1e9);
+ ws.addEventListener('message', function onMessage(event) {
+ const msg = JSON.parse(event.data);
+ if (msg.id !== id) return;
+ ws.removeEventListener('message', onMessage);
+ resolve(msg.result);
+ });
+ ws.send(JSON.stringify({ id, method, params }));
+ });
+ if (expression === '--shot') {
+ const { data } = await send('Page.captureScreenshot', { format: 'png' });
+ writeFileSync(process.argv[4], Buffer.from(data, 'base64'));
+ console.log(`screenshot ${process.argv[4]}`);
+ } else {
+ const result = await send('Runtime.evaluate', {
+ awaitPromise: true,
+ expression,
+ returnByValue: true,
+ });
+ console.log(JSON.stringify(result?.result?.value ?? result, null, 2));
+ }
+ ws.close();
+ },
+
+ state() {
+ for (const name of ['pointer.json', 'boot.json']) {
+ const file = path.join(USER_DATA, 'core-ota', name);
+ console.log(`--- ${name}`);
+ console.log(existsSync(file) ? readFileSync(file, 'utf8') : '(missing)');
+ }
+ const cores = path.join(USER_DATA, 'core-ota/cores');
+ console.log(
+ '--- cores:',
+ existsSync(cores) ? readdirSync(cores).join(' ').toString().trim() : '(none)',
+ );
+ },
+
+ reset() {
+ rmSync(USER_DATA, { force: true, recursive: true });
+ rmSync(path.dirname(LOG), { force: true, recursive: true });
+ console.log('user data + logs removed');
+ },
+
+ restore() {
+ sh('git checkout -- package.json');
+ },
+};
+
+const step = process.argv[2];
+if (!steps[step]) {
+ console.error(`usage: node scripts/core-ota-test/run.mjs <${Object.keys(steps).join('|')}>`);
+ process.exit(1);
+}
+await steps[step]();
diff --git a/apps/desktop/scripts/renderer-ota-test/serveOta.mjs b/apps/desktop/scripts/core-ota-test/serve.mjs
similarity index 56%
rename from apps/desktop/scripts/renderer-ota-test/serveOta.mjs
rename to apps/desktop/scripts/core-ota-test/serve.mjs
index 41571d15dcb..b39bb02148a 100644
--- a/apps/desktop/scripts/renderer-ota-test/serveOta.mjs
+++ b/apps/desktop/scripts/core-ota-test/serve.mjs
@@ -2,9 +2,15 @@ import { createReadStream, existsSync, statSync } from 'node:fs';
import http from 'node:http';
import path from 'node:path';
-const root = path.resolve(process.argv[2] ?? 'release/renderer-ota');
+const root = path.resolve(process.argv[2] ?? 'release/core-ota');
const port = Number(process.argv[3] ?? 8787);
+const contentType = (pathname) => {
+ if (pathname.endsWith('.zip')) return 'application/zip';
+ if (pathname.endsWith('.zst')) return 'application/zstd';
+ return 'application/json';
+};
+
const server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
const file = path.resolve(root, `.${url.pathname}`);
@@ -13,16 +19,16 @@ const server = http.createServer((req, res) => {
console.log(`404 ${url.pathname}`);
return;
}
-
- const immutable = url.pathname.includes('/packs/');
+ const immutable = url.pathname.startsWith('/cas/') || url.pathname.includes('/packs/');
res.writeHead(200, {
'cache-control': immutable ? 'public,max-age=31536000,immutable' : 'no-store',
- 'content-type': url.pathname.endsWith('.zip') ? 'application/zip' : 'application/json',
+ 'content-length': statSync(file).size,
+ 'content-type': contentType(url.pathname),
});
createReadStream(file).pipe(res);
console.log(`200 ${url.pathname}`);
});
-server.listen(port, () => {
- console.log(`renderer OTA feed: http://127.0.0.1:${port}/ -> ${root}`);
+server.listen(port, '127.0.0.1', () => {
+ console.log(`core OTA feed: http://127.0.0.1:${port}/ -> ${root}`);
});
diff --git a/apps/desktop/scripts/mainHash.mjs b/apps/desktop/scripts/mainHash.mjs
deleted file mode 100644
index e914fee8170..00000000000
--- a/apps/desktop/scripts/mainHash.mjs
+++ /dev/null
@@ -1,469 +0,0 @@
-import { createHash } from 'node:crypto';
-import { glob, mkdir, readFile, realpath, stat, writeFile } from 'node:fs/promises';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-import { createModuleRecord, moduleRequests, parseModule, walkGraph } from './mainHashGraph.mjs';
-
-const scriptPath = fileURLToPath(import.meta.url);
-const defaultRoot = path.resolve(path.dirname(scriptPath), '../../..');
-const collectEnv = 'RENDERER_OTA_COLLECT_INPUTS';
-export const MAIN_HASH_PLACEHOLDER = '__LOBEMAINHASH_SOURCE_GRAPH__';
-export const MAIN_HASH_ALGORITHM = 'graph-v2';
-
-// A workspace with platform-dependent imports can opt into whole-source hashing.
-// Keep this list in source control: every build and OTA gate must use the same scope.
-// napi-loader is bundled on Linux/Windows but externalized with the macOS addon.
-export const wholeSourcePackages = ['packages/napi-loader'];
-
-const excluded = [
- '**/node_modules/**',
- '**/dist/**',
- '**/build/**',
- '**/release/**',
- '**/prebuilds/**',
- '**/__tests__/**',
- '**/__mocks__/**',
- '**/fixtures/**',
- '**/.git/**',
- '**/resources/bin/**',
- '**/resources/cli-package.json',
- '**/*.test.*',
- '**/*.spec.*',
- '**/*.md',
- '**/*.mdx',
- '**/*.map',
- '**/*.node',
-];
-const textFile =
- /\.(?:[cm]?[jt]sx?|json|ya?ml|gypi?|mm?|cc|cpp|c|h|hpp|swift|html|css|svg|sh|txt)$/i;
-const sha256 = (value) => createHash('sha256').update(value).digest('hex');
-const slash = (value) => value.replaceAll('\\', '/');
-const inside = (root, file) => {
- const relative = path.relative(root, file);
- return (
- relative === '' ||
- (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative))
- );
-};
-const stableJson = (value) =>
- JSON.stringify(value, (_, item) =>
- item && typeof item === 'object' && !Array.isArray(item)
- ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
- : item,
- );
-
-export function lockedPackages(lockfile) {
- const locked = new Set();
- let inPackages = false;
- for (const line of lockfile.split('\n')) {
- if (/^\S/.test(line)) inPackages = line.startsWith('packages:');
- const key = inPackages && line.match(/^ {2}'?(\S+?)'?:\s*$/)?.[1];
- if (key) locked.add(key);
- }
- return locked;
-}
-
-export function createInputManifest(inputs) {
- const sorted = [...inputs].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
- if (new Set(sorted.map((input) => input.path)).size !== sorted.length) {
- throw new Error('Duplicate main hash input path');
- }
- return {
- algorithm: MAIN_HASH_ALGORITHM,
- inputs: sorted,
- mainHash: sha256(stableJson({ algorithm: MAIN_HASH_ALGORITHM, inputs: sorted })),
- };
-}
-
-/** Capture pre-render code and final retention; chunk-generated names never enter the hash. */
-export async function collectViteGraph(options) {
- const { build, parseSync } = await import('vite');
- const nodes = new Map();
- const configFiles = new Set();
- let defines;
- await build({
- ...options,
- build: { ...options.build, minify: false, sourcemap: false, write: false },
- logLevel: 'silent',
- plugins: [
- ...(options.plugins ?? []),
- {
- name: 'renderer-ota-source-inputs',
- configResolved(config) {
- for (const file of config.configFileDependencies) configFiles.add(file);
- defines = config.define;
- },
- async generateBundle(_options, bundle) {
- const retained = new Set(
- Object.values(bundle).flatMap((chunk) =>
- chunk.type === 'chunk' ? Object.keys(chunk.modules) : [],
- ),
- );
- for (const id of this.getModuleIds()) {
- const info = this.getModuleInfo(id);
- const owned = !slash(id).includes('/node_modules/') && !info.isExternal;
- if (owned && retained.has(id) && info.code == null) {
- throw new Error(`Missing transformed code for retained main hash module: ${id}`);
- }
- const ast =
- owned && info.code != null ? parseModule(info.code, id, parseSync) : undefined;
- const resolutions = {};
- if (ast) {
- for (const source of moduleRequests(ast)) {
- const resolved = await this.resolve(source, id);
- if (!resolved) throw new Error(`Unresolved main hash input ${source} in ${id}`);
- resolutions[source] = resolved.id;
- }
- }
- nodes.set(id, {
- id,
- ast,
- resolutions,
- entry: info.isEntry,
- external: info.isExternal,
- inputFormat: info.inputFormat,
- exports: info.exports,
- imports: info.importedIds,
- dynamicImports: info.dynamicallyImportedIds,
- retained: retained.has(id),
- });
- }
- },
- },
- ],
- });
- return { configFiles: [...configFiles], defines, nodes };
-}
-
-export async function collectSourceInputs({
- repoRoot = defaultRoot,
- cloudRoot,
- graph = [],
- sourcePackages = wholeSourcePackages,
- publicKey = process.env.RENDERER_OTA_PUBLIC_KEY ?? '',
-} = {}) {
- repoRoot = await realpath(repoRoot);
- if (cloudRoot) cloudRoot = await realpath(cloudRoot);
- const inputs = new Map();
- const addValue = (name, value, group) =>
- inputs.set(name, { group, path: name, sha256: sha256(value) });
- const roots = [['oss', repoRoot], ...(cloudRoot ? [['cloud', cloudRoot]] : [])];
-
- const addFile = async (file, group) => {
- // Queries identify Vite transforms, not a different source file.
- if (file.startsWith('\0')) return;
- file = file.split('?')[0];
- if (!path.isAbsolute(file)) return;
- file = await realpath(file);
- if (slash(file).includes('/node_modules/')) return;
- const owner = roots.find(([, root]) => inside(root, file));
- if (!owner) throw new Error(`Main hash input is outside the source roots: ${file}`);
- if (!(await stat(file)).isFile()) return;
- const [prefix, root] = owner;
- const name = `${prefix}/${slash(path.relative(root, file))}`;
- const bytes = await readFile(file);
- // JSON key order affects exports conditions and runtime iteration; preserve source order.
- const content = textFile.test(file) ? bytes.toString('utf8').replaceAll('\r\n', '\n') : bytes;
- addValue(name, content, group);
- };
- const addTree = async (root, relative, group) => {
- const dir = path.resolve(root, relative);
- if (!inside(root, dir)) throw new Error(`Invalid source directory: ${relative}`);
- await stat(dir); // Missing declared inputs must not silently produce a compatible hash.
- for await (const file of glob(`${slash(relative)}/**/*`, { cwd: root, exclude: excluded })) {
- await addFile(path.join(root, file), group);
- }
- };
-
- const sourceFile = (id) => id.replace(/^\0/, '').split('?')[0];
- // The lockfile is the only dependency input to the hash, so every bundled npm module
- // must resolve to a version it pins, wherever pnpm happened to link it from.
- let locked;
- const packageIdentity = async (file) => {
- for (let dir = path.dirname(file); ; dir = path.dirname(dir)) {
- try {
- const { name, version } = JSON.parse(
- await readFile(path.join(dir, 'package.json'), 'utf8'),
- );
- if (name && version) return `${name}@${version}`;
- } catch (error) {
- if (error.code !== 'ENOENT') throw error;
- }
- if (dir === path.dirname(dir)) return undefined;
- }
- };
- for (const target of graph) {
- for (const id of target.nodes.keys()) {
- const file = sourceFile(id);
- if (!path.isAbsolute(file) || !slash(file).includes('/node_modules/')) continue;
- locked ??= lockedPackages(
- await readFile(path.join(repoRoot, 'apps/desktop/pnpm-lock.yaml'), 'utf8'),
- );
- const dependency = await packageIdentity(await realpath(file));
- const name = dependency?.slice(0, dependency.lastIndexOf('@'));
- // Tarball, git, file: and link: specifiers pin by resolution instead of version.
- const pinned =
- dependency &&
- (locked.has(dependency) ||
- [...locked].some(
- (key) => key.startsWith(`${name}@`) && /^[a-z+]+:/.test(key.slice(name.length + 1)),
- ));
- if (!pinned) {
- throw new Error(
- `Main hash dependency is not pinned by apps/desktop/pnpm-lock.yaml: ${dependency ?? 'unknown'} (${file})`,
- );
- }
- }
- }
- const identity = (id) => {
- let normalized = slash(id);
- for (const [prefix, root] of roots) normalized = normalized.replaceAll(slash(root), prefix);
- return normalized;
- };
- const sourceRoots = new Map();
- for (const relative of sourcePackages)
- sourceRoots.set(path.join(repoRoot, relative), 'workspace');
- for (const [, root] of roots) {
- for await (const binding of glob('packages/*/binding.gyp', { cwd: root })) {
- sourceRoots.set(path.join(root, path.dirname(binding)), 'native');
- }
- }
- const inSourceTree = (id) => [...sourceRoots.keys()].some((dir) => inside(dir, sourceFile(id)));
- const families = new Map();
- for (const target of graph) {
- for (const id of target.nodes.keys()) {
- const file = sourceFile(id);
- if (!path.isAbsolute(file) || slash(file).includes('/node_modules/')) continue;
- const base = file.replace(/\.(mac|linux|windows)(?=\.[^.]+$)/, '');
- const ext = path.extname(base);
- if (!/\.[cm]?[jt]sx?$/.test(ext)) continue;
- const variants = [];
- for (const suffix of ['', '.mac', '.linux', '.windows']) {
- const variant = base.slice(0, -ext.length) + suffix + ext;
- try {
- if ((await stat(variant)).isFile()) variants.push(variant);
- } catch (error) {
- if (error.code !== 'ENOENT') throw error;
- }
- }
- if (variants.some((variant) => variant !== base)) {
- for (const variant of variants) {
- families.set(variant, base);
- await addFile(variant, 'platform');
- }
- }
- }
- }
- const diagnostics = [];
- for (const [index, target] of graph.entries()) {
- const label = target.label ?? (index === 0 ? 'main' : 'preload');
- const nodes = target.nodes;
- const boundaries = new Set(
- [...nodes.keys()].filter((id) => families.has(sourceFile(id)) || inSourceTree(id)),
- );
- const common = walkGraph(
- nodes,
- [...nodes.values()].filter((node) => node.entry).map((node) => node.id),
- boundaries,
- );
- const exclusive = new Set([...walkGraph(nodes, boundaries)].filter((id) => !common.has(id)));
- const opaque = (id, source) => {
- const file = sourceFile(id);
- if (families.has(file)) return `platform:${identity(families.get(file))}`;
- if (inSourceTree(id)) return `source:${source ?? identity(file)}`;
- if (
- !nodes.has(id) &&
- path.isAbsolute(file) &&
- !slash(file).includes('/node_modules/') &&
- roots.some(([, root]) => inside(root, file))
- ) {
- throw new Error(
- `Runtime source is outside the Vite graph; declare its package in wholeSourcePackages: ${file}`,
- );
- }
- if (slash(id).includes('/node_modules/') || !nodes.has(id) || nodes.get(id)?.external)
- return `package:${source ?? id}`;
- if (exclusive.has(id)) return `platform:${identity(file)}`;
- return undefined;
- };
- const summary = [];
- for (const [id, node] of nodes) {
- const file = sourceFile(id);
- if (slash(id).includes('/node_modules/') || node.external) continue;
- if (path.isAbsolute(file)) {
- let dir = path.dirname(await realpath(file));
- const owner = roots.find(([, root]) => inside(root, dir));
- if (!owner) throw new Error(`Main hash input is outside the source roots: ${file}`);
- while (dir !== owner[1]) {
- try {
- await addFile(path.join(dir, 'package.json'), 'config');
- break;
- } catch (error) {
- if (error.code !== 'ENOENT') throw error;
- }
- dir = path.dirname(dir);
- }
- }
- if (exclusive.has(id) || inSourceTree(id)) {
- if (path.isAbsolute(file)) await addFile(file, 'platform');
- continue;
- }
- if (!node.retained || !node.ast) continue;
- const record = createModuleRecord(node, { nodes, identity, opaque });
- const name = `$graph/${label}/${identity(id)}`;
- addValue(name, stableJson(record), 'runtime');
- summary.push({
- id: identity(id),
- retained: true,
- sha256: inputs.get(name).sha256,
- bindings: record.bindings,
- dynamicBindings: record.dynamicBindings,
- effects: record.effects,
- inlined: Object.keys(record.inlined),
- fallback: Object.keys(record.fallback),
- });
- }
- diagnostics.push({
- label,
- nodes: [...nodes.values()]
- .map((node) => ({
- id: identity(node.id),
- imports: node.imports.map(identity),
- dynamicImports: node.dynamicImports.map(identity),
- retained: node.retained,
- boundary: opaque(node.id)
- ? exclusive.has(node.id)
- ? 'platform'
- : 'dependency'
- : undefined,
- codeHash: node.ast ? sha256(stableJson(node.ast)) : undefined,
- }))
- .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)),
- modules: summary.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)),
- });
- for (const file of target.configFiles) await addFile(file, 'config');
- addValue(`$defines/${label}`, stableJson(target.defines ?? {}), 'config');
- }
- for (const [dir, group] of sourceRoots) {
- const owner = roots.find(([, root]) => inside(root, dir));
- await addTree(owner[1], path.relative(owner[1], dir), group);
- }
- await addTree(repoRoot, 'apps/desktop/resources', 'desktop');
- for (const [prefix, root] of roots) {
- // Cloud's plugin helpers are loaded at config time, outside the application graph.
- if (prefix === 'cloud') {
- await addTree(root, 'scripts/cloud-desktop', 'config');
- // Overlay runtime/build dependencies (e.g. Sentry) are declared outside Desktop.
- const { dependencies, devDependencies, optionalDependencies } = JSON.parse(
- await readFile(path.join(root, 'package.json'), 'utf8'),
- );
- addValue(
- '$cloud-dependencies',
- stableJson({ dependencies, devDependencies, optionalDependencies }),
- 'dependencies',
- );
- }
- }
- for (const file of [
- 'apps/desktop/package.json',
- 'apps/desktop/pnpm-lock.yaml',
- 'apps/desktop/pnpm-workspace.yaml',
- 'apps/desktop/vite.main.config.ts',
- 'apps/desktop/vite.preload.config.ts',
- 'apps/desktop/vite.shared.ts',
- 'apps/desktop/tsconfig.json',
- 'apps/desktop/native-deps.config.mjs',
- 'apps/desktop/external-runtime-deps.config.mjs',
- 'apps/desktop/module-deps.config.mjs',
- 'apps/desktop/scripts/mainHash.mjs',
- 'apps/desktop/scripts/mainHashGraph.mjs',
- ]) {
- await addFile(
- path.join(repoRoot, file),
- file.endsWith('pnpm-lock.yaml') ? 'dependencies' : 'config',
- );
- }
- await addTree(repoRoot, 'plugins/vite', 'config');
- addValue('$public-key', publicKey.replaceAll('\r\n', '\n').trim(), 'metadata');
- return { ...createInputManifest(inputs.values()), graph: diagnostics };
-}
-
-export async function computeMainHash() {
- const desktopRoot = path.join(defaultRoot, 'apps/desktop');
- const previous = process.env[collectEnv];
- const previousPlatform = process.env.npm_config_platform;
- process.env[collectEnv] = '1';
- // Vite config messages must not contaminate the CLI hash on stdout.
- const originalInfo = console.info;
- const originalLog = console.log;
- console.log = (...args) => console.error(...args);
- console.info = (...args) => console.error(...args);
- let manifest;
- try {
- const graph = [];
- // All hosts inspect the same platform implementations, including unselected branches.
- for (const platform of ['darwin', 'linux', 'win32']) {
- process.env.npm_config_platform = platform;
- for (const target of ['main', 'preload']) {
- graph.push({
- ...(await collectViteGraph({
- configFile: path.join(desktopRoot, `vite.${target}.config.ts`),
- mode: 'production',
- })),
- label: `${target}/${platform}`,
- });
- }
- }
- manifest = await collectSourceInputs({
- cloudRoot: process.env.CLOUD_DESKTOP === '1' ? path.dirname(defaultRoot) : undefined,
- graph,
- });
- } finally {
- if (previousPlatform === undefined) delete process.env.npm_config_platform;
- else process.env.npm_config_platform = previousPlatform;
- console.info = originalInfo;
- console.log = originalLog;
- if (previous === undefined) delete process.env[collectEnv];
- else process.env[collectEnv] = previous;
- }
- const releaseDir = path.join(desktopRoot, 'release');
- await mkdir(releaseDir, { recursive: true });
- await writeFile(
- path.join(releaseDir, 'renderer-mainhash-inputs.json'),
- `${JSON.stringify(manifest, null, 2)}\n`,
- );
- return manifest.mainHash;
-}
-
-export async function resolveMainHash(mode) {
- if (process.env[collectEnv] === '1') return MAIN_HASH_PLACEHOLDER;
- if (!process.env.MAIN_HASH) return mode === 'development' ? '' : computeMainHash();
- if (!/^[0-9a-f]{64}$/.test(process.env.MAIN_HASH)) {
- throw new Error('MAIN_HASH must be a 64-character lowercase SHA-256');
- }
- return process.env.MAIN_HASH;
-}
-
-export const rendererMainHashArtifact = (mainHash) => ({
- name: 'renderer-main-hash-artifact',
- async writeBundle() {
- const releaseDir = path.join(defaultRoot, 'apps/desktop/release');
- await mkdir(releaseDir, { recursive: true });
- await writeFile(path.join(releaseDir, 'renderer-mainhash.txt'), `${mainHash}\n`);
- },
-});
-
-if (
- process.env[collectEnv] !== '1' &&
- process.argv[1] &&
- path.resolve(process.argv[1]) === scriptPath
-) {
- computeMainHash().then(
- (hash) => console.log(hash),
- (error) => {
- console.error(error);
- process.exitCode = 1;
- },
- );
-}
diff --git a/apps/desktop/scripts/mainHashGraph.mjs b/apps/desktop/scripts/mainHashGraph.mjs
deleted file mode 100644
index eb0a1e70678..00000000000
--- a/apps/desktop/scripts/mainHashGraph.mjs
+++ /dev/null
@@ -1,376 +0,0 @@
-const name = (node) => node?.name ?? node?.value;
-const positions = new Set(['start', 'end', 'loc', 'raw']);
-const bindingNames = (pattern) => {
- if (!pattern) return [];
- if (pattern.type === 'Identifier') return [pattern.name];
- if (pattern.type === 'RestElement') return bindingNames(pattern.argument);
- if (pattern.type === 'AssignmentPattern') return bindingNames(pattern.left);
- if (pattern.type === 'ArrayPattern') return pattern.elements.flatMap(bindingNames);
- if (pattern.type === 'ObjectPattern')
- return pattern.properties.flatMap((item) =>
- bindingNames(item.type === 'RestElement' ? item.argument : item.value),
- );
- return [];
-};
-
-// Keep tree-shaking directives: moving a PURE annotation can change runtime behavior.
-export function parseModule(code, id, parseSync) {
- const { program, comments, errors } = parseSync(id, code);
- if (errors.length) throw new Error(`Cannot parse main hash module ${id}: ${errors[0].message}`);
- const nodes = [];
- const visit = (value) => {
- if (!value || typeof value !== 'object') return;
- if (typeof value.type === 'string') nodes.push(value);
- for (const child of Object.values(value)) {
- if (Array.isArray(child)) child.forEach(visit);
- else visit(child);
- }
- };
- visit(program);
- const annotations = new Map();
- for (const comment of comments) {
- if (!/[@#]__(?:PURE|NO_SIDE_EFFECTS)__|@vite-/.test(comment.value)) continue;
- const start = Math.min(
- ...nodes.filter((node) => node.start >= comment.end).map((node) => node.start),
- );
- const target = Number.isFinite(start) ? start : program.start;
- annotations.set(target, [...(annotations.get(target) ?? []), comment.value.trim()]);
- }
- return JSON.parse(
- JSON.stringify(program, (key, value) => {
- if (positions.has(key)) return undefined;
- if (typeof value === 'bigint') return String(value);
- if (value?.type && annotations.has(value.start)) {
- return { ...value, annotations: annotations.get(value.start) };
- }
- return value;
- }),
- );
-}
-
-export function moduleRequests(ast) {
- const requests = new Set();
- const visit = (node) => {
- if (!node || typeof node !== 'object') return;
- if (node.source?.type === 'Literal' && typeof node.source.value === 'string') {
- requests.add(node.source.value);
- }
- if (
- node.type === 'CallExpression' &&
- node.callee?.name === 'require' &&
- node.arguments?.[0]?.type === 'Literal' &&
- typeof node.arguments[0].value === 'string'
- ) {
- requests.add(node.arguments[0].value);
- }
- for (const value of Object.values(node)) {
- if (Array.isArray(value)) value.forEach(visit);
- else if (value && typeof value === 'object') visit(value);
- }
- };
- visit(ast);
- return [...requests];
-}
-
-export function walkGraph(nodes, starts, stops = new Set()) {
- const seen = new Set();
- const pending = [...starts];
- while (pending.length) {
- const id = pending.pop();
- if (seen.has(id) || stops.has(id)) continue;
- seen.add(id);
- const node = nodes.get(id);
- if (node) pending.push(...node.imports, ...node.dynamicImports);
- }
- return seen;
-}
-
-const pureExpression = (node) =>
- !node || ['Literal', 'FunctionExpression', 'ArrowFunctionExpression'].includes(node.type);
-const hasOwnEffects = (ast) =>
- ast.body.some((statement) => {
- if (
- [
- 'ImportDeclaration',
- 'ExportAllDeclaration',
- 'EmptyStatement',
- 'FunctionDeclaration',
- ].includes(statement.type)
- )
- return false;
- const declaration =
- statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;
- if (!declaration || declaration.type === 'FunctionDeclaration') return false;
- if (declaration.type === 'VariableDeclaration')
- return declaration.declarations.some((item) => !pureExpression(item.init));
- return true;
- });
-
-const namespaceReads = (ast, local) => {
- const names = new Set();
- let escapes = false;
- const visit = (node, parent, grandparent) => {
- if (!node || typeof node !== 'object' || node.type === 'ImportDeclaration') return;
- if (node.type === 'Identifier' && node.name === local) {
- const member = parent?.type === 'MemberExpression' && parent.object === node;
- const property =
- member &&
- (!parent.computed
- ? name(parent.property)
- : parent.property.type === 'Literal'
- ? parent.property.value
- : undefined);
- // Calling ns.method() exposes the entire namespace through `this`.
- if (
- typeof property !== 'string' ||
- (grandparent?.type === 'CallExpression' && grandparent.callee === parent) ||
- (grandparent?.type === 'TaggedTemplateExpression' && grandparent.tag === parent)
- )
- escapes = true;
- else names.add(property);
- }
- for (const child of Object.values(node)) {
- if (Array.isArray(child)) child.forEach((item) => visit(item, node, parent));
- else if (child && typeof child === 'object') visit(child, node, parent);
- }
- };
- visit(ast);
- return escapes ? undefined : [...names].sort();
-};
-
-/**
- * Resolve forwarding modules even when Rolldown omitted them from chunk.modules.
- * Unsupported/cyclic bindings retain their source closure instead of assuming equality.
- */
-export function createModuleRecord(node, { nodes, identity, opaque, seen = new Set() }) {
- if (seen.has(node.id)) {
- return {
- cycle: Object.fromEntries(
- [...walkGraph(nodes, [node.id])]
- .filter((id) => !opaque(id) && nodes.get(id)?.ast)
- .sort()
- .map((id) => [identity(id), nodes.get(id).ast]),
- ),
- };
- }
- seen = new Set([...seen, node.id]);
- const seenFallbacks = new Set();
- const inlinedSources = new Set();
- const terminal = (id, local) => {
- // Constant folding can remove the contributing module from chunk.modules entirely.
- if (!nodes.get(id)?.retained) inlinedSources.add(id);
- return { module: identity(id), local };
- };
- const fallback = (id) => {
- const files = [...walkGraph(nodes, [id])].filter(
- (item) => !opaque(item) && nodes.get(item)?.ast,
- );
- for (const file of files) seenFallbacks.add(file);
- return { fallback: identity(id) };
- };
- const request = (from, source) => {
- const resolution = nodes.get(from)?.resolutions[source];
- if (!resolution) throw new Error(`Unresolved main hash binding ${source} in ${from}`);
- return resolution;
- };
- const exportNames = (id, seen = new Set()) => {
- if (seen.has(id)) return [];
- seen = new Set([...seen, id]);
- const names = new Set();
- for (const statement of nodes.get(id)?.ast?.body ?? []) {
- if (statement.type === 'ExportDefaultDeclaration') names.add('default');
- if (statement.type === 'ExportNamedDeclaration') {
- for (const specifier of statement.specifiers) names.add(name(specifier.exported));
- for (const binding of bindingNames(statement.declaration?.id)) names.add(binding);
- for (const item of statement.declaration?.declarations ?? []) {
- for (const binding of bindingNames(item.id)) names.add(binding);
- }
- }
- if (statement.type === 'ExportAllDeclaration') {
- if (statement.exported) names.add(name(statement.exported));
- else {
- const child = request(id, statement.source.value);
- if (!opaque(child))
- for (const binding of exportNames(child, seen)) {
- if (binding !== 'default') names.add(binding);
- }
- }
- }
- }
- return [...names].sort();
- };
- const imported = (from, source, exported, seen) => {
- const id = request(from, source);
- // Use the import spelling at package boundaries, not bundled/external IDs.
- if (opaque(id)) return { module: opaque(id, source), exported };
- return resolve(id, exported, seen);
- };
- const local = (id, binding, seen) => {
- for (const statement of nodes.get(id)?.ast?.body ?? []) {
- if (statement.type !== 'ImportDeclaration') continue;
- const specifier = statement.specifiers.find((item) => name(item.local) === binding);
- if (specifier)
- return imported(
- id,
- statement.source.value,
- specifier.type === 'ImportNamespaceSpecifier'
- ? '*'
- : specifier.type === 'ImportDefaultSpecifier'
- ? 'default'
- : name(specifier.imported),
- seen,
- );
- }
- return terminal(id, binding);
- };
- const resolve = (id, exported, seen = new Set()) => {
- const key = `${id}\0${exported}`;
- if (seen.has(key)) return fallback(id);
- seen = new Set([...seen, key]);
- const target = nodes.get(id);
- if (!target?.ast) return fallback(id);
- if (exported === '*') {
- if (
- target.ast.body.some(
- (item) =>
- item.type === 'ExportAllDeclaration' &&
- !item.exported &&
- opaque(request(id, item.source.value)),
- )
- )
- return fallback(id);
- const names = exportNames(id);
- if (!names.length && target.inputFormat === 'cjs') return fallback(id);
- return {
- namespace: Object.fromEntries(names.map((item) => [item, resolve(id, item, seen)])),
- };
- }
- for (const statement of target.ast.body) {
- if (exported === 'default' && statement.type === 'ExportDefaultDeclaration') {
- // A default expression is a value snapshot, unlike a live export specifier.
- return target.retained ? { module: identity(id), exported } : fallback(id);
- }
- if (statement.type === 'ExportAllDeclaration' && name(statement.exported) === exported) {
- return imported(id, statement.source.value, '*', seen);
- }
- if (statement.type !== 'ExportNamedDeclaration') continue;
- const specifier = statement.specifiers.find((item) => name(item.exported) === exported);
- if (specifier)
- return statement.source
- ? imported(id, statement.source.value, name(specifier.local), seen)
- : local(id, name(specifier.local), seen);
- const declaration = statement.declaration;
- if (
- bindingNames(declaration?.id).includes(exported) ||
- declaration?.declarations?.some((item) => bindingNames(item.id).includes(exported))
- ) {
- return terminal(id, exported);
- }
- }
- if (exported !== 'default') {
- const matches = [];
- for (const statement of target.ast.body) {
- if (statement.type !== 'ExportAllDeclaration' || statement.exported) continue;
- const child = request(id, statement.source.value);
- if (opaque(child)) return fallback(id);
- if (exportNames(child).includes(exported)) matches.push(resolve(child, exported, seen));
- }
- const unique = [...new Map(matches.map((item) => [JSON.stringify(item), item])).values()];
- if (unique.length === 1) return unique[0];
- }
- return fallback(id);
- };
- const effects = (id, seen = new Set()) => {
- if (seen.has(id)) return [];
- seen.add(id);
- const target = nodes.get(id);
- if (!target?.ast) return [];
- const result = [];
- for (const statement of target.ast.body) {
- if (
- !statement.source ||
- !['ImportDeclaration', 'ExportNamedDeclaration', 'ExportAllDeclaration'].includes(
- statement.type,
- )
- )
- continue;
- const child = request(id, statement.source.value);
- if (opaque(child)) result.push(opaque(child, statement.source.value));
- else result.push(...effects(child, seen));
- }
- if (target.retained && hasOwnEffects(target.ast)) result.push(identity(id));
- return [...new Set(result)];
- };
- const bindings = [];
- for (const statement of node.ast.body) {
- if (statement.type !== 'ImportDeclaration') continue;
- for (const specifier of statement.specifiers) {
- const selected =
- specifier.type === 'ImportNamespaceSpecifier'
- ? namespaceReads(node.ast, name(specifier.local))
- : undefined;
- bindings.push({
- local: name(specifier.local),
- origin: selected
- ? {
- namespace: Object.fromEntries(
- selected.map((item) => [item, imported(node.id, statement.source.value, item)]),
- ),
- }
- : imported(
- node.id,
- statement.source.value,
- specifier.type === 'ImportNamespaceSpecifier'
- ? '*'
- : specifier.type === 'ImportDefaultSpecifier'
- ? 'default'
- : name(specifier.imported),
- ),
- });
- }
- }
- const dynamicBindings = node.dynamicImports.map((id) => {
- const source =
- Object.keys(node.resolutions).find((key) => node.resolutions[key] === id) ?? identity(id);
- return opaque(id) ? { module: opaque(id, source) } : resolve(id, '*');
- });
- const visit = (value) => {
- if (!value || typeof value !== 'object') return;
- if (value.type === 'ImportExpression' && typeof value.source?.value === 'string') {
- dynamicBindings.push(imported(node.id, value.source.value, '*'));
- }
- if (
- value.type === 'CallExpression' &&
- value.callee?.name === 'require' &&
- typeof value.arguments?.[0]?.value === 'string'
- ) {
- const source = value.arguments[0].value;
- const child = request(node.id, source);
- dynamicBindings.push(opaque(child) ? { module: opaque(child, source) } : fallback(child));
- }
- for (const child of Object.values(value)) {
- if (Array.isArray(child)) child.forEach(visit);
- else if (child && typeof child === 'object') visit(child);
- }
- };
- visit(node.ast);
- const exports = node.entry ? resolve(node.id, '*') : undefined;
- return {
- code: node.ast,
- bindings,
- dynamicBindings,
- effects: effects(node.id),
- exports,
- inlined: Object.fromEntries(
- [...inlinedSources]
- .sort()
- .map((id) => [
- identity(id),
- createModuleRecord(nodes.get(id), { nodes, identity, opaque, seen }),
- ]),
- ),
- fallback: Object.fromEntries(
- [...seenFallbacks].sort().map((id) => [identity(id), nodes.get(id).ast]),
- ),
- };
-}
diff --git a/apps/desktop/scripts/renderer-ota-test/README.md b/apps/desktop/scripts/renderer-ota-test/README.md
deleted file mode 100644
index 5a636511469..00000000000
--- a/apps/desktop/scripts/renderer-ota-test/README.md
+++ /dev/null
@@ -1,95 +0,0 @@
-# Renderer OTA 本地 E2E 测试
-
-在本地完整走通 V2 协议:检查 → 下载一个 full/delta pack → staged toast → 刷新应用 → boot ping 提交,以及坏增量包自动改下 full pack。全程 dev 模式,不需要打包。
-
-所有命令在 `apps/desktop/` 下执行。
-
-## 协议边界
-
-- V2 客户端只访问 `/<channel>/<appVersion>/renderer/v2`,本地状态只写入 `renderer-ota-v2`。
-- 本地状态按 `renderer-ota-v2/<channel>/<appVersion>` 隔离:full 升级即使 mainHash 相同,也从新版本内置的 r0 开始,不复用旧版本的 current/staged/blacklist。
-- `latest.json` / `versions/rN.json` 只负责选择 pack;目标文件 tree 与 delta 重建信息放在所选 ZIP 的 `meta.json` 中。
-- 新构建不包含 V1 manifest/CAS 解析、URL fallback 或 pointer 迁移。
-- 发布流程不会删除或覆盖远端既有 V1 feed/object;旧客户端继续停留在冻结的 V1 数据上。
-
-## 0. 生成测试密钥 (一次)
-
-```bash
-node scripts/buildRendererManifest.mjs --gen-key > /tmp/ota-keys.pem
-# 拆成两个文件:第一段 PRIVATE KEY 存 /tmp/ota-priv.pem,第二段 PUBLIC KEY 存 /tmp/ota-pub.pem
-```
-
-## 1. 构建 v0 renderer (内置基线)
-
-```bash
-npm run build:renderer
-rm -rf /tmp/lobehub-ota-r0
-cp -R dist/renderer /tmp/lobehub-ota-r0
-```
-
-## 2. 以「生产形态」启动 dev 应用
-
-静态 renderer (不走 Vite 代理)+ 强制启用 OTA + 5 秒后首查:
-
-```bash
-DESKTOP_RENDERER_STATIC=1 \
- RENDERER_OTA_FORCE=1 \
- RENDERER_OTA_CHECK_DELAY=5000 \
- RENDERER_OTA_PUBLIC_KEY="$(cat /tmp/ota-pub.pem)" \
- UPDATE_SERVER_URL=http://127.0.0.1:8787 \
- npm run dev
-```
-
-此时 feed 还没起,日志应出现 `Renderer OTA check failed`(fetch 拒连) 或 404 —— 属预期。
-
-## 3. 做一个肉眼可见的 renderer 改动并发布 r1
-
-改任意 renderer 侧文案 (例如 `src/features/` 下某个标题), 然后:
-
-```bash
-npm run build:renderer
-RENDERER_OTA_PRIVATE_KEY="$(cat /tmp/ota-priv.pem)" \
- node scripts/buildRendererManifest.mjs \
- --renderer=dist/renderer --out=/tmp/ota-feed --channel=stable --version=r1 \
- --from-dir=/tmp/lobehub-ota-r0 --from-version=r0
-node scripts/renderer-ota-test/serveOta.mjs /tmp/ota-feed 8787
-```
-
-注意 `--channel` 要和应用实际渠道一致 (dev 默认 stable; feed 路径为
-`/<channel>/<appVersion>/renderer/v2`)。
-
-## 4. 验收 happy path
-
-- 等下一轮检查,或在 DevTools console 手动触发:
- `await window.electronAPI.invoke('rendererOta.checkNow')`
-- serveOta 日志:每次检查只下载一个 `packs/<sha256>.zip`;pack 内 `meta.json` 携带目标 tree,增量 pack 另含新增对象与 zstd dictionary patch
-- 应用左下角出现「新版本已就绪,刷新即可使用」toast
-- 点「立即刷新」: 窗口 reload (应用不重启), 改动的文案出现
-- `~/Library/Application Support/<dev userData>/renderer-ota-v2/stable/<appVersion>/pointer.json`:
- `current: "r1"`, 收到 boot ping 后 `pendingBootCheck: false`
-- `versions/` 只留 current (+previous)
-
-## 5. 验收回退路径
-
-发布一个必挂的 r2: 构建后把 `dist/renderer/assets/entry-*.js` 的内容整体替换为
-`throw new Error('boom')`(bundle 求值即抛 → 发不出 loaded ping; 注意不能删
-script 引用 —— 没有 script 的 index.html 会被 staging 期完整性检查直接拒掉),
-再按步骤 3 发布 `--version=r2`。
-
-- `checkNow` → toast → 刷新:白屏 / 报错页
-- **约 3 秒**自动回退 (loaded ping 未到); 若 bundle 能求值但挂不上,则 15 秒兜底
-- `pointer.json`:`current: "r1"`,`blacklist: ["r2"]`
-- 再次 `checkNow`:r2 被拉黑,不再下载
-
-## 6. 验收 mainHash 门禁
-
-改一行 `src/main/` 下的代码 (不重启应用), 重新按步骤 3 发布 r3:
-manifest 的 mainHash 会与运行中应用注入的不一致 → 日志
-`Manifest mainHash mismatch`, 拒绝更新。
-
-## 已知差异 (dev vs 打包)
-
-- dev 的 `MAIN_HASH` 在 vite 启动时计算;启动后改 main 源码不会让运行中的
- 应用变 hash (打包产物没有这个问题)。
-- `RENDERER_OTA_FORCE` / `RENDERER_OTA_CHECK_DELAY` 是运行时 env, 打包产物
- 不设置即无效,不影响生产行为。
diff --git a/apps/desktop/scripts/reportRendererOta.mjs b/apps/desktop/scripts/reportRendererOta.mjs
index b4890a73612..908424d5cd5 100644
--- a/apps/desktop/scripts/reportRendererOta.mjs
+++ b/apps/desktop/scripts/reportRendererOta.mjs
@@ -6,35 +6,44 @@ import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';
const exec = promisify(execFile);
-const patchStages = {
- checkout: 'checkout-failed',
- server: 'server-config-failed',
- base: 'base-fetch-failed',
- setup: 'environment-setup-failed',
- app_version: 'app-version-failed',
- gate: 'hash-compute-failed',
- version: 'patch-version-failed',
- renderer: 'renderer-build-failed',
- sign: 'manifest-sign-failed',
- publish: 'upload-failed',
-};
-const buildStages = {
- setup: 'environment-setup-failed',
- app_version: 'app-version-failed',
- build_macos: 'desktop-build-failed',
- build_windows: 'desktop-build-failed',
- build_linux: 'desktop-build-failed',
- upload: 'artifact-preparation-failed',
-};
-
-const releaseStages = {
- setup: 'environment-setup-failed',
- validate: 'baseline-validation-failed',
- installers: 'installer-upload-failed',
- base: 'renderer-base-upload-failed',
+const stageMaps = {
+ 'gate': {
+ 'checkout': 'checkout-failed',
+ 'server': 'server-config-failed',
+ 'base': 'base-fetch-failed',
+ 'gate': 'abi-compute-failed',
+ 'version': 'core-version-failed',
+ 'cloud-ref': 'cloud-ref-failed',
+ },
+ 'core-build': {
+ setup: 'environment-setup-failed',
+ app_version: 'app-version-failed',
+ build: 'core-build-failed',
+ previous: 'previous-manifest-failed',
+ core: 'core-release-failed',
+ upload: 'artifact-upload-failed',
+ },
+ 'core-publish': {
+ collect: 'artifact-download-failed',
+ publish: 'upload-failed',
+ },
+ 'build': {
+ setup: 'environment-setup-failed',
+ app_version: 'app-version-failed',
+ build_macos: 'desktop-build-failed',
+ build_windows: 'desktop-build-failed',
+ build_linux: 'desktop-build-failed',
+ upload: 'artifact-preparation-failed',
+ },
+ 'release': {
+ setup: 'environment-setup-failed',
+ installers: 'installer-upload-failed',
+ shell: 'shell-json-failed',
+ base: 'core-r0-upload-failed',
+ },
};
-export function classifyResult(steps, kind = 'patch', jobStatus = '') {
+export function classifyResult(steps, kind = 'gate', jobStatus = '') {
const result = (outcome, reason, requiresFullRelease = false) => ({
outcome,
reason,
@@ -42,52 +51,57 @@ export function classifyResult(steps, kind = 'patch', jobStatus = '') {
published: outcome === 'published',
version: outcome === 'published' ? (steps.version?.outputs?.version ?? '') : '',
});
- for (const [id, reason] of Object.entries(
- kind === 'patch' ? patchStages : kind === 'release' ? releaseStages : buildStages,
- )) {
+ const stages = stageMaps[kind] ?? stageMaps.gate;
+ for (const [id, reason] of Object.entries(stages)) {
if (steps[id]?.outcome === 'failure') {
- if (kind === 'patch' && id === 'base' && steps.base.outputs?.reason === 'base-invalid')
+ if (kind === 'gate' && id === 'base' && steps.base.outputs?.reason === 'base-invalid')
return result('failed', 'base-invalid');
- return result(
- 'failed',
- id === 'gate' && steps.gate.outputs?.main_hash ? 'hash-comparison-failed' : reason,
- );
+ return result('failed', reason);
}
}
- if (
- kind === 'release' &&
- steps.base?.outcome === 'success' &&
- steps.base.outputs?.published === 'true'
- )
- return result('published', 'published');
- if (kind === 'patch' && steps.publish?.outcome === 'success')
- return result('published', 'published');
if (
jobStatus === 'cancelled' ||
Object.values(steps).some((step) => step.outcome === 'cancelled')
) {
return result('skipped', 'cancelled');
}
- if (kind === 'release')
- return result('skipped', steps.base?.outputs?.reason || 'release-incomplete');
- if (kind === 'build') {
- if (jobStatus === 'failure') return result('failed', 'build-job-failed');
- return steps.upload?.outcome === 'success'
- ? result('built', 'artifacts-ready')
- : result('skipped', 'build-incomplete');
- }
- const base = steps.base?.outputs ?? {};
- if (steps.base?.outcome === 'success' && base.found === 'false') {
- if (['base-missing', 'unsupported-base'].includes(base.reason))
- return result('skipped', base.reason, true);
- return result('failed', 'base-unavailable');
- }
- if (steps.gate?.outcome === 'success' && steps.gate.outputs?.allowed === 'false') {
- return steps.gate.outputs.reason === 'main-changed'
- ? result('skipped', 'main-changed', true)
- : result('failed', 'hash-comparison-failed');
+ switch (kind) {
+ case 'release': {
+ if (steps.base?.outcome === 'success' && steps.base.outputs?.published === 'true')
+ return result('published', 'published');
+ return result('skipped', steps.base?.outputs?.reason || 'release-incomplete');
+ }
+ case 'build': {
+ if (jobStatus === 'failure') return result('failed', 'build-job-failed');
+ return steps.upload?.outcome === 'success'
+ ? result('built', 'artifacts-ready')
+ : result('skipped', 'build-incomplete');
+ }
+ case 'core-build': {
+ if (steps.core?.outputs?.skipped === 'true') return result('skipped', 'core-unchanged');
+ return steps.upload?.outcome === 'success'
+ ? result('built', 'core-ready')
+ : result('failed', 'pipeline-incomplete');
+ }
+ case 'core-publish': {
+ if (steps.publish?.outputs?.published === 'true') return result('published', 'published');
+ if (steps.collect?.outputs?.skipped === 'true') return result('skipped', 'core-unchanged');
+ return result('failed', 'pipeline-incomplete');
+ }
+ default: {
+ const base = steps.base?.outputs ?? {};
+ if (steps.base?.outcome === 'success' && base.found === 'false') {
+ return base.reason === 'base-missing'
+ ? result('skipped', 'base-missing', true)
+ : result('failed', 'base-unavailable');
+ }
+ if (steps.gate?.outcome === 'success' && steps.gate.outputs?.allowed === 'false')
+ return result('skipped', steps.gate.outputs.reason || 'abi-changed', true);
+ if (steps.gate?.outcome === 'success' && steps.version?.outcome === 'success')
+ return result('gated', 'core-allowed');
+ return result('failed', 'pipeline-incomplete');
+ }
}
- return result('failed', 'pipeline-incomplete');
}
async function readOptional(file) {
@@ -104,20 +118,6 @@ export async function writeDiagnostics({ root = process.cwd(), env = process.env
const result = classifyResult(steps, env.DIAGNOSTIC_KIND, env.JOB_STATUS);
const lock = await readOptional(path.join(root, 'apps/desktop/pnpm-lock.yaml'));
const packageJson = await readOptional(path.join(root, 'apps/desktop/package.json'));
- const releaseDir = env.DIAGNOSTIC_KIND === 'release' ? 'release' : 'apps/desktop/release';
- const inputText = await readOptional(
- path.join(root, releaseDir, 'renderer-mainhash-inputs.json'),
- );
- let inputs;
- let inputManifestStatus = 'missing';
- if (inputText) {
- try {
- inputs = JSON.parse(inputText);
- inputManifestStatus = 'available';
- } catch {
- inputManifestStatus = 'invalid';
- }
- }
let pnpmVersion = null;
try {
pnpmVersion = (await exec('pnpm', ['--version'], { timeout: 5000, cwd: root })).stdout.trim();
@@ -126,11 +126,8 @@ export async function writeDiagnostics({ root = process.cwd(), env = process.env
}
const report = {
...result,
- version:
- result.published && env.DIAGNOSTIC_KIND === 'release'
- ? env.APP_VERSION || ''
- : result.version,
- kind: env.DIAGNOSTIC_KIND || 'patch',
+ version: result.published ? env.APP_VERSION || result.version : result.version,
+ kind: env.DIAGNOSTIC_KIND || 'gate',
channel: env.CHANNEL || null,
appVersion:
env.APP_VERSION ||
@@ -148,20 +145,17 @@ export async function writeDiagnostics({ root = process.cwd(), env = process.env
lockSha256: lock
? createHash('sha256').update(lock.replaceAll('\r\n', '\n')).digest('hex')
: null,
- algorithm: inputs?.algorithm || null,
- mainHash: steps.gate?.outputs?.main_hash || inputs?.mainHash || null,
- baseMainHash: steps.base?.outputs?.main_hash || null,
- inputManifestStatus,
- inputCount: Array.isArray(inputs?.inputs) ? inputs.inputs.length : null,
+ shellAbi: steps.gate?.outputs?.shell_abi || null,
+ baseShellAbi: steps.base?.outputs?.shell_abi || null,
stages: Object.fromEntries(
Object.entries(steps).map(([id, step]) => [id, step.outcome ?? 'unknown']),
),
};
- const dir = path.join(root, 'renderer-ota-diagnostics');
+ const dir = path.join(root, 'desktop-ota-diagnostics');
await mkdir(dir, { recursive: true });
await writeFile(path.join(dir, 'result.json'), `${JSON.stringify(report, null, 2)}\n`);
const summary = [
- '## Renderer OTA diagnostics',
+ '## Desktop OTA diagnostics',
'',
'| Field | Value |',
'| --- | --- |',
diff --git a/apps/desktop/scripts/shellAbi.mjs b/apps/desktop/scripts/shellAbi.mjs
new file mode 100644
index 00000000000..1daa8669a16
--- /dev/null
+++ b/apps/desktop/scripts/shellAbi.mjs
@@ -0,0 +1,90 @@
+import { execFileSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
+const ABI_FILE = 'apps/desktop/shell/abi.json';
+
+const TRACKED_INPUTS = [
+ 'apps/desktop/shell',
+ 'apps/desktop/build',
+ 'apps/desktop/electron-builder.mjs',
+ 'apps/desktop/native-deps.config.mjs',
+ 'apps/desktop/module-deps.config.mjs',
+ 'apps/desktop/external-runtime-deps.config.mjs',
+];
+// set-desktop-version copies icon-<channel>.* over these before packaging; the variants stay hashed.
+const EXCLUDED =
+ /^apps\/desktop\/(?:shell\/(?:abi\.json$|__tests__\/)|build\/(?:icon\.png|icon\.ico|Icon\.icns)$)/;
+
+const sha256 = (data) => createHash('sha256').update(data).digest('hex');
+
+const stableJson = (value) =>
+ value && typeof value === 'object'
+ ? `{${Object.keys(value)
+ .sort()
+ .map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`)
+ .join(',')}}`
+ : JSON.stringify(value);
+
+const gitLsFiles = (root, patterns) =>
+ execFileSync('git', ['ls-files', '-z', '--', ...patterns], { cwd: root })
+ .toString()
+ .split('\0')
+ .filter(Boolean);
+
+const lockEntries = (lockText, depNames) => {
+ const section = lockText.split(/^packages:\n/m)[1]?.split(/^\S/m)[0] ?? '';
+ return section
+ .split(/\n(?= {2}\S)/)
+ .map((block) => block.trim())
+ .filter((block) => {
+ const key = block.split('\n')[0].replaceAll(/^'|':?$|:$/g, '');
+ return depNames.has(key.slice(0, key.lastIndexOf('@')));
+ })
+ .sort();
+};
+
+export const shellAbiInputs = ({ root = REPO_ROOT, publicKey = '' } = {}) => {
+ const read = (file) => fs.readFileSync(path.join(root, file));
+ const pkg = JSON.parse(read('apps/desktop/package.json'));
+ const nativePackageDirs = gitLsFiles(root, ['packages/*/binding.gyp']).map((file) =>
+ path.posix.dirname(file),
+ );
+ const files = gitLsFiles(root, [...TRACKED_INPUTS, ...nativePackageDirs])
+ .filter((file) => !EXCLUDED.test(file))
+ .sort();
+
+ return [
+ stableJson({
+ deps: pkg.dependencies,
+ electron: pkg.devDependencies?.electron,
+ sandbox: pkg.devDependencies?.['@anthropic-ai/sandbox-runtime'],
+ }),
+ ...files.map((file) => `${sha256(read(file))} ${file}`),
+ ...lockEntries(
+ read('apps/desktop/pnpm-lock.yaml').toString(),
+ new Set(Object.keys(pkg.dependencies ?? {})),
+ ),
+ sha256(publicKey.replaceAll('\r', '').trim()),
+ ].join('\n');
+};
+
+export const computeShellAbi = (options) => sha256(shellAbiInputs(options));
+
+if (process.argv[1] === fileURLToPath(import.meta.url)) {
+ const publicKey = (process.env.RENDERER_OTA_PUBLIC_KEY ?? '').replaceAll('\r', '').trim();
+ const shellAbi = computeShellAbi({ publicKey });
+ if (process.argv.includes('--write')) {
+ const { version } = JSON.parse(
+ fs.readFileSync(path.join(REPO_ROOT, 'apps/desktop/package.json'), 'utf8'),
+ );
+ fs.writeFileSync(
+ path.join(REPO_ROOT, ABI_FILE),
+ JSON.stringify({ publicKey, shellAbi, shellVersion: version }, null, 2) + '\n',
+ );
+ }
+ console.log(shellAbi);
+}
diff --git a/apps/desktop/scripts/validateMainHash.mjs b/apps/desktop/scripts/validateMainHash.mjs
deleted file mode 100644
index 4d261ac073e..00000000000
--- a/apps/desktop/scripts/validateMainHash.mjs
+++ /dev/null
@@ -1,118 +0,0 @@
-import { access, readdir, readFile, writeFile } from 'node:fs/promises';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-import { createInputManifest, MAIN_HASH_ALGORITHM } from './mainHash.mjs';
-
-export function diffInputs(before, after) {
- const left = new Map(
- before.inputs.map((input) => [input.path, `${input.group}:${input.sha256}`]),
- );
- const right = new Map(
- after.inputs.map((input) => [input.path, `${input.group}:${input.sha256}`]),
- );
- const changes = [...new Set([...left.keys(), ...right.keys()])]
- .sort()
- .filter((file) => left.get(file) !== right.get(file))
- .map(
- (file) => `${file}: ${left.get(file) ?? '(missing)'} -> ${right.get(file) ?? '(missing)'}`,
- );
- if (before.algorithm !== after.algorithm)
- changes.unshift(`algorithm: ${before.algorithm} -> ${after.algorithm}`);
- return changes;
-}
-
-export function validateInputManifest(manifest) {
- if (
- manifest.algorithm !== MAIN_HASH_ALGORITHM ||
- !Array.isArray(manifest.inputs) ||
- !manifest.inputs.length
- ) {
- throw new Error('Unsupported or empty renderer main hash inputs; full release required');
- }
- for (const input of manifest.inputs) {
- if (
- typeof input.path !== 'string' ||
- typeof input.group !== 'string' ||
- !/^[0-9a-f]{64}$/.test(input.sha256)
- ) {
- throw new Error('Invalid renderer main hash input');
- }
- }
- if (createInputManifest(manifest.inputs).mainHash !== manifest.mainHash) {
- throw new Error('Renderer main hash does not match its input manifest');
- }
-}
-
-export async function validateReleaseInputs(releaseDir, expectedArtifacts) {
- if (!expectedArtifacts.length) throw new Error('Expected build artifacts are required');
- const inputDir = path.join(releaseDir, 'renderer-mainhash');
- const actual = (await readdir(inputDir)).filter((file) => file.endsWith('.json')).sort();
- const expected = expectedArtifacts.map((artifact) => `${artifact}.json`).sort();
- if (JSON.stringify(actual) !== JSON.stringify(expected)) {
- throw new Error(
- `Renderer hash artifacts differ: expected ${expected.join(', ')}, received ${actual.join(', ')}`,
- );
- }
- const manifests = await Promise.all(
- actual.map(async (file) => {
- const manifest = JSON.parse(await readFile(path.join(inputDir, file), 'utf8'));
- validateInputManifest(manifest);
- return manifest;
- }),
- );
- const [base] = manifests;
- for (const [index, manifest] of manifests.entries()) {
- if (base.mainHash !== manifest.mainHash) {
- throw new Error(
- `Renderer main hash differs: ${actual[0]} vs ${actual[index]}\n${diffInputs(base, manifest).join('\n')}`,
- );
- }
- }
- await writeFile(path.join(releaseDir, 'renderer-mainhash.txt'), `${base.mainHash}\n`);
- await writeFile(
- path.join(releaseDir, 'renderer-mainhash-inputs.json'),
- `${JSON.stringify(base, null, 2)}\n`,
- );
- return base;
-}
-
-export async function validateRendererBase(releaseDir, channel, appVersion) {
- const inputs = JSON.parse(
- await readFile(path.join(releaseDir, 'renderer-mainhash-inputs.json'), 'utf8'),
- );
- validateInputManifest(inputs);
- const embedded = (await readFile(path.join(releaseDir, 'renderer-mainhash.txt'), 'utf8')).trim();
- if (inputs.mainHash !== embedded) throw new Error('Renderer baseline differs from packaged hash');
- const root = path.join(releaseDir, 'renderer-ota', channel, appVersion, 'renderer/v2');
- for (const file of ['latest.json', 'versions/r0.json']) {
- const manifest = JSON.parse(await readFile(path.join(root, file), 'utf8'));
- if (
- manifest.mainHash !== embedded ||
- manifest.appVersion !== appVersion ||
- manifest.version !== 'r0' ||
- manifest.schemaVersion !== 2
- ) {
- throw new Error(`Renderer r0 does not match the full release: ${file}`);
- }
- if (!/^packs\/[0-9a-f]{64}\.zip$/.test(manifest.full?.path))
- throw new Error('Invalid r0 pack path');
- await access(path.join(root, manifest.full.path));
- }
- return inputs;
-}
-
-if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
- const [dir, ...expected] = process.argv.slice(2);
- const operation =
- dir === '--base'
- ? validateRendererBase(...expected)
- : validateReleaseInputs(path.resolve(dir ?? 'release'), expected);
- operation.then(
- (manifest) => console.log(`Validated ${expected.length} platform hashes: ${manifest.mainHash}`),
- (error) => {
- console.error(error);
- process.exitCode = 1;
- },
- );
-}
diff --git a/apps/desktop/scripts/vendorShellUpdater.mjs b/apps/desktop/scripts/vendorShellUpdater.mjs
new file mode 100644
index 00000000000..f03f69bdc72
--- /dev/null
+++ b/apps/desktop/scripts/vendorShellUpdater.mjs
@@ -0,0 +1,40 @@
+import fs from 'node:fs';
+import { builtinModules, createRequire } from 'node:module';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { build } from 'vite';
+
+const desktopDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const require = createRequire(path.join(desktopDir, 'package.json'));
+const { version } = require('electron-updater/package.json');
+
+const outFile = path.join(desktopDir, 'shell/rescue/electron-updater.cjs');
+
+await build({
+ build: {
+ emptyOutDir: false,
+ minify: true,
+ outDir: path.join(desktopDir, 'shell/rescue'),
+ rolldownOptions: {
+ external: ['electron', ...builtinModules, ...builtinModules.map((m) => `node:${m}`)],
+ output: {
+ entryFileNames: 'electron-updater.cjs',
+ format: 'cjs',
+ },
+ },
+ ssr: require.resolve('electron-updater'),
+ target: 'node22',
+ },
+ configFile: false,
+ logLevel: 'warn',
+ root: desktopDir,
+ ssr: { noExternal: true },
+});
+
+fs.writeFileSync(
+ outFile,
+ `/* electron-updater@${version} generated by shell:vendor */\n${fs.readFileSync(outFile, 'utf8')}`,
+);
+
+console.log(`vendored electron-updater@${version} into shell/rescue/electron-updater.cjs`);
diff --git a/apps/desktop/shell/__tests__/core-loader.test.mjs b/apps/desktop/shell/__tests__/core-loader.test.mjs
new file mode 100644
index 00000000000..2b22b24de33
--- /dev/null
+++ b/apps/desktop/shell/__tests__/core-loader.test.mjs
@@ -0,0 +1,422 @@
+import { createHash, generateKeyPairSync, sign } from 'node:crypto';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { canonicalJson, resolveCore } from '../core-loader.js';
+
+const ABI = 'a'.repeat(64);
+const { privateKey, publicKey } = generateKeyPairSync('ed25519');
+const publicKeyPem = publicKey.export({ format: 'pem', type: 'spki' });
+const privateKeyPem = privateKey.export({ format: 'pem', type: 'pkcs8' });
+
+const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');
+
+const signManifest = (manifest) => ({
+ ...manifest,
+ signature: sign(null, Buffer.from(canonicalJson(manifest)), privateKeyPem).toString('base64'),
+});
+
+let tmp;
+let userData;
+let builtinDir;
+const otaRoot = () => path.join(userData, 'core-ota');
+const pointerFile = () => path.join(otaRoot(), 'pointer.json');
+const readBoot = () => JSON.parse(fs.readFileSync(path.join(otaRoot(), 'boot.json'), 'utf8'));
+const readPointer = () => JSON.parse(fs.readFileSync(pointerFile(), 'utf8'));
+const writeJson = (file, value) => {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, JSON.stringify(value));
+};
+
+const writeCore = (dir, version, { shellAbi = ABI, seq, channel, mutate } = {}) => {
+ const files = {
+ 'cli/lobe-cli.js': 'cli',
+ 'dist/main/index.js': `module.exports = ${JSON.stringify(version)};`,
+ 'dist/preload/index.js': '// preload',
+ 'dist/renderer/index.html': '<html/>',
+ 'node_modules/electron-log/main.js': 'log',
+ 'package.json': '{"type":"commonjs"}',
+ };
+ const tree = Object.entries(files).map(([filePath, content]) => {
+ fs.mkdirSync(path.join(dir, path.dirname(filePath)), { recursive: true });
+ fs.writeFileSync(path.join(dir, filePath), content);
+ return { path: filePath, sha256: sha256(content), size: content.length };
+ });
+ const manifest = signManifest({
+ shellAbi,
+ tree,
+ version,
+ ...(seq === undefined ? {} : { seq }),
+ ...(channel === undefined ? {} : { channel }),
+ });
+ mutate?.(dir, manifest);
+ writeJson(path.join(dir, 'manifest.json'), manifest);
+};
+
+const writePointer = (pointer) => writeJson(pointerFile(), { abi: ABI, ...pointer });
+
+const writeExternal = (version, opts) =>
+ writeCore(path.join(otaRoot(), 'cores', version), version, opts);
+
+const resolve = () => resolveCore({ abi: ABI, builtinDir, publicKey: publicKeyPem, userData });
+
+beforeEach(() => {
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'core-loader-'));
+ userData = path.join(tmp, 'userData');
+ builtinDir = path.join(tmp, 'builtin');
+ writeCore(builtinDir, '1.0.0');
+});
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ fs.rmSync(tmp, { force: true, recursive: true });
+});
+
+describe('resolveCore', () => {
+ it('falls back to builtin when there is no pointer', () => {
+ const core = resolve();
+ expect(core.source).toBe('builtin');
+ expect(core.dir).toBe(builtinDir);
+ expect(core.manifest.version).toBe('1.0.0');
+ });
+
+ it('returns builtin with null manifest when builtin manifest is missing', () => {
+ fs.rmSync(path.join(builtinDir, 'manifest.json'));
+ const core = resolve();
+ expect(core.source).toBe('builtin');
+ expect(core.manifest).toBeNull();
+ expect(core.log.join('\n')).toMatch(/builtin/);
+ });
+
+ it('loads a valid current core and bumps boot failures', () => {
+ writeExternal('1.1.0');
+ writePointer({ current: '1.1.0' });
+ const core = resolve();
+ expect(core.source).toBe('external');
+ expect(core.dir).toBe(path.join(otaRoot(), 'cores', '1.1.0'));
+ expect(core.manifest.version).toBe('1.1.0');
+ expect(readBoot()).toEqual({ failures: 1, healthy: false, version: '1.1.0' });
+ });
+
+ it('rejects a core whose shellAbi differs', () => {
+ writeExternal('1.1.0', { shellAbi: 'b'.repeat(64) });
+ writePointer({ current: '1.1.0' });
+ const core = resolve();
+ expect(core.source).toBe('builtin');
+ expect(core.log.join('\n')).toMatch(/shellAbi/);
+ });
+
+ it('rejects a core with a bad signature', () => {
+ writeExternal('1.1.0', { mutate: (_, manifest) => (manifest.version = '9.9.9') });
+ writePointer({ current: '1.1.0' });
+ const core = resolve();
+ expect(core.source).toBe('builtin');
+ expect(core.log.join('\n')).toMatch(/signature/);
+ });
+
+ it('rejects a core whose main file hash mismatches', () => {
+ writeExternal('1.1.0', {
+ mutate: (dir) => fs.writeFileSync(path.join(dir, 'dist/main/index.js'), 'tampered'),
+ });
+ writePointer({ current: '1.1.0' });
+ const core = resolve();
+ expect(core.source).toBe('builtin');
+ expect(core.log.join('\n')).toMatch(/dist\/main\/index\.js/);
+ });
+
+ it('rejects a core whose renderer file hash mismatches', () => {
+ writeExternal('1.1.0', {
+ mutate: (dir) => fs.writeFileSync(path.join(dir, 'dist/renderer/index.html'), 'changed'),
+ });
+ writePointer({ current: '1.1.0' });
+ const core = resolve();
+ expect(core.source).toBe('builtin');
+ expect(core.log.join('\n')).toContain('hash mismatch dist/renderer/index.html');
+ });
+
+ it.each(['node_modules/electron-log/main.js', 'cli/lobe-cli.js', 'package.json'])(
+ 'rejects a core whose %s hash mismatches',
+ (file) => {
+ writeExternal('1.1.0', {
+ mutate: (dir) => fs.writeFileSync(path.join(dir, file), 'tampered'),
+ });
+ writePointer({ current: '1.1.0' });
+ const core = resolve();
+ expect(core.source).toBe('builtin');
+ expect(core.log.join('\n')).toContain(`hash mismatch ${file}`);
+ },
+ );
+
+ it.each(['../x', 'dist/main/../x', './x', '/x', 'dist\\main\\x'])(
+ 'rejects a signed manifest whose tree contains %s',
+ (unsafe) => {
+ writeExternal('1.1.0', {
+ mutate: (_, manifest) => {
+ delete manifest.signature;
+ manifest.tree.push({ path: unsafe, sha256: sha256(''), size: 0 });
+ Object.assign(manifest, signManifest(manifest));
+ },
+ });
+ writePointer({ current: '1.1.0' });
+ const core = resolve();
+ expect(core.source).toBe('builtin');
+ expect(core.log.join('\n')).toMatch(/unsafe tree path/);
+ },
+ );
+
+ it('falls back to previous after 3 boot failures of current', () => {
+ writeExternal('1.1.0');
+ writeExternal('1.0.5');
+ writePointer({ current: '1.1.0', previous: '1.0.5' });
+ writeJson(path.join(otaRoot(), 'boot.json'), { failures: 3, version: '1.1.0' });
+ const core = resolve();
+ expect(core.source).toBe('external');
+ expect(core.manifest.version).toBe('1.0.5');
+ expect(readBoot()).toEqual({ failures: 1, healthy: false, version: '1.0.5' });
+ expect(readPointer()).toEqual({
+ abi: ABI,
+ blacklist: ['1.1.0'],
+ channel: null,
+ current: '1.0.5',
+ previous: null,
+ staged: null,
+ });
+ });
+
+ it('nulls current after 3 boot failures when previous is unverifiable', () => {
+ writeExternal('1.1.0');
+ writePointer({ current: '1.1.0', previous: '1.0.5' });
+ writeJson(path.join(otaRoot(), 'boot.json'), { failures: 3, version: '1.1.0' });
+ expect(resolve().source).toBe('builtin');
+ expect(readPointer()).toEqual({
+ abi: ABI,
+ blacklist: ['1.1.0'],
+ channel: null,
+ current: null,
+ previous: null,
+ staged: null,
+ });
+ });
+
+ it.each(['__proto__', 'constructor', 'toString'])(
+ 'never treats prototype key %s as a verified core',
+ (version) => {
+ const dir = path.join(otaRoot(), 'cores', version);
+ fs.mkdirSync(path.join(dir, 'dist/main'), { recursive: true });
+ fs.writeFileSync(path.join(dir, 'dist/main/index.js'), 'unsigned');
+ writePointer({ current: version });
+ const core = resolve();
+ expect(core.source).toBe('builtin');
+ expect(core.log.join('\n')).toMatch(/rejected/);
+ },
+ );
+
+ it('nulls current and blacklists after 3 boot failures without previous', () => {
+ writeExternal('1.1.0');
+ writePointer({ current: '1.1.0' });
+ writeJson(path.join(otaRoot(), 'boot.json'), { failures: 3, version: '1.1.0' });
+ expect(resolve().source).toBe('builtin');
+ expect(readPointer()).toEqual({
+ abi: ABI,
+ blacklist: ['1.1.0'],
+ channel: null,
+ current: null,
+ previous: null,
+ staged: null,
+ });
+ });
+
+ it('ignores a pointer written by another shell abi and leaves it untouched', () => {
+ writeExternal('1.1.0');
+ writePointer({ abi: 'b'.repeat(64), current: '1.1.0' });
+ const raw = fs.readFileSync(pointerFile(), 'utf8');
+ const core = resolve();
+ expect(core.source).toBe('builtin');
+ expect(core.log.join('\n')).toMatch(/abi/);
+ expect(fs.readFileSync(pointerFile(), 'utf8')).toBe(raw);
+ });
+
+ it('promotes a valid staged core on cold boot and writes the pointer back', () => {
+ writeExternal('1.1.0');
+ writeExternal('1.2.0');
+ writePointer({ blacklist: [], current: '1.1.0', previous: null, staged: '1.2.0' });
+ const core = resolve();
+ expect(core.source).toBe('external');
+ expect(core.manifest.version).toBe('1.2.0');
+ expect(readBoot()).toEqual({ failures: 1, healthy: false, version: '1.2.0' });
+ expect(readPointer()).toEqual({
+ abi: ABI,
+ blacklist: [],
+ channel: null,
+ current: '1.2.0',
+ previous: '1.1.0',
+ staged: null,
+ });
+ });
+
+ it('drops current and previous when the builtin core has a higher or equal seq', () => {
+ writeCore(builtinDir, '2.0.0', { seq: 5 });
+ writeExternal('1.1.0', { seq: 5 });
+ writeExternal('1.0.5', { seq: 4 });
+ writePointer({ blacklist: [], current: '1.1.0', previous: '1.0.5', staged: null });
+ const core = resolve();
+ expect(core.source).toBe('builtin');
+ expect(core.manifest.version).toBe('2.0.0');
+ expect(core.log).toContain('core 1.1.0 seq 5 superseded by builtin seq 5');
+ expect(readPointer()).toMatchObject({ blacklist: [], current: null, previous: null });
+ expect(readBoot().version).toMatch(/^builtin@/);
+ });
+
+ it('still loads an external core whose seq is above the builtin', () => {
+ writeCore(builtinDir, '2.0.0', { seq: 5 });
+ writeExternal('2.0.0-core.6', { seq: 6 });
+ writePointer({ current: '2.0.0-core.6' });
+ expect(resolve().manifest.version).toBe('2.0.0-core.6');
+ });
+
+ it('drops an external core from another channel than the pointer names', () => {
+ writeCore(builtinDir, '2.0.0', { channel: 'stable', seq: 5 });
+ writeExternal('1.1.0', { channel: 'canary', seq: 300 });
+ writePointer({ channel: 'stable', current: '1.1.0' });
+ const core = resolve();
+ expect(core.source).toBe('builtin');
+ expect(core.log).toContain('core 1.1.0 channel canary != stable');
+ expect(readPointer()).toMatchObject({ channel: 'stable', current: null, previous: null });
+ });
+
+ it('does not let a builtin from another channel supersede the selected channel core', () => {
+ writeCore(builtinDir, '2.0.0', { channel: 'stable', seq: 5 });
+ writeExternal('1.1.0', { channel: 'canary', seq: 3 });
+ writePointer({ channel: 'canary', current: '1.1.0' });
+ expect(resolve().manifest.version).toBe('1.1.0');
+ });
+
+ it('discards a staged core superseded by the builtin instead of promoting it', () => {
+ writeCore(builtinDir, '2.0.0', { seq: 5 });
+ writeExternal('1.2.0', { seq: 3 });
+ writePointer({ blacklist: [], current: null, previous: null, staged: '1.2.0' });
+ const core = resolve();
+ expect(core.source).toBe('builtin');
+ expect(readPointer()).toMatchObject({ current: null, previous: null, staged: null });
+ });
+
+ it('keeps current when staged fails verification', () => {
+ writeExternal('1.1.0');
+ writeExternal('1.2.0', {
+ mutate: (dir) => fs.writeFileSync(path.join(dir, 'dist/main/index.js'), 'tampered'),
+ });
+ writePointer({ current: '1.1.0', staged: '1.2.0' });
+ const raw = fs.readFileSync(pointerFile(), 'utf8');
+ const core = resolve();
+ expect(core.manifest.version).toBe('1.1.0');
+ expect(core.log.join('\n')).toMatch(/staged 1\.2\.0/);
+ expect(fs.readFileSync(pointerFile(), 'utf8')).toBe(raw);
+ });
+
+ it('skips blacklisted versions', () => {
+ writeExternal('1.1.0');
+ writeExternal('1.0.5');
+ writePointer({ blacklist: ['1.1.0'], current: '1.1.0', previous: '1.0.5' });
+ const core = resolve();
+ expect(core.manifest.version).toBe('1.0.5');
+ expect(core.log.join('\n')).toMatch(/1\.1\.0 rejected: blacklisted/);
+ });
+
+ it('rejects version names with path separators', () => {
+ writeCore(path.join(tmp, 'evil'), '1.1.0');
+ writePointer({ current: '../../evil' });
+ const core = resolve();
+ expect(core.source).toBe('builtin');
+ expect(core.log.join('\n')).toMatch(/version/);
+
+ writePointer({ current: '..' });
+ expect(resolve().source).toBe('builtin');
+ });
+
+ it('rejects a signed manifest whose tree omits dist/main/index.js', () => {
+ writeExternal('1.1.0', {
+ mutate: (_, manifest) => {
+ delete manifest.signature;
+ manifest.tree = manifest.tree.filter((entry) => entry.path !== 'dist/main/index.js');
+ Object.assign(manifest, signManifest(manifest));
+ },
+ });
+ writePointer({ current: '1.1.0' });
+ const core = resolve();
+ expect(core.source).toBe('builtin');
+ expect(core.log.join('\n')).toMatch(/dist\/main\/index\.js/);
+ });
+
+ it('markHealthy resets failures for external cores', () => {
+ writeExternal('1.1.0');
+ writePointer({ current: '1.1.0' });
+ writeJson(path.join(otaRoot(), 'boot.json'), { failures: 2, version: '1.1.0' });
+ const core = resolve();
+ expect(readBoot()).toEqual({ failures: 3, healthy: false, version: '1.1.0' });
+ core.markHealthy();
+ expect(readBoot()).toEqual({ failures: 0, healthy: true, version: '1.1.0' });
+ resolve();
+ expect(readBoot()).toEqual({ failures: 1, healthy: true, version: '1.1.0' });
+ });
+
+ it('counts builtin boots under a builtin key and markHealthy resets them', () => {
+ resolve();
+ const core = resolve();
+ expect(core.source).toBe('builtin');
+ expect(readBoot()).toEqual({ failures: 2, healthy: false, version: '[email protected]' });
+ core.markHealthy();
+ expect(readBoot()).toEqual({ failures: 0, healthy: true, version: '[email protected]' });
+ });
+
+ it('asks for rescue after 3 unhealthy builtin boots', () => {
+ for (let i = 0; i < 3; i += 1) expect(resolve().source).toBe('builtin');
+ const core = resolve();
+ expect(core.source).toBe('rescue');
+ expect(core.log.join('\n')).toMatch(/builtin@1\.0\.0 failed 3 boots/);
+ expect(readBoot().failures).toBe(3);
+ });
+
+ it('gives a new builtin version a fresh boot budget', () => {
+ writeJson(path.join(otaRoot(), 'boot.json'), { failures: 3, version: '[email protected]' });
+ expect(resolve().source).toBe('builtin');
+ expect(readBoot()).toEqual({ failures: 1, healthy: false, version: '[email protected]' });
+ });
+
+ it('markBroken on builtin sends the next launch to rescue', () => {
+ resolve().markBroken();
+ expect(resolve().source).toBe('rescue');
+ });
+
+ it('markBroken on an external core falls back to previous on the next launch', () => {
+ writeExternal('1.1.0');
+ writeExternal('1.0.5');
+ writePointer({ current: '1.1.0', previous: '1.0.5' });
+ resolve().markBroken();
+ const core = resolve();
+ expect(core.manifest.version).toBe('1.0.5');
+ expect(readPointer().blacklist).toEqual(['1.1.0']);
+ });
+
+ it('boots builtin even when boot state cannot be written', () => {
+ const blocked = path.join(tmp, 'blocked');
+ fs.writeFileSync(blocked, '');
+ const core = resolveCore({ abi: ABI, builtinDir, publicKey: publicKeyPem, userData: blocked });
+ expect(core.source).toBe('builtin');
+ expect(core.log.join('\n')).toMatch(/builtin boot count failed/);
+ expect(() => core.markHealthy()).not.toThrow();
+ expect(() => core.markBroken()).not.toThrow();
+ });
+
+ it('never throws on corrupt pointer or missing core dir', () => {
+ fs.mkdirSync(otaRoot(), { recursive: true });
+ fs.writeFileSync(path.join(otaRoot(), 'pointer.json'), '{not json');
+ expect(resolve().source).toBe('builtin');
+ writePointer({ current: '9.9.9' });
+ const core = resolve();
+ expect(core.source).toBe('builtin');
+ expect(core.log.join('\n')).toMatch(/9\.9\.9/);
+ });
+});
diff --git a/apps/desktop/shell/__tests__/rescue.test.mjs b/apps/desktop/shell/__tests__/rescue.test.mjs
new file mode 100644
index 00000000000..92faa25e517
--- /dev/null
+++ b/apps/desktop/shell/__tests__/rescue.test.mjs
@@ -0,0 +1,301 @@
+import fs from 'node:fs';
+import { createRequire } from 'node:module';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const rescuePath = fileURLToPath(new URL('../rescue/index.js', import.meta.url));
+const updaterPath = fileURLToPath(new URL('../rescue/electron-updater.cjs', import.meta.url));
+const require = createRequire(rescuePath);
+const electronPath = require.resolve('electron');
+
+let tmp;
+let userData;
+let resourcesPath;
+
+const writeJson = (file, value) => {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, JSON.stringify(value));
+};
+
+const fakeUpdater = ({ check = async () => null } = {}) => {
+ const listeners = {};
+ let channel = null;
+ return {
+ allowDowngrade: false,
+ get channel() {
+ return channel;
+ },
+ set channel(value) {
+ channel = value;
+ this.allowDowngrade = false;
+ },
+ checkForUpdates: vi.fn(check),
+ downloadUpdate: vi.fn(async () => {
+ listeners['download-progress']?.({ percent: 42.7 });
+ }),
+ on: vi.fn((event, handler) => {
+ listeners[event] = handler;
+ }),
+ quitAndInstall: vi.fn(),
+ setFeedURL: vi.fn(),
+ };
+};
+
+const fakeElectron = ({ response = 0 } = {}) => {
+ const handlers = {};
+ const app = {
+ exit: vi.fn(),
+ getLocale: () => 'en-US',
+ getPath: () => userData,
+ on: vi.fn((event, handler) => {
+ handlers[event] = handler;
+ }),
+ relaunch: vi.fn(),
+ releaseSingleInstanceLock: vi.fn(),
+ whenReady: () => Promise.resolve(),
+ };
+ const texts = [];
+ class BrowserWindow {
+ webContents = {
+ executeJavaScript: vi.fn(async (code) => {
+ texts.push(code);
+ }),
+ };
+ isDestroyed = () => false;
+ loadURL = vi.fn(() => Promise.resolve());
+ }
+ return {
+ app,
+ BrowserWindow,
+ dialog: { showMessageBox: vi.fn(async () => ({ response })) },
+ handlers,
+ shell: { openExternal: vi.fn(() => Promise.resolve()) },
+ texts,
+ };
+};
+
+const loadRescue = (electron, updater) => {
+ require.cache[electronPath] = { exports: electron, id: electronPath, loaded: true };
+ if (updater instanceof Error) {
+ require.cache[updaterPath] = {
+ get exports() {
+ throw updater;
+ },
+ id: updaterPath,
+ loaded: true,
+ };
+ } else if (updater) {
+ require.cache[updaterPath] = {
+ exports: { autoUpdater: updater },
+ id: updaterPath,
+ loaded: true,
+ };
+ }
+ delete require.cache[rescuePath];
+ return require(rescuePath);
+};
+
+const run = async (electron, updater) => {
+ const fallback = vi.fn();
+ loadRescue(electron, updater).runRescue({
+ downloadUrl: 'https://example.com/downloads',
+ error: new Error('core boom'),
+ fallback,
+ log: ['shell line'],
+ });
+ await vi.waitFor(() =>
+ expect(
+ electron.app.exit.mock.calls.length +
+ fallback.mock.calls.length +
+ (updater?.quitAndInstall?.mock.calls.length ?? 0),
+ ).toBeGreaterThan(0),
+ );
+ return { fallback };
+};
+
+beforeEach(() => {
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'shell-rescue-'));
+ userData = path.join(tmp, 'userData');
+ resourcesPath = process.resourcesPath;
+ process.resourcesPath = path.join(tmp, 'resources');
+ fs.mkdirSync(process.resourcesPath, { recursive: true });
+ fs.writeFileSync(
+ path.join(process.resourcesPath, 'app-update.yml'),
+ 'provider: generic\nurl: https://releases.example.com/canary\n',
+ );
+});
+
+afterEach(() => {
+ for (const file of [electronPath, rescuePath, updaterPath]) delete require.cache[file];
+ process.resourcesPath = resourcesPath;
+ fs.rmSync(tmp, { force: true, recursive: true });
+});
+
+describe('rescue config', () => {
+ const { resolveChannel, resolveFeedUrl, configureUpdater } = (() => {
+ require.cache[electronPath] = { exports: {}, id: electronPath, loaded: true };
+ delete require.cache[rescuePath];
+ const mod = require(rescuePath);
+ delete require.cache[electronPath];
+ return mod;
+ })();
+
+ it.each([
+ ['canary', undefined, 'canary'],
+ ['stable', 'canary', 'stable'],
+ ['nightly', undefined, 'stable'],
+ [undefined, 'beta', 'canary'],
+ [undefined, 'canary', 'canary'],
+ [undefined, 'stable', 'stable'],
+ [undefined, undefined, 'stable'],
+ ])('stored %s with builtin %s resolves to %s', (stored, built, expected) => {
+ if (stored) writeJson(path.join(userData, 'lobehub-settings.json'), { updateChannel: stored });
+ if (built)
+ writeJson(path.join(process.resourcesPath, 'core', 'manifest.json'), { channel: built });
+ expect(resolveChannel({ resourcesPath: process.resourcesPath, userData })).toBe(expected);
+ });
+
+ it('re-roots the app-update.yml feed on the resolved channel', () => {
+ expect(resolveFeedUrl({ channel: 'stable', resourcesPath: process.resourcesPath })).toBe(
+ 'https://releases.example.com/stable',
+ );
+ });
+
+ it('accepts a quoted url and leaves github builds to app-update.yml', () => {
+ const yml = path.join(process.resourcesPath, 'app-update.yml');
+ fs.writeFileSync(yml, "provider: generic\nurl: 'https://r.example.com/'\n");
+ expect(resolveFeedUrl({ channel: 'canary', resourcesPath: process.resourcesPath })).toBe(
+ 'https://r.example.com/canary',
+ );
+ fs.writeFileSync(yml, 'provider: github\nowner: lobehub\nrepo: lobehub\n');
+ expect(resolveFeedUrl({ channel: 'canary', resourcesPath: process.resourcesPath })).toBe(
+ undefined,
+ );
+ });
+
+ it('keeps downgrades allowed after the channel setter resets them', () => {
+ const updater = fakeUpdater();
+ configureUpdater(updater, { channel: 'canary', feedUrl: 'https://f/canary', logger: {} });
+ expect(updater.channel).toBe('canary');
+ expect(updater.allowDowngrade).toBe(true);
+ expect(updater.allowPrerelease).toBe(true);
+ expect(updater.autoDownload).toBe(false);
+ expect(updater.setFeedURL).toHaveBeenCalledWith({
+ provider: 'generic',
+ url: 'https://f/canary',
+ });
+ });
+});
+
+describe('runRescue', () => {
+ it('downloads and installs an available update', async () => {
+ const electron = fakeElectron();
+ const updater = fakeUpdater({
+ check: async () => ({ isUpdateAvailable: true, updateInfo: { version: '2.0.0' } }),
+ });
+ await run(electron, updater);
+
+ expect(updater.setFeedURL).toHaveBeenCalledWith({
+ provider: 'generic',
+ url: 'https://releases.example.com/stable',
+ });
+ expect(updater.downloadUpdate).toHaveBeenCalled();
+ expect(electron.app.releaseSingleInstanceLock).toHaveBeenCalled();
+ expect(updater.quitAndInstall).toHaveBeenCalledWith(true, true);
+ expect(electron.texts.join('\n')).toMatch(/Downloading update… 42%/);
+
+ electron.handlers['window-all-closed']();
+ expect(electron.app.exit).not.toHaveBeenCalled();
+ });
+
+ it('surfaces an install failure reported after quitAndInstall instead of hanging', async () => {
+ const electron = fakeElectron({ response: 2 });
+ const updater = fakeUpdater({
+ check: async () => ({ isUpdateAvailable: true, updateInfo: { version: '2.0.0' } }),
+ });
+ await run(electron, updater);
+ const onError = updater.on.mock.calls.find(([event]) => event === 'error')[1];
+
+ onError(new Error('Could not locate update bundle'));
+
+ await vi.waitFor(() => expect(electron.app.exit).toHaveBeenCalledWith(1));
+ expect(electron.dialog.showMessageBox.mock.calls[0][1].message).toMatch(/Failed/);
+ });
+
+ it('ignores updater error events that the check already reported', async () => {
+ const electron = fakeElectron({ response: 2 });
+ const updater = fakeUpdater({
+ check: async () => {
+ throw new Error('offline');
+ },
+ });
+ await run(electron, updater);
+ const onError = updater.on.mock.calls.find(([event]) => event === 'error')[1];
+
+ onError(new Error('offline'));
+
+ expect(electron.dialog.showMessageBox).toHaveBeenCalledTimes(1);
+ });
+
+ it('offers a retry launch that clears the boot counter when already on the latest version', async () => {
+ writeJson(path.join(userData, 'core-ota', 'boot.json'), { failures: 3, version: 'builtin@1' });
+ const electron = fakeElectron({ response: 0 });
+ await run(electron, fakeUpdater({ check: async () => ({ isUpdateAvailable: false }) }));
+
+ expect(electron.dialog.showMessageBox.mock.calls[0][1].message).toMatch(/latest version/);
+ expect(fs.existsSync(path.join(userData, 'core-ota', 'boot.json'))).toBe(false);
+ expect(electron.app.relaunch).toHaveBeenCalled();
+ expect(electron.app.exit).toHaveBeenCalledWith(0);
+ });
+
+ it('opens the download page when the check fails', async () => {
+ const electron = fakeElectron({ response: 1 });
+ await run(
+ electron,
+ fakeUpdater({
+ check: async () => {
+ throw new Error('offline');
+ },
+ }),
+ );
+
+ expect(electron.dialog.showMessageBox.mock.calls[0][1].message).toMatch(/Failed/);
+ expect(electron.shell.openExternal).toHaveBeenCalledWith('https://example.com/downloads');
+ expect(electron.app.exit).toHaveBeenCalledWith(1);
+ });
+
+ it('treats an inactive updater as a failure instead of claiming the app is up to date', async () => {
+ const electron = fakeElectron({ response: 2 });
+ await run(electron, fakeUpdater({ check: async () => null }));
+
+ expect(electron.dialog.showMessageBox.mock.calls[0][1].message).toMatch(/Failed/);
+ expect(electron.app.exit).toHaveBeenCalledWith(1);
+ });
+
+ it('hands over to the fallback when the vendored updater cannot load', async () => {
+ const electron = fakeElectron();
+ const { fallback } = await run(electron, new Error('missing bundle'));
+
+ expect(fallback).toHaveBeenCalled();
+ });
+
+ it('logs the core failure and shell log for support', async () => {
+ const electron = fakeElectron({ response: 2 });
+ await run(electron, fakeUpdater({ check: async () => ({ isUpdateAvailable: false }) }));
+
+ const log = fs.readFileSync(path.join(userData, 'logs', 'shell-rescue.log'), 'utf8');
+ expect(log).toMatch(/core boom/);
+ expect(log).toMatch(/shell: shell line/);
+ });
+});
+
+describe('vendored electron-updater', () => {
+ it('matches the installed electron-updater version (run `bun run shell:vendor`)', () => {
+ const banner = fs.readFileSync(updaterPath, 'utf8').split('\n', 1)[0];
+ const { version } = require('electron-updater/package.json');
+ expect(banner).toBe(`/* electron-updater@${version} generated by shell:vendor */`);
+ });
+});
diff --git a/apps/desktop/shell/__tests__/shell-main.test.mjs b/apps/desktop/shell/__tests__/shell-main.test.mjs
new file mode 100644
index 00000000000..322b25030f7
--- /dev/null
+++ b/apps/desktop/shell/__tests__/shell-main.test.mjs
@@ -0,0 +1,180 @@
+import fs from 'node:fs';
+import { createRequire } from 'node:module';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mainPath = fileURLToPath(new URL('../main.js', import.meta.url));
+const loaderPath = fileURLToPath(new URL('../core-loader.js', import.meta.url));
+const rescuePath = fileURLToPath(new URL('../rescue/index.js', import.meta.url));
+const abiPath = fileURLToPath(new URL('../abi.json', import.meta.url));
+const require = createRequire(mainPath);
+const electronPath = require.resolve('electron');
+
+let tmp;
+let resourcesPath;
+let coreMain;
+let wroteAbi = false;
+
+const stub = (file, exports) => {
+ require.cache[file] = { exports, id: file, loaded: true };
+};
+
+const loadMain = ({ app, electron = {}, resolveCore, runRescue = vi.fn() }) => {
+ stub(electronPath, { app, ...electron });
+ if (resolveCore) stub(loaderPath, { installShellResolver: vi.fn(), resolveCore });
+ stub(rescuePath, { runRescue });
+ delete require.cache[mainPath];
+ delete require.cache[coreMain];
+ require(mainPath);
+ return { runRescue };
+};
+
+const packagedApp = (overrides = {}) => ({
+ exit: vi.fn(),
+ getPath: vi.fn(() => path.join(tmp, 'userData')),
+ getVersion: () => '1.0.0',
+ isPackaged: true,
+ relaunch: vi.fn(),
+ requestSingleInstanceLock: vi.fn(() => true),
+ whenReady: vi.fn(() => Promise.resolve()),
+ ...overrides,
+});
+
+const fakeCore = (source, body = 'module.exports = 1;') => {
+ fs.mkdirSync(path.dirname(coreMain), { recursive: true });
+ fs.writeFileSync(coreMain, body);
+ return {
+ dir: path.join(tmp, 'core'),
+ log: ['a log line'],
+ manifest: null,
+ markBroken: vi.fn(),
+ markHealthy: vi.fn(),
+ source,
+ };
+};
+
+beforeEach(() => {
+ // abi.json is generated by beforePack and gitignored, so a clean checkout has none
+ if (!fs.existsSync(abiPath)) {
+ fs.writeFileSync(
+ abiPath,
+ JSON.stringify({ publicKey: '', shellAbi: 'test', shellVersion: '1.0.0' }),
+ );
+ wroteAbi = true;
+ }
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'shell-main-'));
+ coreMain = path.join(tmp, 'core', 'dist', 'main', 'index.js');
+ resourcesPath = process.resourcesPath;
+ process.resourcesPath = path.join(tmp, 'resources');
+});
+
+afterEach(() => {
+ for (const file of [electronPath, loaderPath, rescuePath, mainPath, coreMain, abiPath])
+ delete require.cache[file];
+ if (wroteAbi) {
+ fs.rmSync(abiPath, { force: true });
+ wroteAbi = false;
+ }
+ delete global.__SHELL__;
+ process.resourcesPath = resourcesPath;
+ fs.rmSync(tmp, { force: true, recursive: true });
+});
+
+describe('shell main', () => {
+ it('exits a secondary instance before touching core OTA boot state', () => {
+ const userData = path.join(tmp, 'userData');
+ const app = {
+ exit: vi.fn(),
+ getPath: vi.fn(() => userData),
+ getVersion: () => '1.0.0',
+ isPackaged: true,
+ requestSingleInstanceLock: vi.fn(() => false),
+ };
+
+ stub(electronPath, { app });
+ delete require.cache[mainPath];
+ require(mainPath);
+
+ expect(app.exit).toHaveBeenCalledWith(0);
+ expect(app.getPath).not.toHaveBeenCalled();
+ expect(fs.existsSync(path.join(userData, 'core-ota', 'boot.json'))).toBe(false);
+ });
+
+ it('boots the resolved core and exposes markHealthy to it', () => {
+ const core = fakeCore('builtin', 'global.__BOOTED__ = true;');
+ const { runRescue } = loadMain({ app: packagedApp(), resolveCore: () => core });
+
+ expect(global.__BOOTED__).toBe(true);
+ expect(global.__SHELL__.markHealthy).toBe(core.markHealthy);
+ expect(runRescue).not.toHaveBeenCalled();
+ delete global.__BOOTED__;
+ });
+
+ it('rescues in-process when the builtin core throws while loading', () => {
+ const core = fakeCore('builtin', 'throw new Error("builtin boom");');
+ const { runRescue } = loadMain({ app: packagedApp(), resolveCore: () => core });
+
+ expect(core.markBroken).toHaveBeenCalled();
+ expect(runRescue).toHaveBeenCalledWith(
+ expect.objectContaining({
+ downloadUrl: 'https://lobehub.com/downloads',
+ error: expect.objectContaining({ message: 'builtin boom' }),
+ log: ['a log line'],
+ }),
+ );
+ });
+
+ it('relaunches instead of rescuing when an external core throws while loading', () => {
+ const app = packagedApp();
+ const core = fakeCore('external', 'throw new Error("external boom");');
+ const { runRescue } = loadMain({ app, resolveCore: () => core });
+
+ expect(core.markBroken).toHaveBeenCalled();
+ expect(app.relaunch).toHaveBeenCalled();
+ expect(app.exit).toHaveBeenCalledWith(1);
+ expect(runRescue).not.toHaveBeenCalled();
+ });
+
+ it('rescues without loading any core when the loader asks for it', () => {
+ const core = fakeCore('rescue', 'global.__BOOTED__ = true;');
+ const { runRescue } = loadMain({ app: packagedApp(), resolveCore: () => core });
+
+ expect(global.__BOOTED__).toBeUndefined();
+ expect(runRescue).toHaveBeenCalledWith(expect.objectContaining({ log: ['a log line'] }));
+ });
+
+ it('rescues when the shell itself throws before a core is resolved', () => {
+ const { runRescue } = loadMain({
+ app: packagedApp(),
+ resolveCore: () => {
+ throw new Error('loader boom');
+ },
+ });
+
+ expect(runRescue).toHaveBeenCalledWith(
+ expect.objectContaining({ error: expect.objectContaining({ message: 'loader boom' }) }),
+ );
+ });
+
+ it('falls back to the download page when the rescue module itself fails', async () => {
+ const app = packagedApp();
+ const dialog = { showErrorBox: vi.fn() };
+ const shell = { openExternal: vi.fn(() => Promise.resolve()) };
+ const core = fakeCore('rescue');
+ loadMain({
+ app,
+ electron: { dialog, shell },
+ resolveCore: () => core,
+ runRescue: () => {
+ throw new Error('rescue boom');
+ },
+ });
+
+ await vi.waitFor(() => expect(app.exit).toHaveBeenCalledWith(1));
+ expect(dialog.showErrorBox).toHaveBeenCalled();
+ expect(shell.openExternal).toHaveBeenCalledWith('https://lobehub.com/downloads');
+ });
+});
diff --git a/apps/desktop/shell/__tests__/shell-resolver.test.mjs b/apps/desktop/shell/__tests__/shell-resolver.test.mjs
new file mode 100644
index 00000000000..861b37e96e0
--- /dev/null
+++ b/apps/desktop/shell/__tests__/shell-resolver.test.mjs
@@ -0,0 +1,52 @@
+import fs from 'node:fs';
+import { createRequire } from 'node:module';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { installShellResolver } from '../core-loader.js';
+
+let tmp;
+let restore;
+
+const writePkg = (dir, name, value) => {
+ const pkgDir = path.join(dir, 'node_modules', name);
+ fs.mkdirSync(pkgDir, { recursive: true });
+ fs.writeFileSync(path.join(pkgDir, 'package.json'), JSON.stringify({ main: 'index.js', name }));
+ fs.writeFileSync(path.join(pkgDir, 'index.js'), `module.exports = ${JSON.stringify(value)};`);
+};
+
+beforeEach(() => {
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'shell-resolver-'));
+ writePkg(path.join(tmp, 'shell'), 'a', 'shell-a');
+ writePkg(path.join(tmp, 'shell'), '@scope/c', 'shell-c');
+ writePkg(tmp, 'a', 'ancestor-a');
+ writePkg(path.join(tmp, 'core'), 'b', 'core-b');
+ fs.writeFileSync(path.join(tmp, 'package.json'), JSON.stringify({ type: 'module' }));
+ fs.writeFileSync(path.join(tmp, 'core', 'package.json'), JSON.stringify({ type: 'commonjs' }));
+ fs.writeFileSync(path.join(tmp, 'core', 'entry.js'), '');
+ restore = installShellResolver(path.join(tmp, 'shell', 'node_modules'));
+});
+
+afterEach(() => {
+ restore();
+ fs.rmSync(tmp, { force: true, recursive: true });
+});
+
+describe('installShellResolver', () => {
+ it('prefers shell packages over ancestor node_modules and leaves core packages alone', () => {
+ const req = createRequire(path.join(tmp, 'core', 'entry.js'));
+ expect(req('a')).toBe('shell-a');
+ expect(req('@scope/c/index.js')).toBe('shell-c');
+ expect(req('b')).toBe('core-b');
+ expect(req('node:path')).toBe(path);
+ expect(() => req('missing')).toThrow(/Cannot find module/);
+ });
+
+ it('restores native resolution', () => {
+ restore();
+ const req = createRequire(path.join(tmp, 'core', 'entry.js'));
+ expect(req('a')).toBe('ancestor-a');
+ });
+});
diff --git a/apps/desktop/shell/core-loader.js b/apps/desktop/shell/core-loader.js
new file mode 100644
index 00000000000..1b230d3bf9c
--- /dev/null
+++ b/apps/desktop/shell/core-loader.js
@@ -0,0 +1,242 @@
+const { createHash, verify } = require('node:crypto');
+const fs = require('node:fs');
+const Module = require('node:module');
+const path = require('node:path');
+
+const MAX_BOOT_FAILURES = 3;
+const VERSION_NAME = /^[\w.+-]{1,64}$/;
+const UNSAFE_SEGMENT = /^\.\.?$/;
+const MAIN_ENTRY = 'dist/main/index.js';
+
+const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');
+
+const canonicalJson = (value) => {
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
+ if (value && typeof value === 'object') {
+ const entries = Object.keys(value)
+ .sort()
+ .map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`);
+ return `{${entries.join(',')}}`;
+ }
+ return JSON.stringify(value);
+};
+
+const verifyManifestSignature = (manifest, publicKeyPem) => {
+ const { signature, ...unsigned } = manifest;
+ try {
+ return verify(
+ null,
+ Buffer.from(canonicalJson(unsigned)),
+ publicKeyPem,
+ Buffer.from(signature, 'base64'),
+ );
+ } catch {
+ return false;
+ }
+};
+
+const readJson = (file) => {
+ try {
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
+ } catch {
+ return undefined;
+ }
+};
+
+const writeJson = (file, value) => {
+ fs.writeFileSync(`${file}.tmp`, JSON.stringify(value));
+ fs.renameSync(`${file}.tmp`, file);
+};
+
+const verifyCandidate = (dir, { abi, publicKey }) => {
+ const manifest = readJson(path.join(dir, 'manifest.json'));
+ if (!manifest) throw new Error('manifest missing or unreadable');
+ if (!verifyManifestSignature(manifest, publicKey)) throw new Error('bad signature');
+ if (manifest.shellAbi !== abi) throw new Error(`shellAbi ${manifest.shellAbi} != ${abi}`);
+ for (const entry of manifest.tree) {
+ if (
+ typeof entry.path !== 'string' ||
+ path.isAbsolute(entry.path) ||
+ entry.path.includes('\\') ||
+ entry.path.split('/').some((segment) => UNSAFE_SEGMENT.test(segment))
+ )
+ throw new Error(`unsafe tree path ${JSON.stringify(entry.path)}`);
+ }
+ if (!manifest.tree.some((entry) => entry.path === MAIN_ENTRY))
+ throw new Error(`${MAIN_ENTRY} not in tree`);
+ for (const file of manifest.tree) {
+ if (sha256(fs.readFileSync(path.join(dir, file.path))) !== file.sha256)
+ throw new Error(`hash mismatch ${file.path}`);
+ }
+ return manifest;
+};
+
+function resolveCore({ userData, builtinDir, abi, publicKey }) {
+ const otaRoot = path.join(userData, 'core-ota');
+ const bootFile = path.join(otaRoot, 'boot.json');
+ const pointerFile = path.join(otaRoot, 'pointer.json');
+ const stored = readJson(pointerFile);
+ const pointer = stored?.abi === abi ? stored : {};
+ const boot = readJson(bootFile) ?? {};
+ const blacklist = Array.isArray(pointer.blacklist) ? pointer.blacklist : [];
+ const log = [];
+ if (stored && stored !== pointer) log.push(`pointer abi ${stored.abi} != ${abi}, ignored`);
+
+ const savePointer = (patch) => {
+ Object.assign(pointer, patch);
+ try {
+ writeJson(pointerFile, {
+ abi,
+ blacklist,
+ channel: pointer.channel ?? null,
+ current: pointer.current ?? null,
+ previous: pointer.previous ?? null,
+ staged: pointer.staged ?? null,
+ });
+ } catch (error) {
+ log.push(`pointer write failed: ${error.message}`);
+ }
+ };
+
+ const builtinManifest = readJson(path.join(builtinDir, 'manifest.json')) ?? null;
+ const builtinSeq = typeof builtinManifest?.seq === 'number' ? builtinManifest.seq : null;
+ const channel = typeof pointer.channel === 'string' ? pointer.channel : builtinManifest?.channel;
+ // seq counters are per channel: a full release ships a builtin core with a seq above every
+ // published core of its own channel, so older external cores of that channel must not outlive it.
+ const rejectReason = (manifest) => {
+ if (channel && manifest.channel && manifest.channel !== channel)
+ return `channel ${manifest.channel} != ${channel}`;
+ if (
+ builtinSeq !== null &&
+ manifest.channel === builtinManifest.channel &&
+ typeof manifest.seq === 'number' &&
+ manifest.seq <= builtinSeq
+ )
+ return `seq ${manifest.seq} superseded by builtin seq ${builtinSeq}`;
+ return null;
+ };
+
+ const bootMarkers = (version) => {
+ const mark = (label, value) => () => {
+ try {
+ writeJson(bootFile, { ...value, version });
+ } catch (error) {
+ log.push(`${label} failed: ${error.message}`);
+ }
+ };
+ return {
+ markBroken: mark('markBroken', { failures: MAX_BOOT_FAILURES, healthy: false }),
+ markHealthy: mark('markHealthy', { failures: 0, healthy: true }),
+ };
+ };
+
+ const verified = new Map();
+ const loadCandidate = (version) => {
+ if (typeof version !== 'string' || !VERSION_NAME.test(version) || UNSAFE_SEGMENT.test(version))
+ throw new Error(`invalid core version name ${JSON.stringify(version)}`);
+ if (blacklist.includes(version)) throw new Error('blacklisted');
+ const dir = path.join(otaRoot, 'cores', version);
+ if (!verified.has(version)) verified.set(version, verifyCandidate(dir, { abi, publicKey }));
+ return { dir, manifest: verified.get(version) };
+ };
+ const verifies = (version) => {
+ try {
+ return Boolean(loadCandidate(version));
+ } catch {
+ return false;
+ }
+ };
+
+ if (pointer.staged) {
+ try {
+ const { manifest } = loadCandidate(pointer.staged);
+ const reason = rejectReason(manifest);
+ if (reason) {
+ log.push(`staged ${pointer.staged} ${reason}`);
+ savePointer({ staged: null });
+ } else {
+ savePointer({ current: pointer.staged, previous: pointer.current ?? null, staged: null });
+ }
+ } catch (error) {
+ log.push(`staged ${pointer.staged} rejected: ${error.message}`);
+ }
+ }
+
+ const candidates = [pointer.current, pointer.previous];
+ for (const [index, version] of candidates.entries()) {
+ if (!version) continue;
+ const failures = boot.version === version ? Number(boot.failures) || 0 : 0;
+ if (failures >= MAX_BOOT_FAILURES) {
+ log.push(`core ${version} blacklisted after ${failures} boot failures`);
+ if (!blacklist.includes(version)) blacklist.push(version);
+ const next = candidates[index + 1];
+ savePointer({ current: verifies(next) ? next : null, previous: null });
+ continue;
+ }
+ try {
+ const { dir, manifest } = loadCandidate(version);
+ const reason = rejectReason(manifest);
+ if (reason) {
+ log.push(`core ${version} ${reason}`);
+ savePointer({ current: null, previous: null });
+ break;
+ }
+ const healthy = boot.version === version && boot.healthy === true;
+ writeJson(bootFile, { failures: failures + 1, healthy, version });
+ return { dir, log, manifest, ...bootMarkers(version), source: 'external' };
+ } catch (error) {
+ log.push(`core ${version} rejected: ${error.message}`);
+ }
+ }
+
+ if (!builtinManifest) log.push(`builtin manifest missing at ${builtinDir}`);
+ const builtinKey = `builtin@${builtinManifest?.version ?? 'unknown'}`;
+ const builtinFailures = boot.version === builtinKey ? Number(boot.failures) || 0 : 0;
+ if (builtinFailures >= MAX_BOOT_FAILURES) {
+ log.push(`${builtinKey} failed ${builtinFailures} boots`);
+ return { dir: builtinDir, log, manifest: builtinManifest, source: 'rescue' };
+ }
+ try {
+ fs.mkdirSync(otaRoot, { recursive: true });
+ writeJson(bootFile, {
+ failures: builtinFailures + 1,
+ healthy: boot.version === builtinKey && boot.healthy === true,
+ version: builtinKey,
+ });
+ } catch (error) {
+ log.push(`builtin boot count failed: ${error.message}`);
+ }
+ return {
+ dir: builtinDir,
+ log,
+ manifest: builtinManifest,
+ ...bootMarkers(builtinKey),
+ source: 'builtin',
+ };
+}
+
+const packageName = (request) =>
+ request.startsWith('@') ? request.split('/').slice(0, 2).join('/') : request.split('/')[0];
+
+function installShellResolver(shellNodeModules) {
+ const original = Module._resolveFilename;
+ Module._resolveFilename = function (request, parent, isMain, options) {
+ const bare = !/^(?:\.|node:)/.test(request) && !path.isAbsolute(request);
+ if (bare && fs.existsSync(path.join(shellNodeModules, packageName(request))))
+ return original.call(this, request, parent, isMain, {
+ ...options,
+ paths: [shellNodeModules],
+ });
+ return original.apply(this, arguments);
+ };
+ return () => {
+ Module._resolveFilename = original;
+ };
+}
+
+module.exports = {
+ canonicalJson,
+ installShellResolver,
+ resolveCore,
+ verifyManifestSignature,
+};
diff --git a/apps/desktop/shell/main.js b/apps/desktop/shell/main.js
new file mode 100644
index 00000000000..a0cea7d5722
--- /dev/null
+++ b/apps/desktop/shell/main.js
@@ -0,0 +1,117 @@
+const path = require('node:path');
+const { app } = require('electron');
+
+const DOWNLOAD_URL = 'https://lobehub.com/downloads';
+
+// resolveCore counts every launch as a boot attempt; a secondary instance exits without ever
+// marking the core healthy, so it must leave before touching OTA state. Packaged only: dev
+// moves userData in pre-app-init, and the lock is keyed by that dir.
+if (app.isPackaged && !app.requestSingleInstanceLock()) {
+ console.info('[shell] Another instance is already running, exiting');
+ app.exit(0);
+ return;
+}
+
+const lastResort = (error) => {
+ console.error('[shell] rescue unavailable', error);
+ try {
+ const { dialog, shell } = require('electron');
+ app
+ .whenReady()
+ .then(() => {
+ dialog.showErrorBox(
+ 'LobeHub',
+ `LobeHub failed to start. Please download and reinstall the latest version.\n\n${DOWNLOAD_URL}`,
+ );
+ return shell.openExternal(DOWNLOAD_URL);
+ })
+ .catch(() => {})
+ .finally(() => app.exit(1));
+ } catch {
+ app.exit(1);
+ }
+};
+
+// Every path that ends without a running core lands here: the full-package updater lives in the
+// core, so without this a broken builtin core would leave the user no way to update but reinstall.
+const rescue = (error, log) => {
+ if (!app.isPackaged) throw error;
+ try {
+ require('./rescue').runRescue({ downloadUrl: DOWNLOAD_URL, error, fallback: lastResort, log });
+ } catch (rescueError) {
+ lastResort(rescueError);
+ }
+};
+
+let core;
+try {
+ const { installShellResolver, resolveCore } = require('./core-loader');
+
+ const builtinDir = app.isPackaged
+ ? path.join(process.resourcesPath, 'core')
+ : path.join(__dirname, '..');
+
+ const loadAbi = () => {
+ try {
+ return require('./abi.json');
+ } catch (error) {
+ if (app.isPackaged) throw error;
+ return { publicKey: '', shellAbi: 'dev', shellVersion: app.getVersion() };
+ }
+ };
+
+ const abi = loadAbi();
+
+ core = app.isPackaged
+ ? resolveCore({
+ abi: abi.shellAbi,
+ builtinDir,
+ publicKey: abi.publicKey,
+ userData: app.getPath('userData'),
+ })
+ : {
+ dir: builtinDir,
+ log: [],
+ manifest: null,
+ markBroken() {},
+ markHealthy() {},
+ source: 'builtin',
+ };
+
+ if (app.isPackaged) installShellResolver(path.join(__dirname, '..', 'node_modules'));
+
+ global.__SHELL__ = {
+ abi: abi.shellAbi,
+ builtinDir,
+ coreDir: core.dir,
+ log: core.log,
+ manifest: core.manifest,
+ markHealthy: core.markHealthy ?? (() => {}),
+ publicKey: abi.publicKey,
+ shellVersion: abi.shellVersion,
+ source: core.source,
+ };
+} catch (error) {
+ rescue(error, core?.log);
+ return;
+}
+
+if (core.source === 'rescue') {
+ rescue(new Error('builtin core failed to boot repeatedly'), core.log);
+ return;
+}
+
+try {
+ require(path.join(core.dir, 'dist', 'main', 'index.js'));
+} catch (error) {
+ core.markBroken();
+ // A half-evaluated core may already own ipcMain handlers and app listeners, so the next
+ // candidate gets a fresh process instead of a second require here.
+ if (core.source === 'external') {
+ console.error('[shell] external core threw during load, relaunching', error);
+ app.relaunch();
+ app.exit(1);
+ return;
+ }
+ rescue(error, core.log);
+}
diff --git a/apps/desktop/shell/rescue/electron-updater.cjs b/apps/desktop/shell/rescue/electron-updater.cjs
new file mode 100644
index 00000000000..90461254653
--- /dev/null
+++ b/apps/desktop/shell/rescue/electron-updater.cjs
@@ -0,0 +1,63 @@
+/* [email protected] generated by shell:vendor */
+"use strict";var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=e((e=>{e.fromCallback=function(e){return Object.defineProperty(function(...t){if(typeof t[t.length-1]==`function`)e.apply(this,t);else return new Promise((n,r)=>{t.push((e,t)=>e==null?n(t):r(e)),e.apply(this,t)})},"name",{value:e.name})},e.fromPromise=function(e){return Object.defineProperty(function(...t){let n=t[t.length-1];if(typeof n!=`function`)return e.apply(this,t);t.pop(),e.apply(this,t).then(e=>n(null,e),n)},"name",{value:e.name})}})),n=e(((e,t)=>{var n=require("constants"),r=process.cwd,i=null,a=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return i||=r.call(process),i};try{process.cwd()}catch{}if(typeof process.chdir==`function`){var o=process.chdir;process.chdir=function(e){i=null,o.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,o)}t.exports=s;function s(e){n.hasOwnProperty(`O_SYMLINK`)&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||r(e),e.chown=s(e.chown),e.fchown=s(e.fchown),e.lchown=s(e.lchown),e.chmod=i(e.chmod),e.fchmod=i(e.fchmod),e.lchmod=i(e.lchmod),e.chownSync=c(e.chownSync),e.fchownSync=c(e.fchownSync),e.lchownSync=c(e.lchownSync),e.chmodSync=o(e.chmodSync),e.fchmodSync=o(e.fchmodSync),e.lchmodSync=o(e.lchmodSync),e.stat=l(e.stat),e.fstat=l(e.fstat),e.lstat=l(e.lstat),e.statSync=u(e.statSync),e.fstatSync=u(e.fstatSync),e.lstatSync=u(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(e,t,n){n&&process.nextTick(n)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(e,t,n,r){r&&process.nextTick(r)},e.lchownSync=function(){}),a===`win32`&&(e.rename=typeof e.rename==`function`?(function(t){function n(n,r,i){var a=Date.now(),o=0;t(n,r,function s(c){if(c&&(c.code===`EACCES`||c.code===`EPERM`||c.code===`EBUSY`)&&Date.now()-a<6e4){setTimeout(function(){e.stat(r,function(e,a){e&&e.code===`ENOENT`?t(n,r,s):i(c)})},o),o<100&&(o+=10);return}i&&i(c)})}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.rename):e.rename),e.read=typeof e.read==`function`?(function(t){function n(n,r,i,a,o,s){var c;if(s&&typeof s==`function`){var l=0;c=function(u,d,f){if(u&&u.code===`EAGAIN`&&l<10)return l++,t.call(e,n,r,i,a,o,c);s.apply(this,arguments)}}return t.call(e,n,r,i,a,o,c)}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.read):e.read,e.readSync=typeof e.readSync==`function`?(function(t){return function(n,r,i,a,o){for(var s=0;;)try{return t.call(e,n,r,i,a,o)}catch(e){if(e.code===`EAGAIN`&&s<10){s++;continue}throw e}}})(e.readSync):e.readSync;function t(e){e.lchmod=function(t,r,i){e.open(t,n.O_WRONLY|n.O_SYMLINK,r,function(t,n){if(t){i&&i(t);return}e.fchmod(n,r,function(t){e.close(n,function(e){i&&i(t||e)})})})},e.lchmodSync=function(t,r){var i=e.openSync(t,n.O_WRONLY|n.O_SYMLINK,r),a=!0,o;try{o=e.fchmodSync(i,r),a=!1}finally{if(a)try{e.closeSync(i)}catch{}else e.closeSync(i)}return o}}function r(e){n.hasOwnProperty(`O_SYMLINK`)&&e.futimes?(e.lutimes=function(t,r,i,a){e.open(t,n.O_SYMLINK,function(t,n){if(t){a&&a(t);return}e.futimes(n,r,i,function(t){e.close(n,function(e){a&&a(t||e)})})})},e.lutimesSync=function(t,r,i){var a=e.openSync(t,n.O_SYMLINK),o,s=!0;try{o=e.futimesSync(a,r,i),s=!1}finally{if(s)try{e.closeSync(a)}catch{}else e.closeSync(a)}return o}):e.futimes&&(e.lutimes=function(e,t,n,r){r&&process.nextTick(r)},e.lutimesSync=function(){})}function i(t){return t&&function(n,r,i){return t.call(e,n,r,function(e){d(e)&&(e=null),i&&i.apply(this,arguments)})}}function o(t){return t&&function(n,r){try{return t.call(e,n,r)}catch(e){if(!d(e))throw e}}}function s(t){return t&&function(n,r,i,a){return t.call(e,n,r,i,function(e){d(e)&&(e=null),a&&a.apply(this,arguments)})}}function c(t){return t&&function(n,r,i){try{return t.call(e,n,r,i)}catch(e){if(!d(e))throw e}}}function l(t){return t&&function(n,r,i){typeof r==`function`&&(i=r,r=null);function a(e,t){t&&(t.uid<0&&(t.uid+=4294967296),t.gid<0&&(t.gid+=4294967296)),i&&i.apply(this,arguments)}return r?t.call(e,n,r,a):t.call(e,n,a)}}function u(t){return t&&function(n,r){var i=r?t.call(e,n,r):t.call(e,n);return i&&(i.uid<0&&(i.uid+=4294967296),i.gid<0&&(i.gid+=4294967296)),i}}function d(e){return!e||e.code===`ENOSYS`||(!process.getuid||process.getuid()!==0)&&(e.code===`EINVAL`||e.code===`EPERM`)}}})),r=e(((e,t)=>{var n=require("stream").Stream;t.exports=r;function r(e){return{ReadStream:t,WriteStream:r};function t(r,i){if(!(this instanceof t))return new t(r,i);n.call(this);var a=this;this.path=r,this.fd=null,this.readable=!0,this.paused=!1,this.flags=`r`,this.mode=438,this.bufferSize=64*1024,i||={};for(var o=Object.keys(i),s=0,c=o.length;s<c;s++){var l=o[s];this[l]=i[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.end===void 0)this.end=1/0;else if(typeof this.end!=`number`)throw TypeError(`end must be a Number`);if(this.start>this.end)throw Error(`start must be <= end`);this.pos=this.start}if(this.fd!==null){process.nextTick(function(){a._read()});return}e.open(this.path,this.flags,this.mode,function(e,t){if(e){a.emit(`error`,e),a.readable=!1;return}a.fd=t,a.emit(`open`,t),a._read()})}function r(t,i){if(!(this instanceof r))return new r(t,i);n.call(this),this.path=t,this.fd=null,this.writable=!0,this.flags=`w`,this.encoding=`binary`,this.mode=438,this.bytesWritten=0,i||={};for(var a=Object.keys(i),o=0,s=a.length;o<s;o++){var c=a[o];this[c]=i[c]}if(this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.start<0)throw Error(`start must be >= zero`);this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}})),i=e(((e,t)=>{t.exports=r;var n=Object.getPrototypeOf||function(e){return e.__proto__};function r(e){if(typeof e!=`object`||!e)return e;if(e instanceof Object)var t={__proto__:n(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}})),a=e(((e,t)=>{var a=require("fs"),o=n(),s=r(),c=i(),l=require("util"),u,d;typeof Symbol==`function`&&typeof Symbol.for==`function`?(u=Symbol.for(`graceful-fs.queue`),d=Symbol.for(`graceful-fs.previous`)):(u=`___graceful-fs.queue`,d=`___graceful-fs.previous`);function f(){}function p(e,t){Object.defineProperty(e,u,{get:function(){return t}})}var m=f;l.debuglog?m=l.debuglog(`gfs4`):/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&(m=function(){var e=l.format.apply(l,arguments);e=`GFS4: `+e.split(/\n/).join(`
+GFS4: `),console.error(e)}),a[u]||(p(a,global[u]||[]),a.close=(function(e){function t(t,n){return e.call(a,t,function(e){e||v(),typeof n==`function`&&n.apply(this,arguments)})}return Object.defineProperty(t,d,{value:e}),t})(a.close),a.closeSync=(function(e){function t(t){e.apply(a,arguments),v()}return Object.defineProperty(t,d,{value:e}),t})(a.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&process.on(`exit`,function(){m(a[u]),require("assert").equal(a[u].length,0)})),global[u]||p(global,a[u]),t.exports=h(c(a)),process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!a.__patched&&(t.exports=h(a),a.__patched=!0);function h(e){o(e),e.gracefulify=h,e.createReadStream=T,e.createWriteStream=E;var t=e.readFile;e.readFile=n;function n(e,n,r){return typeof n==`function`&&(r=n,n=null),i(e,n,r);function i(e,n,r,a){return t(e,n,function(t){t&&(t.code===`EMFILE`||t.code===`ENFILE`)?g([i,[e,n,r],t,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var r=e.writeFile;e.writeFile=i;function i(e,t,n,i){return typeof n==`function`&&(i=n,n=null),a(e,t,n,i);function a(e,t,n,i,o){return r(e,t,n,function(r){r&&(r.code===`EMFILE`||r.code===`ENFILE`)?g([a,[e,t,n,i],r,o||Date.now(),Date.now()]):typeof i==`function`&&i.apply(this,arguments)})}}var a=e.appendFile;a&&(e.appendFile=c);function c(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,o){return a(e,t,n,function(a){a&&(a.code===`EMFILE`||a.code===`ENFILE`)?g([i,[e,t,n,r],a,o||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var l=e.copyFile;l&&(e.copyFile=u);function u(e,t,n,r){return typeof n==`function`&&(r=n,n=0),i(e,t,n,r);function i(e,t,n,r,a){return l(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?g([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var d=e.readdir;e.readdir=p;var f=/^v[0-5]\./;function p(e,t,n){typeof t==`function`&&(n=t,t=null);var r=f.test(process.version)?function(e,t,n,r){return d(e,i(e,t,n,r))}:function(e,t,n,r){return d(e,t,i(e,t,n,r))};return r(e,t,n);function i(e,t,n,i){return function(a,o){a&&(a.code===`EMFILE`||a.code===`ENFILE`)?g([r,[e,t,n],a,i||Date.now(),Date.now()]):(o&&o.sort&&o.sort(),typeof n==`function`&&n.call(this,a,o))}}}if(process.version.substr(0,4)===`v0.8`){var m=s(e);x=m.ReadStream,C=m.WriteStream}var _=e.ReadStream;_&&(x.prototype=Object.create(_.prototype),x.prototype.open=S);var v=e.WriteStream;v&&(C.prototype=Object.create(v.prototype),C.prototype.open=w),Object.defineProperty(e,"ReadStream",{get:function(){return x},set:function(e){x=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return C},set:function(e){C=e},enumerable:!0,configurable:!0});var y=x;Object.defineProperty(e,"FileReadStream",{get:function(){return y},set:function(e){y=e},enumerable:!0,configurable:!0});var b=C;Object.defineProperty(e,"FileWriteStream",{get:function(){return b},set:function(e){b=e},enumerable:!0,configurable:!0});function x(e,t){return this instanceof x?(_.apply(this,arguments),this):x.apply(Object.create(x.prototype),arguments)}function S(){var e=this;O(e.path,e.flags,e.mode,function(t,n){t?(e.autoClose&&e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n),e.read())})}function C(e,t){return this instanceof C?(v.apply(this,arguments),this):C.apply(Object.create(C.prototype),arguments)}function w(){var e=this;O(e.path,e.flags,e.mode,function(t,n){t?(e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n))})}function T(t,n){return new e.ReadStream(t,n)}function E(t,n){return new e.WriteStream(t,n)}var D=e.open;e.open=O;function O(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return D(e,t,n,function(o,s){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?g([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}return e}function g(e){m(`ENQUEUE`,e[0].name,e[1]),a[u].push(e),y()}var _;function v(){for(var e=Date.now(),t=0;t<a[u].length;++t)a[u][t].length>2&&(a[u][t][3]=e,a[u][t][4]=e);y()}function y(){if(clearTimeout(_),_=void 0,a[u].length!==0){var e=a[u].shift(),t=e[0],n=e[1],r=e[2],i=e[3],o=e[4];if(i===void 0)m(`RETRY`,t.name,n),t.apply(null,n);else if(Date.now()-i>=6e4){m(`TIMEOUT`,t.name,n);var s=n.pop();typeof s==`function`&&s.call(null,r)}else{var c=Date.now()-o,l=Math.max(o-i,1);c>=Math.min(l*1.2,100)?(m(`RETRY`,t.name,n),t.apply(null,n.concat([i]))):a[u].push(e)}_===void 0&&(_=setTimeout(y,0))}}})),o=e((e=>{var n=t().fromCallback,r=a(),i=`access.appendFile.chmod.chown.close.copyFile.fchmod.fchown.fdatasync.fstat.fsync.ftruncate.futimes.lchmod.lchown.link.lstat.mkdir.mkdtemp.open.opendir.readdir.readFile.readlink.realpath.rename.rm.rmdir.stat.symlink.truncate.unlink.utimes.writeFile`.split(`.`).filter(e=>typeof r[e]==`function`);Object.assign(e,r),i.forEach(t=>{e[t]=n(r[t])}),e.exists=function(e,t){return typeof t==`function`?r.exists(e,t):new Promise(t=>r.exists(e,t))},e.read=function(e,t,n,i,a,o){return typeof o==`function`?r.read(e,t,n,i,a,o):new Promise((o,s)=>{r.read(e,t,n,i,a,(e,t,n)=>{if(e)return s(e);o({bytesRead:t,buffer:n})})})},e.write=function(e,t,...n){return typeof n[n.length-1]==`function`?r.write(e,t,...n):new Promise((i,a)=>{r.write(e,t,...n,(e,t,n)=>{if(e)return a(e);i({bytesWritten:t,buffer:n})})})},typeof r.writev==`function`&&(e.writev=function(e,t,...n){return typeof n[n.length-1]==`function`?r.writev(e,t,...n):new Promise((i,a)=>{r.writev(e,t,...n,(e,t,n)=>{if(e)return a(e);i({bytesWritten:t,buffers:n})})})}),typeof r.realpath.native==`function`?e.realpath.native=n(r.realpath.native):process.emitWarning(`fs.realpath.native is not a function. Is fs being monkey-patched?`,`Warning`,`fs-extra-WARN0003`)})),s=e(((e,t)=>{var n=require("path");t.exports.checkPath=function(e){if(process.platform===`win32`&&/[<>:"|?*]/.test(e.replace(n.parse(e).root,``))){let t=Error(`Path contains invalid characters: ${e}`);throw t.code=`EINVAL`,t}}})),c=e(((e,t)=>{var n=o(),{checkPath:r}=s(),i=e=>typeof e==`number`?e:{mode:511,...e}.mode;t.exports.makeDir=async(e,t)=>(r(e),n.mkdir(e,{mode:i(t),recursive:!0})),t.exports.makeDirSync=(e,t)=>(r(e),n.mkdirSync(e,{mode:i(t),recursive:!0}))})),l=e(((e,n)=>{var r=t().fromPromise,{makeDir:i,makeDirSync:a}=c(),o=r(i);n.exports={mkdirs:o,mkdirsSync:a,mkdirp:o,mkdirpSync:a,ensureDir:o,ensureDirSync:a}})),u=e(((e,n)=>{var r=t().fromPromise,i=o();function a(e){return i.access(e).then(()=>!0).catch(()=>!1)}n.exports={pathExists:r(a),pathExistsSync:i.existsSync}})),d=e(((e,t)=>{var n=a();function r(e,t,r,i){n.open(e,`r+`,(e,a)=>{if(e)return i(e);n.futimes(a,t,r,e=>{n.close(a,t=>{i&&i(e||t)})})})}function i(e,t,r){let i=n.openSync(e,`r+`);return n.futimesSync(i,t,r),n.closeSync(i)}t.exports={utimesMillis:r,utimesMillisSync:i}})),f=e(((e,t)=>{var n=o(),r=require("path"),i=require("util");function a(e,t,r){let i=r.dereference?e=>n.stat(e,{bigint:!0}):e=>n.lstat(e,{bigint:!0});return Promise.all([i(e),i(t).catch(e=>{if(e.code===`ENOENT`)return null;throw e})]).then(([e,t])=>({srcStat:e,destStat:t}))}function s(e,t,r){let i,a=r.dereference?e=>n.statSync(e,{bigint:!0}):e=>n.lstatSync(e,{bigint:!0}),o=a(e);try{i=a(t)}catch(e){if(e.code===`ENOENT`)return{srcStat:o,destStat:null};throw e}return{srcStat:o,destStat:i}}function c(e,t,n,o,s){i.callbackify(a)(e,t,o,(i,a)=>{if(i)return s(i);let{srcStat:o,destStat:c}=a;if(c){if(f(o,c)){let i=r.basename(e),a=r.basename(t);return n===`move`&&i!==a&&i.toLowerCase()===a.toLowerCase()?s(null,{srcStat:o,destStat:c,isChangingCase:!0}):s(Error(`Source and destination must not be the same.`))}if(o.isDirectory()&&!c.isDirectory())return s(Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`));if(!o.isDirectory()&&c.isDirectory())return s(Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`))}return o.isDirectory()&&p(e,t)?s(Error(m(e,t,n))):s(null,{srcStat:o,destStat:c})})}function l(e,t,n,i){let{srcStat:a,destStat:o}=s(e,t,i);if(o){if(f(a,o)){let i=r.basename(e),s=r.basename(t);if(n===`move`&&i!==s&&i.toLowerCase()===s.toLowerCase())return{srcStat:a,destStat:o,isChangingCase:!0};throw Error(`Source and destination must not be the same.`)}if(a.isDirectory()&&!o.isDirectory())throw Error(`Cannot overwrite non-directory '${t}' with directory '${e}'.`);if(!a.isDirectory()&&o.isDirectory())throw Error(`Cannot overwrite directory '${t}' with non-directory '${e}'.`)}if(a.isDirectory()&&p(e,t))throw Error(m(e,t,n));return{srcStat:a,destStat:o}}function u(e,t,i,a,o){let s=r.resolve(r.dirname(e)),c=r.resolve(r.dirname(i));if(c===s||c===r.parse(c).root)return o();n.stat(c,{bigint:!0},(n,r)=>n?n.code===`ENOENT`?o():o(n):f(t,r)?o(Error(m(e,i,a))):u(e,t,c,a,o))}function d(e,t,i,a){let o=r.resolve(r.dirname(e)),s=r.resolve(r.dirname(i));if(s===o||s===r.parse(s).root)return;let c;try{c=n.statSync(s,{bigint:!0})}catch(e){if(e.code===`ENOENT`)return;throw e}if(f(t,c))throw Error(m(e,i,a));return d(e,t,s,a)}function f(e,t){return t.ino&&t.dev&&t.ino===e.ino&&t.dev===e.dev}function p(e,t){let n=r.resolve(e).split(r.sep).filter(e=>e),i=r.resolve(t).split(r.sep).filter(e=>e);return n.reduce((e,t,n)=>e&&i[n]===t,!0)}function m(e,t,n){return`Cannot ${n} '${e}' to a subdirectory of itself, '${t}'.`}t.exports={checkPaths:c,checkPathsSync:l,checkParentPaths:u,checkParentPathsSync:d,isSrcSubdir:p,areIdentical:f}})),p=e(((e,t)=>{var n=a(),r=require("path"),i=l().mkdirs,o=u().pathExists,s=d().utimesMillis,c=f();function p(e,t,n,r){typeof n==`function`&&!r?(r=n,n={}):typeof n==`function`&&(n={filter:n}),r||=function(){},n||={},n.clobber=`clobber`in n?!!n.clobber:!0,n.overwrite=`overwrite`in n?!!n.overwrite:n.clobber,n.preserveTimestamps&&process.arch===`ia32`&&process.emitWarning(`Using the preserveTimestamps option in 32-bit node is not recommended;
+
+ see https://github.com/jprichardson/node-fs-extra/issues/269`,`Warning`,`fs-extra-WARN0001`),c.checkPaths(e,t,`copy`,n,(i,a)=>{if(i)return r(i);let{srcStat:o,destStat:s}=a;c.checkParentPaths(e,o,t,`copy`,i=>i?r(i):n.filter?h(m,s,e,t,n,r):m(s,e,t,n,r))})}function m(e,t,n,a,s){let c=r.dirname(n);o(c,(r,o)=>{if(r)return s(r);if(o)return _(e,t,n,a,s);i(c,r=>r?s(r):_(e,t,n,a,s))})}function h(e,t,n,r,i,a){Promise.resolve(i.filter(n,r)).then(o=>o?e(t,n,r,i,a):a(),e=>a(e))}function g(e,t,n,r,i){return r.filter?h(_,e,t,n,r,i):_(e,t,n,r,i)}function _(e,t,r,i,a){(i.dereference?n.stat:n.lstat)(t,(n,o)=>n?a(n):o.isDirectory()?D(o,e,t,r,i,a):o.isFile()||o.isCharacterDevice()||o.isBlockDevice()?v(o,e,t,r,i,a):o.isSymbolicLink()?j(e,t,r,i,a):o.isSocket()?a(Error(`Cannot copy a socket file: ${t}`)):o.isFIFO()?a(Error(`Cannot copy a FIFO pipe: ${t}`)):a(Error(`Unknown file: ${t}`)))}function v(e,t,n,r,i,a){return t?y(e,n,r,i,a):b(e,n,r,i,a)}function y(e,t,r,i,a){if(i.overwrite)n.unlink(r,n=>n?a(n):b(e,t,r,i,a));else if(i.errorOnExist)return a(Error(`'${r}' already exists`));else return a()}function b(e,t,r,i,a){n.copyFile(t,r,n=>n?a(n):i.preserveTimestamps?x(e.mode,t,r,a):T(r,e.mode,a))}function x(e,t,n,r){return S(e)?C(n,e,i=>i?r(i):w(e,t,n,r)):w(e,t,n,r)}function S(e){return(e&128)==0}function C(e,t,n){return T(e,t|128,n)}function w(e,t,n,r){E(t,n,t=>t?r(t):T(n,e,r))}function T(e,t,r){return n.chmod(e,t,r)}function E(e,t,r){n.stat(e,(e,n)=>e?r(e):s(t,n.atime,n.mtime,r))}function D(e,t,n,r,i,a){return t?k(n,r,i,a):O(e.mode,n,r,i,a)}function O(e,t,r,i,a){n.mkdir(r,n=>{if(n)return a(n);k(t,r,i,t=>t?a(t):T(r,e,a))})}function k(e,t,r,i){n.readdir(e,(n,a)=>n?i(n):A(a,e,t,r,i))}function A(e,t,n,r,i){let a=e.pop();return a?ee(e,a,t,n,r,i):i()}function ee(e,t,n,i,a,o){let s=r.join(n,t),l=r.join(i,t);c.checkPaths(s,l,`copy`,a,(t,r)=>{if(t)return o(t);let{destStat:c}=r;g(c,s,l,a,t=>t?o(t):A(e,n,i,a,o))})}function j(e,t,i,a,o){n.readlink(t,(t,s)=>{if(t)return o(t);if(a.dereference&&(s=r.resolve(process.cwd(),s)),e)n.readlink(i,(t,l)=>t?t.code===`EINVAL`||t.code===`UNKNOWN`?n.symlink(s,i,o):o(t):(a.dereference&&(l=r.resolve(process.cwd(),l)),c.isSrcSubdir(s,l)?o(Error(`Cannot copy '${s}' to a subdirectory of itself, '${l}'.`)):e.isDirectory()&&c.isSrcSubdir(l,s)?o(Error(`Cannot overwrite '${l}' with '${s}'.`)):M(s,i,o)));else return n.symlink(s,i,o)})}function M(e,t,r){n.unlink(t,i=>i?r(i):n.symlink(e,t,r))}t.exports=p})),m=e(((e,t)=>{var n=a(),r=require("path"),i=l().mkdirsSync,o=d().utimesMillisSync,s=f();function c(e,t,n){typeof n==`function`&&(n={filter:n}),n||={},n.clobber=`clobber`in n?!!n.clobber:!0,n.overwrite=`overwrite`in n?!!n.overwrite:n.clobber,n.preserveTimestamps&&process.arch===`ia32`&&process.emitWarning(`Using the preserveTimestamps option in 32-bit node is not recommended;
+
+ see https://github.com/jprichardson/node-fs-extra/issues/269`,`Warning`,`fs-extra-WARN0002`);let{srcStat:r,destStat:i}=s.checkPathsSync(e,t,`copy`,n);return s.checkParentPathsSync(e,r,t,`copy`),u(i,e,t,n)}function u(e,t,a,o){if(o.filter&&!o.filter(t,a))return;let s=r.dirname(a);return n.existsSync(s)||i(s),m(e,t,a,o)}function p(e,t,n,r){if(!(r.filter&&!r.filter(t,n)))return m(e,t,n,r)}function m(e,t,r,i){let a=(i.dereference?n.statSync:n.lstatSync)(t);if(a.isDirectory())return C(a,e,t,r,i);if(a.isFile()||a.isCharacterDevice()||a.isBlockDevice())return h(a,e,t,r,i);if(a.isSymbolicLink())return D(e,t,r,i);throw a.isSocket()?Error(`Cannot copy a socket file: ${t}`):a.isFIFO()?Error(`Cannot copy a FIFO pipe: ${t}`):Error(`Unknown file: ${t}`)}function h(e,t,n,r,i){return t?g(e,n,r,i):_(e,n,r,i)}function g(e,t,r,i){if(i.overwrite)return n.unlinkSync(r),_(e,t,r,i);if(i.errorOnExist)throw Error(`'${r}' already exists`)}function _(e,t,r,i){return n.copyFileSync(t,r),i.preserveTimestamps&&v(e.mode,t,r),x(r,e.mode)}function v(e,t,n){return y(e)&&b(n,e),S(t,n)}function y(e){return(e&128)==0}function b(e,t){return x(e,t|128)}function x(e,t){return n.chmodSync(e,t)}function S(e,t){let r=n.statSync(e);return o(t,r.atime,r.mtime)}function C(e,t,n,r,i){return t?T(n,r,i):w(e.mode,n,r,i)}function w(e,t,r,i){return n.mkdirSync(r),T(t,r,i),x(r,e)}function T(e,t,r){n.readdirSync(e).forEach(n=>E(n,e,t,r))}function E(e,t,n,i){let a=r.join(t,e),o=r.join(n,e),{destStat:c}=s.checkPathsSync(a,o,`copy`,i);return p(c,a,o,i)}function D(e,t,i,a){let o=n.readlinkSync(t);if(a.dereference&&(o=r.resolve(process.cwd(),o)),e){let e;try{e=n.readlinkSync(i)}catch(e){if(e.code===`EINVAL`||e.code===`UNKNOWN`)return n.symlinkSync(o,i);throw e}if(a.dereference&&(e=r.resolve(process.cwd(),e)),s.isSrcSubdir(o,e))throw Error(`Cannot copy '${o}' to a subdirectory of itself, '${e}'.`);if(n.statSync(i).isDirectory()&&s.isSrcSubdir(e,o))throw Error(`Cannot overwrite '${e}' with '${o}'.`);return O(o,i)}else return n.symlinkSync(o,i)}function O(e,t){return n.unlinkSync(t),n.symlinkSync(e,t)}t.exports=c})),h=e(((e,n)=>{var r=t().fromCallback;n.exports={copy:r(p()),copySync:m()}})),g=e(((e,t)=>{var n=a(),r=require("path"),i=require("assert"),o=process.platform===`win32`;function s(e){[`unlink`,`chmod`,`stat`,`lstat`,`rmdir`,`readdir`].forEach(t=>{e[t]=e[t]||n[t],t+=`Sync`,e[t]=e[t]||n[t]}),e.maxBusyTries=e.maxBusyTries||3}function c(e,t,n){let r=0;typeof t==`function`&&(n=t,t={}),i(e,`rimraf: missing path`),i.strictEqual(typeof e,`string`,`rimraf: path should be a string`),i.strictEqual(typeof n,`function`,`rimraf: callback function required`),i(t,`rimraf: invalid options argument provided`),i.strictEqual(typeof t,`object`,`rimraf: options should be object`),s(t),l(e,t,function i(a){if(a){if((a.code===`EBUSY`||a.code===`ENOTEMPTY`||a.code===`EPERM`)&&r<t.maxBusyTries){r++;let n=r*100;return setTimeout(()=>l(e,t,i),n)}a.code===`ENOENT`&&(a=null)}n(a)})}function l(e,t,n){i(e),i(t),i(typeof n==`function`),t.lstat(e,(r,i)=>{if(r&&r.code===`ENOENT`)return n(null);if(r&&r.code===`EPERM`&&o)return u(e,t,r,n);if(i&&i.isDirectory())return f(e,t,r,n);t.unlink(e,r=>{if(r){if(r.code===`ENOENT`)return n(null);if(r.code===`EPERM`)return o?u(e,t,r,n):f(e,t,r,n);if(r.code===`EISDIR`)return f(e,t,r,n)}return n(r)})})}function u(e,t,n,r){i(e),i(t),i(typeof r==`function`),t.chmod(e,438,i=>{i?r(i.code===`ENOENT`?null:n):t.stat(e,(i,a)=>{i?r(i.code===`ENOENT`?null:n):a.isDirectory()?f(e,t,n,r):t.unlink(e,r)})})}function d(e,t,n){let r;i(e),i(t);try{t.chmodSync(e,438)}catch(e){if(e.code===`ENOENT`)return;throw n}try{r=t.statSync(e)}catch(e){if(e.code===`ENOENT`)return;throw n}r.isDirectory()?h(e,t,n):t.unlinkSync(e)}function f(e,t,n,r){i(e),i(t),i(typeof r==`function`),t.rmdir(e,i=>{i&&(i.code===`ENOTEMPTY`||i.code===`EEXIST`||i.code===`EPERM`)?p(e,t,r):i&&i.code===`ENOTDIR`?r(n):r(i)})}function p(e,t,n){i(e),i(t),i(typeof n==`function`),t.readdir(e,(i,a)=>{if(i)return n(i);let o=a.length,s;if(o===0)return t.rmdir(e,n);a.forEach(i=>{c(r.join(e,i),t,r=>{if(!s){if(r)return n(s=r);--o===0&&t.rmdir(e,n)}})})})}function m(e,t){let n;t||={},s(t),i(e,`rimraf: missing path`),i.strictEqual(typeof e,`string`,`rimraf: path should be a string`),i(t,`rimraf: missing options`),i.strictEqual(typeof t,`object`,`rimraf: options should be object`);try{n=t.lstatSync(e)}catch(n){if(n.code===`ENOENT`)return;n.code===`EPERM`&&o&&d(e,t,n)}try{n&&n.isDirectory()?h(e,t,null):t.unlinkSync(e)}catch(n){if(n.code===`ENOENT`)return;if(n.code===`EPERM`)return o?d(e,t,n):h(e,t,n);if(n.code!==`EISDIR`)throw n;h(e,t,n)}}function h(e,t,n){i(e),i(t);try{t.rmdirSync(e)}catch(r){if(r.code===`ENOTDIR`)throw n;if(r.code===`ENOTEMPTY`||r.code===`EEXIST`||r.code===`EPERM`)g(e,t);else if(r.code!==`ENOENT`)throw r}}function g(e,t){if(i(e),i(t),t.readdirSync(e).forEach(n=>m(r.join(e,n),t)),o){let n=Date.now();do try{return t.rmdirSync(e,t)}catch{}while(Date.now()-n<500)}else return t.rmdirSync(e,t)}t.exports=c,c.sync=m})),_=e(((e,n)=>{var r=a(),i=t().fromCallback,o=g();function s(e,t){if(r.rm)return r.rm(e,{recursive:!0,force:!0},t);o(e,t)}function c(e){if(r.rmSync)return r.rmSync(e,{recursive:!0,force:!0});o.sync(e)}n.exports={remove:i(s),removeSync:c}})),v=e(((e,n)=>{var r=t().fromPromise,i=o(),a=require("path"),s=l(),c=_(),u=r(async function(e){let t;try{t=await i.readdir(e)}catch{return s.mkdirs(e)}return Promise.all(t.map(t=>c.remove(a.join(e,t))))});function d(e){let t;try{t=i.readdirSync(e)}catch{return s.mkdirsSync(e)}t.forEach(t=>{t=a.join(e,t),c.removeSync(t)})}n.exports={emptyDirSync:d,emptydirSync:d,emptyDir:u,emptydir:u}})),y=e(((e,n)=>{var r=t().fromCallback,i=require("path"),o=a(),s=l();function c(e,t){function n(){o.writeFile(e,``,e=>{if(e)return t(e);t()})}o.stat(e,(r,a)=>{if(!r&&a.isFile())return t();let c=i.dirname(e);o.stat(c,(e,r)=>{if(e)return e.code===`ENOENT`?s.mkdirs(c,e=>{if(e)return t(e);n()}):t(e);r.isDirectory()?n():o.readdir(c,e=>{if(e)return t(e)})})})}function u(e){let t;try{t=o.statSync(e)}catch{}if(t&&t.isFile())return;let n=i.dirname(e);try{o.statSync(n).isDirectory()||o.readdirSync(n)}catch(e){if(e&&e.code===`ENOENT`)s.mkdirsSync(n);else throw e}o.writeFileSync(e,``)}n.exports={createFile:r(c),createFileSync:u}})),b=e(((e,n)=>{var r=t().fromCallback,i=require("path"),o=a(),s=l(),c=u().pathExists,{areIdentical:d}=f();function p(e,t,n){function r(e,t){o.link(e,t,e=>{if(e)return n(e);n(null)})}o.lstat(t,(a,l)=>{o.lstat(e,(a,o)=>{if(a)return a.message=a.message.replace(`lstat`,`ensureLink`),n(a);if(l&&d(o,l))return n(null);let u=i.dirname(t);c(u,(i,a)=>{if(i)return n(i);if(a)return r(e,t);s.mkdirs(u,i=>{if(i)return n(i);r(e,t)})})})})}function m(e,t){let n;try{n=o.lstatSync(t)}catch{}try{let t=o.lstatSync(e);if(n&&d(t,n))return}catch(e){throw e.message=e.message.replace(`lstat`,`ensureLink`),e}let r=i.dirname(t);return o.existsSync(r)||s.mkdirsSync(r),o.linkSync(e,t)}n.exports={createLink:r(p),createLinkSync:m}})),x=e(((e,t)=>{var n=require("path"),r=a(),i=u().pathExists;function o(e,t,a){if(n.isAbsolute(e))return r.lstat(e,t=>t?(t.message=t.message.replace(`lstat`,`ensureSymlink`),a(t)):a(null,{toCwd:e,toDst:e}));{let o=n.dirname(t),s=n.join(o,e);return i(s,(t,i)=>t?a(t):i?a(null,{toCwd:s,toDst:e}):r.lstat(e,t=>t?(t.message=t.message.replace(`lstat`,`ensureSymlink`),a(t)):a(null,{toCwd:e,toDst:n.relative(o,e)})))}}function s(e,t){let i;if(n.isAbsolute(e)){if(i=r.existsSync(e),!i)throw Error(`absolute srcpath does not exist`);return{toCwd:e,toDst:e}}else{let a=n.dirname(t),o=n.join(a,e);if(i=r.existsSync(o),i)return{toCwd:o,toDst:e};if(i=r.existsSync(e),!i)throw Error(`relative srcpath does not exist`);return{toCwd:e,toDst:n.relative(a,e)}}}t.exports={symlinkPaths:o,symlinkPathsSync:s}})),S=e(((e,t)=>{var n=a();function r(e,t,r){if(r=typeof t==`function`?t:r,t=typeof t==`function`?!1:t,t)return r(null,t);n.lstat(e,(e,n)=>{if(e)return r(null,`file`);t=n&&n.isDirectory()?`dir`:`file`,r(null,t)})}function i(e,t){let r;if(t)return t;try{r=n.lstatSync(e)}catch{return`file`}return r&&r.isDirectory()?`dir`:`file`}t.exports={symlinkType:r,symlinkTypeSync:i}})),C=e(((e,n)=>{var r=t().fromCallback,i=require("path"),a=o(),s=l(),c=s.mkdirs,d=s.mkdirsSync,p=x(),m=p.symlinkPaths,h=p.symlinkPathsSync,g=S(),_=g.symlinkType,v=g.symlinkTypeSync,y=u().pathExists,{areIdentical:b}=f();function C(e,t,n,r){r=typeof n==`function`?n:r,n=typeof n==`function`?!1:n,a.lstat(t,(i,o)=>{!i&&o.isSymbolicLink()?Promise.all([a.stat(e),a.stat(t)]).then(([i,a])=>{if(b(i,a))return r(null);w(e,t,n,r)}):w(e,t,n,r)})}function w(e,t,n,r){m(e,t,(o,s)=>{if(o)return r(o);e=s.toDst,_(s.toCwd,n,(n,o)=>{if(n)return r(n);let s=i.dirname(t);y(s,(n,i)=>{if(n)return r(n);if(i)return a.symlink(e,t,o,r);c(s,n=>{if(n)return r(n);a.symlink(e,t,o,r)})})})})}function T(e,t,n){let r;try{r=a.lstatSync(t)}catch{}if(r&&r.isSymbolicLink()&&b(a.statSync(e),a.statSync(t)))return;let o=h(e,t);e=o.toDst,n=v(o.toCwd,n);let s=i.dirname(t);return a.existsSync(s)||d(s),a.symlinkSync(e,t,n)}n.exports={createSymlink:r(C),createSymlinkSync:T}})),w=e(((e,t)=>{var{createFile:n,createFileSync:r}=y(),{createLink:i,createLinkSync:a}=b(),{createSymlink:o,createSymlinkSync:s}=C();t.exports={createFile:n,createFileSync:r,ensureFile:n,ensureFileSync:r,createLink:i,createLinkSync:a,ensureLink:i,ensureLinkSync:a,createSymlink:o,createSymlinkSync:s,ensureSymlink:o,ensureSymlinkSync:s}})),T=e(((e,t)=>{function n(e,{EOL:t=`
+`,finalEOL:n=!0,replacer:r=null,spaces:i}={}){let a=n?t:``,o=JSON.stringify(e,r,i);if(o===void 0)throw TypeError(`Converting ${typeof e} value to JSON is not supported`);return o.replace(/\n/g,t)+a}function r(e){return Buffer.isBuffer(e)&&(e=e.toString(`utf8`)),e.replace(/^\uFEFF/,``)}t.exports={stringify:n,stripBom:r}})),E=e(((e,n)=>{var r;try{r=a()}catch{r=require("fs")}var i=t(),{stringify:o,stripBom:s}=T();async function c(e,t={}){typeof t==`string`&&(t={encoding:t});let n=t.fs||r,a=`throws`in t?t.throws:!0,o=await i.fromCallback(n.readFile)(e,t);o=s(o);let c;try{c=JSON.parse(o,t?t.reviver:null)}catch(t){if(a)throw t.message=`${e}: ${t.message}`,t;return null}return c}var l=i.fromPromise(c);function u(e,t={}){typeof t==`string`&&(t={encoding:t});let n=t.fs||r,i=`throws`in t?t.throws:!0;try{let r=n.readFileSync(e,t);return r=s(r),JSON.parse(r,t.reviver)}catch(t){if(i)throw t.message=`${e}: ${t.message}`,t;return null}}async function d(e,t,n={}){let a=n.fs||r,s=o(t,n);await i.fromCallback(a.writeFile)(e,s,n)}var f=i.fromPromise(d);function p(e,t,n={}){let i=n.fs||r,a=o(t,n);return i.writeFileSync(e,a,n)}n.exports={readFile:l,readFileSync:u,writeFile:f,writeFileSync:p}})),D=e(((e,t)=>{var n=E();t.exports={readJson:n.readFile,readJsonSync:n.readFileSync,writeJson:n.writeFile,writeJsonSync:n.writeFileSync}})),O=e(((e,n)=>{var r=t().fromCallback,i=a(),o=require("path"),s=l(),c=u().pathExists;function d(e,t,n,r){typeof n==`function`&&(r=n,n=`utf8`);let a=o.dirname(e);c(a,(o,c)=>{if(o)return r(o);if(c)return i.writeFile(e,t,n,r);s.mkdirs(a,a=>{if(a)return r(a);i.writeFile(e,t,n,r)})})}function f(e,...t){let n=o.dirname(e);if(i.existsSync(n))return i.writeFileSync(e,...t);s.mkdirsSync(n),i.writeFileSync(e,...t)}n.exports={outputFile:r(d),outputFileSync:f}})),k=e(((e,t)=>{var{stringify:n}=T(),{outputFile:r}=O();async function i(e,t,i={}){await r(e,n(t,i),i)}t.exports=i})),A=e(((e,t)=>{var{stringify:n}=T(),{outputFileSync:r}=O();function i(e,t,i){r(e,n(t,i),i)}t.exports=i})),ee=e(((e,n)=>{var r=t().fromPromise,i=D();i.outputJson=r(k()),i.outputJsonSync=A(),i.outputJSON=i.outputJson,i.outputJSONSync=i.outputJsonSync,i.writeJSON=i.writeJson,i.writeJSONSync=i.writeJsonSync,i.readJSON=i.readJson,i.readJSONSync=i.readJsonSync,n.exports=i})),j=e(((e,t)=>{var n=a(),r=require("path"),i=h().copy,o=_().remove,s=l().mkdirp,c=u().pathExists,d=f();function p(e,t,n,i){typeof n==`function`&&(i=n,n={}),n||={};let a=n.overwrite||n.clobber||!1;d.checkPaths(e,t,`move`,n,(n,o)=>{if(n)return i(n);let{srcStat:c,isChangingCase:l=!1}=o;d.checkParentPaths(e,c,t,`move`,n=>{if(n)return i(n);if(m(t))return g(e,t,a,l,i);s(r.dirname(t),n=>n?i(n):g(e,t,a,l,i))})})}function m(e){let t=r.dirname(e);return r.parse(t).root===t}function g(e,t,n,r,i){if(r)return v(e,t,n,i);if(n)return o(t,r=>r?i(r):v(e,t,n,i));c(t,(r,a)=>r?i(r):a?i(Error(`dest already exists.`)):v(e,t,n,i))}function v(e,t,r,i){n.rename(e,t,n=>n?n.code===`EXDEV`?y(e,t,r,i):i(n):i())}function y(e,t,n,r){i(e,t,{overwrite:n,errorOnExist:!0},t=>t?r(t):o(e,r))}t.exports=p})),M=e(((e,t)=>{var n=a(),r=require("path"),i=h().copySync,o=_().removeSync,s=l().mkdirpSync,c=f();function u(e,t,n){n||={};let i=n.overwrite||n.clobber||!1,{srcStat:a,isChangingCase:o=!1}=c.checkPathsSync(e,t,`move`,n);return c.checkParentPathsSync(e,a,t,`move`),d(t)||s(r.dirname(t)),p(e,t,i,o)}function d(e){let t=r.dirname(e);return r.parse(t).root===t}function p(e,t,r,i){if(i)return m(e,t,r);if(r)return o(t),m(e,t,r);if(n.existsSync(t))throw Error(`dest already exists.`);return m(e,t,r)}function m(e,t,r){try{n.renameSync(e,t)}catch(n){if(n.code!==`EXDEV`)throw n;return g(e,t,r)}}function g(e,t,n){return i(e,t,{overwrite:n,errorOnExist:!0}),o(e)}t.exports=u})),N=e(((e,n)=>{var r=t().fromCallback;n.exports={move:r(j()),moveSync:M()}})),P=e(((e,t)=>{t.exports={...o(),...h(),...v(),...w(),...ee(),...l(),...N(),...O(),...u(),..._()}})),F=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CancellationError=e.CancellationToken=void 0;var t=require("events");e.CancellationToken=class extends t.EventEmitter{get cancelled(){return this._cancelled||this._parent!=null&&this._parent.cancelled}set parent(e){this.removeParentCancelHandler(),this._parent=e,this.parentCancelHandler=()=>this.cancel(),this._parent.onCancel(this.parentCancelHandler)}constructor(e){super(),this.parentCancelHandler=null,this._parent=null,this._cancelled=!1,e!=null&&(this.parent=e)}cancel(){this._cancelled=!0,this.emit(`cancel`)}onCancel(e){this.cancelled?e():this.once(`cancel`,e)}createPromise(e){if(this.cancelled)return Promise.reject(new n);let t=()=>{if(r!=null)try{this.removeListener(`cancel`,r),r=null}catch{}},r=null;return new Promise((t,i)=>{let a=null;if(r=()=>{try{a!=null&&(a(),a=null)}finally{i(new n)}},this.cancelled){r();return}this.onCancel(r),e(t,i,e=>{a=e})}).then(e=>(t(),e)).catch(e=>{throw t(),e})}removeParentCancelHandler(){let e=this._parent;e!=null&&this.parentCancelHandler!=null&&(e.removeListener(`cancel`,this.parentCancelHandler),this.parentCancelHandler=null)}dispose(){try{this.removeParentCancelHandler()}finally{this.removeAllListeners(),this._parent=null}}};var n=class extends Error{constructor(){super(`cancelled`)}};e.CancellationError=n})),I=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.newError=t;function t(e,t){let n=Error(e);return n.code=t,n}})),te=e(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),ne=e(((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=te(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})),re=e(((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function n(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=ne()(e);var{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),L=e(((e,t)=>{t.exports=(e,t=process.argv)=>{let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}})),ie=e(((e,t)=>{var n=require("os"),r=require("tty"),i=L(),{env:a}=process,o;i(`no-color`)||i(`no-colors`)||i(`color=false`)||i(`color=never`)?o=0:(i(`color`)||i(`colors`)||i(`color=true`)||i(`color=always`))&&(o=1),`FORCE_COLOR`in a&&(o=a.FORCE_COLOR===`true`?1:a.FORCE_COLOR===`false`?0:a.FORCE_COLOR.length===0?1:Math.min(parseInt(a.FORCE_COLOR,10),3));function s(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function c(e,t){if(o===0)return 0;if(i(`color=16m`)||i(`color=full`)||i(`color=truecolor`))return 3;if(i(`color=256`))return 2;if(e&&!t&&o===void 0)return 0;let r=o||0;if(a.TERM===`dumb`)return r;if(process.platform===`win32`){let e=n.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in a)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`].some(e=>e in a)||a.CI_NAME===`codeship`?1:r;if(`TEAMCITY_VERSION`in a)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(a.TEAMCITY_VERSION);if(a.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in a){let e=parseInt((a.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(a.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(a.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(a.TERM)||`COLORTERM`in a?1:r}function l(e){return s(c(e,e&&e.isTTY))}t.exports={supportsColor:l,stdout:s(c(!0,r.isatty(1))),stderr:s(c(!0,r.isatty(2)))}})),R=e(((e,t)=>{var n=require("tty"),r=require("util");e.init=u,e.log=s,e.formatArgs=a,e.save=c,e.load=l,e.useColors=i,e.destroy=r.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{let t=ie();t&&(t.stderr||t).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),r=process.env[t];return r=/^(yes|on|true|enabled)$/i.test(r)?!0:/^(no|off|false|disabled)$/i.test(r)?!1:r===`null`?null:Number(r),e[n]=r,e},{});function i(){return`colors`in e.inspectOpts?!!e.inspectOpts.colors:n.isatty(process.stderr.fd)}function a(e){let{namespace:n,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${n} \u001B[0m`;e[0]=a+e[0].split(`
+`).join(`
+`+a),e.push(i+`m+`+t.exports.humanize(this.diff)+`\x1B[0m`)}else e[0]=o()+n+` `+e[0]}function o(){return e.inspectOpts.hideDate?``:new Date().toISOString()+` `}function s(...t){return process.stderr.write(r.formatWithOptions(e.inspectOpts,...t)+`
+`)}function c(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function l(){return process.env.DEBUG}function u(t){t.inspectOpts={};let n=Object.keys(e.inspectOpts);for(let r=0;r<n.length;r++)t.inspectOpts[n[r]]=e.inspectOpts[n[r]]}t.exports=ne()(e);var{formatters:d}=t.exports;d.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split(`
+`).map(e=>e.trim()).join(` `)},d.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}})),z=e(((e,t)=>{typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?t.exports=re():t.exports=R()})),B=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ProgressCallbackTransform=void 0;var t=require("stream");e.ProgressCallbackTransform=class extends t.Transform{constructor(e,t,n){super(),this.total=e,this.cancellationToken=t,this.onProgress=n,this.start=Date.now(),this.transferred=0,this.delta=0,this.nextUpdate=this.start+1e3}_transform(e,t,n){if(this.cancellationToken.cancelled){n(Error(`cancelled`),null);return}this.transferred+=e.length,this.delta+=e.length;let r=Date.now();r>=this.nextUpdate&&this.transferred!==this.total&&(this.nextUpdate=r+1e3,this.onProgress({total:this.total,delta:this.delta,transferred:this.transferred,percent:this.transferred/this.total*100,bytesPerSecond:Math.round(this.transferred/((r-this.start)/1e3))}),this.delta=0),n(null,e)}_flush(e){if(this.cancellationToken.cancelled){e(Error(`cancelled`));return}this.onProgress({total:this.total,delta:this.delta,transferred:this.total,percent:100,bytesPerSecond:Math.round(this.transferred/((Date.now()-this.start)/1e3))}),this.delta=0,e(null)}}})),ae=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DigestTransform=e.HttpExecutor=e.HttpError=void 0,e.addSensitiveRedirectHeader=m,e.addSensitiveFieldPattern=h,e.createHttpError=g,e.parseJson=y,e.configureRequestOptionsFromUrl=x,e.configureRequestUrl=S,e.safeGetHeader=T,e.configureRequestOptions=D,e.isSensitiveFieldName=O,e.hashSensitiveValue=k,e.safeStringifyJson=A;var t=require("crypto"),n=z(),r=require("fs"),i=require("stream"),a=require("url"),o=F(),s=I(),c=B(),l=(0,n.default)(`electron-builder`),u=e=>e.toLowerCase().replace(/[-_]/g,``),d=new Set([`authorization`,`proxyauthorization`,`privatetoken`,`xapikey`,`xauthtoken`,`xaccesstoken`,`xgitlabtoken`,`cookie`,`xcsrftoken`]),f=[`token`,`password`,`secret`,`authorization`,`credential`,`apikey`,`passphrase`,`auth`],p=[`key`];function m(e){d.add(u(e))}function h(e){f.push(e.toLowerCase().replace(/[-_]/g,``))}function g(e,t=null){return new v(e.statusCode||-1,`${e.statusCode} ${e.statusMessage}`+(t==null?``:`
+`+JSON.stringify(t,null,` `))+`
+Headers: `+A(e.headers),t)}var _=new Map([[429,`Too many requests`],[400,`Bad request`],[403,`Forbidden`],[404,`Not found`],[405,`Method not allowed`],[406,`Not acceptable`],[408,`Request timeout`],[413,`Request entity too large`],[500,`Internal server error`],[502,`Bad gateway`],[503,`Service unavailable`],[504,`Gateway timeout`],[505,`HTTP version not supported`]]),v=class extends Error{constructor(e,t=`HTTP error: ${_.get(e)||e}`,n=null){super(t),this.statusCode=e,this.description=n,this.name=`HttpError`,this.code=`HTTP_ERROR_${e}`}isServerError(){return this.statusCode>=500&&this.statusCode<=599}};e.HttpError=v;function y(e){return e.then(e=>e==null||e.length===0?null:JSON.parse(e))}e.HttpExecutor=class e{constructor(){this.maxRedirects=10}request(e,t=new o.CancellationToken,n){D(e);let r=n==null?void 0:JSON.stringify(n),i=r?Buffer.from(r):void 0;if(i!=null){l.enabled&&l(A(n));let{headers:t,...r}=e;e={method:`post`,headers:{"Content-Type":`application/json`,"Content-Length":i.length,...t},...r}}return this.doApiRequest(e,t,e=>e.end(i))}doApiRequest(e,t,n,r=0){if(l.enabled){let{headers:t,auth:n,...r}=e;l(`Request: ${A(r)}`)}return t.createPromise((i,a,o)=>{let s=this.createRequest(e,o=>{try{this.handleResponse(o,e,t,i,a,r,n)}catch(e){a(e)}});this.addErrorAndTimeoutHandlers(s,a,e.timeout),this.addRedirectHandlers(s,e,a,r,e=>{this.doApiRequest(e,t,n,r).then(i).catch(a)}),n(s,a),o(()=>s.abort())})}addRedirectHandlers(e,t,n,r,i){}addErrorAndTimeoutHandlers(e,t,n=60*1e3){this.addTimeOutHandler(e,t,n),e.on(`error`,t),e.on(`aborted`,()=>{t(Error(`Request has been aborted by the server`))})}handleResponse(t,n,r,i,a,o,s){if(l.enabled){let{headers:e,auth:r,...i}=n;l(`Response: ${t.statusCode} ${t.statusMessage}, request options: ${A(i)}`)}if(t.statusCode===404){a(g(t,`method: ${n.method||`GET`} url: ${n.protocol||`https:`}//${n.hostname}${n.port?`:${n.port}`:``}${n.path}
+
+Please double check that your authentication token is correct. Due to security reasons, actual status maybe not reported, but 404.
+`));return}else if(t.statusCode===204){i();return}let c=t.statusCode??0,u=c>=300&&c<400,d=T(t,`location`);if(u&&d!=null){if(o>this.maxRedirects){a(this.createMaxRedirectError());return}this.doApiRequest(e.prepareRedirectUrlOptions(d,n),r,s,o).then(i).catch(a);return}t.setEncoding(`utf8`);let f=``;t.on(`error`,a),t.on(`data`,e=>f+=e),t.on(`end`,()=>{try{if(t.statusCode!=null&&t.statusCode>=400){let e=T(t,`content-type`),r=e!=null&&(Array.isArray(e)?e.find(e=>e.includes(`json`))!=null:e.includes(`json`));a(g(t,`method: ${n.method||`GET`} url: ${n.protocol||`https:`}//${n.hostname}${n.port?`:${n.port}`:``}${n.path}
+
+ Data:
+ ${r?A(JSON.parse(f)):f}
+ `))}else i(f.length===0?null:f)}catch(e){a(e)}})}async downloadToBuffer(e,t){return await t.cancellationToken.createPromise((n,r,i)=>{let a=[],o={headers:t.headers||void 0,redirect:`manual`};S(e,o),D(o),this.doDownload(o,{destination:null,options:t,onCancel:i,callback:e=>{e==null?n(Buffer.concat(a)):r(e)},responseHandler:(e,t)=>{let n=0;e.on(`data`,e=>{if(n+=e.length,n>524288e3){t(Error(`Maximum allowed size is 500 MB`));return}a.push(e)}),e.on(`end`,()=>{t(null)})}},0)})}doDownload(t,n,r){let i=this.createRequest(t,i=>{if(i.statusCode>=400){n.callback(Error(`Cannot download "${t.protocol||`https:`}//${t.hostname}${t.path}", status ${i.statusCode}: ${i.statusMessage}`));return}i.on(`error`,n.callback);let a=T(i,`location`);if(a!=null){r<this.maxRedirects?this.doDownload(e.prepareRedirectUrlOptions(a,t),n,r++):n.callback(this.createMaxRedirectError());return}n.responseHandler==null?E(n,i):n.responseHandler(i,n.callback)});this.addErrorAndTimeoutHandlers(i,n.callback,t.timeout),this.addRedirectHandlers(i,t,n.callback,r,e=>{this.doDownload(e,n,r++)}),i.end()}createMaxRedirectError(){return Error(`Too many redirects (> ${this.maxRedirects})`)}addTimeOutHandler(e,t,n){e.on(`socket`,r=>{r.setTimeout(n,()=>{e.abort(),t(Error(`Request timed out`))})})}static prepareRedirectUrlOptions(t,n){let r=x(t,{...n}),i=r.headers;if(i==null)return r;let a=e.reconstructOriginalUrl(n),o=b(t,n);if(e.isCrossOriginRedirect(a,o)){l.enabled&&l(`Cross-origin redirect (${a.host} → ${o.host}): stripping sensitive headers`);for(let e of Object.keys(i))d.has(u(e))&&delete i[e]}return r}static reconstructOriginalUrl(e){let t=e.protocol||`https:`;if(!e.hostname)throw Error(`Missing hostname in request options`);let n=e.hostname,r=e.port?`:${e.port}`:``,i=e.path||`/`;return new a.URL(`${t}//${n}${r}${i}`)}static isCrossOriginRedirect(e,t){return e.hostname.toLowerCase()===t.hostname.toLowerCase()?e.protocol===`http:`&&[`80`,``].includes(e.port)&&t.protocol===`https:`&&[`443`,``].includes(t.port)?!1:e.protocol===t.protocol?e.port!==t.port:!0:!0}static async retryOnServerError(e,t=3){for(let n=0;;n++)try{return await e()}catch(e){if(n<t&&(e instanceof v&&e.isServerError()||e.code===`EPIPE`)){await new Promise(e=>setTimeout(e,1e3*(n+1)));continue}throw e}}};function b(e,t){try{return new a.URL(e)}catch{let n=t.hostname,r=`${t.protocol||`https:`}//${n}${t.port?`:${t.port}`:``}`;return new a.URL(e,r)}}function x(e,t){let n=D(t);return S(b(e,t),n),n}function S(e,t){t.protocol=e.protocol,t.hostname=e.hostname,e.port?t.port=e.port:t.port&&delete t.port,t.path=e.pathname+e.search}var C=class extends i.Transform{get actual(){return this._actual}constructor(e,n=`sha512`,r=`base64`){super(),this.expected=e,this.algorithm=n,this.encoding=r,this._actual=null,this.isValidateOnEnd=!0,this.digester=(0,t.createHash)(n)}_transform(e,t,n){this.digester.update(e),n(null,e)}_flush(e){if(this._actual=this.digester.digest(this.encoding),this.isValidateOnEnd)try{this.validate()}catch(t){e(t);return}e(null)}validate(){if(this._actual==null)throw(0,s.newError)(`Not finished yet`,`ERR_STREAM_NOT_FINISHED`);if(this._actual!==this.expected)throw(0,s.newError)(`${this.algorithm} checksum mismatch, expected ${this.expected}, got ${this._actual}`,`ERR_CHECKSUM_MISMATCH`);return null}};e.DigestTransform=C;function w(e,t,n){return e!=null&&t!=null&&e!==t?(n(Error(`checksum mismatch: expected ${t} but got ${e} (X-Checksum-Sha2 header)`)),!1):!0}function T(e,t){let n=e.headers[t];return n==null?null:Array.isArray(n)?n.length===0?null:n[n.length-1]:n}function E(e,t){if(!w(T(t,`X-Checksum-Sha2`),e.options.sha2,e.callback))return;let n=[];if(e.options.onProgress!=null){let r=T(t,`content-length`);r!=null&&n.push(new c.ProgressCallbackTransform(parseInt(r,10),e.options.cancellationToken,e.options.onProgress))}let i=e.options.sha512;i==null?e.options.sha2!=null&&n.push(new C(e.options.sha2,`sha256`,`hex`)):n.push(new C(i,`sha512`,i.length===128&&!i.includes(`+`)&&!i.includes(`Z`)&&!i.includes(`=`)?`hex`:`base64`));let a=(0,r.createWriteStream)(e.destination);n.push(a);let o=t;for(let t of n)t.on(`error`,t=>{a.close(),e.options.cancellationToken.cancelled||e.callback(t)}),o=o.pipe(t);a.on(`finish`,()=>{a.close(e.callback)})}function D(e,t,n){n!=null&&(e.method=n),e.headers={...e.headers};let r=e.headers;return t!=null&&(r.authorization=t.startsWith(`Basic`)||t.startsWith(`Bearer`)?t:`token ${t}`),r[`User-Agent`]??=`electron-builder`,(n==null||n===`GET`||r[`Cache-Control`]==null)&&(r[`Cache-Control`]=`no-cache`),e.protocol==null&&process.versions.electron!=null&&(e.protocol=`https:`),e}function O(e){let t=u(e);return f.some(e=>t.includes(e))||p.some(e=>t.endsWith(e))}function k(e){return`${(0,t.createHash)(`sha256`).update(e).digest(`hex`)} (sha256 hash)`}function A(e,t){return JSON.stringify(e,(e,n)=>O(e)||t!=null&&t.has(e)?typeof n==`string`?k(n):`<stripped sensitive data>`:n,2)}})),V=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MemoLazy=void 0,e.MemoLazy=class{constructor(e,t){this.selector=e,this.creator=t,this.selected=void 0,this._value=void 0}get hasValue(){return this._value!==void 0}get value(){let e=this.selector();if(this._value!==void 0&&t(this.selected,e))return this._value;this.selected=e;let n=this.creator(e);return this.value=n,n}set value(e){this._value=e}};function t(e,n){if(typeof e==`object`&&e&&typeof n==`object`&&n){let r=Object.keys(e),i=Object.keys(n);return r.length===i.length&&r.every(r=>t(e[r],n[r]))}return e===n}})),oe=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.githubUrl=t,e.githubTagPrefix=n,e.getS3LikeProviderBaseUrl=r;function t(e,t=`github.com`){return`${e.protocol||`https`}://${e.host||t}`}function n(e){return e.tagNamePrefix?e.tagNamePrefix:e.vPrefixedTagName??!0?`v`:``}function r(e){let t=e.provider;if(t===`s3`)return i(e);if(t===`spaces`)return o(e);throw Error(`Not supported provider: ${t}`)}function i(e){let t;if(e.accelerate==1)t=`https://${e.bucket}.s3-accelerate.amazonaws.com`;else if(e.endpoint!=null)t=`${e.endpoint}/${e.bucket}`;else if(e.bucket.includes(`.`)){if(e.region==null)throw Error(`Bucket name "${e.bucket}" includes a dot, but S3 region is missing`);t=e.region===`us-east-1`?`https://s3.amazonaws.com/${e.bucket}`:`https://s3-${e.region}.amazonaws.com/${e.bucket}`}else t=e.region===`cn-north-1`?`https://${e.bucket}.s3.${e.region}.amazonaws.com.cn`:`https://${e.bucket}.s3.amazonaws.com`;return a(t,e.path)}function a(e,t){return t!=null&&t.length>0&&(t.startsWith(`/`)||(e+=`/`),e+=t),e}function o(e){if(e.name==null)throw Error(`name is missing`);if(e.region==null)throw Error(`region is missing`);return a(`https://${e.name}.${e.region}.digitaloceanspaces.com`,e.path)}})),H=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.retry=n;var t=F();async function n(e,r){let{retries:i,interval:a,backoff:o=0,attempt:s=0,shouldRetry:c,cancellationToken:l=new t.CancellationToken}=r;try{return await e()}catch(t){if(await Promise.resolve(c?.(t)??!0)&&i>0&&!l.cancelled)return await new Promise(e=>setTimeout(e,a+o*s)),await n(e,{...r,retries:i-1,attempt:s+1});throw t}}})),se=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.parseDn=t;function t(e){let t=!1,n=null,r=``,i=0;e=e.trim();let a=new Map;for(let o=0;o<=e.length;o++){if(o===e.length){n!==null&&a.set(n,r);break}let s=e[o];if(t){if(s===`"`){t=!1;continue}}else{if(s===`"`){t=!0;continue}if(s===`\\`){o++;let t=parseInt(e.slice(o,o+2),16);Number.isNaN(t)?r+=e[o]:(o++,r+=String.fromCharCode(t));continue}if(n===null&&s===`=`){n=r,r=``;continue}if(s===`,`||s===`;`||s===`+`){n!==null&&a.set(n,r),n=null,r=``;continue}}if(s===` `&&!t){if(r.length===0)continue;if(o>i){let t=o;for(;e[t]===` `;)t++;i=t}if(i>=e.length||e[i]===`,`||e[i]===`;`||n===null&&e[i]===`=`||n!==null&&e[i]===`+`){o=i-1;continue}}r+=s}return a}})),ce=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.nil=e.UUID=void 0;var t=require("crypto"),n=I(),r=`options.name must be either a string or a Buffer`,i=(0,t.randomBytes)(16);i[0]|=1;var a={},o=[];for(let e=0;e<256;e++){let t=(e+256).toString(16).substr(1);a[t]=e,o[e]=t}var s=class e{constructor(t){this.ascii=null,this.binary=null;let n=e.check(t);if(!n)throw Error(`not a UUID`);this.version=n.version,n.format===`ascii`?this.ascii=t:this.binary=t}static v5(e,t){return u(e,`sha1`,80,t)}toString(){return this.ascii??=d(this.binary),this.ascii}inspect(){return`UUID v${this.version} ${this.toString()}`}static check(e,t=0){if(typeof e==`string`)return e=e.toLowerCase(),/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-([a-f0-9]{12})$/.test(e)?e===`00000000-0000-0000-0000-000000000000`?{version:void 0,variant:`nil`,format:`ascii`}:{version:(a[e[14]+e[15]]&240)>>4,variant:c((a[e[19]+e[20]]&224)>>5),format:`ascii`}:!1;if(Buffer.isBuffer(e)){if(e.length<t+16)return!1;let n=0;for(;n<16&&e[t+n]===0;n++);return n===16?{version:void 0,variant:`nil`,format:`binary`}:{version:(e[t+6]&240)>>4,variant:c((e[t+8]&224)>>5),format:`binary`}}throw(0,n.newError)(`Unknown type of uuid`,`ERR_UNKNOWN_UUID_TYPE`)}static parse(e){let t=Buffer.allocUnsafe(16),n=0;for(let r=0;r<16;r++)t[r]=a[e[n++]+e[n++]],(r===3||r===5||r===7||r===9)&&(n+=1);return t}};e.UUID=s,s.OID=s.parse(`6ba7b812-9dad-11d1-80b4-00c04fd430c8`);function c(e){switch(e){case 0:case 1:case 3:return`ncs`;case 4:case 5:return`rfc4122`;case 6:return`microsoft`;default:return`future`}}var l;(function(e){e[e.ASCII=0]=`ASCII`,e[e.BINARY=1]=`BINARY`,e[e.OBJECT=2]=`OBJECT`})(l||={});function u(e,i,a,c,u=l.ASCII){let d=(0,t.createHash)(i);if(typeof e!=`string`&&!Buffer.isBuffer(e))throw(0,n.newError)(r,`ERR_INVALID_UUID_NAME`);d.update(c),d.update(e);let f=d.digest(),p;switch(u){case l.BINARY:f[6]=f[6]&15|a,f[8]=f[8]&63|128,p=f;break;case l.OBJECT:f[6]=f[6]&15|a,f[8]=f[8]&63|128,p=new s(f);break;default:p=o[f[0]]+o[f[1]]+o[f[2]]+o[f[3]]+`-`+o[f[4]]+o[f[5]]+`-`+o[f[6]&15|a]+o[f[7]]+`-`+o[f[8]&63|128]+o[f[9]]+`-`+o[f[10]]+o[f[11]]+o[f[12]]+o[f[13]]+o[f[14]]+o[f[15]];break}return p}function d(e){return o[e[0]]+o[e[1]]+o[e[2]]+o[e[3]]+`-`+o[e[4]]+o[e[5]]+`-`+o[e[6]]+o[e[7]]+`-`+o[e[8]]+o[e[9]]+`-`+o[e[10]]+o[e[11]]+o[e[12]]+o[e[13]]+o[e[14]]+o[e[15]]}e.nil=new s(`00000000-0000-0000-0000-000000000000`)})),le=e((e=>{(function(e){e.parser=function(e,t){return new n(e,t)},e.SAXParser=n,e.SAXStream=u,e.createStream=c,e.MAX_BUFFER_LENGTH=64*1024;var t=[`comment`,`sgmlDecl`,`textNode`,`tagName`,`doctype`,`procInstName`,`procInstBody`,`entity`,`attribName`,`attribValue`,`cdata`,`script`];e.EVENTS=[`text`,`processinginstruction`,`sgmldeclaration`,`doctype`,`comment`,`opentagstart`,`attribute`,`opentag`,`closetag`,`opencdata`,`cdata`,`closecdata`,`error`,`end`,`ready`,`script`,`opennamespace`,`closenamespace`];function n(t,r){if(!(this instanceof n))return new n(t,r);var a=this;i(a),a.q=a.c=``,a.bufferCheckPosition=e.MAX_BUFFER_LENGTH,a.encoding=null,a.opt=r||{},a.opt.lowercase=a.opt.lowercase||a.opt.lowercasetags,a.looseCase=a.opt.lowercase?`toLowerCase`:`toUpperCase`,a.opt.maxEntityCount=a.opt.maxEntityCount||512,a.opt.maxEntityDepth=a.opt.maxEntityDepth||4,a.entityCount=a.entityDepth=0,a.tags=[],a.closed=a.closedRoot=a.sawRoot=!1,a.tag=a.error=null,a.strict=!!t,a.noscript=!!(t||a.opt.noscript),a.state=T.BEGIN,a.strictEntities=a.opt.strictEntities,a.ENTITIES=a.strictEntities?Object.create(e.XML_ENTITIES):Object.create(e.ENTITIES),a.attribList=[],a.opt.xmlns&&(a.ns=Object.create(h)),a.opt.unquotedAttributeValues===void 0&&(a.opt.unquotedAttributeValues=!t),a.trackPosition=a.opt.position!==!1,a.trackPosition&&(a.position=a.line=a.column=0),D(a,`onready`)}Object.create||(Object.create=function(e){function t(){}return t.prototype=e,new t}),Object.keys||(Object.keys=function(e){var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(n);return t});function r(n){for(var r=Math.max(e.MAX_BUFFER_LENGTH,10),i=0,a=0,o=t.length;a<o;a++){var s=n[t[a]].length;if(s>r)switch(t[a]){case`textNode`:M(n);break;case`cdata`:j(n,`oncdata`,n.cdata),n.cdata=``;break;case`script`:j(n,`onscript`,n.script),n.script=``;break;default:P(n,`Max buffer length exceeded: `+t[a])}i=Math.max(i,s)}n.bufferCheckPosition=e.MAX_BUFFER_LENGTH-i+n.position}function i(e){for(var n=0,r=t.length;n<r;n++)e[t[n]]=``}function a(e){M(e),e.cdata!==``&&(j(e,`oncdata`,e.cdata),e.cdata=``),e.script!==``&&(j(e,`onscript`,e.script),e.script=``)}n.prototype={end:function(){F(this)},write:ae,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){a(this)}};var o;try{o=require("stream").Stream}catch{o=function(){}}o||=function(){};var s=e.EVENTS.filter(function(e){return e!==`error`&&e!==`end`});function c(e,t){return new u(e,t)}function l(e,t){if(e.length>=2){if(e[0]===255&&e[1]===254)return`utf-16le`;if(e[0]===254&&e[1]===255)return`utf-16be`}return e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191?`utf8`:e.length>=4?e[0]===60&&e[1]===0&&e[2]===63&&e[3]===0?`utf-16le`:e[0]===0&&e[1]===60&&e[2]===0&&e[3]===63?`utf-16be`:`utf8`:t?`utf8`:null}function u(e,t){if(!(this instanceof u))return new u(e,t);o.apply(this),this._parser=new n(e,t),this.writable=!0,this.readable=!0;var r=this;this._parser.onend=function(){r.emit(`end`)},this._parser.onerror=function(e){r.emit(`error`,e),r._parser.error=null},this._decoder=null,this._decoderBuffer=null,s.forEach(function(e){Object.defineProperty(r,`on`+e,{get:function(){return r._parser[`on`+e]},set:function(t){if(!t)return r.removeAllListeners(e),r._parser[`on`+e]=t,t;r.on(e,t)},enumerable:!0,configurable:!1})})}u.prototype=Object.create(o.prototype,{constructor:{value:u}}),u.prototype._decodeBuffer=function(e,t){if(this._decoderBuffer&&=(e=Buffer.concat([this._decoderBuffer,e]),null),!this._decoder){var n=l(e,t);if(!n)return this._decoderBuffer=e,``;this._parser.encoding=n,this._decoder=new TextDecoder(n)}return this._decoder.decode(e,{stream:!t})},u.prototype.write=function(e){if(typeof Buffer==`function`&&typeof Buffer.isBuffer==`function`&&Buffer.isBuffer(e))e=this._decodeBuffer(e,!1);else if(this._decoderBuffer){var t=this._decodeBuffer(Buffer.alloc(0),!0);t&&(this._parser.write(t),this.emit(`data`,t))}return this._parser.write(e.toString()),this.emit(`data`,e),!0},u.prototype.end=function(e){if(e&&e.length&&this.write(e),this._decoderBuffer){var t=this._decodeBuffer(Buffer.alloc(0),!0);t&&(this._parser.write(t),this.emit(`data`,t))}else if(this._decoder){var n=this._decoder.decode();n&&(this._parser.write(n),this.emit(`data`,n))}return this._parser.end(),!0},u.prototype.on=function(e,t){var n=this;return!n._parser[`on`+e]&&s.indexOf(e)!==-1&&(n._parser[`on`+e]=function(){var t=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);t.splice(0,0,e),n.emit.apply(n,t)}),o.prototype.on.call(n,e,t)};var d=`[CDATA[`,f=`DOCTYPE`,p=`http://www.w3.org/XML/1998/namespace`,m=`http://www.w3.org/2000/xmlns/`,h={xml:p,xmlns:m},g=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,_=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,v=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,y=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function b(e){return e===` `||e===`
+`||e===`\r`||e===` `}function x(e){return e===`"`||e===`'`}function S(e){return e===`>`||b(e)}function C(e,t){return e.test(t)}function w(e,t){return!C(e,t)}var T=0;for(var E in e.STATE={BEGIN:T++,BEGIN_WHITESPACE:T++,TEXT:T++,TEXT_ENTITY:T++,OPEN_WAKA:T++,SGML_DECL:T++,SGML_DECL_QUOTED:T++,DOCTYPE:T++,DOCTYPE_QUOTED:T++,DOCTYPE_DTD:T++,DOCTYPE_DTD_QUOTED:T++,COMMENT_STARTING:T++,COMMENT:T++,COMMENT_ENDING:T++,COMMENT_ENDED:T++,CDATA:T++,CDATA_ENDING:T++,CDATA_ENDING_2:T++,PROC_INST:T++,PROC_INST_BODY:T++,PROC_INST_ENDING:T++,OPEN_TAG:T++,OPEN_TAG_SLASH:T++,ATTRIB:T++,ATTRIB_NAME:T++,ATTRIB_NAME_SAW_WHITE:T++,ATTRIB_VALUE:T++,ATTRIB_VALUE_QUOTED:T++,ATTRIB_VALUE_CLOSED:T++,ATTRIB_VALUE_UNQUOTED:T++,ATTRIB_VALUE_ENTITY_Q:T++,ATTRIB_VALUE_ENTITY_U:T++,CLOSE_TAG:T++,CLOSE_TAG_SAW_WHITE:T++,SCRIPT:T++,SCRIPT_ENDING:T++},e.XML_ENTITIES={amp:`&`,gt:`>`,lt:`<`,quot:`"`,apos:`'`},e.ENTITIES={amp:`&`,gt:`>`,lt:`<`,quot:`"`,apos:`'`,AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(e.ENTITIES).forEach(function(t){var n=e.ENTITIES[t],r=typeof n==`number`?String.fromCharCode(n):n;e.ENTITIES[t]=r}),e.STATE)e.STATE[e.STATE[E]]=E;T=e.STATE;function D(e,t,n){e[t]&&e[t](n)}function O(e){var t=e&&e.match(/(?:^|\s)encoding\s*=\s*(['"])([^'"]+)\1/i);return t?t[2]:null}function k(e){return e?e.toLowerCase().replace(/[^a-z0-9]/g,``):null}function A(e,t){let n=k(e),r=k(t);return!n||!r?!0:r===`utf16`?n===`utf16le`||n===`utf16be`:n===r}function ee(e,t){if(!(!e.strict||!e.encoding||!t||t.name!==`xml`)){var n=O(t.body);n&&!A(e.encoding,n)&&I(e,`XML declaration encoding `+n+` does not match detected stream encoding `+e.encoding.toUpperCase())}}function j(e,t,n){e.textNode&&M(e),D(e,t,n)}function M(e){e.textNode=N(e.opt,e.textNode),e.textNode&&D(e,`ontext`,e.textNode),e.textNode=``}function N(e,t){return e.trim&&(t=t.trim()),e.normalize&&(t=t.replace(/\s+/g,` `)),t}function P(e,t){return M(e),e.trackPosition&&(t+=`
+Line: `+e.line+`
+Column: `+e.column+`
+Char: `+e.c),t=Error(t),e.error=t,D(e,`onerror`,t),e}function F(e){return e.sawRoot&&!e.closedRoot&&I(e,`Unclosed root tag`),e.state!==T.BEGIN&&e.state!==T.BEGIN_WHITESPACE&&e.state!==T.TEXT&&P(e,`Unexpected end`),M(e),e.c=``,e.closed=!0,D(e,`onend`),n.call(e,e.strict,e.opt),e}function I(e,t){if(typeof e!=`object`||!(e instanceof n))throw Error(`bad call to strictFail`);e.strict&&P(e,t)}function te(e){e.strict||(e.tagName=e.tagName[e.looseCase]());var t=e.tags[e.tags.length-1]||e,n=e.tag={name:e.tagName,attributes:{}};e.opt.xmlns&&(n.ns=t.ns),e.attribList.length=0,j(e,`onopentagstart`,n)}function ne(e,t){var n=e.indexOf(`:`)<0?[``,e]:e.split(`:`),r=n[0],i=n[1];return t&&e===`xmlns`&&(r=`xmlns`,i=``),{prefix:r,local:i}}function re(e){if(e.strict||(e.attribName=e.attribName[e.looseCase]()),e.attribList.indexOf(e.attribName)!==-1||e.tag.attributes.hasOwnProperty(e.attribName)){e.attribName=e.attribValue=``;return}if(e.opt.xmlns){var t=ne(e.attribName,!0),n=t.prefix,r=t.local;if(n===`xmlns`)if(r===`xml`&&e.attribValue!==p)I(e,`xml: prefix must be bound to `+p+`
+Actual: `+e.attribValue);else if(r===`xmlns`&&e.attribValue!==m)I(e,`xmlns: prefix must be bound to `+m+`
+Actual: `+e.attribValue);else{var i=e.tag,a=e.tags[e.tags.length-1]||e;i.ns===a.ns&&(i.ns=Object.create(a.ns)),i.ns[r]=e.attribValue}e.attribList.push([e.attribName,e.attribValue])}else e.tag.attributes[e.attribName]=e.attribValue,j(e,`onattribute`,{name:e.attribName,value:e.attribValue});e.attribName=e.attribValue=``}function L(e,t){if(e.opt.xmlns){var n=e.tag,r=ne(e.tagName);n.prefix=r.prefix,n.local=r.local,n.uri=n.ns[r.prefix]||``,n.prefix&&!n.uri&&(I(e,`Unbound namespace prefix: `+JSON.stringify(e.tagName)),n.uri=r.prefix);var i=e.tags[e.tags.length-1]||e;n.ns&&i.ns!==n.ns&&Object.keys(n.ns).forEach(function(t){j(e,`onopennamespace`,{prefix:t,uri:n.ns[t]})});for(var a=0,o=e.attribList.length;a<o;a++){var s=e.attribList[a],c=s[0],l=s[1],u=ne(c,!0),d=u.prefix,f=u.local,p=d===``?``:n.ns[d]||``,m={name:c,value:l,prefix:d,local:f,uri:p};d&&d!==`xmlns`&&!p&&(I(e,`Unbound namespace prefix: `+JSON.stringify(d)),m.uri=d),e.tag.attributes[c]=m,j(e,`onattribute`,m)}e.attribList.length=0}e.tag.isSelfClosing=!!t,e.sawRoot=!0,e.tags.push(e.tag),j(e,`onopentag`,e.tag),t||(!e.noscript&&e.tagName.toLowerCase()===`script`?e.state=T.SCRIPT:e.state=T.TEXT,e.tag=null,e.tagName=``),e.attribName=e.attribValue=``,e.attribList.length=0}function ie(e){if(!e.tagName){I(e,`Weird empty close tag.`),e.textNode+=`</>`,e.state=T.TEXT;return}if(e.script){if(e.tagName!==`script`){e.script+=`</`+e.tagName+`>`,e.tagName=``,e.state=T.SCRIPT;return}j(e,`onscript`,e.script),e.script=``}var t=e.tags.length,n=e.tagName;e.strict||(n=n[e.looseCase]());for(var r=n;t--&&e.tags[t].name!==r;)I(e,`Unexpected close tag`);if(t<0){I(e,`Unmatched closing tag: `+e.tagName),e.textNode+=`</`+e.tagName+`>`,e.state=T.TEXT;return}e.tagName=n;for(var i=e.tags.length;i-- >t;){var a=e.tag=e.tags.pop();e.tagName=e.tag.name,j(e,`onclosetag`,e.tagName);var o={};for(var s in a.ns)o[s]=a.ns[s];var c=e.tags[e.tags.length-1]||e;e.opt.xmlns&&a.ns!==c.ns&&Object.keys(a.ns).forEach(function(t){var n=a.ns[t];j(e,`onclosenamespace`,{prefix:t,uri:n})})}t===0&&(e.closedRoot=!0),e.tagName=e.attribValue=e.attribName=``,e.attribList.length=0,e.state=T.TEXT}function R(e){var t=e.entity,n=t.toLowerCase(),r,i=``;return e.ENTITIES[t]?e.ENTITIES[t]:e.ENTITIES[n]?e.ENTITIES[n]:(t=n,t.charAt(0)===`#`&&(t.charAt(1)===`x`?(t=t.slice(2),r=parseInt(t,16),i=r.toString(16)):(t=t.slice(1),r=parseInt(t,10),i=r.toString(10))),t=t.replace(/^0+/,``),isNaN(r)||i.toLowerCase()!==t||r<0||r>1114111?(I(e,`Invalid character entity`),`&`+e.entity+`;`):String.fromCodePoint(r))}function z(e,t){t===`<`?(e.state=T.OPEN_WAKA,e.startTagPosition=e.position):b(t)||(I(e,`Non-whitespace before first tag.`),e.textNode=t,e.state=T.TEXT)}function B(e,t){var n=``;return t<e.length&&(n=e.charAt(t)),n}function ae(t){var n=this;if(this.error)throw this.error;if(n.closed)return P(n,`Cannot write after close. Assign an onready handler.`);if(t===null)return F(n);typeof t==`object`&&(t=t.toString());for(var i=0,a=``;a=B(t,i++),n.c=a,a;)switch(n.trackPosition&&(n.position++,a===`
+`?(n.line++,n.column=0):n.column++),n.state){case T.BEGIN:if(n.state=T.BEGIN_WHITESPACE,a===``)continue;z(n,a);continue;case T.BEGIN_WHITESPACE:z(n,a);continue;case T.TEXT:if(n.sawRoot&&!n.closedRoot){for(var o=i-1;a&&a!==`<`&&a!==`&`;)a=B(t,i++),a&&n.trackPosition&&(n.position++,a===`
+`?(n.line++,n.column=0):n.column++);n.textNode+=t.substring(o,i-1)}a===`<`&&!(n.sawRoot&&n.closedRoot&&!n.strict)?(n.state=T.OPEN_WAKA,n.startTagPosition=n.position):(!b(a)&&(!n.sawRoot||n.closedRoot)&&I(n,`Text data outside of root node.`),a===`&`?n.state=T.TEXT_ENTITY:n.textNode+=a);continue;case T.SCRIPT:a===`<`?n.state=T.SCRIPT_ENDING:n.script+=a;continue;case T.SCRIPT_ENDING:a===`/`?n.state=T.CLOSE_TAG:(n.script+=`<`+a,n.state=T.SCRIPT);continue;case T.OPEN_WAKA:if(a===`!`)n.state=T.SGML_DECL,n.sgmlDecl=``;else if(!b(a))if(C(g,a))n.state=T.OPEN_TAG,n.tagName=a;else if(a===`/`)n.state=T.CLOSE_TAG,n.tagName=``;else if(a===`?`)n.state=T.PROC_INST,n.procInstName=n.procInstBody=``;else{if(I(n,`Unencoded <`),n.startTagPosition+1<n.position){var s=n.position-n.startTagPosition;a=Array(s).join(` `)+a}n.textNode+=`<`+a,n.state=T.TEXT}continue;case T.SGML_DECL:if(n.sgmlDecl+a===`--`){n.state=T.COMMENT,n.comment=``,n.sgmlDecl=``;continue}n.doctype&&n.doctype!==!0&&n.sgmlDecl?(n.state=T.DOCTYPE_DTD,n.doctype+=`<!`+n.sgmlDecl+a,n.sgmlDecl=``):(n.sgmlDecl+a).toUpperCase()===d?(j(n,`onopencdata`),n.state=T.CDATA,n.sgmlDecl=``,n.cdata=``):(n.sgmlDecl+a).toUpperCase()===f?(n.state=T.DOCTYPE,(n.doctype||n.sawRoot)&&I(n,`Inappropriately located doctype declaration`),n.doctype=``,n.sgmlDecl=``):a===`>`?(j(n,`onsgmldeclaration`,n.sgmlDecl),n.sgmlDecl=``,n.state=T.TEXT):(x(a)&&(n.state=T.SGML_DECL_QUOTED),n.sgmlDecl+=a);continue;case T.SGML_DECL_QUOTED:a===n.q&&(n.state=T.SGML_DECL,n.q=``),n.sgmlDecl+=a;continue;case T.DOCTYPE:a===`>`?(n.state=T.TEXT,j(n,`ondoctype`,n.doctype),n.doctype=!0):(n.doctype+=a,a===`[`?n.state=T.DOCTYPE_DTD:x(a)&&(n.state=T.DOCTYPE_QUOTED,n.q=a));continue;case T.DOCTYPE_QUOTED:n.doctype+=a,a===n.q&&(n.q=``,n.state=T.DOCTYPE);continue;case T.DOCTYPE_DTD:a===`]`?(n.doctype+=a,n.state=T.DOCTYPE):a===`<`?(n.state=T.OPEN_WAKA,n.startTagPosition=n.position):x(a)?(n.doctype+=a,n.state=T.DOCTYPE_DTD_QUOTED,n.q=a):n.doctype+=a;continue;case T.DOCTYPE_DTD_QUOTED:n.doctype+=a,a===n.q&&(n.state=T.DOCTYPE_DTD,n.q=``);continue;case T.COMMENT:a===`-`?n.state=T.COMMENT_ENDING:n.comment+=a;continue;case T.COMMENT_ENDING:a===`-`?(n.state=T.COMMENT_ENDED,n.comment=N(n.opt,n.comment),n.comment&&j(n,`oncomment`,n.comment),n.comment=``):(n.comment+=`-`+a,n.state=T.COMMENT);continue;case T.COMMENT_ENDED:a===`>`?n.doctype&&n.doctype!==!0?n.state=T.DOCTYPE_DTD:n.state=T.TEXT:(I(n,`Malformed comment`),n.comment+=`--`+a,n.state=T.COMMENT);continue;case T.CDATA:for(var o=i-1;a&&a!==`]`;)a=B(t,i++),a&&n.trackPosition&&(n.position++,a===`
+`?(n.line++,n.column=0):n.column++);n.cdata+=t.substring(o,i-1),a===`]`&&(n.state=T.CDATA_ENDING);continue;case T.CDATA_ENDING:a===`]`?n.state=T.CDATA_ENDING_2:(n.cdata+=`]`+a,n.state=T.CDATA);continue;case T.CDATA_ENDING_2:a===`>`?(n.cdata&&j(n,`oncdata`,n.cdata),j(n,`onclosecdata`),n.cdata=``,n.state=T.TEXT):a===`]`?n.cdata+=`]`:(n.cdata+=`]]`+a,n.state=T.CDATA);continue;case T.PROC_INST:a===`?`?n.state=T.PROC_INST_ENDING:b(a)?n.state=T.PROC_INST_BODY:n.procInstName+=a;continue;case T.PROC_INST_BODY:if(!n.procInstBody&&b(a))continue;a===`?`?n.state=T.PROC_INST_ENDING:n.procInstBody+=a;continue;case T.PROC_INST_ENDING:if(a===`>`){let e={name:n.procInstName,body:n.procInstBody};ee(n,e),j(n,`onprocessinginstruction`,e),n.procInstName=n.procInstBody=``,n.state=T.TEXT}else n.procInstBody+=`?`+a,n.state=T.PROC_INST_BODY;continue;case T.OPEN_TAG:C(_,a)?n.tagName+=a:(te(n),a===`>`?L(n):a===`/`?n.state=T.OPEN_TAG_SLASH:(b(a)||I(n,`Invalid character in tag name`),n.state=T.ATTRIB));continue;case T.OPEN_TAG_SLASH:a===`>`?(L(n,!0),ie(n)):(I(n,`Forward-slash in opening tag not followed by >`),n.state=T.ATTRIB);continue;case T.ATTRIB:if(b(a))continue;a===`>`?L(n):a===`/`?n.state=T.OPEN_TAG_SLASH:C(g,a)?(n.attribName=a,n.attribValue=``,n.state=T.ATTRIB_NAME):I(n,`Invalid attribute name`);continue;case T.ATTRIB_NAME:a===`=`?n.state=T.ATTRIB_VALUE:a===`>`?(I(n,`Attribute without value`),n.attribValue=n.attribName,re(n),L(n)):b(a)?n.state=T.ATTRIB_NAME_SAW_WHITE:C(_,a)?n.attribName+=a:I(n,`Invalid attribute name`);continue;case T.ATTRIB_NAME_SAW_WHITE:if(a===`=`)n.state=T.ATTRIB_VALUE;else if(b(a))continue;else I(n,`Attribute without value`),n.tag.attributes[n.attribName]=``,n.attribValue=``,j(n,`onattribute`,{name:n.attribName,value:``}),n.attribName=``,a===`>`?L(n):C(g,a)?(n.attribName=a,n.state=T.ATTRIB_NAME):(I(n,`Invalid attribute name`),n.state=T.ATTRIB);continue;case T.ATTRIB_VALUE:if(b(a))continue;x(a)?(n.q=a,n.state=T.ATTRIB_VALUE_QUOTED):(n.opt.unquotedAttributeValues||P(n,`Unquoted attribute value`),n.state=T.ATTRIB_VALUE_UNQUOTED,n.attribValue=a);continue;case T.ATTRIB_VALUE_QUOTED:if(a!==n.q){a===`&`?n.state=T.ATTRIB_VALUE_ENTITY_Q:n.attribValue+=a;continue}re(n),n.q=``,n.state=T.ATTRIB_VALUE_CLOSED;continue;case T.ATTRIB_VALUE_CLOSED:b(a)?n.state=T.ATTRIB:a===`>`?L(n):a===`/`?n.state=T.OPEN_TAG_SLASH:C(g,a)?(I(n,`No whitespace between attributes`),n.attribName=a,n.attribValue=``,n.state=T.ATTRIB_NAME):I(n,`Invalid attribute name`);continue;case T.ATTRIB_VALUE_UNQUOTED:if(!S(a)){a===`&`?n.state=T.ATTRIB_VALUE_ENTITY_U:n.attribValue+=a;continue}re(n),a===`>`?L(n):n.state=T.ATTRIB;continue;case T.CLOSE_TAG:if(n.tagName)a===`>`?ie(n):C(_,a)?n.tagName+=a:n.script?(n.script+=`</`+n.tagName+a,n.tagName=``,n.state=T.SCRIPT):(b(a)||I(n,`Invalid tagname in closing tag`),n.state=T.CLOSE_TAG_SAW_WHITE);else{if(b(a))continue;w(g,a)?n.script?(n.script+=`</`+a,n.state=T.SCRIPT):I(n,`Invalid tagname in closing tag.`):n.tagName=a}continue;case T.CLOSE_TAG_SAW_WHITE:if(b(a))continue;a===`>`?ie(n):I(n,`Invalid characters in closing tag`);continue;case T.TEXT_ENTITY:case T.ATTRIB_VALUE_ENTITY_Q:case T.ATTRIB_VALUE_ENTITY_U:var c,l;switch(n.state){case T.TEXT_ENTITY:c=T.TEXT,l=`textNode`;break;case T.ATTRIB_VALUE_ENTITY_Q:c=T.ATTRIB_VALUE_QUOTED,l=`attribValue`;break;case T.ATTRIB_VALUE_ENTITY_U:c=T.ATTRIB_VALUE_UNQUOTED,l=`attribValue`;break}if(a===`;`){var u=R(n);n.opt.unparsedEntities&&!Object.values(e.XML_ENTITIES).includes(u)?((n.entityCount+=1)>n.opt.maxEntityCount&&P(n,`Parsed entity count exceeds max entity count`),(n.entityDepth+=1)>n.opt.maxEntityDepth&&P(n,`Parsed entity depth exceeds max entity depth`),n.entity=``,n.state=c,n.write(u),--n.entityDepth):(n[l]+=u,n.entity=``,n.state=c)}else C(n.entity.length?y:v,a)?n.entity+=a:(I(n,`Invalid character in entity name`),n[l]+=`&`+n.entity+a,n.entity=``,n.state=c);continue;default:throw Error(n,`Unknown state: `+n.state)}return n.position>=n.bufferCheckPosition&&r(n),n}String.fromCodePoint||(function(){var e=String.fromCharCode,t=Math.floor,n=function(){var n=16384,r=[],i,a,o=-1,s=arguments.length;if(!s)return``;for(var c=``;++o<s;){var l=Number(arguments[o]);if(!isFinite(l)||l<0||l>1114111||t(l)!==l)throw RangeError(`Invalid code point: `+l);l<=65535?r.push(l):(l-=65536,i=(l>>10)+55296,a=l%1024+56320,r.push(i,a)),(o+1===s||r.length>n)&&(c+=e.apply(null,r),r.length=0)}return c};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:n,configurable:!0,writable:!0}):String.fromCodePoint=n})()})(e===void 0?e.sax={}:e)})),ue=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.XElement=void 0,e.parseXml=s;var t=le(),n=I(),r=class{constructor(e){if(this.name=e,this.value=``,this.attributes=null,this.isCData=!1,this.elements=null,!e)throw(0,n.newError)(`Element name cannot be empty`,`ERR_XML_ELEMENT_NAME_EMPTY`);if(!a(e))throw(0,n.newError)(`Invalid element name: ${e}`,`ERR_XML_ELEMENT_INVALID_NAME`)}attribute(e){let t=this.attributes===null?null:this.attributes[e];if(t==null)throw(0,n.newError)(`No attribute "${e}"`,`ERR_XML_MISSED_ATTRIBUTE`);return t}removeAttribute(e){this.attributes!==null&&delete this.attributes[e]}element(e,t=!1,r=null){let i=this.elementOrNull(e,t);if(i===null)throw(0,n.newError)(r||`No element "${e}"`,`ERR_XML_MISSED_ELEMENT`);return i}elementOrNull(e,t=!1){if(this.elements===null)return null;for(let n of this.elements)if(o(n,e,t))return n;return null}getElements(e,t=!1){return this.elements===null?[]:this.elements.filter(n=>o(n,e,t))}elementValueOrEmpty(e,t=!1){let n=this.elementOrNull(e,t);return n===null?``:n.value}};e.XElement=r;var i=new RegExp(/^[A-Za-z_][:A-Za-z0-9_-]*$/i);function a(e){return i.test(e)}function o(e,t,n){let r=e.name;return r===t||n===!0&&r.length===t.length&&r.toLowerCase()===t.toLowerCase()}function s(e){let n=null,i=t.parser(!0,{}),a=[];return i.onopentag=e=>{let t=new r(e.name);if(t.attributes=e.attributes,n===null)n=t;else{let e=a[a.length-1];e.elements??=[],e.elements.push(t)}a.push(t)},i.onclosetag=()=>{a.pop()},i.ontext=e=>{a.length>0&&(a[a.length-1].value=e)},i.oncdata=e=>{let t=a[a.length-1];t.value=e,t.isCData=!0},i.onerror=e=>{throw e},i.write(e),n}})),de=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.mapToObject=t,e.isValidKey=n,e.asArray=r,e.deepAssign=s,e.objectToArgs=u;function t(e){let r={};for(let[i,a]of e)n(i)&&(a instanceof Map?r[i]=t(a):r[i]=a);return r}function n(e){return[`__proto__`,`prototype`,`constructor`].includes(e)?!1:[`string`,`number`,`symbol`,`boolean`].includes(typeof e)||e===null}function r(e){return e==null?[]:Array.isArray(e)?e:[e]}function i(e){if(Array.isArray(e))return!1;let t=typeof e;return t===`object`||t===`function`}function a(e,t,n){let r=t[n];if(r===void 0)return;let a=e[n];a==null||r==null||!i(a)||!i(r)?Array.isArray(a)&&Array.isArray(r)?e[n]=Array.from(new Set(a.concat(r))):e[n]=r:e[n]=o(a,r)}function o(e,t){if(e!==t)for(let r of Object.getOwnPropertyNames(t))n(r)&&a(e,t,r);return e}function s(e,...t){for(let n of t)n!=null&&o(e,n);return e}var c=/^[a-zA-Z][a-zA-Z0-9-]*$/,l=/[\0\r\n]/;function u(e){let t=Object.entries(e).reduce((e,[t,r])=>{if(!n(t)||r==null)return e;if(!c.test(t))throw Error(`objectToArgs: unsafe flag name rejected: ${JSON.stringify(t)}`);if(l.test(r))throw Error(`objectToArgs: value for --${t} contains a null byte or newline`);return e.concat([`--${t}`,r])},[]);return Object.freeze(t)}})),U=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CURRENT_APP_PACKAGE_FILE_NAME=e.CURRENT_APP_INSTALLER_FILE_NAME=e.objectToArgs=e.deepAssign=e.asArray=e.mapToObject=e.isValidKey=e.XElement=e.parseXml=e.UUID=e.parseDn=e.retry=e.githubTagPrefix=e.githubUrl=e.getS3LikeProviderBaseUrl=e.ProgressCallbackTransform=e.MemoLazy=e.safeStringifyJson=e.safeGetHeader=e.parseJson=e.isSensitiveFieldName=e.HttpExecutor=e.hashSensitiveValue=e.HttpError=e.DigestTransform=e.createHttpError=e.configureRequestUrl=e.configureRequestOptionsFromUrl=e.configureRequestOptions=e.newError=e.CancellationToken=e.CancellationError=void 0;var t=F();Object.defineProperty(e,"CancellationError",{enumerable:!0,get:function(){return t.CancellationError}}),Object.defineProperty(e,"CancellationToken",{enumerable:!0,get:function(){return t.CancellationToken}});var n=I();Object.defineProperty(e,"newError",{enumerable:!0,get:function(){return n.newError}});var r=ae();Object.defineProperty(e,"configureRequestOptions",{enumerable:!0,get:function(){return r.configureRequestOptions}}),Object.defineProperty(e,"configureRequestOptionsFromUrl",{enumerable:!0,get:function(){return r.configureRequestOptionsFromUrl}}),Object.defineProperty(e,"configureRequestUrl",{enumerable:!0,get:function(){return r.configureRequestUrl}}),Object.defineProperty(e,"createHttpError",{enumerable:!0,get:function(){return r.createHttpError}}),Object.defineProperty(e,"DigestTransform",{enumerable:!0,get:function(){return r.DigestTransform}}),Object.defineProperty(e,"HttpError",{enumerable:!0,get:function(){return r.HttpError}}),Object.defineProperty(e,"hashSensitiveValue",{enumerable:!0,get:function(){return r.hashSensitiveValue}}),Object.defineProperty(e,"HttpExecutor",{enumerable:!0,get:function(){return r.HttpExecutor}}),Object.defineProperty(e,"isSensitiveFieldName",{enumerable:!0,get:function(){return r.isSensitiveFieldName}}),Object.defineProperty(e,"parseJson",{enumerable:!0,get:function(){return r.parseJson}}),Object.defineProperty(e,"safeGetHeader",{enumerable:!0,get:function(){return r.safeGetHeader}}),Object.defineProperty(e,"safeStringifyJson",{enumerable:!0,get:function(){return r.safeStringifyJson}});var i=V();Object.defineProperty(e,"MemoLazy",{enumerable:!0,get:function(){return i.MemoLazy}});var a=B();Object.defineProperty(e,"ProgressCallbackTransform",{enumerable:!0,get:function(){return a.ProgressCallbackTransform}});var o=oe();Object.defineProperty(e,"getS3LikeProviderBaseUrl",{enumerable:!0,get:function(){return o.getS3LikeProviderBaseUrl}}),Object.defineProperty(e,"githubUrl",{enumerable:!0,get:function(){return o.githubUrl}}),Object.defineProperty(e,"githubTagPrefix",{enumerable:!0,get:function(){return o.githubTagPrefix}});var s=H();Object.defineProperty(e,"retry",{enumerable:!0,get:function(){return s.retry}});var c=se();Object.defineProperty(e,"parseDn",{enumerable:!0,get:function(){return c.parseDn}});var l=ce();Object.defineProperty(e,"UUID",{enumerable:!0,get:function(){return l.UUID}});var u=ue();Object.defineProperty(e,"parseXml",{enumerable:!0,get:function(){return u.parseXml}}),Object.defineProperty(e,"XElement",{enumerable:!0,get:function(){return u.XElement}});var d=de();Object.defineProperty(e,"isValidKey",{enumerable:!0,get:function(){return d.isValidKey}}),Object.defineProperty(e,"mapToObject",{enumerable:!0,get:function(){return d.mapToObject}}),Object.defineProperty(e,"asArray",{enumerable:!0,get:function(){return d.asArray}}),Object.defineProperty(e,"deepAssign",{enumerable:!0,get:function(){return d.deepAssign}}),Object.defineProperty(e,"objectToArgs",{enumerable:!0,get:function(){return d.objectToArgs}}),e.CURRENT_APP_INSTALLER_FILE_NAME=`installer.exe`,e.CURRENT_APP_PACKAGE_FILE_NAME=`package.7z`})),fe=e(((e,t)=>{function n(e){return e==null}function r(e){return typeof e==`object`&&!!e}function i(e){return Array.isArray(e)?e:n(e)?[]:[e]}function a(e,t){if(t){let n=Object.keys(t);for(let r=0,i=n.length;r<i;r+=1){let i=n[r];e[i]=t[i]}}return e}function o(e,t){let n=``;for(let r=0;r<t;r+=1)n+=e;return n}function s(e){return e===0&&1/e==-1/0}t.exports.isNothing=n,t.exports.isObject=r,t.exports.toArray=i,t.exports.repeat=o,t.exports.isNegativeZero=s,t.exports.extend=a})),pe=e(((e,t)=>{function n(e,t){let n=``,r=e.reason||`(unknown reason)`;return e.mark?(e.mark.name&&(n+=`in "`+e.mark.name+`" `),n+=`(`+(e.mark.line+1)+`:`+(e.mark.column+1)+`)`,!t&&e.mark.snippet&&(n+=`
+
+`+e.mark.snippet),r+` `+n):r}function r(e,t){Error.call(this),this.name=`YAMLException`,this.reason=e,this.mark=t,this.message=n(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=Error().stack||``}r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r.prototype.toString=function(e){return this.name+`: `+n(this,e)},t.exports=r})),me=e(((e,t)=>{var n=fe();function r(e,t,n,r,i){let a=``,o=``,s=Math.floor(i/2)-1;return r-t>s&&(a=` ... `,t=r-s+a.length),n-r>s&&(o=` ...`,n=r+s-o.length),{str:a+e.slice(t,n).replace(/\t/g,`→`)+o,pos:r-t+a.length}}function i(e,t){return n.repeat(` `,t-e.length)+e}function a(e,t){if(t=Object.create(t||null),!e.buffer)return null;t.maxLength||=79,typeof t.indent!=`number`&&(t.indent=1),typeof t.linesBefore!=`number`&&(t.linesBefore=3),typeof t.linesAfter!=`number`&&(t.linesAfter=2);let a=/\r?\n|\r|\0/g,o=[0],s=[],c,l=-1;for(;c=a.exec(e.buffer);)s.push(c.index),o.push(c.index+c[0].length),e.position<=c.index&&l<0&&(l=o.length-2);l<0&&(l=o.length-1);let u=``,d=Math.min(e.line+t.linesAfter,s.length).toString().length,f=t.maxLength-(t.indent+d+3);for(let a=1;a<=t.linesBefore&&!(l-a<0);a++){let c=r(e.buffer,o[l-a],s[l-a],e.position-(o[l]-o[l-a]),f);u=n.repeat(` `,t.indent)+i((e.line-a+1).toString(),d)+` | `+c.str+`
+`+u}let p=r(e.buffer,o[l],s[l],e.position,f);u+=n.repeat(` `,t.indent)+i((e.line+1).toString(),d)+` | `+p.str+`
+`,u+=n.repeat(`-`,t.indent+d+3+p.pos)+`^
+`;for(let a=1;a<=t.linesAfter&&!(l+a>=s.length);a++){let c=r(e.buffer,o[l+a],s[l+a],e.position-(o[l]-o[l+a]),f);u+=n.repeat(` `,t.indent)+i((e.line+a+1).toString(),d)+` | `+c.str+`
+`}return u.replace(/\n$/,``)}t.exports=a})),W=e(((e,t)=>{var n=pe(),r=[`kind`,`multi`,`resolve`,`construct`,`instanceOf`,`predicate`,`represent`,`representName`,`defaultStyle`,`styleAliases`],i=[`scalar`,`sequence`,`mapping`];function a(e){let t={};return e!==null&&Object.keys(e).forEach(function(n){e[n].forEach(function(e){t[String(e)]=n})}),t}function o(e,t){if(t||={},Object.keys(t).forEach(function(t){if(r.indexOf(t)===-1)throw new n(`Unknown option "`+t+`" is met in definition of "`+e+`" YAML type.`)}),this.options=t,this.tag=e,this.kind=t.kind||null,this.resolve=t.resolve||function(){return!0},this.construct=t.construct||function(e){return e},this.instanceOf=t.instanceOf||null,this.predicate=t.predicate||null,this.represent=t.represent||null,this.representName=t.representName||null,this.defaultStyle=t.defaultStyle||null,this.multi=t.multi||!1,this.styleAliases=a(t.styleAliases||null),i.indexOf(this.kind)===-1)throw new n(`Unknown kind "`+this.kind+`" is specified for "`+e+`" YAML type.`)}t.exports=o})),he=e(((e,t)=>{var n=pe(),r=W();function i(e,t){let n=[];return e[t].forEach(function(e){let t=n.length;n.forEach(function(n,r){n.tag===e.tag&&n.kind===e.kind&&n.multi===e.multi&&(t=r)}),n[t]=e}),n}function a(){let e={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function t(t){t.multi?(e.multi[t.kind].push(t),e.multi.fallback.push(t)):e[t.kind][t.tag]=e.fallback[t.tag]=t}for(let e=0,n=arguments.length;e<n;e+=1)arguments[e].forEach(t);return e}function o(e){return this.extend(e)}o.prototype.extend=function(e){let t=[],s=[];if(e instanceof r)s.push(e);else if(Array.isArray(e))s=s.concat(e);else if(e&&(Array.isArray(e.implicit)||Array.isArray(e.explicit)))e.implicit&&(t=t.concat(e.implicit)),e.explicit&&(s=s.concat(e.explicit));else throw new n(`Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })`);t.forEach(function(e){if(!(e instanceof r))throw new n(`Specified list of YAML types (or a single Type object) contains a non-Type object.`);if(e.loadKind&&e.loadKind!==`scalar`)throw new n(`There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.`);if(e.multi)throw new n(`There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.`)}),s.forEach(function(e){if(!(e instanceof r))throw new n(`Specified list of YAML types (or a single Type object) contains a non-Type object.`)});let c=Object.create(o.prototype);return c.implicit=(this.implicit||[]).concat(t),c.explicit=(this.explicit||[]).concat(s),c.compiledImplicit=i(c,`implicit`),c.compiledExplicit=i(c,`explicit`),c.compiledTypeMap=a(c.compiledImplicit,c.compiledExplicit),c},t.exports=o})),ge=e(((e,t)=>{t.exports=new(W())(`tag:yaml.org,2002:str`,{kind:`scalar`,construct:function(e){return e===null?``:e}})})),_e=e(((e,t)=>{t.exports=new(W())(`tag:yaml.org,2002:seq`,{kind:`sequence`,construct:function(e){return e===null?[]:e}})})),ve=e(((e,t)=>{t.exports=new(W())(`tag:yaml.org,2002:map`,{kind:`mapping`,construct:function(e){return e===null?{}:e}})})),G=e(((e,t)=>{t.exports=new(he())({explicit:[ge(),_e(),ve()]})})),ye=e(((e,t)=>{var n=W();function r(e){if(e===null)return!0;let t=e.length;return t===1&&e===`~`||t===4&&(e===`null`||e===`Null`||e===`NULL`)}function i(){return null}function a(e){return e===null}t.exports=new n(`tag:yaml.org,2002:null`,{kind:`scalar`,resolve:r,construct:i,predicate:a,represent:{canonical:function(){return`~`},lowercase:function(){return`null`},uppercase:function(){return`NULL`},camelcase:function(){return`Null`},empty:function(){return``}},defaultStyle:`lowercase`})})),K=e(((e,t)=>{var n=W();function r(e){if(e===null)return!1;let t=e.length;return t===4&&(e===`true`||e===`True`||e===`TRUE`)||t===5&&(e===`false`||e===`False`||e===`FALSE`)}function i(e){return e===`true`||e===`True`||e===`TRUE`}function a(e){return Object.prototype.toString.call(e)===`[object Boolean]`}t.exports=new n(`tag:yaml.org,2002:bool`,{kind:`scalar`,resolve:r,construct:i,predicate:a,represent:{lowercase:function(e){return e?`true`:`false`},uppercase:function(e){return e?`TRUE`:`FALSE`},camelcase:function(e){return e?`True`:`False`}},defaultStyle:`lowercase`})})),be=e(((e,t)=>{var n=fe(),r=W();function i(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function a(e){return e>=48&&e<=55}function o(e){return e>=48&&e<=57}function s(e){if(e===null)return!1;let t=e.length,n=0,r=!1;if(!t)return!1;let s=e[n];if((s===`-`||s===`+`)&&(s=e[++n]),s===`0`){if(n+1===t)return!0;if(s=e[++n],s===`b`){for(n++;n<t;n++){if(s=e[n],s!==`0`&&s!==`1`)return!1;r=!0}return r&&isFinite(c(e))}if(s===`x`){for(n++;n<t;n++){if(!i(e.charCodeAt(n)))return!1;r=!0}return r&&isFinite(c(e))}if(s===`o`){for(n++;n<t;n++){if(!a(e.charCodeAt(n)))return!1;r=!0}return r&&isFinite(c(e))}}for(;n<t;n++){if(!o(e.charCodeAt(n)))return!1;r=!0}return r?isFinite(c(e)):!1}function c(e){let t=e,n=1,r=t[0];if((r===`-`||r===`+`)&&(r===`-`&&(n=-1),t=t.slice(1),r=t[0]),t===`0`)return 0;if(r===`0`){if(t[1]===`b`)return n*parseInt(t.slice(2),2);if(t[1]===`x`)return n*parseInt(t.slice(2),16);if(t[1]===`o`)return n*parseInt(t.slice(2),8)}return n*parseInt(t,10)}function l(e){return c(e)}function u(e){return Object.prototype.toString.call(e)===`[object Number]`&&e%1==0&&!n.isNegativeZero(e)}t.exports=new r(`tag:yaml.org,2002:int`,{kind:`scalar`,resolve:s,construct:l,predicate:u,represent:{binary:function(e){return e>=0?`0b`+e.toString(2):`-0b`+e.toString(2).slice(1)},octal:function(e){return e>=0?`0o`+e.toString(8):`-0o`+e.toString(8).slice(1)},decimal:function(e){return e.toString(10)},hexadecimal:function(e){return e>=0?`0x`+e.toString(16).toUpperCase():`-0x`+e.toString(16).toUpperCase().slice(1)}},defaultStyle:`decimal`,styleAliases:{binary:[2,`bin`],octal:[8,`oct`],decimal:[10,`dec`],hexadecimal:[16,`hex`]}})})),xe=e(((e,t)=>{var n=fe(),r=W(),i=RegExp(`^(?:[-+]?(?:[0-9]+)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$`),a=RegExp(`^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$`);function o(e){return e===null||!i.test(e)?!1:isFinite(parseFloat(e,10))?!0:a.test(e)}function s(e){let t=e.toLowerCase(),n=t[0]===`-`?-1:1;return`+-`.indexOf(t[0])>=0&&(t=t.slice(1)),t===`.inf`?n===1?1/0:-1/0:t===`.nan`?NaN:n*parseFloat(t,10)}var c=/^[-+]?[0-9]+e/;function l(e,t){if(isNaN(e))switch(t){case`lowercase`:return`.nan`;case`uppercase`:return`.NAN`;case`camelcase`:return`.NaN`}else if(e===1/0)switch(t){case`lowercase`:return`.inf`;case`uppercase`:return`.INF`;case`camelcase`:return`.Inf`}else if(e===-1/0)switch(t){case`lowercase`:return`-.inf`;case`uppercase`:return`-.INF`;case`camelcase`:return`-.Inf`}else if(n.isNegativeZero(e))return`-0.0`;let r=e.toString(10);return c.test(r)?r.replace(`e`,`.e`):r}function u(e){return Object.prototype.toString.call(e)===`[object Number]`&&(e%1!=0||n.isNegativeZero(e))}t.exports=new r(`tag:yaml.org,2002:float`,{kind:`scalar`,resolve:o,construct:s,predicate:u,represent:l,defaultStyle:`lowercase`})})),Se=e(((e,t)=>{t.exports=G().extend({implicit:[ye(),K(),be(),xe()]})})),q=e(((e,t)=>{t.exports=Se()})),Ce=e(((e,t)=>{var n=W(),r=RegExp(`^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$`),i=RegExp(`^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$`);function a(e){return e===null?!1:r.exec(e)!==null||i.exec(e)!==null}function o(e){let t=0,n=null,a=r.exec(e);if(a===null&&(a=i.exec(e)),a===null)throw Error(`Date resolve error`);let o=+a[1],s=a[2]-1,c=+a[3];if(!a[4])return new Date(Date.UTC(o,s,c));let l=+a[4],u=+a[5],d=+a[6];if(a[7]){for(t=a[7].slice(0,3);t.length<3;)t+=`0`;t=+t}if(a[9]){let e=+a[10],t=+(a[11]||0);n=(e*60+t)*6e4,a[9]===`-`&&(n=-n)}let f=new Date(Date.UTC(o,s,c,l,u,d,t));return n&&f.setTime(f.getTime()-n),f}function s(e){return e.toISOString()}t.exports=new n(`tag:yaml.org,2002:timestamp`,{kind:`scalar`,resolve:a,construct:o,instanceOf:Date,represent:s})})),we=e(((e,t)=>{var n=W();function r(e){return e===`<<`||e===null}t.exports=new n(`tag:yaml.org,2002:merge`,{kind:`scalar`,resolve:r})})),Te=e(((e,t)=>{var n=W(),r=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
+\r`;function i(e){if(e===null)return!1;let t=0,n=e.length,i=r;for(let r=0;r<n;r++){let n=i.indexOf(e.charAt(r));if(!(n>64)){if(n<0)return!1;t+=6}}return t%8==0}function a(e){let t=e.replace(/[\r\n=]/g,``),n=t.length,i=r,a=0,o=[];for(let e=0;e<n;e++)e%4==0&&e&&(o.push(a>>16&255),o.push(a>>8&255),o.push(a&255)),a=a<<6|i.indexOf(t.charAt(e));let s=n%4*6;return s===0?(o.push(a>>16&255),o.push(a>>8&255),o.push(a&255)):s===18?(o.push(a>>10&255),o.push(a>>2&255)):s===12&&o.push(a>>4&255),new Uint8Array(o)}function o(e){let t=``,n=0,i=e.length,a=r;for(let r=0;r<i;r++)r%3==0&&r&&(t+=a[n>>18&63],t+=a[n>>12&63],t+=a[n>>6&63],t+=a[n&63]),n=(n<<8)+e[r];let o=i%3;return o===0?(t+=a[n>>18&63],t+=a[n>>12&63],t+=a[n>>6&63],t+=a[n&63]):o===2?(t+=a[n>>10&63],t+=a[n>>4&63],t+=a[n<<2&63],t+=a[64]):o===1&&(t+=a[n>>2&63],t+=a[n<<4&63],t+=a[64],t+=a[64]),t}function s(e){return Object.prototype.toString.call(e)===`[object Uint8Array]`}t.exports=new n(`tag:yaml.org,2002:binary`,{kind:`scalar`,resolve:i,construct:a,predicate:s,represent:o})})),Ee=e(((e,t)=>{var n=W(),r=Object.prototype.hasOwnProperty,i=Object.prototype.toString;function a(e){if(e===null)return!0;let t=[],n=e;for(let e=0,a=n.length;e<a;e+=1){let a=n[e],o=!1;if(i.call(a)!==`[object Object]`)return!1;let s;for(s in a)if(r.call(a,s))if(!o)o=!0;else return!1;if(!o)return!1;if(t.indexOf(s)===-1)t.push(s);else return!1}return!0}function o(e){return e===null?[]:e}t.exports=new n(`tag:yaml.org,2002:omap`,{kind:`sequence`,resolve:a,construct:o})})),De=e(((e,t)=>{var n=W(),r=Object.prototype.toString;function i(e){if(e===null)return!0;let t=e,n=Array(t.length);for(let e=0,i=t.length;e<i;e+=1){let i=t[e];if(r.call(i)!==`[object Object]`)return!1;let a=Object.keys(i);if(a.length!==1)return!1;n[e]=[a[0],i[a[0]]]}return!0}function a(e){if(e===null)return[];let t=e,n=Array(t.length);for(let e=0,r=t.length;e<r;e+=1){let r=t[e],i=Object.keys(r);n[e]=[i[0],r[i[0]]]}return n}t.exports=new n(`tag:yaml.org,2002:pairs`,{kind:`sequence`,resolve:i,construct:a})})),Oe=e(((e,t)=>{var n=W(),r=Object.prototype.hasOwnProperty;function i(e){if(e===null)return!0;let t=e;for(let e in t)if(r.call(t,e)&&t[e]!==null)return!1;return!0}function a(e){return e===null?{}:e}t.exports=new n(`tag:yaml.org,2002:set`,{kind:`mapping`,resolve:i,construct:a})})),ke=e(((e,t)=>{t.exports=q().extend({implicit:[Ce(),we()],explicit:[Te(),Ee(),De(),Oe()]})})),Ae=e(((e,t)=>{var n=fe(),r=pe(),i=me(),a=ke(),o=Object.prototype.hasOwnProperty,s=1,c=2,l=3,u=4,d=1,f=2,p=3,m=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,h=/[\x85\u2028\u2029]/,g=/[,\[\]{}]/,_=/^(?:!|!!|![0-9A-Za-z-]+!)$/,v=/^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;function y(e){return Object.prototype.toString.call(e)}function b(e){return e===10||e===13}function x(e){return e===9||e===32}function S(e){return e===9||e===32||e===10||e===13}function C(e){return e===44||e===91||e===93||e===123||e===125}function w(e){if(e>=48&&e<=57)return e-48;let t=e|32;return t>=97&&t<=102?t-97+10:-1}function T(e){return e===120?2:e===117?4:e===85?8:0}function E(e){return e>=48&&e<=57?e-48:-1}function D(e){switch(e){case 48:return`\0`;case 97:return`\x07`;case 98:return`\b`;case 116:return` `;case 9:return` `;case 110:return`
+`;case 118:return`\v`;case 102:return`\f`;case 114:return`\r`;case 101:return`\x1B`;case 32:return` `;case 34:return`"`;case 47:return`/`;case 92:return`\\`;case 78:return`…`;case 95:return`\xA0`;case 76:return`\u2028`;case 80:return`\u2029`;default:return``}}function O(e){return e<=65535?String.fromCharCode(e):String.fromCharCode((e-65536>>10)+55296,(e-65536&1023)+56320)}function k(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{configurable:!0,enumerable:!0,writable:!0,value:n}):e[t]=n}var A=Array(256),ee=Array(256);for(let e=0;e<256;e++)A[e]=+!!D(e),ee[e]=D(e);function j(e,t){this.input=e,this.filename=t.filename||null,this.schema=t.schema||a,this.onWarning=t.onWarning||null,this.legacy=t.legacy||!1,this.json=t.json||!1,this.listener=t.listener||null,this.maxDepth=typeof t.maxDepth==`number`?t.maxDepth:100,this.maxTotalMergeKeys=typeof t.maxTotalMergeKeys==`number`?t.maxTotalMergeKeys:1e4,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=e.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.depth=0,this.totalMergeKeys=0,this.firstTabInLine=-1,this.documents=[],this.anchorMapTransactions=[]}function M(e,t){let n={name:e.filename,buffer:e.input.slice(0,-1),position:e.position,line:e.line,column:e.position-e.lineStart};return n.snippet=i(n),new r(t,n)}function N(e,t){throw M(e,t)}function P(e,t){e.onWarning&&e.onWarning.call(null,M(e,t))}function F(e,t,n){let r=e.anchorMapTransactions;if(r.length!==0){let n=r[r.length-1];o.call(n,t)||(n[t]={existed:o.call(e.anchorMap,t),value:e.anchorMap[t]})}e.anchorMap[t]=n}function I(e){e.anchorMapTransactions.push(Object.create(null))}function te(e){let t=e.anchorMapTransactions.pop(),n=e.anchorMapTransactions;if(n.length===0)return;let r=n[n.length-1],i=Object.keys(t);for(let e=0,n=i.length;e<n;e+=1){let n=i[e];o.call(r,n)||(r[n]=t[n])}}function ne(e){let t=e.anchorMapTransactions.pop(),n=Object.keys(t);for(let r=n.length-1;r>=0;--r){let i=t[n[r]];i.existed?e.anchorMap[n[r]]=i.value:delete e.anchorMap[n[r]]}}function re(e){return{position:e.position,line:e.line,lineStart:e.lineStart,lineIndent:e.lineIndent,firstTabInLine:e.firstTabInLine,tag:e.tag,anchor:e.anchor,kind:e.kind,result:e.result}}function L(e,t){e.position=t.position,e.line=t.line,e.lineStart=t.lineStart,e.lineIndent=t.lineIndent,e.firstTabInLine=t.firstTabInLine,e.tag=t.tag,e.anchor=t.anchor,e.kind=t.kind,e.result=t.result}var ie={YAML:function(e,t,n){e.version!==null&&N(e,`duplication of %YAML directive`),n.length!==1&&N(e,`YAML directive accepts exactly one argument`);let r=/^([0-9]+)\.([0-9]+)$/.exec(n[0]);r===null&&N(e,`ill-formed argument of the YAML directive`);let i=parseInt(r[1],10),a=parseInt(r[2],10);i!==1&&N(e,`unacceptable YAML version of the document`),e.version=n[0],e.checkLineBreaks=a<2,a!==1&&a!==2&&P(e,`unsupported YAML version of the document`)},TAG:function(e,t,n){let r;n.length!==2&&N(e,`TAG directive accepts exactly two arguments`);let i=n[0];r=n[1],_.test(i)||N(e,`ill-formed tag handle (first argument) of the TAG directive`),o.call(e.tagMap,i)&&N(e,`there is a previously declared suffix for "`+i+`" tag handle`),v.test(r)||N(e,`ill-formed tag prefix (second argument) of the TAG directive`);try{r=decodeURIComponent(r)}catch{N(e,`tag prefix is malformed: `+r)}e.tagMap[i]=r}};function R(e,t,n,r){if(t<n){let i=e.input.slice(t,n);if(r)for(let t=0,n=i.length;t<n;t+=1){let n=i.charCodeAt(t);n===9||n>=32&&n<=1114111||N(e,`expected valid JSON character`)}else m.test(i)&&N(e,`the stream contains non-printable characters`);e.result+=i}}function z(e,t,r,i){n.isObject(r)||N(e,`cannot merge mappings; the provided source object is unacceptable`);let a=Object.keys(r);for(let n=0,s=a.length;n<s;n+=1){let s=a[n];e.maxTotalMergeKeys!==-1&&++e.totalMergeKeys>e.maxTotalMergeKeys&&N(e,`merge keys exceeded maxTotalMergeKeys (`+e.maxTotalMergeKeys+`)`),o.call(t,s)||(k(t,s,r[s]),i[s]=!0)}}function B(e,t,n,r,i,a,s,c,l){if(Array.isArray(i)){i=Array.prototype.slice.call(i);for(let t=0,n=i.length;t<n;t+=1)Array.isArray(i[t])&&N(e,`nested arrays are not supported inside keys`),typeof i==`object`&&y(i[t])===`[object Object]`&&(i[t]=`[object Object]`)}if(typeof i==`object`&&y(i)===`[object Object]`&&(i=`[object Object]`),i=String(i),t===null&&(t={}),r===`tag:yaml.org,2002:merge`)if(Array.isArray(a))for(let r=0,i=a.length;r<i;r+=1)z(e,t,a[r],n);else z(e,t,a,n);else !e.json&&!o.call(n,i)&&o.call(t,i)&&(e.line=s||e.line,e.lineStart=c||e.lineStart,e.position=l||e.position,N(e,`duplicated mapping key`)),k(t,i,a),delete n[i];return t}function ae(e){let t=e.input.charCodeAt(e.position);t===10?e.position++:t===13?(e.position++,e.input.charCodeAt(e.position)===10&&e.position++):N(e,`a line break is expected`),e.line+=1,e.lineStart=e.position,e.firstTabInLine=-1}function V(e,t,n){let r=0,i=e.input.charCodeAt(e.position);for(;i!==0;){for(;x(i);)i===9&&e.firstTabInLine===-1&&(e.firstTabInLine=e.position),i=e.input.charCodeAt(++e.position);if(t&&i===35)do i=e.input.charCodeAt(++e.position);while(i!==10&&i!==13&&i!==0);if(b(i))for(ae(e),i=e.input.charCodeAt(e.position),r++,e.lineIndent=0;i===32;)e.lineIndent++,i=e.input.charCodeAt(++e.position);else break}return n!==-1&&r!==0&&e.lineIndent<n&&P(e,`deficient indentation`),r}function oe(e){let t=e.position,n=e.input.charCodeAt(t);return!!((n===45||n===46)&&n===e.input.charCodeAt(t+1)&&n===e.input.charCodeAt(t+2)&&(t+=3,n=e.input.charCodeAt(t),n===0||S(n)))}function H(e,t){t===1?e.result+=` `:t>1&&(e.result+=n.repeat(`
+`,t-1))}function se(e,t,n){let r,i,a,o,s,c,l=e.kind,u=e.result,d=e.input.charCodeAt(e.position);if(S(d)||C(d)||d===35||d===38||d===42||d===33||d===124||d===62||d===39||d===34||d===37||d===64||d===96)return!1;if(d===63||d===45){let t=e.input.charCodeAt(e.position+1);if(S(t)||n&&C(t))return!1}for(e.kind=`scalar`,e.result=``,r=i=e.position,a=!1;d!==0;){if(d===58){let t=e.input.charCodeAt(e.position+1);if(S(t)||n&&C(t))break}else if(d===35){if(S(e.input.charCodeAt(e.position-1)))break}else if(e.position===e.lineStart&&oe(e)||n&&C(d))break;else if(b(d))if(o=e.line,s=e.lineStart,c=e.lineIndent,V(e,!1,-1),e.lineIndent>=t){a=!0,d=e.input.charCodeAt(e.position);continue}else{e.position=i,e.line=o,e.lineStart=s,e.lineIndent=c;break}a&&=(R(e,r,i,!1),H(e,e.line-o),r=i=e.position,!1),x(d)||(i=e.position+1),d=e.input.charCodeAt(++e.position)}return R(e,r,i,!1),e.result?!0:(e.kind=l,e.result=u,!1)}function ce(e,t){let n,r,i=e.input.charCodeAt(e.position);if(i!==39)return!1;for(e.kind=`scalar`,e.result=``,e.position++,n=r=e.position;(i=e.input.charCodeAt(e.position))!==0;)if(i===39)if(R(e,n,e.position,!0),i=e.input.charCodeAt(++e.position),i===39)n=e.position,e.position++,r=e.position;else return!0;else b(i)?(R(e,n,r,!0),H(e,V(e,!1,t)),n=r=e.position):e.position===e.lineStart&&oe(e)?N(e,`unexpected end of the document within a single quoted scalar`):(e.position++,x(i)||(r=e.position));N(e,`unexpected end of the stream within a single quoted scalar`)}function le(e,t){let n,r,i,a=e.input.charCodeAt(e.position);if(a!==34)return!1;for(e.kind=`scalar`,e.result=``,e.position++,n=r=e.position;(a=e.input.charCodeAt(e.position))!==0;)if(a===34)return R(e,n,e.position,!0),e.position++,!0;else if(a===92){if(R(e,n,e.position,!0),a=e.input.charCodeAt(++e.position),b(a))V(e,!1,t);else if(a<256&&A[a])e.result+=ee[a],e.position++;else if((i=T(a))>0){let t=i,n=0;for(;t>0;t--)a=e.input.charCodeAt(++e.position),(i=w(a))>=0?n=(n<<4)+i:N(e,`expected hexadecimal character`);e.result+=O(n),e.position++}else N(e,`unknown escape sequence`);n=r=e.position}else b(a)?(R(e,n,r,!0),H(e,V(e,!1,t)),n=r=e.position):e.position===e.lineStart&&oe(e)?N(e,`unexpected end of the document within a double quoted scalar`):(e.position++,x(a)||(r=e.position));N(e,`unexpected end of the stream within a double quoted scalar`)}function ue(e,t){let n=!0,r,i,a,o=e.tag,c,l=e.anchor,u,d,f,p,m=Object.create(null),h,g,_,v=e.input.charCodeAt(e.position);if(v===91)u=93,p=!1,c=[];else if(v===123)u=125,p=!0,c={};else return!1;for(e.anchor!==null&&F(e,e.anchor,c),v=e.input.charCodeAt(++e.position);v!==0;){if(V(e,!0,t),v=e.input.charCodeAt(e.position),v===u)return e.position++,e.tag=o,e.anchor=l,e.kind=p?`mapping`:`sequence`,e.result=c,!0;n?v===44&&N(e,`expected the node content, but found ','`):N(e,`missed comma between flow collection entries`),g=h=_=null,d=f=!1,v===63&&S(e.input.charCodeAt(e.position+1))&&(d=f=!0,e.position++,V(e,!0,t)),r=e.line,i=e.lineStart,a=e.position,G(e,t,s,!1,!0),g=e.tag,h=e.result,V(e,!0,t),v=e.input.charCodeAt(e.position),(f||e.line===r)&&v===58&&(d=!0,v=e.input.charCodeAt(++e.position),V(e,!0,t),G(e,t,s,!1,!0),_=e.result),p?B(e,c,m,g,h,_,r,i,a):d?c.push(B(e,null,m,g,h,_,r,i,a)):c.push(h),V(e,!0,t),v=e.input.charCodeAt(e.position),v===44?(n=!0,v=e.input.charCodeAt(++e.position)):n=!1}N(e,`unexpected end of the stream within a flow collection`)}function de(e,t){let r,i=d,a=!1,o=!1,s=t,c=0,l=!1,u,m=e.input.charCodeAt(e.position);if(m===124)r=!1;else if(m===62)r=!0;else return!1;for(e.kind=`scalar`,e.result=``;m!==0;)if(m=e.input.charCodeAt(++e.position),m===43||m===45)d===i?i=m===43?p:f:N(e,`repeat of a chomping mode identifier`);else if((u=E(m))>=0)u===0?N(e,`bad explicit indentation width of a block scalar; it cannot be less than one`):o?N(e,`repeat of an indentation width identifier`):(s=t+u-1,o=!0);else break;if(x(m)){do m=e.input.charCodeAt(++e.position);while(x(m));if(m===35)do m=e.input.charCodeAt(++e.position);while(!b(m)&&m!==0)}for(;m!==0;){for(ae(e),e.lineIndent=0,m=e.input.charCodeAt(e.position);(!o||e.lineIndent<s)&&m===32;)e.lineIndent++,m=e.input.charCodeAt(++e.position);if(!o&&e.lineIndent>s&&(s=e.lineIndent),b(m)){c++;continue}if(!o&&s===0&&N(e,`missing indentation for block scalar`),e.lineIndent<s){i===p?e.result+=n.repeat(`
+`,a?1+c:c):i===d&&a&&(e.result+=`
+`);break}r?x(m)?(l=!0,e.result+=n.repeat(`
+`,a?1+c:c)):l?(l=!1,e.result+=n.repeat(`
+`,c+1)):c===0?a&&(e.result+=` `):e.result+=n.repeat(`
+`,c):e.result+=n.repeat(`
+`,a?1+c:c),a=!0,o=!0,c=0;let t=e.position;for(;!b(m)&&m!==0;)m=e.input.charCodeAt(++e.position);R(e,t,e.position,!1)}return!0}function U(e,t){let n=e.tag,r=e.anchor,i=[],a=!1;if(e.firstTabInLine!==-1)return!1;e.anchor!==null&&F(e,e.anchor,i);let o=e.input.charCodeAt(e.position);for(;o!==0&&(e.firstTabInLine!==-1&&(e.position=e.firstTabInLine,N(e,`tab characters must not be used in indentation`)),!(o!==45||!S(e.input.charCodeAt(e.position+1))));){if(a=!0,e.position++,V(e,!0,-1)&&e.lineIndent<=t){i.push(null),o=e.input.charCodeAt(e.position);continue}let n=e.line;if(G(e,t,l,!1,!0),i.push(e.result),V(e,!0,-1),o=e.input.charCodeAt(e.position),(e.line===n||e.lineIndent>t)&&o!==0)N(e,`bad indentation of a sequence entry`);else if(e.lineIndent<t)break}return a?(e.tag=n,e.anchor=r,e.kind=`sequence`,e.result=i,!0):!1}function W(e,t,n){let r,i,a,o,s=e.tag,l=e.anchor,d={},f=Object.create(null),p=null,m=null,h=null,g=!1,_=!1;if(e.firstTabInLine!==-1)return!1;e.anchor!==null&&F(e,e.anchor,d);let v=e.input.charCodeAt(e.position);for(;v!==0;){!g&&e.firstTabInLine!==-1&&(e.position=e.firstTabInLine,N(e,`tab characters must not be used in indentation`));let y=e.input.charCodeAt(e.position+1),b=e.line;if((v===63||v===58)&&S(y))v===63?(g&&(B(e,d,f,p,m,null,i,a,o),p=m=h=null),_=!0,g=!0,r=!0):g?(g=!1,r=!0):N(e,`incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line`),e.position+=1,v=y;else{if(i=e.line,a=e.lineStart,o=e.position,!G(e,n,c,!1,!0))break;if(e.line===b){for(v=e.input.charCodeAt(e.position);x(v);)v=e.input.charCodeAt(++e.position);if(v===58)v=e.input.charCodeAt(++e.position),S(v)||N(e,`a whitespace character is expected after the key-value separator within a block mapping`),g&&(B(e,d,f,p,m,null,i,a,o),p=m=h=null),_=!0,g=!1,r=!1,p=e.tag,m=e.result;else if(_)N(e,`can not read an implicit mapping pair; a colon is missed`);else return e.tag=s,e.anchor=l,!0}else if(_)N(e,`can not read a block mapping entry; a multiline key may not be an implicit key`);else return e.tag=s,e.anchor=l,!0}if((e.line===b||e.lineIndent>t)&&(g&&(i=e.line,a=e.lineStart,o=e.position),G(e,t,u,!0,r)&&(g?m=e.result:h=e.result),g||(B(e,d,f,p,m,h,i,a,o),p=m=h=null),V(e,!0,-1),v=e.input.charCodeAt(e.position)),(e.line===b||e.lineIndent>t)&&v!==0)N(e,`bad indentation of a mapping entry`);else if(e.lineIndent<t)break}return g&&B(e,d,f,p,m,null,i,a,o),_&&(e.tag=s,e.anchor=l,e.kind=`mapping`,e.result=d),_}function he(e){let t=!1,n=!1,r,i,a=e.input.charCodeAt(e.position);if(a!==33)return!1;e.tag!==null&&N(e,`duplication of a tag property`),a=e.input.charCodeAt(++e.position),a===60?(t=!0,a=e.input.charCodeAt(++e.position)):a===33?(n=!0,r=`!!`,a=e.input.charCodeAt(++e.position)):r=`!`;let s=e.position;if(t){do a=e.input.charCodeAt(++e.position);while(a!==0&&a!==62);e.position<e.length?(i=e.input.slice(s,e.position),a=e.input.charCodeAt(++e.position)):N(e,`unexpected end of the stream within a verbatim tag`)}else{for(;a!==0&&!S(a);)a===33&&(n?N(e,`tag suffix cannot contain exclamation marks`):(r=e.input.slice(s-1,e.position+1),_.test(r)||N(e,`named tag handle cannot contain such characters`),n=!0,s=e.position+1)),a=e.input.charCodeAt(++e.position);i=e.input.slice(s,e.position),g.test(i)&&N(e,`tag suffix cannot contain flow indicator characters`)}i&&!v.test(i)&&N(e,`tag name cannot contain such characters: `+i);try{i=decodeURIComponent(i)}catch{N(e,`tag name is malformed: `+i)}return t?e.tag=i:o.call(e.tagMap,r)?e.tag=e.tagMap[r]+i:r===`!`?e.tag=`!`+i:r===`!!`?e.tag=`tag:yaml.org,2002:`+i:N(e,`undeclared tag handle "`+r+`"`),!0}function ge(e){let t=e.input.charCodeAt(e.position);if(t!==38)return!1;e.anchor!==null&&N(e,`duplication of an anchor property`),t=e.input.charCodeAt(++e.position);let n=e.position;for(;t!==0&&!S(t)&&!C(t);)t=e.input.charCodeAt(++e.position);return e.position===n&&N(e,`name of an anchor node must contain at least one character`),e.anchor=e.input.slice(n,e.position),!0}function _e(e){let t=e.input.charCodeAt(e.position);if(t!==42)return!1;t=e.input.charCodeAt(++e.position);let n=e.position;for(;t!==0&&!S(t)&&!C(t);)t=e.input.charCodeAt(++e.position);e.position===n&&N(e,`name of an alias node must contain at least one character`);let r=e.input.slice(n,e.position);return o.call(e.anchorMap,r)||N(e,`unidentified alias "`+r+`"`),e.result=e.anchorMap[r],V(e,!0,-1),!0}function ve(e,t,n,r){let i=re(e);return I(e),L(e,t),e.tag=null,e.anchor=null,e.kind=null,e.result=null,W(e,n,r)&&e.kind===`mapping`?(te(e),!0):(ne(e),L(e,i),!1)}function G(e,t,n,r,i){let a,d,f=1,p=!1,m=!1,h=null,g,_,v;e.depth>=e.maxDepth&&N(e,`nesting exceeded maxDepth (`+e.maxDepth+`)`),e.depth+=1,e.listener!==null&&e.listener(`open`,e),e.tag=null,e.anchor=null,e.kind=null,e.result=null;let y=a=d=u===n||l===n;if(r&&V(e,!0,-1)&&(p=!0,e.lineIndent>t?f=1:e.lineIndent===t?f=0:e.lineIndent<t&&(f=-1)),f===1)for(;;){let n=e.input.charCodeAt(e.position),r=re(e);if(p&&(n===33&&e.tag!==null||n===38&&e.anchor!==null)||!he(e)&&!ge(e))break;h===null&&(h=r),V(e,!0,-1)?(p=!0,d=y,e.lineIndent>t?f=1:e.lineIndent===t?f=0:e.lineIndent<t&&(f=-1)):d=!1}if(d&&=p||i,f===1||u===n)if(_=s===n||c===n?t:t+1,v=e.position-e.lineStart,f===1)if(d&&(U(e,v)||W(e,v,_))||ue(e,_))m=!0;else{let t=e.input.charCodeAt(e.position);h!==null&&y&&!d&&t!==124&&t!==62&&ve(e,h,h.position-h.lineStart,_)||a&&de(e,_)||ce(e,_)||le(e,_)?m=!0:_e(e)?(m=!0,(e.tag!==null||e.anchor!==null)&&N(e,`alias node should not have any properties`)):se(e,_,s===n)&&(m=!0,e.tag===null&&(e.tag=`?`)),e.anchor!==null&&F(e,e.anchor,e.result)}else f===0&&(m=d&&U(e,v));if(e.tag===null)e.anchor!==null&&F(e,e.anchor,e.result);else if(e.tag===`?`){e.result!==null&&e.kind!==`scalar`&&N(e,`unacceptable node kind for !<?> tag; it should be "scalar", not "`+e.kind+`"`);for(let t=0,n=e.implicitTypes.length;t<n;t+=1)if(g=e.implicitTypes[t],g.resolve(e.result)){e.result=g.construct(e.result),e.tag=g.tag,e.anchor!==null&&F(e,e.anchor,e.result);break}}else if(e.tag!==`!`){if(o.call(e.typeMap[e.kind||`fallback`],e.tag))g=e.typeMap[e.kind||`fallback`][e.tag];else{g=null;let t=e.typeMap.multi[e.kind||`fallback`];for(let n=0,r=t.length;n<r;n+=1)if(e.tag.slice(0,t[n].tag.length)===t[n].tag){g=t[n];break}}g||N(e,`unknown tag !<`+e.tag+`>`),e.result!==null&&g.kind!==e.kind&&N(e,`unacceptable node kind for !<`+e.tag+`> tag; it should be "`+g.kind+`", not "`+e.kind+`"`),g.resolve(e.result,e.tag)?(e.result=g.construct(e.result,e.tag),e.anchor!==null&&F(e,e.anchor,e.result)):N(e,`cannot resolve a node with !<`+e.tag+`> explicit tag`)}return e.listener!==null&&e.listener(`close`,e),--e.depth,e.tag!==null||e.anchor!==null||m}function ye(e){let t=e.position,n=!1,r;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap=Object.create(null),e.anchorMap=Object.create(null);(r=e.input.charCodeAt(e.position))!==0&&(V(e,!0,-1),r=e.input.charCodeAt(e.position),!(e.lineIndent>0||r!==37));){n=!0,r=e.input.charCodeAt(++e.position);let t=e.position;for(;r!==0&&!S(r);)r=e.input.charCodeAt(++e.position);let i=e.input.slice(t,e.position),a=[];for(i.length<1&&N(e,`directive name must not be less than one character in length`);r!==0;){for(;x(r);)r=e.input.charCodeAt(++e.position);if(r===35){do r=e.input.charCodeAt(++e.position);while(r!==0&&!b(r));break}if(b(r))break;for(t=e.position;r!==0&&!S(r);)r=e.input.charCodeAt(++e.position);a.push(e.input.slice(t,e.position))}r!==0&&ae(e),o.call(ie,i)?ie[i](e,i,a):P(e,`unknown document directive "`+i+`"`)}if(V(e,!0,-1),e.lineIndent===0&&e.input.charCodeAt(e.position)===45&&e.input.charCodeAt(e.position+1)===45&&e.input.charCodeAt(e.position+2)===45?(e.position+=3,V(e,!0,-1)):n&&N(e,`directives end mark is expected`),G(e,e.lineIndent-1,u,!1,!0),V(e,!0,-1),e.checkLineBreaks&&h.test(e.input.slice(t,e.position))&&P(e,`non-ASCII line breaks are interpreted as content`),e.documents.push(e.result),e.position===e.lineStart&&oe(e)){e.input.charCodeAt(e.position)===46&&(e.position+=3,V(e,!0,-1));return}e.position<e.length-1&&N(e,`end of the stream or a document separator is expected`)}function K(e,t){e=String(e),t||={},e.length!==0&&(e.charCodeAt(e.length-1)!==10&&e.charCodeAt(e.length-1)!==13&&(e+=`
+`),e.charCodeAt(0)===65279&&(e=e.slice(1)));let n=new j(e,t),r=e.indexOf(`\0`);for(r!==-1&&(n.position=r,N(n,`null byte is not allowed in input`)),n.input+=`\0`;n.input.charCodeAt(n.position)===32;)n.lineIndent+=1,n.position+=1;for(;n.position<n.length-1;)ye(n);return n.documents}function be(e,t,n){typeof t==`object`&&t&&n===void 0&&(n=t,t=null);let r=K(e,n);if(typeof t!=`function`)return r;for(let e=0,n=r.length;e<n;e+=1)t(r[e])}function xe(e,t){let n=K(e,t);if(n.length!==0){if(n.length===1)return n[0];throw new r(`expected a single document in the stream, but found more`)}}t.exports.loadAll=be,t.exports.load=xe})),je=e(((e,t)=>{var n=fe(),r=pe(),i=ke(),a=Object.prototype.toString,o=Object.prototype.hasOwnProperty,s=65279,c=9,l=10,u=13,d=32,f=33,p=34,m=35,h=37,g=38,_=39,v=42,y=44,b=45,x=58,S=61,C=62,w=63,T=64,E=91,D=93,O=96,k=123,A=124,ee=125,j={};j[0]=`\\0`,j[7]=`\\a`,j[8]=`\\b`,j[9]=`\\t`,j[10]=`\\n`,j[11]=`\\v`,j[12]=`\\f`,j[13]=`\\r`,j[27]=`\\e`,j[34]=`\\"`,j[92]=`\\\\`,j[133]=`\\N`,j[160]=`\\_`,j[8232]=`\\L`,j[8233]=`\\P`;var M=[`y`,`Y`,`yes`,`Yes`,`YES`,`on`,`On`,`ON`,`n`,`N`,`no`,`No`,`NO`,`off`,`Off`,`OFF`],N=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function P(e,t){if(t===null)return{};let n={},r=Object.keys(t);for(let i=0,a=r.length;i<a;i+=1){let a=r[i],s=String(t[a]);a.slice(0,2)===`!!`&&(a=`tag:yaml.org,2002:`+a.slice(2));let c=e.compiledTypeMap.fallback[a];c&&o.call(c.styleAliases,s)&&(s=c.styleAliases[s]),n[a]=s}return n}function F(e){let t,i,a=e.toString(16).toUpperCase();if(e<=255)t=`x`,i=2;else if(e<=65535)t=`u`,i=4;else if(e<=4294967295)t=`U`,i=8;else throw new r(`code point within a string may not be greater than 0xFFFFFFFF`);return`\\`+t+n.repeat(`0`,i-a.length)+a}var I=1,te=2;function ne(e){this.schema=e.schema||i,this.indent=Math.max(1,e.indent||2),this.noArrayIndent=e.noArrayIndent||!1,this.skipInvalid=e.skipInvalid||!1,this.flowLevel=n.isNothing(e.flowLevel)?-1:e.flowLevel,this.styleMap=P(this.schema,e.styles||null),this.sortKeys=e.sortKeys||!1,this.lineWidth=e.lineWidth||80,this.noRefs=e.noRefs||!1,this.noCompatMode=e.noCompatMode||!1,this.condenseFlow=e.condenseFlow||!1,this.quotingType=e.quotingType===`"`?te:I,this.forceQuotes=e.forceQuotes||!1,this.replacer=typeof e.replacer==`function`?e.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result=``,this.duplicates=[],this.usedDuplicates=null}function re(e,t){let r=n.repeat(` `,t),i=0,a=``,o=e.length;for(;i<o;){let t,n=e.indexOf(`
+`,i);n===-1?(t=e.slice(i),i=o):(t=e.slice(i,n+1),i=n+1),t.length&&t!==`
+`&&(a+=r),a+=t}return a}function L(e,t){return`
+`+n.repeat(` `,e.indent*t)}function ie(e,t){for(let n=0,r=e.implicitTypes.length;n<r;n+=1)if(e.implicitTypes[n].resolve(t))return!0;return!1}function R(e){return e===d||e===c}function z(e){return e>=32&&e<=126||e>=161&&e<=55295&&e!==8232&&e!==8233||e>=57344&&e<=65533&&e!==s||e>=65536&&e<=1114111}function B(e){return z(e)&&e!==s&&e!==u&&e!==l}function ae(e,t,n){let r=B(e),i=r&&!R(e);return(n?r:r&&e!==y&&e!==E&&e!==D&&e!==k&&e!==ee)&&e!==m&&!(t===x&&!i)||B(t)&&!R(t)&&e===m||t===x&&i}function V(e){return z(e)&&e!==s&&!R(e)&&e!==b&&e!==w&&e!==x&&e!==y&&e!==E&&e!==D&&e!==k&&e!==ee&&e!==m&&e!==g&&e!==v&&e!==f&&e!==A&&e!==S&&e!==C&&e!==_&&e!==p&&e!==h&&e!==T&&e!==O}function oe(e){return!R(e)&&e!==x}function H(e,t){let n=e.charCodeAt(t),r;return n>=55296&&n<=56319&&t+1<e.length&&(r=e.charCodeAt(t+1),r>=56320&&r<=57343)?(n-55296)*1024+r-56320+65536:n}function se(e){return/^\n* /.test(e)}var ce=1,le=2,ue=3,de=4,U=5;function me(e,t,n,r,i,a,o,s){let c,u=0,d=null,f=!1,p=!1,m=r!==-1,h=-1,g=V(H(e,0))&&oe(H(e,e.length-1));if(t||o)for(c=0;c<e.length;u>=65536?c+=2:c++){if(u=H(e,c),!z(u))return U;g&&=ae(u,d,s),d=u}else{for(c=0;c<e.length;u>=65536?c+=2:c++){if(u=H(e,c),u===l)f=!0,m&&(p||=c-h-1>r&&e[h+1]!==` `,h=c);else if(!z(u))return U;g&&=ae(u,d,s),d=u}p||=m&&c-h-1>r&&e[h+1]!==` `}return!f&&!p?g&&!o&&!i(e)?ce:a===te?U:le:n>9&&se(e)?U:o?a===te?U:le:p?de:ue}function W(e,t,n,i,a){e.dump=function(){if(t.length===0)return e.quotingType===te?`""`:`''`;if(!e.noCompatMode&&(M.indexOf(t)!==-1||N.test(t)))return e.quotingType===te?`"`+t+`"`:`'`+t+`'`;let o=e.indent*Math.max(1,n),s=e.lineWidth===-1?-1:Math.max(Math.min(e.lineWidth,40),e.lineWidth-o),c=i||e.flowLevel>-1&&n>=e.flowLevel;function l(t){return ie(e,t)}switch(me(t,c,e.indent,s,l,e.quotingType,e.forceQuotes&&!i,a)){case ce:return t;case le:return`'`+t.replace(/'/g,`''`)+`'`;case ue:return`|`+he(t,e.indent)+ge(re(t,o));case de:return`>`+he(t,e.indent)+ge(re(_e(t,s),o));case U:return`"`+G(t,s)+`"`;default:throw new r(`impossible error: invalid scalar style`)}}()}function he(e,t){let n=se(e)?String(t):``,r=e[e.length-1]===`
+`;return n+(r&&(e[e.length-2]===`
+`||e===`
+`)?`+`:r?``:`-`)+`
+`}function ge(e){return e[e.length-1]===`
+`?e.slice(0,-1):e}function _e(e,t){let n=/(\n+)([^\n]*)/g,r=function(){let r=e.indexOf(`
+`);return r=r===-1?e.length:r,n.lastIndex=r,ve(e.slice(0,r),t)}(),i=e[0]===`
+`||e[0]===` `,a,o;for(;o=n.exec(e);){let e=o[1],n=o[2];a=n[0]===` `,r+=e+(!i&&!a&&n!==``?`
+`:``)+ve(n,t),i=a}return r}function ve(e,t){if(e===``||e[0]===` `)return e;let n=/ [^ ]/g,r,i=0,a,o=0,s=0,c=``;for(;r=n.exec(e);)s=r.index,s-i>t&&(a=o>i?o:s,c+=`
+`+e.slice(i,a),i=a+1),o=s;return c+=`
+`,e.length-i>t&&o>i?c+=e.slice(i,o)+`
+`+e.slice(o+1):c+=e.slice(i),c.slice(1)}function G(e){let t=``,n=0;for(let r=0;r<e.length;n>=65536?r+=2:r++){n=H(e,r);let i=j[n];!i&&z(n)?(t+=e[r],n>=65536&&(t+=e[r+1])):t+=i||F(n)}return t}function ye(e,t,n){let r=``,i=e.tag;for(let i=0,a=n.length;i<a;i+=1){let a=n[i];e.replacer&&(a=e.replacer.call(n,String(i),a)),(q(e,t,a,!1,!1)||a===void 0&&q(e,t,null,!1,!1))&&(r!==``&&(r+=`,`+(e.condenseFlow?``:` `)),r+=e.dump)}e.tag=i,e.dump=`[`+r+`]`}function K(e,t,n,r){let i=``,a=e.tag;for(let a=0,o=n.length;a<o;a+=1){let o=n[a];e.replacer&&(o=e.replacer.call(n,String(a),o)),(q(e,t+1,o,!0,!0,!1,!0)||o===void 0&&q(e,t+1,null,!0,!0,!1,!0))&&((!r||i!==``)&&(i+=L(e,t)),e.dump&&l===e.dump.charCodeAt(0)?i+=`-`:i+=`- `,i+=e.dump)}e.tag=a,e.dump=i||`[]`}function be(e,t,n){let r=``,i=e.tag,a=Object.keys(n);for(let i=0,o=a.length;i<o;i+=1){let o=``;r!==``&&(o+=`, `),e.condenseFlow&&(o+=`"`);let s=a[i],c=n[s];e.replacer&&(c=e.replacer.call(n,s,c)),q(e,t,s,!1,!1)&&(e.dump.length>1024&&(o+=`? `),o+=e.dump+(e.condenseFlow?`"`:``)+`:`+(e.condenseFlow?``:` `),q(e,t,c,!1,!1)&&(o+=e.dump,r+=o))}e.tag=i,e.dump=`{`+r+`}`}function xe(e,t,n,i){let a=``,o=e.tag,s=Object.keys(n);if(e.sortKeys===!0)s.sort();else if(typeof e.sortKeys==`function`)s.sort(e.sortKeys);else if(e.sortKeys)throw new r(`sortKeys must be a boolean or a function`);for(let r=0,o=s.length;r<o;r+=1){let o=``;(!i||a!==``)&&(o+=L(e,t));let c=s[r],u=n[c];if(e.replacer&&(u=e.replacer.call(n,c,u)),!q(e,t+1,c,!0,!0,!0))continue;let d=e.tag!==null&&e.tag!==`?`||e.dump&&e.dump.length>1024;d&&(e.dump&&l===e.dump.charCodeAt(0)?o+=`?`:o+=`? `),o+=e.dump,d&&(o+=L(e,t)),q(e,t+1,u,!0,d)&&(e.dump&&l===e.dump.charCodeAt(0)?o+=`:`:o+=`: `,o+=e.dump,a+=o)}e.tag=o,e.dump=a||`{}`}function Se(e,t,n){let i=n?e.explicitTypes:e.implicitTypes;for(let s=0,c=i.length;s<c;s+=1){let c=i[s];if((c.instanceOf||c.predicate)&&(!c.instanceOf||typeof t==`object`&&t instanceof c.instanceOf)&&(!c.predicate||c.predicate(t))){if(n?c.multi&&c.representName?e.tag=c.representName(t):e.tag=c.tag:e.tag=`?`,c.represent){let n=e.styleMap[c.tag]||c.defaultStyle,i;if(a.call(c.represent)===`[object Function]`)i=c.represent(t,n);else if(o.call(c.represent,n))i=c.represent[n](t,n);else throw new r(`!<`+c.tag+`> tag resolver accepts not "`+n+`" style`);e.dump=i}return!0}}return!1}function q(e,t,n,i,o,s,c){e.tag=null,e.dump=n,Se(e,n,!1)||Se(e,n,!0);let l=a.call(e.dump),u=i;i&&=e.flowLevel<0||e.flowLevel>t;let d=l===`[object Object]`||l===`[object Array]`,f,p;if(d&&(f=e.duplicates.indexOf(n),p=f!==-1),(e.tag!==null&&e.tag!==`?`||p||e.indent!==2&&t>0)&&(o=!1),p&&e.usedDuplicates[f])e.dump=`*ref_`+f;else{if(d&&p&&!e.usedDuplicates[f]&&(e.usedDuplicates[f]=!0),l===`[object Object]`)i&&Object.keys(e.dump).length!==0?(xe(e,t,e.dump,o),p&&(e.dump=`&ref_`+f+e.dump)):(be(e,t,e.dump),p&&(e.dump=`&ref_`+f+` `+e.dump));else if(l===`[object Array]`)i&&e.dump.length!==0?(e.noArrayIndent&&!c&&t>0?K(e,t-1,e.dump,o):K(e,t,e.dump,o),p&&(e.dump=`&ref_`+f+e.dump)):(ye(e,t,e.dump),p&&(e.dump=`&ref_`+f+` `+e.dump));else if(l===`[object String]`)e.tag!==`?`&&W(e,e.dump,t,s,u);else if(l===`[object Undefined]`)return!1;else{if(e.skipInvalid)return!1;throw new r(`unacceptable kind of an object to dump `+l)}if(e.tag!==null&&e.tag!==`?`){let t=encodeURI(e.tag[0]===`!`?e.tag.slice(1):e.tag).replace(/!/g,`%21`);t=e.tag[0]===`!`?`!`+t:t.slice(0,18)===`tag:yaml.org,2002:`?`!!`+t.slice(18):`!<`+t+`>`,e.dump=t+` `+e.dump}}return!0}function Ce(e,t){let n=[],r=[];we(e,n,r);let i=r.length;for(let e=0;e<i;e+=1)t.duplicates.push(n[r[e]]);t.usedDuplicates=Array(i)}function we(e,t,n){if(typeof e==`object`&&e){let r=t.indexOf(e);if(r!==-1)n.indexOf(r)===-1&&n.push(r);else if(t.push(e),Array.isArray(e))for(let r=0,i=e.length;r<i;r+=1)we(e[r],t,n);else{let r=Object.keys(e);for(let i=0,a=r.length;i<a;i+=1)we(e[r[i]],t,n)}}}function Te(e,t){t||={};let n=new ne(t);n.noRefs||Ce(e,n);let r=e;return n.replacer&&(r=n.replacer.call({"":r},``,r)),q(n,0,r,!0,!0)?n.dump+`
+`:``}t.exports.dump=Te})),Me=e(((e,t)=>{var n=Ae(),r=je();function i(e,t){return function(){throw Error(`Function yaml.`+e+` is removed in js-yaml 4. Use yaml.`+t+` instead, which is now safe by default.`)}}t.exports.Type=W(),t.exports.Schema=he(),t.exports.FAILSAFE_SCHEMA=G(),t.exports.JSON_SCHEMA=Se(),t.exports.CORE_SCHEMA=q(),t.exports.DEFAULT_SCHEMA=ke(),t.exports.load=n.load,t.exports.loadAll=n.loadAll,t.exports.dump=r.dump,t.exports.YAMLException=pe(),t.exports.types={binary:Te(),float:xe(),map:ve(),null:ye(),pairs:De(),set:Oe(),timestamp:Ce(),bool:K(),int:be(),merge:we(),omap:Ee(),seq:_e(),str:ge()},t.exports.safeLoad=i(`safeLoad`,`load`),t.exports.safeLoadAll=i(`safeLoadAll`,`loadAll`),t.exports.safeDump=i(`safeDump`,`dump`)})),Ne=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Lazy=void 0,e.Lazy=class{constructor(e){this._value=null,this.creator=e}get hasValue(){return this.creator==null}get value(){if(this.creator==null)return this._value;let e=this.creator();return this.value=e,e}set value(e){this._value=e,this.creator=null}}})),Pe=e(((e,t)=>{var n=`2.0.0`,r=256;t.exports={MAX_LENGTH:r,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:r-6,MAX_SAFE_INTEGER:2**53-1||9007199254740991,RELEASE_TYPES:[`major`,`premajor`,`minor`,`preminor`,`patch`,`prepatch`,`prerelease`],SEMVER_SPEC_VERSION:n,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}})),Fe=e(((e,t)=>{t.exports=typeof process==`object`&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error(`SEMVER`,...e):()=>{}})),J=e(((e,t)=>{var{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:i}=Pe(),a=Fe();e=t.exports={};var o=e.re=[],s=e.safeRe=[],c=e.src=[],l=e.safeSrc=[],u=e.t={},d=0,f=`[a-zA-Z0-9-]`,p=[[`\\s`,1],[`\\d`,i],[f,r]],m=e=>{for(let[t,n]of p)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e},h=(e,t,n)=>{let r=m(t),i=d++;a(e,i,t),u[e]=i,c[i]=t,l[i]=r,o[i]=new RegExp(t,n?`g`:void 0),s[i]=new RegExp(r,n?`g`:void 0)};h(`NUMERICIDENTIFIER`,`0|[1-9]\\d*`),h(`NUMERICIDENTIFIERLOOSE`,`\\d+`),h(`NONNUMERICIDENTIFIER`,`\\d*[a-zA-Z-]${f}*`),h(`MAINVERSION`,`(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})`),h(`MAINVERSIONLOOSE`,`(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})`),h(`PRERELEASEIDENTIFIER`,`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIER]})`),h(`PRERELEASEIDENTIFIERLOOSE`,`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIERLOOSE]})`),h(`PRERELEASE`,`(?:-(${c[u.PRERELEASEIDENTIFIER]}(?:\\.${c[u.PRERELEASEIDENTIFIER]})*))`),h(`PRERELEASELOOSE`,`(?:-?(${c[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[u.PRERELEASEIDENTIFIERLOOSE]})*))`),h(`BUILDIDENTIFIER`,`${f}+`),h(`BUILD`,`(?:\\+(${c[u.BUILDIDENTIFIER]}(?:\\.${c[u.BUILDIDENTIFIER]})*))`),h(`FULLPLAIN`,`v?${c[u.MAINVERSION]}${c[u.PRERELEASE]}?${c[u.BUILD]}?`),h(`FULL`,`^${c[u.FULLPLAIN]}$`),h(`LOOSEPLAIN`,`[v=\\s]*${c[u.MAINVERSIONLOOSE]}${c[u.PRERELEASELOOSE]}?${c[u.BUILD]}?`),h(`LOOSE`,`^${c[u.LOOSEPLAIN]}$`),h(`GTLT`,`((?:<|>)?=?)`),h(`XRANGEIDENTIFIERLOOSE`,`${c[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h(`XRANGEIDENTIFIER`,`${c[u.NUMERICIDENTIFIER]}|x|X|\\*`),h(`XRANGEPLAIN`,`[v=\\s]*(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:${c[u.PRERELEASE]})?${c[u.BUILD]}?)?)?`),h(`XRANGEPLAINLOOSE`,`[v=\\s]*(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:${c[u.PRERELEASELOOSE]})?${c[u.BUILD]}?)?)?`),h(`XRANGE`,`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAIN]}$`),h(`XRANGELOOSE`,`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAINLOOSE]}$`),h(`COERCEPLAIN`,`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),h(`COERCE`,`${c[u.COERCEPLAIN]}(?:$|[^\\d])`),h(`COERCEFULL`,c[u.COERCEPLAIN]+`(?:${c[u.PRERELEASE]})?(?:${c[u.BUILD]})?(?:$|[^\\d])`),h(`COERCERTL`,c[u.COERCE],!0),h(`COERCERTLFULL`,c[u.COERCEFULL],!0),h(`LONETILDE`,`(?:~>?)`),h(`TILDETRIM`,`(\\s*)${c[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace=`$1~`,h(`TILDE`,`^${c[u.LONETILDE]}${c[u.XRANGEPLAIN]}$`),h(`TILDELOOSE`,`^${c[u.LONETILDE]}${c[u.XRANGEPLAINLOOSE]}$`),h(`LONECARET`,`(?:\\^)`),h(`CARETTRIM`,`(\\s*)${c[u.LONECARET]}\\s+`,!0),e.caretTrimReplace=`$1^`,h(`CARET`,`^${c[u.LONECARET]}${c[u.XRANGEPLAIN]}$`),h(`CARETLOOSE`,`^${c[u.LONECARET]}${c[u.XRANGEPLAINLOOSE]}$`),h(`COMPARATORLOOSE`,`^${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]})$|^$`),h(`COMPARATOR`,`^${c[u.GTLT]}\\s*(${c[u.FULLPLAIN]})$|^$`),h(`COMPARATORTRIM`,`(\\s*)${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]}|${c[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace=`$1$2$3`,h(`HYPHENRANGE`,`^\\s*(${c[u.XRANGEPLAIN]})\\s+-\\s+(${c[u.XRANGEPLAIN]})\\s*$`),h(`HYPHENRANGELOOSE`,`^\\s*(${c[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[u.XRANGEPLAINLOOSE]})\\s*$`),h(`STAR`,`(<|>)?=?\\s*\\*`),h(`GTE0`,`^\\s*>=\\s*0\\.0\\.0\\s*$`),h(`GTE0PRE`,`^\\s*>=\\s*0\\.0\\.0-0\\s*$`)})),Ie=e(((e,t)=>{var n=Object.freeze({loose:!0}),r=Object.freeze({});t.exports=e=>e?typeof e==`object`?e:n:r})),Le=e(((e,t)=>{var n=/^[0-9]+$/,r=(e,t)=>{if(typeof e==`number`&&typeof t==`number`)return e===t?0:e<t?-1:1;let r=n.test(e),i=n.test(t);return r&&i&&(e=+e,t=+t),e===t?0:r&&!i?-1:i&&!r?1:e<t?-1:1};t.exports={compareIdentifiers:r,rcompareIdentifiers:(e,t)=>r(t,e)}})),Y=e(((e,t)=>{var n=Fe(),{MAX_LENGTH:r,MAX_SAFE_INTEGER:i}=Pe(),{safeRe:a,t:o}=J(),s=Ie(),{compareIdentifiers:c}=Le();t.exports=class e{constructor(t,c){if(c=s(c),t instanceof e){if(t.loose===!!c.loose&&t.includePrerelease===!!c.includePrerelease)return t;t=t.version}else if(typeof t!=`string`)throw TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>r)throw TypeError(`version is longer than ${r} characters`);n(`SemVer`,t,c),this.options=c,this.loose=!!c.loose,this.includePrerelease=!!c.includePrerelease;let l=t.trim().match(c.loose?a[o.LOOSE]:a[o.FULL]);if(!l)throw TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+l[1],this.minor=+l[2],this.patch=+l[3],this.major>i||this.major<0)throw TypeError(`Invalid major version`);if(this.minor>i||this.minor<0)throw TypeError(`Invalid minor version`);if(this.patch>i||this.patch<0)throw TypeError(`Invalid patch version`);l[4]?this.prerelease=l[4].split(`.`).map(e=>{if(/^[0-9]+$/.test(e)){let t=+e;if(t>=0&&t<i)return t}return e}):this.prerelease=[],this.build=l[5]?l[5].split(`.`):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(`.`)}`),this.version}toString(){return this.version}compare(t){if(n(`SemVer.compare`,this.version,this.options,t),!(t instanceof e)){if(typeof t==`string`&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:+(this.patch>t.patch)}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let e=this.prerelease[r],i=t.prerelease[r];if(n(`prerelease compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e===i)continue;return c(e,i)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let e=this.build[r],i=t.build[r];if(n(`build compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e===i)continue;return c(e,i)}while(++r)}inc(e,t,n){if(e.startsWith(`pre`)){if(!t&&n===!1)throw Error(`invalid increment argument: identifier is empty`);if(t){let e=`-${t}`.match(this.options.loose?a[o.PRERELEASELOOSE]:a[o.PRERELEASE]);if(!e||e[1]!==t)throw Error(`invalid identifier: ${t}`)}}switch(e){case`premajor`:this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc(`pre`,t,n);break;case`preminor`:this.prerelease.length=0,this.patch=0,this.minor++,this.inc(`pre`,t,n);break;case`prepatch`:this.prerelease.length=0,this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`prerelease`:this.prerelease.length===0&&this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`release`:if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case`major`:(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case`minor`:(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case`patch`:this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case`pre`:{let e=+!!Number(n);if(this.prerelease.length===0)this.prerelease=[e];else{let r=this.prerelease.length;for(;--r>=0;)typeof this.prerelease[r]==`number`&&(this.prerelease[r]++,r=-2);if(r===-1){if(t===this.prerelease.join(`.`)&&n===!1)throw Error(`invalid increment argument: identifier already exists`);this.prerelease.push(e)}}if(t){let r=[t,e];n===!1&&(r=[t]),c(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=r):this.prerelease=r}break}default:throw Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(`.`)}`),this}}})),Re=e(((e,t)=>{var n=Y();t.exports=(e,t,r=!1)=>{if(e instanceof n)return e;try{return new n(e,t)}catch(e){if(!r)return null;throw e}}})),ze=e(((e,t)=>{var n=Re();t.exports=(e,t)=>{let r=n(e,t);return r?r.version:null}})),Be=e(((e,t)=>{var n=Re();t.exports=(e,t)=>{let r=n(e.trim().replace(/^[=v]+/,``),t);return r?r.version:null}})),Ve=e(((e,t)=>{var n=Y();t.exports=(e,t,r,i,a)=>{typeof r==`string`&&(a=i,i=r,r=void 0);try{return new n(e instanceof n?e.version:e,r).inc(t,i,a).version}catch{return null}}})),He=e(((e,t)=>{var n=Re();t.exports=(e,t)=>{let r=n(e,null,!0),i=n(t,null,!0),a=r.compare(i);if(a===0)return null;let o=a>0,s=o?r:i,c=o?i:r,l=!!s.prerelease.length;if(c.prerelease.length&&!l){if(!c.patch&&!c.minor)return`major`;if(c.compareMain(s)===0)return c.minor&&!c.patch?`minor`:`patch`}let u=l?`pre`:``;return r.major===i.major?r.minor===i.minor?r.patch===i.patch?`prerelease`:u+`patch`:u+`minor`:u+`major`}})),Ue=e(((e,t)=>{var n=Y();t.exports=(e,t)=>new n(e,t).major})),We=e(((e,t)=>{var n=Y();t.exports=(e,t)=>new n(e,t).minor})),Ge=e(((e,t)=>{var n=Y();t.exports=(e,t)=>new n(e,t).patch})),Ke=e(((e,t)=>{var n=Re();t.exports=(e,t)=>{let r=n(e,t);return r&&r.prerelease.length?r.prerelease:null}})),X=e(((e,t)=>{var n=Y();t.exports=(e,t,r)=>new n(e,r).compare(new n(t,r))})),qe=e(((e,t)=>{var n=X();t.exports=(e,t,r)=>n(t,e,r)})),Je=e(((e,t)=>{var n=X();t.exports=(e,t)=>n(e,t,!0)})),Ye=e(((e,t)=>{var n=Y();t.exports=(e,t,r)=>{let i=new n(e,r),a=new n(t,r);return i.compare(a)||i.compareBuild(a)}})),Xe=e(((e,t)=>{var n=Ye();t.exports=(e,t)=>e.sort((e,r)=>n(e,r,t))})),Ze=e(((e,t)=>{var n=Ye();t.exports=(e,t)=>e.sort((e,r)=>n(r,e,t))})),Qe=e(((e,t)=>{var n=X();t.exports=(e,t,r)=>n(e,t,r)>0})),$e=e(((e,t)=>{var n=X();t.exports=(e,t,r)=>n(e,t,r)<0})),et=e(((e,t)=>{var n=X();t.exports=(e,t,r)=>n(e,t,r)===0})),tt=e(((e,t)=>{var n=X();t.exports=(e,t,r)=>n(e,t,r)!==0})),nt=e(((e,t)=>{var n=X();t.exports=(e,t,r)=>n(e,t,r)>=0})),rt=e(((e,t)=>{var n=X();t.exports=(e,t,r)=>n(e,t,r)<=0})),it=e(((e,t)=>{var n=et(),r=tt(),i=Qe(),a=nt(),o=$e(),s=rt();t.exports=(e,t,c,l)=>{switch(t){case`===`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e===c;case`!==`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e!==c;case``:case`=`:case`==`:return n(e,c,l);case`!=`:return r(e,c,l);case`>`:return i(e,c,l);case`>=`:return a(e,c,l);case`<`:return o(e,c,l);case`<=`:return s(e,c,l);default:throw TypeError(`Invalid operator: ${t}`)}}})),at=e(((e,t)=>{var n=Y(),r=Re(),{safeRe:i,t:a}=J();t.exports=(e,t)=>{if(e instanceof n)return e;if(typeof e==`number`&&(e=String(e)),typeof e!=`string`)return null;t||={};let o=null;if(!t.rtl)o=e.match(t.includePrerelease?i[a.COERCEFULL]:i[a.COERCE]);else{let n=t.includePrerelease?i[a.COERCERTLFULL]:i[a.COERCERTL],r;for(;(r=n.exec(e))&&(!o||o.index+o[0].length!==e.length);)(!o||r.index+r[0].length!==o.index+o[0].length)&&(o=r),n.lastIndex=r.index+r[1].length+r[2].length;n.lastIndex=-1}if(o===null)return null;let s=o[2];return r(`${s}.${o[3]||`0`}.${o[4]||`0`}${t.includePrerelease&&o[5]?`-${o[5]}`:``}${t.includePrerelease&&o[6]?`+${o[6]}`:``}`,t)}})),ot=e(((e,t)=>{t.exports=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}})),Z=e(((e,t)=>{var n=/\s+/g;t.exports=class e{constructor(t,r){if(r=i(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof a)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(n,` `),this.set=this.raw.split(`||`).map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let e=this.set[0];if(this.set=this.set.filter(e=>!h(e[0])),this.set.length===0)this.set=[e];else if(this.set.length>1){for(let e of this.set)if(e.length===1&&g(e[0])){this.set=[e];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted=``;for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+=`||`);let t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=` `),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let t=((this.options.includePrerelease&&p)|(this.options.loose&&m))+`:`+e,n=r.get(t);if(n)return n;let i=this.options.loose,s=i?c[l.HYPHENRANGELOOSE]:c[l.HYPHENRANGE];e=e.replace(s,O(this.options.includePrerelease)),o(`hyphen replace`,e),e=e.replace(c[l.COMPARATORTRIM],u),o(`comparator trim`,e),e=e.replace(c[l.TILDETRIM],d),o(`tilde trim`,e),e=e.replace(c[l.CARETTRIM],f),o(`caret trim`,e);let g=e.split(` `).map(e=>v(e,this.options)).join(` `).split(/\s+/).map(e=>D(e,this.options));i&&(g=g.filter(e=>(o(`loose invalid filter`,e,this.options),!!e.match(c[l.COMPARATORLOOSE])))),o(`range list`,g);let _=new Map,y=g.map(e=>new a(e,this.options));for(let e of y){if(h(e))return[e];_.set(e.value,e)}_.size>1&&_.has(``)&&_.delete(``);let b=[..._.values()];return r.set(t,b),b}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Range is required`);return this.set.some(e=>_(e,n)&&t.set.some(t=>_(t,n)&&e.every(e=>t.every(t=>e.intersects(t,n)))))}test(e){if(!e)return!1;if(typeof e==`string`)try{e=new s(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(k(this.set[t],e,this.options))return!0;return!1}};var r=new(ot()),i=Ie(),a=Q(),o=Fe(),s=Y(),{safeRe:c,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:f}=J(),{FLAG_INCLUDE_PRERELEASE:p,FLAG_LOOSE:m}=Pe(),h=e=>e.value===`<0.0.0-0`,g=e=>e.value===``,_=(e,t)=>{let n=!0,r=e.slice(),i=r.pop();for(;n&&r.length;)n=r.every(e=>i.intersects(e,t)),i=r.pop();return n},v=(e,t)=>(e=e.replace(c[l.BUILD],``),o(`comp`,e,t),e=S(e,t),o(`caret`,e),e=b(e,t),o(`tildes`,e),e=w(e,t),o(`xrange`,e),e=E(e,t),o(`stars`,e),e),y=e=>!e||e.toLowerCase()===`x`||e===`*`,b=(e,t)=>e.trim().split(/\s+/).map(e=>x(e,t)).join(` `),x=(e,t)=>{let n=t.loose?c[l.TILDELOOSE]:c[l.TILDE];return e.replace(n,(t,n,r,i,a)=>{o(`tilde`,e,t,n,r,i,a);let s;return y(n)?s=``:y(r)?s=`>=${n}.0.0 <${+n+1}.0.0-0`:y(i)?s=`>=${n}.${r}.0 <${n}.${+r+1}.0-0`:a?(o(`replaceTilde pr`,a),s=`>=${n}.${r}.${i}-${a} <${n}.${+r+1}.0-0`):s=`>=${n}.${r}.${i} <${n}.${+r+1}.0-0`,o(`tilde return`,s),s})},S=(e,t)=>e.trim().split(/\s+/).map(e=>C(e,t)).join(` `),C=(e,t)=>{o(`caret`,e,t);let n=t.loose?c[l.CARETLOOSE]:c[l.CARET],r=t.includePrerelease?`-0`:``;return e.replace(n,(t,n,i,a,s)=>{o(`caret`,e,t,n,i,a,s);let c;return y(n)?c=``:y(i)?c=`>=${n}.0.0${r} <${+n+1}.0.0-0`:y(a)?c=n===`0`?`>=${n}.${i}.0${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.0${r} <${+n+1}.0.0-0`:s?(o(`replaceCaret pr`,s),c=n===`0`?i===`0`?`>=${n}.${i}.${a}-${s} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}-${s} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a}-${s} <${+n+1}.0.0-0`):(o(`no pr`),c=n===`0`?i===`0`?`>=${n}.${i}.${a}${r} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a} <${+n+1}.0.0-0`),o(`caret return`,c),c})},w=(e,t)=>(o(`replaceXRanges`,e,t),e.split(/\s+/).map(e=>T(e,t)).join(` `)),T=(e,t)=>{e=e.trim();let n=t.loose?c[l.XRANGELOOSE]:c[l.XRANGE];return e.replace(n,(n,r,i,a,s,c)=>{o(`xRange`,e,n,r,i,a,s,c);let l=y(i),u=l||y(a),d=u||y(s),f=d;return r===`=`&&f&&(r=``),c=t.includePrerelease?`-0`:``,l?n=r===`>`||r===`<`?`<0.0.0-0`:`*`:r&&f?(u&&(a=0),s=0,r===`>`?(r=`>=`,u?(i=+i+1,a=0,s=0):(a=+a+1,s=0)):r===`<=`&&(r=`<`,u?i=+i+1:a=+a+1),r===`<`&&(c=`-0`),n=`${r+i}.${a}.${s}${c}`):u?n=`>=${i}.0.0${c} <${+i+1}.0.0-0`:d&&(n=`>=${i}.${a}.0${c} <${i}.${+a+1}.0-0`),o(`xRange return`,n),n})},E=(e,t)=>(o(`replaceStars`,e,t),e.trim().replace(c[l.STAR],``)),D=(e,t)=>(o(`replaceGTE0`,e,t),e.trim().replace(c[t.includePrerelease?l.GTE0PRE:l.GTE0],``)),O=e=>(t,n,r,i,a,o,s,c,l,u,d,f)=>(n=y(r)?``:y(i)?`>=${r}.0.0${e?`-0`:``}`:y(a)?`>=${r}.${i}.0${e?`-0`:``}`:o?`>=${n}`:`>=${n}${e?`-0`:``}`,c=y(l)?``:y(u)?`<${+l+1}.0.0-0`:y(d)?`<${l}.${+u+1}.0-0`:f?`<=${l}.${u}.${d}-${f}`:e?`<${l}.${u}.${+d+1}-0`:`<=${c}`,`${n} ${c}`.trim()),k=(e,t,n)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!n.includePrerelease){for(let n=0;n<e.length;n++)if(o(e[n].semver),e[n].semver!==a.ANY&&e[n].semver.prerelease.length>0){let r=e[n].semver;if(r.major===t.major&&r.minor===t.minor&&r.patch===t.patch)return!0}return!1}return!0}})),Q=e(((e,t)=>{var n=Symbol(`SemVer ANY`);t.exports=class e{static get ANY(){return n}constructor(t,i){if(i=r(i),t instanceof e){if(t.loose===!!i.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(` `),s(`comparator`,t,i),this.options=i,this.loose=!!i.loose,this.parse(t),this.semver===n?this.value=``:this.value=this.operator+this.semver.version,s(`comp`,this)}parse(e){let t=this.options.loose?i[a.COMPARATORLOOSE]:i[a.COMPARATOR],r=e.match(t);if(!r)throw TypeError(`Invalid comparator: ${e}`);this.operator=r[1]===void 0?``:r[1],this.operator===`=`&&(this.operator=``),r[2]?this.semver=new c(r[2],this.options.loose):this.semver=n}toString(){return this.value}test(e){if(s(`Comparator.test`,e,this.options.loose),this.semver===n||e===n)return!0;if(typeof e==`string`)try{e=new c(e,this.options)}catch{return!1}return o(e,this.operator,this.semver,this.options)}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Comparator is required`);return this.operator===``?this.value===``?!0:new l(t.value,n).test(this.value):t.operator===``?t.value===``?!0:new l(this.value,n).test(t.semver):(n=r(n),n.includePrerelease&&(this.value===`<0.0.0-0`||t.value===`<0.0.0-0`)||!n.includePrerelease&&(this.value.startsWith(`<0.0.0`)||t.value.startsWith(`<0.0.0`))?!1:!!(this.operator.startsWith(`>`)&&t.operator.startsWith(`>`)||this.operator.startsWith(`<`)&&t.operator.startsWith(`<`)||this.semver.version===t.semver.version&&this.operator.includes(`=`)&&t.operator.includes(`=`)||o(this.semver,`<`,t.semver,n)&&this.operator.startsWith(`>`)&&t.operator.startsWith(`<`)||o(this.semver,`>`,t.semver,n)&&this.operator.startsWith(`<`)&&t.operator.startsWith(`>`)))}};var r=Ie(),{safeRe:i,t:a}=J(),o=it(),s=Fe(),c=Y(),l=Z()})),st=e(((e,t)=>{var n=Z();t.exports=(e,t,r)=>{try{t=new n(t,r)}catch{return!1}return t.test(e)}})),ct=e(((e,t)=>{var n=Z();t.exports=(e,t)=>new n(e,t).set.map(e=>e.map(e=>e.value).join(` `).trim().split(` `))})),lt=e(((e,t)=>{var n=Y(),r=Z();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===-1)&&(a=e,o=new n(a,i))}),a}})),ut=e(((e,t)=>{var n=Y(),r=Z();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===1)&&(a=e,o=new n(a,i))}),a}})),dt=e(((e,t)=>{var n=Y(),r=Z(),i=Qe();t.exports=(e,t)=>{e=new r(e,t);let a=new n(`0.0.0`);if(e.test(a)||(a=new n(`0.0.0-0`),e.test(a)))return a;a=null;for(let t=0;t<e.set.length;++t){let r=e.set[t],o=null;r.forEach(e=>{let t=new n(e.semver.version);switch(e.operator){case`>`:t.prerelease.length===0?t.patch++:t.prerelease.push(0),t.raw=t.format();case``:case`>=`:(!o||i(t,o))&&(o=t);break;case`<`:case`<=`:break;default:throw Error(`Unexpected operation: ${e.operator}`)}}),o&&(!a||i(a,o))&&(a=o)}return a&&e.test(a)?a:null}})),ft=e(((e,t)=>{var n=Z();t.exports=(e,t)=>{try{return new n(e,t).range||`*`}catch{return null}}})),pt=e(((e,t)=>{var n=Y(),r=Q(),{ANY:i}=r,a=Z(),o=st(),s=Qe(),c=$e(),l=rt(),u=nt();t.exports=(e,t,d,f)=>{e=new n(e,f),t=new a(t,f);let p,m,h,g,_;switch(d){case`>`:p=s,m=l,h=c,g=`>`,_=`>=`;break;case`<`:p=c,m=u,h=s,g=`<`,_=`<=`;break;default:throw TypeError(`Must provide a hilo val of "<" or ">"`)}if(o(e,t,f))return!1;for(let n=0;n<t.set.length;++n){let a=t.set[n],o=null,s=null;if(a.forEach(e=>{e.semver===i&&(e=new r(`>=0.0.0`)),o||=e,s||=e,p(e.semver,o.semver,f)?o=e:h(e.semver,s.semver,f)&&(s=e)}),o.operator===g||o.operator===_||(!s.operator||s.operator===g)&&m(e,s.semver)||s.operator===_&&h(e,s.semver))return!1}return!0}})),mt=e(((e,t)=>{var n=pt();t.exports=(e,t,r)=>n(e,t,`>`,r)})),ht=e(((e,t)=>{var n=pt();t.exports=(e,t,r)=>n(e,t,`<`,r)})),gt=e(((e,t)=>{var n=Z();t.exports=(e,t,r)=>(e=new n(e,r),t=new n(t,r),e.intersects(t,r))})),_t=e(((e,t)=>{var n=st(),r=X();t.exports=(e,t,i)=>{let a=[],o=null,s=null,c=e.sort((e,t)=>r(e,t,i));for(let e of c)n(e,t,i)?(s=e,o||=e):(s&&a.push([o,s]),s=null,o=null);o&&a.push([o,null]);let l=[];for(let[e,t]of a)e===t?l.push(e):!t&&e===c[0]?l.push(`*`):t?e===c[0]?l.push(`<=${t}`):l.push(`${e} - ${t}`):l.push(`>=${e}`);let u=l.join(` || `),d=typeof t.raw==`string`?t.raw:String(t);return u.length<d.length?u:t}})),vt=e(((e,t)=>{var n=Z(),r=Q(),{ANY:i}=r,a=st(),o=X(),s=(e,t,r={})=>{if(e===t)return!0;e=new n(e,r),t=new n(t,r);let i=!1;OUTER:for(let n of e.set){for(let e of t.set){let t=u(n,e,r);if(i||=t!==null,t)continue OUTER}if(i)return!1}return!0},c=[new r(`>=0.0.0-0`)],l=[new r(`>=0.0.0`)],u=(e,t,n)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===i){if(t.length===1&&t[0].semver===i)return!0;e=n.includePrerelease?c:l}if(t.length===1&&t[0].semver===i){if(n.includePrerelease)return!0;t=l}let r=new Set,s,u;for(let t of e)t.operator===`>`||t.operator===`>=`?s=d(s,t,n):t.operator===`<`||t.operator===`<=`?u=f(u,t,n):r.add(t.semver);if(r.size>1)return null;let p;if(s&&u&&(p=o(s.semver,u.semver,n),p>0||p===0&&(s.operator!==`>=`||u.operator!==`<=`)))return null;for(let e of r){if(s&&!a(e,String(s),n)||u&&!a(e,String(u),n))return null;for(let r of t)if(!a(e,String(r),n))return!1;return!0}let m,h,g,_,v=u&&!n.includePrerelease&&u.semver.prerelease.length?u.semver:!1,y=s&&!n.includePrerelease&&s.semver.prerelease.length?s.semver:!1;v&&v.prerelease.length===1&&u.operator===`<`&&v.prerelease[0]===0&&(v=!1);for(let e of t){if(_=_||e.operator===`>`||e.operator===`>=`,g=g||e.operator===`<`||e.operator===`<=`,s){if(y&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===y.major&&e.semver.minor===y.minor&&e.semver.patch===y.patch&&(y=!1),e.operator===`>`||e.operator===`>=`){if(m=d(s,e,n),m===e&&m!==s)return!1}else if(s.operator===`>=`&&!a(s.semver,String(e),n))return!1}if(u){if(v&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===v.major&&e.semver.minor===v.minor&&e.semver.patch===v.patch&&(v=!1),e.operator===`<`||e.operator===`<=`){if(h=f(u,e,n),h===e&&h!==u)return!1}else if(u.operator===`<=`&&!a(u.semver,String(e),n))return!1}if(!e.operator&&(u||s)&&p!==0)return!1}return!(s&&g&&!u&&p!==0||u&&_&&!s&&p!==0||y||v)},d=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r>0?e:r<0||t.operator===`>`&&e.operator===`>=`?t:e},f=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r<0?e:r>0||t.operator===`<`&&e.operator===`<=`?t:e};t.exports=s})),yt=e(((e,t)=>{var n=J(),r=Pe(),i=Y(),a=Le();t.exports={parse:Re(),valid:ze(),clean:Be(),inc:Ve(),diff:He(),major:Ue(),minor:We(),patch:Ge(),prerelease:Ke(),compare:X(),rcompare:qe(),compareLoose:Je(),compareBuild:Ye(),sort:Xe(),rsort:Ze(),gt:Qe(),lt:$e(),eq:et(),neq:tt(),gte:nt(),lte:rt(),cmp:it(),coerce:at(),Comparator:Q(),Range:Z(),satisfies:st(),toComparators:ct(),maxSatisfying:lt(),minSatisfying:ut(),minVersion:dt(),validRange:ft(),outside:pt(),gtr:mt(),ltr:ht(),intersects:gt(),simplifyRange:_t(),subset:vt(),SemVer:i,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:r.SEMVER_SPEC_VERSION,RELEASE_TYPES:r.RELEASE_TYPES,compareIdentifiers:a.compareIdentifiers,rcompareIdentifiers:a.rcompareIdentifiers}})),bt=e(((e,t)=>{var n=200,r=`__lodash_hash_undefined__`,i=1,a=2,o=9007199254740991,s=`[object Arguments]`,c=`[object Array]`,l=`[object AsyncFunction]`,u=`[object Boolean]`,d=`[object Date]`,f=`[object Error]`,p=`[object Function]`,m=`[object GeneratorFunction]`,h=`[object Map]`,g=`[object Number]`,_=`[object Null]`,v=`[object Object]`,y=`[object Promise]`,b=`[object Proxy]`,x=`[object RegExp]`,S=`[object Set]`,C=`[object String]`,w=`[object Symbol]`,T=`[object Undefined]`,E=`[object WeakMap]`,D=`[object ArrayBuffer]`,O=`[object DataView]`,k=`[object Float32Array]`,A=`[object Float64Array]`,ee=`[object Int8Array]`,j=`[object Int16Array]`,M=`[object Int32Array]`,N=`[object Uint8Array]`,P=`[object Uint8ClampedArray]`,F=`[object Uint16Array]`,I=`[object Uint32Array]`,te=/[\\^$.*+?()[\]{}|]/g,ne=/^\[object .+?Constructor\]$/,re=/^(?:0|[1-9]\d*)$/,L={};L[k]=L[A]=L[ee]=L[j]=L[M]=L[N]=L[P]=L[F]=L[I]=!0,L[s]=L[c]=L[D]=L[u]=L[O]=L[d]=L[f]=L[p]=L[h]=L[g]=L[v]=L[x]=L[S]=L[C]=L[E]=!1;var ie=typeof global==`object`&&global&&global.Object===Object&&global,R=typeof self==`object`&&self&&self.Object===Object&&self,z=ie||R||Function(`return this`)(),B=typeof e==`object`&&e&&!e.nodeType&&e,ae=B&&typeof t==`object`&&t&&!t.nodeType&&t,V=ae&&ae.exports===B,oe=V&&ie.process,H=function(){try{return oe&&oe.binding&&oe.binding(`util`)}catch{}}(),se=H&&H.isTypedArray;function ce(e,t){for(var n=-1,r=e==null?0:e.length,i=0,a=[];++n<r;){var o=e[n];t(o,n,e)&&(a[i++]=o)}return a}function le(e,t){for(var n=-1,r=t.length,i=e.length;++n<r;)e[i+n]=t[n];return e}function ue(e,t){for(var n=-1,r=e==null?0:e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}function de(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}function U(e){return function(t){return e(t)}}function fe(e,t){return e.has(t)}function pe(e,t){return e?.[t]}function me(e){var t=-1,n=Array(e.size);return e.forEach(function(e,r){n[++t]=[r,e]}),n}function W(e,t){return function(n){return e(t(n))}}function he(e){var t=-1,n=Array(e.size);return e.forEach(function(e){n[++t]=e}),n}var ge=Array.prototype,_e=Function.prototype,ve=Object.prototype,G=z[`__core-js_shared__`],ye=_e.toString,K=ve.hasOwnProperty,be=function(){var e=/[^.]+$/.exec(G&&G.keys&&G.keys.IE_PROTO||``);return e?`Symbol(src)_1.`+e:``}(),xe=ve.toString,Se=RegExp(`^`+ye.call(K).replace(te,`\\$&`).replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,`$1.*?`)+`$`),q=V?z.Buffer:void 0,Ce=z.Symbol,we=z.Uint8Array,Te=ve.propertyIsEnumerable,Ee=ge.splice,De=Ce?Ce.toStringTag:void 0,Oe=Object.getOwnPropertySymbols,ke=q?q.isBuffer:void 0,Ae=W(Object.keys,Object),je=$(z,`DataView`),Me=$(z,`Map`),Ne=$(z,`Promise`),Pe=$(z,`Set`),Fe=$(z,`WeakMap`),J=$(Object,`create`),Ie=Ft(je),Le=Ft(Me),Y=Ft(Ne),Re=Ft(Pe),ze=Ft(Fe),Be=Ce?Ce.prototype:void 0,Ve=Be?Be.valueOf:void 0;function He(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function Ue(){this.__data__=J?J(null):{},this.size=0}function We(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=+!!t,t}function Ge(e){var t=this.__data__;if(J){var n=t[e];return n===r?void 0:n}return K.call(t,e)?t[e]:void 0}function Ke(e){var t=this.__data__;return J?t[e]!==void 0:K.call(t,e)}function X(e,t){var n=this.__data__;return this.size+=+!this.has(e),n[e]=J&&t===void 0?r:t,this}He.prototype.clear=Ue,He.prototype.delete=We,He.prototype.get=Ge,He.prototype.has=Ke,He.prototype.set=X;function qe(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function Je(){this.__data__=[],this.size=0}function Ye(e){var t=this.__data__,n=pt(t,e);return n<0?!1:(n==t.length-1?t.pop():Ee.call(t,n,1),--this.size,!0)}function Xe(e){var t=this.__data__,n=pt(t,e);return n<0?void 0:t[n][1]}function Ze(e){return pt(this.__data__,e)>-1}function Qe(e,t){var n=this.__data__,r=pt(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}qe.prototype.clear=Je,qe.prototype.delete=Ye,qe.prototype.get=Xe,qe.prototype.has=Ze,qe.prototype.set=Qe;function $e(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function et(){this.size=0,this.__data__={hash:new He,map:new(Me||qe),string:new He}}function tt(e){var t=Et(this,e).delete(e);return this.size-=+!!t,t}function nt(e){return Et(this,e).get(e)}function rt(e){return Et(this,e).has(e)}function it(e,t){var n=Et(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}$e.prototype.clear=et,$e.prototype.delete=tt,$e.prototype.get=nt,$e.prototype.has=rt,$e.prototype.set=it;function at(e){var t=-1,n=e==null?0:e.length;for(this.__data__=new $e;++t<n;)this.add(e[t])}function ot(e){return this.__data__.set(e,r),this}function Z(e){return this.__data__.has(e)}at.prototype.add=at.prototype.push=ot,at.prototype.has=Z;function Q(e){var t=this.__data__=new qe(e);this.size=t.size}function st(){this.__data__=new qe,this.size=0}function ct(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}function lt(e){return this.__data__.get(e)}function ut(e){return this.__data__.has(e)}function dt(e,t){var r=this.__data__;if(r instanceof qe){var i=r.__data__;if(!Me||i.length<n-1)return i.push([e,t]),this.size=++r.size,this;r=this.__data__=new $e(i)}return r.set(e,t),this.size=r.size,this}Q.prototype.clear=st,Q.prototype.delete=ct,Q.prototype.get=lt,Q.prototype.has=ut,Q.prototype.set=dt;function ft(e,t){var n=Rt(e),r=!n&&Lt(e),i=!n&&!r&&Bt(e),a=!n&&!r&&!i&&Kt(e),o=n||r||i||a,s=o?de(e.length,String):[],c=s.length;for(var l in e)(t||K.call(e,l))&&!(o&&(l==`length`||i&&(l==`offset`||l==`parent`)||a&&(l==`buffer`||l==`byteLength`||l==`byteOffset`)||At(l,c)))&&s.push(l);return s}function pt(e,t){for(var n=e.length;n--;)if(It(e[n][0],t))return n;return-1}function mt(e,t,n){var r=t(e);return Rt(e)?r:le(r,n(e))}function ht(e){return e==null?e===void 0?T:_:De&&De in Object(e)?Dt(e):Pt(e)}function gt(e){return Gt(e)&&ht(e)==s}function _t(e,t,n,r,i){return e===t?!0:e==null||t==null||!Gt(e)&&!Gt(t)?e!==e&&t!==t:vt(e,t,n,r,_t,i)}function vt(e,t,n,r,a,o){var l=Rt(e),u=Rt(t),d=l?c:kt(e),f=u?c:kt(t);d=d==s?v:d,f=f==s?v:f;var p=d==v,m=f==v,h=d==f;if(h&&Bt(e)){if(!Bt(t))return!1;l=!0,p=!1}if(h&&!p)return o||=new Q,l||Kt(e)?St(e,t,n,r,a,o):Ct(e,t,d,n,r,a,o);if(!(n&i)){var g=p&&K.call(e,`__wrapped__`),_=m&&K.call(t,`__wrapped__`);if(g||_){var y=g?e.value():e,b=_?t.value():t;return o||=new Q,a(y,b,n,r,o)}}return h?(o||=new Q,wt(e,t,n,r,a,o)):!1}function yt(e){return!Wt(e)||Mt(e)?!1:(Ht(e)?Se:ne).test(Ft(e))}function bt(e){return Gt(e)&&Ut(e.length)&&!!L[ht(e)]}function xt(e){if(!Nt(e))return Ae(e);var t=[];for(var n in Object(e))K.call(e,n)&&n!=`constructor`&&t.push(n);return t}function St(e,t,n,r,o,s){var c=n&i,l=e.length,u=t.length;if(l!=u&&!(c&&u>l))return!1;var d=s.get(e);if(d&&s.get(t))return d==t;var f=-1,p=!0,m=n&a?new at:void 0;for(s.set(e,t),s.set(t,e);++f<l;){var h=e[f],g=t[f];if(r)var _=c?r(g,h,f,t,e,s):r(h,g,f,e,t,s);if(_!==void 0){if(_)continue;p=!1;break}if(m){if(!ue(t,function(e,t){if(!fe(m,t)&&(h===e||o(h,e,n,r,s)))return m.push(t)})){p=!1;break}}else if(!(h===g||o(h,g,n,r,s))){p=!1;break}}return s.delete(e),s.delete(t),p}function Ct(e,t,n,r,o,s,c){switch(n){case O:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case D:return!(e.byteLength!=t.byteLength||!s(new we(e),new we(t)));case u:case d:case g:return It(+e,+t);case f:return e.name==t.name&&e.message==t.message;case x:case C:return e==t+``;case h:var l=me;case S:var p=r&i;if(l||=he,e.size!=t.size&&!p)return!1;var m=c.get(e);if(m)return m==t;r|=a,c.set(e,t);var _=St(l(e),l(t),r,o,s,c);return c.delete(e),_;case w:if(Ve)return Ve.call(e)==Ve.call(t)}return!1}function wt(e,t,n,r,a,o){var s=n&i,c=Tt(e),l=c.length;if(l!=Tt(t).length&&!s)return!1;for(var u=l;u--;){var d=c[u];if(!(s?d in t:K.call(t,d)))return!1}var f=o.get(e);if(f&&o.get(t))return f==t;var p=!0;o.set(e,t),o.set(t,e);for(var m=s;++u<l;){d=c[u];var h=e[d],g=t[d];if(r)var _=s?r(g,h,d,t,e,o):r(h,g,d,e,t,o);if(!(_===void 0?h===g||a(h,g,n,r,o):_)){p=!1;break}m||=d==`constructor`}if(p&&!m){var v=e.constructor,y=t.constructor;v!=y&&`constructor`in e&&`constructor`in t&&!(typeof v==`function`&&v instanceof v&&typeof y==`function`&&y instanceof y)&&(p=!1)}return o.delete(e),o.delete(t),p}function Tt(e){return mt(e,qt,Ot)}function Et(e,t){var n=e.__data__;return jt(t)?n[typeof t==`string`?`string`:`hash`]:n.map}function $(e,t){var n=pe(e,t);return yt(n)?n:void 0}function Dt(e){var t=K.call(e,De),n=e[De];try{e[De]=void 0;var r=!0}catch{}var i=xe.call(e);return r&&(t?e[De]=n:delete e[De]),i}var Ot=Oe?function(e){return e==null?[]:(e=Object(e),ce(Oe(e),function(t){return Te.call(e,t)}))}:Jt,kt=ht;(je&&kt(new je(new ArrayBuffer(1)))!=O||Me&&kt(new Me)!=h||Ne&&kt(Ne.resolve())!=y||Pe&&kt(new Pe)!=S||Fe&&kt(new Fe)!=E)&&(kt=function(e){var t=ht(e),n=t==v?e.constructor:void 0,r=n?Ft(n):``;if(r)switch(r){case Ie:return O;case Le:return h;case Y:return y;case Re:return S;case ze:return E}return t});function At(e,t){return t??=o,!!t&&(typeof e==`number`||re.test(e))&&e>-1&&e%1==0&&e<t}function jt(e){var t=typeof e;return t==`string`||t==`number`||t==`symbol`||t==`boolean`?e!==`__proto__`:e===null}function Mt(e){return!!be&&be in e}function Nt(e){var t=e&&e.constructor;return e===(typeof t==`function`&&t.prototype||ve)}function Pt(e){return xe.call(e)}function Ft(e){if(e!=null){try{return ye.call(e)}catch{}try{return e+``}catch{}}return``}function It(e,t){return e===t||e!==e&&t!==t}var Lt=gt(function(){return arguments}())?gt:function(e){return Gt(e)&&K.call(e,`callee`)&&!Te.call(e,`callee`)},Rt=Array.isArray;function zt(e){return e!=null&&Ut(e.length)&&!Ht(e)}var Bt=ke||Yt;function Vt(e,t){return _t(e,t)}function Ht(e){if(!Wt(e))return!1;var t=ht(e);return t==p||t==m||t==l||t==b}function Ut(e){return typeof e==`number`&&e>-1&&e%1==0&&e<=o}function Wt(e){var t=typeof e;return e!=null&&(t==`object`||t==`function`)}function Gt(e){return typeof e==`object`&&!!e}var Kt=se?U(se):bt;function qt(e){return zt(e)?ft(e):xt(e)}function Jt(){return[]}function Yt(){return!1}t.exports=Vt})),xt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DownloadedUpdateHelper=void 0,e.createTempUpdateFile=s;var t=require("crypto"),n=require("fs"),r=bt(),i=P(),a=require("path");e.DownloadedUpdateHelper=class{constructor(e){this.cacheDir=e,this._file=null,this._packageFile=null,this.versionInfo=null,this.fileInfo=null,this._downloadedFileInfo=null}get downloadedFileInfo(){return this._downloadedFileInfo}get file(){return this._file}get packageFile(){return this._packageFile}get cacheDirForPendingUpdate(){return a.join(this.cacheDir,`pending`)}async validateDownloadedPath(e,t,n,a){if(this.versionInfo!=null&&this.file===e&&this.fileInfo!=null)return r(this.versionInfo,t)&&r(this.fileInfo.info,n.info)&&await(0,i.pathExists)(e)?e:null;let o=await this.getValidCachedUpdateFile(n,a);return o===null?null:(a.info(`Update has already been downloaded to ${e}).`),this._file=o,o)}async setDownloadedFile(e,t,n,r,a,o){this._file=e,this._packageFile=t,this.versionInfo=n,this.fileInfo=r,this._downloadedFileInfo={fileName:a,sha512:r.info.sha512,isAdminRightsRequired:r.info.isAdminRightsRequired===!0},o&&await(0,i.outputJson)(this.getUpdateInfoFile(),this._downloadedFileInfo)}async clear(){this._file=null,this._packageFile=null,this.versionInfo=null,this.fileInfo=null,await this.cleanCacheDirForPendingUpdate()}async cleanCacheDirForPendingUpdate(){try{await(0,i.emptyDir)(this.cacheDirForPendingUpdate)}catch{}}async getValidCachedUpdateFile(e,t){let n=this.getUpdateInfoFile();if(!await(0,i.pathExists)(n))return null;let r;try{r=await(0,i.readJson)(n)}catch(e){let n=`No cached update info available`;return e.code!==`ENOENT`&&(await this.cleanCacheDirForPendingUpdate(),n+=` (error on read: ${e.message})`),t.info(n),null}if(r?.fileName===null)return t.warn(`Cached update info is corrupted: no fileName, directory for cached update will be cleaned`),await this.cleanCacheDirForPendingUpdate(),null;if(e.info.sha512!==r.sha512)return t.info(`Cached update sha512 checksum doesn't match the latest available update. New update must be downloaded. Cached: ${r.sha512}, expected: ${e.info.sha512}. Directory for cached update will be cleaned`),await this.cleanCacheDirForPendingUpdate(),null;let s=a.join(this.cacheDirForPendingUpdate,r.fileName);if(!await(0,i.pathExists)(s))return t.info(`Cached update file doesn't exist`),null;let c=await o(s);return e.info.sha512===c?(this._downloadedFileInfo=r,s):(t.warn(`Sha512 checksum doesn't match the latest available update. New update must be downloaded. Cached: ${c}, expected: ${e.info.sha512}`),await this.cleanCacheDirForPendingUpdate(),null)}getUpdateInfoFile(){return a.join(this.cacheDirForPendingUpdate,`update-info.json`)}};function o(e,r=`sha512`,i=`base64`,a){return new Promise((o,s)=>{let c=(0,t.createHash)(r);c.on(`error`,s).setEncoding(i),(0,n.createReadStream)(e,{...a,highWaterMark:1024*1024}).on(`error`,s).on(`end`,()=>{c.end(),o(c.read())}).pipe(c,{end:!1})})}async function s(e,t,n){let r=0,o=a.join(t,e);for(let s=0;s<3;s++)try{return await(0,i.unlink)(o),o}catch(i){if(i.code===`ENOENT`)return o;n.warn(`Error on remove temp update file: ${i}`),o=a.join(t,`${r++}-${e}`)}return o}})),St=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getAppCacheDir=r;var t=require("path"),n=require("os");function r(){let e=(0,n.homedir)(),r;return r=process.platform===`win32`?process.env.LOCALAPPDATA||t.join(e,`AppData`,`Local`):process.platform===`darwin`?t.join(e,`Library`,`Caches`):process.env.XDG_CACHE_HOME||t.join(e,`.cache`),r}})),Ct=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ElectronAppAdapter=void 0;var t=require("path"),n=St();e.ElectronAppAdapter=class{constructor(e=require("electron").app){this.app=e}whenReady(){return this.app.whenReady()}get version(){return this.app.getVersion()}get name(){return this.app.getName()}get isPackaged(){return this.app.isPackaged===!0}get appUpdateConfigPath(){return this.isPackaged?t.join(process.resourcesPath,`app-update.yml`):t.join(this.app.getAppPath(),`dev-app-update.yml`)}get userDataPath(){return this.app.getPath(`userData`)}get baseCachePath(){return(0,n.getAppCacheDir)()}quit(){this.app.quit()}relaunch(){this.app.relaunch()}onQuit(e){this.app.once(`quit`,(t,n)=>e(n))}}})),wt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ElectronHttpExecutor=e.NET_SESSION_NAME=void 0,e.getNetSession=n;var t=U();e.NET_SESSION_NAME=`electron-updater`;function n(){return require("electron").session.fromPartition(e.NET_SESSION_NAME,{cache:!1})}e.ElectronHttpExecutor=class extends t.HttpExecutor{constructor(e){super(),this.proxyLoginCallback=e,this.cachedSession=null}async download(e,n,r){return await r.cancellationToken.createPromise((i,a,o)=>{let s={headers:r.headers||void 0,redirect:`manual`};(0,t.configureRequestUrl)(e,s),(0,t.configureRequestOptions)(s),this.doDownload(s,{destination:n,options:r,onCancel:o,callback:e=>{e==null?i(n):a(e)},responseHandler:null},0)})}createRequest(e,t){e.headers&&e.headers.Host&&(e.host=e.headers.Host,delete e.headers.Host),this.cachedSession??=n();let r=require("electron").net.request({...e,session:this.cachedSession});return r.on(`response`,t),this.proxyLoginCallback!=null&&r.on(`login`,this.proxyLoginCallback),r}addRedirectHandlers(e,n,r,i,a){e.on(`redirect`,(o,s,c)=>{e.abort(),i>this.maxRedirects?r(this.createMaxRedirectError()):a(t.HttpExecutor.prepareRedirectUrlOptions(c,n))})}}})),Tt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.newBaseUrl=n,e.newUrlFromBase=r,e.getChannelFilename=i;var t=require("url");function n(e){let n=new t.URL(e);return n.pathname.endsWith(`/`)||(n.pathname+=`/`),n}function r(e,n,r=!1){let i=new t.URL(e,n),a=n.search;return a!=null&&a.length!==0?i.search=a:r&&(i.search=`noCache=${Date.now().toString(32)}`),i}function i(e){return`${e}.yml`}})),Et=e(((e,t)=>{var n=1/0,r=`[object Symbol]`,i=/[\\^$.*+?()[\]{}|]/g,a=RegExp(i.source),o=typeof global==`object`&&global&&global.Object===Object&&global,s=typeof self==`object`&&self&&self.Object===Object&&self,c=o||s||Function(`return this`)(),l=Object.prototype.toString,u=c.Symbol,d=u?u.prototype:void 0,f=d?d.toString:void 0;function p(e){if(typeof e==`string`)return e;if(h(e))return f?f.call(e):``;var t=e+``;return t==`0`&&1/e==-n?`-0`:t}function m(e){return!!e&&typeof e==`object`}function h(e){return typeof e==`symbol`||m(e)&&l.call(e)==r}function g(e){return e==null?``:p(e)}function _(e){return e=g(e),e&&a.test(e)?e.replace(i,`\\$&`):e}t.exports=_})),$=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Provider=void 0,e.findFile=o,e.parseUpdateInfo=s,e.getFileList=c,e.resolveFiles=l;var t=U(),n=Me(),r=require("url"),i=Tt(),a=Et();e.Provider=class{constructor(e){this.runtimeOptions=e,this.requestHeaders=null,this.executor=e.executor}getBlockMapFiles(e,t,n,o=null){let s=(0,i.newUrlFromBase)(`${e.pathname}.blockmap`,e);return[(0,i.newUrlFromBase)(`${e.pathname.replace(new RegExp(a(n),`g`),t)}.blockmap`,o?new r.URL(o):e),s]}get isUseMultipleRangeRequest(){return this.runtimeOptions.isUseMultipleRangeRequest!==!1}getChannelFilePrefix(){if(this.runtimeOptions.platform===`linux`){let e=process.env.TEST_UPDATER_ARCH||process.arch;return`-linux`+(e===`x64`?``:`-${e}`)}else return this.runtimeOptions.platform===`darwin`?`-mac`:``}getDefaultChannelName(){return this.getCustomChannelName(`latest`)}getCustomChannelName(e){return`${e}${this.getChannelFilePrefix()}`}get fileExtraDownloadHeaders(){return null}setRequestHeaders(e){this.requestHeaders=e}httpRequest(e,t,n){return this.executor.request(this.createRequestOptions(e,t),n)}createRequestOptions(e,n){let r={};return this.requestHeaders==null?n!=null&&(r.headers=n):r.headers=n==null?this.requestHeaders:{...this.requestHeaders,...n},(0,t.configureRequestUrl)(e,r),r}};function o(e,n,r){if(e.length===0)throw(0,t.newError)(`No files provided`,`ERR_UPDATER_NO_FILES_PROVIDED`);let i=e.filter(e=>e.url.pathname.toLowerCase().endsWith(`.${n.toLowerCase()}`));return(i.find(e=>[e.url.pathname,e.info.url].some(e=>e.includes(process.arch)))??i.shift())||(r==null?e[0]:e.find(e=>!r.some(t=>e.url.pathname.toLowerCase().endsWith(`.${t.toLowerCase()}`))))}function s(e,r,i){if(e==null)throw(0,t.newError)(`Cannot parse update info from ${r} in the latest release artifacts (${i}): rawData: null`,`ERR_UPDATER_INVALID_UPDATE_INFO`);let a;try{a=(0,n.load)(e)}catch(n){throw(0,t.newError)(`Cannot parse update info from ${r} in the latest release artifacts (${i}): ${n.stack||n.message}, rawData: ${e}`,`ERR_UPDATER_INVALID_UPDATE_INFO`)}return a}function c(e){let n=e.files;if(n!=null&&n.length>0)return n;if(e.path!=null)return[{url:e.path,sha2:e.sha2,sha512:e.sha512}];throw(0,t.newError)(`No files provided: ${(0,t.safeStringifyJson)(e)}`,`ERR_UPDATER_NO_FILES_PROVIDED`)}function l(e,n,r=e=>e){let a=c(e).map(e=>{if(e.sha2==null&&e.sha512==null)throw(0,t.newError)(`Update info doesn't contain nor sha256 neither sha512 checksum: ${(0,t.safeStringifyJson)(e)}`,`ERR_UPDATER_NO_CHECKSUM`);return{url:(0,i.newUrlFromBase)(r(e.url),n),info:e}}),o=e.packages,s=o==null?null:o[process.arch]||o.ia32;return s!=null&&(a[0].packageInfo={...s,path:(0,i.newUrlFromBase)(r(s.path),n).href}),a}})),Dt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.GenericProvider=void 0;var t=U(),n=Tt(),r=$();e.GenericProvider=class extends r.Provider{constructor(e,t,r){super(r),this.configuration=e,this.updater=t,this.baseUrl=(0,n.newBaseUrl)(this.configuration.url)}get channel(){let e=this.updater.channel||this.configuration.channel;return e==null?this.getDefaultChannelName():this.getCustomChannelName(e)}async getLatestVersion(){let e=(0,n.getChannelFilename)(this.channel),i=(0,n.newUrlFromBase)(e,this.baseUrl,this.updater.isAddNoCacheQuery);for(let n=0;;n++)try{return(0,r.parseUpdateInfo)(await this.httpRequest(i),e,i)}catch(r){if(r instanceof t.HttpError&&r.statusCode===404)throw(0,t.newError)(`Cannot find channel "${e}" update info: ${r.stack||r.message}`,`ERR_UPDATER_CHANNEL_FILE_NOT_FOUND`);if(r.code===`ECONNREFUSED`&&n<3){await new Promise((e,t)=>{try{setTimeout(e,1e3*n)}catch(e){t(e)}});continue}throw r}}resolveFiles(e){return(0,r.resolveFiles)(e,this.baseUrl)}}})),Ot=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BitbucketProvider=void 0;var t=U(),n=Tt(),r=$();e.BitbucketProvider=class extends r.Provider{constructor(e,t,r){super({...r,isUseMultipleRangeRequest:!1}),this.configuration=e,this.updater=t;let{owner:i,slug:a}=e;this.baseUrl=(0,n.newBaseUrl)(`https://api.bitbucket.org/2.0/repositories/${i}/${a}/downloads`)}get channel(){return this.updater.channel||this.configuration.channel||`latest`}async getLatestVersion(){let e=new t.CancellationToken,i=(0,n.getChannelFilename)(this.getCustomChannelName(this.channel)),a=(0,n.newUrlFromBase)(i,this.baseUrl,this.updater.isAddNoCacheQuery);try{let t=await this.httpRequest(a,void 0,e);return(0,r.parseUpdateInfo)(t,i,a)}catch(e){throw(0,t.newError)(`Unable to find latest version on ${this.toString()}, please ensure release exists: ${e.stack||e.message}`,`ERR_UPDATER_LATEST_VERSION_NOT_FOUND`)}}resolveFiles(e){return(0,r.resolveFiles)(e,this.baseUrl)}toString(){let{owner:e,slug:t}=this.configuration;return`Bitbucket (owner: ${e}, slug: ${t}, channel: ${this.channel})`}}})),kt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.GitHubProvider=e.BaseGitHubProvider=void 0,e.computeReleaseNotes=l;var t=U(),n=yt(),r=require("url"),i=Tt(),a=$(),o=/\/tag\/(v?[^/]+)$/,s=class extends a.Provider{constructor(e,n,r){super({...r,isUseMultipleRangeRequest:!1}),this.options=e,this.baseUrl=(0,i.newBaseUrl)((0,t.githubUrl)(e,n));let a=n===`github.com`?`api.github.com`:n;this.baseApiUrl=(0,i.newBaseUrl)((0,t.githubUrl)(e,a))}computeGithubBasePath(e){let t=this.options.host;return t&&![`github.com`,`api.github.com`].includes(t)?`/api/v3${e}`:e}};e.BaseGitHubProvider=s,e.GitHubProvider=class extends s{constructor(e,t,n){super(e,`github.com`,n),this.options=e,this.updater=t}get channel(){let e=this.updater.channel||this.options.channel;return e==null?this.getDefaultChannelName():this.getCustomChannelName(e)}async getLatestVersion(){let e=new t.CancellationToken,r=await this.httpRequest((0,i.newUrlFromBase)(`${this.basePath}.atom`,this.baseUrl),{accept:`application/xml, application/atom+xml, text/xml, */*`},e),s=(0,t.parseXml)(r),c=s.element(`entry`,!1,`No published versions on GitHub`),u=null;try{if(this.updater.allowPrerelease){let e=this.updater?.channel||n.prerelease(this.updater.currentVersion)?.[0]||null;if(e===null)u=o.exec(c.element(`link`).attribute(`href`))[1];else for(let t of s.getElements(`entry`)){let r=o.exec(t.element(`link`).attribute(`href`));if(r===null)continue;let i=r[1];if(!n.valid(i))continue;let a=n.prerelease(i)?.[0]||null,s=!e||[`alpha`,`beta`].includes(e),l=a!==null&&![`alpha`,`beta`].includes(String(a));if(s&&!l&&!(e===`beta`&&a===`alpha`)){u=i,c=t;break}if(a&&a===e){u=i,c=t;break}}}else{u=await this.getLatestTagName(e);for(let e of s.getElements(`entry`)){let t=o.exec(e.element(`link`).attribute(`href`));if(t!=null&&t[1]===u){c=e;break}}}}catch(e){throw(0,t.newError)(`Cannot parse releases feed: ${e.stack||e.message},\nXML:\n${r}`,`ERR_UPDATER_INVALID_RELEASE_FEED`)}if(u==null)throw(0,t.newError)(`No published versions on GitHub`,`ERR_UPDATER_NO_PUBLISHED_VERSIONS`);let d,f=``,p=``,m=async n=>{f=(0,i.getChannelFilename)(n),p=(0,i.newUrlFromBase)(this.getBaseDownloadPath(String(u),f),this.baseUrl);let r=this.createRequestOptions(p);try{return await this.executor.request(r,e)}catch(e){throw e instanceof t.HttpError&&e.statusCode===404?(0,t.newError)(`Cannot find ${f} in the latest release artifacts (${p}): ${e.stack||e.message}`,`ERR_UPDATER_CHANNEL_FILE_NOT_FOUND`):e}};try{let e=this.channel;this.updater.allowPrerelease&&n.prerelease(u)?.[0]&&(e=this.getCustomChannelName(String(n.prerelease(u)?.[0]))),d=await m(e)}catch(e){if(this.updater.allowPrerelease)d=await m(this.getDefaultChannelName());else throw e}let h=(0,a.parseUpdateInfo)(d,f,p);return h.releaseName??=c.elementValueOrEmpty(`title`),h.releaseNotes??=l(this.updater.currentVersion,this.updater.fullChangelog,s,c),{tag:u,...h}}async getLatestTagName(e){let n=this.options,a=n.host==null||n.host===`github.com`?(0,i.newUrlFromBase)(`${this.basePath}/latest`,this.baseUrl):new r.URL(`${this.computeGithubBasePath(`/repos/${n.owner}/${n.repo}/releases`)}/latest`,this.baseApiUrl);try{let t=await this.httpRequest(a,{Accept:`application/json`},e);return t==null?null:JSON.parse(t).tag_name}catch(e){throw(0,t.newError)(`Unable to find latest version on GitHub (${a}), please ensure a production release exists: ${e.stack||e.message}`,`ERR_UPDATER_LATEST_VERSION_NOT_FOUND`)}}get basePath(){return`/${this.options.owner}/${this.options.repo}/releases`}resolveFiles(e){return(0,a.resolveFiles)(e,this.baseUrl,t=>this.getBaseDownloadPath(e.tag,t.replace(/ /g,`-`)))}getBaseDownloadPath(e,t){return`${this.basePath}/download/${e}/${t}`}};function c(e){let t=e.elementValueOrEmpty(`content`);return t===`No content.`?``:t}function l(e,t,r,i){if(!t)return c(i);let a=/\/tag\/v?([^/]+)$/,o;try{o=a.exec(i.element(`link`).attribute(`href`))[1],o=n.valid(o)?o:void 0}catch{}if(o==null)return null;let s=[];for(let t of r.getElements(`entry`)){let r;try{let e=a.exec(t.element(`link`).attribute(`href`));if(!e)continue;r=e[1]}catch{continue}if(!n.valid(r))continue;let i=n.gt(r,e.raw),l=n.lte(r,o);i&&l&&s.push({version:r,note:c(t)})}return s.sort((e,t)=>n.rcompare(e.version,t.version))}})),At=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.GitLabProvider=void 0;var t=U(),n=require("url"),r=Et(),i=Tt(),a=$();e.GitLabProvider=class extends a.Provider{normalizeFilename(e){return e.replace(/ |_/g,`-`)}constructor(e,t,n){super({...n,isUseMultipleRangeRequest:!1}),this.options=e,this.updater=t,this.cachedLatestVersion=null;let r=e.host||`gitlab.com`;this.baseApiUrl=(0,i.newBaseUrl)(`https://${r}/api/v4`)}createRequestOptions(e,t){let n=super.createRequestOptions(e,t);return n.redirect=`manual`,n}get channel(){let e=this.updater.channel||this.options.channel;return e==null?this.getDefaultChannelName():this.getCustomChannelName(e)}async getLatestVersion(){let e=new t.CancellationToken,r=(0,i.newUrlFromBase)(`projects/${this.options.projectId}/releases/permalink/latest`,this.baseApiUrl),o={Accept:`application/json`,...this.setAuthHeaderForToken(this.options.token||null)},s;try{s=await this.httpRequest(r,o,e)}catch(e){throw(0,t.newError)(`Unable to find latest release on GitLab (${r}): ${e.stack||e.message}`,`ERR_UPDATER_LATEST_VERSION_NOT_FOUND`)}if(!s)throw(0,t.newError)(`No published releases on GitLab`,`ERR_UPDATER_NO_PUBLISHED_VERSIONS`);let c;try{c=JSON.parse(s)}catch(e){throw(0,t.newError)(`Unable to parse latest release response from GitLab (${r}): response was not valid JSON: ${e.stack||e.message}`,`ERR_UPDATER_LATEST_VERSION_NOT_FOUND`)}if(c.upcoming_release)throw(0,t.newError)(`Latest GitLab release is scheduled but not yet published`,`ERR_UPDATER_LATEST_VERSION_NOT_FOUND`);let l=c.tag_name,u=null,d=``,f=null,p=async r=>{d=(0,i.getChannelFilename)(r);let a=c.assets.links.find(e=>e.name===d);if(!a)throw(0,t.newError)(`Cannot find ${d} in the latest release assets`,`ERR_UPDATER_CHANNEL_FILE_NOT_FOUND`);f=new n.URL(a.direct_asset_url);let o=this.setAuthHeaderForToken(this.options.token||null),s=Object.keys(o).length?o:void 0;try{let n=await this.httpRequest(f,s,e);if(!n)throw(0,t.newError)(`Empty response from ${f}`,`ERR_UPDATER_CHANNEL_FILE_NOT_FOUND`);return n}catch(e){throw e instanceof t.HttpError&&e.statusCode===404?(0,t.newError)(`Cannot find ${d} in the latest release artifacts (${f}): ${e.stack||e.message}`,`ERR_UPDATER_CHANNEL_FILE_NOT_FOUND`):e}};try{u=await p(this.channel)}catch(e){if(this.channel!==this.getDefaultChannelName())u=await p(this.getDefaultChannelName());else throw e}if(!u)throw(0,t.newError)(`Unable to parse channel data from ${d}`,`ERR_UPDATER_INVALID_UPDATE_INFO`);let m=(0,a.parseUpdateInfo)(u,d,f);m.releaseName??=c.name,m.releaseNotes??=c.description||null;let h={tag:l,assets:this.convertAssetsToMap(c.assets),...m};return this.cachedLatestVersion=h,h}convertAssetsToMap(e){let t=new Map;for(let n of e.links)t.set(this.normalizeFilename(n.name),n.direct_asset_url);return t}findBlockMapInAssets(e,t){let r=[`${t}.blockmap`,`${this.normalizeFilename(t)}.blockmap`];for(let t of r){let r=e.get(t);if(r)return new n.URL(r)}return null}async fetchReleaseInfoByVersion(e){let n=new t.CancellationToken,r=[`v${e}`,e];for(let e of r){let r=(0,i.newUrlFromBase)(`projects/${this.options.projectId}/releases/${encodeURIComponent(e)}`,this.baseApiUrl);try{let e={Accept:`application/json`,...this.setAuthHeaderForToken(this.options.token||null)},t=await this.httpRequest(r,e,n);if(t)return JSON.parse(t)}catch(n){if(n instanceof t.HttpError&&n.statusCode===404)continue;throw(0,t.newError)(`Unable to find release ${e} on GitLab (${r}): ${n.stack||n.message}`,`ERR_UPDATER_RELEASE_NOT_FOUND`)}}throw(0,t.newError)(`Unable to find release with version ${e} (tried: ${r.join(`, `)}) on GitLab`,`ERR_UPDATER_RELEASE_NOT_FOUND`)}setAuthHeaderForToken(e){let t={};return e!=null&&(e.startsWith(`Bearer`)?t.authorization=e:t[`PRIVATE-TOKEN`]=e),t}async getVersionInfoForBlockMap(e){if(this.cachedLatestVersion&&this.cachedLatestVersion.version===e)return this.cachedLatestVersion.assets;let t=await this.fetchReleaseInfoByVersion(e);return t&&t.assets?this.convertAssetsToMap(t.assets):null}async findBlockMapUrlsFromAssets(e,t,n){let i=null,a=null,o=await this.getVersionInfoForBlockMap(t);o&&(i=this.findBlockMapInAssets(o,n));let s=await this.getVersionInfoForBlockMap(e);if(s){let i=n.replace(new RegExp(r(t),`g`),e);a=this.findBlockMapInAssets(s,i)}return[a,i]}async getBlockMapFiles(e,n,r,i=null){if(this.options.uploadTarget===`project_upload`){let i=e.pathname.split(`/`).pop()||``,[a,o]=await this.findBlockMapUrlsFromAssets(n,r,i);if(!o)throw(0,t.newError)(`Cannot find blockmap file for ${r} in GitLab assets`,`ERR_UPDATER_BLOCKMAP_FILE_NOT_FOUND`);if(!a)throw(0,t.newError)(`Cannot find blockmap file for ${n} in GitLab assets`,`ERR_UPDATER_BLOCKMAP_FILE_NOT_FOUND`);return[a,o]}else return super.getBlockMapFiles(e,n,r,i)}resolveFiles(e){return(0,a.getFileList)(e).map(r=>{let i=[r.url,this.normalizeFilename(r.url)].find(t=>e.assets.has(t)),a=i?e.assets.get(i):void 0;if(!a)throw(0,t.newError)(`Cannot find asset "${r.url}" in GitLab release assets. Available assets: ${Array.from(e.assets.keys()).join(`, `)}`,`ERR_UPDATER_ASSET_NOT_FOUND`);return{url:new n.URL(a),info:r}})}toString(){return`GitLab (projectId: ${this.options.projectId}, channel: ${this.channel})`}}})),jt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.KeygenProvider=void 0;var t=U(),n=Tt(),r=$();e.KeygenProvider=class extends r.Provider{constructor(e,t,r){super({...r,isUseMultipleRangeRequest:!1}),this.configuration=e,this.updater=t,this.defaultHostname=`api.keygen.sh`;let i=this.configuration.host||this.defaultHostname;this.baseUrl=(0,n.newBaseUrl)(`https://${i}/v1/accounts/${this.configuration.account}/artifacts?product=${this.configuration.product}`)}get channel(){return this.updater.channel||this.configuration.channel||`stable`}async getLatestVersion(){let e=new t.CancellationToken,i=(0,n.getChannelFilename)(this.getCustomChannelName(this.channel)),a=(0,n.newUrlFromBase)(i,this.baseUrl,this.updater.isAddNoCacheQuery);try{let t=await this.httpRequest(a,{Accept:`application/vnd.api+json`,"Keygen-Version":`1.1`},e);return(0,r.parseUpdateInfo)(t,i,a)}catch(e){throw(0,t.newError)(`Unable to find latest version on ${this.toString()}, please ensure release exists: ${e.stack||e.message}`,`ERR_UPDATER_LATEST_VERSION_NOT_FOUND`)}}resolveFiles(e){return(0,r.resolveFiles)(e,this.baseUrl)}toString(){let{account:e,product:t,platform:n}=this.configuration;return`Keygen (account: ${e}, product: ${t}, platform: ${n}, channel: ${this.channel})`}}})),Mt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PrivateGitHubProvider=void 0;var t=U(),n=Me(),r=require("path"),i=require("url"),a=Tt(),o=kt(),s=$();e.PrivateGitHubProvider=class extends o.BaseGitHubProvider{constructor(e,t,n,r){super(e,`api.github.com`,r),this.updater=t,this.token=n}createRequestOptions(e,t){let n=super.createRequestOptions(e,t);return n.redirect=`manual`,n}async getLatestVersion(){let e=new t.CancellationToken,r=(0,a.getChannelFilename)(this.getDefaultChannelName()),o=await this.getLatestVersionInfo(e),s=o.assets.find(e=>e.name===r);if(s==null)throw(0,t.newError)(`Cannot find ${r} in the release ${o.html_url||o.name}`,`ERR_UPDATER_CHANNEL_FILE_NOT_FOUND`);let c=new i.URL(s.url),l;try{l=(0,n.load)(await this.httpRequest(c,this.configureHeaders(`application/octet-stream`),e))}catch(e){throw e instanceof t.HttpError&&e.statusCode===404?(0,t.newError)(`Cannot find ${r} in the latest release artifacts (${c}): ${e.stack||e.message}`,`ERR_UPDATER_CHANNEL_FILE_NOT_FOUND`):e}return l.assets=o.assets,l}get fileExtraDownloadHeaders(){return this.configureHeaders(`application/octet-stream`)}configureHeaders(e){return{accept:e,authorization:`token ${this.token}`}}async getLatestVersionInfo(e){let n=this.updater.allowPrerelease,r=this.basePath;n||(r=`${r}/latest`);let i=(0,a.newUrlFromBase)(r,this.baseUrl);try{let t=JSON.parse(await this.httpRequest(i,this.configureHeaders(`application/vnd.github.v3+json`),e));if(n){let e=t.filter(e=>!e.draft);return e.find(e=>e.prerelease)||e[0]}else return t}catch(e){throw(0,t.newError)(`Unable to find latest version on GitHub (${i}), please ensure a production release exists: ${e.stack||e.message}`,`ERR_UPDATER_LATEST_VERSION_NOT_FOUND`)}}get basePath(){return this.computeGithubBasePath(`/repos/${this.options.owner}/${this.options.repo}/releases`)}resolveFiles(e){return(0,s.getFileList)(e).map(n=>{let a=r.posix.basename(n.url).replace(/ /g,`-`),o=e.assets.find(e=>e!=null&&e.name===a);if(o==null)throw(0,t.newError)(`Cannot find asset "${a}" in: ${JSON.stringify(e.assets,null,2)}`,`ERR_UPDATER_ASSET_NOT_FOUND`);return{url:new i.URL(o.url),info:n}})}}})),Nt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.isUrlProbablySupportMultiRangeRequests=c,e.createClient=l;var t=U(),n=Ot(),r=Dt(),i=kt(),a=At(),o=jt(),s=Mt();function c(e){return!e.includes(`s3.amazonaws.com`)}function l(e,l,u){if(typeof e==`string`)throw(0,t.newError)(`Please pass PublishConfiguration object`,`ERR_UPDATER_INVALID_PROVIDER_CONFIGURATION`);let d=e.provider;switch(d){case`github`:{let t=e,n=(t.private?process.env.GH_TOKEN||process.env.GITHUB_TOKEN:null)||t.token;return n==null?new i.GitHubProvider(t,l,u):new s.PrivateGitHubProvider(t,l,n,u)}case`bitbucket`:return new n.BitbucketProvider(e,l,u);case`gitlab`:return new a.GitLabProvider(e,l,u);case`keygen`:return new o.KeygenProvider(e,l,u);case`s3`:case`spaces`:return new r.GenericProvider({provider:`generic`,url:(0,t.getS3LikeProviderBaseUrl)(e),channel:e.channel||null},l,{...u,isUseMultipleRangeRequest:!1});case`generic`:{let t=e;return new r.GenericProvider(t,l,{...u,isUseMultipleRangeRequest:t.useMultipleRangeRequest!==!1&&c(t.url)})}case`custom`:{let n=e,r=n.updateProvider;if(!r)throw(0,t.newError)(`Custom provider not specified`,`ERR_UPDATER_INVALID_PROVIDER_CONFIGURATION`);return new r(n,l,u)}default:throw(0,t.newError)(`Unsupported provider: ${d}`,`ERR_UPDATER_UNSUPPORTED_PROVIDER`)}}})),Pt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.OperationKind=void 0,e.computeOperations=n;var t;(function(e){e[e.COPY=0]=`COPY`,e[e.DOWNLOAD=1]=`DOWNLOAD`})(t||(e.OperationKind=t={}));function n(e,n,r){let s=o(e.files),c=o(n.files),l=null,u=n.files[0],d=[],f=u.name,p=s.get(f);if(p==null)throw Error(`no file ${f} in old blockmap`);let m=c.get(f),h=0,{checksumToOffset:g,checksumToOldSize:_}=a(s.get(f),p.offset,r),v=u.offset;for(let e=0;e<m.checksums.length;v+=m.sizes[e],e++){let n=m.sizes[e],a=m.checksums[e],o=g.get(a);o!=null&&_.get(a)!==n&&(r.warn(`Checksum ("${a}") matches, but size differs (old: ${_.get(a)}, new: ${n})`),o=void 0),o===void 0?(h++,l!=null&&l.kind===t.DOWNLOAD&&l.end===v?l.end+=n:(l={kind:t.DOWNLOAD,start:v,end:v+n},i(l,d,a,e))):l!=null&&l.kind===t.COPY&&l.end===o?l.end+=n:(l={kind:t.COPY,start:o,end:o+n},i(l,d,a,e))}return h>0&&r.info(`File${u.name===`file`?``:` `+u.name} has ${h} changed blocks`),d}var r=process.env.DIFFERENTIAL_DOWNLOAD_PLAN_BUILDER_VALIDATE_RANGES===`true`;function i(e,n,i,a){if(r&&n.length!==0){let r=n[n.length-1];if(r.kind===e.kind&&e.start<r.end&&e.start>r.start){let n=[r.start,r.end,e.start,e.end].reduce((e,t)=>e<t?e:t);throw Error(`operation (block index: ${a}, checksum: ${i}, kind: ${t[e.kind]}) overlaps previous operation (checksum: ${i}):\nabs: ${r.start} until ${r.end} and ${e.start} until ${e.end}\nrel: ${r.start-n} until ${r.end-n} and ${e.start-n} until ${e.end-n}`)}}n.push(e)}function a(e,t,n){let r=new Map,i=new Map,a=t;for(let t=0;t<e.checksums.length;t++){let o=e.checksums[t],s=e.sizes[t],c=i.get(o);if(c===void 0)r.set(o,a),i.set(o,s);else if(n.debug!=null){let e=c===s?`(same size)`:`(size: ${c}, this size: ${s})`;n.debug(`${o} duplicated in blockmap ${e}, it doesn't lead to broken differential downloader, just corresponding block will be skipped)`)}a+=s}return{checksumToOffset:r,checksumToOldSize:i}}function o(e){let t=new Map;for(let n of e)t.set(n.name,n);return t}})),Ft=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DataSplitter=void 0,e.copyData=s;var t=U(),n=require("fs"),r=require("stream"),i=Pt(),a=Buffer.from(`\r
+\r
+`),o;(function(e){e[e.INIT=0]=`INIT`,e[e.HEADER=1]=`HEADER`,e[e.BODY=2]=`BODY`})(o||={});function s(e,t,r,i,a){let o=(0,n.createReadStream)(``,{fd:r,autoClose:!1,start:e.start,end:e.end-1});o.on(`error`,i),o.once(`end`,a),o.pipe(t,{end:!1})}e.DataSplitter=class extends r.Writable{constructor(e,t,n,r,i,a,s,c){super(),this.out=e,this.options=t,this.partIndexToTaskIndex=n,this.partIndexToLength=i,this.finishHandler=a,this.grandTotalBytes=s,this.onProgress=c,this.start=Date.now(),this.nextUpdate=this.start+1e3,this.transferred=0,this.delta=0,this.partIndex=-1,this.headerListBuffer=null,this.readState=o.INIT,this.ignoreByteCount=0,this.remainingPartDataCount=0,this.actualPartLength=0,this.boundaryLength=r.length+4,this.ignoreByteCount=this.boundaryLength-2}get isFinished(){return this.partIndex===this.partIndexToLength.length}_write(e,t,n){if(this.isFinished){console.error(`Trailing ignored data: ${e.length} bytes`);return}this.handleData(e).then(()=>{if(this.onProgress){let e=Date.now();(e>=this.nextUpdate||this.transferred===this.grandTotalBytes)&&this.grandTotalBytes&&(e-this.start)/1e3&&(this.nextUpdate=e+1e3,this.onProgress({total:this.grandTotalBytes,delta:this.delta,transferred:this.transferred,percent:this.transferred/this.grandTotalBytes*100,bytesPerSecond:Math.round(this.transferred/((e-this.start)/1e3))}),this.delta=0)}n()}).catch(n)}async handleData(e){let n=0;if(this.ignoreByteCount!==0&&this.remainingPartDataCount!==0)throw(0,t.newError)(`Internal error`,`ERR_DATA_SPLITTER_BYTE_COUNT_MISMATCH`);if(this.ignoreByteCount>0){let t=Math.min(this.ignoreByteCount,e.length);this.ignoreByteCount-=t,n=t}else if(this.remainingPartDataCount>0){let t=Math.min(this.remainingPartDataCount,e.length);this.remainingPartDataCount-=t,await this.processPartData(e,0,t),n=t}if(n!==e.length){if(this.readState===o.HEADER){let t=this.searchHeaderListEnd(e,n);if(t===-1)return;n=t,this.readState=o.BODY,this.headerListBuffer=null}for(;;){if(this.readState===o.BODY)this.readState=o.INIT;else{this.partIndex++;let r=this.partIndexToTaskIndex.get(this.partIndex);if(r==null)if(this.isFinished)r=this.options.end;else throw(0,t.newError)(`taskIndex is null`,`ERR_DATA_SPLITTER_TASK_INDEX_IS_NULL`);let i=this.partIndex===0?this.options.start:this.partIndexToTaskIndex.get(this.partIndex-1)+1;if(i<r)await this.copyExistingData(i,r);else if(i>r)throw(0,t.newError)(`prevTaskIndex must be < taskIndex`,`ERR_DATA_SPLITTER_TASK_INDEX_ASSERT_FAILED`);if(this.isFinished){this.onPartEnd(),this.finishHandler();return}if(n=this.searchHeaderListEnd(e,n),n===-1){this.readState=o.HEADER;return}}let r=this.partIndexToLength[this.partIndex],i=n+r,a=Math.min(i,e.length);if(await this.processPartStarted(e,n,a),this.remainingPartDataCount=r-(a-n),this.remainingPartDataCount>0)return;if(n=i+this.boundaryLength,n>=e.length){this.ignoreByteCount=this.boundaryLength-(e.length-i);return}}}}copyExistingData(e,t){return new Promise((n,r)=>{let a=()=>{if(e===t){n();return}let o=this.options.tasks[e];if(o.kind!==i.OperationKind.COPY){r(Error(`Task kind must be COPY`));return}s(o,this.out,this.options.oldFileFd,r,()=>{e++,a()})};a()})}searchHeaderListEnd(e,t){let n=e.indexOf(a,t);if(n!==-1)return n+a.length;let r=t===0?e:e.slice(t);return this.headerListBuffer==null?this.headerListBuffer=r:this.headerListBuffer=Buffer.concat([this.headerListBuffer,r]),-1}onPartEnd(){let e=this.partIndexToLength[this.partIndex-1];if(this.actualPartLength!==e)throw(0,t.newError)(`Expected length: ${e} differs from actual: ${this.actualPartLength}`,`ERR_DATA_SPLITTER_LENGTH_MISMATCH`);this.actualPartLength=0}processPartStarted(e,t,n){return this.partIndex!==0&&this.onPartEnd(),this.processPartData(e,t,n)}processPartData(e,t,n){this.actualPartLength+=n-t,this.transferred+=n-t,this.delta+=n-t;let r=this.out;return r.write(t===0&&e.length===n?e:e.slice(t,n))?Promise.resolve():new Promise((e,t)=>{r.on(`error`,t),r.once(`drain`,()=>{r.removeListener(`error`,t),e()})})}}})),It=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.executeTasksUsingMultipleRangeRequests=i,e.checkIsRangesSupported=o;var t=U(),n=Ft(),r=Pt();function i(e,t,n,r,i){let o=s=>{if(s>=t.length){e.fileMetadataBuffer!=null&&n.write(e.fileMetadataBuffer),n.end();return}let c=s+1e3;a(e,{tasks:t,start:s,end:Math.min(t.length,c),oldFileFd:r},n,()=>o(c),i)};return o}function a(e,i,a,s,c){let l=`bytes=`,u=0,d=0,f=new Map,p=[];for(let e=i.start;e<i.end;e++){let t=i.tasks[e];t.kind===r.OperationKind.DOWNLOAD&&(l+=`${t.start}-${t.end-1}, `,f.set(u,e),u++,p.push(t.end-t.start),d+=t.end-t.start)}if(u<=1){let t=l=>{if(l>=i.end){s();return}let u=i.tasks[l++];if(u.kind===r.OperationKind.COPY)(0,n.copyData)(u,a,i.oldFileFd,c,()=>t(l));else{let n=e.createRequestOptions();n.headers.Range=`bytes=${u.start}-${u.end-1}`;let r=e.httpExecutor.createRequest(n,e=>{e.on(`error`,c),o(e,c)&&(e.pipe(a,{end:!1}),e.once(`end`,()=>t(l)))});e.httpExecutor.addErrorAndTimeoutHandlers(r,c),r.end()}};t(i.start);return}let m=e.createRequestOptions();m.headers.Range=l.substring(0,l.length-2);let h=e.httpExecutor.createRequest(m,r=>{if(!o(r,c))return;let l=(0,t.safeGetHeader)(r,`content-type`),u=/^multipart\/.+?\s*;\s*boundary=(?:"([^"]+)"|([^\s";]+))\s*$/i.exec(l);if(u==null){c(Error(`Content-Type "multipart/byteranges" is expected, but got "${l}"`));return}let m=new n.DataSplitter(a,i,f,u[1]||u[2],p,s,d,e.options.onProgress);m.on(`error`,c),r.pipe(m),r.on(`end`,()=>{setTimeout(()=>{h.abort(),c(Error(`Response ends without calling any handlers`))},1e4)})});e.httpExecutor.addErrorAndTimeoutHandlers(h,c),h.end()}function o(e,n){if(e.statusCode>=400)return n((0,t.createHttpError)(e)),!1;if(e.statusCode!==206){let r=(0,t.safeGetHeader)(e,`accept-ranges`);if(r==null||r===`none`)return n(Error(`Server doesn't support Accept-Ranges (response code ${e.statusCode})`)),!1}return!0}})),Lt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ProgressDifferentialDownloadCallbackTransform=void 0;var t=require("stream"),n;(function(e){e[e.COPY=0]=`COPY`,e[e.DOWNLOAD=1]=`DOWNLOAD`})(n||={}),e.ProgressDifferentialDownloadCallbackTransform=class extends t.Transform{constructor(e,t,r){super(),this.progressDifferentialDownloadInfo=e,this.cancellationToken=t,this.onProgress=r,this.start=Date.now(),this.transferred=0,this.delta=0,this.expectedBytes=0,this.index=0,this.operationType=n.COPY,this.nextUpdate=this.start+1e3}_transform(e,t,r){if(this.cancellationToken.cancelled){r(Error(`cancelled`),null);return}if(this.operationType==n.COPY){r(null,e);return}this.transferred+=e.length,this.delta+=e.length;let i=Date.now();i>=this.nextUpdate&&this.transferred!==this.expectedBytes&&this.transferred!==this.progressDifferentialDownloadInfo.grandTotal&&(this.nextUpdate=i+1e3,this.onProgress({total:this.progressDifferentialDownloadInfo.grandTotal,delta:this.delta,transferred:this.transferred,percent:this.transferred/this.progressDifferentialDownloadInfo.grandTotal*100,bytesPerSecond:Math.round(this.transferred/((i-this.start)/1e3))}),this.delta=0),r(null,e)}beginFileCopy(){this.operationType=n.COPY}beginRangeDownload(){this.operationType=n.DOWNLOAD,this.expectedBytes+=this.progressDifferentialDownloadInfo.expectedByteCounts[this.index++]}endRangeDownload(){this.transferred!==this.progressDifferentialDownloadInfo.grandTotal&&this.onProgress({total:this.progressDifferentialDownloadInfo.grandTotal,delta:this.delta,transferred:this.transferred,percent:this.transferred/this.progressDifferentialDownloadInfo.grandTotal*100,bytesPerSecond:Math.round(this.transferred/((Date.now()-this.start)/1e3))})}_flush(e){if(this.cancellationToken.cancelled){e(Error(`cancelled`));return}this.onProgress({total:this.progressDifferentialDownloadInfo.grandTotal,delta:this.delta,transferred:this.transferred,percent:100,bytesPerSecond:Math.round(this.transferred/((Date.now()-this.start)/1e3))}),this.delta=0,this.transferred=0,e(null)}}})),Rt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DifferentialDownloader=void 0;var t=U(),n=P(),r=require("fs"),i=Ft(),a=require("url"),o=Pt(),s=It(),c=Lt();e.DifferentialDownloader=class{constructor(e,t,n){this.blockAwareFileInfo=e,this.httpExecutor=t,this.options=n,this.fileMetadataBuffer=null,this.logger=n.logger}createRequestOptions(){let e={headers:{...this.options.requestHeaders,accept:`*/*`}};return(0,t.configureRequestUrl)(this.options.newUrl,e),(0,t.configureRequestOptions)(e),e}doDownload(e,t){if(e.version!==t.version)throw Error(`version is different (${e.version} - ${t.version}), full download is required`);let n=this.logger,r=(0,o.computeOperations)(e,t,n);n.debug!=null&&n.debug(JSON.stringify(r,null,2));let i=0,a=0;for(let e of r){let t=e.end-e.start;e.kind===o.OperationKind.DOWNLOAD?i+=t:a+=t}let s=this.blockAwareFileInfo.size;if(i+a+(this.fileMetadataBuffer==null?0:this.fileMetadataBuffer.length)!==s)throw Error(`Internal error, size mismatch: downloadSize: ${i}, copySize: ${a}, newSize: ${s}`);return n.info(`Full: ${l(s)}, To download: ${l(i)} (${Math.round(i/(s/100))}%)`),this.downloadFile(r)}downloadFile(e){let t=[],r=()=>Promise.all(t.map(e=>(0,n.close)(e.descriptor).catch(t=>{this.logger.error(`cannot close file "${e.path}": ${t}`)})));return this.doDownloadFile(e,t).then(r).catch(e=>r().catch(t=>{try{this.logger.error(`cannot close files: ${t}`)}catch(e){try{console.error(e)}catch{}}throw e}).then(()=>{throw e}))}async doDownloadFile(e,l){let d=await(0,n.open)(this.options.oldFile,`r`);l.push({descriptor:d,path:this.options.oldFile});let f=await(0,n.open)(this.options.newFile,`w`);l.push({descriptor:f,path:this.options.newFile});let p=(0,r.createWriteStream)(this.options.newFile,{fd:f});await new Promise((n,r)=>{let f=[],m;if(!this.options.isUseMultipleRangeRequest&&this.options.onProgress){let t=[],n=0;for(let r of e)r.kind===o.OperationKind.DOWNLOAD&&(t.push(r.end-r.start),n+=r.end-r.start);let r={expectedByteCounts:t,grandTotal:n};m=new c.ProgressDifferentialDownloadCallbackTransform(r,this.options.cancellationToken,this.options.onProgress),f.push(m)}let h=new t.DigestTransform(this.blockAwareFileInfo.sha512);h.isValidateOnEnd=!1,f.push(h),p.on(`finish`,()=>{p.close(()=>{l.splice(1,1);try{h.validate()}catch(e){r(e);return}n(void 0)})}),f.push(p);let g=null;for(let e of f)e.on(`error`,r),g=g==null?e:g.pipe(e);let _=f[0],v;if(this.options.isUseMultipleRangeRequest){v=(0,s.executeTasksUsingMultipleRangeRequests)(this,e,_,d,r),v(0);return}let y=0,b=null;this.logger.info(`Differential download: ${this.options.newUrl}`);let x=this.createRequestOptions();x.redirect=`manual`,v=n=>{var s,c;if(n>=e.length){this.fileMetadataBuffer!=null&&_.write(this.fileMetadataBuffer),_.end();return}let l=e[n++];if(l.kind===o.OperationKind.COPY){m&&m.beginFileCopy(),(0,i.copyData)(l,_,d,r,()=>v(n));return}let f=`bytes=${l.start}-${l.end-1}`;x.headers.range=f,(c=(s=this.logger)?.debug)==null||c.call(s,`download range: ${f}`),m&&m.beginRangeDownload();let p=this.httpExecutor.createRequest(x,e=>{e.on(`error`,r),e.on(`aborted`,()=>{r(Error(`response has been aborted by the server`))}),e.statusCode>=400&&r((0,t.createHttpError)(e)),e.pipe(_,{end:!1}),e.once(`end`,()=>{m&&m.endRangeDownload(),++y===100?(y=0,setTimeout(()=>v(n),1e3)):v(n)})});p.on(`redirect`,(e,n,r)=>{this.logger.info(`Redirect to ${u(r)}`),b=r,(0,t.configureRequestUrl)(new a.URL(b),x),p.followRedirect()}),this.httpExecutor.addErrorAndTimeoutHandlers(p,r),p.end()},v(0)})}async readRemoteBytes(e,t){let n=Buffer.allocUnsafe(t+1-e),r=this.createRequestOptions();r.headers.range=`bytes=${e}-${t}`;let i=0;if(await this.request(r,e=>{e.copy(n,i),i+=e.length}),i!==n.length)throw Error(`Received data length ${i} is not equal to expected ${n.length}`);return n}request(e,t){return new Promise((n,r)=>{let i=this.httpExecutor.createRequest(e,e=>{(0,s.checkIsRangesSupported)(e,r)&&(e.on(`error`,r),e.on(`aborted`,()=>{r(Error(`response has been aborted by the server`))}),e.on(`data`,t),e.on(`end`,()=>n()))});this.httpExecutor.addErrorAndTimeoutHandlers(i,r),i.end()})}};function l(e,t=` KB`){return new Intl.NumberFormat(`en`).format((e/1024).toFixed(2))+t}function u(e){let t=e.indexOf(`?`);return t<0?e:e.substring(0,t)}})),zt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.GenericDifferentialDownloader=void 0;var t=Rt();e.GenericDifferentialDownloader=class extends t.DifferentialDownloader{download(e,t){return this.doDownload(e,t)}}})),Bt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.UpdaterSignal=e.UPDATE_DOWNLOADED=e.DOWNLOAD_PROGRESS=e.CancellationToken=void 0,e.addHandler=n;var t=U();Object.defineProperty(e,"CancellationToken",{enumerable:!0,get:function(){return t.CancellationToken}}),e.DOWNLOAD_PROGRESS=`download-progress`,e.UPDATE_DOWNLOADED=`update-downloaded`,e.UpdaterSignal=class{constructor(e){this.emitter=e}login(e){n(this.emitter,`login`,e)}progress(t){n(this.emitter,e.DOWNLOAD_PROGRESS,t)}updateDownloaded(t){n(this.emitter,e.UPDATE_DOWNLOADED,t)}updateCancelled(e){n(this.emitter,`update-cancelled`,e)}};function n(e,t,n){e.on(t,n)}})),Vt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.NoOpLogger=e.AppUpdater=void 0;var t=U(),n=require("crypto"),r=require("os"),i=require("events"),a=P(),o=Me(),s=Ne(),c=require("path"),l=yt(),u=xt(),d=Ct(),f=wt(),p=Dt(),m=Nt(),h=require("zlib"),g=zt(),_=Bt();e.AppUpdater=class e extends i.EventEmitter{get channel(){return this._channel}set channel(e){if(this._channel!=null){if(typeof e!=`string`)throw(0,t.newError)(`Channel must be a string, but got: ${e}`,`ERR_UPDATER_INVALID_CHANNEL`);if(e.length===0)throw(0,t.newError)(`Channel must be not an empty string`,`ERR_UPDATER_INVALID_CHANNEL`)}this._channel=e,this.allowDowngrade=!0}addAuthHeader(e){this.requestHeaders=Object.assign({},this.requestHeaders,{authorization:e})}get netSession(){return(0,f.getNetSession)()}get logger(){return this._logger}set logger(e){this._logger=e??new y}set updateConfigPath(e){this.clientPromise=null,this._appUpdateConfigPath=e,this.configOnDisk=new s.Lazy(()=>this.loadUpdateConfig())}get isUpdateSupported(){return this._isUpdateSupported}set isUpdateSupported(e){e&&(this._isUpdateSupported=e)}get isUserWithinRollout(){return this._isUserWithinRollout}set isUserWithinRollout(e){e&&(this._isUserWithinRollout=e)}constructor(e,n){super(),this.autoDownload=!0,this.autoInstallOnAppQuit=!0,this.autoRunAppAfterInstall=!0,this.allowPrerelease=!1,this.fullChangelog=!1,this.allowDowngrade=!1,this.disableWebInstaller=!1,this.disableDifferentialDownload=!1,this.forceDevUpdateConfig=!1,this.previousBlockmapBaseUrlOverride=null,this._channel=null,this.downloadedUpdateHelper=null,this.requestHeaders=null,this._logger=console,this.signals=new _.UpdaterSignal(this),this._appUpdateConfigPath=null,this._isUpdateSupported=e=>this.checkIfUpdateSupported(e),this._isUserWithinRollout=e=>this.isStagingMatch(e),this.clientPromise=null,this.stagingUserIdPromise=new s.Lazy(()=>this.getOrCreateStagingUserId()),this.configOnDisk=new s.Lazy(()=>this.loadUpdateConfig()),this.checkForUpdatesPromise=null,this.downloadPromise=null,this.updateInfoAndProvider=null,this._testOnlyOptions=null,this.on(`error`,e=>{this._logger.error(`Error: ${e.stack||e.message}`)}),n==null?(this.app=new d.ElectronAppAdapter,this.httpExecutor=new f.ElectronHttpExecutor((e,t)=>this.emit(`login`,e,t))):(this.app=n,this.httpExecutor=null);let r=this.app.version,i=(0,l.parse)(r);if(i==null)throw(0,t.newError)(`App version is not a valid semver version: "${r}"`,`ERR_UPDATER_INVALID_VERSION`);this.currentVersion=i,this.allowPrerelease=v(i),e!=null&&(this.setFeedURL(e),typeof e!=`string`&&e.requestHeaders&&(this.requestHeaders=e.requestHeaders))}getFeedURL(){return`Deprecated. Do not use it.`}setFeedURL(e){let t=this.createProviderRuntimeOptions(),n;n=typeof e==`string`?new p.GenericProvider({provider:`generic`,url:e},this,{...t,isUseMultipleRangeRequest:(0,m.isUrlProbablySupportMultiRangeRequests)(e)}):(0,m.createClient)(e,this,t),this.clientPromise=Promise.resolve(n)}checkForUpdates(){if(!this.isUpdaterActive())return Promise.resolve(null);let e=this.checkForUpdatesPromise;if(e!=null)return this._logger.info(`Checking for update (already in progress)`),e;let t=()=>this.checkForUpdatesPromise=null;return this._logger.info(`Checking for update`),e=this.doCheckForUpdates().then(e=>(t(),e)).catch(e=>{throw t(),this.emit(`error`,e,`Cannot check for updates: ${(e.stack||e).toString()}`),e}),this.checkForUpdatesPromise=e,e}isUpdaterActive(){return this.app.isPackaged||this.forceDevUpdateConfig?!0:(this._logger.info(`Skip checkForUpdates because application is not packed and dev update config is not forced`),!1)}checkForUpdatesAndNotify(t){return this.checkForUpdates().then(n=>n?.downloadPromise?(n.downloadPromise.then(()=>{let r=e.formatDownloadNotification(n.updateInfo.version,this.app.name,t);new(require("electron")).Notification(r).show()}),n):(this._logger.debug!=null&&this._logger.debug(`checkForUpdatesAndNotify called, downloadPromise is null`),n))}static formatDownloadNotification(e,t,n){return n??={title:`A new update is ready to install`,body:`{appName} version {version} has been downloaded and will be automatically installed on exit`},n={title:n.title.replace(`{appName}`,t).replace(`{version}`,e),body:n.body.replace(`{appName}`,t).replace(`{version}`,e)},n}async isStagingMatch(e){let n=e.stagingPercentage,r=n;if(r==null)return!0;if(r=parseInt(r,10),isNaN(r))return this._logger.warn(`Staging percentage is NaN: ${n}`),!0;r/=100;let i=await this.stagingUserIdPromise.value,a=t.UUID.parse(i).readUInt32BE(12)/4294967295;return this._logger.info(`Staging percentage: ${r}, percentage: ${a}, user id: ${i}`),a<r}computeFinalHeaders(e){return this.requestHeaders!=null&&Object.assign(e,this.requestHeaders),e}async isUpdateAvailable(e){let n=(0,l.parse)(e.version);if(n==null)throw(0,t.newError)(`This file could not be downloaded, or the latest version (from update server) does not have a valid semver version: "${e.version}"`,`ERR_UPDATER_INVALID_VERSION`);let r=this.currentVersion;if((0,l.eq)(n,r)||!await Promise.resolve(this.isUpdateSupported(e))||!await Promise.resolve(this.isUserWithinRollout(e)))return!1;let i=(0,l.gt)(n,r),a=(0,l.lt)(n,r);return i?!0:this.allowDowngrade&&a}checkIfUpdateSupported(e){let t=e?.minimumSystemVersion,n=(0,r.release)();if(t)try{if((0,l.lt)(n,t))return this._logger.info(`Current OS version ${n} is less than the minimum OS version required ${t} for version ${n}`),!1}catch(e){this._logger.warn(`Failed to compare current OS version(${n}) with minimum OS version(${t}): ${(e.message||e).toString()}`)}return!0}async getUpdateInfoAndProvider(){await this.app.whenReady(),this.clientPromise??=this.configOnDisk.value.then(e=>(0,m.createClient)(e,this,this.createProviderRuntimeOptions()));let e=await this.clientPromise,t=await this.stagingUserIdPromise.value;return e.setRequestHeaders(this.computeFinalHeaders({"x-user-staging-id":t})),{info:await e.getLatestVersion(),provider:e}}createProviderRuntimeOptions(){return{isUseMultipleRangeRequest:!0,platform:this._testOnlyOptions==null?process.platform:this._testOnlyOptions.platform,executor:this.httpExecutor}}async doCheckForUpdates(){this.emit(`checking-for-update`);let e=await this.getUpdateInfoAndProvider(),n=e.info;if(!await this.isUpdateAvailable(n))return this._logger.info(`Update for version ${this.currentVersion.format()} is not available (latest version: ${n.version}, downgrade is ${this.allowDowngrade?`allowed`:`disallowed`}).`),this.emit(`update-not-available`,n),{isUpdateAvailable:!1,versionInfo:n,updateInfo:n};this.updateInfoAndProvider=e,this.onUpdateAvailable(n);let r=new t.CancellationToken;return{isUpdateAvailable:!0,versionInfo:n,updateInfo:n,cancellationToken:r,downloadPromise:this.autoDownload?this.downloadUpdate(r):null}}onUpdateAvailable(e){this._logger.info(`Found version ${e.version} (url: ${(0,t.asArray)(e.files).map(e=>e.url).join(`, `)})`),this.emit(`update-available`,e)}downloadUpdate(e=new t.CancellationToken){let n=this.updateInfoAndProvider;if(n==null){let e=Error(`Please check update first`);return this.dispatchError(e),Promise.reject(e)}if(this.downloadPromise!=null)return this._logger.info(`Downloading update (already in progress)`),this.downloadPromise;this._logger.info(`Downloading update from ${(0,t.asArray)(n.info.files).map(e=>e.url).join(`, `)}`);let r=e=>{if(!(e instanceof t.CancellationError))try{this.dispatchError(e)}catch(e){this._logger.warn(`Cannot dispatch error event: ${e.stack||e}`)}return e};return this.downloadPromise=this.doDownloadUpdate({updateInfoAndProvider:n,requestHeaders:this.computeRequestHeaders(n.provider),cancellationToken:e,disableWebInstaller:this.disableWebInstaller,disableDifferentialDownload:this.disableDifferentialDownload}).catch(e=>{throw r(e)}).finally(()=>{this.downloadPromise=null}),this.downloadPromise}dispatchError(e){this.emit(`error`,e,(e.stack||e).toString())}dispatchUpdateDownloaded(e){this.emit(_.UPDATE_DOWNLOADED,e)}async loadUpdateConfig(){return this._appUpdateConfigPath??=this.app.appUpdateConfigPath,(0,o.load)(await(0,a.readFile)(this._appUpdateConfigPath,`utf-8`))}computeRequestHeaders(e){let t=e.fileExtraDownloadHeaders;if(t!=null){let e=this.requestHeaders;return e==null?t:{...t,...e}}return this.computeFinalHeaders({accept:`*/*`})}async getOrCreateStagingUserId(){let e=c.join(this.app.userDataPath,`.updaterId`);try{let n=await(0,a.readFile)(e,`utf-8`);if(t.UUID.check(n))return n;this._logger.warn(`Staging user id file exists, but content was invalid: ${n}`)}catch(e){e.code!==`ENOENT`&&this._logger.warn(`Couldn't read staging user ID, creating a blank one: ${e}`)}let r=t.UUID.v5((0,n.randomBytes)(4096),t.UUID.OID);this._logger.info(`Generated new staging user ID: ${r}`);try{await(0,a.outputFile)(e,r)}catch(e){this._logger.warn(`Couldn't write out staging user ID: ${e}`)}return r}get isAddNoCacheQuery(){let e=this.requestHeaders;if(e==null)return!0;for(let t of Object.keys(e)){let e=t.toLowerCase();if(e===`authorization`||e===`private-token`)return!1}return!0}async getOrCreateDownloadHelper(){let e=this.downloadedUpdateHelper;if(e==null){let t=(await this.configOnDisk.value).updaterCacheDirName,n=this._logger;t??n.error(`updaterCacheDirName is not specified in app-update.yml Was app build using at least electron-builder 20.34.0?`);let r=c.join(this.app.baseCachePath,t||this.app.name);n.debug!=null&&n.debug(`updater cache dir: ${r}`),e=new u.DownloadedUpdateHelper(r),this.downloadedUpdateHelper=e}return e}async executeDownload(e){let n=e.fileInfo,r={headers:e.downloadUpdateOptions.requestHeaders,cancellationToken:e.downloadUpdateOptions.cancellationToken,sha2:n.info.sha2,sha512:n.info.sha512};this.listenerCount(_.DOWNLOAD_PROGRESS)>0&&(r.onProgress=e=>this.emit(_.DOWNLOAD_PROGRESS,e));let i=e.downloadUpdateOptions.updateInfoAndProvider.info,o=i.version,s=n.packageInfo;function l(){let t=decodeURIComponent(e.fileInfo.url.pathname);return t.toLowerCase().endsWith(`.${e.fileExtension.toLowerCase()}`)?c.basename(t):c.basename(e.fileInfo.info.url)}let d=await this.getOrCreateDownloadHelper(),f=d.cacheDirForPendingUpdate;await(0,a.mkdir)(f,{recursive:!0});let p=l(),m=c.join(f,p),h=s==null?null:c.join(f,`package-${o}${c.extname(s.path)||`.7z`}`),g=async t=>{await d.setDownloadedFile(m,h,i,n,p,t),await e.done({...i,downloadedFile:m});let r=c.join(f,`current.blockmap`);return await(0,a.pathExists)(r)&&await(0,a.copyFile)(r,c.join(d.cacheDir,`current.blockmap`)),h==null?[m]:[m,h]},v=this._logger,y=await d.validateDownloadedPath(m,i,n,v);if(y!=null)return m=y,await g(!1);let b=async()=>(await d.clear().catch(()=>{}),await(0,a.unlink)(m).catch(()=>{})),x=await(0,u.createTempUpdateFile)(`temp-${p}`,f,v);try{await e.task(x,r,h,b),await(0,t.retry)(()=>(0,a.rename)(x,m),{retries:60,interval:500,shouldRetry:e=>e instanceof Error&&/^EBUSY:/.test(e.message)?!0:(v.warn(`Cannot rename temp file to final file: ${e.message||e.stack}`),!1)})}catch(e){throw await b(),e instanceof t.CancellationError&&(v.info(`cancelled`),this.emit(`update-cancelled`,i)),e}return v.info(`New version ${o} has been downloaded to ${m}`),await g(!0)}async differentialDownloadInstaller(e,t,n,r,i){try{if(this._testOnlyOptions!=null&&!this._testOnlyOptions.isUseDifferentialDownload)return!0;let r=t.updateInfoAndProvider.provider,o=await r.getBlockMapFiles(e.url,this.app.version,t.updateInfoAndProvider.info.version,this.previousBlockmapBaseUrlOverride);this._logger.info(`Download block maps (old: "${o[0]}", new: ${o[1]})`);let s=async e=>{let n=await this.httpExecutor.downloadToBuffer(e,{headers:t.requestHeaders,cancellationToken:t.cancellationToken});if(n==null||n.length===0)throw Error(`Blockmap "${e.href}" is empty`);try{return JSON.parse((0,h.gunzipSync)(n).toString())}catch(t){throw Error(`Cannot parse blockmap "${e.href}", error: ${t}`)}},l={newUrl:e.url,oldFile:c.join(this.downloadedUpdateHelper.cacheDir,i),logger:this._logger,newFile:n,isUseMultipleRangeRequest:r.isUseMultipleRangeRequest,requestHeaders:t.requestHeaders,cancellationToken:t.cancellationToken};this.listenerCount(_.DOWNLOAD_PROGRESS)>0&&(l.onProgress=e=>this.emit(_.DOWNLOAD_PROGRESS,e));let u=async(e,t)=>{let n=c.join(t,`current.blockmap`);await(0,a.outputFile)(n,(0,h.gzipSync)(JSON.stringify(e)))},d=async e=>{let t=c.join(e,`current.blockmap`);try{if(await(0,a.pathExists)(t))return JSON.parse((0,h.gunzipSync)(await(0,a.readFile)(t)).toString())}catch(e){this._logger.warn(`Cannot parse blockmap "${t}", error: ${e}`)}return null},f=await s(o[1]);await u(f,this.downloadedUpdateHelper.cacheDirForPendingUpdate);let p=await d(this.downloadedUpdateHelper.cacheDir);return p??=await s(o[0]),await new g.GenericDifferentialDownloader(e.info,this.httpExecutor,l).download(p,f),!1}catch(e){if(this._logger.error(`Cannot download differentially, fallback to full download: ${e.stack||e}`),this._testOnlyOptions!=null)throw e;return!0}}};function v(e){let t=(0,l.prerelease)(e);return t!=null&&t.length>0}var y=class{info(e){}warn(e){}error(e){}};e.NoOpLogger=y})),Ht=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BaseUpdater=void 0;var t=require("child_process"),n=require("path"),r=Vt();e.BaseUpdater=class extends r.AppUpdater{constructor(e,t){super(e,t),this.quitAndInstallCalled=!1,this.quitHandlerAdded=!1}quitAndInstall(e=!1,t=!1){this._logger.info(`Install on explicit quitAndInstall`),this.install(e,e?t:this.autoRunAppAfterInstall)?setImmediate(()=>{require("electron").autoUpdater.emit(`before-quit-for-update`),this.app.quit()}):this.quitAndInstallCalled=!1}executeDownload(e){return super.executeDownload({...e,done:e=>(this.dispatchUpdateDownloaded(e),this.addQuitHandler(),Promise.resolve())})}get installerPath(){return this.downloadedUpdateHelper==null?null:this.downloadedUpdateHelper.file}install(e=!1,t=!1){if(this.quitAndInstallCalled)return this._logger.warn(`install call ignored: quitAndInstallCalled is set to true`),!1;let n=this.downloadedUpdateHelper,r=this.installerPath,i=n==null?null:n.downloadedFileInfo;if(r==null||i==null)return this.dispatchError(Error(`No update filepath provided, can't quit and install`)),!1;this.quitAndInstallCalled=!0;try{return this._logger.info(`Install: isSilent: ${e}, isForceRunAfter: ${t}`),this.doInstall({isSilent:e,isForceRunAfter:t,isAdminRightsRequired:i.isAdminRightsRequired})}catch(e){return this.dispatchError(e),!1}}addQuitHandler(){this.quitHandlerAdded||!this.autoInstallOnAppQuit||(this.quitHandlerAdded=!0,this.app.onQuit(e=>{if(this.quitAndInstallCalled){this._logger.info(`Update installer has already been triggered. Quitting application.`);return}if(!this.autoInstallOnAppQuit){this._logger.info(`Update will not be installed on quit because autoInstallOnAppQuit is set to false.`);return}if(e!==0){this._logger.info(`Update will be not installed on quit because application is quitting with exit code ${e}`);return}this._logger.info(`Auto install update on quit`),this.install(!0,!1)}))}sanitizeEnvPath(e){return e.split(n.delimiter).filter(e=>n.isAbsolute(e)).join(n.delimiter)}spawnSyncLog(e,n=[],r={}){this._logger.info(`Executing: ${e} with args: ${n}`);let i={...process.env,...r},{error:a,status:o,stdout:s,stderr:c}=(0,t.spawnSync)(e,n,{env:{...i,PATH:this.sanitizeEnvPath(i.PATH??``)},encoding:`utf-8`,shell:!0});if(a!=null)throw this._logger.error(c),a;if(o!=null&&o!==0)throw this._logger.error(c),Error(`Command ${e} exited with code ${o}`);return s.trim()}async spawnLog(e,n=[],r=void 0,i=`ignore`){return this._logger.info(`Executing: ${e} with args: ${n}`),new Promise((a,o)=>{try{let s={stdio:i,env:r,detached:!0},c=(0,t.spawn)(e,n,s);c.on(`error`,e=>{o(e)}),c.unref(),c.pid!==void 0&&a(!0)}catch(e){o(e)}})}}})),Ut=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FileWithEmbeddedBlockMapDifferentialDownloader=void 0;var t=P(),n=Rt(),r=require("zlib");e.FileWithEmbeddedBlockMapDifferentialDownloader=class extends n.DifferentialDownloader{async download(){let e=this.blockAwareFileInfo,t=e.size,n=t-(e.blockMapSize+4);this.fileMetadataBuffer=await this.readRemoteBytes(n,t-1);let r=i(this.fileMetadataBuffer.slice(0,this.fileMetadataBuffer.length-4));await this.doDownload(await a(this.options.oldFile),r)}};function i(e){return JSON.parse((0,r.inflateRawSync)(e).toString())}async function a(e){let n=await(0,t.open)(e,`r`);try{let e=(await(0,t.fstat)(n)).size,r=Buffer.allocUnsafe(4);await(0,t.read)(n,r,0,r.length,e-r.length);let a=Buffer.allocUnsafe(r.readUInt32BE(0));return await(0,t.read)(n,a,0,a.length,e-r.length-a.length),await(0,t.close)(n),i(a)}catch(e){throw await(0,t.close)(n),e}}})),Wt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AppImageUpdater=void 0;var t=U(),n=require("child_process"),r=P(),i=require("fs"),a=require("path"),o=Ht(),s=Ut(),c=$(),l=Bt();e.AppImageUpdater=class extends o.BaseUpdater{constructor(e,t){super(e,t)}isUpdaterActive(){return process.env.APPIMAGE==null&&!this.forceDevUpdateConfig?(process.env.SNAP==null?this._logger.warn(`APPIMAGE env is not defined, current application is not an AppImage`):this._logger.info(`SNAP env is defined, updater is disabled`),!1):super.isUpdaterActive()}doDownloadUpdate(e){let n=e.updateInfoAndProvider.provider,i=(0,c.findFile)(n.resolveFiles(e.updateInfoAndProvider.info),`AppImage`,[`rpm`,`deb`,`pacman`]);return this.executeDownload({fileExtension:`AppImage`,fileInfo:i,downloadUpdateOptions:e,task:async(a,o)=>{let s=process.env.APPIMAGE;if(s==null)throw(0,t.newError)(`APPIMAGE env is not defined`,`ERR_UPDATER_OLD_FILE_NOT_FOUND`);(e.disableDifferentialDownload||await this.downloadDifferential(i,s,a,n,e))&&await this.httpExecutor.download(i.url,a,o),await(0,r.chmod)(a,493)}})}async downloadDifferential(e,t,n,r,i){try{let a={newUrl:e.url,oldFile:t,logger:this._logger,newFile:n,isUseMultipleRangeRequest:r.isUseMultipleRangeRequest,requestHeaders:i.requestHeaders,cancellationToken:i.cancellationToken};return this.listenerCount(l.DOWNLOAD_PROGRESS)>0&&(a.onProgress=e=>this.emit(l.DOWNLOAD_PROGRESS,e)),await new s.FileWithEmbeddedBlockMapDifferentialDownloader(e.info,this.httpExecutor,a).download(),!1}catch(e){return this._logger.error(`Cannot download differentially, fallback to full download: ${e.stack||e}`),process.platform===`linux`}}doInstall(e){let r=process.env.APPIMAGE;if(r==null)throw(0,t.newError)(`APPIMAGE env is not defined`,`ERR_UPDATER_OLD_FILE_NOT_FOUND`);if(!a.isAbsolute(r)||r.includes(`\0`))throw(0,t.newError)(`APPIMAGE env is not a valid absolute path: "${r}"`,`ERR_UPDATER_OLD_FILE_NOT_FOUND`);(0,i.unlinkSync)(r);let o,s=a.basename(r),c=this.installerPath;if(c==null)return this.dispatchError(Error(`No update filepath provided, can't quit and install`)),!1;o=a.basename(c)===s||!/\d+\.\d+\.\d+/.test(s)?r:a.join(a.dirname(r),a.basename(c)),(0,n.execFileSync)(`mv`,[`-f`,c,o]),o!==r&&this.emit(`appimage-filename-updated`,o);let l={...process.env,APPIMAGE_SILENT_INSTALL:`true`};return e.isForceRunAfter?this.spawnLog(o,[],l):(l.APPIMAGE_EXIT_AFTER_INSTALL=`true`,(0,n.execFileSync)(o,[],{env:l})),!0}}})),Gt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.LinuxUpdater=void 0;var t=Ht(),n=/^[a-zA-Z0-9_-]+$/;e.LinuxUpdater=class extends t.BaseUpdater{constructor(e,t){super(e,t)}isRunningAsRoot(){return process.getuid?.call(process)===0}get installerPath(){let e=super.installerPath;return e==null?null:e.replace(/\\/g,`\\\\`).replace(/([`$!" ;|&()<>])/g,`\\$1`).replace(/[\n\r]/g,``)}runCommandWithSudoIfNeeded(e){if(this.isRunningAsRoot())return this._logger.info(`Running as root, no need to use sudo`),this.spawnSyncLog(e[0],e.slice(1));let{name:t}=this.app,n=`"${t.replace(/["`$\\!\n\r;|&<>(){}*?[\]#~]/g,``)} would like to update"`,r=this.sudoWithArgs(n);this._logger.info(`Running as non-root user, using sudo to install: ${r}`);let i=`"`;return(/pkexec/i.test(r[0])||r[0]===`sudo`)&&(i=``),this.spawnSyncLog(r[0],[...r.length>1?r.slice(1):[],`${i}/bin/bash`,`-c`,`'${e.join(` `)}'${i}`])}sudoWithArgs(e){let t=this.determineSudoCommand(),n=[t];return/kdesudo/i.test(t)?(n.push(`--comment`,e),n.push(`-c`)):/gksudo/i.test(t)?n.push(`--message`,e):/pkexec/i.test(t)&&n.push(`--disable-internal-agent`),n}hasCommand(e){try{return this.spawnSyncLog(`command`,[`-v`,e]),!0}catch{return!1}}determineSudoCommand(){for(let e of[`gksudo`,`kdesudo`,`pkexec`,`beesu`])if(this.hasCommand(e))return e;return`sudo`}detectPackageManager(e){let t=e,r=process.env.ELECTRON_BUILDER_LINUX_PACKAGE_MANAGER?.trim();r&&(n.test(r)?t=[r]:this._logger.warn(`ELECTRON_BUILDER_LINUX_PACKAGE_MANAGER "${r}" contains unsafe characters. Ignoring override.`));for(let e of t)if(this.hasCommand(e))return e;let i=r?`ELECTRON_BUILDER_LINUX_PACKAGE_MANAGER override "${r}", `:``,a=e[0];return this._logger.warn(`No package manager found in the list: ${i}${e.join(`, `)}. Utilizing default: ${a}`),a}}})),Kt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DebUpdater=void 0;var t=$(),n=Bt(),r=Gt();e.DebUpdater=class e extends r.LinuxUpdater{constructor(e,t){super(e,t)}doDownloadUpdate(e){let r=e.updateInfoAndProvider.provider,i=(0,t.findFile)(r.resolveFiles(e.updateInfoAndProvider.info),`deb`,[`AppImage`,`rpm`,`pacman`]);return this.executeDownload({fileExtension:`deb`,fileInfo:i,downloadUpdateOptions:e,task:async(e,t)=>{this.listenerCount(n.DOWNLOAD_PROGRESS)>0&&(t.onProgress=e=>this.emit(n.DOWNLOAD_PROGRESS,e)),await this.httpExecutor.download(i.url,e,t)}})}doInstall(t){let n=this.installerPath;if(n==null)return this.dispatchError(Error(`No update filepath provided, can't quit and install`)),!1;if(!this.hasCommand(`dpkg`)&&!this.hasCommand(`apt`))return this.dispatchError(Error(`Neither dpkg nor apt command found. Cannot install .deb package.`)),!1;let r=this.detectPackageManager([`dpkg`,`apt`]);try{e.installWithCommandRunner(r,n,this.runCommandWithSudoIfNeeded.bind(this),this._logger)}catch(e){return this.dispatchError(e),!1}return t.isForceRunAfter&&this.app.relaunch(),!0}static installWithCommandRunner(e,t,n,r){if(e===`dpkg`)try{n([`dpkg`,`-i`,t])}catch(e){r.warn(e.message??e),r.warn(`dpkg installation failed, trying to fix broken dependencies with apt-get`),n([`apt-get`,`install`,`-f`,`-y`])}else if(e===`apt`)r.warn(`Using apt to install a local .deb. This may fail for unsigned packages unless properly configured.`),n([`apt`,`install`,`-y`,`--allow-unauthenticated`,`--allow-downgrades`,`--allow-change-held-packages`,t]);else throw Error(`Package manager ${e} not supported`)}}})),qt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PacmanUpdater=void 0;var t=Bt(),n=$(),r=Gt();e.PacmanUpdater=class e extends r.LinuxUpdater{constructor(e,t){super(e,t)}doDownloadUpdate(e){let r=e.updateInfoAndProvider.provider,i=(0,n.findFile)(r.resolveFiles(e.updateInfoAndProvider.info),`pacman`,[`AppImage`,`deb`,`rpm`]);return this.executeDownload({fileExtension:`pacman`,fileInfo:i,downloadUpdateOptions:e,task:async(e,n)=>{this.listenerCount(t.DOWNLOAD_PROGRESS)>0&&(n.onProgress=e=>this.emit(t.DOWNLOAD_PROGRESS,e)),await this.httpExecutor.download(i.url,e,n)}})}doInstall(t){let n=this.installerPath;if(n==null)return this.dispatchError(Error(`No update filepath provided, can't quit and install`)),!1;try{e.installWithCommandRunner(n,this.runCommandWithSudoIfNeeded.bind(this),this._logger)}catch(e){return this.dispatchError(e),!1}return t.isForceRunAfter&&this.app.relaunch(),!0}static installWithCommandRunner(e,t,n){try{t([`pacman`,`-U`,`--noconfirm`,e])}catch(r){n.warn(r.message??r),n.warn(`pacman installation failed, attempting to update package database and retry`);try{t([`pacman`,`-Sy`,`--noconfirm`]),t([`pacman`,`-U`,`--noconfirm`,e])}catch(e){throw n.error(`Retry after pacman -Sy failed`),e}}}}})),Jt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.RpmUpdater=void 0;var t=Bt(),n=$(),r=Gt();e.RpmUpdater=class e extends r.LinuxUpdater{constructor(e,t){super(e,t)}doDownloadUpdate(e){let r=e.updateInfoAndProvider.provider,i=(0,n.findFile)(r.resolveFiles(e.updateInfoAndProvider.info),`rpm`,[`AppImage`,`deb`,`pacman`]);return this.executeDownload({fileExtension:`rpm`,fileInfo:i,downloadUpdateOptions:e,task:async(e,n)=>{this.listenerCount(t.DOWNLOAD_PROGRESS)>0&&(n.onProgress=e=>this.emit(t.DOWNLOAD_PROGRESS,e)),await this.httpExecutor.download(i.url,e,n)}})}doInstall(t){let n=this.installerPath;if(n==null)return this.dispatchError(Error(`No update filepath provided, can't quit and install`)),!1;let r=this.detectPackageManager([`zypper`,`dnf`,`yum`,`rpm`]);try{e.installWithCommandRunner(r,n,this.runCommandWithSudoIfNeeded.bind(this),this._logger)}catch(e){return this.dispatchError(e),!1}return t.isForceRunAfter&&this.app.relaunch(),!0}static installWithCommandRunner(e,t,n,r){if(e===`zypper`)return n([`zypper`,`--non-interactive`,`--no-refresh`,`install`,`--allow-unsigned-rpm`,`-f`,t]);if(e===`dnf`)return n([`dnf`,`install`,`--nogpgcheck`,`-y`,t]);if(e===`yum`)return n([`yum`,`install`,`--nogpgcheck`,`-y`,t]);if(e===`rpm`)return r.warn(`Installing with rpm only (no dependency resolution).`),n([`rpm`,`-Uvh`,`--replacepkgs`,`--replacefiles`,`--nodeps`,t]);throw Error(`Package manager ${e} not supported`)}}})),Yt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MacUpdater=void 0;var t=U(),n=P(),r=require("fs"),i=require("path"),a=require("http"),o=Vt(),s=$(),c=require("child_process"),l=require("crypto");e.MacUpdater=class e extends o.AppUpdater{constructor(e,t){super(e,t),this.nativeUpdater=require("electron").autoUpdater,this.squirrelDownloadedUpdate=!1,this.nativeUpdater.on(`error`,e=>{this._logger.warn(e),this.emit(`error`,e)}),this.nativeUpdater.on(`update-downloaded`,()=>{this.squirrelDownloadedUpdate=!0,this.debug(`nativeUpdater.update-downloaded`)})}static filterFilesForArch(e,t){let n=e=>e.url.pathname.includes(`arm64`)||e.info.url?.includes(`arm64`);return t&&e.some(n)?e.filter(e=>t===n(e)):e.filter(e=>!n(e))}debug(e){this._logger.debug!=null&&this._logger.debug(e)}closeServerIfExists(){this.server&&(this.debug(`Closing proxy server`),this.server.close(e=>{e&&this.debug(`proxy server wasn't already open, probably attempted closing again as a safety check before quit`)}))}async doDownloadUpdate(r){let a=r.updateInfoAndProvider.provider.resolveFiles(r.updateInfoAndProvider.info),o=this._logger,l=`sysctl.proc_translated`,u=!1;try{this.debug(`Checking for macOS Rosetta environment`),u=(0,c.execFileSync)(`sysctl`,[l],{encoding:`utf8`}).includes(`${l}: 1`),o.info(`Checked for macOS Rosetta environment (isRosetta=${u})`)}catch(e){o.warn(`sysctl shell command to check for macOS Rosetta environment failed: ${e}`)}let d=!1;try{this.debug(`Checking for arm64 in uname`);let e=(0,c.execFileSync)(`uname`,[`-a`],{encoding:`utf8`}).includes(`ARM`);o.info(`Checked 'uname -a': arm64=${e}`),d||=e}catch(e){o.warn(`uname shell command to check for arm64 failed: ${e}`)}d=d||process.arch===`arm64`||u,a=e.filterFilesForArch(a,d);let f=(0,s.findFile)(a,`zip`,[`pkg`,`dmg`]);if(f==null)throw(0,t.newError)(`ZIP file not provided: ${(0,t.safeStringifyJson)(a)}`,`ERR_UPDATER_ZIP_FILE_NOT_FOUND`);let p=r.updateInfoAndProvider.provider,m=`update.zip`;return this.executeDownload({fileExtension:`zip`,fileInfo:f,downloadUpdateOptions:r,task:async(e,t)=>{let a=i.join(this.downloadedUpdateHelper.cacheDir,m),s=()=>(0,n.pathExistsSync)(a)?!r.disableDifferentialDownload:(o.info(`Unable to locate previous update.zip for differential download (is this first install?), falling back to full download`),!1),c=!0;s()&&(c=await this.differentialDownloadInstaller(f,r,e,p,m)),c&&await this.httpExecutor.download(f.url,e,t)},done:async e=>{if(!r.disableDifferentialDownload)try{let t=i.join(this.downloadedUpdateHelper.cacheDir,m);await(0,n.copyFile)(e.downloadedFile,t)}catch(e){this._logger.warn(`Unable to copy file for caching for future differential downloads: ${e.message}`)}return this.updateDownloaded(f,e)}})}async updateDownloaded(e,t){let i=t.downloadedFile,o=e.info.size??(await(0,n.stat)(i)).size,s=this._logger,c=`fileToProxy=${e.url.href}`;this.closeServerIfExists(),this.debug(`Creating proxy server for native Squirrel.Mac (${c})`),this.server=(0,a.createServer)(),this.debug(`Proxy server for native Squirrel.Mac is created (${c})`),this.server.on(`close`,()=>{s.info(`Proxy server for native Squirrel.Mac is closed (${c})`)});let u=e=>{let t=e.address();return typeof t==`string`?t:`http://127.0.0.1:${t?.port}`};return await new Promise((e,n)=>{let a=(0,l.randomBytes)(64).toString(`base64`).replace(/\//g,`_`).replace(/\+/g,`-`),d=Buffer.from(`autoupdater:${a}`,`ascii`),f=`/${(0,l.randomBytes)(64).toString(`hex`)}.zip`;this.server.on(`request`,(t,c)=>{let l=t.url;if(s.info(`${l} requested`),l===`/`){if(!t.headers.authorization||t.headers.authorization.indexOf(`Basic `)===-1){c.statusCode=401,c.statusMessage=`Invalid Authentication Credentials`,c.end(),s.warn(`No authenthication info`);return}let e=t.headers.authorization.split(` `)[1],[n,r]=Buffer.from(e,`base64`).toString(`ascii`).split(`:`);if(n!==`autoupdater`||r!==a){c.statusCode=401,c.statusMessage=`Invalid Authentication Credentials`,c.end(),s.warn(`Invalid authenthication credentials`);return}let i=Buffer.from(`{ "url": "${u(this.server)}${f}" }`);c.writeHead(200,{"Content-Type":`application/json`,"Content-Length":i.length}),c.end(i);return}if(!l.startsWith(f)){s.warn(`${l} requested, but not supported`),c.writeHead(404),c.end();return}s.info(`${f} requested by Squirrel.Mac, pipe ${i}`);let d=!1;c.on(`finish`,()=>{d||(this.nativeUpdater.removeListener(`error`,n),e([]))});let p=(0,r.createReadStream)(i);p.on(`error`,e=>{try{c.end()}catch(e){s.warn(`cannot end response: ${e}`)}d=!0,this.nativeUpdater.removeListener(`error`,n),n(Error(`Cannot pipe "${i}": ${e}`))}),c.writeHead(200,{"Content-Type":`application/zip`,"Content-Length":o}),p.pipe(c)}),this.debug(`Proxy server for native Squirrel.Mac is starting to listen (${c})`),this.server.listen(0,`127.0.0.1`,()=>{this.debug(`Proxy server for native Squirrel.Mac is listening (address=${u(this.server)}, ${c})`),this.nativeUpdater.setFeedURL({url:u(this.server),headers:{"Cache-Control":`no-cache`,Authorization:`Basic ${d.toString(`base64`)}`}}),this.dispatchUpdateDownloaded(t),this.autoInstallOnAppQuit?(this.nativeUpdater.once(`error`,n),this.nativeUpdater.checkForUpdates()):e([])})})}handleUpdateDownloaded(){this.autoRunAppAfterInstall?this.nativeUpdater.quitAndInstall():this.app.quit(),this.closeServerIfExists()}quitAndInstall(){this.squirrelDownloadedUpdate?this.handleUpdateDownloaded():(this.nativeUpdater.on(`update-downloaded`,()=>this.handleUpdateDownloaded()),this.autoInstallOnAppQuit||this.nativeUpdater.checkForUpdates())}}})),Xt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.verifySignature=o;var t=U(),n=require("child_process"),r=require("os"),i=require("path");function a(e,t){return[`set "PSModulePath=" & chcp 65001 >NUL & powershell.exe`,[`-NoProfile`,`-NonInteractive`,`-InputFormat`,`None`,`-Command`,e],{shell:!0,timeout:t}]}function o(e,r,o){return new Promise((l,u)=>{let d=r.replace(/'/g,`''`);o.info(`Verifying signature ${d}`),(0,n.execFile)(...a(`"Get-AuthenticodeSignature -LiteralPath '${d}' | ConvertTo-Json -Compress"`,20*1e3),(n,a,d)=>{try{if(n!=null||d){c(o,n,d,u),l(null);return}let f=s(a);if(f.Status===0){try{let e=i.normalize(f.Path),t=i.normalize(r);if(o.info(`LiteralPath: ${e}. Update Path: ${t}`),e!==t){c(o,Error(`LiteralPath of ${e} is different than ${t}`),d,u),l(null);return}}catch(e){o.warn(`Unable to verify LiteralPath of update asset due to missing data.Path. Skipping this step of validation. Message: ${e.message??e.stack}`)}let n=(0,t.parseDn)(f.SignerCertificate.Subject),a=!1;for(let r of e){let e=(0,t.parseDn)(r);if(e.size?a=Array.from(e.keys()).every(t=>e.get(t)===n.get(t)):r===n.get(`CN`)&&(o.warn(`Signature validated using only CN ${r}. Please add your full Distinguished Name (DN) to publisherNames configuration`),a=!0),a){l(null);return}}}let p=`publisherNames: ${e.join(` | `)}, raw info: `+JSON.stringify(f,(e,t)=>e===`RawData`?void 0:t,2);o.warn(`Sign verification failed, installer signed with incorrect certificate: ${p}`),l(p)}catch(e){c(o,e,null,u),l(null);return}})})}function s(e){let t=JSON.parse(e);delete t.PrivateKey,delete t.IsOSBinary,delete t.SignatureType;let n=t.SignerCertificate;return n!=null&&(delete n.Archived,delete n.Extensions,delete n.Handle,delete n.HasPrivateKey,delete n.SubjectName),t}function c(e,t,r,i){if(l()){e.warn(`Cannot execute Get-AuthenticodeSignature: ${t||r}. Ignoring signature validation due to unsupported powershell version. Please upgrade to powershell 3 or higher.`);return}try{(0,n.execFileSync)(...a(`ConvertTo-Json test`,10*1e3))}catch(t){e.warn(`Cannot execute ConvertTo-Json: ${t.message}. Ignoring signature validation due to unsupported powershell version. Please upgrade to powershell 3 or higher.`);return}t!=null&&i(t),r&&i(Error(`Cannot execute Get-AuthenticodeSignature, stderr: ${r}. Failing signature validation due to unknown stderr.`))}function l(){let e=r.release();return e.startsWith(`6.`)&&!e.startsWith(`6.3`)}})),Zt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.NsisUpdater=void 0;var t=U(),n=require("path"),r=Ht(),i=Ut(),a=Bt(),o=$(),s=P(),c=Xt(),l=require("url");e.NsisUpdater=class extends r.BaseUpdater{constructor(e,t){super(e,t),this._verifyUpdateCodeSignature=(e,t)=>(0,c.verifySignature)(e,t,this._logger)}get verifyUpdateCodeSignature(){return this._verifyUpdateCodeSignature}set verifyUpdateCodeSignature(e){e&&(this._verifyUpdateCodeSignature=e)}doDownloadUpdate(e){let n=e.updateInfoAndProvider.provider,r=(0,o.findFile)(n.resolveFiles(e.updateInfoAndProvider.info),`exe`);return this.executeDownload({fileExtension:`exe`,downloadUpdateOptions:e,fileInfo:r,task:async(i,a,o,c)=>{let u=r.packageInfo,d=u!=null&&o!=null;if(d&&e.disableWebInstaller)throw(0,t.newError)(`Unable to download new version ${e.updateInfoAndProvider.info.version}. Web Installers are disabled`,`ERR_UPDATER_WEB_INSTALLER_DISABLED`);!d&&!e.disableWebInstaller&&this._logger.warn(`disableWebInstaller is set to false, you should set it to true if you do not plan on using a web installer. This will default to true in a future version.`),(d||e.disableDifferentialDownload||await this.differentialDownloadInstaller(r,e,i,n,t.CURRENT_APP_INSTALLER_FILE_NAME))&&await this.httpExecutor.download(r.url,i,a);let f=await this.verifySignature(i);if(f!=null)throw await c(),(0,t.newError)(`New version ${e.updateInfoAndProvider.info.version} is not signed by the application owner: ${f}`,`ERR_UPDATER_INVALID_SIGNATURE`);if(d&&await this.differentialDownloadWebPackage(e,u,o,n))try{await this.httpExecutor.download(new l.URL(u.path),o,{headers:e.requestHeaders,cancellationToken:e.cancellationToken,sha512:u.sha512})}catch(e){try{await(0,s.unlink)(o)}catch{}throw e}}})}async verifySignature(e){let t;try{if(t=(await this.configOnDisk.value).publisherName,t==null)return null}catch(e){if(e.code===`ENOENT`)return null;throw e}return await this._verifyUpdateCodeSignature(Array.isArray(t)?t:[t],e)}doInstall(e){let t=this.installerPath;if(t==null)return this.dispatchError(Error(`No update filepath provided, can't quit and install`)),!1;let r=[`--updated`];e.isSilent&&r.push(`/S`),e.isForceRunAfter&&r.push(`--force-run`),this.installDirectory&&r.push(`/D=${this.installDirectory}`);let i=this.downloadedUpdateHelper==null?null:this.downloadedUpdateHelper.packageFile;i!=null&&r.push(`--package-file=${i}`);let a=()=>{this.spawnLog(n.join(process.resourcesPath,`elevate.exe`),[t].concat(r)).catch(e=>this.dispatchError(e))};return e.isAdminRightsRequired?(this._logger.info(`isAdminRightsRequired is set to true, run installer using elevate.exe`),a(),!0):(this.spawnLog(t,r).catch(e=>{let n=e.code;this._logger.info(`Cannot run installer: error code: ${n}, error message: "${e.message}", will be executed again using elevate if EACCES, and will try to use electron.shell.openItem if ENOENT`),n===`UNKNOWN`||n===`EACCES`?a():n===`ENOENT`?require("electron").shell.openPath(t).catch(e=>this.dispatchError(e)):this.dispatchError(e)}),!0)}async differentialDownloadWebPackage(e,r,o,s){if(r.blockMapSize==null)return!0;try{let c={newUrl:new l.URL(r.path),oldFile:n.join(this.downloadedUpdateHelper.cacheDir,t.CURRENT_APP_PACKAGE_FILE_NAME),logger:this._logger,newFile:o,requestHeaders:this.requestHeaders,isUseMultipleRangeRequest:s.isUseMultipleRangeRequest,cancellationToken:e.cancellationToken};this.listenerCount(a.DOWNLOAD_PROGRESS)>0&&(c.onProgress=e=>this.emit(a.DOWNLOAD_PROGRESS,e)),await new i.FileWithEmbeddedBlockMapDifferentialDownloader(r,this.httpExecutor,c).download()}catch(e){return this._logger.error(`Cannot download differentially, fallback to full download: ${e.stack||e}`),process.platform===`win32`}return!1}}})),Qt=exports&&exports.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),$t=exports&&exports.__exportStar||function(e,t){for(var n in e)n!==`default`&&!Object.prototype.hasOwnProperty.call(t,n)&&Qt(t,e,n)};Object.defineProperty(exports,"__esModule",{value:!0}),exports.NsisUpdater=exports.MacUpdater=exports.RpmUpdater=exports.PacmanUpdater=exports.DebUpdater=exports.AppImageUpdater=exports.Provider=exports.NoOpLogger=exports.AppUpdater=exports.BaseUpdater=void 0;var en=P(),tn=require("path"),nn=Ht();Object.defineProperty(exports,"BaseUpdater",{enumerable:!0,get:function(){return nn.BaseUpdater}});var rn=Vt();Object.defineProperty(exports,"AppUpdater",{enumerable:!0,get:function(){return rn.AppUpdater}}),Object.defineProperty(exports,"NoOpLogger",{enumerable:!0,get:function(){return rn.NoOpLogger}});var an=$();Object.defineProperty(exports,"Provider",{enumerable:!0,get:function(){return an.Provider}});var on=Wt();Object.defineProperty(exports,"AppImageUpdater",{enumerable:!0,get:function(){return on.AppImageUpdater}});var sn=Kt();Object.defineProperty(exports,"DebUpdater",{enumerable:!0,get:function(){return sn.DebUpdater}});var cn=qt();Object.defineProperty(exports,"PacmanUpdater",{enumerable:!0,get:function(){return cn.PacmanUpdater}});var ln=Jt();Object.defineProperty(exports,"RpmUpdater",{enumerable:!0,get:function(){return ln.RpmUpdater}});var un=Yt();Object.defineProperty(exports,"MacUpdater",{enumerable:!0,get:function(){return un.MacUpdater}});var dn=Zt();Object.defineProperty(exports,"NsisUpdater",{enumerable:!0,get:function(){return dn.NsisUpdater}}),$t(Bt(),exports);var fn;function pn(){if(process.platform===`win32`)fn=new(Zt()).NsisUpdater;else if(process.platform===`darwin`)fn=new(Yt()).MacUpdater;else{fn=new(Wt()).AppImageUpdater;try{let e=tn.join(process.resourcesPath,`package-type`);if(!(0,en.existsSync)(e))return fn;switch((0,en.readFileSync)(e).toString().trim()){case`deb`:fn=new(Kt()).DebUpdater;break;case`rpm`:fn=new(Jt()).RpmUpdater;break;case`pacman`:fn=new(qt()).PacmanUpdater;break;default:break}}catch(e){console.warn(`Unable to detect 'package-type' for autoUpdater (rpm/deb/pacman support). If you'd like to expand support, please consider contributing to electron-builder`,e.message)}}return fn}Object.defineProperty(exports,"autoUpdater",{enumerable:!0,get:()=>fn||pn()});
\ No newline at end of file
diff --git a/apps/desktop/shell/rescue/index.js b/apps/desktop/shell/rescue/index.js
new file mode 100644
index 00000000000..8e3986d978b
--- /dev/null
+++ b/apps/desktop/shell/rescue/index.js
@@ -0,0 +1,220 @@
+const fs = require('node:fs');
+const path = require('node:path');
+const { app, BrowserWindow, dialog, shell } = require('electron');
+
+const CHECK_TIMEOUT_MS = 30_000;
+
+const readJson = (file) => {
+ try {
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
+ } catch {
+ return undefined;
+ }
+};
+
+const resolveChannel = ({ resourcesPath, userData }) => {
+ const stored = readJson(path.join(userData, 'lobehub-settings.json'))?.updateChannel;
+ if (stored != null) return stored === 'canary' ? 'canary' : 'stable';
+ const built = readJson(path.join(resourcesPath, 'core', 'manifest.json'))?.channel;
+ return built === 'canary' || built === 'beta' ? 'canary' : 'stable';
+};
+
+const resolveFeedUrl = ({ channel, resourcesPath }) => {
+ try {
+ const yml = fs.readFileSync(path.join(resourcesPath, 'app-update.yml'), 'utf8');
+ const url = /^url:\s*['"]?([^\s'"]+)/m.exec(yml)?.[1];
+ if (!url) return undefined;
+ return `${url.replace(/\/(stable|nightly|canary|beta)\/?$/, '').replace(/\/$/, '')}/${channel}`;
+ } catch {
+ return undefined;
+ }
+};
+
+const configureUpdater = (autoUpdater, { channel, feedUrl, logger }) => {
+ autoUpdater.logger = logger;
+ autoUpdater.autoDownload = false;
+ autoUpdater.autoInstallOnAppQuit = false;
+ autoUpdater.allowPrerelease = channel !== 'stable';
+ if (feedUrl) {
+ autoUpdater.channel = channel;
+ autoUpdater.setFeedURL({ provider: 'generic', url: feedUrl });
+ }
+ // The channel setter flips allowDowngrade; republishing an older yml is how a broken
+ // release gets rolled back, so rescue must accept it.
+ autoUpdater.allowDowngrade = true;
+};
+
+const strings = (zh) =>
+ zh
+ ? {
+ checking: 'LobeHub 启动失败,正在检查更新…',
+ downloadPage: '打开下载页',
+ downloading: (percent) => `正在下载更新… ${percent}%`,
+ failed: '检查或下载更新失败',
+ installing: '下载完成,正在安装…',
+ latest: 'LobeHub 启动失败,且当前已是最新版本。',
+ quit: '退出',
+ retryCheck: '重试',
+ retryLaunch: '重试启动',
+ }
+ : {
+ checking: 'LobeHub failed to start. Checking for updates…',
+ downloadPage: 'Open download page',
+ downloading: (percent) => `Downloading update… ${percent}%`,
+ failed: 'Failed to check for or download the update',
+ installing: 'Download complete. Installing…',
+ latest: 'LobeHub failed to start and is already on the latest version.',
+ quit: 'Quit',
+ retryCheck: 'Retry',
+ retryLaunch: 'Retry launch',
+ };
+
+const createStatusWindow = (text) => {
+ const win = new BrowserWindow({
+ height: 140,
+ maximizable: false,
+ minimizable: false,
+ resizable: false,
+ title: 'LobeHub',
+ webPreferences: { contextIsolation: true, javascript: true, nodeIntegration: false },
+ width: 420,
+ });
+ const html = `<!doctype html><meta charset="utf-8"><body style="margin:0;height:100vh;display:flex;align-items:center;justify-content:center;font:14px system-ui;padding:0 24px;text-align:center"><p id="s"></p>`;
+ const ready = win.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(html)}`);
+ const setText = (value) =>
+ ready
+ .then(() =>
+ win.isDestroyed()
+ ? undefined
+ : win.webContents.executeJavaScript(
+ `document.getElementById('s').textContent = ${JSON.stringify(value)}`,
+ ),
+ )
+ .catch(() => {});
+ setText(text);
+ return { setText, win };
+};
+
+const withTimeout = (promise, ms) =>
+ Promise.race([
+ promise,
+ new Promise((_, reject) => setTimeout(() => reject(new Error(`timed out after ${ms}ms`)), ms)),
+ ]);
+
+function runRescue({ downloadUrl, error, fallback, log = [] }) {
+ const userData = app.getPath('userData');
+ const logFile = path.join(userData, 'logs', 'shell-rescue.log');
+ const write = (level, ...args) => {
+ const line = args.map((arg) => (arg instanceof Error ? arg.stack : String(arg))).join(' ');
+ try {
+ fs.mkdirSync(path.dirname(logFile), { recursive: true });
+ fs.appendFileSync(logFile, `[${new Date().toISOString()}] [${level}] ${line}\n`);
+ } catch {
+ // an unwritable log dir must not stop the rescue flow
+ }
+ };
+ const logger = {
+ debug: (...args) => write('debug', ...args),
+ error: (...args) => write('error', ...args),
+ info: (...args) => write('info', ...args),
+ warn: (...args) => write('warn', ...args),
+ };
+
+ logger.error('core failed to start', error);
+ for (const entry of log) logger.info(`shell: ${entry}`);
+
+ const channel = resolveChannel({ resourcesPath: process.resourcesPath, userData });
+ const feedUrl = resolveFeedUrl({ channel, resourcesPath: process.resourcesPath });
+ logger.info(`channel=${channel} feed=${feedUrl ?? '(app-update.yml)'}`);
+
+ let installing = false;
+ // quitAndInstall closes every window before Squirrel.Mac takes over; exiting there would
+ // abort the install.
+ app.on('window-all-closed', () => {
+ if (!installing) app.exit(0);
+ });
+
+ app
+ .whenReady()
+ .then(() => {
+ const { autoUpdater } = require('./electron-updater.cjs');
+ configureUpdater(autoUpdater, { channel, feedUrl, logger });
+
+ const t = strings(app.getLocale().startsWith('zh'));
+ const status = createStatusWindow(t.checking);
+
+ const choose = async (message, buttons) => {
+ const { response } = await dialog.showMessageBox(status.win, {
+ buttons: buttons.map(([label]) => label),
+ cancelId: buttons.length - 1,
+ defaultId: 0,
+ message,
+ type: 'error',
+ });
+ return buttons[response][1]();
+ };
+ const openDownloadPage = () => shell.openExternal(downloadUrl).finally(() => app.exit(1));
+ const quit = () => app.exit(1);
+
+ autoUpdater.on('download-progress', ({ percent }) =>
+ status.setText(t.downloading(Math.floor(percent))),
+ );
+
+ const attempt = async () => {
+ status.setText(t.checking);
+ try {
+ const result = await withTimeout(autoUpdater.checkForUpdates(), CHECK_TIMEOUT_MS);
+ if (!result) throw new Error('updater is not active for this build');
+ if (!result.isUpdateAvailable) {
+ logger.info('no update available');
+ return choose(t.latest, [
+ [
+ t.retryLaunch,
+ () => {
+ fs.rmSync(path.join(userData, 'core-ota', 'boot.json'), { force: true });
+ app.relaunch();
+ app.exit(0);
+ },
+ ],
+ [t.downloadPage, openDownloadPage],
+ [t.quit, quit],
+ ]);
+ }
+ logger.info(`downloading ${result.updateInfo.version}`);
+ await autoUpdater.downloadUpdate();
+ status.setText(t.installing);
+ logger.info('installing');
+ installing = true;
+ app.releaseSingleInstanceLock();
+ autoUpdater.quitAndInstall(true, true);
+ } catch (updateError) {
+ logger.error('update failed', updateError);
+ return choose(t.failed, [
+ [t.retryCheck, attempt],
+ [t.downloadPage, openDownloadPage],
+ [t.quit, quit],
+ ]);
+ }
+ };
+
+ // Squirrel.Mac reports install failures only through this event, after quitAndInstall.
+ autoUpdater.on('error', (installError) => {
+ if (!installing) return;
+ installing = false;
+ logger.error('install failed', installError);
+ choose(t.failed, [
+ [t.retryCheck, attempt],
+ [t.downloadPage, openDownloadPage],
+ [t.quit, quit],
+ ]).catch(fallback);
+ });
+
+ return attempt();
+ })
+ .catch((rescueError) => {
+ logger.error('rescue failed', rescueError);
+ fallback(rescueError);
+ });
+}
+
+module.exports = { configureUpdater, resolveChannel, resolveFeedUrl, runRescue };
diff --git a/apps/desktop/src/main/const/__tests__/shell.test.ts b/apps/desktop/src/main/const/__tests__/shell.test.ts
new file mode 100644
index 00000000000..ffaaa2674e2
--- /dev/null
+++ b/apps/desktop/src/main/const/__tests__/shell.test.ts
@@ -0,0 +1,34 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const fakeShell = {
+ abi: 'a'.repeat(64),
+ builtinDir: '/res/core',
+ coreDir: '/res/core',
+ log: ['loaded builtin'],
+ manifest: null,
+ markHealthy: vi.fn(),
+ publicKey: '',
+ shellVersion: '1.0.0',
+ source: 'builtin' as const,
+};
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.resetModules();
+});
+
+describe('shellInfo', () => {
+ it('is undefined when the shell did not inject __SHELL__', async () => {
+ vi.resetModules();
+ const { shellInfo } = await import('../shell');
+ expect(shellInfo).toBeUndefined();
+ });
+
+ it('captures __SHELL__ when present', async () => {
+ vi.stubGlobal('__SHELL__', fakeShell);
+ vi.resetModules();
+ const { shellInfo } = await import('../shell');
+ expect(shellInfo).toBe(fakeShell);
+ expect(shellInfo?.coreDir).toBe('/res/core');
+ });
+});
diff --git a/apps/desktop/src/main/const/dir.ts b/apps/desktop/src/main/const/dir.ts
index 9084b01c464..774883b60c1 100644
--- a/apps/desktop/src/main/const/dir.ts
+++ b/apps/desktop/src/main/const/dir.ts
@@ -14,9 +14,7 @@ export const binDir = app.isPackaged
? path.join(process.resourcesPath, 'bin')
: path.join(resourcesDir, 'bin');
-const appPath = app.getAppPath();
-
-export const rendererDir = path.join(appPath, 'dist', 'renderer');
+export const rendererDir = path.join(mainDir, '../renderer');
export const userDataDir = app.getPath('userData');
diff --git a/apps/desktop/src/main/const/shell.ts b/apps/desktop/src/main/const/shell.ts
new file mode 100644
index 00000000000..84d29dfbbaa
--- /dev/null
+++ b/apps/desktop/src/main/const/shell.ts
@@ -0,0 +1,19 @@
+import type { CoreManifest } from '@/core/infrastructure/coreOta/manifest';
+
+export interface ShellGlobal {
+ readonly abi: string;
+ readonly builtinDir: string;
+ readonly coreDir: string;
+ readonly log: string[];
+ readonly manifest: CoreManifest | null;
+ readonly markHealthy: () => void;
+ readonly publicKey: string;
+ readonly shellVersion: string;
+ readonly source: 'builtin' | 'external';
+}
+
+declare global {
+ var __SHELL__: ShellGlobal | undefined;
+}
+
+export const shellInfo: ShellGlobal | undefined = globalThis.__SHELL__;
diff --git a/apps/desktop/src/main/controllers/RendererOtaCtr.ts b/apps/desktop/src/main/controllers/RendererOtaCtr.ts
index cee0dad9c5d..8960f2b96eb 100644
--- a/apps/desktop/src/main/controllers/RendererOtaCtr.ts
+++ b/apps/desktop/src/main/controllers/RendererOtaCtr.ts
@@ -1,26 +1,33 @@
+import { shellInfo } from '@/const/shell';
+
import { ControllerModule, IpcMethod } from './index';
export default class RendererOtaCtr extends ControllerModule {
static override readonly groupName = 'rendererOta';
+ private coreMarkedHealthy = false;
+
@IpcMethod()
async bootPing(stage?: 'loaded' | 'mounted') {
- this.app.rendererUpdateManager.handleBootPing(stage);
+ this.app.coreUpdateManager.handleBootPing(stage);
+ if (stage === 'loaded' || this.coreMarkedHealthy) return;
+ this.coreMarkedHealthy = true;
+ shellInfo?.markHealthy();
}
@IpcMethod()
async applyNow(): Promise<boolean> {
- return this.app.rendererUpdateManager.applyStagedNow();
+ return this.app.coreUpdateManager.applyStagedNow();
}
@IpcMethod()
async getStatus() {
- return this.app.rendererUpdateManager.getStatus();
+ return this.app.coreUpdateManager.getStatus();
}
@IpcMethod()
async checkNow() {
- await this.app.rendererUpdateManager.checkForUpdates();
- return this.app.rendererUpdateManager.getStatus();
+ await this.app.coreUpdateManager.checkForUpdates();
+ return this.app.coreUpdateManager.getStatus();
}
}
diff --git a/apps/desktop/src/main/controllers/UpdaterCtr.ts b/apps/desktop/src/main/controllers/UpdaterCtr.ts
index 5a60d51b5b4..9da552a20ca 100644
--- a/apps/desktop/src/main/controllers/UpdaterCtr.ts
+++ b/apps/desktop/src/main/controllers/UpdaterCtr.ts
@@ -77,7 +77,7 @@ export default class UpdaterCtr extends ControllerModule {
logger.info(`Set update channel requested: ${channel}`);
this.app.storeManager.set('updateChannel', channel);
- this.app.rendererUpdateManager.switchChannel(channel);
+ this.app.coreUpdateManager.switchChannel(channel);
(await this.getUpdaterManager()).switchChannel(channel);
}
diff --git a/apps/desktop/src/main/controllers/__tests__/RendererOtaCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/RendererOtaCtr.test.ts
new file mode 100644
index 00000000000..9109e087d6a
--- /dev/null
+++ b/apps/desktop/src/main/controllers/__tests__/RendererOtaCtr.test.ts
@@ -0,0 +1,30 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import RendererOtaCtr from '../RendererOtaCtr';
+
+const { markHealthy } = vi.hoisted(() => ({ markHealthy: vi.fn() }));
+
+vi.mock('@/const/shell', () => ({ shellInfo: { markHealthy } }));
+
+const makeCtr = () => {
+ const handleBootPing = vi.fn();
+ const ctr = new RendererOtaCtr({ coreUpdateManager: { handleBootPing } } as never);
+ return { ctr, handleBootPing };
+};
+
+beforeEach(() => {
+ markHealthy.mockClear();
+});
+
+describe('RendererOtaCtr.bootPing', () => {
+ it('forwards every ping and marks the core healthy once on mount', async () => {
+ const { ctr, handleBootPing } = makeCtr();
+ await ctr.bootPing('loaded');
+ expect(markHealthy).not.toHaveBeenCalled();
+ await ctr.bootPing('mounted');
+ await ctr.bootPing('mounted');
+ await ctr.bootPing();
+ expect(handleBootPing).toHaveBeenCalledTimes(4);
+ expect(markHealthy).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/desktop/src/main/controllers/__tests__/UpdaterCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/UpdaterCtr.test.ts
index 0d210d03492..ac16e05635b 100644
--- a/apps/desktop/src/main/controllers/__tests__/UpdaterCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/UpdaterCtr.test.ts
@@ -30,7 +30,7 @@ const mockStoreGet = vi.fn();
const mockStoreSet = vi.fn();
const mockApp = {
- rendererUpdateManager: {
+ coreUpdateManager: {
switchChannel: mockRendererSwitchChannel,
},
storeManager: {
diff --git a/apps/desktop/src/main/core/App.ts b/apps/desktop/src/main/core/App.ts
index 3bfacc6d3fb..18aa7b9e3db 100644
--- a/apps/desktop/src/main/core/App.ts
+++ b/apps/desktop/src/main/core/App.ts
@@ -10,6 +10,7 @@ import { app, ipcMain, nativeTheme, protocol } from 'electron';
import { name } from '@/../../package.json';
import { binDir, buildDir } from '@/const/dir';
import { isDev } from '@/const/env';
+import { shellInfo } from '@/const/shell';
import type { IControlModule } from '@/controllers';
import AuthCtr from '@/controllers/AuthCtr';
import RemoteServerConfigCtr from '@/controllers/RemoteServerConfigCtr';
@@ -34,11 +35,11 @@ import { refreshShellPath } from '@/utils/shellPath';
import { BrowserManager } from './browser/BrowserManager';
import { backendProxyProtocolManager } from './infrastructure/BackendProxyProtocolManager';
import { BinaryManager } from './infrastructure/BinaryManager';
+import { CoreUpdateManager } from './infrastructure/coreOta/CoreUpdateManager';
import { I18nManager } from './infrastructure/I18nManager';
import { IoCContainer } from './infrastructure/IoCContainer';
import { LocalFileProtocolManager } from './infrastructure/LocalFileProtocolManager';
import { ProtocolManager } from './infrastructure/ProtocolManager';
-import { RendererUpdateManager } from './infrastructure/rendererOta/RendererUpdateManager';
import { RendererUrlManager } from './infrastructure/RendererUrlManager';
import { StaticFileServerManager } from './infrastructure/StaticFileServerManager';
import { StoreManager } from './infrastructure/StoreManager';
@@ -69,7 +70,7 @@ export class App {
staticFileServerManager: StaticFileServerManager;
protocolManager: ProtocolManager;
rendererUrlManager: RendererUrlManager;
- rendererUpdateManager: RendererUpdateManager;
+ coreUpdateManager: CoreUpdateManager;
localFileProtocolManager: LocalFileProtocolManager;
binaryManager: BinaryManager;
screenCaptureManager: ScreenCaptureManager;
@@ -100,6 +101,8 @@ export class App {
logger.info(`PATH: ${app.getAppPath()}`);
logger.info(` lng: ${app.getLocale()}`);
logger.info(` res: ${binDir}`);
+ logger.info(`core: ${shellInfo?.source} ${shellInfo?.coreDir} abi=${shellInfo?.abi}`);
+ for (const line of shellInfo?.log ?? []) logger.info(`shell: ${line}`);
logger.info('----------------------------------------------');
logger.info('Starting LobeHub...');
@@ -159,13 +162,14 @@ export class App {
this.binaryManager = new BinaryManager(this);
this.screenCaptureManager = new ScreenCaptureManager(this);
- // Resolve the renderer OTA pointer and set the app:// serving root before
- // any window starts loading.
- this.rendererUpdateManager = new RendererUpdateManager(this);
- this.rendererUpdateManager.initialize();
+ this.coreUpdateManager = new CoreUpdateManager(this);
+ this.coreUpdateManager.initialize();
app.on('web-contents-created', (_event, webContents) => {
webContents.on('render-process-gone', () => {
- this.rendererUpdateManager.handleRendererCrash();
+ this.coreUpdateManager.handleRendererCrash();
+ });
+ webContents.on('will-prevent-unload', () => {
+ this.coreUpdateManager.handleUnloadPrevented();
});
});
@@ -345,7 +349,7 @@ export class App {
// Initialize updater manager
await this.updaterManager.initialize();
- this.rendererUpdateManager.startScheduledChecks();
+ this.coreUpdateManager.startScheduledChecks();
this.screenCaptureManager.prewarmPermissionCheck();
logger.info('Post-first-frame initialization completed');
diff --git a/apps/desktop/src/main/core/infrastructure/RendererUrlManager.ts b/apps/desktop/src/main/core/infrastructure/RendererUrlManager.ts
index dfae15a65f8..18f24fdc9a5 100644
--- a/apps/desktop/src/main/core/infrastructure/RendererUrlManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/RendererUrlManager.ts
@@ -26,6 +26,7 @@ export class RendererUrlManager {
private readonly rendererStaticOverride = getDesktopEnv().DESKTOP_RENDERER_STATIC;
private readonly rendererLoadedUrl: string;
private activeRendererDir = rendererDir;
+ private previousRendererDir: string | null = null;
constructor() {
this.rendererProtocolManager = new RendererProtocolManager({
@@ -56,6 +57,7 @@ export class RendererUrlManager {
return;
}
logger.info(`Renderer serving root: ${next}`);
+ if (next !== this.activeRendererDir) this.previousRendererDir = this.activeRendererDir;
this.activeRendererDir = next;
}
@@ -98,7 +100,11 @@ export class RendererUrlManager {
// Static assets: direct file mapping
if (pathname.startsWith('/assets/') || path.extname(pathname)) {
const filePath = path.join(root, pathname);
- return existsSync(filePath) ? filePath : null;
+ if (existsSync(filePath)) return filePath;
+ // Windows that cancelled the OTA reload via beforeunload still lazy-load
+ // hash-named chunks from the previous tree.
+ const previous = this.previousRendererDir && path.join(this.previousRendererDir, pathname);
+ return previous && pathname.startsWith('/assets/') && existsSync(previous) ? previous : null;
}
// Overlay entry (separate MPA page)
diff --git a/apps/desktop/src/main/core/infrastructure/UpdaterManager.ts b/apps/desktop/src/main/core/infrastructure/UpdaterManager.ts
index 06f47f410a1..30b1ad08868 100644
--- a/apps/desktop/src/main/core/infrastructure/UpdaterManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/UpdaterManager.ts
@@ -269,7 +269,7 @@ export class UpdaterManager {
}
};
- private captureRestoreRoute = () => {
+ captureRestoreRoute = () => {
try {
const url = this.mainWindow.webContents?.getURL();
if (!url) return;
diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.ts b/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.ts
new file mode 100644
index 00000000000..148d7103de3
--- /dev/null
+++ b/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.ts
@@ -0,0 +1,508 @@
+import { createHash } from 'node:crypto';
+import { existsSync, readFileSync, rmSync } from 'node:fs';
+import path from 'node:path';
+
+import type { UpdateChannel } from '@lobechat/electron-client-ipc';
+import { app as electronApp, BrowserWindow, net } from 'electron';
+
+import { type ShellGlobal, shellInfo } from '@/const/shell';
+import {
+ BUILD_CHANNEL,
+ coerceStoredUpdateChannel,
+ UPDATE_CHANNEL,
+ UPDATE_SERVER_URL,
+} from '@/modules/updater/configs';
+import { createLogger } from '@/utils/logger';
+
+import type { App } from '../../App';
+import { type ApplyMode, computeApplyMode } from './applyMode';
+import {
+ builtinManifestSchema,
+ type CoreManifest,
+ coreManifestSchema,
+ verifyManifestSignature,
+} from './manifest';
+import {
+ type CorePointer,
+ emptyPointer,
+ readPointer,
+ readPointerAbi,
+ writePointer,
+} from './pointer';
+import { cleanupLegacy, CoreStore } from './store';
+
+const logger = createLogger('core:CoreUpdateManager');
+
+const BOOT_CHECK_TIMEOUT = 15_000;
+const COLD_BOOT_CHECK_TIMEOUT = 60_000;
+const FETCH_TIMEOUT = 60_000;
+const DOWNLOAD_TIMEOUT = 15 * 60 * 1000;
+const LOAD_PING_TIMEOUT = 3000;
+const MAX_BOOT_CRASHES = 2;
+const CHECK_INTERVAL = 60 * 60 * 1000;
+const FIRST_CHECK_DELAY = Number(process.env['RENDERER_OTA_CHECK_DELAY']) || 90 * 1000;
+const IDLE_APPLY_DELAY = 5 * 60 * 1000;
+const RENDERER_ROOT = 'dist/renderer';
+const FEED_BASE_URL =
+ UPDATE_SERVER_URL?.replace(/\/(stable|nightly|canary|beta)\/?$/, '').replace(/\/$/, '') || '';
+
+type FetchImpl = (url: string, init?: RequestInit) => Promise<Response>;
+type CoreChannel = CoreManifest['channel'];
+type Staged = { applyMode: ApplyMode; version: string };
+type Options = { fetchImpl?: FetchImpl; shell?: ShellGlobal };
+
+const readBuiltinManifest = (shell: ShellGlobal): CoreManifest | null => {
+ if (shell.source === 'builtin') return shell.manifest;
+ try {
+ const raw = JSON.parse(readFileSync(path.join(shell.builtinDir, 'manifest.json'), 'utf8'));
+ return builtinManifestSchema.parse(raw);
+ } catch {
+ return null;
+ }
+};
+
+class SkipCheck extends Error {}
+
+export class CoreUpdateManager {
+ private readonly app: App;
+ private readonly shell: ShellGlobal | undefined;
+ private readonly fetchImpl: FetchImpl;
+ private readonly otaRoot: string;
+ private readonly store: CoreStore;
+ private readonly builtinManifest: CoreManifest | null;
+ readonly disabledReasons: string[];
+ private activeChannel: CoreChannel;
+ private pointer: CorePointer;
+ private staged: Staged | null = null;
+ private busy = false;
+ private checkGeneration = 0;
+ private lastCheckAt: number | null = null;
+ private lastError: string | null = null;
+ private needsFullRelease = false;
+ private unloadPrevented = false;
+ private rollbackRendererDir: string | null = null;
+ private pendingBootCheck = false;
+ private coldBootCheck = false;
+ private mountedSeen = false;
+ private bootCrashCount = 0;
+ private bootCheckTimer: NodeJS.Timeout | null = null;
+ private loadPingTimer: NodeJS.Timeout | null = null;
+ private checkTimer: NodeJS.Timeout | null = null;
+ private checkInterval: NodeJS.Timeout | null = null;
+ private idleTimer: NodeJS.Timeout | null = null;
+ private gcTask: Promise<void> = Promise.resolve();
+ private checkTask: Promise<void> = Promise.resolve();
+
+ constructor(app: App, options: Options = {}) {
+ this.app = app;
+ this.shell = options.shell ?? shellInfo;
+ this.fetchImpl =
+ options.fetchImpl ??
+ ((url, init) => net.fetch(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT), ...init }));
+ this.otaRoot = path.join(electronApp.getPath('userData'), 'core-ota');
+ this.store = new CoreStore(this.otaRoot, (url) =>
+ this.fetchImpl(url, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT) }),
+ );
+ this.builtinManifest = this.shell ? readBuiltinManifest(this.shell) : null;
+ this.activeChannel = this.coreChannel(
+ coerceStoredUpdateChannel(this.app.storeManager.get('updateChannel') as string | undefined) ||
+ UPDATE_CHANNEL,
+ );
+ this.pointer = emptyPointer(this.shell?.abi ?? '');
+ this.disabledReasons = [
+ !this.shell && 'missing-shell',
+ this.shell && !this.shell.manifest && 'missing-core-manifest',
+ this.shell && !this.builtinManifest && 'missing-builtin-manifest',
+ this.shell && !this.shell.publicKey && 'missing-public-key',
+ !FEED_BASE_URL && 'missing-server-url',
+ ].filter((reason): reason is string => typeof reason === 'string');
+ }
+
+ get enabled() {
+ return this.disabledReasons.length === 0;
+ }
+
+ private get running() {
+ return this.shell!.manifest!;
+ }
+
+ private get runningVersion() {
+ return this.shell?.source === 'external' ? this.running.version : null;
+ }
+
+ private get keepVersions() {
+ const { current, previous, staged } = this.pointer;
+ return [current, previous, staged, this.runningVersion].filter((v): v is string => !!v);
+ }
+
+ initialize = () => {
+ logger.info('Core OTA configuration', {
+ abi: this.shell?.abi,
+ channel: this.activeChannel,
+ disabledReasons: this.disabledReasons,
+ enabled: this.enabled,
+ running: this.runningVersion ?? 'builtin',
+ source: this.shell?.source,
+ });
+ if (!this.enabled) return;
+
+ rmSync(path.join(this.otaRoot, 'staging'), { force: true, recursive: true });
+ cleanupLegacy(electronApp.getPath('userData')).catch((error) =>
+ logger.warn('Legacy renderer OTA cleanup failed:', error),
+ );
+ const abiChanged = readPointerAbi(this.otaRoot) !== this.shell!.abi;
+ const stored = readPointer(this.otaRoot, this.shell!.abi);
+ this.pointer = { ...this.reconcilePointer(stored), channel: this.activeChannel };
+ writePointer(this.otaRoot, this.pointer);
+ logger.info('Core OTA boot state', this.pointer);
+ this.gc(abiChanged);
+ };
+
+ private reconcilePointer(pointer: CorePointer): CorePointer {
+ const running = this.runningVersion;
+ if (!running && pointer.current) {
+ const rejected = existsSync(path.join(this.coreDirOf(pointer.current), 'manifest.json'));
+ return {
+ ...pointer,
+ blacklist: rejected
+ ? [...new Set([...pointer.blacklist, pointer.current])]
+ : pointer.blacklist,
+ current: null,
+ previous: null,
+ };
+ }
+ if (running && pointer.current !== running) {
+ return { ...pointer, current: running, previous: null };
+ }
+ return pointer;
+ }
+
+ private isFirstBootOfRunningCore() {
+ try {
+ const boot = JSON.parse(readFileSync(path.join(this.otaRoot, 'boot.json'), 'utf8'));
+ return boot?.version === this.runningVersion && boot?.healthy !== true;
+ } catch {
+ return false;
+ }
+ }
+
+ startScheduledChecks = () => {
+ if (!this.enabled) return;
+ if (this.runningVersion && !this.mountedSeen && this.isFirstBootOfRunningCore()) {
+ this.armBootCheck({ cold: true });
+ }
+ electronApp.on('browser-window-blur', this.handleWindowBlur);
+ electronApp.on('browser-window-focus', this.clearIdleTimer);
+ this.scheduleChecks();
+ };
+
+ switchChannel = (channel: UpdateChannel) => {
+ const next = this.coreChannel(channel);
+ if (next === this.activeChannel) return;
+ logger.info('Core OTA channel changed', { from: this.activeChannel, to: next });
+ this.activeChannel = next;
+ if (!this.enabled) return;
+ this.checkGeneration += 1;
+ this.busy = false;
+ this.savePointer({
+ channel: next,
+ staged: null,
+ ...(this.staged?.applyMode === 'relaunch'
+ ? { current: this.pointer.previous, previous: null }
+ : {}),
+ });
+ this.staged = null;
+ this.gc();
+ if (this.checkTimer || this.checkInterval) this.scheduleChecks();
+ };
+
+ handleBootPing = (stage?: 'loaded' | 'mounted') => {
+ if (stage !== 'loaded') this.mountedSeen = true;
+ if (!this.pendingBootCheck) return;
+ if (stage === 'loaded') {
+ this.clearLoadPingTimer();
+ return;
+ }
+ logger.info(`Core ${this.pointer.current} boot check passed`);
+ this.clearBootTimers();
+ this.pendingBootCheck = false;
+ this.bootCrashCount = 0;
+ this.rollbackRendererDir = null;
+ this.gc();
+ };
+
+ handleRendererCrash = () => {
+ if (!this.pendingBootCheck) return;
+ this.bootCrashCount += 1;
+ logger.warn(`Renderer crashed during boot check (${this.bootCrashCount}/${MAX_BOOT_CRASHES})`);
+ if (this.bootCrashCount >= MAX_BOOT_CRASHES) this.failBootCheck('renderer-crash');
+ };
+
+ handleUnloadPrevented = () => {
+ this.unloadPrevented = true;
+ if (!this.pendingBootCheck || this.coldBootCheck) return;
+ logger.info('Reload cancelled by renderer, cancelling boot check');
+ this.clearBootTimers();
+ this.pendingBootCheck = false;
+ this.rollbackRendererDir = null;
+ };
+
+ applyStagedNow = () => {
+ if (!this.staged) return false;
+ if (this.staged.applyMode === 'relaunch') {
+ this.relaunchIntoCore();
+ return true;
+ }
+ const { version } = this.staged;
+ logger.info(`Applying core ${version} renderer now`);
+ const rendererDir = this.rendererDirOf(version);
+ this.rollbackRendererDir = this.app.rendererUrlManager.getActiveRendererDir();
+ this.app.rendererUrlManager.setActiveRendererDir(rendererDir);
+ if (this.app.rendererUrlManager.getActiveRendererDir() !== rendererDir) {
+ logger.warn('Core OTA staged apply rejected', { reason: 'renderer-dir-unusable', version });
+ this.app.rendererUrlManager.setActiveRendererDir(this.rollbackRendererDir);
+ this.rollbackRendererDir = null;
+ this.savePointer({
+ blacklist: [...new Set([...this.pointer.blacklist, version])],
+ staged: null,
+ });
+ this.staged = null;
+ return false;
+ }
+ this.savePointer({ current: version, previous: this.pointer.current, staged: null });
+ this.staged = null;
+ this.clearIdleTimer();
+ this.reloadAllWindows();
+ this.armBootCheck();
+ return true;
+ };
+
+ getStatus = () => ({
+ applyMode: this.staged?.applyMode ?? null,
+ current: this.pointer.current,
+ disabledReasons: this.disabledReasons,
+ enabled: this.enabled,
+ lastCheckAt: this.lastCheckAt,
+ lastError: this.lastError,
+ needsFullRelease: this.needsFullRelease,
+ staged: this.staged?.version ?? null,
+ });
+
+ checkForUpdates = () => {
+ this.checkTask = this.checkTask.catch(() => {}).then(() => this.runCheck());
+ return this.checkTask;
+ };
+
+ private async runCheck() {
+ if (!this.enabled || this.busy || this.staged) {
+ logger.info('Core OTA check skipped', {
+ reason: !this.enabled ? 'disabled' : this.busy ? 'busy' : 'already-staged',
+ });
+ return;
+ }
+ const generation = this.checkGeneration;
+ const feedUrl = this.feedUrl();
+ this.busy = true;
+ this.lastCheckAt = Date.now();
+ let outcome = 'skipped';
+ try {
+ const remote = await this.fetchRemote(feedUrl, generation);
+ if (!remote) return;
+ const { version } = remote;
+ this.needsFullRelease = remote.shellAbi !== this.shell!.abi;
+ if (this.needsFullRelease) throw new SkipCheck('needs-full-release');
+ if (remote.channel === this.running.channel && remote.seq <= this.running.seq)
+ throw new SkipCheck('up-to-date');
+ if (version === this.pointer.current) throw new SkipCheck('already-current');
+ if (this.pointer.blacklist.includes(version)) throw new SkipCheck('blacklisted');
+ if (!this.inRollout(version, remote.rollout)) throw new SkipCheck('rollout-excluded');
+
+ await this.gcTask;
+ const staged = await this.store.stage({
+ builtin: { dir: this.shell!.builtinDir, manifest: this.builtinManifest! },
+ current:
+ this.shell!.source === 'external'
+ ? { dir: this.shell!.coreDir, manifest: this.running }
+ : null,
+ objectsBaseUrl: remote.objectsBaseUrl,
+ packsBaseUrl: feedUrl,
+ remote,
+ });
+ if (generation !== this.checkGeneration) throw new SkipCheck('superseded');
+ const applyMode = computeApplyMode(this.running.tree, remote.tree);
+ logger.info('Core OTA staged', { applyMode, version, ...staged.downloaded });
+ this.staged = { applyMode, version };
+ this.unloadPrevented = false;
+ this.savePointer(
+ applyMode === 'relaunch'
+ ? { current: version, previous: this.pointer.current, staged: null }
+ : { staged: version },
+ );
+ this.lastError = null;
+ this.app.browserManager.broadcastToAllWindows('updateReady', {
+ kind: applyMode === 'relaunch' ? 'core-relaunch' : 'core-reload',
+ version,
+ });
+ this.gc();
+ if (applyMode === 'reload') this.handleWindowBlur();
+ outcome = 'staged';
+ } catch (error) {
+ if (error instanceof SkipCheck) {
+ outcome = error.message;
+ return;
+ }
+ outcome = 'failed';
+ this.lastError = error instanceof Error ? error.message : String(error);
+ logger.error('Core OTA check failed:', error);
+ if (generation === this.checkGeneration) {
+ rmSync(path.join(this.otaRoot, 'staging'), { force: true, recursive: true });
+ }
+ } finally {
+ if (generation === this.checkGeneration) this.busy = false;
+ logger.info('Core OTA check finished', { channel: this.activeChannel, outcome });
+ }
+ }
+
+ private async fetchRemote(feedUrl: string, generation: number): Promise<CoreManifest | null> {
+ const res = await this.fetchImpl(`${feedUrl}/latest.json`, { cache: 'no-store' });
+ if (res.status === 404) throw new SkipCheck('feed-not-found');
+ if (!res.ok) throw new Error(`Manifest fetch failed: ${res.status}`);
+ const parsed = coreManifestSchema.safeParse(await res.json());
+ if (!parsed.success) throw new Error('Manifest shape invalid');
+ const remote = parsed.data;
+ if (!verifyManifestSignature(remote, this.shell!.publicKey)) {
+ throw new Error('Manifest signature invalid');
+ }
+ if (generation !== this.checkGeneration) throw new SkipCheck('superseded');
+ if (remote.channel !== this.activeChannel) throw new Error('Manifest channel mismatch');
+ if (remote.platform !== process.platform) throw new Error('Manifest platform mismatch');
+ return remote;
+ }
+
+ private inRollout(version: string, rollout: number) {
+ if (rollout >= 1) return true;
+ const digest = createHash('sha256')
+ .update(electronApp.getPath('userData') + version)
+ .digest();
+ return digest.readUInt32BE(0) / 2 ** 32 < rollout;
+ }
+
+ private coreChannel(channel: UpdateChannel): CoreChannel {
+ return BUILD_CHANNEL === 'beta' && channel === 'canary' ? 'beta' : channel;
+ }
+
+ private feedUrl() {
+ return `${FEED_BASE_URL}/${this.activeChannel}/core/${process.platform}`;
+ }
+
+ private coreDirOf(version: string) {
+ return path.join(this.otaRoot, 'cores', version);
+ }
+
+ private rendererDirOf(version: string) {
+ return path.join(this.coreDirOf(version), RENDERER_ROOT);
+ }
+
+ private savePointer(patch: Partial<CorePointer>) {
+ this.pointer = { ...this.pointer, ...patch };
+ writePointer(this.otaRoot, this.pointer);
+ }
+
+ private scheduleChecks() {
+ if (this.checkTimer) clearTimeout(this.checkTimer);
+ if (this.checkInterval) clearInterval(this.checkInterval);
+ this.checkTimer = setTimeout(() => this.checkForUpdates(), FIRST_CHECK_DELAY);
+ this.checkInterval = setInterval(() => this.checkForUpdates(), CHECK_INTERVAL);
+ this.checkTimer.unref?.();
+ this.checkInterval.unref?.();
+ }
+
+ private relaunchIntoCore() {
+ logger.info(`Relaunching into core ${this.pointer.current}`);
+ this.app.updaterManager?.captureRestoreRoute();
+ this.app.isQuiting = true;
+ electronApp.releaseSingleInstanceLock();
+ electronApp.relaunch(
+ process.env.APPIMAGE
+ ? { args: process.argv.slice(1), execPath: process.env.APPIMAGE }
+ : { args: process.argv.slice(1) },
+ );
+ electronApp.quit();
+ }
+
+ private handleWindowBlur = () => {
+ if (BrowserWindow.getAllWindows().some((window) => window.isFocused())) return;
+ this.clearIdleTimer();
+ this.idleTimer = setTimeout(() => {
+ if (this.staged?.applyMode === 'reload' && !this.unloadPrevented) this.applyStagedNow();
+ }, IDLE_APPLY_DELAY);
+ this.idleTimer.unref?.();
+ };
+
+ private clearIdleTimer = () => {
+ if (this.idleTimer) clearTimeout(this.idleTimer);
+ this.idleTimer = null;
+ };
+
+ private failBootCheck(reason: string) {
+ this.clearBootTimers();
+ const bad = this.pointer.current;
+ const coldBoot = this.coldBootCheck;
+ logger.warn('Core OTA rolled back', { coldBoot, failedVersion: bad, reason });
+ this.pendingBootCheck = false;
+ this.savePointer({
+ blacklist: bad ? [...new Set([...this.pointer.blacklist, bad])] : this.pointer.blacklist,
+ current: this.pointer.previous,
+ previous: null,
+ });
+ if (coldBoot) {
+ this.relaunchIntoCore();
+ return;
+ }
+ this.app.rendererUrlManager.setActiveRendererDir(this.rollbackRendererDir);
+ this.rollbackRendererDir = null;
+ this.gc();
+ this.reloadAllWindows();
+ }
+
+ private armBootCheck({ cold = false } = {}) {
+ this.pendingBootCheck = true;
+ this.coldBootCheck = cold;
+ this.bootCrashCount = 0;
+ this.clearBootTimers();
+ if (!cold) {
+ this.loadPingTimer = setTimeout(() => this.failBootCheck('load-timeout'), LOAD_PING_TIMEOUT);
+ this.loadPingTimer.unref?.();
+ }
+ this.bootCheckTimer = setTimeout(
+ () => this.failBootCheck('boot-timeout'),
+ cold ? COLD_BOOT_CHECK_TIMEOUT : BOOT_CHECK_TIMEOUT,
+ );
+ this.bootCheckTimer.unref?.();
+ }
+
+ private clearLoadPingTimer() {
+ if (this.loadPingTimer) clearTimeout(this.loadPingTimer);
+ this.loadPingTimer = null;
+ }
+
+ private clearBootTimers() {
+ this.clearLoadPingTimer();
+ if (this.bootCheckTimer) clearTimeout(this.bootCheckTimer);
+ this.bootCheckTimer = null;
+ }
+
+ private reloadAllWindows() {
+ this.app.browserManager.browsers.forEach((browser) => {
+ try {
+ browser.browserWindow.webContents.reloadIgnoringCache();
+ } catch {}
+ });
+ }
+
+ private gc(keepStore = false) {
+ this.gcTask = this.gcTask
+ .then(() => this.store.gc(this.keepVersions, { keepStore }))
+ .catch((error) => logger.warn('Core OTA gc failed:', error));
+ }
+}
diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/CoreUpdateManager.int.test.ts b/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/CoreUpdateManager.int.test.ts
new file mode 100644
index 00000000000..4f042235740
--- /dev/null
+++ b/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/CoreUpdateManager.int.test.ts
@@ -0,0 +1,768 @@
+import { generateKeyPairSync, sign } from 'node:crypto';
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { constants, zstdCompressSync } from 'node:zlib';
+
+import { zipSync } from 'fflate';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { ShellGlobal } from '@/const/shell';
+
+import { canonicalJson, type CoreManifest, sha256File } from '../manifest';
+import { readPointer, writePointer } from '../pointer';
+import { SAFE_VERSION } from '../store';
+
+const { privateKey, publicKey } = generateKeyPairSync('ed25519');
+const PUBLIC_KEY_PEM = publicKey.export({ format: 'pem', type: 'spki' }).toString();
+const ABI = 'a'.repeat(64);
+const SERVER = 'https://updates.test';
+const OBJECTS = 'https://cdn.test/cas';
+const PLATFORM = process.platform as CoreManifest['platform'];
+
+const BASE_FILES: Record<string, string> = {
+ 'dist/main/index.js': 'main-v1',
+ 'dist/renderer/apps/desktop/index.html': '<script src="/assets/index.js"></script>',
+ 'dist/renderer/apps/desktop/overlay.html': '<script src="/assets/overlay.js"></script>',
+ 'dist/renderer/apps/desktop/popup.html': '<script src="/assets/popup.js"></script>',
+ 'dist/renderer/assets/index.js': 'index-v1',
+ 'dist/renderer/assets/overlay.js': 'overlay',
+ 'dist/renderer/assets/popup.js': 'popup',
+ 'package.json': '{"main":"dist/main/index.js"}',
+};
+
+let userDataDir: string;
+let builtinDir: string;
+let served: Map<string, Buffer>;
+
+const { electronMock, loggerMock } = vi.hoisted(() => ({
+ electronMock: {
+ app: {
+ getPath: vi.fn(),
+ on: vi.fn(),
+ quit: vi.fn(),
+ relaunch: vi.fn(),
+ releaseSingleInstanceLock: vi.fn(),
+ },
+ BrowserWindow: { getAllWindows: vi.fn(() => []) },
+ net: { fetch: vi.fn() },
+ },
+ loggerMock: { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() },
+}));
+
+vi.mock('@/utils/logger', () => ({ createLogger: () => loggerMock }));
+vi.mock('electron', () => electronMock);
+vi.mock('@/modules/updater/configs', () => ({
+ BUILD_CHANNEL: 'stable',
+ UPDATE_CHANNEL: 'stable',
+ UPDATE_SERVER_URL: 'https://updates.test/stable',
+ coerceStoredUpdateChannel: (channel?: string) => (channel === 'canary' ? 'canary' : 'stable'),
+}));
+
+const makeApp = () => ({
+ browserManager: {
+ broadcastToAllWindows: vi.fn(),
+ browsers: new Map([
+ ['main', { browserWindow: { webContents: { reloadIgnoringCache: vi.fn() } } }],
+ ]),
+ },
+ isQuiting: false,
+ rendererUrlManager: {
+ activeDir: null as string | null,
+ getActiveRendererDir() {
+ return this.activeDir;
+ },
+ setActiveRendererDir: vi.fn(function (this: { activeDir: string | null }, dir: string | null) {
+ this.activeDir = dir;
+ }),
+ },
+ storeManager: { get: vi.fn(() => 'stable') },
+ updaterManager: { captureRestoreRoute: vi.fn() },
+});
+
+const signManifest = (unsigned: Omit<CoreManifest, 'signature'>): CoreManifest => ({
+ ...unsigned,
+ signature: sign(null, Buffer.from(canonicalJson(unsigned)), privateKey).toString('base64'),
+});
+
+const zst = (content: Buffer) =>
+ zstdCompressSync(content, { params: { [constants.ZSTD_c_compressionLevel]: 3 } });
+
+const buildManifest = (
+ version: string,
+ seq: number,
+ files: Record<string, string>,
+ overrides: Partial<Omit<CoreManifest, 'signature'>> = {},
+): CoreManifest => {
+ const objects = new Map(Object.entries(files).map(([p, c]) => [p, Buffer.from(c)] as const));
+ const tree = [...objects]
+ .map(([p, content]) => ({ path: p, sha256: sha256File(content), size: content.length }))
+ .sort((a, b) => a.path.localeCompare(b.path));
+ const zippable: Record<string, Uint8Array> = {};
+ for (const [, content] of objects) zippable[`objects/${sha256File(content)}`] = content;
+ const pack = Buffer.from(zipSync(zippable));
+ const packSha = sha256File(pack);
+ served.set(`${SERVER}/stable/core/${PLATFORM}/packs/${packSha}.zip`, pack);
+ for (const [, content] of objects) {
+ served.set(`${OBJECTS}/objects/${sha256File(content)}.zst`, zst(content));
+ }
+ return signManifest({
+ applyMode: null,
+ channel: 'stable',
+ full: { path: `packs/${packSha}.zip`, sha256: packSha, size: pack.length },
+ objectsBaseUrl: OBJECTS,
+ patches: [],
+ platform: PLATFORM,
+ previous: null,
+ rollout: 1,
+ schemaVersion: 3,
+ seq,
+ shellAbi: ABI,
+ tree,
+ version,
+ ...overrides,
+ });
+};
+
+const materialize = (dir: string, files: Record<string, string>, manifest: CoreManifest) => {
+ for (const [p, c] of Object.entries(files)) {
+ mkdirSync(path.dirname(path.join(dir, p)), { recursive: true });
+ writeFileSync(path.join(dir, p), c);
+ }
+ writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify(manifest));
+};
+
+const serveLatest = (manifest: CoreManifest | null) => {
+ const url = `${SERVER}/stable/core/${PLATFORM}/latest.json`;
+ if (manifest) served.set(url, Buffer.from(JSON.stringify(manifest)));
+ else served.delete(url);
+};
+
+const fetchImpl = vi.fn(async (url: string) =>
+ served.has(url)
+ ? new Response(new Uint8Array(served.get(url)!))
+ : new Response('nope', { status: 404 }),
+);
+
+const otaRoot = () => path.join(userDataDir, 'core-ota');
+const storeDir = () => path.join(otaRoot(), 'store');
+const pointerAt = (patch: Partial<ReturnType<typeof readPointer>>) =>
+ writePointer(otaRoot(), {
+ abi: ABI,
+ blacklist: [],
+ channel: 'stable',
+ current: null,
+ previous: null,
+ staged: null,
+ ...patch,
+ });
+const coreDir = (version: string) => path.join(otaRoot(), 'cores', version);
+
+const makeShell = (overrides: Partial<ShellGlobal> = {}): ShellGlobal => ({
+ abi: ABI,
+ builtinDir,
+ coreDir: builtinDir,
+ log: [],
+ manifest: builtinManifest,
+ markHealthy: () => {},
+ publicKey: PUBLIC_KEY_PEM,
+ shellVersion: '1.0.0',
+ source: 'builtin',
+ ...overrides,
+});
+
+const loadManager = async (app = makeApp(), shell: ShellGlobal | null = makeShell()) => {
+ vi.resetModules();
+ const { CoreUpdateManager } = await import('../CoreUpdateManager');
+ const manager = new CoreUpdateManager(app as never, { fetchImpl, shell: shell ?? undefined });
+ manager.initialize();
+ return { app, manager };
+};
+
+const flushGc = () => new Promise((resolve) => setTimeout(resolve, 20));
+
+let builtinManifest: CoreManifest;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ served = new Map();
+ userDataDir = mkdtempSync(path.join(tmpdir(), 'core-ota-user-'));
+ builtinDir = mkdtempSync(path.join(tmpdir(), 'core-ota-builtin-'));
+ electronMock.app.getPath.mockReturnValue(userDataDir);
+ builtinManifest = buildManifest('1.0.0', 0, BASE_FILES);
+ materialize(builtinDir, BASE_FILES, builtinManifest);
+});
+
+afterEach(() => {
+ rmSync(userDataDir, { force: true, recursive: true });
+ rmSync(builtinDir, { force: true, recursive: true });
+});
+
+const rendererOnly = (version: string, seq: number) =>
+ buildManifest(version, seq, {
+ ...BASE_FILES,
+ 'dist/renderer/assets/index.js': `index-${version}`,
+ });
+
+const mainChanged = (version: string, seq: number) =>
+ buildManifest(version, seq, { ...BASE_FILES, 'dist/main/index.js': `main-${version}` });
+
+describe('CoreUpdateManager initialize', () => {
+ it('reports disabled reasons when shell is missing', async () => {
+ const { manager } = await loadManager(makeApp(), null);
+ expect(manager.enabled).toBe(false);
+ expect(manager.disabledReasons).toEqual(['missing-shell']);
+ });
+
+ it('reports disabled reasons when public key is missing', async () => {
+ const { manager } = await loadManager(makeApp(), makeShell({ publicKey: '' }));
+ expect(manager.disabledReasons).toEqual(['missing-public-key']);
+ });
+
+ it('resets pointer and clears cores when abi changed', async () => {
+ mkdirSync(coreDir('0.9.0'), { recursive: true });
+ writePointer(otaRoot(), {
+ abi: 'b'.repeat(64),
+ blacklist: ['0.8.0'],
+ channel: 'stable',
+ current: '0.9.0',
+ previous: null,
+ staged: null,
+ });
+
+ const { manager } = await loadManager();
+ await flushGc();
+
+ expect(manager.getStatus().current).toBeNull();
+ expect(readPointer(otaRoot(), ABI)).toMatchObject({ blacklist: [], current: null });
+ expect(existsSync(coreDir('0.9.0'))).toBe(false);
+ });
+
+ it('keeps store objects across an abi reset', async () => {
+ mkdirSync(storeDir(), { recursive: true });
+ writeFileSync(path.join(storeDir(), 'f'.repeat(64)), 'blob');
+ pointerAt({ abi: 'b'.repeat(64) } as never);
+
+ await loadManager();
+ await flushGc();
+
+ expect(existsSync(path.join(storeDir(), 'f'.repeat(64)))).toBe(true);
+ });
+
+ it('clears pointer.current when the shell fell back to builtin and the core dir is gone', async () => {
+ pointerAt({ current: '1.0.1', previous: '0.9.0' });
+
+ const { manager } = await loadManager();
+
+ expect(readPointer(otaRoot(), ABI)).toMatchObject({
+ blacklist: [],
+ current: null,
+ previous: null,
+ });
+ serveLatest(rendererOnly('1.0.1', 1));
+ await manager.checkForUpdates();
+ expect(manager.getStatus().staged).toBe('1.0.1');
+ });
+
+ it('blacklists pointer.current when the shell rejected a core that still exists', async () => {
+ const v1 = rendererOnly('1.0.1', 1);
+ materialize(coreDir('1.0.1'), BASE_FILES, v1);
+ pointerAt({ current: '1.0.1' });
+
+ await loadManager();
+
+ expect(readPointer(otaRoot(), ABI)).toMatchObject({ blacklist: ['1.0.1'], current: null });
+ });
+
+ it('realigns pointer.current with the running external core', async () => {
+ const v1Files = { ...BASE_FILES, 'dist/renderer/assets/index.js': 'index-1.0.1' };
+ const v1 = buildManifest('1.0.1', 1, v1Files);
+ materialize(coreDir('1.0.1'), v1Files, v1);
+ pointerAt({ current: '1.0.2', previous: '1.0.1' });
+
+ await loadManager(
+ makeApp(),
+ makeShell({ coreDir: coreDir('1.0.1'), manifest: v1, source: 'external' }),
+ );
+
+ expect(readPointer(otaRoot(), ABI)).toMatchObject({ current: '1.0.1', previous: null });
+ });
+
+ it('accepts an unsigned builtin manifest while running an external core', async () => {
+ materialize(builtinDir, BASE_FILES, { ...builtinManifest, signature: '' });
+ const v1Files = { ...BASE_FILES, 'dist/renderer/assets/index.js': 'index-1.0.1' };
+ const v1 = buildManifest('1.0.1', 1, v1Files);
+ materialize(coreDir('1.0.1'), v1Files, v1);
+ pointerAt({ current: '1.0.1' });
+
+ const { manager } = await loadManager(
+ makeApp(),
+ makeShell({ coreDir: coreDir('1.0.1'), manifest: v1, source: 'external' }),
+ );
+
+ expect(manager.disabledReasons).toEqual([]);
+ });
+
+ it('shares the version-name rule with the shell loader', () => {
+ const loader = readFileSync(
+ path.join(__dirname, '../../../../../../shell/core-loader.js'),
+ 'utf8',
+ );
+ expect(loader).toContain(`const VERSION_NAME = ${SAFE_VERSION};`);
+ });
+
+ describe('cold-boot check for an external core', () => {
+ const bootExternal = async (bootJson: unknown) => {
+ const v1Files = { ...BASE_FILES, 'dist/renderer/assets/index.js': 'index-1.0.1' };
+ const v1 = buildManifest('1.0.1', 1, v1Files);
+ materialize(coreDir('1.0.1'), v1Files, v1);
+ pointerAt({ current: '1.0.1', previous: null });
+ writeFileSync(path.join(otaRoot(), 'boot.json'), JSON.stringify(bootJson));
+ return loadManager(
+ makeApp(),
+ makeShell({ coreDir: coreDir('1.0.1'), manifest: v1, source: 'external' }),
+ );
+ };
+
+ it('rolls back and relaunches when the first boot of a version never mounts', async () => {
+ vi.useFakeTimers();
+ try {
+ const { app, manager } = await bootExternal({ failures: 1, version: '1.0.1' });
+ manager.startScheduledChecks();
+
+ vi.advanceTimersByTime(30_000);
+ expect(electronMock.app.relaunch).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(31_000);
+
+ expect(readPointer(otaRoot(), ABI)).toMatchObject({ blacklist: ['1.0.1'], current: null });
+ expect(electronMock.app.relaunch).toHaveBeenCalled();
+ expect(app.rendererUrlManager.setActiveRendererDir).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('does not arm when the renderer already mounted before scheduling', async () => {
+ vi.useFakeTimers();
+ try {
+ const { manager } = await bootExternal({ failures: 1, version: '1.0.1' });
+ manager.handleBootPing('mounted');
+ manager.startScheduledChecks();
+
+ vi.advanceTimersByTime(120_000);
+
+ expect(electronMock.app.relaunch).not.toHaveBeenCalled();
+ expect(readPointer(otaRoot(), ABI).blacklist).toEqual([]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('does not arm on later boots of an already-confirmed version', async () => {
+ vi.useFakeTimers();
+ try {
+ const { manager } = await bootExternal({ failures: 1, healthy: true, version: '1.0.1' });
+ manager.startScheduledChecks();
+
+ vi.advanceTimersByTime(120_000);
+
+ expect(electronMock.app.relaunch).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+ });
+});
+
+describe('CoreUpdateManager checkForUpdates', () => {
+ it('is up-to-date when remote seq does not increase', async () => {
+ serveLatest(rendererOnly('1.0.1', 0));
+ const { app, manager } = await loadManager();
+
+ await manager.checkForUpdates();
+
+ expect(manager.getStatus().staged).toBeNull();
+ expect(app.browserManager.broadcastToAllWindows).not.toHaveBeenCalled();
+ expect(existsSync(coreDir('1.0.1'))).toBe(false);
+ });
+
+ it('stages a lower-seq core from the newly selected channel', async () => {
+ const canary = buildManifest('1.0.1', 0, BASE_FILES, { channel: 'canary' });
+ materialize(coreDir('1.0.1'), BASE_FILES, canary);
+ pointerAt({ channel: 'canary', current: '1.0.1' });
+ const { manager } = await loadManager(
+ makeApp(),
+ makeShell({
+ coreDir: coreDir('1.0.1'),
+ manifest: { ...canary, seq: 300 },
+ source: 'external',
+ }),
+ );
+ serveLatest(rendererOnly('1.0.2', 20));
+
+ manager.switchChannel('stable');
+ await manager.checkForUpdates();
+
+ expect(manager.getStatus().staged).toBe('1.0.2');
+ expect(readPointer(otaRoot(), ABI).channel).toBe('stable');
+ });
+
+ it('rejects a manifest with a bad signature', async () => {
+ serveLatest({ ...rendererOnly('1.0.1', 1), signature: Buffer.from('bad').toString('base64') });
+ const { manager } = await loadManager();
+
+ await manager.checkForUpdates();
+
+ expect(manager.getStatus()).toMatchObject({
+ lastError: 'Manifest signature invalid',
+ staged: null,
+ });
+ });
+
+ it.each([
+ ['channel', { channel: 'canary' as const }, 'Manifest channel mismatch'],
+ [
+ 'platform',
+ { platform: PLATFORM === 'win32' ? 'linux' : 'win32' } as const,
+ 'Manifest platform mismatch',
+ ],
+ ])('rejects a %s mismatch', async (_label, overrides, message) => {
+ serveLatest(
+ buildManifest('1.0.1', 1, { ...BASE_FILES, 'dist/renderer/assets/index.js': 'x' }, overrides),
+ );
+ const { manager } = await loadManager();
+
+ await manager.checkForUpdates();
+
+ expect(manager.getStatus()).toMatchObject({ lastError: message, staged: null });
+ });
+
+ it('flags needsFullRelease when shell abi differs', async () => {
+ serveLatest(buildManifest('1.0.1', 1, BASE_FILES, { shellAbi: 'c'.repeat(64) }));
+ const { manager } = await loadManager();
+
+ await manager.checkForUpdates();
+
+ expect(manager.getStatus()).toMatchObject({ needsFullRelease: true, staged: null });
+ expect(existsSync(coreDir('1.0.1'))).toBe(false);
+ });
+
+ it('stages a renderer-only update as core-reload and applies it in place', async () => {
+ const remote = rendererOnly('1.0.1', 1);
+ serveLatest(remote);
+ const { app, manager } = await loadManager();
+ app.rendererUrlManager.activeDir = path.join(builtinDir, 'dist/renderer');
+
+ await manager.checkForUpdates();
+
+ expect(manager.getStatus()).toMatchObject({ applyMode: 'reload', staged: '1.0.1' });
+ expect(app.browserManager.broadcastToAllWindows).toHaveBeenCalledWith('updateReady', {
+ kind: 'core-reload',
+ version: '1.0.1',
+ });
+ expect(readPointer(otaRoot(), ABI)).toMatchObject({ current: null, staged: '1.0.1' });
+ expect(existsSync(path.join(coreDir('1.0.1'), 'dist/renderer/assets/index.js'))).toBe(true);
+
+ expect(manager.applyStagedNow()).toBe(true);
+
+ expect(app.rendererUrlManager.setActiveRendererDir).toHaveBeenCalledWith(
+ path.join(coreDir('1.0.1'), 'dist/renderer'),
+ );
+ expect(readPointer(otaRoot(), ABI)).toMatchObject({
+ current: '1.0.1',
+ previous: null,
+ staged: null,
+ });
+ expect(manager.getStatus().staged).toBeNull();
+ const reload =
+ app.browserManager.browsers.get('main')!.browserWindow.webContents.reloadIgnoringCache;
+ expect(reload).toHaveBeenCalledTimes(1);
+ });
+
+ it('stages a main-process change as core-relaunch and switches pointer immediately', async () => {
+ serveLatest(mainChanged('1.0.1', 1));
+ const { app, manager } = await loadManager();
+
+ await manager.checkForUpdates();
+
+ expect(manager.getStatus()).toMatchObject({ applyMode: 'relaunch', staged: '1.0.1' });
+ expect(app.browserManager.broadcastToAllWindows).toHaveBeenCalledWith('updateReady', {
+ kind: 'core-relaunch',
+ version: '1.0.1',
+ });
+ expect(readPointer(otaRoot(), ABI)).toMatchObject({
+ current: '1.0.1',
+ previous: null,
+ staged: null,
+ });
+
+ expect(manager.applyStagedNow()).toBe(true);
+
+ expect(app.updaterManager.captureRestoreRoute).toHaveBeenCalled();
+ expect(app.isQuiting).toBe(true);
+ expect(electronMock.app.releaseSingleInstanceLock).toHaveBeenCalled();
+ expect(electronMock.app.relaunch).toHaveBeenCalled();
+ expect(electronMock.app.quit).toHaveBeenCalled();
+ expect(app.rendererUrlManager.setActiveRendererDir).not.toHaveBeenCalled();
+ });
+
+ it('rolls back and blacklists the version when the boot check fails', async () => {
+ serveLatest(rendererOnly('1.0.1', 1));
+ const { app, manager } = await loadManager();
+ const builtinRenderer = path.join(builtinDir, 'dist/renderer');
+ app.rendererUrlManager.activeDir = builtinRenderer;
+ await manager.checkForUpdates();
+ manager.applyStagedNow();
+
+ manager.handleRendererCrash();
+ manager.handleRendererCrash();
+
+ expect(app.rendererUrlManager.activeDir).toBe(builtinRenderer);
+ expect(readPointer(otaRoot(), ABI)).toMatchObject({
+ blacklist: ['1.0.1'],
+ current: null,
+ previous: null,
+ });
+ const reload =
+ app.browserManager.browsers.get('main')!.browserWindow.webContents.reloadIgnoringCache;
+ expect(reload).toHaveBeenCalledTimes(2);
+
+ fetchImpl.mockClear();
+ await manager.checkForUpdates();
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
+ expect(manager.getStatus().staged).toBeNull();
+ });
+
+ it('clears the boot check on a successful ping', async () => {
+ serveLatest(rendererOnly('1.0.1', 1));
+ const { manager } = await loadManager();
+ await manager.checkForUpdates();
+ manager.applyStagedNow();
+
+ manager.handleBootPing('loaded');
+ manager.handleBootPing('mounted');
+ manager.handleRendererCrash();
+ manager.handleRendererCrash();
+
+ expect(readPointer(otaRoot(), ABI)).toMatchObject({ blacklist: [], current: '1.0.1' });
+ });
+
+ it('skips versions excluded by rollout', async () => {
+ serveLatest(buildManifest('1.0.1', 1, BASE_FILES, { rollout: 0 }));
+ const { manager } = await loadManager();
+
+ await manager.checkForUpdates();
+
+ expect(manager.getStatus().staged).toBeNull();
+ expect(existsSync(coreDir('1.0.1'))).toBe(false);
+ });
+
+ it('runs from an external core and keeps only current, previous and staged after gc', async () => {
+ const v1Files = { ...BASE_FILES, 'dist/renderer/assets/index.js': 'index-1.0.1' };
+ const v1 = buildManifest('1.0.1', 1, v1Files);
+ materialize(coreDir('1.0.1'), v1Files, v1);
+ for (const stale of ['0.9.0', '0.9.5']) mkdirSync(coreDir(stale), { recursive: true });
+ writePointer(otaRoot(), {
+ abi: ABI,
+ blacklist: [],
+ channel: 'stable',
+ current: '1.0.1',
+ previous: '0.9.5',
+ staged: null,
+ });
+ serveLatest(rendererOnly('1.0.2', 2));
+
+ const { manager } = await loadManager(
+ makeApp(),
+ makeShell({ coreDir: coreDir('1.0.1'), manifest: v1, source: 'external' }),
+ );
+ await flushGc();
+ expect(readdirSync(path.join(otaRoot(), 'cores')).sort()).toEqual(['0.9.5', '1.0.1']);
+
+ await manager.checkForUpdates();
+ await flushGc();
+
+ expect(manager.getStatus()).toMatchObject({ applyMode: 'reload', staged: '1.0.2' });
+ expect(readPointer(otaRoot(), ABI)).toMatchObject({
+ current: '1.0.1',
+ previous: '0.9.5',
+ staged: '1.0.2',
+ });
+ expect(readdirSync(path.join(otaRoot(), 'cores')).sort()).toEqual(['0.9.5', '1.0.1', '1.0.2']);
+ });
+
+ it('cancels the boot check instead of blacklisting when the renderer vetoes reload', async () => {
+ vi.useFakeTimers();
+ try {
+ serveLatest(rendererOnly('1.0.1', 1));
+ const { manager } = await loadManager();
+ await manager.checkForUpdates();
+ manager.applyStagedNow();
+
+ manager.handleUnloadPrevented();
+ vi.advanceTimersByTime(20_000);
+
+ expect(readPointer(otaRoot(), ABI)).toMatchObject({ blacklist: [], current: '1.0.1' });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('rolls back on load timeout', async () => {
+ vi.useFakeTimers();
+ try {
+ serveLatest(rendererOnly('1.0.1', 1));
+ const { manager } = await loadManager();
+ await manager.checkForUpdates();
+ manager.applyStagedNow();
+
+ vi.advanceTimersByTime(3500);
+
+ expect(readPointer(otaRoot(), ABI)).toMatchObject({ blacklist: ['1.0.1'], current: null });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('refuses to apply when the staged renderer dir is unusable', async () => {
+ serveLatest(rendererOnly('1.0.1', 1));
+ const { app, manager } = await loadManager();
+ await manager.checkForUpdates();
+ rmSync(path.join(coreDir('1.0.1'), 'dist/renderer/apps/desktop/index.html'));
+ app.rendererUrlManager.setActiveRendererDir = vi.fn(function (
+ this: { activeDir: string | null },
+ dir,
+ ) {
+ this.activeDir = dir && existsSync(path.join(dir, 'apps/desktop/index.html')) ? dir : null;
+ });
+
+ expect(manager.applyStagedNow()).toBe(false);
+
+ expect(readPointer(otaRoot(), ABI)).toMatchObject({
+ blacklist: ['1.0.1'],
+ current: null,
+ staged: null,
+ });
+ expect(manager.getStatus().staged).toBeNull();
+ });
+
+ it('reverts pointer.current when the channel switches after a relaunch stage', async () => {
+ serveLatest(mainChanged('1.0.1', 1));
+ const { manager } = await loadManager();
+ await manager.checkForUpdates();
+ expect(readPointer(otaRoot(), ABI).current).toBe('1.0.1');
+
+ manager.switchChannel('canary');
+ await flushGc();
+
+ expect(readPointer(otaRoot(), ABI)).toMatchObject({ current: null, previous: null });
+ expect(existsSync(coreDir('1.0.1'))).toBe(false);
+ });
+
+ it('auto-applies a reload-mode stage after five idle minutes, even when staged while idle', async () => {
+ vi.useFakeTimers();
+ try {
+ serveLatest(rendererOnly('1.0.1', 1));
+ const { app, manager } = await loadManager();
+ manager.startScheduledChecks();
+ await manager.checkForUpdates();
+
+ vi.advanceTimersByTime(5 * 60 * 1000 - 1);
+ expect(app.rendererUrlManager.setActiveRendererDir).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+
+ expect(app.rendererUrlManager.setActiveRendererDir).toHaveBeenCalledWith(
+ path.join(coreDir('1.0.1'), 'dist/renderer'),
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('does not auto-apply while focused or after an unload veto', async () => {
+ vi.useFakeTimers();
+ try {
+ serveLatest(rendererOnly('1.0.1', 1));
+ const { app, manager } = await loadManager();
+ manager.startScheduledChecks();
+ await manager.checkForUpdates();
+ const focus = electronMock.app.on.mock.calls.find(
+ ([name]) => name === 'browser-window-focus',
+ )![1];
+ const blur = electronMock.app.on.mock.calls.find(
+ ([name]) => name === 'browser-window-blur',
+ )![1];
+
+ focus();
+ vi.advanceTimersByTime(6 * 60 * 1000);
+ expect(app.rendererUrlManager.setActiveRendererDir).not.toHaveBeenCalled();
+
+ manager.handleUnloadPrevented();
+ blur();
+ vi.advanceTimersByTime(6 * 60 * 1000);
+ expect(app.rendererUrlManager.setActiveRendererDir).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('auto-applies a new stage even if an unload was vetoed before it was staged', async () => {
+ vi.useFakeTimers();
+ try {
+ serveLatest(rendererOnly('1.0.1', 1));
+ const { app, manager } = await loadManager();
+ manager.startScheduledChecks();
+ manager.handleUnloadPrevented();
+ await manager.checkForUpdates();
+
+ vi.advanceTimersByTime(5 * 60 * 1000);
+
+ expect(app.rendererUrlManager.setActiveRendererDir).toHaveBeenCalledWith(
+ path.join(coreDir('1.0.1'), 'dist/renderer'),
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('records a stage failure and clears staging', async () => {
+ const remote = rendererOnly('1.0.1', 1);
+ serveLatest({ ...remote, signature: remote.signature });
+ served.delete(`${SERVER}/stable/core/${PLATFORM}/${remote.full.path}`);
+ for (const key of served.keys()) if (key.startsWith(OBJECTS)) served.delete(key);
+ const { manager } = await loadManager();
+
+ await manager.checkForUpdates();
+
+ expect(manager.getStatus().lastError).toMatch(/fetch failed/);
+ expect(existsSync(path.join(otaRoot(), 'staging'))).toBe(false);
+ serveLatest(null);
+ await manager.checkForUpdates();
+ expect(fetchImpl).toHaveBeenLastCalledWith(
+ expect.stringContaining('latest.json'),
+ expect.anything(),
+ );
+ });
+
+ it('drops the staged version when the channel switches', async () => {
+ serveLatest(rendererOnly('1.0.1', 1));
+ const { manager } = await loadManager();
+ await manager.checkForUpdates();
+ expect(manager.getStatus().staged).toBe('1.0.1');
+
+ manager.switchChannel('canary');
+ await flushGc();
+
+ expect(manager.getStatus().staged).toBeNull();
+ expect(readPointer(otaRoot(), ABI).staged).toBeNull();
+ expect(existsSync(coreDir('1.0.1'))).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/applyMode.test.ts b/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/applyMode.test.ts
new file mode 100644
index 00000000000..539ce2a5da2
--- /dev/null
+++ b/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/applyMode.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from 'vitest';
+
+import { computeApplyMode } from '../applyMode';
+
+const file = (p: string, sha: string) => ({ path: p, sha256: sha.repeat(64), size: 1 });
+
+describe('computeApplyMode', () => {
+ const base = [
+ file('dist/main/index.js', 'a'),
+ file('dist/preload/index.js', 'b'),
+ file('dist/renderer/assets/x.js', 'c'),
+ file('package.json', 'd'),
+ ];
+
+ it('is reload when only renderer files change, are added or removed', () => {
+ expect(
+ computeApplyMode(base, [
+ ...base.slice(0, 2),
+ file('dist/renderer/assets/x.js', 'e'),
+ base[3],
+ ]),
+ ).toBe('reload');
+ expect(computeApplyMode(base, [...base, file('dist/renderer/assets/y.js', 'f')])).toBe(
+ 'reload',
+ );
+ expect(
+ computeApplyMode(
+ base,
+ base.filter((f) => !f.path.startsWith('dist/renderer/')),
+ ),
+ ).toBe('reload');
+ });
+
+ it('is relaunch for main, preload or package.json changes', () => {
+ expect(computeApplyMode(base, [file('dist/main/index.js', 'z'), ...base.slice(1)])).toBe(
+ 'relaunch',
+ );
+ expect(
+ computeApplyMode(base, [base[0], file('dist/preload/index.js', 'z'), ...base.slice(2)]),
+ ).toBe('relaunch');
+ expect(computeApplyMode(base, [...base.slice(0, 3), file('package.json', 'z')])).toBe(
+ 'relaunch',
+ );
+ });
+
+ it('is reload for identical trees', () => {
+ expect(computeApplyMode(base, [...base].reverse())).toBe('reload');
+ });
+});
diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/store.test.ts b/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/store.test.ts
new file mode 100644
index 00000000000..4b84b1d7714
--- /dev/null
+++ b/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/store.test.ts
@@ -0,0 +1,321 @@
+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs';
+import type * as fsp from 'node:fs/promises';
+import { link, mkdir, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { constants, zstdCompressSync } from 'node:zlib';
+
+import { zipSync } from 'fflate';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { type CoreManifest, sha256File } from '../manifest';
+import { cleanupLegacy, CoreStore, indexLocal, isSafeVersion } from '../store';
+
+vi.mock('node:fs/promises', async (importOriginal) => {
+ const actual = await importOriginal<typeof fsp>();
+ return { ...actual, link: vi.fn(actual.link) };
+});
+
+const OBJECTS = 'https://cdn.test/cas';
+const PACKS = 'https://cdn.test/core/darwin';
+const ENTRY_FILES: Record<string, string> = {
+ 'dist/renderer/apps/desktop/index.html': '<script src="/assets/index.js"></script>',
+ 'dist/renderer/apps/desktop/overlay.html': '<script src="/assets/overlay.js"></script>',
+ 'dist/renderer/apps/desktop/popup.html': '<script src="/assets/popup.js"></script>',
+ 'dist/renderer/assets/index.js': 'index',
+ 'dist/renderer/assets/overlay.js': 'overlay',
+ 'dist/renderer/assets/popup.js': 'popup',
+};
+
+let root: string;
+let served: Map<string, Buffer>;
+let fetchImpl: ReturnType<typeof vi.fn<(url: string) => Promise<Response>>>;
+
+const zst = (content: Buffer, dictionary?: Buffer) =>
+ zstdCompressSync(content, {
+ dictionary,
+ params: { [constants.ZSTD_c_compressionLevel]: 19 },
+ });
+
+const manifestFor = (version: string, files: Record<string, string>): CoreManifest => {
+ const objects = new Map(Object.entries(files).map(([p, c]) => [p, Buffer.from(c)] as const));
+ const tree = [...objects]
+ .map(([p, content]) => ({ path: p, sha256: sha256File(content), size: content.length }))
+ .sort((a, b) => a.path.localeCompare(b.path));
+ const zippable: Record<string, Uint8Array> = {};
+ for (const [, content] of objects) zippable[`objects/${sha256File(content)}`] = content;
+ const pack = Buffer.from(zipSync(zippable));
+ const packSha = sha256File(pack);
+ served.set(`${PACKS}/packs/${packSha}.zip`, pack);
+ for (const [, content] of objects) {
+ served.set(`${OBJECTS}/objects/${sha256File(content)}.zst`, zst(content));
+ }
+ return {
+ applyMode: 'reload',
+ channel: 'stable',
+ full: { path: `packs/${packSha}.zip`, sha256: packSha, size: pack.length },
+ objectsBaseUrl: OBJECTS,
+ patches: [],
+ platform: 'darwin',
+ previous: null,
+ rollout: 1,
+ schemaVersion: 3,
+ seq: 1,
+ shellAbi: 'a'.repeat(64),
+ signature: 'sig',
+ tree,
+ version,
+ };
+};
+
+const materialize = async (dir: string, files: Record<string, string>) => {
+ for (const [p, c] of Object.entries(files)) {
+ await mkdir(path.dirname(path.join(dir, p)), { recursive: true });
+ await writeFile(path.join(dir, p), c);
+ }
+};
+
+const localCore = async (name: string, files: Record<string, string>) => {
+ const dir = path.join(root, name);
+ await materialize(dir, files);
+ return { dir, manifest: manifestFor(name, files) };
+};
+
+const readTree = (dir: string) =>
+ Object.fromEntries(
+ readdirSync(dir, { recursive: true, withFileTypes: true })
+ .filter((entry) => entry.isFile() && entry.name !== 'manifest.json')
+ .map((entry) => {
+ const abs = path.join(entry.parentPath, entry.name);
+ return [path.relative(dir, abs), readFileSync(abs, 'utf8')];
+ }),
+ );
+
+beforeEach(() => {
+ root = mkdtempSync(path.join(tmpdir(), 'core-store-'));
+ served = new Map();
+ fetchImpl = vi.fn(async (url: string) =>
+ served.has(url)
+ ? new Response(new Uint8Array(served.get(url)!))
+ : new Response(null, { status: 404 }),
+ );
+ vi.mocked(link).mockClear();
+});
+
+afterEach(() => rmSync(root, { force: true, recursive: true }));
+
+const store = () => new CoreStore(path.join(root, 'ota'), fetchImpl);
+const stage = async (
+ remote: CoreManifest,
+ current: Awaited<ReturnType<typeof localCore>> | null,
+ builtin: Awaited<ReturnType<typeof localCore>>,
+) => store().stage({ builtin, current, objectsBaseUrl: OBJECTS, packsBaseUrl: PACKS, remote });
+
+describe('indexLocal', () => {
+ it('maps every tree sha to its absolute path', async () => {
+ const builtin = await localCore('builtin', ENTRY_FILES);
+ const index = indexLocal(builtin.dir, builtin.manifest);
+ expect(index.size).toBe(Object.keys(ENTRY_FILES).length);
+ expect(index.get(sha256File(Buffer.from('index')))).toBe(
+ path.join(builtin.dir, 'dist/renderer/assets/index.js'),
+ );
+ });
+});
+
+describe('CoreStore.stage', () => {
+ it('downloads every object for a fresh tree and assembles cores/<v>', async () => {
+ const builtin = await localCore('builtin', { 'cli/old.js': 'old' });
+ const files = { ...ENTRY_FILES, 'package.json': '{}' };
+ const remote = manifestFor('1.1.0', files);
+
+ const result = await stage(remote, null, builtin);
+
+ expect(result.dir).toBe(path.join(root, 'ota/cores/1.1.0'));
+ expect(result.fallbackFull).toBe(false);
+ expect(result.downloaded).toMatchObject({ objects: 7, patches: 0 });
+ expect(result.downloaded.bytes).toBeGreaterThan(0);
+ expect(readTree(result.dir)).toEqual(files);
+ expect(JSON.parse(readFileSync(path.join(result.dir, 'manifest.json'), 'utf8'))).toEqual(
+ remote,
+ );
+ for (const file of remote.tree) {
+ expect(existsSync(path.join(root, 'ota/store', file.sha256))).toBe(true);
+ }
+ expect(existsSync(path.join(root, 'ota/cores/1.1.0.tmp'))).toBe(false);
+ });
+
+ it('downloads nothing when every sha is present locally', async () => {
+ const builtin = await localCore('builtin', ENTRY_FILES);
+ const remote = manifestFor('1.1.0', { ...ENTRY_FILES });
+
+ const result = await stage(remote, null, builtin);
+
+ expect(fetchImpl).not.toHaveBeenCalled();
+ expect(result.downloaded).toEqual({ bytes: 0, objects: 0, patches: 0 });
+ expect(readTree(result.dir)).toEqual(ENTRY_FILES);
+ });
+
+ it('prefers a patch when the base sha is local', async () => {
+ const oldContent = Buffer.from('a'.repeat(4000));
+ const newContent = Buffer.from(`${'a'.repeat(4000)}!`);
+ const builtin = await localCore('builtin', {
+ ...ENTRY_FILES,
+ 'cli/big.js': oldContent.toString(),
+ });
+ const remote = manifestFor('1.1.0', { ...ENTRY_FILES, 'cli/big.js': newContent.toString() });
+ const from = sha256File(oldContent);
+ const to = sha256File(newContent);
+ const patch = zst(newContent, oldContent);
+ served.set(`${OBJECTS}/patches/${from}-${to}.zst`, patch);
+ remote.patches = [{ fromSha256: from, size: patch.length, toSha256: to }];
+
+ const result = await stage(remote, null, builtin);
+
+ expect(result.downloaded).toEqual({ bytes: patch.length, objects: 0, patches: 1 });
+ expect(readFileSync(path.join(result.dir, 'cli/big.js'), 'utf8')).toBe(newContent.toString());
+ });
+
+ it('falls back to the object when the patch is corrupt', async () => {
+ const builtin = await localCore('builtin', { ...ENTRY_FILES, 'cli/x.js': 'old' });
+ const remote = manifestFor('1.1.0', { ...ENTRY_FILES, 'cli/x.js': 'new' });
+ const from = sha256File(Buffer.from('old'));
+ const to = sha256File(Buffer.from('new'));
+ served.set(`${OBJECTS}/patches/${from}-${to}.zst`, Buffer.from('garbage'));
+ remote.patches = [{ fromSha256: from, size: 7, toSha256: to }];
+
+ const result = await stage(remote, null, builtin);
+
+ expect(result.downloaded).toMatchObject({ objects: 1, patches: 0 });
+ expect(result.fallbackFull).toBe(false);
+ expect(readFileSync(path.join(result.dir, 'cli/x.js'), 'utf8')).toBe('new');
+ });
+
+ it('falls back to the full pack when an object download fails', async () => {
+ const builtin = await localCore('builtin', ENTRY_FILES);
+ const remote = manifestFor('1.1.0', { ...ENTRY_FILES, 'cli/x.js': 'new' });
+ served.delete(`${OBJECTS}/objects/${sha256File(Buffer.from('new'))}.zst`);
+
+ const result = await stage(remote, null, builtin);
+
+ expect(result.fallbackFull).toBe(true);
+ expect(result.downloaded.objects).toBe(0);
+ expect(readFileSync(path.join(result.dir, 'cli/x.js'), 'utf8')).toBe('new');
+ expect(fetchImpl).toHaveBeenCalledWith(`${PACKS}/${remote.full.path}`);
+ });
+
+ it('goes straight to the full pack when too many objects are missing', async () => {
+ const builtin = await localCore('builtin', ENTRY_FILES);
+ const files = { ...ENTRY_FILES };
+ for (let i = 0; i < 401; i++) files[`cli/${i}.js`] = `file-${i}`;
+ const remote = manifestFor('1.1.0', files);
+
+ const result = await stage(remote, null, builtin);
+
+ expect(result.fallbackFull).toBe(true);
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
+ expect(readTree(result.dir)).toEqual(files);
+ });
+
+ it('never lands a sha-mismatched object in the store', async () => {
+ const builtin = await localCore('builtin', ENTRY_FILES);
+ const remote = manifestFor('1.1.0', { ...ENTRY_FILES, 'cli/x.js': 'new' });
+ const sha = sha256File(Buffer.from('new'));
+ served.set(`${OBJECTS}/objects/${sha}.zst`, zst(Buffer.from('evil')));
+ served.set(`${PACKS}/${remote.full.path}`, Buffer.from('not a zip'));
+
+ await expect(stage(remote, null, builtin)).rejects.toThrow();
+
+ expect(existsSync(path.join(root, 'ota/store', sha))).toBe(false);
+ expect(readdirSync(path.join(root, 'ota/store')).some((n) => n.endsWith('.tmp'))).toBe(false);
+ expect(existsSync(path.join(root, 'ota/cores/1.1.0.tmp'))).toBe(false);
+ });
+
+ it('rejects tree paths escaping the target dir and leaves no residue', async () => {
+ const builtin = await localCore('builtin', ENTRY_FILES);
+ const remote = manifestFor('1.1.0', { ...ENTRY_FILES, 'cli/x.js': 'new' });
+ remote.tree.find((file) => file.path === 'cli/x.js')!.path = '../../escape.js';
+
+ await expect(stage(remote, null, builtin)).rejects.toThrow(/outside/);
+
+ expect(existsSync(path.join(root, 'ota/cores/1.1.0.tmp'))).toBe(false);
+ expect(existsSync(path.join(root, 'ota/cores/1.1.0'))).toBe(false);
+ expect(existsSync(path.join(root, 'escape.js'))).toBe(false);
+ });
+
+ it('rejects an unsafe version before touching the filesystem', async () => {
+ const builtin = await localCore('builtin', ENTRY_FILES);
+ await materialize(root, { 'evil/keep.txt': 'x' });
+ const remote = manifestFor('../../evil', { ...ENTRY_FILES, 'cli/x.js': 'new' });
+
+ await expect(stage(remote, null, builtin)).rejects.toThrow(/Unsafe version/);
+
+ expect(fetchImpl).not.toHaveBeenCalled();
+ expect(existsSync(path.join(root, 'evil/keep.txt'))).toBe(true);
+ expect(existsSync(path.join(root, 'evil.tmp'))).toBe(false);
+ expect(existsSync(path.join(root, 'ota/cores'))).toBe(false);
+ });
+
+ it('hard-links assembled files and copies when link fails', async () => {
+ const builtin = await localCore('builtin', ENTRY_FILES);
+ const remote = manifestFor('1.1.0', { ...ENTRY_FILES, 'cli/x.js': 'new' });
+
+ const linked = await stage(remote, null, builtin);
+ expect(statSync(path.join(linked.dir, 'cli/x.js')).nlink).toBe(2);
+ expect(statSync(path.join(linked.dir, 'dist/renderer/assets/index.js')).nlink).toBe(2);
+
+ vi.mocked(link).mockRejectedValue(Object.assign(new Error('EXDEV'), { code: 'EXDEV' }));
+ const copied = await stage(
+ manifestFor('1.2.0', { ...ENTRY_FILES, 'cli/x.js': 'new' }),
+ null,
+ builtin,
+ );
+ expect(statSync(path.join(copied.dir, 'cli/x.js')).nlink).toBe(1);
+ expect(readTree(copied.dir)).toEqual({ ...ENTRY_FILES, 'cli/x.js': 'new' });
+ vi.mocked(link).mockReset();
+ });
+});
+
+describe('CoreStore.gc', () => {
+ it('keeps listed versions and their referenced objects only', async () => {
+ const builtin = await localCore('builtin', { 'cli/unrelated.js': 'x' });
+ const kept = manifestFor('1.1.0', { ...ENTRY_FILES, 'cli/a.js': 'keep' });
+ const keep = await stage(kept, null, builtin);
+ await stage(manifestFor('1.2.0', { ...ENTRY_FILES, 'cli/b.js': 'drop' }), null, builtin);
+ const ota = path.join(root, 'ota');
+ await materialize(ota, {
+ 'cores/1.3.0.tmp/manifest.json': '{}',
+ 'staging/leftover': 'x',
+ 'store/deadbeef.tmp': 'x',
+ });
+
+ await store().gc(['1.1.0']);
+
+ expect(readdirSync(path.join(ota, 'cores'))).toEqual(['1.1.0']);
+ expect(existsSync(path.join(ota, 'staging'))).toBe(false);
+ expect(readTree(keep.dir)).toEqual({ ...ENTRY_FILES, 'cli/a.js': 'keep' });
+ expect(readdirSync(path.join(ota, 'store')).sort()).toEqual(
+ [...new Set(kept.tree.map((file) => file.sha256))].sort(),
+ );
+ });
+});
+
+describe('isSafeVersion', () => {
+ it('accepts plain version segments only', () => {
+ expect(['1.2.3', '1.2.3-beta.1+build', 'v1_2']).toEqual(
+ ['1.2.3', '1.2.3-beta.1+build', 'v1_2'].filter(isSafeVersion),
+ );
+ expect(['', '.', '..', '../x', 'a/b', 'a\\b', 'x'.repeat(65)].some(isSafeVersion)).toBe(false);
+ });
+});
+
+describe('cleanupLegacy', () => {
+ it('removes the legacy renderer OTA dirs', async () => {
+ await materialize(root, { 'renderer-ota-v2/x': '1', 'renderer-ota/y': '2', 'other/z': '3' });
+
+ await cleanupLegacy(root);
+
+ expect(existsSync(path.join(root, 'renderer-ota-v2'))).toBe(false);
+ expect(existsSync(path.join(root, 'renderer-ota'))).toBe(false);
+ expect(existsSync(path.join(root, 'other/z'))).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/zstdPatch.test.ts b/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/zstdPatch.test.ts
similarity index 100%
rename from apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/zstdPatch.test.ts
rename to apps/desktop/src/main/core/infrastructure/coreOta/__tests__/zstdPatch.test.ts
diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/applyMode.ts b/apps/desktop/src/main/core/infrastructure/coreOta/applyMode.ts
new file mode 100644
index 00000000000..da3bea1843f
--- /dev/null
+++ b/apps/desktop/src/main/core/infrastructure/coreOta/applyMode.ts
@@ -0,0 +1,10 @@
+import type { RendererTreeFile } from './manifest';
+
+export type ApplyMode = 'reload' | 'relaunch';
+
+export const computeApplyMode = (from: RendererTreeFile[], to: RendererTreeFile[]): ApplyMode => {
+ const a = new Map(from.map((file) => [file.path, file.sha256]));
+ const b = new Map(to.map((file) => [file.path, file.sha256]));
+ const changed = [...new Set([...a.keys(), ...b.keys()])].filter((p) => a.get(p) !== b.get(p));
+ return changed.every((p) => p.startsWith('dist/renderer/')) ? 'reload' : 'relaunch';
+};
diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/manifest.ts b/apps/desktop/src/main/core/infrastructure/coreOta/manifest.ts
new file mode 100644
index 00000000000..359f55738aa
--- /dev/null
+++ b/apps/desktop/src/main/core/infrastructure/coreOta/manifest.ts
@@ -0,0 +1,125 @@
+import { createHash, verify as cryptoVerify } from 'node:crypto';
+
+import * as z from 'zod/v4';
+
+const sha256Schema = z.string().regex(/^[0-9a-f]{64}$/);
+const packPathSchema = z.string().regex(/^packs\/[0-9a-f]{64}\.zip$/);
+const relativePathSchema = z.string().refine((value) => {
+ if (!value || value.startsWith('/') || value.startsWith('\\') || value.includes('\\')) {
+ return false;
+ }
+ return value.split('/').every((segment) => segment && segment !== '.' && segment !== '..');
+});
+
+export const rendererTreeFileSchema = z
+ .object({
+ path: relativePathSchema,
+ sha256: sha256Schema,
+ size: z.number().int().nonnegative(),
+ })
+ .strict();
+
+export const rendererArtifactSchema = z
+ .object({
+ path: packPathSchema,
+ sha256: sha256Schema,
+ size: z.number().int().positive(),
+ })
+ .strict()
+ .refine((artifact) => artifact.path === `packs/${artifact.sha256}.zip`);
+
+export const rendererTreeSchema = z
+ .array(rendererTreeFileSchema)
+ .min(1)
+ .superRefine((tree, ctx) => {
+ const paths = new Set<string>();
+ for (const file of tree) {
+ if (paths.has(file.path)) {
+ ctx.addIssue({ code: 'custom', message: `duplicate renderer path: ${file.path}` });
+ }
+ paths.add(file.path);
+ }
+ });
+
+export const corePatchSchema = z
+ .object({
+ fromSha256: sha256Schema,
+ size: z.number().int().positive(),
+ toSha256: sha256Schema,
+ })
+ .strict();
+
+export const coreManifestSchema = z
+ .object({
+ applyMode: z.enum(['reload', 'relaunch']).nullable(),
+ channel: z.enum(['stable', 'beta', 'canary', 'nightly']),
+ full: rendererArtifactSchema,
+ objectsBaseUrl: z.url(),
+ patches: z.array(corePatchSchema),
+ platform: z.enum(['darwin', 'win32', 'linux']),
+ previous: z.string().nullable(),
+ rollout: z.number().min(0).max(1).default(1),
+ schemaVersion: z.literal(3),
+ seq: z.number().int().nonnegative(),
+ shellAbi: sha256Schema,
+ signature: z.string().min(1),
+ tree: rendererTreeSchema,
+ version: z.string().min(1),
+ })
+ .strict();
+
+// The builtin manifest ships inside the code-signed app bundle, so it is built without the OTA key.
+export const builtinManifestSchema = coreManifestSchema.extend({ signature: z.string() });
+
+export type CoreManifest = z.infer<typeof coreManifestSchema>;
+export type CorePatch = z.infer<typeof corePatchSchema>;
+export type RendererArtifact = z.infer<typeof rendererArtifactSchema>;
+export type RendererTreeFile = z.infer<typeof rendererTreeFileSchema>;
+
+export const canonicalJson = (value: unknown): string => {
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
+ if (value && typeof value === 'object') {
+ const entries = Object.keys(value as Record<string, unknown>)
+ .sort()
+ .map(
+ (key) => `${JSON.stringify(key)}:${canonicalJson((value as Record<string, unknown>)[key])}`,
+ );
+ return `{${entries.join(',')}}`;
+ }
+ return JSON.stringify(value);
+};
+
+export const verifyManifestSignature = (
+ manifest: { signature: string },
+ publicKeyPem: string,
+): boolean => {
+ const { signature, ...unsigned } = manifest;
+ try {
+ return cryptoVerify(
+ null,
+ Buffer.from(canonicalJson(unsigned)),
+ publicKeyPem,
+ Buffer.from(signature, 'base64'),
+ );
+ } catch {
+ return false;
+ }
+};
+
+export const isValidManifestShape = (value: unknown): value is CoreManifest =>
+ coreManifestSchema.safeParse(value).success;
+
+export const sha256File = (content: Buffer): string =>
+ createHash('sha256').update(content).digest('hex');
+
+export const findMissingEntryAssets = (
+ html: string,
+ exists: (relPath: string) => boolean,
+): string[] => {
+ const refs = [...html.matchAll(/(?:src|href)="\.?\/([^"]+\.(?:m?js|css))"/g)].map(
+ (match) => match[1],
+ );
+ const missing = refs.filter((ref) => !exists(ref));
+ if (!refs.some((ref) => /\.m?js$/.test(ref))) missing.push('<no script referenced>');
+ return missing;
+};
diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/pointer.ts b/apps/desktop/src/main/core/infrastructure/coreOta/pointer.ts
new file mode 100644
index 00000000000..43e79b54c48
--- /dev/null
+++ b/apps/desktop/src/main/core/infrastructure/coreOta/pointer.ts
@@ -0,0 +1,60 @@
+import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+
+import { isSafeVersion } from './store';
+
+export interface CorePointer {
+ abi: string;
+ blacklist: string[];
+ channel: string | null;
+ current: string | null;
+ previous: string | null;
+ staged: string | null;
+}
+
+const versionOrNull = (value: unknown): string | null =>
+ typeof value === 'string' && isSafeVersion(value) ? value : null;
+
+export const emptyPointer = (abi: string): CorePointer => ({
+ abi,
+ blacklist: [],
+ channel: null,
+ current: null,
+ previous: null,
+ staged: null,
+});
+
+const readRaw = (otaRoot: string) => {
+ try {
+ return JSON.parse(readFileSync(path.join(otaRoot, 'pointer.json'), 'utf8'));
+ } catch {
+ return null;
+ }
+};
+
+export const readPointerAbi = (otaRoot: string): string | null => {
+ const abi = readRaw(otaRoot)?.abi;
+ return typeof abi === 'string' ? abi : null;
+};
+
+export const readPointer = (otaRoot: string, abi: string): CorePointer => {
+ const raw = readRaw(otaRoot);
+ if (raw?.abi === abi) {
+ return {
+ abi,
+ blacklist: Array.isArray(raw.blacklist) ? raw.blacklist.filter(versionOrNull) : [],
+ channel: typeof raw.channel === 'string' ? raw.channel : null,
+ current: versionOrNull(raw.current),
+ previous: versionOrNull(raw.previous),
+ staged: versionOrNull(raw.staged),
+ };
+ }
+ return emptyPointer(abi);
+};
+
+export const writePointer = (otaRoot: string, pointer: CorePointer): void => {
+ mkdirSync(otaRoot, { mode: 0o700, recursive: true });
+ const target = path.join(otaRoot, 'pointer.json');
+ writeFileSync(`${target}.tmp`, JSON.stringify(pointer, null, 2));
+ renameSync(`${target}.tmp`, target);
+};
diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/store.ts b/apps/desktop/src/main/core/infrastructure/coreOta/store.ts
new file mode 100644
index 00000000000..cf3bf8760db
--- /dev/null
+++ b/apps/desktop/src/main/core/infrastructure/coreOta/store.ts
@@ -0,0 +1,275 @@
+import { existsSync } from 'node:fs';
+import { copyFile, link, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import { promisify } from 'node:util';
+import { zstdDecompress } from 'node:zlib';
+
+import { unzip } from 'fflate';
+
+import { createLogger } from '@/utils/logger';
+
+import { type CoreManifest, findMissingEntryAssets, sha256File } from './manifest';
+import { applyZstdPatch } from './zstdPatch';
+
+const logger = createLogger('core:CoreStore');
+
+type FetchImpl = (url: string) => Promise<Response>;
+type LocalCore = { dir: string; manifest: CoreManifest };
+type StageInput = {
+ builtin: LocalCore;
+ current: LocalCore | null;
+ objectsBaseUrl: string;
+ packsBaseUrl: string;
+ remote: CoreManifest;
+};
+type StageResult = {
+ dir: string;
+ downloaded: { bytes: number; objects: number; patches: number };
+ fallbackFull: boolean;
+};
+
+const RENDERER_ROOT = 'dist/renderer';
+const ENTRY_HTMLS = ['index.html', 'overlay.html', 'popup.html'].map((name) =>
+ path.join(RENDERER_ROOT, 'apps', 'desktop', name),
+);
+const FULL_FALLBACK_THRESHOLD = 400;
+const CONCURRENCY = 8;
+const PACK_ENTRY = /^objects\/([0-9a-f]{64})$/;
+const DIR_MODE = 0o700;
+export const SAFE_VERSION = /^[\w.+-]{1,64}$/;
+
+const zstdDecompressAsync = promisify(zstdDecompress);
+
+// Settles every lane before rethrowing so callers' cleanup never races in-flight writes.
+const runPool = async <T>(items: T[], worker: (item: T) => Promise<void>) => {
+ let next = 0;
+ let failed = false;
+ const lane = async () => {
+ while (!failed && next < items.length) {
+ try {
+ await worker(items[next++]);
+ } catch (error) {
+ failed = true;
+ throw error;
+ }
+ }
+ };
+ const results = await Promise.allSettled(
+ Array.from({ length: Math.min(CONCURRENCY, items.length) }, lane),
+ );
+ const rejected = results.find((result) => result.status === 'rejected');
+ if (rejected) throw rejected.reason;
+};
+
+const attempt = (label: string, task: () => Promise<void>) =>
+ task().then(
+ () => true,
+ (error) => {
+ logger.warn(`Core OTA ${label} failed`, error);
+ return false;
+ },
+ );
+
+const resolveInside = (root: string, relPath: string): string => {
+ const target = path.join(root, relPath);
+ const relative = path.relative(root, target);
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) {
+ throw new Error(`Tree path resolves outside target dir: ${relPath}`);
+ }
+ return target;
+};
+
+const readDirNames = async (dir: string): Promise<string[]> => {
+ try {
+ return await readdir(dir);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
+ throw error;
+ }
+};
+
+export const isSafeVersion = (version: string): boolean =>
+ SAFE_VERSION.test(version) && version !== '.' && version !== '..';
+
+export const indexLocal = (coreDir: string, manifest: CoreManifest): Map<string, string> =>
+ new Map(manifest.tree.map((file) => [file.sha256, path.join(coreDir, file.path)]));
+
+export const decodeCorePack = (content: Buffer): Promise<Map<string, Buffer>> =>
+ new Promise((resolve, reject) => {
+ unzip(new Uint8Array(content), (error, unpacked) => {
+ if (error) return reject(error);
+ const entries = new Map<string, Buffer>();
+ for (const [name, raw] of Object.entries(unpacked)) {
+ const sha256 = PACK_ENTRY.exec(name)?.[1];
+ const value = Buffer.from(raw);
+ if (!sha256 || sha256File(value) !== sha256) {
+ return reject(new Error(`Core pack entry invalid: ${name}`));
+ }
+ entries.set(sha256, value);
+ }
+ resolve(entries);
+ });
+ });
+
+export const cleanupLegacy = async (userData: string) => {
+ for (const name of ['renderer-ota-v2', 'renderer-ota']) {
+ await rm(path.join(userData, name), { force: true, recursive: true });
+ }
+};
+
+export class CoreStore {
+ private readonly storeDir: string;
+ private readonly coresDir: string;
+
+ constructor(
+ private readonly otaRoot: string,
+ private readonly fetchImpl: FetchImpl,
+ ) {
+ this.storeDir = path.join(otaRoot, 'store');
+ this.coresDir = path.join(otaRoot, 'cores');
+ }
+
+ async stage({ builtin, current, objectsBaseUrl, packsBaseUrl, remote }: StageInput) {
+ if (!isSafeVersion(remote.version)) throw new Error(`Unsafe version: ${remote.version}`);
+ await mkdir(this.storeDir, { mode: DIR_MODE, recursive: true });
+ await mkdir(this.coresDir, { mode: DIR_MODE, recursive: true });
+
+ const byHash = new Map([
+ ...indexLocal(builtin.dir, builtin.manifest),
+ ...(current ? indexLocal(current.dir, current.manifest) : []),
+ ]);
+ const missing = [...new Set(remote.tree.map((file) => file.sha256))].filter(
+ (sha256) => !byHash.has(sha256) && !existsSync(this.objectPath(sha256)),
+ );
+ const downloaded = { bytes: 0, objects: 0, patches: 0 };
+ const failed: string[] = [];
+
+ if (missing.length <= FULL_FALLBACK_THRESHOLD) {
+ const patches = new Map(
+ remote.patches
+ .filter((patch) => byHash.has(patch.fromSha256))
+ .map((patch) => [patch.toSha256, patch]),
+ );
+ await runPool(missing, async (sha256) => {
+ const patch = patches.get(sha256);
+ const patched =
+ patch &&
+ (await attempt(`patch ${patch.fromSha256}->${patch.toSha256}`, async () => {
+ const url = `${objectsBaseUrl}/patches/${patch.fromSha256}-${patch.toSha256}.zst`;
+ const raw = await this.fetchBytes(url);
+ const base = await readFile(byHash.get(patch.fromSha256)!);
+ await this.putObject(sha256, await applyZstdPatch(base, raw));
+ downloaded.patches += 1;
+ downloaded.bytes += raw.byteLength;
+ }));
+ if (patched) return;
+ const fetched = await attempt(`object ${sha256}`, async () => {
+ const raw = await this.fetchBytes(`${objectsBaseUrl}/objects/${sha256}.zst`);
+ await this.putObject(sha256, Buffer.from(await zstdDecompressAsync(raw)));
+ downloaded.objects += 1;
+ downloaded.bytes += raw.byteLength;
+ });
+ if (!fetched) failed.push(sha256);
+ });
+ }
+
+ const fallbackFull = failed.length > 0 || missing.length > FULL_FALLBACK_THRESHOLD;
+ if (fallbackFull) {
+ const pack = await this.fetchBytes(`${packsBaseUrl}/${remote.full.path}`);
+ if (sha256File(pack) !== remote.full.sha256) {
+ throw new Error(`Core pack integrity mismatch: ${remote.full.path}`);
+ }
+ downloaded.bytes += pack.byteLength;
+ const entries = await decodeCorePack(pack);
+ for (const sha256 of missing) {
+ if (existsSync(this.objectPath(sha256))) continue;
+ const content = entries.get(sha256);
+ if (!content) throw new Error(`Core pack missing object ${sha256}`);
+ await this.putObject(sha256, content);
+ }
+ }
+
+ const dir = await this.assemble(remote, byHash);
+ return { dir, downloaded, fallbackFull } satisfies StageResult;
+ }
+
+ async gc(keep: string[], { keepStore = false } = {}) {
+ await rm(path.join(this.otaRoot, 'staging'), { force: true, recursive: true });
+ const referenced = new Set<string>();
+ for (const name of await readDirNames(this.coresDir)) {
+ const dir = path.join(this.coresDir, name);
+ if (!keep.includes(name) || name.endsWith('.tmp')) {
+ await rm(dir, { force: true, recursive: true });
+ continue;
+ }
+ const manifest = await this.readManifest(dir);
+ for (const file of manifest?.tree ?? []) referenced.add(file.sha256);
+ }
+ if (keepStore) return;
+ const unreferenced = (await readDirNames(this.storeDir)).filter(
+ (name) => !referenced.has(name),
+ );
+ await runPool(unreferenced, (name) => rm(path.join(this.storeDir, name), { force: true }));
+ }
+
+ private objectPath(sha256: string) {
+ return path.join(this.storeDir, sha256);
+ }
+
+ private async fetchBytes(url: string): Promise<Buffer> {
+ const response = await this.fetchImpl(url);
+ if (!response.ok) throw new Error(`Core OTA fetch failed (${response.status}): ${url}`);
+ return Buffer.from(await response.arrayBuffer());
+ }
+
+ private async putObject(sha256: string, content: Buffer) {
+ if (sha256File(content) !== sha256) throw new Error(`Object sha mismatch: ${sha256}`);
+ const target = this.objectPath(sha256);
+ await writeFile(`${target}.tmp`, content);
+ await rename(`${target}.tmp`, target);
+ }
+
+ private async readManifest(dir: string): Promise<CoreManifest | null> {
+ try {
+ return JSON.parse(await readFile(path.join(dir, 'manifest.json'), 'utf8'));
+ } catch {
+ return null;
+ }
+ }
+
+ private async assemble(remote: CoreManifest, byHash: Map<string, string>): Promise<string> {
+ const finalDir = resolveInside(this.coresDir, remote.version);
+ const tmpDir = `${finalDir}.tmp`;
+ await rm(tmpDir, { force: true, recursive: true });
+ await mkdir(tmpDir, { mode: DIR_MODE, recursive: true });
+ try {
+ await runPool(remote.tree, async (file) => {
+ const target = resolveInside(tmpDir, file.path);
+ await mkdir(path.dirname(target), { mode: DIR_MODE, recursive: true });
+ const source = byHash.get(file.sha256) ?? this.objectPath(file.sha256);
+ try {
+ await link(source, target);
+ } catch {
+ await copyFile(source, target);
+ }
+ });
+ await writeFile(path.join(tmpDir, 'manifest.json'), JSON.stringify(remote));
+ const rendererDir = path.join(tmpDir, RENDERER_ROOT);
+ for (const entry of ENTRY_HTMLS) {
+ const missing = findMissingEntryAssets(
+ await readFile(path.join(tmpDir, entry), 'utf8'),
+ (relPath) => existsSync(path.join(rendererDir, relPath)),
+ );
+ if (missing.length > 0) {
+ throw new Error(`Entry integrity check failed (${entry}): ${missing.join(', ')}`);
+ }
+ }
+ await rm(finalDir, { force: true, recursive: true });
+ await rename(tmpDir, finalDir);
+ return finalDir;
+ } catch (error) {
+ await rm(tmpDir, { force: true, recursive: true });
+ throw error;
+ }
+ }
+}
diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/zstdPatch.ts b/apps/desktop/src/main/core/infrastructure/coreOta/zstdPatch.ts
similarity index 100%
rename from apps/desktop/src/main/core/infrastructure/rendererOta/zstdPatch.ts
rename to apps/desktop/src/main/core/infrastructure/coreOta/zstdPatch.ts
diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/RendererUpdateManager.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/RendererUpdateManager.ts
deleted file mode 100644
index e19c249822b..00000000000
--- a/apps/desktop/src/main/core/infrastructure/rendererOta/RendererUpdateManager.ts
+++ /dev/null
@@ -1,685 +0,0 @@
-import { randomUUID } from 'node:crypto';
-import { existsSync, mkdirSync, readdirSync, renameSync, rmSync } from 'node:fs';
-import { copyFile, link, mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
-import path from 'node:path';
-
-import type { UpdateChannel } from '@lobechat/electron-client-ipc';
-import { app as electronApp } from 'electron';
-
-import { rendererDir } from '@/const/dir';
-import { isDev } from '@/const/env';
-import {
- BUILD_CHANNEL,
- coerceStoredUpdateChannel,
- UPDATE_CHANNEL,
- UPDATE_SERVER_URL,
-} from '@/modules/updater/configs';
-import { createLogger } from '@/utils/logger';
-
-import type { App } from '../../App';
-import {
- findMissingEntryAssets,
- isValidManifestShape,
- patchNumber,
- type RendererArtifact,
- type RendererDelta,
- type RendererManifest,
- type RendererTreeFile,
- sha256File,
- verifyManifestSignature,
-} from './manifest';
-import { decodeRendererPack } from './pack';
-import { emptyPointer, type OtaPointer, readPointer, writePointer } from './pointer';
-import { canApplyDelta, indexLocalByHash, pickDelta } from './updatePlan';
-import { applyZstdPatch } from './zstdPatch';
-
-const logger = createLogger('core:RendererUpdateManager');
-
-const BOOT_CHECK_TIMEOUT = 15_000;
-const LOAD_PING_TIMEOUT = 3000;
-const MAX_BOOT_CRASHES = 2;
-const CHECK_INTERVAL = 60 * 60 * 1000;
-
-const APP_VERSION = electronApp.getVersion();
-const MAIN_HASH = process.env.MAIN_HASH || '';
-const PUBLIC_KEY = process.env.RENDERER_OTA_PUBLIC_KEY || '';
-const UPDATE_SERVER_BASE_URL =
- UPDATE_SERVER_URL?.replace(/\/(stable|nightly|canary|beta)\/?$/, '').replace(/\/$/, '') || '';
-// Local e2e escape hatches (never set in packaged builds): force-enable in
-// dev and shorten the first scheduled check.
-const FORCE_IN_DEV = process.env['RENDERER_OTA_FORCE'] === '1';
-const FIRST_CHECK_DELAY = Number(process.env['RENDERER_OTA_CHECK_DELAY']) || 90 * 1000;
-
-type OtaState = 'idle' | 'checking' | 'downloading' | 'staged';
-type RendererOtaChannel = UpdateChannel | 'beta';
-
-export class RendererUpdateManager {
- private readonly app: App;
- private readonly legacyOtaRootDir: string;
- private readonly otaRootDir: string;
- private activeChannel: RendererOtaChannel;
- private pointer: OtaPointer;
- private state: OtaState = 'idle';
- private stagedManifest: RendererManifest | null = null;
- private bootCheckTimer: NodeJS.Timeout | null = null;
- private loadPingTimer: NodeJS.Timeout | null = null;
- private bootCrashCount = 0;
- private checkTimer: NodeJS.Timeout | null = null;
- private checkGeneration = 0;
-
- constructor(app: App) {
- this.app = app;
- const userDataDir = electronApp.getPath('userData');
- this.legacyOtaRootDir = path.join(userDataDir, 'renderer-ota');
- this.otaRootDir = path.join(userDataDir, 'renderer-ota-v2');
- this.activeChannel = this.rendererChannel(
- coerceStoredUpdateChannel(this.app.storeManager.get('updateChannel') as string | undefined) ||
- UPDATE_CHANNEL,
- );
- this.pointer = emptyPointer(MAIN_HASH);
- }
-
- private get otaDir() {
- // Patch numbers restart at r0 for each full release, even when mainHash is unchanged.
- return path.join(this.otaRootDir, this.activeChannel, APP_VERSION);
- }
-
- private get disabledReasons() {
- return [
- isDev && !FORCE_IN_DEV && 'development-build',
- !MAIN_HASH && 'missing-main-hash',
- !PUBLIC_KEY && 'missing-public-key',
- !UPDATE_SERVER_URL && 'missing-server-url',
- ].filter(Boolean);
- }
-
- get enabled() {
- return this.disabledReasons.length === 0;
- }
-
- private logContext() {
- return {
- appVersion: APP_VERSION,
- channel: this.activeChannel,
- current: this.pointer.current ?? 'r0',
- localMainHash: MAIN_HASH,
- staged: this.pointer.staged,
- };
- }
-
- /**
- * Must run before the first window loads: resolves the pointer, applies a
- * restart-pending staged version, garbage-collects, and sets the app://
- * serving root.
- */
- initialize = () => {
- this.cleanupLegacyV1();
-
- logger.info('Renderer OTA configuration', {
- appVersion: APP_VERSION,
- arch: process.arch,
- buildChannel: BUILD_CHANNEL,
- channel: this.activeChannel,
- disabledReasons: this.disabledReasons,
- enabled: this.enabled,
- hasPublicKey: !!PUBLIC_KEY,
- hasServerUrl: !!UPDATE_SERVER_URL,
- mainHash: MAIN_HASH,
- platform: process.platform,
- });
-
- if (!this.enabled) {
- logger.info('Renderer OTA disabled (dev build or missing MAIN_HASH/key/server url)');
- return;
- }
-
- mkdirSync(path.join(this.otaDir, 'versions'), { recursive: true });
- this.pointer = readPointer(this.otaDir, MAIN_HASH);
- logger.info('Renderer OTA boot state', this.pointer);
-
- if (this.pointer.staged && this.versionDirValid(this.pointer.staged)) {
- logger.info(`Applying staged renderer ${this.pointer.staged} on boot`);
- this.promoteToCurrent(this.pointer.staged);
- } else if (this.pointer.pendingBootCheck && this.pointer.current) {
- // Previous session died before the boot check passed — treat as a failed boot.
- logger.warn(`Renderer ${this.pointer.current} never passed boot check, rolling back`);
- this.rollback('previous-boot-unconfirmed');
- }
-
- this.gc();
- writePointer(this.otaDir, this.pointer);
- this.applyServingRoot();
-
- if (this.pointer.pendingBootCheck) this.armBootCheck();
- };
-
- startScheduledChecks = () => {
- if (!this.enabled) return;
- logger.info('Renderer OTA checks scheduled', {
- firstCheckDelayMs: FIRST_CHECK_DELAY,
- intervalMs: CHECK_INTERVAL,
- });
- this.checkTimer = setTimeout(() => this.checkForUpdates(), FIRST_CHECK_DELAY);
- setInterval(() => this.checkForUpdates(), CHECK_INTERVAL);
- };
-
- switchChannel = (channel: UpdateChannel) => {
- const nextChannel = this.rendererChannel(channel);
- if (nextChannel === this.activeChannel) return;
- logger.info('Renderer OTA channel changed', { ...this.logContext(), nextChannel });
-
- if (!this.enabled) {
- this.activeChannel = nextChannel;
- return;
- }
-
- this.checkGeneration += 1;
- this.clearBootTimers();
- this.state = 'idle';
- this.stagedManifest = null;
- this.activeChannel = nextChannel;
-
- mkdirSync(path.join(this.otaDir, 'versions'), { recursive: true });
- this.pointer = readPointer(this.otaDir, MAIN_HASH);
- if (this.pointer.pendingBootCheck) this.rollback('channel-switch-pending-boot');
- this.state = this.pointer.staged ? 'staged' : 'idle';
- this.gc();
- writePointer(this.otaDir, this.pointer);
- this.applyServingRoot();
- this.reloadAllWindows();
- };
-
- handleBootPing = (stage?: 'loaded' | 'mounted') => {
- if (!this.pointer.pendingBootCheck) return;
-
- if (stage === 'loaded') {
- logger.info(`Renderer ${this.pointer.current} bundle evaluated (load ping)`);
- this.clearLoadPingTimer();
- return;
- }
-
- logger.info(`Renderer ${this.pointer.current} boot check passed`);
- this.clearBootTimers();
- this.bootCrashCount = 0;
- this.pointer = { ...this.pointer, pendingBootCheck: false };
- writePointer(this.otaDir, this.pointer);
- this.gc();
- logger.info('Renderer OTA apply result', {
- ...this.logContext(),
- outcome: 'applied',
- reason: 'boot-confirmed',
- });
- };
-
- handleRendererCrash = () => {
- if (!this.pointer.pendingBootCheck) return;
- this.bootCrashCount += 1;
- logger.warn(`Renderer crashed during boot check (${this.bootCrashCount}/${MAX_BOOT_CRASHES})`);
- if (this.bootCrashCount >= MAX_BOOT_CRASHES) this.failBootCheck('renderer-crash');
- };
-
- applyStagedNow = () => {
- if (!this.pointer.staged || !this.versionDirValid(this.pointer.staged)) {
- logger.info('Renderer OTA apply result', {
- ...this.logContext(),
- outcome: 'skipped',
- reason: this.pointer.staged ? 'staged-files-missing' : 'no-staged-version',
- });
- return false;
- }
- logger.info(`Applying staged renderer ${this.pointer.staged} now`);
- this.promoteToCurrent(this.pointer.staged);
- this.stagedManifest = null;
- this.state = 'idle';
- this.applyServingRoot();
- this.reloadAllWindows(true);
- // Hot apply is an in-place reload from local disk: the bundle must
- // evaluate within seconds, so a missing load ping fails fast. Cold-boot
- // arming (initialize) keeps only the long mount timeout.
- this.armBootCheck({ expectFastLoad: true });
- return true;
- };
-
- getStatus = () => ({
- current: this.pointer.current,
- enabled: this.enabled,
- staged: this.pointer.staged,
- state: this.state,
- });
-
- checkForUpdates = async () => {
- const context = { ...this.logContext(), checkId: randomUUID() };
- if (!this.enabled || this.state !== 'idle') {
- logger.info('Renderer OTA check finished', {
- ...context,
- disabledReasons: this.disabledReasons,
- elapsedMs: 0,
- outcome: 'skipped',
- reason: !this.enabled ? 'disabled' : this.state === 'staged' ? 'already-staged' : 'busy',
- state: this.state,
- });
- return;
- }
- const generation = this.checkGeneration;
- const channel = this.activeChannel;
- const otaDir = this.otaDir;
- const pointer = this.pointer;
- const startedAt = Date.now();
- let outcome = 'failed';
- let reason = 'manifest-fetch-failed';
- let remote: RendererManifest | undefined;
- let httpStatus: number | undefined;
- this.state = 'checking';
- logger.info('Renderer OTA check started', context);
-
- try {
- const rendererUrl = this.rendererUrl(channel);
- const res = await fetch(`${rendererUrl}/latest.json`, { cache: 'no-store' });
- httpStatus = res.status;
- logger.info('Renderer OTA manifest response', {
- checkId: context.checkId,
- status: httpStatus,
- });
- if (httpStatus === 404) {
- outcome = 'skipped';
- reason = 'feed-not-found';
- return;
- }
- if (!res.ok) throw new Error(`Manifest fetch failed: ${httpStatus}`);
-
- reason = 'manifest-invalid';
- const raw = await res.json();
- if (!isValidManifestShape(raw)) throw new Error('Manifest shape invalid');
- remote = raw;
- logger.info('Renderer OTA manifest compatibility', {
- localAppVersion: APP_VERSION,
- localMainHash: MAIN_HASH,
- remoteAppVersion: raw.appVersion,
- remoteMainHash: raw.mainHash,
- remoteVersion: raw.version,
- });
- reason = 'app-version-mismatch';
- if (raw.appVersion !== APP_VERSION) throw new Error('Manifest appVersion mismatch');
- reason = 'hash-mismatch';
- if (raw.mainHash !== MAIN_HASH) throw new Error('Manifest mainHash mismatch');
- reason = 'signature-invalid';
- if (!verifyManifestSignature(raw, PUBLIC_KEY)) throw new Error('Manifest signature invalid');
- if (generation !== this.checkGeneration) return;
- const manifest = raw;
- const currentN = pointer.current ? patchNumber(pointer.current) : 0;
- if (patchNumber(manifest.version) <= currentN) {
- outcome = 'skipped';
- reason = 'already-current';
- return;
- }
- if (pointer.blacklist.includes(manifest.version)) {
- outcome = 'skipped';
- reason = 'blacklisted';
- return;
- }
- if (pointer.staged === manifest.version) {
- outcome = 'skipped';
- reason = 'already-staged';
- return;
- }
-
- reason = 'download-failed';
- this.state = 'downloading';
- await this.downloadAndStage(manifest, otaDir, pointer, rendererUrl);
- if (generation !== this.checkGeneration) return;
-
- reason = 'staging-failed';
- this.stagedManifest = manifest;
- this.pointer = { ...this.pointer, staged: manifest.version };
- writePointer(otaDir, this.pointer);
- this.state = 'staged';
- reason = 'notification-failed';
- this.app.browserManager.broadcastToAllWindows('updateReady', {
- kind: 'renderer',
- version: `${manifest.appVersion}.${manifest.version}`,
- });
- outcome = 'staged';
- reason = 'staged';
- } catch (error) {
- if (generation === this.checkGeneration)
- logger.error('Renderer OTA check failed:', error, { ...context, reason });
- rmSync(path.join(otaDir, 'staging'), { force: true, recursive: true });
- } finally {
- const superseded = generation !== this.checkGeneration;
- if (!superseded && this.state !== 'staged') this.state = 'idle';
- logger.info('Renderer OTA check finished', {
- ...context,
- elapsedMs: Date.now() - startedAt,
- httpStatus,
- outcome: superseded ? 'skipped' : outcome,
- reason: superseded ? 'superseded' : reason,
- remoteAppVersion: remote?.appVersion,
- remoteMainHash: remote?.mainHash,
- remoteVersion: remote?.version,
- staged: superseded ? pointer.staged : this.pointer.staged,
- state: superseded ? 'superseded' : this.state,
- });
- }
- };
-
- private rendererChannel(channel: UpdateChannel): RendererOtaChannel {
- return BUILD_CHANNEL === 'beta' && channel === 'canary' ? 'beta' : channel;
- }
-
- private cleanupLegacyV1() {
- if (!existsSync(this.legacyOtaRootDir)) return;
-
- try {
- rmSync(this.legacyOtaRootDir, { force: true, recursive: true });
- logger.info('Removed legacy Renderer OTA V1 data');
- } catch (error) {
- logger.warn(`Failed to remove legacy Renderer OTA V1 data: ${String(error)}`);
- }
- }
-
- private rendererUrl(channel: RendererOtaChannel) {
- return `${UPDATE_SERVER_BASE_URL}/${channel}/${APP_VERSION}/renderer/v2`;
- }
-
- private async downloadAndStage(
- manifest: RendererManifest,
- otaDir: string,
- pointer: OtaPointer,
- rendererUrl: string,
- ) {
- const stagingRoot = path.join(otaDir, 'staging');
- rmSync(stagingRoot, { force: true, recursive: true });
- const stagingDir = path.join(stagingRoot, manifest.version);
- mkdirSync(stagingDir, { recursive: true });
-
- const localHashes = await this.hashLocalTree(otaDir, pointer);
- const byHash = indexLocalByHash(localHashes);
- const localVersion = pointer.current ?? 'r0';
- const delta = pickDelta(manifest, localVersion);
- let targetTree: RendererTreeFile[];
-
- if (delta) {
- logger.info(`Renderer ${manifest.version}: applying delta from ${delta.fromVersion}`);
- try {
- targetTree = await this.stageDelta(manifest, delta, stagingDir, byHash, rendererUrl);
- } catch (error) {
- logger.warn(`Renderer delta failed, retrying full pack: ${String(error)}`);
- rmSync(stagingDir, { force: true, recursive: true });
- mkdirSync(stagingDir, { recursive: true });
- targetTree = await this.stageFull(manifest, stagingDir, rendererUrl);
- }
- } else {
- logger.info(`Renderer ${manifest.version}: applying full pack`);
- targetTree = await this.stageFull(manifest, stagingDir, rendererUrl);
- }
-
- for (const file of targetTree) {
- const content = await readFile(path.join(stagingDir, file.path));
- if (content.byteLength !== file.size || sha256File(content) !== file.sha256) {
- throw new Error(`Hash mismatch after staging: ${file.path}`);
- }
- }
-
- for (const entry of ['index.html', 'popup.html', 'overlay.html']) {
- const entryHtml = await readFile(path.join(stagingDir, 'apps', 'desktop', entry), 'utf8');
- const missingAssets = findMissingEntryAssets(entryHtml, (relPath) =>
- existsSync(path.join(stagingDir, relPath)),
- );
- if (missingAssets.length > 0) {
- throw new Error(`Entry integrity check failed (${entry}): ${missingAssets.join(', ')}`);
- }
- }
-
- const finalDir = path.join(otaDir, 'versions', manifest.version);
- rmSync(finalDir, { force: true, recursive: true });
- renameSync(stagingDir, finalDir);
- rmSync(stagingRoot, { force: true, recursive: true });
- }
-
- private async stageFull(
- manifest: RendererManifest,
- stagingDir: string,
- rendererUrl: string,
- ): Promise<RendererTreeFile[]> {
- const { entries, metadata } = await this.fetchPack(rendererUrl, manifest.full, {
- kind: 'full',
- version: manifest.version,
- });
- if (metadata.kind !== 'full') throw new Error('Full pack metadata mismatch');
- for (const file of metadata.tree) {
- const content = entries.get(`objects/${file.sha256}`);
- if (!content) throw new Error(`Full pack missing ${file.path}`);
- await this.writeStaged(stagingDir, file.path, content);
- }
- return metadata.tree;
- }
-
- private async stageDelta(
- manifest: RendererManifest,
- delta: RendererDelta,
- stagingDir: string,
- byHash: Map<string, string>,
- rendererUrl: string,
- ): Promise<RendererTreeFile[]> {
- const { entries, metadata } = await this.fetchPack(rendererUrl, delta.pack, {
- fromVersion: delta.fromVersion,
- kind: 'delta',
- version: manifest.version,
- });
- if (metadata.kind !== 'delta') throw new Error('Delta pack metadata mismatch');
- if (!canApplyDelta(metadata, byHash)) throw new Error('Delta base content is incomplete');
- const objects = new Set(metadata.objects);
- const patches = new Map(metadata.patches.map((patch) => [patch.toSha256, patch]));
-
- for (const file of metadata.tree) {
- const localPath = byHash.get(file.sha256);
- if (localPath) {
- await this.placeLocalFile(localPath, path.join(stagingDir, file.path));
- continue;
- }
-
- if (objects.has(file.sha256)) {
- const content = entries.get(`objects/${file.sha256}`);
- if (!content) throw new Error(`Delta pack missing full object ${file.path}`);
- await this.writeStaged(stagingDir, file.path, content);
- continue;
- }
-
- const patch = patches.get(file.sha256);
- const basePath = patch && byHash.get(patch.fromSha256);
- const patchContent = patch && entries.get(`patches/${patch.patchSha256}`);
- if (!patch || !basePath || !patchContent) {
- throw new Error(`Delta cannot reconstruct ${file.path}`);
- }
- const next = await applyZstdPatch(await readFile(basePath), patchContent);
- await this.writeStaged(stagingDir, file.path, next);
- }
- return metadata.tree;
- }
-
- private async placeLocalFile(localPath: string, target: string) {
- await mkdir(path.dirname(target), { recursive: true });
- try {
- await link(localPath, target);
- } catch {
- await copyFile(localPath, target);
- }
- }
-
- private async writeStaged(stagingDir: string, relPath: string, content: Buffer) {
- const target = path.join(stagingDir, relPath);
- await mkdir(path.dirname(target), { recursive: true });
- await writeFile(target, content);
- }
-
- private async fetchPack(
- rendererUrl: string,
- artifact: RendererArtifact,
- expected: Parameters<typeof decodeRendererPack>[1],
- ) {
- const startedAt = Date.now();
- logger.info('Renderer OTA pack download started', {
- ...expected,
- bytes: artifact.size,
- });
- const res = await fetch(`${rendererUrl}/${artifact.path}`);
- if (!res.ok) throw new Error(`Renderer pack fetch failed (${res.status}): ${artifact.path}`);
- const content = Buffer.from(await res.arrayBuffer());
- if (content.byteLength !== artifact.size || sha256File(content) !== artifact.sha256) {
- throw new Error(`Renderer pack integrity mismatch: ${artifact.path}`);
- }
- logger.info('Renderer OTA pack download verified', {
- ...expected,
- bytes: content.byteLength,
- elapsedMs: Date.now() - startedAt,
- });
- return decodeRendererPack(content, expected);
- }
-
- private async hashLocalTree(otaDir: string, pointer: OtaPointer): Promise<Map<string, string>> {
- const root = pointer.current ? path.join(otaDir, 'versions', pointer.current) : rendererDir;
- const hashes = new Map<string, string>();
-
- const walk = async (dir: string) => {
- let entries;
- try {
- entries = await readdir(dir, { withFileTypes: true });
- } catch {
- return;
- }
- for (const entry of entries) {
- const full = path.join(dir, entry.name);
- if (entry.isDirectory()) await walk(full);
- else hashes.set(full, sha256File(await readFile(full)));
- }
- };
- await walk(root);
- return hashes;
- }
-
- private versionDirValid(version: string) {
- return existsSync(path.join(this.otaDir, 'versions', version, 'apps', 'desktop', 'index.html'));
- }
-
- private promoteToCurrent(version: string) {
- this.pointer = {
- ...this.pointer,
- current: version,
- pendingBootCheck: true,
- previous: this.pointer.current,
- staged: this.pointer.staged === version ? null : this.pointer.staged,
- };
- writePointer(this.otaDir, this.pointer);
- logger.info('Renderer OTA apply result', {
- ...this.logContext(),
- outcome: 'pending',
- reason: 'boot-check-pending',
- });
- }
-
- private rollback(reason: string) {
- const bad = this.pointer.current;
- const fallback =
- this.pointer.previous && this.versionDirValid(this.pointer.previous)
- ? this.pointer.previous
- : null;
-
- this.pointer = {
- ...this.pointer,
- blacklist: bad ? [...new Set([...this.pointer.blacklist, bad])] : this.pointer.blacklist,
- current: fallback,
- pendingBootCheck: false,
- previous: null,
- };
- writePointer(this.otaDir, this.pointer);
- logger.warn('Renderer OTA apply result', {
- ...this.logContext(),
- failedVersion: bad,
- outcome: 'rolled-back',
- reason,
- });
- this.gc();
- }
-
- private failBootCheck(reason: string) {
- this.clearBootTimers();
- this.rollback(reason);
- this.applyServingRoot();
- this.reloadAllWindows();
- }
-
- private clearLoadPingTimer() {
- if (this.loadPingTimer) clearTimeout(this.loadPingTimer);
- this.loadPingTimer = null;
- }
-
- private clearBootTimers() {
- this.clearLoadPingTimer();
- if (this.bootCheckTimer) clearTimeout(this.bootCheckTimer);
- this.bootCheckTimer = null;
- }
-
- private armBootCheck(options?: { expectFastLoad?: boolean }) {
- this.bootCrashCount = 0;
- this.clearBootTimers();
-
- if (options?.expectFastLoad) {
- this.loadPingTimer = setTimeout(() => {
- logger.warn(`No load ping within ${LOAD_PING_TIMEOUT}ms`);
- this.failBootCheck('load-timeout');
- }, LOAD_PING_TIMEOUT);
- this.loadPingTimer.unref?.();
- }
-
- this.bootCheckTimer = setTimeout(() => {
- logger.warn(`No boot ping within ${BOOT_CHECK_TIMEOUT}ms`);
- this.failBootCheck('boot-timeout');
- }, BOOT_CHECK_TIMEOUT);
- this.bootCheckTimer.unref?.();
- }
-
- private applyServingRoot() {
- const dir =
- this.pointer.current && this.versionDirValid(this.pointer.current)
- ? path.join(this.otaDir, 'versions', this.pointer.current)
- : null;
- this.app.rendererUrlManager.setActiveRendererDir(dir);
- logger.info('Renderer OTA serving root', {
- ...this.logContext(),
- servedVersion: dir ? this.pointer.current : 'r0',
- reason: this.pointer.current && !dir ? 'current-files-missing' : 'selected',
- });
- }
-
- private reloadAllWindows(ignoreBeforeUnload = false) {
- this.app.browserManager.browsers.forEach((browser) => {
- try {
- browser.reloadIgnoringCache(ignoreBeforeUnload);
- } catch {
- /* window may be destroyed */
- }
- });
- }
-
- private gc() {
- const versionsDir = path.join(this.otaDir, 'versions');
- const keep = new Set(
- [this.pointer.current, this.pointer.previous, this.pointer.staged].filter(Boolean),
- );
-
- rmSync(path.join(this.otaDir, 'staging'), { force: true, recursive: true });
-
- let entries;
- try {
- entries = readdirSync(versionsDir);
- } catch {
- return;
- }
- for (const entry of entries) {
- if (!keep.has(entry)) {
- logger.debug(`GC renderer version ${entry}`);
- rmSync(path.join(versionsDir, entry), { force: true, recursive: true });
- }
- }
- }
-}
diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/RendererUpdateManager.int.test.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/RendererUpdateManager.int.test.ts
deleted file mode 100644
index a79156c43e8..00000000000
--- a/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/RendererUpdateManager.int.test.ts
+++ /dev/null
@@ -1,699 +0,0 @@
-import { generateKeyPairSync, sign } from 'node:crypto';
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import path from 'node:path';
-import { zstdCompressSync } from 'node:zlib';
-
-import { zipSync } from 'fflate';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import {
- canonicalJson,
- type RendererDeltaPackMetadata,
- type RendererManifest,
- type RendererPackMetadata,
- type RendererTreeFile,
- sha256File,
-} from '../manifest';
-import { emptyPointer, readPointer, writePointer } from '../pointer';
-
-const { privateKey, publicKey } = generateKeyPairSync('ed25519');
-const PUBLIC_KEY_PEM = publicKey.export({ format: 'pem', type: 'spki' }).toString();
-const APP_VERSION = '1.0.0';
-const MAIN_HASH = 'a'.repeat(64);
-const SERVER = 'https://updates.test';
-
-let userDataDir: string;
-let builtinDir: string;
-const { loggerMock, updaterConfigMock } = vi.hoisted(() => ({
- loggerMock: { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() },
- updaterConfigMock: { buildChannel: 'stable', isDev: false },
-}));
-
-vi.mock('@/utils/logger', () => ({ createLogger: () => loggerMock }));
-vi.mock('electron', () => ({
- app: { getPath: () => userDataDir, getVersion: () => APP_VERSION },
-}));
-vi.mock('@/const/dir', () => ({
- get rendererDir() {
- return builtinDir;
- },
-}));
-vi.mock('@/const/env', () => ({
- get isDev() {
- return updaterConfigMock.isDev;
- },
-}));
-vi.mock('@/modules/updater/configs', () => ({
- get BUILD_CHANNEL() {
- return updaterConfigMock.buildChannel;
- },
- UPDATE_CHANNEL: 'stable',
- UPDATE_SERVER_URL: 'https://updates.test/stable',
- coerceStoredUpdateChannel: (channel?: string) => (channel === 'canary' ? 'canary' : 'stable'),
-}));
-const makeApp = () => ({
- browserManager: { broadcastToAllWindows: vi.fn(), browsers: new Map() },
- rendererUrlManager: { setActiveRendererDir: vi.fn() },
- storeManager: { get: vi.fn(() => 'stable') },
-});
-
-const channelDir = (channel = 'stable') =>
- path.join(userDataDir, 'renderer-ota-v2', channel, APP_VERSION);
-
-const signManifest = (unsigned: Omit<RendererManifest, 'signature'>): RendererManifest => ({
- ...unsigned,
- signature: sign(null, Buffer.from(canonicalJson(unsigned)), privateKey).toString('base64'),
-});
-
-const entryHtml = (marker: string) =>
- `<html><head><script type="module" src="/assets/entry-e2e.js"></script></head><body>${marker}</body></html>`;
-
-type Feed = {
- manifest: RendererManifest;
- objects: Map<string, Buffer>;
- packs: Map<string, Buffer>;
- tree: RendererTreeFile[];
-};
-
-const createPack = (metadata: RendererPackMetadata, entries: Map<string, Buffer>) => {
- const input = Object.fromEntries([
- ['meta.json', Buffer.from(JSON.stringify(metadata))],
- ...entries,
- ]);
- const content = Buffer.from(zipSync(input));
- const sha256 = sha256File(content);
- return {
- artifact: { path: `packs/${sha256}.zip`, sha256, size: content.byteLength },
- content,
- };
-};
-
-const buildFeed = (version: string, files: Record<string, Buffer | string>): Feed => {
- const withEntries = {
- 'apps/desktop/overlay.html': entryHtml(`${version}-overlay`),
- 'apps/desktop/popup.html': entryHtml(`${version}-popup`),
- ...files,
- };
- const objects = new Map<string, Buffer>();
- const tree = Object.entries(withEntries).map(([filePath, value]) => {
- const content = Buffer.isBuffer(value) ? value : Buffer.from(value);
- const sha256 = sha256File(content);
- objects.set(sha256, content);
- return { path: filePath, sha256, size: content.byteLength };
- });
- const fullPack = createPack(
- { kind: 'full', packVersion: 1, tree, version },
- new Map([...objects].map(([sha256, content]) => [`objects/${sha256}`, content])),
- );
- return {
- manifest: signManifest({
- appVersion: APP_VERSION,
- full: fullPack.artifact,
- mainHash: MAIN_HASH,
- schemaVersion: 2,
- version,
- }),
- objects,
- packs: new Map([[fullPack.artifact.path, fullPack.content]]),
- tree,
- };
-};
-
-const addDelta = (
- feed: Feed,
- delta: Pick<RendererDeltaPackMetadata, 'fromVersion' | 'objects' | 'patches'>,
- payloads: Map<string, Buffer>,
-) => {
- const pack = createPack(
- {
- ...delta,
- kind: 'delta',
- packVersion: 1,
- tree: feed.tree,
- version: feed.manifest.version,
- },
- payloads,
- );
- feed.packs.set(pack.artifact.path, pack.content);
- const { signature: _signature, ...unsigned } = feed.manifest;
- feed.manifest = signManifest({
- ...unsigned,
- deltas: [{ fromVersion: delta.fromVersion, pack: pack.artifact }],
- });
-};
-
-const stubFetch = (feed: Feed | null, channel = 'stable') => {
- vi.stubGlobal(
- 'fetch',
- vi.fn(async (input: string | URL) => {
- const url = String(input);
- const root = `${SERVER}/${channel}/${APP_VERSION}/renderer/v2`;
- if (url === `${root}/latest.json`) {
- if (!feed) return new Response('nope', { status: 404 });
- return Response.json(feed.manifest);
- }
- const relative = url.startsWith(`${root}/`) ? url.slice(root.length + 1) : '';
- const content = feed?.packs.get(relative);
- if (content) return new Response(new Uint8Array(content));
- return new Response('nope', { status: 404 });
- }),
- );
-};
-
-const loadManager = async (app: ReturnType<typeof makeApp>) => {
- vi.resetModules();
- process.env.MAIN_HASH = MAIN_HASH;
- process.env.RENDERER_OTA_PUBLIC_KEY = PUBLIC_KEY_PEM;
- const { RendererUpdateManager } = await import('../RendererUpdateManager');
- return new RendererUpdateManager(app as never);
-};
-
-beforeEach(() => {
- vi.clearAllMocks();
- updaterConfigMock.buildChannel = 'stable';
- updaterConfigMock.isDev = false;
- userDataDir = mkdtempSync(path.join(tmpdir(), 'ota-user-'));
- builtinDir = mkdtempSync(path.join(tmpdir(), 'ota-builtin-'));
- mkdirSync(path.join(builtinDir, 'apps', 'desktop'), { recursive: true });
- writeFileSync(path.join(builtinDir, 'apps', 'desktop', 'index.html'), '<html>builtin</html>');
- writeFileSync(path.join(builtinDir, 'shared.js'), 'shared-content');
-});
-
-afterEach(() => {
- rmSync(userDataDir, { force: true, recursive: true });
- rmSync(builtinDir, { force: true, recursive: true });
- vi.unstubAllGlobals();
- delete process.env.MAIN_HASH;
- delete process.env.RENDERER_OTA_PUBLIC_KEY;
-});
-
-describe('RendererUpdateManager V2 lifecycle', () => {
- it.each(['', '0.9.0'])(
- 'ignores prior full-release state with the same mainHash (%s)',
- async (version) => {
- const oldDir = path.join(userDataDir, 'renderer-ota-v2', 'stable', version);
- const oldEntry = path.join(oldDir, 'versions', 'r9', 'apps', 'desktop', 'index.html');
- mkdirSync(path.dirname(oldEntry), { recursive: true });
- writeFileSync(oldEntry, '<html>previous full release</html>');
- writePointer(oldDir, {
- ...emptyPointer(MAIN_HASH),
- blacklist: ['r1'],
- current: 'r9',
- staged: 'r9',
- });
-
- const app = makeApp();
- const manager = await loadManager(app);
- manager.initialize();
- expect(app.rendererUrlManager.setActiveRendererDir).toHaveBeenLastCalledWith(null);
- expect(manager.getStatus()).toMatchObject({ current: null, staged: null });
- expect(readFileSync(oldEntry, 'utf8')).toContain('previous full release');
-
- stubFetch(
- buildFeed('r0', {
- 'apps/desktop/index.html': entryHtml('builtin'),
- 'assets/entry-e2e.js': 'console.log("builtin")',
- }),
- );
- await manager.checkForUpdates();
- expect(app.browserManager.broadcastToAllWindows).not.toHaveBeenCalled();
- expect(fetch).toHaveBeenCalledTimes(1);
-
- stubFetch(
- buildFeed('r1', {
- 'apps/desktop/index.html': entryHtml('new patch'),
- 'assets/entry-e2e.js': 'console.log("new patch")',
- }),
- );
- await manager.checkForUpdates();
- expect(manager.getStatus().staged).toBe('r1');
- expect(app.browserManager.broadcastToAllWindows).toHaveBeenCalledWith('updateReady', {
- kind: 'renderer',
- version: `${APP_VERSION}.r1`,
- });
- },
- );
-
- it('records both compatibility hashes and rejects the patch before downloading', async () => {
- const app = makeApp();
- const manager = await loadManager(app);
- manager.initialize();
- const feed = buildFeed('r1', {
- 'apps/desktop/index.html': entryHtml('v1'),
- 'assets/entry-e2e.js': 'console.log("v1")',
- });
- const { signature: _signature, ...unsigned } = feed.manifest;
- feed.manifest = signManifest({ ...unsigned, mainHash: 'b'.repeat(64) });
- stubFetch(feed);
-
- await manager.checkForUpdates();
-
- expect(loggerMock.info).toHaveBeenCalledWith('Renderer OTA manifest compatibility', {
- localAppVersion: APP_VERSION,
- localMainHash: MAIN_HASH,
- remoteAppVersion: APP_VERSION,
- remoteMainHash: 'b'.repeat(64),
- remoteVersion: 'r1',
- });
- expect(loggerMock.error).toHaveBeenCalledWith(
- 'Renderer OTA check failed:',
- expect.objectContaining({ message: 'Manifest mainHash mismatch' }),
- expect.objectContaining({ reason: 'hash-mismatch', checkId: expect.any(String) }),
- );
- expect(loggerMock.info).toHaveBeenCalledWith(
- 'Renderer OTA check finished',
- expect.objectContaining({
- outcome: 'failed',
- reason: 'hash-mismatch',
- localMainHash: MAIN_HASH,
- remoteMainHash: 'b'.repeat(64),
- remoteVersion: 'r1',
- state: 'idle',
- }),
- );
- expect(fetch).toHaveBeenCalledTimes(1);
- expect(manager.getStatus()).toMatchObject({ current: null, staged: null, state: 'idle' });
- expect(app.browserManager.broadcastToAllWindows).not.toHaveBeenCalled();
- expect(JSON.stringify(loggerMock.info.mock.calls)).not.toContain(PUBLIC_KEY_PEM);
- });
-
- it('downloads one full pack, stages it, applies it, and commits after boot ping', async () => {
- const app = makeApp();
- const reloadIgnoringCache = vi.fn();
- app.browserManager.browsers.set('app', {
- reloadIgnoringCache,
- });
- const manager = await loadManager(app);
- manager.initialize();
- const feed = buildFeed('r1', {
- 'apps/desktop/index.html': entryHtml('v1'),
- 'assets/entry-e2e.js': 'console.log("v1")',
- 'shared.js': 'shared-content',
- });
- stubFetch(feed);
-
- await manager.checkForUpdates();
-
- const otaDir = channelDir();
- expect(readPointer(otaDir, MAIN_HASH).staged).toBe('r1');
- expect(loggerMock.info).toHaveBeenCalledWith(
- 'Renderer OTA check finished',
- expect.objectContaining({ outcome: 'staged', reason: 'staged', staged: 'r1' }),
- );
- expect(loggerMock.info.mock.calls.some(([name]) => name === 'Renderer OTA apply result')).toBe(
- false,
- );
- expect(app.browserManager.broadcastToAllWindows).toHaveBeenCalledWith('updateReady', {
- kind: 'renderer',
- version: `${APP_VERSION}.r1`,
- });
- const fetchedUrls = (fetch as ReturnType<typeof vi.fn>).mock.calls.map((call) => call[0]);
- expect(fetchedUrls).toEqual([
- `${SERVER}/stable/${APP_VERSION}/renderer/v2/latest.json`,
- `${SERVER}/stable/${APP_VERSION}/renderer/v2/${feed.manifest.full.path}`,
- ]);
- expect(fetchedUrls.some((url: string) => url.includes('/renderer/files/'))).toBe(false);
-
- expect(manager.applyStagedNow()).toBe(true);
- expect(reloadIgnoringCache).toHaveBeenCalledWith(true);
- expect(
- readFileSync(path.join(otaDir, 'versions', 'r1', 'apps', 'desktop', 'index.html'), 'utf8'),
- ).toBe(entryHtml('v1'));
- expect(loggerMock.info).toHaveBeenCalledWith(
- 'Renderer OTA apply result',
- expect.objectContaining({ outcome: 'pending', reason: 'boot-check-pending' }),
- );
- manager.handleBootPing();
- expect(loggerMock.info).toHaveBeenCalledWith(
- 'Renderer OTA apply result',
- expect.objectContaining({ outcome: 'applied', reason: 'boot-confirmed', current: 'r1' }),
- );
- expect(readPointer(otaDir, MAIN_HASH)).toMatchObject({
- current: 'r1',
- pendingBootCheck: false,
- });
- });
-
- it('uses one delta pack to reuse, patch, and add renderer files', async () => {
- const oldChunk = Buffer.alloc(32 * 1024, 7);
- const newChunk = Buffer.from(oldChunk);
- newChunk[10] = 9;
- writeFileSync(path.join(builtinDir, 'chunk.bin'), oldChunk);
-
- const app = makeApp();
- const manager = await loadManager(app);
- manager.initialize();
- const feed = buildFeed('r1', {
- 'apps/desktop/index.html': entryHtml('v1'),
- 'assets/entry-e2e.js': 'console.log("v1")',
- 'chunk.bin': newChunk,
- 'shared.js': 'shared-content',
- });
- const chunk = feed.tree.find((file) => file.path === 'chunk.bin');
- const shared = feed.tree.find((file) => file.path === 'shared.js');
- if (!chunk || !shared) throw new Error('expected files');
- const patch = Buffer.from(zstdCompressSync(newChunk, { dictionary: oldChunk }));
- const patchSha256 = sha256File(patch);
- const fullObjects = feed.tree.filter(
- (file) => file.sha256 !== chunk.sha256 && file.sha256 !== shared.sha256,
- );
- addDelta(
- feed,
- {
- fromVersion: 'r0',
- objects: fullObjects.map((file) => file.sha256),
- patches: [{ fromSha256: sha256File(oldChunk), patchSha256, toSha256: chunk.sha256 }],
- },
- new Map([
- ...fullObjects.map(
- (file) => [`objects/${file.sha256}`, feed.objects.get(file.sha256) as Buffer] as const,
- ),
- [`patches/${patchSha256}`, patch],
- ]),
- );
- stubFetch(feed);
-
- await manager.checkForUpdates();
-
- const fetchedUrls = (fetch as ReturnType<typeof vi.fn>).mock.calls.map((call) => call[0]);
- const delta = feed.manifest.deltas?.[0];
- expect(fetchedUrls).toEqual([
- `${SERVER}/stable/${APP_VERSION}/renderer/v2/latest.json`,
- `${SERVER}/stable/${APP_VERSION}/renderer/v2/${delta?.pack.path}`,
- ]);
- expect(readFileSync(path.join(channelDir(), 'versions', 'r1', 'chunk.bin'))).toEqual(newChunk);
- });
-
- it('falls back to the full pack when the selected delta pack is corrupt', async () => {
- const app = makeApp();
- const manager = await loadManager(app);
- manager.initialize();
- const feed = buildFeed('r1', {
- 'apps/desktop/index.html': entryHtml('v1'),
- 'assets/entry-e2e.js': 'console.log("v1")',
- 'shared.js': 'shared-content',
- });
- const localHash = sha256File(Buffer.from('shared-content'));
- const targetHashes = [
- ...new Set(feed.tree.filter((file) => file.sha256 !== localHash).map((file) => file.sha256)),
- ];
- addDelta(
- feed,
- { fromVersion: 'r0', objects: targetHashes, patches: [] },
- new Map(
- targetHashes.map((sha256) => [`objects/${sha256}`, feed.objects.get(sha256) as Buffer]),
- ),
- );
- const delta = feed.manifest.deltas?.[0];
- if (!delta) throw new Error('expected delta');
- feed.packs.set(delta.pack.path, Buffer.from('corrupt'));
- stubFetch(feed);
-
- await manager.checkForUpdates();
-
- const fetchedUrls = (fetch as ReturnType<typeof vi.fn>).mock.calls.map((call) => call[0]);
- expect(fetchedUrls).toEqual([
- `${SERVER}/stable/${APP_VERSION}/renderer/v2/latest.json`,
- `${SERVER}/stable/${APP_VERSION}/renderer/v2/${delta.pack.path}`,
- `${SERVER}/stable/${APP_VERSION}/renderer/v2/${feed.manifest.full.path}`,
- ]);
- expect(readPointer(channelDir(), MAIN_HASH).staged).toBe('r1');
- });
-
- it('keeps the current renderer when a full pack fails integrity verification', async () => {
- const app = makeApp();
- const manager = await loadManager(app);
- manager.initialize();
- const feed = buildFeed('r1', {
- 'apps/desktop/index.html': entryHtml('v1'),
- 'assets/entry-e2e.js': 'console.log("v1")',
- });
- feed.packs.set(feed.manifest.full.path, Buffer.from('tampered-on-cdn'));
- stubFetch(feed);
-
- await manager.checkForUpdates();
-
- expect(readPointer(channelDir(), MAIN_HASH).staged).toBeNull();
- expect(existsSync(path.join(channelDir(), 'staging'))).toBe(false);
- expect(loggerMock.info).toHaveBeenCalledWith(
- 'Renderer OTA check finished',
- expect.objectContaining({ reason: 'download-failed', outcome: 'failed' }),
- );
- });
-
- it('rejects a manifest signed by a foreign key', async () => {
- const app = makeApp();
- const manager = await loadManager(app);
- manager.initialize();
- const feed = buildFeed('r1', {
- 'apps/desktop/index.html': entryHtml('evil'),
- 'assets/entry-e2e.js': 'evil',
- });
- const foreign = generateKeyPairSync('ed25519').privateKey;
- const { signature: _signature, ...unsigned } = feed.manifest;
- feed.manifest = {
- ...unsigned,
- signature: sign(null, Buffer.from(canonicalJson(unsigned)), foreign).toString('base64'),
- };
- stubFetch(feed);
-
- await manager.checkForUpdates();
-
- expect(readPointer(channelDir(), MAIN_HASH).staged).toBeNull();
- expect(app.browserManager.broadcastToAllWindows).not.toHaveBeenCalled();
- expect(loggerMock.info).toHaveBeenCalledWith(
- 'Renderer OTA check finished',
- expect.objectContaining({ reason: 'signature-invalid', outcome: 'failed' }),
- );
- });
-
- it('clears the complete V1 root without migrating its state', async () => {
- const legacyRoot = path.join(userDataDir, 'renderer-ota');
- const legacyDir = path.join(legacyRoot, 'stable');
- mkdirSync(path.join(legacyDir, 'versions', 'r9', 'assets'), { recursive: true });
- mkdirSync(path.join(legacyDir, 'staging', 'r10'), { recursive: true });
- mkdirSync(path.join(legacyRoot, 'cache'), { recursive: true });
- writeFileSync(
- path.join(legacyDir, 'pointer.json'),
- JSON.stringify({ current: 'r9', mainHash: MAIN_HASH }),
- );
- writeFileSync(path.join(legacyDir, 'versions', 'r9', 'assets', 'app.js'), 'v1');
- writeFileSync(path.join(legacyRoot, 'cache', 'patch.bin'), 'cached-patch');
-
- const app = makeApp();
- const manager = await loadManager(app);
- manager.initialize();
-
- expect(readPointer(channelDir(), MAIN_HASH).current).toBeNull();
- expect(existsSync(legacyRoot)).toBe(false);
- expect(app.rendererUrlManager.setActiveRendererDir).toHaveBeenLastCalledWith(null);
- });
-
- it('resets V2 state when a full release changes mainHash', async () => {
- const otaDir = channelDir();
- mkdirSync(otaDir, { recursive: true });
- writeFileSync(
- path.join(otaDir, 'pointer.json'),
- JSON.stringify({
- blacklist: ['r9'],
- current: 'r9',
- mainHash: 'b'.repeat(64),
- pendingBootCheck: false,
- previous: null,
- staged: null,
- }),
- );
-
- const app = makeApp();
- const manager = await loadManager(app);
- manager.initialize();
-
- expect(readPointer(otaDir, MAIN_HASH)).toMatchObject({
- blacklist: [],
- current: null,
- mainHash: MAIN_HASH,
- });
- });
-
- it('rejects a staged tree whose entry html references a missing chunk', async () => {
- const app = makeApp();
- const manager = await loadManager(app);
- manager.initialize();
- stubFetch(
- buildFeed('r1', {
- 'apps/desktop/index.html':
- '<html><script type="module" src="/assets/gone.js"></script></html>',
- }),
- );
-
- await manager.checkForUpdates();
-
- expect(readPointer(channelDir(), MAIN_HASH).staged).toBeNull();
- expect(existsSync(path.join(channelDir(), 'staging'))).toBe(false);
- });
-
- it('rolls back and blacklists a renderer that never sends the load ping', async () => {
- const app = makeApp();
- const manager = await loadManager(app);
- manager.initialize();
- stubFetch(
- buildFeed('r1', {
- 'apps/desktop/index.html': entryHtml('v1'),
- 'assets/entry-e2e.js': 'throw new Error("boom")',
- }),
- );
- await manager.checkForUpdates();
-
- vi.useFakeTimers();
- try {
- manager.applyStagedNow();
- vi.advanceTimersByTime(3100);
- } finally {
- vi.useRealTimers();
- }
-
- expect(readPointer(channelDir(), MAIN_HASH)).toMatchObject({
- blacklist: ['r1'],
- current: null,
- });
- expect(loggerMock.warn).toHaveBeenCalledWith(
- 'Renderer OTA apply result',
- expect.objectContaining({
- reason: 'load-timeout',
- outcome: 'rolled-back',
- failedVersion: 'r1',
- current: 'r0',
- }),
- );
- });
-
- it('keeps V2 patch state independent across update channels', async () => {
- const app = makeApp();
- const manager = await loadManager(app);
- manager.initialize();
- const feed = buildFeed('r1', {
- 'apps/desktop/index.html': entryHtml('v1'),
- 'assets/entry-e2e.js': 'console.log("v1")',
- });
- stubFetch(feed);
- await manager.checkForUpdates();
-
- manager.switchChannel('canary');
- stubFetch(feed, 'canary');
- await manager.checkForUpdates();
-
- expect(readPointer(channelDir(), MAIN_HASH).staged).toBe('r1');
- expect(readPointer(channelDir('canary'), MAIN_HASH).staged).toBe('r1');
- });
-
- it.each([
- [404, 'feed-not-found', 'skipped'],
- [503, 'manifest-fetch-failed', 'failed'],
- [200, 'manifest-invalid', 'failed'],
- ])('reports HTTP %s with one final reason %s', async (status, reason, outcome) => {
- const manager = await loadManager(makeApp());
- manager.initialize();
- vi.stubGlobal(
- 'fetch',
- vi.fn(async () => Response.json({}, { status })),
- );
- await manager.checkForUpdates();
- const finished = loggerMock.info.mock.calls.filter(
- ([name]) => name === 'Renderer OTA check finished',
- );
- expect(finished).toHaveLength(1);
- expect(finished[0][1]).toMatchObject({
- reason,
- outcome,
- httpStatus: status,
- localMainHash: MAIN_HASH,
- appVersion: APP_VERSION,
- channel: 'stable',
- state: 'idle',
- });
- });
-
- it('explains disabled, busy and superseded checks without reporting an update', async () => {
- updaterConfigMock.isDev = true;
- const disabled = await loadManager(makeApp());
- await disabled.checkForUpdates();
- expect(loggerMock.info).toHaveBeenCalledWith(
- 'Renderer OTA check finished',
- expect.objectContaining({ reason: 'disabled', disabledReasons: ['development-build'] }),
- );
- updaterConfigMock.isDev = false;
- const manager = await loadManager(makeApp());
- manager.initialize();
- let respond!: (response: Response) => void;
- vi.stubGlobal(
- 'fetch',
- vi.fn(
- () =>
- new Promise<Response>((resolve) => {
- respond = resolve;
- }),
- ),
- );
- const checking = manager.checkForUpdates();
- await manager.checkForUpdates();
- manager.switchChannel('canary');
- respond(new Response('', { status: 404 }));
- await checking;
- const finished = loggerMock.info.mock.calls.filter(
- ([name]) => name === 'Renderer OTA check finished',
- );
- expect(finished.map(([, detail]) => detail.reason)).toEqual(['disabled', 'busy', 'superseded']);
- expect(new Set(finished.map(([, detail]) => detail.checkId)).size).toBe(3);
- expect(finished[2][1]).toMatchObject({
- channel: 'stable',
- state: 'superseded',
- outcome: 'skipped',
- });
- });
-
- it.each(['already-current', 'blacklisted', 'already-staged'])(
- 'explains %s without downloading',
- async (reason) => {
- const manager = await loadManager(makeApp());
- const pointer = emptyPointer(MAIN_HASH);
- if (reason === 'blacklisted') pointer.blacklist = ['r1'];
- if (reason === 'already-staged') pointer.staged = 'r1';
- mkdirSync(channelDir(), { recursive: true });
- writePointer(channelDir(), pointer);
- manager.initialize();
- const feed = buildFeed(reason === 'already-current' ? 'r0' : 'r1', {
- 'apps/desktop/index.html': entryHtml('v1'),
- 'assets/entry-e2e.js': 'console.log("v1")',
- });
- stubFetch(feed);
- await manager.checkForUpdates();
- expect(fetch).toHaveBeenCalledTimes(1);
- expect(loggerMock.info).toHaveBeenCalledWith(
- 'Renderer OTA check finished',
- expect.objectContaining({
- reason,
- outcome: 'skipped',
- remoteVersion: feed.manifest.version,
- }),
- );
- },
- );
-
- it('uses the dedicated V2 beta feed for beta binaries', async () => {
- updaterConfigMock.buildChannel = 'beta';
- const app = makeApp();
- app.storeManager.get.mockReturnValue('canary');
- const manager = await loadManager(app);
- manager.initialize();
- const feed = buildFeed('r1', {
- 'apps/desktop/index.html': entryHtml('beta'),
- 'assets/entry-e2e.js': 'console.log("beta")',
- });
- stubFetch(feed, 'beta');
-
- await manager.checkForUpdates();
-
- expect(readPointer(channelDir('beta'), MAIN_HASH).staged).toBe('r1');
- });
-});
diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/manifest.test.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/manifest.test.ts
deleted file mode 100644
index 3396ab693d0..00000000000
--- a/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/manifest.test.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-import { generateKeyPairSync, sign } from 'node:crypto';
-
-import { describe, expect, it } from 'vitest';
-
-import {
- canonicalJson,
- isValidManifestShape,
- patchNumber,
- type RendererManifest,
- verifyManifestSignature,
-} from '../manifest';
-
-const { privateKey, publicKey } = generateKeyPairSync('ed25519');
-const publicKeyPem = publicKey.export({ format: 'pem', type: 'spki' }).toString();
-const sha = (character: string) => character.repeat(64);
-
-const signManifest = (unsigned: Omit<RendererManifest, 'signature'>): RendererManifest => ({
- ...unsigned,
- signature: sign(null, Buffer.from(canonicalJson(unsigned)), privateKey).toString('base64'),
-});
-
-const baseManifest = (): RendererManifest =>
- signManifest({
- appVersion: '1.147.0',
- full: { path: `packs/${sha('c')}.zip`, sha256: sha('c'), size: 30 },
- mainHash: sha('f'),
- schemaVersion: 2,
- version: 'r3',
- });
-
-describe('canonicalJson', () => {
- it('sorts keys deterministically', () => {
- expect(canonicalJson({ b: 1, a: [{ d: 2, c: 3 }] })).toBe('{"a":[{"c":3,"d":2}],"b":1}');
- });
-});
-
-describe('verifyManifestSignature', () => {
- it('accepts a valid signature', () => {
- expect(verifyManifestSignature(baseManifest(), publicKeyPem)).toBe(true);
- });
-
- it('rejects a tampered manifest', () => {
- const manifest = baseManifest();
- manifest.full.size += 1;
- expect(verifyManifestSignature(manifest, publicKeyPem)).toBe(false);
- });
-
- it('rejects a foreign key', () => {
- const other = generateKeyPairSync('ed25519')
- .publicKey.export({ format: 'pem', type: 'spki' })
- .toString();
- expect(verifyManifestSignature(baseManifest(), other)).toBe(false);
- });
-});
-
-describe('isValidManifestShape', () => {
- it('accepts a well-formed V2 manifest', () => {
- expect(isValidManifestShape(baseManifest())).toBe(true);
- });
-
- it('rejects the V1 CAS manifest shape', () => {
- const { full: _full, schemaVersion: _schemaVersion, ...rest } = baseManifest();
- expect(
- isValidManifestShape({
- ...rest,
- files: [{ path: 'index.html', sha256: sha('a'), size: 10 }],
- }),
- ).toBe(false);
- });
-
- it('rejects unsafe artifact paths', () => {
- const artifactTraversal = baseManifest();
- artifactTraversal.full.path = '../foreign.zip';
- expect(isValidManifestShape(artifactTraversal)).toBe(false);
- });
-
- it('rejects a pack path that does not match its content hash', () => {
- const manifest = baseManifest();
- manifest.full.path = `packs/${sha('b')}.zip`;
- expect(isValidManifestShape(manifest)).toBe(false);
- });
-
- it('rejects non r<N> versions', () => {
- expect(isValidManifestShape({ ...baseManifest(), version: '1.2.3' })).toBe(false);
- });
-
- it('accepts a signed V2 delta pack', () => {
- const manifest = baseManifest();
- manifest.deltas = [
- {
- fromVersion: 'r0',
- pack: { path: `packs/${sha('d')}.zip`, sha256: sha('d'), size: 12 },
- },
- ];
- expect(isValidManifestShape(manifest)).toBe(true);
- });
-
- it('rejects a target tree in the outer manifest', () => {
- expect(
- isValidManifestShape({
- ...baseManifest(),
- tree: [{ path: 'index.html', sha256: sha('a'), size: 10 }],
- }),
- ).toBe(false);
- });
-});
-
-describe('patchNumber', () => {
- it('parses r<N>', () => {
- expect(patchNumber('r12')).toBe(12);
- });
-});
diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/pack.test.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/pack.test.ts
deleted file mode 100644
index 8f82aa3ef23..00000000000
--- a/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/pack.test.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { zipSync } from 'fflate';
-import { describe, expect, it } from 'vitest';
-
-import { sha256File } from '../manifest';
-import { decodeRendererPack } from '../pack';
-
-describe('decodeRendererPack', () => {
- it('loads the target tree from a full pack and returns its verified objects', async () => {
- const content = Buffer.from('renderer object');
- const sha256 = sha256File(content);
- const name = `objects/${sha256}`;
- const metadata = {
- kind: 'full',
- packVersion: 1,
- tree: [{ path: 'assets/app.js', sha256, size: content.byteLength }],
- version: 'r1',
- } as const;
- const pack = Buffer.from(
- zipSync({ 'meta.json': Buffer.from(JSON.stringify(metadata)), [name]: content }),
- );
-
- const decoded = await decodeRendererPack(pack, { kind: 'full', version: 'r1' });
- expect(decoded.metadata).toEqual(metadata);
- expect(decoded.entries.get(name)).toEqual(content);
- });
-
- it('loads delta reconstruction metadata from the selected pack', async () => {
- const content = Buffer.from('next renderer object');
- const sha256 = sha256File(content);
- const name = `objects/${sha256}`;
- const metadata = {
- fromVersion: 'r0',
- kind: 'delta',
- objects: [sha256],
- packVersion: 1,
- patches: [],
- tree: [{ path: 'assets/app.js', sha256, size: content.byteLength }],
- version: 'r1',
- } as const;
- const pack = Buffer.from(
- zipSync({ 'meta.json': Buffer.from(JSON.stringify(metadata)), [name]: content }),
- );
-
- const decoded = await decodeRendererPack(pack, {
- fromVersion: 'r0',
- kind: 'delta',
- version: 'r1',
- });
- expect(decoded.metadata).toEqual(metadata);
- expect(decoded.entries.get(name)).toEqual(content);
- });
-
- it('rejects unexpected, tampered, or path-traversing pack content', async () => {
- const content = Buffer.from('renderer object');
- const sha256 = sha256File(content);
- const name = `objects/${sha256}`;
- const metadata = {
- kind: 'full',
- packVersion: 1,
- tree: [{ path: 'assets/app.js', sha256, size: content.byteLength }],
- version: 'r1',
- } as const;
- const encodedMetadata = Buffer.from(JSON.stringify(metadata));
-
- await expect(
- decodeRendererPack(Buffer.from(zipSync({ 'extra': content, 'meta.json': encodedMetadata })), {
- kind: 'full',
- version: 'r1',
- }),
- ).rejects.toThrow('entries do not match metadata');
- await expect(
- decodeRendererPack(
- Buffer.from(zipSync({ [name]: Buffer.from('tampered'), 'meta.json': encodedMetadata })),
- { kind: 'full', version: 'r1' },
- ),
- ).rejects.toThrow(`pack entry invalid: ${name}`);
-
- await expect(
- decodeRendererPack(
- Buffer.from(
- zipSync({
- [name]: content,
- 'meta.json': Buffer.from(
- JSON.stringify({
- ...metadata,
- tree: [{ ...metadata.tree[0], path: '../app.js' }],
- }),
- ),
- }),
- ),
- { kind: 'full', version: 'r1' },
- ),
- ).rejects.toThrow('pack metadata invalid');
- });
-});
diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/pointer.test.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/pointer.test.ts
deleted file mode 100644
index a3864ac46ca..00000000000
--- a/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/pointer.test.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import path from 'node:path';
-
-import { afterEach, describe, expect, it } from 'vitest';
-
-import { emptyPointer, readPointer, writePointer } from '../pointer';
-
-const HASH_A = 'a'.repeat(64);
-const HASH_B = 'b'.repeat(64);
-
-let dirs: string[] = [];
-const makeDir = () => {
- const dir = mkdtempSync(path.join(tmpdir(), 'renderer-ota-'));
- dirs.push(dir);
- return dir;
-};
-
-afterEach(() => {
- for (const dir of dirs) rmSync(dir, { force: true, recursive: true });
- dirs = [];
-});
-
-describe('pointer', () => {
- it('round-trips through write/read', () => {
- const dir = makeDir();
- const pointer = {
- ...emptyPointer(HASH_A),
- current: 'r2',
- pendingBootCheck: true,
- previous: 'r1',
- staged: 'r3',
- };
-
- writePointer(dir, pointer);
-
- expect(readPointer(dir, HASH_A)).toEqual(pointer);
- });
-
- it('returns an empty pointer when the file is missing', () => {
- expect(readPointer(makeDir(), HASH_A)).toEqual(emptyPointer(HASH_A));
- });
-
- it('resets the lineage when mainHash changed (full release installed)', () => {
- const dir = makeDir();
- writePointer(dir, { ...emptyPointer(HASH_A), current: 'r5' });
-
- expect(readPointer(dir, HASH_B)).toEqual(emptyPointer(HASH_B));
- });
-
- it('survives a corrupt pointer file', () => {
- const dir = makeDir();
- writeFileSync(path.join(dir, 'pointer.json'), '{not json');
-
- expect(readPointer(dir, HASH_A)).toEqual(emptyPointer(HASH_A));
- });
-
- it('writes atomically via temp+rename', () => {
- const dir = makeDir();
- writePointer(dir, emptyPointer(HASH_A));
-
- const raw = JSON.parse(readFileSync(path.join(dir, 'pointer.json'), 'utf8'));
- expect(raw.mainHash).toBe(HASH_A);
- });
-});
diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/updatePlan.test.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/updatePlan.test.ts
deleted file mode 100644
index 6fdddd6a9f9..00000000000
--- a/apps/desktop/src/main/core/infrastructure/rendererOta/__tests__/updatePlan.test.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import type { RendererDelta, RendererDeltaPackMetadata, RendererManifest } from '../manifest';
-import { canApplyDelta, indexLocalByHash, pickDelta } from '../updatePlan';
-
-const sha = (character: string) => character.repeat(64);
-
-const delta = (fromVersion: string): RendererDelta => ({
- fromVersion,
- pack: { path: `packs/${sha('a')}.zip`, sha256: sha('a'), size: 10 },
-});
-
-const manifest = (deltas?: RendererManifest['deltas']): RendererManifest => ({
- appVersion: '1.0.0',
- deltas,
- full: { path: `packs/${sha('f')}.zip`, sha256: sha('f'), size: 20 },
- mainHash: sha('m'),
- schemaVersion: 2,
- signature: 'sig',
- version: 'r2',
-});
-
-const metadata = (): RendererDeltaPackMetadata => ({
- fromVersion: 'r0',
- kind: 'delta',
- objects: [sha('n')],
- packVersion: 1,
- patches: [{ fromSha256: sha('o'), patchSha256: sha('b'), toSha256: sha('t') }],
- tree: [
- { path: 'unchanged.js', sha256: sha('u'), size: 1 },
- { path: 'patched.js', sha256: sha('t'), size: 1 },
- { path: 'new.js', sha256: sha('n'), size: 1 },
- ],
- version: 'r2',
-});
-
-describe('pickDelta', () => {
- it('selects only the pack matching the local version', () => {
- const r0 = delta('r0');
- const r1 = delta('r1');
- expect(pickDelta(manifest([r0, r1]), 'r0')).toBe(r0);
- expect(pickDelta(manifest([r0, r1]), 'r3')).toBeUndefined();
- });
-});
-
-describe('canApplyDelta', () => {
- it('accepts locally reusable files plus declared full and patch payloads', () => {
- const byHash = indexLocalByHash(
- new Map([
- ['/old/unchanged.js', sha('u')],
- ['/old/base.js', sha('o')],
- ]),
- );
- expect(canApplyDelta(metadata(), byHash)).toBe(true);
- });
-
- it('requires every target to be locally reusable or reconstructable from the pack', () => {
- const byHash = indexLocalByHash(new Map([['/old/unchanged.js', sha('u')]]));
- expect(canApplyDelta(metadata(), byHash)).toBe(false);
- });
-});
diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/manifest.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/manifest.ts
deleted file mode 100644
index b3fb54f2682..00000000000
--- a/apps/desktop/src/main/core/infrastructure/rendererOta/manifest.ts
+++ /dev/null
@@ -1,211 +0,0 @@
-import { createHash, verify as cryptoVerify } from 'node:crypto';
-
-import * as z from 'zod/v4';
-
-const sha256Schema = z.string().regex(/^[0-9a-f]{64}$/);
-const versionSchema = z.string().regex(/^r\d+$/);
-const packPathSchema = z.string().regex(/^packs\/[0-9a-f]{64}\.zip$/);
-const relativePathSchema = z.string().refine((value) => {
- if (!value || value.startsWith('/') || value.startsWith('\\') || value.includes('\\')) {
- return false;
- }
- return value.split('/').every((segment) => segment && segment !== '.' && segment !== '..');
-});
-
-export const rendererTreeFileSchema = z
- .object({
- path: relativePathSchema,
- sha256: sha256Schema,
- size: z.number().int().nonnegative(),
- })
- .strict();
-
-export const rendererArtifactSchema = z
- .object({
- path: packPathSchema,
- sha256: sha256Schema,
- size: z.number().int().positive(),
- })
- .strict()
- .refine((artifact) => artifact.path === `packs/${artifact.sha256}.zip`);
-
-export const rendererPatchSchema = z
- .object({
- fromSha256: sha256Schema,
- patchSha256: sha256Schema,
- toSha256: sha256Schema,
- })
- .strict();
-
-export const rendererDeltaSchema = z
- .object({
- fromVersion: versionSchema,
- pack: rendererArtifactSchema,
- })
- .strict();
-
-export const rendererTreeSchema = z
- .array(rendererTreeFileSchema)
- .min(1)
- .superRefine((tree, ctx) => {
- const paths = new Set<string>();
- for (const file of tree) {
- if (paths.has(file.path)) {
- ctx.addIssue({ code: 'custom', message: `duplicate renderer path: ${file.path}` });
- }
- paths.add(file.path);
- }
- });
-
-export const rendererFullPackMetadataSchema = z
- .object({
- kind: z.literal('full'),
- packVersion: z.literal(1),
- tree: rendererTreeSchema,
- version: versionSchema,
- })
- .strict();
-
-export const rendererDeltaPackMetadataSchema = z
- .object({
- fromVersion: versionSchema,
- kind: z.literal('delta'),
- objects: z.array(sha256Schema),
- packVersion: z.literal(1),
- patches: z.array(rendererPatchSchema),
- tree: rendererTreeSchema,
- version: versionSchema,
- })
- .strict()
- .superRefine((metadata, ctx) => {
- if (metadata.fromVersion === metadata.version) {
- ctx.addIssue({ code: 'custom', message: 'delta base and target versions must differ' });
- }
-
- const targets = new Set(metadata.tree.map((file) => file.sha256));
- const objectHashes = new Set<string>();
- for (const sha256 of metadata.objects) {
- if (objectHashes.has(sha256)) {
- ctx.addIssue({ code: 'custom', message: `duplicate renderer object: ${sha256}` });
- }
- if (!targets.has(sha256)) {
- ctx.addIssue({
- code: 'custom',
- message: `renderer object is not in target tree: ${sha256}`,
- });
- }
- objectHashes.add(sha256);
- }
-
- const patchTargets = new Set<string>();
- for (const patch of metadata.patches) {
- if (patchTargets.has(patch.toSha256)) {
- ctx.addIssue({
- code: 'custom',
- message: `duplicate renderer patch target: ${patch.toSha256}`,
- });
- }
- if (objectHashes.has(patch.toSha256)) {
- ctx.addIssue({
- code: 'custom',
- message: `renderer target has both object and patch: ${patch.toSha256}`,
- });
- }
- if (!targets.has(patch.toSha256)) {
- ctx.addIssue({
- code: 'custom',
- message: `renderer patch target is not in target tree: ${patch.toSha256}`,
- });
- }
- patchTargets.add(patch.toSha256);
- }
- });
-
-export const rendererPackMetadataSchema = z.discriminatedUnion('kind', [
- rendererFullPackMetadataSchema,
- rendererDeltaPackMetadataSchema,
-]);
-
-export const rendererManifestSchema = z
- .object({
- appVersion: z.string().min(1),
- deltas: z.array(rendererDeltaSchema).optional(),
- full: rendererArtifactSchema,
- mainHash: sha256Schema,
- schemaVersion: z.literal(2),
- signature: z.string().min(1),
- version: versionSchema,
- })
- .strict()
- .superRefine((manifest, ctx) => {
- const fromVersions = new Set<string>();
- for (const delta of manifest.deltas ?? []) {
- if (fromVersions.has(delta.fromVersion)) {
- ctx.addIssue({ code: 'custom', message: `duplicate delta base: ${delta.fromVersion}` });
- }
- fromVersions.add(delta.fromVersion);
- }
- });
-
-export type RendererArtifact = z.infer<typeof rendererArtifactSchema>;
-export type RendererDelta = z.infer<typeof rendererDeltaSchema>;
-export type RendererDeltaPackMetadata = z.infer<typeof rendererDeltaPackMetadataSchema>;
-export type RendererFullPackMetadata = z.infer<typeof rendererFullPackMetadataSchema>;
-export type RendererManifest = z.infer<typeof rendererManifestSchema>;
-export type RendererPackMetadata = z.infer<typeof rendererPackMetadataSchema>;
-export type RendererPatch = z.infer<typeof rendererPatchSchema>;
-export type RendererTreeFile = z.infer<typeof rendererTreeFileSchema>;
-
-export const canonicalJson = (value: unknown): string => {
- if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
- if (value && typeof value === 'object') {
- const entries = Object.keys(value as Record<string, unknown>)
- .sort()
- .map(
- (key) => `${JSON.stringify(key)}:${canonicalJson((value as Record<string, unknown>)[key])}`,
- );
- return `{${entries.join(',')}}`;
- }
- return JSON.stringify(value);
-};
-
-export const verifyManifestSignature = (
- manifest: RendererManifest,
- publicKeyPem: string,
-): boolean => {
- const { signature, ...unsigned } = manifest;
- try {
- return cryptoVerify(
- null,
- Buffer.from(canonicalJson(unsigned)),
- publicKeyPem,
- Buffer.from(signature, 'base64'),
- );
- } catch {
- return false;
- }
-};
-
-export const isValidManifestShape = (value: unknown): value is RendererManifest =>
- rendererManifestSchema.safeParse(value).success;
-
-export const patchNumber = (version: string): number => Number(version.slice(1));
-
-export const sha256File = (content: Buffer): string =>
- createHash('sha256').update(content).digest('hex');
-
-/**
- * Static integrity check on a staged tree's entry html: every referenced local
- * js/css must exist, and at least one script must be referenced.
- */
-export const findMissingEntryAssets = (
- html: string,
- exists: (relPath: string) => boolean,
-): string[] => {
- const refs = [...html.matchAll(/(?:src|href)="\.?\/([^"]+\.(?:m?js|css))"/g)].map(
- (match) => match[1],
- );
- const missing = refs.filter((ref) => !exists(ref));
- if (!refs.some((ref) => /\.m?js$/.test(ref))) missing.push('<no script referenced>');
- return missing;
-};
diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/pack.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/pack.ts
deleted file mode 100644
index c293da1ba06..00000000000
--- a/apps/desktop/src/main/core/infrastructure/rendererOta/pack.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import { unzip } from 'fflate';
-
-import { type RendererPackMetadata, rendererPackMetadataSchema, sha256File } from './manifest';
-
-const PACK_METADATA_ENTRY = 'meta.json';
-const PACK_CONTENT_ENTRY = /^(?:objects|patches)\/([0-9a-f]{64})$/;
-
-type PackExpectation =
- { kind: 'full'; version: string } | { fromVersion: string; kind: 'delta'; version: string };
-
-const expectedContentEntries = (metadata: RendererPackMetadata): Set<string> => {
- if (metadata.kind === 'full') {
- return new Set(metadata.tree.map((file) => `objects/${file.sha256}`));
- }
- return new Set([
- ...metadata.objects.map((sha256) => `objects/${sha256}`),
- ...metadata.patches.map((patch) => `patches/${patch.patchSha256}`),
- ]);
-};
-
-const matchesExpectation = (metadata: RendererPackMetadata, expected: PackExpectation): boolean =>
- metadata.kind === expected.kind &&
- metadata.version === expected.version &&
- (metadata.kind === 'full' ||
- (expected.kind === 'delta' && metadata.fromVersion === expected.fromVersion));
-
-const unzipPack = (content: Buffer) =>
- new Promise<Record<string, Uint8Array>>((resolve, reject) => {
- unzip(new Uint8Array(content), (error, unpacked) => {
- if (error) reject(error);
- else resolve(unpacked);
- });
- });
-
-export const decodeRendererPack = async (
- content: Buffer,
- expected: PackExpectation,
-): Promise<{ entries: Map<string, Buffer>; metadata: RendererPackMetadata }> => {
- const unpacked = await unzipPack(content);
- const rawMetadata = unpacked[PACK_METADATA_ENTRY];
- if (!rawMetadata) throw new Error('Renderer OTA pack metadata missing');
-
- let parsed: unknown;
- try {
- parsed = JSON.parse(Buffer.from(rawMetadata).toString('utf8'));
- } catch {
- throw new Error('Renderer OTA pack metadata invalid');
- }
- const result = rendererPackMetadataSchema.safeParse(parsed);
- if (!result.success || !matchesExpectation(result.data, expected)) {
- throw new Error('Renderer OTA pack metadata invalid');
- }
-
- const metadata = result.data;
- const expectedEntries = expectedContentEntries(metadata);
- const names = Object.keys(unpacked).filter((name) => name !== PACK_METADATA_ENTRY);
- if (names.length !== expectedEntries.size || names.some((name) => !expectedEntries.has(name))) {
- throw new Error('Renderer OTA pack entries do not match metadata');
- }
-
- const entries = new Map<string, Buffer>();
- for (const name of names) {
- const match = PACK_CONTENT_ENTRY.exec(name);
- const value = Buffer.from(unpacked[name]);
- if (!match || sha256File(value) !== match[1]) {
- throw new Error(`Renderer OTA pack entry invalid: ${name}`);
- }
- entries.set(name, value);
- }
- return { entries, metadata };
-};
diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/pointer.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/pointer.ts
deleted file mode 100644
index c7534568c07..00000000000
--- a/apps/desktop/src/main/core/infrastructure/rendererOta/pointer.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { readFileSync, renameSync, writeFileSync } from 'node:fs';
-import path from 'node:path';
-
-export interface OtaPointer {
- blacklist: string[];
- current: string | null;
- mainHash: string;
- pendingBootCheck: boolean;
- previous: string | null;
- staged: string | null;
-}
-
-export const emptyPointer = (mainHash: string): OtaPointer => ({
- blacklist: [],
- current: null,
- mainHash,
- pendingBootCheck: false,
- previous: null,
- staged: null,
-});
-
-export const readPointer = (otaDir: string, mainHash: string): OtaPointer => {
- try {
- const raw = JSON.parse(readFileSync(path.join(otaDir, 'pointer.json'), 'utf8'));
- if (
- raw?.mainHash === mainHash &&
- Array.isArray(raw.blacklist) &&
- (raw.current === null || typeof raw.current === 'string')
- ) {
- return {
- blacklist: raw.blacklist,
- current: raw.current,
- mainHash: raw.mainHash,
- pendingBootCheck: !!raw.pendingBootCheck,
- previous: typeof raw.previous === 'string' ? raw.previous : null,
- staged: typeof raw.staged === 'string' ? raw.staged : null,
- };
- }
- } catch {
- /* missing or corrupt -> fresh pointer */
- }
- return emptyPointer(mainHash);
-};
-
-export const writePointer = (otaDir: string, pointer: OtaPointer): void => {
- const target = path.join(otaDir, 'pointer.json');
- const tmp = `${target}.tmp`;
- writeFileSync(tmp, JSON.stringify(pointer, null, 2));
- renameSync(tmp, target);
-};
diff --git a/apps/desktop/src/main/core/infrastructure/rendererOta/updatePlan.ts b/apps/desktop/src/main/core/infrastructure/rendererOta/updatePlan.ts
deleted file mode 100644
index 84d63998b37..00000000000
--- a/apps/desktop/src/main/core/infrastructure/rendererOta/updatePlan.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import type { RendererDelta, RendererDeltaPackMetadata, RendererManifest } from './manifest';
-
-export const indexLocalByHash = (localHashes: Map<string, string>): Map<string, string> => {
- const byHash = new Map<string, string>();
- for (const [localPath, hash] of localHashes) {
- if (!byHash.has(hash)) byHash.set(hash, localPath);
- }
- return byHash;
-};
-
-export const pickDelta = (
- manifest: RendererManifest,
- localVersion: string,
-): RendererDelta | undefined =>
- manifest.deltas?.find((delta) => delta.fromVersion === localVersion);
-
-export const canApplyDelta = (
- metadata: RendererDeltaPackMetadata,
- byHash: Map<string, string>,
-): boolean => {
- const objects = new Set(metadata.objects);
- const patches = new Map(metadata.patches.map((patch) => [patch.toSha256, patch]));
-
- return metadata.tree.every((file) => {
- if (byHash.has(file.sha256) || objects.has(file.sha256)) return true;
- const patch = patches.get(file.sha256);
- return !!patch && byHash.has(patch.fromSha256);
- });
-};
diff --git a/apps/desktop/src/main/modules/cliEmbedding/generateCliWrapper.ts b/apps/desktop/src/main/modules/cliEmbedding/generateCliWrapper.ts
index f1eaa4f8200..e5f163b9912 100644
--- a/apps/desktop/src/main/modules/cliEmbedding/generateCliWrapper.ts
+++ b/apps/desktop/src/main/modules/cliEmbedding/generateCliWrapper.ts
@@ -24,7 +24,11 @@ function resolveElectronBinary(): string {
*/
export function resolveCliScript(): string {
if (app.isPackaged) {
- return path.join(process.resourcesPath, 'bin', 'lobe-cli.js');
+ return path.join(
+ globalThis.__SHELL__?.coreDir ?? path.join(process.resourcesPath, 'core'),
+ 'cli',
+ 'lobe-cli.js',
+ );
}
// Dev mode: app.getAppPath() points to apps/desktop/, go up to apps/cli/
return path.join(app.getAppPath(), '..', 'cli', 'dist', 'index.js');
diff --git a/apps/desktop/src/main/pre-app-init.ts b/apps/desktop/src/main/pre-app-init.ts
index 48459157f4c..c4530a2665d 100644
--- a/apps/desktop/src/main/pre-app-init.ts
+++ b/apps/desktop/src/main/pre-app-init.ts
@@ -24,3 +24,5 @@ if (electronIs.dev()) {
userDataOverride || path.join(app.getPath('appData'), 'lobehub-desktop-dev'),
);
}
+
+if (globalThis.__SHELL__) Object.freeze(globalThis.__SHELL__);
diff --git a/apps/desktop/vite.main.config.ts b/apps/desktop/vite.main.config.ts
index 9bb34b1916b..1aed6bdc70a 100644
--- a/apps/desktop/vite.main.config.ts
+++ b/apps/desktop/vite.main.config.ts
@@ -7,7 +7,6 @@ import { viteCompletionSounds } from '../../plugins/vite/completionSounds';
import { viteOsPlatformResolve } from '../../plugins/vite/osPlatformResolve';
import { externalRuntimeModules } from './external-runtime-deps.config.mjs';
import { getNativeExternalDependencies } from './native-deps.config.mjs';
-import { rendererMainHashArtifact, resolveMainHash } from './scripts/mainHash.mjs';
import {
applyDesktopViteConfigExtension,
isCloudDesktopBuild,
@@ -25,7 +24,6 @@ export default defineConfig(async (env) => {
const isDev = mode === 'development';
const updateChannel = process.env.UPDATE_CHANNEL;
const isCloudDesktop = isCloudDesktopBuild();
- const mainHash = await resolveMainHash(mode);
const externalNavigationHosts =
process.env.DESKTOP_EXTERNAL_NAVIGATION_HOSTS ?? (isCloudDesktop ? 'stripe.com' : '');
@@ -58,6 +56,7 @@ export default defineConfig(async (env) => {
],
output: {
assetFileNames: 'chunks/[name]-[hash].[ext]',
+ dynamicImportInCjs: false,
// Rolldown hoists chunk requires above any entry statement, so the V8
// compile cache has to be switched on from a banner to cover `main-app`.
banner: (chunk) =>
@@ -118,7 +117,6 @@ export default defineConfig(async (env) => {
define: {
...processEnvDefine,
'process.env.DESKTOP_EXTERNAL_NAVIGATION_HOSTS': JSON.stringify(externalNavigationHosts),
- 'process.env.MAIN_HASH': JSON.stringify(mainHash),
'process.env.RENDERER_OTA_PUBLIC_KEY': JSON.stringify(process.env.RENDERER_OTA_PUBLIC_KEY),
'process.env.UPDATE_CHANNEL': JSON.stringify(process.env.UPDATE_CHANNEL),
'process.env.UPDATE_SERVER_URL': JSON.stringify(process.env.UPDATE_SERVER_URL),
@@ -126,7 +124,6 @@ export default defineConfig(async (env) => {
plugins: [
viteOsPlatformResolve(),
zodCompiler(),
- rendererMainHashArtifact(mainHash),
viteCompletionSounds({ aiffDir: path.resolve(__dirname, 'resources/sounds') }),
],
publicDir: false,
diff --git a/apps/desktop/vite.preload.config.ts b/apps/desktop/vite.preload.config.ts
index 9006dfce3af..01ba87fe847 100644
--- a/apps/desktop/vite.preload.config.ts
+++ b/apps/desktop/vite.preload.config.ts
@@ -37,6 +37,9 @@ export default defineConfig(async (env) => {
reportCompressedSize: false,
rolldownOptions: {
external: nodeExternals,
+ output: {
+ dynamicImportInCjs: false,
+ },
},
sourcemap: isDev ? 'inline' : false,
ssr: true,
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 0c93f387847..dc5c1d1d0c7 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -132,6 +132,8 @@ export default eslint(
ignores: [
// Generated skill release; maintained in lobehub/acceptance.
'.agents/skills/acceptance/**',
+ // Generated by `bun run shell:vendor` in apps/desktop.
+ 'apps/desktop/shell/rescue/electron-updater.cjs',
// dependencies
'node_modules',
// ci
@@ -603,7 +605,7 @@ export default eslint(
},
// CommonJS files rely on `require()` by design
{
- files: ['**/*.cjs'],
+ files: ['**/*.cjs', 'apps/desktop/shell/**/*.js'],
rules: {
'@typescript-eslint/no-require-imports': 0,
},
diff --git a/packages/electron-client-ipc/src/types/update.ts b/packages/electron-client-ipc/src/types/update.ts
index f321449ecb4..4f139efc37c 100644
--- a/packages/electron-client-ipc/src/types/update.ts
+++ b/packages/electron-client-ipc/src/types/update.ts
@@ -1,5 +1,5 @@
export type UpdateChannel = 'stable' | 'canary';
-export type UpdateKind = 'app' | 'renderer';
+export type UpdateKind = 'app' | 'renderer' | 'core-reload' | 'core-relaunch';
export interface ReleaseNoteInfo {
/**
diff --git a/src/features/Electron/updater/UpdateNotification.tsx b/src/features/Electron/updater/UpdateNotification.tsx
index 61f561e8774..8a2eda04e28 100644
--- a/src/features/Electron/updater/UpdateNotification.tsx
+++ b/src/features/Electron/updater/UpdateNotification.tsx
@@ -9,10 +9,10 @@ import React, { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { autoUpdateService } from '@/services/electron/autoUpdate';
-import { rendererOtaService } from '@/services/electron/rendererOta';
import { useUserStore } from '@/store/user';
import { userGeneralSettingsSelectors } from '@/store/user/selectors';
+import { applyCoreUpdate } from './applyCoreUpdate';
import { selectUpdateInfo } from './selectUpdateInfo';
const styles = createStaticStyles(({ css, cssVar }) => ({
@@ -146,7 +146,7 @@ export const UpdateNotification: React.FC = () => {
useWatchBroadcast('updateReady', (info) => {
setUpdateInfo((current) => selectUpdateInfo(current, info));
- if (info.kind === 'app') setInstallConfirmMode('unconfirm');
+ if (info.kind === 'app' || info.kind === 'core-relaunch') setInstallConfirmMode('unconfirm');
});
useWatchBroadcast('updateWillInstallLater', () => {
@@ -155,7 +155,15 @@ export const UpdateNotification: React.FC = () => {
setTimeout(() => setInstallConfirmMode(null), 5000);
});
- if (updateInfo?.kind === 'renderer') {
+ const applyCoreUpdateNow = async (keepLoadingOnSuccess: boolean) => {
+ setIsInstalling(true);
+ const applied = await applyCoreUpdate(() =>
+ toast.error(tElectron('updater.rendererUpdateError')),
+ );
+ if (!applied || !keepLoadingOnSuccess) setIsInstalling(false);
+ };
+
+ if (updateInfo?.kind === 'renderer' || updateInfo?.kind === 'core-reload') {
return (
<div className={styles.installLaterToast}>
<span>{tElectron('updater.rendererReady', { version: updateInfo.version })}</span>
@@ -166,19 +174,29 @@ export const UpdateNotification: React.FC = () => {
loading={isInstalling}
size={'small'}
type={'primary'}
- onClick={async () => {
- setIsInstalling(true);
- try {
- if (!(await rendererOtaService.applyNow())) {
- toast.error(tElectron('updater.rendererUpdateError'));
- }
- } catch (error) {
- console.error('Failed to apply renderer update:', error);
- toast.error(tElectron('updater.rendererUpdateError'));
- } finally {
- setIsInstalling(false);
- }
- }}
+ onClick={() => applyCoreUpdateNow(false)}
+ >
+ {tElectron('updater.upgradeNow')}
+ </BaseButton>
+ </div>
+ );
+ }
+
+ if (updateInfo?.kind === 'core-relaunch') {
+ return (
+ <div className={styles.installLaterToast}>
+ <span>
+ {tElectron('updater.updateReady')}
+ {isDevMode ? ` · ${updateInfo.version}` : ''}
+ </span>
+ <BaseButton size={'small'} type={'text'} onClick={() => setUpdateInfo(null)}>
+ {tElectron('updater.later')}
+ </BaseButton>
+ <BaseButton
+ loading={isInstalling}
+ size={'small'}
+ type={'primary'}
+ onClick={() => applyCoreUpdateNow(true)}
>
{tElectron('updater.upgradeNow')}
</BaseButton>
@@ -207,22 +225,11 @@ export const UpdateNotification: React.FC = () => {
if (installConfirmMode === 'unconfirm')
return (
<div className={styles.installLaterToast}>
- <span
- style={{ cursor: 'pointer' }}
- onClick={() => {
- if (updateInfo) openUpdateDetailModal(updateInfo);
- }}
- >
+ <span style={{ cursor: 'pointer' }} onClick={() => openUpdateDetailModal(updateInfo)}>
{tElectron('updater.updateReady')}
{isDevMode && updateInfo?.version ? ` · ${updateInfo.version}` : ''}
</span>
- <BaseButton
- size={'small'}
- type={'text'}
- onClick={() => {
- autoUpdateService.installLater();
- }}
- >
+ <BaseButton size={'small'} type={'text'} onClick={() => autoUpdateService.installLater()}>
{tElectron('updater.later')}
</BaseButton>
<BaseButton
diff --git a/src/features/Electron/updater/applyCoreUpdate.test.ts b/src/features/Electron/updater/applyCoreUpdate.test.ts
new file mode 100644
index 00000000000..f8d5857e22e
--- /dev/null
+++ b/src/features/Electron/updater/applyCoreUpdate.test.ts
@@ -0,0 +1,40 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { applyCoreUpdate } from './applyCoreUpdate';
+
+const applyNowMock = vi.hoisted(() => vi.fn());
+
+vi.mock('@/services/electron/rendererOta', () => ({
+ rendererOtaService: { applyNow: applyNowMock },
+}));
+
+describe('applyCoreUpdate', () => {
+ beforeEach(() => {
+ applyNowMock.mockReset();
+ });
+
+ it('reports failure when the main process refuses to apply', async () => {
+ applyNowMock.mockResolvedValue(false);
+ const onFailure = vi.fn();
+
+ await expect(applyCoreUpdate(onFailure)).resolves.toBe(false);
+ expect(onFailure).toHaveBeenCalledOnce();
+ });
+
+ it('reports failure when the apply call throws', async () => {
+ applyNowMock.mockRejectedValue(new Error('ipc down'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const onFailure = vi.fn();
+
+ await expect(applyCoreUpdate(onFailure)).resolves.toBe(false);
+ expect(onFailure).toHaveBeenCalledOnce();
+ });
+
+ it('stays silent when the update is applied', async () => {
+ applyNowMock.mockResolvedValue(true);
+ const onFailure = vi.fn();
+
+ await expect(applyCoreUpdate(onFailure)).resolves.toBe(true);
+ expect(onFailure).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Electron/updater/applyCoreUpdate.ts b/src/features/Electron/updater/applyCoreUpdate.ts
new file mode 100644
index 00000000000..be3ae24fd6c
--- /dev/null
+++ b/src/features/Electron/updater/applyCoreUpdate.ts
@@ -0,0 +1,11 @@
+import { rendererOtaService } from '@/services/electron/rendererOta';
+
+export const applyCoreUpdate = async (onFailure: () => void) => {
+ try {
+ if (await rendererOtaService.applyNow()) return true;
+ } catch (error) {
+ console.error('Failed to apply core update:', error);
+ }
+ onFailure();
+ return false;
+};
diff --git a/src/features/Electron/updater/selectUpdateInfo.ts b/src/features/Electron/updater/selectUpdateInfo.ts
index bd7ebd272db..ce46ff485bc 100644
--- a/src/features/Electron/updater/selectUpdateInfo.ts
+++ b/src/features/Electron/updater/selectUpdateInfo.ts
@@ -1,4 +1,4 @@
import type { UpdateInfo } from '@lobechat/electron-client-ipc';
export const selectUpdateInfo = (current: UpdateInfo | null, incoming: UpdateInfo): UpdateInfo =>
- current?.kind === 'app' && incoming.kind === 'renderer' ? current : incoming;
+ current?.kind === 'app' && incoming.kind !== 'app' ? current : incoming;