mirror of
https://github.com/expo/eas-cli.git
synced 2026-11-14 10:08:06 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5484dd6074 | ||
|
|
8fd3fe0a3a | ||
|
|
ce93a92dc8 | ||
|
|
3f4ed25bb9 | ||
|
|
02b54ac216 | ||
|
|
4b44fecc69 | ||
|
|
1c082665e8 | ||
|
|
7cec953e9a | ||
|
|
868178fb37 | ||
|
|
8439f4fbc9 | ||
|
|
78644d299f | ||
|
|
0d0134dae5 | ||
|
|
b03d31561c | ||
|
|
0e85408741 | ||
|
|
4107b7e611 | ||
|
|
6cbddf5b8e | ||
|
|
a3f4136ac8 | ||
|
|
6926209e53 | ||
|
|
efc97f3bdb | ||
|
|
f72cff08a1 | ||
|
|
7b98b074f4 | ||
|
|
40b02895f7 | ||
|
|
1f4c1edd99 | ||
|
|
2f320aea43 | ||
|
|
f41696701e | ||
|
|
a9d693d867 | ||
|
|
b92a9cc5a7 | ||
|
|
763cbadaaa | ||
|
|
3cc58e500f | ||
|
|
2a7cb5e1fe | ||
|
|
289d579869 | ||
|
|
067c0e578f | ||
|
|
520c63fd3e | ||
|
|
221e01568c | ||
|
|
b8cff20089 | ||
|
|
c99ec44b92 | ||
|
|
90501af961 | ||
|
|
4c317292d2 | ||
|
|
16cf32ae73 | ||
|
|
1ec9e83c3b | ||
|
|
3b1b96e71f | ||
|
|
2f081de936 | ||
|
|
954534df42 |
No files matched your search
@@ -1,12 +1,13 @@
|
||||
name: notify-slack-on-fail-or-recover
|
||||
description: Notify a Slack channel when a workflow fails, or when it recovers after a previous failure.
|
||||
|
||||
inputs:
|
||||
channel:
|
||||
description: Slack channel to send the notification to.
|
||||
required: true
|
||||
type: string
|
||||
slack_webhook:
|
||||
description: Slack incoming webhook URL used to post the notification.
|
||||
required: true
|
||||
type: string
|
||||
|
||||
runs:
|
||||
using: 'composite'
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
name: setup-gcloud
|
||||
description: Authenticate to Google Cloud via workload identity federation and set up the gcloud CLI.
|
||||
|
||||
runs:
|
||||
using: "composite"
|
||||
|
||||
@@ -27,6 +27,9 @@ jobs:
|
||||
|
||||
- uses: ./.github/actions/setup-mise
|
||||
|
||||
- name: Install eas-cli
|
||||
run: npm install --global eas-cli@latest
|
||||
|
||||
- uses: ./.github/internal-actions/setup-gcloud
|
||||
|
||||
- name: Check if worker already exists
|
||||
@@ -38,7 +41,7 @@ jobs:
|
||||
for platform in android ios; do
|
||||
GCP_TARBALL="worker-$platform-sha1-$GITHUB_SHA.tar.gz"
|
||||
|
||||
if ! gsutil stat gs://eas-build-worker-tarballs/$GCP_TARBALL; then
|
||||
if ! gsutil stat "gs://eas-build-worker-tarballs/$GCP_TARBALL"; then
|
||||
echo "worker_exists=false" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
@@ -61,7 +64,7 @@ jobs:
|
||||
SHOULD_UPLOAD_ARTIFACT="${{ inputs.environment != '' && steps.check_worker_exists.outputs.worker_exists == 'false' }}"
|
||||
|
||||
# Run workflow and capture output (includes run ID)
|
||||
WORKFLOW_OUTPUT=$(npx -y eas-cli@latest workflow:run build-worker.yml \
|
||||
WORKFLOW_OUTPUT=$(eas workflow:run build-worker.yml \
|
||||
--ref ${{ github.sha }} \
|
||||
--input upload_artifact=$SHOULD_UPLOAD_ARTIFACT \
|
||||
--non-interactive \
|
||||
@@ -96,7 +99,7 @@ jobs:
|
||||
SHOULD_UPLOAD_ARTIFACT="${{ inputs.environment != '' && steps.check_worker_exists.outputs.worker_exists == 'false' }}"
|
||||
|
||||
while true; do
|
||||
VIEW_OUTPUT=$(npx -y eas-cli@latest workflow:view "$WORKFLOW_RUN_ID" \
|
||||
VIEW_OUTPUT=$(eas workflow:view "$WORKFLOW_RUN_ID" \
|
||||
--non-interactive \
|
||||
--json)
|
||||
STATUS=$(echo "$VIEW_OUTPUT" | jq -r '.status')
|
||||
@@ -181,7 +184,7 @@ jobs:
|
||||
|
||||
WORKFLOW_RUN_ID="${{ steps.eas_workflow.outputs.workflow_run_id }}"
|
||||
if [ -n "$WORKFLOW_RUN_ID" ]; then
|
||||
npx -y eas-cli@latest workflow:cancel "$WORKFLOW_RUN_ID" --non-interactive
|
||||
eas workflow:cancel "$WORKFLOW_RUN_ID" --non-interactive
|
||||
fi
|
||||
|
||||
- name: Upload worker tarballs to GCP
|
||||
@@ -191,8 +194,8 @@ jobs:
|
||||
run: |
|
||||
IOS_GCP_TARBALL="worker-ios-sha1-$GITHUB_SHA.tar.gz"
|
||||
ANDROID_GCP_TARBALL="worker-android-sha1-$GITHUB_SHA.tar.gz"
|
||||
curl -L "${{ steps.eas_artifacts.outputs.download_ios_url }}" | gsutil cp - gs://eas-build-worker-tarballs/$IOS_GCP_TARBALL
|
||||
curl -L "${{ steps.eas_artifacts.outputs.download_android_url }}" | gsutil cp - gs://eas-build-worker-tarballs/$ANDROID_GCP_TARBALL
|
||||
curl -L "${{ steps.eas_artifacts.outputs.download_ios_url }}" | gsutil cp - "gs://eas-build-worker-tarballs/$IOS_GCP_TARBALL"
|
||||
curl -L "${{ steps.eas_artifacts.outputs.download_android_url }}" | gsutil cp - "gs://eas-build-worker-tarballs/$ANDROID_GCP_TARBALL"
|
||||
|
||||
- name: Promote worker to ${{ inputs.environment }}
|
||||
if: inputs.environment != ''
|
||||
@@ -201,5 +204,5 @@ jobs:
|
||||
GCP_TARBALL="worker-$platform-sha1-$GITHUB_SHA.tar.gz"
|
||||
WORKER_STAGING_TARBALL="worker-$platform-${{ inputs.environment }}.tar.gz"
|
||||
|
||||
gsutil cp gs://eas-build-worker-tarballs/$GCP_TARBALL gs://eas-build-worker-tarballs/$WORKER_STAGING_TARBALL
|
||||
gsutil cp "gs://eas-build-worker-tarballs/$GCP_TARBALL" "gs://eas-build-worker-tarballs/$WORKER_STAGING_TARBALL"
|
||||
done
|
||||
@@ -60,9 +60,11 @@ jobs:
|
||||
elif [ "$rest" != "all" ]; then
|
||||
agents=$(printf '%s' "$rest" | tr ' ' ',' | tr -cd 'a-zA-Z0-9,_-')
|
||||
fi
|
||||
echo "run=true" >> "$GITHUB_OUTPUT"
|
||||
echo "agents=$agents" >> "$GITHUB_OUTPUT"
|
||||
echo "route=$route" >> "$GITHUB_OUTPUT"
|
||||
{
|
||||
echo "run=true"
|
||||
echo "agents=$agents"
|
||||
echo "route=$route"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Acknowledge
|
||||
if: steps.cmd.outputs.run == 'true'
|
||||
@@ -137,10 +139,10 @@ jobs:
|
||||
AGENTS: ${{ steps.cmd.outputs.agents }}
|
||||
ROUTE: ${{ steps.cmd.outputs.route }}
|
||||
run: |
|
||||
ARGS=""
|
||||
ARGS=()
|
||||
if [ -n "$AGENTS" ]; then
|
||||
ARGS="--agents $AGENTS"
|
||||
ARGS=(--agents "$AGENTS")
|
||||
elif [ "$ROUTE" = "true" ]; then
|
||||
ARGS="--route"
|
||||
ARGS=(--route)
|
||||
fi
|
||||
npx --yes -p "@expo/code-review-cli@$ECR_VERSION" ecr ci $ARGS
|
||||
npx --yes -p "@expo/code-review-cli@$ECR_VERSION" ecr ci "${ARGS[@]}"
|
||||
@@ -61,10 +61,12 @@ jobs:
|
||||
if [ -z "$(printf '%s' "$ids" | tr -d ' ')" ]; then
|
||||
echo "run=false" >> "$GITHUB_OUTPUT"; exit 0
|
||||
fi
|
||||
echo "run=true" >> "$GITHUB_OUTPUT"
|
||||
echo "sub=$sub" >> "$GITHUB_OUTPUT"
|
||||
echo "ids=$ids" >> "$GITHUB_OUTPUT"
|
||||
echo "reason=$reason" >> "$GITHUB_OUTPUT"
|
||||
{
|
||||
echo "run=true"
|
||||
echo "sub=$sub"
|
||||
echo "ids=$ids"
|
||||
echo "reason=$reason"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Acknowledge
|
||||
if: steps.cmd.outputs.run == 'true'
|
||||
|
||||
@@ -74,9 +74,11 @@ jobs:
|
||||
else
|
||||
route=true # bare `ai-review` => let the router pick
|
||||
fi
|
||||
echo "run=true" >> "$GITHUB_OUTPUT"
|
||||
echo "agents=$agents" >> "$GITHUB_OUTPUT"
|
||||
echo "route=$route" >> "$GITHUB_OUTPUT"
|
||||
{
|
||||
echo "run=true"
|
||||
echo "agents=$agents"
|
||||
echo "route=$route"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
# SECURITY: check out the PR's immutable BASE commit, never the PR head or
|
||||
# merge ref — everything on this runner's disk comes from a commit that
|
||||
@@ -172,13 +174,13 @@ jobs:
|
||||
AGENTS: ${{ steps.resolve.outputs.agents }}
|
||||
ROUTE: ${{ steps.resolve.outputs.route }}
|
||||
run: |
|
||||
ARGS=""
|
||||
ARGS=()
|
||||
if [ -n "$AGENTS" ]; then
|
||||
ARGS="--agents $AGENTS"
|
||||
ARGS=(--agents "$AGENTS")
|
||||
elif [ "$ROUTE" = "true" ]; then
|
||||
ARGS="--route"
|
||||
ARGS=(--route)
|
||||
fi
|
||||
npx --yes -p "@expo/code-review-cli@$ECR_VERSION" ecr ci $ARGS
|
||||
npx --yes -p "@expo/code-review-cli@$ECR_VERSION" ecr ci "${ARGS[@]}"
|
||||
|
||||
# Persist the run log (decision, per-agent cost, duration, token/cache
|
||||
# metrics) so cost/latency/cache reuse are observable over time — CI is
|
||||
|
||||
@@ -5,7 +5,7 @@ on:
|
||||
|
||||
jobs:
|
||||
needs-repro:
|
||||
runs-on: ubuntu-20.04
|
||||
runs-on: ubuntu-latest
|
||||
if: "${{ contains(github.event.label.name, 'incomplete issue: missing or invalid repro') }}"
|
||||
steps:
|
||||
- uses: actions/github-script@ffc2c79a5b2490bd33e0a41c1de74b877714d736 # v3
|
||||
@@ -49,7 +49,7 @@ jobs:
|
||||
})
|
||||
|
||||
needs-info:
|
||||
runs-on: ubuntu-20.04
|
||||
runs-on: ubuntu-latest
|
||||
if: "${{ contains(github.event.label.name, 'incomplete issue: missing info') }}"
|
||||
steps:
|
||||
- uses: actions/github-script@ffc2c79a5b2490bd33e0a41c1de74b877714d736 # v3
|
||||
@@ -78,7 +78,7 @@ jobs:
|
||||
})
|
||||
|
||||
issue-accepted:
|
||||
runs-on: ubuntu-20.04
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event.label.name == 'issue accepted'
|
||||
steps:
|
||||
- uses: actions/github-script@ffc2c79a5b2490bd33e0a41c1de74b877714d736 # v3
|
||||
@@ -95,7 +95,7 @@ jobs:
|
||||
`})
|
||||
|
||||
question:
|
||||
runs-on: ubuntu-20.04
|
||||
runs-on: ubuntu-latest
|
||||
if: "${{ contains(github.event.label.name, 'invalid issue: question') }}"
|
||||
steps:
|
||||
- uses: actions/github-script@ffc2c79a5b2490bd33e0a41c1de74b877714d736 # v3
|
||||
@@ -123,7 +123,7 @@ jobs:
|
||||
})
|
||||
|
||||
feature-request:
|
||||
runs-on: ubuntu-20.04
|
||||
runs-on: ubuntu-latest
|
||||
if: "${{ contains(github.event.label.name, 'invalid issue: feature request') }}"
|
||||
steps:
|
||||
- uses: actions/github-script@ffc2c79a5b2490bd33e0a41c1de74b877714d736 # v3
|
||||
|
||||
@@ -66,12 +66,12 @@ jobs:
|
||||
working-directory: ./scripts
|
||||
run: yarn install --immutable
|
||||
- name: Resolve version
|
||||
run: echo "EAS_CLI_VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_ENV
|
||||
run: echo "EAS_CLI_VERSION=${GITHUB_REF#refs/tags/v}" >> "$GITHUB_ENV"
|
||||
- name: Update changelog
|
||||
working-directory: ./scripts
|
||||
run: yarn release-changelog $EAS_CLI_VERSION > /tmp/current-changelog
|
||||
run: yarn release-changelog "$EAS_CLI_VERSION" > /tmp/current-changelog
|
||||
- name: Publish release
|
||||
run: gh release edit v$EAS_CLI_VERSION --draft=false -F /tmp/current-changelog
|
||||
run: gh release edit "v$EAS_CLI_VERSION" --draft=false -F /tmp/current-changelog
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Commit and push
|
||||
@@ -90,9 +90,11 @@ jobs:
|
||||
run: |
|
||||
tail -n +3 /tmp/current-changelog > /tmp/changelog.md
|
||||
npx slackmd /tmp/changelog.md
|
||||
echo 'SLACK_CHANGELOG<<EOF' >> $GITHUB_ENV
|
||||
cat /tmp/changelog.slack.md >> $GITHUB_ENV
|
||||
echo 'EOF' >> $GITHUB_ENV
|
||||
{
|
||||
echo 'SLACK_CHANGELOG<<EOF'
|
||||
cat /tmp/changelog.slack.md
|
||||
echo 'EOF'
|
||||
} >> "$GITHUB_ENV"
|
||||
- name: Slack Notification
|
||||
uses: rtCamp/action-slack-notify@e31e87e03dd19038e411e38ae27cbad084a90661 # v2
|
||||
env:
|
||||
|
||||
@@ -60,6 +60,7 @@ jobs:
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
- run: yarn lint
|
||||
- run: yarn fmt:check
|
||||
- run: yarn actionlint
|
||||
- name: Install scripts dependencies
|
||||
if: ${{ matrix.coverage }}
|
||||
run: yarn install --immutable
|
||||
|
||||
@@ -42,5 +42,5 @@ jobs:
|
||||
yarn release
|
||||
else
|
||||
echo "Releasing with version $INPUT_VERSION"
|
||||
yarn release $INPUT_VERSION
|
||||
yarn release "$INPUT_VERSION"
|
||||
fi
|
||||
@@ -15,12 +15,15 @@ jobs:
|
||||
|
||||
- uses: ./.github/actions/setup-mise
|
||||
|
||||
- name: Install eas-cli
|
||||
run: npm install --global eas-cli@latest
|
||||
|
||||
- name: Create test app
|
||||
run: npx -y create-expo-app@latest ${{ runner.temp }}/test-app --template tabs
|
||||
|
||||
- name: Link to EAS project
|
||||
working-directory: ${{ runner.temp }}/test-app
|
||||
run: npx -y eas-cli@latest init --id 6ae8028d-4e6d-4912-8eb2-87d4e6122880 --force --non-interactive
|
||||
run: eas init --id 6ae8028d-4e6d-4912-8eb2-87d4e6122880 --force --non-interactive
|
||||
|
||||
- name: Add bundle identifiers to app.json
|
||||
working-directory: ${{ runner.temp }}/test-app
|
||||
@@ -30,7 +33,7 @@ jobs:
|
||||
|
||||
- name: Configure EAS Build
|
||||
working-directory: ${{ runner.temp }}/test-app
|
||||
run: npx -y eas-cli@latest build:configure --platform all
|
||||
run: eas build:configure --platform all
|
||||
|
||||
- name: Add system-test profile to eas.json
|
||||
working-directory: ${{ runner.temp }}/test-app
|
||||
@@ -49,7 +52,7 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
BUILD_JSON=$(npx -y eas-cli@latest build --platform ios --profile system-test --non-interactive --no-wait --json)
|
||||
BUILD_JSON=$(eas build --platform ios --profile system-test --non-interactive --no-wait --json)
|
||||
BUILD_ID=$(echo "$BUILD_JSON" | jq -r 'if type=="array" then .[0].id // .[0].build.id // .[0].buildId else .id // .build.id // .buildId end // empty')
|
||||
if [ -z "$BUILD_ID" ]; then
|
||||
echo "Error: could not determine build ID"
|
||||
@@ -59,7 +62,7 @@ jobs:
|
||||
echo "BUILD_ID=$BUILD_ID" >> "$GITHUB_ENV"
|
||||
echo "Resolved BUILD_ID=$BUILD_ID"
|
||||
|
||||
WORKFLOW_JSON=$(npx -y eas-cli@latest workflow:run build-android.yml --non-interactive --no-wait --json)
|
||||
WORKFLOW_JSON=$(eas workflow:run build-android.yml --non-interactive --no-wait --json)
|
||||
WORKFLOW_RUN_ID=$(echo "$WORKFLOW_JSON" | jq -r '.id // .workflowRun.id // .workflowRunId // empty')
|
||||
if [ -z "$WORKFLOW_RUN_ID" ]; then
|
||||
echo "Error: could not determine workflow run ID"
|
||||
@@ -95,8 +98,8 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
BUILD_STATUS=$(npx -y eas-cli@latest build:view "$BUILD_ID" --json | jq -r '.status // empty')
|
||||
WORKFLOW_STATUS=$(npx -y eas-cli@latest workflow:view "$WORKFLOW_RUN_ID" --non-interactive --json | jq -r '.status // empty')
|
||||
BUILD_STATUS=$(eas build:view "$BUILD_ID" --json | jq -r '.status // empty')
|
||||
WORKFLOW_STATUS=$(eas workflow:view "$WORKFLOW_RUN_ID" --non-interactive --json | jq -r '.status // empty')
|
||||
|
||||
echo "iOS build status: $BUILD_STATUS"
|
||||
echo "Android workflow status: $WORKFLOW_STATUS"
|
||||
@@ -130,13 +133,13 @@ jobs:
|
||||
|
||||
if [ -n "${BUILD_ID:-}" ]; then
|
||||
echo "Canceling EAS build: $BUILD_ID"
|
||||
BUILD_CANCEL_OUTPUT=$(npx -y eas-cli@latest build:cancel "$BUILD_ID" --non-interactive 2>&1 || true)
|
||||
BUILD_CANCEL_OUTPUT=$(eas build:cancel "$BUILD_ID" --non-interactive 2>&1 || true)
|
||||
if [ -n "$BUILD_CANCEL_OUTPUT" ]; then
|
||||
echo "$BUILD_CANCEL_OUTPUT"
|
||||
else
|
||||
echo "build:cancel produced no output"
|
||||
fi
|
||||
BUILD_STATUS=$(npx -y eas-cli@latest build:view "$BUILD_ID" --json 2>/dev/null | jq -r '.status // empty' || true)
|
||||
BUILD_STATUS=$(eas build:view "$BUILD_ID" --json 2>/dev/null | jq -r '.status // empty' || true)
|
||||
if [ -n "$BUILD_STATUS" ]; then
|
||||
echo "Post-cancel build status: $BUILD_STATUS"
|
||||
else
|
||||
@@ -145,13 +148,13 @@ jobs:
|
||||
fi
|
||||
if [ -n "${WORKFLOW_RUN_ID:-}" ]; then
|
||||
echo "Canceling EAS workflow run: $WORKFLOW_RUN_ID"
|
||||
WORKFLOW_CANCEL_OUTPUT=$(npx -y eas-cli@latest workflow:cancel "$WORKFLOW_RUN_ID" --non-interactive 2>&1 || true)
|
||||
WORKFLOW_CANCEL_OUTPUT=$(eas workflow:cancel "$WORKFLOW_RUN_ID" --non-interactive 2>&1 || true)
|
||||
if [ -n "$WORKFLOW_CANCEL_OUTPUT" ]; then
|
||||
echo "$WORKFLOW_CANCEL_OUTPUT"
|
||||
else
|
||||
echo "workflow:cancel produced no output"
|
||||
fi
|
||||
WORKFLOW_STATUS=$(npx -y eas-cli@latest workflow:view "$WORKFLOW_RUN_ID" --non-interactive --json 2>/dev/null | jq -r '.status // empty' || true)
|
||||
WORKFLOW_STATUS=$(eas workflow:view "$WORKFLOW_RUN_ID" --non-interactive --json 2>/dev/null | jq -r '.status // empty' || true)
|
||||
if [ -n "$WORKFLOW_STATUS" ]; then
|
||||
echo "Post-cancel workflow status: $WORKFLOW_STATUS"
|
||||
else
|
||||
|
||||
@@ -8,10 +8,49 @@ This is the log of notable changes to EAS CLI and related packages.
|
||||
|
||||
### 🎉 New features
|
||||
|
||||
- [eas-cli] Add `--device` flag to `eas simulator` for selecting the virtual device to start. ([#4172](https://github.com/expo/eas-cli/pull/4172) by [@szdziedzic](https://github.com/szdziedzic))
|
||||
- [eas-cli] Add support for Appium EAS Simulator sessions. ([#4190](https://github.com/expo/eas-cli/pull/4190) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
|
||||
### 🐛 Bug fixes
|
||||
|
||||
- [eas-cli] Disallow 0-length uploads. ([#4192](https://github.com/expo/eas-cli/pull/4192) by [@wschurman](https://github.com/wschurman))
|
||||
- [eas-cli] Send the expected `Content-MD5` checksum with GCS signed URL uploads so GCS rejects corrupted uploads. ([#4208](https://github.com/expo/eas-cli/pull/4208) by [@wschurman](https://github.com/wschurman))
|
||||
- [eas-cli] Resolve the `eas go` SDK version to its repack target, so `--sdk-version 57` no longer fails with "No Expo Go repack target is published for SDK 57". ([#4215](https://github.com/expo/eas-cli/pull/4215) by [@gwdp](https://github.com/gwdp))
|
||||
- [eas-cli] Handle missing fingerprint source in fingerprint:compare command. ([#4210](https://github.com/expo/eas-cli/pull/4210) by [@wschurman](https://github.com/wschurman))
|
||||
|
||||
### 🧹 Chores
|
||||
|
||||
- [eas-cli] Fix lint and enforce max-warnings=0. ([#4219](https://github.com/expo/eas-cli/pull/4219) by [@wschurman](https://github.com/wschurman))
|
||||
- [build-tools] Rename serve-sim ngrok preview URLs to use the `web-preview` prefix. ([#4231](https://github.com/expo/eas-cli/pull/4231) by [@szdziedzic](https://github.com/szdziedzic))
|
||||
|
||||
## [22.0.0](https://github.com/expo/eas-cli/releases/tag/v22.0.0) - 2026-08-14
|
||||
|
||||
### 🛠 Breaking changes
|
||||
|
||||
- [eas-cli] Build objects in `--json` output (`eas build`, `eas build:list`, `eas build:view`, `eas build:resign`) now have `app`, `updateChannel` (object with `id` and `name`), and `runtime` (object with `id` and `version`) instead of `project`, `channel`, and `runtimeVersion`. `eas update:republish --json` output likewise has `runtime` instead of `runtimeVersion`. Other update commands' `--json` output and `eas-update-metadata.json` are unchanged. ([#4021](https://github.com/expo/eas-cli/pull/4021) by [@tchayen](https://github.com/tchayen))
|
||||
|
||||
### 🎉 New features
|
||||
|
||||
- [build-tools] Upload JavaScript source maps generated by builds. ([#4170](https://github.com/expo/eas-cli/pull/4170) by [@AbbanMustafa](https://github.com/AbbanMustafa))
|
||||
- [eas-cli] Set the project icon on the EAS dashboard from the app config when running `eas init`, if the project does not have one yet. ([#4177](https://github.com/expo/eas-cli/pull/4177) by [@tchayen](https://github.com/tchayen))
|
||||
|
||||
### 🐛 Bug fixes
|
||||
|
||||
- [eas-cli] Report EAS Simulator as available to Expo admins in `eas simulator:availability`, even when the project account's feature gate is disabled. ([#4181](https://github.com/expo/eas-cli/pull/4181) by [@szdziedzic](https://github.com/szdziedzic))
|
||||
- [eas-cli] Make the non-interactive "EAS project not configured" error actionable on every path: list the exact `eas init --id` / `eas init --account` commands and the accounts you can create projects in, instead of suggesting bare `eas init`, which fails the same way. ([#4153](https://github.com/expo/eas-cli/pull/4153) by [@williamgrosset](https://github.com/williamgrosset))
|
||||
- [eas-cli] Set up the internal TestFlight group and invite admin testers when submitting interactively with an existing `ascAppId`, with `--no-auto-testflight-setup` to disable it, and fix the TestFlight group URL printed when adding testers partially fails. ([#4136](https://github.com/expo/eas-cli/pull/4136) by [@tchayen](https://github.com/tchayen))
|
||||
|
||||
## [21.8.0](https://github.com/expo/eas-cli/releases/tag/v21.8.0) - 2026-08-11
|
||||
|
||||
### 🎉 New features
|
||||
|
||||
- [eas-cli] Add Supabase integration foundation: GraphQL client, shared integration helpers, and provisioning utilities. ([#4130](https://github.com/expo/eas-cli/pull/4130) by [@gwdp](https://github.com/gwdp))
|
||||
- [eas-cli] Add `eas integrations:supabase:connect` command. ([#4106](https://github.com/expo/eas-cli/pull/4106) by [@gwdp](https://github.com/gwdp))
|
||||
- [eas-cli] Add `eas integrations:supabase:dashboard` command. ([#4107](https://github.com/expo/eas-cli/pull/4107) by [@gwdp](https://github.com/gwdp))
|
||||
- [eas-cli] Add `eas integrations:supabase:disconnect` command. ([#4108](https://github.com/expo/eas-cli/pull/4108) by [@gwdp](https://github.com/gwdp))
|
||||
|
||||
## [21.7.1](https://github.com/expo/eas-cli/releases/tag/v21.7.1) - 2026-08-10
|
||||
|
||||
## [21.7.0](https://github.com/expo/eas-cli/releases/tag/v21.7.0) - 2026-08-07
|
||||
|
||||
### 🎉 New features
|
||||
@@ -62,6 +101,7 @@ This is the log of notable changes to EAS CLI and related packages.
|
||||
|
||||
### 🐛 Bug fixes
|
||||
|
||||
- [build-tools] Soft-stop EAS Simulator sessions before the backing job times out so cleanup can finish. ([#4117](https://github.com/expo/eas-cli/pull/4117) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
- [eas-cli] clean up error handling in local builds. ([#4105](https://github.com/expo/eas-cli/pull/4105) by [@douglowder](https://github.com/douglowder))
|
||||
- [build-tools] Install ffmpeg when it is missing so Argent screen recording works in EAS Simulator sessions. ([#4110](https://github.com/expo/eas-cli/pull/4110) by [@szdziedzic](https://github.com/szdziedzic))
|
||||
- [eas-cli] Stop simulator job runs when `eas simulator:start` is canceled before the session is ready. ([#4113](https://github.com/expo/eas-cli/pull/4113) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
{
|
||||
"STAGING": "21.7.0",
|
||||
"STAGING": "22.0.0",
|
||||
"PRODUCTION": "21.5.0"
|
||||
}
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"npmClient": "yarn",
|
||||
"version": "21.7.1",
|
||||
"version": "22.2.0",
|
||||
"$schema": "node_modules/lerna/schemas/lerna-schema.json"
|
||||
}
|
||||
@@ -3,6 +3,7 @@ _.path = "./tools/bin"
|
||||
MISE_NODE_COREPACK = "true"
|
||||
|
||||
[tools]
|
||||
actionlint = "1.7.12"
|
||||
gcloud = "570.0.0"
|
||||
jq = "1.8.1"
|
||||
node = "20.19.4"
|
||||
+2
-1
@@ -11,7 +11,8 @@
|
||||
"start-allow-unused": "lerna run watch-allow-unused --stream --parallel",
|
||||
"watch": "yarn start",
|
||||
"eas": "packages/eas-cli/bin/run",
|
||||
"lint": "oxlint --type-aware --import-plugin --tsconfig ./tsconfig.oxlint.json .",
|
||||
"actionlint": "actionlint",
|
||||
"lint": "oxlint --type-aware --import-plugin --max-warnings=0 --tsconfig ./tsconfig.oxlint.json .",
|
||||
"fmt": "oxfmt .",
|
||||
"fmt:check": "oxfmt --check .",
|
||||
"lint-changelog": "./scripts/bin/run lint-changelog",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/build-tools",
|
||||
"version": "21.7.1",
|
||||
"version": "22.2.0",
|
||||
"bugs": "https://github.com/expo/eas-cli/issues",
|
||||
"license": "BUSL-1.1",
|
||||
"author": "Expo <[email protected]>",
|
||||
@@ -38,17 +38,17 @@
|
||||
"dependencies": {
|
||||
"@expo/config": "55.0.10",
|
||||
"@expo/config-plugins": "55.0.7",
|
||||
"@expo/downloader": "21.0.0",
|
||||
"@expo/eas-build-job": "21.6.0",
|
||||
"@expo/downloader": "22.0.0",
|
||||
"@expo/eas-build-job": "22.0.0",
|
||||
"@expo/env": "^0.4.0",
|
||||
"@expo/logger": "21.0.0",
|
||||
"@expo/logger": "22.0.0",
|
||||
"@expo/package-manager": "1.9.10",
|
||||
"@expo/plist": "^0.3.5",
|
||||
"@expo/results": "^1.0.0",
|
||||
"@expo/spawn-async": "1.7.2",
|
||||
"@expo/steps": "21.7.1",
|
||||
"@expo/template-file": "21.0.2",
|
||||
"@expo/turtle-spawn": "21.0.0",
|
||||
"@expo/steps": "22.1.0",
|
||||
"@expo/template-file": "22.0.0",
|
||||
"@expo/turtle-spawn": "22.0.0",
|
||||
"@expo/xcpretty": "^4.3.1",
|
||||
"@ngrok/ngrok": "1.7.0",
|
||||
"@sentry/node": "7.77.0",
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Artifacts, BuildContext } from '../context';
|
||||
import { findAndUploadXcodeBuildLogsAsync } from '../ios/xcodeBuildLogs';
|
||||
import { maybeFindAndUploadBuildArtifacts } from '../utils/artifacts';
|
||||
import { Hook, runHookIfPresent } from '../utils/hooks';
|
||||
import { maybeUploadSourceMapAsync } from '../utils/sourceMaps';
|
||||
|
||||
export async function runBuilderWithHooksAsync<T extends BuildJob>(
|
||||
ctx: BuildContext<T>,
|
||||
@@ -38,6 +39,9 @@ export async function runBuilderWithHooksAsync<T extends BuildJob>(
|
||||
}
|
||||
|
||||
await ctx.runBuildPhase(BuildPhase.UPLOAD_BUILD_ARTIFACTS, async () => {
|
||||
if (buildSuccess) {
|
||||
await maybeUploadSourceMapAsync(ctx);
|
||||
}
|
||||
await maybeFindAndUploadBuildArtifacts(ctx, {
|
||||
logger: ctx.logger,
|
||||
});
|
||||
|
||||
@@ -29,6 +29,7 @@ import { uploadEmbeddedBundleAsync } from '../utils/expoUpdatesEmbedded';
|
||||
import { Hook, runHookIfPresent } from '../utils/hooks';
|
||||
import { prepareExecutableAsync } from '../utils/prepareBuildExecutable';
|
||||
import { getParentAndDescendantProcessPidsAsync } from '../utils/processes';
|
||||
import { isSourceMapUploadEnabled, resolveIosSourceMapPathAsync } from '../utils/sourceMaps';
|
||||
|
||||
const INSTALL_PODS_WARN_TIMEOUT_MS = 15 * 60 * 1000; // 15 minutes
|
||||
const INSTALL_PODS_KILL_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
|
||||
@@ -168,20 +169,24 @@ async function buildInnerAsync(
|
||||
fastlaneResult = await ctx.runBuildPhase(BuildPhase.RUN_FASTLANE, async () => {
|
||||
const scheme = resolveScheme(ctx);
|
||||
const entitlements = await readEntitlementsAsync(ctx, { scheme, buildConfiguration });
|
||||
const sourceMapPath = isSourceMapUploadEnabled(ctx)
|
||||
? await resolveIosSourceMapPathAsync(ctx)
|
||||
: null;
|
||||
return await runFastlaneGym(ctx, {
|
||||
credentials,
|
||||
scheme,
|
||||
buildConfiguration,
|
||||
entitlements,
|
||||
...(resolvedExpoUpdatesRuntimeVersion?.runtimeVersion
|
||||
? {
|
||||
extraEnv: {
|
||||
extraEnv: {
|
||||
...(resolvedExpoUpdatesRuntimeVersion?.runtimeVersion
|
||||
? {
|
||||
EXPO_UPDATES_FINGERPRINT_OVERRIDE:
|
||||
resolvedExpoUpdatesRuntimeVersion?.runtimeVersion,
|
||||
EXPO_UPDATES_WORKFLOW_OVERRIDE: ctx.job.type,
|
||||
},
|
||||
}
|
||||
: null),
|
||||
}
|
||||
: null),
|
||||
...(sourceMapPath ? { SOURCEMAP_FILE: sourceMapPath } : null),
|
||||
},
|
||||
});
|
||||
});
|
||||
} finally {
|
||||
|
||||
@@ -45,6 +45,7 @@ import { createSendSlackMessageFunction } from './functions/sendSlackMessage';
|
||||
import { createStartAgentDeviceRemoteSessionBuildFunction } from './functions/startAgentDeviceRemoteSession';
|
||||
import { createStartAndroidEmulatorBuildFunction } from './functions/startAndroidEmulator';
|
||||
import { createStartArgentRemoteSessionBuildFunction } from './functions/startArgentRemoteSession';
|
||||
import { createStartAppiumRemoteSessionBuildFunction } from './functions/startAppiumRemoteSession';
|
||||
import { createStartCuttlefishDeviceBuildFunction } from './functions/startCuttlefishDevice';
|
||||
import { createStartIosSimulatorBuildFunction } from './functions/startIosSimulator';
|
||||
import { createStartIosSimulatorRecordingsBuildFunction } from './functions/startIosSimulatorRecordings';
|
||||
@@ -94,6 +95,7 @@ export function getEasFunctions(ctx: CustomBuildContext): BuildFunction[] {
|
||||
parseXcactivitylogFunction(),
|
||||
createStartAgentDeviceRemoteSessionBuildFunction(ctx),
|
||||
createStartArgentRemoteSessionBuildFunction(ctx),
|
||||
createStartAppiumRemoteSessionBuildFunction(ctx),
|
||||
createStartAndroidEmulatorBuildFunction(),
|
||||
createStartCuttlefishDeviceBuildFunction(),
|
||||
createStartIosSimulatorBuildFunction(),
|
||||
|
||||
+12
-1
@@ -1,6 +1,6 @@
|
||||
import { createGlobalContextMock } from '../../../__tests__/utils/context';
|
||||
import { createMockLogger } from '../../../__tests__/utils/logger';
|
||||
import { createInstallMaestroBuildFunction } from '../installMaestro';
|
||||
import { createInstallMaestroBuildFunction, installIdbFromBrew } from '../installMaestro';
|
||||
|
||||
jest.unmock('fs');
|
||||
jest.unmock('@expo/logger');
|
||||
@@ -57,3 +57,14 @@ describe('createInstallMaestroBuildFunction', () => {
|
||||
console.log(latestStep.outputs[0].value);
|
||||
}, 180_000);
|
||||
});
|
||||
|
||||
describe('installIdbFromBrew', () => {
|
||||
it('installs 1.1.8 version', async () => {
|
||||
const logger = createMockLogger({ logToConsole: true });
|
||||
|
||||
await installIdbFromBrew({
|
||||
logger,
|
||||
env: process.env,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,6 @@
|
||||
import { SystemError, UserError } from '@expo/eas-build-job';
|
||||
import spawn from '@expo/turtle-spawn';
|
||||
import { BuildRuntimePlatform } from '@expo/steps';
|
||||
|
||||
import { createGlobalContextMock } from '../../../__tests__/utils/context';
|
||||
import { Datadog } from '../../../datadog';
|
||||
@@ -38,6 +40,7 @@ describe('createInstallMaestroBuildFunction', () => {
|
||||
expect(step.getOutputValueByName('maestro_version')).toBe('1.41.0');
|
||||
expect(Datadog.distribution).toHaveBeenCalledWith('eas.maestro.install', 1, {
|
||||
maestro_version: '1.41.0',
|
||||
maestro_backend: 'maestro',
|
||||
});
|
||||
});
|
||||
|
||||
@@ -70,6 +73,7 @@ describe('createInstallMaestroBuildFunction', () => {
|
||||
expect(step.getOutputValueByName('maestro_version')).toBe('2.0.10');
|
||||
expect(Datadog.distribution).toHaveBeenCalledWith('eas.maestro.install', 1, {
|
||||
maestro_version: '2.0.10',
|
||||
maestro_backend: 'maestro',
|
||||
});
|
||||
});
|
||||
|
||||
@@ -87,4 +91,352 @@ describe('createInstallMaestroBuildFunction', () => {
|
||||
|
||||
expect(step.getOutputValueByName('maestro_version')).toBe('2.0.10');
|
||||
});
|
||||
|
||||
it('checks maestro-runner when selected by input', async () => {
|
||||
mockedSpawn.mockImplementation((async (command: string) => ({
|
||||
stdout:
|
||||
command === 'maestro-runner'
|
||||
? 'maestro-runner 1.2.3\n Commit: abc123\n Built: 2026-08-13\n Go: go1.26.5\n OS/Arch: darwin/arm64\n'
|
||||
: '',
|
||||
})) as any);
|
||||
|
||||
const installMaestro = createInstallMaestroBuildFunction();
|
||||
const globalCtx = createGlobalContextMock();
|
||||
globalCtx.updateEnv({ EAS_BUILD_RUNNER: 'eas-build' });
|
||||
const step = installMaestro.createBuildStepFromFunctionCall(globalCtx, {
|
||||
callInputs: { backend: 'maestro-runner' },
|
||||
});
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedSpawn).toHaveBeenCalledTimes(2);
|
||||
expect(mockedSpawn.mock.calls.map(([command]) => command)).toEqual([
|
||||
'maestro-runner',
|
||||
'maestro-runner',
|
||||
]);
|
||||
expect(step.getOutputValueByName('maestro_version')).toBe('1.2.3');
|
||||
expect(Datadog.distribution).toHaveBeenCalledWith('eas.maestro.install', 1, {
|
||||
maestro_version: '1.2.3',
|
||||
maestro_backend: 'maestro-runner',
|
||||
});
|
||||
});
|
||||
|
||||
it('selects maestro-runner from EAS_MAESTRO_BACKEND', async () => {
|
||||
mockedSpawn.mockImplementation((async (command: string) => ({
|
||||
stdout: command === 'maestro-runner' ? 'maestro-runner 1.2.3\n' : '',
|
||||
})) as any);
|
||||
|
||||
const installMaestro = createInstallMaestroBuildFunction();
|
||||
const globalCtx = createGlobalContextMock();
|
||||
globalCtx.updateEnv({
|
||||
EAS_BUILD_RUNNER: 'eas-build',
|
||||
EAS_MAESTRO_BACKEND: 'maestro-runner',
|
||||
});
|
||||
const step = installMaestro.createBuildStepFromFunctionCall(globalCtx, { callInputs: {} });
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedSpawn.mock.calls.map(([command]) => command)).toEqual([
|
||||
'maestro-runner',
|
||||
'maestro-runner',
|
||||
]);
|
||||
});
|
||||
|
||||
it('installs the latest maestro-runner version when it is missing', async () => {
|
||||
let versionChecks = 0;
|
||||
mockedSpawn.mockImplementation((async (command: string) => {
|
||||
if (command === 'maestro-runner' && versionChecks++ === 0) {
|
||||
throw Object.assign(new Error('not found'), { code: 'ENOENT' });
|
||||
}
|
||||
return { stdout: command === 'maestro-runner' ? 'maestro-runner 1.2.3\n' : '' };
|
||||
}) as any);
|
||||
const fetchSpy = jest.spyOn(global, 'fetch').mockResolvedValue({
|
||||
ok: true,
|
||||
text: async () => '#!/bin/sh\n',
|
||||
} as Response);
|
||||
const originalPath = process.env.PATH;
|
||||
|
||||
try {
|
||||
const installMaestro = createInstallMaestroBuildFunction();
|
||||
const globalCtx = createGlobalContextMock();
|
||||
globalCtx.updateEnv({
|
||||
EAS_BUILD_RUNNER: 'eas-build',
|
||||
HOME: '/home/expo',
|
||||
PATH: '/usr/bin',
|
||||
});
|
||||
const step = installMaestro.createBuildStepFromFunctionCall(globalCtx, {
|
||||
callInputs: { backend: 'maestro-runner' },
|
||||
});
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledWith('https://open.devicelab.dev/install/maestro-runner');
|
||||
expect(mockedSpawn).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/install_maestro_runner.*\/install_maestro_runner\.sh$/),
|
||||
[],
|
||||
expect.objectContaining({ env: expect.objectContaining({ HOME: '/home/expo' }) })
|
||||
);
|
||||
expect(mockedSpawn).toHaveBeenLastCalledWith(
|
||||
'maestro-runner',
|
||||
['--version'],
|
||||
expect.objectContaining({
|
||||
env: expect.objectContaining({
|
||||
PATH: expect.stringMatching(/^\/home\/expo\/\.maestro-runner\/bin:/),
|
||||
}),
|
||||
})
|
||||
);
|
||||
} finally {
|
||||
fetchSpy.mockRestore();
|
||||
process.env.PATH = originalPath;
|
||||
}
|
||||
});
|
||||
|
||||
it('installs maestro-runner 1.1.15 on Xcode versions below 26', async () => {
|
||||
let versionChecks = 0;
|
||||
mockedSpawn.mockImplementation((async (command: string) => {
|
||||
switch (command) {
|
||||
case 'xcodebuild':
|
||||
return { stdout: 'Xcode 16.4\nBuild version 16F6\n' };
|
||||
case 'maestro-runner':
|
||||
return {
|
||||
stdout: versionChecks++ === 0 ? 'maestro-runner 1.1.23\n' : 'maestro-runner 1.1.15\n',
|
||||
};
|
||||
default:
|
||||
return { stdout: '' };
|
||||
}
|
||||
}) as any);
|
||||
const fetchSpy = jest.spyOn(global, 'fetch').mockResolvedValue({
|
||||
text: async () => '#!/bin/sh\n',
|
||||
} as Response);
|
||||
const originalPath = process.env.PATH;
|
||||
|
||||
try {
|
||||
const installMaestro = createInstallMaestroBuildFunction();
|
||||
const globalCtx = createGlobalContextMock({
|
||||
runtimePlatform: BuildRuntimePlatform.DARWIN,
|
||||
});
|
||||
globalCtx.updateEnv({
|
||||
EAS_BUILD_RUNNER: 'eas-build',
|
||||
HOME: '/home/expo',
|
||||
PATH: '/usr/bin',
|
||||
});
|
||||
const step = installMaestro.createBuildStepFromFunctionCall(globalCtx, {
|
||||
callInputs: { backend: 'maestro-runner' },
|
||||
});
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedSpawn).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/install_maestro_runner.*\/install_maestro_runner\.sh$/),
|
||||
['--version', '1.1.15'],
|
||||
expect.objectContaining({ env: expect.objectContaining({ HOME: '/home/expo' }) })
|
||||
);
|
||||
expect(step.getOutputValueByName('maestro_version')).toBe('1.1.15');
|
||||
} finally {
|
||||
fetchSpy.mockRestore();
|
||||
process.env.PATH = originalPath;
|
||||
}
|
||||
});
|
||||
|
||||
it('does not check Xcode when a compatible maestro-runner version is installed', async () => {
|
||||
mockedSpawn.mockImplementation((async (command: string) => {
|
||||
if (command === 'xcodebuild') {
|
||||
throw new Error('xcodebuild should not be called');
|
||||
}
|
||||
return { stdout: command === 'maestro-runner' ? 'maestro-runner 1.1.15\n' : '' };
|
||||
}) as any);
|
||||
|
||||
const installMaestro = createInstallMaestroBuildFunction();
|
||||
const globalCtx = createGlobalContextMock({
|
||||
runtimePlatform: BuildRuntimePlatform.DARWIN,
|
||||
});
|
||||
globalCtx.updateEnv({
|
||||
EAS_BUILD_RUNNER: 'eas-build',
|
||||
HOME: '/home/expo',
|
||||
PATH: '/usr/bin',
|
||||
});
|
||||
const step = installMaestro.createBuildStepFromFunctionCall(globalCtx, {
|
||||
callInputs: { backend: 'maestro-runner' },
|
||||
});
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedSpawn).not.toHaveBeenCalledWith(
|
||||
'xcodebuild',
|
||||
expect.anything(),
|
||||
expect.anything()
|
||||
);
|
||||
expect(step.getOutputValueByName('maestro_version')).toBe('1.1.15');
|
||||
});
|
||||
|
||||
it('checks Xcode for latest when a compatible maestro-runner version is installed', async () => {
|
||||
mockedSpawn.mockImplementation((async (command: string) => {
|
||||
switch (command) {
|
||||
case 'xcodebuild':
|
||||
return { stdout: 'Xcode 16.4\nBuild version 16F6\n' };
|
||||
case 'maestro-runner':
|
||||
return { stdout: 'maestro-runner 1.1.15\n' };
|
||||
default:
|
||||
return { stdout: '' };
|
||||
}
|
||||
}) as any);
|
||||
|
||||
const installMaestro = createInstallMaestroBuildFunction();
|
||||
const globalCtx = createGlobalContextMock({
|
||||
runtimePlatform: BuildRuntimePlatform.DARWIN,
|
||||
});
|
||||
globalCtx.updateEnv({
|
||||
EAS_BUILD_RUNNER: 'eas-build',
|
||||
HOME: '/home/expo',
|
||||
PATH: '/usr/bin',
|
||||
});
|
||||
const step = installMaestro.createBuildStepFromFunctionCall(globalCtx, {
|
||||
callInputs: { backend: 'maestro-runner', maestro_version: 'latest' },
|
||||
});
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedSpawn).toHaveBeenCalledWith(
|
||||
'xcodebuild',
|
||||
['-version'],
|
||||
expect.objectContaining({ env: expect.anything() })
|
||||
);
|
||||
expect(step.getOutputValueByName('maestro_version')).toBe('1.1.15');
|
||||
});
|
||||
|
||||
it('installs the latest maestro-runner version on Xcode 26', async () => {
|
||||
let versionChecks = 0;
|
||||
mockedSpawn.mockImplementation((async (command: string) => {
|
||||
if (command === 'xcodebuild') {
|
||||
return { stdout: 'Xcode 26.0\nBuild version 17A324\n' };
|
||||
}
|
||||
if (command === 'maestro-runner' && versionChecks++ === 0) {
|
||||
throw Object.assign(new Error('not found'), { code: 'ENOENT' });
|
||||
}
|
||||
return { stdout: command === 'maestro-runner' ? 'maestro-runner 1.1.23\n' : '' };
|
||||
}) as any);
|
||||
const fetchSpy = jest.spyOn(global, 'fetch').mockResolvedValue({
|
||||
text: async () => '#!/bin/sh\n',
|
||||
} as Response);
|
||||
const originalPath = process.env.PATH;
|
||||
|
||||
try {
|
||||
const installMaestro = createInstallMaestroBuildFunction();
|
||||
const globalCtx = createGlobalContextMock({
|
||||
runtimePlatform: BuildRuntimePlatform.DARWIN,
|
||||
});
|
||||
globalCtx.updateEnv({
|
||||
EAS_BUILD_RUNNER: 'eas-build',
|
||||
HOME: '/home/expo',
|
||||
PATH: '/usr/bin',
|
||||
});
|
||||
const step = installMaestro.createBuildStepFromFunctionCall(globalCtx, {
|
||||
callInputs: { backend: 'maestro-runner' },
|
||||
});
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedSpawn).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/install_maestro_runner.*\/install_maestro_runner\.sh$/),
|
||||
[],
|
||||
expect.objectContaining({ env: expect.objectContaining({ HOME: '/home/expo' }) })
|
||||
);
|
||||
expect(step.getOutputValueByName('maestro_version')).toBe('1.1.23');
|
||||
} finally {
|
||||
fetchSpy.mockRestore();
|
||||
process.env.PATH = originalPath;
|
||||
}
|
||||
});
|
||||
|
||||
it('throws a system error when the Xcode version cannot be determined', async () => {
|
||||
mockedSpawn.mockImplementation((async (command: string) => {
|
||||
if (command === 'xcodebuild') {
|
||||
return { stdout: 'unexpected output' };
|
||||
}
|
||||
throw Object.assign(new Error('not found'), { code: 'ENOENT' });
|
||||
}) as any);
|
||||
|
||||
const installMaestro = createInstallMaestroBuildFunction();
|
||||
const globalCtx = createGlobalContextMock({
|
||||
runtimePlatform: BuildRuntimePlatform.DARWIN,
|
||||
});
|
||||
globalCtx.updateEnv({
|
||||
EAS_BUILD_RUNNER: 'eas-build',
|
||||
HOME: '/home/expo',
|
||||
PATH: '/usr/bin',
|
||||
});
|
||||
const step = installMaestro.createBuildStepFromFunctionCall(globalCtx, {
|
||||
callInputs: { backend: 'maestro-runner' },
|
||||
});
|
||||
|
||||
await expect(step.executeAsync()).rejects.toThrow(SystemError);
|
||||
});
|
||||
|
||||
it('rejects a requested maestro-runner version that is incompatible with Xcode', async () => {
|
||||
mockedSpawn.mockImplementation((async (command: string) => {
|
||||
if (command === 'xcodebuild') {
|
||||
return { stdout: 'Xcode 16.4\nBuild version 16F6\n' };
|
||||
}
|
||||
throw Object.assign(new Error('not found'), { code: 'ENOENT' });
|
||||
}) as any);
|
||||
|
||||
const installMaestro = createInstallMaestroBuildFunction();
|
||||
const globalCtx = createGlobalContextMock({
|
||||
runtimePlatform: BuildRuntimePlatform.DARWIN,
|
||||
});
|
||||
globalCtx.updateEnv({
|
||||
EAS_BUILD_RUNNER: 'eas-build',
|
||||
HOME: '/home/expo',
|
||||
PATH: '/usr/bin',
|
||||
});
|
||||
const step = installMaestro.createBuildStepFromFunctionCall(globalCtx, {
|
||||
callInputs: { backend: 'maestro-runner', maestro_version: '1.1.23' },
|
||||
});
|
||||
|
||||
const executePromise = step.executeAsync();
|
||||
await expect(executePromise).rejects.toThrow(UserError);
|
||||
await expect(executePromise).rejects.toMatchObject({
|
||||
errorCode: 'ERR_MAESTRO_INVALID_INPUT',
|
||||
message:
|
||||
'maestro-runner 1.1.23 is not compatible with Xcode 16.4.0. Use maestro-runner 1.1.15 or an Xcode 26+ image.',
|
||||
});
|
||||
});
|
||||
|
||||
it('installs the requested maestro-runner version', async () => {
|
||||
let versionChecks = 0;
|
||||
mockedSpawn.mockImplementation((async (command: string) => {
|
||||
if (command === 'maestro-runner' && versionChecks++ === 0) {
|
||||
throw Object.assign(new Error('not found'), { code: 'ENOENT' });
|
||||
}
|
||||
return { stdout: command === 'maestro-runner' ? 'maestro-runner 1.0.9\n' : '' };
|
||||
}) as any);
|
||||
jest.spyOn(global, 'fetch').mockResolvedValue({
|
||||
text: async () => '#!/bin/sh\n',
|
||||
} as Response);
|
||||
const originalPath = process.env.PATH;
|
||||
|
||||
try {
|
||||
const installMaestro = createInstallMaestroBuildFunction();
|
||||
const globalCtx = createGlobalContextMock();
|
||||
globalCtx.updateEnv({
|
||||
EAS_BUILD_RUNNER: 'eas-build',
|
||||
HOME: '/home/expo',
|
||||
PATH: '/usr/bin',
|
||||
});
|
||||
const step = installMaestro.createBuildStepFromFunctionCall(globalCtx, {
|
||||
callInputs: { backend: 'maestro-runner', maestro_version: '1.0.9' },
|
||||
});
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedSpawn).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/install_maestro_runner.*\/install_maestro_runner\.sh$/),
|
||||
['--version', '1.0.9'],
|
||||
expect.objectContaining({ env: expect.objectContaining({ HOME: '/home/expo' }) })
|
||||
);
|
||||
} finally {
|
||||
jest.restoreAllMocks();
|
||||
process.env.PATH = originalPath;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -10,11 +10,92 @@ import {
|
||||
parseFailedFlowNamesFromJUnitFile,
|
||||
parseFailedFlowsFromFileAttrs,
|
||||
parseFailedFlowsFromJUnit,
|
||||
parseFailedFlowsFromMaestroRunnerReport,
|
||||
parseJUnitTestCases,
|
||||
parseMaestroResults,
|
||||
parseMaestroResultsFromFileAttrs,
|
||||
parseMaestroRunnerReport,
|
||||
} from '../maestroResultParser';
|
||||
|
||||
describe(parseFailedFlowsFromMaestroRunnerReport, () => {
|
||||
it('returns exact sourceFile paths for failed flows', async () => {
|
||||
vol.fromJSON({
|
||||
'/project/flows/pass.yml': '',
|
||||
'/project/flows/nested/fail.yml': '',
|
||||
'/reports/attempt-0/report.json': JSON.stringify({
|
||||
flows: [
|
||||
{ name: 'Passing flow', sourceFile: 'flows/pass.yml', status: 'passed' },
|
||||
{
|
||||
name: 'Failing flow',
|
||||
sourceFile: 'flows/nested/fail.yml',
|
||||
status: 'failed',
|
||||
},
|
||||
{ status: 'skipped' },
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
await expect(
|
||||
parseFailedFlowsFromMaestroRunnerReport({
|
||||
reportDirectory: '/reports/attempt-0',
|
||||
workingDirectory: '/project',
|
||||
})
|
||||
).resolves.toEqual(['flows/nested/fail.yml']);
|
||||
await expect(parseMaestroRunnerReport('/reports/attempt-0')).resolves.toEqual({
|
||||
flows: [
|
||||
{ name: 'Passing flow', sourceFile: 'flows/pass.yml', status: 'passed' },
|
||||
{
|
||||
name: 'Failing flow',
|
||||
sourceFile: 'flows/nested/fail.yml',
|
||||
status: 'failed',
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: 'incomplete flow',
|
||||
report: {
|
||||
version: '1.0.0',
|
||||
status: 'failed',
|
||||
summary: { total: 1 },
|
||||
flows: [{ name: 'Failing flow', sourceFile: 'flows/fail.yml', status: 'running' }],
|
||||
},
|
||||
},
|
||||
])('returns null for an $name', async ({ report }) => {
|
||||
vol.fromJSON({
|
||||
'/project/flows/fail.yml': '',
|
||||
'/reports/attempt-0/report.json': JSON.stringify(report),
|
||||
});
|
||||
|
||||
await expect(
|
||||
parseFailedFlowsFromMaestroRunnerReport({
|
||||
reportDirectory: '/reports/attempt-0',
|
||||
workingDirectory: '/project',
|
||||
})
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when a failed sourceFile does not exist', async () => {
|
||||
vol.fromJSON({
|
||||
'/reports/attempt-0/report.json': JSON.stringify({
|
||||
version: '1.0.0',
|
||||
status: 'failed',
|
||||
summary: { total: 1 },
|
||||
flows: [{ name: 'Failing flow', sourceFile: 'flows/missing.yml', status: 'failed' }],
|
||||
}),
|
||||
});
|
||||
|
||||
await expect(
|
||||
parseFailedFlowsFromMaestroRunnerReport({
|
||||
reportDirectory: '/reports/attempt-0',
|
||||
workingDirectory: '/project',
|
||||
})
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe(parseFailedFlowNamesFromJUnitFile, () => {
|
||||
it('returns the names of failed testcases, keeping slashes', async () => {
|
||||
vol.fromJSON({
|
||||
@@ -453,6 +534,20 @@ describe('junitFileHasFileAttrs', () => {
|
||||
expect(await junitFileHasFileAttrs('/junit/report.xml')).toBe(false);
|
||||
});
|
||||
|
||||
it('returns true for a maestro-runner report with a file property', async () => {
|
||||
vol.fromJSON({
|
||||
'/junit/report.xml': [
|
||||
'<?xml version="1.0"?>',
|
||||
'<testsuites><testsuite>',
|
||||
' <testcase name="a" time="1.0">',
|
||||
' <properties><property name="file" value="flows/a.yaml"/></properties>',
|
||||
' </testcase>',
|
||||
'</testsuite></testsuites>',
|
||||
].join('\n'),
|
||||
});
|
||||
expect(await junitFileHasFileAttrs('/junit/report.xml')).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false when the file cannot be read', async () => {
|
||||
expect(await junitFileHasFileAttrs('/missing.xml')).toBe(false);
|
||||
});
|
||||
@@ -478,6 +573,41 @@ describe(parseJUnitTestCases, () => {
|
||||
expect(results[0].file).toBe('.maestro/login.yaml');
|
||||
});
|
||||
|
||||
it('parses maestro-runner file properties and standard JUnit pass status', async () => {
|
||||
vol.fromJSON({
|
||||
'/junit/report.xml': [
|
||||
'<?xml version="1.0"?>',
|
||||
'<testsuites><testsuite>',
|
||||
' <testcase name="login" time="1.0">',
|
||||
' <properties><property name="file" value="flows/login.yaml"/></properties>',
|
||||
' </testcase>',
|
||||
'</testsuite></testsuites>',
|
||||
].join('\n'),
|
||||
});
|
||||
|
||||
const results = await parseJUnitTestCases('/junit');
|
||||
|
||||
expect(results[0]).toEqual(
|
||||
expect.objectContaining({ file: 'flows/login.yaml', status: 'passed' })
|
||||
);
|
||||
});
|
||||
|
||||
it('excludes skipped testcases instead of counting them as passed', async () => {
|
||||
vol.fromJSON({
|
||||
'/junit/report.xml': [
|
||||
'<?xml version="1.0"?>',
|
||||
'<testsuites><testsuite>',
|
||||
' <testcase name="passing" time="1.0"/>',
|
||||
' <testcase name="skipped-flow" time="0"><skipped/></testcase>',
|
||||
'</testsuite></testsuites>',
|
||||
].join('\n'),
|
||||
});
|
||||
|
||||
const results = await parseJUnitTestCases('/junit');
|
||||
|
||||
expect(results.map(r => r.name)).toEqual(['passing']);
|
||||
});
|
||||
|
||||
it('treats a missing or empty file= attribute as undefined', async () => {
|
||||
vol.fromJSON({
|
||||
'/junit/report.xml': [
|
||||
|
||||
@@ -3,14 +3,160 @@ import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
import { createMockLogger } from '../../../__tests__/utils/logger';
|
||||
import { Sentry } from '../../../sentry';
|
||||
import {
|
||||
type HarvestedScreenshot,
|
||||
computePureFailureFlowNames,
|
||||
harvestFailureScreenshotsAsync,
|
||||
harvestMaestroRunnerFailureScreenshotsAsync,
|
||||
parseFailureScreenshotFilename,
|
||||
selectFailureScreenshots,
|
||||
} from '../maestroScreenshots';
|
||||
|
||||
describe(harvestMaestroRunnerFailureScreenshotsAsync, () => {
|
||||
const logger = createMockLogger();
|
||||
let reportDirectory: string;
|
||||
let captureSpy: jest.SpiedFunction<typeof Sentry.capture>;
|
||||
|
||||
beforeEach(async () => {
|
||||
reportDirectory = await fs.mkdtemp(path.join(os.tmpdir(), 'maestro-runner-harvest-test-'));
|
||||
await fs.mkdir(path.join(reportDirectory, 'flows'));
|
||||
await fs.mkdir(path.join(reportDirectory, 'assets', 'flow-000'), { recursive: true });
|
||||
captureSpy = jest.spyOn(Sentry, 'capture').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await fs.rm(reportDirectory, { recursive: true, force: true });
|
||||
captureSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('reads the failed command screenshot from a maestro-runner report bundle', async () => {
|
||||
const capturedSinceMs = Date.now() - 1_000;
|
||||
await fs.writeFile(
|
||||
path.join(reportDirectory, 'report.json'),
|
||||
JSON.stringify({
|
||||
flows: [
|
||||
{
|
||||
name: 'authentication/Login',
|
||||
status: 'failed',
|
||||
dataFile: 'flows/flow-000.json',
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
await fs.writeFile(
|
||||
path.join(reportDirectory, 'flows', 'flow-000.json'),
|
||||
JSON.stringify({
|
||||
commands: [
|
||||
{
|
||||
status: 'failed',
|
||||
artifacts: { screenshotAfter: 'assets/flow-000/cmd-001-after.png' },
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
const screenshotPath = path.join(reportDirectory, 'assets', 'flow-000', 'cmd-001-after.png');
|
||||
await fs.writeFile(screenshotPath, 'png');
|
||||
|
||||
const shots = await harvestMaestroRunnerFailureScreenshotsAsync({
|
||||
reportDirectory,
|
||||
capturedSinceMs,
|
||||
attemptIndex: 1,
|
||||
logger,
|
||||
});
|
||||
|
||||
expect(shots).toEqual([
|
||||
{
|
||||
fileAbsPath: screenshotPath,
|
||||
displayName: 'Failure Screenshot: authentication_Login (attempt 2)',
|
||||
metadata: {
|
||||
kind: 'maestro-test-screenshot',
|
||||
flowName: 'authentication_Login',
|
||||
attemptIndex: 1,
|
||||
capturedAtMs: expect.any(Number),
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('rejects a screenshot path that resolves to the parent directory (exact "..")', async () => {
|
||||
await fs.writeFile(
|
||||
path.join(reportDirectory, 'report.json'),
|
||||
JSON.stringify({
|
||||
flows: [{ name: 'Login', status: 'failed', dataFile: 'flows/flow-000.json' }],
|
||||
})
|
||||
);
|
||||
await fs.writeFile(
|
||||
path.join(reportDirectory, 'flows', 'flow-000.json'),
|
||||
JSON.stringify({
|
||||
commands: [{ status: 'failed', artifacts: { screenshotAfter: '..' } }],
|
||||
})
|
||||
);
|
||||
|
||||
await expect(
|
||||
harvestMaestroRunnerFailureScreenshotsAsync({
|
||||
reportDirectory,
|
||||
capturedSinceMs: 0,
|
||||
attemptIndex: 0,
|
||||
logger,
|
||||
})
|
||||
).resolves.toEqual([]);
|
||||
});
|
||||
|
||||
it('ignores passing flows and paths outside the report directory', async () => {
|
||||
await fs.writeFile(
|
||||
path.join(reportDirectory, 'report.json'),
|
||||
JSON.stringify({
|
||||
flows: [
|
||||
{ name: 'Passing', status: 'passed', dataFile: 'flows/flow-000.json' },
|
||||
{ name: 'Unsafe', status: 'failed', dataFile: '../outside.json' },
|
||||
],
|
||||
})
|
||||
);
|
||||
|
||||
await expect(
|
||||
harvestMaestroRunnerFailureScreenshotsAsync({
|
||||
reportDirectory,
|
||||
capturedSinceMs: 0,
|
||||
attemptIndex: 0,
|
||||
logger,
|
||||
})
|
||||
).resolves.toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['null', 'null'],
|
||||
['a non-object flows value', JSON.stringify({ flows: 5 })],
|
||||
['a null flow entry', JSON.stringify({ flows: [null] })],
|
||||
])('reports to Sentry and returns [] when report.json is %s', async (_label, contents) => {
|
||||
await fs.writeFile(path.join(reportDirectory, 'report.json'), contents);
|
||||
|
||||
await expect(
|
||||
harvestMaestroRunnerFailureScreenshotsAsync({
|
||||
reportDirectory,
|
||||
capturedSinceMs: 0,
|
||||
attemptIndex: 0,
|
||||
logger,
|
||||
})
|
||||
).resolves.toEqual([]);
|
||||
expect(captureSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('returns [] without reporting to Sentry when report.json is not valid JSON', async () => {
|
||||
await fs.writeFile(path.join(reportDirectory, 'report.json'), 'not-json');
|
||||
|
||||
await expect(
|
||||
harvestMaestroRunnerFailureScreenshotsAsync({
|
||||
reportDirectory,
|
||||
capturedSinceMs: 0,
|
||||
attemptIndex: 0,
|
||||
logger,
|
||||
})
|
||||
).resolves.toEqual([]);
|
||||
expect(captureSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe(parseFailureScreenshotFilename, () => {
|
||||
it('parses a plain failure screenshot', () => {
|
||||
expect(parseFailureScreenshotFilename('screenshot-❌-1781186692250-(Login Flow).png')).toEqual({
|
||||
|
||||
@@ -27,10 +27,14 @@ jest.mock('../../../utils/retry', () => ({
|
||||
jest.mock('../maestroScreenshots', () => ({
|
||||
...jest.requireActual('../maestroScreenshots'),
|
||||
harvestFailureScreenshotsAsync: jest.fn(),
|
||||
harvestMaestroRunnerFailureScreenshotsAsync: jest.fn(),
|
||||
}));
|
||||
|
||||
const mockedSpawn = jest.mocked(spawn);
|
||||
const mockedHarvest = jest.mocked(maestroScreenshots.harvestFailureScreenshotsAsync);
|
||||
const mockedRunnerHarvest = jest.mocked(
|
||||
maestroScreenshots.harvestMaestroRunnerFailureScreenshotsAsync
|
||||
);
|
||||
const mockUploadArtifact = jest.fn();
|
||||
|
||||
function makeShot(index: number): maestroScreenshots.HarvestedScreenshot {
|
||||
@@ -63,11 +67,14 @@ const rejectExit1 = (): Error => {
|
||||
|
||||
function createStep(
|
||||
callInputs?: Record<string, unknown>,
|
||||
options: { env?: Record<string, string | undefined> } = {}
|
||||
options: {
|
||||
env?: Record<string, string | undefined>;
|
||||
logger?: ReturnType<typeof createMockLogger>;
|
||||
} = {}
|
||||
): ReturnType<
|
||||
ReturnType<typeof createMaestroTestsBuildFunction>['createBuildStepFromFunctionCall']
|
||||
> {
|
||||
const logger = createMockLogger();
|
||||
const logger = options.logger ?? createMockLogger();
|
||||
const ctx = {
|
||||
runtimeApi: { uploadArtifact: mockUploadArtifact },
|
||||
} as unknown as CustomBuildContext;
|
||||
@@ -86,6 +93,8 @@ describe('createMaestroTestsBuildFunction', () => {
|
||||
jest.spyOn(parser, 'mergeJUnitReports').mockResolvedValue();
|
||||
mockedHarvest.mockReset();
|
||||
mockedHarvest.mockResolvedValue([]);
|
||||
mockedRunnerHarvest.mockReset();
|
||||
mockedRunnerHarvest.mockResolvedValue([]);
|
||||
mockUploadArtifact.mockReset();
|
||||
mockUploadArtifact.mockResolvedValue({ artifactId: 'artifact-1' });
|
||||
});
|
||||
@@ -134,6 +143,418 @@ describe('createMaestroTestsBuildFunction', () => {
|
||||
expect(args!.join(' ')).toMatch(/--output=.*android-maestro-junit-attempt-0\.xml/);
|
||||
});
|
||||
|
||||
it('runs maestro-runner and collects its JUnit report when selected by input', async () => {
|
||||
mockedSpawn.mockResolvedValue(SPAWN_SUCCESS);
|
||||
const copyFileSpy = jest.spyOn(fs, 'copyFile').mockResolvedValue();
|
||||
const junitFailureNamesSpy = jest.spyOn(parser, 'parseFailedFlowNamesFromJUnitFile');
|
||||
const step = createStep({
|
||||
flow_path: ['flows/a.yaml', 'flows/b.yaml'],
|
||||
output_format: 'junit',
|
||||
platform: 'ios',
|
||||
backend: 'maestro-runner',
|
||||
});
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedSpawn).toHaveBeenCalledTimes(1);
|
||||
const [command, args] = mockedSpawn.mock.calls[0];
|
||||
expect(command).toBe('maestro-runner');
|
||||
expect(args).toEqual([
|
||||
'--platform=ios',
|
||||
'test',
|
||||
'--output=/home/expo/.maestro/tests/ios-maestro-runner-attempt-0',
|
||||
'--flatten',
|
||||
'flows/a.yaml',
|
||||
'flows/b.yaml',
|
||||
]);
|
||||
expect(copyFileSpy).toHaveBeenCalledWith(
|
||||
'/home/expo/.maestro/tests/ios-maestro-runner-attempt-0/junit-report.xml',
|
||||
'/home/expo/.maestro/tests/junit-reports/ios-maestro-junit-attempt-0.xml'
|
||||
);
|
||||
expect(mockedHarvest).not.toHaveBeenCalled();
|
||||
expect(junitFailureNamesSpy).not.toHaveBeenCalled();
|
||||
expect(mockedRunnerHarvest).toHaveBeenCalledWith({
|
||||
reportDirectory: '/home/expo/.maestro/tests/ios-maestro-runner-attempt-0',
|
||||
capturedSinceMs: expect.any(Number),
|
||||
attemptIndex: 0,
|
||||
logger: expect.anything(),
|
||||
});
|
||||
});
|
||||
|
||||
it('clears the deterministic maestro-runner output directory before each attempt', async () => {
|
||||
mockedSpawn.mockResolvedValue(SPAWN_SUCCESS);
|
||||
jest.spyOn(fs, 'copyFile').mockResolvedValue();
|
||||
const rmSpy = jest.spyOn(fs, 'rm').mockResolvedValue();
|
||||
const step = createStep({
|
||||
flow_path: ['flows/a.yaml'],
|
||||
output_format: 'junit',
|
||||
platform: 'ios',
|
||||
backend: 'maestro-runner',
|
||||
});
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(rmSpy).toHaveBeenCalledWith('/home/expo/.maestro/tests/ios-maestro-runner-attempt-0', {
|
||||
recursive: true,
|
||||
force: true,
|
||||
});
|
||||
// Cleared before the run, so a crash before fresh output can't resurrect stale results.
|
||||
expect(rmSpy.mock.invocationCallOrder[0]).toBeLessThan(mockedSpawn.mock.invocationCallOrder[0]);
|
||||
});
|
||||
|
||||
it('selects maestro-runner from EAS_MAESTRO_BACKEND', async () => {
|
||||
mockedSpawn.mockResolvedValue(SPAWN_SUCCESS);
|
||||
jest.spyOn(fs, 'copyFile').mockResolvedValue();
|
||||
const step = createStep(
|
||||
{ flow_path: ['flows/a.yaml'], platform: 'android' },
|
||||
{ env: { HOME: '/home/expo', EAS_MAESTRO_BACKEND: 'maestro-runner' } }
|
||||
);
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedSpawn.mock.calls[0][0]).toBe('maestro-runner');
|
||||
});
|
||||
|
||||
it('prefers the backend input over EAS_MAESTRO_BACKEND', async () => {
|
||||
mockedSpawn.mockResolvedValue(SPAWN_SUCCESS);
|
||||
const step = createStep(
|
||||
{ flow_path: ['flows/a.yaml'], platform: 'android', backend: 'maestro' },
|
||||
{ env: { HOME: '/home/expo', EAS_MAESTRO_BACKEND: 'maestro-runner' } }
|
||||
);
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedSpawn.mock.calls[0][0]).toBe('maestro');
|
||||
});
|
||||
|
||||
it('passes tags to maestro-runner', async () => {
|
||||
mockedSpawn.mockResolvedValue(SPAWN_SUCCESS);
|
||||
jest.spyOn(fs, 'copyFile').mockResolvedValue();
|
||||
const step = createStep({
|
||||
flow_path: ['flows/a.yaml'],
|
||||
platform: 'android',
|
||||
backend: 'maestro-runner',
|
||||
include_tags: 'smoke',
|
||||
exclude_tags: 'slow',
|
||||
});
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedSpawn.mock.calls[0][1]).toEqual(
|
||||
expect.arrayContaining(['--include-tags=smoke', '--exclude-tags=slow'])
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects invalid backend values', async () => {
|
||||
const step = createStep({
|
||||
flow_path: ['flows/a.yaml'],
|
||||
platform: 'android',
|
||||
backend: 'other',
|
||||
});
|
||||
|
||||
await expect(step.executeAsync()).rejects.toThrow(UserError);
|
||||
expect(mockedSpawn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects sharding with maestro-runner', async () => {
|
||||
const step = createStep({
|
||||
flow_path: ['flows/a.yaml'],
|
||||
platform: 'android',
|
||||
backend: 'maestro-runner',
|
||||
shards: 2,
|
||||
});
|
||||
|
||||
await expect(step.executeAsync()).rejects.toThrow(
|
||||
'maestro-runner does not support EAS Maestro test sharding'
|
||||
);
|
||||
expect(mockedSpawn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a non-junit output_format with maestro-runner', async () => {
|
||||
const step = createStep({
|
||||
flow_path: ['flows/a.yaml'],
|
||||
platform: 'android',
|
||||
backend: 'maestro-runner',
|
||||
output_format: 'html',
|
||||
});
|
||||
|
||||
await expect(step.executeAsync()).rejects.toThrow(
|
||||
'maestro-runner only supports the "junit" output_format'
|
||||
);
|
||||
expect(mockedSpawn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('logs that maestro-runner does not support direct DADB', async () => {
|
||||
mockedSpawn.mockResolvedValue(SPAWN_SUCCESS);
|
||||
jest.spyOn(fs, 'copyFile').mockResolvedValue();
|
||||
const logger = createMockLogger();
|
||||
jest.mocked(logger.child).mockReturnValue(logger);
|
||||
const step = createStep(
|
||||
{
|
||||
flow_path: ['flows/a.yaml'],
|
||||
platform: 'android',
|
||||
backend: 'maestro-runner',
|
||||
android_connection_mode: 'dadb',
|
||||
},
|
||||
{ env: { HOME: '/home/expo', PATH: '/usr/bin' }, logger }
|
||||
);
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedSpawn).toHaveBeenCalledTimes(1);
|
||||
expect(mockedSpawn.mock.calls[0][0]).toBe('maestro-runner');
|
||||
expect(logger.info).toHaveBeenCalledWith(
|
||||
'maestro-runner does not support DADB. Using the default ADB connection.'
|
||||
);
|
||||
});
|
||||
|
||||
it('uses direct DADB when android_connection_mode is dadb without cleanup', async () => {
|
||||
mockedSpawn.mockResolvedValue(SPAWN_SUCCESS);
|
||||
const writeFileSpy = jest.spyOn(fs, 'writeFile');
|
||||
const rmSpy = jest.spyOn(fs, 'rm');
|
||||
const logger = createMockLogger();
|
||||
jest.mocked(logger.child).mockReturnValue(logger);
|
||||
const step = createStep(
|
||||
{
|
||||
flow_path: ['flows/a.yaml'],
|
||||
platform: 'android',
|
||||
android_connection_mode: 'dadb',
|
||||
},
|
||||
{ env: { HOME: '/home/expo', PATH: '/usr/bin' }, logger }
|
||||
);
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedSpawn).toHaveBeenCalledTimes(2);
|
||||
expect(mockedSpawn.mock.calls[0].slice(0, 2)).toEqual(['adb', ['kill-server']]);
|
||||
expect(mockedSpawn.mock.calls[1][0]).toBe('maestro');
|
||||
expect(mockedSpawn.mock.calls[0][2]?.signal).toBe(mockedSpawn.mock.calls[1][2]?.signal);
|
||||
|
||||
const maestroEnv = mockedSpawn.mock.calls[1][2]?.env;
|
||||
expect(maestroEnv?.PATH).toMatch(
|
||||
new RegExp(`^${os.tmpdir()}/maestro-tests-adb-override-.+${path.delimiter}/usr/bin$`)
|
||||
);
|
||||
expect(mockedSpawn.mock.calls[0][2]?.env?.PATH).not.toContain('maestro-tests-adb-override-');
|
||||
expect(logger.info).toHaveBeenCalledWith(
|
||||
'Using a direct DADB connection for Android Maestro tests after stopping the ADB server.'
|
||||
);
|
||||
|
||||
expect(writeFileSpy).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/maestro-tests-adb-override-.+\/adb$/),
|
||||
'#!/bin/sh\nexit 1\n',
|
||||
{ mode: 0o755 }
|
||||
);
|
||||
expect(rmSpy).not.toHaveBeenCalledWith(
|
||||
expect.stringMatching(/maestro-tests-adb-override-/),
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
|
||||
it('continues with direct DADB and warns when adb kill-server fails', async () => {
|
||||
const killServerError = new Error('ADB server is unavailable');
|
||||
mockedSpawn.mockImplementation((async (command: string) => {
|
||||
if (command === 'adb') {
|
||||
throw killServerError;
|
||||
}
|
||||
return SPAWN_SUCCESS;
|
||||
}) as any);
|
||||
const logger = createMockLogger();
|
||||
jest.mocked(logger.child).mockReturnValue(logger);
|
||||
const step = createStep(
|
||||
{
|
||||
flow_path: ['flows/a.yaml'],
|
||||
platform: 'android',
|
||||
android_connection_mode: 'dadb',
|
||||
},
|
||||
{ env: { HOME: '/home/expo', PATH: '/usr/bin' }, logger }
|
||||
);
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedSpawn.mock.calls.map(([command]) => command)).toEqual(['adb', 'maestro']);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
{ err: killServerError },
|
||||
'Using a direct DADB connection for Android Maestro tests, but failed to stop the ADB server.'
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
source: 'omitted',
|
||||
callInputs: { flow_path: ['flows/a.yaml'], platform: 'android' },
|
||||
env: { HOME: '/home/expo' },
|
||||
},
|
||||
{
|
||||
source: 'empty input',
|
||||
callInputs: { flow_path: ['flows/a.yaml'], platform: 'android', android_connection_mode: '' },
|
||||
env: { HOME: '/home/expo' },
|
||||
},
|
||||
{
|
||||
source: 'empty environment variable',
|
||||
callInputs: { flow_path: ['flows/a.yaml'], platform: 'android' },
|
||||
env: { HOME: '/home/expo', EAS_MAESTRO_ANDROID_CONNECTION_MODE: '' },
|
||||
},
|
||||
])('treats an $source connection mode value as adb', async ({ callInputs, env }) => {
|
||||
mockedSpawn.mockResolvedValue(SPAWN_SUCCESS);
|
||||
const step = createStep(callInputs, { env });
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedSpawn).toHaveBeenCalledTimes(1);
|
||||
expect(mockedSpawn.mock.calls[0][0]).toBe('maestro');
|
||||
});
|
||||
|
||||
it('uses direct DADB when EAS_MAESTRO_ANDROID_CONNECTION_MODE is dadb', async () => {
|
||||
mockedSpawn.mockResolvedValue(SPAWN_SUCCESS);
|
||||
const step = createStep(
|
||||
{
|
||||
flow_path: ['flows/a.yaml'],
|
||||
platform: 'android',
|
||||
},
|
||||
{
|
||||
env: {
|
||||
HOME: '/home/expo',
|
||||
PATH: '/usr/bin',
|
||||
EAS_MAESTRO_ANDROID_CONNECTION_MODE: 'dadb',
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedSpawn.mock.calls[0].slice(0, 2)).toEqual(['adb', ['kill-server']]);
|
||||
expect(mockedSpawn.mock.calls[1][0]).toBe('maestro');
|
||||
});
|
||||
|
||||
it('prefers android_connection_mode over EAS_MAESTRO_ANDROID_CONNECTION_MODE', async () => {
|
||||
mockedSpawn.mockResolvedValue(SPAWN_SUCCESS);
|
||||
const step = createStep(
|
||||
{
|
||||
flow_path: ['flows/a.yaml'],
|
||||
platform: 'android',
|
||||
android_connection_mode: 'adb',
|
||||
},
|
||||
{
|
||||
env: {
|
||||
HOME: '/home/expo',
|
||||
PATH: '/usr/bin',
|
||||
EAS_MAESTRO_ANDROID_CONNECTION_MODE: 'dadb',
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedSpawn).toHaveBeenCalledTimes(1);
|
||||
expect(mockedSpawn.mock.calls[0][0]).toBe('maestro');
|
||||
});
|
||||
|
||||
it('uses the same direct DADB environment for all retries', async () => {
|
||||
let maestroAttempt = 0;
|
||||
mockedSpawn.mockImplementation((async (command: string) => {
|
||||
if (command === 'maestro' && maestroAttempt++ === 0) {
|
||||
throw rejectExit1();
|
||||
}
|
||||
return SPAWN_SUCCESS;
|
||||
}) as any);
|
||||
jest.spyOn(parser, 'parseFailedFlowsFromJUnit').mockResolvedValue(null);
|
||||
const step = createStep(
|
||||
{
|
||||
flow_path: ['flows/a.yaml'],
|
||||
retries: 1,
|
||||
platform: 'android',
|
||||
android_connection_mode: 'dadb',
|
||||
},
|
||||
{ env: { HOME: '/home/expo', PATH: '/usr/bin' } }
|
||||
);
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
const maestroCalls = mockedSpawn.mock.calls.filter(([command]) => command === 'maestro');
|
||||
expect(maestroCalls).toHaveLength(2);
|
||||
expect(maestroCalls[0][2]?.env?.PATH).toBe(maestroCalls[1][2]?.env?.PATH);
|
||||
expect(mockedSpawn.mock.calls.filter(([command]) => command === 'adb')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('rejects invalid android_connection_mode values', async () => {
|
||||
const step = createStep({
|
||||
flow_path: ['flows/a.yaml'],
|
||||
platform: 'android',
|
||||
android_connection_mode: 'automatic',
|
||||
});
|
||||
|
||||
await expect(step.executeAsync()).rejects.toThrow(UserError);
|
||||
expect(mockedSpawn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects invalid EAS_MAESTRO_ANDROID_CONNECTION_MODE values', async () => {
|
||||
const step = createStep(
|
||||
{
|
||||
flow_path: ['flows/a.yaml'],
|
||||
platform: 'android',
|
||||
},
|
||||
{ env: { HOME: '/home/expo', EAS_MAESTRO_ANDROID_CONNECTION_MODE: 'automatic' } }
|
||||
);
|
||||
|
||||
await expect(step.executeAsync()).rejects.toThrow(UserError);
|
||||
expect(mockedSpawn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ignores direct DADB input mode on iOS', async () => {
|
||||
mockedSpawn.mockResolvedValue(SPAWN_SUCCESS);
|
||||
const step = createStep({
|
||||
flow_path: ['flows/a.yaml'],
|
||||
platform: 'ios',
|
||||
android_connection_mode: 'dadb',
|
||||
});
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedSpawn).toHaveBeenCalledTimes(1);
|
||||
expect(mockedSpawn.mock.calls[0][0]).toBe('maestro');
|
||||
});
|
||||
|
||||
it('ignores direct DADB environment mode on iOS', async () => {
|
||||
mockedSpawn.mockResolvedValue(SPAWN_SUCCESS);
|
||||
const step = createStep(
|
||||
{
|
||||
flow_path: ['flows/a.yaml'],
|
||||
platform: 'ios',
|
||||
},
|
||||
{ env: { HOME: '/home/expo', EAS_MAESTRO_ANDROID_CONNECTION_MODE: 'dadb' } }
|
||||
);
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedSpawn).toHaveBeenCalledTimes(1);
|
||||
expect(mockedSpawn.mock.calls[0][0]).toBe('maestro');
|
||||
});
|
||||
|
||||
it('does not clean up direct DADB mode when Maestro fails', async () => {
|
||||
mockedSpawn.mockImplementation((async (command: string) => {
|
||||
if (command === 'maestro') {
|
||||
throw new Error('maestro crashed');
|
||||
}
|
||||
return SPAWN_SUCCESS;
|
||||
}) as any);
|
||||
const rmSpy = jest.spyOn(fs, 'rm');
|
||||
const step = createStep(
|
||||
{
|
||||
flow_path: ['flows/a.yaml'],
|
||||
platform: 'android',
|
||||
android_connection_mode: 'dadb',
|
||||
},
|
||||
{ env: { HOME: '/home/expo', PATH: '/usr/bin' } }
|
||||
);
|
||||
|
||||
await expect(step.executeAsync()).rejects.toThrow('Unexpected spawn failure invoking maestro');
|
||||
expect(mockedSpawn.mock.calls.filter(([command]) => command === 'adb')).toHaveLength(1);
|
||||
expect(rmSpy).not.toHaveBeenCalledWith(
|
||||
expect.stringMatching(/maestro-tests-adb-override-/),
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
|
||||
it('throws SystemError when spawn fails with ENOENT (binary missing)', async () => {
|
||||
mockedSpawn.mockRejectedValue(Object.assign(new Error('not found'), { code: 'ENOENT' }));
|
||||
const step = createStep({ flow_path: ['a.yaml'], platform: 'android' });
|
||||
@@ -203,6 +624,36 @@ describe('createMaestroTestsBuildFunction', () => {
|
||||
expect(a1Args).not.toContain('flows/c.yaml');
|
||||
});
|
||||
|
||||
it('uses maestro-runner report.json for junit retries', async () => {
|
||||
mockedSpawn.mockRejectedValueOnce(rejectExit1()).mockResolvedValueOnce(SPAWN_SUCCESS);
|
||||
jest.spyOn(fs, 'copyFile').mockResolvedValue();
|
||||
const runnerReportSpy = jest
|
||||
.spyOn(parser, 'parseFailedFlowsFromMaestroRunnerReport')
|
||||
.mockResolvedValue(['flows/b.yaml']);
|
||||
const junitParseSpy = jest.spyOn(parser, 'parseFailedFlowsFromJUnit');
|
||||
|
||||
const step = createStep({
|
||||
flow_path: ['flows/a.yaml', 'flows/b.yaml'],
|
||||
retries: 1,
|
||||
output_format: 'junit',
|
||||
platform: 'ios',
|
||||
backend: 'maestro-runner',
|
||||
});
|
||||
await step.executeAsync();
|
||||
|
||||
expect(runnerReportSpy).toHaveBeenCalledWith({
|
||||
reportDirectory: '/home/expo/.maestro/tests/ios-maestro-runner-attempt-0',
|
||||
workingDirectory: expect.any(String),
|
||||
});
|
||||
expect(junitParseSpy).not.toHaveBeenCalled();
|
||||
expect(mockedSpawn.mock.calls[0][1]).toEqual(
|
||||
expect.arrayContaining(['flows/a.yaml', 'flows/b.yaml'])
|
||||
);
|
||||
const retryArgs = mockedSpawn.mock.calls[1][1]!;
|
||||
expect(retryArgs).toContain('flows/b.yaml');
|
||||
expect(retryArgs).not.toContain('flows/a.yaml');
|
||||
});
|
||||
|
||||
it('retries all flows when parseFailedFlowsFromJUnit returns null', async () => {
|
||||
const spawnMock = mockedSpawn
|
||||
.mockRejectedValueOnce(rejectExit1())
|
||||
@@ -764,6 +1215,29 @@ describe('createMaestroTestsBuildFunction', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('discovers maestro-runner flow results from the attempt report directory', async () => {
|
||||
mockedSpawn.mockResolvedValue(SPAWN_SUCCESS);
|
||||
const shot = makeShot(0);
|
||||
jest.spyOn(fs, 'copyFile').mockResolvedValue();
|
||||
mockedRunnerHarvest.mockResolvedValue([shot]);
|
||||
const parseFlowResultsSpy = jest.spyOn(parser, 'parseMaestroRunnerReport').mockResolvedValue({
|
||||
flows: [{ name: 'Login', sourceFile: 'a.yaml', status: 'failed' }],
|
||||
});
|
||||
|
||||
const step = createStep({
|
||||
flow_path: ['a.yaml'],
|
||||
platform: 'ios',
|
||||
output_format: 'junit',
|
||||
backend: 'maestro-runner',
|
||||
});
|
||||
await step.executeAsync();
|
||||
|
||||
expect(parseFlowResultsSpy).toHaveBeenCalledWith(
|
||||
'/home/expo/.maestro/tests/ios-maestro-runner-attempt-0'
|
||||
);
|
||||
expect(mockUploadArtifact).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('uploads screenshots even when all attempts fail, before throwing ERR_MAESTRO_TESTS_FAILED', async () => {
|
||||
mockedSpawn.mockRejectedValue(rejectExit1());
|
||||
const shot = makeShot(0);
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { type bunyan } from '@expo/logger';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
import { compressCacheAsync } from '../saveCache';
|
||||
import { decompressCacheAsync } from '../restoreCache';
|
||||
|
||||
function createLoggerMock(): bunyan {
|
||||
return { info: jest.fn(), warn: jest.fn(), error: jest.fn() } as unknown as bunyan;
|
||||
}
|
||||
|
||||
describe('cache compress/decompress round trip', () => {
|
||||
it('preserves multiple sibling directories archived together', async () => {
|
||||
const logger = createLoggerMock();
|
||||
|
||||
const cachesDir = path.join(os.tmpdir(), 'gradle-caches');
|
||||
const buildCacheDir = path.join(cachesDir, 'build-cache-1');
|
||||
const journalDir = path.join(cachesDir, 'journal-1');
|
||||
await fs.promises.mkdir(buildCacheDir, { recursive: true });
|
||||
await fs.promises.mkdir(journalDir, { recursive: true });
|
||||
await fs.promises.writeFile(path.join(buildCacheDir, 'entry'), 'cache entry');
|
||||
await fs.promises.writeFile(path.join(journalDir, 'file-access.properties'), 'inception=1');
|
||||
|
||||
const { archivePath } = await compressCacheAsync({
|
||||
paths: [buildCacheDir, journalDir],
|
||||
workingDirectory: cachesDir,
|
||||
verbose: false,
|
||||
logger,
|
||||
});
|
||||
|
||||
const restoreDir = path.join(os.tmpdir(), 'gradle-caches-restored');
|
||||
await fs.promises.mkdir(restoreDir, { recursive: true });
|
||||
await decompressCacheAsync({
|
||||
archivePath,
|
||||
workingDirectory: restoreDir,
|
||||
verbose: false,
|
||||
logger,
|
||||
});
|
||||
|
||||
expect(
|
||||
await fs.promises.readFile(path.join(restoreDir, 'build-cache-1', 'entry'), 'utf8')
|
||||
).toBe('cache entry');
|
||||
expect(
|
||||
await fs.promises.readFile(
|
||||
path.join(restoreDir, 'journal-1', 'file-access.properties'),
|
||||
'utf8'
|
||||
)
|
||||
).toBe('inception=1');
|
||||
});
|
||||
|
||||
it('preserves file modification times so journal-fallback entries can still age out', async () => {
|
||||
const logger = createLoggerMock();
|
||||
|
||||
const sourceDir = path.join(os.tmpdir(), 'mtime-source');
|
||||
await fs.promises.mkdir(sourceDir, { recursive: true });
|
||||
const filePath = path.join(sourceDir, 'entry');
|
||||
await fs.promises.writeFile(filePath, 'cache entry');
|
||||
|
||||
// A whole-second value in the past — tar stores mtimes at one-second resolution.
|
||||
const mtime = new Date('2026-08-01T00:00:00.000Z');
|
||||
await fs.promises.utimes(filePath, mtime, mtime);
|
||||
|
||||
const { archivePath } = await compressCacheAsync({
|
||||
paths: [sourceDir],
|
||||
workingDirectory: sourceDir,
|
||||
verbose: false,
|
||||
logger,
|
||||
});
|
||||
|
||||
const restoreDir = path.join(os.tmpdir(), 'mtime-restored');
|
||||
await fs.promises.mkdir(restoreDir, { recursive: true });
|
||||
await decompressCacheAsync({
|
||||
archivePath,
|
||||
workingDirectory: restoreDir,
|
||||
verbose: false,
|
||||
logger,
|
||||
});
|
||||
|
||||
const restoredStat = await fs.promises.stat(path.join(restoreDir, 'entry'));
|
||||
expect(Math.floor(restoredStat.mtimeMs / 1000)).toBe(Math.floor(mtime.getTime() / 1000));
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import spawn from '@expo/turtle-spawn';
|
||||
import fs from 'node:fs';
|
||||
|
||||
import { createGlobalContextMock } from '../../../__tests__/utils/context';
|
||||
import { createMockLogger } from '../../../__tests__/utils/logger';
|
||||
@@ -34,6 +35,7 @@ jest.mock('../../../utils/AndroidEmulatorUtils', () => ({
|
||||
const mockedSpawn = jest.mocked(spawn);
|
||||
const mockedRetryAsync = jest.mocked(retryAsync);
|
||||
const mockedAndroidUtils = jest.mocked(AndroidEmulatorUtils);
|
||||
const mockedMkdtemp = jest.spyOn(fs.promises, 'mkdtemp');
|
||||
function createStep(callInputs?: Record<string, unknown>, envOverrides?: NodeJS.ProcessEnv) {
|
||||
const logger = createMockLogger();
|
||||
const fn = createStartAndroidEmulatorBuildFunction();
|
||||
@@ -54,6 +56,7 @@ function createStartResult(serialId: string) {
|
||||
|
||||
describe(createStartAndroidEmulatorBuildFunction, () => {
|
||||
beforeEach(() => {
|
||||
mockedMkdtemp.mockResolvedValue('/tmp/logcat-directory');
|
||||
mockedSpawn.mockResolvedValue({ stdout: '', stderr: '' } as any);
|
||||
mockedAndroidUtils.getAvailableDevicesAsync.mockResolvedValue([]);
|
||||
mockedAndroidUtils.createAsync.mockResolvedValue(undefined);
|
||||
@@ -76,6 +79,10 @@ describe(createStartAndroidEmulatorBuildFunction, () => {
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
mockedMkdtemp.mockRestore();
|
||||
});
|
||||
|
||||
it('retries base emulator startup with increasing readiness timeouts', async () => {
|
||||
mockedAndroidUtils.startAsync
|
||||
.mockResolvedValueOnce(createStartResult('emulator-1111'))
|
||||
@@ -106,6 +113,20 @@ describe(createStartAndroidEmulatorBuildFunction, () => {
|
||||
serialId: 'emulator-2222',
|
||||
})
|
||||
);
|
||||
expect(mockedAndroidUtils.startAsync).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({
|
||||
deviceName: 'EasAndroidDevice01',
|
||||
logcatDirectory: '/tmp/logcat-directory',
|
||||
})
|
||||
);
|
||||
expect(mockedAndroidUtils.startAsync).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({
|
||||
deviceName: 'EasAndroidDevice01',
|
||||
logcatDirectory: '/tmp/logcat-directory',
|
||||
})
|
||||
);
|
||||
expect(mockedAndroidUtils.deleteAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
serialId: 'emulator-1111',
|
||||
@@ -174,6 +195,24 @@ describe(createStartAndroidEmulatorBuildFunction, () => {
|
||||
serialId: 'emulator-clone-2-attempt-1',
|
||||
})
|
||||
);
|
||||
expect(mockedAndroidUtils.startAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
deviceName: 'EasAndroidDevice01',
|
||||
logcatDirectory: '/tmp/logcat-directory',
|
||||
})
|
||||
);
|
||||
expect(mockedAndroidUtils.startAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
deviceName: 'eas-simulator-1',
|
||||
logcatDirectory: '/tmp/logcat-directory',
|
||||
})
|
||||
);
|
||||
expect(mockedAndroidUtils.startAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
deviceName: 'eas-simulator-2',
|
||||
logcatDirectory: '/tmp/logcat-directory',
|
||||
})
|
||||
);
|
||||
|
||||
expect(mockedAndroidUtils.deleteAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
@@ -200,6 +239,24 @@ describe(createStartAndroidEmulatorBuildFunction, () => {
|
||||
})
|
||||
);
|
||||
expect(mockedAndroidUtils.deleteAsync).toHaveBeenCalledTimes(3);
|
||||
expect(mockedAndroidUtils.startAsync).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('outputs and uses a temporary logcat directory', async () => {
|
||||
const step = createStep();
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedAndroidUtils.startAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
logcatDirectory: '/tmp/logcat-directory',
|
||||
})
|
||||
);
|
||||
expect(step.getOutputValueByName('logcat_directory')).toBe('/tmp/logcat-directory');
|
||||
expect(mockedAndroidUtils.waitForReadyAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
serialId: 'emulator-default',
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('skips animation scale adjustments when opt out env var is disabled', async () => {
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { BuildRuntimePlatform } from '@expo/steps';
|
||||
|
||||
import { AndroidEmulatorUtils } from '../../../utils/AndroidEmulatorUtils';
|
||||
import { IosSimulatorUtils } from '../../../utils/IosSimulatorUtils';
|
||||
import { selectXcodeDeveloperDirectoryAsync } from '../../utils/remoteDeviceRunSession';
|
||||
|
||||
import { resolveAppium3VersionSpec, resolveAppiumDeviceAsync } from '../startAppiumRemoteSession';
|
||||
|
||||
jest.mock('../../../utils/AndroidEmulatorUtils', () => ({
|
||||
AndroidEmulatorUtils: { getAttachedDevicesAsync: jest.fn() },
|
||||
}));
|
||||
jest.mock('../../../utils/IosSimulatorUtils', () => ({
|
||||
IosSimulatorUtils: { getAvailableDevicesAsync: jest.fn() },
|
||||
}));
|
||||
jest.mock('../../utils/remoteDeviceRunSession', () => ({
|
||||
selectXcodeDeveloperDirectoryAsync: jest.fn(),
|
||||
}));
|
||||
|
||||
const logger = { info: jest.fn(), warn: jest.fn() } as never;
|
||||
|
||||
describe(resolveAppium3VersionSpec, () => {
|
||||
it('uses the worker-supported Appium 3 version by default', () => {
|
||||
expect(resolveAppium3VersionSpec(undefined)).toBe('^3');
|
||||
});
|
||||
|
||||
it.each(['3', '^3', '3.x', '3.5.0', '>=3 <4'])('accepts Appium 3 version %s', version => {
|
||||
expect(resolveAppium3VersionSpec(version)).toBe(version);
|
||||
});
|
||||
|
||||
it.each(['2', '2.19.0', 'latest', '4.0.0', '>=3'])('rejects version %s', version => {
|
||||
expect(() => resolveAppium3VersionSpec(version)).toThrow(
|
||||
`Appium 3 is required for EAS Simulator sessions. Received package version "${version}".`
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe(resolveAppiumDeviceAsync, () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('returns XCUITest capabilities for the booted iOS simulator', async () => {
|
||||
jest
|
||||
.mocked(IosSimulatorUtils.getAvailableDevicesAsync)
|
||||
.mockResolvedValue([{ udid: 'ios-simulator-id' } as never]);
|
||||
|
||||
await expect(
|
||||
resolveAppiumDeviceAsync({
|
||||
runtimePlatform: BuildRuntimePlatform.DARWIN,
|
||||
env: {},
|
||||
logger,
|
||||
})
|
||||
).resolves.toEqual({
|
||||
platformName: 'iOS',
|
||||
automationName: 'XCUITest',
|
||||
driverName: 'xcuitest',
|
||||
udid: 'ios-simulator-id',
|
||||
});
|
||||
expect(selectXcodeDeveloperDirectoryAsync).toHaveBeenCalledWith({ env: {}, logger });
|
||||
expect(IosSimulatorUtils.getAvailableDevicesAsync).toHaveBeenCalledWith({
|
||||
env: {},
|
||||
filter: 'booted',
|
||||
});
|
||||
});
|
||||
|
||||
it('returns UiAutomator2 capabilities for the booted Android emulator', async () => {
|
||||
jest
|
||||
.mocked(AndroidEmulatorUtils.getAttachedDevicesAsync)
|
||||
.mockResolvedValue([{ serialId: 'emulator-5554', state: 'device' } as never]);
|
||||
|
||||
await expect(
|
||||
resolveAppiumDeviceAsync({
|
||||
runtimePlatform: BuildRuntimePlatform.LINUX,
|
||||
env: {},
|
||||
logger,
|
||||
})
|
||||
).resolves.toEqual({
|
||||
platformName: 'Android',
|
||||
automationName: 'UiAutomator2',
|
||||
driverName: 'uiautomator2',
|
||||
udid: 'emulator-5554',
|
||||
});
|
||||
expect(AndroidEmulatorUtils.getAttachedDevicesAsync).toHaveBeenCalledWith({ env: {} });
|
||||
expect(selectXcodeDeveloperDirectoryAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { SystemError, UserError } from '@expo/eas-build-job';
|
||||
import { bunyan } from '@expo/logger';
|
||||
import { asyncResult } from '@expo/results';
|
||||
import {
|
||||
@@ -14,7 +15,9 @@ import assert from 'assert';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import semver from 'semver';
|
||||
|
||||
import { MaestroBackend, resolveMaestroBackend } from './maestroBackend';
|
||||
import { Datadog } from '../../datadog';
|
||||
|
||||
export function createInstallMaestroBuildFunction(): BuildFunction {
|
||||
@@ -29,6 +32,11 @@ export function createInstallMaestroBuildFunction(): BuildFunction {
|
||||
required: false,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'backend',
|
||||
required: false,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
],
|
||||
outputProviders: [
|
||||
BuildStepOutput.createProvider({
|
||||
@@ -37,22 +45,28 @@ export function createInstallMaestroBuildFunction(): BuildFunction {
|
||||
}),
|
||||
],
|
||||
fn: async ({ logger, global }, { inputs, env, outputs }) => {
|
||||
const requestedMaestroVersion = inputs.maestro_version.value as string | undefined;
|
||||
const { value: currentMaestroVersion } = await asyncResult(getMaestroVersion({ env }));
|
||||
const backend = resolveMaestroBackend({
|
||||
input: inputs.backend.value,
|
||||
env,
|
||||
});
|
||||
const requestedVersion = inputs.maestro_version.value as string | undefined;
|
||||
const { value: currentMaestroVersion } = await asyncResult(
|
||||
getMaestroVersion({ env, backend })
|
||||
);
|
||||
|
||||
// When not running in EAS Build VM, do not modify local environment.
|
||||
if (env.EAS_BUILD_RUNNER !== 'eas-build') {
|
||||
const currentIsJavaInstalled = await isJavaInstalled({ env });
|
||||
const currentIsIdbInstalled = await isIdbInstalled({ env });
|
||||
const needsToInstallJava = backend === 'maestro' && !(await isJavaInstalled({ env }));
|
||||
const needsToInstallIdb = backend === 'maestro' && !(await isIdbInstalled({ env }));
|
||||
|
||||
if (!currentIsJavaInstalled) {
|
||||
if (needsToInstallJava) {
|
||||
logger.warn(
|
||||
'It seems Java is not installed. It is required to run Maestro. If the job fails, this may be the reason.'
|
||||
);
|
||||
logger.info('');
|
||||
}
|
||||
|
||||
if (!currentIsIdbInstalled) {
|
||||
if (needsToInstallIdb) {
|
||||
logger.warn(
|
||||
'It seems IDB is not installed. Maestro requires it to run flows on iOS Simulator. If the job fails, this may be the reason.'
|
||||
);
|
||||
@@ -61,27 +75,32 @@ export function createInstallMaestroBuildFunction(): BuildFunction {
|
||||
|
||||
if (!currentMaestroVersion) {
|
||||
logger.warn(
|
||||
'It seems Maestro is not installed. Please install Maestro manually and rerun the job.'
|
||||
`It seems ${backend} is not installed. Please install it manually and rerun the job.`
|
||||
);
|
||||
logger.info('');
|
||||
}
|
||||
|
||||
// Guide is helpful in these two cases, it doesn't mention Java.
|
||||
if (!currentIsIdbInstalled || !currentMaestroVersion) {
|
||||
if (backend === 'maestro' && (needsToInstallIdb || !currentMaestroVersion)) {
|
||||
logger.warn(
|
||||
'For more info, check out Maestro installation guide: https://maestro.mobile.dev/getting-started/installing-maestro'
|
||||
);
|
||||
} else if (backend === 'maestro-runner' && !currentMaestroVersion) {
|
||||
logger.warn(
|
||||
'For more info, check out maestro-runner installation guide: https://github.com/devicelab-dev/maestro-runner#install'
|
||||
);
|
||||
}
|
||||
|
||||
if (currentMaestroVersion) {
|
||||
outputs.maestro_version.set(currentMaestroVersion);
|
||||
logger.info(`Maestro ${currentMaestroVersion} is ready.`);
|
||||
logger.info(`${backend} ${currentMaestroVersion} is ready.`);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!(await isJavaInstalled({ env }))) {
|
||||
const needsToInstallJava = backend === 'maestro' && !(await isJavaInstalled({ env }));
|
||||
if (needsToInstallJava) {
|
||||
if (global.runtimePlatform === BuildRuntimePlatform.DARWIN) {
|
||||
logger.info('Installing Java');
|
||||
await installJavaFromGcs({ logger, env });
|
||||
@@ -94,55 +113,173 @@ export function createInstallMaestroBuildFunction(): BuildFunction {
|
||||
}
|
||||
|
||||
// IDB is only a requirement on macOS.
|
||||
if (
|
||||
const needsToInstallIdb =
|
||||
backend === 'maestro' &&
|
||||
global.runtimePlatform === BuildRuntimePlatform.DARWIN &&
|
||||
!(await isIdbInstalled({ env }))
|
||||
) {
|
||||
!(await isIdbInstalled({ env }));
|
||||
if (needsToInstallIdb) {
|
||||
logger.info('Installing IDB');
|
||||
await installIdbFromBrew({ logger, env });
|
||||
}
|
||||
|
||||
// Skip installing if the input sets a specific Maestro version to install
|
||||
// and it is already installed which happens when developing on a local computer.
|
||||
if (
|
||||
!currentMaestroVersion ||
|
||||
(requestedMaestroVersion && requestedMaestroVersion !== currentMaestroVersion)
|
||||
) {
|
||||
await installMaestro({
|
||||
version: requestedMaestroVersion,
|
||||
global,
|
||||
logger,
|
||||
env,
|
||||
});
|
||||
switch (backend) {
|
||||
case 'maestro':
|
||||
// Skip installing if the input sets a specific Maestro version to install
|
||||
// and it is already installed, either on a build image or a local computer.
|
||||
if (
|
||||
!currentMaestroVersion ||
|
||||
(requestedVersion && requestedVersion !== currentMaestroVersion)
|
||||
) {
|
||||
await installMaestro({ version: requestedVersion, global, logger, env });
|
||||
}
|
||||
break;
|
||||
case 'maestro-runner': {
|
||||
let maestroRunnerVersionToInstall = requestedVersion;
|
||||
const currentMaestroRunnerVersion = semver.coerce(currentMaestroVersion)?.version;
|
||||
const requestedMaestroRunnerVersion =
|
||||
requestedVersion && requestedVersion !== 'latest'
|
||||
? semver.valid(requestedVersion)
|
||||
: null;
|
||||
if (
|
||||
global.runtimePlatform === BuildRuntimePlatform.DARWIN &&
|
||||
((requestedMaestroRunnerVersion &&
|
||||
semver.gte(requestedMaestroRunnerVersion, '1.1.16')) ||
|
||||
requestedVersion === 'latest' ||
|
||||
(requestedVersion === undefined &&
|
||||
(!currentMaestroRunnerVersion || semver.gt(currentMaestroRunnerVersion, '1.1.15'))))
|
||||
) {
|
||||
const xcodeVersion = await getXcodeVersion({ env });
|
||||
|
||||
// maestro-runner 1.1.16 added `arch` to its xcodebuild destination. Xcode versions
|
||||
// below 26 reject that option, so use the last compatible maestro-runner version.
|
||||
if (semver.lt(xcodeVersion, '26.0.0')) {
|
||||
if (requestedMaestroRunnerVersion) {
|
||||
throw new UserError(
|
||||
'ERR_MAESTRO_INVALID_INPUT',
|
||||
`maestro-runner ${requestedVersion} is not compatible with Xcode ${xcodeVersion}. Use maestro-runner 1.1.15 or an Xcode 26+ image.`
|
||||
);
|
||||
}
|
||||
maestroRunnerVersionToInstall = '1.1.15';
|
||||
logger.info(
|
||||
`Xcode ${xcodeVersion} requires maestro-runner ${maestroRunnerVersionToInstall}.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
!currentMaestroVersion ||
|
||||
(maestroRunnerVersionToInstall &&
|
||||
maestroRunnerVersionToInstall !== currentMaestroVersion)
|
||||
) {
|
||||
await installMaestroRunner({
|
||||
version: maestroRunnerVersionToInstall,
|
||||
global,
|
||||
logger,
|
||||
env,
|
||||
});
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const maestroVersionResult = await asyncResult(getMaestroVersion({ env }));
|
||||
const maestroVersionResult = await asyncResult(getMaestroVersion({ env, backend }));
|
||||
if (!maestroVersionResult.ok) {
|
||||
logger.error(maestroVersionResult.reason, 'Failed to get Maestro version.');
|
||||
|
||||
throw new Error('Failed to ensure Maestro is installed.');
|
||||
throw new Error(`Failed to ensure ${backend} is installed.`);
|
||||
}
|
||||
|
||||
logger.info(`Maestro ${maestroVersionResult.value} is ready.`);
|
||||
logger.info(`${backend} ${maestroVersionResult.value} is ready.`);
|
||||
outputs.maestro_version.set(maestroVersionResult.value);
|
||||
|
||||
Datadog.distribution('eas.maestro.install', 1, {
|
||||
maestro_version: maestroVersionResult.value,
|
||||
maestro_backend: backend,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function getMaestroVersion({ env }: { env: BuildStepEnv }): Promise<string> {
|
||||
const { stdout } = await spawn('maestro', ['--version'], { stdio: 'pipe', env });
|
||||
// `maestro --version` can print an analytics notice to stdout before the version,
|
||||
// e.g. "Anonymous analytics enabled. To opt out, set MAESTRO_CLI_NO_ANALYTICS...\n2.0.10".
|
||||
// Take the last version-looking token: the real version is printed after the notice, so
|
||||
// this stays correct even if the notice itself contains a version-like string. Keeps the
|
||||
// step output and the eas.maestro.install metric tag clean. Best-effort only: fall back to
|
||||
// the raw output if none is found, so we never fail the build over a version string.
|
||||
const versions = stdout.match(/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?/g);
|
||||
return versions?.at(-1) ?? stdout.trim();
|
||||
async function getXcodeVersion({ env }: { env: BuildStepEnv }): Promise<string> {
|
||||
let stdout: string;
|
||||
try {
|
||||
({ stdout } = await spawn('xcodebuild', ['-version'], { stdio: 'pipe', env }));
|
||||
} catch (error) {
|
||||
throw new SystemError('Failed to get Xcode version', { cause: error });
|
||||
}
|
||||
|
||||
const xcodeVersion = semver.coerce(/^Xcode\s+(\S+)/m.exec(stdout)?.[1])?.version;
|
||||
if (!xcodeVersion) {
|
||||
throw new SystemError(`Failed to parse Xcode version from xcodebuild output: ${stdout.trim()}`);
|
||||
}
|
||||
return xcodeVersion;
|
||||
}
|
||||
|
||||
async function getMaestroVersion({
|
||||
env,
|
||||
backend,
|
||||
}: {
|
||||
env: BuildStepEnv;
|
||||
backend: MaestroBackend;
|
||||
}): Promise<string> {
|
||||
switch (backend) {
|
||||
case 'maestro': {
|
||||
const { stdout } = await spawn('maestro', ['--version'], { stdio: 'pipe', env });
|
||||
// `maestro --version` can print an analytics notice to stdout before the version,
|
||||
// e.g. "Anonymous analytics enabled. To opt out, set MAESTRO_CLI_NO_ANALYTICS...\n2.0.10".
|
||||
// Take the last version-looking token: the real version is printed after the notice.
|
||||
const versions = stdout.match(/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?/g);
|
||||
return versions?.at(-1) ?? stdout.trim();
|
||||
}
|
||||
case 'maestro-runner': {
|
||||
const { stdout } = await spawn('maestro-runner', ['--version'], { stdio: 'pipe', env });
|
||||
// maestro-runner prints build information after its version. The Go runtime version in
|
||||
// that output is also semver-shaped, so read only the prefixed runner version.
|
||||
return /^maestro-runner\s+(\S+)/m.exec(stdout)?.[1] ?? stdout.trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function installMaestroRunner({
|
||||
global,
|
||||
version,
|
||||
logger,
|
||||
env,
|
||||
}: {
|
||||
version?: string;
|
||||
logger: bunyan;
|
||||
global: BuildStepGlobalContext;
|
||||
env: BuildStepEnv;
|
||||
}): Promise<void> {
|
||||
logger.info('Fetching maestro-runner install script');
|
||||
const tempDirectory = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'install_maestro_runner'));
|
||||
try {
|
||||
const installMaestroRunnerScriptResponse = await fetch(
|
||||
'https://open.devicelab.dev/install/maestro-runner'
|
||||
);
|
||||
const installMaestroRunnerScript = await installMaestroRunnerScriptResponse.text();
|
||||
const scriptPath = path.join(tempDirectory, 'install_maestro_runner.sh');
|
||||
await fs.promises.writeFile(scriptPath, installMaestroRunnerScript, { mode: 0o777 });
|
||||
logger.info('Installing maestro-runner');
|
||||
assert(
|
||||
env.HOME,
|
||||
'Failed to infer directory to install maestro-runner in: $HOME environment variable is empty.'
|
||||
);
|
||||
await spawn(scriptPath, version && version !== 'latest' ? ['--version', version] : [], {
|
||||
logger,
|
||||
env,
|
||||
});
|
||||
const binDir = path.join(env.HOME, '.maestro-runner', 'bin');
|
||||
global.updateEnv({
|
||||
...global.env,
|
||||
PATH: `${binDir}:${global.env.PATH}`,
|
||||
});
|
||||
env.PATH = `${binDir}:${env.PATH}`;
|
||||
process.env.PATH = `${binDir}:${process.env.PATH}`;
|
||||
} finally {
|
||||
await fs.promises.rm(tempDirectory, { force: true, recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
async function installMaestro({
|
||||
@@ -186,10 +323,10 @@ async function installMaestro({
|
||||
const maestroBinDir = path.join(maestroDir, 'bin');
|
||||
global.updateEnv({
|
||||
...global.env,
|
||||
PATH: `${global.env.PATH}:${maestroBinDir}`,
|
||||
PATH: `${maestroBinDir}:${global.env.PATH}`,
|
||||
});
|
||||
env.PATH = `${env.PATH}:${maestroBinDir}`;
|
||||
process.env.PATH = `${process.env.PATH}:${maestroBinDir}`;
|
||||
env.PATH = `${maestroBinDir}:${env.PATH}`;
|
||||
process.env.PATH = `${maestroBinDir}:${process.env.PATH}`;
|
||||
} finally {
|
||||
await fs.promises.rm(tempDirectory, { force: true, recursive: true });
|
||||
}
|
||||
@@ -197,37 +334,64 @@ async function installMaestro({
|
||||
|
||||
async function isIdbInstalled({ env }: { env: BuildStepEnv }): Promise<boolean> {
|
||||
try {
|
||||
await spawn('idb', ['-h'], { ignoreStdio: true, env });
|
||||
await spawn('idb_companion', ['--version'], { ignoreStdio: true, env });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function installIdbFromBrew({
|
||||
export async function installIdbFromBrew({
|
||||
logger,
|
||||
env,
|
||||
}: {
|
||||
logger: bunyan;
|
||||
env: BuildStepEnv;
|
||||
}): Promise<void> {
|
||||
// Unfortunately our Mac images sometimes have two Homebrew
|
||||
// installations. We should use the ARM64 one, located in /opt/homebrew.
|
||||
const brewPath = '/opt/homebrew/bin/brew';
|
||||
const localEnv = {
|
||||
...env,
|
||||
HOMEBREW_NO_AUTO_UPDATE: '1',
|
||||
HOMEBREW_NO_INSTALL_CLEANUP: '1',
|
||||
};
|
||||
try {
|
||||
// Unfortunately our Mac images sometimes have two Homebrew
|
||||
// installations. We should use the ARM64 one, located in /opt/homebrew.
|
||||
const brewPath = '/opt/homebrew/bin/brew';
|
||||
const localEnv = {
|
||||
...env,
|
||||
HOMEBREW_NO_AUTO_UPDATE: '1',
|
||||
HOMEBREW_NO_INSTALL_CLEANUP: '1',
|
||||
};
|
||||
|
||||
await spawn(brewPath, ['tap', 'facebook/fb'], {
|
||||
env: localEnv,
|
||||
logger,
|
||||
});
|
||||
await spawn(brewPath, ['install', 'idb-companion'], {
|
||||
env: localEnv,
|
||||
logger,
|
||||
});
|
||||
logger.info('Tapping facebook/fb...');
|
||||
await spawn(brewPath, ['tap', 'facebook/fb'], {
|
||||
env: localEnv,
|
||||
logger,
|
||||
});
|
||||
|
||||
const brewRepo = await spawn(brewPath, ['--repo', 'facebook/fb'], {
|
||||
env: localEnv,
|
||||
});
|
||||
const tapPath = brewRepo.stdout.trim();
|
||||
|
||||
// c0386793f59da10c619787f2aa18d938ef1d69c9 is hash for 1.1.8 release,
|
||||
// last known compatible version + post_install fix.
|
||||
const gitSha = 'c0386793f59da10c619787f2aa18d938ef1d69c9';
|
||||
logger.info('Checking out facebook/fb at [email protected]...');
|
||||
await spawn('git', ['fetch', 'origin', gitSha], {
|
||||
cwd: tapPath,
|
||||
logger,
|
||||
});
|
||||
await spawn('git', ['checkout', gitSha], {
|
||||
cwd: tapPath,
|
||||
logger,
|
||||
});
|
||||
|
||||
logger.info('Installing idb_companion v1.1.8...');
|
||||
await spawn(brewPath, ['install', 'facebook/fb/idb-companion'], {
|
||||
env: localEnv,
|
||||
logger,
|
||||
});
|
||||
} catch (err) {
|
||||
throw new SystemError('Failed to install idb-companion required for Maestro to run.', {
|
||||
cause: err,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function isJavaInstalled({ env }: { env: BuildStepEnv }): Promise<boolean> {
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { UserError } from '@expo/eas-build-job';
|
||||
import { BuildStepEnv } from '@expo/steps';
|
||||
import { z } from 'zod';
|
||||
|
||||
export const MaestroBackendSchema = z.enum(['maestro', 'maestro-runner']).default('maestro');
|
||||
|
||||
export type MaestroBackend = z.output<typeof MaestroBackendSchema>;
|
||||
|
||||
export function resolveMaestroBackend({
|
||||
input,
|
||||
env,
|
||||
}: {
|
||||
input: unknown;
|
||||
env: BuildStepEnv;
|
||||
}): MaestroBackend {
|
||||
const result = MaestroBackendSchema.safeParse(input || env.EAS_MAESTRO_BACKEND || undefined);
|
||||
if (!result.success) {
|
||||
throw new UserError(
|
||||
'ERR_MAESTRO_INVALID_INPUT',
|
||||
'backend and EAS_MAESTRO_BACKEND must be either "maestro" or "maestro-runner".',
|
||||
{ cause: result.error }
|
||||
);
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { asyncResult } from '@expo/results';
|
||||
import { XMLBuilder, XMLParser, XMLValidator } from 'fast-xml-parser';
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
import { z } from 'zod';
|
||||
|
||||
export interface MaestroFlowResult {
|
||||
name: string;
|
||||
@@ -34,10 +35,16 @@ const xmlParser = new XMLParser({
|
||||
isArray: name => ['testsuite', 'testcase', 'property'].includes(name),
|
||||
});
|
||||
|
||||
// A `file=` attribute counts as present only when it is a non-empty string.
|
||||
// Official Maestro writes the flow path as a `file=` testcase attribute. maestro-runner writes
|
||||
// the same value as a `<property name="file" value="..."/>` child.
|
||||
function fileAttrOf(tc: any): string | undefined {
|
||||
const f = tc?.['@_file'];
|
||||
return typeof f === 'string' && f.length > 0 ? f : undefined;
|
||||
if (typeof f === 'string' && f.length > 0) {
|
||||
return f;
|
||||
}
|
||||
const properties: { '@_name'?: unknown; '@_value'?: unknown }[] = tc?.properties?.property ?? [];
|
||||
const fileProperty = properties.find(property => property['@_name'] === 'file')?.['@_value'];
|
||||
return typeof fileProperty === 'string' && fileProperty.length > 0 ? fileProperty : undefined;
|
||||
}
|
||||
|
||||
function parseJUnitContent(content: string): JUnitTestCaseResult[] {
|
||||
@@ -62,26 +69,46 @@ function parseJUnitContent(content: string): JUnitTestCaseResult[] {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Standard JUnit marks skipped tests with a <skipped/> child (no failure/error). Exclude
|
||||
// them so they aren't miscounted as passed, matching the report.json path which drops
|
||||
// skipped flows.
|
||||
if (tc.skipped != null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const file = fileAttrOf(tc);
|
||||
|
||||
const timeStr = tc['@_time'];
|
||||
const timeSeconds = timeStr ? parseFloat(timeStr) : 0;
|
||||
const duration = Number.isFinite(timeSeconds) ? Math.round(timeSeconds * 1000) : 0;
|
||||
|
||||
const status: 'passed' | 'failed' = tc['@_status'] === 'SUCCESS' ? 'passed' : 'failed';
|
||||
// maestro-runner puts the real error in the `message` attribute and the command
|
||||
// label (e.g. `tapOn`) in the body; official Maestro only writes the body. Prefer
|
||||
// `@_message` and fall back to `#text` so both stay correct.
|
||||
const failureText =
|
||||
tc.failure != null
|
||||
? typeof tc.failure === 'string'
|
||||
? tc.failure
|
||||
: (tc.failure?.['#text'] ?? null)
|
||||
: (tc.failure?.['@_message'] ?? tc.failure?.['#text'] ?? null)
|
||||
: null;
|
||||
const errorText =
|
||||
tc.error != null
|
||||
? typeof tc.error === 'string'
|
||||
? tc.error
|
||||
: (tc.error?.['#text'] ?? null)
|
||||
: (tc.error?.['@_message'] ?? tc.error?.['#text'] ?? null)
|
||||
: null;
|
||||
const errorMessage: string | null = failureText ?? errorText ?? null;
|
||||
// Official Maestro uses status="SUCCESS". maestro-runner uses standard JUnit semantics:
|
||||
// a testcase passes when it has no failure or error child.
|
||||
const statusAttribute = tc['@_status'];
|
||||
const status: 'passed' | 'failed' =
|
||||
typeof statusAttribute === 'string'
|
||||
? statusAttribute === 'SUCCESS'
|
||||
? 'passed'
|
||||
: 'failed'
|
||||
: tc.failure == null && tc.error == null
|
||||
? 'passed'
|
||||
: 'failed';
|
||||
|
||||
const rawProperties: { '@_name': string; '@_value': string }[] =
|
||||
tc.properties?.property ?? [];
|
||||
@@ -176,6 +203,69 @@ async function fileExists(absPath: string): Promise<boolean> {
|
||||
return (await asyncResult(fs.stat(absPath))).ok;
|
||||
}
|
||||
|
||||
// maestro-runner writes report.json as the source of truth for a run. Use it for runner control
|
||||
// flow because sourceFile preserves the exact flow path, while older runner JUnit reports flatten
|
||||
// it to a basename. Keep only passed and failed flows so the result matches Maestro JUnit reports,
|
||||
// which do not include skipped flows.
|
||||
const MaestroRunnerRecordedFlowSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
sourceFile: z.string().min(1),
|
||||
status: z.enum(['passed', 'failed']),
|
||||
});
|
||||
const MaestroRunnerReportSchema = z.object({
|
||||
flows: z
|
||||
.array(
|
||||
z.discriminatedUnion('status', [
|
||||
MaestroRunnerRecordedFlowSchema,
|
||||
z.object({ status: z.literal('skipped') }),
|
||||
])
|
||||
)
|
||||
.transform(flows =>
|
||||
flows.filter(
|
||||
(flow): flow is z.infer<typeof MaestroRunnerRecordedFlowSchema> => flow.status !== 'skipped'
|
||||
)
|
||||
),
|
||||
});
|
||||
|
||||
type MaestroRunnerReport = z.infer<typeof MaestroRunnerReportSchema>;
|
||||
|
||||
export async function parseFailedFlowsFromMaestroRunnerReport(args: {
|
||||
reportDirectory: string;
|
||||
workingDirectory: string;
|
||||
}): Promise<string[] | null> {
|
||||
const report = await parseMaestroRunnerReport(args.reportDirectory);
|
||||
if (report === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const failedPaths = [
|
||||
...new Set(report.flows.filter(flow => flow.status === 'failed').map(flow => flow.sourceFile)),
|
||||
];
|
||||
if (failedPaths.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const flowPath of failedPaths) {
|
||||
if (!(await fileExists(path.resolve(args.workingDirectory, flowPath)))) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return failedPaths;
|
||||
}
|
||||
|
||||
export async function parseMaestroRunnerReport(
|
||||
reportDirectory: string
|
||||
): Promise<MaestroRunnerReport | null> {
|
||||
let report: unknown;
|
||||
try {
|
||||
report = JSON.parse(await fs.readFile(path.join(reportDirectory, 'report.json'), 'utf8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const result = MaestroRunnerReportSchema.safeParse(report);
|
||||
return result.success ? result.data : null;
|
||||
}
|
||||
|
||||
// Group by `file=` so two same-named flows in different files stay separate.
|
||||
export async function parseMaestroResultsFromFileAttrs(
|
||||
junitDirectory: string
|
||||
|
||||
@@ -2,6 +2,9 @@ import { bunyan } from '@expo/logger';
|
||||
import { type Dirent } from 'fs';
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { Sentry } from '../../sentry';
|
||||
|
||||
export interface ParsedFailureScreenshot {
|
||||
flowName: string;
|
||||
@@ -133,6 +136,156 @@ export async function harvestFailureScreenshotsAsync(args: {
|
||||
return [...legacyShots, ...dedupeBundleShotsByFlowName(bundleShots)];
|
||||
}
|
||||
|
||||
const MaestroRunnerCommandSchema = z.object({
|
||||
status: z.string().optional(),
|
||||
artifacts: z
|
||||
.object({
|
||||
screenshotBefore: z.string().optional(),
|
||||
screenshotAfter: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
get subCommands() {
|
||||
return z.array(MaestroRunnerCommandSchema).optional();
|
||||
},
|
||||
});
|
||||
type MaestroRunnerCommand = z.infer<typeof MaestroRunnerCommandSchema>;
|
||||
|
||||
const MaestroRunnerFlowDetailSchema = z.object({
|
||||
commands: z.array(MaestroRunnerCommandSchema).optional(),
|
||||
});
|
||||
|
||||
const MaestroRunnerScreenshotReportSchema = z.object({
|
||||
flows: z
|
||||
.array(
|
||||
z.object({
|
||||
name: z.string().optional(),
|
||||
status: z.string().optional(),
|
||||
dataFile: z.string().optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
// maestro-runner records failure screenshot paths in its report JSON instead of using the
|
||||
// official Maestro debug-directory layout. Never throws, so screenshots cannot change the test
|
||||
// result.
|
||||
export async function harvestMaestroRunnerFailureScreenshotsAsync(args: {
|
||||
reportDirectory: string;
|
||||
capturedSinceMs: number;
|
||||
attemptIndex: number;
|
||||
logger: bunyan;
|
||||
}): Promise<HarvestedScreenshot[]> {
|
||||
let report: unknown;
|
||||
try {
|
||||
report = JSON.parse(await fs.readFile(path.join(args.reportDirectory, 'report.json'), 'utf8'));
|
||||
} catch (err: any) {
|
||||
args.logger.info(
|
||||
{ err },
|
||||
`Skipping maestro-runner screenshot harvest: cannot read ${args.reportDirectory}.`
|
||||
);
|
||||
return [];
|
||||
}
|
||||
|
||||
const parsedReport = MaestroRunnerScreenshotReportSchema.safeParse(report);
|
||||
if (!parsedReport.success) {
|
||||
args.logger.warn(
|
||||
{ err: parsedReport.error },
|
||||
`Skipping maestro-runner screenshot harvest: unexpected report.json shape in ${args.reportDirectory}.`
|
||||
);
|
||||
Sentry.capture('maestro-runner report.json failed schema validation', parsedReport.error);
|
||||
return [];
|
||||
}
|
||||
const flows = parsedReport.data.flows ?? [];
|
||||
|
||||
const shots: HarvestedScreenshot[] = [];
|
||||
for (const { name, status, dataFile } of flows) {
|
||||
if (status !== 'failed' || !name || !dataFile) {
|
||||
continue;
|
||||
}
|
||||
const flowDataPath = resolvePathInsideDirectory(args.reportDirectory, dataFile);
|
||||
if (!flowDataPath) {
|
||||
args.logger.info(`Skipping maestro-runner flow data outside the report directory.`);
|
||||
continue;
|
||||
}
|
||||
|
||||
let screenshotPath: string | undefined;
|
||||
try {
|
||||
const detail = MaestroRunnerFlowDetailSchema.safeParse(
|
||||
JSON.parse(await fs.readFile(flowDataPath, 'utf8'))
|
||||
);
|
||||
if (!detail.success) {
|
||||
args.logger.warn(
|
||||
{ err: detail.error },
|
||||
`Skipping malformed maestro-runner flow data ${flowDataPath}.`
|
||||
);
|
||||
Sentry.capture('maestro-runner flow data failed schema validation', detail.error);
|
||||
continue;
|
||||
}
|
||||
screenshotPath = findFailedMaestroRunnerScreenshot(detail.data.commands ?? []);
|
||||
} catch (err: any) {
|
||||
args.logger.info({ err }, `Skipping unreadable maestro-runner flow data ${flowDataPath}.`);
|
||||
continue;
|
||||
}
|
||||
if (!screenshotPath) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const fileAbsPath = resolvePathInsideDirectory(args.reportDirectory, screenshotPath);
|
||||
if (!fileAbsPath) {
|
||||
args.logger.info(`Skipping maestro-runner screenshot outside the report directory.`);
|
||||
continue;
|
||||
}
|
||||
let capturedAtMs: number;
|
||||
try {
|
||||
capturedAtMs = Math.round((await fs.stat(fileAbsPath)).mtimeMs);
|
||||
} catch (err: any) {
|
||||
args.logger.info({ err }, `Skipping unreadable screenshot ${fileAbsPath}.`);
|
||||
continue;
|
||||
}
|
||||
if (capturedAtMs < args.capturedSinceMs) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const flowName = normalizeFlowName(name);
|
||||
shots.push({
|
||||
fileAbsPath,
|
||||
displayName: `Failure Screenshot: ${flowName} (attempt ${args.attemptIndex + 1})`,
|
||||
metadata: {
|
||||
kind: 'maestro-test-screenshot',
|
||||
flowName,
|
||||
attemptIndex: args.attemptIndex,
|
||||
capturedAtMs,
|
||||
},
|
||||
});
|
||||
}
|
||||
return shots;
|
||||
}
|
||||
|
||||
function findFailedMaestroRunnerScreenshot(
|
||||
commands: readonly MaestroRunnerCommand[]
|
||||
): string | undefined {
|
||||
for (const command of commands) {
|
||||
if (command.status !== 'failed') {
|
||||
continue;
|
||||
}
|
||||
const nested = findFailedMaestroRunnerScreenshot(command.subCommands ?? []);
|
||||
const screenshot =
|
||||
nested ?? command.artifacts?.screenshotAfter ?? command.artifacts?.screenshotBefore;
|
||||
if (screenshot) {
|
||||
return screenshot;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function resolvePathInsideDirectory(directory: string, relativePath: string): string | null {
|
||||
const candidate = path.resolve(directory, relativePath);
|
||||
const relative = path.relative(directory, candidate);
|
||||
return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)
|
||||
? candidate
|
||||
: null;
|
||||
}
|
||||
|
||||
// Maestro >= 2.7.0: resolve a bundle dir to its owning failed flow and return that flow's failure
|
||||
// screenshot — the highest-numbered step in `screenshots/`. A required failure halts the flow, so
|
||||
// the failed step is normally the last (highest-numbered) captured step; earlier warned steps have
|
||||
|
||||
@@ -13,6 +13,7 @@ import os from 'os';
|
||||
import path from 'path';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { MaestroBackend, resolveMaestroBackend } from './maestroBackend';
|
||||
import { buildFlowNameToPathMap } from './maestroFlowDiscovery';
|
||||
import {
|
||||
copyLatestAttemptXml,
|
||||
@@ -21,12 +22,15 @@ import {
|
||||
parseFailedFlowNamesFromJUnitFile,
|
||||
parseFailedFlowsFromFileAttrs,
|
||||
parseFailedFlowsFromJUnit,
|
||||
parseFailedFlowsFromMaestroRunnerReport,
|
||||
parseJUnitTestCases,
|
||||
parseMaestroRunnerReport,
|
||||
} from './maestroResultParser';
|
||||
import {
|
||||
type HarvestedScreenshot,
|
||||
computePureFailureFlowNames,
|
||||
harvestFailureScreenshotsAsync,
|
||||
harvestMaestroRunnerFailureScreenshotsAsync,
|
||||
selectFailureScreenshots,
|
||||
} from './maestroScreenshots';
|
||||
import { CustomBuildContext } from '../../customBuildContext';
|
||||
@@ -35,6 +39,7 @@ import { sleepAsync } from '../../utils/retry';
|
||||
const FlowPathSchema = z.array(z.string().min(1)).min(1);
|
||||
const RetriesSchema = z.number().int().min(0).default(0);
|
||||
const ShardsSchema = z.number().int().min(1).optional();
|
||||
const AndroidConnectionModeSchema = z.enum(['adb', 'dadb']).default('adb');
|
||||
|
||||
function parseInput<S extends z.ZodTypeAny>(
|
||||
schema: S,
|
||||
@@ -61,35 +66,58 @@ function isFilesystemError(err: any): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
// `outputPath: null` means "let maestro pick" (no --output flag). Junit and
|
||||
// other declared formats pass an explicit path so downstream upload steps
|
||||
// know where to find the result.
|
||||
function buildMaestroArgs(args: {
|
||||
flow_path: string[];
|
||||
outputPath: string | null;
|
||||
output_format: string | undefined;
|
||||
function buildMaestroArgs({
|
||||
backend,
|
||||
platform,
|
||||
flowPaths,
|
||||
output,
|
||||
outputFormat,
|
||||
shards,
|
||||
includeTags,
|
||||
excludeTags,
|
||||
}: {
|
||||
backend: MaestroBackend;
|
||||
platform: 'ios' | 'android';
|
||||
flowPaths: string[];
|
||||
output: string | null;
|
||||
outputFormat: string | undefined;
|
||||
shards: number | undefined;
|
||||
include_tags: string | undefined;
|
||||
exclude_tags: string | undefined;
|
||||
}): string[] {
|
||||
const out: string[] = ['test'];
|
||||
if (args.output_format) {
|
||||
out.push(`--format=${args.output_format.toUpperCase()}`);
|
||||
includeTags: string | undefined;
|
||||
excludeTags: string | undefined;
|
||||
}): { executable: MaestroBackend; args: string[] } {
|
||||
switch (backend) {
|
||||
case 'maestro': {
|
||||
const args = ['test'];
|
||||
if (outputFormat) {
|
||||
args.push(`--format=${outputFormat.toUpperCase()}`);
|
||||
}
|
||||
if (output) {
|
||||
args.push(`--output=${output}`);
|
||||
}
|
||||
if (shards !== undefined) {
|
||||
args.push(`--shard-split=${shards}`);
|
||||
}
|
||||
if (includeTags) {
|
||||
args.push(`--include-tags=${includeTags}`);
|
||||
}
|
||||
if (excludeTags) {
|
||||
args.push(`--exclude-tags=${excludeTags}`);
|
||||
}
|
||||
args.push(...flowPaths);
|
||||
return { executable: 'maestro', args };
|
||||
}
|
||||
case 'maestro-runner': {
|
||||
const args = [`--platform=${platform}`, 'test', `--output=${output}`, '--flatten'];
|
||||
if (includeTags) {
|
||||
args.push(`--include-tags=${includeTags}`);
|
||||
}
|
||||
if (excludeTags) {
|
||||
args.push(`--exclude-tags=${excludeTags}`);
|
||||
}
|
||||
args.push(...flowPaths);
|
||||
return { executable: 'maestro-runner', args };
|
||||
}
|
||||
}
|
||||
if (args.outputPath) {
|
||||
out.push(`--output=${args.outputPath}`);
|
||||
}
|
||||
if (args.shards !== undefined) {
|
||||
out.push(`--shard-split=${args.shards}`);
|
||||
}
|
||||
if (args.include_tags) {
|
||||
out.push(`--include-tags=${args.include_tags}`);
|
||||
}
|
||||
if (args.exclude_tags) {
|
||||
out.push(`--exclude-tags=${args.exclude_tags}`);
|
||||
}
|
||||
out.push(...args.flow_path);
|
||||
return out;
|
||||
}
|
||||
|
||||
export function createMaestroTestsBuildFunction(ctx: CustomBuildContext): BuildFunction {
|
||||
@@ -143,6 +171,16 @@ export function createMaestroTestsBuildFunction(ctx: CustomBuildContext): BuildF
|
||||
required: false,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'android_connection_mode',
|
||||
required: false,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'backend',
|
||||
required: false,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
],
|
||||
outputProviders: [
|
||||
BuildStepOutput.createProvider({ id: 'junit_report_directory', required: true }),
|
||||
@@ -180,7 +218,7 @@ export function createMaestroTestsBuildFunction(ctx: CustomBuildContext): BuildF
|
||||
// Public docs (EAS workflows pre-packaged-jobs) document
|
||||
// `${MAESTRO_TESTS_DIR}` for users to save screenshots/recordings into
|
||||
// the uploaded dir.
|
||||
const spawnEnv = { ...env, MAESTRO_TESTS_DIR: testsDirectory };
|
||||
const spawnEnv: NodeJS.ProcessEnv = { ...env, MAESTRO_TESTS_DIR: testsDirectory };
|
||||
|
||||
// Outputs are published BEFORE any throw below so downstream
|
||||
// `if: always()` upload steps still see populated values when this
|
||||
@@ -191,6 +229,14 @@ export function createMaestroTestsBuildFunction(ctx: CustomBuildContext): BuildF
|
||||
outputs.final_report_path.set(finalReportPath);
|
||||
}
|
||||
|
||||
// Resolved after the output assignments above: an invalid backend input or
|
||||
// EAS_MAESTRO_BACKEND throws, and downstream `if: always()` upload steps still
|
||||
// need the outputs interpolated.
|
||||
const backend = resolveMaestroBackend({
|
||||
input: inputs.backend.value,
|
||||
env,
|
||||
});
|
||||
|
||||
const flowPaths = parseInput(
|
||||
FlowPathSchema,
|
||||
inputs.flow_path.value,
|
||||
@@ -206,6 +252,25 @@ export function createMaestroTestsBuildFunction(ctx: CustomBuildContext): BuildF
|
||||
inputs.shards.value,
|
||||
'shards must be a positive integer.'
|
||||
);
|
||||
const androidConnectionMode = parseInput(
|
||||
AndroidConnectionModeSchema,
|
||||
inputs.android_connection_mode.value ||
|
||||
env.EAS_MAESTRO_ANDROID_CONNECTION_MODE ||
|
||||
undefined,
|
||||
'android_connection_mode and EAS_MAESTRO_ANDROID_CONNECTION_MODE must be either "adb" or "dadb".'
|
||||
);
|
||||
if (backend === 'maestro-runner' && shards !== undefined && shards > 1) {
|
||||
throw new UserError(
|
||||
'ERR_MAESTRO_INVALID_INPUT',
|
||||
'maestro-runner does not support EAS Maestro test sharding. Remove shards or set it to 1.'
|
||||
);
|
||||
}
|
||||
if (backend === 'maestro-runner' && outputFormat !== undefined && outputFormat !== 'junit') {
|
||||
throw new UserError(
|
||||
'ERR_MAESTRO_INVALID_INPUT',
|
||||
`maestro-runner only supports the "junit" output_format, but received "${outputFormat}".`
|
||||
);
|
||||
}
|
||||
const retryFailedOnly = inputs.retry_failed_only.value as boolean;
|
||||
|
||||
try {
|
||||
@@ -214,7 +279,7 @@ export function createMaestroTestsBuildFunction(ctx: CustomBuildContext): BuildF
|
||||
throw new SystemError('Failed to create JUnit report directory', { cause: err });
|
||||
}
|
||||
|
||||
// Legacy-only (Maestro < 2.6.0 reports carry no `file=` attribute): the
|
||||
// Official Maestro legacy-only (Maestro < 2.6.0 reports carry no `file=` attribute): the
|
||||
// flow scan is built lazily in the retry branch below and memoized so
|
||||
// retries share one scan. Never runs when the report has `file=`.
|
||||
let nameToPathPromise: Promise<Map<string, string> | null> | undefined;
|
||||
@@ -224,38 +289,96 @@ export function createMaestroTestsBuildFunction(ctx: CustomBuildContext): BuildF
|
||||
// numeric err.status → maestro exited non-zero → retry.
|
||||
// else (signal-only, OOM kill, unknown) → infra → SystemError, never
|
||||
// downgraded to "tests failed".
|
||||
// Retry-failed-only (junit mode): after a failed attempt, subset to the failing
|
||||
// flows. The failed-flow parsers return null when the JUnit cannot be
|
||||
// trusted; we then fall through to dumb retry (re-run everything).
|
||||
// Retry-failed-only: after a failed attempt, subset to the failing flows. The
|
||||
// failed-flow parsers return null when a report cannot be trusted; we then fall
|
||||
// through to dumb retry (re-run everything).
|
||||
let flowsToRun: string[] = flowPaths;
|
||||
let lastAttemptExitCode: number | null = null;
|
||||
const harvested: HarvestedScreenshot[] = [];
|
||||
const reportDirectories = backend === 'maestro' ? [junitReportDirectory] : [];
|
||||
|
||||
const totalAttempts = retries + 1;
|
||||
if (
|
||||
backend === 'maestro-runner' &&
|
||||
platform === 'android' &&
|
||||
androidConnectionMode === 'dadb'
|
||||
) {
|
||||
logger.info('maestro-runner does not support DADB. Using the default ADB connection.');
|
||||
}
|
||||
if (backend === 'maestro' && platform === 'android' && androidConnectionMode === 'dadb') {
|
||||
try {
|
||||
const adbOverrideDirectoryPath = await fs.mkdtemp(
|
||||
path.join(os.tmpdir(), 'maestro-tests-adb-override-')
|
||||
);
|
||||
await fs.writeFile(path.join(adbOverrideDirectoryPath, 'adb'), '#!/bin/sh\nexit 1\n', {
|
||||
mode: 0o755,
|
||||
});
|
||||
|
||||
// DADB starts an ADB server when it can find an adb binary. Stop the existing
|
||||
// server first, then make only the Maestro process find the failing shim.
|
||||
try {
|
||||
await spawn('adb', ['kill-server'], { env: { ...spawnEnv }, logger, signal });
|
||||
logger.info(
|
||||
'Using a direct DADB connection for Android Maestro tests after stopping the ADB server.'
|
||||
);
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ err },
|
||||
'Using a direct DADB connection for Android Maestro tests, but failed to stop the ADB server.'
|
||||
);
|
||||
}
|
||||
spawnEnv.PATH = spawnEnv.PATH
|
||||
? `${adbOverrideDirectoryPath}${path.delimiter}${spawnEnv.PATH}`
|
||||
: adbOverrideDirectoryPath;
|
||||
} catch (err) {
|
||||
// Intentionally skip cleanup because the worker is disposable.
|
||||
throw new SystemError('Failed to enable direct DADB connection for Maestro', {
|
||||
cause: err,
|
||||
});
|
||||
}
|
||||
// Do not restart ADB or remove the override. This keeps Maestro in direct DADB mode.
|
||||
}
|
||||
|
||||
for (let attempt = 0; attempt <= retries; attempt++) {
|
||||
// maestro-runner writes its JUnit report and screenshot metadata to this directory.
|
||||
const runnerOutputDirectory = path.join(
|
||||
testsDirectory,
|
||||
`${platform}-maestro-runner-attempt-${attempt}`
|
||||
);
|
||||
const outputPath =
|
||||
outputFormat === 'junit'
|
||||
? path.join(junitReportDirectory, `${platform}-maestro-junit-attempt-${attempt}.xml`)
|
||||
: outputFormat
|
||||
: backend === 'maestro' && outputFormat
|
||||
? path.join(testsDirectory, `${platform}-maestro-${outputFormat}.${outputFormat}`)
|
||||
: null;
|
||||
|
||||
const maestroArgs = buildMaestroArgs({
|
||||
flow_path: flowsToRun,
|
||||
outputPath,
|
||||
output_format: outputFormat,
|
||||
const { executable, args: maestroArgs } = buildMaestroArgs({
|
||||
backend,
|
||||
platform,
|
||||
flowPaths: flowsToRun,
|
||||
output: backend === 'maestro-runner' ? runnerOutputDirectory : outputPath,
|
||||
outputFormat,
|
||||
shards,
|
||||
include_tags: includeTags,
|
||||
exclude_tags: excludeTags,
|
||||
includeTags,
|
||||
excludeTags,
|
||||
});
|
||||
logger.info(
|
||||
`Running maestro (attempt ${attempt + 1}/${totalAttempts}): maestro ${maestroArgs.join(' ')}`
|
||||
`Running ${executable} (attempt ${attempt + 1}/${totalAttempts}): ${executable} ${maestroArgs.join(' ')}`
|
||||
);
|
||||
|
||||
// The runner output directory is deterministic and can survive a prior run; clear it
|
||||
// best-effort so a crash before it writes fresh output can't resurrect stale results.
|
||||
if (backend === 'maestro-runner') {
|
||||
try {
|
||||
await fs.rm(runnerOutputDirectory, { recursive: true, force: true });
|
||||
} catch (err) {
|
||||
logger.warn({ err }, `Failed to clear ${runnerOutputDirectory} before the attempt.`);
|
||||
}
|
||||
}
|
||||
|
||||
const attemptStartedAtMs = Date.now();
|
||||
|
||||
try {
|
||||
await spawn('maestro', maestroArgs, {
|
||||
await spawn(executable, maestroArgs, {
|
||||
cwd: stepCtx.workingDirectory,
|
||||
env: spawnEnv,
|
||||
logger,
|
||||
@@ -264,56 +387,108 @@ export function createMaestroTestsBuildFunction(ctx: CustomBuildContext): BuildF
|
||||
lastAttemptExitCode = 0;
|
||||
} catch (err: any) {
|
||||
if (err && (err.code === 'ENOENT' || err.code === 'EACCES')) {
|
||||
throw new SystemError('Failed to invoke maestro', { cause: err });
|
||||
throw new SystemError(`Failed to invoke ${executable}`, { cause: err });
|
||||
}
|
||||
if (err && typeof err.status === 'number') {
|
||||
lastAttemptExitCode = err.status;
|
||||
} else {
|
||||
throw new SystemError('Unexpected spawn failure invoking maestro', { cause: err });
|
||||
throw new SystemError(`Unexpected spawn failure invoking ${executable}`, {
|
||||
cause: err,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// maestro-runner writes a report directory. Copy its JUnit file into the existing
|
||||
// per-attempt directory so retry parsing and final report merging remain shared.
|
||||
if (backend === 'maestro-runner' && outputPath) {
|
||||
try {
|
||||
await fs.copyFile(path.join(runnerOutputDirectory, 'junit-report.xml'), outputPath);
|
||||
} catch (err: any) {
|
||||
logger.warn(
|
||||
{ err },
|
||||
`Failed to collect the maestro-runner JUnit report for attempt ${attempt + 1}.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (backend === 'maestro-runner') {
|
||||
reportDirectories.push(runnerOutputDirectory);
|
||||
}
|
||||
|
||||
// Harvest this attempt's failure screenshots before any retry subsetting. Gated on
|
||||
// junit: test-case-result rows (and therefore the summary icons) only exist for junit
|
||||
// runs, so harvesting other formats would just create orphan artifacts the website hides.
|
||||
if (outputFormat === 'junit') {
|
||||
const failedFlowNames = outputPath
|
||||
? await parseFailedFlowNamesFromJUnitFile(outputPath)
|
||||
: new Set<string>();
|
||||
harvested.push(
|
||||
...(await harvestFailureScreenshotsAsync({
|
||||
testsDirectory,
|
||||
capturedSinceMs: attemptStartedAtMs,
|
||||
attemptIndex: attempt,
|
||||
failedFlowNames,
|
||||
logger,
|
||||
}))
|
||||
);
|
||||
let screenshots: HarvestedScreenshot[];
|
||||
switch (backend) {
|
||||
case 'maestro': {
|
||||
const failedFlowNames = outputPath
|
||||
? await parseFailedFlowNamesFromJUnitFile(outputPath)
|
||||
: new Set<string>();
|
||||
screenshots = await harvestFailureScreenshotsAsync({
|
||||
testsDirectory,
|
||||
capturedSinceMs: attemptStartedAtMs,
|
||||
attemptIndex: attempt,
|
||||
failedFlowNames,
|
||||
logger,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'maestro-runner':
|
||||
screenshots = await harvestMaestroRunnerFailureScreenshotsAsync({
|
||||
reportDirectory: runnerOutputDirectory,
|
||||
capturedSinceMs: attemptStartedAtMs,
|
||||
attemptIndex: attempt,
|
||||
logger,
|
||||
});
|
||||
break;
|
||||
}
|
||||
harvested.push(...screenshots);
|
||||
}
|
||||
|
||||
if (lastAttemptExitCode === 0 || attempt === retries) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (retryFailedOnly && outputFormat === 'junit' && outputPath) {
|
||||
if (
|
||||
retryFailedOnly &&
|
||||
(backend === 'maestro-runner' || (outputFormat === 'junit' && outputPath))
|
||||
) {
|
||||
let failed: string[] | null;
|
||||
if (await junitFileHasFileAttrs(outputPath)) {
|
||||
failed = await parseFailedFlowsFromFileAttrs({
|
||||
junitFile: outputPath,
|
||||
workingDirectory: stepCtx.workingDirectory,
|
||||
});
|
||||
} else {
|
||||
// Legacy (Maestro < 2.6.0): map failed testcase names back to flow
|
||||
// paths via the flow-file scan. DELETE this arm once the fleet is
|
||||
// on >= 2.6.0.
|
||||
const nameToPath = await (nameToPathPromise ??= buildFlowNameToPathMap({
|
||||
inputFlowPaths: flowPaths,
|
||||
projectRoot: stepCtx.workingDirectory,
|
||||
logger,
|
||||
}));
|
||||
failed = nameToPath
|
||||
? await parseFailedFlowsFromJUnit({ junitFile: outputPath, nameToPath })
|
||||
: null;
|
||||
switch (backend) {
|
||||
case 'maestro-runner':
|
||||
failed = await parseFailedFlowsFromMaestroRunnerReport({
|
||||
reportDirectory: runnerOutputDirectory,
|
||||
workingDirectory: stepCtx.workingDirectory,
|
||||
});
|
||||
break;
|
||||
case 'maestro':
|
||||
if (!outputPath) {
|
||||
failed = null;
|
||||
break;
|
||||
}
|
||||
if (await junitFileHasFileAttrs(outputPath)) {
|
||||
failed = await parseFailedFlowsFromFileAttrs({
|
||||
junitFile: outputPath,
|
||||
workingDirectory: stepCtx.workingDirectory,
|
||||
});
|
||||
break;
|
||||
}
|
||||
// Legacy (Maestro < 2.6.0): map failed testcase names back to flow
|
||||
// paths via the flow-file scan. DELETE this arm once the fleet is
|
||||
// on >= 2.6.0.
|
||||
const nameToPath = await (nameToPathPromise ??= buildFlowNameToPathMap({
|
||||
inputFlowPaths: flowPaths,
|
||||
projectRoot: stepCtx.workingDirectory,
|
||||
logger,
|
||||
}));
|
||||
failed = nameToPath
|
||||
? await parseFailedFlowsFromJUnit({
|
||||
junitFile: outputPath,
|
||||
nameToPath,
|
||||
})
|
||||
: null;
|
||||
break;
|
||||
}
|
||||
if (failed !== null && failed.length > 0) {
|
||||
flowsToRun = failed;
|
||||
@@ -366,7 +541,13 @@ export function createMaestroTestsBuildFunction(ctx: CustomBuildContext): BuildF
|
||||
// Upload before the ERR_MAESTRO_TESTS_FAILED throw below so fully-failed runs (which need
|
||||
// screenshots most) still upload. Harvest only ran for junit, so guard the same way.
|
||||
if (outputFormat === 'junit') {
|
||||
await uploadFailureScreenshotsAsync({ harvested, junitReportDirectory, ctx, logger });
|
||||
await uploadFailureScreenshotsAsync({
|
||||
harvested,
|
||||
backend,
|
||||
reportDirectories,
|
||||
ctx,
|
||||
logger,
|
||||
});
|
||||
}
|
||||
|
||||
// The retry loop exits via success (0), numeric status (retryable),
|
||||
@@ -387,12 +568,14 @@ export function createMaestroTestsBuildFunction(ctx: CustomBuildContext): BuildF
|
||||
// the maestro test result. Caller guards on junit (harvest only runs for junit).
|
||||
async function uploadFailureScreenshotsAsync({
|
||||
harvested,
|
||||
junitReportDirectory,
|
||||
backend,
|
||||
reportDirectories,
|
||||
ctx,
|
||||
logger,
|
||||
}: {
|
||||
harvested: HarvestedScreenshot[];
|
||||
junitReportDirectory: string;
|
||||
backend: MaestroBackend;
|
||||
reportDirectories: string[];
|
||||
ctx: CustomBuildContext;
|
||||
logger: bunyan;
|
||||
}): Promise<void> {
|
||||
@@ -402,9 +585,25 @@ async function uploadFailureScreenshotsAsync({
|
||||
// test verdict (the whole step is verdict-neutral for screenshots).
|
||||
let selected: HarvestedScreenshot[];
|
||||
try {
|
||||
const pureFailureFlowNames = computePureFailureFlowNames(
|
||||
await parseJUnitTestCases(junitReportDirectory)
|
||||
);
|
||||
let flowResults: { name: string; status: 'passed' | 'failed' }[];
|
||||
switch (backend) {
|
||||
case 'maestro':
|
||||
flowResults = (
|
||||
await Promise.all(reportDirectories.map(directory => parseJUnitTestCases(directory)))
|
||||
).flat();
|
||||
break;
|
||||
case 'maestro-runner': {
|
||||
const results = await Promise.all(
|
||||
reportDirectories.map(directory => parseMaestroRunnerReport(directory))
|
||||
);
|
||||
// Use whichever reports parsed. An unreadable report (e.g. a final retry that crashed
|
||||
// before writing report.json) contributes no flows rather than discarding screenshots
|
||||
// harvested from the attempts that did report — mirroring the maestro path above.
|
||||
flowResults = results.flatMap(result => result?.flows ?? []);
|
||||
break;
|
||||
}
|
||||
}
|
||||
const pureFailureFlowNames = computePureFailureFlowNames(flowResults);
|
||||
selected = selectFailureScreenshots(harvested, pureFailureFlowNames);
|
||||
} catch (err: any) {
|
||||
logger.warn({ err }, 'Failed to classify failure screenshots; skipping screenshot upload.');
|
||||
|
||||
@@ -258,13 +258,14 @@ export async function restoreGradleCacheAsync({
|
||||
const gradleCachesPath = path.join(os.homedir(), '.gradle', 'caches');
|
||||
|
||||
const buildCachePath = path.join(gradleCachesPath, 'build-cache-1');
|
||||
const journalPath = path.join(gradleCachesPath, 'journal-1');
|
||||
|
||||
const { archivePath, matchedKey } = await downloadCacheAsync({
|
||||
logger,
|
||||
jobId,
|
||||
expoApiServerURL,
|
||||
robotAccessToken,
|
||||
paths: [buildCachePath],
|
||||
paths: [buildCachePath, journalPath],
|
||||
key: cacheKey,
|
||||
keyPrefixes: [GRADLE_CACHE_KEY_PREFIX],
|
||||
platform: Platform.ANDROID,
|
||||
|
||||
@@ -167,6 +167,7 @@ export async function saveGradleCacheAsync({
|
||||
|
||||
const gradleCachesPath = path.join(os.homedir(), '.gradle', 'caches');
|
||||
const buildCachePath = path.join(gradleCachesPath, 'build-cache-1');
|
||||
const journalPath = path.join(gradleCachesPath, 'journal-1');
|
||||
|
||||
try {
|
||||
await fs.promises.access(buildCachePath);
|
||||
@@ -186,9 +187,11 @@ export async function saveGradleCacheAsync({
|
||||
);
|
||||
const expoApiServerURL = nullthrows(env.__API_SERVER_URL, '__API_SERVER_URL is not set');
|
||||
|
||||
await fs.promises.mkdir(journalPath, { recursive: true });
|
||||
|
||||
logger.info('Compressing Gradle build cache...');
|
||||
const { archivePath } = await compressCacheAsync({
|
||||
paths: [buildCachePath],
|
||||
paths: [buildCachePath, journalPath],
|
||||
workingDirectory: gradleCachesPath,
|
||||
verbose: env.EXPO_DEBUG === '1',
|
||||
logger,
|
||||
@@ -204,7 +207,7 @@ export async function saveGradleCacheAsync({
|
||||
robotAccessToken,
|
||||
archivePath,
|
||||
key: cacheKey,
|
||||
paths: [buildCachePath],
|
||||
paths: [buildCachePath, journalPath],
|
||||
size,
|
||||
platform: Platform.ANDROID,
|
||||
});
|
||||
|
||||
@@ -348,7 +348,10 @@ export async function compressCacheAsync({
|
||||
for (const { absolutePath, archivePath: targetRelativePath } of allFiles) {
|
||||
const targetPath = path.join(tempDir, targetRelativePath);
|
||||
await fs.promises.mkdir(path.dirname(targetPath), { recursive: true });
|
||||
// We want to keep source timestamps since Gradle may check them when pruning cache.
|
||||
const { atime, mtime } = await fs.promises.stat(absolutePath);
|
||||
await fs.promises.copyFile(absolutePath, targetPath);
|
||||
await fs.promises.utimes(targetPath, atime, mtime);
|
||||
|
||||
if (verbose) {
|
||||
logger.info(`- ${targetRelativePath}`);
|
||||
|
||||
@@ -60,6 +60,11 @@ export function createStartAgentDeviceRemoteSessionBuildFunction(
|
||||
required: false,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.NUMBER,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'max_duration_seconds',
|
||||
required: false,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.NUMBER,
|
||||
}),
|
||||
],
|
||||
fn: async ({ logger, global }, { inputs, env, signal }) => {
|
||||
// Fail fast before any expensive setup if the injected env
|
||||
@@ -73,6 +78,7 @@ export function createStartAgentDeviceRemoteSessionBuildFunction(
|
||||
const packageVersion = inputs.package_version.value as string | undefined;
|
||||
// A missing or non-positive value disables the idle timeout (opt-in feature).
|
||||
const maxIdleTimeMinutes = inputs.max_idle_time_minutes.value as number | undefined;
|
||||
const maxDurationSeconds = inputs.max_duration_seconds?.value as number | undefined;
|
||||
const { runtimePlatform } = global;
|
||||
logger.info(
|
||||
`Starting agent-device remote session (version: ${packageVersion ?? 'latest'}, runtime: ${runtimePlatform}).`
|
||||
@@ -146,6 +152,7 @@ export function createStartAgentDeviceRemoteSessionBuildFunction(
|
||||
ctx,
|
||||
deviceRunSessionId,
|
||||
logger,
|
||||
maxDurationSeconds,
|
||||
signal,
|
||||
idleTimeout:
|
||||
maxIdleTimeMinutes !== undefined && maxIdleTimeMinutes > 0
|
||||
|
||||
@@ -5,8 +5,12 @@ import {
|
||||
BuildRuntimePlatform,
|
||||
BuildStepInput,
|
||||
BuildStepInputValueTypeName,
|
||||
BuildStepOutput,
|
||||
} from '@expo/steps';
|
||||
import spawn from '@expo/turtle-spawn';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import {
|
||||
AndroidDeviceName,
|
||||
@@ -49,7 +53,18 @@ export function createStartAndroidEmulatorBuildFunction(): BuildFunction {
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.NUMBER,
|
||||
}),
|
||||
],
|
||||
fn: async ({ logger }, { inputs, env }) => {
|
||||
outputProviders: [
|
||||
BuildStepOutput.createProvider({
|
||||
id: 'logcat_directory',
|
||||
required: true,
|
||||
}),
|
||||
],
|
||||
fn: async ({ logger }, { inputs, outputs, env }) => {
|
||||
const logcatDirectory = await fs.promises.mkdtemp(
|
||||
path.join(os.tmpdir(), 'eas-android-emulator-logcat-')
|
||||
);
|
||||
outputs.logcat_directory.set(logcatDirectory);
|
||||
|
||||
if (env.EAS_NO_EMULATOR_HOST_SUPPORT_CHECK !== '1') {
|
||||
await assertAndroidEmulatorHostSupportAsync({ env });
|
||||
} else {
|
||||
@@ -122,6 +137,7 @@ export function createStartAndroidEmulatorBuildFunction(): BuildFunction {
|
||||
const startResult = await AndroidEmulatorUtils.startAsync({
|
||||
deviceName,
|
||||
env,
|
||||
logcatDirectory,
|
||||
});
|
||||
attemptSerialId = startResult.serialId;
|
||||
await AndroidEmulatorUtils.waitForReadyAsync({
|
||||
@@ -211,6 +227,7 @@ export function createStartAndroidEmulatorBuildFunction(): BuildFunction {
|
||||
const startResult = await AndroidEmulatorUtils.startAsync({
|
||||
deviceName: cloneIdentifier,
|
||||
env,
|
||||
logcatDirectory,
|
||||
});
|
||||
cloneSerialId = startResult.serialId;
|
||||
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
import { SystemError } from '@expo/eas-build-job';
|
||||
import { type bunyan } from '@expo/logger';
|
||||
import {
|
||||
BuildFunction,
|
||||
BuildRuntimePlatform,
|
||||
type BuildStepEnv,
|
||||
BuildStepInput,
|
||||
BuildStepInputValueTypeName,
|
||||
} from '@expo/steps';
|
||||
import spawn from '@expo/turtle-spawn';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import semver from 'semver';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { type CustomBuildContext } from '../../customBuildContext';
|
||||
import { AndroidEmulatorUtils } from '../../utils/AndroidEmulatorUtils';
|
||||
import { IosSimulatorUtils } from '../../utils/IosSimulatorUtils';
|
||||
import { sleepAsync } from '../../utils/retry';
|
||||
import { turtleFetch } from '../../utils/turtleFetch';
|
||||
import { startAppiumEventCollectionAsync } from '../utils/appiumEvents';
|
||||
import {
|
||||
getDeviceRunSessionIdOrThrow,
|
||||
getNgrokAuthtokenOrThrow,
|
||||
getNgrokTunnelDomainOrThrow,
|
||||
selectXcodeDeveloperDirectoryAsync,
|
||||
spawnDetached,
|
||||
startNgrokTunnelAsync,
|
||||
startServeSimWithTunnelAsync,
|
||||
uploadRemoteSessionConfigAsync,
|
||||
waitForDeviceRunSessionStoppedAsync,
|
||||
} from '../utils/remoteDeviceRunSession';
|
||||
|
||||
const APPIUM_HOST = '127.0.0.1';
|
||||
const APPIUM_PORT = 4723;
|
||||
const APPIUM_STARTUP_TIMEOUT_MS = 120_000;
|
||||
const DEFAULT_APPIUM_VERSION = '^3';
|
||||
|
||||
const AppiumInstalledDriversSchema = z.record(
|
||||
z.string(),
|
||||
z.object({ installed: z.boolean().optional() }).passthrough()
|
||||
);
|
||||
|
||||
export function createStartAppiumRemoteSessionBuildFunction(
|
||||
ctx: CustomBuildContext
|
||||
): BuildFunction {
|
||||
return new BuildFunction({
|
||||
namespace: 'eas',
|
||||
id: 'start_appium_remote_session',
|
||||
name: 'Start Appium remote session',
|
||||
__metricsId: 'eas/start_appium_remote_session',
|
||||
inputProviders: [
|
||||
BuildStepInput.createProvider({
|
||||
id: 'package_version',
|
||||
required: false,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'max_idle_time_minutes',
|
||||
required: false,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.NUMBER,
|
||||
}),
|
||||
],
|
||||
fn: async ({ logger, global }, { inputs, env, signal }) => {
|
||||
const deviceRunSessionId = getDeviceRunSessionIdOrThrow(env);
|
||||
const ngrokTunnelDomain = getNgrokTunnelDomainOrThrow(env);
|
||||
const ngrokAuthtoken = getNgrokAuthtokenOrThrow(env);
|
||||
const packageVersion = inputs.package_version.value as string | undefined;
|
||||
const maxIdleTimeMinutes = inputs.max_idle_time_minutes.value as number | undefined;
|
||||
const { runtimePlatform } = global;
|
||||
const versionSpec = resolveAppium3VersionSpec(packageVersion);
|
||||
|
||||
logger.info(
|
||||
`Starting Appium remote session (version: ${versionSpec}, runtime: ${runtimePlatform}).`
|
||||
);
|
||||
const device = await resolveAppiumDeviceAsync({ runtimePlatform, env, logger });
|
||||
const { appiumHome, appiumBinPath, appiumEnv } = await installAppiumAsync({
|
||||
versionSpec,
|
||||
driverName: device.driverName,
|
||||
env,
|
||||
logger,
|
||||
});
|
||||
|
||||
const appiumProcess = spawnDetached({
|
||||
command: appiumBinPath,
|
||||
args: [
|
||||
'--address',
|
||||
APPIUM_HOST,
|
||||
'--port',
|
||||
String(APPIUM_PORT),
|
||||
'--base-path',
|
||||
'/',
|
||||
'--log-level',
|
||||
'error',
|
||||
// Appium 3 gates session listing (GET /appium/sessions) behind the
|
||||
// session_discovery insecure feature. We rely on it to poll for
|
||||
// Appium Event Timings, so enable it for all drivers.
|
||||
'--allow-insecure',
|
||||
'*:session_discovery',
|
||||
'--default-capabilities',
|
||||
JSON.stringify({ 'appium:eventTimings': true }),
|
||||
],
|
||||
env: appiumEnv,
|
||||
});
|
||||
try {
|
||||
await waitForAppiumReadyAsync({ appiumProcess, logger });
|
||||
} catch (error) {
|
||||
await appiumProcess.stopAsync();
|
||||
await fs.promises.rm(appiumHome, { recursive: true, force: true });
|
||||
throw error;
|
||||
}
|
||||
|
||||
const eventCollection = await startAppiumEventCollectionAsync({
|
||||
ctx,
|
||||
deviceRunSessionId,
|
||||
appiumUrl: `http://${APPIUM_HOST}:${APPIUM_PORT}/`,
|
||||
logger,
|
||||
});
|
||||
let appiumTunnel: Awaited<ReturnType<typeof startNgrokTunnelAsync>> | undefined;
|
||||
let serveSim: Awaited<ReturnType<typeof startServeSimWithTunnelAsync>> | undefined;
|
||||
try {
|
||||
appiumTunnel = await startNgrokTunnelAsync({
|
||||
port: APPIUM_PORT,
|
||||
subdomainPrefix: 'appium',
|
||||
baseDomain: ngrokTunnelDomain,
|
||||
authtoken: ngrokAuthtoken,
|
||||
logger,
|
||||
});
|
||||
|
||||
switch (runtimePlatform) {
|
||||
case BuildRuntimePlatform.DARWIN:
|
||||
serveSim = await startServeSimWithTunnelAsync(ctx, {
|
||||
baseDomain: ngrokTunnelDomain,
|
||||
env,
|
||||
logger,
|
||||
timeoutMs: APPIUM_STARTUP_TIMEOUT_MS,
|
||||
});
|
||||
break;
|
||||
case BuildRuntimePlatform.LINUX:
|
||||
break;
|
||||
}
|
||||
|
||||
await uploadRemoteSessionConfigAsync({
|
||||
ctx,
|
||||
deviceRunSessionId,
|
||||
remoteConfig: {
|
||||
appiumUrl: appiumTunnel.url,
|
||||
capabilities: {
|
||||
platformName: device.platformName,
|
||||
'appium:automationName': device.automationName,
|
||||
'appium:udid': device.udid,
|
||||
},
|
||||
...(serveSim ? { webPreviewUrl: serveSim.previewUrl } : {}),
|
||||
},
|
||||
logger,
|
||||
});
|
||||
|
||||
await waitForDeviceRunSessionStoppedAsync({
|
||||
ctx,
|
||||
deviceRunSessionId,
|
||||
logger,
|
||||
signal,
|
||||
idleTimeout:
|
||||
maxIdleTimeMinutes !== undefined && maxIdleTimeMinutes > 0
|
||||
? {
|
||||
maxIdleTimeMinutes,
|
||||
getLastEventObservedAt: eventCollection.getLastEventObservedAt,
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
} finally {
|
||||
if (serveSim) {
|
||||
await serveSim.stopAsync();
|
||||
}
|
||||
if (appiumTunnel) {
|
||||
await appiumTunnel.stopAsync();
|
||||
}
|
||||
await eventCollection.stopAsync();
|
||||
await appiumProcess.stopAsync();
|
||||
await fs.promises.rm(appiumHome, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveAppium3VersionSpec(packageVersion: string | undefined): string {
|
||||
const versionSpec = packageVersion ?? DEFAULT_APPIUM_VERSION;
|
||||
const range = semver.validRange(versionSpec);
|
||||
if (!range || !semver.subset(range, '>=3.0.0 <4.0.0-0')) {
|
||||
throw new SystemError(
|
||||
`Appium 3 is required for EAS Simulator sessions. Received package version "${versionSpec}".`
|
||||
);
|
||||
}
|
||||
return versionSpec;
|
||||
}
|
||||
|
||||
type AppiumDevice = {
|
||||
platformName: 'iOS' | 'Android';
|
||||
automationName: 'XCUITest' | 'UiAutomator2';
|
||||
driverName: 'xcuitest' | 'uiautomator2';
|
||||
udid: string;
|
||||
};
|
||||
|
||||
export async function resolveAppiumDeviceAsync({
|
||||
runtimePlatform,
|
||||
env,
|
||||
logger,
|
||||
}: {
|
||||
runtimePlatform: BuildRuntimePlatform;
|
||||
env: BuildStepEnv;
|
||||
logger: bunyan;
|
||||
}): Promise<AppiumDevice> {
|
||||
switch (runtimePlatform) {
|
||||
case BuildRuntimePlatform.DARWIN: {
|
||||
await selectXcodeDeveloperDirectoryAsync({ env, logger });
|
||||
const [bootedDevice] = await IosSimulatorUtils.getAvailableDevicesAsync({
|
||||
env,
|
||||
filter: 'booted',
|
||||
});
|
||||
if (!bootedDevice) {
|
||||
throw new SystemError('Could not find a booted iOS simulator for the Appium session.');
|
||||
}
|
||||
return {
|
||||
platformName: 'iOS',
|
||||
automationName: 'XCUITest',
|
||||
driverName: 'xcuitest',
|
||||
udid: bootedDevice.udid,
|
||||
};
|
||||
}
|
||||
case BuildRuntimePlatform.LINUX: {
|
||||
const attachedDevices = await AndroidEmulatorUtils.getAttachedDevicesAsync({ env });
|
||||
const bootedDevice = attachedDevices.find(device => device.state === 'device');
|
||||
if (!bootedDevice) {
|
||||
throw new SystemError('Could not find a booted Android emulator for the Appium session.');
|
||||
}
|
||||
return {
|
||||
platformName: 'Android',
|
||||
automationName: 'UiAutomator2',
|
||||
driverName: 'uiautomator2',
|
||||
udid: bootedDevice.serialId,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function installAppiumAsync({
|
||||
versionSpec,
|
||||
driverName,
|
||||
env,
|
||||
logger,
|
||||
}: {
|
||||
versionSpec: string;
|
||||
driverName: AppiumDevice['driverName'];
|
||||
env: BuildStepEnv;
|
||||
logger: bunyan;
|
||||
}): Promise<{ appiumHome: string; appiumBinPath: string; appiumEnv: BuildStepEnv }> {
|
||||
const appiumHome = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'eas-appium-home-'));
|
||||
await fs.promises.writeFile(
|
||||
path.join(appiumHome, 'package.json'),
|
||||
`${JSON.stringify({ name: 'eas-appium-home', private: true })}\n`
|
||||
);
|
||||
const appiumEnv: BuildStepEnv = { ...env, APPIUM_HOME: appiumHome };
|
||||
const appiumBinPath = path.join(appiumHome, 'node_modules', '.bin', 'appium');
|
||||
|
||||
logger.info(`Installing appium@${versionSpec}.`);
|
||||
await spawn('npm', ['install', '--prefix', appiumHome, `appium@${versionSpec}`], {
|
||||
env: appiumEnv,
|
||||
logger,
|
||||
});
|
||||
const { stdout } = await spawn(appiumBinPath, ['driver', 'list', '--installed', '--json'], {
|
||||
env: appiumEnv,
|
||||
stdio: 'pipe',
|
||||
});
|
||||
const installedDrivers = AppiumInstalledDriversSchema.parse(JSON.parse(stdout));
|
||||
if (installedDrivers[driverName]?.installed) {
|
||||
logger.info(`Updating the installed Appium ${driverName} driver.`);
|
||||
await spawn(appiumBinPath, ['driver', 'update', driverName], { env: appiumEnv, logger });
|
||||
} else {
|
||||
logger.info(`Installing the Appium ${driverName} driver.`);
|
||||
await spawn(appiumBinPath, ['driver', 'install', driverName], { env: appiumEnv, logger });
|
||||
}
|
||||
return { appiumHome, appiumBinPath, appiumEnv };
|
||||
}
|
||||
|
||||
async function waitForAppiumReadyAsync({
|
||||
appiumProcess,
|
||||
logger,
|
||||
}: {
|
||||
appiumProcess: { getOutput: () => string };
|
||||
logger: bunyan;
|
||||
}): Promise<void> {
|
||||
const deadline = Date.now() + APPIUM_STARTUP_TIMEOUT_MS;
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
const response = await turtleFetch(`http://${APPIUM_HOST}:${APPIUM_PORT}/status`, 'GET', {
|
||||
timeout: 2_000,
|
||||
retries: 0,
|
||||
logger,
|
||||
});
|
||||
if (response.ok) {
|
||||
return;
|
||||
}
|
||||
} catch {}
|
||||
await sleepAsync(1_000);
|
||||
}
|
||||
const output = appiumProcess.getOutput();
|
||||
throw new SystemError(
|
||||
`Timed out waiting for Appium to become ready.${output ? `\nAppium output:\n${output}` : ''}`
|
||||
);
|
||||
}
|
||||
@@ -73,6 +73,11 @@ export function createStartArgentRemoteSessionBuildFunction(
|
||||
required: false,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.NUMBER,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'max_duration_seconds',
|
||||
required: false,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.NUMBER,
|
||||
}),
|
||||
],
|
||||
fn: async ({ logger, global }, { inputs, env, signal }) => {
|
||||
// Fail fast before any expensive setup if the injected env
|
||||
@@ -86,6 +91,7 @@ export function createStartArgentRemoteSessionBuildFunction(
|
||||
const packageVersion = inputs.package_version.value as string | undefined;
|
||||
// A missing or non-positive value disables the idle timeout (opt-in feature).
|
||||
const maxIdleTimeMinutes = inputs.max_idle_time_minutes.value as number | undefined;
|
||||
const maxDurationSeconds = inputs.max_duration_seconds?.value as number | undefined;
|
||||
warnIfArgentPackageVersionCannotBeVerified({ packageVersion, logger });
|
||||
const versionSpec = packageVersion ?? 'latest';
|
||||
const { runtimePlatform } = global;
|
||||
@@ -221,6 +227,7 @@ export function createStartArgentRemoteSessionBuildFunction(
|
||||
ctx,
|
||||
deviceRunSessionId,
|
||||
logger,
|
||||
maxDurationSeconds,
|
||||
signal,
|
||||
idleTimeout:
|
||||
maxIdleTimeMinutes !== undefined && maxIdleTimeMinutes > 0
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { BuildFunction, BuildRuntimePlatform } from '@expo/steps';
|
||||
import {
|
||||
BuildFunction,
|
||||
BuildRuntimePlatform,
|
||||
BuildStepInput,
|
||||
BuildStepInputValueTypeName,
|
||||
} from '@expo/steps';
|
||||
|
||||
import { CustomBuildContext } from '../../customBuildContext';
|
||||
import {
|
||||
@@ -21,9 +26,17 @@ export function createStartServeSimRemoteSessionBuildFunction(
|
||||
name: 'Start serve-sim remote session',
|
||||
__metricsId: 'eas/start_serve_sim_remote_session',
|
||||
supportedRuntimePlatforms: [BuildRuntimePlatform.DARWIN],
|
||||
fn: async ({ logger }, { env, signal }) => {
|
||||
inputProviders: [
|
||||
BuildStepInput.createProvider({
|
||||
id: 'max_duration_seconds',
|
||||
required: false,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.NUMBER,
|
||||
}),
|
||||
],
|
||||
fn: async ({ logger }, { inputs, env, signal }) => {
|
||||
const deviceRunSessionId = getDeviceRunSessionIdOrThrow(env);
|
||||
const ngrokTunnelDomain = getNgrokTunnelDomainOrThrow(env);
|
||||
const maxDurationSeconds = inputs.max_duration_seconds?.value as number | undefined;
|
||||
|
||||
logger.info('Starting serve-sim remote session.');
|
||||
|
||||
@@ -49,6 +62,7 @@ export function createStartServeSimRemoteSessionBuildFunction(
|
||||
ctx,
|
||||
deviceRunSessionId,
|
||||
logger,
|
||||
maxDurationSeconds,
|
||||
signal,
|
||||
});
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import fs from 'node:fs';
|
||||
|
||||
import { turtleFetch } from '../../../utils/turtleFetch';
|
||||
import { startAppiumEventCollectionAsync } from '../appiumEvents';
|
||||
import { startDeviceRunSessionEventCollectionAsync } from '../deviceRunSessionEvents';
|
||||
|
||||
jest.mock('../../../utils/turtleFetch');
|
||||
jest.mock('../deviceRunSessionEvents', () => ({
|
||||
startDeviceRunSessionEventCollectionAsync: jest.fn(async () => ({
|
||||
getLastEventObservedAt: () => undefined,
|
||||
stopAsync: async () => undefined,
|
||||
})),
|
||||
}));
|
||||
|
||||
describe(startAppiumEventCollectionAsync, () => {
|
||||
it('writes new Appium Event Timings commands to a normal event file', async () => {
|
||||
jest
|
||||
.mocked(turtleFetch)
|
||||
.mockResolvedValueOnce(response({ value: [{ id: 'appium-session-id' }] }))
|
||||
.mockResolvedValueOnce(
|
||||
response({
|
||||
value: {
|
||||
commands: [
|
||||
{ cmd: 'getOrientation', startTime: 1_786_693_000_000, endTime: 1_786_693_000_025 },
|
||||
{ cmd: 'getLogEvents', startTime: 1_786_693_000_026, endTime: 1_786_693_000_027 },
|
||||
],
|
||||
},
|
||||
})
|
||||
)
|
||||
.mockResolvedValueOnce(response({ value: [] }));
|
||||
|
||||
const collection = await startAppiumEventCollectionAsync({
|
||||
ctx: {} as never,
|
||||
deviceRunSessionId: 'device-session-id',
|
||||
appiumUrl: 'http://127.0.0.1:4723/',
|
||||
logger: { warn: jest.fn() } as never,
|
||||
pollIntervalMs: 60_000,
|
||||
});
|
||||
const source = jest.mocked(startDeviceRunSessionEventCollectionAsync).mock.calls[0][0].source;
|
||||
const [eventFile] = await source.findEventFilesAsync();
|
||||
let contents = '';
|
||||
await waitForAsync(async () => {
|
||||
contents = await fs.promises.readFile(eventFile, 'utf8');
|
||||
expect(contents).toContain('getOrientation');
|
||||
});
|
||||
const lines = contents.trim().split('\n');
|
||||
expect(lines).toHaveLength(1);
|
||||
const [line] = lines;
|
||||
expect(
|
||||
source.parseLine({
|
||||
line,
|
||||
sourceKey: source.sourceKeyForFile(eventFile),
|
||||
sequenceNumber: 1,
|
||||
deviceRunSessionId: 'device-session-id',
|
||||
})
|
||||
).toMatchObject({
|
||||
event: {
|
||||
producer: 'appium',
|
||||
type: 'operation.completed',
|
||||
durationMs: 25,
|
||||
summary: 'getOrientation',
|
||||
},
|
||||
});
|
||||
|
||||
// Appium 3 removed GET /sessions; session discovery must use /appium/sessions.
|
||||
expect(turtleFetch).toHaveBeenCalledWith(
|
||||
'http://127.0.0.1:4723/appium/sessions',
|
||||
'GET',
|
||||
expect.anything()
|
||||
);
|
||||
expect(turtleFetch).toHaveBeenCalledWith(
|
||||
'http://127.0.0.1:4723/session/appium-session-id/appium/events',
|
||||
'POST',
|
||||
expect.anything()
|
||||
);
|
||||
|
||||
await collection.stopAsync();
|
||||
});
|
||||
});
|
||||
|
||||
async function waitForAsync(assertion: () => Promise<void>): Promise<void> {
|
||||
for (let attempt = 0; attempt < 20; attempt += 1) {
|
||||
try {
|
||||
await assertion();
|
||||
return;
|
||||
} catch {
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
}
|
||||
}
|
||||
await assertion();
|
||||
}
|
||||
|
||||
function response(value: unknown): Awaited<ReturnType<typeof turtleFetch>> {
|
||||
return { json: async () => value } as never;
|
||||
}
|
||||
@@ -2,6 +2,10 @@ import { bunyan } from '@expo/logger';
|
||||
import { BuildRuntimePlatform, BuildStepEnv } from '@expo/steps';
|
||||
import spawn from '@expo/turtle-spawn';
|
||||
import * as ngrok from '@ngrok/ngrok';
|
||||
import {
|
||||
clearTimeout as clearTimeoutCallback,
|
||||
setTimeout as setTimeoutCallback,
|
||||
} from 'node:timers';
|
||||
import { setTimeout as setTimeoutAsync } from 'node:timers/promises';
|
||||
|
||||
import { CustomBuildContext } from '../../../customBuildContext';
|
||||
@@ -20,6 +24,7 @@ import {
|
||||
} from '../remoteDeviceRunSession';
|
||||
|
||||
jest.mock('@ngrok/ngrok');
|
||||
jest.mock('node:timers');
|
||||
jest.mock('node:timers/promises');
|
||||
jest.mock('../../../utils/turtleFetch');
|
||||
jest.mock('../../../utils/retry', () => ({ sleepAsync: jest.fn() }));
|
||||
@@ -216,14 +221,14 @@ describe(startNgrokTunnelAsync, () => {
|
||||
it('uses a 128-bit capability hostname and exposes explicit cleanup', async () => {
|
||||
const close = jest.fn().mockResolvedValue(undefined);
|
||||
jest.mocked(ngrok.forward).mockResolvedValue({
|
||||
url: () => 'https://serve-sim.example.test',
|
||||
url: () => 'https://web-preview.example.test',
|
||||
close,
|
||||
} as never);
|
||||
|
||||
const tunnel = await startNgrokTunnelAsync({
|
||||
port: 4321,
|
||||
subdomainPrefix: 'serve-sim',
|
||||
baseDomain: 'tunnel.example.test',
|
||||
subdomainPrefix: 'web-preview',
|
||||
baseDomain: 'eas-simulator.ngrok.dev',
|
||||
authtoken: 'token',
|
||||
logger: createLoggerMock(),
|
||||
});
|
||||
@@ -232,10 +237,10 @@ describe(startNgrokTunnelAsync, () => {
|
||||
expect.objectContaining({
|
||||
addr: 4321,
|
||||
authtoken: 'token',
|
||||
domain: expect.stringMatching(/^serve-sim-[a-f0-9]{32}\.tunnel\.example\.test$/),
|
||||
domain: expect.stringMatching(/^web-preview-[a-f0-9]{32}\.eas-simulator\.ngrok\.dev$/),
|
||||
})
|
||||
);
|
||||
expect(tunnel.url).toBe('https://serve-sim.example.test');
|
||||
expect(tunnel.url).toBe('https://web-preview.example.test');
|
||||
await tunnel.stopAsync();
|
||||
await tunnel.stopAsync();
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
@@ -360,8 +365,13 @@ describe(fetchServeSimTurnArgsAsync, () => {
|
||||
});
|
||||
|
||||
describe(waitForDeviceRunSessionStoppedAsync, () => {
|
||||
const durationTimeout = {} as NodeJS.Timeout;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.mocked(Sentry).capture.mockReset();
|
||||
jest.mocked(setTimeoutCallback).mockReset();
|
||||
jest.mocked(setTimeoutCallback).mockReturnValue(durationTimeout);
|
||||
jest.mocked(clearTimeoutCallback).mockReset();
|
||||
jest.mocked(setTimeoutAsync).mockReset();
|
||||
jest.mocked(setTimeoutAsync).mockResolvedValue(undefined);
|
||||
});
|
||||
@@ -378,6 +388,57 @@ describe(waitForDeviceRunSessionStoppedAsync, () => {
|
||||
|
||||
expect(ctx.graphqlClient.query).toHaveBeenCalledTimes(2);
|
||||
expect(logger.info).toHaveBeenCalledWith('Device run session drs-id was stopped.');
|
||||
expect(setTimeoutCallback).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns normally when the maximum duration elapses', async () => {
|
||||
const ctx = createStatusCtxMock([{ status: 'IN_PROGRESS' }]);
|
||||
const logger = createLoggerMock();
|
||||
const waitPromise = waitForDeviceRunSessionStoppedAsync({
|
||||
ctx,
|
||||
deviceRunSessionId: 'drs-id',
|
||||
logger,
|
||||
maxDurationSeconds: 1,
|
||||
});
|
||||
|
||||
expect(setTimeoutCallback).toHaveBeenCalledWith(expect.any(Function), 1_000);
|
||||
const durationTimeoutCallback = jest.mocked(setTimeoutCallback).mock.calls[0][0];
|
||||
durationTimeoutCallback();
|
||||
await waitPromise;
|
||||
|
||||
expect(ctx.graphqlClient.query).toHaveBeenCalledTimes(1);
|
||||
expect(logger.info).toHaveBeenCalledWith(
|
||||
'Device run session drs-id reached its maximum duration.'
|
||||
);
|
||||
expect(clearTimeoutCallback).toHaveBeenCalledWith(durationTimeout);
|
||||
});
|
||||
|
||||
it('clears the duration timeout when the session stops first', async () => {
|
||||
await waitForDeviceRunSessionStoppedAsync({
|
||||
ctx: createStatusCtxMock([{ status: 'STOPPED' }]),
|
||||
deviceRunSessionId: 'drs-id',
|
||||
logger: createLoggerMock(),
|
||||
maxDurationSeconds: 30,
|
||||
});
|
||||
|
||||
expect(clearTimeoutCallback).toHaveBeenCalledWith(durationTimeout);
|
||||
});
|
||||
|
||||
it('does not poll when the build step is already aborted', async () => {
|
||||
const ctx = createStatusCtxMock([]);
|
||||
const abortController = new AbortController();
|
||||
abortController.abort();
|
||||
|
||||
await waitForDeviceRunSessionStoppedAsync({
|
||||
ctx,
|
||||
deviceRunSessionId: 'drs-id',
|
||||
logger: createLoggerMock(),
|
||||
maxDurationSeconds: 30,
|
||||
signal: abortController.signal,
|
||||
});
|
||||
|
||||
expect(ctx.graphqlClient.query).not.toHaveBeenCalled();
|
||||
expect(setTimeoutCallback).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('throws when the device run session errors', async () => {
|
||||
@@ -388,8 +449,28 @@ describe(waitForDeviceRunSessionStoppedAsync, () => {
|
||||
ctx,
|
||||
deviceRunSessionId: 'drs-id',
|
||||
logger: createLoggerMock(),
|
||||
maxDurationSeconds: 30,
|
||||
})
|
||||
).rejects.toThrow('Device run session drs-id errored.');
|
||||
expect(clearTimeoutCallback).toHaveBeenCalledWith(durationTimeout);
|
||||
});
|
||||
|
||||
it('clears the duration timeout when the build step is aborted', async () => {
|
||||
const ctx = createStatusCtxMock([{ status: 'IN_PROGRESS' }]);
|
||||
const abortController = new AbortController();
|
||||
const waitPromise = waitForDeviceRunSessionStoppedAsync({
|
||||
ctx,
|
||||
deviceRunSessionId: 'drs-id',
|
||||
logger: createLoggerMock(),
|
||||
maxDurationSeconds: 30,
|
||||
signal: abortController.signal,
|
||||
});
|
||||
|
||||
abortController.abort();
|
||||
await waitPromise;
|
||||
|
||||
expect(ctx.graphqlClient.query).toHaveBeenCalledTimes(1);
|
||||
expect(clearTimeoutCallback).toHaveBeenCalledWith(durationTimeout);
|
||||
});
|
||||
|
||||
it('logs and retries transient polling errors', async () => {
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
import { type bunyan } from '@expo/logger';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { setTimeout as setTimeoutAsync } from 'node:timers/promises';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { type CustomBuildContext } from '../../customBuildContext';
|
||||
import { turtleFetch } from '../../utils/turtleFetch';
|
||||
import {
|
||||
type DeviceRunSessionEventCollection,
|
||||
type DeviceRunSessionEventSource,
|
||||
startDeviceRunSessionEventCollectionAsync,
|
||||
} from './deviceRunSessionEvents';
|
||||
|
||||
const APPIUM_REQUEST_TIMEOUT_MS = 10_000;
|
||||
const POLL_INTERVAL_MS = 1_000;
|
||||
const GET_LOG_EVENTS_COMMAND = 'getLogEvents';
|
||||
|
||||
const AppiumSessionsResponseSchema = z.object({
|
||||
value: z.array(z.object({ id: z.string() }).passthrough()),
|
||||
});
|
||||
|
||||
const AppiumCommandSchema = z.object({
|
||||
appiumSessionId: z.string(),
|
||||
cmd: z.string(),
|
||||
startTime: z.number(),
|
||||
endTime: z.number(),
|
||||
});
|
||||
|
||||
const AppiumEventsResponseSchema = z.object({
|
||||
value: z.object({
|
||||
commands: z.array(AppiumCommandSchema.omit({ appiumSessionId: true })),
|
||||
}),
|
||||
});
|
||||
|
||||
type AppiumCommand = z.infer<typeof AppiumCommandSchema>;
|
||||
|
||||
export async function startAppiumEventCollectionAsync({
|
||||
ctx,
|
||||
deviceRunSessionId,
|
||||
appiumUrl,
|
||||
logger,
|
||||
pollIntervalMs = POLL_INTERVAL_MS,
|
||||
}: {
|
||||
ctx: CustomBuildContext;
|
||||
deviceRunSessionId: string;
|
||||
appiumUrl: string;
|
||||
logger: bunyan;
|
||||
pollIntervalMs?: number;
|
||||
}): Promise<DeviceRunSessionEventCollection> {
|
||||
const eventDirectory = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'eas-appium-events-'));
|
||||
const eventFile = path.join(eventDirectory, 'commands.ndjson');
|
||||
await fs.promises.writeFile(eventFile, '');
|
||||
|
||||
let eventCollection: DeviceRunSessionEventCollection;
|
||||
try {
|
||||
eventCollection = await startDeviceRunSessionEventCollectionAsync({
|
||||
ctx,
|
||||
deviceRunSessionId,
|
||||
logger,
|
||||
pollIntervalMs,
|
||||
source: createAppiumEventSource(eventFile),
|
||||
});
|
||||
} catch (error) {
|
||||
await fs.promises.rm(eventDirectory, { recursive: true, force: true });
|
||||
throw error;
|
||||
}
|
||||
|
||||
const observedCommandKeys = new Set<string>();
|
||||
const controller = new AbortController();
|
||||
let didReportCollectionFailure = false;
|
||||
const collectSafelyAsync = async (): Promise<void> => {
|
||||
try {
|
||||
await collectAppiumCommandsAsync({
|
||||
appiumUrl,
|
||||
eventFile,
|
||||
observedCommandKeys,
|
||||
logger,
|
||||
});
|
||||
didReportCollectionFailure = false;
|
||||
} catch (error) {
|
||||
if (!didReportCollectionFailure) {
|
||||
didReportCollectionFailure = true;
|
||||
logger.warn({ err: error }, 'Could not collect Appium events.');
|
||||
}
|
||||
}
|
||||
};
|
||||
const pollingPromise = (async () => {
|
||||
while (!controller.signal.aborted) {
|
||||
await collectSafelyAsync();
|
||||
try {
|
||||
await setTimeoutAsync(pollIntervalMs, undefined, { signal: controller.signal });
|
||||
} catch (error) {
|
||||
if (!controller.signal.aborted) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
})().catch(error => {
|
||||
logger.warn({ err: error }, 'Appium event collection poller failed.');
|
||||
});
|
||||
|
||||
return {
|
||||
getLastEventObservedAt: eventCollection.getLastEventObservedAt,
|
||||
stopAsync: async () => {
|
||||
controller.abort();
|
||||
await pollingPromise;
|
||||
await collectSafelyAsync();
|
||||
try {
|
||||
await eventCollection.stopAsync();
|
||||
} finally {
|
||||
await fs.promises.rm(eventDirectory, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createAppiumEventSource(eventFile: string): DeviceRunSessionEventSource {
|
||||
return {
|
||||
producer: 'appium',
|
||||
findEventFilesAsync: async () => [eventFile],
|
||||
sourceKeyForFile: file => path.basename(file, path.extname(file)),
|
||||
parseLine: ({ line, sourceKey, sequenceNumber, deviceRunSessionId }) => {
|
||||
if (!line.trim()) {
|
||||
return {};
|
||||
}
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(line);
|
||||
} catch {
|
||||
return { failure: 'invalid-json' };
|
||||
}
|
||||
const result = AppiumCommandSchema.safeParse(parsed);
|
||||
if (!result.success) {
|
||||
return { failure: 'invalid-event' };
|
||||
}
|
||||
const command = result.data;
|
||||
const operationId = `${sourceKey}:${sequenceNumber}`;
|
||||
return {
|
||||
event: {
|
||||
v: 1,
|
||||
eventId: `appium:${deviceRunSessionId}:${operationId}`,
|
||||
ts: new Date(command.endTime).toISOString(),
|
||||
producer: 'appium',
|
||||
type: 'operation.completed',
|
||||
operationId,
|
||||
durationMs: Math.max(0, command.endTime - command.startTime),
|
||||
summary: command.cmd,
|
||||
data: {
|
||||
command: command.cmd,
|
||||
appiumSessionId: command.appiumSessionId,
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function collectAppiumCommandsAsync({
|
||||
appiumUrl,
|
||||
eventFile,
|
||||
observedCommandKeys,
|
||||
logger,
|
||||
}: {
|
||||
appiumUrl: string;
|
||||
eventFile: string;
|
||||
observedCommandKeys: Set<string>;
|
||||
logger: bunyan;
|
||||
}): Promise<void> {
|
||||
const response = await turtleFetch(new URL('appium/sessions', appiumUrl).toString(), 'GET', {
|
||||
timeout: APPIUM_REQUEST_TIMEOUT_MS,
|
||||
retries: 0,
|
||||
logger,
|
||||
});
|
||||
const sessions = AppiumSessionsResponseSchema.parse(await response.json()).value;
|
||||
const newCommands: { key: string; command: AppiumCommand }[] = [];
|
||||
const pendingCommandKeys = new Set<string>();
|
||||
|
||||
for (const { id: appiumSessionId } of sessions) {
|
||||
const eventsResponse = await turtleFetch(
|
||||
new URL(`session/${encodeURIComponent(appiumSessionId)}/appium/events`, appiumUrl).toString(),
|
||||
'POST',
|
||||
{
|
||||
json: {},
|
||||
timeout: APPIUM_REQUEST_TIMEOUT_MS,
|
||||
retries: 0,
|
||||
logger,
|
||||
}
|
||||
);
|
||||
const commands = AppiumEventsResponseSchema.parse(await eventsResponse.json()).value.commands;
|
||||
for (const command of commands) {
|
||||
const key = [appiumSessionId, command.cmd, command.startTime, command.endTime].join(':');
|
||||
if (
|
||||
command.cmd === GET_LOG_EVENTS_COMMAND ||
|
||||
observedCommandKeys.has(key) ||
|
||||
pendingCommandKeys.has(key)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
pendingCommandKeys.add(key);
|
||||
newCommands.push({ key, command: { appiumSessionId, ...command } });
|
||||
}
|
||||
}
|
||||
|
||||
if (newCommands.length === 0) {
|
||||
return;
|
||||
}
|
||||
await fs.promises.appendFile(
|
||||
eventFile,
|
||||
`${newCommands.map(({ command }) => JSON.stringify(command)).join('\n')}\n`
|
||||
);
|
||||
for (const { key } of newCommands) {
|
||||
observedCommandKeys.add(key);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { z } from 'zod';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import { createServer } from 'node:net';
|
||||
import { clearTimeout, setTimeout } from 'node:timers';
|
||||
import { setTimeout as setTimeoutAsync } from 'node:timers/promises';
|
||||
|
||||
import { CustomBuildContext } from '../../customBuildContext';
|
||||
@@ -144,77 +145,107 @@ export async function waitForDeviceRunSessionStoppedAsync({
|
||||
ctx,
|
||||
deviceRunSessionId,
|
||||
logger,
|
||||
signal,
|
||||
maxDurationSeconds,
|
||||
signal: cancelSignal,
|
||||
idleTimeout,
|
||||
}: {
|
||||
ctx: CustomBuildContext;
|
||||
deviceRunSessionId: string;
|
||||
logger: bunyan;
|
||||
maxDurationSeconds?: number;
|
||||
signal?: AbortSignal;
|
||||
idleTimeout?: DeviceRunSessionIdleTimeout;
|
||||
}): Promise<void> {
|
||||
logger.info(
|
||||
`Remote session is live. Polling device run session ${deviceRunSessionId} until it is stopped.`
|
||||
);
|
||||
if (idleTimeout) {
|
||||
logger.info(
|
||||
`The session stops automatically after ${idleTimeout.maxIdleTimeMinutes} minute(s) without activity.`
|
||||
);
|
||||
const durationAbortController = new AbortController();
|
||||
const signal = cancelSignal
|
||||
? AbortSignal.any([cancelSignal, durationAbortController.signal])
|
||||
: durationAbortController.signal;
|
||||
// Nothing to wait for if the step was already aborted before we started;
|
||||
// return before logging so we don't claim to be polling a session we never poll.
|
||||
if (signal.aborted) {
|
||||
return;
|
||||
}
|
||||
let pollErrorCount = 0;
|
||||
let lastActivityAt = new Date();
|
||||
const durationTimeout =
|
||||
maxDurationSeconds === undefined
|
||||
? undefined
|
||||
: setTimeout(() => {
|
||||
logger.info(`Device run session ${deviceRunSessionId} reached its maximum duration.`);
|
||||
durationAbortController.abort();
|
||||
}, maxDurationSeconds * 1_000);
|
||||
|
||||
while (!signal?.aborted) {
|
||||
try {
|
||||
logger.info(
|
||||
`Remote session is live. Polling device run session ${deviceRunSessionId} until it is stopped.`
|
||||
);
|
||||
if (durationTimeout !== undefined) {
|
||||
logger.info(
|
||||
`The device run session will stop automatically after ${maxDurationSeconds} seconds.`
|
||||
);
|
||||
}
|
||||
if (idleTimeout) {
|
||||
const lastEventObservedAt = idleTimeout.getLastEventObservedAt();
|
||||
if (lastEventObservedAt && lastEventObservedAt > lastActivityAt) {
|
||||
lastActivityAt = lastEventObservedAt;
|
||||
}
|
||||
if (Date.now() - lastActivityAt.getTime() >= idleTimeout.maxIdleTimeMinutes * 60_000) {
|
||||
logger.info(
|
||||
`Device run session ${deviceRunSessionId} had no activity for ` +
|
||||
`${idleTimeout.maxIdleTimeMinutes} minute(s) (max idle time). Stopping the session.`
|
||||
);
|
||||
await ensureDeviceRunSessionStoppedSafelyAsync({ ctx, deviceRunSessionId, logger });
|
||||
return;
|
||||
}
|
||||
logger.info(
|
||||
`The session stops automatically after ${idleTimeout.maxIdleTimeMinutes} minute(s) without activity.`
|
||||
);
|
||||
}
|
||||
try {
|
||||
const result = await ctx.graphqlClient
|
||||
.query(DEVICE_RUN_SESSION_STATUS_QUERY, { deviceRunSessionId })
|
||||
.toPromise();
|
||||
if (result.error) {
|
||||
throw result.error;
|
||||
}
|
||||
let pollErrorCount = 0;
|
||||
let lastActivityAt = new Date();
|
||||
|
||||
const status = result.data?.deviceRunSessions?.byId?.status;
|
||||
if (!status) {
|
||||
throw new Error(`Device run session ${deviceRunSessionId} status response was missing.`);
|
||||
}
|
||||
pollErrorCount = 0;
|
||||
if (status === 'STOPPED') {
|
||||
logger.info(`Device run session ${deviceRunSessionId} was stopped.`);
|
||||
return;
|
||||
}
|
||||
if (status === 'ERRORED') {
|
||||
throw new SystemError(`Device run session ${deviceRunSessionId} errored.`);
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof SystemError) {
|
||||
throw err;
|
||||
while (!signal.aborted) {
|
||||
if (idleTimeout) {
|
||||
const lastEventObservedAt = idleTimeout.getLastEventObservedAt();
|
||||
if (lastEventObservedAt && lastEventObservedAt > lastActivityAt) {
|
||||
lastActivityAt = lastEventObservedAt;
|
||||
}
|
||||
if (Date.now() - lastActivityAt.getTime() >= idleTimeout.maxIdleTimeMinutes * 60_000) {
|
||||
logger.info(
|
||||
`Device run session ${deviceRunSessionId} had no activity for ` +
|
||||
`${idleTimeout.maxIdleTimeMinutes} minute(s) (max idle time). Stopping the session.`
|
||||
);
|
||||
await ensureDeviceRunSessionStoppedSafelyAsync({ ctx, deviceRunSessionId, logger });
|
||||
return;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const result = await ctx.graphqlClient
|
||||
.query(DEVICE_RUN_SESSION_STATUS_QUERY, { deviceRunSessionId })
|
||||
.toPromise();
|
||||
if (result.error) {
|
||||
throw result.error;
|
||||
}
|
||||
|
||||
const error = err instanceof Error ? err : new Error(String(err));
|
||||
pollErrorCount += 1;
|
||||
if (pollErrorCount === 1 || pollErrorCount % 5 === 0) {
|
||||
Sentry.capture('Could not poll device run session status', error, { level: 'warning' });
|
||||
logger.warn(
|
||||
{ err: error, failedStatusPollCount: pollErrorCount },
|
||||
'Could not poll device run session status; will retry.'
|
||||
);
|
||||
const status = result.data?.deviceRunSessions?.byId?.status;
|
||||
if (!status) {
|
||||
throw new Error(`Device run session ${deviceRunSessionId} status response was missing.`);
|
||||
}
|
||||
pollErrorCount = 0;
|
||||
if (status === 'STOPPED') {
|
||||
logger.info(`Device run session ${deviceRunSessionId} was stopped.`);
|
||||
return;
|
||||
}
|
||||
if (status === 'ERRORED') {
|
||||
throw new SystemError(`Device run session ${deviceRunSessionId} errored.`);
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof SystemError) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
const error = err instanceof Error ? err : new Error(String(err));
|
||||
pollErrorCount += 1;
|
||||
if (pollErrorCount === 1 || pollErrorCount % 5 === 0) {
|
||||
Sentry.capture('Could not poll device run session status', error, { level: 'warning' });
|
||||
logger.warn(
|
||||
{ err: error, failedStatusPollCount: pollErrorCount },
|
||||
'Could not poll device run session status; will retry.'
|
||||
);
|
||||
}
|
||||
}
|
||||
await sleepUntilAbortedAsync(DEVICE_RUN_SESSION_STATUS_POLL_INTERVAL_MS, signal);
|
||||
}
|
||||
} finally {
|
||||
if (durationTimeout !== undefined) {
|
||||
clearTimeout(durationTimeout);
|
||||
}
|
||||
await sleepUntilAbortedAsync(DEVICE_RUN_SESSION_STATUS_POLL_INTERVAL_MS, signal);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -691,7 +722,7 @@ export async function startServeSimWithTunnelAsync(
|
||||
await waitForServeSimReadyAsync({ serveSim, port, timeoutMs });
|
||||
const tunnel = await startNgrokTunnelAsync({
|
||||
port,
|
||||
subdomainPrefix: 'serve-sim',
|
||||
subdomainPrefix: 'web-preview',
|
||||
baseDomain,
|
||||
authtoken: getNgrokAuthtokenOrThrow(env),
|
||||
logger,
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
import { SystemError } from '@expo/eas-build-job';
|
||||
import { bunyan } from '@expo/logger';
|
||||
import { asyncResult } from '@expo/results';
|
||||
import spawn, { SpawnPromise, SpawnResult } from '@expo/turtle-spawn';
|
||||
import assert from 'assert';
|
||||
import FastGlob from 'fast-glob';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import { Socket } from 'node:net';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { setTimeout } from 'node:timers/promises';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { Sentry } from '../sentry';
|
||||
import { retryAsync } from './retry';
|
||||
|
||||
/** Android Virtual Device is the device we run. */
|
||||
@@ -294,10 +298,36 @@ export namespace AndroidEmulatorUtils {
|
||||
export async function startAsync({
|
||||
deviceName,
|
||||
env,
|
||||
logcatDirectory,
|
||||
}: {
|
||||
deviceName: AndroidVirtualDeviceName;
|
||||
env: NodeJS.ProcessEnv;
|
||||
}): Promise<{ emulatorPromise: SpawnPromise<SpawnResult>; serialId: AndroidDeviceSerialId }> {
|
||||
logcatDirectory: string;
|
||||
}): Promise<{
|
||||
emulatorPromise: SpawnPromise<SpawnResult>;
|
||||
serialId: AndroidDeviceSerialId;
|
||||
logcatOutputPath: string;
|
||||
emulatorOutputPath: string;
|
||||
}> {
|
||||
let logcatOutputPath: string;
|
||||
let emulatorOutputPath: string;
|
||||
try {
|
||||
await fs.promises.mkdir(logcatDirectory, { recursive: true });
|
||||
const safeDeviceName = deviceName.replace(/[^a-zA-Z0-9_.-]/g, '_');
|
||||
const timestamp = Math.floor(Date.now() / 1000)
|
||||
.toString(16)
|
||||
.padStart(8, '0');
|
||||
const outputName = `${safeDeviceName}-${timestamp}-${randomBytes(2).toString('hex')}`;
|
||||
logcatOutputPath = path.join(logcatDirectory, `${outputName}-logcat.log`);
|
||||
emulatorOutputPath = path.join(logcatDirectory, `${outputName}-emulator.log`);
|
||||
await fs.promises.writeFile(logcatOutputPath, '');
|
||||
await fs.promises.writeFile(emulatorOutputPath, '');
|
||||
} catch (err) {
|
||||
throw new SystemError(`Failed to prepare Android emulator output for ${deviceName}.`, {
|
||||
cause: err,
|
||||
});
|
||||
}
|
||||
|
||||
const emulatorPromise = spawn(
|
||||
`${process.env.ANDROID_HOME}/emulator/emulator`,
|
||||
[
|
||||
@@ -306,6 +336,10 @@ export namespace AndroidEmulatorUtils {
|
||||
'-writable-system',
|
||||
'-noaudio',
|
||||
'-no-snapshot-save',
|
||||
'-logcat',
|
||||
'*:v',
|
||||
'-logcat-output',
|
||||
logcatOutputPath,
|
||||
'-avd',
|
||||
deviceName,
|
||||
'-accel',
|
||||
@@ -316,7 +350,8 @@ export namespace AndroidEmulatorUtils {
|
||||
],
|
||||
{
|
||||
detached: true,
|
||||
stdio: 'inherit',
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
ignoreStdio: true,
|
||||
env: {
|
||||
...env,
|
||||
// We don't need to wait for emulator to exit gracefully.
|
||||
@@ -324,6 +359,43 @@ export namespace AndroidEmulatorUtils {
|
||||
},
|
||||
}
|
||||
);
|
||||
const emulatorOutputStream = fs.createWriteStream(emulatorOutputPath, { flags: 'a' });
|
||||
let reportedEmulatorOutputError = false;
|
||||
emulatorOutputStream.on('error', err => {
|
||||
process.stderr.write(
|
||||
`Failed to write Android emulator output to ${emulatorOutputPath}: ${err}\n`
|
||||
);
|
||||
if (!reportedEmulatorOutputError) {
|
||||
reportedEmulatorOutputError = true;
|
||||
Sentry.capture('Failed to write Android emulator process output', err, {
|
||||
level: 'warning',
|
||||
tags: {
|
||||
errorCode: (err as NodeJS.ErrnoException).code ?? 'unknown',
|
||||
},
|
||||
extras: {
|
||||
deviceName,
|
||||
emulatorOutputPath,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
// Only into the log file -- this process' stdout/stderr is not watched or uploaded.
|
||||
emulatorPromise.child.stdout?.pipe(emulatorOutputStream, { end: false });
|
||||
emulatorPromise.child.stderr?.pipe(emulatorOutputStream, { end: false });
|
||||
emulatorPromise.child.once('close', () => {
|
||||
emulatorOutputStream.end();
|
||||
});
|
||||
// Piped stdio creates socket handles in this process which, unlike inherited
|
||||
// file descriptors, keep the event loop alive for as long as the emulator runs.
|
||||
// We never stop the emulator explicitly, so without unref-ing these the process
|
||||
// would never exit on its own -- defeating the `detached` + `unref()` below.
|
||||
// Output is still captured for as long as this process lives.
|
||||
if (emulatorPromise.child.stdout instanceof Socket) {
|
||||
emulatorPromise.child.stdout.unref();
|
||||
}
|
||||
if (emulatorPromise.child.stderr instanceof Socket) {
|
||||
emulatorPromise.child.stderr.unref();
|
||||
}
|
||||
// If emulator fails to start, throw its error.
|
||||
if (!emulatorPromise.child.pid) {
|
||||
await emulatorPromise;
|
||||
@@ -352,7 +424,7 @@ export namespace AndroidEmulatorUtils {
|
||||
|
||||
// We don't want to await the SpawnPromise here.
|
||||
// eslint-disable-next-line @typescript-eslint/return-await
|
||||
return { emulatorPromise, serialId };
|
||||
return { emulatorPromise, serialId, logcatOutputPath, emulatorOutputPath };
|
||||
}
|
||||
|
||||
export async function waitForReadyAsync({
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { asyncResult } from '@expo/results';
|
||||
import spawn from '@expo/turtle-spawn';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { setTimeout } from 'timers/promises';
|
||||
|
||||
import { createMockLogger } from '../../__tests__/utils/logger';
|
||||
@@ -16,6 +19,8 @@ jest.unmock('fs');
|
||||
jest.unmock('node:fs');
|
||||
|
||||
describe('AndroidEmulatorUtils', () => {
|
||||
const logcatDirectory = path.join(os.tmpdir(), 'android-emulator-utils-integration-logs');
|
||||
|
||||
beforeEach(async () => {
|
||||
const devices = await AndroidEmulatorUtils.getAttachedDevicesAsync({ env: process.env });
|
||||
for (const { serialId } of devices) {
|
||||
@@ -42,6 +47,7 @@ describe('AndroidEmulatorUtils', () => {
|
||||
console.error('Failed to delete emulator', error);
|
||||
}
|
||||
}
|
||||
await fs.promises.rm(logcatDirectory, { force: true, recursive: true });
|
||||
});
|
||||
|
||||
describe('getAvailableDevicesAsync', () => {
|
||||
@@ -71,6 +77,7 @@ describe('AndroidEmulatorUtils', () => {
|
||||
({ serialId } = await AndroidEmulatorUtils.startAsync({
|
||||
deviceName,
|
||||
env: { ...process.env, ANDROID_EMULATOR_WAIT_TIME_BEFORE_KILL: '1' },
|
||||
logcatDirectory,
|
||||
}));
|
||||
await AndroidEmulatorUtils.waitForReadyAsync({
|
||||
serialId,
|
||||
@@ -94,6 +101,7 @@ describe('AndroidEmulatorUtils', () => {
|
||||
const { serialId, emulatorPromise } = await AndroidEmulatorUtils.startAsync({
|
||||
deviceName,
|
||||
env: { ...process.env, ANDROID_EMULATOR_WAIT_TIME_BEFORE_KILL: '1' },
|
||||
logcatDirectory,
|
||||
});
|
||||
await AndroidEmulatorUtils.waitForReadyAsync({
|
||||
serialId,
|
||||
@@ -123,6 +131,7 @@ describe('AndroidEmulatorUtils', () => {
|
||||
await AndroidEmulatorUtils.startAsync({
|
||||
deviceName: cloneDeviceName,
|
||||
env: { ...process.env, ANDROID_EMULATOR_WAIT_TIME_BEFORE_KILL: '1' },
|
||||
logcatDirectory,
|
||||
});
|
||||
await AndroidEmulatorUtils.waitForReadyAsync({
|
||||
serialId: serialIdClone,
|
||||
@@ -156,6 +165,7 @@ describe('AndroidEmulatorUtils', () => {
|
||||
const { serialId, emulatorPromise } = await AndroidEmulatorUtils.startAsync({
|
||||
deviceName,
|
||||
env: { ...process.env, ANDROID_EMULATOR_WAIT_TIME_BEFORE_KILL: '1' },
|
||||
logcatDirectory,
|
||||
});
|
||||
await AndroidEmulatorUtils.waitForReadyAsync({
|
||||
serialId,
|
||||
@@ -206,6 +216,7 @@ describe('AndroidEmulatorUtils', () => {
|
||||
const startResult = await AndroidEmulatorUtils.startAsync({
|
||||
deviceName,
|
||||
env: envForAttempt,
|
||||
logcatDirectory,
|
||||
});
|
||||
serialId = startResult.serialId;
|
||||
emulatorPromise = asyncResult(startResult.emulatorPromise);
|
||||
@@ -262,6 +273,88 @@ describe('AndroidEmulatorUtils', () => {
|
||||
expect(attemptCounter).toBe(2);
|
||||
}, 360_000);
|
||||
|
||||
it('captures emulator and native logcat output across an ADB server restart', async () => {
|
||||
const testLogcatDirectory = await fs.promises.mkdtemp(
|
||||
path.join(os.tmpdir(), 'android-emulator-logcat-e2e-')
|
||||
);
|
||||
const deviceName =
|
||||
`android-emulator-logcat-e2e-${randomUUID().slice(0, 8)}` as AndroidVirtualDeviceName;
|
||||
let emulatorPromise: Promise<unknown> | null = null;
|
||||
let serialId: AndroidDeviceSerialId | null = null;
|
||||
|
||||
try {
|
||||
const logger = createMockLogger({ logToConsole: true });
|
||||
const marker = `ENG-20762-${randomUUID()}`;
|
||||
|
||||
await AndroidEmulatorUtils.createAsync({
|
||||
deviceName,
|
||||
systemImagePackage: AndroidEmulatorUtils.defaultSystemImagePackage,
|
||||
deviceIdentifier: null,
|
||||
env: process.env,
|
||||
logger,
|
||||
});
|
||||
const startResult = await AndroidEmulatorUtils.startAsync({
|
||||
deviceName,
|
||||
env: { ...process.env, ANDROID_EMULATOR_WAIT_TIME_BEFORE_KILL: '1' },
|
||||
logcatDirectory: testLogcatDirectory,
|
||||
});
|
||||
serialId = startResult.serialId;
|
||||
emulatorPromise = asyncResult(startResult.emulatorPromise);
|
||||
|
||||
await AndroidEmulatorUtils.waitForReadyAsync({ serialId, env: process.env });
|
||||
await retryAsync(
|
||||
async () => {
|
||||
const contents = await fs.promises.readFile(startResult.emulatorOutputPath, 'utf-8');
|
||||
if (!contents.includes('Android emulator version')) {
|
||||
throw new Error('Did not find the emulator version in emulator process output yet.');
|
||||
}
|
||||
},
|
||||
{
|
||||
logger,
|
||||
retryOptions: {
|
||||
retries: 10,
|
||||
retryIntervalMs: 1_000,
|
||||
},
|
||||
}
|
||||
);
|
||||
await spawn('adb', ['kill-server'], { env: process.env });
|
||||
await spawn('adb', ['start-server'], { env: process.env });
|
||||
await spawn('adb', ['-s', serialId, 'shell', 'log', '-t', 'EAS_CLI_TEST', marker], {
|
||||
env: process.env,
|
||||
});
|
||||
|
||||
await retryAsync(
|
||||
async () => {
|
||||
const contents = await fs.promises.readFile(startResult.logcatOutputPath, 'utf-8');
|
||||
if (!contents.includes(marker)) {
|
||||
throw new Error(`Did not find marker ${marker} in logcat output yet.`);
|
||||
}
|
||||
},
|
||||
{
|
||||
logger,
|
||||
retryOptions: {
|
||||
retries: 10,
|
||||
retryIntervalMs: 1_000,
|
||||
},
|
||||
}
|
||||
);
|
||||
} finally {
|
||||
try {
|
||||
await AndroidEmulatorUtils.deleteAsync({
|
||||
...(serialId ? { serialId } : {}),
|
||||
deviceName,
|
||||
env: process.env,
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn('Failed to clean up emulator during logcat integration test', error);
|
||||
}
|
||||
if (emulatorPromise) {
|
||||
await emulatorPromise;
|
||||
}
|
||||
await fs.promises.rm(testLogcatDirectory, { recursive: true, force: true });
|
||||
}
|
||||
}, 180_000);
|
||||
|
||||
it('should work with screen recording', async () => {
|
||||
const deviceName = 'android-emulator-screen-recording-test' as AndroidVirtualDeviceName;
|
||||
await AndroidEmulatorUtils.createAsync({
|
||||
@@ -275,6 +368,7 @@ describe('AndroidEmulatorUtils', () => {
|
||||
const { serialId, emulatorPromise } = await AndroidEmulatorUtils.startAsync({
|
||||
deviceName,
|
||||
env: { ...process.env, ANDROID_EMULATOR_WAIT_TIME_BEFORE_KILL: '1' },
|
||||
logcatDirectory,
|
||||
});
|
||||
|
||||
await AndroidEmulatorUtils.waitForReadyAsync({
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
import { SystemError } from '@expo/eas-build-job';
|
||||
import spawn from '@expo/turtle-spawn';
|
||||
import { EventEmitter, once } from 'node:events';
|
||||
import fs from 'node:fs';
|
||||
import { Socket } from 'node:net';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { createMockLogger } from '../../__tests__/utils/logger';
|
||||
import { AndroidEmulatorUtils } from '../AndroidEmulatorUtils';
|
||||
import { Sentry } from '../../sentry';
|
||||
import { AndroidEmulatorUtils, AndroidVirtualDeviceName } from '../AndroidEmulatorUtils';
|
||||
import { retryAsync } from '../retry';
|
||||
|
||||
jest.mock('@expo/turtle-spawn', () => ({
|
||||
@@ -13,15 +20,154 @@ jest.mock('../retry', () => ({
|
||||
retryAsync: jest.fn(async fn => await fn(0)),
|
||||
}));
|
||||
|
||||
jest.mock('../../sentry', () => ({
|
||||
Sentry: {
|
||||
capture: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockedSpawn = jest.mocked(spawn);
|
||||
const mockedRetryAsync = jest.mocked(retryAsync);
|
||||
|
||||
describe('AndroidEmulatorUtils', () => {
|
||||
let temporaryDirectories: string[] = [];
|
||||
|
||||
beforeEach(() => {
|
||||
temporaryDirectories = [];
|
||||
jest.mocked(Sentry.capture).mockReset();
|
||||
mockedSpawn.mockResolvedValue({ stdout: '', stderr: '' } as any);
|
||||
mockedRetryAsync.mockImplementation(async fn => await fn(0));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
jest.restoreAllMocks();
|
||||
await Promise.all(
|
||||
temporaryDirectories.map(async temporaryDirectory => {
|
||||
await fs.promises.rm(temporaryDirectory, { force: true, recursive: true });
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
describe(AndroidEmulatorUtils.startAsync, () => {
|
||||
function mockSuccessfulStart(deviceName: AndroidVirtualDeviceName) {
|
||||
// Under `stdio: 'pipe'` these are net.Sockets, which is what startAsync
|
||||
// narrows on before unref-ing them.
|
||||
const stdout = new Socket();
|
||||
const stderr = new Socket();
|
||||
jest.spyOn(stdout, 'unref').mockReturnValue(stdout);
|
||||
jest.spyOn(stderr, 'unref').mockReturnValue(stderr);
|
||||
const child = Object.assign(new EventEmitter(), {
|
||||
pid: 1234,
|
||||
unref: jest.fn(),
|
||||
stdout,
|
||||
stderr,
|
||||
});
|
||||
const spawnPromise = Promise.resolve({ stdout: '', stderr: '' }) as any;
|
||||
spawnPromise.child = child;
|
||||
mockedSpawn.mockImplementation(((command: string, args: string[]) => {
|
||||
if (command.endsWith('/emulator/emulator')) {
|
||||
return spawnPromise;
|
||||
}
|
||||
if (command === 'adb' && args[0] === 'devices') {
|
||||
return Promise.resolve({ stdout: 'emulator-5554\tdevice\n', stderr: '' });
|
||||
}
|
||||
if (command === 'adb' && args[0] === '-s' && args[2] === 'emu') {
|
||||
return Promise.resolve({ stdout: `${deviceName}\nOK\n`, stderr: '' });
|
||||
}
|
||||
throw new Error(`Unexpected command: ${command} ${args.join(' ')}`);
|
||||
}) as any);
|
||||
return { child };
|
||||
}
|
||||
|
||||
it('captures logcat and emulator process output', async () => {
|
||||
const outputDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'logcat-staging-'));
|
||||
temporaryDirectories.push(outputDir);
|
||||
const deviceName = 'eas-simulator' as AndroidVirtualDeviceName;
|
||||
const { child } = mockSuccessfulStart(deviceName);
|
||||
const createWriteStreamSpy = jest.spyOn(fs, 'createWriteStream');
|
||||
|
||||
const result = await AndroidEmulatorUtils.startAsync({
|
||||
deviceName,
|
||||
env: process.env,
|
||||
logcatDirectory: outputDir,
|
||||
});
|
||||
|
||||
expect(result.logcatOutputPath).toMatch(
|
||||
new RegExp(`^${outputDir}/eas-simulator-[a-f0-9]{8}-[a-f0-9]{4}-logcat\\.log$`)
|
||||
);
|
||||
expect(result.emulatorOutputPath).toMatch(
|
||||
new RegExp(`^${outputDir}/eas-simulator-[a-f0-9]{8}-[a-f0-9]{4}-emulator\\.log$`)
|
||||
);
|
||||
await expect(fs.promises.access(result.logcatOutputPath)).resolves.toBeUndefined();
|
||||
await expect(fs.promises.access(result.emulatorOutputPath)).resolves.toBeUndefined();
|
||||
expect(mockedSpawn).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/\/emulator\/emulator$/),
|
||||
expect.arrayContaining(['-logcat', '*:v', '-logcat-output', result.logcatOutputPath]),
|
||||
expect.objectContaining({
|
||||
detached: true,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
ignoreStdio: true,
|
||||
})
|
||||
);
|
||||
expect(mockedSpawn).not.toHaveBeenCalledWith(
|
||||
'adb',
|
||||
expect.arrayContaining(['logcat']),
|
||||
expect.anything()
|
||||
);
|
||||
expect(child.unref).toHaveBeenCalled();
|
||||
// Piped stdio would otherwise keep this process' event loop alive
|
||||
// for as long as the emulator runs.
|
||||
expect(child.stdout.unref).toHaveBeenCalled();
|
||||
expect(child.stderr.unref).toHaveBeenCalled();
|
||||
const emulatorOutputStream = createWriteStreamSpy.mock.results[0].value;
|
||||
const stderrWriteSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => true);
|
||||
const writeError = Object.assign(new Error('disk full'), { code: 'ENOSPC' });
|
||||
emulatorOutputStream.emit('error', writeError);
|
||||
emulatorOutputStream.emit('error', writeError);
|
||||
expect(stderrWriteSpy).toHaveBeenCalledTimes(2);
|
||||
expect(Sentry.capture).toHaveBeenCalledTimes(1);
|
||||
expect(Sentry.capture).toHaveBeenCalledWith(
|
||||
'Failed to write Android emulator process output',
|
||||
writeError,
|
||||
{
|
||||
level: 'warning',
|
||||
tags: { errorCode: 'ENOSPC' },
|
||||
extras: {
|
||||
deviceName,
|
||||
emulatorOutputPath: result.emulatorOutputPath,
|
||||
},
|
||||
}
|
||||
);
|
||||
const emulatorOutputStreamClosed = once(emulatorOutputStream, 'close');
|
||||
child.emit('close');
|
||||
await emulatorOutputStreamClosed;
|
||||
});
|
||||
|
||||
it('throws a SystemError when the staging directory cannot be prepared', async () => {
|
||||
const outputDir = '/unwritable/logcat-staging';
|
||||
const deviceName = 'eas-simulator' as AndroidVirtualDeviceName;
|
||||
const mkdirError = new Error('mkdir failed');
|
||||
const mkdirSpy = jest.spyOn(fs.promises, 'mkdir').mockRejectedValueOnce(mkdirError);
|
||||
|
||||
try {
|
||||
await expect(
|
||||
AndroidEmulatorUtils.startAsync({
|
||||
deviceName,
|
||||
env: process.env,
|
||||
logcatDirectory: outputDir,
|
||||
})
|
||||
).rejects.toEqual(
|
||||
new SystemError('Failed to prepare Android emulator output for eas-simulator.', {
|
||||
cause: mkdirError,
|
||||
})
|
||||
);
|
||||
expect(mockedSpawn).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
mkdirSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe(AndroidEmulatorUtils.waitForReadyAsync, () => {
|
||||
it('checks boot completion and verifies network with netcat to 1.1.1.1:443', async () => {
|
||||
mockedSpawn.mockImplementation((async (_command: string, args: string[]) => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import resolveFrom from 'resolve-from';
|
||||
import spawnAsync from '@expo/turtle-spawn';
|
||||
|
||||
import { expoCommandAsync, ExpoCLIModuleNotFoundError } from '../expoCli';
|
||||
import { ExpoCLIModuleNotFoundError, expoCommandAsync } from '../expoCli';
|
||||
|
||||
jest.mock('resolve-from', () => ({
|
||||
__esModule: true,
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import { BuildJob, ManagedArtifactType } from '@expo/eas-build-job';
|
||||
import fs from 'fs-extra';
|
||||
import { vol } from 'memfs';
|
||||
|
||||
import { createTestAndroidJob, createTestIosJob } from '../../__tests__/utils/job';
|
||||
import { createMockLogger } from '../../__tests__/utils/logger';
|
||||
import { BuildContext } from '../../context';
|
||||
import { maybeUploadSourceMapAsync, resolveIosSourceMapPathAsync } from '../sourceMaps';
|
||||
|
||||
function enableSourceMapUpload<TJob extends BuildJob>(job: TJob): TJob {
|
||||
return {
|
||||
...job,
|
||||
experimental: {
|
||||
...job.experimental,
|
||||
uploadSourceMaps: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createContext<TJob extends BuildJob>(
|
||||
job: TJob,
|
||||
env: Record<string, string> = {}
|
||||
): { ctx: BuildContext<TJob>; uploadArtifact: jest.Mock } {
|
||||
const uploadArtifact = jest.fn(async () => ({ filename: null }));
|
||||
const ctx = new BuildContext(job, {
|
||||
workingdir: '/workingdir',
|
||||
logBuffer: { getLogs: () => [], getPhaseLogs: () => [] },
|
||||
logger: createMockLogger(),
|
||||
env: {
|
||||
__API_SERVER_URL: 'http://api.expo.test',
|
||||
EAS_BUILD_RUNNER: 'eas-build',
|
||||
...env,
|
||||
},
|
||||
uploadArtifact,
|
||||
});
|
||||
return { ctx, uploadArtifact };
|
||||
}
|
||||
|
||||
describe(maybeUploadSourceMapAsync.name, () => {
|
||||
it('uploads the final Android source map without sourcesContent', async () => {
|
||||
const finalSourceMapPath =
|
||||
'/workingdir/build/android/app/build/generated/sourcemaps/react/release/index.android.bundle.map';
|
||||
vol.fromJSON({
|
||||
[finalSourceMapPath]: JSON.stringify({
|
||||
version: 3,
|
||||
sources: ['App.tsx'],
|
||||
sourcesContent: ['customer source'],
|
||||
names: [],
|
||||
mappings: '',
|
||||
sections: [
|
||||
{
|
||||
map: {
|
||||
version: 3,
|
||||
sources: ['nested.ts'],
|
||||
sourcesContent: ['nested customer source'],
|
||||
names: [],
|
||||
mappings: '',
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
[`${finalSourceMapPath.slice(0, -4)}.packager.map`]: JSON.stringify({ version: 3 }),
|
||||
[`${finalSourceMapPath.slice(0, -4)}.compiler.map`]: JSON.stringify({ version: 3 }),
|
||||
});
|
||||
const { ctx, uploadArtifact } = createContext(enableSourceMapUpload(createTestAndroidJob()));
|
||||
|
||||
await maybeUploadSourceMapAsync(ctx);
|
||||
|
||||
expect(uploadArtifact).toHaveBeenCalledWith({
|
||||
artifact: {
|
||||
type: ManagedArtifactType.SOURCE_MAP,
|
||||
paths: ['/workingdir/observe-source-maps/android.map'],
|
||||
},
|
||||
logger: ctx.logger,
|
||||
});
|
||||
const uploadedSourceMap = await fs.readJson('/workingdir/observe-source-maps/android.map');
|
||||
expect(uploadedSourceMap).not.toHaveProperty('sourcesContent');
|
||||
expect(uploadedSourceMap.sections[0].map).not.toHaveProperty('sourcesContent');
|
||||
});
|
||||
|
||||
it('does not guess when an Android build produces multiple final source maps', async () => {
|
||||
vol.fromJSON({
|
||||
'/workingdir/build/android/app/build/generated/sourcemaps/react/release/one.map':
|
||||
JSON.stringify({ version: 3 }),
|
||||
'/workingdir/build/android/other/build/generated/sourcemaps/react/release/two.map':
|
||||
JSON.stringify({ version: 3 }),
|
||||
});
|
||||
const { ctx, uploadArtifact } = createContext(enableSourceMapUpload(createTestAndroidJob()));
|
||||
const markBuildPhaseHasWarnings = jest.spyOn(ctx, 'markBuildPhaseHasWarnings');
|
||||
|
||||
await expect(maybeUploadSourceMapAsync(ctx)).resolves.toBeUndefined();
|
||||
|
||||
expect(uploadArtifact).not.toHaveBeenCalled();
|
||||
expect(markBuildPhaseHasWarnings).toHaveBeenCalled();
|
||||
expect(ctx.logger.warn).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ err: expect.any(Error) }),
|
||||
'Failed to upload source map.'
|
||||
);
|
||||
});
|
||||
|
||||
it('does nothing when source-map upload is disabled', async () => {
|
||||
const { ctx, uploadArtifact } = createContext(createTestAndroidJob());
|
||||
|
||||
await maybeUploadSourceMapAsync(ctx);
|
||||
|
||||
expect(uploadArtifact).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not upload source maps from local builds', async () => {
|
||||
const { ctx, uploadArtifact } = createContext(enableSourceMapUpload(createTestAndroidJob()), {
|
||||
EAS_BUILD_RUNNER: 'local-build-plugin',
|
||||
});
|
||||
|
||||
await maybeUploadSourceMapAsync(ctx);
|
||||
|
||||
expect(uploadArtifact).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe(resolveIosSourceMapPathAsync.name, () => {
|
||||
it('uses an absolute worker-owned path by default', async () => {
|
||||
const { ctx } = createContext(createTestIosJob());
|
||||
|
||||
await expect(resolveIosSourceMapPathAsync(ctx)).resolves.toBe(
|
||||
'/workingdir/observe-source-maps/main.jsbundle.map'
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves a configured path relative to the iOS project', async () => {
|
||||
const { ctx } = createContext(createTestIosJob(), {
|
||||
SOURCEMAP_FILE: 'build/custom/main.jsbundle.map',
|
||||
});
|
||||
|
||||
await expect(resolveIosSourceMapPathAsync(ctx)).resolves.toBe(
|
||||
'/workingdir/build/ios/build/custom/main.jsbundle.map'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import { BuildJob, ManagedArtifactType, Platform, SystemError } from '@expo/eas-build-job';
|
||||
import fg from 'fast-glob';
|
||||
import fs from 'fs-extra';
|
||||
import path from 'path';
|
||||
|
||||
import { BuildContext } from '../context';
|
||||
|
||||
const ANDROID_SOURCE_MAP_PATTERN = 'android/**/build/generated/sourcemaps/react/**/*.map';
|
||||
const SOURCE_MAP_UPLOAD_DIRECTORY = 'observe-source-maps';
|
||||
|
||||
export function isSourceMapUploadEnabled(ctx: BuildContext<BuildJob>): boolean {
|
||||
return !ctx.isLocal && ctx.job.experimental?.uploadSourceMaps === true;
|
||||
}
|
||||
|
||||
export async function resolveIosSourceMapPathAsync(ctx: BuildContext<BuildJob>): Promise<string> {
|
||||
const configuredPath = ctx.env.SOURCEMAP_FILE;
|
||||
const sourceMapPath = configuredPath
|
||||
? path.resolve(ctx.getReactNativeProjectDirectory(), 'ios', configuredPath)
|
||||
: path.join(ctx.workingdir, SOURCE_MAP_UPLOAD_DIRECTORY, 'main.jsbundle.map');
|
||||
|
||||
await fs.ensureDir(path.dirname(sourceMapPath));
|
||||
return sourceMapPath;
|
||||
}
|
||||
|
||||
export async function maybeUploadSourceMapAsync(ctx: BuildContext<BuildJob>): Promise<void> {
|
||||
if (!isSourceMapUploadEnabled(ctx)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const sourceMapPath = await resolveSourceMapPathAsync(ctx);
|
||||
const strippedSourceMapPath = await stripSourcesContentAsync(ctx, sourceMapPath);
|
||||
|
||||
ctx.logger.info(`Uploading source map: ${sourceMapPath}`);
|
||||
await ctx.uploadArtifact({
|
||||
artifact: {
|
||||
type: ManagedArtifactType.SOURCE_MAP,
|
||||
paths: [strippedSourceMapPath],
|
||||
},
|
||||
logger: ctx.logger,
|
||||
});
|
||||
} catch (err: any) {
|
||||
ctx.logger.warn({ err }, 'Failed to upload source map.');
|
||||
ctx.markBuildPhaseHasWarnings();
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveSourceMapPathAsync(ctx: BuildContext<BuildJob>): Promise<string> {
|
||||
if (ctx.job.platform === Platform.IOS) {
|
||||
const sourceMapPath = await resolveIosSourceMapPathAsync(ctx);
|
||||
if (!(await fs.pathExists(sourceMapPath))) {
|
||||
throw new SystemError(`The iOS source map was not generated at ${sourceMapPath}.`);
|
||||
}
|
||||
return sourceMapPath;
|
||||
}
|
||||
|
||||
if (ctx.job.platform === Platform.ANDROID) {
|
||||
const projectDir = ctx.getReactNativeProjectDirectory();
|
||||
const sourceMapPaths = (
|
||||
await fg(ANDROID_SOURCE_MAP_PATTERN, {
|
||||
absolute: true,
|
||||
cwd: projectDir,
|
||||
onlyFiles: true,
|
||||
})
|
||||
).filter(sourceMapPath => !isIntermediateAndroidSourceMap(sourceMapPath));
|
||||
|
||||
if (sourceMapPaths.length === 0) {
|
||||
throw new SystemError('The Android build did not generate a final composed source map.');
|
||||
}
|
||||
if (sourceMapPaths.length > 1) {
|
||||
throw new SystemError(
|
||||
`Found multiple final Android source maps: ${sourceMapPaths.join(', ')}. ` +
|
||||
'Refusing to upload a source map that may not match the application archive.'
|
||||
);
|
||||
}
|
||||
return sourceMapPaths[0];
|
||||
}
|
||||
|
||||
throw new SystemError('Source-map upload is not supported for this build platform.');
|
||||
}
|
||||
|
||||
function isIntermediateAndroidSourceMap(sourceMapPath: string): boolean {
|
||||
return sourceMapPath.endsWith('.packager.map') || sourceMapPath.endsWith('.compiler.map');
|
||||
}
|
||||
|
||||
async function stripSourcesContentAsync(
|
||||
ctx: BuildContext<BuildJob>,
|
||||
sourceMapPath: string
|
||||
): Promise<string> {
|
||||
const sourceMap = JSON.parse(await fs.readFile(sourceMapPath, 'utf8')) as unknown;
|
||||
if (!isRecord(sourceMap) || sourceMap.version !== 3) {
|
||||
throw new SystemError(`Invalid source map at ${sourceMapPath}.`);
|
||||
}
|
||||
|
||||
removeSourcesContent(sourceMap);
|
||||
|
||||
const uploadDirectory = path.join(ctx.workingdir, SOURCE_MAP_UPLOAD_DIRECTORY);
|
||||
const uploadPath = path.join(uploadDirectory, `${ctx.job.platform}.map`);
|
||||
await fs.ensureDir(uploadDirectory);
|
||||
await fs.writeFile(uploadPath, JSON.stringify(sourceMap), 'utf8');
|
||||
return uploadPath;
|
||||
}
|
||||
|
||||
function removeSourcesContent(value: unknown): void {
|
||||
if (Array.isArray(value)) {
|
||||
for (const child of value) {
|
||||
removeSourcesContent(child);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!isRecord(value)) {
|
||||
return;
|
||||
}
|
||||
|
||||
delete value.sourcesContent;
|
||||
for (const child of Object.values(value)) {
|
||||
removeSourcesContent(child);
|
||||
}
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "create-eas-build-function",
|
||||
"version": "21.7.1",
|
||||
"version": "22.2.0",
|
||||
"description": "Create functions for use in EAS Build custom builds.",
|
||||
"keywords": [
|
||||
"expo",
|
||||
@@ -26,7 +26,7 @@
|
||||
},
|
||||
"scripts": {
|
||||
"prepack": "yarn run clean && yarn run build",
|
||||
"lint": "oxlint --type-aware --tsconfig ../../tsconfig.oxlint.json .",
|
||||
"lint": "oxlint --type-aware --max-warnings=0 --tsconfig ../../tsconfig.oxlint.json .",
|
||||
"test": "echo 'No tests yet.'",
|
||||
"watch": "yarn run build:dev -w",
|
||||
"build:dev": "ncc build ./src/index.ts -o build/",
|
||||
@@ -35,7 +35,7 @@
|
||||
"clean": "rimraf ./build/ \"*.tsbuildinfo\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@expo/steps": "21.7.1"
|
||||
"@expo/steps": "22.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/package-manager": "1.9.10",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/downloader",
|
||||
"version": "21.0.0",
|
||||
"version": "22.0.0",
|
||||
"bugs": "https://github.com/expo/eas-cli/issues",
|
||||
"license": "BUSL-1.1",
|
||||
"author": "Expo <[email protected]>",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "eas-build-cache-provider",
|
||||
"version": "21.0.0",
|
||||
"version": "22.0.0",
|
||||
"description": "A build cache provider plugin for the Expo CLI",
|
||||
"homepage": "https://github.com/expo/eas-cli",
|
||||
"bugs": "https://github.com/expo/eas-cli/issues",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/eas-build-job",
|
||||
"version": "21.6.0",
|
||||
"version": "22.0.0",
|
||||
"bugs": "https://github.com/expo/eas-cli/issues",
|
||||
"license": "MIT",
|
||||
"author": "Expo <[email protected]>",
|
||||
@@ -25,9 +25,9 @@
|
||||
"clean": "rimraf node_modules dist coverage \"*.tsbuildinfo\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@expo/logger": "21.0.0",
|
||||
"@expo/logger": "22.0.0",
|
||||
"@expo/results": "1.0.0",
|
||||
"@expo/turtle-spawn": "21.0.0",
|
||||
"@expo/turtle-spawn": "22.0.0",
|
||||
"joi": "^17.13.1",
|
||||
"semver": "^7.6.2",
|
||||
"zod": "^4.3.5"
|
||||
|
||||
@@ -47,6 +47,9 @@ describe('Android.JobSchema', () => {
|
||||
},
|
||||
},
|
||||
expoBuildUrl: 'https://expo.dev/fake/build/url',
|
||||
experimental: {
|
||||
uploadSourceMaps: true,
|
||||
},
|
||||
initiatingUserId: randomUUID(),
|
||||
appId: randomUUID(),
|
||||
};
|
||||
|
||||
@@ -49,6 +49,9 @@ describe('Ios.JobSchema', () => {
|
||||
},
|
||||
},
|
||||
expoBuildUrl: 'https://expo.dev/fake/build/url',
|
||||
experimental: {
|
||||
uploadSourceMaps: true,
|
||||
},
|
||||
initiatingUserId: randomUUID(),
|
||||
appId: randomUUID(),
|
||||
};
|
||||
|
||||
@@ -119,6 +119,7 @@ export interface Job {
|
||||
|
||||
experimental?: {
|
||||
prebuildCommand?: string;
|
||||
uploadSourceMaps?: boolean;
|
||||
};
|
||||
expoBuildUrl?: string;
|
||||
githubTriggerOptions?: {
|
||||
@@ -186,6 +187,7 @@ export const JobSchema = Joi.object({
|
||||
|
||||
experimental: Joi.object({
|
||||
prebuildCommand: Joi.string(),
|
||||
uploadSourceMaps: Joi.boolean(),
|
||||
}),
|
||||
expoBuildUrl: Joi.string().uri().optional(),
|
||||
githubTriggerOptions: Joi.object({
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
export enum ManagedArtifactType {
|
||||
APPLICATION_ARCHIVE = 'APPLICATION_ARCHIVE',
|
||||
BUILD_ARTIFACTS = 'BUILD_ARTIFACTS',
|
||||
SOURCE_MAP = 'SOURCE_MAP',
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
|
||||
@@ -133,6 +133,7 @@ export interface Job {
|
||||
|
||||
experimental?: {
|
||||
prebuildCommand?: string;
|
||||
uploadSourceMaps?: boolean;
|
||||
};
|
||||
expoBuildUrl?: string;
|
||||
githubTriggerOptions?: {
|
||||
@@ -222,6 +223,7 @@ export const JobSchema = Joi.object({
|
||||
|
||||
experimental: Joi.object({
|
||||
prebuildCommand: Joi.string(),
|
||||
uploadSourceMaps: Joi.boolean(),
|
||||
}),
|
||||
expoBuildUrl: Joi.string().uri().optional(),
|
||||
githubTriggerOptions: Joi.object({
|
||||
|
||||
+297
-179
File diff suppressed because it is too large.
Load diff
Generated
+1848
-61
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "eas-cli",
|
||||
"version": "21.7.1",
|
||||
"version": "22.2.0",
|
||||
"description": "EAS command line tool",
|
||||
"keywords": [
|
||||
"cli",
|
||||
@@ -48,11 +48,11 @@
|
||||
"@expo/code-signing-certificates": "0.0.5",
|
||||
"@expo/config": "55.0.10",
|
||||
"@expo/config-plugins": "55.0.7",
|
||||
"@expo/eas-build-job": "21.6.0",
|
||||
"@expo/eas-json": "21.6.0",
|
||||
"@expo/eas-build-job": "22.0.0",
|
||||
"@expo/eas-json": "22.0.0",
|
||||
"@expo/env": "^1.0.0",
|
||||
"@expo/json-file": "8.3.3",
|
||||
"@expo/logger": "21.0.0",
|
||||
"@expo/logger": "22.0.0",
|
||||
"@expo/multipart-body-parser": "2.0.0",
|
||||
"@expo/osascript": "2.1.4",
|
||||
"@expo/package-manager": "1.9.10",
|
||||
@@ -64,7 +64,7 @@
|
||||
"@expo/results": "1.0.0",
|
||||
"@expo/rudder-sdk-node": "1.1.1",
|
||||
"@expo/spawn-async": "1.7.2",
|
||||
"@expo/steps": "21.7.1",
|
||||
"@expo/steps": "22.1.0",
|
||||
"@expo/timeago.js": "1.0.0",
|
||||
"@oclif/core": "^4.8.3",
|
||||
"@oclif/plugin-autocomplete": "^3.2.40",
|
||||
@@ -72,7 +72,7 @@
|
||||
"@sentry/node": "7.77.0",
|
||||
"@urql/core": "4.0.11",
|
||||
"@urql/exchange-retry": "1.2.0",
|
||||
"agent-cli-detector": "0.1.2",
|
||||
"agent-cli-detector": "0.1.6",
|
||||
"ajv": "8.11.0",
|
||||
"ajv-formats": "2.1.1",
|
||||
"better-opn": "3.0.2",
|
||||
|
||||
@@ -11,7 +11,7 @@ import { getPrivateExpoConfigAsync } from '../../project/expoConfig';
|
||||
import { uploadAccountScopedFileAsync } from '../../project/uploadAccountScopedFileAsync';
|
||||
import { uploadAccountScopedProjectSourceAsync } from '../../project/uploadAccountScopedProjectSourceAsync';
|
||||
import { ensureActorHasPrimaryAccount } from '../../user/actions';
|
||||
import { detectProjectSdkVersionAsync } from '../../commands/go';
|
||||
import { detectProjectSdkVersionAsync, toRepackTargetSdkVersion } from '../../commands/go';
|
||||
import { mockTestCommand } from './utils';
|
||||
|
||||
jest.mock('@expo/config', () => ({
|
||||
@@ -81,6 +81,25 @@ describe('detectProjectSdkVersionAsync', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('toRepackTargetSdkVersion', () => {
|
||||
it.each([
|
||||
['57', '57.0.0'],
|
||||
['57.0.0', '57.0.0'],
|
||||
['57.0.9', '57.0.0'],
|
||||
['57.0.0-canary-20260101', '57.0.0'],
|
||||
])('resolves %s to the %s repack target', (sdkVersion, expected) => {
|
||||
expect(toRepackTargetSdkVersion(sdkVersion)).toBe(expected);
|
||||
});
|
||||
|
||||
it('returns undefined when no version is requested', () => {
|
||||
expect(toRepackTargetSdkVersion(undefined)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns the requested version unchanged when it holds no version number', () => {
|
||||
expect(toRepackTargetSdkVersion('latest')).toBe('latest');
|
||||
});
|
||||
});
|
||||
|
||||
const mockAccount = { id: 'account-id', name: 'testuser' };
|
||||
const mockActor = {
|
||||
__typename: 'User' as const,
|
||||
@@ -112,7 +131,7 @@ describe('Go command', () => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
function makeCmd(argv: string[] = []) {
|
||||
function makeCmd(argv: string[] = []): Go {
|
||||
const ctx = {
|
||||
loggedIn: { actor: mockActor as any, graphqlClient: {} as any },
|
||||
analytics: {} as any,
|
||||
@@ -149,6 +168,17 @@ describe('Go command', () => {
|
||||
expect(Log.log).not.toHaveBeenCalledWith(expect.stringContaining('Auto-selected'));
|
||||
});
|
||||
|
||||
it('requests the repack configuration with the repack target SDK version', async () => {
|
||||
mockGetConfigFilePaths.mockReturnValue({ staticConfigPath: null, dynamicConfigPath: null });
|
||||
|
||||
await makeCmd(['--sdk-version', '57']).run();
|
||||
|
||||
expect(WorkflowRunQuery.expoGoRepackConfigurationAsync).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({ sdkVersion: '57.0.0' })
|
||||
);
|
||||
});
|
||||
|
||||
it('prompts for SDK version when no project config is found', async () => {
|
||||
mockGetConfigFilePaths.mockReturnValue({ staticConfigPath: null, dynamicConfigPath: null });
|
||||
jest.mocked(WorkflowRunQuery.expoGoSupportedSdkVersionsAsync).mockResolvedValue([
|
||||
|
||||
@@ -38,14 +38,9 @@ export function getMockAppFragment(): AppFragment {
|
||||
ownerAccount: {
|
||||
id: 'test-account-id',
|
||||
name: 'testuser',
|
||||
users: [
|
||||
{
|
||||
role: Role.Owner,
|
||||
actor: {
|
||||
id: 'test-user-id',
|
||||
},
|
||||
},
|
||||
],
|
||||
viewerUserPermission: {
|
||||
role: Role.Owner,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -180,7 +180,7 @@ describe(WorkflowLogView, () => {
|
||||
createdAt: '2022-01-01T00:00:00.000Z',
|
||||
updatedAt: '2022-01-01T00:00:00.000Z',
|
||||
isForIosSimulator: false,
|
||||
project: {
|
||||
app: {
|
||||
id: mockProjectId,
|
||||
__typename: 'App',
|
||||
name: 'App',
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import crypto from 'node:crypto';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import fs from 'fs-extra';
|
||||
|
||||
import { computeFileMd5Base64Async } from '../uploads';
|
||||
|
||||
describe(computeFileMd5Base64Async, () => {
|
||||
let tmpDir: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'eas-cli-uploads-test-'));
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await fs.remove(tmpDir);
|
||||
});
|
||||
|
||||
it('computes the base64 MD5 checksum of a small file', async () => {
|
||||
const file = path.join(tmpDir, 'small.txt');
|
||||
await fs.writeFile(file, 'abc');
|
||||
// md5("abc") = 900150983cd24fb0d6963f7d28e17f72
|
||||
expect(await computeFileMd5Base64Async(file)).toBe('kAFQmDzST7DWlj99KOF/cg==');
|
||||
});
|
||||
|
||||
it('computes the same checksum as a one-shot hash for a file larger than one stream chunk', async () => {
|
||||
const file = path.join(tmpDir, 'large.bin');
|
||||
const data = Buffer.alloc(256 * 1024);
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
data[i] = i % 251;
|
||||
}
|
||||
await fs.writeFile(file, data);
|
||||
const expected = crypto.createHash('md5').update(data).digest('base64');
|
||||
expect(await computeFileMd5Base64Async(file)).toBe(expected);
|
||||
});
|
||||
});
|
||||
@@ -74,7 +74,7 @@ function createMockBuildFragment({
|
||||
id: buildId ?? uuid(),
|
||||
logFiles: [],
|
||||
priority: BuildPriority.Normal,
|
||||
project: {
|
||||
app: {
|
||||
__typename: 'App',
|
||||
slug: 'test-project',
|
||||
id: projectId,
|
||||
|
||||
@@ -74,7 +74,7 @@ function createMockBuildFragment({
|
||||
platform: AppPlatform.Android,
|
||||
id: buildId ?? uuid(),
|
||||
priority: BuildPriority.Normal,
|
||||
project: {
|
||||
app: {
|
||||
__typename: 'App',
|
||||
slug: 'test-project',
|
||||
id: projectId,
|
||||
|
||||
@@ -104,6 +104,7 @@ export async function prepareJobAsync(
|
||||
}),
|
||||
experimental: {
|
||||
prebuildCommand: buildProfile.prebuildCommand,
|
||||
uploadSourceMaps: buildProfile.uploadSourceMaps,
|
||||
},
|
||||
mode: buildMode,
|
||||
triggeredBy: BuildTrigger.EAS_CLI,
|
||||
|
||||
@@ -99,6 +99,7 @@ export async function prepareJobAsync(
|
||||
}),
|
||||
experimental: {
|
||||
prebuildCommand: buildProfile.prebuildCommand,
|
||||
uploadSourceMaps: buildProfile.uploadSourceMaps,
|
||||
},
|
||||
mode: buildMode,
|
||||
triggeredBy: BuildTrigger.EAS_CLI,
|
||||
|
||||
@@ -76,7 +76,6 @@ export async function collectMetadataAsync<T extends Platform>(
|
||||
customWorkflowName: ctx.customBuildConfigMetadata?.workflowName,
|
||||
developmentClient: ctx.developmentClient,
|
||||
requiredPackageManager: ctx.requiredPackageManager ?? undefined,
|
||||
selectedImage: ctx.buildProfile.image,
|
||||
customNodeVersion: ctx.buildProfile.node,
|
||||
simulator: 'simulator' in ctx.buildProfile && ctx.buildProfile.simulator,
|
||||
};
|
||||
|
||||
@@ -597,7 +597,7 @@ export async function downloadAndRunAsync(
|
||||
simulator?: SimulatorRunTarget
|
||||
): Promise<void> {
|
||||
assert(build.artifacts?.applicationArchiveUrl);
|
||||
const cachedAppPath = getEasBuildRunCachedAppPath(build.project.id, build.id, build.platform);
|
||||
const cachedAppPath = getEasBuildRunCachedAppPath(build.app.id, build.id, build.platform);
|
||||
|
||||
if (await pathExists(cachedAppPath)) {
|
||||
Log.newLine();
|
||||
|
||||
@@ -93,7 +93,7 @@ export function formatGraphQLBuild(build: BuildFragment): string {
|
||||
},
|
||||
{
|
||||
label: 'Channel',
|
||||
value: build.channel,
|
||||
value: build.updateChannel?.name,
|
||||
},
|
||||
{
|
||||
label: 'SDK Version',
|
||||
@@ -101,7 +101,7 @@ export function formatGraphQLBuild(build: BuildFragment): string {
|
||||
},
|
||||
{
|
||||
label: 'Runtime Version',
|
||||
value: build.runtimeVersion,
|
||||
value: build.runtime?.version,
|
||||
},
|
||||
{
|
||||
label: 'Version',
|
||||
|
||||
@@ -19,13 +19,10 @@ export function getProjectPageUrl(
|
||||
}
|
||||
|
||||
export function getBuildLogsUrl(build: BuildFragment, hash?: string): string {
|
||||
const { project } = build;
|
||||
const url =
|
||||
project.__typename !== 'App'
|
||||
? `/builds/${build.id}`
|
||||
: `/accounts/${project.ownerAccount.name}/projects/${project.slug}/builds/${build.id}${
|
||||
hash ? `#${hash}` : ''
|
||||
}`;
|
||||
const { app } = build;
|
||||
const url = `/accounts/${app.ownerAccount.name}/projects/${app.slug}/builds/${build.id}${
|
||||
hash ? `#${hash}` : ''
|
||||
}`;
|
||||
|
||||
return new URL(url, getExpoWebsiteBaseUrl()).toString();
|
||||
}
|
||||
@@ -37,7 +34,7 @@ export function getArtifactUrl(artifactId: string): string {
|
||||
export function getInternalDistributionInstallUrl(build: BuildFragment): string {
|
||||
if (build.platform === AppPlatform.Ios) {
|
||||
return `itms-services://?action=download-manifest;url=${getExpoApiBaseUrl()}/v2/projects/${
|
||||
build.project.id
|
||||
build.app.id
|
||||
}/builds/${build.id}/manifest.plist`;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ export const testUpdateBranch1: UpdateBranchObject = {
|
||||
group: '16ca6dba-e63b-48b0-baa3-15a894ee9434',
|
||||
message: 'fix bug',
|
||||
createdAt: '2023-07-17T22:48:59.278Z',
|
||||
runtimeVersion: 'exposdk:48.0.0',
|
||||
runtime: { id: 'runtime-exposdk-48', version: 'exposdk:48.0.0' },
|
||||
platform: 'ios',
|
||||
manifestFragment:
|
||||
'{"extra":{"expoClient":{"ios":{"supportsTablet":true,"bundleIdentifier":"com.quintest113.updatestest4"},"web":{"favicon":"./assets/favicon.png"},"icon":"./assets/icon.png","name":"updates-test-4","slug":"updates-test-4","extra":{"eas":{"projectId":"789a8784-0186-4f41-8bd2-7f219291a2b8"}},"splash":{"image":"./assets/splash.png","resizeMode":"contain","backgroundColor":"#ffffff"},"android":{"package":"com.quintest113.updatestest4","adaptiveIcon":{"backgroundColor":"#ffffff","foregroundImage":"./assets/adaptive-icon.png"}},"updates":{"url":"https://u.expo.dev/789a8784-0186-4f41-8bd2-7f219291a2b8"},"version":"1.0.0","platforms":["ios","android"],"sdkVersion":"48.0.0","orientation":"portrait","runtimeVersion":{"policy":"sdkVersion"},"currentFullName":"@quintest113/updates-test-4","originalFullName":"@quintest113/updates-test-4","userInterfaceStyle":"light","assetBundlePatterns":["**/*"]}},"assets":[{"bundleKey":"7d40544b395c5949f4646f5e150fe020","fileSHA256":"LN_rjlzN55dvcBL7jM5zryIpAp7iHU8VCf7RFIccbNg","storageKey":"Pi65ns2w9xLI5G_m9aGrJ5wK5FpWcGcInSSFwnA_0aA","contentType":"image/png","fileExtension":".png"},{"bundleKey":"cdd04e13d4ec83ff0cd13ec8dabdc341","fileSHA256":"irHji01LPI9giDYxtJo9bTPHaEHzuUcCMTlb4xn90Ks","storageKey":"oJZ9JX1m8IKNDgnIqcKOo5KUFOoa_NCaxruigZu65E0","contentType":"image/png","fileExtension":".png"},{"bundleKey":"a132ecc4ba5c1517ff83c0fb321bc7fc","fileSHA256":"K3RDqaWOksoRpXW9wRWYYVpX3eMFzYznDWAmBrMCzZg","storageKey":"X3OAkUu5P_LqyKFx1bNkA_qDQFLlSjCYNAlVEaOamHE","contentType":"image/png","fileExtension":".png"},{"bundleKey":"0ea69b5077e7c4696db85dbcba75b0e1","fileSHA256":"Pd0Hc-0n4j0leJ8wFzGzrEVa2L5aonoKG4OPicbSciU","storageKey":"FwJkAbrRNahBGX1KXnTAgiiwyzENu3D7DeEzCwmInyo","contentType":"image/png","fileExtension":".png"},{"bundleKey":"f5b790e2ac193b3d41015edb3551f9b8","fileSHA256":"vCfIss7SLYKt1AAi0hxjsgOMEDceLJB6ZWjQf6gTU4k","storageKey":"GQtYm7r0G9N3WJyrymjZ26p8eNMIb7rzqwSVgGco5EU","contentType":"image/png","fileExtension":".png"},{"bundleKey":"5223c8d9b0d08b82a5670fb5f71faf78","fileSHA256":"LJXowmdeeZM1_QBGuwfb2gbLfs_1HtN5IsYwnWGcxNM","storageKey":"jeqOrdQBNY4hgl04B3wtGs8QNWMDmjvbjIMUXPtOBpw","contentType":"image/png","fileExtension":".png"},{"bundleKey":"02d5848f62ade9617cf96894727d32e7","fileSHA256":"u1-8zHOj9oxS8maH-7JbShJIq1-KEV7FXnrGpEUcR-4","storageKey":"LMUvUZZpdGFb7KqaB_l9N4TXTkFn1Pw92ws9fWDNZPw","contentType":"model/gltf-binary","fileExtension":".glb"},{"bundleKey":"6013c27e421ab23c826713af3ebec891","fileSHA256":"dutQNnvzTCS4NgwvbeMbvhro5QnW0GJUeY_4rrvlcLY","storageKey":"85KB9Jr7eqz1Jwt1mYQGRzTy6ZXyO0j7ZcaLImCbzkU","contentType":"image/jpeg","fileExtension":".jpg"}],"launchAsset":{"bundleKey":"3d0ac172fe41ab941a8c68cd7e3a17ee","fileSHA256":"jjnar-ZPrb_g0Bx5tcFfjJrP3v8HdeAlXMk__xN7I1U","storageKey":"bimf-UXq5IFH5nNHCIHdcQ2MyJwTnwDVBb-P8hr2CZw","contentType":"application/javascript","fileExtension":".bundle"}}',
|
||||
@@ -37,7 +37,7 @@ export const testUpdateBranch1: UpdateBranchObject = {
|
||||
group: '16ca6dba-e63b-48b0-baa3-15a894ee9434',
|
||||
message: 'fix bug',
|
||||
createdAt: '2023-07-17T22:48:59.278Z',
|
||||
runtimeVersion: 'exposdk:48.0.0',
|
||||
runtime: { id: 'runtime-exposdk-48', version: 'exposdk:48.0.0' },
|
||||
platform: 'android',
|
||||
manifestFragment:
|
||||
'{"extra":{"expoClient":{"ios":{"supportsTablet":true,"bundleIdentifier":"com.quintest113.updatestest4"},"web":{"favicon":"./assets/favicon.png"},"icon":"./assets/icon.png","name":"updates-test-4","slug":"updates-test-4","extra":{"eas":{"projectId":"789a8784-0186-4f41-8bd2-7f219291a2b8"}},"splash":{"image":"./assets/splash.png","resizeMode":"contain","backgroundColor":"#ffffff"},"android":{"package":"com.quintest113.updatestest4","adaptiveIcon":{"backgroundColor":"#ffffff","foregroundImage":"./assets/adaptive-icon.png"}},"updates":{"url":"https://u.expo.dev/789a8784-0186-4f41-8bd2-7f219291a2b8"},"version":"1.0.0","platforms":["ios","android"],"sdkVersion":"48.0.0","orientation":"portrait","runtimeVersion":{"policy":"sdkVersion"},"currentFullName":"@quintest113/updates-test-4","originalFullName":"@quintest113/updates-test-4","userInterfaceStyle":"light","assetBundlePatterns":["**/*"]}},"assets":[{"bundleKey":"778ffc9fe8773a878e9c30a6304784de","fileSHA256":"i2Gkx-9w3JJ1PwSUl2SC9m_UFQ7CPfx3KrZeEDc6-lU","storageKey":"idnX8z03q4vGLzhYMPaQGBADjhqvWe67_afPqJ1vGzM","contentType":"image/png","fileExtension":".png"},{"bundleKey":"376d6a4c7f622917c39feb23671ef71d","fileSHA256":"QJsG0VpGM-5viirUgoKq0M4zQ_TYyPfLhAhN5mrM54I","storageKey":"46DQ95-UdSKiRkQgt5FyXkE1FrKOT9tBZP3nS7auKlg","contentType":"image/png","fileExtension":".png"},{"bundleKey":"c79c3606a1cf168006ad3979763c7e0c","fileSHA256":"kGZm3WiTRq2iMs42ia3vkHtCV_obWT8DY40rlJf2SIQ","storageKey":"k-3xHp3vP8mR36WdccUZVPTRJKpP-zlyboWdkXCIQpQ","contentType":"image/png","fileExtension":".png"},{"bundleKey":"02bc1fa7c0313217bde2d65ccbff40c9","fileSHA256":"_6fuRbdkBbpzkhSVAI99aMneY5X0tpQdsGNGX244IyA","storageKey":"lfqeUjiWFXwowhxVDBEzxsbTOEzYxMLebljy5Bh1mpU","contentType":"image/png","fileExtension":".png"},{"bundleKey":"35ba0eaec5a4f5ed12ca16fabeae451d","fileSHA256":"hM9es7ICUPaeDkczvrTaX0F_BoKJKlrRteYlcHU8IbE","storageKey":"fMoMrsUeB5xWw_Ugn8FqGJf-M2pld2hkXKR704z0MM8","contentType":"image/png","fileExtension":".png"},{"bundleKey":"5223c8d9b0d08b82a5670fb5f71faf78","fileSHA256":"LJXowmdeeZM1_QBGuwfb2gbLfs_1HtN5IsYwnWGcxNM","storageKey":"jeqOrdQBNY4hgl04B3wtGs8QNWMDmjvbjIMUXPtOBpw","contentType":"image/png","fileExtension":".png"},{"bundleKey":"02d5848f62ade9617cf96894727d32e7","fileSHA256":"u1-8zHOj9oxS8maH-7JbShJIq1-KEV7FXnrGpEUcR-4","storageKey":"LMUvUZZpdGFb7KqaB_l9N4TXTkFn1Pw92ws9fWDNZPw","contentType":"model/gltf-binary","fileExtension":".glb"},{"bundleKey":"6013c27e421ab23c826713af3ebec891","fileSHA256":"dutQNnvzTCS4NgwvbeMbvhro5QnW0GJUeY_4rrvlcLY","storageKey":"85KB9Jr7eqz1Jwt1mYQGRzTy6ZXyO0j7ZcaLImCbzkU","contentType":"image/jpeg","fileExtension":".jpg"}],"launchAsset":{"bundleKey":"4cc2ee49988e438ac066827b809721de","fileSHA256":"ctfK72f8EdS1IQmDvJLya38RMSma16beJcMoQToZIe0","storageKey":"QdEoKuCQPvVPA71gY52wqJ9vmtV4ObnCcPE2FP4SIdo","contentType":"application/javascript","fileExtension":".bundle"}}',
|
||||
@@ -73,7 +73,7 @@ export const testUpdateBranch2: UpdateBranchObject = {
|
||||
group: 'e40ad156-e9af-4cc2-8e9d-c7b5c328db48',
|
||||
message: 'fix bug',
|
||||
createdAt: '2023-06-23T23:37:10.004Z',
|
||||
runtimeVersion: 'exposdk:48.0.0',
|
||||
runtime: { id: 'runtime-exposdk-48', version: 'exposdk:48.0.0' },
|
||||
platform: 'ios',
|
||||
manifestFragment:
|
||||
'{"extra":{"expoClient":{"ios":{"supportsTablet":true,"bundleIdentifier":"com.quintest113.updatestest4"},"web":{"favicon":"./assets/favicon.png"},"icon":"./assets/icon.png","name":"updates-test-4","slug":"updates-test-4","extra":{"eas":{"projectId":"789a8784-0186-4f41-8bd2-7f219291a2b8"}},"splash":{"image":"./assets/splash.png","resizeMode":"contain","backgroundColor":"#ffffff"},"android":{"package":"com.quintest113.updatestest4","adaptiveIcon":{"backgroundColor":"#ffffff","foregroundImage":"./assets/adaptive-icon.png"}},"updates":{"url":"https://u.expo.dev/789a8784-0186-4f41-8bd2-7f219291a2b8"},"version":"1.0.0","platforms":["ios","android"],"sdkVersion":"48.0.0","orientation":"portrait","runtimeVersion":{"policy":"sdkVersion"},"currentFullName":"@quintest113/updates-test-4","originalFullName":"@quintest113/updates-test-4","userInterfaceStyle":"light","assetBundlePatterns":["**/*"]}},"assets":[{"bundleKey":"7d40544b395c5949f4646f5e150fe020","fileSHA256":"LN_rjlzN55dvcBL7jM5zryIpAp7iHU8VCf7RFIccbNg","storageKey":"Pi65ns2w9xLI5G_m9aGrJ5wK5FpWcGcInSSFwnA_0aA","contentType":"image/png","fileExtension":".png"},{"bundleKey":"cdd04e13d4ec83ff0cd13ec8dabdc341","fileSHA256":"irHji01LPI9giDYxtJo9bTPHaEHzuUcCMTlb4xn90Ks","storageKey":"oJZ9JX1m8IKNDgnIqcKOo5KUFOoa_NCaxruigZu65E0","contentType":"image/png","fileExtension":".png"},{"bundleKey":"a132ecc4ba5c1517ff83c0fb321bc7fc","fileSHA256":"K3RDqaWOksoRpXW9wRWYYVpX3eMFzYznDWAmBrMCzZg","storageKey":"X3OAkUu5P_LqyKFx1bNkA_qDQFLlSjCYNAlVEaOamHE","contentType":"image/png","fileExtension":".png"},{"bundleKey":"0ea69b5077e7c4696db85dbcba75b0e1","fileSHA256":"Pd0Hc-0n4j0leJ8wFzGzrEVa2L5aonoKG4OPicbSciU","storageKey":"FwJkAbrRNahBGX1KXnTAgiiwyzENu3D7DeEzCwmInyo","contentType":"image/png","fileExtension":".png"},{"bundleKey":"f5b790e2ac193b3d41015edb3551f9b8","fileSHA256":"vCfIss7SLYKt1AAi0hxjsgOMEDceLJB6ZWjQf6gTU4k","storageKey":"GQtYm7r0G9N3WJyrymjZ26p8eNMIb7rzqwSVgGco5EU","contentType":"image/png","fileExtension":".png"},{"bundleKey":"5223c8d9b0d08b82a5670fb5f71faf78","fileSHA256":"LJXowmdeeZM1_QBGuwfb2gbLfs_1HtN5IsYwnWGcxNM","storageKey":"jeqOrdQBNY4hgl04B3wtGs8QNWMDmjvbjIMUXPtOBpw","contentType":"image/png","fileExtension":".png"},{"bundleKey":"02d5848f62ade9617cf96894727d32e7","fileSHA256":"u1-8zHOj9oxS8maH-7JbShJIq1-KEV7FXnrGpEUcR-4","storageKey":"LMUvUZZpdGFb7KqaB_l9N4TXTkFn1Pw92ws9fWDNZPw","contentType":"model/gltf-binary","fileExtension":".glb"},{"bundleKey":"6013c27e421ab23c826713af3ebec891","fileSHA256":"dutQNnvzTCS4NgwvbeMbvhro5QnW0GJUeY_4rrvlcLY","storageKey":"85KB9Jr7eqz1Jwt1mYQGRzTy6ZXyO0j7ZcaLImCbzkU","contentType":"image/jpeg","fileExtension":".jpg"}],"launchAsset":{"bundleKey":"76ec49faddaef30ba78fe50edc5ab3d6","fileSHA256":"OLUdgP-fZI2shwGS5qlIk7nWnybL_13RJl5xR85CDBU","storageKey":"OCvI0-34zApbdo3eSGfIaQUbWdZeLeKH-nJSeedKTFs","contentType":"application/javascript","fileExtension":".bundle"}}',
|
||||
@@ -99,7 +99,7 @@ export const testUpdateBranch2: UpdateBranchObject = {
|
||||
group: 'e40ad156-e9af-4cc2-8e9d-c7b5c328db48',
|
||||
message: 'fix bug',
|
||||
createdAt: '2023-06-23T23:37:10.004Z',
|
||||
runtimeVersion: 'exposdk:48.0.0',
|
||||
runtime: { id: 'runtime-exposdk-48', version: 'exposdk:48.0.0' },
|
||||
platform: 'android',
|
||||
manifestFragment:
|
||||
'{"extra":{"expoClient":{"ios":{"supportsTablet":true,"bundleIdentifier":"com.quintest113.updatestest4"},"web":{"favicon":"./assets/favicon.png"},"icon":"./assets/icon.png","name":"updates-test-4","slug":"updates-test-4","extra":{"eas":{"projectId":"789a8784-0186-4f41-8bd2-7f219291a2b8"}},"splash":{"image":"./assets/splash.png","resizeMode":"contain","backgroundColor":"#ffffff"},"android":{"package":"com.quintest113.updatestest4","adaptiveIcon":{"backgroundColor":"#ffffff","foregroundImage":"./assets/adaptive-icon.png"}},"updates":{"url":"https://u.expo.dev/789a8784-0186-4f41-8bd2-7f219291a2b8"},"version":"1.0.0","platforms":["ios","android"],"sdkVersion":"48.0.0","orientation":"portrait","runtimeVersion":{"policy":"sdkVersion"},"currentFullName":"@quintest113/updates-test-4","originalFullName":"@quintest113/updates-test-4","userInterfaceStyle":"light","assetBundlePatterns":["**/*"]}},"assets":[{"bundleKey":"778ffc9fe8773a878e9c30a6304784de","fileSHA256":"i2Gkx-9w3JJ1PwSUl2SC9m_UFQ7CPfx3KrZeEDc6-lU","storageKey":"idnX8z03q4vGLzhYMPaQGBADjhqvWe67_afPqJ1vGzM","contentType":"image/png","fileExtension":".png"},{"bundleKey":"376d6a4c7f622917c39feb23671ef71d","fileSHA256":"QJsG0VpGM-5viirUgoKq0M4zQ_TYyPfLhAhN5mrM54I","storageKey":"46DQ95-UdSKiRkQgt5FyXkE1FrKOT9tBZP3nS7auKlg","contentType":"image/png","fileExtension":".png"},{"bundleKey":"c79c3606a1cf168006ad3979763c7e0c","fileSHA256":"kGZm3WiTRq2iMs42ia3vkHtCV_obWT8DY40rlJf2SIQ","storageKey":"k-3xHp3vP8mR36WdccUZVPTRJKpP-zlyboWdkXCIQpQ","contentType":"image/png","fileExtension":".png"},{"bundleKey":"02bc1fa7c0313217bde2d65ccbff40c9","fileSHA256":"_6fuRbdkBbpzkhSVAI99aMneY5X0tpQdsGNGX244IyA","storageKey":"lfqeUjiWFXwowhxVDBEzxsbTOEzYxMLebljy5Bh1mpU","contentType":"image/png","fileExtension":".png"},{"bundleKey":"35ba0eaec5a4f5ed12ca16fabeae451d","fileSHA256":"hM9es7ICUPaeDkczvrTaX0F_BoKJKlrRteYlcHU8IbE","storageKey":"fMoMrsUeB5xWw_Ugn8FqGJf-M2pld2hkXKR704z0MM8","contentType":"image/png","fileExtension":".png"},{"bundleKey":"5223c8d9b0d08b82a5670fb5f71faf78","fileSHA256":"LJXowmdeeZM1_QBGuwfb2gbLfs_1HtN5IsYwnWGcxNM","storageKey":"jeqOrdQBNY4hgl04B3wtGs8QNWMDmjvbjIMUXPtOBpw","contentType":"image/png","fileExtension":".png"},{"bundleKey":"02d5848f62ade9617cf96894727d32e7","fileSHA256":"u1-8zHOj9oxS8maH-7JbShJIq1-KEV7FXnrGpEUcR-4","storageKey":"LMUvUZZpdGFb7KqaB_l9N4TXTkFn1Pw92ws9fWDNZPw","contentType":"model/gltf-binary","fileExtension":".glb"},{"bundleKey":"6013c27e421ab23c826713af3ebec891","fileSHA256":"dutQNnvzTCS4NgwvbeMbvhro5QnW0GJUeY_4rrvlcLY","storageKey":"85KB9Jr7eqz1Jwt1mYQGRzTy6ZXyO0j7ZcaLImCbzkU","contentType":"image/jpeg","fileExtension":".jpg"}],"launchAsset":{"bundleKey":"f4c6981626dbabcf51078d07a1611f4e","fileSHA256":"q-k1hSWl49aXpSg4jOSaVVnYFSFL6xf7HVl_TQE-ObM","storageKey":"FwK1PaZqtpL0QZIgaHsxU1AV93JhMdu9K1wZizXROAc","contentType":"application/javascript","fileExtension":".bundle"}}',
|
||||
|
||||
@@ -46,7 +46,11 @@ function makeInsights(
|
||||
id: u.id,
|
||||
group: u.group,
|
||||
message: u.message,
|
||||
runtimeVersion: u.runtimeVersion,
|
||||
runtime: {
|
||||
__typename: 'Runtime' as const,
|
||||
id: `${u.id}-runtime`,
|
||||
version: u.runtimeVersion,
|
||||
},
|
||||
platform: u.platform,
|
||||
insights: {
|
||||
__typename: 'UpdateInsights' as const,
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import {
|
||||
SupabaseConnectionData,
|
||||
SupabaseOrganizationData,
|
||||
SupabaseProjectData,
|
||||
} from '../../graphql/types/SupabaseConnection';
|
||||
import Log from '../../log';
|
||||
import {
|
||||
formatSupabaseOrganization,
|
||||
formatSupabaseProject,
|
||||
formatSupabaseProjectLabel,
|
||||
getSupabaseProjectDashboardUrl,
|
||||
logNoSupabaseProject,
|
||||
parseSupabaseProjectRef,
|
||||
} from '../supabase';
|
||||
|
||||
jest.mock('../../log', () => ({
|
||||
__esModule: true,
|
||||
default: {
|
||||
warn: jest.fn(),
|
||||
log: jest.fn(),
|
||||
},
|
||||
link: jest.fn((url: string) => url),
|
||||
}));
|
||||
|
||||
describe('commandUtils/supabase', () => {
|
||||
const project: SupabaseProjectData = {
|
||||
id: 'project-1',
|
||||
supabaseProjectRef: 'abcdefghijklmnop',
|
||||
supabaseProjectName: 'Demo App',
|
||||
supabaseProjectUrl: 'https://abcdefghijklmnop.supabase.co',
|
||||
supabaseRegion: 'us-east-1',
|
||||
createdAt: '2024-01-01T00:00:00.000Z',
|
||||
updatedAt: '2024-01-01T00:00:00.000Z',
|
||||
};
|
||||
|
||||
it('getSupabaseProjectDashboardUrl encodes the project ref', () => {
|
||||
expect(getSupabaseProjectDashboardUrl({ supabaseProjectRef: 'abc/def' })).toBe(
|
||||
'https://supabase.com/dashboard/project/abc%2Fdef'
|
||||
);
|
||||
});
|
||||
|
||||
it('formatSupabaseOrganization prefers a distinct name', () => {
|
||||
const connection: Pick<
|
||||
SupabaseConnectionData,
|
||||
'supabaseOrganizationSlug' | 'supabaseOrganizationName'
|
||||
> = {
|
||||
supabaseOrganizationSlug: 'org-slug',
|
||||
supabaseOrganizationName: 'Org Name',
|
||||
};
|
||||
expect(formatSupabaseOrganization(connection)).toBe('Org Name (org-slug)');
|
||||
});
|
||||
|
||||
it('formatSupabaseOrganization falls back to live org name', () => {
|
||||
const connection = {
|
||||
supabaseOrganizationSlug: 'org-slug',
|
||||
supabaseOrganizationName: null as unknown as string,
|
||||
};
|
||||
const organizations: SupabaseOrganizationData[] = [
|
||||
{ id: '1', slug: 'org-slug', name: 'Live Name' },
|
||||
];
|
||||
expect(formatSupabaseOrganization(connection, organizations)).toBe('Live Name (org-slug)');
|
||||
});
|
||||
|
||||
it('formatSupabaseOrganization returns slug when name matches or is missing', () => {
|
||||
expect(
|
||||
formatSupabaseOrganization({
|
||||
supabaseOrganizationSlug: 'same',
|
||||
supabaseOrganizationName: 'same',
|
||||
})
|
||||
).toBe('same');
|
||||
expect(
|
||||
formatSupabaseOrganization({
|
||||
supabaseOrganizationSlug: 'only-slug',
|
||||
supabaseOrganizationName: '',
|
||||
})
|
||||
).toBe('only-slug');
|
||||
});
|
||||
|
||||
it('formatSupabaseProjectLabel prefers a distinct name', () => {
|
||||
expect(formatSupabaseProjectLabel(project)).toBe('Demo App (abcdefghijklmnop)');
|
||||
});
|
||||
|
||||
it('formatSupabaseProjectLabel returns ref when name matches or is missing', () => {
|
||||
expect(
|
||||
formatSupabaseProjectLabel({
|
||||
supabaseProjectRef: 'ref',
|
||||
supabaseProjectName: 'ref',
|
||||
})
|
||||
).toBe('ref');
|
||||
expect(
|
||||
formatSupabaseProjectLabel({
|
||||
supabaseProjectRef: 'ref',
|
||||
supabaseProjectName: '',
|
||||
})
|
||||
).toBe('ref');
|
||||
});
|
||||
|
||||
it('formatSupabaseProject includes key fields', () => {
|
||||
const formatted = formatSupabaseProject(project);
|
||||
expect(formatted).toContain('Demo App');
|
||||
expect(formatted).toContain('abcdefghijklmnop');
|
||||
expect(formatted).toContain('https://abcdefghijklmnop.supabase.co');
|
||||
expect(formatted).toContain('us-east-1');
|
||||
expect(formatted).toContain('https://supabase.com/dashboard/project/abcdefghijklmnop');
|
||||
});
|
||||
|
||||
it('logNoSupabaseProject warns with the project name', () => {
|
||||
logNoSupabaseProject('my-app');
|
||||
expect(Log.warn).toHaveBeenCalledWith(expect.stringContaining('my-app'));
|
||||
});
|
||||
});
|
||||
|
||||
describe(parseSupabaseProjectRef, () => {
|
||||
it('accepts a bare reference ID', () => {
|
||||
expect(parseSupabaseProjectRef('jfurmbuioogljwsqwnpd')).toBe('jfurmbuioogljwsqwnpd');
|
||||
expect(parseSupabaseProjectRef(' jfurmbuioogljwsqwnpd ')).toBe('jfurmbuioogljwsqwnpd');
|
||||
});
|
||||
|
||||
it('accepts a dashboard URL', () => {
|
||||
expect(
|
||||
parseSupabaseProjectRef('https://supabase.com/dashboard/project/kwdfdxdzurxigtbtwddj')
|
||||
).toBe('kwdfdxdzurxigtbtwddj');
|
||||
expect(
|
||||
parseSupabaseProjectRef(
|
||||
'https://supabase.com/dashboard/project/kwdfdxdzurxigtbtwddj/settings/general'
|
||||
)
|
||||
).toBe('kwdfdxdzurxigtbtwddj');
|
||||
});
|
||||
|
||||
it('accepts a project API URL', () => {
|
||||
expect(parseSupabaseProjectRef('https://kwdfdxdzurxigtbtwddj.supabase.co')).toBe(
|
||||
'kwdfdxdzurxigtbtwddj'
|
||||
);
|
||||
});
|
||||
|
||||
it('lowercases the reference ID, which the server matches exactly', () => {
|
||||
expect(parseSupabaseProjectRef('JFURMBUIOOGLJWSQWNPD')).toBe('jfurmbuioogljwsqwnpd');
|
||||
expect(
|
||||
parseSupabaseProjectRef('https://supabase.com/dashboard/project/KWDFDXDZURXIGTBTWDDJ')
|
||||
).toBe('kwdfdxdzurxigtbtwddj');
|
||||
});
|
||||
|
||||
it('rejects a project name with guidance', () => {
|
||||
expect(() => parseSupabaseProjectRef('@testuser/test-app-personal-661c52f1')).toThrow(
|
||||
/not a Supabase project reference ID/
|
||||
);
|
||||
expect(() => parseSupabaseProjectRef('@testuser/test-app-personal-661c52f1')).toThrow(
|
||||
/Project Settings/
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects an unrelated URL and an empty value', () => {
|
||||
expect(() => parseSupabaseProjectRef('https://example.com/foo')).toThrow(
|
||||
/not a Supabase project reference ID/
|
||||
);
|
||||
expect(() => parseSupabaseProjectRef(' ')).toThrow(/No Supabase project given/);
|
||||
});
|
||||
|
||||
it('treats a malformed URL as a non-ref and rejects it', () => {
|
||||
expect(() => parseSupabaseProjectRef('https://[')).toThrow(
|
||||
/not a Supabase project reference ID/
|
||||
);
|
||||
});
|
||||
});
|
||||
+82
-11
@@ -4,7 +4,7 @@ import { anything, instance, mock, when } from 'ts-mockito';
|
||||
|
||||
import { Role } from '../../../../graphql/generated';
|
||||
import { AppQuery } from '../../../../graphql/queries/AppQuery';
|
||||
import { learnMore } from '../../../../log';
|
||||
import Log, { learnMore } from '../../../../log';
|
||||
import { fetchOrCreateProjectIDForWriteToConfigWithConfirmationAsync } from '../../../../project/fetchOrCreateProjectIDForWriteToConfigWithConfirmationAsync';
|
||||
import { isExpoInstalled } from '../../../../project/projectUtils';
|
||||
import { promptAsync } from '../../../../prompts';
|
||||
@@ -32,6 +32,8 @@ describe(getProjectIdAsync, () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
|
||||
jest.spyOn(Log, 'warn').mockImplementation(() => {});
|
||||
|
||||
jest
|
||||
.mocked(getConfigFilePaths)
|
||||
.mockReturnValue({ staticConfigPath: null, dynamicConfigPath: null });
|
||||
@@ -46,18 +48,18 @@ describe(getProjectIdAsync, () => {
|
||||
primaryAccount: {
|
||||
id: 'account_id_1',
|
||||
name: 'notnotbrent',
|
||||
users: [{ role: Role.Owner, actor: { id: 'user_id' } }],
|
||||
viewerUserPermission: { role: Role.Owner },
|
||||
},
|
||||
accounts: [
|
||||
{
|
||||
id: 'account_id_1',
|
||||
name: 'notnotbrent',
|
||||
users: [{ role: Role.Owner, actor: { id: 'user_id' } }],
|
||||
viewerUserPermission: { role: Role.Owner },
|
||||
},
|
||||
{
|
||||
id: 'account_id_2',
|
||||
name: 'dominik',
|
||||
users: [{ role: Role.ViewOnly, actor: { id: 'user_id' } }],
|
||||
viewerUserPermission: { role: Role.ViewOnly },
|
||||
},
|
||||
],
|
||||
isExpoAdmin: false,
|
||||
@@ -196,12 +198,12 @@ describe(getProjectIdAsync, () => {
|
||||
{
|
||||
id: 'account_id_1',
|
||||
name: 'notnotbrent',
|
||||
users: [{ role: Role.Admin, actor: { id: 'robot_id' } }],
|
||||
viewerUserPermission: { role: Role.Admin },
|
||||
},
|
||||
{
|
||||
id: 'account_id_2',
|
||||
name: 'dominik',
|
||||
users: [{ role: Role.ViewOnly, actor: { id: 'robot_id' } }],
|
||||
viewerUserPermission: { role: Role.ViewOnly },
|
||||
},
|
||||
],
|
||||
isExpoAdmin: false,
|
||||
@@ -379,6 +381,7 @@ describe(getProjectIdAsync, () => {
|
||||
).resolves.toEqual('2345');
|
||||
|
||||
expect(promptAsync).toHaveBeenCalledTimes(1);
|
||||
expect(Log.warn).toHaveBeenCalledWith('EAS project not configured.');
|
||||
expect(fetchOrCreateProjectIDForWriteToConfigWithConfirmationAsync).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
{ accountName: 'dominik', projectName: 'test' },
|
||||
@@ -420,13 +423,13 @@ describe(getProjectIdAsync, () => {
|
||||
primaryAccount: {
|
||||
id: 'account_id_1',
|
||||
name: 'notnotbrent',
|
||||
users: [{ role: Role.Owner, actor: { id: 'user_id' } }],
|
||||
viewerUserPermission: { role: Role.Owner },
|
||||
},
|
||||
accounts: [
|
||||
{
|
||||
id: 'account_id_1',
|
||||
name: 'notnotbrent',
|
||||
users: [{ role: Role.Owner, actor: { id: 'user_id' } }],
|
||||
viewerUserPermission: { role: Role.Owner },
|
||||
},
|
||||
],
|
||||
isExpoAdmin: false,
|
||||
@@ -462,7 +465,7 @@ describe(getProjectIdAsync, () => {
|
||||
{
|
||||
id: 'account_id_1',
|
||||
name: 'notnotbrent',
|
||||
users: [{ role: Role.Admin, actor: { id: 'robot_id' } }],
|
||||
viewerUserPermission: { role: Role.Admin },
|
||||
},
|
||||
],
|
||||
isExpoAdmin: false,
|
||||
@@ -478,7 +481,14 @@ describe(getProjectIdAsync, () => {
|
||||
{ nonInteractive: false }
|
||||
)
|
||||
).rejects.toThrow(
|
||||
'Project is not configured. When using a robot access token, run "eas init --account <name> --non-interactive" or set the "owner" field in your app config before managing the project. Accounts this token can create projects in: notnotbrent'
|
||||
`EAS project not configured. A robot access token cannot configure it interactively. ` +
|
||||
`Run one of the following, then re-run this command:\n\n` +
|
||||
`To link an existing project:\n\n` +
|
||||
` eas init --id <project-id> --non-interactive\n\n` +
|
||||
`To create a new project:\n\n` +
|
||||
` eas init --account <account-name> --non-interactive\n\n` +
|
||||
`Accounts you can create projects in: notnotbrent\n\n` +
|
||||
`Alternatively, set the "owner" field in your app config.`
|
||||
);
|
||||
|
||||
expect(promptAsync).not.toHaveBeenCalled();
|
||||
@@ -493,12 +503,73 @@ describe(getProjectIdAsync, () => {
|
||||
{ nonInteractive: true }
|
||||
)
|
||||
).rejects.toThrow(
|
||||
`Must configure EAS project by running 'eas init' before this command can be run in non-interactive mode.`
|
||||
`EAS project not configured. This command cannot configure it in non-interactive mode. ` +
|
||||
`Run one of the following, then re-run this command:\n\n` +
|
||||
`To link an existing project:\n\n` +
|
||||
` eas init --id <project-id> --non-interactive\n\n` +
|
||||
`To create a new project:\n\n` +
|
||||
` eas init --account <account-name> --non-interactive\n\n` +
|
||||
`Accounts you can create projects in: notnotbrent`
|
||||
);
|
||||
|
||||
expect(promptAsync).not.toHaveBeenCalled();
|
||||
expect(fetchOrCreateProjectIDForWriteToConfigWithConfirmationAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('defers to the project fetch in non-interactive mode when the account is already known', async () => {
|
||||
const sessionManagerMock = mock<SessionManager>();
|
||||
when(sessionManagerMock.ensureLoggedInAsync(anything())).thenResolve({
|
||||
actor: {
|
||||
__typename: 'User',
|
||||
id: 'user_id',
|
||||
email: '[email protected]',
|
||||
username: 'notnotbrent',
|
||||
primaryAccount: {
|
||||
id: 'account_id_1',
|
||||
name: 'notnotbrent',
|
||||
users: [{ role: Role.Owner, actor: { id: 'user_id' } }],
|
||||
},
|
||||
accounts: [
|
||||
{
|
||||
id: 'account_id_1',
|
||||
name: 'notnotbrent',
|
||||
users: [{ role: Role.Owner, actor: { id: 'user_id' } }],
|
||||
},
|
||||
],
|
||||
isExpoAdmin: false,
|
||||
featureGates: {},
|
||||
},
|
||||
authenticationInfo: { accessToken: 'fake', sessionSecret: null },
|
||||
} as any);
|
||||
|
||||
await expect(
|
||||
getProjectIdAsync(
|
||||
instance(sessionManagerMock),
|
||||
{ sdkVersion: '52.0.0', name: 'test', slug: 'test' },
|
||||
{ nonInteractive: true }
|
||||
)
|
||||
).resolves.toEqual('2345');
|
||||
|
||||
expect(promptAsync).not.toHaveBeenCalled();
|
||||
expect(fetchOrCreateProjectIDForWriteToConfigWithConfirmationAsync).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
{ accountName: 'notnotbrent', projectName: 'test' },
|
||||
{ nonInteractive: true },
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
|
||||
it('does not warn that the project is not configured in non-interactive mode', async () => {
|
||||
await expect(
|
||||
getProjectIdAsync(
|
||||
sessionManager,
|
||||
{ sdkVersion: '52.0.0', name: 'test', slug: 'test' },
|
||||
{ nonInteractive: true }
|
||||
)
|
||||
).rejects.toThrow();
|
||||
|
||||
expect(Log.warn).not.toHaveBeenCalledWith('EAS project not configured.');
|
||||
});
|
||||
});
|
||||
|
||||
it('throws if writing the ID back to the config fails', async () => {
|
||||
|
||||
@@ -17,9 +17,10 @@ import {
|
||||
getPrivateExpoConfigAsync,
|
||||
} from '../../../project/expoConfig';
|
||||
import { fetchOrCreateProjectIDForWriteToConfigWithConfirmationAsync } from '../../../project/fetchOrCreateProjectIDForWriteToConfigWithConfirmationAsync';
|
||||
import { getUnconfiguredProjectError } from '../../../project/projectNotConfiguredError';
|
||||
import { promptAsync } from '../../../prompts';
|
||||
import SessionManager from '../../../user/SessionManager';
|
||||
import { Actor, getActorUsername, getCreatableAccountNames } from '../../../user/User';
|
||||
import { Actor, getActorUsername } from '../../../user/User';
|
||||
|
||||
/**
|
||||
* Save an EAS project ID to the appropriate field in the app config.
|
||||
@@ -183,7 +184,9 @@ export async function validateOrSetProjectIdAsync({
|
||||
throw new Error('This command must be run inside a project directory.');
|
||||
}
|
||||
|
||||
Log.warn('EAS project not configured.');
|
||||
if (!options.nonInteractive) {
|
||||
Log.warn('EAS project not configured.');
|
||||
}
|
||||
|
||||
const accountName = await chooseAccountNameForEASProjectAsync(exp, actor, options);
|
||||
|
||||
@@ -226,11 +229,11 @@ async function chooseAccountNameForEASProjectAsync(
|
||||
}
|
||||
|
||||
if (actor.__typename === 'Robot') {
|
||||
throw new Error(
|
||||
`Project is not configured. When using a robot access token, run "eas init --account <name> --non-interactive" or set the "owner" field in your app config before managing the project. Accounts this token can create projects in: ${getCreatableAccountNames(
|
||||
actor
|
||||
).join(', ')}`
|
||||
);
|
||||
throw getUnconfiguredProjectError({
|
||||
actor,
|
||||
reason: 'A robot access token cannot configure it interactively.',
|
||||
additionalFix: 'Alternatively, set the "owner" field in your app config.',
|
||||
});
|
||||
}
|
||||
|
||||
const allAccounts = actor.accounts;
|
||||
@@ -239,9 +242,7 @@ async function chooseAccountNameForEASProjectAsync(
|
||||
}
|
||||
|
||||
if (options.nonInteractive) {
|
||||
throw new Error(
|
||||
`Must configure EAS project by running 'eas init' before this command can be run in non-interactive mode.`
|
||||
);
|
||||
throw getUnconfiguredProjectError({ actor });
|
||||
}
|
||||
|
||||
const choices = getAccountChoices(
|
||||
|
||||
@@ -2,7 +2,7 @@ import { ExpoConfig } from '@expo/config';
|
||||
import fs from 'fs-extra';
|
||||
|
||||
import { getEASUpdateURL } from '../../../api';
|
||||
import { AppFragment } from '../../../graphql/generated';
|
||||
import { AppFragment, Role } from '../../../graphql/generated';
|
||||
import { easCliVersion } from '../../../utils/easCli';
|
||||
import {
|
||||
cleanAndPrefix,
|
||||
@@ -62,7 +62,7 @@ describe('projectFiles', () => {
|
||||
ownerAccount: {
|
||||
id: 'testowner-account-id',
|
||||
name: 'testowner',
|
||||
users: [],
|
||||
viewerUserPermission: { role: Role.Owner },
|
||||
},
|
||||
...overrides,
|
||||
});
|
||||
@@ -126,7 +126,7 @@ describe('projectFiles', () => {
|
||||
ownerAccount: {
|
||||
id: 'test-owner-account-id',
|
||||
name: 'test-owner',
|
||||
users: [],
|
||||
viewerUserPermission: { role: Role.Owner },
|
||||
},
|
||||
});
|
||||
|
||||
@@ -151,7 +151,7 @@ describe('projectFiles', () => {
|
||||
ownerAccount: {
|
||||
id: 'test-owner-123-account-id',
|
||||
name: 'test-owner-123',
|
||||
users: [],
|
||||
viewerUserPermission: { role: Role.Owner },
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -80,8 +80,7 @@ function getAccountPermissionsMap(actor: Actor): Map<string, boolean> {
|
||||
const permissionsMap = new Map<string, boolean>();
|
||||
|
||||
for (const account of actor.accounts) {
|
||||
const hasPermission =
|
||||
account.users.find(it => it.actor.id === actor.id)?.role !== Role.ViewOnly;
|
||||
const hasPermission = account.viewerUserPermission.role !== Role.ViewOnly;
|
||||
permissionsMap.set(account.name, hasPermission);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import chalk from 'chalk';
|
||||
|
||||
import {
|
||||
SupabaseConnectionData,
|
||||
SupabaseOrganizationData,
|
||||
SupabaseProjectData,
|
||||
} from '../graphql/types/SupabaseConnection';
|
||||
import Log, { link } from '../log';
|
||||
|
||||
export function getSupabaseProjectDashboardUrl(
|
||||
project: Pick<SupabaseProjectData, 'supabaseProjectRef'>
|
||||
): string {
|
||||
return `https://supabase.com/dashboard/project/${encodeURIComponent(project.supabaseProjectRef)}`;
|
||||
}
|
||||
|
||||
function extractProjectRefFromUrl(value: string): string | null {
|
||||
if (!/^https?:\/\//i.test(value)) {
|
||||
return null;
|
||||
}
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const projectHost = url.hostname.match(/^([a-z0-9]+)\.supabase\./i);
|
||||
if (projectHost) {
|
||||
return projectHost[1];
|
||||
}
|
||||
const dashboardPath = url.pathname.match(/\/dashboard\/project\/([^/]+)/);
|
||||
if (dashboardPath) {
|
||||
return decodeURIComponent(dashboardPath[1]);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts whatever a user is likely to have on hand: the bare reference ID, the dashboard URL, or
|
||||
* the project API URL. Supabase labels the ref "Reference ID" under Project Settings → General.
|
||||
*/
|
||||
export function parseSupabaseProjectRef(input: string): string {
|
||||
const value = input.trim();
|
||||
if (!value) {
|
||||
throw new Error(
|
||||
'No Supabase project given. Pass the project reference ID or its dashboard URL, for example --link jfurmbuioogljwsqwnpd.'
|
||||
);
|
||||
}
|
||||
const ref = extractProjectRefFromUrl(value) ?? value;
|
||||
if (!/^[a-z0-9]+$/i.test(ref)) {
|
||||
throw new Error(
|
||||
`"${input}" is not a Supabase project reference ID. Supabase shows it as "Reference ID" under Project Settings → General; you can also paste the dashboard URL (https://supabase.com/dashboard/project/<ref>). Note that a project name is not a reference ID.`
|
||||
);
|
||||
}
|
||||
// Refs are lowercase, and the server matches them exactly.
|
||||
return ref.toLowerCase();
|
||||
}
|
||||
|
||||
/** Prefer human-readable org name; Supabase slugs are often opaque ids like `ycjmzsygzfkryaazoitp`. */
|
||||
export function formatSupabaseOrganization(
|
||||
connection: Pick<SupabaseConnectionData, 'supabaseOrganizationSlug' | 'supabaseOrganizationName'>,
|
||||
organizations: readonly SupabaseOrganizationData[] = []
|
||||
): string {
|
||||
const slug = connection.supabaseOrganizationSlug;
|
||||
const storedName = connection.supabaseOrganizationName;
|
||||
const liveName = organizations.find(organization => organization.slug === slug)?.name;
|
||||
const name = storedName || liveName;
|
||||
if (name && name !== slug) {
|
||||
return `${name} (${slug})`;
|
||||
}
|
||||
return slug;
|
||||
}
|
||||
|
||||
/** Prefer human-readable project name over the opaque project ref. */
|
||||
export function formatSupabaseProjectLabel(
|
||||
project: Pick<SupabaseProjectData, 'supabaseProjectRef' | 'supabaseProjectName'>
|
||||
): string {
|
||||
const { supabaseProjectRef: ref, supabaseProjectName: name } = project;
|
||||
if (name && name !== ref) {
|
||||
return `${name} (${ref})`;
|
||||
}
|
||||
return ref;
|
||||
}
|
||||
|
||||
export function formatSupabaseProject(project: SupabaseProjectData): string {
|
||||
return [
|
||||
`${chalk.bold('Name')}: ${project.supabaseProjectName}`,
|
||||
`${chalk.bold('Ref')}: ${project.supabaseProjectRef}`,
|
||||
`${chalk.bold('URL')}: ${project.supabaseProjectUrl}`,
|
||||
`${chalk.bold('Region')}: ${project.supabaseRegion}`,
|
||||
`${chalk.bold('Dashboard')}: ${link(getSupabaseProjectDashboardUrl(project), { dim: false })}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
export function logNoSupabaseProject(projectName: string): void {
|
||||
Log.warn(`No Supabase project is linked to Expo app ${chalk.bold(projectName)} on EAS.`);
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import chalk from 'chalk';
|
||||
import nullthrows from 'nullthrows';
|
||||
|
||||
import EasCommand from '../../commandUtils/EasCommand';
|
||||
import { Role } from '../../graphql/generated';
|
||||
@@ -52,7 +51,7 @@ export default class AccountView extends EasCommand {
|
||||
return Role.Owner;
|
||||
}
|
||||
|
||||
return nullthrows(account.users.find(user => user.actor.id === actor.id)?.role);
|
||||
return account.viewerUserPermission.role;
|
||||
}
|
||||
|
||||
private static getLabelForRole(role: Role): string {
|
||||
|
||||
@@ -27,8 +27,8 @@ async function cancelBuildAsync(
|
||||
.mutation<CancelBuildMutation, CancelBuildMutationVariables>(
|
||||
gql`
|
||||
mutation CancelBuildMutation($buildId: ID!) {
|
||||
build(buildId: $buildId) {
|
||||
cancel {
|
||||
build {
|
||||
cancelBuild(buildId: $buildId) {
|
||||
id
|
||||
status
|
||||
}
|
||||
@@ -39,7 +39,7 @@ async function cancelBuildAsync(
|
||||
)
|
||||
.toPromise()
|
||||
);
|
||||
return data.build.cancel;
|
||||
return data.build.cancelBuild;
|
||||
}
|
||||
|
||||
export async function selectBuildToCancelAsync(
|
||||
|
||||
@@ -235,7 +235,7 @@ export default class Download extends EasCommand {
|
||||
|
||||
async getPathToBuildArtifactAsync(build: BuildFragment, platform: AppPlatform): Promise<string> {
|
||||
const cachedBuildArtifactPath = getEasBuildRunCachedAppPath(
|
||||
build.project.id,
|
||||
build.app.id,
|
||||
build.id,
|
||||
platform
|
||||
);
|
||||
|
||||
@@ -26,7 +26,7 @@ const insightsResponse = {
|
||||
id: 'u1',
|
||||
group: 'group-a',
|
||||
message: 'first',
|
||||
runtimeVersion: '1.0.0',
|
||||
runtime: { __typename: 'Runtime' as const, id: 'u1-runtime', version: '1.0.0' },
|
||||
platform: 'ios',
|
||||
insights: { __typename: 'UpdateInsights' as const, id: 'u1-i', totalUniqueUsers: 200 },
|
||||
},
|
||||
|
||||
@@ -54,6 +54,18 @@ type FingerprintOrigin = {
|
||||
update?: UpdateFragment;
|
||||
};
|
||||
|
||||
type FingerprintInfo = {
|
||||
fingerprint: Fingerprint;
|
||||
platforms?: AppPlatform[];
|
||||
origin: FingerprintOrigin;
|
||||
/**
|
||||
* Whether the uploaded fingerprint source file could not be downloaded or parsed
|
||||
* (e.g. it expired in GCS or is zero-length). The hash is still valid in that case,
|
||||
* but `fingerprint.sources` is empty and a detailed diff cannot be computed.
|
||||
*/
|
||||
isFingerprintSourceUnavailable: boolean;
|
||||
};
|
||||
|
||||
export default class FingerprintCompare extends EasCommand {
|
||||
static override description = 'compare fingerprints of the current project, builds, and updates';
|
||||
static override strict = false;
|
||||
@@ -170,7 +182,15 @@ export default class FingerprintCompare extends EasCommand {
|
||||
const { fingerprint: secondFingerprint, origin: secondFingerprintOrigin } =
|
||||
secondFingerprintInfo;
|
||||
|
||||
const unavailableSourceHashes = [
|
||||
firstFingerprintInfo.isFingerprintSourceUnavailable ? firstFingerprint.hash : null,
|
||||
secondFingerprintInfo.isFingerprintSourceUnavailable ? secondFingerprint.hash : null,
|
||||
].filter((hash): hash is string => hash !== null);
|
||||
|
||||
if (json) {
|
||||
if (unavailableSourceHashes.length > 0) {
|
||||
throw new Error(getUnavailableSourceMessage(unavailableSourceHashes));
|
||||
}
|
||||
printJsonOnlyOutput({ fingerprint1: firstFingerprint, fingerprint2: secondFingerprint });
|
||||
return;
|
||||
}
|
||||
@@ -190,55 +210,62 @@ export default class FingerprintCompare extends EasCommand {
|
||||
);
|
||||
}
|
||||
|
||||
const fingerprintDiffs = diffFingerprint(projectDir, firstFingerprint, secondFingerprint);
|
||||
if (!fingerprintDiffs) {
|
||||
Log.error('Fingerprint diffs can only be computed for projects with SDK 52 or higher');
|
||||
return;
|
||||
}
|
||||
|
||||
const filePathDiffs = fingerprintDiffs.filter(diff => {
|
||||
let sourceType;
|
||||
if (diff.op === 'added') {
|
||||
sourceType = diff.addedSource.type;
|
||||
} else if (diff.op === 'removed') {
|
||||
sourceType = diff.removedSource.type;
|
||||
} else if (diff.op === 'changed') {
|
||||
sourceType = diff.beforeSource.type;
|
||||
}
|
||||
return sourceType === 'dir' || sourceType === 'file';
|
||||
});
|
||||
if (filePathDiffs.length > 0) {
|
||||
if (unavailableSourceHashes.length > 0) {
|
||||
Log.newLine();
|
||||
Log.log('📁 Paths with native dependencies:');
|
||||
}
|
||||
const fields = [];
|
||||
for (const diff of filePathDiffs) {
|
||||
const field = getDiffFilePathFields(diff);
|
||||
if (!field) {
|
||||
throw new Error(`Unsupported diff: ${JSON.stringify(diff)}`);
|
||||
Log.warn(
|
||||
`A detailed diff cannot be shown. ${getUnavailableSourceMessage(unavailableSourceHashes)}`
|
||||
);
|
||||
} else {
|
||||
const fingerprintDiffs = diffFingerprint(projectDir, firstFingerprint, secondFingerprint);
|
||||
if (!fingerprintDiffs) {
|
||||
Log.error('Fingerprint diffs can only be computed for projects with SDK 52 or higher');
|
||||
return;
|
||||
}
|
||||
fields.push(field);
|
||||
}
|
||||
Log.log(
|
||||
formatFields(fields, {
|
||||
labelFormat: label => ` ${chalk.dim(label)}:`,
|
||||
})
|
||||
);
|
||||
|
||||
const contentDiffs = fingerprintDiffs.filter(diff => {
|
||||
let sourceType;
|
||||
if (diff.op === 'added') {
|
||||
sourceType = diff.addedSource.type;
|
||||
} else if (diff.op === 'removed') {
|
||||
sourceType = diff.removedSource.type;
|
||||
} else if (diff.op === 'changed') {
|
||||
sourceType = diff.beforeSource.type;
|
||||
const filePathDiffs = fingerprintDiffs.filter(diff => {
|
||||
let sourceType;
|
||||
if (diff.op === 'added') {
|
||||
sourceType = diff.addedSource.type;
|
||||
} else if (diff.op === 'removed') {
|
||||
sourceType = diff.removedSource.type;
|
||||
} else if (diff.op === 'changed') {
|
||||
sourceType = diff.beforeSource.type;
|
||||
}
|
||||
return sourceType === 'dir' || sourceType === 'file';
|
||||
});
|
||||
if (filePathDiffs.length > 0) {
|
||||
Log.newLine();
|
||||
Log.log('📁 Paths with native dependencies:');
|
||||
}
|
||||
return sourceType === 'contents';
|
||||
});
|
||||
const fields = [];
|
||||
for (const diff of filePathDiffs) {
|
||||
const field = getDiffFilePathFields(diff);
|
||||
if (!field) {
|
||||
throw new Error(`Unsupported diff: ${JSON.stringify(diff)}`);
|
||||
}
|
||||
fields.push(field);
|
||||
}
|
||||
Log.log(
|
||||
formatFields(fields, {
|
||||
labelFormat: label => ` ${chalk.dim(label)}:`,
|
||||
})
|
||||
);
|
||||
|
||||
for (const diff of contentDiffs) {
|
||||
printContentDiff(diff);
|
||||
const contentDiffs = fingerprintDiffs.filter(diff => {
|
||||
let sourceType;
|
||||
if (diff.op === 'added') {
|
||||
sourceType = diff.addedSource.type;
|
||||
} else if (diff.op === 'removed') {
|
||||
sourceType = diff.removedSource.type;
|
||||
} else if (diff.op === 'changed') {
|
||||
sourceType = diff.beforeSource.type;
|
||||
}
|
||||
return sourceType === 'contents';
|
||||
});
|
||||
|
||||
for (const diff of contentDiffs) {
|
||||
printContentDiff(diff);
|
||||
}
|
||||
}
|
||||
|
||||
if (nonInteractive) {
|
||||
@@ -285,12 +312,8 @@ async function getFingerprintInfoAsync(
|
||||
environmentForProjectFingerprint?: string;
|
||||
nonInteractive: boolean;
|
||||
},
|
||||
firstFingerprintInfo?: {
|
||||
fingerprint: Fingerprint;
|
||||
platforms?: AppPlatform[];
|
||||
origin: FingerprintOrigin;
|
||||
}
|
||||
): Promise<{ fingerprint: Fingerprint; origin: FingerprintOrigin }> {
|
||||
firstFingerprintInfo?: FingerprintInfo
|
||||
): Promise<FingerprintInfo> {
|
||||
if (hash) {
|
||||
return await getFingerprintInfoFromHashAsync(graphqlClient, projectId, hash);
|
||||
} else if (updateId) {
|
||||
@@ -349,13 +372,9 @@ async function getFingerprintInfoInteractiveAsync({
|
||||
projectId: string;
|
||||
vcsClient: Client;
|
||||
getServerSideEnvironmentVariablesAsync: GetServerSideEnvironmentVariablesFn;
|
||||
firstFingerprintInfo?: {
|
||||
fingerprint: Fingerprint;
|
||||
platforms?: AppPlatform[];
|
||||
origin: FingerprintOrigin;
|
||||
};
|
||||
firstFingerprintInfo?: FingerprintInfo;
|
||||
environmentForProjectFingerprint?: string;
|
||||
}): Promise<{ fingerprint: Fingerprint; platforms?: AppPlatform[]; origin: FingerprintOrigin }> {
|
||||
}): Promise<FingerprintInfo> {
|
||||
const prompt = firstFingerprintInfo
|
||||
? 'Select the second fingerprint to compare against'
|
||||
: 'Select a reference fingerprint for comparison';
|
||||
@@ -449,13 +468,9 @@ async function getFingerprintInfoFromLocalProjectAsync({
|
||||
projectId: string;
|
||||
vcsClient: Client;
|
||||
getServerSideEnvironmentVariablesAsync: GetServerSideEnvironmentVariablesFn;
|
||||
firstFingerprintInfo: {
|
||||
fingerprint: Fingerprint;
|
||||
platforms?: AppPlatform[];
|
||||
origin: FingerprintOrigin;
|
||||
};
|
||||
firstFingerprintInfo: FingerprintInfo;
|
||||
environment?: string;
|
||||
}): Promise<{ fingerprint: Fingerprint; platforms?: AppPlatform[]; origin: FingerprintOrigin }> {
|
||||
}): Promise<FingerprintInfo> {
|
||||
const firstFingerprintPlatforms = firstFingerprintInfo.platforms;
|
||||
if (!firstFingerprintPlatforms || firstFingerprintPlatforms.length === 0) {
|
||||
throw new Error(
|
||||
@@ -477,22 +492,27 @@ async function getFingerprintInfoFromLocalProjectAsync({
|
||||
firstFingerprintPlatforms,
|
||||
{ env }
|
||||
);
|
||||
return { fingerprint, origin: { type: FingerprintOriginType.Project } };
|
||||
return {
|
||||
fingerprint,
|
||||
origin: { type: FingerprintOriginType.Project },
|
||||
isFingerprintSourceUnavailable: false,
|
||||
};
|
||||
}
|
||||
|
||||
async function getFingerprintFromUpdateFragmentAsync(
|
||||
updateWithFingerprint: UpdateFragment
|
||||
): Promise<{ fingerprint: Fingerprint; platforms?: AppPlatform[]; origin: FingerprintOrigin }> {
|
||||
): Promise<FingerprintInfo> {
|
||||
if (!updateWithFingerprint.fingerprint) {
|
||||
throw new Error(`Fingerprint for update ${updateWithFingerprint.id} was not computed.`);
|
||||
} else if (!updateWithFingerprint.fingerprint.debugInfoUrl) {
|
||||
throw new Error(`Fingerprint source for update ${updateWithFingerprint.id} was not computed.`);
|
||||
}
|
||||
|
||||
const { fingerprint, isFingerprintSourceUnavailable } =
|
||||
await getFingerprintFromFingerprintFragmentAsync(updateWithFingerprint.fingerprint);
|
||||
return {
|
||||
fingerprint: await getFingerprintFromFingerprintFragmentAsync(
|
||||
updateWithFingerprint.fingerprint
|
||||
),
|
||||
fingerprint,
|
||||
isFingerprintSourceUnavailable,
|
||||
platforms: [stringToAppPlatform(updateWithFingerprint.platform)],
|
||||
origin: {
|
||||
type: FingerprintOriginType.Update,
|
||||
@@ -505,13 +525,14 @@ async function getFingerprintInfoFromHashAsync(
|
||||
graphqlClient: ExpoGraphqlClient,
|
||||
projectId: string,
|
||||
hash: string
|
||||
): Promise<{ fingerprint: Fingerprint; platforms?: AppPlatform[]; origin: FingerprintOrigin }> {
|
||||
): Promise<FingerprintInfo> {
|
||||
const fingerprintFragment = await getFingerprintFragmentFromHashAsync(
|
||||
graphqlClient,
|
||||
projectId,
|
||||
hash
|
||||
);
|
||||
const fingerprint = await getFingerprintFromFingerprintFragmentAsync(fingerprintFragment);
|
||||
const { fingerprint, isFingerprintSourceUnavailable } =
|
||||
await getFingerprintFromFingerprintFragmentAsync(fingerprintFragment);
|
||||
let platforms;
|
||||
const fingerprintBuilds = fingerprintFragment.builds?.edges.map(edge => edge.node) ?? [];
|
||||
const fingerprintUpdates = fingerprintFragment.updates?.edges.map(edge => edge.node) ?? [];
|
||||
@@ -522,6 +543,7 @@ async function getFingerprintInfoFromHashAsync(
|
||||
}
|
||||
return {
|
||||
fingerprint,
|
||||
isFingerprintSourceUnavailable,
|
||||
platforms,
|
||||
origin: {
|
||||
type: FingerprintOriginType.Hash,
|
||||
@@ -534,7 +556,7 @@ async function getFingerprintInfoFromUpdateGroupIdOrUpdateIdAsync(
|
||||
projectId: string,
|
||||
nonInteractive: boolean,
|
||||
updateGroupIdOrUpdateId: string
|
||||
): Promise<{ fingerprint: Fingerprint; platforms?: AppPlatform[]; origin: FingerprintOrigin }> {
|
||||
): Promise<FingerprintInfo> {
|
||||
// Some people may pass in update group id instead of update id, so add interactive support for that
|
||||
try {
|
||||
const maybeUpdateGroupId = updateGroupIdOrUpdateId;
|
||||
@@ -578,15 +600,18 @@ async function getFingerprintInfoFromUpdateGroupIdOrUpdateIdAsync(
|
||||
async function getFingerprintInfoFromBuildIdAsync(
|
||||
graphqlClient: ExpoGraphqlClient,
|
||||
buildId: string
|
||||
): Promise<{ fingerprint: Fingerprint; platforms?: AppPlatform[]; origin: FingerprintOrigin }> {
|
||||
): Promise<FingerprintInfo> {
|
||||
const buildWithFingerprint = await BuildQuery.withFingerprintByIdAsync(graphqlClient, buildId);
|
||||
if (!buildWithFingerprint.fingerprint) {
|
||||
throw new Error(`Fingerprint for build ${buildId} was not computed.`);
|
||||
} else if (!buildWithFingerprint.fingerprint.debugInfoUrl) {
|
||||
throw new Error(`Fingerprint source for build ${buildId} was not computed.`);
|
||||
}
|
||||
const { fingerprint, isFingerprintSourceUnavailable } =
|
||||
await getFingerprintFromFingerprintFragmentAsync(buildWithFingerprint.fingerprint);
|
||||
return {
|
||||
fingerprint: await getFingerprintFromFingerprintFragmentAsync(buildWithFingerprint.fingerprint),
|
||||
fingerprint,
|
||||
isFingerprintSourceUnavailable,
|
||||
platforms: [buildWithFingerprint.platform],
|
||||
origin: {
|
||||
type: FingerprintOriginType.Build,
|
||||
@@ -611,17 +636,48 @@ async function getFingerprintFragmentFromHashAsync(
|
||||
return fingerprint;
|
||||
}
|
||||
|
||||
async function fetchFingerprintSourceAsync(fingerprintDebugUrl: string): Promise<Fingerprint> {
|
||||
const fingerprintResponse = await fetch(fingerprintDebugUrl);
|
||||
if (!fingerprintResponse.ok) {
|
||||
throw new Error(`Fingerprint source request failed: ${fingerprintResponse.status}`);
|
||||
}
|
||||
const fingerprintSource = (await fingerprintResponse.json()) as Partial<Fingerprint> | null;
|
||||
if (!Array.isArray(fingerprintSource?.sources)) {
|
||||
throw new Error('Fingerprint source file does not contain a list of sources');
|
||||
}
|
||||
return fingerprintSource as Fingerprint;
|
||||
}
|
||||
|
||||
async function getFingerprintFromFingerprintFragmentAsync(
|
||||
fingerprintFragment: Pick<FingerprintFragment, 'debugInfoUrl' | 'hash'>
|
||||
): Promise<Fingerprint> {
|
||||
): Promise<{ fingerprint: Fingerprint; isFingerprintSourceUnavailable: boolean }> {
|
||||
const fingerprintDebugUrl = fingerprintFragment.debugInfoUrl;
|
||||
if (!fingerprintDebugUrl) {
|
||||
throw new Error(
|
||||
`The source for fingerprint hash ${fingerprintFragment.hash} was not computed.`
|
||||
);
|
||||
}
|
||||
const fingerprintResponse = await fetch(fingerprintDebugUrl);
|
||||
return (await fingerprintResponse.json()) as Fingerprint;
|
||||
try {
|
||||
return {
|
||||
fingerprint: await fetchFingerprintSourceAsync(fingerprintDebugUrl),
|
||||
isFingerprintSourceUnavailable: false,
|
||||
};
|
||||
} catch (error) {
|
||||
// Uploaded source files expire after a period of time or may be malformed
|
||||
// (e.g. zero-length). The hash from the API is still valid, so fall back to a
|
||||
// sourceless fingerprint instead of failing the whole comparison.
|
||||
Log.debug(`Failed to fetch source for fingerprint hash ${fingerprintFragment.hash}`, error);
|
||||
return {
|
||||
fingerprint: { hash: fingerprintFragment.hash, sources: [] },
|
||||
isFingerprintSourceUnavailable: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function getUnavailableSourceMessage(hashes: string[]): string {
|
||||
return hashes.length === 1
|
||||
? `The uploaded source file for fingerprint ${hashes[0]} has expired or is invalid.`
|
||||
: `The uploaded source files for fingerprints ${hashes.join(' and ')} have expired or are invalid.`;
|
||||
}
|
||||
|
||||
function printContentDiff(diff: FingerprintDiffItem): void {
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { ExpoConfig, getConfigFilePaths } from '@expo/config';
|
||||
import { App, User, UserRole } from '@expo/apple-utils';
|
||||
import { App } from '@expo/apple-utils';
|
||||
import { Flags } from '@oclif/core';
|
||||
import chalk from 'chalk';
|
||||
import * as fs from 'fs-extra';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
import semver from 'semver';
|
||||
import { Analytics } from '../analytics/AnalyticsManager';
|
||||
import EasCommand from '../commandUtils/EasCommand';
|
||||
import { ExpoGraphqlClient } from '../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
@@ -15,6 +16,7 @@ import { SetUpAscApiKey } from '../credentials/ios/actions/SetUpAscApiKey';
|
||||
import { SetUpBuildCredentials } from '../credentials/ios/actions/SetUpBuildCredentials';
|
||||
import { SetUpPushKey } from '../credentials/ios/actions/SetUpPushKey';
|
||||
import { ensureAppExistsAsync } from '../credentials/ios/appstore/ensureAppExists';
|
||||
import { ensureTestFlightGroupExistsAsync } from '../credentials/ios/appstore/ensureTestFlightGroup';
|
||||
import { Target } from '../credentials/ios/types';
|
||||
import {
|
||||
WorkflowJobStatus,
|
||||
@@ -60,62 +62,13 @@ export async function detectProjectSdkVersionAsync(
|
||||
}
|
||||
}
|
||||
|
||||
const TESTFLIGHT_GROUP_NAME = 'Team (Expo)';
|
||||
export function toRepackTargetSdkVersion(sdkVersion: string | undefined): string | undefined {
|
||||
const coerced = semver.coerce(sdkVersion);
|
||||
return coerced ? `${coerced.major}.0.0` : sdkVersion;
|
||||
}
|
||||
|
||||
async function setupTestFlightAsync(ascApp: App): Promise<void> {
|
||||
let group;
|
||||
for (let attempt = 0; attempt < 10; attempt++) {
|
||||
try {
|
||||
const groups = await ascApp.getBetaGroupsAsync({
|
||||
query: { includes: ['betaTesters'] },
|
||||
});
|
||||
|
||||
group = groups.find(
|
||||
g => g.attributes.isInternalGroup && g.attributes.name === TESTFLIGHT_GROUP_NAME
|
||||
);
|
||||
|
||||
if (!group) {
|
||||
group = await ascApp.createBetaGroupAsync({
|
||||
name: TESTFLIGHT_GROUP_NAME,
|
||||
isInternalGroup: true,
|
||||
hasAccessToAllBuilds: true,
|
||||
});
|
||||
}
|
||||
break;
|
||||
} catch (error: any) {
|
||||
// Apple returns this error when the app isn't ready yet
|
||||
if (error?.data?.errors?.some((e: any) => e.code === 'ENTITY_ERROR.RELATIONSHIP.INVALID')) {
|
||||
if (attempt < 9) {
|
||||
await sleepAsync(10_000);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (!group) {
|
||||
throw new Error('Failed to create TestFlight group');
|
||||
}
|
||||
|
||||
const users = await User.getAsync(ascApp.context);
|
||||
const admins = users.filter(u => u.attributes.roles?.includes(UserRole.ADMIN));
|
||||
|
||||
const existingEmails = new Set(
|
||||
group.attributes.betaTesters?.map((t: any) => t.attributes.email?.toLowerCase()) ?? []
|
||||
);
|
||||
|
||||
const newTesters = admins
|
||||
.filter(u => u.attributes.email && !existingEmails.has(u.attributes.email.toLowerCase()))
|
||||
.map(u => ({
|
||||
email: u.attributes.email!,
|
||||
firstName: u.attributes.firstName ?? '',
|
||||
lastName: u.attributes.lastName ?? '',
|
||||
}));
|
||||
|
||||
if (newTesters.length > 0) {
|
||||
await group.createBulkBetaTesterAssignmentsAsync(newTesters);
|
||||
}
|
||||
await ensureTestFlightGroupExistsAsync(ascApp);
|
||||
}
|
||||
|
||||
/* eslint-disable no-console */
|
||||
@@ -173,7 +126,8 @@ export default class Go extends EasCommand {
|
||||
default: 'My Expo Go',
|
||||
}),
|
||||
'sdk-version': Flags.string({
|
||||
description: 'Expo Go SDK version to prepare (default: latest)',
|
||||
description:
|
||||
'Expo Go SDK version to prepare, for example 57 (default: the SDK version of the current project)',
|
||||
required: false,
|
||||
}),
|
||||
credentials: Flags.boolean({
|
||||
@@ -210,7 +164,7 @@ export default class Go extends EasCommand {
|
||||
`Current project using SDK ${detectedSdkVersion.split('.')[0]}. Auto-selected same version. To use a different version, pass --sdk-version.`
|
||||
);
|
||||
}
|
||||
let sdkVersion = flags['sdk-version'] ?? detectedSdkVersion;
|
||||
let sdkVersion = toRepackTargetSdkVersion(flags['sdk-version'] ?? detectedSdkVersion);
|
||||
if (!sdkVersion) {
|
||||
({ sdkVersion } = await this.selectSdkVersionAsync(graphqlClient));
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { AppStoreConnectApiKeyQuery } from '../../../../credentials/ios/api/grap
|
||||
import { AscAppLinkMutation } from '../../../../graphql/mutations/AscAppLinkMutation';
|
||||
import { AscAppLinkQuery } from '../../../../graphql/queries/AscAppLinkQuery';
|
||||
import IntegrationsAscConnect from '../connect';
|
||||
import { Role } from '../../../../graphql/generated';
|
||||
|
||||
jest.mock('../../../../graphql/queries/AscAppLinkQuery');
|
||||
jest.mock('../../../../graphql/mutations/AscAppLinkMutation');
|
||||
@@ -18,7 +19,12 @@ const testProjectId = 'test-project-id';
|
||||
const mockMetadataConnected = {
|
||||
id: testProjectId,
|
||||
fullName: '@testuser/testapp',
|
||||
ownerAccount: { id: 'account-id', name: 'testuser', ownerUserActor: null, users: [] },
|
||||
ownerAccount: {
|
||||
id: 'account-id',
|
||||
name: 'testuser',
|
||||
ownerUserActor: null,
|
||||
viewerUserPermission: { role: Role.Owner },
|
||||
},
|
||||
appStoreConnectApp: {
|
||||
id: 'asc-app-link-id',
|
||||
ascAppIdentifier: '1234567890',
|
||||
@@ -34,7 +40,12 @@ const mockMetadataConnected = {
|
||||
const mockMetadataDisconnected = {
|
||||
id: testProjectId,
|
||||
fullName: '@testuser/testapp',
|
||||
ownerAccount: { id: 'account-id', name: 'testuser', ownerUserActor: null, users: [] },
|
||||
ownerAccount: {
|
||||
id: 'account-id',
|
||||
name: 'testuser',
|
||||
ownerUserActor: null,
|
||||
viewerUserPermission: { role: Role.Owner },
|
||||
},
|
||||
appStoreConnectApp: null,
|
||||
};
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import { AscAppLinkQuery } from '../../../../graphql/queries/AscAppLinkQuery';
|
||||
import Log from '../../../../log';
|
||||
import { toggleConfirmAsync } from '../../../../prompts';
|
||||
import IntegrationsAscDisconnect from '../disconnect';
|
||||
import { Role } from '../../../../graphql/generated';
|
||||
|
||||
jest.mock('../../../../graphql/queries/AscAppLinkQuery');
|
||||
jest.mock('../../../../graphql/mutations/AscAppLinkMutation');
|
||||
@@ -19,7 +20,12 @@ const testProjectId = 'test-project-id';
|
||||
const mockMetadataConnected = {
|
||||
id: testProjectId,
|
||||
fullName: '@testuser/testapp',
|
||||
ownerAccount: { id: 'account-id', name: 'testuser', ownerUserActor: null, users: [] },
|
||||
ownerAccount: {
|
||||
id: 'account-id',
|
||||
name: 'testuser',
|
||||
ownerUserActor: null,
|
||||
viewerUserPermission: { role: Role.Owner },
|
||||
},
|
||||
appStoreConnectApp: {
|
||||
id: 'asc-app-link-id',
|
||||
ascAppIdentifier: '1234567890',
|
||||
@@ -35,7 +41,12 @@ const mockMetadataConnected = {
|
||||
const mockMetadataDisconnected = {
|
||||
id: testProjectId,
|
||||
fullName: '@testuser/testapp',
|
||||
ownerAccount: { id: 'account-id', name: 'testuser', ownerUserActor: null, users: [] },
|
||||
ownerAccount: {
|
||||
id: 'account-id',
|
||||
name: 'testuser',
|
||||
ownerUserActor: null,
|
||||
viewerUserPermission: { role: Role.Owner },
|
||||
},
|
||||
appStoreConnectApp: null,
|
||||
};
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import { ExpoGraphqlClient } from '../../../../commandUtils/context/contextUtils
|
||||
import { AscAppLinkQuery } from '../../../../graphql/queries/AscAppLinkQuery';
|
||||
import Log from '../../../../log';
|
||||
import IntegrationsAscStatus from '../status';
|
||||
import { Role } from '../../../../graphql/generated';
|
||||
|
||||
jest.mock('../../../../graphql/queries/AscAppLinkQuery');
|
||||
jest.mock('../../../../log');
|
||||
@@ -15,7 +16,12 @@ const testProjectId = 'test-project-id';
|
||||
const mockMetadataConnected = {
|
||||
id: testProjectId,
|
||||
fullName: '@testuser/testapp',
|
||||
ownerAccount: { id: 'account-id', name: 'testuser', ownerUserActor: null, users: [] },
|
||||
ownerAccount: {
|
||||
id: 'account-id',
|
||||
name: 'testuser',
|
||||
ownerUserActor: null,
|
||||
viewerUserPermission: { role: Role.Owner },
|
||||
},
|
||||
appStoreConnectApp: {
|
||||
id: 'asc-app-link-id',
|
||||
ascAppIdentifier: '1234567890',
|
||||
@@ -31,7 +37,12 @@ const mockMetadataConnected = {
|
||||
const mockMetadataDisconnected = {
|
||||
id: testProjectId,
|
||||
fullName: '@testuser/testapp',
|
||||
ownerAccount: { id: 'account-id', name: 'testuser', ownerUserActor: null, users: [] },
|
||||
ownerAccount: {
|
||||
id: 'account-id',
|
||||
name: 'testuser',
|
||||
ownerUserActor: null,
|
||||
viewerUserPermission: { role: Role.Owner },
|
||||
},
|
||||
appStoreConnectApp: null,
|
||||
};
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
EnvironmentSecretType,
|
||||
EnvironmentVariableScope,
|
||||
EnvironmentVariableVisibility,
|
||||
Role,
|
||||
} from '../../../../graphql/generated';
|
||||
import { ConvexMutation } from '../../../../graphql/mutations/ConvexMutation';
|
||||
import { EnvironmentVariableMutation } from '../../../../graphql/mutations/EnvironmentVariableMutation';
|
||||
@@ -59,7 +60,7 @@ describe(IntegrationsConvexConnect, () => {
|
||||
id: testAccountId,
|
||||
name: testAccountName,
|
||||
ownerUserActor: null,
|
||||
users: [],
|
||||
viewerUserPermission: { role: Role.Owner },
|
||||
},
|
||||
accounts: [],
|
||||
};
|
||||
@@ -76,7 +77,7 @@ describe(IntegrationsConvexConnect, () => {
|
||||
id: testAccountId,
|
||||
name: testAccountName,
|
||||
ownerUserActor: { id: 'test-user-id', username: testAccountName },
|
||||
users: [{ role: 'OWNER' as any, actor: { id: 'test-user-id' } }],
|
||||
viewerUserPermission: { role: 'OWNER' as any },
|
||||
};
|
||||
|
||||
const mockConnection: ConvexTeamConnectionData = {
|
||||
|
||||
@@ -32,7 +32,7 @@ describe(IntegrationsConvexTeamDelete, () => {
|
||||
id: testAccountId,
|
||||
name: testAccountName,
|
||||
ownerUserActor: { id: 'test-user-id', username: testAccountName },
|
||||
users: [{ role: 'OWNER' as any, actor: { id: 'test-user-id' } }],
|
||||
viewerUserPermission: { role: 'OWNER' as any },
|
||||
};
|
||||
|
||||
const mockConnection: ConvexTeamConnectionData = {
|
||||
|
||||
@@ -41,7 +41,7 @@ describe(IntegrationsConvexTeamInvite, () => {
|
||||
id: testAccountId,
|
||||
name: testAccountName,
|
||||
ownerUserActor: { id: 'test-user-id', username: testAccountName },
|
||||
users: [{ role: 'OWNER' as any, actor: { id: 'test-user-id' } }],
|
||||
viewerUserPermission: { role: 'OWNER' as any },
|
||||
};
|
||||
|
||||
const mockConnection: ConvexTeamConnectionData = {
|
||||
|
||||
@@ -21,7 +21,7 @@ describe(IntegrationsConvexTeam, () => {
|
||||
id: testAccountId,
|
||||
name: testAccountName,
|
||||
ownerUserActor: { id: 'test-user-id', username: testAccountName },
|
||||
users: [{ role: 'OWNER' as any, actor: { id: 'test-user-id' } }],
|
||||
viewerUserPermission: { role: 'OWNER' as any },
|
||||
};
|
||||
|
||||
const mockConnection: ConvexTeamConnectionData = {
|
||||
|
||||
@@ -62,7 +62,12 @@ describe(IntegrationsPostHogConnect, () => {
|
||||
email: '[email protected]',
|
||||
featureGates: {},
|
||||
isExpoAdmin: false,
|
||||
primaryAccount: { id: testAccountId, name: testAccountName, ownerUserActor: null, users: [] },
|
||||
primaryAccount: {
|
||||
id: testAccountId,
|
||||
name: testAccountName,
|
||||
ownerUserActor: null,
|
||||
viewerUserPermission: { role: Role.Owner },
|
||||
},
|
||||
accounts: [],
|
||||
};
|
||||
|
||||
@@ -70,7 +75,7 @@ describe(IntegrationsPostHogConnect, () => {
|
||||
id: testAccountId,
|
||||
name: testAccountName,
|
||||
ownerUserActor: { id: 'test-user-id', username: testAccountName },
|
||||
users: [{ role: Role.Owner, actor: { id: 'test-user-id' } }],
|
||||
viewerUserPermission: { role: Role.Owner },
|
||||
};
|
||||
|
||||
const mockConnection: PostHogOrganizationConnectionData = {
|
||||
|
||||
@@ -0,0 +1,961 @@
|
||||
import spawnAsync from '@expo/spawn-async';
|
||||
import openBrowserAsync from 'better-opn';
|
||||
import * as fs from 'fs-extra';
|
||||
|
||||
import { getMockOclifConfig } from '../../../../__tests__/commands/utils';
|
||||
import { ExpoGraphqlClient } from '../../../../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
import * as supabaseCommandUtils from '../../../../commandUtils/supabase';
|
||||
import { testProjectId } from '../../../../credentials/__tests__/fixtures-constants';
|
||||
import {
|
||||
EnvironmentVariableScope,
|
||||
EnvironmentVariableVisibility,
|
||||
Role,
|
||||
} from '../../../../graphql/generated';
|
||||
import { EnvironmentVariableMutation } from '../../../../graphql/mutations/EnvironmentVariableMutation';
|
||||
import { SupabaseMutation } from '../../../../graphql/mutations/SupabaseMutation';
|
||||
import { EnvironmentVariablesQuery } from '../../../../graphql/queries/EnvironmentVariablesQuery';
|
||||
import { SupabaseQuery } from '../../../../graphql/queries/SupabaseQuery';
|
||||
import {
|
||||
SupabaseConnectionData,
|
||||
SupabaseOrganizationData,
|
||||
SupabaseProjectData,
|
||||
} from '../../../../graphql/types/SupabaseConnection';
|
||||
import Log from '../../../../log';
|
||||
import { createOrModifyExpoConfigAsync } from '../../../../project/expoConfig';
|
||||
import { getOwnerAccountForProjectIdAsync } from '../../../../project/projectUtils';
|
||||
import { confirmAsync, promptAsync, selectAsync } from '../../../../prompts';
|
||||
import { printJsonOnlyOutput } from '../../../../utils/json';
|
||||
import {
|
||||
BackgroundJobReceiptPollError,
|
||||
BackgroundJobReceiptPollErrorType,
|
||||
pollForBackgroundJobReceiptAsync,
|
||||
} from '../../../../utils/pollForBackgroundJobReceiptAsync';
|
||||
import IntegrationsSupabaseConnect from '../connect';
|
||||
|
||||
jest.mock('@expo/spawn-async');
|
||||
jest.mock('better-opn');
|
||||
jest.mock('fs-extra');
|
||||
jest.mock('../../../../project/expoConfig');
|
||||
jest.mock('../../../../graphql/queries/SupabaseQuery');
|
||||
jest.mock('../../../../graphql/queries/EnvironmentVariablesQuery');
|
||||
jest.mock('../../../../graphql/mutations/SupabaseMutation');
|
||||
jest.mock('../../../../graphql/mutations/EnvironmentVariableMutation');
|
||||
jest.mock('../../../../project/projectUtils');
|
||||
jest.mock('../../../../prompts');
|
||||
jest.mock('../../../../log');
|
||||
jest.mock('../../../../utils/json');
|
||||
jest.mock('../../../../utils/pollForBackgroundJobReceiptAsync', () => ({
|
||||
...jest.requireActual('../../../../utils/pollForBackgroundJobReceiptAsync'),
|
||||
pollForBackgroundJobReceiptAsync: jest.fn(),
|
||||
}));
|
||||
jest.mock('../../../../ora', () => ({
|
||||
ora: () => ({
|
||||
start: jest.fn().mockReturnThis(),
|
||||
succeed: jest.fn().mockReturnThis(),
|
||||
warn: jest.fn().mockReturnThis(),
|
||||
fail: jest.fn().mockReturnThis(),
|
||||
stop: jest.fn().mockReturnThis(),
|
||||
text: '',
|
||||
}),
|
||||
}));
|
||||
|
||||
describe(IntegrationsSupabaseConnect, () => {
|
||||
const graphqlClient = {} as ExpoGraphqlClient;
|
||||
const mockConfig = getMockOclifConfig();
|
||||
const testAccountId = 'test-account-id';
|
||||
const testAccountName = 'testuser';
|
||||
|
||||
const mockAccount = {
|
||||
id: testAccountId,
|
||||
name: testAccountName,
|
||||
ownerUserActor: { id: 'test-user-id', username: testAccountName },
|
||||
users: [{ role: Role.Owner, actor: { id: 'test-user-id' } }],
|
||||
};
|
||||
|
||||
const mockConnection: SupabaseConnectionData = {
|
||||
id: 'connection-1',
|
||||
supabaseOrganizationSlug: 'org-slug',
|
||||
supabaseOrganizationName: 'Primary Org',
|
||||
createdAt: '2024-01-01T00:00:00.000Z',
|
||||
updatedAt: '2024-01-01T00:00:00.000Z',
|
||||
};
|
||||
|
||||
const mockOrganizations: SupabaseOrganizationData[] = [
|
||||
{ id: 'org-1', slug: 'org-slug', name: 'Primary Org' },
|
||||
{ id: 'org-2', slug: 'other-org', name: 'Other Org' },
|
||||
];
|
||||
|
||||
const mockProject: SupabaseProjectData = {
|
||||
id: 'project-1',
|
||||
supabaseProjectRef: 'abcdefghijklmnop',
|
||||
supabaseProjectName: 'Test App',
|
||||
supabaseProjectUrl: 'https://abcdefghijklmnop.supabase.co',
|
||||
supabaseRegion: 'us-east-1',
|
||||
createdAt: '2024-01-01T00:00:00.000Z',
|
||||
updatedAt: '2024-01-01T00:00:00.000Z',
|
||||
};
|
||||
|
||||
function createCommand(argv: string[]): IntegrationsSupabaseConnect {
|
||||
const command = new IntegrationsSupabaseConnect(argv, mockConfig);
|
||||
jest.spyOn(command as any, 'getContextAsync').mockReturnValue({
|
||||
privateProjectConfig: {
|
||||
projectId: testProjectId,
|
||||
exp: { name: 'testapp', slug: 'testapp', plugins: [] },
|
||||
projectDir: '/test/project',
|
||||
},
|
||||
loggedIn: { graphqlClient },
|
||||
} as never);
|
||||
return command;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
jest.spyOn(Log, 'log').mockImplementation(() => {});
|
||||
jest.spyOn(Log, 'warn').mockImplementation(() => {});
|
||||
jest.spyOn(Log, 'error').mockImplementation(() => {});
|
||||
jest.spyOn(Log, 'withTick').mockImplementation(() => {});
|
||||
jest.spyOn(Log, 'addNewLineIfNone').mockImplementation(() => {});
|
||||
jest.spyOn(Log, 'newLine').mockImplementation(() => {});
|
||||
jest.spyOn(Log, 'debug').mockImplementation(() => {});
|
||||
|
||||
jest.mocked(getOwnerAccountForProjectIdAsync).mockResolvedValue(mockAccount as any);
|
||||
jest.mocked(selectAsync).mockResolvedValue('americas');
|
||||
jest.mocked(confirmAsync).mockResolvedValue(true);
|
||||
jest.mocked(promptAsync).mockResolvedValue({ linkValue: mockProject.supabaseProjectRef });
|
||||
jest.mocked(spawnAsync).mockResolvedValue({} as any);
|
||||
jest.mocked(fs.pathExists).mockResolvedValue(false as never);
|
||||
jest.mocked(fs.writeFile).mockResolvedValue(undefined as never);
|
||||
jest.mocked(createOrModifyExpoConfigAsync).mockResolvedValue({ type: 'success' } as any);
|
||||
jest.mocked(openBrowserAsync).mockResolvedValue(true as never);
|
||||
jest.mocked(EnvironmentVariablesQuery.byAppIdAsync).mockResolvedValue([]);
|
||||
jest
|
||||
.mocked(EnvironmentVariablesQuery.environmentVariableEnvironmentsAsync)
|
||||
.mockResolvedValue(['production', 'preview', 'development']);
|
||||
jest.mocked(EnvironmentVariableMutation.createForAppAsync).mockResolvedValue({
|
||||
id: 'env-var-1',
|
||||
scope: EnvironmentVariableScope.Project,
|
||||
} as any);
|
||||
jest
|
||||
.mocked(EnvironmentVariableMutation.updateAsync)
|
||||
.mockResolvedValue({ id: 'env-var-1' } as any);
|
||||
jest.mocked(EnvironmentVariableMutation.deleteAsync).mockResolvedValue({ id: 'env-var-extra' });
|
||||
|
||||
jest
|
||||
.mocked(SupabaseQuery.getSupabaseConnectionByAccountIdAsync)
|
||||
.mockResolvedValue(mockConnection);
|
||||
jest
|
||||
.mocked(SupabaseMutation.listSupabaseOrganizationsAsync)
|
||||
.mockResolvedValue(mockOrganizations);
|
||||
jest
|
||||
.mocked(SupabaseMutation.fetchSupabasePublishableKeyAsync)
|
||||
.mockResolvedValue('sb_publishable_test');
|
||||
jest.mocked(SupabaseQuery.getSupabaseProjectByAppIdAsync).mockResolvedValue(mockProject);
|
||||
jest.mocked(SupabaseMutation.linkSupabaseProjectAsync).mockResolvedValue(mockProject);
|
||||
jest.mocked(SupabaseMutation.provisionSupabaseProjectAsync).mockResolvedValue({
|
||||
id: 'receipt-1',
|
||||
} as any);
|
||||
jest.mocked(pollForBackgroundJobReceiptAsync).mockResolvedValue({
|
||||
id: 'receipt-1',
|
||||
resultData: { supabaseProjectRef: mockProject.supabaseProjectRef },
|
||||
} as any);
|
||||
});
|
||||
|
||||
it('reuses an existing connection and project and writes public env vars', async () => {
|
||||
await createCommand([]).runAsync();
|
||||
|
||||
expect(SupabaseMutation.beginSupabaseOAuthAsync).not.toHaveBeenCalled();
|
||||
expect(SupabaseMutation.provisionSupabaseProjectAsync).not.toHaveBeenCalled();
|
||||
expect(spawnAsync).toHaveBeenCalledWith(
|
||||
'npx',
|
||||
expect.arrayContaining(['expo', 'install', '@supabase/supabase-js', 'expo-sqlite']),
|
||||
expect.objectContaining({
|
||||
cwd: '/test/project',
|
||||
})
|
||||
);
|
||||
expect(createOrModifyExpoConfigAsync).toHaveBeenCalled();
|
||||
const createdNames = jest
|
||||
.mocked(EnvironmentVariableMutation.createForAppAsync)
|
||||
.mock.calls.map(call => call[1].name);
|
||||
expect(createdNames).toEqual([
|
||||
'EXPO_PUBLIC_SUPABASE_URL',
|
||||
'EXPO_PUBLIC_SUPABASE_PUBLISHABLE_KEY',
|
||||
]);
|
||||
expect(
|
||||
jest.mocked(EnvironmentVariableMutation.createForAppAsync).mock.calls[0][1].visibility
|
||||
).toBe(EnvironmentVariableVisibility.Public);
|
||||
});
|
||||
|
||||
it('loads organizations once when formatting the existing connection label', async () => {
|
||||
await createCommand([]).runAsync();
|
||||
|
||||
expect(SupabaseMutation.listSupabaseOrganizationsAsync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('formats the connection when organization listing fails', async () => {
|
||||
jest
|
||||
.mocked(SupabaseMutation.listSupabaseOrganizationsAsync)
|
||||
.mockRejectedValue(new Error('skip'));
|
||||
|
||||
await createCommand(['--overwrite']).runAsync();
|
||||
|
||||
expect(Log.withTick).toHaveBeenCalledWith(expect.stringContaining('Primary Org'));
|
||||
});
|
||||
|
||||
it('strips EXPO_LOCAL / EXPO_STAGING / EXPO_UNIVERSE_DIR from the expo install env', async () => {
|
||||
const previous = {
|
||||
EXPO_LOCAL: process.env.EXPO_LOCAL,
|
||||
EXPO_STAGING: process.env.EXPO_STAGING,
|
||||
EXPO_UNIVERSE_DIR: process.env.EXPO_UNIVERSE_DIR,
|
||||
};
|
||||
process.env.EXPO_LOCAL = '1';
|
||||
process.env.EXPO_STAGING = '1';
|
||||
process.env.EXPO_UNIVERSE_DIR = '/tmp/universe';
|
||||
try {
|
||||
await createCommand([]).runAsync();
|
||||
const spawnOptions = jest.mocked(spawnAsync).mock.calls[0]?.[2] as {
|
||||
env?: NodeJS.ProcessEnv;
|
||||
};
|
||||
expect(spawnOptions.env?.EXPO_LOCAL).toBeUndefined();
|
||||
expect(spawnOptions.env?.EXPO_STAGING).toBeUndefined();
|
||||
expect(spawnOptions.env?.EXPO_UNIVERSE_DIR).toBeUndefined();
|
||||
} finally {
|
||||
for (const [key, value] of Object.entries(previous)) {
|
||||
if (value === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('links an existing project and skips provisioning', async () => {
|
||||
jest.mocked(SupabaseQuery.getSupabaseProjectByAppIdAsync).mockResolvedValue(null);
|
||||
jest.mocked(SupabaseMutation.linkSupabaseProjectAsync).mockResolvedValue(mockProject);
|
||||
|
||||
await createCommand(['--link', mockProject.supabaseProjectRef]).runAsync();
|
||||
|
||||
expect(SupabaseMutation.linkSupabaseProjectAsync).toHaveBeenCalledWith(graphqlClient, {
|
||||
appId: testProjectId,
|
||||
supabaseProjectRef: mockProject.supabaseProjectRef,
|
||||
});
|
||||
expect(SupabaseMutation.provisionSupabaseProjectAsync).not.toHaveBeenCalled();
|
||||
expect(SupabaseMutation.fetchSupabasePublishableKeyAsync).toHaveBeenCalled();
|
||||
expect(SupabaseQuery.getSupabaseProjectByAppIdAsync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('provisions via background receipt when no project is linked', async () => {
|
||||
jest
|
||||
.mocked(SupabaseQuery.getSupabaseProjectByAppIdAsync)
|
||||
.mockResolvedValueOnce(null)
|
||||
.mockResolvedValueOnce(mockProject);
|
||||
|
||||
await createCommand(['--region', 'americas', '--organization', 'org-slug']).runAsync();
|
||||
|
||||
expect(SupabaseMutation.provisionSupabaseProjectAsync).toHaveBeenCalledWith(graphqlClient, {
|
||||
appId: testProjectId,
|
||||
region: 'americas',
|
||||
});
|
||||
expect(pollForBackgroundJobReceiptAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
expect.anything(),
|
||||
expect.objectContaining({
|
||||
maxChecks: 420,
|
||||
maxConsecutiveFetchErrors: 3,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('surfaces a permanent provision failure with a --link hint', async () => {
|
||||
jest.mocked(SupabaseQuery.getSupabaseProjectByAppIdAsync).mockResolvedValue(null);
|
||||
jest.mocked(pollForBackgroundJobReceiptAsync).mockRejectedValue(
|
||||
new BackgroundJobReceiptPollError({
|
||||
errorType: BackgroundJobReceiptPollErrorType.JOB_FAILED_NO_WILL_RETRY,
|
||||
receiptErrorMessage: 'name already taken',
|
||||
})
|
||||
);
|
||||
|
||||
await expect(
|
||||
createCommand(['--region', 'americas', '--organization', 'org-slug']).runAsync()
|
||||
).rejects.toThrow(/name already taken[\s\S]*--link/);
|
||||
});
|
||||
|
||||
it('maps NULL_RECEIPT poll errors to a recoverable timeout hint', async () => {
|
||||
jest.mocked(SupabaseQuery.getSupabaseProjectByAppIdAsync).mockResolvedValue(null);
|
||||
jest.mocked(pollForBackgroundJobReceiptAsync).mockRejectedValue(
|
||||
new BackgroundJobReceiptPollError({
|
||||
errorType: BackgroundJobReceiptPollErrorType.NULL_RECEIPT,
|
||||
})
|
||||
);
|
||||
|
||||
await expect(
|
||||
createCommand(['--region', 'americas', '--organization', 'org-slug']).runAsync()
|
||||
).rejects.toThrow(/Timed out or lost contact[\s\S]*--link/);
|
||||
});
|
||||
|
||||
it('switches organization when --organization differs from the connection', async () => {
|
||||
jest
|
||||
.mocked(SupabaseQuery.getSupabaseProjectByAppIdAsync)
|
||||
.mockResolvedValueOnce(null)
|
||||
.mockResolvedValueOnce(mockProject);
|
||||
jest.mocked(SupabaseMutation.setSupabaseConnectionOrganizationAsync).mockResolvedValue({
|
||||
...mockConnection,
|
||||
supabaseOrganizationSlug: 'other-org',
|
||||
supabaseOrganizationName: 'Other Org',
|
||||
});
|
||||
|
||||
await createCommand(['--region', 'americas', '--organization', 'other-org']).runAsync();
|
||||
|
||||
expect(SupabaseMutation.setSupabaseConnectionOrganizationAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
{
|
||||
supabaseConnectionId: mockConnection.id,
|
||||
organizationSlug: 'other-org',
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
it('resets the connection with --reauth, then links an existing project by default', async () => {
|
||||
jest
|
||||
.mocked(SupabaseQuery.getSupabaseConnectionByAccountIdAsync)
|
||||
.mockResolvedValueOnce(mockConnection)
|
||||
.mockResolvedValueOnce(null)
|
||||
.mockResolvedValue(mockConnection);
|
||||
// Cascade delete removes the EAS project link with the connection.
|
||||
jest.mocked(SupabaseQuery.getSupabaseProjectByAppIdAsync).mockResolvedValue(null);
|
||||
jest.mocked(SupabaseMutation.beginSupabaseOAuthAsync).mockResolvedValue({
|
||||
url: 'https://api.supabase.com/v1/oauth/authorize',
|
||||
});
|
||||
jest.mocked(SupabaseMutation.disconnectSupabaseAsync).mockResolvedValue(mockConnection.id);
|
||||
jest.mocked(selectAsync).mockResolvedValueOnce('link').mockResolvedValue('americas');
|
||||
jest.mocked(promptAsync).mockResolvedValue({ linkValue: mockProject.supabaseProjectRef });
|
||||
jest.mocked(SupabaseMutation.linkSupabaseProjectAsync).mockResolvedValue(mockProject);
|
||||
|
||||
await createCommand(['--reauth']).runAsync();
|
||||
|
||||
expect(SupabaseMutation.disconnectSupabaseAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
mockConnection.id
|
||||
);
|
||||
expect(SupabaseMutation.beginSupabaseOAuthAsync).toHaveBeenCalled();
|
||||
expect(openBrowserAsync).toHaveBeenCalled();
|
||||
expect(selectAsync).toHaveBeenCalledWith(
|
||||
expect.stringContaining('previous EAS project link was removed'),
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ value: 'link' }),
|
||||
expect.objectContaining({ value: 'provision' }),
|
||||
]),
|
||||
expect.objectContaining({ initial: 'link' })
|
||||
);
|
||||
const promptOpts = jest.mocked(promptAsync).mock.calls[0]?.[0] as {
|
||||
validate?: (value: string) => true | string;
|
||||
};
|
||||
expect(promptOpts.validate?.(mockProject.supabaseProjectRef)).toBe(true);
|
||||
expect(promptOpts.validate?.('not a ref')).toEqual(expect.any(String));
|
||||
const parseSpy = jest
|
||||
.spyOn(supabaseCommandUtils, 'parseSupabaseProjectRef')
|
||||
.mockImplementationOnce(() => {
|
||||
throw 'nope';
|
||||
});
|
||||
expect(promptOpts.validate?.('x')).toBe('Invalid project ref or URL');
|
||||
parseSpy.mockRestore();
|
||||
expect(SupabaseMutation.linkSupabaseProjectAsync).toHaveBeenCalledWith(graphqlClient, {
|
||||
appId: testProjectId,
|
||||
supabaseProjectRef: mockProject.supabaseProjectRef,
|
||||
});
|
||||
expect(SupabaseMutation.provisionSupabaseProjectAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('provisions after --reauth when the user chooses provision', async () => {
|
||||
jest
|
||||
.mocked(SupabaseQuery.getSupabaseConnectionByAccountIdAsync)
|
||||
.mockResolvedValueOnce(mockConnection)
|
||||
.mockResolvedValueOnce(null)
|
||||
.mockResolvedValue(mockConnection);
|
||||
jest
|
||||
.mocked(SupabaseQuery.getSupabaseProjectByAppIdAsync)
|
||||
.mockResolvedValueOnce(null)
|
||||
.mockResolvedValue(mockProject);
|
||||
jest.mocked(SupabaseMutation.beginSupabaseOAuthAsync).mockResolvedValue({
|
||||
url: 'https://api.supabase.com/v1/oauth/authorize',
|
||||
});
|
||||
jest.mocked(SupabaseMutation.disconnectSupabaseAsync).mockResolvedValue(mockConnection.id);
|
||||
jest
|
||||
.mocked(selectAsync)
|
||||
.mockResolvedValueOnce('provision')
|
||||
.mockResolvedValueOnce('org-slug')
|
||||
.mockResolvedValue('americas');
|
||||
|
||||
await createCommand(['--reauth']).runAsync();
|
||||
|
||||
expect(SupabaseMutation.provisionSupabaseProjectAsync).toHaveBeenCalled();
|
||||
expect(SupabaseMutation.linkSupabaseProjectAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('skips the post-reauth prompt when --link is passed', async () => {
|
||||
jest
|
||||
.mocked(SupabaseQuery.getSupabaseConnectionByAccountIdAsync)
|
||||
.mockResolvedValueOnce(mockConnection)
|
||||
.mockResolvedValueOnce(null)
|
||||
.mockResolvedValue(mockConnection);
|
||||
jest.mocked(SupabaseQuery.getSupabaseProjectByAppIdAsync).mockResolvedValue(null);
|
||||
jest.mocked(SupabaseMutation.beginSupabaseOAuthAsync).mockResolvedValue({
|
||||
url: 'https://api.supabase.com/v1/oauth/authorize',
|
||||
});
|
||||
jest.mocked(SupabaseMutation.disconnectSupabaseAsync).mockResolvedValue(mockConnection.id);
|
||||
jest.mocked(SupabaseMutation.linkSupabaseProjectAsync).mockResolvedValue(mockProject);
|
||||
|
||||
await createCommand(['--reauth', '--link', mockProject.supabaseProjectRef]).runAsync();
|
||||
|
||||
expect(SupabaseMutation.linkSupabaseProjectAsync).toHaveBeenCalledWith(graphqlClient, {
|
||||
appId: testProjectId,
|
||||
supabaseProjectRef: mockProject.supabaseProjectRef,
|
||||
});
|
||||
expect(SupabaseMutation.provisionSupabaseProjectAsync).not.toHaveBeenCalled();
|
||||
expect(selectAsync).not.toHaveBeenCalledWith(
|
||||
expect.stringContaining('previous EAS project link was removed'),
|
||||
expect.anything(),
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects --reauth in non-interactive mode when a connection exists', async () => {
|
||||
await expect(createCommand(['--reauth', '--non-interactive']).runAsync()).rejects.toThrow(
|
||||
/non-interactive/
|
||||
);
|
||||
expect(SupabaseMutation.disconnectSupabaseAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ignores --reauth when there is no connection', async () => {
|
||||
jest
|
||||
.mocked(SupabaseQuery.getSupabaseConnectionByAccountIdAsync)
|
||||
.mockResolvedValueOnce(null)
|
||||
.mockResolvedValue(mockConnection);
|
||||
jest.mocked(SupabaseMutation.beginSupabaseOAuthAsync).mockResolvedValue({
|
||||
url: 'https://api.supabase.com/v1/oauth/authorize',
|
||||
});
|
||||
|
||||
await createCommand(['--reauth']).runAsync();
|
||||
|
||||
expect(Log.warn).toHaveBeenCalledWith(expect.stringContaining('--reauth ignored'));
|
||||
expect(SupabaseMutation.disconnectSupabaseAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('prints json output for an already-connected project', async () => {
|
||||
await createCommand(['--json']).runAsync();
|
||||
|
||||
expect(printJsonOnlyOutput).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
project: expect.objectContaining({ ref: mockProject.supabaseProjectRef }),
|
||||
envLocalWritten: true,
|
||||
manualSteps: [],
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('requires --region in non-interactive mode when provisioning', async () => {
|
||||
jest.mocked(SupabaseQuery.getSupabaseProjectByAppIdAsync).mockResolvedValue(null);
|
||||
|
||||
await expect(createCommand(['--non-interactive']).runAsync()).rejects.toThrow(/--region/);
|
||||
});
|
||||
|
||||
it('provisions an additional project for --environment preview', async () => {
|
||||
jest.mocked(SupabaseMutation.provisionAdditionalSupabaseProjectAsync).mockResolvedValue({
|
||||
id: 'receipt-additional',
|
||||
} as any);
|
||||
jest.mocked(pollForBackgroundJobReceiptAsync).mockResolvedValue({
|
||||
id: 'receipt-additional',
|
||||
resultData: {
|
||||
supabaseProjectRef: 'previewref123456',
|
||||
supabaseProjectUrl: 'https://previewref123456.supabase.co',
|
||||
supabaseRegion: 'us-east-1',
|
||||
publishableKey: 'sb_publishable_preview',
|
||||
},
|
||||
} as any);
|
||||
|
||||
await createCommand([
|
||||
'--environment',
|
||||
'preview',
|
||||
'--region',
|
||||
'americas',
|
||||
'--overwrite',
|
||||
]).runAsync();
|
||||
|
||||
expect(SupabaseMutation.provisionAdditionalSupabaseProjectAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
expect.objectContaining({
|
||||
appId: testProjectId,
|
||||
region: 'americas',
|
||||
projectNameSuffix: 'preview',
|
||||
})
|
||||
);
|
||||
expect(SupabaseMutation.provisionSupabaseProjectAsync).not.toHaveBeenCalled();
|
||||
expect(EnvironmentVariableMutation.createForAppAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
expect.objectContaining({
|
||||
name: 'EXPO_PUBLIC_SUPABASE_URL',
|
||||
value: 'https://previewref123456.supabase.co',
|
||||
environments: ['preview'],
|
||||
}),
|
||||
testProjectId
|
||||
);
|
||||
expect(spawnAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('surfaces additional provision failures with --link guidance', async () => {
|
||||
jest.mocked(SupabaseMutation.provisionAdditionalSupabaseProjectAsync).mockResolvedValue({
|
||||
id: 'receipt-additional',
|
||||
} as any);
|
||||
jest.mocked(pollForBackgroundJobReceiptAsync).mockRejectedValue(
|
||||
new BackgroundJobReceiptPollError({
|
||||
errorType: BackgroundJobReceiptPollErrorType.JOB_FAILED_NO_WILL_RETRY,
|
||||
receiptErrorMessage: 'maximum limits for the number of active free projects',
|
||||
})
|
||||
);
|
||||
|
||||
await expect(
|
||||
createCommand(['--environment', 'preview', '--region', 'americas', '--overwrite']).runAsync()
|
||||
).rejects.toThrow(
|
||||
/maximum limits for the number of active free projects[\s\S]*--environment preview(?!.*--link)/
|
||||
);
|
||||
});
|
||||
|
||||
it('peels preview off the primary env var when adding --environment preview', async () => {
|
||||
jest.mocked(EnvironmentVariablesQuery.byAppIdAsync).mockResolvedValue([
|
||||
{
|
||||
id: 'primary-url',
|
||||
name: 'EXPO_PUBLIC_SUPABASE_URL',
|
||||
value: 'https://primary.supabase.co',
|
||||
scope: EnvironmentVariableScope.Project,
|
||||
environments: ['production', 'preview', 'development'],
|
||||
},
|
||||
{
|
||||
id: 'primary-key',
|
||||
name: 'EXPO_PUBLIC_SUPABASE_PUBLISHABLE_KEY',
|
||||
value: 'sb_publishable_primary',
|
||||
scope: EnvironmentVariableScope.Project,
|
||||
environments: ['production', 'preview', 'development'],
|
||||
},
|
||||
] as any);
|
||||
jest.mocked(SupabaseMutation.provisionAdditionalSupabaseProjectAsync).mockResolvedValue({
|
||||
id: 'receipt-additional',
|
||||
} as any);
|
||||
jest.mocked(pollForBackgroundJobReceiptAsync).mockResolvedValue({
|
||||
id: 'receipt-additional',
|
||||
resultData: {
|
||||
supabaseProjectRef: 'previewref123456',
|
||||
supabaseProjectUrl: 'https://previewref123456.supabase.co',
|
||||
supabaseRegion: 'us-east-1',
|
||||
publishableKey: 'sb_publishable_preview',
|
||||
},
|
||||
} as any);
|
||||
|
||||
await createCommand([
|
||||
'--environment',
|
||||
'preview',
|
||||
'--region',
|
||||
'americas',
|
||||
'--overwrite',
|
||||
]).runAsync();
|
||||
|
||||
expect(EnvironmentVariableMutation.updateAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
expect.objectContaining({
|
||||
id: 'primary-url',
|
||||
environments: ['production', 'development'],
|
||||
})
|
||||
);
|
||||
expect(EnvironmentVariableMutation.createForAppAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
expect.objectContaining({
|
||||
name: 'EXPO_PUBLIC_SUPABASE_URL',
|
||||
value: 'https://previewref123456.supabase.co',
|
||||
environments: ['preview'],
|
||||
}),
|
||||
testProjectId
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects empty --environment', async () => {
|
||||
await expect(createCommand(['--environment', ' ']).runAsync()).rejects.toThrow(
|
||||
/at least one EAS environment/
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects unknown --environment in non-interactive mode', async () => {
|
||||
await expect(
|
||||
createCommand([
|
||||
'--environment',
|
||||
'prevew',
|
||||
'--region',
|
||||
'americas',
|
||||
'--non-interactive',
|
||||
]).runAsync()
|
||||
).rejects.toThrow(/EAS environment\(s\) not found/);
|
||||
});
|
||||
|
||||
it('proceeds with unknown --environment after confirmation', async () => {
|
||||
jest.mocked(SupabaseMutation.provisionAdditionalSupabaseProjectAsync).mockResolvedValue({
|
||||
id: 'receipt-additional',
|
||||
} as any);
|
||||
jest.mocked(pollForBackgroundJobReceiptAsync).mockResolvedValue({
|
||||
id: 'receipt-additional',
|
||||
resultData: {
|
||||
supabaseProjectRef: 'stagingref123456',
|
||||
supabaseProjectUrl: 'https://stagingref123456.supabase.co',
|
||||
supabaseRegion: 'us-east-1',
|
||||
publishableKey: 'sb_publishable_staging',
|
||||
},
|
||||
} as any);
|
||||
jest.mocked(confirmAsync).mockResolvedValue(true);
|
||||
|
||||
await createCommand(['--environment', 'staging', '--region', 'americas']).runAsync();
|
||||
|
||||
expect(confirmAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
message: expect.stringMatching(
|
||||
/EAS environment "staging" is not used on this project yet.*Continue provisioning\?/i
|
||||
),
|
||||
})
|
||||
);
|
||||
expect(EnvironmentVariableMutation.createForAppAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
expect.objectContaining({
|
||||
name: 'EXPO_PUBLIC_SUPABASE_URL',
|
||||
environments: ['staging'],
|
||||
}),
|
||||
testProjectId
|
||||
);
|
||||
});
|
||||
|
||||
it('aborts when declining to create an unknown --environment', async () => {
|
||||
jest.mocked(confirmAsync).mockResolvedValue(false);
|
||||
|
||||
await expect(
|
||||
createCommand(['--environment', 'staging', '--region', 'americas']).runAsync()
|
||||
).rejects.toThrow(/Canceled\. No additional Supabase project was provisioned/);
|
||||
expect(SupabaseMutation.provisionAdditionalSupabaseProjectAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects --environment with --link', async () => {
|
||||
await expect(
|
||||
createCommand(['--environment', 'preview', '--link', 'abcdefghijklmnop']).runAsync()
|
||||
).rejects.toThrow(/Cannot combine --environment with --link/);
|
||||
});
|
||||
|
||||
it('reconciles split env vars on a plain reconnect', async () => {
|
||||
jest.mocked(EnvironmentVariablesQuery.byAppIdAsync).mockResolvedValue([
|
||||
{
|
||||
id: 'primary-url',
|
||||
name: 'EXPO_PUBLIC_SUPABASE_URL',
|
||||
value: 'https://primary.supabase.co',
|
||||
scope: EnvironmentVariableScope.Project,
|
||||
environments: ['production', 'development'],
|
||||
},
|
||||
{
|
||||
id: 'preview-url',
|
||||
name: 'EXPO_PUBLIC_SUPABASE_URL',
|
||||
value: 'https://preview.supabase.co',
|
||||
scope: EnvironmentVariableScope.Project,
|
||||
environments: ['preview'],
|
||||
},
|
||||
] as any);
|
||||
|
||||
await createCommand(['--overwrite']).runAsync();
|
||||
|
||||
expect(EnvironmentVariableMutation.deleteAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'preview-url'
|
||||
);
|
||||
expect(EnvironmentVariableMutation.updateAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
expect.objectContaining({
|
||||
id: 'primary-url',
|
||||
value: mockProject.supabaseProjectUrl,
|
||||
environments: ['production', 'preview', 'development'],
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects --environment in non-interactive mode when env vars would be skipped', async () => {
|
||||
jest.mocked(EnvironmentVariablesQuery.byAppIdAsync).mockResolvedValue([
|
||||
{
|
||||
id: 'primary-url',
|
||||
name: 'EXPO_PUBLIC_SUPABASE_URL',
|
||||
value: 'https://primary.supabase.co',
|
||||
scope: EnvironmentVariableScope.Project,
|
||||
environments: ['production', 'preview', 'development'],
|
||||
},
|
||||
] as any);
|
||||
|
||||
await expect(
|
||||
createCommand([
|
||||
'--environment',
|
||||
'preview',
|
||||
'--region',
|
||||
'americas',
|
||||
'--non-interactive',
|
||||
]).runAsync()
|
||||
).rejects.toThrow(/--overwrite/);
|
||||
expect(SupabaseMutation.provisionAdditionalSupabaseProjectAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects --environment without a primary project', async () => {
|
||||
jest.mocked(SupabaseQuery.getSupabaseProjectByAppIdAsync).mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
createCommand(['--environment', 'preview', '--region', 'americas']).runAsync()
|
||||
).rejects.toThrow(/without --environment first/);
|
||||
});
|
||||
|
||||
it('continues and still writes env vars when SDK installation fails', async () => {
|
||||
jest.mocked(spawnAsync).mockRejectedValue(new Error('npm exploded'));
|
||||
|
||||
await createCommand(['--overwrite']).runAsync();
|
||||
|
||||
expect(EnvironmentVariableMutation.createForAppAsync).toHaveBeenCalled();
|
||||
expect(Log.warn).toHaveBeenCalledWith(expect.stringContaining('npx expo install'));
|
||||
});
|
||||
|
||||
it('on a dynamic config, shows Expo install guidance and skips a second plugin rewrite', async () => {
|
||||
const expoGuidance = [
|
||||
'Cannot automatically write to dynamic config at: app.config.js',
|
||||
'Add the following to your Expo config',
|
||||
'',
|
||||
'{',
|
||||
' "plugins": [',
|
||||
' "expo-sqlite"',
|
||||
' ]',
|
||||
'}',
|
||||
].join('\n');
|
||||
jest.mocked(spawnAsync).mockRejectedValue(
|
||||
Object.assign(new Error('Process exited with non-zero code: 1'), {
|
||||
stdout: `${expoGuidance}\n`,
|
||||
stderr: '',
|
||||
})
|
||||
);
|
||||
|
||||
await createCommand(['--overwrite']).runAsync();
|
||||
|
||||
expect(EnvironmentVariableMutation.createForAppAsync).toHaveBeenCalled();
|
||||
expect(createOrModifyExpoConfigAsync).not.toHaveBeenCalled();
|
||||
expect(Log.warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Cannot automatically write to dynamic config at: app.config.js')
|
||||
);
|
||||
expect(Log.warn).toHaveBeenCalledWith(expect.stringContaining('"expo-sqlite"'));
|
||||
expect(Log.warn).not.toHaveBeenCalledWith(expect.stringContaining("didn't install"));
|
||||
});
|
||||
|
||||
it('rejects --environment with --reauth', async () => {
|
||||
await expect(
|
||||
createCommand(['--environment', 'preview', '--reauth']).runAsync()
|
||||
).rejects.toThrow(/Cannot combine --environment with --reauth/);
|
||||
});
|
||||
|
||||
it('warns when --link differs from an already linked project', async () => {
|
||||
await createCommand(['--link', 'differentref12345', '--overwrite']).runAsync();
|
||||
|
||||
expect(Log.warn).toHaveBeenCalledWith(expect.stringContaining('Ignoring --link'));
|
||||
expect(SupabaseMutation.linkSupabaseProjectAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('warns when --region is passed for an already linked project', async () => {
|
||||
await createCommand(['--region', 'emea', '--overwrite']).runAsync();
|
||||
|
||||
expect(Log.warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Ignoring --region/--organization')
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when primary provision succeeds without a project link', async () => {
|
||||
jest.mocked(SupabaseQuery.getSupabaseProjectByAppIdAsync).mockResolvedValue(null);
|
||||
jest.mocked(pollForBackgroundJobReceiptAsync).mockResolvedValue({
|
||||
id: 'receipt-1',
|
||||
resultData: { supabaseProjectRef: 'newref1234567890' },
|
||||
} as any);
|
||||
|
||||
await expect(createCommand(['--region', 'americas', '--overwrite']).runAsync()).rejects.toThrow(
|
||||
/link with --link newref1234567890/
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when primary provision succeeds without a project ref in the receipt', async () => {
|
||||
jest.mocked(SupabaseQuery.getSupabaseProjectByAppIdAsync).mockResolvedValue(null);
|
||||
jest.mocked(pollForBackgroundJobReceiptAsync).mockResolvedValue({
|
||||
id: 'receipt-1',
|
||||
resultData: {},
|
||||
} as any);
|
||||
|
||||
await expect(createCommand(['--region', 'americas', '--overwrite']).runAsync()).rejects.toThrow(
|
||||
/Provision succeeded but the Expo project link was not found/
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when primary provision receipt data is not an object', async () => {
|
||||
jest.mocked(SupabaseQuery.getSupabaseProjectByAppIdAsync).mockResolvedValue(null);
|
||||
jest.mocked(pollForBackgroundJobReceiptAsync).mockResolvedValue({
|
||||
id: 'receipt-1',
|
||||
resultData: 'not-an-object',
|
||||
} as any);
|
||||
|
||||
await expect(createCommand(['--region', 'americas', '--overwrite']).runAsync()).rejects.toThrow(
|
||||
/Provision succeeded but the Expo project link was not found/
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects --environment without a connection', async () => {
|
||||
jest.mocked(SupabaseQuery.getSupabaseConnectionByAccountIdAsync).mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
createCommand(['--environment', 'preview', '--region', 'americas']).runAsync()
|
||||
).rejects.toThrow(/No Supabase connection found/);
|
||||
});
|
||||
|
||||
it('rejects --organization with --environment', async () => {
|
||||
await expect(
|
||||
createCommand([
|
||||
'--environment',
|
||||
'preview',
|
||||
'--region',
|
||||
'americas',
|
||||
'--organization',
|
||||
'other-org',
|
||||
'--overwrite',
|
||||
]).runAsync()
|
||||
).rejects.toThrow(/Cannot use --organization with --environment/);
|
||||
});
|
||||
|
||||
it('throws when additional provision omits credentials', async () => {
|
||||
jest.mocked(SupabaseMutation.provisionAdditionalSupabaseProjectAsync).mockResolvedValue({
|
||||
id: 'receipt-additional',
|
||||
} as any);
|
||||
jest.mocked(pollForBackgroundJobReceiptAsync).mockResolvedValue({
|
||||
id: 'receipt-additional',
|
||||
resultData: { supabaseProjectRef: 'previewref123456' },
|
||||
} as any);
|
||||
|
||||
await expect(
|
||||
createCommand(['--environment', 'preview', '--region', 'americas', '--overwrite']).runAsync()
|
||||
).rejects.toThrow(
|
||||
/did not return project credentials[\s\S]*Do not re-run connect --environment/
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when additional env writes partially skip', async () => {
|
||||
jest.mocked(SupabaseMutation.provisionAdditionalSupabaseProjectAsync).mockResolvedValue({
|
||||
id: 'receipt-additional',
|
||||
} as any);
|
||||
jest.mocked(pollForBackgroundJobReceiptAsync).mockResolvedValue({
|
||||
id: 'receipt-additional',
|
||||
resultData: {
|
||||
supabaseProjectRef: 'previewref123456',
|
||||
supabaseProjectUrl: 'https://previewref123456.supabase.co',
|
||||
supabaseRegion: 'us-east-1',
|
||||
publishableKey: 'sb_publishable_preview',
|
||||
},
|
||||
} as any);
|
||||
jest
|
||||
.mocked(EnvironmentVariablesQuery.byAppIdAsync)
|
||||
.mockResolvedValueOnce([]) // ensure: URL
|
||||
.mockResolvedValueOnce([]) // ensure: KEY
|
||||
.mockResolvedValueOnce([]) // upsert URL: create
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
id: 'existing-key',
|
||||
name: 'EXPO_PUBLIC_SUPABASE_PUBLISHABLE_KEY',
|
||||
value: 'different',
|
||||
scope: EnvironmentVariableScope.Project,
|
||||
environments: ['preview'],
|
||||
},
|
||||
] as any); // upsert KEY: exact match
|
||||
jest.mocked(confirmAsync).mockResolvedValue(false);
|
||||
|
||||
await expect(
|
||||
createCommand(['--environment', 'preview', '--region', 'americas']).runAsync()
|
||||
).rejects.toThrow(
|
||||
/did not write all EAS environment variables[\s\S]*Do not re-run connect --environment[\s\S]*sb_publishable_preview/
|
||||
);
|
||||
});
|
||||
|
||||
it('prints json for additional environment setup', async () => {
|
||||
jest.mocked(SupabaseMutation.provisionAdditionalSupabaseProjectAsync).mockResolvedValue({
|
||||
id: 'receipt-additional',
|
||||
} as any);
|
||||
jest.mocked(pollForBackgroundJobReceiptAsync).mockResolvedValue({
|
||||
id: 'receipt-additional',
|
||||
resultData: {
|
||||
supabaseProjectRef: 'previewref123456',
|
||||
supabaseProjectUrl: 'https://previewref123456.supabase.co',
|
||||
publishableKey: 'sb_publishable_preview',
|
||||
},
|
||||
} as any);
|
||||
jest
|
||||
.mocked(SupabaseMutation.listSupabaseOrganizationsAsync)
|
||||
.mockRejectedValue(new Error('skip'));
|
||||
|
||||
await createCommand([
|
||||
'--environment',
|
||||
'preview',
|
||||
'--region',
|
||||
'americas',
|
||||
'--overwrite',
|
||||
'--json',
|
||||
]).runAsync();
|
||||
|
||||
expect(printJsonOnlyOutput).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
additionalProject: expect.objectContaining({
|
||||
ref: 'previewref123456',
|
||||
region: 'americas',
|
||||
}),
|
||||
environments: ['preview'],
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('wraps env write failures after additional provision', async () => {
|
||||
jest.mocked(SupabaseMutation.provisionAdditionalSupabaseProjectAsync).mockResolvedValue({
|
||||
id: 'receipt-additional',
|
||||
} as any);
|
||||
jest.mocked(pollForBackgroundJobReceiptAsync).mockResolvedValue({
|
||||
id: 'receipt-additional',
|
||||
resultData: {
|
||||
supabaseProjectRef: 'previewref123456',
|
||||
supabaseProjectUrl: 'https://previewref123456.supabase.co',
|
||||
supabaseRegion: 'us-east-1',
|
||||
publishableKey: 'sb_publishable_preview',
|
||||
},
|
||||
} as any);
|
||||
jest
|
||||
.mocked(EnvironmentVariableMutation.createForAppAsync)
|
||||
.mockRejectedValue(new Error('graphql down'));
|
||||
|
||||
await expect(
|
||||
createCommand(['--environment', 'preview', '--region', 'americas', '--overwrite']).runAsync()
|
||||
).rejects.toThrow(
|
||||
/could not write EAS environment variables.*graphql down[\s\S]*Do not re-run connect --environment[\s\S]*EXPO_PUBLIC_SUPABASE_PUBLISHABLE_KEY=sb_publishable_preview/
|
||||
);
|
||||
});
|
||||
|
||||
it('wraps non-Error env write failures after additional provision', async () => {
|
||||
jest.mocked(SupabaseMutation.provisionAdditionalSupabaseProjectAsync).mockResolvedValue({
|
||||
id: 'receipt-additional',
|
||||
} as any);
|
||||
jest.mocked(pollForBackgroundJobReceiptAsync).mockResolvedValue({
|
||||
id: 'receipt-additional',
|
||||
resultData: {
|
||||
supabaseProjectRef: 'previewref123456',
|
||||
supabaseProjectUrl: 'https://previewref123456.supabase.co',
|
||||
supabaseRegion: 'us-east-1',
|
||||
publishableKey: 'sb_publishable_preview',
|
||||
},
|
||||
} as any);
|
||||
jest.mocked(EnvironmentVariableMutation.createForAppAsync).mockRejectedValue('graphql down');
|
||||
|
||||
await expect(
|
||||
createCommand(['--environment', 'preview', '--region', 'americas', '--overwrite']).runAsync()
|
||||
).rejects.toThrow(
|
||||
/could not write EAS environment variables.*graphql down[\s\S]*Do not re-run connect --environment/
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,130 @@
|
||||
import openBrowserAsync from 'better-opn';
|
||||
|
||||
import { getMockOclifConfig } from '../../../../__tests__/commands/utils';
|
||||
import { ExpoGraphqlClient } from '../../../../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
import { testProjectId } from '../../../../credentials/__tests__/fixtures-constants';
|
||||
import { SupabaseQuery } from '../../../../graphql/queries/SupabaseQuery';
|
||||
import { SupabaseProjectData } from '../../../../graphql/types/SupabaseConnection';
|
||||
import Log from '../../../../log';
|
||||
import { printJsonOnlyOutput } from '../../../../utils/json';
|
||||
import IntegrationsSupabaseDashboard from '../dashboard';
|
||||
|
||||
jest.mock('better-opn');
|
||||
jest.mock('../../../../graphql/queries/SupabaseQuery');
|
||||
jest.mock('../../../../log');
|
||||
jest.mock('../../../../utils/json');
|
||||
jest.mock('../../../../ora', () => ({
|
||||
ora: jest.fn(() => ({
|
||||
start: jest.fn().mockReturnThis(),
|
||||
succeed: jest.fn().mockReturnThis(),
|
||||
fail: jest.fn().mockReturnThis(),
|
||||
})),
|
||||
}));
|
||||
|
||||
describe(IntegrationsSupabaseDashboard, () => {
|
||||
const graphqlClient = {} as ExpoGraphqlClient;
|
||||
const mockConfig = getMockOclifConfig();
|
||||
|
||||
const mockProject: SupabaseProjectData = {
|
||||
id: 'project-1',
|
||||
supabaseProjectRef: 'abcdefghijklmnop',
|
||||
supabaseProjectName: 'Test App',
|
||||
supabaseProjectUrl: 'https://abcdefghijklmnop.supabase.co',
|
||||
supabaseRegion: 'us-east-1',
|
||||
createdAt: '2024-01-01T00:00:00.000Z',
|
||||
updatedAt: '2024-01-01T00:00:00.000Z',
|
||||
};
|
||||
|
||||
function createCommand(argv: string[]): IntegrationsSupabaseDashboard {
|
||||
const command = new IntegrationsSupabaseDashboard(argv, mockConfig);
|
||||
jest.spyOn(command as any, 'getContextAsync').mockReturnValue({
|
||||
privateProjectConfig: {
|
||||
projectId: testProjectId,
|
||||
exp: { slug: 'testapp' },
|
||||
},
|
||||
loggedIn: { graphqlClient },
|
||||
} as never);
|
||||
return command;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
jest.spyOn(Log, 'log').mockImplementation(() => {});
|
||||
jest.spyOn(Log, 'warn').mockImplementation(() => {});
|
||||
jest.mocked(SupabaseQuery.getSupabaseProjectByAppIdAsync).mockResolvedValue(mockProject);
|
||||
jest.mocked(openBrowserAsync).mockResolvedValue(true as never);
|
||||
});
|
||||
|
||||
it('opens the Supabase project dashboard', async () => {
|
||||
await createCommand([]).runAsync();
|
||||
|
||||
expect(openBrowserAsync).toHaveBeenCalledWith(
|
||||
'https://supabase.com/dashboard/project/abcdefghijklmnop'
|
||||
);
|
||||
});
|
||||
|
||||
it('prints the dashboard URL as JSON', async () => {
|
||||
await createCommand(['--json']).runAsync();
|
||||
|
||||
expect(printJsonOnlyOutput).toHaveBeenCalledWith({
|
||||
dashboardUrl: 'https://supabase.com/dashboard/project/abcdefghijklmnop',
|
||||
});
|
||||
expect(openBrowserAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('warns when no project is linked', async () => {
|
||||
jest.mocked(SupabaseQuery.getSupabaseProjectByAppIdAsync).mockResolvedValue(null);
|
||||
|
||||
await createCommand([]).runAsync();
|
||||
|
||||
expect(Log.warn).toHaveBeenCalledWith(expect.stringContaining('No Supabase project'));
|
||||
expect(openBrowserAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('emits a null dashboardUrl as JSON when no project is linked', async () => {
|
||||
jest.mocked(SupabaseQuery.getSupabaseProjectByAppIdAsync).mockResolvedValue(null);
|
||||
|
||||
await createCommand(['--json']).runAsync();
|
||||
|
||||
expect(printJsonOnlyOutput).toHaveBeenCalledWith({ dashboardUrl: null });
|
||||
expect(openBrowserAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('prints the dashboard URL in non-interactive mode', async () => {
|
||||
await createCommand(['--non-interactive']).runAsync();
|
||||
|
||||
expect(openBrowserAsync).not.toHaveBeenCalled();
|
||||
expect(Log.log).toHaveBeenCalledWith('https://supabase.com/dashboard/project/abcdefghijklmnop');
|
||||
});
|
||||
|
||||
it('fails the spinner when the browser cannot be opened', async () => {
|
||||
jest.mocked(openBrowserAsync).mockResolvedValue(false as never);
|
||||
const { ora } = jest.requireMock('../../../../ora');
|
||||
const spinner = {
|
||||
start: jest.fn().mockReturnThis(),
|
||||
succeed: jest.fn().mockReturnThis(),
|
||||
fail: jest.fn().mockReturnThis(),
|
||||
};
|
||||
ora.mockReturnValue(spinner);
|
||||
|
||||
await createCommand([]).runAsync();
|
||||
|
||||
expect(spinner.fail).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Unable to open a web browser')
|
||||
);
|
||||
});
|
||||
|
||||
it('fails the spinner and rethrows when opening the browser throws', async () => {
|
||||
jest.mocked(openBrowserAsync).mockRejectedValue(new Error('no browser'));
|
||||
const { ora } = jest.requireMock('../../../../ora');
|
||||
const spinner = {
|
||||
start: jest.fn().mockReturnThis(),
|
||||
succeed: jest.fn().mockReturnThis(),
|
||||
fail: jest.fn().mockReturnThis(),
|
||||
};
|
||||
ora.mockReturnValue(spinner);
|
||||
|
||||
await expect(createCommand([]).runAsync()).rejects.toThrow('no browser');
|
||||
expect(spinner.fail).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
import { getMockOclifConfig } from '../../../../__tests__/commands/utils';
|
||||
import { ExpoGraphqlClient } from '../../../../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
import { testProjectId } from '../../../../credentials/__tests__/fixtures-constants';
|
||||
import { SupabaseMutation } from '../../../../graphql/mutations/SupabaseMutation';
|
||||
import { SupabaseQuery } from '../../../../graphql/queries/SupabaseQuery';
|
||||
import { SupabaseProjectData } from '../../../../graphql/types/SupabaseConnection';
|
||||
import Log from '../../../../log';
|
||||
import { confirmAsync } from '../../../../prompts';
|
||||
import { printJsonOnlyOutput } from '../../../../utils/json';
|
||||
import IntegrationsSupabaseDisconnect from '../disconnect';
|
||||
|
||||
jest.mock('../../../../graphql/queries/SupabaseQuery');
|
||||
jest.mock('../../../../graphql/mutations/SupabaseMutation');
|
||||
jest.mock('../../../../prompts');
|
||||
jest.mock('../../../../log');
|
||||
jest.mock('../../../../utils/json');
|
||||
jest.mock('../../../../ora', () => ({
|
||||
ora: jest.fn(),
|
||||
}));
|
||||
|
||||
import { ora } from '../../../../ora';
|
||||
|
||||
function mockOraSpinner(): {
|
||||
start: jest.Mock;
|
||||
succeed: jest.Mock;
|
||||
fail: jest.Mock;
|
||||
} {
|
||||
const spinner = {
|
||||
start: jest.fn().mockReturnThis(),
|
||||
succeed: jest.fn().mockReturnThis(),
|
||||
fail: jest.fn().mockReturnThis(),
|
||||
};
|
||||
jest.mocked(ora).mockReturnValue(spinner as never);
|
||||
return spinner;
|
||||
}
|
||||
|
||||
describe(IntegrationsSupabaseDisconnect, () => {
|
||||
const graphqlClient = {} as ExpoGraphqlClient;
|
||||
const mockConfig = getMockOclifConfig();
|
||||
|
||||
const mockProject: SupabaseProjectData = {
|
||||
id: 'project-1',
|
||||
supabaseProjectRef: 'abcdefghijklmnop',
|
||||
supabaseProjectName: 'Test App',
|
||||
supabaseProjectUrl: 'https://abcdefghijklmnop.supabase.co',
|
||||
supabaseRegion: 'us-east-1',
|
||||
createdAt: '2024-01-01T00:00:00.000Z',
|
||||
updatedAt: '2024-01-01T00:00:00.000Z',
|
||||
};
|
||||
|
||||
function createCommand(argv: string[]): IntegrationsSupabaseDisconnect {
|
||||
const command = new IntegrationsSupabaseDisconnect(argv, mockConfig);
|
||||
jest.spyOn(command as any, 'getContextAsync').mockReturnValue({
|
||||
privateProjectConfig: {
|
||||
projectId: testProjectId,
|
||||
exp: { slug: 'testapp' },
|
||||
},
|
||||
loggedIn: { graphqlClient },
|
||||
} as never);
|
||||
return command;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
mockOraSpinner();
|
||||
jest.spyOn(Log, 'log').mockImplementation(() => {});
|
||||
jest.spyOn(Log, 'warn').mockImplementation(() => {});
|
||||
jest.spyOn(Log, 'error').mockImplementation(() => {});
|
||||
jest.spyOn(Log, 'addNewLineIfNone').mockImplementation(() => {});
|
||||
jest.spyOn(Log, 'newLine').mockImplementation(() => {});
|
||||
jest.mocked(SupabaseQuery.getSupabaseProjectByAppIdAsync).mockResolvedValue(mockProject);
|
||||
jest.mocked(SupabaseMutation.deleteSupabaseProjectAsync).mockResolvedValue(mockProject.id);
|
||||
jest.mocked(confirmAsync).mockResolvedValue(true);
|
||||
});
|
||||
|
||||
it('removes the project link after confirmation', async () => {
|
||||
await createCommand([]).runAsync();
|
||||
|
||||
expect(SupabaseMutation.deleteSupabaseProjectAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
mockProject.id
|
||||
);
|
||||
});
|
||||
|
||||
it('skips confirmation with --yes', async () => {
|
||||
await createCommand(['--yes']).runAsync();
|
||||
|
||||
expect(confirmAsync).not.toHaveBeenCalled();
|
||||
expect(SupabaseMutation.deleteSupabaseProjectAsync).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('cancels when confirmation is declined', async () => {
|
||||
jest.mocked(confirmAsync).mockResolvedValue(false);
|
||||
|
||||
await createCommand([]).runAsync();
|
||||
|
||||
expect(SupabaseMutation.deleteSupabaseProjectAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('prints json when no project is linked', async () => {
|
||||
jest.mocked(SupabaseQuery.getSupabaseProjectByAppIdAsync).mockResolvedValue(null);
|
||||
|
||||
await createCommand(['--json']).runAsync();
|
||||
|
||||
expect(printJsonOnlyOutput).toHaveBeenCalledWith({ id: null });
|
||||
});
|
||||
|
||||
it('warns when no project is linked', async () => {
|
||||
jest.mocked(SupabaseQuery.getSupabaseProjectByAppIdAsync).mockResolvedValue(null);
|
||||
|
||||
await createCommand([]).runAsync();
|
||||
|
||||
expect(Log.warn).toHaveBeenCalledWith(expect.stringContaining('No Supabase project'));
|
||||
expect(SupabaseMutation.deleteSupabaseProjectAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('prints json with id and ref on success', async () => {
|
||||
await createCommand(['--json', '--yes']).runAsync();
|
||||
|
||||
expect(printJsonOnlyOutput).toHaveBeenCalledWith({
|
||||
id: mockProject.id,
|
||||
ref: mockProject.supabaseProjectRef,
|
||||
});
|
||||
});
|
||||
|
||||
it('fails the spinner and rethrows when delete fails', async () => {
|
||||
jest
|
||||
.mocked(SupabaseMutation.deleteSupabaseProjectAsync)
|
||||
.mockRejectedValue(new Error('delete failed'));
|
||||
const spinner = mockOraSpinner();
|
||||
|
||||
await expect(createCommand(['--yes']).runAsync()).rejects.toThrow('delete failed');
|
||||
expect(spinner.fail).toHaveBeenCalledWith('Failed to remove Supabase project link');
|
||||
});
|
||||
});
|
||||
Loaded 100 of 222 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user