Compare commits

..
Author SHA1 Message Date
Ash Wu f208266373 [build-tools] run build jobs that carry builder: xcode through the Xcode steps 2026-11-23 23:05:23 +08:00
Ash Wu a7e76a6cb5 [build-tools] add the step function that verifies the artifact of a native iOS build 2026-11-23 23:05:23 +08:00
Ash Wu fb96dc6b0f [build-tools] add the step function that signs and builds a native iOS project 2026-11-23 23:05:22 +08:00
Ash Wu 5fe8c311d7 [build-tools] add the step functions that detect the Xcode project of a native iOS build 2026-11-23 23:05:17 +08:00
Ash Wu 6936b4f4e6 [eas-build-job] add builder to the build metadata 2026-11-23 22:32:24 +08:00
Ash Wu 346cc030d8 [eas-build-job] add the native job schema for Android 2026-11-23 22:32:23 +08:00
Ash Wu 8b683079c6 [eas-build-job] add the native job schema for iOS 2026-11-23 22:32:23 +08:00
Ash Wu 22f1fae8ec [eas-build-job] add the NativeBuilder enum 2026-11-23 22:32:22 +08:00
Ash Wu 7abd3fe05a [build-tools] extract the custom build project preparation into prepareProjectForStepsAsync 2026-11-23 22:32:22 +08:00
Ash Wu bf5ba2b25a [build-tools] run the after_checkout hook in builds without custom steps (#4920) 2026-11-23 15:30:12 +08:00
Expo CI b78cda16a5 bump STAGING and PRODUCTION to 27.11.0 in cli-versions.json 2026-11-19 17:02:36 +00:00
Expo CI 67972c5d6a v27.11.0 2026-11-19 16:17:39 +00:00
Mustafa Abban d88708d842 [eas-build-job] support Observe error occurrence events (#4860) 2026-11-19 10:41:38 -05:00
expo-tuft[bot] 13056cac22 [build-tools] report the installed app identifier in the agent-device remote config (#4831) 2026-11-19 18:02:26 +08:00
David Mokos 1b45814e3c updates agent-cli-detector to 0.1.8 (#4912) 2026-11-19 00:34:22 +01:00
Tomasz Mazur 8d00e33806 [build-tools] Compress dSYMs with zip level 1 in fastlane gym (#4909) 2026-11-18 21:05:24 +01:00
Szymon Świerk f27e7988a1 [eas-build-job] Accept issue_comment as a workflow github.event_name (#4906) 2026-11-17 18:45:59 +01:00
Gabe DebesandClaude Opus 5.5 b4e4229464 [build-tools] Add step functions to record simulator crash artifacts (#4596)
* [build-tools] Collect simulator crash artifacts

* [build-tools] Use shared crash artifact upload deadlines

* [build-tools] Link crash artifact changelog entry

* [build-tools] Bound crash collection retries and uploads

* [build-tools] Keep retrying productive crash streams

* [build-tools] preserve crash shutdown mock in merged host tests

* Save individual native IPS crash artifacts

* [build-tools] Keep missing crash reports outside artifact limits

* [build-tools] Verify missing crash reports across reconnects

* [build-tools] Reserve crash collection before asynchronous setup

* [build-tools] Release failed crash recorder initialization

* [build-tools] Address crash artifact review findings

Skip a crash occurrence whose detail fails or exceeds 8 MiB instead of
reconnecting, and check each device's crash list once more on stop so
occurrences the stream had not delivered are kept. Key occurrences by
capture time and report path, merge the seen and skipped sets, create the
directory before the session is registered, and log dropped errors.
Artifacts are now kind simulator-crash with per-device numbered ids,
names, and filenames.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* [build-tools] Retry transient crash detail failures

Try a failed crash detail up to three times before skipping it; skip a
missing, mismatched, malformed, or oversized detail at once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* [build-tools] Address second crash artifact review

Keep each device's serve-sim address current for the final pass, warn
when its deadline stops a device, report poller and upload failures to
Sentry, name failed uploads by report, and fall back to the process name
when the app name is empty.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* [build-tools] Skip crash details that a retry cannot fix

Treat invalid JSON and permanent 4xx responses as unusable, so they are
not retried three times before later reports are collected.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* [build-tools] Upload crash reports with the shared file upload helper

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-16 16:09:00 -07:00
Gabe DebesandClaude Opus 5.5 a04489e678 [build-tools] Add step functions to record simulator HAR artifacts (#4495)
* [build-tools] record network capture with serve-sim capture har steps

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* [build-tools] Rename the network capture recording step

Edited-by: Codex

* [build-tools] Remove the capture recorder command override

Edited-by: Codex

* [build-tools] Bound failed network capture followers

* [build-tools] Limit HAR artifact uploads to 500 MiB

* [build-tools] Address HAR capture review findings

Rename the record step to eas/start_serve_sim_network_capture and the
upload helper to a one-file serveSimNetworkCaptureArtifacts; the collect
step numbers parts. Count HARs by their entry log so empty recordings
are neither uploaded nor use recording slots, give followers that record
nothing a slower restart and a separate start cap, drop the spawn
failure throttle and unreachable guards, and allow 60 s for the final
HAR rebuild with followers stopped together.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* [build-tools] Bound HAR recording slots and uploads

Exited followers that recorded nothing no longer use recording slots, a
restarted serve-sim replaces the old identity's follower, the recording
limit warns once, and each HAR upload has a 10-minute limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* [build-tools] Keep the ngrok token from the HAR follower

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* [build-tools] Drop requests a restarted HAR follower replays

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* [build-tools] Keep unflushed HAR requests and remove replayed parts

Rebuild every kept HAR from its entry log before its requests count as
recorded, and delete the files of a follower that held only replayed
requests when it is dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* [build-tools] Upload network captures with the shared file upload helper

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* [build-tools] Import formatBytes from eas-build-job

Main moved formatBytes into @expo/eas-build-job (#4854).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
2026-11-16 16:09:00 -07:00
4b6fd3c942 Remove sjchmiela from automated routing (#4862)
Co-authored-by: sjchmiela <[email protected]>
Co-authored-by: Copilot <[email protected]>
2026-11-14 23:47:39 +00:00
Gabe Debes e34c0cb3f6 [eas-cli] Mark default devices in simulator:devices (#4895) 2026-11-13 23:52:38 +00:00
Szymon Dziedzic c7f766568c [build-tools] Count Android web preview input toward the session idle timeout (#4890)
* [build-tools] Count Android web preview input toward the session idle timeout

* [build-tools] Count an expo-device-hub read timeout as unobservable, not as a down device
2026-11-14 00:32:58 +01:00
Szymon Dziedzic a328e59ee4 [build-tools] Do not fail a successful session when its tool tunnel cannot stop (#4893)
* [build-tools] Do not fail a successful session when its tool tunnel cannot stop

* Shorten the changeset to one sentence

* Name the options for tool tunnels and test a startup Stop
2026-11-14 00:27:04 +01:00
Expo CI f843a97165 bump STAGING and PRODUCTION to 27.10.0 in cli-versions.json 2026-11-13 23:05:29 +00:00
Expo CI 1e112fee24 v27.10.0 2026-11-13 22:56:24 +00:00
Brent Vatne 6d3e79c255 [eas-cli] Add simulator:devices command (#4879)
* [eas-cli] Add simulator:devices command

* [eas-cli] Use offered devices in the simulator:start --device help

* [eas-cli] Show simulator:devices as a table of suggested devices
2026-11-13 15:19:37 -07:00
Ramon Claudio 04e909c4d9 [eas-cli][build-tools] Bump Node.js to 22.23.5 (#4889)
* [eas-cli] Bump Node.js to 22.23.5

* [eas-cli] Add changeset

* [build-tools] Bump Node.js to 22.23.5
2026-11-13 17:16:06 -05:00
David Mokos 1a6e94123a [eas-cli] Report the parent CLI command in telemetry (#4876) 2026-11-13 21:01:05 +01:00
Szymon Dziedzic 544cd18bac [build-tools] Retry the first ngrok tunnel open in device run sessions (#4874)
* [build-tools] Retry the first ngrok tunnel open in device run sessions

* [build-tools] Retry the first ngrok open only after the failed open settles

@ngrok/ngrok runs every forward behind one process-wide lock, so a retry
while a timed-out open is still pending only waits behind it. Keep the rule
that no open starts while another is pending: after a time-out, wait a
bounded time for the open to settle, then retry, or fail at once.

Retry only time-outs and ERR_NGROK_802, and let callers cancel startup
retries with a signal.

* [build-tools] Fail ngrok startup with the abort reason and keep the endpoint free

An abort during the wait for a failed open to settle threw the time-out
error, so callers that compare against the startup signal's reason reported
a failed session instead of a stop. Throw the abort reason. Do not retry
while a late listener from the failed open is still open. Add the startup
abort listener only after the local target listens, so it is always removed.

* [build-tools] Log why the first ngrok open is not retried

Say whether the failed open is still pending or its late listener did not
close. Test that an abort while the local target starts prevents the open.

* [build-tools] Keep a late first ngrok open and retry only rejected opens

The first open now waits 19 s instead of retrying a timed-out open. ngrok runs one
open at a time, so a retry after a time-out could only start after the stuck open
settled, and it closed a listener that had arrived late. Only a rejected open with
an exact retryable ngrok error code (ERR_NGROK_802) is retried.

The preview tunnel in the session host now stops retrying when the host finishes.
An open in progress continues, so preview retirement still waits for it.

* [build-tools] Test a non-retryable first-open failure after 15 seconds

* [build-tools] Give ngrok open retries the reopen time-out and log late opens

Retries use the 15 s reopen time-out, so all three attempts fit in the 60 s
preview opening bound. A timed-out or cancelled open logs its outcome and
elapsed time when it settles, so the first-open time-out can be tuned.

* [build-tools] Document why ngrok open retries use a new agent session
2026-11-13 11:52:23 -07:00
krystofwoldrich-agentandClaude Opus 5.5 8dc514e9f2 [build-tools] Preload the experimental emulator capture into the Android Emulator (#4827)
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-13 18:35:40 +01:00
Tomasz Mazur f4b4f035b0 [build-tools] Run the client's command in worker SSH sessions (#4863) 2026-11-12 13:47:29 +01:00
Tomasz Mazur 92397fd3d4 [build-tools] Always download upterm for worker SSH sessions (#4859) 2026-11-12 13:47:29 +01:00
Tomasz Mazur 154d90d3ce [build-tools] Run worker SSH sessions as detached upterm sessions (#4857)
* [build-tools] Run worker SSH sessions as detached upterm sessions

* [build-tools] Redact the upterm session id by its JSON field and known value

* [build-tools] Remove the known session id redaction

* [build-tools] Remove the URL userinfo redaction fallback

* [build-tools] Test that a failed upterm start stops the session

* [build-tools] Keep using an upterm found on PATH for SSH sessions

* [build-tools] Report the SSH reconnecting state from the supervisor

* [build-tools] Count SSH guests with upterm's guestCount
2026-11-12 13:47:28 +01:00
Expo CI 5a0908533b bump STAGING and PRODUCTION to 27.9.0 in cli-versions.json 2026-11-12 12:31:34 +00:00
Expo CI 14e9f1af44 v27.9.0 2026-11-12 12:16:18 +00:00
Szymon Dziedzic 291ec6f2c8 [eas-cli] Warn about EAS Simulator outages in simulator:start (#4873)
* [eas-cli] warn about EAS Simulator outages in simulator:start

* [eas-cli] name the simulator status page service Expo Simulators
2026-11-12 13:13:42 +01:00
Expo CI a4edee8178 bump STAGING and PRODUCTION to 27.8.0 in cli-versions.json 2026-11-12 11:11:46 +00:00
Expo CI 6fa3f47f91 v27.8.0 2026-11-12 11:04:19 +00:00
Szymon DziedzicandClaude Opus 5.5 71338cbaa2 [eas-cli] Remove Android in-development warning from eas simulator (#4870)
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-12 11:48:16 +01:00
Szymon DziedzicandClaude Opus 5.5 36f83dee90 [eas-cli] Drop the experimental label from simulator commands except local egress (#4869)
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-12 11:48:01 +01:00
Szymon Dziedzic 352c3b68f0 [eas-cli] Point gated simulator accounts at paid plans instead of the waitlist (#4866)
* [eas-cli] Point gated simulator accounts at paid plans instead of the waitlist

* [eas-cli] Tell annual Enterprise accounts to contact their account executive

The server does not include annual Enterprise prices at simulator GA. The CLI cannot see the plan, so the gated message covers this case too.
2026-11-12 11:47:36 +01:00
Gabe DebesandCodex 5dafefd484 [eas-cli] Upload local Simulator app bundles (#4684)
* [eas-cli] Upload local Simulator app bundles

* [eas-cli] Reject unsupported Simulator install archives before upload

* [eas-cli] Keep upload folder guidance specific to the action

* [eas-cli] Clean interrupted app archives and serialize packaging

Start progress before packaging, require archive support for local archives, and keep unknown capability metadata from rejecting the action catalog. Add child-process interruption and packaging coverage.

Co-authored-by: Codex <[email protected]>

---------

Co-authored-by: Codex <[email protected]>
2026-11-11 21:02:10 -07:00
Vojtech NovakandClaude Fable 5.2 b7ff9b10d8 [eas-build-job][build-tools][eas-cli] Share one formatBytes helper and fix sizes of 102.4 GB and larger (#4854)
* [build-tools] Fix formatBytes for sizes of 102.4 GB and larger

The last branch divided by 1024 instead of by the GB multiplier, so
200 GB was formatted as "209715200 GB". Add table tests for the helper.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* [eas-build-job][build-tools][eas-cli] Share one formatBytes helper

build-tools and eas-cli each had the same formatBytes copy. Move it to
@expo/eas-build-job, migrate all callers, and delete both copies.
eas-cli now also gets the fix for sizes of 102.4 GB and larger.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* [build-tools] Import formatBytes from eas-build-job in androidEmulatorLogs

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Merge the two formatBytes changesets

Co-Authored-By: Claude Fable 5.2 <[email protected]>

---------

Co-authored-by: Claude Fable 5.2 <[email protected]>
2026-11-11 20:41:11 -07:00
SJ Kim 55d1e2942d [build-tools] Point Android device sessions at the scrcpy server copy (#4848) 2026-11-11 05:34:51 -05:00
Ash Wu a7f9742a03 [build-tools] report maestro-runner flow tags from report.json (#4853) 2026-11-11 16:10:16 +08:00
Hirbod f615fc5ba3 [build-tools] Send session preview size metadata (#4864)
* [build-tools] Send session preview size metadata

* [build-tools] Store a new preview size only after its image uploads
2026-11-10 23:45:44 +00:00
Hirbod 00ef775b2b [build-tools] Send screenshot size metadata (#4858)
* [build-tools] Send screenshot size metadata

* [build-tools] Keep only the screenshot metadata fields that are set

* [build-tools] Send screenshot size metadata for Argent screenshots

* [build-tools] Send screenshot size metadata for Argent screenshot diffs
2026-11-10 22:32:39 +00:00
Gabe Debes e914819052 [build-tools] Fix iOS session thumbnails on multi-display Simulators (#4777)
* [build-tools] Capture iOS session thumbnails through serve-sim

Edited-by: Codex

* [build-tools] Mark thumbnail captures as automation

Edited-by: Codex

* [build-tools] Keep the default screenshot Desktop copy

* [build-tools] Clarify session preview errors

* [build-tools] Capture session previews without probing the catalog

Edited-by: Codex

* [build-tools] Check automated screenshot support before previews
2026-11-10 10:52:09 -07:00
Expo CI ab32f0c241 bump STAGING and PRODUCTION to 27.7.2 in cli-versions.json 2026-11-10 17:07:58 +00:00
Expo CI 951ccba62c v27.7.2 2026-11-10 17:00:49 +00:00
Tomasz Mazur 8c0e01d64c [eas-cli] Show the ID argument and examples in workflow:ssh help (#4829)
* [eas-cli] Fix workflow SSH help and error text

* [eas-cli] Revert worker wording in workflow:run SSH text

* [eas-cli] Revert workflow:ssh error text
2026-11-10 17:36:59 +01:00
Vojtech NovakandClaude Fable 5.1 539acb8c23 [eas-cli] Add --log-source to eas simulator (#4823)
* [eas-cli] Add --android-log-source to eas simulator

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* [eas-cli] Drop the retention period from the --android-log-source help

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* [eas-cli] Shorten the --android-log-source changeset

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* [eas-cli] Rename --android-log-source to --log-source

The flag is unprefixed like the step input it feeds. Passing it without
--platform android fails at runtime.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
2026-11-10 17:18:53 +01:00
Expo CI 18d85d571a bump STAGING and PRODUCTION to 27.7.1 in cli-versions.json 2026-11-10 13:36:49 +00:00
Tomasz Mazur f2cf409b21 [build-tools] Start SSH session shells in the build directory (#4843) 2026-11-10 13:40:14 +01:00
Tomasz Mazur 0cf8cd014f [eas-cli] Show the ended message when workflow:ssh is given a finished build ID (#4842) 2026-11-10 13:38:46 +01:00
Expo CI 8df11a04ee v27.7.1 2026-11-10 11:28:19 +00:00
Tomek Czajecki c9d198a894 [eas-cli] update dependencies with security advisories (#4847)
* [eas-cli] update dependencies with security advisories

* [eas-cli] remove unrelated lockfile dedupe
2026-11-10 13:03:43 +02:00
Szymon Świerk 4b70eb14fb [build-tools] Strip the repository access token from the git remote before the sandbox agent starts (#4826)
* [build-tools] Strip the repository access token from the git remote before the sandbox agent starts

* [build-tools] improve the comment explaining why the repository token is stripped before the sandbox starts
2026-11-10 11:25:41 +01:00
Expo CI c224ba58ff bump STAGING and PRODUCTION to 27.7.0 in cli-versions.json 2026-11-10 08:32:43 +00:00
Expo CI 8d5a2e3332 v27.7.0 2026-11-10 08:25:21 +00:00
Vojtech NovakandClaude Fable 5.1 b95b7c930a [build-tools] Record and upload selected Android emulator logs (#4822)
* [build-tools] Record and upload selected Android emulator logs

Select Android log sources at session startup, attach the bounded capture
to every emulator launch, and upload the finalized logs as simulator
session artifacts with truncation metadata.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* [build-tools] Upload one Android log artifact per source

Pass the source selection through the capture instead of a second
parameter, let the capture create the launch files, and name artifacts
after the source ring. Finalize the other-workflow capture in the
collection test so no handle closes at garbage collection.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* [build-tools] Shorten the Android log changeset

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* [build-tools] Choose the Android log writer by session

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* [build-tools] Rename android_log_sources to log_sources

The input is unprefixed like every other step input. A non-empty list on an
iOS session fails at runtime, the way network_capture does on Android. The
agent-device step drops its default so an omitted input stays distinguishable
from an explicit selection; the fallback is resolved in code.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* [build-tools] Format the retained log size with formatBytes

Co-Authored-By: Claude Fable 5.1 <[email protected]>

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
2026-11-10 09:01:58 +01:00
Vojtech NovakandClaude Fable 5.1 8ed5c16c7b [build-tools] Add bounded Android emulator log capture (#4821)
* [build-tools] Add bounded Android emulator log capture

Capture emulator output and logcat into fixed-size ring files that keep
the last 20 MiB per source across launches, with logcat delivered through
a named pipe. No caller yet; the emulator wiring follows.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* [build-tools] Keep one ring file per Android log source

Sessions write every launch of a source into one ring, `<source>.log`,
with a marker line per launch that produced output. This replaces the
per-launch rings and their cross-file eviction, and bounds disk use at the
budget. Ordinary builds keep plain per-launch files closed per launch. The
capture now owns the source selection.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* [build-tools] Split the plain Android log writer from the ring

`AndroidEmulatorLogCapture` is now the interface both writers implement.
`AndroidEmulatorLogRing` serves sessions and has no mode checks;
`AndroidEmulatorLogFiles` serves ordinary builds with one appended file
per launch. Document what the logcat output's `closed` promise is for.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
2026-11-10 09:01:57 +01:00
Vojtech NovakandClaude Fable 5.1 fa5dee437f [build-tools] Share device run session file uploads (#4820)
Move the stat, size-zero skip and per-attempt stream reopening into one
helper, and use it for serve-sim app logs.

Co-authored-by: Claude Fable 5.1 <[email protected]>
2026-11-10 09:01:57 +01:00
Ash Wu 65ef172a78 [eas-cli] add --git-branch and --git-commit-hash to workflow:run (#4815)
`eas workflow:run <file>` uploads the local project, so the run carries
no branch or commit and the EAS dashboard cannot list it under a branch.
The two flags record the branch and commit the uploaded
project comes from. They must be given together and cannot be combined
with `--ref`. The server verifies the commit in the project's linked
GitHub repository and reads the commit message from GitHub.

Generated GraphQL types come from production plus the pending www
schema change, so the diff also carries unrelated schema drift.
2026-11-10 15:11:23 +08:00
Brent Vatne b15ea359b6 [eas-cli] Send each spinner frame as one write to stop flicker (#4850) 2026-11-09 22:16:21 -07:00
Brent Vatne ab86b647cf [ci] Compare the changeset check with the base branch, not a stale base SHA (#4851) 2026-11-09 20:06:47 -07:00
Expo CI f6669461cd bump STAGING and PRODUCTION to 27.6.0 in cli-versions.json 2026-11-10 01:22:04 +00:00
Expo CI 5f560f8fc2 v27.6.0 2026-11-10 01:17:13 +00:00
Gabe Debes a3e4617d1c [simulator-launcher] Add Simulator and native tool warmup (#4838)
* [simulator-launcher] Add Simulator and native tool warmup

Edited-by: Codex

* [simulator-launcher] Simplify Expo Go preparation call
2026-11-09 17:44:56 -07:00
Gabe Debes 2e45595250 [build-tools] Reuse prefetched Simulator tools (#4837)
* [build-tools] Reuse prepared Simulator tools

Edited-by: Codex

* [build-tools] Preserve cold Appium setup and validate cached WDA

* [build-tools] Retry cancelled Appium version lookups after adoption fails

* [build-tools] Clarify prepared Appium version matching
2026-11-09 17:44:56 -07:00
Gabe Debes 0c768729a9 [simulator-launcher] Report caller-supplied tool versions (#4845)
* [simulator-launcher] Report caller-supplied tool versions

Edited-by: Codex

* [simulator-launcher] Use semver for version validation

Edited-by: Codex
2026-11-09 17:44:56 -07:00
Gabe Debes f37ad5e137 [simulator-launcher] Prefetch Appium and WebDriverAgent files (#4836)
* [simulator-launcher] Prefetch Appium and WebDriverAgent files

Edited-by: Codex

* [simulator-launcher] Validate the downloaded WDA bundle
2026-11-09 17:44:55 -07:00
Gabe Debes 4d3cba95af [simulator-launcher] Prefetch the selected Expo Go archive (#4834)
* [simulator-launcher] Prefetch the selected Expo Go archive

Edited-by: Codex

* [simulator-launcher] Simplify the changeset

Edited-by: Codex
2026-11-09 17:44:55 -07:00
Gabe Debes d57eadf887 [vm-tools] Use interactive scheduling for Simulator sessions (#4833) 2026-11-09 12:55:32 -07:00
Jakub Tkacz ccba9a0c8d [eas-cli] Add --property filter to observe:events (#4812)
* [eas-cli] Add --property filter to observe:events

Adds a repeatable --property key=value flag that filters events by an exact property match.

Closes ENG-28851

* [eas-cli] Test that observe:events --property forwards an empty value

* [eas-cli] Address review: reject empty, repeated, and more than 5 --property filters
2026-11-09 09:00:31 +01:00
Jakub Tkacz 3fc8dadd63 [eas-cli] Stop suggesting event names when observe:events --session-id finds nothing (#4813)
* [eas-cli] Stop suggesting event names when observe:events --session-id finds nothing

With an event name and --session-id, an empty result does not mean the event name is wrong, so show the plain empty result instead of other event names.

* [eas-cli] Address review: scope comment to --session-id, add --json test

* [eas-cli] Address review: skip suggestions for --app-version, --build-number and --update-id
2026-11-09 09:00:30 +01:00
Tomasz Mazur 50dcb89a0c [build-tools] Require the sandbox worker token for sandbox jobs (#4808) 2026-11-06 15:25:32 +01:00
Ash Wu 84b3bc6354 [build-tools] make iOS Simulator readiness work on the iOS 27.2 runtime (#4816)
On iOS 27.2 `com.apple.datamigrator` stays resident as an idle launchd_sim
service after it reports that no migration is needed, so waiting for it to
exit never ends. The wait is now skipped on iOS 27.2 and later and kept on
earlier runtimes, where the process exits within about a minute of boot and
the wait still keeps the data-migration screen from appearing mid-test
(eas-build #579). The version is the one `simctl list runtimes` reports for
the device's runtime, compared with semver. `simctl list devices` lists UDIDs
in upper case, so a UDID given in lower case is upper-cased first.

The iPhone Duo on iOS 27.2 exposes two integrated screens, and
`simctl io screenshot` without `--display` exits 22, so the readiness
screenshot names the first integrated screen from `simctl io enumerate` when
more than one is listed. Single-screen devices keep the plain command: the
simctl in Xcode 15.3 rejects a numeric `--display`.
2026-11-06 14:46:08 +08:00
Expo CI 2749518a31 bump STAGING and PRODUCTION to 27.5.0 in cli-versions.json 2026-11-05 23:08:41 +00:00
Expo CI 7819779519 v27.5.0 2026-11-05 23:03:34 +00:00
Gabe Debes 1eee88fc8f [eas-cli] Import simulator startup configuration (#4687) 2026-11-05 15:33:26 -07:00
Gabe Debes ab50bdf55a [eas-cli] Import simulator control actions from a file (#4686) 2026-11-05 15:33:25 -07:00
Gabe DebesandCodex ec9896ae23 [eas-cli] Share simulator controls and keep connections alive (#4791)
Co-authored-by: Codex <[email protected]>
2026-11-05 15:33:25 -07:00
Byron KarlenandClaude Opus 5.5 21a16849c1 [eas-cli] Decouple username from account name (#3922)
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-05 13:57:23 -08:00
Tomasz Mazur 8501f3e7d8 [build-tools][worker] Use the sandbox worker API when www provides a sandbox worker token (#4807) 2026-11-05 15:44:27 +01:00
Szymon DziedzicandClaude eedff0c99d [eas-cli] Add simulators, emulator and emulators aliases for simulator commands (#4794)
Claude-Session: https://claude.ai/code/session_018fQcYvCuJxvWc1i889MW2r

Co-authored-by: Claude <[email protected]>
2026-11-05 14:05:30 +01:00
Tomasz Mazur c7e9fe56de [build-tools] Extract a shared worker API client from the device run session client (#4806) 2026-11-05 13:59:40 +01:00
Tomasz Mazur b8505a90f1 [eas-cli] Unhide the workflow:ssh command (#4793) 2026-11-05 12:28:52 +01:00
361 changed files with 30180 additions and 5045 deletions

No files matched your search

@@ -1,5 +0,0 @@
---
'@expo/build-tools': patch
---
Stop an agent-device session that is still starting up when it is stopped.
-6
View File
@@ -1,6 +0,0 @@
---
'@expo/build-tools': patch
---
Stop an Appium session that is still starting up when it is stopped.
Report temporary-directory cleanup failures when Stop interrupts Appium installation.
-5
View File
@@ -1,5 +0,0 @@
---
'@expo/build-tools': patch
---
Stop an Argent session that is still starting up when it is stopped.
+5
View File
@@ -0,0 +1,5 @@
---
'@expo/build-tools': minor
---
Run the `after_checkout` workflow hook in build jobs that do not use custom steps.
+5
View File
@@ -0,0 +1,5 @@
---
'@expo/eas-build-job': minor
---
Add the native job schema for Android, with the `builder` field.
+5
View File
@@ -0,0 +1,5 @@
---
'@expo/eas-build-job': minor
---
Add `builder` to the build metadata.
+5
View File
@@ -0,0 +1,5 @@
---
'@expo/eas-build-job': minor
---
Add the `NativeBuilder` enum.
+5
View File
@@ -0,0 +1,5 @@
---
'@expo/build-tools': none
---
Add the step function that signs and builds a native iOS project with fastlane gym.
+5
View File
@@ -0,0 +1,5 @@
---
'@expo/eas-build-job': minor
---
Add the native job schema for iOS: `builder`, `projectFile`, and `secrets.credentialsByBundleIdentifier`.
+5
View File
@@ -0,0 +1,5 @@
---
'@expo/build-tools': none
---
Add the step function that verifies the artifact of a native iOS build.
+5
View File
@@ -0,0 +1,5 @@
---
'@expo/build-tools': none
---
Add the step functions that install pods and detect the Xcode project for a native iOS build.
+5
View File
@@ -0,0 +1,5 @@
---
'@expo/build-tools': none
---
Extract the custom build project preparation into `prepareProjectForStepsAsync`.
-8
View File
@@ -1,8 +0,0 @@
---
'@expo/build-tools': patch
'eas-cli': patch
---
Record and upload Android emulator process output as a simulator session artifact by default. Add explicit source selection and a simulator CLI flag to opt in to recording and uploading device-wide logcat. Unselected sources are not recorded by simulator sessions.
Simulator sessions retain the first 20 MiB of each selected Android log source across launches and retries. The limit is enforced while recording; excess output is drained without saving, and artifacts remain uncompressed.
-5
View File
@@ -1,5 +0,0 @@
---
'eas-cli': patch
---
Show the Expo Simulators hint after a successful build from November 12 instead of November 10.
@@ -1,5 +0,0 @@
---
'@expo/build-tools': patch
---
Stop a web-preview session that is still starting up when it is stopped.
+5
View File
@@ -0,0 +1,5 @@
---
'@expo/build-tools': minor
---
Build a native iOS project with Xcode when the build job carries `builder: xcode`.
-6
View File
@@ -22,9 +22,3 @@ rules:
mentions: ['kitten', 'kadikraman']
- patterns: ['packages/eas-cli/src/commands/deploy/**']
mentions: ['kitten', 'kadikraman']
- patterns: ['packages/eas-cli/src/commands/build/**']
mentions: ['sjchmiela']
- patterns: ['packages/eas-cli/src/build/**']
mentions: ['sjchmiela']
- patterns: ['packages/eas-cli/src/commands/workflow/**']
mentions: ['sjchmiela']
+195 -26
View File
@@ -1,39 +1,208 @@
name: Build Android worker for manual testing
name: build-and-deploy-worker
# Assumes main branch always specifies an environment (staging/production).
# If environment is empty: PR testing build (no upload, no deploy)
# If environment is set: Build (unless cached on main), upload, and deploy
on:
workflow_dispatch:
inputs:
environment:
description: Build a Linux artifact for manual staging testing; does not deploy
type: choice
options:
- staging
default: staging
description: '"staging", "production" or empty'
type: string
required: true
permissions:
contents: read
workflow_call:
inputs:
environment:
description: '"staging", "production" or empty'
type: string
required: true
jobs:
build-android-staging-test:
if: inputs.environment == 'staging'
build-and-deploy:
runs-on: ubuntu-latest
timeout-minutes: 25
permissions:
id-token: write
steps:
- uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4
- uses: ./.github/actions/setup-mise
- run: yarn install --immutable
- name: Package Linux worker from this checkout
- name: Install eas-cli
run: npm install --global eas-cli@latest
- uses: ./.github/internal-actions/setup-gcloud
- name: Check if worker already exists
id: check_worker_exists
# Check if tarballs for this SHA already exist
# If they do, we can skip building regardless of branch
if: inputs.environment != ''
run: |
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
echo "worker_exists=false" >> "$GITHUB_OUTPUT"
exit 0
fi
done
echo "worker_exists=true" >> "$GITHUB_OUTPUT"
- name: Start EAS Workflow to build worker tarballs
id: eas_workflow
# Build if: PR testing (no env), or deploying but tarballs don't exist
if: inputs.environment == '' || steps.check_worker_exists.outputs.worker_exists == 'false'
working-directory: packages/worker
env:
OUTPUT_DIR: ${{ runner.temp }}/android-worker-staging-test
EXPO_TOKEN: ${{ secrets.EXPO_DEV_EXPO_GITHUB_ROBOT_ACCESS_TOKEN }}
run: |
set -euo pipefail
mkdir -p "$OUTPUT_DIR"
bash packages/worker/package.sh "$OUTPUT_DIR/worker-android.tar.gz" android
tar -xOf "$OUTPUT_DIR/worker-android.tar.gz" ./packages/build-tools/dist/steps/utils/androidEmulatorLogs.js > "$OUTPUT_DIR/androidEmulatorLogs.js"
cd "$OUTPUT_DIR"
sha256sum worker-android.tar.gz androidEmulatorLogs.js > SHA256SUMS
printf '%s\n' "$GITHUB_SHA" > build-revision.txt
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: android-worker-staging-test
path: ${{ runner.temp }}/android-worker-staging-test/
retention-days: 7
if-no-files-found: error
# Only upload artifacts from EAS if GHA will upload them to GCS
# This avoids unnecessary artifact uploads for PR builds
SHOULD_UPLOAD_ARTIFACT="${{ inputs.environment != '' && steps.check_worker_exists.outputs.worker_exists == 'false' }}"
# Run workflow and capture output (includes run ID)
WORKFLOW_OUTPUT=$(eas workflow:run build-worker.yml \
--ref ${{ github.sha }} \
--input upload_artifact=$SHOULD_UPLOAD_ARTIFACT \
--non-interactive \
--no-wait \
--json)
WORKFLOW_RUN_ID=$(echo "$WORKFLOW_OUTPUT" | jq -r '.id')
if [ -z "$WORKFLOW_RUN_ID" ] || [ "$WORKFLOW_RUN_ID" = "null" ]; then
echo "Error: Could not determine workflow run ID"
echo "Workflow output:"
echo "$WORKFLOW_OUTPUT" | jq .
exit 1
fi
echo "workflow_run_id=$WORKFLOW_RUN_ID" >> "$GITHUB_OUTPUT"
- name: Wait for EAS workflow and capture artifacts
id: eas_artifacts
if: inputs.environment == '' || steps.check_worker_exists.outputs.worker_exists == 'false'
working-directory: packages/worker
env:
EXPO_TOKEN: ${{ secrets.EXPO_DEV_EXPO_GITHUB_ROBOT_ACCESS_TOKEN }}
run: |
set -euo pipefail
WORKFLOW_RUN_ID="${{ steps.eas_workflow.outputs.workflow_run_id }}"
if [ -z "$WORKFLOW_RUN_ID" ]; then
echo "Error: Missing workflow run ID"
exit 1
fi
SHOULD_UPLOAD_ARTIFACT="${{ inputs.environment != '' && steps.check_worker_exists.outputs.worker_exists == 'false' }}"
while true; do
VIEW_OUTPUT=$(eas workflow:view "$WORKFLOW_RUN_ID" \
--non-interactive \
--json)
STATUS=$(echo "$VIEW_OUTPUT" | jq -r '.status')
case "$STATUS" in
SUCCESS)
break
;;
FAILURE)
echo "EAS workflow failed."
echo "$VIEW_OUTPUT" | jq .
exit 1
;;
CANCELED)
echo "EAS workflow canceled."
echo "$VIEW_OUTPUT" | jq .
exit 1
;;
ACTION_REQUIRED)
echo "EAS workflow requires action."
echo "$VIEW_OUTPUT" | jq .
exit 1
;;
NEW|IN_PROGRESS)
sleep 7
;;
*)
echo "Unexpected workflow status: $STATUS"
echo "$VIEW_OUTPUT" | jq .
exit 1
;;
esac
done
# Skip artifact extraction if we didn't request uploads
if [ "$SHOULD_UPLOAD_ARTIFACT" == "false" ]; then
echo "Skipping artifact download - upload was disabled for this run"
exit 0
fi
# Extract artifact download URLs from workflow output
# Artifacts are in jobs[].artifacts[] for custom jobs
DOWNLOAD_IOS_URL=$(echo "$VIEW_OUTPUT" | jq -r '
.jobs[]
| .artifacts[]?
| select(.name == "worker-ios-tarball")
| .downloadUrl
' | head -1)
DOWNLOAD_ANDROID_URL=$(echo "$VIEW_OUTPUT" | jq -r '
.jobs[]
| .artifacts[]?
| select(.name == "worker-android-tarball")
| .downloadUrl
' | head -1)
if [ -z "$DOWNLOAD_IOS_URL" ] || [ "$DOWNLOAD_IOS_URL" = "null" ]; then
echo "Error: Could not find iOS artifact download URL"
echo "$VIEW_OUTPUT" | jq .
exit 1
fi
if [ -z "$DOWNLOAD_ANDROID_URL" ] || [ "$DOWNLOAD_ANDROID_URL" = "null" ]; then
echo "Error: Could not find Android artifact download URL"
echo "$VIEW_OUTPUT" | jq .
exit 1
fi
# Mask the download URLs
echo "::add-mask::$DOWNLOAD_IOS_URL"
echo "::add-mask::$DOWNLOAD_ANDROID_URL"
echo "download_ios_url=$DOWNLOAD_IOS_URL" >> "$GITHUB_OUTPUT"
echo "download_android_url=$DOWNLOAD_ANDROID_URL" >> "$GITHUB_OUTPUT"
- name: Cancel EAS workflow on GitHub cancellation
if: cancelled()
working-directory: packages/worker
env:
EXPO_TOKEN: ${{ secrets.EXPO_DEV_EXPO_GITHUB_ROBOT_ACCESS_TOKEN }}
run: |
set -euo pipefail
WORKFLOW_RUN_ID="${{ steps.eas_workflow.outputs.workflow_run_id }}"
if [ -n "$WORKFLOW_RUN_ID" ]; then
eas workflow:cancel "$WORKFLOW_RUN_ID" --non-interactive
fi
- name: Upload worker tarballs to GCP
# Upload when deploying if we built something new
# Don't upload PR builds (no environment) or when using cached tarballs
if: inputs.environment != '' && steps.check_worker_exists.outputs.worker_exists == 'false'
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"
- name: Promote worker to ${{ inputs.environment }}
if: inputs.environment != ''
run: |
for platform in android ios; do
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"
done
+3 -1
View File
@@ -28,7 +28,9 @@ jobs:
contains(github.event.pull_request.labels.*.name, 'no changelog') ||
github.event.pull_request.user.login == 'dependabot[bot]'
}}
BASE_REF: ${{ github.event.pull_request.base.sha || 'origin/main' }}
# The base branch, not `pull_request.base.sha`: that SHA can be older than the base that the
# checked-out merge commit contains, and the diff then includes other people's changes.
BASE_REF: origin/${{ github.base_ref || 'main' }}
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
+2 -2
View File
@@ -83,8 +83,8 @@ jobs:
git push --force-with-lease origin "$branch"
if gh pr view "$branch" --json state --jq '.state' 2>/dev/null | grep -q OPEN; then
gh pr edit "$branch" --title "$title" --body "$body" --add-reviewer sjchmiela
gh pr edit "$branch" --title "$title" --body "$body"
else
gh pr create --base main --head "$branch" --title "$title" --body "$body" \
--label 'no changelog' --reviewer sjchmiela
--label 'no changelog'
fi
+137
View File
@@ -2,6 +2,143 @@
This is the log of notable changes to EAS CLI and related packages.
## [27.11.0](https://github.com/expo/eas-cli/releases/tag/v27.11.0) - 2026-11-19
### 🎉 New features
- [build-tools] Report the identifier of the installed app as `applicationIdentifier` in the agent-device remote config, so clients can attach to the app of an `application_archive_url` session. ([#4831](https://github.com/expo/eas-cli/pull/4831) by [@expo-tuft](https://github.com/apps/expo-tuft))
- [build-tools] Count Android web preview input as session activity, so `max_idle_time_minutes` works on Android sessions. `eas/start_serve_sim_remote_session` no longer rejects it on Android; the API does not accept an idle timeout for Android web-preview-only sessions yet. ([#4890](https://github.com/expo/eas-cli/pull/4890) by [@szdziedzic](https://github.com/szdziedzic))
- [eas-build-job] Accept `issue_comment` as a `github.event_name` value in the workflow interpolation context. ([#4906](https://github.com/expo/eas-cli/pull/4906) by [@sswrk](https://github.com/sswrk))
- [eas-build-job] Support error occurrence events in Observe workflow context. ([#4860](https://github.com/expo/eas-cli/pull/4860) by [@AbbanMustafa](https://github.com/AbbanMustafa))
- [build-tools] Add start and collect steps that attach serve-sim simulator crash reports to device run sessions as IPS files. ([#4596](https://github.com/expo/eas-cli/pull/4596) by [@gwdp](https://github.com/gwdp))
- [build-tools] Add start and collect steps that attach serve-sim network captures to device run sessions as HAR files. ([#4495](https://github.com/expo/eas-cli/pull/4495) by [@gwdp](https://github.com/gwdp))
### 🐛 Bug fixes
- [eas-cli] Detect Factory Droid, Grok Bot, Claude Cowork, and Muse in EAS CLI telemetry. ([#4912](https://github.com/expo/eas-cli/pull/4912) by [@davidmokos](https://github.com/davidmokos))
- [build-tools] Default `fastlane gym` dSYM compression level to 1. ([#4909](https://github.com/expo/eas-cli/pull/4909) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
- [eas-cli] Mark the default device for each platform in `eas simulator:devices` and include `isDefault` in JSON output. ([#4895](https://github.com/expo/eas-cli/pull/4895) by [@gwdp](https://github.com/gwdp))
- [build-tools] A successful remote device run session no longer fails when its agent-device, Appium, or Argent tunnel does not stop within its time-out. ([#4893](https://github.com/expo/eas-cli/pull/4893) by [@szdziedzic](https://github.com/szdziedzic))
## [27.10.0](https://github.com/expo/eas-cli/releases/tag/v27.10.0) - 2026-11-13
### 🎉 New features
- [build-tools] Add the experimental `experimental_emulator_capture_version` input to `eas/start_android_emulator`. The Android Emulator then preloads that version of the `expo-emulator-capture` agent and uses the lavapipe renderer, and later steps start expo-device-hub with the emulator capture on. When the agent cannot install, the emulator starts as before. Only web preview sessions support the capture for now, so other session types fail with an error when the input is set. ([#4827](https://github.com/expo/eas-cli/pull/4827) by [@krystofwoldrich-agent](https://github.com/krystofwoldrich-agent))
- [eas-cli] Add `eas simulator:devices` to list the devices Expo suggests for a simulator session. ([#4879](https://github.com/expo/eas-cli/pull/4879) by [@brentvatne](https://github.com/brentvatne))
### 🐛 Bug fixes
- [build-tools] Retry the first ngrok tunnel open of a device run session up to two times when ngrok rejects it with ERR_NGROK_802. The first open now waits 19 seconds instead of 15, so a tunnel that opens late is kept instead of closed. Startup can be cancelled during the retries, and a preview tunnel stops retrying when its session host finishes. ([#4874](https://github.com/expo/eas-cli/pull/4874) by [@szdziedzic](https://github.com/szdziedzic))
- [eas-cli] Include the parent CLI command in telemetry to distinguish nested commands from direct usage. ([#4876](https://github.com/expo/eas-cli/pull/4876) by [@davidmokos](https://github.com/davidmokos))
- [build-tools] Run worker SSH sessions as detached upterm sessions that reconnect on their own under the same session ID, and stop them with `upterm session stop`. ([#4857](https://github.com/expo/eas-cli/pull/4857) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
- [build-tools] Run the command a client passes with `eas workflow:ssh <id> <command>` in worker SSH sessions, in the build directory. ([#4863](https://github.com/expo/eas-cli/pull/4863) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
- [build-tools] Always download upterm for worker SSH sessions instead of using an `upterm` found on `PATH`. ([#4859](https://github.com/expo/eas-cli/pull/4859) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
### 🧹 Chores
- [eas-cli][build-tools] Bump Node.js to 22.23.5 to fix the CVEs in the [November 2026 Node.js security releases](https://nodejs.org/en/blog/vulnerability/november-2026-security-releases). ([#4889](https://github.com/expo/eas-cli/pull/4889) by [@ramonclaudio](https://github.com/ramonclaudio))
## [27.9.0](https://github.com/expo/eas-cli/releases/tag/v27.9.0) - 2026-11-12
### 🎉 New features
- [eas-cli] Warn about Expo Simulators and EAS Workflows outages from status.expo.dev before `eas simulator:start` creates a session, and describe degraded performance and maintenance correctly in all outage warnings. ([#4873](https://github.com/expo/eas-cli/pull/4873) by [@szdziedzic](https://github.com/szdziedzic))
## [27.8.0](https://github.com/expo/eas-cli/releases/tag/v27.8.0) - 2026-11-12
### 🎉 New features
- [eas-cli] Tell accounts without EAS Simulator access that it is available on the Starter, Production, and Enterprise plans and link to the billing page, instead of pointing at the waitlist. `simulator:availability --json` now returns `billingUrl` instead of `waitlistUrl`. ([#4866](https://github.com/expo/eas-cli/pull/4866) by [@szdziedzic](https://github.com/szdziedzic))
### 🐛 Bug fixes
- [build-tools] Point expo-device-hub at the scrcpy server copy in the `turtle-v2` bucket in Android device sessions, so a failed GitHub release download no longer fails the session. expo-device-hub falls back to GitHub when the copy is missing. ([#4848](https://github.com/expo/eas-cli/pull/4848) by [@sjkim-expo](https://github.com/sjkim-expo))
- [build-tools] Fix black iOS session preview artifacts on multi-display Simulators by capturing the active display through serve-sim. ([#4777](https://github.com/expo/eas-cli/pull/4777) by [@gwdp](https://github.com/gwdp))
Skip automatic previews on older serve-sim versions that cannot exclude them from idle activity.
- [build-tools] Report flow tags with the Maestro test results of jobs that run `maestro-runner`. The tags are read from the runner's `report.json`. ([#4853](https://github.com/expo/eas-cli/pull/4853) by [@hSATAC](https://github.com/hSATAC))
- [build-tools] Send the session preview size to `preview-upload-session` and refresh it when the size changes. ([#4864](https://github.com/expo/eas-cli/pull/4864) by [@hirbod](https://github.com/hirbod))
- [eas-cli] Remove the "Android emulator support is still in development" warning from `eas simulator`. ([#4870](https://github.com/expo/eas-cli/pull/4870) by [@szdziedzic](https://github.com/szdziedzic))
- [build-tools] Send the width, height and source of simulator session screenshots (manual, agent-device and Argent, including Argent screenshot diffs) as artifact metadata, read from the image header. ([#4858](https://github.com/expo/eas-cli/pull/4858) by [@hirbod](https://github.com/hirbod))
- [eas-cli][build-tools][eas-build-job] Fix sizes of 102.4 GB and larger being printed with a value about a million times too large, and share one `formatBytes` helper between `eas-cli` and `build-tools`. ([#4854](https://github.com/expo/eas-cli/pull/4854) by [@vonovak](https://github.com/vonovak))
- [eas-cli] Package local Simulator app bundles for upload when the host supports gzip tar archives, and reject unsupported IPA and ZIP installs before uploading. ([#4684](https://github.com/expo/eas-cli/pull/4684) by [@gwdp](https://github.com/gwdp))
Fix packaging stalls for app bundles containing hard links and clean temporary archives when interrupted. Local app directories and `.tar.gz`/`.tgz` files require a host advertising archive support.
- [eas-cli] Remove the `[EXPERIMENTAL]` label from `eas simulator` commands, except `eas simulator:egress` and the `--egress` flag. ([#4869](https://github.com/expo/eas-cli/pull/4869) by [@szdziedzic](https://github.com/szdziedzic))
## [27.7.2](https://github.com/expo/eas-cli/releases/tag/v27.7.2) - 2026-11-10
### 🐛 Bug fixes
- [eas-cli] Add `--log-source` to `eas simulator` to select which Android logs a session records. ([#4823](https://github.com/expo/eas-cli/pull/4823) by [@vonovak](https://github.com/vonovak))
- [build-tools] Start SSH session shells in the job's build directory instead of the worker's directory. ([#4843](https://github.com/expo/eas-cli/pull/4843) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
- [eas-cli] Show that the ssh session has ended, instead of saying SSH was not enabled, when `eas workflow:ssh` is given the ID of a finished build. ([#4842](https://github.com/expo/eas-cli/pull/4842) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
- [eas-cli] Show the ID argument and examples in `eas workflow:ssh --help`. ([#4829](https://github.com/expo/eas-cli/pull/4829) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
## [27.7.1](https://github.com/expo/eas-cli/releases/tag/v27.7.1) - 2026-11-10
### 🐛 Bug fixes
- [eas-cli][eas-json][build-tools][eas-build-job][steps][local-build-plugin][worker][simulator-launcher] Update `node-forge`, `tar`, `nanoid`, `minimatch`, `joi`, `ajv`, `yaml`, and `zod` to versions with fixes for published security advisories. ([#4847](https://github.com/expo/eas-cli/pull/4847) by [@tchayen](https://github.com/tchayen))
- [build-tools] Strip the GitHub repository access token from the git remote before a sandbox agent starts. ([#4826](https://github.com/expo/eas-cli/pull/4826) by [@sswrk](https://github.com/sswrk))
## [27.7.0](https://github.com/expo/eas-cli/releases/tag/v27.7.0) - 2026-11-10
### 🎉 New features
- [eas-cli] Add `--git-branch` and `--git-commit-hash` to `eas workflow:run` to record the branch and commit of the uploaded project. ([#4815](https://github.com/expo/eas-cli/pull/4815) by [@hSATAC](https://github.com/hSATAC))
### 🐛 Bug fixes
- [build-tools] Record Android emulator output and, when selected, device logcat during simulator sessions, and upload the last 20 MiB of each as a session artifact. ([#4822](https://github.com/expo/eas-cli/pull/4822) by [@vonovak](https://github.com/vonovak))
- [eas-cli] Stop spinners from flickering when their text wraps onto a second line, such as the `simulator:start` queue message in a narrow terminal. ([#4850](https://github.com/expo/eas-cli/pull/4850) by [@brentvatne](https://github.com/brentvatne))
## [27.6.0](https://github.com/expo/eas-cli/releases/tag/v27.6.0) - 2026-11-10
### 🎉 New features
- [build-tools] Reuse compatible prefetched Appium and XCUITest files without removing them during cleanup. Resolve explicit package versions, including `latest`, and reuse prepared tools only when they match. Use the launcher's runtime serve-sim version for warm adoption and recordings, including prereleases. ([#4837](https://github.com/expo/eas-cli/pull/4837) by [@gwdp](https://github.com/gwdp))
- [eas-cli] Add the `--property key=value` flag to `eas observe:events` to filter events by a property value. ([#4812](https://github.com/expo/eas-cli/pull/4812) by [@Ubax](https://github.com/Ubax))
- [simulator-launcher] Prepare pinned Appium, XCUITest and WebDriverAgent files with `prefetch`. ([#4836](https://github.com/expo/eas-cli/pull/4836) by [@gwdp](https://github.com/gwdp))
- [simulator-launcher] Add `simulator-launcher prefetch` to cache Expo Go downloads. ([#4834](https://github.com/expo/eas-cli/pull/4834) by [@gwdp](https://github.com/gwdp))
- [simulator-launcher] Use caller-supplied serve-sim, agent-device and Argent versions and include exact version inputs in claims. ([#4845](https://github.com/expo/eas-cli/pull/4845) by [@gwdp](https://github.com/gwdp))
- [simulator-launcher] Add `simulator-launcher warmup` so consumers can warm up Simulators, install Expo Go and prepare native tool caches. The command stops its tools and shuts down the selected Simulators before returning. ([#4838](https://github.com/expo/eas-cli/pull/4838) by [@gwdp](https://github.com/gwdp))
### 🐛 Bug fixes
- [build-tools] Stop waiting for `com.apple.datamigrator` to exit before an iOS Simulator on iOS 27.2 or later counts as ready; there it stays resident, so the wait never finished. Earlier runtimes keep the wait. Take the readiness screenshot from the first integrated screen when the device lists several, so the iPhone Duo on iOS 27.2 passes the check. ([#4816](https://github.com/expo/eas-cli/pull/4816) by [@hSATAC](https://github.com/hSATAC))
- [eas-cli] Stop suggesting other event names in `eas observe:events` when an event name with `--session-id`, `--app-version`, `--build-number`, or `--update-id` returns no events. ([#4813](https://github.com/expo/eas-cli/pull/4813) by [@Ubax](https://github.com/Ubax))
- [build-tools] Require the sandbox worker token for sandbox jobs and remove the sandbox GraphQL fallback. ([#4808](https://github.com/expo/eas-cli/pull/4808) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
- [vm-tools] Run the macOS VM-tools service with interactive scheduling so Simulator startup and preview processes avoid launchd's default CPU and I/O throttling. ([#4833](https://github.com/expo/eas-cli/pull/4833) by [@gwdp](https://github.com/gwdp))
## [27.5.0](https://github.com/expo/eas-cli/releases/tag/v27.5.0) - 2026-11-05
### 🎉 New features
- [eas-cli] Import ordered action configurations with `eas simulator:control --import` and show progress for each action. ([#4686](https://github.com/expo/eas-cli/pull/4686) by [@gwdp](https://github.com/gwdp))
- [eas-cli] Reuse simulator control connections with `--keep-alive` or `simulator:control:connection open`. Set an idle timeout, inspect the connection, or close it without stopping the simulator session. Keep-alive currently supports macOS and Linux. ([#4791](https://github.com/expo/eas-cli/pull/4791) by [@gwdp](https://github.com/gwdp))
- [eas-cli] Start simulator sessions from saved settings and apply control actions after readiness. ([#4687](https://github.com/expo/eas-cli/pull/4687) by [@gwdp](https://github.com/gwdp))
- [eas-cli] Run `eas simulator` commands also as `eas simulators`, `eas emulator` and `eas emulators`, for example `eas emulators:start` or `eas simulators:list`. These aliases are hidden from help. ([#4794](https://github.com/expo/eas-cli/pull/4794) by [@szdziedzic](https://github.com/szdziedzic))
- [eas-cli] List `eas workflow:ssh` in `eas --help`. ([#4793](https://github.com/expo/eas-cli/pull/4793) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
### 🐛 Bug fixes
- [build-tools] Stop an agent-device session that is still starting up when it is stopped. ([#4666](https://github.com/expo/eas-cli/pull/4666) by [@gwdp](https://github.com/gwdp))
- [build-tools] Stop an Appium session that is still starting up when it is stopped. ([#4668](https://github.com/expo/eas-cli/pull/4668) by [@gwdp](https://github.com/gwdp))
Report temporary-directory cleanup failures when Stop interrupts Appium installation.
- [build-tools] Stop an Argent session that is still starting up when it is stopped. ([#4667](https://github.com/expo/eas-cli/pull/4667) by [@gwdp](https://github.com/gwdp))
- [eas-cli] Find the personal account by its owner instead of assuming that its name equals the username. ([#3922](https://github.com/expo/eas-cli/pull/3922) by [@byronkarlen](https://github.com/byronkarlen))
- [build-tools][worker] Use the sandbox worker token for sandbox jobs when www provides one, and keep Expo credentials out of the commands of those jobs. ([#4807](https://github.com/expo/eas-cli/pull/4807) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
- [eas-cli] Show the Expo Simulators hint after a successful build from November 12 instead of November 10. ([#4817](https://github.com/expo/eas-cli/pull/4817) by [@williamgrosset](https://github.com/williamgrosset))
- [build-tools] Stop a web-preview session that is still starting up when it is stopped. ([#4669](https://github.com/expo/eas-cli/pull/4669) by [@gwdp](https://github.com/gwdp))
### 🧹 Chores
- [build-tools] Extract the worker API client core from the device run session worker API client. ([#4806](https://github.com/expo/eas-cli/pull/4806) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
## [27.4.1](https://github.com/expo/eas-cli/releases/tag/v27.4.1) - 2026-11-04
### 🐛 Bug fixes
+2 -2
View File
@@ -1,4 +1,4 @@
{
"STAGING": "27.4.1",
"PRODUCTION": "27.4.1"
"STAGING": "27.11.0",
"PRODUCTION": "27.11.0"
}
+1 -1
View File
@@ -1,5 +1,5 @@
{
"npmClient": "yarn",
"version": "27.4.1",
"version": "27.11.0",
"$schema": "node_modules/lerna/schemas/lerna-schema.json"
}
+1 -1
View File
@@ -6,4 +6,4 @@ MISE_NODE_COREPACK = "true"
actionlint = "1.7.12"
gcloud = "570.0.0"
jq = "1.8.1"
node = "22.23.4"
node = "22.23.5"
+86
View File
@@ -1,5 +1,91 @@
# @expo/build-tools
## 27.11.0
### Minor Changes
- Report the identifier of the installed app as `applicationIdentifier` in the agent-device remote config, so clients can attach to the app of an `application_archive_url` session. ([#4831](https://github.com/expo/eas-cli/pull/4831) by [@expo-tuft](https://github.com/apps/expo-tuft))
- Count Android web preview input as session activity, so `max_idle_time_minutes` works on Android sessions. `eas/start_serve_sim_remote_session` no longer rejects it on Android; the API does not accept an idle timeout for Android web-preview-only sessions yet. ([#4890](https://github.com/expo/eas-cli/pull/4890) by [@szdziedzic](https://github.com/szdziedzic))
- Add start and collect steps that attach serve-sim simulator crash reports to device run sessions as IPS files. ([#4596](https://github.com/expo/eas-cli/pull/4596) by [@gwdp](https://github.com/gwdp))
- Add start and collect steps that attach serve-sim network captures to device run sessions as HAR files. ([#4495](https://github.com/expo/eas-cli/pull/4495) by [@gwdp](https://github.com/gwdp))
### Patch Changes
- Default `fastlane gym` dSYM compression level to 1. ([#4909](https://github.com/expo/eas-cli/pull/4909) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
- A successful remote device run session no longer fails when its agent-device, Appium, or Argent tunnel does not stop within its time-out. ([#4893](https://github.com/expo/eas-cli/pull/4893) by [@szdziedzic](https://github.com/szdziedzic))
## 27.10.0
### Minor Changes
- Add the experimental `experimental_emulator_capture_version` input to `eas/start_android_emulator`. The Android Emulator then preloads that version of the `expo-emulator-capture` agent and uses the lavapipe renderer, and later steps start expo-device-hub with the emulator capture on. When the agent cannot install, the emulator starts as before. Only web preview sessions support the capture for now, so other session types fail with an error when the input is set. ([#4827](https://github.com/expo/eas-cli/pull/4827) by [@krystofwoldrich-agent](https://github.com/krystofwoldrich-agent))
### Patch Changes
- Retry the first ngrok tunnel open of a device run session up to two times when ngrok rejects it with ERR_NGROK_802. The first open now waits 19 seconds instead of 15, so a tunnel that opens late is kept instead of closed. Startup can be cancelled during the retries, and a preview tunnel stops retrying when its session host finishes. ([#4874](https://github.com/expo/eas-cli/pull/4874) by [@szdziedzic](https://github.com/szdziedzic))
- Run worker SSH sessions as detached upterm sessions that reconnect on their own under the same session ID, and stop them with `upterm session stop`. ([#4857](https://github.com/expo/eas-cli/pull/4857) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
- Run the command a client passes with `eas workflow:ssh <id> <command>` in worker SSH sessions, in the build directory. ([#4863](https://github.com/expo/eas-cli/pull/4863) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
- Always download upterm for worker SSH sessions instead of using an `upterm` found on `PATH`. ([#4859](https://github.com/expo/eas-cli/pull/4859) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
## 27.9.0
No changes in this release.
## 27.8.0
### Patch Changes
- Point expo-device-hub at the scrcpy server copy in the `turtle-v2` bucket in Android device sessions, so a failed GitHub release download no longer fails the session. expo-device-hub falls back to GitHub when the copy is missing. ([#4848](https://github.com/expo/eas-cli/pull/4848) by [@sjkim-expo](https://github.com/sjkim-expo))
- Fix black iOS session preview artifacts on multi-display Simulators by capturing the active display through serve-sim. ([#4777](https://github.com/expo/eas-cli/pull/4777) by [@gwdp](https://github.com/gwdp))
Skip automatic previews on older serve-sim versions that cannot exclude them from idle activity.
- Report flow tags with the Maestro test results of jobs that run `maestro-runner`. The tags are read from the runner's `report.json`. ([#4853](https://github.com/expo/eas-cli/pull/4853) by [@hSATAC](https://github.com/hSATAC))
- Send the session preview size to `preview-upload-session` and refresh it when the size changes. ([#4864](https://github.com/expo/eas-cli/pull/4864) by [@hirbod](https://github.com/hirbod))
- Send the width, height and source of simulator session screenshots (manual, agent-device and Argent, including Argent screenshot diffs) as artifact metadata, read from the image header. ([#4858](https://github.com/expo/eas-cli/pull/4858) by [@hirbod](https://github.com/hirbod))
- Fix sizes of 102.4 GB and larger being printed with a value about a million times too large, and share one `formatBytes` helper between `eas-cli` and `build-tools`. ([#4854](https://github.com/expo/eas-cli/pull/4854) by [@vonovak](https://github.com/vonovak))
## 27.7.2
### Patch Changes
- Start SSH session shells in the job's build directory instead of the worker's directory. ([#4843](https://github.com/expo/eas-cli/pull/4843) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
## 27.7.1
### Patch Changes
- Update `node-forge`, `tar`, `nanoid`, `minimatch`, `joi`, `ajv`, `yaml`, and `zod` to versions with fixes for published security advisories. ([#4847](https://github.com/expo/eas-cli/pull/4847) by [@tchayen](https://github.com/tchayen))
- Strip the GitHub repository access token from the git remote before a sandbox agent starts. ([#4826](https://github.com/expo/eas-cli/pull/4826) by [@sswrk](https://github.com/sswrk))
## 27.7.0
### Patch Changes
- Record Android emulator output and, when selected, device logcat during simulator sessions, and upload the last 20 MiB of each as a session artifact. ([#4822](https://github.com/expo/eas-cli/pull/4822) by [@vonovak](https://github.com/vonovak))
## 27.6.0
### Minor Changes
- Reuse compatible prefetched Appium and XCUITest files without removing them during cleanup. Resolve explicit package versions, including `latest`, and reuse prepared tools only when they match. Use the launcher's runtime serve-sim version for warm adoption and recordings, including prereleases. ([#4837](https://github.com/expo/eas-cli/pull/4837) by [@gwdp](https://github.com/gwdp))
### Patch Changes
- Stop waiting for `com.apple.datamigrator` to exit before an iOS Simulator on iOS 27.2 or later counts as ready; there it stays resident, so the wait never finished. Earlier runtimes keep the wait. Take the readiness screenshot from the first integrated screen when the device lists several, so the iPhone Duo on iOS 27.2 passes the check. ([#4816](https://github.com/expo/eas-cli/pull/4816) by [@hSATAC](https://github.com/hSATAC))
- Require the sandbox worker token for sandbox jobs and remove the sandbox GraphQL fallback. ([#4808](https://github.com/expo/eas-cli/pull/4808) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
## 27.5.0
### Patch Changes
- Stop an agent-device session that is still starting up when it is stopped. ([#4666](https://github.com/expo/eas-cli/pull/4666) by [@gwdp](https://github.com/gwdp))
- Stop an Appium session that is still starting up when it is stopped. ([#4668](https://github.com/expo/eas-cli/pull/4668) by [@gwdp](https://github.com/gwdp))
Report temporary-directory cleanup failures when Stop interrupts Appium installation.
- Stop an Argent session that is still starting up when it is stopped. ([#4667](https://github.com/expo/eas-cli/pull/4667) by [@gwdp](https://github.com/gwdp))
- Use the sandbox worker token for sandbox jobs when www provides one, and keep Expo credentials out of the commands of those jobs. ([#4807](https://github.com/expo/eas-cli/pull/4807) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
- Stop a web-preview session that is still starting up when it is stopped. ([#4669](https://github.com/expo/eas-cli/pull/4669) by [@gwdp](https://github.com/gwdp))
## 27.4.1
### Patch Changes
+14 -13
View File
@@ -1,6 +1,6 @@
{
"name": "@expo/build-tools",
"version": "27.4.1",
"version": "27.11.0",
"bugs": "https://github.com/expo/eas-cli/issues",
"license": "BUSL-1.1",
"author": "Expo <[email protected]>",
@@ -26,7 +26,7 @@
"build:egress-guard": "resources/egress-guard/build.sh",
"test:egress-guard": "resources/egress-guard/tests/run-policy-tests.sh && resources/egress-guard/tests/run-guard-tests.sh",
"typecheck": "tsc",
"generate-appium-commands": "mise exec [email protected].4 -- node scripts/generate-appium-commands.js",
"generate-appium-commands": "mise exec [email protected].5 -- node scripts/generate-appium-commands.js",
"prepack": "rimraf dist \"*.tsbuildinfo\" && yarn gql && tsc -p tsconfig.build.json",
"jest-unit": "jest --config jest/unit-config.ts",
"jest-integration": "jest --config jest/integration-config.ts",
@@ -42,17 +42,17 @@
"dependencies": {
"@expo/config": "55.0.10",
"@expo/config-plugins": "55.0.7",
"@expo/downloader": "27.4.1",
"@expo/eas-build-job": "27.4.1",
"@expo/downloader": "27.11.0",
"@expo/eas-build-job": "27.11.0",
"@expo/env": "^0.4.0",
"@expo/logger": "27.4.1",
"@expo/logger": "27.11.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": "27.4.1",
"@expo/template-file": "27.4.1",
"@expo/turtle-spawn": "27.4.1",
"@expo/steps": "27.11.0",
"@expo/template-file": "27.11.0",
"@expo/turtle-spawn": "27.11.0",
"@expo/xcpretty": "^4.4.7",
"@ngrok/ngrok": "1.7.0",
"@sentry/node": "7.77.0",
@@ -63,11 +63,11 @@
"fast-xml-parser": "^4.4.1",
"fs-extra": "^11.2.0",
"gql.tada": "^1.11.3",
"joi": "^17.13.1",
"joi": "^17.13.9",
"jose": "5.10.0",
"lodash": "^4.18.1",
"node-fetch": "^2.7.0",
"node-forge": "^1.3.1",
"node-forge": "^1.4.3",
"node-pty": "1.2.0-beta.15",
"node-stream-zip": "1.15.0",
"nullthrows": "^1.1.1",
@@ -77,11 +77,12 @@
"resolve-from": "^5.0.0",
"retry": "^0.13.1",
"semver": "^7.6.2",
"tar": "7.5.19",
"tar": "7.5.22",
"uuid": "9.0.1",
"ws": "8.21.1",
"yaml": "^2.8.1",
"zod": "^4.3.5"
"xcode": "^3.0.1",
"yaml": "^2.9.1",
"zod": "^4.6.7"
},
"devDependencies": {
"@expo/repack-app": "~0.9.0",
@@ -2,6 +2,7 @@ import {
BuildPhase,
BuildPhaseResult,
BuildTrigger,
EnvironmentSecretType,
Job,
Metadata,
Platform,
@@ -31,6 +32,34 @@ describe('BuildContext', () => {
(fs.readdir as unknown as jest.Mock).mockResolvedValue([]);
});
it('keeps the sandbox worker token out of the env and keeps the other secrets', () => {
const ctx = new BuildContext(
{
triggeredBy: BuildTrigger.GIT_BASED_INTEGRATION,
secrets: {
environmentSecrets: [
{
name: 'EAS_SANDBOX_WORKER_TOKEN',
value: 'sandbox-worker-token',
type: EnvironmentSecretType.STRING,
},
{ name: 'KEEP', value: 'value', type: EnvironmentSecretType.STRING },
],
},
} as Job,
{
env: { __API_SERVER_URL: 'https://api.expo.test' },
workingdir: '/workingdir',
logger: createMockLogger(),
logBuffer: { getLogs: () => [], getPhaseLogs: () => [] },
uploadArtifact: jest.fn(),
}
);
expect(ctx.env.EAS_SANDBOX_WORKER_TOKEN).toBeUndefined();
expect(ctx.env.KEEP).toBe('value');
});
it('should merge secrets', async () => {
const robotAccessToken = randomUUID();
await vol.promises.mkdir('/workingdir/eas-environment-secrets/', { recursive: true });
@@ -361,6 +361,67 @@ describe('Datadog singleton', () => {
expect(turtleFetchMock).not.toHaveBeenCalled();
});
it('POSTs distribution metrics to the sandbox worker API with the sandbox worker token', () => {
turtleFetchMock.mockResolvedValueOnce({} as Response);
Datadog.setup({
expoApiV2BaseUrl: 'https://api.expo.test/v2/',
sandboxWorkerToken: 'sandbox-token',
target: { kind: 'sandbox' },
});
Datadog.distribution('eas.workflow.hook', 1, { hook: 'on_start' });
expect(turtleFetchMock).toHaveBeenCalledWith(
'https://api.expo.test/v2/sandbox-worker/metrics',
'POST',
{
json: {
metrics: [
{
name: 'eas.workflow.hook',
type: 'distribution',
value: 1,
tags: { hook: 'on_start', target: 'job_run' },
},
],
},
headers: { 'expo-sandbox-worker-token': 'sandbox-token' },
retries: 2,
}
);
});
it('labels metric upload failures for sandbox targets with the sandbox kind', async () => {
turtleFetchMock.mockRejectedValueOnce(new Error('network down'));
Datadog.setup({
expoApiV2BaseUrl: 'https://api.expo.test/v2/',
sandboxWorkerToken: 'sandbox-token',
target: { kind: 'sandbox' },
});
Datadog.distribution('eas.workflow.hook', 1);
await flushPromises();
expect(sentryCaptureMock).toHaveBeenCalledWith(
'Failed to report turtle sandbox metric',
expect.any(Error),
expect.anything()
);
});
it('does not report logs for sandbox targets', () => {
Datadog.setup({
expoApiV2BaseUrl: 'https://api.expo.test/v2/',
sandboxWorkerToken: 'sandbox-token',
target: { kind: 'sandbox' },
});
Datadog.log('Custom build saw user-provided function');
expect(turtleFetchMock).not.toHaveBeenCalled();
});
it('flushes pending metric uploads', async () => {
let resolveUpload!: (response: Response) => void;
turtleFetchMock.mockReturnValueOnce(
@@ -1,3 +1,4 @@
import { Job, Metadata } from '@expo/eas-build-job';
import { bunyan } from '@expo/logger';
import {
BuildRuntimePlatform,
@@ -75,6 +76,20 @@ export function createStepContextMock({
});
}
export function createTestBuildContext<TJob extends Job>(
job: TJob,
metadata?: Metadata
): BuildContext<TJob> {
return new BuildContext(job, {
env: { __API_SERVER_URL: 'http://api.expo.test' },
logBuffer: { getLogs: () => [], getPhaseLogs: () => [] },
logger: createMockLogger(),
uploadArtifact: jest.fn(),
workingdir: '/workingdir',
metadata,
});
}
export function createCustomBuildContextMock(): CustomBuildContext {
const ctx = new BuildContext(createTestIosJob({}), {
env: {
@@ -4,6 +4,7 @@ import {
BuildMode,
BuildTrigger,
Ios,
NativeBuilder,
Platform,
Workflow,
} from '@expo/eas-build-job';
@@ -92,3 +93,31 @@ export function createTestIosJob({
workflowInterpolationContext,
};
}
export function createTestXcodeJob(overrides: Record<string, unknown> = {}): Ios.Job {
return {
mode: BuildMode.BUILD,
builder: NativeBuilder.XCODE,
platform: Platform.IOS,
triggeredBy: BuildTrigger.GIT_BASED_INTEGRATION,
type: Workflow.GENERIC,
projectArchive: {
type: ArchiveSourceType.GIT,
gitCommitHash: '0123456789abcdef0123456789abcdef01234567',
gitRef: 'refs/heads/main',
},
projectRootDirectory: '.',
simulator: false,
secrets: {
credentialsByBundleIdentifier: {
'dev.expo.nativeapp': {
provisioningProfileBase64: 'cHJvZmlsZQ==',
distributionCertificate: { dataBase64: 'Y2VydGlmaWNhdGU=', password: '' },
},
},
},
appId: randomUUID(),
initiatingUserId: randomUUID(),
...overrides,
} as Ios.Job;
}
@@ -91,7 +91,7 @@ describe(androidBuilder, () => {
);
});
it('passes the install_node_modules anchor and a hooks ref to setupAsync', async () => {
it('passes a hooks ref to setupAsync', async () => {
const ctx = new BuildContext(createTestAndroidJob(), {
workingdir: '/workingdir',
logBuffer: { getLogs: () => [], getPhaseLogs: () => [] },
@@ -105,7 +105,6 @@ describe(androidBuilder, () => {
expect(setupAsync).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
wrappedAnchors: ['install_node_modules'],
jobHooksRef: expect.objectContaining({ current: null }),
})
);
@@ -0,0 +1,70 @@
import { BuildMode, Ios, Metadata } from '@expo/eas-build-job';
import { vol } from 'memfs';
import { createTestBuildContext } from '../../__tests__/utils/context';
import { createTestIosJob, createTestXcodeJob } from '../../__tests__/utils/job';
import { prepareProjectSourcesAsync } from '../../common/projectSources';
import { runBuilderWithHooksAsync } from '../common';
import { runCustomBuildAsync } from '../custom';
import iosBuilder from '../ios';
jest.mock('../common', () => ({ runBuilderWithHooksAsync: jest.fn(async () => ({})) }));
jest.mock('../custom', () => ({ runCustomBuildAsync: jest.fn(async () => ({})) }));
jest.mock('../../common/projectSources');
jest.mock('../../ios/xcodeBuildLogs');
jest.mock('../../utils/prepareBuildExecutable', () => ({ prepareExecutableAsync: jest.fn() }));
const METADATA = { appIdentifier: 'dev.expo.nativeapp' } as Metadata;
afterEach(() => {
vol.reset();
});
describe(iosBuilder, () => {
it.each([
['an unknown builder', { builder: 'unknown' }, '"builder" must be [xcode]'],
['a builder and the custom mode', { mode: BuildMode.CUSTOM }, '"mode" must be [build]'],
['a builder and the resign mode', { mode: BuildMode.RESIGN }, '"mode" must be [build]'],
['a builder and the repack mode', { mode: BuildMode.REPACK }, '"mode" must be [build]'],
])(
'fails a job with %s in the validation of the Xcode runner',
async (_description, overrides, expectedMessage) => {
await expect(
iosBuilder(createTestBuildContext(createTestXcodeJob(overrides), METADATA))
).rejects.toMatchObject({
trackingCode: 'NATIVE_INVALID_JOB',
message: expect.stringContaining(expectedMessage),
});
expect(runCustomBuildAsync).not.toHaveBeenCalled();
expect(runBuilderWithHooksAsync).not.toHaveBeenCalled();
expect(prepareProjectSourcesAsync).not.toHaveBeenCalled();
}
);
it('runs a valid job with the Xcode builder through the Xcode steps', async () => {
jest.mocked(prepareProjectSourcesAsync).mockImplementation(async () => {
vol.mkdirSync('/workingdir/env', { recursive: true });
vol.fromJSON({ 'README.md': '' }, '/workingdir/temporary-custom-build');
return { handled: true };
});
const ctx = createTestBuildContext(
createTestXcodeJob({ simulator: true, secrets: {} }),
METADATA
);
await expect(iosBuilder(ctx)).rejects.toMatchObject({
errorCode: 'NATIVE_XCODE_PROJECT_FILE_NOT_FOUND',
});
expect(runBuilderWithHooksAsync).not.toHaveBeenCalled();
});
it('routes a job without a builder by its mode', async () => {
await iosBuilder(createTestBuildContext(createTestIosJob(), METADATA));
expect(runBuilderWithHooksAsync).toHaveBeenCalledTimes(1);
await iosBuilder(
createTestBuildContext({ ...createTestIosJob(), mode: BuildMode.CUSTOM }, METADATA)
);
expect(runCustomBuildAsync).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,177 @@
import { BuildMode, Ios, Metadata } from '@expo/eas-build-job';
import { BuildStepGlobalContext } from '@expo/steps';
import { vol } from 'memfs';
import { createTestBuildContext } from '../../__tests__/utils/context';
import { createTestXcodeJob } from '../../__tests__/utils/job';
import { prepareProjectSourcesAsync } from '../../common/projectSources';
import { CustomBuildContext } from '../../customBuildContext';
import { findAndUploadXcodeBuildLogsAsync } from '../../ios/xcodeBuildLogs';
import { createXcodeWorkflowAsync, runXcodeBuildAsync, validateXcodeJob } from '../xcode';
jest.mock('../../common/projectSources');
jest.mock('../../ios/xcodeBuildLogs');
const METADATA = { appIdentifier: 'dev.expo.nativeapp' } as Metadata;
async function createWorkflowAsync(
job: Ios.Job,
metadata?: Metadata
): ReturnType<typeof createXcodeWorkflowAsync> {
const customBuildCtx = new CustomBuildContext(createTestBuildContext(job, metadata));
return await createXcodeWorkflowAsync(
new BuildStepGlobalContext(customBuildCtx, false),
customBuildCtx
);
}
afterEach(() => {
vol.reset();
});
describe(validateXcodeJob, () => {
it('accepts a signed job with an app identifier, and keys the schema does not know', () => {
expect(() =>
validateXcodeJob(createTestXcodeJob({ keyFromANewerServer: true }), METADATA)
).not.toThrow();
});
it('accepts a simulator job without an app identifier', () => {
expect(() =>
validateXcodeJob(createTestXcodeJob({ simulator: true, secrets: {} }), undefined)
).not.toThrow();
});
it.each([
['an unknown builder', { builder: 'unknown' }, '"builder" must be [xcode]'],
['a mode other than build', { mode: BuildMode.CUSTOM }, '"mode" must be [build]'],
['a field native jobs do not read', { buildProfile: 'production' }, '"buildProfile"'],
['a value of another type', { simulator: 'false' }, '"simulator" must be a boolean'],
['no credentials for a device build', { secrets: {} }, 'credentialsByBundleIdentifier'],
])('rejects a job with %s', (_description, overrides, expectedMessage) => {
expect(() => validateXcodeJob(createTestXcodeJob(overrides), METADATA)).toThrow(
expect.objectContaining({
trackingCode: 'NATIVE_INVALID_JOB',
message: expect.stringContaining(expectedMessage),
})
);
});
it('rejects a signed job without an app identifier', () => {
expect(() => validateXcodeJob(createTestXcodeJob(), undefined)).toThrow(
expect.objectContaining({
trackingCode: 'NATIVE_INVALID_JOB',
message: expect.stringContaining('app identifier'),
})
);
});
});
describe(createXcodeWorkflowAsync, () => {
it('builds a valid workflow from the public and the private functions', async () => {
const workflow = await createWorkflowAsync(createTestXcodeJob(), METADATA);
expect(workflow.buildSteps.map(step => step.__metricsId)).toEqual([
'eas/checkout',
'eas/install_native_pods',
'eas/detect_native_xcode',
'eas/build_native_ios',
'eas/verify_native_ios',
'eas/update_resolved_version',
'eas/upload_artifact',
]);
});
it('passes the values known from the job and the metadata to detection and verification', async () => {
const workflow = await createWorkflowAsync(
createTestXcodeJob({
projectFile: 'App.xcworkspace',
scheme: 'App',
buildConfiguration: 'Staging',
}),
METADATA
);
const rawInputsByMetricsId = Object.fromEntries(
workflow.buildSteps.map(step => [
step.__metricsId,
Object.fromEntries((step.inputs ?? []).map(input => [input.id, input.rawValue])),
])
);
expect(rawInputsByMetricsId['eas/detect_native_xcode']).toEqual({
project_file: 'App.xcworkspace',
scheme: 'App',
build_configuration: 'Staging',
expected_identifier: 'dev.expo.nativeapp',
});
expect(rawInputsByMetricsId['eas/verify_native_ios']).toMatchObject({
expected_identifier: 'dev.expo.nativeapp',
});
});
it('runs the after_checkout hook of the job after the checkout step', async () => {
const workflow = await createWorkflowAsync(
createTestXcodeJob({ hooks: { after_checkout: [{ run: 'git submodule update --init' }] } }),
METADATA
);
const checkoutStep = workflow.buildSteps.find(step => step.__metricsId === 'eas/checkout')!;
expect(workflow.hooksByAnchorStep.get(checkoutStep)).toMatchObject({
anchor: 'checkout',
before: [],
after: [expect.anything()],
});
});
});
describe(runXcodeBuildAsync, () => {
it('validates the job before it prepares the project', async () => {
const ctx = createTestBuildContext(createTestXcodeJob({ builder: 'unknown' }), METADATA);
await expect(runXcodeBuildAsync(ctx)).rejects.toMatchObject({
trackingCode: 'NATIVE_INVALID_JOB',
});
expect(prepareProjectSourcesAsync).not.toHaveBeenCalled();
});
it('logs each reason when the hooks of the job make the workflow invalid', async () => {
vol.mkdirSync('/workingdir/env', { recursive: true });
const ctx = createTestBuildContext(
createTestXcodeJob({
simulator: true,
secrets: {},
hooks: {
after_checkout: [
{ id: 'same', run: 'echo first' },
{ id: 'same', run: 'echo second' },
],
},
}),
undefined
);
await expect(runXcodeBuildAsync(ctx)).rejects.toThrow('Build workflow is invalid.');
expect(ctx.logger.error).toHaveBeenCalledWith({
err: expect.objectContaining({ message: 'Duplicated step IDs: "same"' }),
});
});
it('runs the steps, uploads the Xcode logs once and attaches the artifacts to a failure', async () => {
jest.mocked(prepareProjectSourcesAsync).mockImplementation(async () => {
vol.mkdirSync('/workingdir/env', { recursive: true });
vol.fromJSON({ 'README.md': '' }, '/workingdir/temporary-custom-build');
return { handled: true };
});
const ctx = createTestBuildContext(
createTestXcodeJob({ simulator: true, secrets: {} }),
undefined
);
await expect(runXcodeBuildAsync(ctx)).rejects.toMatchObject({
errorCode: 'NATIVE_XCODE_PROJECT_FILE_NOT_FOUND',
artifacts: ctx.artifacts,
});
expect(vol.existsSync('/workingdir/build/README.md')).toBe(true);
expect(findAndUploadXcodeBuildLogsAsync).toHaveBeenCalledTimes(1);
});
});
+1 -1
View File
@@ -72,7 +72,7 @@ async function buildInnerAsync(
ctx: BuildContext<Android.Job>,
jobHooksRef: JobHooksRef
): Promise<void> {
await setupAsync(ctx, { wrappedAnchors: ['install_node_modules'], jobHooksRef });
await setupAsync(ctx, { jobHooksRef });
const evictUsedBefore = new Date();
const workingDirectory = ctx.getReactNativeProjectDirectory();
const hasNativeCode = ctx.job.type === Workflow.GENERIC;
+2 -19
View File
@@ -9,39 +9,22 @@ import {
errors,
} from '@expo/steps';
import assert from 'assert';
import fs from 'fs/promises';
import nullthrows from 'nullthrows';
import path from 'path';
import { prepareProjectForStepsAsync } from './prepareProjectForSteps';
import { resolveEnvFromBuildProfileAsync } from '../common/easBuildInternal';
import { prepareProjectSourcesAsync } from '../common/projectSources';
import { Artifacts, BuildContext } from '../context';
import { CustomBuildContext } from '../customBuildContext';
import { Datadog } from '../datadog';
import { findAndUploadXcodeBuildLogsAsync } from '../ios/xcodeBuildLogs';
import { getEasFunctionGroups } from '../steps/easFunctionGroups';
import { getEasFunctions } from '../steps/easFunctions';
import { retryAsync } from '../utils/retry';
export async function runCustomBuildAsync(ctx: BuildContext<BuildJob>): Promise<Artifacts> {
const customBuildCtx = new CustomBuildContext(ctx);
await ctx.runBuildPhase(BuildPhase.PREPARE_PROJECT, async () => {
await retryAsync(
async () => {
await fs.rm(customBuildCtx.projectSourceDirectory, { recursive: true, force: true });
await fs.mkdir(customBuildCtx.projectSourceDirectory, { recursive: true });
await prepareProjectSourcesAsync(ctx, customBuildCtx.projectSourceDirectory);
},
{
retryOptions: {
retries: 3,
retryIntervalMs: 1_000,
},
}
);
});
await prepareProjectForStepsAsync(ctx, customBuildCtx.projectSourceDirectory);
if (ctx.job.triggeredBy === BuildTrigger.GIT_BASED_INTEGRATION) {
// We need to setup envs from eas.json
+5 -1
View File
@@ -6,6 +6,7 @@ import nullthrows from 'nullthrows';
import { runBuilderWithHooksAsync } from './common';
import { runCustomBuildAsync } from './custom';
import { runXcodeBuildAsync } from './xcode';
import { eagerBundleAsync, shouldUseEagerBundle } from '../common/eagerBundle';
import { prebuildAsync } from '../common/prebuild';
import { JobHooksRef, setupAsync } from '../common/setup';
@@ -48,6 +49,9 @@ const INSTALL_PODS_KILL_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
class InstallPodsTimeoutError extends Error {}
export default async function iosBuilder(ctx: BuildContext<Ios.Job>): Promise<Artifacts> {
if (ctx.job.builder !== undefined) {
return await runXcodeBuildAsync(ctx);
}
if (ctx.job.mode === BuildMode.BUILD) {
await prepareExecutableAsync(ctx);
return await runBuilderWithHooksAsync(ctx, buildAsync);
@@ -76,7 +80,7 @@ async function buildInnerAsync(
ctx: BuildContext<Ios.Job>,
jobHooksRef: JobHooksRef
): Promise<void> {
await setupAsync(ctx, { wrappedAnchors: ['install_node_modules'], jobHooksRef });
await setupAsync(ctx, { jobHooksRef });
const hasNativeCode = ctx.job.type === Workflow.GENERIC;
const evictUsedBefore = new Date();
const credentialsManager = new CredentialsManager(ctx);
@@ -0,0 +1,28 @@
import { BuildJob, BuildPhase } from '@expo/eas-build-job';
import fs from 'fs/promises';
import { prepareProjectSourcesAsync } from '../common/projectSources';
import { BuildContext } from '../context';
import { retryAsync } from '../utils/retry';
export async function prepareProjectForStepsAsync(
ctx: BuildContext<BuildJob>,
projectSourceDirectory: string
): Promise<void> {
await ctx.runBuildPhase(BuildPhase.PREPARE_PROJECT, async () => {
await retryAsync(
async () => {
await fs.rm(projectSourceDirectory, { recursive: true, force: true });
await fs.mkdir(projectSourceDirectory, { recursive: true });
await prepareProjectSourcesAsync(ctx, projectSourceDirectory);
},
{
retryOptions: {
retries: 3,
retryIntervalMs: 1_000,
},
}
);
});
}
+134
View File
@@ -0,0 +1,134 @@
import { Ios, Metadata, Step, SystemError } from '@expo/eas-build-job';
import {
BuildStepGlobalContext,
BuildWorkflow,
StepsConfigParser,
createLocalCompositeFunctionLoader,
errors,
} from '@expo/steps';
import path from 'node:path';
import { prepareProjectForStepsAsync } from './prepareProjectForSteps';
import { Artifacts, BuildContext } from '../context';
import { CustomBuildContext } from '../customBuildContext';
import { findAndUploadXcodeBuildLogsAsync } from '../ios/xcodeBuildLogs';
import { getEasFunctions } from '../steps/easFunctions';
import { createBuildNativeIosBuildFunction } from '../steps/functions/native/xcode/buildNativeIos';
import { createDetectNativeXcodeBuildFunction } from '../steps/functions/native/xcode/detectNativeXcode';
import { createInstallNativePodsBuildFunction } from '../steps/functions/native/xcode/installNativePods';
import { createVerifyNativeIosBuildFunction } from '../steps/functions/native/xcode/verifyNativeIos';
export async function runXcodeBuildAsync(ctx: BuildContext<Ios.Job>): Promise<Artifacts> {
validateXcodeJob(ctx.job, ctx.metadata);
const customBuildCtx = new CustomBuildContext(ctx);
await prepareProjectForStepsAsync(ctx, customBuildCtx.projectSourceDirectory);
const globalContext = new BuildStepGlobalContext(customBuildCtx, /* skipCleanup */ false);
let workflow: BuildWorkflow;
try {
workflow = await createXcodeWorkflowAsync(globalContext, customBuildCtx);
} catch (parseError) {
if (parseError instanceof errors.BuildWorkflowError) {
for (const err of parseError.errors) {
ctx.logger.error({ err });
}
}
throw parseError;
}
try {
await workflow.executeAsync();
} catch (err: any) {
err.artifacts = ctx.artifacts;
throw err;
} finally {
await findAndUploadXcodeBuildLogsAsync(ctx, { logger: ctx.logger });
await customBuildCtx.drainPendingMetricUploads();
}
return ctx.artifacts;
}
export function validateXcodeJob(job: Ios.Job, metadata: Metadata | undefined): void {
const { error } = Ios.JobSchema.validate(job, {
allowUnknown: true,
convert: false,
abortEarly: false,
});
if (error) {
throw new SystemError(
`EAS created an Xcode build job that is not valid: ${error.message}. Your project did not cause this. Run the build again, and contact Expo support if it keeps failing.`,
{ trackingCode: 'NATIVE_INVALID_JOB' }
);
}
if (!job.simulator && !metadata?.appIdentifier) {
throw new SystemError(
'EAS created an Xcode build job for devices without the app identifier that the signed app must have. Your project did not cause this. Run the build again, and contact Expo support if it keeps failing.',
{ trackingCode: 'NATIVE_INVALID_JOB' }
);
}
}
export async function createXcodeWorkflowAsync(
globalContext: BuildStepGlobalContext,
customBuildCtx: CustomBuildContext<Ios.Job>
): Promise<BuildWorkflow> {
const { job, metadata } = customBuildCtx;
const steps: Step[] = [
{ uses: 'eas/checkout' },
{ uses: 'eas/install_native_pods' },
{
id: 'detect_native_xcode',
uses: 'eas/detect_native_xcode',
with: {
project_file: job.projectFile,
scheme: job.scheme,
build_configuration: job.buildConfiguration,
expected_identifier: metadata?.appIdentifier,
},
},
{
id: 'build_native_ios',
uses: 'eas/build_native_ios',
with: {
project_file: '${{ steps.detect_native_xcode.outputs.project_file }}',
scheme: '${{ steps.detect_native_xcode.outputs.scheme }}',
build_configuration: '${{ steps.detect_native_xcode.outputs.build_configuration }}',
xcodeproj_path: '${{ steps.detect_native_xcode.outputs.xcodeproj_path }}',
targets: '${{ steps.detect_native_xcode.outputs.targets }}',
},
},
{
uses: 'eas/verify_native_ios',
with: {
archive_path: '${{ steps.build_native_ios.outputs.archive_path }}',
expected_identifier: metadata?.appIdentifier,
},
},
{
uses: 'eas/update_resolved_version',
with: { application_archive_path: '${{ steps.build_native_ios.outputs.archive_path }}' },
},
{
uses: 'eas/upload_artifact',
with: {
type: 'application-archive',
path: '${{ steps.build_native_ios.outputs.archive_path }}',
},
},
];
return await new StepsConfigParser(globalContext, {
steps,
hooks: job.hooks,
externalFunctions: [
...getEasFunctions(customBuildCtx),
createInstallNativePodsBuildFunction(),
createDetectNativeXcodeBuildFunction(),
createBuildNativeIosBuildFunction(),
createVerifyNativeIosBuildFunction(),
],
loadCompositeFunction: createLocalCompositeFunctionLoader(
path.join(customBuildCtx.projectSourceDirectory, job.projectRootDirectory ?? '.'),
{ logger: customBuildCtx.logger }
),
}).parseAsync();
}
@@ -1,8 +1,8 @@
import { UserError } from '@expo/eas-build-job';
import { SystemError, UserError } from '@expo/eas-build-job';
import spawn from '@expo/turtle-spawn';
import { vol } from 'memfs';
import { fetchAndCheckoutRefAsync } from '../git';
import { fetchAndCheckoutRefAsync, stripRepositoryCredentialsAsync } from '../git';
jest.mock('@expo/turtle-spawn');
@@ -147,3 +147,64 @@ describe(fetchAndCheckoutRefAsync, () => {
expect(error.message).not.toContain('ghs_secret123');
});
});
describe(stripRepositoryCredentialsAsync, () => {
const token = 'ghs_secret123';
function mockRemoteUrl(url: string): void {
jest.mocked(spawn).mockResolvedValueOnce({ stdout: `${url}\n` } as never);
}
it('strips the token from the origin remote', async () => {
mockRemoteUrl(`https://x-access-token:${token}@github.com/expo/app.git`);
await stripRepositoryCredentialsAsync({ repositoryDirectory });
expect(spawn).toHaveBeenNthCalledWith(1, 'git', ['remote', 'get-url', 'origin'], {
cwd: repositoryDirectory,
});
expect(spawn).toHaveBeenNthCalledWith(
2,
'git',
['remote', 'set-url', 'origin', 'https://github.com/expo/app.git'],
{ cwd: repositoryDirectory }
);
expect(spawn).toHaveBeenCalledTimes(2);
});
it('keeps the host and port of a GitHub Enterprise remote', async () => {
mockRemoteUrl(`https://x-access-token:${token}@ghe.example.com:8443/org/app.git`);
await stripRepositoryCredentialsAsync({ repositoryDirectory });
expect(spawn).toHaveBeenNthCalledWith(
2,
'git',
['remote', 'set-url', 'origin', 'https://ghe.example.com:8443/org/app.git'],
{ cwd: repositoryDirectory }
);
});
it('does nothing when the origin remote carries no credentials', async () => {
mockRemoteUrl('https://github.com/expo/app.git');
await stripRepositoryCredentialsAsync({ repositoryDirectory });
expect(spawn).toHaveBeenCalledTimes(1);
});
it('throws when the remote URL cannot be rewritten', async () => {
mockRemoteUrl(`https://x-access-token:${token}@github.com/expo/app.git`);
const gitError = Object.assign(new Error('git exited with non-zero code: 128'), {
stderr: "fatal: No such remote 'origin'",
});
jest.mocked(spawn).mockRejectedValueOnce(gitError);
const promise = stripRepositoryCredentialsAsync({ repositoryDirectory });
await expect(promise).rejects.toBeInstanceOf(SystemError);
await expect(promise).rejects.toMatchObject({ cause: gitError });
const error = await promise.catch(err => err);
expect(error.message).not.toContain(token);
});
});
@@ -1,10 +1,10 @@
import { BuildPhase, BuildTrigger, Hooks, Ios } from '@expo/eas-build-job';
import { BuildPhase, BuildTrigger, HookKey, Hooks, Ios } from '@expo/eas-build-job';
import { bunyan } from '@expo/logger';
import { executeHookStepsAsync } from '@expo/steps';
import { createTestIosJob } from '../../__tests__/utils/job';
import { BuildContext } from '../../context';
import { runHookableBuildPhaseAsync } from '../hookableBuildPhase';
import { runHookEntriesAsync, runHookableBuildPhaseAsync } from '../hookableBuildPhase';
import { ParsedJobHooks, parseJobHooksAsync } from '../jobHooks';
// The primitive's step-execution rules (failure()/success(), no-if continuation,
@@ -16,7 +16,10 @@ jest.mock('@expo/steps', () => ({
}));
const executeHookStepsMock = jest.mocked(executeHookStepsAsync);
async function setup(hooks: Hooks | undefined): Promise<{
async function setup(
hooks: Hooks | undefined,
hookKeys: readonly HookKey[] = ['before_install_node_modules', 'after_install_node_modules']
): Promise<{
ctx: BuildContext<Ios.Job>;
hooks: ParsedJobHooks | null;
}> {
@@ -40,7 +43,7 @@ async function setup(hooks: Hooks | undefined): Promise<{
jest
.spyOn(ctx, 'runBuildPhase')
.mockImplementation((_phase: BuildPhase, fn: () => Promise<unknown>) => fn() as never);
return { ctx, hooks: await parseJobHooksAsync(ctx, ['install_node_modules']) };
return { ctx, hooks: await parseJobHooksAsync(ctx, hookKeys) };
}
const runArgs = <TJob extends Ios.Job>(
@@ -162,3 +165,23 @@ describe(runHookableBuildPhaseAsync, () => {
expect(writeBack).toHaveBeenCalled();
});
});
describe(runHookEntriesAsync, () => {
beforeEach(() => {
executeHookStepsMock.mockReset();
executeHookStepsMock.mockResolvedValue({ failedLocally: false, firstError: undefined });
});
it('runs the after_checkout entries that the parser built', async () => {
const { ctx, hooks } = await setup({ after_checkout: [{ run: 'echo after' }] }, [
'after_checkout',
]);
await runHookEntriesAsync({ ctx, hooks: hooks!, timing: 'after', anchor: 'checkout' });
expect(hooks!.hookEntriesByKey.after_checkout).toHaveLength(1);
expect(executeHookStepsMock).toHaveBeenCalledWith(
hooks!.globalContext,
hooks!.hookEntriesByKey.after_checkout,
{ anchor: 'checkout', timing: 'after', anchorResult: 'success' }
);
});
});
@@ -9,7 +9,7 @@ import { createTestIosJob } from '../../__tests__/utils/job';
import { BuildContext } from '../../context';
import { parseJobHooksAsync } from '../jobHooks';
const INSTALL: ['install_node_modules'] = ['install_node_modules'];
const INSTALL = ['before_install_node_modules', 'after_install_node_modules'] as const;
function createCtx(
hooks: Hooks | undefined,
@@ -2,6 +2,7 @@ import {
ArchiveSourceType,
BuildMode,
BuildTrigger,
EnvironmentSecretType,
ErrorCode,
Job,
Platform,
@@ -116,6 +117,73 @@ describe('projectSources', () => {
);
});
it('fetches a sandbox project source from the sandbox worker router with only the worker token', async () => {
const gitCommitHash = randomBytes(20).toString('hex');
const ctx = new BuildContext(
{
triggeredBy: BuildTrigger.GIT_BASED_INTEGRATION,
projectArchive: {
type: ArchiveSourceType.GIT,
gitRef: 'refs/heads/main',
gitCommitHash,
},
secrets: {
robotAccessToken: 'sandbox-worker-token',
environmentSecrets: [
{
name: 'EAS_SANDBOX_WORKER_TOKEN',
type: EnvironmentSecretType.STRING,
value: 'sandbox-worker-token',
},
],
},
} as unknown as Job,
{
env: {
__API_SERVER_URL: 'https://api.expo.dev',
EAS_BUILD_ID: randomUUID(),
EAS_BUILD_RUNNER: 'eas-build',
},
workingdir: '/workingdir',
logger: createMockLogger(),
logBuffer: { getLogs: () => [], getPhaseLogs: () => [] },
uploadArtifact: jest.fn(),
}
);
const fetchMock = jest.mocked(fetch);
fetchMock.mockImplementation(
async () =>
({
ok: true,
json: async () => ({
data: {
gitRef: 'refs/heads/main',
gitCommitHash,
repositoryUrl: 'https://x-access-token:[email protected]/expo/eas-cli.git',
type: ArchiveSourceType.GIT,
},
}),
}) as Response
);
await prepareProjectSourcesAsync(ctx, ctx.buildDirectory);
expect(fetchMock).toHaveBeenCalledWith(
'https://api.expo.dev/v2/sandbox-worker/project-archive',
expect.objectContaining({
method: 'POST',
headers: { 'expo-sandbox-worker-token': 'sandbox-worker-token' },
})
);
expect(shallowCloneRepositoryAsync).toHaveBeenCalledWith(
expect.objectContaining({
archiveSource: expect.objectContaining({
repositoryUrl: 'https://x-access-token:[email protected]/expo/eas-cli.git',
}),
})
);
});
it.each(['http', 'network', 'json', 'schema', 'missing-url', 'PATH', 'GCS', 'R2'])(
'throws a system error if refresh fails (%s)',
async failure => {
@@ -4,7 +4,7 @@ import { createTestAndroidJob } from '../../__tests__/utils/job';
import { createMockLogger } from '../../__tests__/utils/logger';
import { BuildContext } from '../../context';
import { resolveEnvFromBuildProfileAsync, runEasBuildInternalAsync } from '../easBuildInternal';
import { runHookableBuildPhaseAsync } from '../hookableBuildPhase';
import { runHookEntriesAsync, runHookableBuildPhaseAsync } from '../hookableBuildPhase';
import { JobHooksRef, setupAsync } from '../setup';
import { ParsedJobHooks, parseJobHooksAsync } from '../jobHooks';
import { prepareProjectSourcesAsync } from '../projectSources';
@@ -15,7 +15,10 @@ jest.mock('../easBuildInternal', () => ({
resolveEnvFromBuildProfileAsync: jest.fn(),
runEasBuildInternalAsync: jest.fn(),
}));
jest.mock('../hookableBuildPhase', () => ({ runHookableBuildPhaseAsync: jest.fn() }));
jest.mock('../hookableBuildPhase', () => ({
runHookEntriesAsync: jest.fn(),
runHookableBuildPhaseAsync: jest.fn(),
}));
jest.mock('../jobHooks', () => ({ parseJobHooksAsync: jest.fn() }));
jest.mock('../../utils/npmrc', () => ({ setUpNpmrcAsync: jest.fn() }));
jest.mock('../../utils/hooks', () => ({
@@ -79,6 +82,9 @@ describe(setupAsync, () => {
order.push('parse-hooks');
return PARSED;
});
jest.mocked(runHookEntriesAsync).mockImplementation(async () => {
order.push('after-checkout-hooks');
});
jest.mocked(runHookableBuildPhaseAsync).mockImplementation(async () => {
// Record the wrapper call; deliberately do NOT run its `fn` so the install
// internals stay out of the ordering test.
@@ -91,23 +97,50 @@ describe(setupAsync, () => {
}));
});
it('parses hooks after project prep + profile-env + pre-install hook, and before the install wrapper', async () => {
it('parses hooks after project prep + profile-env + pre-install hook, then runs the after_checkout hooks before the install wrapper', async () => {
const jobHooksRef: JobHooksRef = { current: null };
await setupAsync(createCtx(BuildTrigger.GIT_BASED_INTEGRATION), {
wrappedAnchors: ['install_node_modules'],
jobHooksRef,
});
const parseAt = order.indexOf('parse-hooks');
expect(order.indexOf('prepare-project')).toBeLessThan(parseAt);
expect(order.indexOf('profile-env')).toBeLessThan(parseAt);
expect(order.indexOf('pre-install-hook')).toBeLessThan(parseAt);
expect(parseAt).toBeLessThan(order.indexOf('install-wrapper'));
expect(order).toEqual([
'prepare-project',
'profile-env',
'pre-install-hook',
'parse-hooks',
'after-checkout-hooks',
'install-wrapper',
]);
expect(parseJobHooksAsync).toHaveBeenCalledWith(expect.anything(), [
'after_checkout',
'before_install_node_modules',
'after_install_node_modules',
]);
expect(runHookEntriesAsync).toHaveBeenCalledWith(
expect.objectContaining({ hooks: PARSED, timing: 'after', anchor: 'checkout' })
);
});
it('publishes the parsed hooks to the ref before an after_checkout hook can fail', async () => {
jest.mocked(runHookEntriesAsync).mockRejectedValueOnce(new Error('hook boom'));
const jobHooksRef: JobHooksRef = { current: null };
await expect(
setupAsync(createCtx(BuildTrigger.GIT_BASED_INTEGRATION), { jobHooksRef })
).rejects.toThrow('hook boom');
expect(jobHooksRef.current).toBe(PARSED);
expect(runHookableBuildPhaseAsync).not.toHaveBeenCalled();
});
it('runs no after_checkout hooks when the job has no hooks', async () => {
jest.mocked(parseJobHooksAsync).mockResolvedValueOnce(null);
await setupAsync(createCtx(BuildTrigger.GIT_BASED_INTEGRATION), {
jobHooksRef: { current: null },
});
expect(runHookEntriesAsync).not.toHaveBeenCalled();
});
it('parses hooks unconditionally on a non-git-based build (never parked in the git-only branch)', async () => {
const jobHooksRef: JobHooksRef = { current: null };
await setupAsync(createCtx(BuildTrigger.EAS_CLI), {
wrappedAnchors: ['install_node_modules'],
jobHooksRef,
});
expect(parseJobHooksAsync).toHaveBeenCalledTimes(1);
@@ -119,7 +152,6 @@ describe(setupAsync, () => {
it('publishes the parsed hooks to the ref before the install wrapper runs', async () => {
const jobHooksRef: JobHooksRef = { current: null };
await setupAsync(createCtx(BuildTrigger.GIT_BASED_INTEGRATION), {
wrappedAnchors: ['install_node_modules'],
jobHooksRef,
});
expect(jobHooksRef.current).toBe(PARSED);
@@ -5,3 +5,7 @@ export const COMMON_FASTLANE_ENV = {
FASTLANE_HIDE_TIMESTAMP: 'true',
LC_ALL: 'en_US.UTF-8',
};
export const DEFAULT_FASTLANE_GYM_ENV = {
ZIPOPT: '-1',
};
+40 -1
View File
@@ -1,4 +1,4 @@
import { ArchiveSource, ArchiveSourceType, UserError } from '@expo/eas-build-job';
import { ArchiveSource, ArchiveSourceType, SystemError, UserError } from '@expo/eas-build-job';
import { bunyan } from '@expo/logger';
import spawn from '@expo/turtle-spawn';
import fs from 'fs-extra';
@@ -99,6 +99,45 @@ export async function fetchAndCheckoutRefAsync({
}
}
export async function stripRepositoryCredentialsAsync({
repositoryDirectory,
}: {
repositoryDirectory: string;
}): Promise<void> {
let remoteUrl: URL;
try {
const { stdout } = await spawn('git', ['remote', 'get-url', 'origin'], {
cwd: repositoryDirectory,
});
remoteUrl = new URL(stdout.trim());
} catch (err) {
throw new SystemError('Failed to read the origin remote URL of the project repository.', {
cause: err,
});
}
if (!remoteUrl.username && !remoteUrl.password) {
return;
}
try {
await spawn('git', ['remote', 'set-url', 'origin', stripCredentialsFromGitUrl(remoteUrl)], {
cwd: repositoryDirectory,
});
} catch (err) {
throw new SystemError('Failed to strip credentials from the origin remote URL.', {
cause: err,
});
}
}
function stripCredentialsFromGitUrl(url: URL): string {
const strippedUrl = new URL(url.toString());
strippedUrl.username = '';
strippedUrl.password = '';
return strippedUrl.toString();
}
function getSanitizedGitUrl(maybeGitUrl: string): string | null {
try {
const url = new URL(maybeGitUrl);
@@ -57,7 +57,7 @@ export async function runHookableBuildPhaseAsync<TJob extends BuildJob, T>({
return result;
}
async function runHookEntriesAsync<TJob extends BuildJob>({
export async function runHookEntriesAsync<TJob extends BuildJob>({
ctx,
hooks,
timing,
+32 -36
View File
@@ -2,7 +2,6 @@ import {
BuildJob,
CompositeFunctionCatalog,
ErrorCode,
HookAnchorId,
HookKey,
UserError,
parseHookKey,
@@ -37,12 +36,12 @@ export interface ParsedJobHooks {
/**
* Parses the native job's `hooks` into engine-ready entries, once, at setup
* time. Shape-validates every registered key (reachable or not); constructs
* entries only for the anchors this build actually wraps. Returns null when the
* entries only for the hook keys this build runs. Returns null when the
* job declares no hooks.
*/
export async function parseJobHooksAsync<TJob extends BuildJob>(
ctx: BuildContext<TJob>,
wrappedAnchors: readonly HookAnchorId[]
hookKeys: readonly HookKey[]
): Promise<ParsedJobHooks | null> {
const hooks = ctx.job.hooks;
if (!hooks || Object.keys(hooks).length === 0) {
@@ -81,8 +80,8 @@ export async function parseJobHooksAsync<TJob extends BuildJob>(
}
}
// Construct entries for the wrapped anchors in EXECUTION order (per anchor,
// before_ then after_) so generated step ids and output references follow the
// Construct entries for the given hook keys in the order given, which is
// EXECUTION order, so generated step ids and output references follow the
// order steps actually run. All entries share one globalContext, so env and
// outputs accumulate across keys.
const hookEntriesByKey: Partial<Record<HookKey, HookEntry[]>> = {};
@@ -92,37 +91,34 @@ export async function parseJobHooksAsync<TJob extends BuildJob>(
ctx.getReactNativeProjectDirectory(),
{ logger: ctx.logger }
);
for (const anchor of wrappedAnchors) {
for (const side of ['before', 'after'] as const) {
const key: HookKey = `${side}_${anchor}`;
const steps = hooks[key];
if (!Array.isArray(steps) || steps.length === 0) {
continue;
}
let entries: HookEntry[];
try {
// Extended per key so a bad `uses:` path is attributed to that hook key.
await extendCompositeFunctionCatalogFromStepsAsync({
catalog: compositeFunctionCatalog,
rootSteps: steps,
loadCompositeFunction,
});
entries = await constructHookEntriesAsync(globalContext, steps, {
externalFunctions,
externalFunctionGroups,
compositeFunctionCatalog,
});
} catch (err) {
throw new UserError(
ErrorCode.HOOKS_ERROR,
`Failed to parse hooks.${key}: ${err instanceof Error ? err.message : String(err)}. Hooks use the same syntax as workflow steps.`,
{ cause: err }
);
}
hookEntriesByKey[key] = entries;
for (const entry of entries) {
orderedSteps.push(...entry.steps);
}
for (const key of hookKeys) {
const steps = hooks[key];
if (!Array.isArray(steps) || steps.length === 0) {
continue;
}
let entries: HookEntry[];
try {
// Extended per key so a bad `uses:` path is attributed to that hook key.
await extendCompositeFunctionCatalogFromStepsAsync({
catalog: compositeFunctionCatalog,
rootSteps: steps,
loadCompositeFunction,
});
entries = await constructHookEntriesAsync(globalContext, steps, {
externalFunctions,
externalFunctionGroups,
compositeFunctionCatalog,
});
} catch (err) {
throw new UserError(
ErrorCode.HOOKS_ERROR,
`Failed to parse hooks.${key}: ${err instanceof Error ? err.message : String(err)}. Hooks use the same syntax as workflow steps.`,
{ cause: err }
);
}
hookEntriesByKey[key] = entries;
for (const entry of entries) {
orderedSteps.push(...entry.steps);
}
}
@@ -0,0 +1,15 @@
import { ArchiveSourceType } from '@expo/eas-build-job';
import { z } from 'zod';
export const ProjectArchiveSourceSchema = z.discriminatedUnion('type', [
z.object({
type: z.literal(ArchiveSourceType.GIT),
repositoryUrl: z.string().url(),
gitRef: z.string().nullable(),
gitCommitHash: z.string(),
}),
z.object({ type: z.literal(ArchiveSourceType.URL), url: z.string().url() }),
z.object({ type: z.literal(ArchiveSourceType.NONE) }),
]);
export type ProjectArchiveSource = z.infer<typeof ProjectArchiveSourceSchema>;
@@ -10,7 +10,9 @@ import path from 'path';
import { z } from 'zod';
import { shallowCloneRepositoryAsync } from './git';
import { type ProjectArchiveSource, ProjectArchiveSourceSchema } from './projectArchiveSource';
import { BuildContext } from '../context';
import { getSandboxWorkerApi } from '../steps/utils/sandboxWorkerApi';
import { uploadContentWithSignedUrl } from '../storage/uploadWithSignedUrl';
import { turtleFetch } from '../utils/turtleFetch';
@@ -245,7 +247,18 @@ async function uploadProjectMetadataAsync(
}
}
async function fetchProjectArchiveSourceAsync(ctx: BuildContext<Job>) {
async function fetchProjectArchiveSourceAsync(
ctx: BuildContext<Job>
): Promise<ProjectArchiveSource> {
const sandboxWorkerApi = getSandboxWorkerApi(ctx);
if (sandboxWorkerApi) {
return await sandboxWorkerApi.getProjectArchiveSourceAsync({
timeoutMs: 20000,
retries: 3,
logger: ctx.logger,
});
}
const taskId = nullthrows(ctx.env.EAS_BUILD_ID, 'EAS_BUILD_ID is not set');
const expoApiServerURL = nullthrows(ctx.env.__API_SERVER_URL, '__API_SERVER_URL is not set');
const robotAccessToken = nullthrows(
@@ -283,20 +296,7 @@ async function fetchProjectArchiveSourceAsync(ctx: BuildContext<Job>) {
);
}
const dataResult = z
.object({
data: z.discriminatedUnion('type', [
z.object({
type: z.literal(ArchiveSourceType.GIT),
repositoryUrl: z.string().url(),
gitRef: z.string().nullable(),
gitCommitHash: z.string(),
}),
z.object({ type: z.literal(ArchiveSourceType.URL), url: z.string().url() }),
z.object({ type: z.literal(ArchiveSourceType.NONE) }),
]),
})
.safeParse(jsonResult.value);
const dataResult = z.object({ data: ProjectArchiveSourceSchema }).safeParse(jsonResult.value);
if (!dataResult.success) {
throw new Error(
`Unexpected data from server (${response.status}): ${z.prettifyError(dataResult.error)}`
+15 -7
View File
@@ -3,7 +3,6 @@ import {
BuildJob,
BuildPhase,
BuildTrigger,
HookAnchorId,
Ios,
Job,
Platform,
@@ -15,7 +14,7 @@ import nullthrows from 'nullthrows';
import path from 'path';
import { resolveEnvFromBuildProfileAsync, runEasBuildInternalAsync } from './easBuildInternal';
import { runHookableBuildPhaseAsync } from './hookableBuildPhase';
import { runHookEntriesAsync, runHookableBuildPhaseAsync } from './hookableBuildPhase';
import { installDependenciesAsync, resolvePackagerDir } from './installDependencies';
import { ParsedJobHooks, parseJobHooksAsync } from './jobHooks';
import { prepareProjectSourcesAsync } from './projectSources';
@@ -50,10 +49,7 @@ export interface JobHooksRef {
export async function setupAsync<TJob extends BuildJob>(
ctx: BuildContext<TJob>,
{
wrappedAnchors,
jobHooksRef,
}: { wrappedAnchors: readonly HookAnchorId[]; jobHooksRef: JobHooksRef }
{ jobHooksRef }: { jobHooksRef: JobHooksRef }
): Promise<void> {
await ctx.runBuildPhase(BuildPhase.PREPARE_PROJECT, async () => {
await retryAsync(
@@ -111,7 +107,19 @@ export async function setupAsync<TJob extends BuildJob>(
// Parse hooks unconditionally, after every pre-install env mutation
// (PREPARE_PROJECT, the git-based profile-env block, PRE_INSTALL_HOOK) and
// before the first wrapped phase.
jobHooksRef.current = await parseJobHooksAsync(ctx, wrappedAnchors);
jobHooksRef.current = await parseJobHooksAsync(ctx, [
'after_checkout',
'before_install_node_modules',
'after_install_node_modules',
]);
if (jobHooksRef.current) {
await runHookEntriesAsync({
ctx,
hooks: jobHooksRef.current,
timing: 'after',
anchor: 'checkout',
});
}
await runHookableBuildPhaseAsync({
ctx,
+9 -1
View File
@@ -3,6 +3,7 @@ import {
BuildPhase,
BuildPhaseResult,
Env,
type EnvironmentSecret,
EnvironmentSecretType,
Job,
LogMarker,
@@ -18,6 +19,7 @@ import path from 'path';
import { resolveBuildPhaseErrorAsync } from './buildErrors/detectError';
import { Datadog } from './datadog';
import { SANDBOX_WORKER_TOKEN_ENV } from './steps/utils/sandboxWorkerApi';
import { readAppConfig } from './utils/appConfig';
import { createTemporaryEnvironmentSecretFile } from './utils/environmentSecrets';
import { PackageManager, resolvePackageManager } from './utils/packageManager';
@@ -408,7 +410,7 @@ export class BuildContext<TJob extends Job = Job> {
const environmentSecretsDirectory = path.join(this.workingdir, 'eas-environment-secrets');
const environmentSecrets: Record<string, string> = {};
for (const { name, type, value } of job.secrets.environmentSecrets) {
for (const { name, type, value } of job.secrets.environmentSecrets.filter(isJobSecret)) {
if (type === EnvironmentSecretType.STRING) {
environmentSecrets[name] = value;
} else {
@@ -422,3 +424,9 @@ export class BuildContext<TJob extends Job = Job> {
return environmentSecrets;
}
}
const EXCLUDED_JOB_SECRET_NAMES: ReadonlySet<string> = new Set([SANDBOX_WORKER_TOKEN_ENV]);
function isJobSecret({ name }: EnvironmentSecret): boolean {
return !EXCLUDED_JOB_SECRET_NAMES.has(name);
}
+15 -2
View File
@@ -1,23 +1,30 @@
import { Sentry } from './sentry';
import { DEVICE_RUN_SESSION_TOKEN_HEADER } from './steps/utils/deviceRunSessionWorkerApi';
import { SANDBOX_WORKER_TOKEN_HEADER } from './steps/utils/sandboxWorkerApi';
import { turtleFetch } from './utils/turtleFetch';
type MetricsTarget =
| { kind: 'build'; turtleBuildId: string }
| { kind: 'jobRun'; turtleJobRunId: string }
// A device run session job with a session token. The token names the session and its job run.
| { kind: 'deviceRunSession' };
| { kind: 'deviceRunSession' }
| { kind: 'sandbox' };
type DatadogSetupOptions =
| {
expoApiV2BaseUrl: string;
robotAccessToken: string;
target: Exclude<MetricsTarget, { kind: 'deviceRunSession' }>;
target: Exclude<MetricsTarget, { kind: 'deviceRunSession' | 'sandbox' }>;
}
| {
expoApiV2BaseUrl: string;
deviceRunSessionToken: string;
target: Extract<MetricsTarget, { kind: 'deviceRunSession' }>;
}
| {
expoApiV2BaseUrl: string;
sandboxWorkerToken: string;
target: Extract<MetricsTarget, { kind: 'sandbox' }>;
};
let setupOptions: DatadogSetupOptions | null = null;
@@ -41,6 +48,12 @@ function getMetricsRequest(options: DatadogSetupOptions): {
headers: { [DEVICE_RUN_SESSION_TOKEN_HEADER]: options.deviceRunSessionToken },
};
}
if ('sandboxWorkerToken' in options) {
return {
path: 'sandbox-worker/metrics',
headers: { [SANDBOX_WORKER_TOKEN_HEADER]: options.sandboxWorkerToken },
};
}
const { target, robotAccessToken } = options;
return {
path:
+1
View File
@@ -43,5 +43,6 @@ export * from './generic';
export { Datadog } from './datadog';
export { getDeviceRunSessionTokenFromEnvironmentSecrets } from './steps/utils/deviceRunSessionWorkerApi';
export { getSandboxWorkerTokenFromEnvironmentSecrets } from './steps/utils/sandboxWorkerApi';
export { Sentry } from './sentry';
export * from './runtimeSettings';
@@ -23,13 +23,19 @@ const WORKING_DIR = '/workingdir';
// BuildContext.getReactNativeProjectDirectory() nests the RN project under `${workingdir}/build`.
const IOS_DIR = path.join(WORKING_DIR, 'build', 'ios');
function makeIosBuildContext({ simulator }: { simulator: boolean }): BuildContext<Ios.Job> {
function makeIosBuildContext({
simulator,
env = {},
}: {
simulator: boolean;
env?: Record<string, string>;
}): BuildContext<Ios.Job> {
const job: Ios.Job = { ...createTestIosJob(), simulator };
return new BuildContext(job, {
workingdir: WORKING_DIR,
logger: createMockLogger(),
logBuffer: { getLogs: () => [], getPhaseLogs: () => [] },
env: { __API_SERVER_URL: 'http://api.expo.test' },
env: { __API_SERVER_URL: 'http://api.expo.test', ...env },
uploadArtifact: jest.fn(),
});
}
@@ -125,4 +131,25 @@ describe(runFastlaneGym, () => {
workspacePath: IOS_DIR,
});
});
it.each<{ name: string; env: Record<string, string>; expectedZipopt: string }>([
{ name: 'defaults ZIPOPT to -1', env: {}, expectedZipopt: '-1' },
{ name: 'keeps ZIPOPT from the build env', env: { ZIPOPT: '-9' }, expectedZipopt: '-9' },
])('$name', async ({ env, expectedZipopt }) => {
const ctx = makeIosBuildContext({ simulator: false, env });
await runFastlaneGym(ctx, {
scheme: 'App',
credentials: ARCHIVE_CREDENTIALS,
entitlements: null,
});
expect(spawn).toHaveBeenCalledWith(
'fastlane',
['gym'],
expect.objectContaining({
env: expect.objectContaining({ ZIPOPT: expectedZipopt }),
})
);
});
});
+1 -1
View File
@@ -84,7 +84,7 @@ async function updateVersionsAsync(
targetName,
buildConfiguration,
});
const infoPlist = xcBuildConfiguration.buildSettings.INFOPLIST_FILE;
const infoPlist = xcBuildConfiguration!.buildSettings.INFOPLIST_FILE;
if (infoPlist) {
const evaluatedInfoPlistPath = trimQuotes(
evaluateTemplateString(infoPlist, {
+2 -2
View File
@@ -10,7 +10,7 @@ import type { Credentials } from './credentials/manager';
import { createFastfileForResigningBuild } from './fastfile';
import { createGymfileForArchiveBuild, createGymfileForSimulatorBuild } from './gymfile';
import { isTVOS } from './tvos';
import { COMMON_FASTLANE_ENV } from '../common/fastlane';
import { COMMON_FASTLANE_ENV, DEFAULT_FASTLANE_GYM_ENV } from '../common/fastlane';
import { XcodeBuildLogger } from '../common/xcpretty';
import { BuildContext, SkipNativeBuildError } from '../context';
@@ -52,7 +52,7 @@ export async function runFastlaneGym<TJob extends Ios.Job>(
await runFastlane(['gym'], {
cwd: workspacePath,
logger: ctx.logger,
env: { ...ctx.env, ...extraEnv },
env: { ...DEFAULT_FASTLANE_GYM_ENV, ...ctx.env, ...extraEnv },
});
} finally {
await buildLogger.flush();
+1 -1
View File
@@ -28,5 +28,5 @@ export async function isTVOS(ctx: BuildContext<Ios.Job>): Promise<boolean> {
targetName,
buildConfiguration,
});
return xcBuildConfiguration?.buildSettings?.SDKROOT?.includes('appletv');
return xcBuildConfiguration?.buildSettings?.SDKROOT?.includes('appletv') ?? false;
}
@@ -62,9 +62,13 @@ import { createStartWebPreviewRemoteSessionBuildFunction } from './functions/sta
import { createStartServeSimMetricsBuildFunction } from './functions/startServeSimMetrics';
import { createStartServeSimLogsBuildFunction } from './functions/startServeSimLogs';
import { createCollectServeSimLogsBuildFunction } from './functions/collectServeSimLogs';
import { createStartServeSimNetworkCaptureBuildFunction } from './functions/startServeSimNetworkCapture';
import { createStartServeSimCrashesBuildFunction } from './functions/startServeSimCrashes';
import { createCollectServeSimCrashesBuildFunction } from './functions/collectServeSimCrashes';
import { createCollectAndroidEmulatorLogsBuildFunction } from './functions/collectAndroidEmulatorLogs';
import { createStartSandboxBuildFunction } from './functions/startSandbox';
import { createCollectServeSimMetricsBuildFunction } from './functions/collectServeSimMetrics';
import { createCollectServeSimNetworkCaptureBuildFunction } from './functions/collectServeSimNetworkCapture';
import { createUploadArtifactBuildFunction } from './functions/uploadArtifact';
import { createUploadDeviceRunSessionScreenRecordingsBuildFunction } from './functions/uploadDeviceRunSessionScreenRecordings';
import { createUploadEmbeddedBundleBuildFunction } from './functions/uploadEmbeddedBundle';
@@ -129,11 +133,15 @@ export function getEasFunctions(ctx: CustomBuildContext): BuildFunction[] {
createStartWebPreviewRemoteSessionBuildFunction(ctx, { warm: true }),
createStartServeSimMetricsBuildFunction(),
createStartServeSimLogsBuildFunction(),
createStartServeSimCrashesBuildFunction(),
createCollectServeSimCrashesBuildFunction(ctx),
createCollectServeSimLogsBuildFunction(ctx),
createCollectAndroidEmulatorLogsBuildFunction(ctx),
createStartSandboxBuildFunction(ctx),
createRunAgentBuildFunction(ctx),
createCollectServeSimMetricsBuildFunction(ctx),
createStartServeSimNetworkCaptureBuildFunction(),
createCollectServeSimNetworkCaptureBuildFunction(ctx),
createInstallMaestroBuildFunction(),
createInstallMitmproxyBuildFunction(),
@@ -24,7 +24,7 @@ function createStep(callInputs: Record<string, unknown> = {}) {
return { ctx, global, logger, fn, step };
}
it('defaults an existing workflow without inputs to emulator output only', async () => {
it('collects captured logs without a second source selection', async () => {
const { ctx, global, fn, step } = createStep();
expect(fn.supportedRuntimePlatforms).toEqual([BuildRuntimePlatform.LINUX]);
await step.executeAsync();
@@ -32,37 +32,9 @@ it('defaults an existing workflow without inputs to emulator output only', async
global,
deviceRunSessionId: 'session',
logger: expect.anything(),
sources: ['emulator-output'],
});
});
it.each([
{ sources: ['emulator-output', 'device-logcat'] },
{ sources: ['device-logcat'] },
{ sources: [] },
])('passes an explicit selection of $sources through the step input', async ({ sources }) => {
const { step } = createStep({ sources });
await step.executeAsync();
expect(collectAndroidEmulatorLogsAsync).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ sources })
);
});
it.each([
{ sources: ['unknown'] },
{ sources: ['emulator-output', 'unknown'] },
{ sources: [1] },
{ sources: { logcat: true } },
])('does not collect any logs for invalid sources %j', async ({ sources }) => {
const { step } = createStep({ sources });
const collect = jest.mocked(collectAndroidEmulatorLogsAsync);
collect.mockClear();
await step.executeAsync();
expect(collect).not.toHaveBeenCalled();
expect(Sentry.capture).toHaveBeenCalled();
});
it('reports collection failure without changing the session result', async () => {
jest
.mocked(collectAndroidEmulatorLogsAsync)
@@ -15,6 +15,7 @@ import {
parseMaestroResults,
parseMaestroResultsFromFileAttrs,
parseMaestroRunnerReport,
parseMaestroRunnerResults,
} from '../maestroResultParser';
describe(parseFailedFlowsFromMaestroRunnerReport, () => {
@@ -483,6 +484,271 @@ describe(parseMaestroResultsFromFileAttrs, () => {
});
});
describe(parseMaestroRunnerResults, () => {
function runnerJUnit(testcases: { name: string; file: string; failed?: boolean }[]): string {
return [
'<?xml version="1.0" encoding="UTF-8"?>',
'<testsuites>',
' <testsuite name="maestro-runner">',
...testcases.flatMap(({ name, file, failed }) => [
` <testcase id="${name}" name="${name}" classname="${name}" time="1.000" status="${failed ? 'ERROR' : 'SUCCESS'}">`,
' <properties>',
` <property name="file" value="${file}"/>`,
' <property name="device.platform" value="android"/>',
' </properties>',
...(failed ? [' <failure message="Element not found">tapOn</failure>'] : []),
' </testcase>',
]),
' </testsuite>',
'</testsuites>',
].join('\n');
}
it('adds the tags of each flow from the report.json of its attempt', async () => {
vol.fromJSON({
'/junit/android-maestro-junit-attempt-0.xml': runnerJUnit([
{ name: 'sign-in', file: 'flows/auth/sign-in.yaml', failed: true },
{ name: 'settings', file: 'flows/settings.yaml' },
]),
'/tests/android-maestro-runner-attempt-0/report.json': JSON.stringify({
flows: [
{
name: 'sign-in',
sourceFile: 'flows/auth/sign-in.yaml',
status: 'failed',
tags: ['auth', 'smoke'],
},
{ name: 'settings', sourceFile: 'flows/settings.yaml', status: 'passed' },
],
}),
'/junit/android-maestro-junit-attempt-1.xml': runnerJUnit([
{ name: 'sign-in', file: 'flows/auth/sign-in.yaml' },
]),
'/tests/android-maestro-runner-attempt-1/report.json': JSON.stringify({
flows: [
{
name: 'sign-in',
sourceFile: 'flows/auth/sign-in.yaml',
status: 'passed',
tags: ['auth'],
},
],
}),
});
const results = await parseMaestroRunnerResults({
junitDirectory: '/junit',
testsDirectory: '/tests',
workingDirectory: '/project',
});
expect(results).toEqual([
{
name: 'sign-in',
path: 'flows/auth/sign-in.yaml',
status: 'failed',
errorMessage: 'Element not found',
duration: 1000,
retryCount: 0,
tags: ['auth', 'smoke'],
properties: { file: 'flows/auth/sign-in.yaml', 'device.platform': 'android' },
},
expect.objectContaining({ path: 'flows/auth/sign-in.yaml', retryCount: 1, tags: ['auth'] }),
expect.objectContaining({ path: 'flows/settings.yaml', retryCount: 0, tags: [] }),
]);
});
it('matches an absolute sourceFile with a JUnit path relative to the working directory', async () => {
vol.fromJSON({
'/junit/ios-maestro-junit-attempt-0.xml': runnerJUnit([
{ name: 'sign-in', file: 'flows/sign-in.yaml' },
]),
'/tests/ios-maestro-runner-attempt-0/report.json': JSON.stringify({
flows: [
{
name: 'sign-in',
sourceFile: '/project/flows/sign-in.yaml',
status: 'passed',
tags: ['auth'],
},
],
}),
});
const results = await parseMaestroRunnerResults({
junitDirectory: '/junit',
testsDirectory: '/tests',
workingDirectory: '/project',
});
expect(results).toEqual([
expect.objectContaining({ path: 'flows/sign-in.yaml', tags: ['auth'] }),
]);
});
it('matches a sourceFile under a symlinked directory with the JUnit path of its target', async () => {
vol.fromJSON({
'/project/flows/sign-in.yaml': '',
'/junit/ios-maestro-junit-attempt-0.xml': runnerJUnit([
{ name: 'sign-in', file: 'flows/sign-in.yaml' },
]),
'/tests/ios-maestro-runner-attempt-0/report.json': JSON.stringify({
flows: [
{ name: 'sign-in', sourceFile: 'linked/sign-in.yaml', status: 'passed', tags: ['auth'] },
],
}),
});
vol.symlinkSync('/project/flows', '/project/linked');
const results = await parseMaestroRunnerResults({
junitDirectory: '/junit',
testsDirectory: '/tests',
workingDirectory: '/project',
});
expect(results).toEqual([
expect.objectContaining({ path: 'flows/sign-in.yaml', tags: ['auth'] }),
]);
});
it('matches a sourceFile whose symlink leaves the working directory by the path as given', async () => {
vol.fromJSON({
'/project/.keep': '',
'/shared/sign-in.yaml': '',
'/junit/ios-maestro-junit-attempt-0.xml': runnerJUnit([
{ name: 'sign-in', file: 'linked/sign-in.yaml' },
]),
'/tests/ios-maestro-runner-attempt-0/report.json': JSON.stringify({
flows: [
{ name: 'sign-in', sourceFile: 'linked/sign-in.yaml', status: 'passed', tags: ['auth'] },
],
}),
});
vol.symlinkSync('/shared', '/project/linked');
const results = await parseMaestroRunnerResults({
junitDirectory: '/junit',
testsDirectory: '/tests',
workingDirectory: '/project',
});
expect(results).toEqual([
expect.objectContaining({ path: 'linked/sign-in.yaml', tags: ['auth'] }),
]);
});
it('does not follow a symlink from the bare file name that maestro-runner <= 1.1.17 writes', async () => {
vol.fromJSON({
'/project/flows/sign-in.yaml': '',
'/project/settings.yaml': '',
'/junit/ios-maestro-junit-attempt-0.xml': runnerJUnit([
{ name: 'sign-in', file: 'sign-in.yaml' },
{ name: 'settings', file: 'settings.yaml' },
]),
'/tests/ios-maestro-runner-attempt-0/report.json': JSON.stringify({
flows: [
{ name: 'sign-in', sourceFile: 'flows/sign-in.yaml', status: 'passed', tags: ['auth'] },
{ name: 'settings', sourceFile: 'settings.yaml', status: 'passed', tags: ['settings'] },
],
}),
});
vol.symlinkSync('/project/settings.yaml', '/project/sign-in.yaml');
const results = await parseMaestroRunnerResults({
junitDirectory: '/junit',
testsDirectory: '/tests',
workingDirectory: '/project',
});
expect(results).toEqual([
expect.objectContaining({ path: 'sign-in.yaml', tags: ['auth'] }),
expect.objectContaining({ path: 'settings.yaml', tags: ['settings'] }),
]);
});
it('matches by file name when JUnit has only the file name and it is unique', async () => {
vol.fromJSON({
'/junit/ios-maestro-junit-attempt-0.xml': runnerJUnit([
{ name: 'sign-in', file: 'sign-in.yaml' },
]),
'/tests/ios-maestro-runner-attempt-0/report.json': JSON.stringify({
flows: [
{
name: 'sign-in',
sourceFile: 'flows/auth/sign-in.yaml',
status: 'passed',
tags: ['auth'],
},
{
name: 'settings',
sourceFile: 'flows/settings.yaml',
status: 'passed',
tags: ['settings'],
},
],
}),
});
const results = await parseMaestroRunnerResults({
junitDirectory: '/junit',
testsDirectory: '/tests',
workingDirectory: '/project',
});
expect(results).toEqual([expect.objectContaining({ path: 'sign-in.yaml', tags: ['auth'] })]);
});
it('adds no tags when two flows of the attempt have the same file name', async () => {
vol.fromJSON({
'/junit/ios-maestro-junit-attempt-0.xml': runnerJUnit([
{ name: 'sign-in', file: 'sign-in.yaml' },
]),
'/tests/ios-maestro-runner-attempt-0/report.json': JSON.stringify({
flows: [
{ name: 'a', sourceFile: 'flows/a/sign-in.yaml', status: 'passed', tags: ['a'] },
{ name: 'b', sourceFile: 'flows/b/sign-in.yaml', status: 'passed', tags: ['b'] },
],
}),
});
const results = await parseMaestroRunnerResults({
junitDirectory: '/junit',
testsDirectory: '/tests',
workingDirectory: '/project',
});
expect(results).toEqual([expect.objectContaining({ path: 'sign-in.yaml', tags: [] })]);
});
it.each([
{ name: 'is not valid JSON', content: '{' },
{ name: 'has an unknown shape', content: JSON.stringify({ flows: [{ name: 'sign-in' }] }) },
{
name: 'does not have the flow',
content: JSON.stringify({
flows: [{ name: 'other', sourceFile: 'flows/other.yaml', status: 'passed', tags: ['x'] }],
}),
},
])('keeps the JUnit result without tags when report.json $name', async ({ content }) => {
vol.fromJSON({
'/junit/android-maestro-junit-attempt-0.xml': runnerJUnit([
{ name: 'sign-in', file: 'flows/sign-in.yaml' },
]),
'/tests/android-maestro-runner-attempt-0/report.json': content,
});
const results = await parseMaestroRunnerResults({
junitDirectory: '/junit',
testsDirectory: '/tests',
workingDirectory: '/project',
});
expect(results).toEqual([
expect.objectContaining({ name: 'sign-in', path: 'flows/sign-in.yaml', tags: [] }),
]);
});
});
describe('junitFileHasFileAttrs', () => {
it('returns true when every testcase has a non-empty file= attribute', async () => {
vol.fromJSON({
@@ -358,6 +358,51 @@ describe(createReportMaestroTestResultsFunction, () => {
);
});
it('reports maestro-runner results with the tags from report.json', async () => {
vol.fromJSON({
'/junit/android-maestro-junit-attempt-0.xml': [
'<testsuites><testsuite name="maestro-runner">',
' <testcase id="sign-in" name="sign-in" classname="sign-in" time="2.000" status="SUCCESS">',
' <properties><property name="file" value="flows/sign-in.yaml"/></properties>',
' </testcase>',
'</testsuite></testsuites>',
].join('\n'),
'/tests/android-maestro-runner-attempt-0/report.json': JSON.stringify({
flows: [
{
name: 'sign-in',
sourceFile: 'flows/sign-in.yaml',
status: 'passed',
tags: ['auth', 'smoke'],
},
],
}),
});
mockMutationFn.mockResolvedValue({
data: {
workflowDeviceTestCaseResult: {
createWorkflowDeviceTestCaseResults: [{ id: 'id-1' }],
},
},
});
await createStep().executeAsync();
const variables = (mockGraphqlClient.mutation as jest.Mock).mock.calls[0][1];
expect(variables.input.testCaseResults).toEqual([
{
name: 'sign-in',
path: 'flows/sign-in.yaml',
status: 'PASSED',
errorMessage: null,
duration: 2000,
retryCount: 0,
tags: ['auth', 'smoke'],
properties: { file: 'flows/sign-in.yaml' },
},
]);
});
it('uses default directories when inputs are not provided', async () => {
vol.fromJSON({
'/home/expo/.maestro/tests/report.xml': JUNIT_PASS,
@@ -0,0 +1,121 @@
import { type bunyan } from '@expo/logger';
import { type BuildStepContext, type BuildStepEnv } from '@expo/steps';
import { access, mkdir, mkdtemp, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { type CustomBuildContext } from '../../../customBuildContext';
import { Sentry } from '../../../sentry';
import { getDeviceRunSessionIdOrThrow } from '../../utils/remoteDeviceRunSession';
import { uploadServeSimCrashesFileAsync } from '../../utils/serveSimCrashesArtifacts';
import { ServeSimCrashesRecorder } from '../../utils/serveSimCrashesRecorder';
import { createCollectServeSimCrashesBuildFunction } from '../collectServeSimCrashes';
import { createStartServeSimCrashesBuildFunction } from '../startServeSimCrashes';
jest.mock('../../../sentry');
jest.mock('../../utils/serveSimCrashesRecorder');
jest.mock('../../utils/serveSimCrashesArtifacts');
jest.mock('../../utils/remoteDeviceRunSession');
const logger = { info: jest.fn(), warn: jest.fn() } as unknown as bunyan;
const ctx = {} as CustomBuildContext;
const step = { logger } as BuildStepContext;
const args = { inputs: {}, outputs: {}, env: {} as BuildStepEnv };
beforeEach(() => {
jest.mocked(getDeviceRunSessionIdOrThrow).mockReturnValue('session-id');
jest
.mocked(ServeSimCrashesRecorder.finishAsync)
.mockResolvedValue({ outputDirectory: null, crashes: [] });
});
it('starts collection and tolerates startup failures', async () => {
jest.mocked(ServeSimCrashesRecorder.startAsync).mockRejectedValueOnce(new Error('disk failure'));
await expect(createStartServeSimCrashesBuildFunction().fn?.(step, args)).resolves.toBeUndefined();
expect(logger.warn).toHaveBeenCalled();
expect(Sentry.capture).toHaveBeenCalledWith(
'Could not start serve-sim simulator crashes',
expect.any(Error)
);
});
it('uploads each report and removes the collection directory', async () => {
const directory = '/tmp/crashes-collected';
await mkdir(directory, { recursive: true });
await writeFile(`${directory}/A.ips`, 'private crash report');
jest.mocked(ServeSimCrashesRecorder.finishAsync).mockResolvedValue({
outputDirectory: directory,
crashes: [
{ udid: 'A', filePath: `${directory}/A.ips`, size: 20, number: 1 },
{ udid: 'B', filePath: `${directory}/B.ips`, size: 20, number: 1 },
],
});
await createCollectServeSimCrashesBuildFunction(ctx).fn?.(step, args);
expect(uploadServeSimCrashesFileAsync).toHaveBeenCalledTimes(2);
expect(uploadServeSimCrashesFileAsync).toHaveBeenCalledWith(ctx, {
deviceRunSessionId: 'session-id',
crash: { udid: 'A', filePath: `${directory}/A.ips`, size: 20, number: 1 },
logger,
signal: expect.any(AbortSignal),
});
await expect(access(directory)).rejects.toMatchObject({ code: 'ENOENT' });
});
it('skips empty collection and warns on finalization failure', async () => {
await createCollectServeSimCrashesBuildFunction(ctx).fn?.(step, args);
expect(uploadServeSimCrashesFileAsync).not.toHaveBeenCalled();
jest.mocked(ServeSimCrashesRecorder.finishAsync).mockRejectedValueOnce(new Error('failure'));
await expect(
createCollectServeSimCrashesBuildFunction(ctx).fn?.(step, args)
).resolves.toBeUndefined();
expect(logger.warn).toHaveBeenCalled();
expect(Sentry.capture).toHaveBeenCalledWith(
'Could not finalize serve-sim simulator crashes',
expect.any(Error)
);
});
it.each([
['no crashes were recorded', [], false],
['session resolution fails', [{ udid: 'A', filePath: 'A.ips', size: 20, number: 1 }], true],
])('removes the collection directory when %s', async (_name, crashes, failSession) => {
const outputDirectory = await mkdtemp(path.join(os.tmpdir(), 'crashes-collected-'));
jest.mocked(ServeSimCrashesRecorder.finishAsync).mockResolvedValue({ outputDirectory, crashes });
if (failSession) {
jest.mocked(getDeviceRunSessionIdOrThrow).mockImplementationOnce(() => {
throw new Error('Missing session ID');
});
}
await expect(
createCollectServeSimCrashesBuildFunction(ctx).fn?.(step, args)
).resolves.toBeUndefined();
await expect(access(outputDirectory)).rejects.toMatchObject({ code: 'ENOENT' });
expect(uploadServeSimCrashesFileAsync).not.toHaveBeenCalled();
});
it('skips remaining reports for an exhausted device and continues with other devices', async () => {
jest.mocked(ServeSimCrashesRecorder.finishAsync).mockResolvedValue({
outputDirectory: null,
crashes: [
{ udid: 'A', filePath: '/tmp/A-1.ips', size: 20, number: 1 },
{ udid: 'A', filePath: '/tmp/A-2.ips', size: 20, number: 2 },
{ udid: 'B', filePath: '/tmp/B-1.ips', size: 20, number: 1 },
],
});
const controller = new AbortController();
const timeout = jest.spyOn(AbortSignal, 'timeout').mockReturnValueOnce(controller.signal);
jest.mocked(uploadServeSimCrashesFileAsync).mockImplementationOnce(async () => {
controller.abort(new Error('Upload budget exhausted'));
});
try {
await createCollectServeSimCrashesBuildFunction(ctx).fn?.(step, args);
expect(
jest.mocked(uploadServeSimCrashesFileAsync).mock.calls.map(([, { crash }]) => crash.filePath)
).toEqual(['/tmp/A-1.ips', '/tmp/B-1.ips']);
expect(logger.warn).toHaveBeenCalledWith(
'Simulator crash upload reached its time limit for A; remaining reports will not be uploaded.'
);
} finally {
timeout.mockRestore();
}
});
@@ -0,0 +1,104 @@
import { bunyan } from '@expo/logger';
import { type BuildStepEnv } from '@expo/steps';
import { access, mkdtemp } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { type CustomBuildContext } from '../../../customBuildContext';
import { uploadServeSimNetworkCaptureFileAsync } from '../../utils/serveSimNetworkCaptureArtifacts';
import { ServeSimNetworkCaptureRecorder } from '../../utils/serveSimNetworkCaptureRecorder';
import { createCollectServeSimNetworkCaptureBuildFunction } from '../collectServeSimNetworkCapture';
import { createStartServeSimNetworkCaptureBuildFunction } from '../startServeSimNetworkCapture';
jest.mock('../../../sentry');
jest.mock('../../utils/serveSimNetworkCaptureArtifacts');
jest.mock('../../utils/serveSimNetworkCaptureRecorder');
const ctx = {} as CustomBuildContext;
const logger = {
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
debug: jest.fn(),
} as unknown as bunyan;
type Fn = (stepCtx: unknown, options: unknown) => Promise<void>;
function runFn(
fn: unknown,
options: { env: BuildStepEnv; inputs?: Record<string, { value: unknown }> }
): Promise<void> {
return (fn as Fn)({ logger }, { inputs: {}, ...options });
}
beforeEach(() => {
jest.clearAllMocks();
});
it('starts the recorder with the session package version and never fails the step', async () => {
const buildFunction = createStartServeSimNetworkCaptureBuildFunction();
expect(buildFunction.id).toBe('start_serve_sim_network_capture');
const { fn } = buildFunction as unknown as { fn: Fn };
const env = {} as BuildStepEnv;
await runFn(fn, { env, inputs: { package_version: { value: '0.5.0' } } });
expect(ServeSimNetworkCaptureRecorder.startAsync).toHaveBeenCalledWith({
logger,
env,
packageVersion: '0.5.0',
});
jest.mocked(ServeSimNetworkCaptureRecorder.startAsync).mockRejectedValueOnce(new Error('ENOSPC'));
await expect(
runFn(fn, { env, inputs: { package_version: { value: undefined } } })
).resolves.toBeUndefined();
expect(logger.warn).toHaveBeenCalledWith(
{ err: expect.objectContaining({ message: 'ENOSPC' }) },
'Could not start the serve-sim network capture recorder.'
);
});
it('uploads each recorded HAR as a numbered part per device, then removes the directory', async () => {
const outputDirectory = await mkdtemp(path.join(os.tmpdir(), 'serve-sim-network-capture-'));
const captures = [
{ udid: 'SIM-A', filePath: path.join(outputDirectory, 'SIM-A-1.har'), size: 24 },
{ udid: 'SIM-B', filePath: path.join(outputDirectory, 'SIM-B-1.har'), size: 25 },
{ udid: 'SIM-A', filePath: path.join(outputDirectory, 'SIM-A-3.har'), size: 26 },
];
jest
.mocked(ServeSimNetworkCaptureRecorder.finishAsync)
.mockResolvedValueOnce({ outputDirectory, captures });
const { fn } = createCollectServeSimNetworkCaptureBuildFunction(ctx) as unknown as { fn: Fn };
await runFn(fn, { env: { DEVICE_RUN_SESSION_ID: 'drs-id' } as BuildStepEnv });
const signal = expect.any(AbortSignal);
expect(jest.mocked(uploadServeSimNetworkCaptureFileAsync).mock.calls).toEqual([
[ctx, { deviceRunSessionId: 'drs-id', ...captures[0], part: 1, logger, signal }],
[ctx, { deviceRunSessionId: 'drs-id', ...captures[1], part: 1, logger, signal }],
[ctx, { deviceRunSessionId: 'drs-id', ...captures[2], part: 2, logger, signal }],
]);
await expect(access(outputDirectory)).rejects.toThrow();
});
it('does not fail the step without a device run session, and still removes the directory', async () => {
const outputDirectory = await mkdtemp(path.join(os.tmpdir(), 'serve-sim-network-capture-'));
jest.mocked(ServeSimNetworkCaptureRecorder.finishAsync).mockResolvedValueOnce({
outputDirectory,
captures: [{ udid: 'SIM-A', filePath: path.join(outputDirectory, 'SIM-A-1.har'), size: 24 }],
});
const { fn } = createCollectServeSimNetworkCaptureBuildFunction(ctx) as unknown as { fn: Fn };
await expect(runFn(fn, { env: {} as BuildStepEnv })).resolves.toBeUndefined();
expect(uploadServeSimNetworkCaptureFileAsync).not.toHaveBeenCalled();
expect(logger.warn).toHaveBeenCalledWith(
{ err: expect.any(Error) },
'Could not upload the network capture.'
);
await expect(access(outputDirectory)).rejects.toThrow();
});
it('skips the upload when nothing was recorded', async () => {
jest
.mocked(ServeSimNetworkCaptureRecorder.finishAsync)
.mockResolvedValueOnce({ outputDirectory: null, captures: [] });
const { fn } = createCollectServeSimNetworkCaptureBuildFunction(ctx) as unknown as { fn: Fn };
await runFn(fn, { env: { DEVICE_RUN_SESSION_ID: 'drs-id' } as BuildStepEnv });
expect(uploadServeSimNetworkCaptureFileAsync).not.toHaveBeenCalled();
expect(logger.info).toHaveBeenCalledWith('No network capture was recorded; skipping upload.');
});
@@ -201,6 +201,51 @@ describe('runAgentDeviceRemoteSessionAsync orchestration', () => {
expect(mockDaemonStopAsync).toHaveBeenCalledTimes(1);
});
it('does not fail a session when only the agent-device tunnel cannot stop', async () => {
const logger = { info: jest.fn(), warn: jest.fn(), child: jest.fn().mockReturnThis() };
const tunnelError = new Error('Ngrok tunnel stop timed out after 4000ms.');
mockTunnelStopAsync.mockRejectedValueOnce(tunnelError);
await expect(runAsync(logger, BuildRuntimePlatform.LINUX)).resolves.toBeUndefined();
expect(mockPreviewStopAsync).toHaveBeenCalledTimes(1);
expect(mockDaemonStopAsync).toHaveBeenCalledTimes(1);
expect(logger.warn).toHaveBeenCalledWith(
{ err: tunnelError },
'Could not stop the agent-device tunnel during remote session teardown.'
);
});
it.each([
[
BuildRuntimePlatform.DARWIN,
{
iosSimulatorUdid: 'selected-udid',
application: Promise.resolve({
installAppPath: '/tmp/App.app',
launchAppIdentifier: 'com.example.archive',
}),
},
],
[
BuildRuntimePlatform.LINUX,
{ booted: Promise.resolve(), ready: Promise.resolve('com.example.archive') },
],
])(
'reports the identifier of the app the %s device launched',
async (runtimePlatform, device) => {
const logger = { info: jest.fn(), warn: jest.fn(), child: jest.fn().mockReturnThis() };
await runAsync(logger, runtimePlatform, { device });
expect(uploadRemoteSessionConfigAsync).toHaveBeenCalledWith(
expect.objectContaining({
remoteConfig: expect.objectContaining({ applicationIdentifier: 'com.example.archive' }),
})
);
}
);
it('uses the warm daemon after adoption and starts no daemon of its own', async () => {
const logger = { info: jest.fn(), warn: jest.fn(), child: jest.fn().mockReturnThis() };
const warmServer = { port: 3200 } as never;
@@ -918,6 +963,21 @@ describe('runAgentDeviceRemoteSessionAsync orchestration', () => {
await expect(session).rejects.toBe(failed);
});
it('reports a startup Stop when only the agent-device tunnel cannot stop', async () => {
const stopped = new DeviceRunSessionStoppedError('stopped during startup');
let tasks!: StartupTasks;
const session = startSession(startup => {
tasks = startup;
return { booted: Promise.resolve(), ready: tasks.untilAborted(new Promise(() => {})) };
});
session.catch(() => {});
await flushAsync();
mockTunnelStopAsync.mockRejectedValueOnce(new Error('tunnel stop timed out'));
tasks.abort(stopped);
await expect(session).rejects.toBe(stopped);
expect(mockTunnelStopAsync).toHaveBeenCalledTimes(1);
});
it('retires startup monitoring after reporting and before lifetime waiting', async () => {
const retired = deferred();
const retiring = jest.fn(() => retired.promise);
@@ -4,8 +4,8 @@ import spawn from '@expo/turtle-spawn';
import { createGlobalContextMock } from '../../../__tests__/utils/context';
import { type CustomBuildContext } from '../../../customBuildContext';
import { AndroidEmulatorLogCapture } from '../../../utils/androidEmulatorLogCapture';
import { registerAndroidEmulatorLogDirectory } from '../../utils/androidEmulatorLogs';
import { AndroidEmulatorLogRing } from '../../../utils/androidEmulatorLogCapture';
import { getAndroidEmulatorLogCapture } from '../../utils/androidEmulatorLogs';
import { IosSimulatorUtils } from '../../../utils/IosSimulatorUtils';
import { stopLocalEgressResourcesAsync } from '../../utils/localEgress';
import {
@@ -116,46 +116,21 @@ function runStep(
): Promise<void> {
const buildFunction = createStartAgentDeviceSessionBuildFunction(stepCtx, { warm });
const logger = { info: jest.fn(), warn: jest.fn(), child: jest.fn().mockReturnThis() };
const global = createGlobalContextMock({
runtimePlatform,
staticContextContent: { job: { secrets: { robotAccessToken: 'robot-token' } } },
});
const inputs = Object.fromEntries(
[
'android_log_sources',
'device_identifier',
'system_image_package',
'lcd_width',
'lcd_height',
'lcd_density',
'install_app_path',
'build_id',
'application_archive_url',
'launch_app_identifier',
'launch_args',
'open_url',
'network_capture',
'network_capture_fields',
'public_preview',
'private_preview_url',
'frame_ancestors',
'cors_origins',
'package_version',
'max_idle_time_minutes',
'max_duration_seconds',
].map(id => [
id,
{
value:
id === 'android_log_sources' && !(id in inputValues)
? ['emulator-output', 'device-logcat']
: inputValues[id],
},
])
(buildFunction.inputProviders ?? []).map(provider => {
const input = provider(global, 'test');
input.set(inputValues[input.id]);
return [input.id, { value: input.rawValue }];
})
);
return buildFunction.fn!(
{
logger,
global: {
runtimePlatform,
staticContext: { job: { secrets: { robotAccessToken: 'robot-token' } } },
},
global,
} as unknown as BuildStepContext,
{ inputs, outputs: {}, env, signal } as never
) as Promise<void>;
@@ -186,6 +161,11 @@ describe(createStartAgentDeviceSessionBuildFunction, () => {
}
beforeEach(() => {
jest
.mocked(getAndroidEmulatorLogCapture)
.mockImplementation(
jest.requireActual('../../utils/androidEmulatorLogs').getAndroidEmulatorLogCapture
);
deviceLaunch = undefined;
jest.clearAllMocks();
jest.mocked(resolveLocalEgressServeSimBootEnvironmentAsync).mockResolvedValue(null);
@@ -450,7 +430,7 @@ describe(createStartAgentDeviceSessionBuildFunction, () => {
expect(installBuildAsync).not.toHaveBeenCalled();
expect(launchApplicationAsync).not.toHaveBeenCalled();
expect(registerAndroidEmulatorLogDirectory).not.toHaveBeenCalled();
expect(getAndroidEmulatorLogCapture).not.toHaveBeenCalled();
expect(sessionDevice()).toEqual({
iosSimulatorUdid: 'SELECTED-UDID',
bootEnv: undefined,
@@ -458,36 +438,59 @@ describe(createStartAgentDeviceSessionBuildFunction, () => {
});
});
it.each([
{ sources: [] },
{ sources: ['emulator-output'] },
{ sources: ['device-logcat'] },
{ sources: ['emulator-output', 'device-logcat'] },
])('selects $sources before Android boot', async ({ sources }) => {
const capture = new AndroidEmulatorLogCapture();
jest.mocked(registerAndroidEmulatorLogDirectory).mockReturnValue(capture);
await runStep(
BuildRuntimePlatform.LINUX,
{ android_log_sources: sources },
undefined,
ctx,
false,
{
DEVICE_RUN_SESSION_ID: 'session',
}
);
it('defaults an omitted session log input to emulator output through the step boundary', async () => {
const buildFunction = createStartAgentDeviceSessionBuildFunction(ctx);
const global = createGlobalContextMock({ runtimePlatform: BuildRuntimePlatform.LINUX });
const step = buildFunction.createBuildStepFromFunctionCall(global, {
callInputs: {},
env: { DEVICE_RUN_SESSION_ID: 'session' },
});
await step.executeAsync();
expect(startAndroidEmulatorAsync).toHaveBeenCalledWith(
expect.objectContaining({ logSources: sources, logCapture: capture })
expect.objectContaining({
logCapture: expect.objectContaining({ sources: ['emulator-output'] }),
})
);
});
it('rejects invalid Android log sources before boot', async () => {
it('passes an explicit empty source list and the workflow capture to Android boot', async () => {
const capture = new AndroidEmulatorLogRing({ sources: [] });
jest.mocked(getAndroidEmulatorLogCapture).mockReturnValue(capture);
const env = { DEVICE_RUN_SESSION_ID: 'session' };
await runStep(BuildRuntimePlatform.LINUX, { log_sources: [] }, undefined, ctx, false, env);
expect(getAndroidEmulatorLogCapture).toHaveBeenCalledWith(expect.anything(), env, []);
expect(startAndroidEmulatorAsync).toHaveBeenCalledWith(
expect.objectContaining({ logCapture: capture })
);
});
it('rejects invalid Android log sources before boot or downloading', async () => {
await expect(
runStep(BuildRuntimePlatform.LINUX, {
android_log_sources: ['unknown'],
log_sources: ['unknown'],
build_id: 'build-id',
})
).rejects.toThrow();
expect(startAndroidEmulatorAsync).not.toHaveBeenCalled();
expect(downloadBuildAsync).not.toHaveBeenCalled();
});
it('rejects Android log sources on an iOS session before boot or downloading', async () => {
await expect(
runStep(BuildRuntimePlatform.DARWIN, {
log_sources: ['device-logcat'],
build_id: 'build-id',
})
).rejects.toThrow('Input "log_sources" selects Android emulator logs');
expect(runAgentDeviceRemoteSessionAsync).not.toHaveBeenCalled();
expect(IosSimulatorUtils.resolveUdidAsync).not.toHaveBeenCalled();
expect(downloadBuildAsync).not.toHaveBeenCalled();
});
it('boots an iOS session with an explicit empty source list', async () => {
await runStep(BuildRuntimePlatform.DARWIN, { log_sources: [] });
expect(runAgentDeviceRemoteSessionAsync).toHaveBeenCalled();
expect(startAndroidEmulatorAsync).not.toHaveBeenCalled();
});
it('boots the Android Emulator with the device inputs', async () => {
@@ -501,10 +504,6 @@ describe(createStartAgentDeviceSessionBuildFunction, () => {
});
expect(selectXcodeDeveloperDirectoryAsync).not.toHaveBeenCalled();
expect(registerAndroidEmulatorLogDirectory).toHaveBeenCalledWith(
expect.objectContaining({ runtimePlatform: BuildRuntimePlatform.LINUX }),
jest.mocked(startAndroidEmulatorAsync).mock.calls[0][0].logcatDirectory
);
expect(startAndroidEmulatorAsync).toHaveBeenCalledWith(
expect.objectContaining({
deviceIdentifier: 'pixel_7',
@@ -518,24 +517,26 @@ describe(createStartAgentDeviceSessionBuildFunction, () => {
expect(launchApplicationAsync).toHaveBeenCalledWith(
expect.objectContaining({ applicationIdentifier: 'dev.example.app', activityName: '.Main' })
);
// The remote session reports it so clients can attach to an archive session's app.
await expect((sessionDevice() as { ready: Promise<unknown> }).ready).resolves.toBe(
'dev.example.app'
);
});
it('stops the download and waits for it when Android boot fails', async () => {
const download = mockStalledDownload();
jest.mocked(startAndroidEmulatorAsync).mockRejectedValue(new Error('boot failed'));
await expect(runStep(BuildRuntimePlatform.LINUX, { build_id: 'build-id' })).rejects.toThrow(
'boot failed'
);
await expect(
runStep(BuildRuntimePlatform.LINUX, { build_id: 'build-id' }, undefined, ctx, false, {
DEVICE_RUN_SESSION_ID: 'session',
})
).rejects.toThrow('boot failed');
expect(download.aborted()).toBe(true);
// The step returned only after the download stopped.
expect(download.settled()).toBe(true);
expect(installBuildAsync).not.toHaveBeenCalled();
expect(registerAndroidEmulatorLogDirectory).toHaveBeenCalledTimes(1);
expect(
jest.mocked(registerAndroidEmulatorLogDirectory).mock.invocationCallOrder[0]
).toBeLessThan(jest.mocked(startAndroidEmulatorAsync).mock.invocationCallOrder[0]);
});
it('does not start work for an already cancelled step', async () => {
@@ -685,7 +686,7 @@ describe(createStartAgentDeviceSessionBuildFunction, () => {
expect(
buildFunction.inputProviders?.map(provider => provider(globalCtx, 'Test step').id)
).toEqual([
'android_log_sources',
'log_sources',
'device_identifier',
'system_image_package',
'lcd_width',
@@ -890,6 +891,17 @@ describe(createStartAgentDeviceSessionBuildFunction, () => {
expect(runAgentDeviceRemoteSessionAsync).toHaveBeenCalledTimes(2);
});
it('passes the resolved version to agent-device after a warm version mismatch', async () => {
jest
.mocked(runOnWarmIosSimulatorAsync)
.mockImplementation((_claim, run) => run(undefined, '999.1.0'));
await runStep(BuildRuntimePlatform.DARWIN, { package_version: 'latest' }, undefined, ctx, true);
expect(runAgentDeviceRemoteSessionAsync).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ packageVersion: '999.1.0' })
);
});
it('accepts only one application source', async () => {
await expect(
runStep(BuildRuntimePlatform.DARWIN, { install_app_path: '/tmp/App.app', build_id: 'id' })
@@ -9,8 +9,9 @@ import {
} from '../../../utils/AndroidEmulatorUtils';
import { retryAsync } from '../../../utils/retry';
import { resolveAndroidEmulatorLocalEgressAsync } from '../../utils/androidLocalEgress';
import { AndroidEmulatorLogCapture } from '../../../utils/androidEmulatorLogCapture';
import { registerAndroidEmulatorLogDirectory } from '../../utils/androidEmulatorLogs';
import { AndroidEmulatorLogRing } from '../../../utils/androidEmulatorLogCapture';
import { getAndroidEmulatorLogCapture } from '../../utils/androidEmulatorLogs';
import { installEmulatorCaptureAsync } from '../../utils/emulatorCapture';
import { createStartAndroidEmulatorBuildFunction } from '../startAndroidEmulator';
jest.mock('@expo/turtle-spawn', () => ({
@@ -28,6 +29,11 @@ jest.mock('../../utils/androidLocalEgress', () => ({
jest.mock('../../utils/androidEmulatorLogs');
jest.mock('../../utils/emulatorCapture', () => ({
...jest.requireActual('../../utils/emulatorCapture'),
installEmulatorCaptureAsync: jest.fn(),
}));
jest.mock('../../../utils/AndroidEmulatorUtils', () => ({
AndroidEmulatorUtils: {
defaultSystemImagePackage: 'system-images;android-30;default;x86_64',
@@ -38,6 +44,7 @@ jest.mock('../../../utils/AndroidEmulatorUtils', () => ({
waitForReadyAsync: jest.fn(),
disableWindowAndTransitionAnimationsAsync: jest.fn(),
deleteAsync: jest.fn(),
findFreeConsolePortAsync: jest.fn(),
},
}));
@@ -54,7 +61,12 @@ function createStep(callInputs?: Record<string, unknown>, envOverrides?: NodeJS.
const step = fn.createBuildStepFromFunctionCall(globalCtx, {
callInputs,
});
return Object.assign(step, { logger });
return Object.assign(step, { logger, globalCtx });
}
/** The logger that the step function gets: a child of the base logger. */
function stepLogger(step: ReturnType<typeof createStep>) {
return jest.mocked(step.logger.child).mock.results[0].value;
}
function createStartResult(serialId: string) {
@@ -66,6 +78,11 @@ function createStartResult(serialId: string) {
describe(createStartAndroidEmulatorBuildFunction, () => {
beforeEach(() => {
jest
.mocked(getAndroidEmulatorLogCapture)
.mockImplementation(
jest.requireActual('../../utils/androidEmulatorLogs').getAndroidEmulatorLogCapture
);
mockedMkdtemp.mockResolvedValue('/tmp/logcat-directory');
mockedSpawn.mockResolvedValue({ stdout: '', stderr: '' } as any);
mockedAndroidUtils.getAvailableDevicesAsync.mockResolvedValue([]);
@@ -94,28 +111,27 @@ describe(createStartAndroidEmulatorBuildFunction, () => {
mockedMkdtemp.mockRestore();
});
it.each([
{ sources: [] },
{ sources: ['emulator-output'] },
{ sources: ['device-logcat'] },
{ sources: ['emulator-output', 'device-logcat'] },
])('preserves $sources through boot retries and clones', async ({ sources }) => {
it('preserves an explicit empty source list and one capture through boot retries and clones', async () => {
mockedAndroidUtils.waitForReadyAsync.mockRejectedValueOnce(new Error('retry boot'));
const capture = new AndroidEmulatorLogCapture();
jest.mocked(registerAndroidEmulatorLogDirectory).mockReturnValue(capture);
const capture = new AndroidEmulatorLogRing({ sources: [] });
jest.mocked(getAndroidEmulatorLogCapture).mockReturnValue(capture);
await createStep(
{ android_log_sources: sources, count: 2 },
{ log_sources: [], count: 2 },
{ DEVICE_RUN_SESSION_ID: 'session' }
).executeAsync();
expect(getAndroidEmulatorLogCapture).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ DEVICE_RUN_SESSION_ID: 'session' }),
[]
);
expect(mockedAndroidUtils.startAsync).toHaveBeenCalledTimes(4);
for (const [options] of mockedAndroidUtils.startAsync.mock.calls) {
expect(options.logSources).toEqual(sources);
expect(options.logCapture).toBe(capture);
}
});
it('rejects invalid sources before starting the emulator', async () => {
await expect(createStep({ android_log_sources: ['unknown'] }).executeAsync()).rejects.toThrow();
await expect(createStep({ log_sources: ['unknown'] }).executeAsync()).rejects.toThrow();
expect(mockedAndroidUtils.startAsync).not.toHaveBeenCalled();
});
@@ -140,7 +156,7 @@ describe(createStartAndroidEmulatorBuildFunction, () => {
deviceName: 'EasAndroidDevice01',
env: expect.any(Object),
logcatDirectory: '/tmp/logcat-directory',
logSources: ['emulator-output', 'device-logcat'],
logCapture: expect.objectContaining({ sources: ['emulator-output', 'device-logcat'] }),
});
expect(mockedAndroidUtils.waitForReadyAsync).toHaveBeenCalledWith({
env: expect.any(Object),
@@ -256,7 +272,6 @@ describe(createStartAndroidEmulatorBuildFunction, () => {
expect.objectContaining({
deviceName: 'EasAndroidDevice01',
logcatDirectory: '/tmp/logcat-directory',
logSources: ['emulator-output', 'device-logcat'],
})
);
expect(mockedAndroidUtils.startAsync).toHaveBeenNthCalledWith(
@@ -264,7 +279,6 @@ describe(createStartAndroidEmulatorBuildFunction, () => {
expect.objectContaining({
deviceName: 'EasAndroidDevice01',
logcatDirectory: '/tmp/logcat-directory',
logSources: ['emulator-output', 'device-logcat'],
})
);
expect(mockedAndroidUtils.deleteAsync).toHaveBeenCalledWith(
@@ -339,21 +353,18 @@ describe(createStartAndroidEmulatorBuildFunction, () => {
expect.objectContaining({
deviceName: 'EasAndroidDevice01',
logcatDirectory: '/tmp/logcat-directory',
logSources: ['emulator-output', 'device-logcat'],
})
);
expect(mockedAndroidUtils.startAsync).toHaveBeenCalledWith(
expect.objectContaining({
deviceName: 'eas-simulator-1',
logcatDirectory: '/tmp/logcat-directory',
logSources: ['emulator-output', 'device-logcat'],
})
);
expect(mockedAndroidUtils.startAsync).toHaveBeenCalledWith(
expect.objectContaining({
deviceName: 'eas-simulator-2',
logcatDirectory: '/tmp/logcat-directory',
logSources: ['emulator-output', 'device-logcat'],
})
);
@@ -383,13 +394,6 @@ describe(createStartAndroidEmulatorBuildFunction, () => {
);
expect(mockedAndroidUtils.deleteAsync).toHaveBeenCalledTimes(3);
expect(mockedAndroidUtils.startAsync).toHaveBeenCalledTimes(3);
expect(registerAndroidEmulatorLogDirectory).toHaveBeenCalledWith(
expect.anything(),
'/tmp/logcat-directory'
);
expect(
jest.mocked(registerAndroidEmulatorLogDirectory).mock.invocationCallOrder[0]
).toBeLessThan(mockedAndroidUtils.startAsync.mock.invocationCallOrder[0]);
});
it('outputs and uses a temporary logcat directory', async () => {
@@ -399,14 +403,9 @@ describe(createStartAndroidEmulatorBuildFunction, () => {
expect(mockedAndroidUtils.startAsync).toHaveBeenCalledWith(
expect.objectContaining({
logcatDirectory: '/tmp/logcat-directory',
logSources: ['emulator-output', 'device-logcat'],
})
);
expect(step.getOutputValueByName('logcat_directory')).toBe('/tmp/logcat-directory');
expect(registerAndroidEmulatorLogDirectory).toHaveBeenCalledWith(
step.ctx.global,
'/tmp/logcat-directory'
);
expect(mockedAndroidUtils.waitForReadyAsync).toHaveBeenCalledWith(
expect.objectContaining({
serialId: 'emulator-default',
@@ -483,4 +482,170 @@ describe(createStartAndroidEmulatorBuildFunction, () => {
}
);
});
describe('experimental emulator capture', () => {
const LIBRARY = '/tmp/package/libexpo_emulator_capture.so';
const mockedInstall = jest.mocked(installEmulatorCaptureAsync);
function captureStart(port: number) {
return {
deviceName: 'EasAndroidDevice01',
env: expect.any(Object),
logcatDirectory: '/tmp/logcat-directory',
logCapture: expect.objectContaining({ sources: ['emulator-output', 'device-logcat'] }),
consolePort: port,
extraArgs: ['-gpu', 'lavapipe'],
extraEnv: {
LD_PRELOAD: LIBRARY,
EXPO_EMULATOR_CAPTURE_SOCKET: `/tmp/job/expo-emulator-capture/emulator-${port}.sock`,
},
};
}
beforeEach(() => {
mockedInstall.mockReset().mockResolvedValue(LIBRARY);
mockedAndroidUtils.findFreeConsolePortAsync
.mockReset()
.mockResolvedValueOnce(5554)
.mockResolvedValueOnce(5556);
mockedAndroidUtils.startAsync.mockResolvedValue(createStartResult('emulator-5554'));
});
it('preloads the agent and turns the capture on for expo-device-hub', async () => {
const step = createStep(
{ experimental_emulator_capture_version: '0.1.0' },
{ TMPDIR: '/tmp/job' }
);
await step.executeAsync();
expect(mockedInstall).toHaveBeenCalledWith({
version: '0.1.0',
env: expect.any(Object),
logger: expect.anything(),
});
expect(mockedAndroidUtils.startAsync).toHaveBeenCalledWith(captureStart(5554));
expect(step.globalCtx.env).toMatchObject({
EXPO_DEVICE_HUB_EXPERIMENTAL_EMULATOR_CAPTURE: '1',
EXPO_DEVICE_HUB_EMULATOR_CAPTURE_LIBRARY: LIBRARY,
});
expect(stepLogger(step).info).toHaveBeenCalledWith(
'emulator-5554 preloads [email protected] with -gpu lavapipe, and its agent socket is /tmp/job/expo-emulator-capture/emulator-5554.sock. Later steps start expo-device-hub with the emulator capture on.'
);
});
it('uses the temporary directory rule of Node when TMPDIR is empty', async () => {
await createStep(
{ experimental_emulator_capture_version: '0.1.0' },
{ TMPDIR: '', TMP: '/tmp/from-tmp' }
).executeAsync();
expect(mockedAndroidUtils.startAsync).toHaveBeenCalledWith(
expect.objectContaining({
extraEnv: expect.objectContaining({
EXPO_EMULATOR_CAPTURE_SOCKET: '/tmp/from-tmp/expo-emulator-capture/emulator-5554.sock',
}),
})
);
});
it('uses /tmp when the job env names no temporary directory', async () => {
await createStep({ experimental_emulator_capture_version: '0.1.0' }).executeAsync();
expect(mockedAndroidUtils.startAsync).toHaveBeenCalledWith(
expect.objectContaining({
extraEnv: expect.objectContaining({
EXPO_EMULATOR_CAPTURE_SOCKET: '/tmp/expo-emulator-capture/emulator-5554.sock',
}),
})
);
});
it('does not turn the capture on when the emulator runs on another console port', async () => {
mockedAndroidUtils.startAsync.mockResolvedValue(createStartResult('emulator-5560'));
const step = createStep(
{ experimental_emulator_capture_version: '0.1.0' },
{ TMPDIR: '/tmp/job' }
);
await step.executeAsync();
expect(step.globalCtx.env.EXPO_DEVICE_HUB_EXPERIMENTAL_EMULATOR_CAPTURE).toBeUndefined();
expect(stepLogger(step).warn).toHaveBeenCalledWith(
expect.stringContaining('emulator-5560 does not use console port 5554')
);
});
it('keeps a library that the job already preloads, after the agent', async () => {
await createStep(
{ experimental_emulator_capture_version: '0.1.0' },
{ TMPDIR: '/tmp/job', LD_PRELOAD: '/opt/other.so' }
).executeAsync();
expect(mockedAndroidUtils.startAsync).toHaveBeenCalledWith(
expect.objectContaining({
extraEnv: expect.objectContaining({ LD_PRELOAD: `${LIBRARY}:/opt/other.so` }),
})
);
});
it('chooses a new console port for each start attempt', async () => {
mockedAndroidUtils.startAsync
.mockRejectedValueOnce(new Error('emulator did not start'))
.mockResolvedValue(createStartResult('emulator-5556'));
await createStep(
{ experimental_emulator_capture_version: '0.1.0' },
{ TMPDIR: '/tmp/job' }
).executeAsync();
expect(mockedAndroidUtils.startAsync).toHaveBeenNthCalledWith(2, captureStart(5556));
});
it('starts the emulator as without the input when the install fails', async () => {
mockedInstall.mockResolvedValue(undefined);
const step = createStep({ experimental_emulator_capture_version: '0.1.0' });
await step.executeAsync();
expect(mockedAndroidUtils.startAsync).toHaveBeenCalledWith({
deviceName: 'EasAndroidDevice01',
env: expect.any(Object),
logcatDirectory: '/tmp/logcat-directory',
logCapture: expect.objectContaining({ sources: ['emulator-output', 'device-logcat'] }),
});
expect(mockedAndroidUtils.findFreeConsolePortAsync).not.toHaveBeenCalled();
expect(step.globalCtx.env.EXPO_DEVICE_HUB_EXPERIMENTAL_EMULATOR_CAPTURE).toBeUndefined();
// The session step still rejects session types without the capture.
expect(step.globalCtx.env.EAS_EXPERIMENTAL_EMULATOR_CAPTURE_VERSION).toBe('0.1.0');
});
it('installs nothing without the input', async () => {
const step = createStep();
await step.executeAsync();
expect(mockedInstall).not.toHaveBeenCalled();
expect(mockedAndroidUtils.findFreeConsolePortAsync).not.toHaveBeenCalled();
expect(step.globalCtx.env.EXPO_DEVICE_HUB_EXPERIMENTAL_EMULATOR_CAPTURE).toBeUndefined();
expect(step.globalCtx.env.EAS_EXPERIMENTAL_EMULATOR_CAPTURE_VERSION).toBeUndefined();
});
it('rejects the capture for more than one emulator before it starts one', async () => {
await expect(
createStep({ experimental_emulator_capture_version: '0.1.0', count: 2 }).executeAsync()
).rejects.toThrow('experimental_emulator_capture_version supports one emulator');
expect(mockedInstall).not.toHaveBeenCalled();
expect(mockedAndroidUtils.startAsync).not.toHaveBeenCalled();
});
it('rejects a version that is not an exact npm version or a dist-tag', async () => {
await expect(
createStep({ experimental_emulator_capture_version: 'npm:[email protected]' }).executeAsync()
).rejects.toThrow('must be an npm version or dist-tag of expo-emulator-capture');
expect(mockedInstall).not.toHaveBeenCalled();
});
});
});
@@ -1,7 +1,10 @@
import { type WarmIosSession } from '../../utils/warmIosSession';
import { BuildRuntimePlatform, type BuildStepContext } from '@expo/steps';
import spawn from '@expo/turtle-spawn';
import { vol } from 'memfs';
import plist from 'plist';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import * as timersPromises from 'node:timers/promises';
@@ -9,6 +12,7 @@ import { createGlobalContextMock } from '../../../__tests__/utils/context';
import { type CustomBuildContext } from '../../../customBuildContext';
import { AndroidEmulatorUtils } from '../../../utils/AndroidEmulatorUtils';
import { IosSimulatorUtils } from '../../../utils/IosSimulatorUtils';
import { PackageManager, resolveConfiguredPackageManager } from '../../../utils/packageManager';
import * as processes from '../../../utils/processes';
import { sleepAsync } from '../../../utils/retry';
import { turtleFetch } from '../../../utils/turtleFetch';
@@ -98,6 +102,46 @@ jest.mock('../../utils/localEgressSession', () => ({
}));
const logger = { info: jest.fn(), warn: jest.fn() } as never;
const preparedHome = path.join(os.homedir(), 'Library/Caches/expo-simulator-startup/appium');
const preparedManifest = path.join(path.dirname(preparedHome), 'prepared.json');
const preparedBin = path.join(preparedHome, 'node_modules', '.bin', 'appium');
const preparedRunner = path.join(
preparedHome,
'preinstalled-wda',
'WebDriverAgentRunner-Runner.app'
);
const driverList = ['driver', 'list', '--installed', '--json'];
/** Today's `driver list` output: the prepared home lists xcuitest, a new home lists nothing. */
function driverListStdout(command: string): string {
return JSON.stringify(command === preparedBin ? { xcuitest: { installed: true } } : {});
}
/** Writes the Appium home that `simulator-launcher prefetch` prepares for reuse. */
function writePreparedHome(): void {
fs.mkdirSync(path.dirname(preparedBin), { recursive: true });
fs.writeFileSync(preparedBin, '');
writeInstalledVersion('appium', '3.9.0');
writeInstalledVersion('appium-xcuitest-driver', '12.22.8');
fs.mkdirSync(preparedRunner, { recursive: true });
fs.writeFileSync(
path.join(preparedRunner, 'Info.plist'),
plist.build({ CFBundleExecutable: 'Runner' })
);
fs.writeFileSync(path.join(preparedRunner, 'Runner'), 'executable', { mode: 0o755 });
writePreparedManifest({ version: '3.9.0', xcuitest: '12.22.8', home: preparedHome });
}
function writePreparedManifest(appium: unknown): void {
fs.writeFileSync(preparedManifest, `${JSON.stringify({ tools: { appium } })}\n`);
}
function writeInstalledVersion(name: string, version: string): void {
const directory = path.join(preparedHome, 'node_modules', name);
fs.mkdirSync(directory, { recursive: true });
fs.writeFileSync(path.join(directory, 'package.json'), JSON.stringify({ name, version }));
}
describe(resolveAppium3VersionSpec, () => {
it('uses the worker-supported Appium 3 version by default', () => {
@@ -172,9 +216,9 @@ describe(installAppiumAsync, () => {
beforeEach(() => {
jest.clearAllMocks();
jest.mocked(watchDeviceRunSessionStartup).mockImplementation(createStartupWatchMock);
jest.mocked(spawn).mockImplementation((async (_command: string, args: string[]) => {
jest.mocked(spawn).mockImplementation((async (command: string, args: string[]) => {
if (args.includes('--json')) {
return { stdout: JSON.stringify({}) };
return { stdout: driverListStdout(command) };
}
return { stdout: '' };
}) as never);
@@ -208,6 +252,255 @@ describe(installAppiumAsync, () => {
}
});
it('uses the xcuitest home prefetched without installing', async () => {
writePreparedHome();
const info = jest.fn();
const result = await installAppiumAsync({
versionSpec: '^3',
driverName: 'xcuitest',
env: { EXISTING: 'value' },
logger: { info } as never,
});
expect(jest.mocked(spawn).mock.calls).toEqual([
[
preparedBin,
driverList,
{ env: { EXISTING: 'value', APPIUM_HOME: preparedHome }, stdio: 'pipe' },
],
]);
expect(info).toHaveBeenCalledWith(
'Using the prefetched Appium home (appium 3.9.0, xcuitest 12.22.8).'
);
expect(result).toEqual({
appiumHome: preparedHome,
appiumBinPath: preparedBin,
appiumEnv: { EXISTING: 'value', APPIUM_HOME: preparedHome },
prepared: true,
});
const env = { EAS_OVERRIDE_PACKAGE_MANAGER: 'nope' };
const expected = (() => {
try {
resolveConfiguredPackageManager(env, PackageManager.NPM);
} catch (error) {
return error;
}
})();
const onError = jest.fn();
await expect(
installAppiumAsync({ versionSpec: '^3', driverName: 'xcuitest', env, logger, onError })
).rejects.toEqual(expected);
expect(onError).toHaveBeenCalledWith(expected);
expect(jest.mocked(spawn).mock.calls.map(([, args]) => args)).toEqual([driverList, driverList]);
});
it('reuses WDA with binary bundle metadata', async () => {
writePreparedHome();
fs.writeFileSync(
path.join(preparedRunner, 'Info.plist'),
Buffer.from(
'YnBsaXN0MDDRAQJfEBJDRkJ1bmRsZUV4ZWN1dGFibGVWUnVubmVyCAsgAAAAAAAAAQEAAAAAAAAAAwAAAAAAAAAAAAAAAAAAACc=',
'base64'
)
);
const result = await installAppiumAsync({
versionSpec: '^3',
driverName: 'xcuitest',
env: {},
logger,
});
expect(result.prepared).toBe(true);
});
it.each([
['a version spec it does not satisfy', { versionSpec: '3.5.0' }, () => {}],
['the uiautomator2 driver', { driverName: 'uiautomator2' as const }, () => {}],
['no prepared.json', {}, () => fs.rmSync(preparedManifest)],
['an invalid prepared.json', {}, () => fs.writeFileSync(preparedManifest, 'not json')],
['a prepared.json without xcuitest', {}, () => writePreparedManifest({ version: '3.9.0' })],
[
'an older per-tool manifest',
{},
() => {
fs.rmSync(preparedManifest);
fs.writeFileSync(
path.join(preparedHome, 'prepared.json'),
JSON.stringify({
appium: '3.9.0',
xcuitest: '12.22.8',
home: preparedHome,
})
);
},
],
[
'a home prepared at another path',
{},
() =>
writePreparedManifest({
version: '3.9.0',
xcuitest: '12.22.8',
home: '/Users/other/appium',
}),
],
['another installed Appium', {}, () => writeInstalledVersion('appium', '2.19.0')],
[
'another installed xcuitest driver',
{},
() => writeInstalledVersion('appium-xcuitest-driver', '12.0.0'),
],
[
'no xcuitest driver',
{},
() =>
fs.rmSync(path.join(preparedHome, 'node_modules', 'appium-xcuitest-driver'), {
recursive: true,
}),
],
['no runner', {}, () => fs.rmSync(preparedRunner, { recursive: true })],
['no runner metadata', {}, () => fs.rmSync(path.join(preparedRunner, 'Info.plist'))],
[
'invalid runner metadata',
{},
() => fs.writeFileSync(path.join(preparedRunner, 'Info.plist'), 'invalid'),
],
['no runner executable', {}, () => fs.rmSync(path.join(preparedRunner, 'Runner'))],
[
'a non-executable runner binary',
{},
() => fs.chmodSync(path.join(preparedRunner, 'Runner'), 0o644),
],
['an empty runner binary', {}, () => fs.writeFileSync(path.join(preparedRunner, 'Runner'), '')],
[
'a directory as runner binary',
{},
() => {
fs.rmSync(path.join(preparedRunner, 'Runner'));
fs.mkdirSync(path.join(preparedRunner, 'Runner'));
},
],
[
'an executable outside the bundle',
{},
() =>
fs.writeFileSync(
path.join(preparedRunner, 'Info.plist'),
plist.build({ CFBundleExecutable: '../outside' })
),
],
['an unreadable runner', {}, () => fs.chmodSync(preparedRunner, 0o000)],
[
'a runner that is a file',
{},
() => {
fs.rmSync(preparedRunner, { recursive: true });
// Readable and executable, so only the directory check rejects it.
fs.writeFileSync(preparedRunner, '', { mode: 0o755 });
},
],
])('installs as before for %s', async (_name, options, breakHome) => {
writePreparedHome();
breakHome();
const before = vol.toJSON(preparedHome);
const versionSpec = 'versionSpec' in options ? options.versionSpec : '^3';
const resolveRequestedVersionAsync = jest.fn(async () => {
throw new Error('registry unavailable');
});
const result = await installAppiumAsync({
versionSpec,
resolveRequestedVersionAsync,
driverName: 'driverName' in options ? options.driverName : 'xcuitest',
env: {},
logger,
});
try {
expect(spawn).toHaveBeenNthCalledWith(
1,
'npm',
['install', '--no-audit', `appium@${versionSpec}`],
expect.objectContaining({ cwd: result.appiumHome })
);
expect(path.basename(result.appiumHome)).toMatch(/^eas-appium-home-/);
expect(result.prepared).toBe(false);
expect(resolveRequestedVersionAsync).not.toHaveBeenCalled();
expect(vol.toJSON(preparedHome)).toEqual(before);
} finally {
await fs.promises.rm(result.appiumHome, { recursive: true, force: true });
}
});
it.each([
['a driver list without xcuitest', async () => ({ stdout: '{}' })],
['a failed driver list', async () => Promise.reject(new Error('appium exited with 1.'))],
])('installs as before after %s in the prepared home', async (_name, list) => {
writePreparedHome();
jest.mocked(spawn).mockImplementationOnce(list as never);
const before = vol.toJSON(preparedHome);
const result = await installAppiumAsync({
versionSpec: '^3',
driverName: 'xcuitest',
env: {},
logger,
});
try {
expect(jest.mocked(spawn).mock.calls.slice(0, 2)).toEqual([
[preparedBin, driverList, expect.objectContaining({ stdio: 'pipe' })],
[
'npm',
['install', '--no-audit', 'appium@^3'],
expect.objectContaining({ cwd: result.appiumHome }),
],
]);
expect(result.prepared).toBe(false);
expect(vol.toJSON(preparedHome)).toEqual(before);
} finally {
await fs.promises.rm(result.appiumHome, { recursive: true, force: true });
}
});
it('kills the prepared-home driver list on a stop and installs nothing', async () => {
writePreparedHome();
const before = vol.toJSON(preparedHome);
const controller = new AbortController();
const failure = new Error('session stopped');
const child = { pid: 4242, kill: jest.fn() };
let finishList!: (error: Error) => void;
let listStarted!: () => void;
const started = new Promise<void>(resolve => {
listStarted = resolve;
});
jest.mocked(spawn).mockImplementationOnce(() => {
listStarted();
return Object.assign(
new Promise((_resolve, reject) => {
finishList = reject;
}),
{ child }
) as never;
});
const killGroup = jest.spyOn(processes, 'killProcessGroup').mockImplementation(() => {});
const running = installAppiumAsync({
versionSpec: '^3',
driverName: 'xcuitest',
env: {},
logger,
signal: controller.signal,
});
running.catch(() => {});
try {
await started;
controller.abort(failure);
expect(killGroup).toHaveBeenCalledWith(child, 'SIGKILL');
finishList(new Error('killed'));
await expect(running).rejects.toBe(failure);
expect(spawn).toHaveBeenCalledTimes(1);
expect(vol.toJSON(preparedHome)).toEqual(before);
} finally {
finishList?.(new Error('test cleanup'));
killGroup.mockRestore();
}
});
it('installs Appium with bun add when EAS_OVERRIDE_PACKAGE_MANAGER is bun', async () => {
const result = await installAppiumAsync({
versionSpec: '3.5.0',
@@ -302,6 +595,115 @@ describe('createStartAppiumRemoteSessionBuildFunction', () => {
});
});
it.each(
[BuildRuntimePlatform.DARWIN, BuildRuntimePlatform.LINUX].flatMap(platform =>
['^3', '3.x'].map(version => [platform, version] as const)
)
)(
'starts cold Appium on %s with cached installer range %s and no registry lookup',
async (runtimePlatform, packageVersion) => {
// Android must ignore prepared XCUITest files too.
if (runtimePlatform === BuildRuntimePlatform.LINUX) {
writePreparedHome();
}
jest.mocked(spawn).mockImplementation((async (_command: string, args: string[]) => {
if (args[0] === 'view') {
throw new Error('registry unavailable');
}
return { stdout: '{}' };
}) as never);
jest
.mocked(IosSimulatorUtils.getAvailableDevicesAsync)
.mockResolvedValue([{ udid: 'simulator' }] as never);
jest
.mocked(AndroidEmulatorUtils.getAttachedDevicesAsync)
.mockResolvedValue([{ serialId: 'emulator-5554', state: 'device' }] as never);
const launched = new Error('launch captured');
jest.mocked(spawnDetached).mockImplementation(() => {
throw launched;
});
const buildFunction = createStartAppiumRemoteSessionBuildFunction({} as CustomBuildContext);
await expect(
buildFunction.fn!(
{ logger, global: { runtimePlatform } } as unknown as BuildStepContext,
{
inputs: {
package_version: { value: packageVersion },
max_idle_time_minutes: { value: undefined },
},
outputs: {},
env: {
DEVICE_RUN_SESSION_ID: 'session',
EAS_SIMULATOR_NGROK_TUNNEL_DOMAIN: 'example.test',
NGROK_AUTHTOKEN: 'token',
EAS_OVERRIDE_PACKAGE_MANAGER: 'bun',
},
} as never
)
).rejects.toBe(launched);
expect(jest.mocked(spawn).mock.calls.some(([, args]) => args[0] === 'view')).toBe(false);
expect(spawn).toHaveBeenCalledWith(
'bun',
['add', `appium@${packageVersion}`],
expect.anything()
);
}
);
it.each(
['latest', '^3', '3.x'].flatMap(requested =>
['3.9.0', '3.10.0'].map(latest => [requested, latest])
)
)('checks %s before using the prepared Appium version (%s)', async (requested, latest) => {
writePreparedHome();
const before = vol.toJSON(preparedHome);
jest.mocked(spawn).mockImplementation((async (command: string, args: string[]) => ({
stdout:
args[0] === 'view'
? JSON.stringify(latest)
: args.includes('--json')
? driverListStdout(command)
: '',
})) as never);
jest
.mocked(IosSimulatorUtils.getAvailableDevicesAsync)
.mockResolvedValue([{ udid: 'simulator' }] as never);
const launched = new Error('launch captured');
jest.mocked(spawnDetached).mockImplementation(() => {
throw launched;
});
const buildFunction = createStartAppiumRemoteSessionBuildFunction({} as CustomBuildContext);
await expect(
buildFunction.fn!(
{
logger,
global: { runtimePlatform: BuildRuntimePlatform.DARWIN },
} as unknown as BuildStepContext,
{
inputs: {
package_version: { value: requested },
max_idle_time_minutes: { value: undefined },
},
outputs: {},
env: {
DEVICE_RUN_SESSION_ID: 'session',
EAS_SIMULATOR_NGROK_TUNNEL_DOMAIN: 'example.test',
NGROK_AUTHTOKEN: 'token',
},
} as never
)
).rejects.toBe(launched);
const installs = jest.mocked(spawn).mock.calls.filter(([, args]) => args[0] === 'install');
if (latest === '3.9.0') {
expect(installs).toHaveLength(0);
expect(jest.mocked(spawnDetached).mock.calls[0][0].env.APPIUM_HOME).toBe(preparedHome);
} else {
expect(installs).toHaveLength(1);
expect(installs[0][1]).toContain('[email protected]');
}
expect(vol.toJSON(preparedHome)).toEqual(before);
});
it('claims the warm Simulator for Appium without its package version', async () => {
jest.mocked(runOnWarmIosSimulatorAsync).mockResolvedValue(undefined);
const buildFunction = createStartAppiumRemoteSessionBuildFunction({} as CustomBuildContext, {
@@ -369,8 +771,8 @@ describe('createStartAppiumRemoteSessionBuildFunction session lifecycle', () =>
runtime: 'com.apple.CoreSimulator.SimRuntime.iOS-26-5',
state: 'Shutdown',
} as never);
jest.mocked(spawn).mockImplementation((async (_command: string, args: string[]) => ({
stdout: args.includes('--json') ? '{}' : '',
jest.mocked(spawn).mockImplementation((async (command: string, args: string[]) => ({
stdout: args.includes('--json') ? driverListStdout(command) : '',
})) as never);
jest
.mocked(AndroidEmulatorUtils.getAttachedDevicesAsync)
@@ -448,6 +850,26 @@ describe('createStartAppiumRemoteSessionBuildFunction session lifecycle', () =>
);
}
it('does not fail a session when only the Appium tunnel cannot stop', async () => {
const tunnelError = new Error('Ngrok tunnel stop timed out after 4000ms.');
const logger = { info: jest.fn(), warn: jest.fn() };
stopAppium.mockResolvedValueOnce(undefined);
jest.mocked(startNgrokTunnelAsync).mockResolvedValueOnce({
url: 'https://appium-abc.tunnel.example.com',
subdomainId: 'appium-abc',
stopAsync: jest.fn().mockRejectedValue(tunnelError),
});
await expect(runSessionAsync(logger)).resolves.toBeUndefined();
expect(stopAppium).toHaveBeenCalledTimes(1);
expect(finishHost).toHaveBeenCalledTimes(1);
expect(logger.warn).toHaveBeenCalledWith(
{ err: tunnelError },
'Could not stop the Appium tunnel during remote session teardown.'
);
});
it('does not allocate Appium or a host after parent cancellation during Xcode selection', async () => {
const controller = new AbortController();
const failure = new Error('parent step cancelled');
@@ -625,6 +1047,73 @@ describe('createStartAppiumRemoteSessionBuildFunction session lifecycle', () =>
return stopWarm;
}
it.each(['cancelled lookup', 'AbortError lookup', 'resolved lookup'])(
'recovers from failed warm adoption with a %s',
async stage => {
writePreparedHome();
const stopWarm = mockWarmSession();
stopAppium.mockResolvedValue(undefined);
const adoptionError = new WarmSessionAdoptionError();
let failHost!: (error: Error) => void;
jest.mocked(startDeviceSessionHostAsync).mockReturnValueOnce(
new Promise((_resolve, reject) => {
failHost = reject;
})
);
let lookups = 0;
jest.mocked(spawn).mockImplementation((async (command, args, options) => {
if (args[0] !== 'view') {
return { stdout: args.includes('--json') ? driverListStdout(command) : '' };
}
lookups++;
if (lookups === 1 && stage !== 'resolved lookup') {
return await new Promise((_resolve, reject) => {
options!.signal!.addEventListener(
'abort',
() => {
reject(
stage === 'AbortError lookup'
? new DOMException('Aborted', 'AbortError')
: options!.signal!.reason
);
},
{ once: true }
);
failHost(adoptionError);
});
}
return { stdout: JSON.stringify('3.9.0') };
}) as typeof spawn);
if (stage === 'resolved lookup') {
const process = jest.mocked(spawnDetached).getMockImplementation()!;
jest.mocked(spawnDetached).mockImplementationOnce(options => {
failHost(adoptionError);
return process(options);
});
}
await expect(
runSessionAsync(
logger,
undefined,
BuildRuntimePlatform.DARWIN,
{
boot_simulator: { value: true },
device_identifier: { value: 'iPhone 17' },
package_version: { value: '^3' },
},
true
)
).resolves.toBeUndefined();
expect(lookups).toBe(stage === 'resolved lookup' ? 1 : 2);
expect(stopWarm).toHaveBeenCalledTimes(1);
expect(startDeviceSessionHostAsync).toHaveBeenCalledTimes(2);
expect(spawnDetached).toHaveBeenCalledTimes(stage === 'resolved lookup' ? 2 : 1);
expect(fs.existsSync(preparedRunner)).toBe(true);
}
);
it.each(['event collection', 'Appium process'])(
'waits for warm %s teardown before finishing the session host',
async stage => {
@@ -1102,6 +1591,31 @@ describe('createStartAppiumRemoteSessionBuildFunction session lifecycle', () =>
);
});
it('a Darwin session uses the prepared Appium home and keeps it', async () => {
stopAppium.mockResolvedValue(undefined);
writePreparedHome();
jest.mocked(IosSimulatorUtils.getAvailableDevicesAsync).mockResolvedValue([
{
udid: 'chosen-ios-udid',
runtime: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',
} as never,
]);
await runSessionAsync(
{ info: jest.fn(), warn: jest.fn() },
undefined,
BuildRuntimePlatform.DARWIN
);
expect(jest.mocked(spawnDetached).mock.calls[0][0].env.APPIUM_HOME).toBe(preparedHome);
expect(preparePreinstalledWdaAsync).toHaveBeenCalledWith(
expect.objectContaining({ appiumHome: preparedHome, prepared: true })
);
expect(jest.mocked(spawn).mock.calls.map(([command, args]) => [command, args])).toEqual([
[preparedBin, driverList],
]);
expect(stopAppium).toHaveBeenCalledTimes(1);
expect(fs.existsSync(preparedManifest)).toBe(true);
});
it('starts serve-sim on the selected iOS device while Appium installation is pending', async () => {
stopAppium.mockResolvedValue(undefined);
jest.mocked(selectXcodeDeveloperDirectoryAsync).mockClear();
@@ -322,6 +322,29 @@ describe('createStartArgentRemoteSessionBuildFunction orchestration', () => {
expect(uploadRemoteSessionConfigAsync).not.toHaveBeenCalled();
});
it('uses the resolved Argent version after a warm mismatch', async () => {
jest
.mocked(runOnWarmIosSimulatorAsync)
.mockImplementation((_claim, run) => run(undefined, '999.1.0'));
await createStartArgentRemoteSessionBuildFunction({} as CustomBuildContext, { warm: true }).fn!(
{
logger: { info: jest.fn(), warn: jest.fn(), child: jest.fn().mockReturnThis() },
global: { runtimePlatform: BuildRuntimePlatform.DARWIN },
} as never,
{
inputs: {
package_version: { value: 'latest' },
max_idle_time_minutes: { value: undefined },
},
outputs: {},
env: {},
} as never
);
expect(spawnDetached).toHaveBeenCalledWith(
expect.objectContaining({ args: expect.arrayContaining(['@swmansion/[email protected]']) })
);
});
it('keeps watching startup when warm adoption retries cold', async () => {
const ctx = {} as CustomBuildContext;
const logger = { info: jest.fn(), warn: jest.fn(), child: jest.fn().mockReturnThis() };
@@ -644,7 +667,7 @@ describe('createStartArgentRemoteSessionBuildFunction orchestration', () => {
['succeeded', false],
['failed', true],
])(
'fails after stopping the host and tools when the tools tunnel cannot close and the session %s',
'stops the host and tools when the tools tunnel cannot close and the session %s',
async (_description, sessionFails) => {
const closeError = new Error('ngrok close failed');
const sessionError = new Error('session failed');
@@ -654,23 +677,26 @@ describe('createStartArgentRemoteSessionBuildFunction orchestration', () => {
}
const logger = { info: jest.fn(), warn: jest.fn() };
const buildFunction = createStartArgentRemoteSessionBuildFunction({} as CustomBuildContext);
// The tunnel may still be serving, so its failure fails a session that otherwise succeeded.
await expect(
buildFunction.fn!(
{
logger,
global: { runtimePlatform: BuildRuntimePlatform.LINUX },
} as unknown as BuildStepContext,
{
inputs: {
package_version: { value: undefined },
max_idle_time_minutes: { value: undefined },
},
outputs: {},
env: {},
} as never
)
).rejects.toBe(sessionFails ? sessionError : closeError);
// A stopped tunnel's proxy drops every connection, so its failure does not fail a session.
const running = buildFunction.fn!(
{
logger,
global: { runtimePlatform: BuildRuntimePlatform.LINUX },
} as unknown as BuildStepContext,
{
inputs: {
package_version: { value: undefined },
max_idle_time_minutes: { value: undefined },
},
outputs: {},
env: {},
} as never
);
if (sessionFails) {
await expect(running).rejects.toBe(sessionError);
} else {
await expect(running).resolves.toBeUndefined();
}
expect(mockTunnelStopAsync).toHaveBeenCalledTimes(1);
expect(mockPreviewStopAsync).toHaveBeenCalledTimes(1);
expect(mockStopAsync).toHaveBeenCalledTimes(1);
@@ -679,17 +705,13 @@ describe('createStartArgentRemoteSessionBuildFunction orchestration', () => {
{ err: closeError },
'Could not stop the Argent tunnel during remote session teardown.'
);
expect(jest.mocked(Sentry.capture).mock.calls).toEqual(
sessionFails
? [
[
'Could not stop the Argent tunnel after the remote session failed',
closeError,
{ level: 'warning' },
],
]
: []
);
expect(jest.mocked(Sentry.capture).mock.calls).toEqual([
[
`Could not stop the Argent tunnel after the remote session ${sessionFails ? 'failed' : 'ended'}`,
closeError,
{ level: 'warning' },
],
]);
}
);
@@ -1,11 +1,51 @@
import { SystemError, UserError } from '@expo/eas-build-job';
import { Client, fetchExchange } from '@urql/core';
import {
ArchiveSourceType,
EnvironmentSecretType,
SystemError,
UserError,
} from '@expo/eas-build-job';
import fetch from 'node-fetch';
import { stripRepositoryCredentialsAsync } from '../../../common/git';
import * as sandboxDaemon from '../../utils/sandboxDaemon';
import { SandboxWorkerApi } from '../../utils/sandboxWorkerApi';
import { createStartSandboxBuildFunction } from '../startSandbox';
import { createStartSandboxBuildFunction, markSandboxReadyAsync } from '../startSandbox';
const { AbortError, Response } = jest.requireActual('node-fetch') as typeof import('node-fetch');
jest.mock('../../../common/git');
const checkedOutStepCtx = { logger: {}, global: { wasCheckedOut: () => true } } as any;
const notCheckedOutStepCtx = { logger: {}, global: { wasCheckedOut: () => false } } as any;
const URL_JOB = {
projectArchive: { type: ArchiveSourceType.URL, url: 'https://example.com/project.tar.gz' },
};
const context = {
job: {
...URL_JOB,
secrets: {
environmentSecrets: [
{
name: 'EAS_SANDBOX_WORKER_TOKEN',
type: EnvironmentSecretType.STRING,
value: 'worker-token',
},
],
},
},
env: {},
expoApiV2BaseUrl: 'https://api.expo.test/v2/',
mcpServerUrl: 'ws://localhost:8787',
};
const inputs = { sandbox_id: { value: 'sandbox-id' } };
describe('sandbox build functions', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it.each([
{ completion: 'duration', duration: 0.02 },
{ completion: 'cancellation', duration: 60 },
@@ -16,49 +56,41 @@ describe('sandbox build functions', () => {
const controller = new AbortController();
let ready!: () => void;
const stopAsync = jest.fn(async () => {});
const start = jest.spyOn(sandboxDaemon, 'startSandboxDaemonAsync').mockResolvedValue({
jest.spyOn(sandboxDaemon, 'startSandboxDaemonAsync').mockResolvedValue({
ready: new Promise<void>(resolve => {
ready = resolve;
}),
stopAsync,
});
const mutation = jest.fn(() => ({ toPromise: async () => ({ data: {} }) }));
const markReady = jest
.spyOn(SandboxWorkerApi.prototype, 'markReadyAsync')
.mockResolvedValue(undefined);
const logger = { info: jest.fn(), child: jest.fn() };
logger.child.mockReturnValue(logger);
const fn = createStartSandboxBuildFunction({
mcpServerUrl: 'ws://localhost:8787',
graphqlClient: { mutation },
} as any);
try {
const pending = fn.fn!({ logger } as any, {
inputs: {
sandbox_id: { value: 'sandbox-id' },
max_duration_seconds: { value: duration },
},
outputs: {},
env: { __EAS_SANDBOX_MCP_TOKEN: 'token' },
signal: controller.signal,
});
await new Promise(resolve => setTimeout(resolve, 40));
expect(mutation).not.toHaveBeenCalled();
const fn = createStartSandboxBuildFunction(context as any);
const pending = fn.fn!({ logger } as any, {
inputs: { ...inputs, max_duration_seconds: { value: duration } },
outputs: {},
env: {},
signal: controller.signal,
});
await new Promise(resolve => setTimeout(resolve, 40));
expect(markReady).not.toHaveBeenCalled();
expect(stopAsync).not.toHaveBeenCalled();
ready();
if (completion === 'cancellation') {
await new Promise(resolve => setImmediate(resolve));
expect(stopAsync).not.toHaveBeenCalled();
ready();
if (completion === 'cancellation') {
await new Promise(resolve => setImmediate(resolve));
expect(stopAsync).not.toHaveBeenCalled();
controller.abort();
}
await pending;
expect(mutation).toHaveBeenCalledTimes(1);
expect(stopAsync).toHaveBeenCalledTimes(1);
const timeoutMessage = `Sandbox reached its maximum runtime of ${duration} seconds. Stopping.`;
if (completion === 'duration') {
expect(logger.info).toHaveBeenCalledWith(timeoutMessage);
} else {
expect(logger.info).not.toHaveBeenCalledWith(timeoutMessage);
}
} finally {
start.mockRestore();
controller.abort();
}
await pending;
expect(markReady).toHaveBeenCalledTimes(1);
expect(stopAsync).toHaveBeenCalledTimes(1);
const timeoutMessage = `Sandbox reached its maximum runtime of ${duration} seconds. Stopping.`;
if (completion === 'duration') {
expect(logger.info).toHaveBeenCalledWith(timeoutMessage);
} else {
expect(logger.info).not.toHaveBeenCalledWith(timeoutMessage);
}
}
);
@@ -67,177 +99,221 @@ describe('sandbox build functions', () => {
'rejects invalid maximum duration %s before starting the daemon',
async duration => {
const start = jest.spyOn(sandboxDaemon, 'startSandboxDaemonAsync');
const fn = createStartSandboxBuildFunction({
mcpServerUrl: 'ws://localhost:8787',
} as any);
try {
const result = fn.fn!({} as any, {
inputs: {
sandbox_id: { value: 'sandbox-id' },
max_duration_seconds: { value: duration },
},
outputs: {},
env: { __EAS_SANDBOX_MCP_TOKEN: 'token' },
});
await expect(result).rejects.toBeInstanceOf(UserError);
await expect(result).rejects.toThrow(
`Invalid sandbox maximum duration: ${duration}. Provide a finite number greater than zero, or omit max_duration_seconds.`
);
expect(start).not.toHaveBeenCalled();
} finally {
start.mockRestore();
}
const fn = createStartSandboxBuildFunction(context as any);
const result = fn.fn!({} as any, {
inputs: { ...inputs, max_duration_seconds: { value: duration } },
outputs: {},
env: {},
});
await expect(result).rejects.toBeInstanceOf(UserError);
await expect(result).rejects.toThrow(
`Invalid sandbox maximum duration: ${duration}. Provide a finite number greater than zero, or omit max_duration_seconds.`
);
expect(start).not.toHaveBeenCalled();
}
);
it('aborts an active ready request and keeps its authentication headers', async () => {
it('connects with the worker token from the job secrets, which the step env does not have', async () => {
const env = { PREPARED_BY_EARLIER_STEP: 'value' };
const startupError = new Error('stop after checking options');
const start = jest
.spyOn(sandboxDaemon, 'startSandboxDaemonAsync')
.mockRejectedValue(startupError);
const fn = createStartSandboxBuildFunction(context as any);
await expect(fn.fn!({ logger: {} } as any, { inputs, outputs: {}, env })).rejects.toBe(
startupError
);
expect(start.mock.calls[0][0]).toMatchObject({ credential: 'worker-token', env });
});
it('does not mark the sandbox ready if startup was canceled', async () => {
const controller = new AbortController();
const stopAsync = jest.fn(async () => {});
jest.spyOn(sandboxDaemon, 'startSandboxDaemonAsync').mockImplementation(async options => {
expect(options.signal).toBe(controller.signal);
controller.abort();
return { ready: Promise.resolve(), stopAsync };
});
const fn = createStartSandboxBuildFunction(context as any);
await expect(
fn.fn!({ logger: {} } as any, { inputs, outputs: {}, env: {}, signal: controller.signal })
).rejects.toMatchObject({ name: 'AbortError' });
expect(fetch).not.toHaveBeenCalled();
expect(stopAsync).toHaveBeenCalledTimes(1);
});
it('marks the sandbox ready with only the worker token and aborts the request when canceled', async () => {
const controller = new AbortController();
const stopAsync = jest.fn(async () => {});
jest
.spyOn(sandboxDaemon, 'startSandboxDaemonAsync')
.mockResolvedValue({ ready: Promise.resolve(), stopAsync });
let requestStarted!: () => void;
const started = new Promise<void>(resolve => {
requestStarted = resolve;
});
const fetchMock = jest.spyOn(globalThis, 'fetch').mockImplementation(async (_input, init) => {
expect(new Headers(init?.headers).get('Authorization')).toBe('Bearer test-token');
return await new Promise<Response>((_resolve, reject) => {
init!.signal!.addEventListener('abort', () => reject(init!.signal!.reason), { once: true });
jest.mocked(fetch).mockImplementationOnce(async (url, init) => {
expect(url).toBe('https://api.expo.test/v2/sandbox-worker/ready');
expect(init?.headers).toEqual({ 'expo-sandbox-worker-token': 'worker-token' });
return await new Promise((_resolve, reject) => {
init!.signal!.addEventListener('abort', () => reject(new AbortError('Aborted')));
requestStarted();
});
});
const graphqlClient = new Client({
url: 'https://api.expo.test/graphql',
exchanges: [fetchExchange],
fetchOptions: { headers: { Authorization: 'Bearer test-token' } },
const fn = createStartSandboxBuildFunction(context as any);
const pending = fn.fn!({ logger: {} } as any, {
inputs,
outputs: {},
env: {},
signal: controller.signal,
});
try {
const pending = markSandboxReadyAsync(
{ graphqlClient } as any,
'sandbox-id',
controller.signal
);
const rejected = expect(pending).rejects.toMatchObject({ name: 'AbortError' });
await started;
controller.abort();
await rejected;
} finally {
fetchMock.mockRestore();
}
const rejected = expect(pending).rejects.toMatchObject({ name: 'AbortError' });
await started;
controller.abort();
await rejected;
expect(stopAsync).toHaveBeenCalledTimes(1);
});
it('does not mark the sandbox ready if startup was canceled', async () => {
const controller = new AbortController();
it('throws a system error and stops the daemon when readiness fails', async () => {
const stopAsync = jest.fn(async () => {});
const start = jest
jest
.spyOn(sandboxDaemon, 'startSandboxDaemonAsync')
.mockImplementation(async options => {
expect(options.signal).toBe(controller.signal);
controller.abort();
return { ready: Promise.resolve(), stopAsync };
});
const mutation = jest.fn();
const fn = createStartSandboxBuildFunction({
env: { __EAS_SANDBOX_MCP_TOKEN: 'token' },
mcpServerUrl: 'ws://localhost:8787',
graphqlClient: { mutation },
} as any);
try {
await expect(
fn.fn!({ logger: {} } as any, {
inputs: { sandbox_id: { value: 'sandbox-id' } },
outputs: {},
env: { __EAS_SANDBOX_MCP_TOKEN: 'token' },
signal: controller.signal,
})
).rejects.toMatchObject({ name: 'AbortError' });
expect(mutation).not.toHaveBeenCalled();
expect(stopAsync).toHaveBeenCalledTimes(1);
} finally {
start.mockRestore();
}
.mockResolvedValue({ ready: Promise.resolve(), stopAsync });
jest.mocked(fetch).mockResolvedValueOnce(
new Response(JSON.stringify({ errors: [{ message: 'Sandbox has stopped.' }] }), {
status: 400,
})
);
const fn = createStartSandboxBuildFunction(context as any);
const result = fn.fn!({ logger: {} } as any, { inputs, outputs: {}, env: {} });
await expect(result).rejects.toBeInstanceOf(SystemError);
await expect(result).rejects.toMatchObject({
message: 'Failed to mark sandbox sandbox-id as ready.',
cause: expect.objectContaining({ status: 400 }),
});
expect(stopAsync).toHaveBeenCalledTimes(1);
});
it('excludes the MCP token from the command environment', async () => {
const env = {
PREPARED_BY_EARLIER_STEP: 'value',
EXPO_TOKEN: 'expo-token',
__EAS_SANDBOX_MCP_TOKEN: 'token',
};
it('strips the repository credentials before starting the daemon for git sources', async () => {
const startupError = new Error('stop after checking options');
const start = jest
.spyOn(sandboxDaemon, 'startSandboxDaemonAsync')
.mockRejectedValue(startupError);
const fn = createStartSandboxBuildFunction({
env: { __EAS_SANDBOX_MCP_TOKEN: 'token' },
mcpServerUrl: 'ws://localhost:8787',
} as any);
try {
await expect(
fn.fn!({ logger: {} } as any, {
inputs: { sandbox_id: { value: 'sandbox-id' } },
outputs: {},
env,
})
).rejects.toBe(startupError);
expect(start.mock.calls[0][0]).toMatchObject({ credential: 'token' });
expect(start.mock.calls[0][0].env).toEqual({
PREPARED_BY_EARLIER_STEP: 'value',
EXPO_TOKEN: 'expo-token',
});
expect(env.__EAS_SANDBOX_MCP_TOKEN).toBe('token');
} finally {
start.mockRestore();
}
});
it('throws a system error when the sandbox token is missing', async () => {
const fn = createStartSandboxBuildFunction({
job: {},
env: {},
mcpServerUrl: 'ws://localhost:8787',
...context,
job: {
...context.job,
projectArchive: {
type: ArchiveSourceType.GIT,
gitRef: 'refs/heads/main',
gitCommitHash: '0123456789abcdef0123456789abcdef01234567',
},
},
projectTargetDirectory: '/workingdir/build',
} as any);
await expect(
fn.fn!({} as any, {
inputs: { sandbox_id: { value: 'sandbox-id' } },
outputs: {},
env: {},
})
).rejects.toBeInstanceOf(SystemError);
});
it('throws a system error when the MCP server URL is missing', async () => {
const fn = createStartSandboxBuildFunction({
job: {},
env: { __EAS_SANDBOX_MCP_TOKEN: 'sandbox-token' },
} as any);
await expect(
fn.fn!({} as any, {
inputs: { sandbox_id: { value: 'sandbox-id' } },
outputs: {},
env: { __EAS_SANDBOX_MCP_TOKEN: 'sandbox-token' },
})
).rejects.toThrow('MCP server URL is required to start the sandbox daemon.');
});
it('marks the sandbox as ready', async () => {
const mutation = jest.fn(() => ({
toPromise: async () => ({ data: { sandbox: { markSandboxReady: { id: 'sandbox-id' } } } }),
}));
await markSandboxReadyAsync({ graphqlClient: { mutation } } as any, 'sandbox-id');
expect(mutation).toHaveBeenCalledWith(
expect.anything(),
{ sandboxId: 'sandbox-id' },
undefined
await expect(fn.fn!(checkedOutStepCtx, { inputs, outputs: {}, env: {} })).rejects.toBe(
startupError
);
expect(stripRepositoryCredentialsAsync).toHaveBeenCalledWith({
repositoryDirectory: '/workingdir/build',
});
expect(jest.mocked(stripRepositoryCredentialsAsync).mock.invocationCallOrder[0]).toBeLessThan(
start.mock.invocationCallOrder[0]
);
});
it('throws a system error when marking the sandbox as ready fails', async () => {
const mutation = jest.fn(() => ({
toPromise: async () => ({ error: new Error('request failed') }),
}));
it('strips the repository credentials from the source directory before eas/checkout', async () => {
const startupError = new Error('stop after checking options');
jest.spyOn(sandboxDaemon, 'startSandboxDaemonAsync').mockRejectedValue(startupError);
const fn = createStartSandboxBuildFunction({
...context,
job: {
...context.job,
projectArchive: {
type: ArchiveSourceType.GIT,
gitRef: null,
gitCommitHash: '0123456789abcdef0123456789abcdef01234567',
},
},
projectSourceDirectory: '/workingdir/temporary-custom-build',
projectTargetDirectory: '/workingdir/build',
} as any);
await expect(
markSandboxReadyAsync({ graphqlClient: { mutation } } as any, 'sandbox-id')
).rejects.toThrow('Failed to mark sandbox sandbox-id as ready.');
await expect(fn.fn!(notCheckedOutStepCtx, { inputs, outputs: {}, env: {} })).rejects.toBe(
startupError
);
expect(stripRepositoryCredentialsAsync).toHaveBeenCalledWith({
repositoryDirectory: '/workingdir/temporary-custom-build',
});
});
it('does not start the daemon when stripping the repository credentials fails', async () => {
const stripError = new SystemError('Failed to strip credentials from the origin remote URL.');
jest.mocked(stripRepositoryCredentialsAsync).mockRejectedValueOnce(stripError);
const start = jest.spyOn(sandboxDaemon, 'startSandboxDaemonAsync');
const fn = createStartSandboxBuildFunction({
...context,
job: {
...context.job,
projectArchive: {
type: ArchiveSourceType.GIT,
gitRef: null,
gitCommitHash: '0123456789abcdef0123456789abcdef01234567',
},
},
projectTargetDirectory: '/workingdir/build',
} as any);
await expect(fn.fn!(checkedOutStepCtx, { inputs, outputs: {}, env: {} })).rejects.toBe(
stripError
);
expect(start).not.toHaveBeenCalled();
});
it('leaves the remote alone for non-git sources', async () => {
const startupError = new Error('stop after checking options');
jest.spyOn(sandboxDaemon, 'startSandboxDaemonAsync').mockRejectedValue(startupError);
const fn = createStartSandboxBuildFunction({
...context,
projectTargetDirectory: '/workingdir/build',
} as any);
await expect(fn.fn!({ logger: {} } as any, { inputs, outputs: {}, env: {} })).rejects.toBe(
startupError
);
expect(stripRepositoryCredentialsAsync).not.toHaveBeenCalled();
});
it.each([
{
missing: 'the sandbox worker token',
overrides: { job: {} },
message: 'This sandbox job has no EAS_SANDBOX_WORKER_TOKEN secret.',
},
{
missing: 'the MCP server URL',
overrides: { mcpServerUrl: undefined },
message: 'MCP server URL is required to start the sandbox daemon.',
},
{
missing: 'the API server URL',
overrides: { expoApiV2BaseUrl: undefined },
message: 'The API server URL is not set',
},
])('throws a system error without $missing', async ({ overrides, message }) => {
const start = jest.spyOn(sandboxDaemon, 'startSandboxDaemonAsync');
const fn = createStartSandboxBuildFunction({ ...context, ...overrides } as any);
const result = fn.fn!({} as any, { inputs, outputs: {}, env: {} });
await expect(result).rejects.toBeInstanceOf(SystemError);
await expect(result).rejects.toThrow(message);
expect(start).not.toHaveBeenCalled();
});
});
@@ -224,18 +224,43 @@ describe(createStartWebPreviewRemoteSessionBuildFunction, () => {
);
});
it('uses preview activity to reset the configured idle timeout', async () => {
await runAsync(BuildRuntimePlatform.DARWIN, { max_idle_time_minutes: { value: 5 } });
const { idleTimeout } = jest.mocked(waitForDeviceRunSessionStoppedAsync).mock.calls[0][0];
expect(idleTimeout?.maxIdleTimeMinutes).toBe(5);
expect(idleTimeout?.getLastEventObservedAt()).toBeUndefined();
const host = await jest.mocked(startDeviceSessionHostAsync).mock.results[0].value;
const observedAt = new Date();
jest.mocked(host.getLastPreviewActivityAt).mockReturnValue(observedAt);
expect(idleTimeout?.getLastPreviewActivityAt?.()).toBe(observedAt);
expect(stopAsync).toHaveBeenCalledTimes(1);
it('passes the resolved version to cold setup after a warm version mismatch', async () => {
jest
.mocked(runOnWarmIosSimulatorAsync)
.mockImplementation((_claim, run) => run(undefined, '0.14.0'));
await createStartWebPreviewRemoteSessionBuildFunction(ctx, { warm: true }).fn!(
{ logger, global: { runtimePlatform: BuildRuntimePlatform.DARWIN } } as never,
{ inputs: { package_version: { value: 'latest' } }, outputs: {}, env } as never
);
expect(startDeviceSessionHostAsync).toHaveBeenCalledWith(
ctx,
expect.objectContaining({ packageVersion: '0.14.0' })
);
});
it('lets the session host use the experimental emulator capture', async () => {
await runAsync(BuildRuntimePlatform.LINUX);
expect(startDeviceSessionHostAsync).toHaveBeenCalledWith(
ctx,
expect.objectContaining({ emulatorCapture: true })
);
});
it.each([BuildRuntimePlatform.DARWIN, BuildRuntimePlatform.LINUX])(
'uses preview activity to reset the configured idle timeout on %s',
async runtimePlatform => {
await runAsync(runtimePlatform, { max_idle_time_minutes: { value: 5 } });
const { idleTimeout } = jest.mocked(waitForDeviceRunSessionStoppedAsync).mock.calls[0][0];
expect(idleTimeout?.maxIdleTimeMinutes).toBe(5);
expect(idleTimeout?.getLastEventObservedAt()).toBeUndefined();
const host = await jest.mocked(startDeviceSessionHostAsync).mock.results[0].value;
const observedAt = new Date();
jest.mocked(host.getLastPreviewActivityAt).mockReturnValue(observedAt);
expect(idleTimeout?.getLastPreviewActivityAt?.()).toBe(observedAt);
expect(stopAsync).toHaveBeenCalledTimes(1);
}
);
it.each([BuildRuntimePlatform.DARWIN, BuildRuntimePlatform.LINUX])(
'leaves the idle timer disabled when omitted on %s',
async runtimePlatform => {
@@ -255,16 +280,6 @@ describe(createStartWebPreviewRemoteSessionBuildFunction, () => {
);
});
it('rejects an Android idle timeout before starting the host', async () => {
await expect(
runAsync(BuildRuntimePlatform.LINUX, {
max_idle_time_minutes: { value: 5 },
})
).rejects.toThrow('Omit max_idle_time_minutes for Android sessions.');
expect(startDeviceSessionHostAsync).not.toHaveBeenCalled();
expect(waitForDeviceRunSessionStoppedAsync).not.toHaveBeenCalled();
});
it.each([BuildRuntimePlatform.DARWIN, BuildRuntimePlatform.LINUX])(
'handles Stop while the %s host starts',
async runtimePlatform => {
@@ -494,6 +509,7 @@ describe(createStartWebPreviewRemoteSessionBuildFunction, () => {
}
: {}),
packageVersion: '1.2.3',
emulatorCapture: true,
disableShare: false,
frameAncestors: [],
corsOrigins: [],
@@ -1,13 +1,7 @@
import {
BuildFunction,
BuildRuntimePlatform,
BuildStepInput,
BuildStepInputValueTypeName,
} from '@expo/steps';
import { BuildFunction, BuildRuntimePlatform } from '@expo/steps';
import { type CustomBuildContext } from '../../customBuildContext';
import { Sentry } from '../../sentry';
import { AndroidEmulatorLogSourcesSchema } from '../../utils/androidEmulatorLogSources';
import { collectAndroidEmulatorLogsAsync } from '../utils/androidEmulatorLogs';
import { getDeviceRunSessionIdOrThrow } from '../utils/remoteDeviceRunSession';
@@ -20,21 +14,12 @@ export function createCollectAndroidEmulatorLogsBuildFunction(
name: 'Collect Android emulator logs',
__metricsId: 'eas/collect_android_emulator_logs',
supportedRuntimePlatforms: [BuildRuntimePlatform.LINUX],
inputProviders: [
BuildStepInput.createProvider({
id: 'sources',
required: false,
defaultValue: ['emulator-output'],
allowedValueTypeName: BuildStepInputValueTypeName.JSON,
}),
],
fn: async ({ logger, global }, { inputs, env }) => {
fn: async ({ logger, global }, { env }) => {
try {
await collectAndroidEmulatorLogsAsync(ctx, {
global,
deviceRunSessionId: getDeviceRunSessionIdOrThrow(env),
logger,
sources: AndroidEmulatorLogSourcesSchema.parse(inputs.sources.value),
});
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err));
@@ -0,0 +1,62 @@
import { BuildFunction, BuildRuntimePlatform } from '@expo/steps';
import { rm } from 'node:fs/promises';
import { type CustomBuildContext } from '../../customBuildContext';
import { Sentry } from '../../sentry';
import { getDeviceRunSessionIdOrThrow } from '../utils/remoteDeviceRunSession';
import { uploadServeSimCrashesFileAsync } from '../utils/serveSimCrashesArtifacts';
import { ServeSimCrashesRecorder } from '../utils/serveSimCrashesRecorder';
const UPLOAD_TIMEOUT_MS = 30_000;
export function createCollectServeSimCrashesBuildFunction(ctx: CustomBuildContext): BuildFunction {
return new BuildFunction({
namespace: 'eas',
id: 'collect_serve_sim_crashes',
name: 'Collect serve-sim simulator crashes',
__metricsId: 'eas/collect_serve_sim_crashes',
supportedRuntimePlatforms: [BuildRuntimePlatform.DARWIN],
fn: async ({ logger }, { env }) => {
let outputDirectory: string | null = null;
try {
const collected = await ServeSimCrashesRecorder.finishAsync();
outputDirectory = collected.outputDirectory;
if (collected.crashes.length === 0) {
logger.info('No simulator crashes collected; skipping upload.');
return;
}
const deviceRunSessionId = getDeviceRunSessionIdOrThrow(env);
for (const udid of new Set(collected.crashes.map(crash => crash.udid))) {
const signal = AbortSignal.timeout(UPLOAD_TIMEOUT_MS);
for (const crash of collected.crashes.filter(crash => crash.udid === udid)) {
if (signal.aborted) {
logger.warn(
`Simulator crash upload reached its time limit for ${udid}; remaining reports will not be uploaded.`
);
break;
}
await uploadServeSimCrashesFileAsync(ctx, {
deviceRunSessionId,
crash,
logger,
signal,
});
}
}
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err));
Sentry.capture('Could not finalize serve-sim simulator crashes', error);
logger.warn(
{ err: error },
'Could not finalize simulator crashes; the session result is unchanged.'
);
} finally {
if (outputDirectory) {
await rm(outputDirectory, { recursive: true, force: true }).catch(err => {
logger.warn({ err }, 'Could not remove the simulator crash directory.');
});
}
}
},
});
}
@@ -0,0 +1,63 @@
import { BuildFunction, BuildRuntimePlatform } from '@expo/steps';
import { rm } from 'node:fs/promises';
import { type CustomBuildContext } from '../../customBuildContext';
import { Sentry } from '../../sentry';
import { getDeviceRunSessionIdOrThrow } from '../utils/remoteDeviceRunSession';
import { uploadServeSimNetworkCaptureFileAsync } from '../utils/serveSimNetworkCaptureArtifacts';
import { ServeSimNetworkCaptureRecorder } from '../utils/serveSimNetworkCaptureRecorder';
// Each HAR may be up to 500 MiB, so one slow upload gets its own long limit.
const UPLOAD_TIMEOUT_MS = 10 * 60 * 1000;
export function createCollectServeSimNetworkCaptureBuildFunction(
ctx: CustomBuildContext
): BuildFunction {
return new BuildFunction({
namespace: 'eas',
id: 'collect_serve_sim_network_capture',
name: 'Collect serve-sim network capture',
__metricsId: 'eas/collect_serve_sim_network_capture',
supportedRuntimePlatforms: [BuildRuntimePlatform.DARWIN],
fn: async ({ logger }, { env }) => {
const { outputDirectory, captures } = await ServeSimNetworkCaptureRecorder.finishAsync({
logger,
});
try {
if (captures.length === 0) {
logger.info('No network capture was recorded; skipping upload.');
return;
}
const deviceRunSessionId = getDeviceRunSessionIdOrThrow(env);
// A device's HARs are numbered parts, one per capture har run that recorded requests.
const parts = new Map<string, number>();
for (const { udid, filePath, size } of captures) {
const part = (parts.get(udid) ?? 0) + 1;
parts.set(udid, part);
await uploadServeSimNetworkCaptureFileAsync(ctx, {
deviceRunSessionId,
udid,
filePath,
size,
part,
logger,
signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS),
});
}
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err));
Sentry.capture('Could not upload the network capture', error);
logger.warn({ err: error }, 'Could not upload the network capture.');
} finally {
if (outputDirectory) {
await rm(outputDirectory, { recursive: true, force: true }).catch(err => {
logger.warn(
{ err },
`Could not remove the network capture directory ${outputDirectory}.`
);
});
}
}
},
});
}
@@ -1,4 +1,4 @@
import { SystemError } from '@expo/eas-build-job';
import { SystemError, formatBytes } from '@expo/eas-build-job';
import { bunyan } from '@expo/logger';
import { asyncResult } from '@expo/results';
import {
@@ -15,7 +15,6 @@ import stream from 'stream';
import { promisify } from 'util';
import { z } from 'zod';
import { formatBytes } from '../../utils/artifacts';
import { decompressTarAsync, isFileTarGzAsync } from '../../utils/files';
import { retryOnDNSFailure } from '../../utils/retryOnDNSFailure';
@@ -1,4 +1,4 @@
import { SystemError, UserError } from '@expo/eas-build-job';
import { SystemError, UserError, formatBytes } from '@expo/eas-build-job';
import { bunyan } from '@expo/logger';
import { asyncResult } from '@expo/results';
import {
@@ -23,7 +23,6 @@ import bplistParser from 'bplist-parser';
import plist from 'plist';
import { CustomBuildContext } from '../../customBuildContext';
import { formatBytes } from '../../utils/artifacts';
import { decompressTarAsync, isFileTarGzAsync } from '../../utils/files';
import { graphqlAbortContext } from '../../utils/graphqlAbort';
import {
@@ -35,9 +34,9 @@ import { retryOnNetworkFailureAsync } from '../../utils/retryOnNetworkFailure';
import { pluralize } from '../../utils/strings';
import {
type DeviceRunSessionWorkerApi,
DeviceRunSessionWorkerApiError,
getDeviceRunSessionWorkerApi,
} from '../utils/deviceRunSessionWorkerApi';
import { WorkerApiError } from '../utils/workerApi';
const streamPipeline = promisify(stream.pipeline);
@@ -219,7 +218,7 @@ async function fetchDeviceRunSessionApplicationArchiveUrlAsync({
{
operation: 'download_build.session_build_lookup',
signal,
isRetryable: error => error instanceof DeviceRunSessionWorkerApiError && error.isTransient,
isRetryable: error => error instanceof WorkerApiError && error.isTransient,
}
);
} catch (err) {
@@ -1,4 +1,4 @@
import { BuildFunction } from '@expo/steps';
import { BuildFunction, BuildStepContext, BuildStepEnv } from '@expo/steps';
import spawn from '@expo/turtle-spawn';
export function createInstallPodsBuildFunction(): BuildFunction {
@@ -8,29 +8,36 @@ export function createInstallPodsBuildFunction(): BuildFunction {
name: 'Install Pods',
__metricsId: 'eas/install_pods',
fn: async (stepsCtx, { env }) => {
stepsCtx.logger.info('Installing pods');
const verboseFlag = stepsCtx.global.env['EAS_VERBOSE'] === '1' ? ['--verbose'] : [];
const cocoapodsDeploymentFlag =
stepsCtx.global.env['POD_INSTALL_DEPLOYMENT'] === '1' ? ['--deployment'] : [];
await runPodInstallAsync(stepsCtx, env);
},
});
}
await spawn('pod', ['install', ...verboseFlag, ...cocoapodsDeploymentFlag], {
logger: stepsCtx.logger,
env: {
...env,
LANG: 'en_US.UTF-8',
},
cwd: stepsCtx.workingDirectory,
lineTransformer: (line?: string) => {
if (
!line ||
/\[!\] '[\w-]+' uses the unencrypted 'http' protocol to transfer the Pod\./.exec(line)
) {
return null;
} else {
return line;
}
},
});
export async function runPodInstallAsync(
stepsCtx: BuildStepContext,
env: BuildStepEnv
): Promise<void> {
stepsCtx.logger.info('Installing pods');
const verboseFlag = stepsCtx.global.env['EAS_VERBOSE'] === '1' ? ['--verbose'] : [];
const cocoapodsDeploymentFlag =
stepsCtx.global.env['POD_INSTALL_DEPLOYMENT'] === '1' ? ['--deployment'] : [];
await spawn('pod', ['install', ...verboseFlag, ...cocoapodsDeploymentFlag], {
logger: stepsCtx.logger,
env: {
...env,
LANG: 'en_US.UTF-8',
},
cwd: stepsCtx.workingDirectory,
lineTransformer: (line?: string) => {
if (
!line ||
/\[!\] '[\w-]+' uses the unencrypted 'http' protocol to transfer the Pod\./.exec(line)
) {
return null;
} else {
return line;
}
},
});
}
@@ -211,7 +211,9 @@ const MaestroRunnerRecordedFlowSchema = z.object({
name: z.string().min(1),
sourceFile: z.string().min(1),
status: z.enum(['passed', 'failed']),
tags: z.array(z.string()).optional(),
});
type MaestroRunnerRecordedFlow = z.infer<typeof MaestroRunnerRecordedFlowSchema>;
const MaestroRunnerReportSchema = z.object({
flows: z
.array(
@@ -379,6 +381,111 @@ export async function parseFailedFlowsFromFileAttrs(args: {
return paths;
}
const MAESTRO_RUNNER_ATTEMPT_DIRECTORY_PATTERN = /-maestro-runner-attempt-(\d+)$/;
export function maestroRunnerAttemptDirectoryName(args: {
platform: string;
attempt: number;
}): string {
return `${args.platform}-maestro-runner-attempt-${args.attempt}`;
}
async function listMaestroRunnerAttemptDirectories(
testsDirectory: string
): Promise<{ attempt: number; reportDirectory: string }[]> {
let entries: string[];
try {
entries = await fs.readdir(testsDirectory);
} catch {
return [];
}
return entries.flatMap(entry => {
const match = entry.match(MAESTRO_RUNNER_ATTEMPT_DIRECTORY_PATTERN);
return match
? [{ attempt: parseInt(match[1], 10), reportDirectory: path.join(testsDirectory, entry) }]
: [];
});
}
export async function hasMaestroRunnerAttemptDirectories(testsDirectory: string): Promise<boolean> {
return (await listMaestroRunnerAttemptDirectories(testsDirectory)).length > 0;
}
export async function parseMaestroRunnerResults(args: {
junitDirectory: string;
testsDirectory: string;
workingDirectory: string;
}): Promise<MaestroFlowResult[]> {
const results = await parseMaestroResultsFromFileAttrs(args.junitDirectory);
const attempts = await listMaestroRunnerAttemptDirectories(args.testsDirectory);
const flows = await Promise.all(
attempts.map(({ reportDirectory }) =>
parseMaestroRunnerFlowsWithPaths({
reportDirectory,
workingDirectory: args.workingDirectory,
})
)
);
const flowsByAttempt = new Map(attempts.map(({ attempt }, index) => [attempt, flows[index]]));
const realWorkingDirectory = await resolveRealPath(args.workingDirectory);
return results.map(result => {
const tags = findMaestroRunnerFlowTags({
flows: flowsByAttempt.get(result.retryCount) ?? [],
junitFlowPath: result.path,
workingDirectory: args.workingDirectory,
realWorkingDirectory,
});
return tags ? { ...result, tags } : result;
});
}
type MaestroRunnerFlowWithPaths = MaestroRunnerRecordedFlow & {
resolvedPath: string;
realPath: string;
};
// maestro-runner >= 1.1.18 resolves symlinks in the JUnit path, but not in report.json.
async function parseMaestroRunnerFlowsWithPaths(args: {
reportDirectory: string;
workingDirectory: string;
}): Promise<MaestroRunnerFlowWithPaths[]> {
const report = await parseMaestroRunnerReport(args.reportDirectory);
return await Promise.all(
(report?.flows ?? []).map(async flow => {
const resolvedPath = path.resolve(args.workingDirectory, flow.sourceFile);
return { ...flow, resolvedPath, realPath: await resolveRealPath(resolvedPath) };
})
);
}
async function resolveRealPath(filePath: string): Promise<string> {
const realPathResult = await asyncResult(fs.realpath(filePath));
return realPathResult.ok ? realPathResult.value : filePath;
}
function findMaestroRunnerFlowTags(args: {
flows: MaestroRunnerFlowWithPaths[];
junitFlowPath: string;
workingDirectory: string;
realWorkingDirectory: string;
}): string[] | undefined {
const junitPath = path.resolve(args.workingDirectory, args.junitFlowPath);
const junitRealPath = path.resolve(args.realWorkingDirectory, args.junitFlowPath);
const samePath = args.flows.find(
flow => flow.resolvedPath === junitPath || flow.realPath === junitRealPath
);
if (samePath) {
return samePath.tags;
}
// maestro-runner <= 1.1.17 writes only the file name to JUnit.
const sameFileName = args.flows.filter(
flow => path.basename(flow.sourceFile) === args.junitFlowPath
);
return sameFileName.length === 1 ? sameFileName[0].tags : undefined;
}
export async function parseMaestroResults(
junitDirectory: string,
nameToPath: Map<string, string> | null
@@ -18,6 +18,7 @@ import { buildFlowNameToPathMap } from './maestroFlowDiscovery';
import {
copyLatestAttemptXml,
junitFileHasFileAttrs,
maestroRunnerAttemptDirectoryName,
mergeJUnitReports,
parseFailedFlowNamesFromJUnitFile,
parseFailedFlowsFromFileAttrs,
@@ -353,7 +354,7 @@ export function createMaestroTestsBuildFunction(ctx: CustomBuildContext): BuildF
// maestro-runner writes all report formats and screenshot metadata here.
const runnerOutputDirectory = path.join(
testsDirectory,
`${platform}-maestro-runner-attempt-${attempt}`
maestroRunnerAttemptDirectoryName({ platform, attempt })
);
const outputPath = mayHaveJUnitReports
? path.join(junitReportDirectory, `${platform}-maestro-junit-attempt-${attempt}.xml`)
@@ -0,0 +1,440 @@
import { vol } from 'memfs';
import os from 'os';
import path from 'path';
import { createGlobalContextMock } from '../../../../../__tests__/utils/context';
import IosCredentialsManager from '../../../../utils/ios/credentials/manager';
import { DistributionType } from '../../../../utils/ios/credentials/provisioningProfile';
import { runFastlaneGym } from '../../../../utils/ios/fastlane';
import { readBuildSettingsByTargetNameAsync } from '../../../../utils/ios/xcodeProject/buildSettings';
import {
assertSigningBuildSettingsAreEffective,
writeSigningBuildSettingsAsync,
} from '../../../../utils/ios/xcodeProject/signing';
import { createBuildNativeIosBuildFunction } from '../buildNativeIos';
jest.mock('../../../../utils/ios/credentials/manager');
jest.mock('../../../../utils/ios/fastlane');
jest.mock('../../../../utils/ios/xcodeProject/buildSettings');
jest.mock('../../../../utils/ios/xcodeProject/signing');
const projectDirectory = '/project';
const TARGETS = [
{ id: 'APP', name: 'NativeApp', bundleIdentifier: 'dev.expo.nativeapp' },
{ id: 'WIDGET', name: 'Widget', bundleIdentifier: 'dev.expo.nativeapp.widget' },
];
const DISTRIBUTION_CERTIFICATE = { dataBase64: 'Y2VydGlmaWNhdGU=', password: '' };
const APP_CREDENTIALS = {
provisioningProfileBase64: 'YXBw',
distributionCertificate: DISTRIBUTION_CERTIFICATE,
};
const WIDGET_CREDENTIALS = {
provisioningProfileBase64: 'd2lkZ2V0',
distributionCertificate: DISTRIBUTION_CERTIFICATE,
};
function infoPlist(bundleIdentifier: string): string {
return `<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0"><dict><key>CFBundleIdentifier</key><string>${bundleIdentifier}</string></dict></plist>`;
}
function createBuildStep({
job,
projectFile = '/project/NativeApp.xcodeproj',
targets = TARGETS,
}: {
job: Record<string, unknown>;
projectFile?: string;
targets?: typeof TARGETS;
}): ReturnType<
ReturnType<typeof createBuildNativeIosBuildFunction>['createBuildStepFromFunctionCall']
> {
const globalCtx = createGlobalContextMock({
projectTargetDirectory: projectDirectory,
staticContextContent: { job },
});
return createBuildNativeIosBuildFunction().createBuildStepFromFunctionCall(globalCtx, {
callInputs: {
project_file: projectFile,
scheme: 'NativeApp',
build_configuration: 'Release',
xcodeproj_path: '/project/NativeApp.xcodeproj',
targets,
},
});
}
function mockGymProducing(relativePaths: Record<string, string>): { gymfile: () => string } {
let gymfileDirectory = '';
jest.mocked(runFastlaneGym).mockImplementation(async options => {
gymfileDirectory = options.gymfileDirectory!;
vol.fromJSON(relativePaths, gymfileDirectory);
});
return {
gymfile: () => vol.readFileSync(path.join(gymfileDirectory, 'Gymfile'), 'utf-8') as string,
};
}
beforeEach(() => {
vol.fromJSON({ [path.join(os.tmpdir(), 'placeholder')]: '', '/project/placeholder': '' });
jest.mocked(readBuildSettingsByTargetNameAsync).mockResolvedValue({ NativeApp: {}, Widget: {} });
});
afterEach(() => {
vol.reset();
});
describe(createBuildNativeIosBuildFunction, () => {
it('signs every detected target with the credentials of its bundle identifier and archives', async () => {
jest.mocked(IosCredentialsManager.prototype.prepare).mockResolvedValue({
keychainPath: '/keychains/build.keychain',
distributionType: DistributionType.APP_STORE,
teamId: 'ABCDE12345',
targetProvisioningProfiles: {
NativeApp: { name: 'App Profile', uuid: 'app-uuid', teamId: 'ABCDE12345' },
Widget: { name: 'Widget Profile', uuid: 'widget-uuid', teamId: 'ABCDE12345' },
},
} as any);
const gym = mockGymProducing({ 'output/NativeApp.ipa': '' });
const step = createBuildStep({
job: {
simulator: false,
secrets: {
credentialsByBundleIdentifier: {
'dev.expo.nativeapp.widget': WIDGET_CREDENTIALS,
'dev.expo.nativeapp': APP_CREDENTIALS,
},
},
},
});
await step.executeAsync();
expect(IosCredentialsManager).toHaveBeenCalledWith({
NativeApp: APP_CREDENTIALS,
Widget: WIDGET_CREDENTIALS,
});
const targetSignings = [
{
target: TARGETS[0],
buildSettings: {
PROVISIONING_PROFILE_SPECIFIER: 'App Profile',
DEVELOPMENT_TEAM: 'ABCDE12345',
CODE_SIGN_IDENTITY: 'iPhone Distribution',
CODE_SIGN_STYLE: 'Manual',
},
},
{
target: TARGETS[1],
buildSettings: {
PROVISIONING_PROFILE_SPECIFIER: 'Widget Profile',
DEVELOPMENT_TEAM: 'ABCDE12345',
CODE_SIGN_IDENTITY: 'iPhone Distribution',
CODE_SIGN_STYLE: 'Manual',
},
},
];
expect(writeSigningBuildSettingsAsync).toHaveBeenCalledWith({
xcodeprojPath: '/project/NativeApp.xcodeproj',
buildConfiguration: 'Release',
targetSignings,
});
expect(readBuildSettingsByTargetNameAsync).toHaveBeenCalledWith(
expect.objectContaining({
xcodeprojPath: '/project/NativeApp.xcodeproj',
targetNames: ['NativeApp', 'Widget'],
buildConfiguration: 'Release',
})
);
expect(assertSigningBuildSettingsAreEffective).toHaveBeenCalledWith({
buildConfiguration: 'Release',
targetSignings,
effectiveBuildSettingsByTargetName: { NativeApp: {}, Widget: {} },
});
const gymfile = gym.gymfile();
expect(gymfile).toContain('project("/project/NativeApp.xcodeproj")');
expect(gymfile).toContain('xcargs("-skipPackagePluginValidation -skipMacroValidation")');
expect(gymfile).toContain('scheme("NativeApp")');
expect(gymfile).toContain('configuration("Release")');
expect(gymfile).toContain('method: "app-store"');
expect(gymfile).toContain('"dev.expo.nativeapp" => "app-uuid"');
expect(gymfile).toContain('"dev.expo.nativeapp.widget" => "widget-uuid"');
expect(gymfile).toContain('--keychain /keychains/build.keychain');
expect(step.outputById.archive_path.value).toMatch(
/native-ios-build-[^/]+\/output\/NativeApp\.ipa$/
);
expect(path.isAbsolute(step.outputById.archive_path.value as string)).toBe(true);
});
it('uses the common name of the certificate as the identity for a development profile', async () => {
jest.mocked(IosCredentialsManager.prototype.prepare).mockResolvedValue({
keychainPath: '/keychains/build.keychain',
distributionType: DistributionType.DEVELOPMENT,
teamId: 'ABCDE12345',
targetProvisioningProfiles: {
NativeApp: {
name: 'Development Profile',
uuid: 'app-uuid',
teamId: 'ABCDE12345',
certificateCommonName: 'Apple Development: Example (ABCDE12345)',
},
},
} as any);
mockGymProducing({ 'output/NativeApp.ipa': '' });
const step = createBuildStep({
job: {
simulator: false,
secrets: { credentialsByBundleIdentifier: { 'dev.expo.nativeapp': APP_CREDENTIALS } },
},
targets: [TARGETS[0]],
});
await step.executeAsync();
expect(
jest.mocked(writeSigningBuildSettingsAsync).mock.calls[0][0].targetSignings[0].buildSettings
.CODE_SIGN_IDENTITY
).toBe('Apple Development: Example (ABCDE12345)');
});
it('builds for the simulator without credentials and returns the app with the bundle identifier', async () => {
const products = 'derived-data/Build/Products/Release-iphonesimulator';
const gym = mockGymProducing({
[`${products}/Clip.app/Info.plist`]: infoPlist('dev.expo.nativeapp.clip'),
[`${products}/NativeApp.app/Info.plist`]: infoPlist('dev.expo.nativeapp'),
});
const step = createBuildStep({
job: { simulator: true, secrets: {} },
projectFile: '/project/NativeApp.xcworkspace',
targets: [TARGETS[0]],
});
await step.executeAsync();
expect(IosCredentialsManager).not.toHaveBeenCalled();
expect(writeSigningBuildSettingsAsync).not.toHaveBeenCalled();
const gymfile = gym.gymfile();
expect(gymfile).toContain('workspace("/project/NativeApp.xcworkspace")');
expect(gymfile).toContain('destination("generic/platform=iOS Simulator")');
expect(gymfile).toContain('xcargs("-skipPackagePluginValidation -skipMacroValidation")');
expect(gymfile).not.toContain('export_options');
expect(step.outputById.archive_path.value).toMatch(/Release-iphonesimulator\/NativeApp\.app$/);
expect(runFastlaneGym).toHaveBeenCalledWith(
expect.objectContaining({
workingDir: projectDirectory,
gymfileDirectory: expect.stringContaining('native-ios-build-'),
})
);
});
it('fails before it prepares credentials when a target has none', async () => {
const step = createBuildStep({
job: {
simulator: false,
secrets: { credentialsByBundleIdentifier: { 'dev.expo.nativeapp': APP_CREDENTIALS } },
},
});
await expect(step.executeAsync()).rejects.toMatchObject({
errorCode: 'NATIVE_XCODE_MISSING_CREDENTIALS',
message: expect.stringContaining(
'no credentials for "dev.expo.nativeapp.widget" (target "Widget")'
),
});
expect(IosCredentialsManager).not.toHaveBeenCalled();
expect(runFastlaneGym).not.toHaveBeenCalled();
});
it('fails with a user error that points to the logs when the Xcode build fails', async () => {
const gymError = new Error('fastlane exited with non-zero code: 1');
jest.mocked(runFastlaneGym).mockRejectedValue(gymError);
const step = createBuildStep({ job: { simulator: true }, targets: [TARGETS[0]] });
await expect(step.executeAsync()).rejects.toMatchObject({
errorCode: 'NATIVE_XCODE_BUILD_FAILED',
message: expect.stringContaining('The errors are in the "Build with Xcode" step.'),
cause: gymError,
});
});
it('rejects a targets input that is not the list the detection step produces', async () => {
const step = createBuildStep({
job: { simulator: true },
targets: [{ id: 'APP', name: 'NativeApp' }] as any,
});
await expect(step.executeAsync()).rejects.toThrow(/bundleIdentifier/);
expect(runFastlaneGym).not.toHaveBeenCalled();
});
it('fails when the build produced no archive', async () => {
mockGymProducing({ 'output/placeholder': '' });
jest.mocked(IosCredentialsManager.prototype.prepare).mockResolvedValue({
keychainPath: '/keychains/build.keychain',
distributionType: DistributionType.AD_HOC,
teamId: 'ABCDE12345',
targetProvisioningProfiles: {
NativeApp: { name: 'App Profile', uuid: 'app-uuid', teamId: 'ABCDE12345' },
},
} as any);
const step = createBuildStep({
job: {
simulator: false,
secrets: { credentialsByBundleIdentifier: { 'dev.expo.nativeapp': APP_CREDENTIALS } },
},
targets: [TARGETS[0]],
});
await expect(step.executeAsync()).rejects.toMatchObject({
errorCode: 'NATIVE_XCODE_NO_BUILD_OUTPUT',
});
});
describe('the iCloud container environment of the export', () => {
function entitlementsWithEnvironment(environment: string): string {
return `<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0"><dict><key>com.apple.developer.icloud-container-environment</key><string>${environment}</string></dict></plist>`;
}
const ENTITLEMENTS_WITHOUT_ENVIRONMENT = `<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0"><dict><key>aps-environment</key><string>production</string></dict></plist>`;
async function exportAsync({
applicationBuildSettings,
widgetBuildSettings = {},
files = {},
}: {
applicationBuildSettings: Record<string, string>;
widgetBuildSettings?: Record<string, string>;
files?: Record<string, string>;
}): Promise<{ gymfile: string; warn: jest.Mock }> {
jest.mocked(IosCredentialsManager.prototype.prepare).mockResolvedValue({
keychainPath: '/keychains/build.keychain',
distributionType: DistributionType.AD_HOC,
teamId: 'ABCDE12345',
targetProvisioningProfiles: {
NativeApp: { name: 'App Profile', uuid: 'app-uuid', teamId: 'ABCDE12345' },
Widget: { name: 'Widget Profile', uuid: 'widget-uuid', teamId: 'ABCDE12345' },
},
} as any);
jest
.mocked(readBuildSettingsByTargetNameAsync)
.mockResolvedValue({ NativeApp: applicationBuildSettings, Widget: widgetBuildSettings });
vol.fromJSON(files);
const gym = mockGymProducing({ 'output/NativeApp.ipa': '' });
const step = createBuildStep({
job: {
simulator: false,
secrets: {
credentialsByBundleIdentifier: {
'dev.expo.nativeapp': APP_CREDENTIALS,
'dev.expo.nativeapp.widget': WIDGET_CREDENTIALS,
},
},
},
});
await step.executeAsync();
return { gymfile: gym.gymfile(), warn: jest.mocked(step.ctx.logger.warn) };
}
it.each([
[
'a path relative to the source root',
{ SRCROOT: '/project/app', CODE_SIGN_ENTITLEMENTS: 'NativeApp/NativeApp.entitlements' },
'/project/app/NativeApp/NativeApp.entitlements',
],
[
'an absolute path',
{ SRCROOT: '/project/app', CODE_SIGN_ENTITLEMENTS: '/project/Shared/App.entitlements' },
'/project/Shared/App.entitlements',
],
])(
'passes the value of the entitlements file of the application target, given as %s',
async (_description, applicationBuildSettings, entitlementsPath) => {
const { gymfile, warn } = await exportAsync({
applicationBuildSettings,
files: { [entitlementsPath]: entitlementsWithEnvironment('Development') },
});
expect(gymfile).toContain('iCloudContainerEnvironment: "Development"');
expect(warn).not.toHaveBeenCalled();
}
);
it.each([
['the target has no entitlements file', { SRCROOT: '/project' }, {}],
[
'the entitlements file does not name an environment',
{ SRCROOT: '/project', CODE_SIGN_ENTITLEMENTS: 'NativeApp.entitlements' },
{ '/project/NativeApp.entitlements': ENTITLEMENTS_WITHOUT_ENVIRONMENT },
],
[
'the environment in the entitlements file is empty',
{ SRCROOT: '/project', CODE_SIGN_ENTITLEMENTS: 'NativeApp.entitlements' },
{ '/project/NativeApp.entitlements': entitlementsWithEnvironment('') },
],
])('passes no value and does not warn when %s', async (_description, settings, files) => {
const { gymfile, warn } = await exportAsync({ applicationBuildSettings: settings, files });
expect(gymfile).not.toContain('iCloudContainerEnvironment');
expect(warn).not.toHaveBeenCalled();
});
it.each([
['uses the value of the application target', 'NativeApp.entitlements', true],
['passes no value when only another target names one', undefined, false],
])(
'reads the application target only: %s',
async (_description, applicationEntitlements, isEnvironmentExpected) => {
const { gymfile } = await exportAsync({
applicationBuildSettings: {
SRCROOT: '/project',
...(applicationEntitlements && { CODE_SIGN_ENTITLEMENTS: applicationEntitlements }),
},
widgetBuildSettings: {
SRCROOT: '/project',
CODE_SIGN_ENTITLEMENTS: 'Widget.entitlements',
},
files: {
'/project/NativeApp.entitlements': entitlementsWithEnvironment('Development'),
'/project/Widget.entitlements': entitlementsWithEnvironment('Production'),
},
});
expect(gymfile).not.toContain('"Production"');
expect(gymfile.includes('iCloudContainerEnvironment: "Development"')).toBe(
isEnvironmentExpected
);
}
);
it.each([
['is missing', {}],
['is not a property list', { '/project/App.entitlements': 'not a property list' }],
[
'holds null in place of a dictionary',
{ '/project/App.entitlements': '<plist version="1.0"><null/></plist>' },
],
])(
'warns and exports without a value when the entitlements file %s',
async (_description, files) => {
const { gymfile, warn } = await exportAsync({
applicationBuildSettings: {
SRCROOT: '/project',
CODE_SIGN_ENTITLEMENTS: 'App.entitlements',
},
files,
});
expect(gymfile).not.toContain('iCloudContainerEnvironment');
expect(warn).toHaveBeenCalledWith(
expect.anything(),
expect.stringContaining(
'could not read the entitlements file "/project/App.entitlements"'
)
);
}
);
});
});
@@ -0,0 +1,288 @@
import spawn from '@expo/turtle-spawn';
import { vol } from 'memfs';
import path from 'path';
import { createGlobalContextMock } from '../../../../../__tests__/utils/context';
import { createDetectNativeXcodeBuildFunction } from '../detectNativeXcode';
jest.mock('@expo/turtle-spawn', () => ({ __esModule: true, default: jest.fn() }));
const originalFs = jest.requireActual('fs');
const projectDirectory = '/project';
const fixturesDirectory = path.join(
__dirname,
'../../../../utils/ios/xcodeProject/__tests__/fixtures'
);
const FRAMEWORK_ONLY_SCHEME = `<?xml version="1.0" encoding="UTF-8"?>
<Scheme version = "1.3">
<BuildAction>
<BuildActionEntries>
<BuildActionEntry buildForArchiving = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "BBCC7F97904CEBE3743A2D6F"
BuildableName = "Core.framework"
BlueprintName = "Core"
ReferencedContainer = "container:NativeApp.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<LaunchAction buildConfiguration = "Debug"></LaunchAction>
<ArchiveAction buildConfiguration = "Release"></ArchiveAction>
</Scheme>`;
function writeProject(extraFiles: Record<string, string> = {}): void {
vol.fromJSON(
{
'NativeApp.xcodeproj/project.pbxproj': originalFs.readFileSync(
path.join(fixturesDirectory, 'native-app.pbxproj'),
'utf-8'
),
'NativeApp.xcodeproj/xcshareddata/xcschemes/NativeApp.xcscheme': originalFs.readFileSync(
path.join(fixturesDirectory, 'native-app.xcscheme'),
'utf-8'
),
...extraFiles,
},
projectDirectory
);
}
const APPLICATION_BUILD_SETTINGS = {
PLATFORM_NAME: 'iphoneos',
PRODUCT_BUNDLE_IDENTIFIER: 'dev.expo.nativeapp',
PROVISIONING_PROFILE_REQUIRED: 'YES',
};
const WIDGET_BUILD_SETTINGS = {
PLATFORM_NAME: 'iphoneos',
PRODUCT_BUNDLE_IDENTIFIER: 'dev.expo.nativeapp.widget',
PROVISIONING_PROFILE_REQUIRED: 'YES',
};
const BUILD_SETTINGS_BY_TARGET_NAME = {
NativeApp: APPLICATION_BUILD_SETTINGS,
Widget: WIDGET_BUILD_SETTINGS,
Core: { PLATFORM_NAME: 'iphoneos', PRODUCT_BUNDLE_IDENTIFIER: 'dev.expo.nativeapp.core' },
Support: { PLATFORM_NAME: 'iphoneos' },
};
function mockBuildSettings(
...buildSettingsByTargetNameOfEachCall: Record<string, Record<string, string>>[]
): void {
for (const buildSettingsByTargetName of buildSettingsByTargetNameOfEachCall) {
jest.mocked(spawn).mockResolvedValueOnce({
stdout: JSON.stringify(
Object.entries(buildSettingsByTargetName).map(([target, buildSettings]) => ({
action: 'build',
target,
buildSettings,
}))
),
} as any);
}
}
function createDetectStep({
job,
callInputs = {},
}: {
job: Record<string, unknown>;
callInputs?: Record<string, unknown>;
}): ReturnType<
ReturnType<typeof createDetectNativeXcodeBuildFunction>['createBuildStepFromFunctionCall']
> {
const globalCtx = createGlobalContextMock({
projectTargetDirectory: projectDirectory,
staticContextContent: { job },
});
return createDetectNativeXcodeBuildFunction().createBuildStepFromFunctionCall(globalCtx, {
callInputs,
});
}
const signedJob = { simulator: false };
afterEach(() => {
vol.reset();
jest.mocked(spawn).mockReset();
});
describe(createDetectNativeXcodeBuildFunction, () => {
it('detects the project, the scheme, the archive configuration and the targets that need a provisioning profile', async () => {
writeProject();
mockBuildSettings(BUILD_SETTINGS_BY_TARGET_NAME);
const step = createDetectStep({
job: signedJob,
callInputs: { expected_identifier: 'dev.expo.nativeapp' },
});
await step.executeAsync();
expect(step.outputById.project_file.value).toBe('/project/NativeApp.xcodeproj');
expect(step.outputById.scheme.value).toBe('NativeApp');
expect(step.outputById.build_configuration.value).toBe('Release');
expect(step.outputById.xcodeproj_path.value).toBe('/project/NativeApp.xcodeproj');
expect(JSON.parse(step.outputById.targets.value as string)).toEqual([
{ id: '2870BA69F546F142D461562E', name: 'NativeApp', bundleIdentifier: 'dev.expo.nativeapp' },
{
id: '5CAE5500641C3F327B201839',
name: 'Widget',
bundleIdentifier: 'dev.expo.nativeapp.widget',
},
]);
expect(spawn).toHaveBeenCalledWith(
'xcodebuild',
[
'-project',
'/project/NativeApp.xcodeproj',
'-target',
'NativeApp',
'-target',
'Widget',
'-target',
'Core',
'-target',
'Support',
'-configuration',
'Release',
'-showBuildSettings',
'-json',
],
expect.anything()
);
expect(spawn).toHaveBeenCalledTimes(1);
});
it('reads the settings again with the iOS SDK for the targets that Xcode resolved no platform for', async () => {
writeProject();
mockBuildSettings(
{
...BUILD_SETTINGS_BY_TARGET_NAME,
Widget: { PRODUCT_BUNDLE_IDENTIFIER: 'dev.expo.nativeapp.widget' },
Support: {},
},
{ Widget: WIDGET_BUILD_SETTINGS, Support: { PLATFORM_NAME: 'iphoneos' } }
);
const step = createDetectStep({ job: signedJob });
await step.executeAsync();
expect(JSON.parse(step.outputById.targets.value as string)).toEqual([
{ id: '2870BA69F546F142D461562E', name: 'NativeApp', bundleIdentifier: 'dev.expo.nativeapp' },
{
id: '5CAE5500641C3F327B201839',
name: 'Widget',
bundleIdentifier: 'dev.expo.nativeapp.widget',
},
]);
expect(spawn).toHaveBeenCalledTimes(2);
expect(jest.mocked(spawn).mock.calls[1][1]).toEqual([
'-project',
'/project/NativeApp.xcodeproj',
'-target',
'Widget',
'-target',
'Support',
'-configuration',
'Release',
'-sdk',
'iphoneos',
'-showBuildSettings',
'-json',
]);
});
it('uses the Run configuration, the simulator SDK and only the application target for a simulator build', async () => {
writeProject();
mockBuildSettings({ NativeApp: APPLICATION_BUILD_SETTINGS });
const step = createDetectStep({ job: { simulator: true } });
await step.executeAsync();
expect(step.outputById.build_configuration.value).toBe('Debug');
expect(JSON.parse(step.outputById.targets.value as string)).toEqual([
{ id: '2870BA69F546F142D461562E', name: 'NativeApp', bundleIdentifier: 'dev.expo.nativeapp' },
]);
expect(jest.mocked(spawn).mock.calls[0][1]).toEqual(
expect.arrayContaining([
'-target',
'NativeApp',
'-configuration',
'Debug',
'-sdk',
'iphonesimulator',
])
);
expect(jest.mocked(spawn).mock.calls[0][1]).not.toContain('Widget');
});
it('uses the given build configuration', async () => {
writeProject();
mockBuildSettings(BUILD_SETTINGS_BY_TARGET_NAME);
const step = createDetectStep({
job: signedJob,
callInputs: { build_configuration: 'Debug' },
});
await step.executeAsync();
expect(step.outputById.build_configuration.value).toBe('Debug');
});
it('fails with the build configurations of the target when the given one does not exist', async () => {
writeProject();
const step = createDetectStep({
job: signedJob,
callInputs: { build_configuration: 'Staging' },
});
await expect(step.executeAsync()).rejects.toMatchObject({
errorCode: 'NATIVE_XCODE_BUILD_CONFIGURATION_NOT_FOUND',
message: expect.stringContaining(
'"Staging". Build configurations of the target: Debug, Release.'
),
});
expect(spawn).not.toHaveBeenCalled();
});
it('fails when the bundle identifier differs from the expected identifier', async () => {
writeProject();
mockBuildSettings(BUILD_SETTINGS_BY_TARGET_NAME);
const step = createDetectStep({
job: signedJob,
callInputs: { expected_identifier: 'dev.expo.other' },
});
await expect(step.executeAsync()).rejects.toMatchObject({
errorCode: 'NATIVE_XCODE_APP_IDENTIFIER_MISMATCH',
message: expect.stringMatching(/"dev\.expo\.other".*"NativeApp".*"dev\.expo\.nativeapp"/),
});
});
it('fails when a target that needs a provisioning profile has no bundle identifier', async () => {
writeProject();
mockBuildSettings({
...BUILD_SETTINGS_BY_TARGET_NAME,
Widget: { PLATFORM_NAME: 'iphoneos', PROVISIONING_PROFILE_REQUIRED: 'YES' },
});
const step = createDetectStep({ job: signedJob });
await expect(step.executeAsync()).rejects.toMatchObject({
errorCode: 'NATIVE_XCODE_NO_BUNDLE_IDENTIFIER',
message: expect.stringContaining('The target "Widget" has no bundle identifier'),
});
});
it('fails with the other schemes when the scheme builds no application', async () => {
writeProject({
'NativeApp.xcodeproj/xcshareddata/xcschemes/Core.xcscheme': FRAMEWORK_ONLY_SCHEME,
});
const step = createDetectStep({ job: signedJob, callInputs: { scheme: 'Core' } });
await expect(step.executeAsync()).rejects.toMatchObject({
errorCode: 'NATIVE_XCODE_NO_APPLICATION_TARGET',
message: expect.stringMatching(/scheme "Core".*Other shared schemes: NativeApp\./),
});
});
});
@@ -0,0 +1,43 @@
import spawn from '@expo/turtle-spawn';
import { vol } from 'memfs';
import { createGlobalContextMock } from '../../../../../__tests__/utils/context';
import { createInstallNativePodsBuildFunction } from '../installNativePods';
jest.mock('@expo/turtle-spawn', () => ({ __esModule: true, default: jest.fn() }));
const projectDirectory = '/project';
async function runInstallNativePodsAsync(): Promise<void> {
const globalCtx = createGlobalContextMock({ projectTargetDirectory: projectDirectory });
await createInstallNativePodsBuildFunction()
.createBuildStepFromFunctionCall(globalCtx)
.executeAsync();
}
afterEach(() => {
vol.reset();
});
describe(createInstallNativePodsBuildFunction, () => {
it('runs pod install in the project directory when it has a Podfile', async () => {
vol.fromJSON({ Podfile: '', 'App.xcodeproj/project.pbxproj': '' }, projectDirectory);
await runInstallNativePodsAsync();
expect(spawn).toHaveBeenCalledTimes(1);
expect(spawn).toHaveBeenCalledWith(
'pod',
['install'],
expect.objectContaining({ cwd: projectDirectory })
);
});
it('does nothing when the project directory has no Podfile', async () => {
vol.fromJSON({ 'App.xcodeproj/project.pbxproj': '', 'ios/Podfile': '' }, projectDirectory);
await runInstallNativePodsAsync();
expect(spawn).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,99 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
jest.unmock('fs');
jest.unmock('node:fs');
jest.unmock('fs/promises');
jest.unmock('node:fs/promises');
import { createGlobalContextMock } from '../../../../../__tests__/utils/context';
import { createVerifyNativeIosBuildFunction } from '../verifyNativeIos';
const IPA_PATH = path.join(__dirname, '../../../__tests__/fixtures/SmallestAppExample.ipa');
const IPA_BUNDLE_IDENTIFIER = 'dev.expo.SmallestAppExample';
async function writeAppAsync(bundleIdentifier: string, platformName: string): Promise<string> {
const directory = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'verify-native-ios-'));
const appPath = path.join(directory, 'NativeApp.app');
await fs.promises.mkdir(appPath);
await fs.promises.writeFile(
path.join(appPath, 'Info.plist'),
`<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0"><dict>
<key>CFBundleIdentifier</key><string>${bundleIdentifier}</string>
<key>DTPlatformName</key><string>${platformName}</string>
</dict></plist>`
);
return appPath;
}
async function verifyAsync({
simulator,
archivePath,
expectedIdentifier,
}: {
simulator: boolean;
archivePath: string;
expectedIdentifier?: string;
}): Promise<void> {
const globalCtx = createGlobalContextMock({ staticContextContent: { job: { simulator } } });
await createVerifyNativeIosBuildFunction()
.createBuildStepFromFunctionCall(globalCtx, {
callInputs: { archive_path: archivePath, expected_identifier: expectedIdentifier },
})
.executeAsync();
}
describe(createVerifyNativeIosBuildFunction, () => {
it('accepts an IPA for devices with the expected identifier', async () => {
await expect(
verifyAsync({
simulator: false,
archivePath: IPA_PATH,
expectedIdentifier: IPA_BUNDLE_IDENTIFIER,
})
).resolves.toBeUndefined();
});
it('accepts a simulator app with the expected identifier', async () => {
await expect(
verifyAsync({
simulator: true,
archivePath: await writeAppAsync('dev.expo.nativeapp', 'iphonesimulator'),
expectedIdentifier: 'dev.expo.nativeapp',
})
).resolves.toBeUndefined();
});
it('accepts an artifact when no identifier is expected', async () => {
await expect(verifyAsync({ simulator: false, archivePath: IPA_PATH })).resolves.toBeUndefined();
});
it('fails when the identifier of the artifact differs', async () => {
await expect(
verifyAsync({ simulator: false, archivePath: IPA_PATH, expectedIdentifier: 'dev.expo.other' })
).rejects.toMatchObject({
errorCode: 'NATIVE_XCODE_ARTIFACT_IDENTIFIER_MISMATCH',
message: expect.stringMatching(/"dev\.expo\.SmallestAppExample".*"dev\.expo\.other"/),
});
});
it('fails when a simulator build produced an artifact for devices', async () => {
await expect(verifyAsync({ simulator: true, archivePath: IPA_PATH })).rejects.toMatchObject({
errorCode: 'NATIVE_XCODE_ARTIFACT_PLATFORM_MISMATCH',
});
});
it('fails when a device build produced an artifact for the simulator', async () => {
await expect(
verifyAsync({
simulator: false,
archivePath: await writeAppAsync('dev.expo.nativeapp', 'iphonesimulator'),
})
).rejects.toMatchObject({
errorCode: 'NATIVE_XCODE_ARTIFACT_PLATFORM_MISMATCH',
message: expect.stringContaining('"iphonesimulator"'),
});
});
});
@@ -0,0 +1,339 @@
import { Ios, UserError } from '@expo/eas-build-job';
import {
BuildFunction,
BuildStepContext,
BuildStepEnv,
BuildStepInput,
BuildStepInputValueTypeName,
BuildStepOutput,
} from '@expo/steps';
import { templateString } from '@expo/template-file';
import fg from 'fast-glob';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { z } from 'zod';
import { GymfileArchiveTemplate } from '../../../../templates/GymfileArchive';
import { GymfileSimulatorTemplate } from '../../../../templates/GymfileSimulator';
import IosCredentialsManager from '../../../utils/ios/credentials/manager';
import { DistributionType } from '../../../utils/ios/credentials/provisioningProfile';
import { runFastlaneGym } from '../../../utils/ios/fastlane';
import { readBuildSettingsByTargetNameAsync } from '../../../utils/ios/xcodeProject/buildSettings';
import { XcodeTargetWithBundleIdentifier } from '../../../utils/ios/xcodeProject/pbxproj';
import { isWorkspace } from '../../../utils/ios/xcodeProject/projectFile';
import {
assertSigningBuildSettingsAreEffective,
writeSigningBuildSettingsAsync,
} from '../../../utils/ios/xcodeProject/signing';
import { parseInfoPlistBuffer } from '../../readIpaInfo';
const STEP_NAME = 'Build with Xcode';
interface ExportOptions {
keychainPath: string;
distributionType: DistributionType;
provisioningProfileUuidByBundleIdentifier: Record<string, string>;
iCloudContainerEnvironment?: string;
}
export function createBuildNativeIosBuildFunction(): BuildFunction {
return new BuildFunction({
namespace: 'eas',
id: 'build_native_ios',
name: STEP_NAME,
__metricsId: 'eas/build_native_ios',
inputProviders: [
BuildStepInput.createProvider({
id: 'project_file',
required: true,
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
}),
BuildStepInput.createProvider({
id: 'scheme',
required: true,
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
}),
BuildStepInput.createProvider({
id: 'build_configuration',
required: true,
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
}),
BuildStepInput.createProvider({
id: 'xcodeproj_path',
required: true,
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
}),
BuildStepInput.createProvider({
id: 'targets',
required: true,
allowedValueTypeName: BuildStepInputValueTypeName.JSON,
}),
],
outputProviders: [BuildStepOutput.createProvider({ id: 'archive_path', required: true })],
fn: async (stepsCtx, { inputs, outputs, env }) => {
const job = stepsCtx.global.staticContext.job as Ios.Job;
const projectFilePath = inputs.project_file.value as string;
const scheme = inputs.scheme.value as string;
const buildConfiguration = inputs.build_configuration.value as string;
const targets: XcodeTargetWithBundleIdentifier[] = z
.array(z.object({ id: z.string(), name: z.string(), bundleIdentifier: z.string() }))
.parse(inputs.targets.value);
const [applicationTarget] = targets;
const exportOptions = job.simulator
? undefined
: await configureSigningAsync(stepsCtx, {
credentialsByBundleIdentifier: job.secrets?.credentialsByBundleIdentifier ?? {},
targets,
xcodeprojPath: inputs.xcodeproj_path.value as string,
buildConfiguration,
env,
});
const buildDirectory = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'native-ios-build-'));
const derivedDataPath = path.join(buildDirectory, 'derived-data');
const outputDirectory = path.join(buildDirectory, 'output');
await fs.promises.writeFile(
path.join(buildDirectory, 'Gymfile'),
createGymfile({
projectFilePath,
scheme,
buildConfiguration,
derivedDataPath,
outputDirectory,
resultBundlePath: path.join(buildDirectory, 'build.xcresult'),
logsDirectory: stepsCtx.global.buildLogsDirectory,
exportOptions,
})
);
await fs.promises.mkdir(stepsCtx.global.buildLogsDirectory, { recursive: true });
try {
await runFastlaneGym({
workingDir: stepsCtx.workingDirectory,
gymfileDirectory: buildDirectory,
logger: stepsCtx.logger,
buildLogsDirectory: stepsCtx.global.buildLogsDirectory,
env,
});
} catch (err) {
throw new UserError(
'NATIVE_XCODE_BUILD_FAILED',
`The Xcode build failed. The errors are in the "${STEP_NAME}" step. Refer to "Xcode Logs" below for additional, more detailed logs.`,
{ cause: err }
);
}
const archivePath = job.simulator
? await findSimulatorAppAsync(derivedDataPath, applicationTarget.bundleIdentifier)
: (await fg('*.ipa', { cwd: outputDirectory, absolute: true }))[0];
if (!archivePath) {
throw new UserError(
'NATIVE_XCODE_NO_BUILD_OUTPUT',
job.simulator
? `The build finished, but EAS found no ".app" with the bundle identifier "${applicationTarget.bundleIdentifier}" in "${derivedDataPath}/Build/Products". Check in the Xcode logs which products the scheme "${scheme}" built.`
: `The build finished, but EAS found no ".ipa" in "${outputDirectory}". Check the Xcode logs for an export error.`
);
}
outputs.archive_path.set(archivePath);
},
});
}
async function configureSigningAsync(
{ logger }: BuildStepContext,
{
credentialsByBundleIdentifier,
targets,
xcodeprojPath,
buildConfiguration,
env,
}: {
credentialsByBundleIdentifier: Record<string, Ios.TargetCredentials>;
targets: XcodeTargetWithBundleIdentifier[];
xcodeprojPath: string;
buildConfiguration: string;
env: BuildStepEnv;
}
): Promise<ExportOptions> {
const targetsWithoutCredentials = targets.filter(
({ bundleIdentifier }) => !credentialsByBundleIdentifier[bundleIdentifier]
);
if (targetsWithoutCredentials.length > 0) {
throw new UserError(
'NATIVE_XCODE_MISSING_CREDENTIALS',
`The build job has no credentials for ${targetsWithoutCredentials
.map(({ name, bundleIdentifier }) => `"${bundleIdentifier}" (target "${name}")`)
.join(
', '
)}. EAS signs the application target and every target it depends on that needs a provisioning profile, and each one needs credentials for its bundle identifier. Add each bundle identifier with a distribution certificate and a provisioning profile on the Credentials page of the project on expo.dev, then run the build again.`
);
}
const credentialsByTargetName = Object.fromEntries(
targets.map(({ name, bundleIdentifier }) => [
name,
credentialsByBundleIdentifier[bundleIdentifier],
])
);
const { keychainPath, distributionType, targetProvisioningProfiles } =
await new IosCredentialsManager(credentialsByTargetName).prepare(logger);
const targetSignings = targets.map(target => {
const profile = targetProvisioningProfiles[target.name];
logger.info(
`Assigning provisioning profile '${profile.name}' (Apple Team ID: ${profile.teamId}) to target '${target.name}'`
);
return {
target,
buildSettings: {
PROVISIONING_PROFILE_SPECIFIER: profile.name,
DEVELOPMENT_TEAM: profile.teamId,
CODE_SIGN_IDENTITY:
distributionType === DistributionType.DEVELOPMENT
? profile.certificateCommonName
: 'iPhone Distribution',
CODE_SIGN_STYLE: 'Manual',
},
};
});
await writeSigningBuildSettingsAsync({ xcodeprojPath, buildConfiguration, targetSignings });
const effectiveBuildSettingsByTargetName = await readBuildSettingsByTargetNameAsync({
xcodeprojPath,
targetNames: targets.map(({ name }) => name),
buildConfiguration,
env,
logger,
});
assertSigningBuildSettingsAreEffective({
buildConfiguration,
targetSignings,
effectiveBuildSettingsByTargetName,
});
const [applicationTarget] = targets;
const iCloudContainerEnvironment = await readICloudContainerEnvironmentAsync(logger, {
targetName: applicationTarget.name,
buildSettings: effectiveBuildSettingsByTargetName[applicationTarget.name],
});
return {
keychainPath,
distributionType,
provisioningProfileUuidByBundleIdentifier: Object.fromEntries(
targets.map(({ name, bundleIdentifier }) => [
bundleIdentifier,
targetProvisioningProfiles[name].uuid,
])
),
iCloudContainerEnvironment,
};
}
async function readICloudContainerEnvironmentAsync(
logger: BuildStepContext['logger'],
{ targetName, buildSettings }: { targetName: string; buildSettings: Record<string, string> }
): Promise<string | undefined> {
if (!buildSettings.CODE_SIGN_ENTITLEMENTS) {
return undefined;
}
const entitlementsPath = path.resolve(
buildSettings.SRCROOT,
buildSettings.CODE_SIGN_ENTITLEMENTS
);
let environment: unknown;
try {
const entitlements = parseInfoPlistBuffer(await fs.promises.readFile(entitlementsPath));
environment = entitlements['com.apple.developer.icloud-container-environment'];
} catch (err) {
logger.warn(
{ err },
`EAS could not read the entitlements file "${entitlementsPath}" of the target "${targetName}", so the export does not set an iCloud container environment. If the app uses CloudKit, check that CODE_SIGN_ENTITLEMENTS points to a property list file in the repository.`
);
return undefined;
}
if (typeof environment !== 'string' || environment === '') {
return undefined;
}
logger.info(
`Exporting with the iCloud container environment "${environment}" from "${path.basename(entitlementsPath)}".`
);
return environment;
}
function createGymfile({
projectFilePath,
scheme,
buildConfiguration,
derivedDataPath,
outputDirectory,
resultBundlePath,
logsDirectory,
exportOptions,
}: {
projectFilePath: string;
scheme: string;
buildConfiguration: string;
derivedDataPath: string;
outputDirectory: string;
resultBundlePath: string;
logsDirectory: string;
exportOptions?: ExportOptions;
}): string {
const sharedVars = {
SCHEME: scheme,
SCHEME_BUILD_CONFIGURATION: buildConfiguration,
DERIVED_DATA_PATH: derivedDataPath,
RESULT_BUNDLE_PATH: resultBundlePath,
CLEAN: 'false',
LOGS_DIRECTORY: logsDirectory,
};
return [
`${isWorkspace(projectFilePath) ? 'workspace' : 'project'}(${JSON.stringify(projectFilePath)})`,
// xcodebuild refuses Swift package plugins and macros until someone approves them in the Xcode UI.
'xcargs("-skipPackagePluginValidation -skipMacroValidation")',
exportOptions
? templateString({
input: GymfileArchiveTemplate,
vars: {
...sharedVars,
OUTPUT_DIRECTORY: outputDirectory,
KEYCHAIN_PATH: exportOptions.keychainPath,
EXPORT_METHOD: exportOptions.distributionType,
PROFILES: Object.entries(exportOptions.provisioningProfileUuidByBundleIdentifier).map(
([bundleIdentifier, uuid]) => ({ BUNDLE_ID: bundleIdentifier, UUID: uuid })
),
ICLOUD_CONTAINER_ENVIRONMENT: exportOptions.iCloudContainerEnvironment,
},
mustache: false,
})
: templateString({
input: GymfileSimulatorTemplate,
vars: {
...sharedVars,
SCHEME_SIMULATOR_DESTINATION: 'generic/platform=iOS Simulator',
},
mustache: false,
}),
].join('\n');
}
async function findSimulatorAppAsync(
derivedDataPath: string,
bundleIdentifier: string
): Promise<string | undefined> {
const appPaths = await fg('Build/Products/*-iphonesimulator/*.app', {
cwd: derivedDataPath,
onlyDirectories: true,
absolute: true,
});
for (const appPath of appPaths) {
const infoPlist = parseInfoPlistBuffer(
await fs.promises.readFile(path.join(appPath, 'Info.plist'))
);
if (infoPlist.CFBundleIdentifier === bundleIdentifier) {
return appPath;
}
}
return undefined;
}
@@ -0,0 +1,176 @@
import { IOSConfig } from '@expo/config-plugins';
import { Ios, UserError } from '@expo/eas-build-job';
import {
BuildFunction,
BuildStepInput,
BuildStepInputValueTypeName,
BuildStepOutput,
} from '@expo/steps';
import path from 'node:path';
import { XcodeProject } from 'xcode';
import { readBuildSettingsByTargetNameAsync } from '../../../utils/ios/xcodeProject/buildSettings';
import {
XcodeTarget,
XcodeTargetWithBundleIdentifier,
findApplicationTargetById,
findDependencyTargets,
getBuildConfigurations,
openXcodeProject,
} from '../../../utils/ios/xcodeProject/pbxproj';
import { resolveProjectFilePathAsync } from '../../../utils/ios/xcodeProject/projectFile';
import {
XcodeSchemeDetails,
findSharedSchemesAsync,
readSchemeAsync,
selectScheme,
} from '../../../utils/ios/xcodeProject/schemes';
export function createDetectNativeXcodeBuildFunction(): BuildFunction {
return new BuildFunction({
namespace: 'eas',
id: 'detect_native_xcode',
name: 'Detect Xcode project',
__metricsId: 'eas/detect_native_xcode',
inputProviders: [
BuildStepInput.createProvider({
id: 'project_file',
required: false,
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
}),
BuildStepInput.createProvider({
id: 'scheme',
required: false,
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
}),
BuildStepInput.createProvider({
id: 'build_configuration',
required: false,
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
}),
BuildStepInput.createProvider({
id: 'expected_identifier',
required: false,
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
}),
],
outputProviders: [
BuildStepOutput.createProvider({ id: 'project_file', required: true }),
BuildStepOutput.createProvider({ id: 'scheme', required: true }),
BuildStepOutput.createProvider({ id: 'build_configuration', required: true }),
BuildStepOutput.createProvider({ id: 'xcodeproj_path', required: true }),
BuildStepOutput.createProvider({ id: 'targets', required: true }),
],
fn: async (stepsCtx, { inputs, outputs, env }) => {
const { logger, workingDirectory } = stepsCtx;
const job = stepsCtx.global.staticContext.job as Ios.Job;
const needsSigning = !job.simulator;
const projectFilePath = await resolveProjectFilePathAsync(
workingDirectory,
inputs.project_file.value as string | undefined
);
const schemes = await findSharedSchemesAsync(projectFilePath);
const scheme = selectScheme(schemes, {
requestedName: inputs.scheme.value as string | undefined,
logger,
});
const { applicationTargetReference, archiveConfiguration, launchConfiguration } =
await readSchemeAsync(scheme);
const application = openApplicationTarget(applicationTargetReference);
if (!application) {
const otherSchemeNames = schemes
.map(({ name }) => name)
.filter(name => name !== scheme.name);
throw new UserError(
'NATIVE_XCODE_NO_APPLICATION_TARGET',
`The scheme "${scheme.name}" does not build an iOS application target, so EAS has no app to sign and upload. ${
otherSchemeNames.length > 0
? `Other shared schemes: ${otherSchemeNames.sort().join(', ')}. Set "xcode_scheme" to the scheme of the app.`
: 'Share the scheme of the app in Xcode (Product > Scheme > Manage Schemes) and commit its ".xcscheme" file.'
}`
);
}
const { project, xcodeprojPath, target: applicationTarget } = application;
const buildConfiguration =
(inputs.build_configuration.value as string | undefined) ??
(needsSigning ? archiveConfiguration : launchConfiguration);
const buildConfigurationNames = getBuildConfigurations(project, applicationTarget.id).map(
({ name }) => IOSConfig.XcodeUtils.unquote(name)
);
if (!buildConfiguration || !buildConfigurationNames.includes(buildConfiguration)) {
throw new UserError(
'NATIVE_XCODE_BUILD_CONFIGURATION_NOT_FOUND',
`${
buildConfiguration
? `The target "${applicationTarget.name}" has no build configuration named "${buildConfiguration}".`
: `The scheme "${scheme.name}" names no build configuration for its ${needsSigning ? 'Archive' : 'Run'} action.`
} Build configurations of the target: ${buildConfigurationNames.join(', ')}. Set "xcode_configuration" to one of them.`
);
}
const dependencyTargets = needsSigning
? findDependencyTargets(project, applicationTarget.id)
: [];
const buildSettingsByTargetName = await readBuildSettingsByTargetNameAsync({
xcodeprojPath,
targetNames: [applicationTarget, ...dependencyTargets].map(({ name }) => name),
buildConfiguration,
sdk: job.simulator ? 'iphonesimulator' : undefined,
env,
logger,
});
const targets: XcodeTargetWithBundleIdentifier[] = [
applicationTarget,
// Xcode sets this on products that need a provisioning profile (DarwinProductTypes.xcspec).
...dependencyTargets.filter(
({ name }) => buildSettingsByTargetName[name]?.PROVISIONING_PROFILE_REQUIRED === 'YES'
),
].map(target => {
const bundleIdentifier = buildSettingsByTargetName[target.name]?.PRODUCT_BUNDLE_IDENTIFIER;
if (!bundleIdentifier) {
throw new UserError(
'NATIVE_XCODE_NO_BUNDLE_IDENTIFIER',
`The target "${target.name}" has no bundle identifier in the build configuration "${buildConfiguration}". EAS finds the built app and picks the signing credentials by bundle identifier, for the application target and for every target it depends on that needs a provisioning profile. Set PRODUCT_BUNDLE_IDENTIFIER for this target in Xcode.`
);
}
return { ...target, bundleIdentifier };
});
const expectedIdentifier = inputs.expected_identifier.value as string | undefined;
const [{ bundleIdentifier: applicationIdentifier }] = targets;
if (expectedIdentifier && applicationIdentifier !== expectedIdentifier) {
throw new UserError(
'NATIVE_XCODE_APP_IDENTIFIER_MISMATCH',
`"app_identifier" is "${expectedIdentifier}", but the target "${applicationTarget.name}" has the bundle identifier "${applicationIdentifier}" in the build configuration "${buildConfiguration}". Set "app_identifier" to "${applicationIdentifier}", or set "xcode_scheme" and "xcode_configuration" to the ones that build "${expectedIdentifier}".`
);
}
logger.info(
`Building the scheme "${scheme.name}" of "${path.basename(projectFilePath)}" with the build configuration "${buildConfiguration}".`
);
for (const { name, bundleIdentifier } of targets) {
logger.info(`Target "${name}": ${bundleIdentifier}`);
}
outputs.project_file.set(projectFilePath);
outputs.scheme.set(scheme.name);
outputs.build_configuration.set(buildConfiguration);
outputs.xcodeproj_path.set(xcodeprojPath);
outputs.targets.set(JSON.stringify(targets));
},
});
}
function openApplicationTarget(
reference: XcodeSchemeDetails['applicationTargetReference']
): { project: XcodeProject; xcodeprojPath: string; target: XcodeTarget } | undefined {
if (!reference) {
return undefined;
}
const project = openXcodeProject(reference.xcodeprojPath);
const target = findApplicationTargetById(project, reference.targetId);
return target && { project, xcodeprojPath: reference.xcodeprojPath, target };
}
@@ -0,0 +1,21 @@
import { BuildFunction } from '@expo/steps';
import fs from 'node:fs';
import path from 'node:path';
import { runPodInstallAsync } from '../../installPods';
export function createInstallNativePodsBuildFunction(): BuildFunction {
return new BuildFunction({
namespace: 'eas',
id: 'install_native_pods',
name: 'Install Pods',
__metricsId: 'eas/install_native_pods',
fn: async (stepsCtx, { env }) => {
if (!fs.existsSync(path.join(stepsCtx.workingDirectory, 'Podfile'))) {
stepsCtx.logger.info('The project directory has no Podfile. Skipping "pod install".');
return;
}
await runPodInstallAsync(stepsCtx, env);
},
});
}
@@ -0,0 +1,68 @@
import { Ios, UserError } from '@expo/eas-build-job';
import { BuildFunction, BuildStepInput, BuildStepInputValueTypeName } from '@expo/steps';
import fs from 'node:fs';
import path from 'node:path';
import { parseInfoPlistBuffer, readIpaInfoAsync } from '../../readIpaInfo';
export function createVerifyNativeIosBuildFunction(): BuildFunction {
return new BuildFunction({
namespace: 'eas',
id: 'verify_native_ios',
name: 'Verify the build artifact',
__metricsId: 'eas/verify_native_ios',
inputProviders: [
BuildStepInput.createProvider({
id: 'archive_path',
required: true,
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
}),
BuildStepInput.createProvider({
id: 'expected_identifier',
required: false,
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
}),
],
fn: async (stepsCtx, { inputs }) => {
const job = stepsCtx.global.staticContext.job as Ios.Job;
const archivePath = inputs.archive_path.value as string;
const expectedIdentifier = inputs.expected_identifier.value as string | undefined;
const expectedPlatformName = job.simulator ? 'iphonesimulator' : 'iphoneos';
const { bundleIdentifier, platformName } = await readArtifactInfoAsync(archivePath);
if (platformName !== expectedPlatformName) {
throw new UserError(
'NATIVE_XCODE_ARTIFACT_PLATFORM_MISMATCH',
`The build artifact "${path.basename(archivePath)}" was built for "${platformName}", but this build is for ${
job.simulator ? 'the iOS simulator' : 'iOS devices'
} and needs "${expectedPlatformName}". Check that the scheme builds an iOS app.`
);
}
if (expectedIdentifier && bundleIdentifier !== expectedIdentifier) {
throw new UserError(
'NATIVE_XCODE_ARTIFACT_IDENTIFIER_MISMATCH',
`The build artifact "${path.basename(archivePath)}" has the bundle identifier "${bundleIdentifier}", but "app_identifier" is "${expectedIdentifier}". Set "app_identifier" to "${bundleIdentifier}", or set "xcode_scheme" and "xcode_configuration" to the ones that build "${expectedIdentifier}".`
);
}
stepsCtx.logger.info(
`Verified "${path.basename(archivePath)}": ${bundleIdentifier}, built for ${platformName}.`
);
},
});
}
async function readArtifactInfoAsync(
archivePath: string
): Promise<{ bundleIdentifier: unknown; platformName: unknown }> {
if ((await fs.promises.stat(archivePath)).isDirectory()) {
const infoPlist = parseInfoPlistBuffer(
await fs.promises.readFile(path.join(archivePath, 'Info.plist'))
);
return {
bundleIdentifier: infoPlist.CFBundleIdentifier,
platformName: infoPlist.DTPlatformName,
};
}
const { bundleIdentifier, dtPlatformName } = await readIpaInfoAsync(archivePath);
return { bundleIdentifier, platformName: dtPlatformName };
}
@@ -5,10 +5,12 @@ import { z } from 'zod';
import { buildFlowNameToPathMap } from './maestroFlowDiscovery';
import {
MaestroFlowResult,
hasMaestroRunnerAttemptDirectories,
isFileAttrRun,
parseJUnitTestCases,
parseMaestroResults,
parseMaestroResultsFromFileAttrs,
parseMaestroRunnerResults,
} from './maestroResultParser';
import { CustomBuildContext } from '../../customBuildContext';
@@ -73,8 +75,15 @@ export function createReportMaestroTestResultsFunction(ctx: CustomBuildContext):
// map testcase names back to paths.
const usedFileAttrs = isFileAttrRun(await parseJUnitTestCases(junitDirectory));
const testsDirectory = (inputs.tests_directory.value as string | undefined) ?? '';
let flowResults: MaestroFlowResult[];
if (usedFileAttrs) {
if (usedFileAttrs && (await hasMaestroRunnerAttemptDirectories(testsDirectory))) {
flowResults = await parseMaestroRunnerResults({
junitDirectory,
testsDirectory,
workingDirectory: stepsCtx.workingDirectory,
});
} else if (usedFileAttrs) {
flowResults = await parseMaestroResultsFromFileAttrs(junitDirectory);
} else {
// Legacy (Maestro < 2.6.0) — DELETE this arm once the fleet is on >= 2.6.0.
@@ -1,4 +1,4 @@
import { Platform } from '@expo/eas-build-job';
import { Platform, formatBytes } from '@expo/eas-build-job';
import { bunyan } from '@expo/logger';
import { asyncResult } from '@expo/results';
import {
@@ -17,7 +17,6 @@ import * as tar from 'tar';
import { promisify } from 'util';
import z from 'zod';
import { formatBytes } from '../../utils/artifacts';
import { PUBLIC_CACHE_KEY_PREFIX_BY_PLATFORM } from '../../utils/cacheKey';
import { retryOnDNSFailure } from '../../utils/retryOnDNSFailure';
import { TurtleFetchError, turtleFetch } from '../../utils/turtleFetch';
@@ -4,6 +4,7 @@ import {
BuildStepInputValueTypeName,
BuildStepOutput,
} from '@expo/steps';
import path from 'path';
import { runFastlaneGym } from '../utils/ios/fastlane';
import { BuildStatusText, BuildStepOutputName } from '../utils/slackMessageDynamicFields';
@@ -39,6 +40,7 @@ export function runFastlaneFunction(): BuildFunction {
try {
await runFastlaneGym({
workingDir: stepCtx.workingDirectory,
gymfileDirectory: path.join(stepCtx.workingDirectory, 'ios'),
env,
logger: stepCtx.logger,
buildLogsDirectory: stepCtx.global.buildLogsDirectory,
@@ -1,4 +1,4 @@
import { Platform } from '@expo/eas-build-job';
import { Platform, formatBytes } from '@expo/eas-build-job';
import { bunyan } from '@expo/logger';
import { asyncResult } from '@expo/results';
import {
@@ -14,7 +14,6 @@ import os from 'os';
import path from 'path';
import { compressCacheAsync, uploadCacheAsync } from './saveCache';
import { formatBytes } from '../../utils/artifacts';
import {
CcacheBuildTarget,
generateDefaultBuildCacheKeyAsync,
@@ -1,4 +1,4 @@
import { Platform } from '@expo/eas-build-job';
import { Platform, formatBytes } from '@expo/eas-build-job';
import { bunyan } from '@expo/logger';
import { asyncResult } from '@expo/results';
import { BuildFunction, BuildStepInput, BuildStepInputValueTypeName } from '@expo/steps';
@@ -12,7 +12,6 @@ import * as tar from 'tar';
import z from 'zod';
import { uploadWithSignedUrl } from '../../storage/uploadWithSignedUrl';
import { formatBytes } from '../../utils/artifacts';
import { retryOnDNSFailure } from '../../utils/retryOnDNSFailure';
import { getCacheVersion } from '../utils/cache';
@@ -26,6 +26,7 @@ import { type StartupTasks } from '../utils/startupTasks';
import {
type DetachedProcessHandle,
DeviceRunSessionStoppedError,
TOOL_TUNNEL_TEARDOWN_OPTIONS,
finishRemoteSessionAsync,
getDeviceRunSessionIdOrThrow,
getNgrokAuthtokenOrThrow,
@@ -125,7 +126,8 @@ export async function runAgentDeviceRemoteSessionAsync(
device:
| {
booted: Promise<unknown>;
ready: Promise<unknown>;
/** Resolves with the identifier of the app it installed, if any. */
ready: Promise<string | void>;
}
| {
iosSimulatorUdid: string;
@@ -213,6 +215,7 @@ export async function runAgentDeviceRemoteSessionAsync(
authtoken: ngrokAuthtoken,
healthCheck: { path: '/health' },
logger: taskLogger,
signal: tasks.signal,
});
tasks.signal.throwIfAborted();
taskLogger.info(`Tunnel is ready at ${agentDeviceTunnel.url}.`);
@@ -242,6 +245,7 @@ export async function runAgentDeviceRemoteSessionAsync(
const [
{ port: daemonPort, token: daemonToken, remoteSessionUrl: agentDeviceRemoteSessionUrl },
webPreview,
installedApplicationIdentifier,
] = await Promise.all([agentDeviceStartup, sessionHostStartup, deviceReady]).catch(
(err: unknown) => {
// Also aborts for a `device.ready` that does not come from `tasks.run`.
@@ -251,6 +255,11 @@ export async function runAgentDeviceRemoteSessionAsync(
);
tasks.signal.throwIfAborted();
logger.info(tasks.summary());
// Reported so clients can attach to the app of a session with no build record, like an
// `application_archive_url` one. The session host already launched the iOS app.
const applicationIdentifier = hostBootedDevice?.application
? (await tasks.untilAborted(hostBootedDevice.application))?.launchAppIdentifier
: installedApplicationIdentifier;
const sessionStart = await uploadRemoteSessionConfigWithLocalEgressAsync({
env,
@@ -263,6 +272,7 @@ export async function runAgentDeviceRemoteSessionAsync(
webPreviewUrl: webPreview.previewPageUrl,
previewApiUrl: webPreview.apiUrl,
...(webPreview.previewToken ? { webPreviewToken: webPreview.previewToken } : {}),
...(applicationIdentifier ? { applicationIdentifier } : {}),
},
logger,
});
@@ -351,7 +361,7 @@ export async function runAgentDeviceRemoteSessionAsync(
? [['startup cleanup', Promise.reject(result.reason)]]
: []
),
['agent-device tunnel', agentDeviceTunnel?.stopAsync()],
['agent-device tunnel', agentDeviceTunnel?.stopAsync(), TOOL_TUNNEL_TEARDOWN_OPTIONS],
['agent-device daemon', toolTeardown],
[
'session host',
@@ -16,11 +16,8 @@ import {
AndroidVirtualDeviceName,
} from '../../utils/AndroidEmulatorUtils';
import { watchDeviceRunSessionStartup } from '../utils/deviceRunSessionStartup';
import {
AndroidEmulatorLogSourcesSchema,
LEGACY_ANDROID_EMULATOR_LOG_SOURCES,
} from '../../utils/androidEmulatorLogSources';
import { registerAndroidEmulatorLogDirectory } from '../utils/androidEmulatorLogs';
import { getAndroidEmulatorLogCapture } from '../utils/androidEmulatorLogs';
import { parseLogSourcesInput } from '../utils/logSourcesInput';
import { getDeviceRunSessionWorkerApi } from '../utils/deviceRunSessionWorkerApi';
import { readIosApplicationIdentifierAsync } from '../utils/iosAppArtifact';
import { resolveIosSessionStartupAsync } from '../utils/iosSimulatorSession';
@@ -76,10 +73,10 @@ export function createStartAgentDeviceSessionBuildFunction(
name: 'Start agent-device session',
__metricsId: warm ? 'eas/start_warm_agent_device_session' : 'eas/start_agent_device_session',
inputProviders: [
// No default: an omitted input must stay distinguishable from an explicit selection.
BuildStepInput.createProvider({
id: 'android_log_sources',
id: 'log_sources',
required: false,
defaultValue: [...LEGACY_ANDROID_EMULATOR_LOG_SOURCES],
allowedValueTypeName: BuildStepInputValueTypeName.JSON,
}),
// Device. On iOS a Simulator name or UDID, on Android an AVD hardware profile.
@@ -199,6 +196,10 @@ export function createStartAgentDeviceSessionBuildFunction(
} else {
validateAndroidLaunchOptions({ launchArgs, openUrl });
}
const logSources = parseLogSourcesInput(inputs.log_sources.value, {
runtimePlatform,
fallback: isIos ? [] : ['emulator-output'],
});
const deviceIdentifier = inputs.device_identifier.value as string | undefined;
const capture = parseNetworkCaptureInputs(
{
@@ -216,12 +217,16 @@ export function createStartAgentDeviceSessionBuildFunction(
logger,
startup: { signal: startupSignal, abort: reason => startup.abort(reason) },
});
const startSessionAsync = async (warmSession?: WarmIosSession): Promise<void> => {
const startSessionAsync = async (
warmSession?: WarmIosSession,
resolvedPackageVersion = inputs.package_version.value as string | undefined
): Promise<void> => {
const tasks = createStartupTasks(logger, startupSignal);
let booted: Promise<void> | undefined;
let sessionOwnsTeardown = false;
let downloaded: Promise<string> | undefined;
let applicationReady: Promise<ServeSimApplicationOptions | void> | undefined;
let installedAndroidApplication: Promise<string> | undefined;
try {
if (isIos) {
@@ -252,13 +257,9 @@ export function createStartAgentDeviceSessionBuildFunction(
booted = iosSimulatorUdid
? Promise.resolve()
: tasks.run('Android Emulator boot', async taskLogger => {
const logSources = AndroidEmulatorLogSourcesSchema.parse(
inputs.android_log_sources.value
);
const logcatDirectory = await fs.promises.mkdtemp(
path.join(os.tmpdir(), 'eas-android-emulator-logcat-')
);
const capture = registerAndroidEmulatorLogDirectory(global, logcatDirectory);
tasks.signal.throwIfAborted();
await startAndroidEmulatorAsync({
deviceName: ANDROID_DEVICE_NAME,
@@ -268,8 +269,7 @@ export function createStartAgentDeviceSessionBuildFunction(
lcdHeight: inputs.lcd_height.value as number | undefined,
lcdDensity: inputs.lcd_density.value as number | undefined,
logcatDirectory,
logSources,
logCapture: env.DEVICE_RUN_SESSION_ID ? capture : undefined,
logCapture: getAndroidEmulatorLogCapture(global, env, logSources),
env,
logger: taskLogger,
});
@@ -322,7 +322,7 @@ export function createStartAgentDeviceSessionBuildFunction(
installAppPath,
});
} else if (!isIos && (installAppPath || downloadedApp)) {
applicationReady = tasks.run('app install and launch', async taskLogger => {
installedAndroidApplication = tasks.run('app install and launch', async taskLogger => {
await tasks.untilAborted(booted!);
const artifactPath = installAppPath ?? (await downloadedApp);
if (!artifactPath) {
@@ -345,6 +345,7 @@ export function createStartAgentDeviceSessionBuildFunction(
env,
logger: taskLogger,
});
return applicationIdentifier;
});
}
@@ -355,7 +356,7 @@ export function createStartAgentDeviceSessionBuildFunction(
signal,
runtimePlatform,
sessionEnv,
packageVersion: inputs.package_version.value as string | undefined,
packageVersion: resolvedPackageVersion,
// A missing or non-positive value disables the idle timeout (opt-in feature).
maxIdleTimeMinutes: inputs.max_idle_time_minutes.value as number | undefined,
maxDurationSeconds: inputs.max_duration_seconds.value as number | undefined,
@@ -375,7 +376,7 @@ export function createStartAgentDeviceSessionBuildFunction(
}
: {
booted,
ready: applicationReady ?? tasks.untilAborted(booted),
ready: installedAndroidApplication ?? tasks.untilAborted(booted),
},
});
} catch (error) {
@@ -389,7 +390,12 @@ export function createStartAgentDeviceSessionBuildFunction(
throw error;
} finally {
tasks.abort(new Error('Agent-device session ended.'));
await Promise.allSettled([booted, downloaded, applicationReady]);
await Promise.allSettled([
booted,
downloaded,
applicationReady,
installedAndroidApplication,
]);
}
};
try {
@@ -23,12 +23,14 @@ import {
import { type AndroidEmulatorLogCapture } from '../../utils/androidEmulatorLogCapture';
import { retryAsync } from '../../utils/retry';
import { resolveAndroidEmulatorLocalEgressAsync } from '../utils/androidLocalEgress';
import { ALL_ANDROID_EMULATOR_LOG_SOURCES } from '../../utils/androidEmulatorLogSources';
import { getAndroidEmulatorLogCapture } from '../utils/androidEmulatorLogs';
import {
type AndroidEmulatorLogSource,
AndroidEmulatorLogSourcesSchema,
LEGACY_ANDROID_EMULATOR_LOG_SOURCES,
} from '../../utils/androidEmulatorLogSources';
import { registerAndroidEmulatorLogDirectory } from '../utils/androidEmulatorLogs';
EMULATOR_CAPTURE_REQUESTED_ENV,
installEmulatorCaptureAsync,
parseExperimentalEmulatorCaptureVersionInput,
} from '../utils/emulatorCapture';
import { parseLogSourcesInput } from '../utils/logSourcesInput';
const ANDROID_STARTUP_ATTEMPT_TIMEOUT_MS = [60_000, 120_000, 180_000];
const ANDROID_STARTUP_RETRIES_COUNT = ANDROID_STARTUP_ATTEMPT_TIMEOUT_MS.length - 1;
@@ -41,9 +43,9 @@ export function createStartAndroidEmulatorBuildFunction(): BuildFunction {
__metricsId: 'eas/start_android_emulator',
inputProviders: [
BuildStepInput.createProvider({
id: 'android_log_sources',
id: 'log_sources',
required: false,
defaultValue: [...LEGACY_ANDROID_EMULATOR_LOG_SOURCES],
defaultValue: [...ALL_ANDROID_EMULATOR_LOG_SOURCES],
allowedValueTypeName: BuildStepInputValueTypeName.JSON,
}),
BuildStepInput.createProvider({
@@ -84,6 +86,12 @@ export function createStartAndroidEmulatorBuildFunction(): BuildFunction {
defaultValue: 1,
allowedValueTypeName: BuildStepInputValueTypeName.NUMBER,
}),
// Experimental: the expo-emulator-capture version that the emulator preloads.
BuildStepInput.createProvider({
id: 'experimental_emulator_capture_version',
required: false,
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
}),
],
outputProviders: [
BuildStepOutput.createProvider({
@@ -92,16 +100,40 @@ export function createStartAndroidEmulatorBuildFunction(): BuildFunction {
}),
],
fn: async ({ logger, global }, { inputs, outputs, env }) => {
const logSources = AndroidEmulatorLogSourcesSchema.parse(inputs.android_log_sources.value);
const count = Number(inputs.count.value ?? 1);
const emulatorCaptureVersion = parseExperimentalEmulatorCaptureVersionInput(
inputs.experimental_emulator_capture_version.value
);
if (emulatorCaptureVersion && count > 1) {
throw new UserError(
'EAS_EMULATOR_CAPTURE_INVALID_INPUT',
'experimental_emulator_capture_version supports one emulator. Remove it, or set count to 1.'
);
}
const logSources = parseLogSourcesInput(inputs.log_sources.value, {
runtimePlatform: global.runtimePlatform,
fallback: ALL_ANDROID_EMULATOR_LOG_SOURCES,
});
if (emulatorCaptureVersion) {
// Marks the request for the session step, which rejects session types that cannot use
// the capture. The mark does not depend on the install, so the rejection does not either.
global.updateEnv({
...global.env,
[EMULATOR_CAPTURE_REQUESTED_ENV]: emulatorCaptureVersion,
});
}
const emulatorCaptureLibrary = emulatorCaptureVersion
? await installEmulatorCaptureAsync({ version: emulatorCaptureVersion, env, logger })
: undefined;
const logcatDirectory = await fs.promises.mkdtemp(
path.join(os.tmpdir(), 'eas-android-emulator-logcat-')
);
const capture = registerAndroidEmulatorLogDirectory(global, logcatDirectory);
const logCapture = env.DEVICE_RUN_SESSION_ID ? capture : undefined;
const logCapture = getAndroidEmulatorLogCapture(global, env, logSources);
outputs.logcat_directory.set(logcatDirectory);
const deviceName = `${inputs.device_name.value}` as AndroidVirtualDeviceName;
const { serialId, emulatorPromise, shouldAdjustAnimationScale } =
const { serialId, emulatorPromise, shouldAdjustAnimationScale, emulatorCaptureSocketPath } =
await startAndroidEmulatorAsync({
deviceName,
systemImagePackage: `${inputs.system_image_package.value}`,
@@ -111,13 +143,24 @@ export function createStartAndroidEmulatorBuildFunction(): BuildFunction {
lcdHeight: inputs.lcd_height.value as number | undefined,
lcdDensity: inputs.lcd_density.value as number | undefined,
logcatDirectory,
logSources,
logCapture,
env,
logger,
emulatorCaptureLibrary,
});
if (emulatorCaptureLibrary && emulatorCaptureSocketPath) {
// The session step starts expo-device-hub with the job env. A Hub version without the
// emulator capture ignores these variables.
global.updateEnv({
...global.env,
EXPO_DEVICE_HUB_EXPERIMENTAL_EMULATOR_CAPTURE: '1',
EXPO_DEVICE_HUB_EMULATOR_CAPTURE_LIBRARY: emulatorCaptureLibrary,
});
logger.info(
`${serialId} preloads expo-emulator-capture@${emulatorCaptureVersion} with -gpu lavapipe, and its agent socket is ${emulatorCaptureSocketPath}. Later steps start expo-device-hub with the emulator capture on.`
);
}
const count = Number(inputs.count.value ?? 1);
if (count > 1) {
logger.info(`Requested ${count} emulators, shutting down ${deviceName} for cloning.`);
await spawn('adb', ['-s', serialId, 'shell', 'reboot', '-p'], {
@@ -151,7 +194,6 @@ export function createStartAndroidEmulatorBuildFunction(): BuildFunction {
deviceName: cloneIdentifier,
env,
logcatDirectory,
logSources,
logCapture,
});
cloneSerialId = startResult.serialId;
@@ -222,10 +264,10 @@ export async function startAndroidEmulatorAsync({
lcdHeight,
lcdDensity,
logcatDirectory,
logSources,
logCapture,
env,
logger,
emulatorCaptureLibrary,
}: {
deviceName: AndroidVirtualDeviceName;
systemImagePackage: string;
@@ -234,14 +276,17 @@ export async function startAndroidEmulatorAsync({
lcdHeight?: number;
lcdDensity?: number;
logcatDirectory: string;
logSources?: readonly AndroidEmulatorLogSource[];
logCapture?: AndroidEmulatorLogCapture;
logCapture: AndroidEmulatorLogCapture;
env: BuildStepEnv;
logger: bunyan;
/** The expo-emulator-capture agent library that the emulator preloads (experimental). */
emulatorCaptureLibrary?: string;
}): Promise<{
serialId: AndroidDeviceSerialId;
emulatorPromise: Promise<unknown>;
shouldAdjustAnimationScale: boolean;
/** The capture agent's socket, when the emulator preloads the agent on the expected serial. */
emulatorCaptureSocketPath?: string;
}> {
if (env.EAS_NO_EMULATOR_HOST_SUPPORT_CHECK !== '1') {
await assertAndroidEmulatorHostSupportAsync({ env });
@@ -289,8 +334,16 @@ export async function startAndroidEmulatorAsync({
}
);
// expo-device-hub gets the job env and finds the agent sockets in `<tmpdir>/expo-emulator-capture`,
// where Node's os.tmpdir() applies this rule to that env. On EAS, TMPDIR is not set.
const captureSocketDirectory = path.join(
env.TMPDIR || env.TMP || env.TEMP || '/tmp',
'expo-emulator-capture'
);
let emulatorPromise = null;
let serialId = null;
// Set by the attempt that starts; the cast keeps the type wide after the retry callback.
let captureLaunch = undefined as { consolePort: number; socketPath: string } | undefined;
await retryAsync(
async attemptCount => {
const timeoutMs = ANDROID_STARTUP_ATTEMPT_TIMEOUT_MS[attemptCount];
@@ -313,13 +366,37 @@ export async function startAndroidEmulatorAsync({
});
logger.info(`Starting emulator device${attemptSuffix}.`);
// expo-device-hub finds the capture agent's socket by the serial, so the console port,
// which sets the serial, is chosen before the start, again for each attempt.
const consolePort = emulatorCaptureLibrary
? await AndroidEmulatorUtils.findFreeConsolePortAsync()
: undefined;
const launch =
consolePort !== undefined
? {
consolePort,
socketPath: path.join(captureSocketDirectory, `emulator-${consolePort}.sock`),
}
: undefined;
const startResult = await AndroidEmulatorUtils.startAsync({
deviceName,
env,
logcatDirectory,
logSources,
logCapture,
...(localEgress ? { launchGate: localEgress.launchGate } : {}),
...(emulatorCaptureLibrary && launch
? {
consolePort: launch.consolePort,
// The Linux agent kept 60 fps with the lavapipe renderer.
extraArgs: ['-gpu', 'lavapipe'],
extraEnv: {
// A library that the job already preloads stays preloaded, after the agent.
LD_PRELOAD: [emulatorCaptureLibrary, env.LD_PRELOAD].filter(Boolean).join(':'),
// The agent creates the directory.
EXPO_EMULATOR_CAPTURE_SOCKET: launch.socketPath,
},
}
: {}),
});
attemptSerialId = startResult.serialId;
await AndroidEmulatorUtils.waitForReadyAsync({
@@ -341,6 +418,7 @@ export async function startAndroidEmulatorAsync({
serialId = attemptSerialId;
emulatorPromise = startResult.emulatorPromise;
captureLaunch = launch;
} catch (err) {
logger.warn({ err }, `${deviceName} failed to start on attempt ${attempt}/${maxAttempts}.`);
try {
@@ -374,7 +452,19 @@ export async function startAndroidEmulatorAsync({
if (!serialId || !emulatorPromise) {
throw new Error(`Failed to start emulator ${deviceName}.`);
}
return { serialId, emulatorPromise, shouldAdjustAnimationScale };
// The Hub looks for the socket by serial. $ANDROID_EMULATOR_EXTRA_ARGS can override -port.
if (captureLaunch && serialId !== `emulator-${captureLaunch.consolePort}`) {
logger.warn(
`${serialId} does not use console port ${captureLaunch.consolePort}, so expo-device-hub cannot find its capture agent socket ${captureLaunch.socketPath}. The session streams without the emulator capture. Remove -port from $ANDROID_EMULATOR_EXTRA_ARGS.`
);
captureLaunch = undefined;
}
return {
serialId,
emulatorPromise,
shouldAdjustAnimationScale,
emulatorCaptureSocketPath: captureLaunch?.socketPath,
};
}
async function assertAndroidEmulatorHostSupportAsync({
@@ -14,6 +14,8 @@ import os from 'node:os';
import path from 'node:path';
import { setTimeout as setTimeoutAsync } from 'node:timers/promises';
import semver from 'semver';
import bplistParser from 'bplist-parser';
import plist from 'plist';
import { z } from 'zod';
import { type CustomBuildContext } from '../../customBuildContext';
@@ -43,11 +45,14 @@ import {
import { killProcessGroup } from '../../utils/processes';
import { sleepAsync } from '../../utils/retry';
import { turtleFetch } from '../../utils/turtleFetch';
import { resolveSimulatorPackageVersionAsync } from '../../utils/simulatorPackageVersion';
import { readPreparedSimulatorToolAsync } from '../../utils/warmSimulator';
import { startAppiumEventCollectionAsync } from '../utils/appiumEvents';
import { preparePreinstalledWdaAsync } from '../utils/preinstalledWda';
import { watchDeviceRunSessionStartup } from '../utils/deviceRunSessionStartup';
import {
DeviceRunSessionStoppedError,
TOOL_TUNNEL_TEARDOWN_OPTIONS,
createCorsOriginsInputProvider,
createFrameAncestorsInputProvider,
createIosSessionStartupInputProviders,
@@ -79,6 +84,12 @@ const AppiumInstalledDriversSchema = z.record(
z.string(),
z.object({ installed: z.boolean().optional() }).passthrough()
);
const PreparedAppiumSchema = z.object({
version: z.string(),
xcuitest: z.string(),
home: z.string(),
});
const PackageVersionSchema = z.object({ version: z.string() });
export function createStartAppiumRemoteSessionBuildFunction(
ctx: CustomBuildContext,
@@ -127,6 +138,7 @@ export function createStartAppiumRemoteSessionBuildFunction(
startup: { signal: watchSignal, abort: reason => startupStop.abort(reason) },
});
const deviceIdentifier = inputs.device_identifier?.value as string | undefined;
let requestedVersion: string | undefined;
const startSessionAsync = async (warmSession?: WarmIosSession): Promise<void> => {
const startupAbortController = new AbortController();
const startupSignal = AbortSignal.any([watchSignal, startupAbortController.signal]);
@@ -149,7 +161,21 @@ export function createStartAppiumRemoteSessionBuildFunction(
},
{ runtimePlatform }
);
const versionSpec = resolveAppium3VersionSpec(packageVersion);
const resolveRequestedVersionAsync =
packageVersion === undefined
? undefined
: async (): Promise<string> =>
(requestedVersion ??= await resolveSimulatorPackageVersionAsync(
'appium',
packageVersion,
{ env, signal: startupSignal }
));
// Keep cold ranges on the configured installer's path. Tags need resolution to enforce Appium 3.
const versionSpec = resolveAppium3VersionSpec(
packageVersion !== undefined && !semver.validRange(packageVersion)
? await resolveRequestedVersionAsync!()
: packageVersion
);
logger.info(
`Starting Appium remote session (version: ${versionSpec}, runtime: ${runtimePlatform}).`
@@ -211,6 +237,7 @@ export function createStartAppiumRemoteSessionBuildFunction(
asyncResult(
installAppiumAsync({
versionSpec,
resolveRequestedVersionAsync,
driverName: device.driverName,
env,
logger,
@@ -231,7 +258,8 @@ export function createStartAppiumRemoteSessionBuildFunction(
),
]);
const installation = appiumInstall.enforceValue();
appiumHome = installation.appiumHome;
// A prepared home is shared across sessions; remove only a job-owned home after a session.
appiumHome = installation.prepared ? undefined : installation.appiumHome;
startupSignal?.throwIfAborted();
const { appiumBinPath, appiumEnv } = installation;
const wdaCapabilities = await preparePreinstalledWdaAsync({
@@ -243,7 +271,8 @@ export function createStartAppiumRemoteSessionBuildFunction(
})
)?.runtime
: device.runtimeIdentifier,
appiumHome,
appiumHome: installation.appiumHome,
prepared: installation.prepared,
appiumBinPath,
appiumEnv,
logger,
@@ -300,6 +329,7 @@ export function createStartAppiumRemoteSessionBuildFunction(
authtoken: ngrokAuthtoken,
healthCheck: { path: '/status' },
logger,
signal: startupSignal,
});
// The preview host uses the same device selected for Appium.
@@ -387,7 +417,7 @@ export function createStartAppiumRemoteSessionBuildFunction(
logger,
sessionFailed,
teardown: [
['Appium tunnel', appiumTunnel?.stopAsync()],
['Appium tunnel', appiumTunnel?.stopAsync(), TOOL_TUNNEL_TEARDOWN_OPTIONS],
['Appium server', appiumTeardown],
[
'session host',
@@ -418,7 +448,8 @@ export function createStartAppiumRemoteSessionBuildFunction(
watchSignal.throwIfAborted();
if (warm && runtimePlatform === BuildRuntimePlatform.DARWIN) {
await runOnWarmIosSimulatorAsync(
// package_version is the Appium version, which the job installs either way.
// package_version is the Appium version. The job installs it or uses the prepared
// home; the warm claim does not depend on it.
{
engine: 'appium',
requestedDevice: deviceIdentifier,
@@ -503,6 +534,7 @@ export async function resolveAppiumDeviceAsync({
export async function installAppiumAsync({
versionSpec,
resolveRequestedVersionAsync,
driverName,
env,
logger,
@@ -510,13 +542,53 @@ export async function installAppiumAsync({
onError,
}: {
versionSpec: string;
resolveRequestedVersionAsync?: () => Promise<string>;
driverName: AppiumDevice['driverName'];
env: BuildStepEnv;
logger: bunyan;
signal?: AbortSignal;
onError?: (error: unknown) => void;
}): Promise<{ appiumHome: string; appiumBinPath: string; appiumEnv: BuildStepEnv }> {
}): Promise<{
appiumHome: string;
appiumBinPath: string;
appiumEnv: BuildStepEnv;
prepared: boolean;
}> {
signal?.throwIfAborted();
let prepared =
driverName === 'xcuitest'
? await readPreparedSimulatorToolAsync('appium', PreparedAppiumSchema)
: undefined;
if (
prepared &&
!(await isPreparedAppiumCompatibleAsync(prepared, { versionSpec, env, signal }))
) {
prepared = undefined;
}
if (prepared && resolveRequestedVersionAsync) {
versionSpec = resolveAppium3VersionSpec(await resolveRequestedVersionAsync());
if (!semver.satisfies(prepared.version, versionSpec)) {
prepared = undefined;
}
}
if (prepared) {
try {
// An invalid package manager override fails as it does without a prepared home.
resolveConfiguredPackageManager(env, PackageManager.NPM);
} catch (error) {
onError?.(error);
throw error;
}
logger.info(
`Using the prefetched Appium home (appium ${prepared.version}, xcuitest ${prepared.xcuitest}).`
);
return {
appiumHome: prepared.home,
appiumBinPath: path.join(prepared.home, 'node_modules', '.bin', 'appium'),
appiumEnv: { ...env, APPIUM_HOME: prepared.home },
prepared: true,
};
}
const appiumHome = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'eas-appium-home-'));
try {
signal?.throwIfAborted();
@@ -569,7 +641,7 @@ export async function installAppiumAsync({
signal
);
}
return { appiumHome, appiumBinPath, appiumEnv };
return { appiumHome, appiumBinPath, appiumEnv, prepared: false };
} catch (error) {
onError?.(error);
if (signal) {
@@ -580,6 +652,67 @@ export async function installAppiumAsync({
}
}
/** A metadata hit still needs Appium-specific version, driver and runner checks before reuse. */
async function isPreparedAppiumCompatibleAsync(
prepared: z.infer<typeof PreparedAppiumSchema>,
{ versionSpec, env, signal }: { versionSpec: string; env: BuildStepEnv; signal?: AbortSignal }
): Promise<boolean> {
const { home } = prepared;
if (home !== path.join(os.homedir(), 'Library', 'Caches', 'expo-simulator-startup', 'appium')) {
return false;
}
try {
const installedVersionAsync = async (name: string): Promise<string> =>
PackageVersionSchema.parse(
JSON.parse(
await fs.promises.readFile(path.join(home, 'node_modules', name, 'package.json'), 'utf8')
)
).version;
if (
!semver.satisfies(prepared.version, versionSpec) ||
(await installedVersionAsync('appium')) !== prepared.version ||
(await installedVersionAsync('appium-xcuitest-driver')) !== prepared.xcuitest
) {
return false;
}
const runner = path.join(home, 'preinstalled-wda', 'WebDriverAgentRunner-Runner.app');
await fs.promises.access(runner, fs.constants.R_OK | fs.constants.X_OK);
if (!(await fs.promises.stat(runner)).isDirectory()) {
return false;
}
const metadata = await fs.promises.readFile(path.join(runner, 'Info.plist'));
const info =
metadata.subarray(0, 8).toString('ascii') === 'bplist00'
? bplistParser.parseBuffer(metadata)[0]
: plist.parse(metadata.toString('utf8'));
const executable = z
.object({ CFBundleExecutable: z.string().min(1) })
.parse(info).CFBundleExecutable;
if (path.basename(executable) !== executable || executable === '.' || executable === '..') {
return false;
}
const executablePath = path.join(runner, executable);
await fs.promises.access(executablePath, fs.constants.R_OK | fs.constants.X_OK);
const executableStat = await fs.promises.stat(executablePath);
if (!executableStat.isFile() || executableStat.size === 0) {
return false;
}
// Today's driver list shows that the Appium CLI runs from this home. It does not load the driver.
const { stdout } = await runAppiumSetupCommandAsync(
path.join(home, 'node_modules', '.bin', 'appium'),
['driver', 'list', '--installed', '--json'],
{ env: { ...env, APPIUM_HOME: home }, stdio: 'pipe' },
signal
);
if (!AppiumInstalledDriversSchema.parse(JSON.parse(stdout)).xcuitest?.installed) {
return false;
}
return true;
} catch {
return false;
}
}
async function runAppiumSetupCommandAsync(
command: string,
args: string[],
@@ -44,6 +44,7 @@ import { ARGENT_EVENT_LOG_FILENAME, startArgentEventCollectionAsync } from '../u
import { watchDeviceRunSessionStartup } from '../utils/deviceRunSessionStartup';
import {
DeviceRunSessionStoppedError,
TOOL_TUNNEL_TEARDOWN_OPTIONS,
createCorsOriginsInputProvider,
createFrameAncestorsInputProvider,
createIosSessionStartupInputProviders,
@@ -137,13 +138,6 @@ export function createStartArgentRemoteSessionBuildFunction(
// 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;
validateControllerVersion({
packageName: ARGENT_PACKAGE_NAME,
minimumVersion: MIN_ARGENT_REMOTE_SESSION_VERSION,
packageVersion,
logger,
});
const versionSpec = packageVersion ?? 'latest';
const { runtimePlatform } = global;
const startupStop = new AbortController();
const watchSignal = signal
@@ -156,7 +150,17 @@ export function createStartArgentRemoteSessionBuildFunction(
startup: { signal: watchSignal, abort: reason => startupStop.abort(reason) },
});
const deviceIdentifier = inputs.device_identifier?.value as string | undefined;
const startSessionAsync = async (warmSession?: WarmIosSession): Promise<void> => {
const startSessionAsync = async (
warmSession?: WarmIosSession,
resolvedPackageVersion = packageVersion
): Promise<void> => {
const versionSpec = resolvedPackageVersion ?? 'latest';
validateControllerVersion({
packageName: ARGENT_PACKAGE_NAME,
minimumVersion: MIN_ARGENT_REMOTE_SESSION_VERSION,
packageVersion: resolvedPackageVersion,
logger,
});
const startupAbortController = new AbortController();
const startupSignal = AbortSignal.any([watchSignal, startupAbortController.signal]);
const { launch, iosStartup } = await resolveIosSessionStartupAsync({
@@ -383,6 +387,7 @@ export function createStartArgentRemoteSessionBuildFunction(
rewriteHostHeader: true,
healthCheck: { path: '/tools', statuses: [200, 401] },
logger,
signal: startupSignal,
});
const publicToolsUrl = toolsTunnel.url;
logger.info(`Tunnel is ready at ${publicToolsUrl}.`);
@@ -478,7 +483,7 @@ export function createStartArgentRemoteSessionBuildFunction(
logger,
sessionFailed,
teardown: [
['Argent tunnel', toolsTunnel?.stopAsync()],
['Argent tunnel', toolsTunnel?.stopAsync(), TOOL_TUNNEL_TEARDOWN_OPTIONS],
['Argent tool-server', toolTeardown],
[
'session host',
@@ -170,6 +170,7 @@ export function createStartLocalEgressBuildFunction(): BuildFunction {
baseDomain: ngrokTunnelDomain,
authtoken: ngrokAuthtoken,
logger,
signal: startupSignal,
}),
startupSignal,
async listener => await listener?.stopAsync(),
@@ -1,21 +1,11 @@
import { SystemError, UserError } from '@expo/eas-build-job';
import { ArchiveSourceType, SystemError, UserError } from '@expo/eas-build-job';
import { BuildFunction, BuildStepInput, BuildStepInputValueTypeName } from '@expo/steps';
import { graphql } from 'gql.tada';
import { stripRepositoryCredentialsAsync } from '../../common/git';
import { CustomBuildContext } from '../../customBuildContext';
import { graphqlAbortContext } from '../../utils/graphqlAbort';
import { withLogPhaseAsync } from '../../utils/logPhase';
import { startSandboxDaemonAsync } from '../utils/sandboxDaemon';
const MARK_SANDBOX_READY_MUTATION = graphql(`
mutation MarkSandboxReady($sandboxId: ID!) {
sandbox {
markSandboxReady(sandboxId: $sandboxId) {
id
}
}
}
`);
import { requireSandboxWorkerApi } from '../utils/sandboxWorkerApi';
const RECONNECT_DELAY_MS = 1_000;
const AWAIT_SANDBOX_STEP_NAME = 'Await sandbox completion';
@@ -39,16 +29,11 @@ export function createStartSandboxBuildFunction(ctx: CustomBuildContext): BuildF
}),
],
fn: async (stepCtx, { inputs, signal, env }) => {
// The daemon needs this credential, but shell commands do not.
const { __EAS_SANDBOX_MCP_TOKEN: sandboxToken, ...commandEnv } = env;
if (!sandboxToken) {
throw new SystemError('__EAS_SANDBOX_MCP_TOKEN is required to start the sandbox daemon.');
}
const workerApi = requireSandboxWorkerApi(ctx);
const mcpServerUrl = ctx.mcpServerUrl;
if (!mcpServerUrl) {
throw new SystemError('MCP server URL is required to start the sandbox daemon.');
}
const sandboxId = String(inputs.sandbox_id.value);
const maxDurationSeconds = inputs.max_duration_seconds?.value;
if (
maxDurationSeconds !== undefined &&
@@ -61,21 +46,35 @@ export function createStartSandboxBuildFunction(ctx: CustomBuildContext): BuildF
`Invalid sandbox maximum duration: ${String(maxDurationSeconds)}. Provide a finite number greater than zero, or omit max_duration_seconds.`
);
}
if (ctx.job.projectArchive.type === ArchiveSourceType.GIT) {
// Scripts and commands inside the sandbox could read the token from .git/config.
await stripRepositoryCredentialsAsync({
repositoryDirectory: stepCtx.global.wasCheckedOut()
? ctx.projectTargetDirectory
: ctx.projectSourceDirectory,
});
}
const daemon = await startSandboxDaemonAsync({
credential: sandboxToken,
credential: workerApi.token,
serverUrl: mcpServerUrl,
reconnectDelayMs: RECONNECT_DELAY_MS,
logger: stepCtx.logger,
signal,
workingDirectory: stepCtx.workingDirectory,
env: commandEnv,
graphqlClient: ctx.graphqlClient,
sandboxId,
env,
workerApi,
});
try {
await daemon.ready;
signal?.throwIfAborted();
await markSandboxReadyAsync(ctx, sandboxId, signal);
await workerApi.markReadyAsync({ signal }).catch((error: unknown) => {
signal?.throwIfAborted();
throw new SystemError(
`Failed to mark sandbox ${String(inputs.sandbox_id.value)} as ready.`,
{ cause: error }
);
});
signal?.throwIfAborted();
stepCtx.logger.info('Sandbox daemon started.');
@@ -103,23 +102,6 @@ export function createStartSandboxBuildFunction(ctx: CustomBuildContext): BuildF
});
}
export async function markSandboxReadyAsync(
ctx: CustomBuildContext,
sandboxId: string,
signal?: AbortSignal
): Promise<void> {
signal?.throwIfAborted();
const result = await ctx.graphqlClient
.mutation(MARK_SANDBOX_READY_MUTATION, { sandboxId }, graphqlAbortContext(signal))
.toPromise();
signal?.throwIfAborted();
if (result.error) {
throw new SystemError(`Failed to mark sandbox ${sandboxId} as ready.`, {
cause: result.error,
});
}
}
async function waitForCompletionAsync(signal: AbortSignal): Promise<void> {
if (signal.aborted) {
return;
@@ -0,0 +1,26 @@
import { BuildFunction, BuildRuntimePlatform } from '@expo/steps';
import { Sentry } from '../../sentry';
import { ServeSimCrashesRecorder } from '../utils/serveSimCrashesRecorder';
export function createStartServeSimCrashesBuildFunction(): BuildFunction {
return new BuildFunction({
namespace: 'eas',
id: 'start_serve_sim_crashes',
name: 'Start serve-sim simulator crashes',
__metricsId: 'eas/start_serve_sim_crashes',
supportedRuntimePlatforms: [BuildRuntimePlatform.DARWIN],
fn: async ({ logger }) => {
try {
await ServeSimCrashesRecorder.startAsync({ logger });
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err));
Sentry.capture('Could not start serve-sim simulator crashes', error);
logger.warn(
{ err: error },
'Could not start simulator crash collection; the session will continue.'
);
}
},
});
}
@@ -0,0 +1,39 @@
import {
BuildFunction,
BuildRuntimePlatform,
BuildStepInput,
BuildStepInputValueTypeName,
} from '@expo/steps';
import { Sentry } from '../../sentry';
import { ServeSimNetworkCaptureRecorder } from '../utils/serveSimNetworkCaptureRecorder';
export function createStartServeSimNetworkCaptureBuildFunction(): BuildFunction {
return new BuildFunction({
namespace: 'eas',
id: 'start_serve_sim_network_capture',
name: 'Start serve-sim network capture',
__metricsId: 'eas/start_serve_sim_network_capture',
supportedRuntimePlatforms: [BuildRuntimePlatform.DARWIN],
inputProviders: [
BuildStepInput.createProvider({
id: 'package_version',
required: false,
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
}),
],
fn: async ({ logger }, { inputs, env }) => {
try {
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
packageVersion: inputs.package_version.value as string | undefined,
});
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err));
Sentry.capture('Could not start the serve-sim network capture recorder', error);
logger.warn({ err: error }, 'Could not start the serve-sim network capture recorder.');
}
},
});
}
Loaded 100 of 361 files, more files were not shown because too many files have changed in this diff. Show more