Compare commits

...
Author SHA1 Message Date
Gabe DebesandClaude Opus 5.5 74c9eae5f6 [eas-cli] Add the simulator topic aliases to simulator:network-requests
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 14:22:24 -07:00
Gabe DebesandClaude Opus 5.5 218fc0280b [eas-cli] Add the simulator:network-requests changeset
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 14:22:24 -07:00
Codex c4beb8d1d9 [eas-cli] Download capture artifacts from stopped simulator sessions 2026-11-20 14:22:24 -07:00
Gabe DebesandClaude Opus 5.5 8706252ab9 [eas-cli] Drop update suggestions from network capture errors
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 14:22:24 -07:00
Gabe DebesandClaude Opus 5.5 f5a1ab7eb5 [eas-cli] Only remove a HAR file that simulator:network-requests opened
Track the write stream's open event so a failed download never deletes a file that
another process created at the --output path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 14:22:24 -07:00
Gabe DebesandClaude Opus 5.5 36e5808521 [eas-cli] Create the simulator:network-requests HAR exclusively
Open the --output file with wx so a file created during the download is never
overwritten or removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 14:22:24 -07:00
Gabe DebesandClaude Opus 5.5 bd6af12110 [eas-cli] Match eas-cli patterns in simulator:network-requests
Validate capture data with zod, write the HAR the way src/utils/download.ts does, and
move 404 messages, Ctrl+C, and the --output spinner to the caller like sibling commands.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 14:22:24 -07:00
Gabe DebesandClaude Opus 5.5 5287f2a60e [eas-cli] Say what, why, and how in simulator:network-requests errors
Enable JSON output before parsing flags, and rewrite the network capture
errors to say what failed, why, and what to do next.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-11-20 14:22:24 -07:00
Gabe DebesandClaude Opus 5.5 f6a411eb7d [eas-cli] Add simulator:network-requests
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-11-20 14:22:24 -07:00
Gabe DebesandClaude Opus 5.5 03f9690d4f [eas-cli] Merge crash artifact support into --network-capture-recording
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 11:11:47 -07:00
Gabe DebesandClaude Opus 5.5 aecc6e5a0b [build-tools] Merge HAR artifact support into crash artifacts
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 11:11:47 -07:00
Gabe DebesandClaude Opus 5.5 c04843393f [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]>
2026-11-16 11:11:47 -07:00
Gabe DebesandClaude Opus 5.5 83cbfeb132 [build-tools] Merge main into HAR artifact support
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 11:11:47 -07:00
Gabe DebesandClaude Opus 5.5 08dc6c48f9 [eas-cli] Regenerate the README for --network-capture-recording
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 13:18:42 -07:00
Gabe DebesandClaude Opus 5.5 86b68eb790 [eas-cli] Drop saved network capture recording when --no-network-capture is passed
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 13:18:24 -07:00
Gabe Debes 60b08403c2 [eas-cli] Merge crash artifacts into recording flag
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	packages/eas-cli/README.md
2026-11-10 13:17:59 -07:00
Gabe DebesandClaude Opus 5.5 497cb86e8e [build-tools] Upload crash reports with the shared file upload helper
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 13:16:41 -07:00
Gabe Debes d4e7848353 [build-tools] Merge HAR artifact support into crash artifacts
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	packages/build-tools/src/steps/easFunctions.ts
#	packages/build-tools/src/steps/utils/__tests__/deviceSessionHost.test.ts
2026-11-10 13:15:25 -07:00
Gabe DebesandClaude Opus 5.5 1d8033904e [build-tools] Upload network captures with the shared file upload helper
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 13:14:28 -07:00
Gabe Debes 505e91d2f3 [build-tools] Merge main into HAR artifact support
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	packages/build-tools/src/steps/easFunctions.ts
2026-11-10 13:13:07 -07:00
Gabe DebesandClaude Opus 5.5 e8a6a2149e [build-tools] Merge crash artifacts into recording flag
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 22:03:19 -07:00
Gabe DebesandClaude Opus 5.5 c2564f520c [build-tools] Merge HAR artifact support into crash artifacts
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 22:02:26 -07:00
Gabe DebesandClaude Opus 5.5 a064599d97 [build-tools] Merge main into HAR artifact support
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 22:00:58 -07:00
Gabe DebesandClaude Opus 5.5 b9989b2168 [build-tools] Merge crash artifacts into recording flag
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 21:46:59 -07:00
Gabe DebesandClaude Opus 5.5 591e88bb3f [build-tools] Merge HAR artifact support into crash artifacts
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 21:46:55 -07:00
Gabe DebesandClaude Opus 5.5 7159c9b123 [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]>
2026-11-03 21:45:04 -07:00
Gabe DebesandClaude Opus 5.5 66b2726108 [build-tools] Merge crash artifacts into recording flag
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 21:50:18 -07:00
Gabe Debes 6247180a10 [build-tools] Merge HAR artifact support into crash artifacts
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	packages/build-tools/src/steps/utils/__tests__/deviceSessionHost.test.ts
2026-11-02 21:48:46 -07:00
Gabe DebesandClaude Opus 5.5 3dcef3ae5a [build-tools] Merge main into HAR artifact support
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 21:47:32 -07:00
Gabe DebesandClaude Opus 5.5 4f05b96052 [build-tools] Merge crash artifacts into recording flag
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 16:20:38 -07:00
Gabe DebesandClaude Opus 5.5 1de4c20d3f [build-tools] Merge HAR artifact support into crash artifacts
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 16:20:37 -07:00
Gabe DebesandClaude Opus 5.5 47e2ead086 [build-tools] Merge main into HAR artifact support
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 16:20:37 -07:00
Gabe DebesandClaude Opus 5.5 05226eb77c [eas-cli] Merge crash steps and main into network capture flag
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 10:33:18 -07:00
Gabe DebesandClaude Opus 5.5 f109a9798f [build-tools] Merge HAR steps and main into crash artifact steps
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 10:33:18 -07:00
Gabe DebesandClaude Opus 5.5 d6db6f6ec6 [build-tools] Merge main into HAR artifact steps
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 10:33:18 -07:00
Gabe DebesandClaude Opus 5.5 9eeb2de7c5 [eas-cli] Merge HAR review fixes into network capture flag
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 10:29:20 -07:00
Gabe DebesandClaude Opus 5.5 9c7be9ab93 [build-tools] Merge HAR review fixes into crash artifact steps
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 10:28:59 -07:00
Gabe DebesandClaude Opus 5.5 b7d6856183 [build-tools] Drop requests a restarted HAR follower replays
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 10:28:44 -07:00
Gabe DebesandClaude Opus 5.5 d3ec4feada [build-tools] Keep the ngrok token from the HAR follower
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 10:26:24 -07:00
Gabe Debes e731ac8f18 [eas-cli] Merge crash steps and main into network capture flag
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	packages/eas-cli/README.md
2026-10-21 16:28:54 -07:00
Gabe DebesandClaude Opus 5.5 35d5409cc2 [build-tools] Merge HAR steps and main into crash artifact steps
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 16:27:58 -07:00
Gabe DebesandClaude Opus 5.5 6a39e1b5ee [build-tools] Merge main into HAR artifact steps
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 16:27:58 -07:00
Gabe DebesandClaude Opus 5.5 d63cb6db75 [eas-cli] Merge crash detail retry fix into the recording flag
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 12:04:18 -07:00
Gabe DebesandClaude Opus 5.5 d5a939572b [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]>
2026-10-20 12:04:18 -07:00
Gabe DebesandClaude Opus 5.5 9ba08884f3 [build-tools] Merge main into HAR artifact steps
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 11:55:49 -07:00
Gabe DebesandClaude Opus 5.5 8e1d9ad87c [eas-cli] Merge crash artifact steps and main into the recording flag
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 11:55:49 -07:00
Gabe DebesandClaude Opus 5.5 fb8a87ecd6 [build-tools] Merge HAR steps and main into crash artifact steps
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 11:55:49 -07:00
Gabe DebesandClaude Opus 5.5 181a902986 Merge branch 'gwdp/simulator-crash-artifacts-20261009' into gwdp/network-capture-recording-flag
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 11:46:16 -07:00
Gabe DebesandClaude Opus 5.5 fde3ff8bd9 [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]>
2026-10-20 11:46:15 -07:00
Gabe DebesandClaude Opus 5.5 8039db75fb [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]>
2026-10-20 11:44:16 -07:00
Gabe DebesandClaude Opus 5.5 5f2fdf4314 Merge branch 'gwdp/network-capture-har-artifact' into gwdp/simulator-crash-artifacts-20261009
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 11:44:16 -07:00
Gabe DebesandClaude Opus 5.5 e911ad6924 Merge branch 'gwdp/simulator-crash-artifacts-20261009' into gwdp/network-capture-recording-flag
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 11:27:37 -07:00
Gabe DebesandClaude Opus 5.5 be61a921eb [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]>
2026-10-20 11:27:37 -07:00
Gabe DebesandClaude Opus 5.5 69a3a1fa6a Merge branch 'gwdp/simulator-crash-artifacts-20261009' into gwdp/network-capture-recording-flag
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 11:25:09 -07:00
Gabe DebesandClaude Opus 5.5 a2a916a9ac [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]>
2026-10-20 11:25:09 -07:00
Gabe DebesandClaude Opus 5.5 fcf2ec4100 Merge branch 'gwdp/network-capture-har-artifact' into gwdp/simulator-crash-artifacts-20261009
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 11:25:09 -07:00
Gabe DebesandClaude Opus 5.5 6a95d4b1ab [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]>
2026-10-20 11:18:13 -07:00
Gabe Debes ab8aa9d0e2 Merge refreshed artifact stack into HAR recording flag 2026-10-16 18:19:02 -07:00
Gabe Debes 4956551d28 Merge refreshed HAR parent and update worker upload fixtures 2026-10-16 18:18:23 -07:00
Gabe Debes dd047782c7 Merge main into HAR artifact changes 2026-10-16 18:15:36 -07:00
Gabe Debes ff27838146 Merge branch 'gwdp/artifact-worker-stack-crashes-20261015' into gwdp/har-recording-main-20261014 2026-10-16 18:13:17 -07:00
Gabe Debes 654b9f9f10 Merge branch 'gwdp/artifact-worker-stack-base-20261015' into gwdp/artifact-worker-stack-crashes-20261015 2026-10-16 18:12:47 -07:00
Gabe Debes 1083ff0576 [build-tools] Limit HAR artifact uploads to 500 MiB 2026-10-16 18:12:46 -07:00
Gabe Debes e83fcf4e5f Merge branch 'gwdp/artifact-worker-stack-crashes-20261015' into gwdp/har-recording-main-20261014 2026-10-15 22:37:36 -07:00
Gabe Debes 0d7945d8e8 [build-tools] Release failed crash recorder initialization 2026-10-15 22:37:35 -07:00
Gabe Debes a48038ffee Merge branch 'gwdp/artifact-worker-stack-crashes-20261015' into gwdp/har-recording-main-20261014 2026-10-15 22:30:21 -07:00
Gabe Debes 05957f021e [build-tools] Reserve crash collection before asynchronous setup 2026-10-15 22:30:20 -07:00
Gabe Debes 1caa82cef1 Merge branch 'gwdp/artifact-worker-stack-crashes-20261015' into gwdp/har-recording-main-20261014 2026-10-15 22:23:24 -07:00
Gabe Debes 495a51756f [build-tools] Verify missing crash reports across reconnects 2026-10-15 22:23:23 -07:00
Gabe Debes 963573e78d Merge branch 'gwdp/artifact-worker-stack-crashes-20261015' into gwdp/har-recording-main-20261014 2026-10-15 22:18:20 -07:00
Gabe Debes 8c7d43d4a6 [build-tools] Keep missing crash reports outside artifact limits 2026-10-15 22:17:36 -07:00
Gabe Debes 81f386fa70 Merge branch 'gwdp/artifact-worker-stack-crashes-20261015' into gwdp/har-recording-main-20261014 2026-10-15 22:03:08 -07:00
Gabe Debes a2916ba845 Save individual native IPS crash artifacts 2026-10-15 22:02:48 -07:00
Gabe Debes 802c625b78 [eas-cli] merge refreshed artifact worker parent into recording flag 2026-10-15 11:52:58 -07:00
Gabe Debes adb2894929 [build-tools] preserve crash shutdown mock in merged host tests 2026-10-15 11:52:17 -07:00
Gabe Debes 9583825c8c [build-tools] merge refreshed HAR parent into crash artifacts 2026-10-15 11:50:52 -07:00
Gabe Debes 3695045516 [build-tools] merge main into HAR artifact support 2026-10-15 11:50:31 -07:00
Gabe Debes 4febaa5e13 [eas-cli] stack recording flag on artifact worker support 2026-10-15 11:49:39 -07:00
Gabe Debes 4a90c66a70 [eas-cli] Merge main and add capture recording changeset 2026-10-14 15:07:44 -07:00
Gabe Debes d7f3890d32 Merge HAR parent and add crash artifact changeset 2026-10-14 15:06:23 -07:00
Gabe Debes b46f00a805 Merge main and add HAR artifact changeset 2026-10-14 15:06:03 -07:00
Gabe Debes 83333f5bf9 [eas-cli] Merge v24.14 main into optional HAR recording 2026-10-14 14:18:49 -07:00
Gabe Debes b6a213a6fc [build-tools] Merge updated HAR parent into crash artifacts 2026-10-14 14:16:17 -07:00
Gabe Debes 288ee9627d [build-tools] Merge v24.14 main into HAR recording 2026-10-14 14:15:46 -07:00
Gabe Debes 08c0b6f1e6 [eas-cli] Merge current main into optional HAR recording 2026-10-14 01:49:42 -07:00
Gabe Debes ad7ae463e5 [build-tools] Merge updated HAR parent into crash artifacts 2026-10-14 01:41:33 -07:00
Gabe Debes 9de77f29d6 [build-tools] Merge current main into HAR recording 2026-10-14 01:40:31 -07:00
Gabe Debes e4ceb4ab94 [eas-cli] Merge main into optional HAR recording 2026-10-12 10:54:11 -07:00
Gabe Debes f8bd548924 [build-tools] Merge HAR updates and adapt crash upload sources 2026-10-12 10:51:37 -07:00
Gabe Debes d53c874ad0 [build-tools] Merge main and update HAR upload sources 2026-10-12 10:50:47 -07:00
Gabe Debes 292cf995b6 [eas-cli] Describe live network capture in the startup warning 2026-10-09 16:54:03 -07:00
Gabe Debes f41156802c [eas-cli] Document optional network capture recording 2026-10-09 16:50:08 -07:00
Gabe Debes 75656f3452 [eas-cli] Make saved network capture recording opt-in 2026-10-09 16:49:32 -07:00
Gabe Debes 77bbc62394 [build-tools] Keep retrying productive crash streams 2026-10-09 15:49:14 -07:00
Gabe Debes 485e8d82e5 [build-tools] Bound crash collection retries and uploads 2026-10-09 15:43:56 -07:00
Gabe Debes 470aa638c5 [build-tools] Link crash artifact changelog entry 2026-10-09 15:28:30 -07:00
Gabe Debes 8b4371ee99 [build-tools] Use shared crash artifact upload deadlines 2026-10-09 15:20:59 -07:00
Gabe Debes 521549e7e7 [build-tools] Collect simulator crash artifacts 2026-10-09 15:20:06 -07:00
Gabe Debes 6b2dfc660a [build-tools] Bound failed network capture followers 2026-10-09 15:19:53 -07:00
Gabe Debes 1395bd97f9 [build-tools] Remove the capture recorder command override
Edited-by: Codex
2026-10-09 15:05:35 -07:00
Gabe Debes f2001fd269 [build-tools] Rename the network capture recording step
Edited-by: Codex
2026-10-09 15:05:35 -07:00
Gabe DebesandClaude Opus 5.5 b3ecc60c4c [build-tools] record network capture with serve-sim capture har steps
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-09 15:05:35 -07:00
33 changed files with 4701 additions and 29 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
'eas-cli': minor
---
Add `--network-capture-recording` to keep captured traffic as HAR session artifacts.
+5
View File
@@ -0,0 +1,5 @@
---
'@expo/build-tools': minor
---
Add start and collect steps that attach serve-sim simulator crash reports to device run sessions as IPS files.
+5
View File
@@ -0,0 +1,5 @@
---
'@expo/build-tools': minor
---
Add start and collect steps that attach serve-sim network captures to device run sessions as HAR files.
+5
View File
@@ -0,0 +1,5 @@
---
'eas-cli': minor
---
Add `simulator:network-requests` to list, follow, and inspect captured requests and download HAR files.
@@ -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(),
@@ -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.');
});
@@ -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}.`
);
});
}
}
},
});
}
@@ -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.');
}
},
});
}
@@ -47,9 +47,11 @@ import {
} from '../serveSimActions';
import { startPreviewActivityPolling } from '../previewActivity';
import { readServeSimServersAsync } from '../serveSimMetricsRecorder';
import { ServeSimCrashesRecorder } from '../serveSimCrashesRecorder';
import * as previewCapture from '../serveSimPreviewCapture';
jest.mock('@ngrok/ngrok');
jest.mock('../serveSimCrashesRecorder');
jest.mock('@expo/turtle-spawn');
jest.mock('../../../utils/IosSimulatorUtils', () => ({
IosSimulatorUtils: { disableApsdAsync: jest.fn(), waitForReadyAsync: jest.fn() },
@@ -152,6 +154,7 @@ const stopSessionPreview = jest.fn();
beforeEach(() => {
jest.clearAllMocks();
jest.mocked(ServeSimCrashesRecorder.stopAsync).mockReset().mockResolvedValue(undefined);
jest
.mocked(startNgrokTunnelAsync)
.mockReset()
@@ -2360,6 +2363,22 @@ it('cancels an in-flight install while Simulator setup is pending', async () =>
expect(stopServer).toHaveBeenCalledTimes(1);
});
it('finishes in-flight crash collection before stopping the host', async () => {
const host = await startHostAsync();
const collecting = deferred<void>();
const entered = deferred<void>();
jest.mocked(ServeSimCrashesRecorder.stopAsync).mockImplementationOnce(async () => {
entered.resolve();
await collecting.promise;
});
const finishing = host.finishAsync();
await entered.promise;
expect(stopServer).not.toHaveBeenCalled();
collecting.resolve();
await finishing;
expect(stopServer).toHaveBeenCalledTimes(1);
});
it('redacts bearer tokens from preview readiness diagnostics while preserving the failure', async () => {
const output = [
'Native addon failed to initialize',
@@ -0,0 +1,69 @@
import type { bunyan } from '@expo/logger';
import { 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 { uploadDeviceRunSessionArtifactAsync } from '../deviceRunSessionArtifacts';
import { uploadServeSimCrashesFileAsync } from '../serveSimCrashesArtifacts';
jest.mock('../../../sentry');
jest.mock('../deviceRunSessionArtifacts');
jest.unmock('fs');
jest.unmock('node:fs');
jest.unmock('fs/promises');
jest.unmock('node:fs/promises');
const ctx = {} as CustomBuildContext;
const logger = { info: jest.fn(), warn: jest.fn() } as unknown as bunyan;
let crash: { udid: string; filePath: string; size: number; number: number };
beforeAll(async () => {
const filePath = path.join(await mkdtemp(path.join(os.tmpdir(), 'crash-test-')), 'A-2.ips');
await writeFile(filePath, '{"app_name":"Crash"}');
crash = { udid: 'ABCDEF123456', filePath, size: 20, number: 2 };
});
beforeEach(() => {
jest.clearAllMocks();
});
it.each([
[undefined, 'Crash report 2 (ABCDEF12)', 'crash-2.ips'],
['My/App:Beta\n', 'Crash report 2: My/App:Beta\n (ABCDEF12)', 'My-App-Beta--2.ips'],
])('names the report for process %j', async (processName, name, filename) => {
await uploadServeSimCrashesFileAsync(ctx, {
deviceRunSessionId: 'drs-id',
crash: { ...crash, ...(processName ? { processName } : {}) },
logger,
});
expect(uploadDeviceRunSessionArtifactAsync).toHaveBeenCalledWith(ctx, {
deviceRunSessionId: 'drs-id',
artifactId: 'simulator-crash-ABCDEF123456-2',
name,
filename,
kind: 'simulator-crash',
metadata: { __eas_type: 'simulator-crash', udid: 'ABCDEF123456', source: 'serve-sim/crashes' },
size: 20,
openStream: expect.any(Function),
signal: expect.any(AbortSignal),
attempts: 3,
});
});
it('reports a failed upload by report number without rejecting', async () => {
jest.mocked(uploadDeviceRunSessionArtifactAsync).mockRejectedValueOnce(new Error('offline'));
await expect(
uploadServeSimCrashesFileAsync(ctx, { deviceRunSessionId: 'drs-id', crash, logger })
).resolves.toBeUndefined();
expect(Sentry.capture).toHaveBeenCalledWith(
'Could not upload a simulator crash report',
expect.objectContaining({ message: 'offline' }),
{ level: 'warning' }
);
expect(logger.warn).toHaveBeenCalledWith(
{ err: expect.objectContaining({ message: 'offline' }) },
'Could not upload crash report 2 for ABCDEF123456; other artifacts will continue.'
);
});
@@ -0,0 +1,816 @@
import { type bunyan } from '@expo/logger';
import { mkdtemp, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises';
import { type IncomingMessage, type Server, type ServerResponse, createServer } from 'node:http';
import { type AddressInfo } from 'node:net';
import os from 'node:os';
import path from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { type CustomBuildContext } from '../../../customBuildContext';
import { DEVICE_RUN_SESSION_TOKEN_HEADER } from '../deviceRunSessionWorkerApi';
import { uploadServeSimCrashesFileAsync } from '../serveSimCrashesArtifacts';
import { ServeSimCrashesRecorder } from '../serveSimCrashesRecorder';
import * as serveSimServers from '../serveSimMetricsRecorder';
jest.mock('../../../sentry');
jest.unmock('fs');
jest.unmock('node:fs');
jest.unmock('fs/promises');
jest.unmock('node:fs/promises');
jest.unmock('node-fetch');
const fs = jest.requireActual<typeof import('node:fs/promises')>('node:fs/promises');
const logger = { info: jest.fn(), warn: jest.fn() } as unknown as bunyan;
let directory: string;
let server: Server;
let baseUrl: string;
const summary = { id: 'crash/a', appName: 'Fixture', occurrenceTimes: [{ key: 1 }, { key: 2 }] };
const report = (key: number) =>
JSON.stringify({ app_name: 'Fixture 서울 🌲', incident_id: `INC-${key}` }) +
'\n' +
JSON.stringify({ exception: { type: 'EXC_CRASH', signal: 'SIGABRT' }, incident: `INC-${key}` }) +
'\n';
const detail = (key: number) => ({
record: { id: summary.id, bundleId: 'dev.expo.fixture' },
occurrence: { key, incidentId: `INC-${key}`, logTail: ['PRIVATE APP LOG'], pid: 123 },
report: report(key),
reportError: null,
});
/** Answers the one-shot list that stopping reads; returns false for other requests. */
function answerList(
request: IncomingMessage,
response: ServerResponse,
crashes: unknown[] = []
): boolean {
if (request.headers.accept !== 'application/json') {
return false;
}
response.setHeader('Content-Type', 'application/json');
response.end(JSON.stringify({ meta: { statusError: null }, crashes }));
return true;
}
function stoppedRetrying(): boolean {
return jest
.mocked(logger.warn)
.mock.calls.some(([message]) =>
String(message).startsWith('Stopped retrying simulator crash collection')
);
}
async function waitFor(read: () => boolean | Promise<boolean>): Promise<void> {
for (let i = 0; i < 200; i++) {
if (await read()) {
return;
}
await delay(10);
}
throw new Error('Timed out waiting for crash recording');
}
async function start(maxBytes?: number): Promise<void> {
await writeFile(
path.join(directory, 'server-device-A.json'),
JSON.stringify({
device: 'device-A',
url: baseUrl,
token: 'test-token',
})
);
await ServeSimCrashesRecorder.startAsync({
logger,
stateDir: directory,
pollIntervalMs: 10,
maxBytes,
});
}
beforeEach(async () => {
directory = await mkdtemp(path.join(os.tmpdir(), 'crashes-http-test-'));
server = createServer();
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
afterEach(async () => {
const { outputDirectory } = await ServeSimCrashesRecorder.finishAsync();
if (outputDirectory) {
await rm(outputDirectory, { recursive: true, force: true });
}
server.closeAllConnections();
await new Promise<void>(resolve => server.close(() => resolve()));
await rm(directory, { recursive: true, force: true });
});
it('saves recurrences as separate private IPS files and uploads unchanged reports without app logs', async () => {
let connections = 0;
let requests = 0;
const uploaded: Buffer[] = [];
let uploadAttempts = 0;
const uploadInputs: { filename: string }[] = [];
server.on('request', (request, response) => {
if (request.url === '/v2/device-run-session-worker/artifact-upload-sessions') {
expect(request.method).toBe('POST');
expect(request.headers[DEVICE_RUN_SESSION_TOKEN_HEADER]).toBe('worker-token');
const chunks: Buffer[] = [];
request.on('data', chunk => chunks.push(chunk));
request.on('end', () => {
uploadInputs.push(JSON.parse(Buffer.concat(chunks).toString()));
response.setHeader('Content-Type', 'application/json');
response.end(
JSON.stringify({ data: { uploadSession: { url: baseUrl + '/upload', headers: {} } } })
);
});
return;
}
if (request.method === 'PUT') {
const chunks: Buffer[] = [];
request.on('data', chunk => chunks.push(chunk));
request.on('end', () => {
uploaded.push(Buffer.concat(chunks));
uploadAttempts += 1;
response.writeHead(uploadAttempts === 1 ? 503 : 200).end();
});
return;
}
expect(request.headers.authorization).toBe('Bearer test-token');
const url = new URL(request.url!, baseUrl);
expect(url.searchParams.get('device')).toBe('device-A');
if (answerList(request, response, [summary])) {
return;
}
if (url.pathname === '/crashes') {
expect(url.searchParams.has('tail')).toBe(false);
expect(request.headers.accept).toBe('text/event-stream');
connections += 1;
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
const initial = { ...summary, occurrenceTimes: [{ key: 1 }] };
const wire = `data: ${JSON.stringify({ type: 'list', crashes: [initial] })}\r\n\r\n`;
if (connections === 1) {
response.end(wire);
} else {
response.write(
wire + `data: ${JSON.stringify({ type: 'recurred', record: summary })}\r\n\r\n`
);
}
} else {
expect(url.pathname).toBe('/crashes/crash%2Fa');
requests += 1;
response.end(JSON.stringify(detail(Number(url.searchParams.get('key')))));
}
});
await start();
await waitFor(() => requests === 2);
await ServeSimCrashesRecorder.stopAsync();
const { crashes: files } = await ServeSimCrashesRecorder.finishAsync();
expect(files).toHaveLength(2);
expect(requests).toBe(2);
const expected = [Buffer.from(report(1)), Buffer.from(report(2))];
for (const [index, file] of files.entries()) {
expect(path.extname(file.filePath)).toBe('.ips');
expect(await readFile(file.filePath)).toEqual(expected[index]);
expect((await stat(file.filePath)).mode & 0o777).toBe(0o600);
expect((await stat(path.dirname(file.filePath))).mode & 0o777).toBe(0o700);
}
expect(files[0].filePath).not.toBe(files[1].filePath);
const context = {
env: { EAS_DEVICE_RUN_SESSION_TOKEN: 'worker-token' },
expoApiV2BaseUrl: baseUrl + '/v2/',
} as unknown as CustomBuildContext;
for (const crash of files) {
await uploadServeSimCrashesFileAsync(context, {
deviceRunSessionId: 'session-id',
crash,
logger,
});
}
expect(uploaded).toEqual([expected[0], expected[0], expected[1]]);
expect(uploadAttempts).toBe(3);
expect(uploadInputs.map(input => input.filename)).toEqual(['Fixture-1.ips', 'Fixture-2.ips']);
expect(uploadInputs[0]).toMatchObject({
name: 'Crash report 1: Fixture (device-A)',
kind: 'simulator-crash',
metadata: { __eas_type: 'simulator-crash', udid: 'device-A', source: 'serve-sim/crashes' },
});
expect(JSON.stringify(uploadInputs)).not.toContain('PRIVATE APP LOG');
expect(await ServeSimCrashesRecorder.finishAsync()).toEqual({
outputDirectory: null,
crashes: [],
});
await rm(path.dirname(files[0].filePath), { recursive: true, force: true });
});
it('keeps an in-flight report download alive during stop and waits for its write', async () => {
let requested = false;
let finishReport: () => void = () => {};
server.on('request', (request, response) => {
if (request.url!.startsWith('/crashes?')) {
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
response.write(`data: ${JSON.stringify({ type: 'crash', record: summary })}\n\n`);
} else {
requested = true;
finishReport = () => response.end(JSON.stringify(detail(1)));
}
});
await start();
await waitFor(() => requested);
const stopped = ServeSimCrashesRecorder.stopAsync();
finishReport();
await stopped;
const { crashes: files } = await ServeSimCrashesRecorder.finishAsync();
expect(await readFile(files[0].filePath, 'utf8')).toBe(report(1));
await rm(path.dirname(files[0].filePath), { recursive: true, force: true });
});
it('closes a rejected stream socket and produces no artifact for an empty session', async () => {
let closed = false;
server.on('request', (request, response) => {
request.socket.on('close', () => {
closed = true;
});
response.writeHead(403).write('unfinished response');
});
await start();
await waitFor(() => closed);
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(collected.crashes).toEqual([]);
expect(collected.outputDirectory).toEqual(expect.any(String));
await rm(collected.outputDirectory!, { recursive: true, force: true });
expect(JSON.stringify(jest.mocked(logger.warn).mock.calls)).not.toContain('test-token');
});
it('stops at a complete-record byte limit and keeps earlier reports', async () => {
let requested = 0;
server.on('request', (request, response) => {
if (request.url!.startsWith('/crashes?')) {
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
response.write(`data: ${JSON.stringify({ type: 'list', crashes: [summary] })}\n\n`);
} else {
requested += 1;
response.end(
JSON.stringify(detail(Number(new URL(request.url!, baseUrl).searchParams.get('key'))))
);
}
});
await writeFile(
path.join(directory, 'server-device-A.json'),
JSON.stringify({ device: 'device-A', url: baseUrl })
);
await ServeSimCrashesRecorder.startAsync({
logger,
stateDir: directory,
pollIntervalMs: 10,
maxBytes: Buffer.byteLength(report(1)),
});
await waitFor(() => requested === 2);
await ServeSimCrashesRecorder.stopAsync();
const { crashes: files } = await ServeSimCrashesRecorder.finishAsync();
expect(await readFile(files[0].filePath, 'utf8')).toBe(report(1));
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('reached its limit'));
await rm(path.dirname(files[0].filePath), { recursive: true, force: true });
});
it.each([
[
'fails on every request',
3,
'Could not download crash occurrence 1 for device-A; skipping it.',
(response: ServerResponse) => response.writeHead(500).end(),
],
[
'is refused with a permanent 4xx',
1,
'Could not download crash occurrence 1 for device-A; skipping it.',
(response: ServerResponse) => response.writeHead(400).end(),
],
[
'is not valid JSON',
1,
'Could not download crash occurrence 1 for device-A; skipping it.',
(response: ServerResponse) => response.end('{broken'),
],
[
'exceeds 8 MiB',
1,
'Could not download crash occurrence 1 for device-A; skipping it.',
(response: ServerResponse) =>
response.end(JSON.stringify({ ...detail(1), report: 'x'.repeat(8 * 1024 * 1024) })),
],
[
'does not match the occurrence',
1,
'Could not download crash occurrence 1 for device-A; skipping it.',
(response: ServerResponse) => response.end(JSON.stringify(detail(2))),
],
[
'is no longer kept',
1,
'Crash occurrence 1 is no longer available for device-A; earlier reports will be retained.',
(response: ServerResponse) => response.writeHead(404).end(),
],
])(
'skips an occurrence whose detail %s after %i attempts and keeps collecting the device',
async (_name, attempts, warning, respond) => {
let connections = 0;
let badRequests = 0;
server.on('request', (request, response) => {
const url = new URL(request.url!, baseUrl);
if (answerList(request, response)) {
return;
}
if (url.pathname === '/crashes') {
connections += 1;
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
// Every stream ends, so each reconnect replays the bad occurrence.
response.end(
`data: ${JSON.stringify({
type: 'list',
crashes: [
{ id: 'crash/b', occurrenceTimes: [{ key: 1 }] },
{ ...summary, occurrenceTimes: [{ key: 1 }] },
],
})}\n\n`
);
} else if (url.pathname === '/crashes/crash%2Fb') {
badRequests += 1;
respond(response);
} else {
response.end(JSON.stringify(detail(1)));
}
});
await start();
await waitFor(() => connections >= 12);
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(badRequests).toBe(attempts);
expect(stoppedRetrying()).toBe(false);
expect(jest.mocked(logger.warn).mock.calls.filter(call => call.includes(warning))).toHaveLength(
1
);
expect(collected.crashes).toHaveLength(1);
expect(await readFile(collected.crashes[0].filePath, 'utf8')).toBe(report(1));
await rm(collected.outputDirectory!, { recursive: true, force: true });
}
);
it('saves an occurrence whose detail fails once, without reconnecting', async () => {
let connections = 0;
let requests = 0;
server.on('request', (request, response) => {
if (answerList(request, response)) {
return;
}
if (request.url!.startsWith('/crashes?')) {
connections += 1;
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
response.write(
`data: ${JSON.stringify({ type: 'list', crashes: [{ ...summary, occurrenceTimes: [{ key: 1 }] }] })}\n\n`
);
} else {
requests += 1;
if (requests === 1) {
response.writeHead(503).end();
} else {
response.end(JSON.stringify(detail(1)));
}
}
});
await start();
await waitFor(() => requests === 2);
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(connections).toBe(1);
expect(collected.crashes).toHaveLength(1);
expect(await readFile(collected.crashes[0].filePath, 'utf8')).toBe(report(1));
expect(logger.warn).not.toHaveBeenCalledWith(
expect.anything(),
expect.stringContaining('Could not download')
);
await rm(collected.outputDirectory!, { recursive: true, force: true });
});
it('collects an occurrence listed after the stream last delivered, when stopping', async () => {
let streaming = false;
server.on('request', (request, response) => {
const url = new URL(request.url!, baseUrl);
const listed = { ...summary, appName: '', procName: 'FixtureProcess' };
if (answerList(request, response, [{ ...listed, occurrenceTimes: [{ key: 1 }] }])) {
return;
}
if (url.pathname === '/crashes') {
streaming = true;
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
response.write(`data: ${JSON.stringify({ type: 'list', crashes: [] })}\n\n`);
} else {
response.end(JSON.stringify(detail(1)));
}
});
await start();
await waitFor(() => streaming);
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(collected.crashes).toEqual([
{
udid: 'device-A',
filePath: path.join(collected.outputDirectory!, 'device-A-1.ips'),
size: Buffer.byteLength(report(1)),
number: 1,
processName: 'FixtureProcess',
},
]);
expect(await readFile(collected.crashes[0].filePath, 'utf8')).toBe(report(1));
await rm(collected.outputDirectory!, { recursive: true, force: true });
});
it('stops the final pass at its deadline and warns', async () => {
let streaming = false;
server.on('request', (request, response) => {
if (answerList(request, response, [{ ...summary, occurrenceTimes: [{ key: 1 }] }])) {
return;
}
if (request.url!.startsWith('/crashes?')) {
streaming = true;
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
response.write(`data: ${JSON.stringify({ type: 'list', crashes: [] })}\n\n`);
}
// The detail never answers.
});
await writeFile(
path.join(directory, 'server-device-A.json'),
JSON.stringify({ device: 'device-A', url: baseUrl, token: 'test-token' })
);
await ServeSimCrashesRecorder.startAsync({
logger,
stateDir: directory,
pollIntervalMs: 10,
finalPassTimeoutMs: 100,
});
await waitFor(() => streaming);
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(collected.crashes).toEqual([]);
expect(logger.warn).toHaveBeenCalledWith(
'Stopped checking device-A for crashes at the end-of-session deadline; collected reports will be retained.'
);
await rm(collected.outputDirectory!, { recursive: true, force: true });
});
it('warns once per device when serve-sim cannot watch crash reports', async () => {
let connections = 0;
server.on('request', (_request, response) => {
connections += 1;
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
response.end(
`data: ${JSON.stringify({ type: 'meta', meta: { statusError: 'EACCES' } })}\n\n` +
`data: ${JSON.stringify({ type: 'list', crashes: [] })}\n\n`
);
});
await start();
await waitFor(() => connections >= 3);
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(
jest
.mocked(logger.warn)
.mock.calls.filter(([message]) => String(message).startsWith('serve-sim cannot watch'))
).toHaveLength(1);
await rm(collected.outputDirectory!, { recursive: true, force: true });
});
it.each([
['empty', ''],
['heartbeat-only', ': heartbeat\n\n'],
['meta-only', `data: ${JSON.stringify({ type: 'meta', meta: { statusError: null } })}\n\n`],
['invalid JSON', 'data: {invalid}\n\n'],
['invalid frame', 'data: {"type":"list","crashes":false}\n\n'],
])('stops retrying after ten %s streams', async (_name, payload) => {
let connections = 0;
server.on('request', (_request, response) => {
connections += 1;
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
response.end(payload);
});
await start();
await waitFor(stoppedRetrying);
await delay(30);
expect(connections).toBe(10);
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(collected.crashes).toEqual([]);
await rm(collected.outputDirectory!, { recursive: true, force: true });
});
it('keeps retrying streams that process a healthy empty crash list', async () => {
let connections = 0;
server.on('request', (_request, response) => {
connections += 1;
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
const frame = `data: ${JSON.stringify({ type: 'list', crashes: [] })}\n\n`;
if (connections < 12) {
response.end(frame);
} else {
response.write(frame);
}
});
await start();
await waitFor(() => connections === 12);
expect(stoppedRetrying()).toBe(false);
});
it('recovers the same server after registry absence without resetting dedupe or the byte budget', async () => {
let connections = 0;
let healthy = false;
let expectAbsence = false;
let observedAbsence = false;
const keys: number[] = [];
const readServers = serveSimServers.readServeSimServersAsync;
const registry = jest
.spyOn(serveSimServers, 'readServeSimServersAsync')
.mockImplementation(async stateDir => {
const servers = await readServers(stateDir);
if (expectAbsence && servers.length === 0) {
observedAbsence = true;
}
return servers;
});
server.on('request', (request, response) => {
const url = new URL(request.url!, baseUrl);
if (url.pathname === '/crashes') {
connections += 1;
if (connections > 1 && !healthy) {
response.writeHead(503).end();
return;
}
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
const record = {
...summary,
occurrenceTimes: healthy ? [{ key: 1 }, { key: 2 }, { key: 3 }] : [{ key: 1 }],
};
const frame = `data: ${JSON.stringify({ type: 'list', crashes: [record] })}\n\n`;
if (healthy) {
response.write(frame);
} else {
response.end(frame);
}
} else {
const key = Number(url.searchParams.get('key'));
keys.push(key);
response.end(JSON.stringify(detail(key)));
}
});
try {
const expected = report(1) + report(2);
await start(Buffer.byteLength(expected));
await waitFor(stoppedRetrying);
expect(connections).toBe(11);
expectAbsence = true;
await rm(path.join(directory, 'server-device-A.json'));
await waitFor(() => observedAbsence);
healthy = true;
await writeFile(
path.join(directory, 'server-device-A.json'),
JSON.stringify({
device: 'device-A',
url: baseUrl,
token: 'test-token',
})
);
await waitFor(() => keys.includes(3));
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(connections).toBe(12);
expect(keys).toEqual([1, 2, 3]);
expect(collected.crashes).toHaveLength(2);
expect(
(await Promise.all(collected.crashes.map(file => readFile(file.filePath, 'utf8')))).join('')
).toBe(expected);
await rm(collected.outputDirectory!, { recursive: true, force: true });
} finally {
registry.mockRestore();
}
});
it('closes a stalled upload within its budget and lets another device upload', async () => {
const firstFile = path.join(directory, 'A.ips');
const secondFile = path.join(directory, 'B.ips');
await writeFile(firstFile, report(1));
const expected = Buffer.from(report(2));
await writeFile(secondFile, expected);
let firstClosed = false;
let firstRequests = 0;
let uploaded: Buffer | undefined;
let sessions = 0;
server.on('request', (request, response) => {
if (request.url === '/v2/device-run-session-worker/artifact-upload-sessions') {
expect(request.method).toBe('POST');
expect(request.headers[DEVICE_RUN_SESSION_TOKEN_HEADER]).toBe('worker-token');
request.resume();
request.on('end', () => {
response.setHeader('Content-Type', 'application/json');
response.end(
JSON.stringify({
data: {
uploadSession: {
url: baseUrl + (sessions++ === 0 ? '/stalled' : '/upload'),
headers: {},
},
},
})
);
});
return;
}
if (request.url === '/stalled') {
firstRequests += 1;
response.on('close', () => {
firstClosed = true;
});
request.resume();
} else {
const chunks: Buffer[] = [];
request.on('data', chunk => chunks.push(chunk));
request.on('end', () => {
uploaded = Buffer.concat(chunks);
response.end();
});
}
});
const context = {
env: { EAS_DEVICE_RUN_SESSION_TOKEN: 'worker-token' },
expoApiV2BaseUrl: baseUrl + '/v2/',
} as unknown as CustomBuildContext;
await uploadServeSimCrashesFileAsync(context, {
deviceRunSessionId: 'session-id',
crash: { udid: 'A', filePath: firstFile, size: Buffer.byteLength(report(1)), number: 1 },
logger,
signal: AbortSignal.timeout(50),
});
await waitFor(() => firstClosed);
expect(firstRequests).toBe(1);
expect(logger.warn).toHaveBeenCalledWith(
expect.any(Object),
'Could not upload crash report 1 for A; other artifacts will continue.'
);
await uploadServeSimCrashesFileAsync(context, {
deviceRunSessionId: 'session-id',
crash: { udid: 'B', filePath: secondFile, size: expected.length, number: 1 },
logger,
signal: AbortSignal.timeout(1_000),
});
expect(sessions).toBe(2);
expect(uploaded).toEqual(expected);
});
it.each([null, ''])(
'does not create an artifact when the native report is %s',
async nativeReport => {
let requested = false;
server.on('request', (request, response) => {
if (request.url!.startsWith('/crashes?')) {
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
response.write(
`data: ${JSON.stringify({ type: 'list', crashes: [{ ...summary, occurrenceTimes: [{ key: 1 }] }] })}\n\n`
);
} else {
requested = true;
response.end(
JSON.stringify({ ...detail(1), report: nativeReport, reportError: 'Report unavailable' })
);
}
});
await start();
await waitFor(() => requested);
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(collected.crashes).toEqual([]);
expect(await readdir(collected.outputDirectory!)).toEqual([]);
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('has no native report'));
await rm(collected.outputDirectory!, { recursive: true, force: true });
}
);
it('does not duplicate a saved incident when a restarted serve-sim reuses occurrence keys', async () => {
let requested = 0;
server.on('request', (request, response) => {
if (answerList(request, response)) {
return;
}
// A restarted serve-sim numbers occurrences from 1 again; the capture time tells them apart.
const restarted = request.headers.authorization === 'Bearer new-token';
if (request.url!.startsWith('/crashes?')) {
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
const occurrence = restarted
? { key: 1, capturedAtMs: 2_000, rawPath: '/DiagnosticReports/Fixture-2.ips' }
: { key: 1, capturedAtMs: 1_000, rawPath: '/DiagnosticReports/Fixture-1.ips' };
response.write(
`data: ${JSON.stringify({ type: 'list', crashes: [{ ...summary, occurrenceTimes: [occurrence] }] })}\n\n`
);
} else {
requested += 1;
response.end(JSON.stringify(detail(1)));
}
});
await start();
await waitFor(() => requested === 1);
await writeFile(
path.join(directory, 'server-device-A.json'),
JSON.stringify({ device: 'device-A', url: baseUrl, token: 'new-token' })
);
server.closeAllConnections();
await waitFor(() => requested === 2);
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(collected.crashes).toHaveLength(1);
expect(await readFile(collected.crashes[0].filePath, 'utf8')).toBe(report(1));
await rm(collected.outputDirectory!, { recursive: true, force: true });
});
it('removes a partial file before retrying a failed write', async () => {
const write = fs.writeFile;
let attempted = 0;
const writing = jest.spyOn(fs, 'writeFile').mockImplementation(async (file, data, options) => {
if (String(file).endsWith('.ips') && attempted++ === 0) {
await write(file, 'partial report', options);
throw new Error('disk write failed');
}
await write(file, data, options);
});
server.on('request', (request, response) => {
if (request.url!.startsWith('/crashes?')) {
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
response.write(
`data: ${JSON.stringify({ type: 'list', crashes: [{ ...summary, occurrenceTimes: [{ key: 1 }] }] })}\n\n`
);
} else {
response.end(JSON.stringify(detail(1)));
}
});
try {
await start();
await waitFor(() => attempted >= 2);
const collected = await ServeSimCrashesRecorder.finishAsync();
expect(collected.crashes).toHaveLength(1);
expect(await readdir(collected.outputDirectory!)).toEqual([
path.basename(collected.crashes[0].filePath),
]);
expect(await readFile(collected.crashes[0].filePath, 'utf8')).toBe(report(1));
await rm(collected.outputDirectory!, { recursive: true, force: true });
} finally {
writing.mockRestore();
}
});
it('keeps the report allowance and deduplicates reconnects after more missing reports than the allowance', async () => {
const missingCount = 1_001;
const requested: number[] = [];
let connections = 0;
let completed: (() => void) | undefined;
const processed = new Promise<void>(resolve => {
completed = resolve;
});
const occurrence = (key: number) => ({ ...summary, occurrenceTimes: [{ key }] });
server.on('request', (request, response) => {
if (answerList(request, response)) {
return;
}
if (request.url!.startsWith('/crashes?')) {
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
connections += 1;
if (connections === 1) {
for (let key = 1; key <= missingCount; key++) {
response.write(
`data: ${JSON.stringify({ type: 'recurred', record: occurrence(key) })}\n\n`
);
}
} else {
const retained = {
...summary,
occurrenceTimes: Array.from({ length: 5 }, (_, index) => ({
key: missingCount - 4 + index,
})),
};
response.write(`data: ${JSON.stringify({ type: 'list', crashes: [retained] })}\n\n`);
}
if (connections < 3) {
response.end();
} else {
response.write(
`data: ${JSON.stringify({ type: 'recurred', record: occurrence(missingCount + 1) })}\n\n`
);
}
} else {
const key = Number(new URL(request.url!, baseUrl).searchParams.get('key'));
requested.push(key);
response.end(
JSON.stringify({ ...detail(key), report: key <= missingCount ? null : report(key) })
);
if (key === missingCount + 1) {
completed?.();
}
}
});
await start();
await processed;
const collected = await ServeSimCrashesRecorder.finishAsync();
try {
expect(connections).toBe(3);
expect(requested).toEqual(Array.from({ length: missingCount + 1 }, (_, index) => index + 1));
expect(collected.crashes).toHaveLength(1);
expect(await readFile(collected.crashes[0].filePath, 'utf8')).toBe(report(missingCount + 1));
expect(logger.warn).not.toHaveBeenCalledWith(expect.stringContaining('reached its limit'));
} finally {
await rm(collected.outputDirectory!, { recursive: true, force: true });
}
}, 15_000);
@@ -0,0 +1,94 @@
import type { bunyan } from '@expo/logger';
import { 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 { uploadDeviceRunSessionArtifactAsync } from '../deviceRunSessionArtifacts';
import { uploadServeSimNetworkCaptureFileAsync } from '../serveSimNetworkCaptureArtifacts';
jest.mock('../../../sentry');
jest.mock('../deviceRunSessionArtifacts');
const ctx = {} as CustomBuildContext;
const logger = { info: jest.fn(), warn: jest.fn() } as unknown as bunyan;
async function harAsync(name: string): Promise<string> {
const filePath = path.join(await mkdtemp(path.join(os.tmpdir(), 'network-capture-test-')), name);
await writeFile(filePath, '{"log":{"entries":[{}]}}');
return filePath;
}
beforeEach(() => {
jest.clearAllMocks();
jest.mocked(uploadDeviceRunSessionArtifactAsync).mockImplementation(async (_ctx, options) => {
options.openStream().destroy();
});
});
it.each([
[1, 'Network capture (ABCDEF12)'],
[2, 'Network capture (ABCDEF12, part 2)'],
])('uploads part %i as a network-capture artifact', async (part, name) => {
const filePath = await harAsync('A.har');
await uploadServeSimNetworkCaptureFileAsync(ctx, {
deviceRunSessionId: 'drs-id',
udid: 'ABCDEF123456',
filePath,
size: 24,
part,
logger,
});
expect(uploadDeviceRunSessionArtifactAsync).toHaveBeenCalledWith(ctx, {
deviceRunSessionId: 'drs-id',
artifactId: `network-capture-ABCDEF123456-${part}`,
name,
filename: 'network-capture.har',
kind: 'network-capture',
metadata: { __eas_type: 'network-capture', format: 'har', udid: 'ABCDEF123456', part },
size: 24,
openStream: expect.any(Function),
signal: expect.any(AbortSignal),
attempts: 3,
});
});
it('logs a failed upload without rejecting', async () => {
jest.mocked(uploadDeviceRunSessionArtifactAsync).mockRejectedValueOnce(new Error('offline'));
await expect(
uploadServeSimNetworkCaptureFileAsync(ctx, {
deviceRunSessionId: 'drs-id',
udid: 'A',
filePath: await harAsync('A.har'),
size: 24,
part: 1,
logger,
})
).resolves.toBeUndefined();
expect(logger.warn).toHaveBeenCalledWith(
{ err: expect.objectContaining({ message: 'offline' }) },
'Could not upload the network capture for A.'
);
expect(Sentry.capture).toHaveBeenCalledTimes(1);
});
it('accepts 500 MiB and skips larger HARs', async () => {
const limit = 500 * 1024 * 1024;
const filePath = await harAsync('A.har');
for (const size of [limit, limit + 1]) {
await uploadServeSimNetworkCaptureFileAsync(ctx, {
deviceRunSessionId: 'drs-id',
udid: 'A',
filePath,
size,
part: 1,
logger,
});
}
expect(uploadDeviceRunSessionArtifactAsync).toHaveBeenCalledTimes(1);
expect(logger.warn).toHaveBeenCalledWith(
'Skipping network capture for A: exceeds the 500 MB upload limit.'
);
expect(Sentry.capture).not.toHaveBeenCalled();
});
@@ -0,0 +1,606 @@
import { bunyan } from '@expo/logger';
import { type BuildStepEnv } from '@expo/steps';
import { appendFileSync, existsSync, writeFileSync } from 'node:fs';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { spawnDetached } from '../remoteDeviceRunSession';
import { ServeSimNetworkCaptureRecorder } from '../serveSimNetworkCaptureRecorder';
jest.mock('../../../sentry');
jest.mock('../remoteDeviceRunSession', () => ({
...jest.requireActual('../remoteDeviceRunSession'),
spawnDetached: jest.fn(),
}));
const logger = {
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
debug: jest.fn(),
} as unknown as bunyan;
const env = {} as BuildStepEnv;
const stopFollower = jest.fn();
let stateDir: string;
async function writeServerAsync(udid: string, state: Record<string, unknown>): Promise<void> {
await writeFile(
path.join(stateDir, `server-${udid}.json`),
JSON.stringify({ device: udid, ...state })
);
}
/** Writes what `capture har` leaves: a HAR, and its entry log with one line per request. */
function record(harPath: string, entries: number): void {
writeFileSync(harPath, `${JSON.stringify({ log: { entries: Array(entries).fill({}) } })}\n`);
writeFileSync(harPath.replace(/\.har$/, '.entries.ndjson'), '{}\n'.repeat(entries));
}
type Request = { id: string; startedAt: number };
function entryFor({ id, startedAt }: Request) {
return {
startedDateTime: new Date(startedAt).toISOString(),
request: { url: `https://example.com/${id}` },
_captureId: id,
_captureStartedAt: startedAt,
};
}
/** Writes a recording as serve-sim does: entries by completion time, the HAR in start order. */
function recordRequests(harPath: string, requests: Request[]): void {
const entries = requests.map(entryFor);
const sorted = [...entries].sort((a, b) => a._captureStartedAt - b._captureStartedAt);
writeFileSync(
harPath,
`${JSON.stringify({
log: {
version: '1.2',
creator: { name: '@expo/serve-sim', version: '0.10.2' },
entries: sorted,
},
})}\n`
);
writeFileSync(
harPath.replace(/\.har$/, '.entries.ndjson'),
entries.map(entry => `${JSON.stringify(entry)}\n`).join('')
);
}
async function readHarAsync(harPath: string): Promise<any> {
return JSON.parse(await readFile(harPath, 'utf8'));
}
function followerArgs(): string[][] {
return jest.mocked(spawnDetached).mock.calls.map(([options]) => options.args);
}
async function waitForFollowersAsync(count: number): Promise<void> {
for (let i = 0; i < 300 && jest.mocked(spawnDetached).mock.calls.length < count; i++) {
await delay(10);
}
expect(spawnDetached).toHaveBeenCalledTimes(count);
}
beforeEach(async () => {
jest.clearAllMocks();
stopFollower.mockResolvedValue(undefined);
jest.mocked(spawnDetached).mockImplementation(() => ({
pid: 1234,
getOutput: () => 'Stopped before recording began.',
getExitError: () => undefined,
stopAsync: stopFollower,
}));
stateDir = await mkdtemp(path.join(os.tmpdir(), 'serve-sim-network-capture-test-'));
await mkdir(stateDir, { recursive: true });
});
afterEach(async () => {
await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
await rm(stateDir, { recursive: true, force: true });
});
it('starts one capture har follower per serve-sim that can serve capture routes', async () => {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await writeServerAsync('SIM-B', { url: 'http://127.0.0.1:4200' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
packageVersion: '0.5.0',
stateDir,
pollIntervalMs: 10,
});
await waitForFollowersAsync(1);
await delay(50);
expect(spawnDetached).toHaveBeenCalledTimes(1);
const [options] = jest.mocked(spawnDetached).mock.calls[0];
expect(options.command).toBe('npx');
expect(options.args).toEqual([
'--yes',
'@expo/[email protected]',
'capture',
'har',
'-o',
expect.stringMatching(/SIM-A-1\.har$/),
'-d',
'SIM-A',
]);
expect(options.stopGracePeriodMs).toBe(60_000);
});
it('does not pass the ngrok token to the follower', async () => {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env: { NGROK_AUTHTOKEN: 'ngrok-secret', PATH: '/usr/bin' } as BuildStepEnv,
stateDir,
pollIntervalMs: 10,
});
await waitForFollowersAsync(1);
expect(jest.mocked(spawnDetached).mock.calls[0][0].env).toEqual({ PATH: '/usr/bin' });
});
it('starts a new follower only when serve-sim restarts for the device', async () => {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 10,
packageVersion: '0.5.0',
});
await waitForFollowersAsync(1);
await delay(50);
expect(spawnDetached).toHaveBeenCalledTimes(1);
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-restarted' });
await waitForFollowersAsync(2);
expect(jest.mocked(spawnDetached).mock.calls[1][0].command).toBe('npx');
expect(followerArgs()[1]).toEqual([
'--yes',
'@expo/[email protected]',
'capture',
'har',
'-o',
expect.stringMatching(/SIM-A-2\.har$/),
'-d',
'SIM-A',
]);
});
it('stops every follower and returns only the HARs that hold requests', async () => {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await writeServerAsync('SIM-B', { url: 'http://127.0.0.1:4200', token: 'token-b' });
await ServeSimNetworkCaptureRecorder.startAsync({ logger, env, stateDir, pollIntervalMs: 10 });
await waitForFollowersAsync(2);
const recorded = followerArgs().find(args => args.includes('SIM-A'))!;
record(recorded[recorded.indexOf('-o') + 1], 1);
// serve-sim writes an empty HAR when recording begins, before any request.
const empty = followerArgs().find(args => args.includes('SIM-B'))!;
record(empty[empty.indexOf('-o') + 1], 0);
const { outputDirectory, captures } = await ServeSimNetworkCaptureRecorder.finishAsync({
logger,
});
expect(stopFollower).toHaveBeenCalledTimes(2);
expect(captures).toEqual([
{ udid: 'SIM-A', filePath: recorded[recorded.indexOf('-o') + 1], size: 25 },
]);
expect(outputDirectory).toBe(path.dirname(captures[0].filePath));
expect(logger.info).toHaveBeenCalledWith(
{ output: 'Stopped before recording began.' },
'No network capture was recorded for SIM-B.'
);
});
it('stops followers in parallel', async () => {
let stopping = 0;
let mostAtOnce = 0;
stopFollower.mockImplementation(async () => {
stopping += 1;
mostAtOnce = Math.max(mostAtOnce, stopping);
await delay(20);
stopping -= 1;
});
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await writeServerAsync('SIM-B', { url: 'http://127.0.0.1:4200', token: 'token-b' });
await ServeSimNetworkCaptureRecorder.startAsync({ logger, env, stateDir, pollIntervalMs: 10 });
await waitForFollowersAsync(2);
await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
expect(mostAtOnce).toBe(2);
});
it('keeps collecting when a follower cannot be stopped', async () => {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({ logger, env, stateDir, pollIntervalMs: 10 });
await waitForFollowersAsync(1);
stopFollower.mockRejectedValueOnce(new Error('EPERM'));
await expect(ServeSimNetworkCaptureRecorder.finishAsync({ logger })).resolves.toEqual({
outputDirectory: expect.any(String),
captures: [],
});
expect(logger.warn).toHaveBeenCalledWith(
{ err: expect.objectContaining({ message: 'EPERM' }) },
'Could not stop the network capture follower for SIM-A.'
);
});
it('returns nothing when the recorder never started', async () => {
await expect(ServeSimNetworkCaptureRecorder.finishAsync({ logger })).resolves.toEqual({
outputDirectory: null,
captures: [],
});
});
describe('restarting followers', () => {
const exits: (Error | undefined)[] = [];
beforeEach(() => {
exits.length = 0;
jest.mocked(spawnDetached).mockImplementation(() => {
const index = exits.push(undefined) - 1;
return {
pid: 1234,
getOutput: () => 'Network capture is not enabled on this device.',
getExitError: () => exits[index],
stopAsync: stopFollower,
};
});
});
function outPath(call: number): string {
const args = followerArgs()[call];
return args[args.indexOf('-o') + 1];
}
it('starts another follower when one exits before capture was on, and drops the empty one', async () => {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 10,
idleRestartIntervalMs: 30,
});
await waitForFollowersAsync(1);
exits[0] = new Error('Process exited with code 1.');
await waitForFollowersAsync(2);
expect(outPath(1)).toMatch(/SIM-A-2\.har$/);
record(outPath(1), 1);
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
expect(captures).toEqual([{ udid: 'SIM-A', filePath: outPath(1), size: 25 }]);
expect(stopFollower).toHaveBeenCalledTimes(1);
});
it('keeps a recording when its stream drops and records the rest in a new part', async () => {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 10,
restartIntervalMs: 30,
});
await waitForFollowersAsync(1);
record(outPath(0), 2);
exits[0] = new Error('Process exited with code 1.');
await waitForFollowersAsync(2);
record(outPath(1), 1);
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
expect(captures).toEqual([
{ udid: 'SIM-A', filePath: outPath(0), size: 28 },
{ udid: 'SIM-A', filePath: outPath(1), size: 25 },
]);
});
describe('when a new follower replays the requests serve-sim holds', () => {
const r1 = { id: 'r1', startedAt: 1_000 };
const r2 = { id: 'r2', startedAt: 2_000 };
async function startAsync(): Promise<void> {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 10,
restartIntervalMs: 30,
});
await waitForFollowersAsync(1);
}
it('drops a part that holds only replayed requests', async () => {
await startAsync();
recordRequests(outPath(0), [r2, r1]);
exits[0] = new Error('Process exited with code 1.');
await waitForFollowersAsync(2);
recordRequests(outPath(1), [r2, r1]);
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
expect(captures.map(capture => capture.filePath)).toEqual([outPath(0)]);
});
it('keeps only the new requests in a later part, in start order', async () => {
await startAsync();
recordRequests(outPath(0), [r1]);
exits[0] = new Error('Process exited with code 1.');
await waitForFollowersAsync(2);
// A request from a later capture session reuses the id r1 with another start time.
const r1Again = { id: 'r1', startedAt: 4_000 };
recordRequests(outPath(1), [r1Again, r1, r2]);
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
expect(captures.map(capture => capture.filePath)).toEqual([outPath(0), outPath(1)]);
const har = await readHarAsync(outPath(1));
expect(har.log.creator).toEqual({ name: '@expo/serve-sim', version: '0.10.2' });
expect(har.log.entries.map((entry: any) => entry._captureStartedAt)).toEqual([2_000, 4_000]);
expect(captures[1].size).toBe((await readFile(outPath(1))).length);
});
it('keeps the requests a killed follower logged before its HAR caught up', async () => {
const r3 = { id: 'r3', startedAt: 3_000 };
await startAsync();
// serve-sim writes the entry log before it rebuilds the HAR, so a killed follower's HAR can
// lack r2 although its entry log has it.
recordRequests(outPath(0), [r1]);
appendFileSync(
outPath(0).replace(/\.har$/, '.entries.ndjson'),
`${JSON.stringify(entryFor(r2))}\n`
);
exits[0] = new Error('Process exited with code 1.');
await waitForFollowersAsync(2);
recordRequests(outPath(1), [r1, r2, r3]);
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
expect(captures.map(capture => capture.filePath)).toEqual([outPath(0), outPath(1)]);
const ids = async (harPath: string): Promise<string[]> =>
(await readHarAsync(harPath)).log.entries.map((entry: any) => entry._captureId);
expect(await ids(outPath(0))).toEqual(['r1', 'r2']);
expect(await ids(outPath(1))).toEqual(['r3']);
});
it('leaves out a line a killed follower cut off', async () => {
await startAsync();
recordRequests(outPath(0), [r1]);
appendFileSync(outPath(0).replace(/\.har$/, '.entries.ndjson'), '{"startedDateTime":"20');
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
expect(captures.map(capture => capture.filePath)).toEqual([outPath(0)]);
const har = await readHarAsync(outPath(0));
expect(har.log.entries.map((entry: any) => entry._captureId)).toEqual(['r1']);
});
it('removes the files of a part that holds only replayed requests', async () => {
await startAsync();
recordRequests(outPath(0), [r1]);
exits[0] = new Error('Process exited with code 1.');
await waitForFollowersAsync(2);
recordRequests(outPath(1), [r1]);
const replayedFiles = [
outPath(1),
outPath(1).replace(/\.har$/, '.entries.ndjson'),
outPath(1).replace(/\.har$/, '.network-capture.json'),
`${outPath(1)}.0f7c2a4e-9d1b-4c3a-8e5f-6a7b8c9d0e1f.seed.tmp`,
];
for (const file of replayedFiles.slice(2)) {
writeFileSync(file, '{}');
}
exits[1] = new Error('Process exited with code 1.');
await waitForFollowersAsync(3);
expect(replayedFiles.filter(file => existsSync(file))).toEqual([]);
expect(existsSync(outPath(0))).toBe(true);
});
it('does not use a recording slot for followers that recorded no new request', async () => {
jest.mocked(spawnDetached).mockImplementation(({ args }) => {
recordRequests(args[args.indexOf('-o') + 1], [r1]);
return {
pid: 1234,
getOutput: () => '',
getExitError: () => new Error('Process exited with code 1.'),
stopAsync: stopFollower,
};
});
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 1,
restartIntervalMs: 0,
});
for (let i = 0; i < 300 && jest.mocked(spawnDetached).mock.calls.length < 25; i++) {
await delay(10);
}
expect(jest.mocked(spawnDetached).mock.calls.length).toBeGreaterThanOrEqual(25);
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
expect(captures.map(capture => capture.filePath)).toEqual([outPath(0)]);
expect(logger.warn).not.toHaveBeenCalledWith(
'Network capture reached its limit of 20 recordings; recorded captures will be retained.'
);
});
});
it('waits longer to replace a follower that recorded nothing than one that recorded requests', async () => {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 10,
restartIntervalMs: 30,
idleRestartIntervalMs: 60_000,
});
await waitForFollowersAsync(1);
exits[0] = new Error('Process exited with code 1.');
await delay(100);
expect(spawnDetached).toHaveBeenCalledTimes(1);
record(outPath(0), 1);
await waitForFollowersAsync(2);
});
it('drops an empty follower from an earlier serve-sim when serve-sim restarts', async () => {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({ logger, env, stateDir, pollIntervalMs: 10 });
await waitForFollowersAsync(1);
exits[0] = new Error('Process exited with code 1.');
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-restarted' });
await waitForFollowersAsync(2);
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
expect(captures).toEqual([]);
// Only the new follower is left to stop, and the device is reported once.
expect(stopFollower).toHaveBeenCalledTimes(1);
expect(
jest
.mocked(logger.info)
.mock.calls.filter(
([, message]) => message === 'No network capture was recorded for SIM-A.'
)
).toHaveLength(1);
});
it('waits 30 s by default before replacing a follower that recorded nothing', async () => {
const startedAt = Date.now();
const now = jest.spyOn(Date, 'now');
try {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 10,
restartIntervalMs: 0,
});
await waitForFollowersAsync(1);
exits[0] = new Error('Process exited with code 1.');
now.mockReturnValue(startedAt + 29_000);
await delay(50);
expect(spawnDetached).toHaveBeenCalledTimes(1);
now.mockReturnValue(startedAt + 31_000);
await waitForFollowersAsync(2);
} finally {
now.mockRestore();
}
});
it('stops starting followers once 20 HARs hold requests', async () => {
jest.mocked(spawnDetached).mockImplementation(({ args }) => {
record(args[args.indexOf('-o') + 1], 1);
return {
pid: 1234,
getOutput: () => '',
getExitError: () => new Error('Process exited with code 1.'),
stopAsync: stopFollower,
};
});
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 1,
restartIntervalMs: 0,
});
await waitForFollowersAsync(20);
await delay(50);
expect(spawnDetached).toHaveBeenCalledTimes(20);
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
expect(captures).toHaveLength(20);
expect(logger.warn).toHaveBeenCalledTimes(1);
expect(logger.warn).toHaveBeenCalledWith(
'Network capture reached its limit of 20 recordings; recorded captures will be retained.'
);
});
});
it('keeps polling after a follower fails to start, and retries on the next poll', async () => {
jest.mocked(spawnDetached).mockImplementationOnce(() => {
throw new Error('spawn EAGAIN');
});
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 10,
restartIntervalMs: 60_000,
idleRestartIntervalMs: 60_000,
});
await waitForFollowersAsync(2);
expect(logger.warn).toHaveBeenCalledWith(
{ err: expect.objectContaining({ message: 'spawn EAGAIN' }) },
'Could not start the network capture follower for SIM-A; retrying.'
);
expect(followerArgs()[1]).toContainEqual(expect.stringMatching(/SIM-A-2\.har$/));
});
it('bounds followers that record nothing, warns once, and retries a new server identity', async () => {
jest.mocked(spawnDetached).mockImplementation(() => ({
pid: 1234,
getOutput: () => 'npm error: the requested serve-sim package was not found',
getExitError: () => new Error('Process exited with code 1.'),
stopAsync: stopFollower,
}));
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 1,
idleRestartIntervalMs: 0,
});
// Runs that recorded nothing do not use up the 20 HARs that may hold requests.
await waitForFollowersAsync(120);
await delay(50);
expect(spawnDetached).toHaveBeenCalledTimes(120);
const warnings = jest
.mocked(logger.warn)
.mock.calls.filter(([, message]) =>
String(message).startsWith('Stopped retrying network capture')
);
expect(warnings).toEqual([
[
{ output: 'npm error: the requested serve-sim package was not found' },
'Stopped retrying network capture for SIM-A after 120 attempts; recorded captures will be retained.',
],
]);
jest.mocked(spawnDetached).mockImplementation(() => ({
pid: 1234,
getOutput: () => '',
getExitError: () => undefined,
stopAsync: stopFollower,
}));
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'new-token' });
await waitForFollowersAsync(121);
await delay(50);
expect(spawnDetached).toHaveBeenCalledTimes(121);
expect(followerArgs()[120]).toContainEqual(expect.stringMatching(/SIM-A-121\.har$/));
});
it('keeps a running empty follower waiting without spending more attempts', async () => {
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
await ServeSimNetworkCaptureRecorder.startAsync({
logger,
env,
stateDir,
pollIntervalMs: 1,
restartIntervalMs: 0,
idleRestartIntervalMs: 0,
});
await waitForFollowersAsync(1);
await delay(50);
expect(spawnDetached).toHaveBeenCalledTimes(1);
expect(logger.warn).not.toHaveBeenCalled();
});
@@ -47,6 +47,7 @@ import {
IosSimulatorRecordingUtils,
SERVE_SIM_STOP_GRACE_PERIOD_MS,
} from './IosSimulatorRecordingUtils';
import { ServeSimCrashesRecorder } from './serveSimCrashesRecorder';
import { SERVE_SIM_STATE_DIR, readServeSimServersAsync } from './serveSimMetricsRecorder';
import { startLogPhase } from '../../utils/logPhase';
import { runServeSimActionAsync, stageServeSimAppAsync } from './serveSimActions';
@@ -128,7 +129,7 @@ export function corsOriginArgs(corsOrigins: readonly string[]): string[] {
return corsOrigins.flatMap(origin => ['--cors-origin', origin]);
}
function createServeSimPackageSpec(packageVersion: string | undefined): string {
export function createServeSimPackageSpec(packageVersion: string | undefined): string {
return `${SERVE_SIM_PACKAGE_NAME}@${packageVersion ?? 'latest'}`;
}
@@ -1175,6 +1176,8 @@ async function finishDeviceSessionHostAsync(
logger,
});
}
// Crash reports are read from serve-sim, so collection finishes before it stops.
await ServeSimCrashesRecorder.stopAsync();
let hostStopped = false;
try {
await previewServer.stopAsync();
@@ -0,0 +1,48 @@
import { type bunyan } from '@expo/logger';
import { type CustomBuildContext } from '../../customBuildContext';
import { Sentry } from '../../sentry';
import { type CollectedCrash } from './serveSimCrashesRecorder';
import { uploadDeviceRunSessionFileAsync } from './uploadDeviceRunSessionFile';
export async function uploadServeSimCrashesFileAsync(
ctx: CustomBuildContext,
{
deviceRunSessionId,
crash: { udid, filePath, number, processName },
logger,
signal,
}: {
deviceRunSessionId: string;
crash: CollectedCrash;
logger: bunyan;
signal?: AbortSignal;
}
): Promise<void> {
const device = udid.slice(0, 8);
try {
await uploadDeviceRunSessionFileAsync(ctx, {
filePath,
describe: () => ({
deviceRunSessionId,
artifactId: `simulator-crash-${udid}-${number}`,
name: processName
? `Crash report ${number}: ${processName} (${device})`
: `Crash report ${number} (${device})`,
// Process names are not paths; keep separators out of the download name.
filename: `${(processName ?? 'crash').replace(/[/\\:\x00-\x1f]/g, '-')}-${number}.ips`,
kind: 'simulator-crash',
metadata: { __eas_type: 'simulator-crash', udid, source: 'serve-sim/crashes' },
}),
attempts: 3,
signal,
});
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err));
Sentry.capture('Could not upload a simulator crash report', error, { level: 'warning' });
logger.warn(
{ err: error },
`Could not upload crash report ${number} for ${udid}; other artifacts will continue.`
);
}
}
@@ -0,0 +1,521 @@
import { type bunyan } from '@expo/logger';
import fetch from 'node-fetch';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { z } from 'zod';
import { Sentry } from '../../sentry';
import { SERVE_SIM_STATE_DIR, readServeSimServersAsync } from './serveSimMetricsRecorder';
const MAX_BYTES_PER_DEVICE = 20 * 1024 * 1024;
const MAX_REPORTS_PER_DEVICE = 1_000;
const MAX_CONSECUTIVE_FAILURES = 10;
const MAX_FRAME_LENGTH = 1024 * 1024;
const MAX_DETAIL_BYTES = 8 * 1024 * 1024;
// A 5xx, timeout, or dropped connection is retried; a missing or unusable detail is not.
const MAX_DETAIL_ATTEMPTS = 3;
const DETAIL_RETRY_DELAY_MS = 500;
// serve-sim lists a crash about 5 s after it happens, once ReportCrash has written the report,
// so stopping checks each device once more for occurrences the stream had not delivered yet.
const FINAL_PASS_TIMEOUT_MS = 10_000;
const SummarySchema = z.object({
id: z.string(),
appName: z.string().nullable().optional(),
procName: z.string().nullable().optional(),
occurrenceTimes: z.array(
z.object({
key: z.number().int().nonnegative(),
capturedAtMs: z.number().nullable().optional(),
rawPath: z.string().optional(),
})
),
});
const FrameSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('meta'), meta: z.object({ statusError: z.string().nullable() }) }),
z.object({ type: z.literal('list'), crashes: z.array(SummarySchema) }),
z.object({ type: z.enum(['crash', 'recurred']), record: SummarySchema }),
]);
const ListSchema = z.object({ crashes: z.array(SummarySchema) });
const DetailSchema = z.object({
record: z.object({ id: z.string() }),
occurrence: z.object({
key: z.number().int().nonnegative(),
incidentId: z.string().nullable().optional(),
}),
report: z.string().nullable(),
});
/** A detail that will not change on retry: mismatched, malformed, or over 8 MiB. */
class UnusableDetailError extends Error {}
type ServeSimServer = { udid: string; url: string; token?: string };
export type CollectedCrash = {
udid: string;
filePath: string;
size: number;
number: number;
processName?: string;
};
type FinishedCrashes = { outputDirectory: string | null; crashes: CollectedCrash[] };
type Device = {
// The latest registry entry; unset while the server is absent, so its return counts as new.
server?: ServeSimServer;
identity?: string;
// Occurrences saved or skipped; reconnects replay the retained list and must not retry them.
handled: Set<string>;
incidents: Set<string>;
bytesWritten: number;
reportsWritten: number;
limitReached: boolean;
failures: number;
stoppedRetrying: boolean;
warnedStatusError: boolean;
};
type Session = {
outputDirectory: string;
logger: bunyan;
maxBytes: number;
finalPassTimeoutMs: number;
controller: AbortController;
timer: NodeJS.Timeout;
polling: Promise<void>;
streams: Map<string, Promise<void>>;
devices: Map<string, Device>;
files: CollectedCrash[];
stopping?: Promise<void>;
finishing?: Promise<FinishedCrashes>;
};
let activeSession: Session | undefined;
export namespace ServeSimCrashesRecorder {
export async function startAsync({
logger,
stateDir = SERVE_SIM_STATE_DIR,
pollIntervalMs = 2_000,
maxBytes = MAX_BYTES_PER_DEVICE,
maxDurationMs = 30 * 60 * 1000,
finalPassTimeoutMs = FINAL_PASS_TIMEOUT_MS,
}: {
logger: bunyan;
stateDir?: string;
pollIntervalMs?: number;
maxBytes?: number;
maxDurationMs?: number;
finalPassTimeoutMs?: number;
}): Promise<void> {
if (activeSession) {
return;
}
const controller = new AbortController();
const session: Session = {
outputDirectory: await mkdtemp(path.join(os.tmpdir(), 'serve-sim-crashes-')),
logger,
maxBytes,
finalPassTimeoutMs,
controller,
timer: setTimeout(() => {
logger.warn(
'Simulator crash collection reached its duration limit; collected reports will be retained.'
);
controller.abort();
}, maxDurationMs),
polling: Promise.resolve(),
streams: new Map(),
devices: new Map(),
files: [],
};
session.timer.unref();
activeSession = session;
session.polling = (async () => {
while (!controller.signal.aborted) {
const servers = await readServeSimServersAsync(stateDir);
const present = new Set(servers.map(server => server.udid));
for (const [udid, device] of session.devices) {
if (!present.has(udid)) {
device.server = undefined;
device.identity = undefined;
}
}
for (const server of servers) {
if (controller.signal.aborted) {
break;
}
const device = getDevice(session, server.udid);
// Kept current while a stream runs, so the final pass reads the latest address.
device.server = server;
if (session.streams.has(server.udid)) {
continue;
}
const identity = JSON.stringify([server.url, server.token]);
if (device.identity !== identity) {
device.identity = identity;
device.failures = 0;
device.stoppedRetrying = false;
}
if (device.limitReached || device.stoppedRetrying) {
continue;
}
if (device.failures >= MAX_CONSECUTIVE_FAILURES) {
device.stoppedRetrying = true;
logger.warn(
`Stopped retrying simulator crash collection for ${server.udid} after ${MAX_CONSECUTIVE_FAILURES} failed connections; collected reports will be retained.`
);
continue;
}
device.failures += 1;
const done = streamServeSimCrashesAsync(session, server, device).finally(() =>
session.streams.delete(server.udid)
);
session.streams.set(server.udid, done);
}
await delay(pollIntervalMs, undefined, { signal: controller.signal }).catch(() => {});
}
})().catch(err => {
const error = err instanceof Error ? err : new Error(String(err));
Sentry.capture('serve-sim simulator crash poller failed', error);
logger.warn(
{ err: error },
'Could not collect simulator crashes; collected reports will be retained.'
);
controller.abort();
});
logger.info('Started collecting simulator crashes (up to 20 MiB per device and 30 minutes).');
}
/** Never rejects. */
export async function stopAsync(): Promise<void> {
const session = activeSession;
if (!session) {
return;
}
session.stopping ??= (async () => {
clearTimeout(session.timer);
session.controller.abort();
await session.polling;
await Promise.all(session.streams.values());
await collectRemainingCrashesAsync(session);
})();
await session.stopping;
}
export async function finishAsync(): Promise<FinishedCrashes> {
const session = activeSession;
if (!session || session.finishing) {
await session?.finishing;
return { outputDirectory: null, crashes: [] };
}
session.finishing = (async () => {
await stopAsync();
return { outputDirectory: session.outputDirectory, crashes: session.files };
})();
try {
return await session.finishing;
} finally {
if (activeSession === session) {
activeSession = undefined;
}
}
}
}
function getDevice(session: Session, udid: string): Device {
let device = session.devices.get(udid);
if (!device) {
device = {
handled: new Set(),
incidents: new Set(),
bytesWritten: 0,
reportsWritten: 0,
limitReached: false,
failures: 0,
stoppedRetrying: false,
warnedStatusError: false,
};
session.devices.set(udid, device);
}
return device;
}
async function streamServeSimCrashesAsync(
session: Session,
server: ServeSimServer,
device: Device
): Promise<void> {
const { logger } = session;
const signal = session.controller.signal;
const controller = new AbortController();
try {
const url = new URL('/crashes', server.url);
url.searchParams.set('device', server.udid);
const response = await fetch(url.toString(), {
redirect: 'error',
signal: AbortSignal.any([signal, controller.signal]),
headers: {
Accept: 'text/event-stream',
...(server.token ? { Authorization: `Bearer ${server.token}` } : {}),
},
});
if (
!response.ok ||
!response.body ||
!response.headers.get('content-type')?.includes('text/event-stream')
) {
throw new Error(`serve-sim /crashes responded ${response.status}`);
}
const decoder = new TextDecoder();
let buffer = '';
for await (const chunk of response.body) {
buffer += decoder.decode(chunk as Buffer, { stream: true });
let newline: number;
while ((newline = buffer.indexOf('\n')) !== -1) {
const line = buffer.slice(0, newline).replace(/\r$/, '');
buffer = buffer.slice(newline + 1);
if (line.length > MAX_FRAME_LENGTH) {
throw new Error('Crash frame exceeded limit');
}
if (!line.startsWith('data:')) {
continue;
}
const frame = FrameSchema.safeParse(JSON.parse(line.slice(5)));
if (!frame.success) {
continue;
}
if (frame.data.type === 'meta') {
if (frame.data.meta.statusError && !device.warnedStatusError) {
device.warnedStatusError = true;
logger.warn(
'serve-sim cannot watch crash reports; crash collection will resume when the watcher recovers.'
);
}
continue;
}
const summaries = frame.data.type === 'list' ? frame.data.crashes : [frame.data.record];
await saveOccurrencesAsync(session, server, device, summaries, { stop: signal });
if (signal.aborted || device.limitReached) {
return;
}
device.failures = 0;
}
if (buffer.length > MAX_FRAME_LENGTH) {
throw new Error('Crash frame exceeded limit');
}
}
} catch (err) {
if (!signal.aborted) {
logger.warn(
{ err },
`Simulator crash stream for ${server.udid} ended; collection will be retried.`
);
}
} finally {
controller.abort();
}
}
/** One look at each device's crash list, for occurrences the stream had not delivered. */
async function collectRemainingCrashesAsync(session: Session): Promise<void> {
const signal = AbortSignal.timeout(session.finalPassTimeoutMs);
await Promise.all(
[...session.devices.values()].map(async device => {
const { server } = device;
if (!server || device.limitReached) {
return;
}
try {
const url = new URL('/crashes', server.url);
url.searchParams.set('device', server.udid);
const response = await fetch(url.toString(), {
redirect: 'error',
signal,
headers: {
Accept: 'application/json',
...(server.token ? { Authorization: `Bearer ${server.token}` } : {}),
},
});
if (!response.ok || !response.headers.get('content-type')?.includes('application/json')) {
throw new Error(`serve-sim /crashes responded ${response.status}`);
}
const { crashes } = ListSchema.parse(await response.json());
await saveOccurrencesAsync(session, server, device, crashes, {
stop: signal,
deadline: signal,
});
} catch (err) {
session.logger.warn(
{ err },
`Could not check ${server.udid} for crashes before the session ended; collected reports will be retained.`
);
}
})
);
}
async function saveOccurrencesAsync(
session: Session,
server: ServeSimServer,
device: Device,
summaries: z.infer<typeof SummarySchema>[],
// `stop` ends the loop between occurrences; `deadline` also aborts a download in progress.
{ stop, deadline }: { stop: AbortSignal; deadline?: AbortSignal }
): Promise<void> {
const { logger } = session;
// Each caller returns once this is true, so the deadline warning is logged once per pass.
const stopped = (): boolean => {
if (deadline?.aborted) {
logger.warn(
`Stopped checking ${server.udid} for crashes at the end-of-session deadline; collected reports will be retained.`
);
}
return stop.aborted || !!deadline?.aborted;
};
for (const summary of summaries) {
for (const occurrence of summary.occurrenceTimes) {
if (device.limitReached || stopped()) {
return;
}
// Keys restart when serve-sim does; the capture time and report path tell such occurrences apart.
const key = JSON.stringify([
summary.id,
occurrence.key,
occurrence.capturedAtMs ?? null,
occurrence.rawPath ?? null,
]);
if (device.handled.has(key)) {
continue;
}
let detail: z.infer<typeof DetailSchema> | undefined;
try {
for (let attempt = 1; ; attempt++) {
try {
detail = await readCrashDetailAsync(server, summary.id, occurrence.key, deadline);
break;
} catch (err) {
if (err instanceof UnusableDetailError || attempt >= MAX_DETAIL_ATTEMPTS) {
throw err;
}
await delay(DETAIL_RETRY_DELAY_MS, undefined, { signal: stop });
}
}
} catch (err) {
// Stopping leaves the occurrence unhandled, so the final pass can still save it.
if (stopped()) {
return;
}
device.handled.add(key);
logger.warn(
{ err },
`Could not download crash occurrence ${occurrence.key} for ${server.udid}; skipping it.`
);
continue;
}
device.handled.add(key);
if (!detail) {
logger.warn(
`Crash occurrence ${occurrence.key} is no longer available for ${server.udid}; earlier reports will be retained.`
);
continue;
}
const { incidentId } = detail.occurrence;
if (incidentId && device.incidents.has(incidentId)) {
continue;
}
if (!detail.report) {
logger.warn(
`Crash occurrence ${occurrence.key} has no native report for ${server.udid}; skipping its artifact.`
);
continue;
}
const size = Buffer.byteLength(detail.report);
if (
device.bytesWritten + size > session.maxBytes ||
device.reportsWritten >= MAX_REPORTS_PER_DEVICE
) {
device.limitReached = true;
logger.warn(
`Simulator crash collection reached its limit for ${server.udid}; collected reports will be retained.`
);
return;
}
const number = device.reportsWritten + 1;
const filePath = path.join(session.outputDirectory, `${server.udid}-${number}.ips`);
try {
await writeFile(filePath, detail.report, { mode: 0o600, flag: 'wx' });
} catch (error) {
device.handled.delete(key);
await rm(filePath, { force: true }).catch(() => {});
throw error;
}
device.bytesWritten += size;
device.reportsWritten = number;
if (incidentId) {
device.incidents.add(incidentId);
}
const processName = summary.appName || summary.procName || undefined;
session.files.push({
udid: server.udid,
filePath,
size,
number,
...(processName ? { processName } : {}),
});
}
}
}
/** Resolves `undefined` when serve-sim no longer keeps the occurrence. */
async function readCrashDetailAsync(
server: ServeSimServer,
id: string,
key: number,
deadline?: AbortSignal
): Promise<z.infer<typeof DetailSchema> | undefined> {
const url = new URL(`/crashes/${encodeURIComponent(id)}`, server.url);
url.searchParams.set('device', server.udid);
url.searchParams.set('key', String(key));
const controller = new AbortController();
try {
const response = await fetch(url.toString(), {
redirect: 'error',
size: MAX_DETAIL_BYTES,
signal: AbortSignal.any([
controller.signal,
AbortSignal.timeout(5_000),
...(deadline ? [deadline] : []),
]),
...(server.token ? { headers: { Authorization: `Bearer ${server.token}` } } : {}),
});
if (response.status === 404) {
return undefined;
}
if (!response.ok) {
// Other 4xx responses will not change on a retry; 408, 429 and 5xx can.
const permanent = response.status < 500 && response.status !== 408 && response.status !== 429;
throw new (permanent ? UnusableDetailError : Error)(
`serve-sim crash detail responded ${response.status}`
);
}
const body = await response.json().catch(err => {
const type = (err as { type?: string }).type;
if (type === 'max-size') {
throw new UnusableDetailError('Crash detail exceeds 8 MiB');
}
if (type === 'invalid-json') {
throw new UnusableDetailError('Crash detail is not valid JSON');
}
throw err;
});
const detail = DetailSchema.safeParse(body);
if (!detail.success) {
throw new UnusableDetailError('Crash detail is not valid');
}
if (detail.data.record.id !== id || detail.data.occurrence.key !== key) {
throw new UnusableDetailError('Crash detail does not match the requested occurrence');
}
return detail.data;
} finally {
controller.abort();
}
}
@@ -0,0 +1,59 @@
import { formatBytes } from '@expo/eas-build-job';
import { type bunyan } from '@expo/logger';
import { CustomBuildContext } from '../../customBuildContext';
import { Sentry } from '../../sentry';
import { uploadDeviceRunSessionFileAsync } from './uploadDeviceRunSessionFile';
const NETWORK_CAPTURE_ARTIFACT_FILENAME = 'network-capture.har';
const MAX_NETWORK_CAPTURE_ARTIFACT_SIZE_BYTES = 500 * 1024 * 1024;
/** Never rejects; a failed upload is logged. */
export async function uploadServeSimNetworkCaptureFileAsync(
ctx: CustomBuildContext,
{
deviceRunSessionId,
udid,
filePath,
size,
part,
logger,
signal,
}: {
deviceRunSessionId: string;
udid: string;
filePath: string;
size: number;
part: number;
logger: bunyan;
signal?: AbortSignal;
}
): Promise<void> {
const label = part > 1 ? `, part ${part}` : '';
if (size > MAX_NETWORK_CAPTURE_ARTIFACT_SIZE_BYTES) {
logger.warn(
`Skipping network capture for ${udid}${label}: exceeds the ${formatBytes(MAX_NETWORK_CAPTURE_ARTIFACT_SIZE_BYTES)} upload limit.`
);
return;
}
try {
logger.info(`Uploading the network capture for ${udid}${label} (${formatBytes(size)}).`);
await uploadDeviceRunSessionFileAsync(ctx, {
filePath,
describe: () => ({
deviceRunSessionId,
artifactId: `network-capture-${udid}-${part}`,
name: `Network capture (${udid.slice(0, 8)}${label})`,
filename: NETWORK_CAPTURE_ARTIFACT_FILENAME,
kind: 'network-capture',
metadata: { __eas_type: 'network-capture', format: 'har', udid, part },
}),
attempts: 3,
signal,
});
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err));
Sentry.capture('Could not upload the network capture', error, { level: 'warning' });
logger.warn({ err: error }, `Could not upload the network capture for ${udid}.`);
}
}
@@ -0,0 +1,472 @@
import { type bunyan } from '@expo/logger';
import { type BuildStepEnv } from '@expo/steps';
import { createReadStream } from 'node:fs';
import { mkdtemp, open, readdir, rename, rm, stat } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { createInterface } from 'node:readline';
import { setTimeout as delay } from 'node:timers/promises';
import { Sentry } from '../../sentry';
import {
PackageManager,
resolveConfiguredPackageManager,
resolvePackageExec,
} from '../../utils/packageManager';
import { createServeSimPackageSpec } from './deviceSessionHost';
import {
type DetachedProcessHandle,
omitNgrokAuthtoken,
spawnDetached,
} from './remoteDeviceRunSession';
import { SERVE_SIM_STATE_DIR, readServeSimServersAsync } from './serveSimMetricsRecorder';
const POLL_INTERVAL_MS = 2_000;
// While serve-sim runs, an exited follower (stream dropped, capture off) is replaced after this long;
// one that recorded nothing (usually capture off) waits longer, since it may stay off all session.
const FOLLOWER_RESTART_INTERVAL_MS = 10_000;
const IDLE_FOLLOWER_RESTART_INTERVAL_MS = 30_000;
// On stop the follower rebuilds the whole HAR from its entry log; a shorter --flush-ms would not
// shorten that last rebuild, so a large recording gets a longer grace before it is killed.
const FOLLOWER_STOP_GRACE_PERIOD_MS = 60_000;
// HARs holding requests, across the session.
const MAX_RECORDINGS = 20;
// Followers started for one serve-sim server; at the idle interval this covers about an hour.
const MAX_FOLLOWER_STARTS = 120;
const OUTPUT_TAIL_CHARS = 2_000;
type Follower = {
udid: string;
filePath: string;
handle: DetachedProcessHandle;
startedAt: number;
/** Set once the follower has exited and holds requests no earlier follower recorded. */
kept?: boolean;
};
type ServeSimNetworkCaptureSession = {
logger: bunyan;
stateDir: string;
pollIntervalMs: number;
restartIntervalMs: number;
idleRestartIntervalMs: number;
outputDirectory: string;
command: { command: string; args: string[] };
env: BuildStepEnv;
followers: Follower[];
current: Map<string, Follower>;
followerStarts: Map<string, number>;
stoppedRetrying: Set<string>;
warnedRecordingLimit: boolean;
fileCounts: Map<string, number>;
/** Per device, the requests of the exited followers that were kept. */
keptRequests: Map<string, Set<string>>;
pollingPromise: Promise<void>;
abortController: AbortController;
};
export type RecordedNetworkCapture = { udid: string; filePath: string; size: number };
let activeSession: ServeSimNetworkCaptureSession | null = null;
/** serve-sim deletes capture files when capture stops; a `capture har` follower keeps the HAR. */
export namespace ServeSimNetworkCaptureRecorder {
export async function startAsync({
logger,
env,
packageVersion,
stateDir = SERVE_SIM_STATE_DIR,
pollIntervalMs = POLL_INTERVAL_MS,
restartIntervalMs = FOLLOWER_RESTART_INTERVAL_MS,
idleRestartIntervalMs = IDLE_FOLLOWER_RESTART_INTERVAL_MS,
}: {
logger: bunyan;
env: BuildStepEnv;
packageVersion?: string;
stateDir?: string;
pollIntervalMs?: number;
restartIntervalMs?: number;
idleRestartIntervalMs?: number;
}): Promise<void> {
if (activeSession) {
logger.info('The serve-sim network capture recorder is already running.');
return;
}
const command = resolvePackageExec(resolveConfiguredPackageManager(env, PackageManager.NPM), [
createServeSimPackageSpec(packageVersion),
]);
const session: ServeSimNetworkCaptureSession = {
logger,
stateDir,
pollIntervalMs,
restartIntervalMs,
idleRestartIntervalMs,
outputDirectory: await mkdtemp(path.join(os.tmpdir(), 'serve-sim-network-capture-')),
command,
env: omitNgrokAuthtoken(env),
followers: [],
current: new Map(),
followerStarts: new Map(),
stoppedRetrying: new Set(),
warnedRecordingLimit: false,
fileCounts: new Map(),
keptRequests: new Map(),
pollingPromise: Promise.resolve(),
abortController: new AbortController(),
};
activeSession = session;
logger.info('Started watching serve-sim for network capture.');
session.pollingPromise = pollServeSimServersAsync(session).catch(err => {
const error = err instanceof Error ? err : new Error(String(err));
Sentry.capture('serve-sim network capture poller failed', error);
logger.warn({ err: error }, 'serve-sim network capture poller failed.');
});
}
/** Never rejects. */
export async function finishAsync({
logger,
}: {
logger: bunyan;
}): Promise<{ outputDirectory: string | null; captures: RecordedNetworkCapture[] }> {
const session = activeSession;
if (!session) {
logger.info('The serve-sim network capture recorder is not running.');
return { outputDirectory: null, captures: [] };
}
activeSession = null;
session.abortController.abort();
await session.pollingPromise;
// Stopped together, so the final HAR rebuilds share one grace period.
await Promise.all(
session.followers.map(follower =>
follower.handle.stopAsync().catch(err => {
logger.warn({ err }, `Could not stop the network capture follower for ${follower.udid}.`);
})
)
);
const captures: RecordedNetworkCapture[] = [];
const recorded = new Map<string, Set<string>>();
for (const follower of session.followers) {
try {
if (!(await rebuildHarAsync(follower, requestsFor(recorded, follower.udid)))) {
continue;
}
} catch (err) {
logger.warn(
{ err },
`Could not rebuild a network capture for ${follower.udid}; its HAR is kept as serve-sim wrote it.`
);
}
const size = await stat(follower.filePath).then(
stats => stats.size,
() => 0
);
if (size > 0) {
captures.push({ udid: follower.udid, filePath: follower.filePath, size });
}
}
for (const follower of session.current.values()) {
if (!captures.some(capture => capture.udid === follower.udid)) {
logger.info(
{ output: follower.handle.getOutput().slice(-OUTPUT_TAIL_CHARS) || '<empty>' },
`No network capture was recorded for ${follower.udid}.`
);
}
}
return { outputDirectory: session.outputDirectory, captures };
}
}
async function pollServeSimServersAsync(session: ServeSimNetworkCaptureSession): Promise<void> {
const { abortController } = session;
while (!abortController.signal.aborted) {
for (const server of await readServeSimServersAsync(session.stateDir)) {
// serve-sim's capture routes require a token, so `capture har` refuses a server without one.
if (!server.token) {
continue;
}
const key = `${server.udid}\n${server.url}\n${server.token}`;
try {
await ensureFollowerAsync(session, key, server.udid);
} catch (err) {
session.logger.warn(
{ err },
`Could not start the network capture follower for ${server.udid}; retrying.`
);
}
}
await delay(session.pollIntervalMs, undefined, { signal: abortController.signal }).catch(
() => {}
);
}
}
async function ensureFollowerAsync(
session: ServeSimNetworkCaptureSession,
key: string,
udid: string
): Promise<void> {
const previous = session.current.get(key);
if (previous) {
if (previous.handle.getExitError() === undefined) {
return;
}
const recorded = await hasEntriesAsync(previous);
const interval = recorded ? session.restartIntervalMs : session.idleRestartIntervalMs;
if (Date.now() - previous.startedAt < interval) {
return;
}
} else {
// serve-sim restarted with a new token; the old identity's follower is no longer current.
for (const [otherKey, other] of session.current) {
if (other.udid === udid) {
session.current.delete(otherKey);
}
}
}
// A new follower replays the requests serve-sim already holds, so an exited follower that recorded
// no new request holds no capture of its own and does not use a recording slot. Another server's
// current follower waits for its own restart, which reads its entry log.
const current = new Set(session.current.values());
for (const follower of [...session.followers]) {
if (
follower.kept ||
follower.handle.getExitError() === undefined ||
(follower !== previous && current.has(follower))
) {
continue;
}
const keptRequests = requestsFor(session.keptRequests, follower.udid);
const requests = await readRequestKeysAsync(entriesPathFor(follower));
if (requests.some(request => request === null || !keptRequests.has(request))) {
follower.kept = true;
for (const request of requests) {
if (request !== null) {
keptRequests.add(request);
}
}
} else {
session.followers.splice(session.followers.indexOf(follower), 1);
await removeFollowerFilesAsync(follower, session.logger);
}
}
if (session.followers.length >= MAX_RECORDINGS) {
if (!session.warnedRecordingLimit) {
session.warnedRecordingLimit = true;
session.logger.warn(
`Network capture reached its limit of ${MAX_RECORDINGS} recordings; recorded captures will be retained.`
);
}
return;
}
const starts = session.followerStarts.get(key) ?? 0;
if (starts >= MAX_FOLLOWER_STARTS) {
if (!session.stoppedRetrying.has(key)) {
session.stoppedRetrying.add(key);
session.logger.warn(
{ output: previous?.handle.getOutput().slice(-OUTPUT_TAIL_CHARS) || '<empty>' },
`Stopped retrying network capture for ${udid} after ${MAX_FOLLOWER_STARTS} attempts; recorded captures will be retained.`
);
}
return;
}
session.followerStarts.set(key, starts + 1);
const count = (session.fileCounts.get(udid) ?? 0) + 1;
session.fileCounts.set(udid, count);
const filePath = path.join(session.outputDirectory, `${udid}-${count}.har`);
if (!previous) {
session.logger.info(`Recording network capture for ${udid}.`);
}
const follower: Follower = {
udid,
filePath,
startedAt: Date.now(),
handle: spawnDetached({
command: session.command.command,
args: [...session.command.args, 'capture', 'har', '-o', filePath, '-d', udid],
env: session.env,
stopGracePeriodMs: FOLLOWER_STOP_GRACE_PERIOD_MS,
}),
};
session.followers.push(follower);
session.current.set(key, follower);
}
/** serve-sim writes an empty HAR when recording begins; requests go to `<stem>.entries.ndjson`. */
function entriesPathFor(follower: Follower): string {
return follower.filePath.replace(/\.har$/, '.entries.ndjson');
}
/** Removes the HAR and the working files serve-sim names after it, such as its entry log. */
async function removeFollowerFilesAsync(follower: Follower, logger: bunyan): Promise<void> {
const directory = path.dirname(follower.filePath);
const prefix = `${path.basename(follower.filePath, '.har')}.`;
try {
const names = (await readdir(directory)).filter(name => name.startsWith(prefix));
await Promise.all(names.map(name => rm(path.join(directory, name), { force: true })));
} catch (err) {
logger.warn({ err }, `Could not remove a replayed network capture for ${follower.udid}.`);
}
}
async function hasEntriesAsync(follower: Follower): Promise<boolean> {
return await stat(entriesPathFor(follower)).then(
stats => stats.size > 0,
() => false
);
}
function requestsFor(requests: Map<string, Set<string>>, udid: string): Set<string> {
let forDevice = requests.get(udid);
if (!forDevice) {
forDevice = new Set();
requests.set(udid, forDevice);
}
return forDevice;
}
type Entry = { _captureId?: unknown; _captureStartedAt?: unknown; startedDateTime?: unknown };
/**
* Reads an entry log line; null when it is not JSON, such as a line a killed follower cut off.
* Entries without a valid start time sort last.
*/
function parseEntry(line: string): { key: string | null; start: number } | null {
let entry: Entry;
try {
entry = JSON.parse(line);
} catch {
return null;
}
const start = Date.parse(String(entry?.startedDateTime));
return { key: requestKey(entry), start: Number.isNaN(start) ? Number.POSITIVE_INFINITY : start };
}
/**
* A request's identity, as serve-sim's `capture har` matches its replays: request ids restart in
* every capture session, so the request's start time tells them apart. null when serve-sim did not
* record an id, so the request cannot be matched.
*/
function requestKey(entry: Entry | null): string | null {
if (typeof entry?._captureId !== 'string') {
return null;
}
return entry._captureStartedAt !== undefined
? `${entry._captureId} ${entry._captureStartedAt}`
: `${entry._captureId} ${entry.startedDateTime}`;
}
/** Streams the entry log, so a large recording never has to fit in memory. */
async function forEachEntryAsync(
entriesPath: string,
onEntry: (line: string, offset: number) => void
): Promise<void> {
// A follower that never began recording leaves no entry log.
if (
!(await stat(entriesPath).then(
() => true,
() => false
))
) {
return;
}
const input = createReadStream(entriesPath, { encoding: 'utf8' });
const lines = createInterface({ input, crlfDelay: Infinity });
let offset = 0;
try {
for await (const line of lines) {
if (line) {
onEntry(line, offset);
}
offset += Buffer.byteLength(line) + 1;
}
} finally {
lines.close();
input.destroy();
}
}
async function readRequestKeysAsync(entriesPath: string): Promise<(string | null)[]> {
const keys: (string | null)[] = [];
await forEachEntryAsync(entriesPath, line => {
const entry = parseEntry(line);
if (entry) {
keys.push(entry.key);
}
});
return keys;
}
/**
* Rebuilds a stopped follower's HAR from its entry log, which a killed follower's HAR can lag,
* without the requests an earlier follower for the device recorded. Then adds its requests to
* `recorded`. Returns false when it holds no new request.
*/
async function rebuildHarAsync(follower: Follower, recorded: Set<string>): Promise<boolean> {
const entriesPath = entriesPathFor(follower);
const entries: { start: number; offset: number; length: number }[] = [];
const requests: string[] = [];
await forEachEntryAsync(entriesPath, (line, offset) => {
const entry = parseEntry(line);
if (!entry || (entry.key !== null && recorded.has(entry.key))) {
return;
}
if (entry.key !== null) {
requests.push(entry.key);
}
entries.push({ start: entry.start, offset, length: Buffer.byteLength(line) });
});
if (entries.length === 0) {
return false;
}
await writeHarAsync(follower.filePath, entriesPath, entries);
for (const request of requests) {
recorded.add(request);
}
return true;
}
const HAR_HEADER_BYTES = 4_096;
const HAR_ENTRIES_START = '"entries":[';
/** Rebuilds the HAR from the given entry log lines, in start order as serve-sim writes it. */
async function writeHarAsync(
harPath: string,
entriesPath: string,
entries: { start: number; offset: number; length: number }[]
): Promise<void> {
// serve-sim writes `{"log":{...,"entries":[` first; its version and creator are kept.
const har = await open(harPath, 'r');
let header: string;
try {
const buffer = Buffer.alloc(HAR_HEADER_BYTES);
const { bytesRead } = await har.read(buffer, 0, buffer.length, 0);
header = buffer.subarray(0, bytesRead).toString('utf8');
} finally {
await har.close();
}
const at = header.indexOf(HAR_ENTRIES_START);
if (at === -1) {
throw new Error('The HAR does not start like a serve-sim HAR.');
}
const tempPath = `${harPath}.rebuilt.tmp`;
const out = await open(tempPath, 'wx', 0o600);
const source = await open(entriesPath, 'r');
try {
await out.write(Buffer.from(header.slice(0, at + HAR_ENTRIES_START.length)));
const sorted = [...entries].sort((a, b) => a.start - b.start);
for (const [index, { offset, length }] of sorted.entries()) {
const line = Buffer.alloc(length);
await source.read(line, 0, length, offset);
await out.write(index > 0 ? Buffer.concat([Buffer.from(','), line]) : line);
}
await out.write(Buffer.from(']}}\n'));
} finally {
await source.close();
await out.close();
}
await rename(tempPath, harPath);
}
+27 -15
View File
@@ -3111,9 +3111,10 @@ USAGE
[--system-image <value>] [--build-id <value> | --build-fingerprint <value> | --application-archive-url <value> |
--expo-go] [--sdk-version <value>] [--launch-arg <value>...] [--open-url <value>] [--type
agent-device|appium|argent|web-preview-only] [--package-version <value>] [--log-source
emulator-output|device-logcat...] [--network-capture-field <value>... --network-capture] [--max-duration-minutes
<value>] [--max-idle-time-minutes <value>] [--egress-allow <value>... --egress local] [--cors-origin <value>...]
[--frame-ancestor <value>...] [--force] [--out-config-type env|dotenv] [--public-link] [--json] [--non-interactive]
emulator-output|device-logcat...] [--network-capture-recording --network-capture] [--network-capture-field
<value>... ] [--max-duration-minutes <value>] [--max-idle-time-minutes <value>] [--egress-allow <value>... --egress
local] [--cors-origin <value>...] [--frame-ancestor <value>...] [--force] [--out-config-type env|dotenv]
[--public-link] [--json] [--non-interactive]
FLAGS
-p, --platform=<option>
@@ -3197,13 +3198,16 @@ FLAGS
Human-readable name for the simulator session, shown in eas simulator:list and on expo.dev. Defaults to unnamed.
--[no-]network-capture
Record HTTP(S) traffic from apps on the device (iOS only). HTTPS is decrypted, so recordings contain credentials in
cleartext and certificate-pinned apps fail to connect.
Capture HTTP(S) traffic from apps on the device for live inspection (iOS only). HTTPS is decrypted, so captured
traffic can contain credentials in cleartext and certificate-pinned apps fail to connect.
--network-capture-field=<value>...
What a recording may keep beyond method, URL, status, timing and size: header, query, request-body, response-body.
Repeatable or comma-separated. Defaults to none of them, because each can carry credentials.
--network-capture-recording
Save network capture as HAR artifacts for access after the session ends.
--non-interactive
Run the command in non-interactive mode.
@@ -3299,9 +3303,10 @@ USAGE
[--system-image <value>] [--build-id <value> | --build-fingerprint <value> | --application-archive-url <value> |
--expo-go] [--sdk-version <value>] [--launch-arg <value>...] [--open-url <value>] [--type
agent-device|appium|argent|web-preview-only] [--package-version <value>] [--log-source
emulator-output|device-logcat...] [--network-capture-field <value>... --network-capture] [--max-duration-minutes
<value>] [--max-idle-time-minutes <value>] [--egress-allow <value>... --egress local] [--cors-origin <value>...]
[--frame-ancestor <value>...] [--force] [--out-config-type env|dotenv] [--public-link] [--json] [--non-interactive]
emulator-output|device-logcat...] [--network-capture-recording --network-capture] [--network-capture-field
<value>... ] [--max-duration-minutes <value>] [--max-idle-time-minutes <value>] [--egress-allow <value>... --egress
local] [--cors-origin <value>...] [--frame-ancestor <value>...] [--force] [--out-config-type env|dotenv]
[--public-link] [--json] [--non-interactive]
FLAGS
-p, --platform=<option>
@@ -3385,13 +3390,16 @@ FLAGS
Human-readable name for the simulator session, shown in eas simulator:list and on expo.dev. Defaults to unnamed.
--[no-]network-capture
Record HTTP(S) traffic from apps on the device (iOS only). HTTPS is decrypted, so recordings contain credentials in
cleartext and certificate-pinned apps fail to connect.
Capture HTTP(S) traffic from apps on the device for live inspection (iOS only). HTTPS is decrypted, so captured
traffic can contain credentials in cleartext and certificate-pinned apps fail to connect.
--network-capture-field=<value>...
What a recording may keep beyond method, URL, status, timing and size: header, query, request-body, response-body.
Repeatable or comma-separated. Defaults to none of them, because each can carry credentials.
--network-capture-recording
Save network capture as HAR artifacts for access after the session ends.
--non-interactive
Run the command in non-interactive mode.
@@ -3775,9 +3783,10 @@ USAGE
[--system-image <value>] [--build-id <value> | --build-fingerprint <value> | --application-archive-url <value> |
--expo-go] [--sdk-version <value>] [--launch-arg <value>...] [--open-url <value>] [--type
agent-device|appium|argent|web-preview-only] [--package-version <value>] [--log-source
emulator-output|device-logcat...] [--network-capture-field <value>... --network-capture] [--max-duration-minutes
<value>] [--max-idle-time-minutes <value>] [--egress-allow <value>... --egress local] [--cors-origin <value>...]
[--frame-ancestor <value>...] [--force] [--out-config-type env|dotenv] [--public-link] [--json] [--non-interactive]
emulator-output|device-logcat...] [--network-capture-recording --network-capture] [--network-capture-field
<value>... ] [--max-duration-minutes <value>] [--max-idle-time-minutes <value>] [--egress-allow <value>... --egress
local] [--cors-origin <value>...] [--frame-ancestor <value>...] [--force] [--out-config-type env|dotenv]
[--public-link] [--json] [--non-interactive]
FLAGS
-p, --platform=<option>
@@ -3861,13 +3870,16 @@ FLAGS
Human-readable name for the simulator session, shown in eas simulator:list and on expo.dev. Defaults to unnamed.
--[no-]network-capture
Record HTTP(S) traffic from apps on the device (iOS only). HTTPS is decrypted, so recordings contain credentials in
cleartext and certificate-pinned apps fail to connect.
Capture HTTP(S) traffic from apps on the device for live inspection (iOS only). HTTPS is decrypted, so captured
traffic can contain credentials in cleartext and certificate-pinned apps fail to connect.
--network-capture-field=<value>...
What a recording may keep beyond method, URL, status, timing and size: header, query, request-body, response-body.
Repeatable or comma-separated. Defaults to none of them, because each can carry credentials.
--network-capture-recording
Save network capture as HAR artifacts for access after the session ends.
--non-interactive
Run the command in non-interactive mode.
+13 -1
View File
@@ -48154,7 +48154,7 @@
},
{
"name": "networkCapture",
"description": "Record HTTP(S) traffic from apps on the device for the whole session. iOS only.\nHTTPS is decrypted, so recordings contain credentials and cookies in cleartext.\nIf omitted, no traffic is recorded.",
"description": "Capture HTTP(S) traffic from apps on the device for live inspection. iOS only.\nHTTPS is decrypted, so captured traffic can contain credentials and cookies in cleartext.\nIf omitted, network capture is disabled.",
"type": {
"kind": "SCALAR",
"name": "Boolean",
@@ -48184,6 +48184,18 @@
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "networkCaptureRecording",
"description": "Record network capture as a HAR artifact for access after the session. Requires networkCapture.\nIf omitted, HAR artifact recording is disabled.",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "openUrl",
"description": "Expo or development-client URL to open after launching the installed application. Requires\nbuildId, applicationArchiveUrl, or expoGo.",
@@ -1761,6 +1761,48 @@ describe(Simulator, () => {
);
});
it('passes --network-capture-recording when requested', async () => {
const { command } = createCommand([
'--platform',
'ios',
'--non-interactive',
'--network-capture',
'--network-capture-recording',
]);
await command.runAsync();
expect(mockCreateDeviceRunSessionAsync).toHaveBeenCalledWith(
graphqlClient,
expect.objectContaining({ networkCapture: true, networkCaptureRecording: true })
);
});
it.each([false, true])('omits recording without the flag (capture: %s)', async capture => {
const { command } = createCommand([
'--platform',
'ios',
'--non-interactive',
...(capture ? ['--network-capture'] : []),
]);
await command.runAsync();
expect(mockCreateDeviceRunSessionAsync.mock.calls[0][1]).not.toHaveProperty(
'networkCaptureRecording'
);
});
it('rejects --network-capture-recording without --network-capture', async () => {
const { command } = createCommand([
'--platform',
'ios',
'--non-interactive',
'--network-capture-recording',
]);
await expect(command.runAsync()).rejects.toThrow(/network-capture/);
expect(mockCreateDeviceRunSessionAsync).not.toHaveBeenCalled();
});
it('passes the requested capture fields, splitting a comma-separated value', async () => {
const { command } = createCommand([
'--platform',
@@ -0,0 +1,492 @@
import { Config } from '@oclif/core';
import chalk from 'chalk';
import { stripVTControlCharacters } from 'node:util';
import { ExpoGraphqlClient } from '../../../commandUtils/context/contextUtils/createGraphqlClient';
import { DeviceRunSessionStatus } from '../../../graphql/generated';
import { DeviceRunSessionQuery } from '../../../graphql/queries/DeviceRunSessionQuery';
import { downloadSimulatorArtifactAsync } from '../../../simulator/artifacts';
import Log from '../../../log';
import { ora } from '../../../ora';
import { loadSimulatorEnvAsync } from '../../../simulator/env';
import {
downloadNetworkCaptureAsync,
readNetworkRequestsAsync,
streamNetworkRequestsAsync,
} from '../../../simulator/networkRequests';
import { resolveSimulatorPreviewAsync } from '../../../simulator/preview';
import { enableJsonOutput, printJsonOnlyOutput } from '../../../utils/json';
import SimulatorNetworkRequests from '../network-requests';
jest.mock('../../../log');
jest.mock('../../../graphql/queries/DeviceRunSessionQuery');
jest.mock('../../../simulator/artifacts', () => ({
...jest.requireActual('../../../simulator/artifacts'),
downloadSimulatorArtifactAsync: jest.fn(),
}));
jest.mock('../../../ora', () => ({
ora: jest.fn(() => {
const spinner = {
fail: jest.fn(),
start: jest.fn(),
succeed: jest.fn(),
};
spinner.start.mockReturnValue(spinner);
return spinner;
}),
}));
jest.mock('../../../simulator/env', () => ({
...jest.requireActual('../../../simulator/env'),
loadSimulatorEnvAsync: jest.fn(),
}));
jest.mock('../../../simulator/networkRequests');
jest.mock('../../../simulator/preview', () => ({
...jest.requireActual('../../../simulator/preview'),
resolveSimulatorPreviewAsync: jest.fn(),
}));
jest.mock('../../../utils/json');
const mockLoadSimulatorEnvAsync = jest.mocked(loadSimulatorEnvAsync);
const mockOra = jest.mocked(ora);
const mockResolvePreviewAsync = jest.mocked(resolveSimulatorPreviewAsync);
const mockReadRequestsAsync = jest.mocked(readNetworkRequestsAsync);
const mockDownloadCaptureAsync = jest.mocked(downloadNetworkCaptureAsync);
const mockStreamRequestsAsync = jest.mocked(streamNetworkRequestsAsync);
const mockEnableJsonOutput = jest.mocked(enableJsonOutput);
const mockPrintJsonOnlyOutput = jest.mocked(printJsonOnlyOutput);
const mockLog = jest.mocked(Log.log);
const originalColorLevel = chalk.level;
const graphqlClient = {} as ExpoGraphqlClient;
const projectDir = '/test/project';
const preview = {
deviceRunSessionId: 'session-id',
baseUrl: new URL('https://preview.test'),
token: 'preview-token',
};
const requestSummary = {
id: 'request-id',
startedAt: Date.parse('2026-10-05T12:00:00.000Z'),
startedDateTime: '2026-10-05T12:00:00.000Z',
method: 'POST',
url: 'https://example.test/posts',
status: 201,
duration: 50,
requestSize: 100,
responseSize: 200,
};
const request = {
_captureId: 'request-id',
startedDateTime: '2026-10-05T12:00:00.000Z',
time: 50,
request: {
method: 'POST',
url: 'https://example.test/posts',
bodySize: 100,
headers: [{ name: 'Content-Type', value: 'application/json' }],
postData: { mimeType: 'application/json', text: '{"title":"Coin Flip"}' },
},
response: {
status: 201,
bodySize: 200,
content: { mimeType: 'application/json', text: '{"id":101}' },
},
};
function getMockOclifConfig(): Config {
const config = new Config({ root: __dirname });
config.runHook = async () => ({ failures: [], successes: [] });
return config;
}
describe(SimulatorNetworkRequests, () => {
beforeEach(() => {
jest.clearAllMocks();
process.env.EAS_SIMULATOR_SESSION_ID = 'session-id';
chalk.level = 0;
mockLoadSimulatorEnvAsync.mockResolvedValue();
jest
.mocked(DeviceRunSessionQuery.byIdAsync)
.mockResolvedValue({ id: 'session-id', status: DeviceRunSessionStatus.InProgress } as Awaited<
ReturnType<typeof DeviceRunSessionQuery.byIdAsync>
>);
mockResolvePreviewAsync.mockResolvedValue(preview);
mockReadRequestsAsync.mockResolvedValue([]);
mockDownloadCaptureAsync.mockResolvedValue('/test/capture.har');
});
afterEach(() => {
delete process.env.EAS_SIMULATOR_SESSION_ID;
chalk.level = originalColorLevel;
});
it.each([DeviceRunSessionStatus.Stopped, DeviceRunSessionStatus.Errored])(
'downloads the capture for a %s session without preview',
async status => {
const session = { id: 'session-id', status } as Awaited<
ReturnType<typeof DeviceRunSessionQuery.byIdAsync>
>;
jest.mocked(DeviceRunSessionQuery.byIdAsync).mockResolvedValue(session);
await createCommand(['--artifact', '2', '--output', 'capture.har', '--json']).runAsync();
expect(downloadSimulatorArtifactAsync).toHaveBeenCalledWith(session, 'network-capture', {
artifact: 2,
output: 'capture.har',
nonInteractive: true,
json: true,
});
expect(mockResolvePreviewAsync).not.toHaveBeenCalled();
expect(DeviceRunSessionQuery.byIdAsync).toHaveBeenCalledTimes(1);
}
);
it.each([['--follow'], ['--request-id', 'r1']])(
'rejects live inspection of a stopped session %s',
async (...args) => {
jest
.mocked(DeviceRunSessionQuery.byIdAsync)
.mockResolvedValue({ id: 'session-id', status: DeviceRunSessionStatus.Stopped } as Awaited<
ReturnType<typeof DeviceRunSessionQuery.byIdAsync>
>);
await expect(createCommand(args).runAsync()).rejects.toThrow('Use --output <path>');
expect(mockResolvePreviewAsync).not.toHaveBeenCalled();
}
);
it('rejects artifact selection on a running session', async () => {
await expect(createCommand(['--artifact', '1']).runAsync()).rejects.toThrow(
'only available for stopped sessions'
);
expect(mockReadRequestsAsync).not.toHaveBeenCalled();
});
it('prints a JSON list for an explicit session with the default limit', async () => {
mockReadRequestsAsync.mockResolvedValue([requestSummary]);
await createCommand(['--id', 'session-id', '--json']).runAsync();
expect(mockEnableJsonOutput).toHaveBeenCalled();
expect(DeviceRunSessionQuery.byIdAsync).toHaveBeenCalledWith(graphqlClient, 'session-id');
expect(mockResolvePreviewAsync).toHaveBeenCalledWith(
expect.objectContaining({ id: 'session-id' })
);
expect(mockReadRequestsAsync).toHaveBeenCalledWith(preview, {
limit: 100,
requestId: undefined,
});
expect(mockPrintJsonOnlyOutput).toHaveBeenCalledWith({
deviceRunSessionId: 'session-id',
requests: [requestSummary],
});
expect(mockLog).not.toHaveBeenCalled();
expect(mockDownloadCaptureAsync).not.toHaveBeenCalled();
});
it('prints a full request detail including captured headers and bodies as JSON', async () => {
mockReadRequestsAsync.mockResolvedValue(request);
await createCommand(['--request-id', 'request-id', '--json']).runAsync();
expect(mockReadRequestsAsync).toHaveBeenCalledWith(preview, {
limit: 100,
requestId: 'request-id',
});
expect(mockPrintJsonOnlyOutput).toHaveBeenCalledWith({
deviceRunSessionId: 'session-id',
request,
});
expect(mockLog).not.toHaveBeenCalled();
});
it('downloads a HAR and prints only the resulting file metadata as JSON', async () => {
await createCommand(['--output', './capture.har', '--json']).runAsync();
expect(mockDownloadCaptureAsync).toHaveBeenCalledWith(preview, './capture.har');
expect(mockPrintJsonOnlyOutput).toHaveBeenCalledWith({
deviceRunSessionId: 'session-id',
filePath: '/test/capture.har',
});
expect(mockReadRequestsAsync).not.toHaveBeenCalled();
expect(mockLog).not.toHaveBeenCalled();
expect(mockOra).not.toHaveBeenCalled();
});
it('shows a spinner with the saved path for human output', async () => {
await createCommand(['-o', './capture.har']).runAsync();
const spinner = mockOra.mock.results[0].value;
expect(mockOra).toHaveBeenCalledWith('Saving network capture');
expect(spinner.succeed).toHaveBeenCalledWith('Saved network capture to /test/capture.har');
expect(mockPrintJsonOnlyOutput).not.toHaveBeenCalled();
expect(mockReadRequestsAsync).not.toHaveBeenCalled();
});
it('forwards an explicit limit and uses the dotenv session ID', async () => {
mockReadRequestsAsync.mockResolvedValue([requestSummary]);
mockLoadSimulatorEnvAsync.mockImplementation(async () => {
process.env.EAS_SIMULATOR_SESSION_ID = 'dotenv-id';
});
await createCommand(['--limit', '3']).runAsync();
expect(mockLoadSimulatorEnvAsync).toHaveBeenCalledWith(projectDir);
expect(DeviceRunSessionQuery.byIdAsync).toHaveBeenCalledWith(graphqlClient, 'dotenv-id');
expect(mockReadRequestsAsync).toHaveBeenCalledWith(preview, { limit: 3, requestId: undefined });
expect(mockLog).toHaveBeenCalledWith(
'request-id POST https://example.test/posts 201 50ms'
);
});
it('sanitizes terminal controls in human request summaries', async () => {
mockReadRequestsAsync.mockResolvedValue([
{ ...requestSummary, url: '\u001b[31mhttps://example.test/posts\u001b[0m\u0007' },
]);
await createCommand([]).runAsync();
expect(mockLog).toHaveBeenCalledWith(
'request-id POST https://example.test/posts 201 50ms'
);
});
it('rounds floating-point HAR timing noise only in human summaries', async () => {
const summary = { ...requestSummary, duration: 2.8999999999999995 };
mockReadRequestsAsync.mockResolvedValue([summary]);
await createCommand([]).runAsync();
expect(mockLog).toHaveBeenCalledWith(
'request-id POST https://example.test/posts 201 2.9ms'
);
await createCommand(['--json']).runAsync();
expect(mockPrintJsonOnlyOutput).toHaveBeenCalledWith({
deviceRunSessionId: 'session-id',
requests: [summary],
});
});
it('adds intentional colors after sanitizing remote text and preserves full URLs', async () => {
chalk.level = 1;
const url = `https://example.test/${'long-path/'.repeat(30)}`;
mockReadRequestsAsync.mockResolvedValue([
{
...requestSummary,
id: '\u001b[35mr1\u001b[0m\u0007',
startedDateTime: '\u001b[35m2026-10-05T12:00:00.000Z\u001b[0m\u0007',
method: '\u001b[35mGET\u001b[0m\u0007',
url: `\u001b[35m${url}\u001b[0m\u0007`,
},
]);
await createCommand(['--timestamp']).runAsync();
const output = mockLog.mock.calls[0][0] as string;
expect(output).toBe(
[
chalk.dim('2026-10-05T12:00:00.000Z'),
chalk.dim('r1 '),
chalk.bold.cyan('GET '),
url,
chalk.green('201'),
chalk.dim('50ms'),
].join(' ')
);
expect(output).toContain('\u001b[1m\u001b[36mGET ');
expect(output).not.toContain('\u001b[35m');
expect(output).not.toContain('\u0007');
expect(stripVTControlCharacters(output)).toBe(
`2026-10-05T12:00:00.000Z r1 GET ${url} 201 50ms`
);
});
it.each([
[200, '\u001b[32m'],
[299, '\u001b[32m'],
[301, '\u001b[36m'],
[399, '\u001b[36m'],
[404, '\u001b[33m'],
[499, '\u001b[33m'],
[500, '\u001b[31m'],
[599, '\u001b[31m'],
[0, '\u001b[31m'],
])('colors numeric status %i by response class', async (status, color) => {
chalk.level = 1;
mockReadRequestsAsync.mockResolvedValue([{ ...requestSummary, status }]);
await createCommand([]).runAsync();
expect(mockLog.mock.calls[0][0]).toContain(`${color}${status}\u001b[39m`);
});
it('leaves JSON data untouched when terminal color is enabled', async () => {
chalk.level = 1;
mockReadRequestsAsync.mockResolvedValue([requestSummary]);
await createCommand(['--json']).runAsync();
expect(mockPrintJsonOnlyOutput).toHaveBeenCalledWith({
deviceRunSessionId: 'session-id',
requests: [requestSummary],
});
expect(JSON.stringify(mockPrintJsonOnlyOutput.mock.calls[0][0])).not.toContain('\\u001b');
expect(mockLog).not.toHaveBeenCalled();
});
it('shows request start timestamps only when requested in human output', async () => {
mockReadRequestsAsync.mockResolvedValue([requestSummary]);
await createCommand(['--timestamp']).runAsync();
expect(mockLog).toHaveBeenCalledWith(
'2026-10-05T12:00:00.000Z request-id POST https://example.test/posts 201 50ms'
);
});
it.each(['--follow', '-f'])(
'streams human summaries with %s without fetching a finite list',
async follow => {
mockStreamRequestsAsync.mockImplementation(async (_preview, onRequest) => {
onRequest(requestSummary);
});
await createCommand([follow, '--timestamp']).runAsync();
expect(mockStreamRequestsAsync).toHaveBeenCalledWith(
preview,
expect.any(Function),
expect.any(AbortSignal)
);
expect(mockLog).toHaveBeenCalledWith(
'2026-10-05T12:00:00.000Z request-id POST https://example.test/posts 201 50ms'
);
expect(mockReadRequestsAsync).not.toHaveBeenCalled();
expect(mockDownloadCaptureAsync).not.toHaveBeenCalled();
expect(mockPrintJsonOnlyOutput).not.toHaveBeenCalled();
}
);
it('stops following on Ctrl+C and removes its interrupt handler', async () => {
const listeners = process.listeners('SIGINT');
let signal: AbortSignal | undefined;
mockStreamRequestsAsync.mockImplementation(async (_preview, _onRequest, followSignal) => {
signal = followSignal;
process.emit('SIGINT');
});
await createCommand(['--follow']).runAsync();
expect(signal?.aborted).toBe(true);
expect(process.listeners('SIGINT')).toEqual(listeners);
});
it.each([
{ options: ['--json'] },
{ options: ['--limit', '1'] },
{ options: ['--request-id', 'r1'] },
{ options: ['--output', 'capture.har'] },
])('rejects incompatible follow options $options before session access', async ({ options }) => {
await expect(createCommand(['--follow', ...options]).runAsync()).rejects.toThrow();
expect(mockResolvePreviewAsync).not.toHaveBeenCalled();
expect(mockStreamRequestsAsync).not.toHaveBeenCalled();
});
it('enables JSON output before rejecting JSON follow output', async () => {
await expect(createCommand(['--json', '--follow']).runAsync()).rejects.toThrow(
'Use either --json or --follow, not both.'
);
expect(mockEnableJsonOutput).toHaveBeenCalled();
expect(mockLoadSimulatorEnvAsync).not.toHaveBeenCalled();
});
it('prints a full request detail for human output', async () => {
mockReadRequestsAsync.mockResolvedValue(request);
await createCommand(['--request-id', 'request-id']).runAsync();
expect(mockLog).toHaveBeenCalledWith(JSON.stringify(request, null, 2));
expect(mockPrintJsonOnlyOutput).not.toHaveBeenCalled();
});
it('explains the initial-launch limitation when the capture is empty', async () => {
await createCommand([]).runAsync();
expect(mockLog).toHaveBeenCalledWith(
'No completed network requests were captured. Initial-launch requests may have been missed.'
);
});
it('rejects combining a request detail and HAR output before resolving a session', async () => {
await expect(
createCommand(['--request-id', 'request-id', '--output', './capture.har']).runAsync()
).rejects.toThrow();
expect(mockResolvePreviewAsync).not.toHaveBeenCalled();
expect(mockReadRequestsAsync).not.toHaveBeenCalled();
expect(mockDownloadCaptureAsync).not.toHaveBeenCalled();
});
it('rejects a nonpositive request limit', async () => {
await expect(createCommand(['--limit', '0']).runAsync()).rejects.toThrow();
expect(mockResolvePreviewAsync).not.toHaveBeenCalled();
});
it('propagates a missing capture error without printing an empty list', async () => {
mockReadRequestsAsync.mockRejectedValue(
new Error('No network capture was found. Start the session with --network-capture.')
);
await expect(createCommand([]).runAsync()).rejects.toThrow(
'Start the session with --network-capture.'
);
expect(mockLog).not.toHaveBeenCalled();
expect(mockPrintJsonOnlyOutput).not.toHaveBeenCalled();
});
it('propagates HAR download failures without claiming a file was saved', async () => {
mockDownloadCaptureAsync.mockRejectedValue(new Error('The output file already exists.'));
await expect(createCommand(['--output', './capture.har', '--json']).runAsync()).rejects.toThrow(
'The output file already exists.'
);
expect(mockPrintJsonOnlyOutput).not.toHaveBeenCalled();
expect(mockLog).not.toHaveBeenCalled();
expect(mockReadRequestsAsync).not.toHaveBeenCalled();
});
it('fails the spinner when the HAR download fails', async () => {
mockDownloadCaptureAsync.mockRejectedValue(new Error('The output file already exists.'));
await expect(createCommand(['--output', './capture.har']).runAsync()).rejects.toThrow(
'The output file already exists.'
);
const spinner = mockOra.mock.results[0].value;
expect(spinner.fail).toHaveBeenCalledWith('Failed to save network capture');
expect(spinner.succeed).not.toHaveBeenCalled();
});
it('stops before reading traffic when there is no simulator session', async () => {
delete process.env.EAS_SIMULATOR_SESSION_ID;
await expect(createCommand([]).runAsync()).rejects.toThrow('No simulator session ID provided.');
expect(mockResolvePreviewAsync).not.toHaveBeenCalled();
expect(mockReadRequestsAsync).not.toHaveBeenCalled();
expect(mockDownloadCaptureAsync).not.toHaveBeenCalled();
});
});
function createCommand(args: string[]): SimulatorNetworkRequests {
const command = new SimulatorNetworkRequests(args, getMockOclifConfig());
// @ts-expect-error getContextAsync is protected
jest.spyOn(command, 'getContextAsync').mockResolvedValue({
loggedIn: { graphqlClient },
projectDir,
});
return command;
}
@@ -198,7 +198,11 @@ With local egress, actions wait for the connection and require interactive mode.
'network-capture': Flags.boolean({
allowNo: true,
description:
'Record HTTP(S) traffic from apps on the device (iOS only). HTTPS is decrypted, so recordings contain credentials in cleartext and certificate-pinned apps fail to connect.',
'Capture HTTP(S) traffic from apps on the device for live inspection (iOS only). HTTPS is decrypted, so captured traffic can contain credentials in cleartext and certificate-pinned apps fail to connect.',
}),
'network-capture-recording': Flags.boolean({
description: 'Save network capture as HAR artifacts for access after the session ends.',
dependsOn: ['network-capture'],
}),
'network-capture-field': Flags.string({
description:
@@ -459,6 +463,7 @@ With local egress, actions wait for the connection and require interactive mode.
publicPreview: flags['public-link'] ?? false,
packageVersion: flags['package-version'],
networkCapture: flags['network-capture'],
...(flags['network-capture-recording'] ? { networkCaptureRecording: true } : {}),
...(networkCaptureFields.length ? { networkCaptureFields } : {}),
...platformInput,
...(buildId ? { buildId } : {}),
@@ -509,7 +514,7 @@ With local egress, actions wait for the connection and require interactive mode.
);
if (flags['network-capture']) {
Log.warn(
'Network capture was requested. HTTPS is decrypted, so recordings contain credentials in cleartext. Relaunch an installed app to record its traffic.'
'Network capture was requested. HTTPS is decrypted, so captured traffic can contain credentials in cleartext. Relaunch an installed app to capture its traffic.'
);
}
} catch (err) {
@@ -0,0 +1,216 @@
import { Flags } from '@oclif/core';
import chalk from 'chalk';
import EasCommand from '../../commandUtils/EasCommand';
import {
EasNonInteractiveAndJsonFlags,
resolveNonInteractiveAndJsonFlags,
} from '../../commandUtils/flags';
import { DeviceRunSessionQuery } from '../../graphql/queries/DeviceRunSessionQuery';
import Log from '../../log';
import { downloadSimulatorArtifactAsync, hasSimulatorArtifacts } from '../../simulator/artifacts';
import {
getSimulatorCommandAliases,
getSimulatorCommandHiddenAliases,
} from '../../simulator/commandAliases';
import { ora } from '../../ora';
import {
EAS_SIMULATOR_SESSION_ID,
SIMULATOR_DOTENV_FILE_NAME,
loadSimulatorEnvAsync,
} from '../../simulator/env';
import {
type NetworkRequestSummary,
downloadNetworkCaptureAsync,
readNetworkRequestsAsync,
streamNetworkRequestsAsync,
} from '../../simulator/networkRequests';
import { resolveSimulatorPreviewAsync } from '../../simulator/preview';
import { stripTerminalControlCharacters } from '../../simulator/utils';
import { enableJsonOutput, printJsonOnlyOutput } from '../../utils/json';
export default class SimulatorNetworkRequests extends EasCommand {
static override aliases = getSimulatorCommandAliases('network-requests');
static override hiddenAliases = getSimulatorCommandHiddenAliases('network-requests');
static override description =
'[EXPERIMENTAL] inspect completed network requests from a capture-enabled simulator session';
static override examples = [
'<%= config.bin %> simulator:network-requests --json',
'<%= config.bin %> simulator:network-requests --follow --timestamp',
'<%= config.bin %> simulator:network-requests --request-id r1 --json',
'<%= config.bin %> simulator:network-requests --output capture.har',
];
static override flags = {
id: Flags.string({
description: `Simulator session ID. Defaults to ${SIMULATOR_DOTENV_FILE_NAME}.`,
}),
artifact: Flags.integer({
min: 1,
description: 'Artifact index to download from a stopped session (1-based).',
}),
'request-id': Flags.string({
description:
'Show a captured request, including the headers and bodies selected for capture.',
exclusive: ['output'],
}),
output: Flags.string({
char: 'o',
description: 'Save the live HAR or a stopped session capture artifact to this path.',
exclusive: ['request-id'],
}),
follow: Flags.boolean({
char: 'f',
description: 'Stream completed requests, including those retained by the current capture.',
exclusive: ['request-id', 'output', 'limit'],
}),
limit: Flags.integer({
description: 'Maximum number of recent live requests to list without --follow.',
default: 100,
min: 1,
}),
timestamp: Flags.boolean({
description: 'Show request start timestamps in live human-readable lists.',
}),
...EasNonInteractiveAndJsonFlags,
};
static override contextDefinition = {
...this.ContextOptions.LoggedIn,
...this.ContextOptions.ProjectDir,
};
async runAsync(): Promise<void> {
// Before parsing, so only the JSON result reaches stdout.
if (this.argv.includes('--json')) {
enableJsonOutput();
}
const { flags } = await this.parse(SimulatorNetworkRequests);
const { json: jsonFlag, nonInteractive } = resolveNonInteractiveAndJsonFlags(flags);
if (jsonFlag && flags.follow) {
throw new Error('Use either --json or --follow, not both.');
}
const {
projectDir,
loggedIn: { graphqlClient },
} = await this.getContextAsync(SimulatorNetworkRequests, { nonInteractive });
await loadSimulatorEnvAsync(projectDir);
const deviceRunSessionId = flags.id ?? process.env[EAS_SIMULATOR_SESSION_ID];
if (!deviceRunSessionId) {
throw new Error(
`No simulator session ID provided. Pass --id, or run \`eas simulator:start\` first to write ${SIMULATOR_DOTENV_FILE_NAME}.`
);
}
const session = await DeviceRunSessionQuery.byIdAsync(graphqlClient, deviceRunSessionId);
if (hasSimulatorArtifacts(session)) {
if (flags.follow || flags['request-id']) {
throw new Error(
'The session has stopped. --follow and --request-id are only available while it runs. Use --output <path> to download its capture artifact.'
);
}
await downloadSimulatorArtifactAsync(session, 'network-capture', {
artifact: flags.artifact,
output: flags.output,
nonInteractive,
json: jsonFlag,
});
return;
}
const preview = await resolveSimulatorPreviewAsync(session);
if (flags.artifact !== undefined) {
throw new Error(
'--artifact is only available for stopped sessions. Use --output <path> to save the live HAR.'
);
}
if (flags.follow) {
const abortController = new AbortController();
const interruptHandler = (): void => {
if (abortController.signal.aborted) {
process.exit(130);
}
abortController.abort();
};
process.on('SIGINT', interruptHandler);
try {
await streamNetworkRequestsAsync(
preview,
request => {
Log.log(formatRequestSummary(request, flags.timestamp));
},
abortController.signal
);
} finally {
process.removeListener('SIGINT', interruptHandler);
}
return;
}
if (flags.output) {
const downloadSpinner = jsonFlag ? null : ora('Saving network capture').start();
let filePath: string;
try {
filePath = await downloadNetworkCaptureAsync(preview, flags.output);
downloadSpinner?.succeed(`Saved network capture to ${filePath}`);
} catch (err) {
downloadSpinner?.fail('Failed to save network capture');
throw err;
}
if (jsonFlag) {
printJsonOnlyOutput({ deviceRunSessionId: preview.deviceRunSessionId, filePath });
}
return;
}
const result = await readNetworkRequestsAsync(preview, {
limit: flags.limit,
requestId: flags['request-id'],
});
if (jsonFlag) {
printJsonOnlyOutput({
deviceRunSessionId: preview.deviceRunSessionId,
...(Array.isArray(result) ? { requests: result } : { request: result }),
});
} else if (!Array.isArray(result)) {
Log.log(
stripTerminalControlCharacters(JSON.stringify(result, null, 2), {
keepNewlinesAndTabs: true,
})
);
} else if (result.length === 0) {
Log.log(
'No completed network requests were captured. Initial-launch requests may have been missed.'
);
} else {
for (const request of result) {
Log.log(formatRequestSummary(request, flags.timestamp));
}
}
}
}
function formatRequestSummary(request: NetworkRequestSummary, timestamp = false): string {
let status = String(request.status);
if (request.status === 0 || request.status >= 500) {
status = chalk.red(status);
} else if (request.status >= 400) {
status = chalk.yellow(status);
} else if (request.status >= 300) {
status = chalk.cyan(status);
} else if (request.status >= 200) {
status = chalk.green(status);
}
const fields = [
chalk.dim(stripTerminalControlCharacters(request.id ?? '-').padEnd(5)),
chalk.bold.cyan(stripTerminalControlCharacters(request.method).padEnd(6)),
stripTerminalControlCharacters(request.url),
status,
chalk.dim(`${Math.round(request.duration * 10) / 10}ms`),
];
if (timestamp) {
fields.unshift(chalk.dim(stripTerminalControlCharacters(request.startedDateTime)));
}
return fields.join(' ');
}
+8 -3
View File
@@ -6805,9 +6805,9 @@ export type CreateDeviceRunSessionInput = {
*/
name?: InputMaybe<Scalars['String']['input']>;
/**
* Record HTTP(S) traffic from apps on the device for the whole session. iOS only.
* HTTPS is decrypted, so recordings contain credentials and cookies in cleartext.
* If omitted, no traffic is recorded.
* Capture HTTP(S) traffic from apps on the device for live inspection. iOS only.
* HTTPS is decrypted, so captured traffic can contain credentials and cookies in cleartext.
* If omitted, network capture is disabled.
*/
networkCapture?: InputMaybe<Scalars['Boolean']['input']>;
/**
@@ -6816,6 +6816,11 @@ export type CreateDeviceRunSessionInput = {
* it is asked for. Requires networkCapture.
*/
networkCaptureFields?: InputMaybe<Array<Scalars['String']['input']>>;
/**
* Record network capture as a HAR artifact for access after the session. Requires networkCapture.
* If omitted, HAR artifact recording is disabled.
*/
networkCaptureRecording?: InputMaybe<Scalars['Boolean']['input']>;
/**
* Expo or development-client URL to open after launching the installed application. Requires
* buildId, applicationArchiveUrl, or expoGo.
@@ -8,6 +8,7 @@ import SimulatorGet from '../../commands/simulator/get';
import Simulator from '../../commands/simulator/index';
import SimulatorList from '../../commands/simulator/list';
import SimulatorLogs from '../../commands/simulator/logs';
import SimulatorNetworkRequests from '../../commands/simulator/network-requests';
import SimulatorStop from '../../commands/simulator/stop';
import { isSimulatorCommandId } from '../commandAliases';
@@ -22,6 +23,7 @@ describe('simulator command aliases', () => {
['get', SimulatorGet],
['list', SimulatorList],
['logs', SimulatorLogs],
['network-requests', SimulatorNetworkRequests],
['stop', SimulatorStop],
])('runs simulator:%s from every simulator topic alias', (name, command) => {
expect(command.aliases).toEqual([`sim:${name}`]);
@@ -0,0 +1,519 @@
import { mkdtemp, readFile, readdir, rm, stat, symlink, writeFile } from 'node:fs/promises';
import { createServer } from 'node:http';
import { type AddressInfo } from 'node:net';
import os from 'node:os';
import path from 'node:path';
import { Readable } from 'node:stream';
import { Response } from '../../fetch';
import {
type NetworkRequest,
type NetworkRequestSummary,
downloadNetworkCaptureAsync,
readNetworkRequestsAsync,
streamNetworkRequestsAsync,
} from '../networkRequests';
import { fetchSimulatorPreviewAsync, streamSimulatorPreviewAsync } from '../preview';
jest.mock('../preview', () => ({
...jest.requireActual('../preview'),
fetchSimulatorPreviewAsync: jest.fn(),
streamSimulatorPreviewAsync: jest.fn(),
}));
const NOT_ENABLED_MESSAGE =
'Network capture is not enabled for this session. Capture must be requested when the session starts. Start a new session with `eas simulator:start --network-capture`.';
const preview = {
deviceRunSessionId: 'session-id',
baseUrl: new URL('https://preview.test'),
token: 'secret',
};
const signal = new AbortController().signal;
let directory: string;
function entry(id: string): NetworkRequest {
return {
_captureId: id,
_captureStartedAt: 123.45,
startedDateTime: '2026-10-05T20:54:22.074Z',
time: 82,
request: { method: 'POST', url: 'https://example.test/posts', bodySize: 0, postData: null },
response: { status: 201, bodySize: 12, content: { text: '{"id":101}' } },
};
}
function reply(body: string | Readable): void {
jest
.mocked(fetchSimulatorPreviewAsync)
.mockResolvedValue(new Response(typeof body === 'string' ? Readable.from([body]) : body));
}
function rejectOnTimeout(): AbortController {
const controller = new AbortController();
jest.spyOn(AbortSignal, 'timeout').mockReturnValue(controller.signal);
jest.mocked(fetchSimulatorPreviewAsync).mockImplementation(
async (_preview, _route, options) =>
await new Promise<Response>((_resolve, reject) => {
if (options?.signal?.aborted) {
reject(new Error('secret remote URL'));
}
options?.signal?.addEventListener('abort', () => {
reject(new Error('secret remote URL'));
});
})
);
return controller;
}
function capturedRequest(
id: string,
startedAt = Date.parse(entry(id).startedDateTime)
): {
id: string;
startedAt: number;
method: string;
url: string;
status: number;
durationMs: number;
requestBytes: number;
responseBytes: number;
} {
return {
id,
startedAt,
method: 'POST',
url: 'https://example.test/posts',
status: 201,
durationMs: 82,
requestBytes: 0,
responseBytes: 12,
};
}
function streamEvents(events: unknown[]): void {
jest.mocked(streamSimulatorPreviewAsync).mockImplementation(async (_preview, _route, onData) => {
for (const event of events) {
onData(typeof event === 'string' ? event : JSON.stringify(event));
}
});
}
beforeEach(async () => {
jest.clearAllMocks();
directory = await mkdtemp(path.join(os.tmpdir(), 'eas-network-requests-test-'));
});
afterEach(async () => {
jest.restoreAllMocks();
await rm(directory, { recursive: true, force: true });
});
describe(readNetworkRequestsAsync, () => {
it('closes a real HTTP response immediately after a malformed capture frame', async () => {
let markClosed: () => void = () => {};
const closed = new Promise<void>(resolve => {
markClosed = resolve;
});
const server = createServer((_request, response) => {
response.writeHead(200, { 'content-type': 'application/x-ndjson' });
response.write('malformed-frame\n');
const timer = setInterval(() => response.write(' \n'), 10);
response.on('close', () => {
clearInterval(timer);
markClosed();
});
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
jest
.mocked(fetchSimulatorPreviewAsync)
.mockImplementationOnce(
jest.requireActual<typeof import('../preview')>('../preview').fetchSimulatorPreviewAsync
);
let timeout: NodeJS.Timeout | undefined;
try {
await expect(
readNetworkRequestsAsync(
{
...preview,
baseUrl: new URL(`http://127.0.0.1:${(server.address() as AddressInfo).port}`),
},
{ limit: 100 }
)
).rejects.toThrow('Could not read the network capture');
await Promise.race([
closed,
new Promise<void>((_resolve, reject) => {
timeout = setTimeout(() => {
reject(new Error('The capture connection stayed open.'));
}, 1000);
}),
]);
} finally {
clearTimeout(timeout);
server.closeAllConnections();
await new Promise<void>(resolve =>
server.close(() => {
resolve();
})
);
}
});
it('keeps recent summaries without retaining captured bodies, including a final line without a newline', async () => {
reply([entry('r1'), entry('r2'), entry('r3')].map(value => JSON.stringify(value)).join('\n'));
const requests = await readNetworkRequestsAsync(preview, { limit: 2 });
expect(fetchSimulatorPreviewAsync).toHaveBeenCalledWith(preview, '/network-capture.ndjson', {
signal: expect.any(AbortSignal),
notFoundMessage: NOT_ENABLED_MESSAGE,
});
expect(requests).toEqual(
['r2', 'r3'].map(id => ({
id,
startedAt: 123.45,
startedDateTime: '2026-10-05T20:54:22.074Z',
method: 'POST',
url: 'https://example.test/posts',
status: 201,
duration: 82,
requestSize: 0,
responseSize: 12,
}))
);
});
it('orders snapshots by start date and limits the latest starts rather than completions', async () => {
const entries = [
{ ...entry('r3'), startedDateTime: '2026-10-05T20:54:24.000Z', _captureStartedAt: 1 },
{ ...entry('r1'), startedDateTime: '2026-10-05T20:54:22.000Z', _captureStartedAt: 3 },
{ ...entry('r2'), startedDateTime: '2026-10-05T20:54:23.000Z', _captureStartedAt: 2 },
];
reply(entries.map(value => JSON.stringify(value)).join('\n'));
expect(await readNetworkRequestsAsync(preview, { limit: 2 })).toEqual([
expect.objectContaining({ id: 'r2' }),
expect.objectContaining({ id: 'r3' }),
]);
reply(entries.map(value => JSON.stringify(value)).join('\n'));
expect(await readNetworkRequestsAsync(preview, { limit: 1 })).toEqual([
expect.objectContaining({ id: 'r3' }),
]);
});
it('uses fractional start times and numeric request IDs to order equal start dates', async () => {
const entries = [
{ ...entry('r10'), _captureStartedAt: 123.45 },
{ ...entry('r3'), _captureStartedAt: 123.5 },
{ ...entry('r2'), _captureStartedAt: 123.45 },
];
reply(entries.map(value => JSON.stringify(value)).join('\n'));
expect(await readNetworkRequestsAsync(preview, { limit: 2 })).toEqual([
expect.objectContaining({ id: 'r10' }),
expect.objectContaining({ id: 'r3' }),
]);
});
it('returns selected captured headers and bodies without depending on the live request buffer', async () => {
const request = entry('r1');
reply(JSON.stringify(request));
expect(await readNetworkRequestsAsync(preview, { limit: 100, requestId: 'r1' })).toEqual(
request
);
});
it('handles UTF-8 split across chunks', async () => {
const bytes = Buffer.from(
JSON.stringify({
...entry('r1'),
request: { ...entry('r1').request, url: 'https://example.test/é' },
})
);
const split = bytes.indexOf(Buffer.from('é')) + 1;
reply(Readable.from([bytes.subarray(0, split), bytes.subarray(split)]));
const result = await readNetworkRequestsAsync(preview, { limit: 1 });
expect(result).toEqual([expect.objectContaining({ url: 'https://example.test/é' })]);
});
it('returns an empty list for an empty capture and reports a missing request', async () => {
reply('');
expect(await readNetworkRequestsAsync(preview, { limit: 100 })).toEqual([]);
reply('');
await expect(
readNetworkRequestsAsync(preview, { limit: 100, requestId: 'r1' })
).rejects.toThrow('not found');
});
it.each([
'secret-body',
'{"startedDateTime":"secret-body"}',
JSON.stringify({ ...entry('r1'), startedDateTime: 'secret-body' }),
])('reports malformed data without echoing decrypted traffic %#', async data => {
reply(data);
const error = readNetworkRequestsAsync(preview, { limit: 100 });
await expect(error).rejects.toThrow('Could not read the network capture.');
await expect(error).rejects.not.toThrow('secret-body');
});
it('reports a capture deadline', async () => {
const controller = rejectOnTimeout();
const pending = readNetworkRequestsAsync(preview, { limit: 100 });
const rejected = expect(pending).rejects.toThrow('The network capture request timed out.');
controller.abort();
await rejected;
expect(AbortSignal.timeout).toHaveBeenCalledWith(10 * 60_000);
});
it('retains useful request failures', async () => {
jest
.mocked(fetchSimulatorPreviewAsync)
.mockRejectedValue(new Error('Preview API access was refused.'));
await expect(readNetworkRequestsAsync(preview, { limit: 100 })).rejects.toThrow(
'Preview API access was refused.'
);
});
});
describe(streamNetworkRequestsAsync, () => {
it('follows retained completed requests and emits live completions immediately', async () => {
const requests: NetworkRequestSummary[] = [];
jest
.mocked(streamSimulatorPreviewAsync)
.mockImplementation(async (_preview, _route, onData) => {
onData(JSON.stringify({ type: 'meta', meta: { attachment: 'starting' }, initial: true }));
onData(JSON.stringify({ type: 'meta', meta: { attachment: 'capturing' } }));
onData(JSON.stringify({ type: 'finished', request: capturedRequest('r1', 1000) }));
onData(JSON.stringify({ type: 'finished', request: capturedRequest('r2', 2000) }));
onData(JSON.stringify({ type: 'started', request: capturedRequest('r3', 3000) }));
onData(JSON.stringify({ type: 'finished', request: capturedRequest('r4', 4000) }));
expect(requests.map(request => request.id)).toEqual(['r1', 'r2', 'r4']);
onData(
JSON.stringify({
type: 'finished',
request: { ...capturedRequest('r3', 3000), status: null, durationMs: null },
})
);
});
await streamNetworkRequestsAsync(preview, request => requests.push(request), signal);
expect(streamSimulatorPreviewAsync).toHaveBeenCalledWith(
preview,
'/network-capture',
expect.any(Function),
{ signal, notFoundMessage: NOT_ENABLED_MESSAGE }
);
expect(fetchSimulatorPreviewAsync).not.toHaveBeenCalled();
expect(requests.map(request => request.id)).toEqual(['r1', 'r2', 'r4', 'r3']);
expect(requests[3]).toEqual({
id: 'r3',
startedAt: 3000,
startedDateTime: '1970-01-01T00:00:03.000Z',
method: 'POST',
url: 'https://example.test/posts',
status: 0,
duration: 0,
requestSize: 0,
responseSize: 12,
});
});
it('keeps following when capture restarts, request IDs are reused, or events are unknown', async () => {
streamEvents([
{ type: 'meta', meta: { attachment: 'capturing' }, initial: true },
{ type: 'session', udid: 'SIM-A' },
{ type: 'finished', request: capturedRequest('r1', 1000) },
{ type: 'cleared' },
{ type: 'meta', meta: { attachment: 'starting' } },
{ type: 'started', request: capturedRequest('r1', 2000) },
{ type: 'finished', request: capturedRequest('r1', 2000) },
{ type: 'evicted', id: 'r1' },
{ type: 'finished', request: capturedRequest('r2', 3000) },
]);
const requests: NetworkRequestSummary[] = [];
await streamNetworkRequestsAsync(preview, request => requests.push(request), signal);
expect(requests.map(request => request.startedAt)).toEqual([1000, 2000, 3000]);
});
it.each([
['not-enabled', NOT_ENABLED_MESSAGE],
[
'failed',
'The network capture failed. The session reported a capture error. Open the session preview to see the error, or start a new session with `eas simulator:start --network-capture`.',
],
])(
'reports the %s capture state without exposing attachment errors',
async (attachment, message) => {
streamEvents([
{ type: 'meta', meta: { attachment, attachError: 'secret remote URL' }, initial: true },
]);
await expect(streamNetworkRequestsAsync(preview, jest.fn(), signal)).rejects.toEqual(
new Error(message)
);
}
);
it('stops on capture failure after emitting earlier completed requests', async () => {
streamEvents([
{ type: 'meta', meta: { attachment: 'capturing' } },
{ type: 'finished', request: capturedRequest('r1') },
{ type: 'meta', meta: { attachment: 'failed' } },
{ type: 'finished', request: capturedRequest('r2') },
]);
const onRequest = jest.fn();
await expect(streamNetworkRequestsAsync(preview, onRequest, signal)).rejects.toThrow(
'The network capture failed.'
);
expect(onRequest).toHaveBeenCalledTimes(1);
});
it('explains when capture is turned off after following has started', async () => {
streamEvents([
{ type: 'meta', meta: { attachment: 'capturing' }, initial: true },
{ type: 'finished', request: capturedRequest('r1', 1000) },
{ type: 'meta', meta: { attachment: 'not-enabled' } },
]);
const onRequest = jest.fn();
await expect(streamNetworkRequestsAsync(preview, onRequest, signal)).rejects.toThrow(
'Network capture was turned off,'
);
expect(onRequest).toHaveBeenCalledTimes(1);
});
it.each(['secret-body', '{"type":"finished","request":{"url":"secret-body"}}'])(
'reports malformed stream data without echoing decrypted traffic %#',
async data => {
streamEvents([data]);
const error = streamNetworkRequestsAsync(preview, jest.fn(), signal);
await expect(error).rejects.toThrow('Could not read the network capture stream.');
await expect(error).rejects.not.toThrow('secret-body');
}
);
it('preserves useful stream setup errors and returns after a clean shared interruption', async () => {
jest
.mocked(streamSimulatorPreviewAsync)
.mockRejectedValueOnce(new Error('The simulator preview is offline.'))
.mockResolvedValueOnce();
await expect(streamNetworkRequestsAsync(preview, jest.fn(), signal)).rejects.toThrow(
'The simulator preview is offline.'
);
await expect(streamNetworkRequestsAsync(preview, jest.fn(), signal)).resolves.toBeUndefined();
});
});
describe(downloadNetworkCaptureAsync, () => {
it('streams an exact HAR into a private file', async () => {
const data = JSON.stringify({ log: { entries: [entry('r1')] } });
reply(Readable.from([data.slice(0, 15), data.slice(15)]));
const output = path.join(directory, 'capture.har');
const oldUmask = process.umask(0);
try {
expect(await downloadNetworkCaptureAsync(preview, output)).toBe(output);
} finally {
process.umask(oldUmask);
}
expect(fetchSimulatorPreviewAsync).toHaveBeenCalledWith(preview, '/network-capture.har', {
signal: expect.any(AbortSignal),
notFoundMessage: NOT_ENABLED_MESSAGE,
});
expect(await readFile(output, 'utf8')).toBe(data);
expect((await stat(output)).mode & 0o777).toBe(0o600);
expect(await readdir(directory)).toEqual(['capture.har']);
});
it('refuses an existing file before requesting the capture', async () => {
const output = path.join(directory, 'capture.har');
await writeFile(output, 'keep');
reply('new capture');
await expect(downloadNetworkCaptureAsync(preview, output)).rejects.toThrow('already exists');
expect(fetchSimulatorPreviewAsync).not.toHaveBeenCalled();
expect(await readFile(output, 'utf8')).toBe('keep');
});
it('does not overwrite a file created during the download', async () => {
const output = path.join(directory, 'capture.har');
jest.mocked(fetchSimulatorPreviewAsync).mockImplementation(async () => {
await writeFile(output, 'created concurrently');
return new Response(Readable.from(['new capture']));
});
await expect(downloadNetworkCaptureAsync(preview, output)).rejects.toThrow('already exists');
expect(await readFile(output, 'utf8')).toBe('created concurrently');
expect(await readdir(directory)).toEqual(['capture.har']);
});
it('keeps a file created during a download whose body fails before the file opens', async () => {
const output = path.join(directory, 'capture.har');
jest.mocked(fetchSimulatorPreviewAsync).mockImplementation(async () => {
await writeFile(output, 'created concurrently');
const body = new Readable({ read() {} });
body.destroy(new Error('secret remote URL'));
return new Response(body);
});
await expect(downloadNetworkCaptureAsync(preview, output)).rejects.toThrow();
expect(await readFile(output, 'utf8')).toBe('created concurrently');
});
it('refuses to write through a dangling symlink', async () => {
const output = path.join(directory, 'capture.har');
await symlink(path.join(directory, 'missing-target'), output);
reply('new capture');
await expect(downloadNetworkCaptureAsync(preview, output)).rejects.toThrow('already exists');
expect(await readdir(directory)).toEqual(['capture.har']);
});
it('explains a missing output directory', async () => {
reply('capture');
await expect(
downloadNetworkCaptureAsync(preview, path.join(directory, 'missing', 'capture.har'))
).rejects.toThrow('Check that the --output directory exists and is writable,');
expect(await readdir(directory)).toEqual([]);
});
it('retains useful request errors without creating a file', async () => {
jest
.mocked(fetchSimulatorPreviewAsync)
.mockRejectedValue(new Error('Start the session with --network-capture.'));
await expect(
downloadNetworkCaptureAsync(preview, path.join(directory, 'capture.har'))
).rejects.toThrow('--network-capture');
expect(await readdir(directory)).toEqual([]);
});
it('removes the partial file after a failed transfer', async () => {
reply(
Readable.from(
(async function* () {
yield 'partial';
throw new Error('secret remote URL');
})()
)
);
const error = downloadNetworkCaptureAsync(preview, path.join(directory, 'capture.har'));
await expect(error).rejects.toThrow('Could not save the download.');
await expect(error).rejects.not.toThrow('secret');
expect(await readdir(directory)).toEqual([]);
});
it('reports a download deadline', async () => {
const controller = rejectOnTimeout();
const pending = downloadNetworkCaptureAsync(preview, path.join(directory, 'capture.har'));
const rejected = expect(pending).rejects.toThrow('The download timed out.');
controller.abort();
await rejected;
expect(AbortSignal.timeout).toHaveBeenCalledWith(10 * 60_000);
expect(await readdir(directory)).toEqual([]);
});
});
@@ -65,12 +65,18 @@ describe('simulator start configuration', () => {
it('lets the CLI disable saved public links and network capture with its saved fields', async () => {
const { parsed } = await resolve(
{ 'public-link': true, 'network-capture': true, 'network-capture-field': ['header'] },
{
'public-link': true,
'network-capture': true,
'network-capture-field': ['header'],
'network-capture-recording': true,
},
['--no-public-link', '--no-network-capture']
);
expect(parsed.flags['public-link']).toBe(false);
expect(parsed.flags['network-capture']).toBe(false);
expect(parsed.flags['network-capture-field']).toBeUndefined();
expect(parsed.flags['network-capture-recording']).toBeUndefined();
});
it('validates dependencies after merging and replaces array flags instead of appending', async () => {
@@ -0,0 +1,211 @@
import readline from 'node:readline';
import { z } from 'zod';
import { downloadSimulatorFileAsync } from './download';
import {
type SimulatorPreview,
fetchSimulatorPreviewAsync,
streamSimulatorPreviewAsync,
} from './preview';
import { type Response } from '../fetch';
const NETWORK_CAPTURE_TIMEOUT_MS = 10 * 60_000;
const NETWORK_CAPTURE_NOT_ENABLED_MESSAGE =
'Network capture is not enabled for this session. Capture must be requested when the session starts. Start a new session with `eas simulator:start --network-capture`.';
const INVALID_NETWORK_CAPTURE_MESSAGE =
'Could not read the network capture. The capture data was incomplete or not in the expected format. Try again.';
const networkRequestSchema = z.looseObject({
_captureId: z.string().optional(),
_captureStartedAt: z.number().nullable().optional(),
startedDateTime: z.string().refine(value => Number.isFinite(Date.parse(value))),
time: z.number(),
request: z.looseObject({ method: z.string(), url: z.string(), bodySize: z.number() }),
response: z.looseObject({ status: z.number(), bodySize: z.number() }),
});
const networkCaptureEventSchema = z.union([
z.object({
type: z.literal('meta'),
initial: z.boolean().optional(),
meta: z.object({ attachment: z.string().optional() }),
}),
z.object({
type: z.literal('finished'),
request: z.object({
id: z.string(),
startedAt: z.number(),
method: z.string(),
url: z.string(),
status: z.number().nullable(),
durationMs: z.number().nullable(),
requestBytes: z.number(),
responseBytes: z.number(),
}),
}),
// Other events, such as `started` and `cleared`, have nothing to print.
z.object({ type: z.string().refine(type => type !== 'meta' && type !== 'finished') }),
]);
export type NetworkRequest = z.infer<typeof networkRequestSchema>;
export type NetworkRequestSummary = {
id: string | null;
startedAt: number | null;
startedDateTime: string;
method: string;
url: string;
status: number;
duration: number;
requestSize: number;
responseSize: number;
};
function parseJson(text: string): unknown {
try {
return JSON.parse(text);
} catch {
return undefined;
}
}
function compareRequestStarts(a: NetworkRequestSummary, b: NetworkRequestSummary): number {
return (
Date.parse(a.startedDateTime) - Date.parse(b.startedDateTime) ||
(a.startedAt ?? 0) - (b.startedAt ?? 0) ||
(a.id ?? '').localeCompare(b.id ?? '', undefined, { numeric: true })
);
}
export async function readNetworkRequestsAsync(
preview: SimulatorPreview,
{ limit, requestId }: { limit: number; requestId?: string }
): Promise<NetworkRequestSummary[] | NetworkRequest> {
const controller = new AbortController();
const signal = AbortSignal.any([
controller.signal,
AbortSignal.timeout(NETWORK_CAPTURE_TIMEOUT_MS),
]);
let response: Response | undefined;
let lines: readline.Interface | undefined;
const requests: NetworkRequestSummary[] = [];
let selected: NetworkRequest | undefined;
try {
response = await fetchSimulatorPreviewAsync(preview, '/network-capture.ndjson', {
signal,
notFoundMessage: NETWORK_CAPTURE_NOT_ENABLED_MESSAGE,
});
lines = readline.createInterface({ input: response.body, crlfDelay: Infinity });
for await (const line of lines) {
if (!line.trim()) {
continue;
}
const result = networkRequestSchema.safeParse(parseJson(line));
if (!result.success) {
throw new Error(INVALID_NETWORK_CAPTURE_MESSAGE);
}
const entry = result.data;
if (requestId) {
if (entry._captureId === requestId) {
selected = entry;
}
continue;
}
requests.push({
id: entry._captureId ?? null,
startedAt: entry._captureStartedAt ?? null,
startedDateTime: entry.startedDateTime,
method: entry.request.method,
url: entry.request.url,
status: entry.response.status,
duration: entry.time,
requestSize: entry.request.bodySize,
responseSize: entry.response.bodySize,
});
}
} catch (error) {
if (signal.aborted) {
throw new Error(
'The network capture request timed out. The capture did not download within 10 minutes. Run `eas simulator:get` to check that the session is still running, then try again.'
);
}
if (!response) {
throw error;
}
throw new Error(INVALID_NETWORK_CAPTURE_MESSAGE);
} finally {
lines?.close();
response?.body.once('error', () => {});
controller.abort();
}
if (!requestId) {
return requests.sort(compareRequestStarts).slice(-limit);
}
if (!selected) {
throw new Error(
'The request was not found in the network capture. The ID does not match a completed request in the current capture. Run `eas simulator:network-requests` to see current request IDs.'
);
}
return selected;
}
export async function streamNetworkRequestsAsync(
preview: SimulatorPreview,
onRequest: (request: NetworkRequestSummary) => void,
signal: AbortSignal
): Promise<void> {
await streamSimulatorPreviewAsync(
preview,
'/network-capture',
data => {
const result = networkCaptureEventSchema.safeParse(parseJson(data));
if (!result.success) {
throw new Error(
'Could not read the network capture stream. An event from the session was not in the expected format. Run the command again.'
);
}
const event = result.data;
if ('meta' in event) {
if (event.meta.attachment === 'not-enabled') {
throw new Error(
event.initial
? NETWORK_CAPTURE_NOT_ENABLED_MESSAGE
: 'Network capture was turned off, so the session no longer records requests. Start a new session with `eas simulator:start --network-capture` to capture again.'
);
}
if (event.meta.attachment === 'failed') {
throw new Error(
'The network capture failed. The session reported a capture error. Open the session preview to see the error, or start a new session with `eas simulator:start --network-capture`.'
);
}
} else if ('request' in event) {
const { request } = event;
onRequest({
id: request.id,
startedAt: request.startedAt,
startedDateTime: new Date(request.startedAt).toISOString(),
method: request.method,
url: request.url,
status: request.status ?? 0,
duration: Math.max(0, request.durationMs ?? 0),
requestSize: request.requestBytes,
responseSize: request.responseBytes,
});
}
},
{ signal, notFoundMessage: NETWORK_CAPTURE_NOT_ENABLED_MESSAGE }
);
}
export async function downloadNetworkCaptureAsync(
preview: SimulatorPreview,
output: string
): Promise<string> {
return await downloadSimulatorFileAsync(
output,
async signal =>
await fetchSimulatorPreviewAsync(preview, '/network-capture.har', {
signal,
notFoundMessage: NETWORK_CAPTURE_NOT_ENABLED_MESSAGE,
})
);
}
@@ -58,12 +58,12 @@ export async function resolveStartConfigAsync(
if (removed.has('expo-go') && !explicitNames.has('sdk-version')) {
delete values['sdk-version'];
}
if (
explicitNames.has('network-capture') &&
values['network-capture'] === false &&
!explicitNames.has('network-capture-field')
) {
delete values['network-capture-field'];
if (explicitNames.has('network-capture') && values['network-capture'] === false) {
for (const name of ['network-capture-field', 'network-capture-recording']) {
if (!explicitNames.has(name)) {
delete values[name];
}
}
}
const effectiveArgv: string[] = [];
for (const [name, value] of Object.entries(values)) {