mirror of
https://github.com/expo/eas-cli.git
synced 2026-11-15 17:31:46 -10:00
Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
49e716de0f | ||
|
|
42fc262d8d | ||
|
|
879a13990b | ||
|
|
6581bb7104 | ||
|
|
7e42b3867d | ||
|
|
5499d03b8f | ||
|
|
03c25a7a29 | ||
|
|
88edfb0729 | ||
|
|
5d8f23e666 | ||
|
|
f77cd548c3 | ||
|
|
0abcbb746d | ||
|
|
7fc29a9f18 | ||
|
|
0a39966a40 | ||
|
|
cf1d77160b |
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/build-tools': patch
|
||||
---
|
||||
|
||||
Explain missing background task identifiers reported by App Store Connect.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/build-tools': patch
|
||||
---
|
||||
|
||||
Explain App Store Connect NOT_AUTHORIZED responses in the shared API client.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/build-tools': patch
|
||||
---
|
||||
|
||||
Explain App Store Connect UNEXPECTED_ERROR responses in the shared API client.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/build-tools': patch
|
||||
---
|
||||
|
||||
Explain missing app icons reported by App Store Connect, including codes 90022 and 90023, while preserving Apple’s validation details.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/build-tools': minor
|
||||
---
|
||||
|
||||
Use single-device previews when the session already has a valid device ID.
|
||||
@@ -19,9 +19,7 @@
|
||||
"@expo/downloader",
|
||||
"@expo/turtle-spawn",
|
||||
"@expo/template-file",
|
||||
"create-eas-build-function",
|
||||
"@expo/vm-tools",
|
||||
"@expo/simulator-launcher"
|
||||
"create-eas-build-function"
|
||||
]
|
||||
],
|
||||
"linked": [],
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'eas-cli': minor
|
||||
---
|
||||
|
||||
Add an experiment that suggests Expo Update to coding agents after a build when the Free plan account is within 5 builds of the platform limit.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/build-tools': patch
|
||||
---
|
||||
|
||||
List failed Google Play commit attempts in order, including network failures, when the outcome is uncertain.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'eas-cli': minor
|
||||
---
|
||||
|
||||
Add `eas observe:traces` to list request trace spans (or a summary of span names and counts), `eas observe:trace` to display one trace as a span tree, and span rows in the `eas observe:session` timeline.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/worker': patch
|
||||
---
|
||||
|
||||
Run package-manager version queries in parallel during worker preparation.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/worker': patch
|
||||
---
|
||||
|
||||
Start the Xcode version check in the background during worker tool preparation. Apply the Xcode 26.0 upload workaround when the query finishes, without delaying job startup.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'eas-cli': patch
|
||||
---
|
||||
|
||||
Remove the Free plan build limit guidance experiment for coding agents from `eas build`.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'eas-cli': minor
|
||||
---
|
||||
|
||||
Import ordered action configurations with `eas simulator:control --import` and show progress for each action.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'eas-cli': minor
|
||||
---
|
||||
|
||||
Add searchable interactive simulator controls with session and device details, guided parameters, and action results.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'eas-cli': minor
|
||||
---
|
||||
|
||||
Start simulator sessions from saved settings and apply control actions after readiness.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/worker': patch
|
||||
---
|
||||
|
||||
Allow jobs to skip installing the CocoaPods cache proxy with EAS_BUILD_DISABLE_COCOAPODS_CACHE_PLUGIN=1.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/build-tools': patch
|
||||
---
|
||||
|
||||
Preserve indented and incomplete Xcode compiler errors in formatted build logs, including the final diagnostic when logging stops.
|
||||
@@ -2,52 +2,6 @@
|
||||
|
||||
This is the log of notable changes to EAS CLI and related packages.
|
||||
|
||||
## [27.3.0](https://github.com/expo/eas-cli/releases/tag/v27.3.0) - 2026-11-02
|
||||
|
||||
### 🎉 New features
|
||||
|
||||
- [eas-build-job] Add optional Observe error context to workflow jobs. ([#4787](https://github.com/expo/eas-cli/pull/4787) by [@AbbanMustafa](https://github.com/AbbanMustafa))
|
||||
|
||||
### 🐛 Bug fixes
|
||||
|
||||
- [eas-cli] Bump `@expo/apple-utils` to `2.3.0` to fix iOS capability sync when App Store Connect rejects enabling, disabling or changing a capability. ([#4790](https://github.com/expo/eas-cli/pull/4790) by [@douglowder](https://github.com/douglowder))
|
||||
- [eas-cli] Keep already linked App Groups, Merchant IDs and iCloud containers when capability sync links another identifier. ([#4584](https://github.com/expo/eas-cli/pull/4584) by [@ceydaakin](https://github.com/ceydaakin))
|
||||
- [worker] Mask secrets in every record the worker process writes to its stdout: the build log records and the worker's own records. ([#4782](https://github.com/expo/eas-cli/pull/4782) by [@hSATAC](https://github.com/hSATAC))
|
||||
- [worker][build-tools] Stop warmup in the background for jobs that do not use the warm Simulator, so job setup does not wait for it. Before build-tools boots or clones a Simulator, it waits until the launcher's state file records that cleanup finished, and fails if cleanup does not finish in time. ([#4721](https://github.com/expo/eas-cli/pull/4721) by [@gwdp](https://github.com/gwdp))
|
||||
- [build-tools] Recover unhealthy device-session tunnels without changing their URLs and block further traffic when shutdown starts, even if ngrok cleanup times out. ([#4526](https://github.com/expo/eas-cli/pull/4526) by [@gwdp](https://github.com/gwdp))
|
||||
- [build-tools] Stop sending the SSH host when registering an SSH session. ([#4784](https://github.com/expo/eas-cli/pull/4784) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
|
||||
|
||||
## [27.2.0](https://github.com/expo/eas-cli/releases/tag/v27.2.0) - 2026-10-29
|
||||
|
||||
### 🎉 New features
|
||||
|
||||
- [build-tools] Use single-device previews when the session already has a valid device ID. ([#4733](https://github.com/expo/eas-cli/pull/4733) by [@gwdp](https://github.com/gwdp))
|
||||
- [eas-cli] Add an experiment that suggests Expo Update to coding agents after a build when the Free plan account is within 5 builds of the platform limit. ([#4758](https://github.com/expo/eas-cli/pull/4758) by [@williamgrosset](https://github.com/williamgrosset))
|
||||
- [eas-cli] Add `eas observe:traces` to list request trace spans (or a summary of span names and counts), `eas observe:trace` to display one trace as a span tree, and span rows in the `eas observe:session` timeline. ([#4772](https://github.com/expo/eas-cli/pull/4772) by [@kadikraman](https://github.com/kadikraman))
|
||||
- [simulator-launcher] Accept a comma-separated list of warm Simulators in `EXPO_SIMULATOR_DEVICE`; the first is the default. One serve-sim serves every listed device on one port. After the default device is ready, warmup preinstalls the latest stable Expo Go from one download and tries to disable apsd on the other devices, until a job claims one. A claim can select any listed device and reports its preinstalled Expo Go. ([#4764](https://github.com/expo/eas-cli/pull/4764) by [@gwdp](https://github.com/gwdp))
|
||||
- [simulator-launcher] Add `@expo/simulator-launcher`, which warms an iOS Simulator at VM boot and hands it to one EAS job (`start`, `claim`, `prepare-tools`, `stop`). ([#4722](https://github.com/expo/eas-cli/pull/4722) by [@gwdp](https://github.com/gwdp))
|
||||
- [eas-cli] Show a one-time Expo Simulators hint after a successful build. ([#4768](https://github.com/expo/eas-cli/pull/4768) by [@FiberJW](https://github.com/FiberJW))
|
||||
- [vm-tools] Add a macOS startup script loader that runs `/usr/local/share/vm-tools/startup.sh` once per VM boot. ([#4725](https://github.com/expo/eas-cli/pull/4725) by [@gwdp](https://github.com/gwdp))
|
||||
|
||||
### 🐛 Bug fixes
|
||||
|
||||
- [build-tools] Explain missing background task identifiers reported by App Store Connect. ([#3465](https://github.com/expo/eas-cli/pull/3465) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
- [build-tools] Explain App Store Connect NOT_AUTHORIZED responses in the shared API client. ([#3462](https://github.com/expo/eas-cli/pull/3462) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
- [build-tools] Explain App Store Connect UNEXPECTED_ERROR responses in the shared API client. ([#3467](https://github.com/expo/eas-cli/pull/3467) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
- [build-tools] Explain missing app icons reported by App Store Connect, including codes 90022 and 90023, while preserving Apple’s validation details. ([#3466](https://github.com/expo/eas-cli/pull/3466) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
- [build-tools] List failed Google Play commit attempts in order, including network failures, when the outcome is uncertain. ([#4660](https://github.com/expo/eas-cli/pull/4660) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
- [worker] Run package-manager version queries in parallel during worker preparation. ([#4710](https://github.com/expo/eas-cli/pull/4710) by [@gwdp](https://github.com/gwdp))
|
||||
- [worker] Start the Xcode version check in the background during worker tool preparation. Apply the Xcode 26.0 upload workaround when the query finishes, without delaying job startup. ([#4707](https://github.com/expo/eas-cli/pull/4707) by [@gwdp](https://github.com/gwdp))
|
||||
- [build-tools] Fix a five-minute cleanup delay when a device session is canceled during startup and its screen recorder fails before connecting. ([#4761](https://github.com/expo/eas-cli/pull/4761) by [@gwdp](https://github.com/gwdp))
|
||||
- [eas-cli] Remove the Free plan build limit guidance experiment for coding agents from `eas build`. ([#4757](https://github.com/expo/eas-cli/pull/4757) by [@williamgrosset](https://github.com/williamgrosset))
|
||||
- [worker] Allow jobs to skip installing the CocoaPods cache proxy with EAS_BUILD_DISABLE_COCOAPODS_CACHE_PLUGIN=1. ([#4709](https://github.com/expo/eas-cli/pull/4709) by [@gwdp](https://github.com/gwdp))
|
||||
- [build-tools] Handle TURN requests for a stopped device session without reporting a warning. ([#4762](https://github.com/expo/eas-cli/pull/4762) by [@gwdp](https://github.com/gwdp))
|
||||
- [build-tools] Preserve indented and incomplete Xcode compiler errors in formatted build logs, including the final diagnostic when logging stops. ([#4365](https://github.com/expo/eas-cli/pull/4365) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
|
||||
### 🧹 Chores
|
||||
|
||||
- [simulator-launcher] Add the state, request command and service helpers for the warm Simulator launcher. The package stays private until #4722 adds its CLI entry point. ([#4766](https://github.com/expo/eas-cli/pull/4766) by [@gwdp](https://github.com/gwdp))
|
||||
|
||||
## [27.1.0](https://github.com/expo/eas-cli/releases/tag/v27.1.0) - 2026-10-28
|
||||
|
||||
### 🎉 New features
|
||||
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
{
|
||||
"STAGING": "27.2.0",
|
||||
"PRODUCTION": "27.2.0"
|
||||
"STAGING": "27.1.0",
|
||||
"PRODUCTION": "27.1.0"
|
||||
}
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"npmClient": "yarn",
|
||||
"version": "27.3.0",
|
||||
"version": "27.1.0",
|
||||
"$schema": "node_modules/lerna/schemas/lerna-schema.json"
|
||||
}
|
||||
@@ -1,30 +1,5 @@
|
||||
# @expo/build-tools
|
||||
|
||||
## 27.3.0
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Stop warmup in the background for jobs that do not use the warm Simulator, so job setup does not wait for it. Before build-tools boots or clones a Simulator, it waits until the launcher's state file records that cleanup finished, and fails if cleanup does not finish in time. ([#4721](https://github.com/expo/eas-cli/pull/4721) by [@gwdp](https://github.com/gwdp))
|
||||
- Recover unhealthy device-session tunnels without changing their URLs and block further traffic when shutdown starts, even if ngrok cleanup times out. ([#4526](https://github.com/expo/eas-cli/pull/4526) by [@gwdp](https://github.com/gwdp))
|
||||
- Stop sending the SSH host when registering an SSH session. ([#4784](https://github.com/expo/eas-cli/pull/4784) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
|
||||
|
||||
## 27.2.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- Use single-device previews when the session already has a valid device ID. ([#4733](https://github.com/expo/eas-cli/pull/4733) by [@gwdp](https://github.com/gwdp))
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Explain missing background task identifiers reported by App Store Connect. ([#3465](https://github.com/expo/eas-cli/pull/3465) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
- Explain App Store Connect NOT_AUTHORIZED responses in the shared API client. ([#3462](https://github.com/expo/eas-cli/pull/3462) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
- Explain App Store Connect UNEXPECTED_ERROR responses in the shared API client. ([#3467](https://github.com/expo/eas-cli/pull/3467) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
- Explain missing app icons reported by App Store Connect, including codes 90022 and 90023, while preserving Apple’s validation details. ([#3466](https://github.com/expo/eas-cli/pull/3466) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
- List failed Google Play commit attempts in order, including network failures, when the outcome is uncertain. ([#4660](https://github.com/expo/eas-cli/pull/4660) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
- Fix a five-minute cleanup delay when a device session is canceled during startup and its screen recorder fails before connecting. ([#4761](https://github.com/expo/eas-cli/pull/4761) by [@gwdp](https://github.com/gwdp))
|
||||
- Handle TURN requests for a stopped device session without reporting a warning. ([#4762](https://github.com/expo/eas-cli/pull/4762) by [@gwdp](https://github.com/gwdp))
|
||||
- Preserve indented and incomplete Xcode compiler errors in formatted build logs, including the final diagnostic when logging stops. ([#4365](https://github.com/expo/eas-cli/pull/4365) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
|
||||
## 27.1.0
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/build-tools",
|
||||
"version": "27.3.0",
|
||||
"version": "27.1.0",
|
||||
"bugs": "https://github.com/expo/eas-cli/issues",
|
||||
"license": "BUSL-1.1",
|
||||
"author": "Expo <[email protected]>",
|
||||
@@ -42,17 +42,17 @@
|
||||
"dependencies": {
|
||||
"@expo/config": "55.0.10",
|
||||
"@expo/config-plugins": "55.0.7",
|
||||
"@expo/downloader": "27.3.0",
|
||||
"@expo/eas-build-job": "27.3.0",
|
||||
"@expo/downloader": "27.1.0",
|
||||
"@expo/eas-build-job": "27.1.0",
|
||||
"@expo/env": "^0.4.0",
|
||||
"@expo/logger": "27.3.0",
|
||||
"@expo/logger": "27.1.0",
|
||||
"@expo/package-manager": "1.9.10",
|
||||
"@expo/plist": "^0.3.5",
|
||||
"@expo/results": "^1.0.0",
|
||||
"@expo/spawn-async": "1.7.2",
|
||||
"@expo/steps": "27.3.0",
|
||||
"@expo/template-file": "27.3.0",
|
||||
"@expo/turtle-spawn": "27.3.0",
|
||||
"@expo/steps": "27.1.0",
|
||||
"@expo/template-file": "27.1.0",
|
||||
"@expo/turtle-spawn": "27.1.0",
|
||||
"@expo/xcpretty": "^4.4.7",
|
||||
"@ngrok/ngrok": "1.7.0",
|
||||
"@sentry/node": "7.77.0",
|
||||
|
||||
@@ -167,7 +167,6 @@ export async function runAgentDeviceRemoteSessionAsync(
|
||||
subdomainPrefix: 'agent-device',
|
||||
baseDomain: ngrokTunnelDomain,
|
||||
authtoken: ngrokAuthtoken,
|
||||
healthCheck: { path: '/health' },
|
||||
logger: taskLogger,
|
||||
});
|
||||
tasks.signal.throwIfAborted();
|
||||
|
||||
@@ -274,7 +274,6 @@ export function createStartAppiumRemoteSessionBuildFunction(
|
||||
subdomainPrefix: 'appium',
|
||||
baseDomain: ngrokTunnelDomain,
|
||||
authtoken: ngrokAuthtoken,
|
||||
healthCheck: { path: '/status' },
|
||||
logger,
|
||||
});
|
||||
|
||||
|
||||
@@ -340,7 +340,6 @@ export function createStartArgentRemoteSessionBuildFunction(
|
||||
baseDomain: ngrokTunnelDomain,
|
||||
authtoken: ngrokAuthtoken,
|
||||
rewriteHostHeader: true,
|
||||
healthCheck: { path: '/tools', statuses: [200, 401] },
|
||||
logger,
|
||||
});
|
||||
const publicToolsUrl = toolsTunnel.url;
|
||||
|
||||
@@ -36,7 +36,7 @@ const SERVE_SIM_LEASE_FINALIZE_TIMEOUT_MS =
|
||||
const SERVE_SIM_FINISH_TIMEOUT_MS =
|
||||
SERVE_SIM_CONTROL_REQUEST_TIMEOUT_MS + SERVE_SIM_LEASE_FINALIZE_TIMEOUT_MS;
|
||||
const SERVE_SIM_FORCE_STOP_TIMEOUT_MS = 5_000;
|
||||
const SERVE_SIM_RECORDING_STARTED_LINE = /(?:^|\n)serve-sim:recording-started\r?\n/;
|
||||
const SERVE_SIM_RECORDING_STARTED = 'serve-sim:recording-started';
|
||||
// The serve-sim package the session host started; every recorder runs `record-video` from it.
|
||||
let serveSimPackageSpec: string | null = null;
|
||||
|
||||
@@ -507,19 +507,14 @@ function captureProcessOutput(recordingProcess: ChildProcess): {
|
||||
} {
|
||||
let output = '';
|
||||
let started = false;
|
||||
const captureStreamOutput = (stream: ChildProcess['stdout']): void => {
|
||||
let streamOutput = '';
|
||||
stream?.on('data', (chunk: Buffer | string) => {
|
||||
const text = chunk.toString();
|
||||
output = `${output}${text}`.slice(-16_384);
|
||||
streamOutput = `${streamOutput}${text}`;
|
||||
if (SERVE_SIM_RECORDING_STARTED_LINE.test(streamOutput)) {
|
||||
started = true;
|
||||
}
|
||||
streamOutput = streamOutput.slice(-16_384);
|
||||
});
|
||||
const appendChunk = (chunk: Buffer | string): void => {
|
||||
output = `${output}${chunk.toString()}`;
|
||||
if (output.includes(SERVE_SIM_RECORDING_STARTED)) {
|
||||
started = true;
|
||||
}
|
||||
output = output.slice(-16_384);
|
||||
};
|
||||
captureStreamOutput(recordingProcess.stdout);
|
||||
captureStreamOutput(recordingProcess.stderr);
|
||||
recordingProcess.stdout?.on('data', appendChunk);
|
||||
recordingProcess.stderr?.on('data', appendChunk);
|
||||
return { getOutput: () => output, hasStarted: () => started };
|
||||
}
|
||||
@@ -144,10 +144,7 @@ test('starts serve-sim record-video and returns only a finalized recording', asy
|
||||
const finishing = IosSimulatorRecordingUtils.finishAsync({ logger });
|
||||
await setTimeout(20);
|
||||
expect(child.kill).not.toHaveBeenCalled();
|
||||
child.stdout?.emit('data', 'Downloading');
|
||||
stderr.write('serve-sim:recording-');
|
||||
child.stdout?.emit('data', ' package');
|
||||
stderr.write('started\r\n');
|
||||
stderr.write('serve-sim:recording-started\n');
|
||||
stderr.write('x'.repeat(17_000));
|
||||
const recordings = await finishing;
|
||||
|
||||
@@ -365,32 +362,6 @@ test('keeps a recorder active after its package-manager wrapper exits', async ()
|
||||
expect(recordings).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('does not mistake bundled source in an error for a recording start', async () => {
|
||||
let currentTime = Date.now();
|
||||
jest.spyOn(Date, 'now').mockImplementation(() => currentTime);
|
||||
jest
|
||||
.mocked(readServeSimServersAsync)
|
||||
.mockResolvedValue([{ udid, url: 'http://127.0.0.1:43563', token: 'session-token' }]);
|
||||
const recorder = mockRecorder();
|
||||
|
||||
await IosSimulatorRecordingUtils.startAsync({ env, logger });
|
||||
await waitForRecorderSpawnAsync();
|
||||
recorder.child.stderr?.emit(
|
||||
'data',
|
||||
'const marker = "serve-sim:recording-started";\nError: No running serve-sim session found.\n'
|
||||
);
|
||||
recorder.fail(new Error('recorder exited before connecting'));
|
||||
|
||||
const finishing = IosSimulatorRecordingUtils.finishAsync({ logger });
|
||||
try {
|
||||
expect(await Promise.race([finishing.then(() => true), setTimeout(250, false)])).toBe(true);
|
||||
} finally {
|
||||
currentTime += 311_000;
|
||||
await finishing;
|
||||
}
|
||||
expect(recorder.child.kill).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('does not signal a recorder that exits before it reports its start', async () => {
|
||||
let currentTime = Date.now();
|
||||
jest.spyOn(Date, 'now').mockImplementation(() => currentTime);
|
||||
|
||||
-43
@@ -7,7 +7,6 @@ import { setImmediate } from 'node:timers/promises';
|
||||
|
||||
import { type CustomBuildContext } from '../../../customBuildContext';
|
||||
import RemoteLoggerStream from '../../../logging/RemoteLoggerStream';
|
||||
import { Sentry } from '../../../sentry';
|
||||
import { turtleFetch } from '../../../utils/turtleFetch';
|
||||
import { downloadBuildAsync } from '../../functions/downloadBuild';
|
||||
import { uploadDeviceRunSessionArtifactAsync } from '../deviceRunSessionArtifacts';
|
||||
@@ -267,48 +266,6 @@ describe('with a device run session token', () => {
|
||||
expect(jest.mocked(turtleFetch)).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('handles a stopped-session TURN response without a warning or retry', async () => {
|
||||
const ctx = createCtx({ withToken: true });
|
||||
jest
|
||||
.mocked(turtleFetch)
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse(
|
||||
{ errors: [{ code: 'DEVICE_RUN_SESSION_ALREADY_STOPPED', message: 'Stopped.' }] },
|
||||
400
|
||||
)
|
||||
);
|
||||
|
||||
await expect(fetchWebPreviewTurnArgsAsync(ctx, { logger })).resolves.toEqual([]);
|
||||
|
||||
expect(logger.info).toHaveBeenCalledWith(
|
||||
'Device run session was stopped before TURN credentials were fetched.'
|
||||
);
|
||||
expect(logger.warn).not.toHaveBeenCalled();
|
||||
expect(Sentry.capture).not.toHaveBeenCalled();
|
||||
expect(turtleFetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each([undefined, 'VALIDATION_ERROR'])(
|
||||
'still warns on a TURN failure with code %s',
|
||||
async code => {
|
||||
const ctx = createCtx({ withToken: true });
|
||||
jest
|
||||
.mocked(turtleFetch)
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse(
|
||||
{ errors: [{ code, message: 'Device run session has already stopped.' }] },
|
||||
400
|
||||
)
|
||||
);
|
||||
|
||||
await expect(fetchWebPreviewTurnArgsAsync(ctx, { logger })).resolves.toEqual([]);
|
||||
|
||||
expect(logger.warn).toHaveBeenCalled();
|
||||
expect(Sentry.capture).toHaveBeenCalled();
|
||||
expect(turtleFetch).toHaveBeenCalledTimes(1);
|
||||
}
|
||||
);
|
||||
|
||||
it('creates artifact upload sessions through the worker API', async () => {
|
||||
const ctx = createCtx({ withToken: true });
|
||||
jest.mocked(turtleFetch).mockResolvedValueOnce(
|
||||
|
||||
@@ -1,873 +0,0 @@
|
||||
import { type bunyan } from '@expo/logger';
|
||||
import * as ngrok from '@ngrok/ngrok';
|
||||
import { once } from 'node:events';
|
||||
import { createServer } from 'node:http';
|
||||
import WebSocket, { WebSocketServer } from 'ws';
|
||||
import { type AddressInfo, createConnection, createServer as createTcpServer } from 'node:net';
|
||||
|
||||
import { turtleFetch } from '../../../utils/turtleFetch';
|
||||
import { startNgrokTunnelAsync } from '../ngrokTunnel';
|
||||
|
||||
jest.mock('@ngrok/ngrok');
|
||||
jest.mock('node:timers', () => ({
|
||||
setTimeout: (...args: Parameters<typeof setTimeout>) => setTimeout(...args),
|
||||
clearTimeout: (...args: Parameters<typeof clearTimeout>) => clearTimeout(...args),
|
||||
}));
|
||||
jest.mock('../../../utils/turtleFetch');
|
||||
|
||||
const { Response } = jest.requireActual<typeof import('node-fetch')>('node-fetch');
|
||||
const url = 'https://web-preview-fixed.example.test';
|
||||
const logger = { info: jest.fn(), warn: jest.fn() } as unknown as bunyan;
|
||||
const options = {
|
||||
port: 4321,
|
||||
subdomainPrefix: 'web-preview',
|
||||
subdomainId: 'fixed',
|
||||
baseDomain: 'example.test',
|
||||
authtoken: 'token',
|
||||
rewriteHostHeader: true,
|
||||
healthCheck: { path: '/healthz' },
|
||||
logger,
|
||||
};
|
||||
|
||||
function listener(publicUrl = url) {
|
||||
return { url: () => publicUrl, close: jest.fn().mockResolvedValue(undefined) };
|
||||
}
|
||||
|
||||
let initial: ReturnType<typeof listener>;
|
||||
let replacement: ReturnType<typeof listener>;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate'] });
|
||||
jest.clearAllMocks();
|
||||
initial = listener();
|
||||
replacement = listener();
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockResolvedValueOnce(initial as never)
|
||||
.mockResolvedValue(replacement as never);
|
||||
jest
|
||||
.mocked(turtleFetch)
|
||||
.mockReset()
|
||||
.mockResolvedValue(new Response(undefined, { status: 200 }));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
function failPublicProbes() {
|
||||
jest.mocked(turtleFetch).mockImplementation(
|
||||
async target =>
|
||||
new Response(undefined, {
|
||||
status: target.startsWith('https:') ? 503 : 200,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
it('keeps tunnels without a health check unsupervised and closes them on stop', async () => {
|
||||
const tunnel = await startNgrokTunnelAsync({ ...options, healthCheck: undefined });
|
||||
await jest.advanceTimersByTimeAsync(90_000);
|
||||
expect(turtleFetch).not.toHaveBeenCalled();
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(1);
|
||||
await tunnel.stopAsync();
|
||||
expect(initial.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('probes the public service and keeps a healthy listener open', async () => {
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
try {
|
||||
await jest.advanceTimersByTimeAsync(45_000);
|
||||
expect(turtleFetch).toHaveBeenCalledTimes(3);
|
||||
expect(turtleFetch).toHaveBeenCalledWith(
|
||||
`${url}/healthz`,
|
||||
'GET',
|
||||
expect.objectContaining({
|
||||
retries: 0,
|
||||
redirect: 'manual',
|
||||
headers: expect.objectContaining({ 'ngrok-skip-browser-warning': 'true' }),
|
||||
})
|
||||
);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
await tunnel.stopAsync();
|
||||
}
|
||||
expect(initial.close).toHaveBeenCalledTimes(1);
|
||||
await jest.advanceTimersByTimeAsync(60_000);
|
||||
expect(turtleFetch).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('reopens after three failed public probes with a healthy local service, preserving the endpoint', async () => {
|
||||
failPublicProbes();
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
try {
|
||||
await jest.advanceTimersByTimeAsync(30_000);
|
||||
expect(initial.close).not.toHaveBeenCalled();
|
||||
await jest.advanceTimersByTimeAsync(15_000);
|
||||
expect(initial.close).toHaveBeenCalledTimes(1);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(2);
|
||||
expect(jest.mocked(ngrok.forward).mock.calls[1][0]).toEqual({
|
||||
addr: expect.any(Number),
|
||||
authtoken: 'token',
|
||||
domain: 'web-preview-fixed.example.test',
|
||||
request_header_add: ['Host:localhost:4321'],
|
||||
force_new_session: true,
|
||||
});
|
||||
expect(tunnel.url).toBe(url);
|
||||
jest.mocked(turtleFetch).mockResolvedValue(new Response(undefined, { status: 200 }));
|
||||
await jest.advanceTimersByTimeAsync(15_000);
|
||||
expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('healthy again'));
|
||||
} finally {
|
||||
await tunnel.stopAsync();
|
||||
}
|
||||
expect(replacement.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not reopen when the local service is unhealthy', async () => {
|
||||
jest.mocked(turtleFetch).mockResolvedValue(new Response(undefined, { status: 503 }));
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
try {
|
||||
await jest.advanceTimersByTimeAsync(90_000);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(1);
|
||||
expect(initial.close).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await tunnel.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('resets consecutive failures after a successful public probe', async () => {
|
||||
failPublicProbes();
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
try {
|
||||
await jest.advanceTimersByTimeAsync(30_000);
|
||||
jest.mocked(turtleFetch).mockResolvedValueOnce(new Response(undefined, { status: 200 }));
|
||||
await jest.advanceTimersByTimeAsync(15_000);
|
||||
await jest.advanceTimersByTimeAsync(30_000);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
await tunnel.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('retries a failed reopen with backoff', async () => {
|
||||
failPublicProbes();
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockResolvedValueOnce(initial as never)
|
||||
.mockRejectedValueOnce(new Error('offline'))
|
||||
.mockResolvedValue(replacement as never);
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
try {
|
||||
await jest.advanceTimersByTimeAsync(45_000);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(2);
|
||||
await jest.advanceTimersByTimeAsync(1_999);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(2);
|
||||
await jest.advanceTimersByTimeAsync(1);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(3);
|
||||
} finally {
|
||||
await tunnel.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('closes a listener that finishes opening after shutdown, with idempotent cleanup', async () => {
|
||||
failPublicProbes();
|
||||
let resolveOpening!: (value: ngrok.Listener) => void;
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockResolvedValueOnce(initial as never)
|
||||
.mockReturnValueOnce(
|
||||
new Promise(resolve => {
|
||||
resolveOpening = resolve;
|
||||
})
|
||||
);
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
await jest.advanceTimersByTimeAsync(45_000);
|
||||
const stopping = tunnel.stopAsync();
|
||||
expect(tunnel.stopAsync()).toBe(stopping);
|
||||
const stopped = jest.fn();
|
||||
void stopping.then(stopped);
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(stopped).not.toHaveBeenCalled();
|
||||
resolveOpening(replacement as never);
|
||||
await stopping;
|
||||
expect(replacement.close).toHaveBeenCalledTimes(1);
|
||||
await jest.advanceTimersByTimeAsync(120_000);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('waits for a replacement acquired during shutdown to finish closing', async () => {
|
||||
failPublicProbes();
|
||||
let resolveOpening!: (value: ngrok.Listener) => void;
|
||||
let resolveClose!: () => void;
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockResolvedValueOnce(initial as never)
|
||||
.mockReturnValueOnce(new Promise(resolve => (resolveOpening = resolve)));
|
||||
replacement.close.mockReturnValue(new Promise<void>(resolve => (resolveClose = resolve)));
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
await jest.advanceTimersByTimeAsync(45_000);
|
||||
let stopped = false;
|
||||
const stopping = tunnel.stopAsync().then(() => {
|
||||
stopped = true;
|
||||
});
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
resolveOpening(replacement as never);
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
const stoppedBeforeClose = stopped;
|
||||
resolveClose();
|
||||
await jest.advanceTimersByTimeAsync(250);
|
||||
await stopping;
|
||||
expect(stoppedBeforeClose).toBe(false);
|
||||
expect(replacement.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each([0, 4, 5, 10])('retires a reopen cancelled after %s promise turns', async turns => {
|
||||
failPublicProbes();
|
||||
let resolveOpening!: (value: ngrok.Listener) => void;
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockResolvedValueOnce(initial as never)
|
||||
.mockReturnValueOnce(new Promise(resolve => (resolveOpening = resolve)));
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
await jest.advanceTimersByTimeAsync(45_000);
|
||||
resolveOpening(replacement as never);
|
||||
for (let turn = 0; turn < turns; turn++) {
|
||||
await Promise.resolve();
|
||||
}
|
||||
await tunnel.stopAsync();
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(replacement.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('retries a rejected close when a reopen finishes after shutdown', async () => {
|
||||
failPublicProbes();
|
||||
let resolveOpening!: (value: ngrok.Listener) => void;
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockResolvedValueOnce(initial as never)
|
||||
.mockReturnValueOnce(new Promise(resolve => (resolveOpening = resolve)));
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
await jest.advanceTimersByTimeAsync(45_000);
|
||||
const stopping = tunnel.stopAsync();
|
||||
replacement.close.mockRejectedValueOnce(new Error('temporary unlisten failure'));
|
||||
resolveOpening(replacement as never);
|
||||
await jest.advanceTimersByTimeAsync(250);
|
||||
await stopping;
|
||||
expect(replacement.close).toHaveBeenCalledTimes(2);
|
||||
const warnings = jest.mocked(logger.warn).mock.calls.length;
|
||||
await jest.advanceTimersByTimeAsync(120_000);
|
||||
expect(logger.warn).toHaveBeenCalledTimes(warnings);
|
||||
});
|
||||
|
||||
it('fails stop if an in-flight reopen still has not settled by the stop deadline', async () => {
|
||||
failPublicProbes();
|
||||
let resolveOpening!: (value: ngrok.Listener) => void;
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockResolvedValueOnce(initial as never)
|
||||
.mockReturnValueOnce(new Promise(resolve => (resolveOpening = resolve)));
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
await jest.advanceTimersByTimeAsync(45_000);
|
||||
const rejected = expect(tunnel.stopAsync()).rejects.toThrow(
|
||||
'Ngrok tunnel web-preview-fixed.example.test stop timed out after 4000ms'
|
||||
);
|
||||
await jest.advanceTimersByTimeAsync(4_000);
|
||||
await rejected;
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(2);
|
||||
resolveOpening(replacement as never);
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(replacement.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('retries an old listener while a reopen outlasts shutdown', async () => {
|
||||
failPublicProbes();
|
||||
initial.close.mockRejectedValueOnce(new Error('agent disconnected'));
|
||||
let resolveOpening!: (value: ngrok.Listener) => void;
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockResolvedValueOnce(initial as never)
|
||||
.mockReturnValueOnce(new Promise(resolve => (resolveOpening = resolve)));
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
await jest.advanceTimersByTimeAsync(45_000);
|
||||
expect(initial.close).toHaveBeenCalledTimes(1);
|
||||
const rejected = expect(tunnel.stopAsync()).rejects.toThrow(
|
||||
'Ngrok tunnel web-preview-fixed.example.test stop timed out after 4000ms'
|
||||
);
|
||||
await jest.advanceTimersByTimeAsync(4_000);
|
||||
await rejected;
|
||||
const oldCloseCalls = initial.close.mock.calls.length;
|
||||
resolveOpening(replacement as never);
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(oldCloseCalls).toBe(2);
|
||||
expect(replacement.close).toHaveBeenCalledTimes(1);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('fails stop if a pending reopen arrives but cannot be retired', async () => {
|
||||
failPublicProbes();
|
||||
let resolveOpening!: (value: ngrok.Listener) => void;
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockResolvedValueOnce(initial as never)
|
||||
.mockReturnValueOnce(new Promise(resolve => (resolveOpening = resolve)));
|
||||
replacement.close.mockRejectedValue(new Error('unlisten failed'));
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
await jest.advanceTimersByTimeAsync(45_000);
|
||||
const rejected = expect(tunnel.stopAsync()).rejects.toThrow(
|
||||
'Ngrok tunnel web-preview-fixed.example.test stop timed out'
|
||||
);
|
||||
resolveOpening(replacement as never);
|
||||
await jest.advanceTimersByTimeAsync(4_000);
|
||||
await rejected;
|
||||
expect(replacement.close.mock.calls.length).toBeGreaterThan(1);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ err: expect.any(Error) }),
|
||||
'Could not retire late ngrok tunnel web-preview-fixed.example.test.'
|
||||
);
|
||||
const warnings = jest.mocked(logger.warn).mock.calls.length;
|
||||
await jest.advanceTimersByTimeAsync(120_000);
|
||||
expect(logger.warn).toHaveBeenCalledTimes(warnings);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('rejects a changed public URL and closes the replacement', async () => {
|
||||
failPublicProbes();
|
||||
const changed = listener('https://different.example.test');
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockResolvedValueOnce(initial as never)
|
||||
.mockResolvedValue(changed as never);
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
try {
|
||||
await jest.advanceTimersByTimeAsync(45_000);
|
||||
expect(changed.close).toHaveBeenCalledTimes(1);
|
||||
expect(tunnel.url).toBe(url);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ err: expect.any(Error) }),
|
||||
expect.stringContaining('Could not reopen')
|
||||
);
|
||||
} finally {
|
||||
await tunnel.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('treats ngrok error responses as failures even if their status is accepted', async () => {
|
||||
jest.mocked(turtleFetch).mockImplementation(
|
||||
async target =>
|
||||
new Response(undefined, {
|
||||
status: 200,
|
||||
headers: target.startsWith('https:') ? { 'ngrok-error-code': 'ERR_NGROK_3200' } : {},
|
||||
})
|
||||
);
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
try {
|
||||
await jest.advanceTimersByTimeAsync(45_000);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
await tunnel.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('reopens on a fresh agent session even if closing the old listener fails', async () => {
|
||||
failPublicProbes();
|
||||
initial.close.mockRejectedValueOnce(new Error('agent disconnected'));
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
try {
|
||||
await jest.advanceTimersByTimeAsync(45_000);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(2);
|
||||
expect(ngrok.forward).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ force_new_session: true })
|
||||
);
|
||||
expect(ngrok.disconnect).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await tunnel.stopAsync();
|
||||
}
|
||||
expect(initial.close).toHaveBeenCalledTimes(2);
|
||||
expect(replacement.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('retries a rejected close before reopening an endpoint that remains bound', async () => {
|
||||
failPublicProbes();
|
||||
let domainOccupied = true;
|
||||
initial.close
|
||||
.mockRejectedValueOnce(new Error('agent disconnected'))
|
||||
.mockImplementation(async () => {
|
||||
domainOccupied = false;
|
||||
});
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockResolvedValueOnce(initial as never)
|
||||
.mockImplementation(async () => {
|
||||
if (domainOccupied) {
|
||||
throw new Error('endpoint is still bound');
|
||||
}
|
||||
return replacement as never;
|
||||
});
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
try {
|
||||
await jest.advanceTimersByTimeAsync(45_000);
|
||||
expect(initial.close).toHaveBeenCalledTimes(1);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(2);
|
||||
await jest.advanceTimersByTimeAsync(2_000);
|
||||
expect(initial.close).toHaveBeenCalledTimes(2);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(3);
|
||||
expect(tunnel.url).toBe(url);
|
||||
} finally {
|
||||
await tunnel.stopAsync();
|
||||
}
|
||||
expect(replacement.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('retires an old listener even after its replacement is healthy', async () => {
|
||||
failPublicProbes();
|
||||
initial.close.mockRejectedValueOnce(new Error('agent disconnected'));
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
try {
|
||||
await jest.advanceTimersByTimeAsync(45_000);
|
||||
expect(initial.close).toHaveBeenCalledTimes(1);
|
||||
jest.mocked(turtleFetch).mockResolvedValue(new Response(undefined, { status: 200 }));
|
||||
await jest.advanceTimersByTimeAsync(15_000);
|
||||
expect(initial.close).toHaveBeenCalledTimes(2);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
await tunnel.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('retries an old listener without repeating its close warning on every probe', async () => {
|
||||
failPublicProbes();
|
||||
initial.close.mockRejectedValue(new Error('old session disconnected'));
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
await jest.advanceTimersByTimeAsync(45_000);
|
||||
const warnings = jest.mocked(logger.warn).mock.calls.length;
|
||||
expect(warnings).toBeGreaterThan(0);
|
||||
jest.mocked(turtleFetch).mockResolvedValue(new Response(undefined, { status: 200 }));
|
||||
await jest.advanceTimersByTimeAsync(120_000);
|
||||
expect(initial.close.mock.calls.length).toBeGreaterThan(1);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(2);
|
||||
expect(logger.warn).toHaveBeenCalledTimes(warnings);
|
||||
const rejected = expect(tunnel.stopAsync()).rejects.toThrow(
|
||||
'Ngrok tunnel web-preview-fixed.example.test stop timed out'
|
||||
);
|
||||
await jest.advanceTimersByTimeAsync(4_000);
|
||||
await rejected;
|
||||
expect(replacement.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('retries a rejected close during shutdown', async () => {
|
||||
const failure = new Error('agent disconnected');
|
||||
initial.close.mockRejectedValueOnce(failure);
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
const stopping = tunnel.stopAsync();
|
||||
await jest.advanceTimersByTimeAsync(250);
|
||||
await stopping;
|
||||
expect(initial.close).toHaveBeenCalledTimes(2);
|
||||
expect(logger.warn).toHaveBeenCalledTimes(1);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
{ err: failure },
|
||||
'Could not stop ngrok tunnel web-preview-fixed.example.test.'
|
||||
);
|
||||
});
|
||||
|
||||
it('logs the first close rejection once while bounded shutdown retries it', async () => {
|
||||
const failure = new Error('agent disconnected');
|
||||
initial.close.mockRejectedValue(failure);
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
const rejected = expect(tunnel.stopAsync()).rejects.toThrow('stop timed out');
|
||||
await jest.advanceTimersByTimeAsync(4_000);
|
||||
await rejected;
|
||||
expect(initial.close.mock.calls.length).toBeGreaterThan(1);
|
||||
expect(logger.warn).toHaveBeenCalledTimes(1);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
{ err: failure },
|
||||
'Could not stop ngrok tunnel web-preview-fixed.example.test.'
|
||||
);
|
||||
});
|
||||
|
||||
it('bounds shutdown during recovery without duplicating a pending native close', async () => {
|
||||
failPublicProbes();
|
||||
let finishClose!: () => void;
|
||||
initial.close.mockReturnValueOnce(new Promise<void>(resolve => (finishClose = resolve)));
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
await jest.advanceTimersByTimeAsync(45_000);
|
||||
const stopping = tunnel.stopAsync();
|
||||
expect(tunnel.stopAsync()).toBe(stopping);
|
||||
const rejected = expect(stopping).rejects.toThrow(
|
||||
'Ngrok tunnel web-preview-fixed.example.test stop timed out after 4000ms'
|
||||
);
|
||||
await jest.advanceTimersByTimeAsync(4_000);
|
||||
await rejected;
|
||||
expect(initial.close).toHaveBeenCalledTimes(1);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(1);
|
||||
const warnings = jest.mocked(logger.warn).mock.calls.length;
|
||||
finishClose();
|
||||
await jest.advanceTimersByTimeAsync(120_000);
|
||||
expect(logger.warn).toHaveBeenCalledTimes(warnings);
|
||||
expect(initial.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('bounds a stalled listener close before reopening', async () => {
|
||||
failPublicProbes();
|
||||
initial.close.mockImplementationOnce(async () => await new Promise(() => {}));
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
try {
|
||||
await jest.advanceTimersByTimeAsync(49_999);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(1);
|
||||
await jest.advanceTimersByTimeAsync(1);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
const stopping = tunnel.stopAsync();
|
||||
const rejected = expect(stopping).rejects.toThrow(
|
||||
'Ngrok tunnel web-preview-fixed.example.test stop timed out'
|
||||
);
|
||||
await jest.advanceTimersByTimeAsync(4_000);
|
||||
await rejected;
|
||||
}
|
||||
});
|
||||
|
||||
it('does not queue more native opens while a timed-out open is still pending', async () => {
|
||||
failPublicProbes();
|
||||
let resolveOpening!: (value: ngrok.Listener) => void;
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockResolvedValueOnce(initial as never)
|
||||
.mockReturnValueOnce(
|
||||
new Promise(resolve => {
|
||||
resolveOpening = resolve;
|
||||
})
|
||||
)
|
||||
.mockResolvedValue(replacement as never);
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
const late = listener();
|
||||
try {
|
||||
await jest.advanceTimersByTimeAsync(180_000);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(2);
|
||||
resolveOpening(late as never);
|
||||
await jest.advanceTimersByTimeAsync(30_000);
|
||||
expect(late.close).toHaveBeenCalledTimes(1);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(3);
|
||||
} finally {
|
||||
await tunnel.stopAsync();
|
||||
}
|
||||
expect(replacement.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('bounds initial tunnel creation and retires a late listener', async () => {
|
||||
let resolveOpening!: (value: ngrok.Listener) => void;
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockReturnValueOnce(
|
||||
new Promise(resolve => {
|
||||
resolveOpening = resolve;
|
||||
})
|
||||
);
|
||||
const opening = startNgrokTunnelAsync(options);
|
||||
const rejected = expect(opening).rejects.toThrow('Ngrok tunnel open timed out');
|
||||
await jest.advanceTimersByTimeAsync(15_000);
|
||||
await rejected;
|
||||
resolveOpening(initial as never);
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(initial.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('retries a rejected close after initial tunnel creation timed out', async () => {
|
||||
let resolveOpening!: (value: ngrok.Listener) => void;
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockReturnValueOnce(new Promise(resolve => (resolveOpening = resolve)));
|
||||
const opening = startNgrokTunnelAsync(options);
|
||||
const rejected = expect(opening).rejects.toThrow('Ngrok tunnel open timed out');
|
||||
await jest.advanceTimersByTimeAsync(15_000);
|
||||
await rejected;
|
||||
initial.close.mockRejectedValueOnce(new Error('temporary unlisten failure'));
|
||||
resolveOpening(initial as never);
|
||||
await jest.advanceTimersByTimeAsync(250);
|
||||
expect(initial.close).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('retires only the late listener without blaming it for an older stuck listener', async () => {
|
||||
failPublicProbes();
|
||||
initial.close.mockRejectedValue(new Error('old session disconnected'));
|
||||
let resolveOpening!: (value: ngrok.Listener) => void;
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockResolvedValueOnce(initial as never)
|
||||
.mockReturnValueOnce(new Promise(resolve => (resolveOpening = resolve)))
|
||||
.mockResolvedValue(replacement as never);
|
||||
const tunnel = await startNgrokTunnelAsync(options);
|
||||
try {
|
||||
await jest.advanceTimersByTimeAsync(60_000);
|
||||
const late = listener();
|
||||
resolveOpening(late as never);
|
||||
jest.mocked(turtleFetch).mockResolvedValue(new Response(undefined, { status: 200 }));
|
||||
await jest.advanceTimersByTimeAsync(4_000);
|
||||
expect(late.close).toHaveBeenCalledTimes(1);
|
||||
expect(
|
||||
jest
|
||||
.mocked(logger.warn)
|
||||
.mock.calls.some(([, message]) => message?.includes('Could not retire late'))
|
||||
).toBe(false);
|
||||
} finally {
|
||||
initial.close.mockResolvedValue(undefined);
|
||||
await tunnel.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('recovers using actual HTTP health probes with a local ngrok adapter', async () => {
|
||||
const actualFetch = jest.requireActual<typeof import('node-fetch')>('node-fetch').default;
|
||||
const realSetTimeout = jest.requireActual<typeof import('node:timers')>('node:timers').setTimeout;
|
||||
let broken = true;
|
||||
const local = createServer((_req, res) => {
|
||||
res.writeHead(200);
|
||||
res.end('healthy');
|
||||
});
|
||||
const publicServer = createServer((_req, res) => {
|
||||
res.writeHead(broken ? 503 : 200);
|
||||
res.end('probe');
|
||||
});
|
||||
await Promise.all(
|
||||
[local, publicServer].map(
|
||||
server => new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
|
||||
)
|
||||
);
|
||||
const publicUrl = `http://127.0.0.1:${(publicServer.address() as AddressInfo).port}`;
|
||||
let completedRequests = 0;
|
||||
jest.mocked(turtleFetch).mockImplementation(async (target, method, requestOptions) => {
|
||||
const response = await actualFetch(target, { ...requestOptions, method });
|
||||
completedRequests++;
|
||||
return response;
|
||||
});
|
||||
const first = listener(publicUrl);
|
||||
const next = listener(publicUrl);
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockResolvedValueOnce(first as never)
|
||||
.mockImplementation(async () => {
|
||||
broken = false;
|
||||
return next as never;
|
||||
});
|
||||
const tunnel = await startNgrokTunnelAsync({
|
||||
...options,
|
||||
port: (local.address() as AddressInfo).port,
|
||||
});
|
||||
try {
|
||||
for (let count = 0; count < 3; count++) {
|
||||
await jest.advanceTimersByTimeAsync(15_000);
|
||||
for (let turns = 0; turns < 50 && completedRequests < (count + 1) * 2; turns++) {
|
||||
await new Promise(resolve => realSetTimeout(resolve, 10));
|
||||
}
|
||||
expect(completedRequests).toBe((count + 1) * 2);
|
||||
}
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(2);
|
||||
expect(first.close).toHaveBeenCalledTimes(1);
|
||||
expect((await actualFetch(`${tunnel.url}/healthz`)).status).toBe(200);
|
||||
} finally {
|
||||
await tunnel.stopAsync();
|
||||
await Promise.all(
|
||||
[local, publicServer].map(
|
||||
server =>
|
||||
new Promise<void>((resolve, reject) =>
|
||||
server.close(err => (err ? reject(err) : resolve()))
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
expect(next.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('blocks HTTP and existing WebSockets on Stop even when ngrok cannot close', async () => {
|
||||
jest.useRealTimers();
|
||||
const actualFetch = jest.requireActual<typeof import('node-fetch')>('node-fetch').default;
|
||||
let requests = 0;
|
||||
let messages = 0;
|
||||
const backend = createServer((_request, response) => {
|
||||
requests++;
|
||||
response.end('owned backend');
|
||||
});
|
||||
const websockets = new WebSocketServer({ server: backend });
|
||||
websockets.on('connection', socket => {
|
||||
socket.on('message', data => {
|
||||
messages++;
|
||||
socket.send(data);
|
||||
});
|
||||
});
|
||||
backend.listen(0, '127.0.0.1');
|
||||
await once(backend, 'listening');
|
||||
const backendPort = (backend.address() as AddressInfo).port;
|
||||
const tunnel = await startNgrokTunnelAsync({
|
||||
...options,
|
||||
port: backendPort,
|
||||
healthCheck: undefined,
|
||||
});
|
||||
const targetPort = (jest.mocked(ngrok.forward).mock.calls[0][0] as ngrok.Config).addr;
|
||||
const targetUrl = `http://127.0.0.1:${targetPort}`;
|
||||
const socket = new WebSocket(`ws://127.0.0.1:${targetPort}`);
|
||||
const opened = once(socket, 'open');
|
||||
try {
|
||||
expect(await (await actualFetch(targetUrl)).text()).toBe('owned backend');
|
||||
await opened;
|
||||
const echoed = once(socket, 'message');
|
||||
socket.send('before-stop');
|
||||
expect((await echoed)[0].toString()).toBe('before-stop');
|
||||
const closed = once(socket, 'close');
|
||||
initial.close.mockRejectedValue(new Error('agent disconnected'));
|
||||
const stopping = tunnel.stopAsync();
|
||||
const rejected = expect(stopping).rejects.toThrow('stop timed out after 4000ms');
|
||||
await expect(actualFetch(targetUrl, { timeout: 1_000 })).rejects.toThrow();
|
||||
await closed;
|
||||
expect(requests).toBe(1);
|
||||
expect(messages).toBe(1);
|
||||
expect(await (await actualFetch(`http://127.0.0.1:${backendPort}`)).text()).toBe(
|
||||
'owned backend'
|
||||
);
|
||||
await rejected;
|
||||
await expect(actualFetch(targetUrl, { timeout: 1_000 })).rejects.toThrow();
|
||||
expect(requests).toBe(2);
|
||||
expect(messages).toBe(1);
|
||||
const competing = createTcpServer();
|
||||
const conflict = once(competing, 'error');
|
||||
competing.listen(targetPort as number, '127.0.0.1');
|
||||
expect((await conflict)[0]).toMatchObject({ code: 'EADDRINUSE' });
|
||||
} finally {
|
||||
socket.terminate();
|
||||
for (const client of websockets.clients) {
|
||||
client.terminate();
|
||||
}
|
||||
websockets.close();
|
||||
backend.closeAllConnections();
|
||||
await new Promise<void>(resolve => backend.close(() => resolve()));
|
||||
await tunnel.stopAsync().catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
it('releases its local target when initial tunnel creation fails', async () => {
|
||||
jest.useRealTimers();
|
||||
jest.mocked(ngrok.forward).mockReset().mockRejectedValue(new Error('forward failed'));
|
||||
await expect(startNgrokTunnelAsync(options)).rejects.toThrow('forward failed');
|
||||
const targetPort = (jest.mocked(ngrok.forward).mock.calls[0][0] as ngrok.Config).addr;
|
||||
const server = createServer();
|
||||
server.listen(targetPort as number, '127.0.0.1');
|
||||
await once(server, 'listening');
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
});
|
||||
|
||||
it('preserves a full response for a half-closed slow reader', async () => {
|
||||
jest.useRealTimers();
|
||||
const payload = Buffer.alloc(4 * 1024 * 1024, 37);
|
||||
const backend = createTcpServer({ allowHalfOpen: true }, socket => {
|
||||
socket.resume();
|
||||
socket.on('end', () => socket.end(payload));
|
||||
});
|
||||
backend.listen(0, '127.0.0.1');
|
||||
await once(backend, 'listening');
|
||||
const tunnel = await startNgrokTunnelAsync({
|
||||
...options,
|
||||
port: (backend.address() as AddressInfo).port,
|
||||
healthCheck: undefined,
|
||||
});
|
||||
const targetPort = (jest.mocked(ngrok.forward).mock.calls[0][0] as ngrok.Config).addr as number;
|
||||
const socket = createConnection({ host: '127.0.0.1', port: targetPort, allowHalfOpen: true });
|
||||
try {
|
||||
const chunks: Buffer[] = [];
|
||||
socket.on('data', chunk => chunks.push(chunk));
|
||||
const ended = once(socket, 'end');
|
||||
socket.pause();
|
||||
socket.end('request');
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
socket.resume();
|
||||
await ended;
|
||||
expect(Buffer.concat(chunks).equals(payload)).toBe(true);
|
||||
} finally {
|
||||
socket.destroy();
|
||||
await tunnel.stopAsync();
|
||||
await new Promise<void>(resolve => backend.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
|
||||
it.each(['resolve', 'reject'])(
|
||||
'releases the target after timed-out startup later %s',
|
||||
async outcome => {
|
||||
let resolveOpening!: (value: ngrok.Listener) => void;
|
||||
let rejectOpening!: (error: Error) => void;
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockReturnValue(
|
||||
new Promise((resolve, reject) => {
|
||||
resolveOpening = resolve;
|
||||
rejectOpening = reject;
|
||||
})
|
||||
);
|
||||
const opening = startNgrokTunnelAsync(options);
|
||||
const rejected = expect(opening).rejects.toThrow('open timed out');
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
await jest.advanceTimersByTimeAsync(15_000);
|
||||
await rejected;
|
||||
const targetPort = (jest.mocked(ngrok.forward).mock.calls[0][0] as ngrok.Config).addr as number;
|
||||
if (outcome === 'resolve') {
|
||||
resolveOpening(replacement as never);
|
||||
} else {
|
||||
rejectOpening(new Error('forward failed'));
|
||||
}
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
const server = createTcpServer();
|
||||
server.listen(targetPort, '127.0.0.1');
|
||||
await once(server, 'listening');
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
}
|
||||
);
|
||||
|
||||
it('drains a full upload when the backend ends its response early', async () => {
|
||||
jest.useRealTimers();
|
||||
const payload = Buffer.alloc(4 * 1024 * 1024, 51);
|
||||
let received!: Buffer;
|
||||
let receivedRequest!: () => void;
|
||||
const completed = new Promise<void>(resolve => {
|
||||
receivedRequest = resolve;
|
||||
});
|
||||
const backend = createTcpServer({ allowHalfOpen: true }, socket => {
|
||||
const chunks: Buffer[] = [];
|
||||
socket.on('data', chunk => chunks.push(chunk));
|
||||
socket.on('end', () => {
|
||||
received = Buffer.concat(chunks);
|
||||
receivedRequest();
|
||||
});
|
||||
socket.pause();
|
||||
socket.end('early response');
|
||||
setTimeout(() => socket.resume(), 100);
|
||||
});
|
||||
backend.listen(0, '127.0.0.1');
|
||||
await once(backend, 'listening');
|
||||
const tunnel = await startNgrokTunnelAsync({
|
||||
...options,
|
||||
port: (backend.address() as AddressInfo).port,
|
||||
healthCheck: undefined,
|
||||
});
|
||||
const targetPort = (jest.mocked(ngrok.forward).mock.calls[0][0] as ngrok.Config).addr as number;
|
||||
const socket = createConnection({ host: '127.0.0.1', port: targetPort, allowHalfOpen: true });
|
||||
try {
|
||||
socket.resume();
|
||||
socket.end(payload);
|
||||
await completed;
|
||||
expect(received.equals(payload)).toBe(true);
|
||||
} finally {
|
||||
socket.destroy();
|
||||
await tunnel.stopAsync();
|
||||
await new Promise<void>(resolve => backend.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
@@ -932,7 +932,7 @@ describe(waitForWebPreviewReadyAsync, () => {
|
||||
|
||||
describe(startNgrokTunnelAsync, () => {
|
||||
it.each(['rejected', 'stalled'] as const)(
|
||||
'bounds %s listener retirement and reuses the stop promise',
|
||||
'retains a %s close failure on repeated stops',
|
||||
async mode => {
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
@@ -954,12 +954,14 @@ describe(startNgrokTunnelAsync, () => {
|
||||
logger: createLoggerMock(),
|
||||
});
|
||||
const stopping = tunnel.stopAsync();
|
||||
const assertion = expect(stopping).rejects.toThrow(/stop timed out after 4000ms/);
|
||||
const assertion = expect(stopping).rejects.toThrow(
|
||||
mode === 'rejected' ? 'close failed' : 'Ngrok tunnel stop timed out after 4000ms.'
|
||||
);
|
||||
expect(tunnel.stopAsync()).toBe(stopping);
|
||||
await jest.advanceTimersByTimeAsync(4_000);
|
||||
await assertion;
|
||||
await expect(tunnel.stopAsync()).rejects.toThrow();
|
||||
expect(close).toHaveBeenCalled();
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
@@ -983,7 +985,7 @@ describe(startNgrokTunnelAsync, () => {
|
||||
|
||||
expect(ngrok.forward).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
addr: expect.any(Number),
|
||||
addr: 4321,
|
||||
authtoken: 'token',
|
||||
domain: expect.stringMatching(/^web-preview-[a-f0-9]{32}\.eas-simulator\.ngrok\.dev$/),
|
||||
})
|
||||
@@ -1300,10 +1302,7 @@ describe(startDeviceSessionHostAsync, () => {
|
||||
recordingDirectory,
|
||||
}),
|
||||
]);
|
||||
expect(ngrok.forward).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ addr: expect.any(Number) })
|
||||
);
|
||||
expect(ngrok.forward).not.toHaveBeenCalledWith(expect.objectContaining({ addr: port }));
|
||||
expect(ngrok.forward).toHaveBeenCalledWith(expect.objectContaining({ addr: port }));
|
||||
expect(preview.apiUrl).toBe('https://android-preview.example.test');
|
||||
|
||||
await host.finishAsync();
|
||||
@@ -1439,10 +1438,7 @@ describe(startDeviceSessionHostAsync, () => {
|
||||
packageVersion,
|
||||
}),
|
||||
]);
|
||||
expect(ngrok.forward).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ addr: expect.any(Number) })
|
||||
);
|
||||
expect(ngrok.forward).not.toHaveBeenCalledWith(expect.objectContaining({ addr: port }));
|
||||
expect(ngrok.forward).toHaveBeenCalledWith(expect.objectContaining({ addr: port }));
|
||||
expect(preview.apiUrl).toBe('https://ios-preview.example.test');
|
||||
|
||||
await host.finishAsync();
|
||||
|
||||
@@ -623,7 +623,6 @@ async function startDeviceSessionHostInternalAsync(
|
||||
subdomainId,
|
||||
baseDomain,
|
||||
authtoken,
|
||||
healthCheck: { path: isAndroid ? '/readyz' : '/healthz' },
|
||||
logger,
|
||||
});
|
||||
if (finishTask) {
|
||||
|
||||
@@ -1,368 +0,0 @@
|
||||
import { SystemError } from '@expo/eas-build-job';
|
||||
import { type bunyan } from '@expo/logger';
|
||||
import * as ngrok from '@ngrok/ngrok';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { once } from 'node:events';
|
||||
import { type AddressInfo, type Socket, createConnection, createServer } from 'node:net';
|
||||
import { clearTimeout, setTimeout } from 'node:timers';
|
||||
|
||||
import { turtleFetch } from '../../utils/turtleFetch';
|
||||
import { withDeviceRunSessionTimeoutAsync } from './deviceRunSessionTimeout';
|
||||
|
||||
const PROBE_INTERVAL_MS = 15_000;
|
||||
const FAILURE_THRESHOLD = 3;
|
||||
const STOP_TIMEOUT_MS = 4_000;
|
||||
|
||||
export type NgrokTunnelHandle = {
|
||||
url: string;
|
||||
subdomainId: string;
|
||||
stopAsync: () => Promise<void>;
|
||||
};
|
||||
|
||||
export async function startNgrokTunnelAsync({
|
||||
port,
|
||||
subdomainPrefix,
|
||||
subdomainId = randomBytes(16).toString('hex'),
|
||||
baseDomain,
|
||||
authtoken,
|
||||
rewriteHostHeader,
|
||||
healthCheck,
|
||||
logger,
|
||||
}: {
|
||||
port: number;
|
||||
subdomainPrefix: string;
|
||||
subdomainId?: string;
|
||||
baseDomain: string;
|
||||
authtoken: string;
|
||||
rewriteHostHeader?: boolean;
|
||||
healthCheck?: { path: string; statuses?: number[] };
|
||||
logger: bunyan;
|
||||
}): Promise<NgrokTunnelHandle> {
|
||||
const domain = `${subdomainPrefix}-${subdomainId}.${baseDomain}`;
|
||||
const controller = new AbortController();
|
||||
const { signal } = controller;
|
||||
const sockets = new Set<Socket>();
|
||||
const target = createServer({ allowHalfOpen: true }, client => {
|
||||
if (signal.aborted) {
|
||||
client.destroy();
|
||||
return;
|
||||
}
|
||||
const upstream = createConnection({ host: '127.0.0.1', port, allowHalfOpen: true });
|
||||
for (const socket of [client, upstream]) {
|
||||
sockets.add(socket);
|
||||
socket.on('error', () => {
|
||||
client.destroy();
|
||||
upstream.destroy();
|
||||
});
|
||||
socket.on('close', () => sockets.delete(socket));
|
||||
}
|
||||
client.pipe(upstream).pipe(client);
|
||||
});
|
||||
target.listen(0, '127.0.0.1');
|
||||
await once(target, 'listening');
|
||||
target.unref();
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
for (const socket of sockets) {
|
||||
socket.destroy();
|
||||
}
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
const config: ngrok.Config = {
|
||||
addr: (target.address() as AddressInfo).port,
|
||||
authtoken,
|
||||
domain,
|
||||
...(rewriteHostHeader ? { request_header_add: [`Host:localhost:${port}`] } : {}),
|
||||
};
|
||||
|
||||
const ownedListeners = new Set<ngrok.Listener>();
|
||||
const retiredListeners = new Set<ngrok.Listener>();
|
||||
const closingListeners = new Map<ngrok.Listener, Promise<void>>();
|
||||
let pendingOpen: Promise<ngrok.Listener> | undefined;
|
||||
let currentListener: ngrok.Listener | undefined;
|
||||
function releaseTarget(): void {
|
||||
if (signal.aborted && !pendingOpen && ownedListeners.size === 0 && target.listening) {
|
||||
target.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function closeAsync(
|
||||
listener: ngrok.Listener,
|
||||
closeSignal: AbortSignal,
|
||||
logFailure = true
|
||||
): Promise<void> {
|
||||
retiredListeners.add(listener);
|
||||
let closing = closingListeners.get(listener);
|
||||
if (!closing) {
|
||||
closing = Promise.resolve().then(async () => await listener.close());
|
||||
closingListeners.set(listener, closing);
|
||||
void closing.then(
|
||||
() => {
|
||||
closingListeners.delete(listener);
|
||||
retiredListeners.delete(listener);
|
||||
ownedListeners.delete(listener);
|
||||
releaseTarget();
|
||||
},
|
||||
() => closingListeners.delete(listener)
|
||||
);
|
||||
}
|
||||
try {
|
||||
await withDeviceRunSessionTimeoutAsync(
|
||||
{ name: 'Ngrok tunnel close', timeoutMs: 5_000, signal: closeSignal },
|
||||
async () => await closing
|
||||
);
|
||||
} catch (err) {
|
||||
if (logFailure && !closeSignal.aborted) {
|
||||
logger.warn({ err }, `Could not stop ngrok tunnel ${domain}.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function retireListenersAsync(retirementSignal: AbortSignal): Promise<void> {
|
||||
let logFailure = true;
|
||||
while (retiredListeners.size > 0) {
|
||||
retirementSignal.throwIfAborted();
|
||||
await Promise.all(
|
||||
[...retiredListeners].map(retired => closeAsync(retired, retirementSignal, logFailure))
|
||||
);
|
||||
logFailure = false;
|
||||
if (retiredListeners.size > 0) {
|
||||
await waitAsync(250, retirementSignal);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function retireLateListenerAsync(listener: ngrok.Listener): Promise<void> {
|
||||
retiredListeners.add(listener);
|
||||
try {
|
||||
await withDeviceRunSessionTimeoutAsync(
|
||||
{ name: 'Late ngrok tunnel retirement', timeoutMs: STOP_TIMEOUT_MS },
|
||||
async retirementSignal => {
|
||||
while (retiredListeners.has(listener)) {
|
||||
retirementSignal.throwIfAborted();
|
||||
await closeAsync(listener, retirementSignal, false);
|
||||
if (retiredListeners.has(listener)) {
|
||||
await waitAsync(250, retirementSignal);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
} catch (err) {
|
||||
logger.warn({ err }, `Could not retire late ngrok tunnel ${domain}.`);
|
||||
}
|
||||
}
|
||||
|
||||
async function openAsync(forceNewSession = false): Promise<ngrok.Listener> {
|
||||
if (pendingOpen) {
|
||||
throw new SystemError(`A previous ngrok tunnel open for ${domain} is still pending.`);
|
||||
}
|
||||
let acquired: ngrok.Listener | undefined;
|
||||
let retirement: Promise<void> | undefined;
|
||||
const retireAcquired = () => {
|
||||
if (acquired) {
|
||||
retirement ??= retireLateListenerAsync(acquired);
|
||||
}
|
||||
};
|
||||
try {
|
||||
return await withDeviceRunSessionTimeoutAsync(
|
||||
{ name: 'Ngrok tunnel open', timeoutMs: 15_000, signal },
|
||||
async openSignal => {
|
||||
openSignal.throwIfAborted();
|
||||
const opening = ngrok
|
||||
.forward({
|
||||
...config,
|
||||
...(forceNewSession ? { force_new_session: true } : {}),
|
||||
})
|
||||
.then(listener => {
|
||||
acquired = listener;
|
||||
ownedListeners.add(listener);
|
||||
return listener;
|
||||
})
|
||||
.finally(() => {
|
||||
pendingOpen = undefined;
|
||||
});
|
||||
pendingOpen = opening;
|
||||
void opening
|
||||
.then(() => {
|
||||
if (openSignal.aborted) {
|
||||
retireAcquired();
|
||||
}
|
||||
})
|
||||
.catch(() => releaseTarget());
|
||||
const listener = await opening;
|
||||
openSignal.throwIfAborted();
|
||||
return listener;
|
||||
}
|
||||
);
|
||||
} catch (err) {
|
||||
retireAcquired();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
logger.info(`Starting ngrok tunnel ${domain} -> http://localhost:${port}.`);
|
||||
let publicUrl: string | null;
|
||||
try {
|
||||
currentListener = await openAsync();
|
||||
publicUrl = currentListener.url();
|
||||
if (!publicUrl) {
|
||||
await closeAsync(currentListener, signal);
|
||||
currentListener = undefined;
|
||||
throw new SystemError(`ngrok tunnel for ${domain} did not return a public URL.`);
|
||||
}
|
||||
} catch (error) {
|
||||
controller.abort();
|
||||
releaseTarget();
|
||||
throw error;
|
||||
}
|
||||
|
||||
const url = publicUrl;
|
||||
|
||||
async function probeAsync(
|
||||
baseUrl: string,
|
||||
{ path, statuses = [200] }: NonNullable<typeof healthCheck>
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
return await withDeviceRunSessionTimeoutAsync(
|
||||
{ name: 'Ngrok tunnel health probe', timeoutMs: 5_000, signal },
|
||||
async probeSignal => {
|
||||
const requestController = new AbortController();
|
||||
try {
|
||||
const response = await turtleFetch(new URL(path, baseUrl).href, 'GET', {
|
||||
retries: 0,
|
||||
redirect: 'manual',
|
||||
shouldThrowOnNotOk: false,
|
||||
headers: { 'ngrok-skip-browser-warning': 'true', 'Cache-Control': 'no-cache' },
|
||||
signal: AbortSignal.any([probeSignal, requestController.signal]),
|
||||
});
|
||||
return !response.headers.has('ngrok-error-code') && statuses.includes(response.status);
|
||||
} finally {
|
||||
requestController.abort();
|
||||
}
|
||||
}
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function superviseAsync(check: NonNullable<typeof healthCheck>): Promise<void> {
|
||||
let failures = 0;
|
||||
let attempts = 0;
|
||||
let localUnhealthy = false;
|
||||
while (
|
||||
await waitAsync(
|
||||
currentListener || localUnhealthy
|
||||
? PROBE_INTERVAL_MS
|
||||
: Math.min(1_000 * 2 ** Math.min(attempts, 5), 30_000),
|
||||
signal
|
||||
)
|
||||
) {
|
||||
await Promise.all([...retiredListeners].map(retired => closeAsync(retired, signal, false)));
|
||||
if (signal.aborted) {
|
||||
return;
|
||||
}
|
||||
if (currentListener && (await probeAsync(url, check))) {
|
||||
if (failures > 0 || attempts > 0 || localUnhealthy) {
|
||||
logger.info(`Ngrok tunnel ${domain} is healthy again.`);
|
||||
}
|
||||
failures = 0;
|
||||
attempts = 0;
|
||||
localUnhealthy = false;
|
||||
continue;
|
||||
}
|
||||
if (signal.aborted) {
|
||||
return;
|
||||
}
|
||||
if (!(await probeAsync(`http://127.0.0.1:${port}`, check))) {
|
||||
if (!localUnhealthy && !signal.aborted) {
|
||||
logger.warn(`Local service on port ${port} is unhealthy; waiting for it to recover.`);
|
||||
}
|
||||
localUnhealthy = true;
|
||||
failures = 0;
|
||||
continue;
|
||||
}
|
||||
localUnhealthy = false;
|
||||
if (currentListener) {
|
||||
failures++;
|
||||
if (failures < FAILURE_THRESHOLD) {
|
||||
continue;
|
||||
}
|
||||
logger.warn(`Ngrok tunnel ${domain} failed ${failures} health probes; reopening it.`);
|
||||
await closeAsync(currentListener, signal);
|
||||
currentListener = undefined;
|
||||
}
|
||||
if (signal.aborted) {
|
||||
return;
|
||||
}
|
||||
attempts++;
|
||||
try {
|
||||
const reopened = await openAsync(/* forceNewSession */ true);
|
||||
if (reopened.url() !== url) {
|
||||
await closeAsync(reopened, signal);
|
||||
throw new SystemError(
|
||||
`Reopened ngrok tunnel for ${domain} returned a different public URL.`
|
||||
);
|
||||
}
|
||||
currentListener = reopened;
|
||||
failures = 0;
|
||||
} catch (err) {
|
||||
if (!signal.aborted && (attempts === 1 || attempts % 5 === 0)) {
|
||||
logger.warn(
|
||||
{ err, attempt: attempts },
|
||||
`Could not reopen ngrok tunnel ${domain}; will retry.`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const supervision = healthCheck
|
||||
? superviseAsync(healthCheck).catch(err => {
|
||||
if (!signal.aborted) {
|
||||
logger.warn({ err }, `Ngrok tunnel supervision stopped for ${domain}.`);
|
||||
}
|
||||
})
|
||||
: Promise.resolve();
|
||||
let stopTask: Promise<void> | undefined;
|
||||
return {
|
||||
url,
|
||||
subdomainId,
|
||||
stopAsync: () =>
|
||||
(stopTask ??= (async () => {
|
||||
controller.abort();
|
||||
await withDeviceRunSessionTimeoutAsync(
|
||||
{ name: `Ngrok tunnel ${domain} stop`, timeoutMs: STOP_TIMEOUT_MS },
|
||||
async stopSignal => {
|
||||
await supervision;
|
||||
if (currentListener) {
|
||||
retiredListeners.add(currentListener);
|
||||
currentListener = undefined;
|
||||
}
|
||||
await Promise.all([pendingOpen?.catch(() => {}), retireListenersAsync(stopSignal)]);
|
||||
await retireListenersAsync(stopSignal);
|
||||
}
|
||||
);
|
||||
releaseTarget();
|
||||
})()),
|
||||
};
|
||||
}
|
||||
|
||||
function waitAsync(ms: number, signal: AbortSignal): Promise<boolean> {
|
||||
if (signal.aborted) {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
return new Promise(resolve => {
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
resolve(false);
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
resolve(true);
|
||||
}, ms);
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
@@ -9,7 +9,9 @@ import {
|
||||
spawnAsync,
|
||||
} from '@expo/steps';
|
||||
import spawn from '@expo/turtle-spawn';
|
||||
import * as ngrok from '@ngrok/ngrok';
|
||||
import { z } from 'zod';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import { createServer } from 'node:net';
|
||||
import path from 'node:path';
|
||||
@@ -522,14 +524,6 @@ export async function fetchWebPreviewTurnArgsAsync(
|
||||
}
|
||||
return args;
|
||||
} catch (err) {
|
||||
if (
|
||||
err instanceof DeviceRunSessionWorkerApiError &&
|
||||
err.code === 'DEVICE_RUN_SESSION_ALREADY_STOPPED'
|
||||
) {
|
||||
logger.info('Device run session was stopped before TURN credentials were fetched.');
|
||||
return [];
|
||||
}
|
||||
|
||||
const error = err instanceof Error ? err : new Error(String(err));
|
||||
Sentry.capture('Could not fetch Cloudflare TURN ICE servers', error, { level: 'warning' });
|
||||
logger.warn(
|
||||
@@ -965,7 +959,63 @@ export async function findAvailablePortAsync(): Promise<number> {
|
||||
return address.port;
|
||||
}
|
||||
|
||||
export { type NgrokTunnelHandle, startNgrokTunnelAsync } from './ngrokTunnel';
|
||||
export type NgrokTunnelHandle = {
|
||||
url: string;
|
||||
subdomainId: string;
|
||||
stopAsync: () => Promise<void>;
|
||||
};
|
||||
|
||||
export async function startNgrokTunnelAsync({
|
||||
port,
|
||||
subdomainPrefix,
|
||||
subdomainId: subdomainIdArg,
|
||||
baseDomain,
|
||||
authtoken,
|
||||
rewriteHostHeader,
|
||||
logger,
|
||||
}: {
|
||||
port: number;
|
||||
subdomainPrefix: string;
|
||||
subdomainId?: string;
|
||||
baseDomain: string;
|
||||
authtoken: string;
|
||||
rewriteHostHeader?: boolean;
|
||||
logger: bunyan;
|
||||
}): Promise<NgrokTunnelHandle> {
|
||||
const subdomainId = subdomainIdArg ?? randomBytes(16).toString('hex');
|
||||
const domain = `${subdomainPrefix}-${subdomainId}.${baseDomain}`;
|
||||
logger.info(`Starting ngrok tunnel ${domain} -> http://localhost:${port}.`);
|
||||
// Run the ngrok agent in-process via the SDK; it keeps the session alive until
|
||||
// the process exits, and the step blocks forever to hold it open.
|
||||
const listener = await ngrok.forward({
|
||||
addr: port,
|
||||
authtoken,
|
||||
domain,
|
||||
...(rewriteHostHeader ? { request_header_add: [`Host:localhost:${port}`] } : {}),
|
||||
});
|
||||
const url = listener.url();
|
||||
if (!url) {
|
||||
await listener.close();
|
||||
throw new SystemError(`ngrok tunnel for ${domain} did not return a public URL.`);
|
||||
}
|
||||
let stopTask: Promise<void> | undefined;
|
||||
return {
|
||||
url,
|
||||
subdomainId,
|
||||
stopAsync: () =>
|
||||
(stopTask ??= (async () => {
|
||||
try {
|
||||
await withDeviceRunSessionTimeoutAsync(
|
||||
{ name: 'Ngrok tunnel stop', timeoutMs: 4_000 },
|
||||
async () => await listener.close()
|
||||
);
|
||||
} catch (error) {
|
||||
logger.warn({ err: error }, `Could not stop ngrok tunnel ${domain}.`);
|
||||
throw error;
|
||||
}
|
||||
})()),
|
||||
};
|
||||
}
|
||||
|
||||
export async function waitForFileAsync<T>({
|
||||
filePath,
|
||||
|
||||
@@ -7,7 +7,6 @@ import { setTimeout } from 'node:timers/promises';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { retryAsync } from './retry';
|
||||
import { waitForWarmSimulatorCleanupAsync } from './warmSimulatorCleanup';
|
||||
|
||||
export type IosSimulatorUuid = string & z.BRAND<'IosSimulatorUuid'>;
|
||||
export type IosSimulatorName = string & z.BRAND<'IosSimulatorName'>;
|
||||
@@ -120,7 +119,6 @@ export namespace IosSimulatorUtils {
|
||||
destinationDeviceName: IosSimulatorName;
|
||||
env: NodeJS.ProcessEnv;
|
||||
}): Promise<void> {
|
||||
await waitForWarmSimulatorCleanupAsync(env);
|
||||
await spawn('xcrun', ['simctl', 'clone', sourceDeviceIdentifier, destinationDeviceName], {
|
||||
env,
|
||||
});
|
||||
@@ -133,7 +131,6 @@ export namespace IosSimulatorUtils {
|
||||
deviceIdentifier: IosSimulatorUuid | IosSimulatorName;
|
||||
env: NodeJS.ProcessEnv;
|
||||
}): Promise<void> {
|
||||
await waitForWarmSimulatorCleanupAsync(env);
|
||||
try {
|
||||
const devices = await getAvailableDevicesAsync({ env, filter: 'available' });
|
||||
const device = devices.find(
|
||||
@@ -234,7 +231,6 @@ export namespace IosSimulatorUtils {
|
||||
env: NodeJS.ProcessEnv;
|
||||
launchdEnvironment?: Record<string, string>;
|
||||
}): Promise<void> {
|
||||
await waitForWarmSimulatorCleanupAsync(env);
|
||||
const bootEnv = { ...env };
|
||||
for (const [name, value] of Object.entries(launchdEnvironment)) {
|
||||
bootEnv[`SIMCTL_CHILD_${name}`] = value;
|
||||
@@ -257,7 +253,6 @@ export namespace IosSimulatorUtils {
|
||||
deviceIdentifier: IosSimulatorUuid | IosSimulatorName;
|
||||
env: NodeJS.ProcessEnv;
|
||||
}): Promise<{ udid: IosSimulatorUuid }> {
|
||||
await waitForWarmSimulatorCleanupAsync(env);
|
||||
const bootstatusResult = await spawn(
|
||||
'xcrun',
|
||||
['simctl', 'bootstatus', deviceIdentifier, '-b'],
|
||||
|
||||
@@ -5,7 +5,6 @@ import path from 'node:path';
|
||||
|
||||
import { IosSimulatorUtils } from '../IosSimulatorUtils';
|
||||
import { retryAsync } from '../retry';
|
||||
import { waitForWarmSimulatorCleanupAsync } from '../warmSimulatorCleanup';
|
||||
|
||||
jest.mock('@expo/turtle-spawn', () => ({
|
||||
__esModule: true,
|
||||
@@ -15,7 +14,6 @@ jest.mock('@expo/turtle-spawn', () => ({
|
||||
jest.mock('../retry', () => ({
|
||||
retryAsync: jest.fn(async fn => await fn(0)),
|
||||
}));
|
||||
jest.mock('../warmSimulatorCleanup');
|
||||
|
||||
const mockedSpawn = jest.mocked(spawn);
|
||||
|
||||
@@ -23,7 +21,6 @@ describe('IosSimulatorUtils', () => {
|
||||
beforeEach(() => {
|
||||
mockedSpawn.mockReset();
|
||||
mockedSpawn.mockResolvedValue({ stdout: '', stderr: '' } as any);
|
||||
jest.mocked(waitForWarmSimulatorCleanupAsync).mockReset().mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
describe(IosSimulatorUtils.getAvailableRuntimesAsync, () => {
|
||||
@@ -154,30 +151,6 @@ describe('IosSimulatorUtils', () => {
|
||||
}) as any);
|
||||
}
|
||||
|
||||
it('waits for warm cleanup before checking device state and writing accessibility prefs', async () => {
|
||||
let finishCleanup: (() => void) | undefined;
|
||||
jest.mocked(waitForWarmSimulatorCleanupAsync).mockImplementationOnce(
|
||||
async () =>
|
||||
await new Promise<void>(resolve => {
|
||||
finishCleanup = resolve;
|
||||
})
|
||||
);
|
||||
mockAvailableDevices([device()]);
|
||||
|
||||
const setup = IosSimulatorUtils.enableAccessibilitySettingsAsync({
|
||||
deviceIdentifier: device().udid as any,
|
||||
env: {},
|
||||
});
|
||||
expect(mockedSpawn).not.toHaveBeenCalled();
|
||||
expect(finishCleanup).toBeDefined();
|
||||
finishCleanup?.();
|
||||
await setup;
|
||||
|
||||
expect(mockedSpawn).toHaveBeenCalledWith('plutil', expect.anything(), {
|
||||
env: {},
|
||||
});
|
||||
});
|
||||
|
||||
it('writes accessibility prefs for an exact shutdown simulator match', async () => {
|
||||
mockAvailableDevices([
|
||||
device({
|
||||
|
||||
@@ -76,7 +76,11 @@ describe(getSshRelayServerUrl, () => {
|
||||
});
|
||||
|
||||
describe(startSshSessionAsync, () => {
|
||||
const config1: SshConnectionConfig = { type: 'upterm-v1', secret: 'secret-1' };
|
||||
const config1: SshConnectionConfig = {
|
||||
type: 'upterm-v1',
|
||||
host: 'relay.expo.dev',
|
||||
secret: 'secret-1',
|
||||
};
|
||||
const config2: SshConnectionConfig = { ...config1, secret: 'secret-2' };
|
||||
const target = { type: 'JOB_RUN', id: 'jr-1' } as const;
|
||||
|
||||
@@ -129,7 +133,7 @@ describe(startSshSessionAsync, () => {
|
||||
|
||||
expect(mutation).toHaveBeenCalledWith(expect.anything(), {
|
||||
target: { type: 'JOB_RUN', id: 'jr-1' },
|
||||
connectionConfig: { type: 'UPTERM_V1', secret: 'secret-1', reconnecting: false },
|
||||
connectionConfig: { ...config1, reconnecting: false, type: 'UPTERM_V1' },
|
||||
sessionSettings: { idleTimeoutSeconds: 900 },
|
||||
});
|
||||
expect(idleTimeoutSeconds).toBe(900);
|
||||
@@ -151,7 +155,7 @@ describe(startSshSessionAsync, () => {
|
||||
|
||||
expect(mutation).toHaveBeenCalledWith(expect.anything(), {
|
||||
target: { type: 'BUILD', id: 'b-1' },
|
||||
connectionConfig: { type: 'UPTERM_V1', secret: 'secret-1', reconnecting: false },
|
||||
connectionConfig: { ...config1, reconnecting: false, type: 'UPTERM_V1' },
|
||||
sessionSettings: { idleTimeoutSeconds: 900 },
|
||||
});
|
||||
});
|
||||
@@ -238,7 +242,7 @@ describe(startSshSessionAsync, () => {
|
||||
);
|
||||
expect(mutation).toHaveBeenLastCalledWith(expect.anything(), {
|
||||
target: { type: 'JOB_RUN', id: 'jr-1' },
|
||||
connectionConfig: { type: 'UPTERM_V1', secret: 'secret-2', reconnecting: false },
|
||||
connectionConfig: { ...config2, reconnecting: false, type: 'UPTERM_V1' },
|
||||
sessionSettings: { idleTimeoutSeconds: 300 },
|
||||
});
|
||||
});
|
||||
@@ -294,7 +298,7 @@ describe(startSshSessionAsync, () => {
|
||||
expect(host.redialAsync).toHaveBeenCalledTimes(1);
|
||||
expect(mutation).toHaveBeenLastCalledWith(expect.anything(), {
|
||||
target: { type: 'JOB_RUN', id: 'jr-1' },
|
||||
connectionConfig: { type: 'UPTERM_V1', secret: 'secret-2', reconnecting: false },
|
||||
connectionConfig: { ...config2, reconnecting: false, type: 'UPTERM_V1' },
|
||||
sessionSettings: { idleTimeoutSeconds: 300 },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,6 +7,7 @@ import { createMockLogger } from '../../__tests__/utils/logger';
|
||||
import { BuildContext } from '../../context';
|
||||
import { sleepAsync } from '../retry';
|
||||
import {
|
||||
connectionConfigFromUptermSession,
|
||||
redactConnectionSecrets,
|
||||
redactSpawnErrorForLog,
|
||||
resolveUptermGcsObjectName,
|
||||
@@ -41,6 +42,49 @@ describe(resolveUptermGcsObjectName, () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe(connectionConfigFromUptermSession, () => {
|
||||
it('parses sessionId and host from session current fields', () => {
|
||||
expect(
|
||||
connectionConfigFromUptermSession({
|
||||
sessionId: 'TOKENabc123',
|
||||
host: 'ssh://relay.expo.dev:22',
|
||||
})
|
||||
).toEqual({
|
||||
type: 'upterm-v1',
|
||||
host: 'relay.expo.dev',
|
||||
secret: 'TOKENabc123',
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts a bare hostname', () => {
|
||||
expect(connectionConfigFromUptermSession({ sessionId: 'tok', host: 'relay.expo.dev' })).toEqual(
|
||||
{
|
||||
type: 'upterm-v1',
|
||||
host: 'relay.expo.dev',
|
||||
secret: 'tok',
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps a non-default port so the CLI can pass it to ssh -p', () => {
|
||||
expect(
|
||||
connectionConfigFromUptermSession({
|
||||
sessionId: 'tok',
|
||||
host: 'ssh://relay.expo.dev:2222',
|
||||
})
|
||||
).toEqual({
|
||||
type: 'upterm-v1',
|
||||
host: 'relay.expo.dev:2222',
|
||||
secret: 'tok',
|
||||
});
|
||||
});
|
||||
|
||||
it('returns null when the host is not a parseable url', () => {
|
||||
expect(connectionConfigFromUptermSession({ sessionId: 'tok', host: 'ssh://' })).toBeNull();
|
||||
expect(connectionConfigFromUptermSession({ sessionId: 'tok', host: 'ssh://[' })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe(redactConnectionSecrets, () => {
|
||||
it('strips the userinfo secret from a connection string', () => {
|
||||
expect(
|
||||
@@ -213,7 +257,11 @@ describe(startUptermHostAsync, () => {
|
||||
relayServerUrl: 'wss://relay.expo.dev',
|
||||
});
|
||||
|
||||
expect(host.connectionConfig).toEqual({ type: 'upterm-v1', secret: 'TOKENx' });
|
||||
expect(host.connectionConfig).toEqual({
|
||||
type: 'upterm-v1',
|
||||
host: 'relay.expo.dev',
|
||||
secret: 'TOKENx',
|
||||
});
|
||||
expect(host.isAlive()).toBe(true);
|
||||
expect(mockedDownloadFile).not.toHaveBeenCalled();
|
||||
expect(mockedSpawn).toHaveBeenCalledWith('upterm', ['version'], {
|
||||
@@ -321,21 +369,6 @@ describe(startUptermHostAsync, () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps polling until upterm reports a session id', async () => {
|
||||
sessionStdout = JSON.stringify({ host: 'ssh://relay.expo.dev:22', clientCount: 0 });
|
||||
mockedSleep.mockImplementationOnce(async () => {
|
||||
sessionStdout = JSON.stringify({
|
||||
sessionId: 'TOKENy',
|
||||
host: 'ssh://relay.expo.dev:22',
|
||||
clientCount: 0,
|
||||
});
|
||||
});
|
||||
|
||||
const host = await startUptermHostAsync(makeCtx(), { relayServerUrl: 'wss://r' });
|
||||
|
||||
expect(host.connectionConfig).toEqual({ type: 'upterm-v1', secret: 'TOKENy' });
|
||||
});
|
||||
|
||||
it('tears down and rethrows when the host never registers with the relay', async () => {
|
||||
jest.useFakeTimers();
|
||||
jest.setSystemTime(0);
|
||||
@@ -387,7 +420,11 @@ describe(startUptermHostAsync, () => {
|
||||
const host = await startUptermHostAsync(makeCtx(), { relayServerUrl: 'wss://r' });
|
||||
const config = await host.redialAsync();
|
||||
|
||||
expect(config).toEqual({ type: 'upterm-v1', secret: 'TOKENx' });
|
||||
expect(config).toEqual({
|
||||
type: 'upterm-v1',
|
||||
host: 'relay.expo.dev',
|
||||
secret: 'TOKENx',
|
||||
});
|
||||
expect(host.connectionConfig).toEqual(config);
|
||||
});
|
||||
|
||||
@@ -425,7 +462,11 @@ describe(startUptermHostAsync, () => {
|
||||
const host = await startUptermHostAsync(makeCtx(), { relayServerUrl: 'wss://r' });
|
||||
hostProcess.catch = () => new Promise<void>(() => {});
|
||||
|
||||
await expect(host.redialAsync()).resolves.toEqual({ type: 'upterm-v1', secret: 'TOKENx' });
|
||||
await expect(host.redialAsync()).resolves.toEqual({
|
||||
type: 'upterm-v1',
|
||||
host: 'relay.expo.dev',
|
||||
secret: 'TOKENx',
|
||||
});
|
||||
expect(mockedSleep).toHaveBeenCalledWith(5_000);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
import spawn from '@expo/turtle-spawn';
|
||||
import fs from 'node:fs/promises';
|
||||
|
||||
import { waitForWarmSimulatorCleanupAsync } from '../warmSimulatorCleanup';
|
||||
|
||||
const STATE_FILE = '/tmp/expo-simulator-startup.json';
|
||||
const STARTUP_SCRIPT = '/usr/local/share/vm-tools/startup.sh';
|
||||
const platform = Object.getOwnPropertyDescriptor(process, 'platform')!;
|
||||
jest.mock('@expo/turtle-spawn');
|
||||
|
||||
async function writeStateAsync(state: object): Promise<void> {
|
||||
await fs.mkdir('/tmp', { recursive: true });
|
||||
await fs.writeFile(STATE_FILE, JSON.stringify({ bootUuid: 'current-boot', ...state }));
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(process, 'platform', { value: 'darwin' });
|
||||
jest.mocked(spawn).mockResolvedValue({ stdout: 'current-boot\n' } as never);
|
||||
});
|
||||
afterEach(() => {
|
||||
Object.defineProperty(process, 'platform', platform);
|
||||
});
|
||||
|
||||
it('continues at once on a VM without warmup', async () => {
|
||||
await expect(waitForWarmSimulatorCleanupAsync({})).resolves.toBeUndefined();
|
||||
expect(spawn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ignores a previous boot cleanup record and reads the current boot only once', async () => {
|
||||
await writeStateAsync({ status: 'disabled', bootUuid: 'old-boot' });
|
||||
let finished = false;
|
||||
const waiting = waitForWarmSimulatorCleanupAsync({}, { pollMs: 5 }).then(() => {
|
||||
finished = true;
|
||||
});
|
||||
await new Promise(resolve => setTimeout(resolve, 30));
|
||||
expect(finished).toBe(false);
|
||||
await writeStateAsync({ status: 'disabled' });
|
||||
await waiting;
|
||||
expect(spawn).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not accept a cleanup record without a boot ID', async () => {
|
||||
await writeStateAsync({ status: 'disabled', bootUuid: undefined });
|
||||
await expect(waitForWarmSimulatorCleanupAsync({}, { timeoutMs: 20, pollMs: 5 })).rejects.toThrow(
|
||||
'Warm Simulator cleanup did not finish'
|
||||
);
|
||||
});
|
||||
|
||||
it.each(['failed', 'empty'])('fails closed when the current boot ID is %s', async mode => {
|
||||
await writeStateAsync({ status: 'disabled' });
|
||||
if (mode === 'failed') {
|
||||
jest.mocked(spawn).mockRejectedValueOnce(new Error('sysctl failed'));
|
||||
} else {
|
||||
jest.mocked(spawn).mockResolvedValueOnce({ stdout: '' } as never);
|
||||
}
|
||||
await expect(waitForWarmSimulatorCleanupAsync({})).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('waits for cleanup when warmup is installed but has not written state yet', async () => {
|
||||
await fs.mkdir('/usr/local/share/vm-tools', { recursive: true });
|
||||
await fs.writeFile(STARTUP_SCRIPT, '');
|
||||
let finished = false;
|
||||
const waiting = waitForWarmSimulatorCleanupAsync({}, { pollMs: 5 }).then(() => {
|
||||
finished = true;
|
||||
});
|
||||
await new Promise(resolve => setTimeout(resolve, 30));
|
||||
expect(finished).toBe(false);
|
||||
await writeStateAsync({ status: 'starting' });
|
||||
await new Promise(resolve => setTimeout(resolve, 30));
|
||||
expect(finished).toBe(false);
|
||||
await writeStateAsync({ status: 'disabled' });
|
||||
await waiting;
|
||||
});
|
||||
|
||||
it('times out when installed warmup never writes state', async () => {
|
||||
await fs.mkdir('/usr/local/share/vm-tools', { recursive: true });
|
||||
await fs.writeFile(STARTUP_SCRIPT, '');
|
||||
await expect(waitForWarmSimulatorCleanupAsync({}, { timeoutMs: 20, pollMs: 5 })).rejects.toThrow(
|
||||
'Warm Simulator cleanup did not finish; the Simulator cannot be used.'
|
||||
);
|
||||
});
|
||||
|
||||
it('waits until the launcher records that cleanup finished', async () => {
|
||||
await writeStateAsync({ status: 'ready' });
|
||||
let finished = false;
|
||||
const waiting = waitForWarmSimulatorCleanupAsync({}, { pollMs: 5 }).then(() => {
|
||||
finished = true;
|
||||
});
|
||||
await new Promise(resolve => setTimeout(resolve, 30));
|
||||
expect(finished).toBe(false);
|
||||
await writeStateAsync({ status: 'stopping' });
|
||||
await new Promise(resolve => setTimeout(resolve, 30));
|
||||
expect(finished).toBe(false);
|
||||
await writeStateAsync({ status: 'disabled' });
|
||||
await waiting;
|
||||
expect(finished).toBe(true);
|
||||
});
|
||||
|
||||
it('fails with the recorded error when cleanup does not finish in time', async () => {
|
||||
await writeStateAsync({ status: 'stopping', error: 'serve-sim did not exit' });
|
||||
await expect(waitForWarmSimulatorCleanupAsync({}, { timeoutMs: 20, pollMs: 5 })).rejects.toThrow(
|
||||
'Warm Simulator cleanup did not finish (serve-sim did not exit); the Simulator cannot be used.'
|
||||
);
|
||||
});
|
||||
|
||||
it('stops waiting when the job is cancelled', async () => {
|
||||
await writeStateAsync({ status: 'stopping' });
|
||||
const controller = new AbortController();
|
||||
const waiting = waitForWarmSimulatorCleanupAsync({}, { pollMs: 5, signal: controller.signal });
|
||||
controller.abort(new Error('cancelled'));
|
||||
await expect(waiting).rejects.toThrow('cancelled');
|
||||
});
|
||||
|
||||
it('does not wait for a job that uses the warm Simulator', async () => {
|
||||
await writeStateAsync({ status: 'claimed' });
|
||||
await expect(
|
||||
waitForWarmSimulatorCleanupAsync({ EAS_USE_WARM_SIMULATOR: '1' }, { timeoutMs: 0 })
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('does nothing outside macOS', async () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'linux' });
|
||||
await writeStateAsync({ status: 'ready' });
|
||||
await expect(waitForWarmSimulatorCleanupAsync({}, { timeoutMs: 0 })).resolves.toBeUndefined();
|
||||
});
|
||||
@@ -37,9 +37,11 @@ const CONNECTION_STARTUP_TIMEOUT_MS = 60_000;
|
||||
const PROCESS_EXIT_TIMEOUT_MS = 5_000;
|
||||
const CLIENT_COUNT_READ_ATTEMPTS = 4;
|
||||
const CLIENT_COUNT_READ_RETRY_MS = 500;
|
||||
const DEFAULT_SSH_PORT = '22';
|
||||
|
||||
export type SshConnectionConfig = {
|
||||
type: 'upterm-v1';
|
||||
host: string;
|
||||
secret: string;
|
||||
};
|
||||
|
||||
@@ -53,10 +55,30 @@ export type UptermHost = {
|
||||
|
||||
const UptermSessionJsonZ = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
host: z.string().min(1),
|
||||
clientCount: z.number().optional(),
|
||||
});
|
||||
type UptermSessionJson = z.infer<typeof UptermSessionJsonZ>;
|
||||
|
||||
export function connectionConfigFromUptermSession(
|
||||
parsed: Pick<UptermSessionJson, 'sessionId' | 'host'>
|
||||
): SshConnectionConfig | null {
|
||||
let host = parsed.host;
|
||||
if (host.includes('://')) {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(host);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
host = url.port && url.port !== DEFAULT_SSH_PORT ? `${url.hostname}:${url.port}` : url.hostname;
|
||||
}
|
||||
if (!host) {
|
||||
return null;
|
||||
}
|
||||
return { type: 'upterm-v1', host, secret: parsed.sessionId };
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip upterm session secrets out of text before it reaches a log or an error message. upterm
|
||||
* prints the session id as the userinfo of the connect line it advertises
|
||||
@@ -174,7 +196,10 @@ async function waitForConnectionConfigAsync(
|
||||
if (adminSocketPath) {
|
||||
const session = await readCurrentSessionJsonAsync(uptermPath, adminSocketPath);
|
||||
if (session) {
|
||||
return { type: 'upterm-v1', secret: session.sessionId };
|
||||
const connectionConfig = connectionConfigFromUptermSession(session);
|
||||
if (connectionConfig) {
|
||||
return connectionConfig;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Date.now() >= deadline) {
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
import { SystemError } from '@expo/eas-build-job';
|
||||
import spawn from '@expo/turtle-spawn';
|
||||
import { existsSync } from 'node:fs';
|
||||
import fs from 'node:fs/promises';
|
||||
import { setTimeout as sleepAsync } from 'node:timers/promises';
|
||||
|
||||
const LAUNCHER_STATE_FILE = '/tmp/expo-simulator-startup.json';
|
||||
const STARTUP_SCRIPT = '/usr/local/share/vm-tools/startup.sh';
|
||||
|
||||
/**
|
||||
* The worker stops warmup in the background for a job that does not use the warm Simulator. Wait
|
||||
* here, before the job changes a Simulator, until the launcher records that its cleanup finished.
|
||||
*/
|
||||
export async function waitForWarmSimulatorCleanupAsync(
|
||||
env: NodeJS.ProcessEnv,
|
||||
{
|
||||
timeoutMs = 150_000,
|
||||
pollMs = 250,
|
||||
signal,
|
||||
}: { timeoutMs?: number; pollMs?: number; signal?: AbortSignal } = {}
|
||||
): Promise<void> {
|
||||
if (process.platform !== 'darwin' || env.EAS_USE_WARM_SIMULATOR === '1') {
|
||||
return;
|
||||
}
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
let bootUuid: string | undefined;
|
||||
for (;;) {
|
||||
signal?.throwIfAborted();
|
||||
let state: { status?: unknown; error?: unknown; bootUuid?: unknown };
|
||||
try {
|
||||
state = JSON.parse(await fs.readFile(LAUNCHER_STATE_FILE, 'utf8'));
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT' && !existsSync(STARTUP_SCRIPT)) {
|
||||
return;
|
||||
}
|
||||
// Warmup may still be loading; only disabled confirms cleanup on an enabled VM.
|
||||
state = {};
|
||||
}
|
||||
if (state.status === 'disabled' && typeof state.bootUuid === 'string') {
|
||||
bootUuid ??= (
|
||||
await spawn('/usr/sbin/sysctl', ['-n', 'kern.bootsessionuuid'], {
|
||||
signal,
|
||||
timeout: Math.max(1, deadline - Date.now()),
|
||||
})
|
||||
).stdout.trim();
|
||||
if (!bootUuid) {
|
||||
throw new SystemError('Could not read the current VM boot ID.');
|
||||
}
|
||||
if (state.bootUuid === bootUuid) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (Date.now() >= deadline) {
|
||||
throw new SystemError(
|
||||
`Warm Simulator cleanup did not finish${typeof state.error === 'string' ? ` (${state.error})` : ''}; the Simulator cannot be used.`
|
||||
);
|
||||
}
|
||||
// The signal is checked at each poll, so a cancelled job stops within one interval.
|
||||
await sleepAsync(pollMs);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,5 @@
|
||||
# create-eas-build-function
|
||||
|
||||
## 27.3.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.2.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.1.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "create-eas-build-function",
|
||||
"version": "27.3.0",
|
||||
"version": "27.1.0",
|
||||
"description": "Create functions for use in EAS Build custom builds.",
|
||||
"keywords": [
|
||||
"expo",
|
||||
@@ -35,7 +35,7 @@
|
||||
"clean": "rimraf ./build/ \"*.tsbuildinfo\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@expo/steps": "27.3.0"
|
||||
"@expo/steps": "27.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/package-manager": "1.9.10",
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
# @expo/downloader
|
||||
|
||||
## 27.3.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.2.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.1.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/downloader",
|
||||
"version": "27.3.0",
|
||||
"version": "27.1.0",
|
||||
"bugs": "https://github.com/expo/eas-cli/issues",
|
||||
"license": "BUSL-1.1",
|
||||
"author": "Expo <[email protected]>",
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
# eas-build-cache-provider
|
||||
|
||||
## 27.3.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.2.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.1.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "eas-build-cache-provider",
|
||||
"version": "27.3.0",
|
||||
"version": "27.1.0",
|
||||
"description": "A build cache provider plugin for the Expo CLI",
|
||||
"homepage": "https://github.com/expo/eas-cli",
|
||||
"bugs": "https://github.com/expo/eas-cli/issues",
|
||||
|
||||
@@ -1,15 +1,5 @@
|
||||
# @expo/eas-build-job
|
||||
|
||||
## 27.3.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- Add optional Observe error context to workflow jobs. ([#4787](https://github.com/expo/eas-cli/pull/4787) by [@AbbanMustafa](https://github.com/AbbanMustafa))
|
||||
|
||||
## 27.2.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.1.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/eas-build-job",
|
||||
"version": "27.3.0",
|
||||
"version": "27.1.0",
|
||||
"bugs": "https://github.com/expo/eas-cli/issues",
|
||||
"license": "MIT",
|
||||
"author": "Expo <[email protected]>",
|
||||
@@ -25,9 +25,9 @@
|
||||
"clean": "rimraf node_modules dist coverage \"*.tsbuildinfo\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@expo/logger": "27.3.0",
|
||||
"@expo/logger": "27.1.0",
|
||||
"@expo/results": "1.0.0",
|
||||
"@expo/turtle-spawn": "27.3.0",
|
||||
"@expo/turtle-spawn": "27.1.0",
|
||||
"joi": "^17.13.1",
|
||||
"semver": "^7.6.2",
|
||||
"zod": "^4.3.5"
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
import { ArchiveSourceType, BuildTrigger, StaticWorkflowInterpolationContextZ } from '../common';
|
||||
import { Generic } from '../generic';
|
||||
|
||||
function createContext() {
|
||||
return {
|
||||
after: {},
|
||||
needs: {},
|
||||
workflow: {
|
||||
id: 'workflow-id',
|
||||
name: 'Investigate error',
|
||||
filename: 'observe.yml',
|
||||
url: 'https://expo.dev/accounts/example/workflows/workflow-id',
|
||||
},
|
||||
app: { id: '123e4567-e89b-42d3-a456-426614174000', slug: 'example' },
|
||||
account: { id: 'account-id', name: 'example' },
|
||||
observe: {
|
||||
event: {
|
||||
id: '123e4567-e89b-42d3-a456-426614174001',
|
||||
type: 'new_error' as const,
|
||||
occurredAt: '2026-10-29T12:00:00.000Z',
|
||||
appId: '123e4567-e89b-42d3-a456-426614174000',
|
||||
fingerprint: { value: 'error-fingerprint', version: 'v1' },
|
||||
severity: 'fatal' as const,
|
||||
environment: 'production',
|
||||
platform: 'ios' as const,
|
||||
deviceOs: 'iOS',
|
||||
exception: { type: 'Error', message: 'Example error' },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('Observe workflow context', () => {
|
||||
it('preserves the event when validating a generic job', () => {
|
||||
const context = createContext();
|
||||
const job = {
|
||||
projectArchive: { type: ArchiveSourceType.GIT, gitCommitHash: 'abc123', gitRef: null },
|
||||
steps: [{ run: 'echo "${{ observe.event.exception.message }}"', shell: 'sh' }],
|
||||
secrets: { robotAccessToken: 'token', environmentSecrets: [] },
|
||||
expoDevUrl: context.workflow.url,
|
||||
builderEnvironment: { image: 'ubuntu', env: {} },
|
||||
triggeredBy: BuildTrigger.GIT_BASED_INTEGRATION,
|
||||
appId: context.app.id,
|
||||
initiatingUserId: '123e4567-e89b-42d3-a456-426614174002',
|
||||
workflowInterpolationContext: context,
|
||||
};
|
||||
|
||||
const parsed = Generic.JobZ.parse(job);
|
||||
|
||||
expect(parsed.workflowInterpolationContext).toEqual(context);
|
||||
});
|
||||
|
||||
it('accepts nullable event metadata and an omitted device OS', () => {
|
||||
const context = createContext();
|
||||
const nullableContext = {
|
||||
...context,
|
||||
observe: {
|
||||
event: {
|
||||
...context.observe.event,
|
||||
fingerprint: { value: 'error-fingerprint', version: null },
|
||||
severity: 'error',
|
||||
environment: null,
|
||||
platform: null,
|
||||
deviceOs: undefined,
|
||||
exception: { type: null, message: null },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
expect(StaticWorkflowInterpolationContextZ.parse(nullableContext)).toEqual(nullableContext);
|
||||
});
|
||||
|
||||
it('preserves additional event fields from a newer producer', () => {
|
||||
const context = createContext();
|
||||
const extendedContext = {
|
||||
...context,
|
||||
observe: {
|
||||
...context.observe,
|
||||
event: {
|
||||
...context.observe.event,
|
||||
additionalMetadata: 'future value',
|
||||
exception: { ...context.observe.event.exception, stacktrace: 'future stack trace' },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
expect(StaticWorkflowInterpolationContextZ.parse(extendedContext)).toEqual(extendedContext);
|
||||
});
|
||||
|
||||
it('rejects an Observe context without an event', () => {
|
||||
expect(
|
||||
StaticWorkflowInterpolationContextZ.safeParse({ ...createContext(), observe: {} }).success
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -344,24 +344,6 @@ const SentryContextZ = z.looseObject({
|
||||
resolution_type: z.string().optional(),
|
||||
});
|
||||
|
||||
const ObserveContextZ = z.looseObject({
|
||||
event: z.looseObject({
|
||||
id: z.uuid(),
|
||||
type: z.literal('new_error'),
|
||||
occurredAt: z.iso.datetime(),
|
||||
appId: z.uuid(),
|
||||
fingerprint: z.looseObject({
|
||||
value: z.string().min(1),
|
||||
version: z.string().min(1).nullable(),
|
||||
}),
|
||||
severity: z.enum(['fatal', 'error']),
|
||||
environment: z.string().nullable(),
|
||||
platform: z.enum(['ios', 'android']).nullable(),
|
||||
deviceOs: z.string().optional(),
|
||||
exception: z.looseObject({ type: z.string().nullable(), message: z.string().nullable() }),
|
||||
}),
|
||||
});
|
||||
|
||||
export const StaticWorkflowInterpolationContextZ = z.object({
|
||||
after: z.record(
|
||||
z.string(),
|
||||
@@ -399,7 +381,6 @@ export const StaticWorkflowInterpolationContextZ = z.object({
|
||||
app_store_connect: AppStoreConnectContextZ.optional(),
|
||||
// We need to .optional() to support jobs that are not triggered by a Sentry event.
|
||||
sentry: SentryContextZ.optional(),
|
||||
observe: ObserveContextZ.optional(),
|
||||
});
|
||||
|
||||
export type StaticWorkflowInterpolationContext = z.infer<
|
||||
|
||||
@@ -1,24 +1,5 @@
|
||||
# eas-cli
|
||||
|
||||
## 27.3.0
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Bump `@expo/apple-utils` to `2.3.0` to fix iOS capability sync when App Store Connect rejects enabling, disabling or changing a capability. ([#4790](https://github.com/expo/eas-cli/pull/4790) by [@douglowder](https://github.com/douglowder))
|
||||
- Keep already linked App Groups, Merchant IDs and iCloud containers when capability sync links another identifier. ([#4584](https://github.com/expo/eas-cli/pull/4584) by [@ceydaakin](https://github.com/ceydaakin))
|
||||
|
||||
## 27.2.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- Add an experiment that suggests Expo Update to coding agents after a build when the Free plan account is within 5 builds of the platform limit. ([#4758](https://github.com/expo/eas-cli/pull/4758) by [@williamgrosset](https://github.com/williamgrosset))
|
||||
- Add `eas observe:traces` to list request trace spans (or a summary of span names and counts), `eas observe:trace` to display one trace as a span tree, and span rows in the `eas observe:session` timeline. ([#4772](https://github.com/expo/eas-cli/pull/4772) by [@kadikraman](https://github.com/kadikraman))
|
||||
- Show a one-time Expo Simulators hint after a successful build. ([#4768](https://github.com/expo/eas-cli/pull/4768) by [@FiberJW](https://github.com/FiberJW))
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Remove the Free plan build limit guidance experiment for coding agents from `eas build`. ([#4757](https://github.com/expo/eas-cli/pull/4757) by [@williamgrosset](https://github.com/williamgrosset))
|
||||
|
||||
## 27.1.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
+146
-221
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "eas-cli",
|
||||
"version": "27.3.0",
|
||||
"version": "27.1.0",
|
||||
"description": "EAS command line tool",
|
||||
"keywords": [
|
||||
"cli",
|
||||
@@ -44,16 +44,16 @@
|
||||
"copy-new-templates": "rimraf build/commandUtils/new/templates && mkdir -p build/commandUtils/new && cp -r src/commandUtils/new/templates build/commandUtils/new"
|
||||
},
|
||||
"dependencies": {
|
||||
"@expo/apple-utils": "2.3.0",
|
||||
"@expo/apple-utils": "2.2.1",
|
||||
"@expo/code-signing-certificates": "0.0.5",
|
||||
"@expo/config": "55.0.10",
|
||||
"@expo/config-plugins": "55.0.7",
|
||||
"@expo/eas-build-job": "27.3.0",
|
||||
"@expo/eas-json": "27.3.0",
|
||||
"@expo/eas-build-job": "27.1.0",
|
||||
"@expo/eas-json": "27.1.0",
|
||||
"@expo/env": "^1.0.0",
|
||||
"@expo/experimentation": "0.0.5",
|
||||
"@expo/json-file": "8.3.3",
|
||||
"@expo/logger": "27.3.0",
|
||||
"@expo/logger": "27.1.0",
|
||||
"@expo/multipart-body-parser": "2.0.0",
|
||||
"@expo/osascript": "2.1.4",
|
||||
"@expo/package-manager": "1.9.10",
|
||||
@@ -65,7 +65,7 @@
|
||||
"@expo/results": "1.0.0",
|
||||
"@expo/rudder-sdk-node": "1.1.1",
|
||||
"@expo/spawn-async": "1.7.2",
|
||||
"@expo/steps": "27.3.0",
|
||||
"@expo/steps": "27.1.0",
|
||||
"@expo/timeago.js": "1.0.0",
|
||||
"@oclif/core": "^4.8.3",
|
||||
"@oclif/plugin-autocomplete": "^3.2.40",
|
||||
|
||||
@@ -71,7 +71,6 @@ export enum BuildEvent {
|
||||
BUILD_REQUEST_FAIL = 'build cli build request fail',
|
||||
FREE_TIER_LIMIT_CHECKOUT_PROMPT = 'build cli free tier limit checkout prompt',
|
||||
FREE_TIER_NEAR_LIMIT_AGENT_UPDATES_TIP = 'build cli free tier near limit agent updates tip',
|
||||
SIMULATORS_LAUNCH_HINT_SHOWN = 'build cli simulators launch hint shown',
|
||||
|
||||
BUILD_STATUS_COMMAND = 'build cli build status',
|
||||
|
||||
|
||||
@@ -143,7 +143,6 @@ export async function runBuildAndSubmitAsync({
|
||||
}): Promise<{
|
||||
buildIds: string[];
|
||||
buildProfiles?: ProfileData<'build'>[];
|
||||
builds?: MaybeBuildFragment[];
|
||||
}> {
|
||||
await vcsClient.ensureRepoExistsAsync();
|
||||
await ensureRepoIsCleanAsync(vcsClient, flags.nonInteractive);
|
||||
@@ -381,7 +380,6 @@ export async function runBuildAndSubmitAsync({
|
||||
return {
|
||||
buildIds: startedBuilds.map(({ build }) => build.id),
|
||||
buildProfiles,
|
||||
builds,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
import { boolish } from 'getenv';
|
||||
|
||||
import { Analytics, BuildEvent } from '../analytics/AnalyticsManager';
|
||||
import { createGraphqlClient } from '../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
import { UserPreferenceMutation } from '../graphql/mutations/UserPreferenceMutation';
|
||||
import { UserPreferenceQuery } from '../graphql/queries/UserPreferenceQuery';
|
||||
import Log, { link } from '../log';
|
||||
import { LoggedInAuthenticationInfo } from '../user/SessionManager';
|
||||
import { Actor } from '../user/User';
|
||||
|
||||
const SIMULATORS_LAUNCH_AT = new Date('2026-11-05T18:00:00Z');
|
||||
const SIMULATORS_LAUNCH_HINT_PREFERENCE_KEY = 'simulators-launch-cli-hint-seen';
|
||||
const REQUEST_TIMEOUT_MS = 3000;
|
||||
const SIMULATORS_QUICKSTART_URL =
|
||||
'https://docs.expo.dev/preview/simulators/get-started/?utm_source=eas-cli&utm_medium=cli&utm_campaign=simulators-launch';
|
||||
|
||||
export async function maybeShowSimulatorsLaunchHintAsync(
|
||||
authenticationInfo: LoggedInAuthenticationInfo,
|
||||
analytics: Analytics,
|
||||
{ actor, nonInteractive }: { actor: Actor; nonInteractive: boolean }
|
||||
): Promise<void> {
|
||||
if (
|
||||
nonInteractive ||
|
||||
boolish('CI', false) ||
|
||||
Date.now() < SIMULATORS_LAUNCH_AT.getTime() ||
|
||||
(actor.__typename !== 'User' && actor.__typename !== 'SSOUser')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const graphqlClient = createGraphqlClient(authenticationInfo, {
|
||||
requestTimeoutMs: REQUEST_TIMEOUT_MS,
|
||||
});
|
||||
const value = await UserPreferenceQuery.getValueAsync(
|
||||
graphqlClient,
|
||||
SIMULATORS_LAUNCH_HINT_PREFERENCE_KEY
|
||||
);
|
||||
if (value && typeof value === 'object' && 'isDismissed' in value && value.isDismissed) {
|
||||
return;
|
||||
}
|
||||
Log.newLine();
|
||||
Log.log(
|
||||
`✨ New: run your build in Expo Simulators, cloud Android and iOS simulators for you and your agents. ${link(SIMULATORS_QUICKSTART_URL)}`
|
||||
);
|
||||
analytics.logEvent(BuildEvent.SIMULATORS_LAUNCH_HINT_SHOWN, {});
|
||||
await UserPreferenceMutation.setAsync(graphqlClient, SIMULATORS_LAUNCH_HINT_PREFERENCE_KEY, {
|
||||
isDismissed: true,
|
||||
});
|
||||
} catch (error) {
|
||||
Log.debug('Failed to show the Expo Simulators hint', error);
|
||||
}
|
||||
}
|
||||
@@ -9,13 +9,12 @@ import path from 'path';
|
||||
|
||||
import { LocalBuildMode } from '../../build/local';
|
||||
import { BuildFlags, runBuildAndSubmitAsync } from '../../build/runBuildAndSubmit';
|
||||
import { maybeShowSimulatorsLaunchHintAsync } from '../../build/simulatorsLaunchHint';
|
||||
import EasCommand from '../../commandUtils/EasCommand';
|
||||
import {
|
||||
EasNonInteractiveAndJsonFlags,
|
||||
resolveNonInteractiveAndJsonFlags,
|
||||
} from '../../commandUtils/flags';
|
||||
import { BuildStatus, StatuspageServiceName } from '../../graphql/generated';
|
||||
import { StatuspageServiceName } from '../../graphql/generated';
|
||||
import Log, { link } from '../../log';
|
||||
import { RequestedPlatform, selectRequestedPlatformAsync } from '../../platform';
|
||||
import { selectAsync } from '../../prompts';
|
||||
@@ -177,7 +176,7 @@ export default class Build extends EasCommand {
|
||||
|
||||
const flagsWithPlatform = await this.ensurePlatformSelectedAsync(flags);
|
||||
|
||||
const { buildProfiles, builds } = await runBuildAndSubmitAsync({
|
||||
const { buildProfiles } = await runBuildAndSubmitAsync({
|
||||
graphqlClient,
|
||||
analytics,
|
||||
vcsClient,
|
||||
@@ -193,13 +192,6 @@ export default class Build extends EasCommand {
|
||||
buildProfiles,
|
||||
nonInteractive: flags.nonInteractive,
|
||||
});
|
||||
|
||||
if (builds?.some(build => build?.status === BuildStatus.Finished)) {
|
||||
await maybeShowSimulatorsLaunchHintAsync(authenticationInfo, analytics, {
|
||||
actor,
|
||||
nonInteractive: flags.nonInteractive,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private sanitizeFlags(
|
||||
|
||||
@@ -4,6 +4,7 @@ import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { ExpoGraphqlClient } from '../../../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
import * as fetchModule from '../../../fetch';
|
||||
import {
|
||||
AppPlatform,
|
||||
DeviceRunSessionByIdQuery,
|
||||
@@ -13,11 +14,16 @@ import {
|
||||
} from '../../../graphql/generated';
|
||||
import { DeviceRunSessionQuery } from '../../../graphql/queries/DeviceRunSessionQuery';
|
||||
import Log from '../../../log';
|
||||
import { loadSimulatorEnvAsync } from '../../../simulator/env';
|
||||
import { ora } from '../../../ora';
|
||||
import { EAS_SIMULATOR_SESSION_ID, loadSimulatorEnvAsync } from '../../../simulator/env';
|
||||
import * as controlSession from '../../../simulator/controlSession';
|
||||
import { runControlMenuAsync } from '../../../simulator/controlInteractive';
|
||||
import { ControlPromptCancelledError } from '../../../simulator/controlPrompts';
|
||||
import {
|
||||
HostActionCatalog,
|
||||
HostActionResult,
|
||||
connectHostActionsAsync,
|
||||
fetchHostActionDeviceAsync,
|
||||
} from '../../../simulator/hostActions';
|
||||
import { enableJsonOutput, printJsonOnlyOutput } from '../../../utils/json';
|
||||
import SimulatorControl from '../control';
|
||||
@@ -31,6 +37,7 @@ jest.mock('../../../simulator/env', () => ({
|
||||
jest.mock('../../../simulator/hostActions', () => ({
|
||||
...jest.requireActual('../../../simulator/hostActions'),
|
||||
connectHostActionsAsync: jest.fn(),
|
||||
fetchHostActionDeviceAsync: jest.fn(),
|
||||
}));
|
||||
jest.mock('../../../ora', () => ({
|
||||
ora: jest.fn(() => {
|
||||
@@ -48,6 +55,7 @@ jest.mock('fs-extra', () => {
|
||||
const actual = jest.requireActual<typeof import('fs-extra')>('fs-extra');
|
||||
return { ...actual, stat: jest.fn(actual.stat) };
|
||||
});
|
||||
jest.mock('../../../simulator/controlInteractive');
|
||||
|
||||
type DeviceRunSessionById = DeviceRunSessionByIdQuery['deviceRunSessions']['byId'];
|
||||
|
||||
@@ -107,6 +115,7 @@ describe(SimulatorControl, () => {
|
||||
let actionResult: HostActionResult;
|
||||
let served: HostActionCatalog;
|
||||
let tmpDir: string;
|
||||
let connectionController: AbortController;
|
||||
const requestAsync = jest.fn(
|
||||
async (action: string, params: Record<string, unknown> = {}): Promise<HostActionResult> => {
|
||||
switch (action) {
|
||||
@@ -129,7 +138,17 @@ describe(SimulatorControl, () => {
|
||||
jest.clearAllMocks();
|
||||
jest.mocked(loadSimulatorEnvAsync).mockResolvedValue();
|
||||
mockByIdAsync.mockResolvedValue(makeDeviceRunSession());
|
||||
mockConnectHostActionsAsync.mockResolvedValue({ requestAsync, close });
|
||||
jest
|
||||
.mocked(fetchHostActionDeviceAsync)
|
||||
.mockResolvedValue({ udid: 'simulator-udid', name: 'iPhone 17 Pro', runtime: 'iOS-26-4' });
|
||||
connectionController = new AbortController();
|
||||
mockConnectHostActionsAsync.mockResolvedValue({
|
||||
requestAsync,
|
||||
close,
|
||||
udid: 'simulator-udid',
|
||||
signal: connectionController.signal,
|
||||
});
|
||||
jest.mocked(runControlMenuAsync).mockResolvedValue(undefined);
|
||||
actionResult = ok('off\n');
|
||||
served = catalog;
|
||||
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'simulator-control-'));
|
||||
@@ -153,6 +172,194 @@ describe(SimulatorControl, () => {
|
||||
return requestAsync.mock.calls.filter(([action]) => action !== 'actions.describe');
|
||||
}
|
||||
|
||||
async function writeImportAsync(actions: unknown[]): Promise<string> {
|
||||
const filePath = path.join(tmpDir, 'control.json');
|
||||
await fs.writeJson(filePath, { version: 1, actions });
|
||||
return filePath;
|
||||
}
|
||||
|
||||
it('imports an ordered config without prompts over the existing connection', async () => {
|
||||
const filePath = await writeImportAsync([
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'off' } },
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'on' } },
|
||||
]);
|
||||
await createCommand([
|
||||
'--import',
|
||||
filePath,
|
||||
'--id',
|
||||
'session-123',
|
||||
'--non-interactive',
|
||||
]).runAsync();
|
||||
expect(actionRequests()).toEqual([
|
||||
['hardwareKeyboard.set', { value: 'off' }],
|
||||
['hardwareKeyboard.set', { value: 'on' }],
|
||||
]);
|
||||
expect(mockConnectHostActionsAsync).toHaveBeenCalledTimes(1);
|
||||
expect(runControlMenuAsync).not.toHaveBeenCalled();
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
expect(Log.log).toHaveBeenCalledWith(expect.stringContaining('iPhone 17 Pro · iOS 26.4'));
|
||||
expect(Log.log).toHaveBeenCalledWith(' off');
|
||||
const spinner = jest.mocked(ora).mock.results[1].value;
|
||||
expect(spinner.start).toHaveBeenCalledWith('[1/2] hardwareKeyboard.set');
|
||||
expect(spinner.start).toHaveBeenCalledWith('[2/2] hardwareKeyboard.set');
|
||||
expect(Log.succeed).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Import complete · 2 actions')
|
||||
);
|
||||
});
|
||||
|
||||
it('prints one JSON result for a successful imported batch', async () => {
|
||||
const filePath = await writeImportAsync([
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'off' } },
|
||||
]);
|
||||
actionResult = ok('{"enabled":false}\n');
|
||||
await createCommand(['--import', filePath, '--id', 'session-123', '--json']).runAsync();
|
||||
expect(mockPrintJsonOnlyOutput).toHaveBeenCalledTimes(1);
|
||||
expect(mockPrintJsonOnlyOutput).toHaveBeenCalledWith({
|
||||
id: 'session-123',
|
||||
session: expect.objectContaining({
|
||||
id: 'session-123',
|
||||
device: { udid: 'simulator-udid', name: 'iPhone 17 Pro', runtime: 'iOS-26-4' },
|
||||
}),
|
||||
config: filePath,
|
||||
results: [{ action: 'hardwareKeyboard.set', output: { enabled: false }, file: null }],
|
||||
});
|
||||
expect(runControlMenuAsync).not.toHaveBeenCalled();
|
||||
expect(ora).toHaveBeenCalledTimes(1);
|
||||
expect(Log.log).not.toHaveBeenCalled();
|
||||
expect(Log.succeed).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('retains completed results and failure metadata in JSON and stops the imported batch', async () => {
|
||||
const filePath = await writeImportAsync([
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'off' } },
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'on' } },
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'off' } },
|
||||
]);
|
||||
requestAsync
|
||||
.mockImplementationOnce(async () => ok(JSON.stringify(served)))
|
||||
.mockResolvedValueOnce(ok('first completed'))
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: 'Permission denied', exitCode: 1 });
|
||||
const previous = process.exitCode;
|
||||
try {
|
||||
await createCommand(['--import', filePath, '--id', 'session-123', '--json']).runAsync();
|
||||
expect(process.exitCode).toBe(1);
|
||||
expect(mockPrintJsonOnlyOutput).toHaveBeenCalledWith({
|
||||
id: 'session-123',
|
||||
session: expect.objectContaining({
|
||||
id: 'session-123',
|
||||
device: { udid: 'simulator-udid', name: 'iPhone 17 Pro', runtime: 'iOS-26-4' },
|
||||
}),
|
||||
config: filePath,
|
||||
results: [{ action: 'hardwareKeyboard.set', output: 'first completed', file: null }],
|
||||
error: {
|
||||
step: 2,
|
||||
action: 'hardwareKeyboard.set',
|
||||
message: expect.stringContaining('Permission denied'),
|
||||
},
|
||||
});
|
||||
expect(actionRequests()).toHaveLength(2);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
process.exitCode = previous;
|
||||
}
|
||||
});
|
||||
|
||||
it('preflights every imported step before running the first action', async () => {
|
||||
const filePath = await writeImportAsync([
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'off' } },
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'invalid' } },
|
||||
]);
|
||||
await expect(
|
||||
createCommand(['--import', filePath, '--id', 'session-123']).runAsync()
|
||||
).rejects.toThrow('Config step 2');
|
||||
expect(actionRequests()).toEqual([]);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
expect(jest.mocked(ora).mock.results[1].value.fail).toHaveBeenCalledWith(
|
||||
'Validation failed. No actions were run.'
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ args: ['hardwareKeyboard.set', 'off'] },
|
||||
{ args: ['--list'] },
|
||||
{ args: ['--output', './out.png'] },
|
||||
])('rejects conflicting import options before connecting: %j', async ({ args }) => {
|
||||
await expect(
|
||||
createCommand(['--import', './control.json', '--id', 'session-123', ...args]).runAsync()
|
||||
).rejects.toThrow('--import cannot be combined');
|
||||
expect(mockByIdAsync).not.toHaveBeenCalled();
|
||||
expect(mockConnectHostActionsAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses Android imports before connecting or reading the config file', async () => {
|
||||
mockByIdAsync.mockResolvedValue(makeDeviceRunSession({ platform: AppPlatform.Android }));
|
||||
await expect(
|
||||
createCommand(['--import', './missing.json', '--id', 'session-123']).runAsync()
|
||||
).rejects.toThrow('not supported yet');
|
||||
expect(mockConnectHostActionsAsync).not.toHaveBeenCalled();
|
||||
expect(runControlMenuAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('prints completed steps before a non-JSON import failure', async () => {
|
||||
const filePath = await writeImportAsync([
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'off' } },
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'on' } },
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'off' } },
|
||||
]);
|
||||
requestAsync
|
||||
.mockImplementationOnce(async () => ok(JSON.stringify(served)))
|
||||
.mockResolvedValueOnce(ok('first done'))
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: 'Native action failed', exitCode: 1 });
|
||||
await expect(
|
||||
createCommand(['--import', filePath, '--id', 'session-123']).runAsync()
|
||||
).rejects.toThrow('Config step 2');
|
||||
expect(Log.log).toHaveBeenCalledWith(' first done');
|
||||
expect(Log.log).toHaveBeenCalledWith('1 completed · 1 failed · 1 skipped');
|
||||
expect(Log.gray).toHaveBeenCalledWith(' [3/3] hardwareKeyboard.set skipped');
|
||||
expect(actionRequests()).toHaveLength(2);
|
||||
expect(runControlMenuAsync).not.toHaveBeenCalled();
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('downloads config-relative outputs and reports each saved file', async () => {
|
||||
const filePath = await writeImportAsync([
|
||||
{ action: 'screenshot.capture', output: './shot.png' },
|
||||
]);
|
||||
actionResult = ok('/remote/screenshot.png');
|
||||
await createCommand(['--import', filePath, '--id', 'session-123']).runAsync();
|
||||
const savedPath = path.join(tmpDir, 'shot.png');
|
||||
expect(await fs.readFile(savedPath, 'utf8')).toBe('png bytes');
|
||||
expect(Log.log).toHaveBeenCalledWith(` Saved: ${savedPath}`);
|
||||
expect(Log.gray).toHaveBeenCalledWith(` Output: ${savedPath}`);
|
||||
expect(Log.gray).toHaveBeenCalledWith(
|
||||
'Explicit output files are overwritten; directory outputs use simulator filenames and fail if the file exists.'
|
||||
);
|
||||
expect(jest.mocked(Log.gray).mock.invocationCallOrder[0]).toBeLessThan(
|
||||
requestAsync.mock.invocationCallOrder[1]
|
||||
);
|
||||
});
|
||||
|
||||
it('reports completion for actions with empty output', async () => {
|
||||
const filePath = await writeImportAsync([
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'off' } },
|
||||
]);
|
||||
actionResult = ok('');
|
||||
await createCommand(['--import', filePath, '--id', 'session-123']).runAsync();
|
||||
expect(jest.mocked(ora).mock.results[1].value.succeed).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/^\[1\/1\] hardwareKeyboard\.set /)
|
||||
);
|
||||
});
|
||||
|
||||
it('formats structured results without opening a picker', async () => {
|
||||
const filePath = await writeImportAsync([
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'off' } },
|
||||
]);
|
||||
actionResult = ok('{"text":"Imported text"}');
|
||||
await createCommand(['--import', filePath, '--id', 'session-123']).runAsync();
|
||||
expect(Log.log).toHaveBeenCalledWith(' {\n "text": "Imported text"\n }');
|
||||
expect(runControlMenuAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([['--id='], ['--id', '']])('refuses an empty session ID in %j', async (...flags) => {
|
||||
const env = jest.replaceProperty(process, 'env', {
|
||||
...process.env,
|
||||
@@ -186,6 +393,7 @@ describe(SimulatorControl, () => {
|
||||
it('runs an action from the catalog with its values and prints the output', async () => {
|
||||
await createCommand(['hardwareKeyboard.set', 'off', '--id', 'session-123']).runAsync();
|
||||
|
||||
expect(fetchHostActionDeviceAsync).not.toHaveBeenCalled();
|
||||
expect(mockByIdAsync).toHaveBeenCalledWith(graphqlClient, 'session-123');
|
||||
expect(mockConnectHostActionsAsync).toHaveBeenCalledWith({
|
||||
apiUrl: 'https://sim.example.test',
|
||||
@@ -196,8 +404,8 @@ describe(SimulatorControl, () => {
|
||||
expect(close).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([false, true])('lists the actions of the session with --list=%s', async list => {
|
||||
await createCommand([...(list ? ['--list'] : []), '--id', 'session-123']).runAsync();
|
||||
it('lists the actions of the session', async () => {
|
||||
await createCommand(['--list', '--id', 'session-123']).runAsync();
|
||||
|
||||
const lines = jest.mocked(Log.log).mock.calls.map(([line]) => String(line));
|
||||
expect(lines.pop()).toBe('For action usage: eas simulator:control <action> --help');
|
||||
@@ -205,6 +413,7 @@ describe(SimulatorControl, () => {
|
||||
Object.keys(catalog).sort()
|
||||
);
|
||||
expect(actionRequests()).toEqual([]);
|
||||
expect(fetchHostActionDeviceAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(['--help', '-h'])('shows action help with %s without running the action', async help => {
|
||||
@@ -278,12 +487,45 @@ describe(SimulatorControl, () => {
|
||||
expect(mockEnableJsonOutput).toHaveBeenCalled();
|
||||
expect(mockPrintJsonOnlyOutput).toHaveBeenCalledWith({
|
||||
id: 'session-123',
|
||||
session: expect.objectContaining({
|
||||
id: 'session-123',
|
||||
device: expect.objectContaining({ udid: 'simulator-udid' }),
|
||||
}),
|
||||
action: 'permissions.list',
|
||||
output: { voiceover: 'off' },
|
||||
file: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('prints plain text as a JSON string and lists a catalog as JSON without opening the menu', async () => {
|
||||
await createCommand([
|
||||
'hardwareKeyboard.set',
|
||||
'off',
|
||||
'--id',
|
||||
'session-123',
|
||||
'--json',
|
||||
]).runAsync();
|
||||
expect(mockPrintJsonOnlyOutput).toHaveBeenCalledWith({
|
||||
id: 'session-123',
|
||||
session: expect.objectContaining({
|
||||
id: 'session-123',
|
||||
project: '@testuser/testapp',
|
||||
device: { udid: 'simulator-udid', name: 'iPhone 17 Pro', runtime: 'iOS-26-4' },
|
||||
}),
|
||||
action: 'hardwareKeyboard.set',
|
||||
output: 'off',
|
||||
file: null,
|
||||
});
|
||||
mockPrintJsonOnlyOutput.mockClear();
|
||||
jest.mocked(fetchHostActionDeviceAsync).mockClear();
|
||||
await createCommand(['--list', '--id', 'session-123', '--json']).runAsync();
|
||||
expect(mockPrintJsonOnlyOutput).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ 'hardwareKeyboard.set': catalog['hardwareKeyboard.set'] })
|
||||
);
|
||||
expect(fetchHostActionDeviceAsync).not.toHaveBeenCalled();
|
||||
expect(runControlMenuAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uploads a local file for an action that takes one and removes it after', async () => {
|
||||
const localFile = path.join(tmpDir, 'MyApp.ipa');
|
||||
await fs.writeFile(localFile, 'app bytes');
|
||||
@@ -522,12 +764,54 @@ describe(SimulatorControl, () => {
|
||||
|
||||
it('refuses an action that the session does not list', async () => {
|
||||
await expect(createCommand(['server.kill', '--id', 'session-123']).runAsync()).rejects.toThrow(
|
||||
'Unknown simulator action "server.kill". Run `eas simulator:control` to see the actions.'
|
||||
'Unknown simulator action "server.kill". Run `eas simulator:control --list` to see the actions.'
|
||||
);
|
||||
expect(actionRequests()).toEqual([]);
|
||||
expect(close).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('opens the interactive menu with one connection and catalog', async () => {
|
||||
await createCommand(['--id', 'session-123']).runAsync();
|
||||
expect(runControlMenuAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
catalog,
|
||||
runActionAsync: expect.any(Function),
|
||||
signal: expect.any(AbortSignal),
|
||||
})
|
||||
);
|
||||
expect(mockConnectHostActionsAsync).toHaveBeenCalledTimes(1);
|
||||
expect(requestAsync).toHaveBeenCalledTimes(1);
|
||||
expect(actionRequests()).toEqual([]);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each(['--json', '--non-interactive'])('requires an action in scripted mode %s', async flag => {
|
||||
await expect(createCommand(['--id', 'session-123', flag]).runAsync()).rejects.toThrow(
|
||||
'No action provided.'
|
||||
);
|
||||
expect(mockByIdAsync).not.toHaveBeenCalled();
|
||||
expect(runControlMenuAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('requires an action without a TTY before it loads the session', async () => {
|
||||
process.stdin.isTTY = false;
|
||||
try {
|
||||
await expect(createCommand(['--id', 'session-123']).runAsync()).rejects.toThrow(
|
||||
'No action provided.'
|
||||
);
|
||||
expect(mockByIdAsync).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
process.stdin.isTTY = true;
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects --output without an action before connecting', async () => {
|
||||
await expect(
|
||||
createCommand(['--id', 'session-123', '--output', './out.png']).runAsync()
|
||||
).rejects.toThrow('--output requires an action');
|
||||
expect(mockConnectHostActionsAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('closes an established connection when catalog setup fails', async () => {
|
||||
requestAsync.mockImplementationOnce(async () => ok('not a catalog'));
|
||||
await expect(createCommand(['--list', '--id', 'session-123']).runAsync()).rejects.toThrow(
|
||||
@@ -536,8 +820,159 @@ describe(SimulatorControl, () => {
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('lists the actions as JSON when no action is provided', async () => {
|
||||
await createCommand(['--id', 'session-123', '--json']).runAsync();
|
||||
it('runs an interactive selection through the shared execution path', async () => {
|
||||
jest.mocked(runControlMenuAsync).mockImplementationOnce(async ({ runActionAsync }) => {
|
||||
await runActionAsync({ action: 'hardwareKeyboard.set', params: { value: 'off' } });
|
||||
});
|
||||
await createCommand(['--id', 'session-123']).runAsync();
|
||||
expect(actionRequests()).toEqual([['hardwareKeyboard.set', { value: 'off' }]]);
|
||||
expect(Log.log).toHaveBeenCalledWith('off');
|
||||
});
|
||||
|
||||
it('cleans up before returning Ctrl-C status', async () => {
|
||||
const previousExitCode = process.exitCode;
|
||||
jest.mocked(runControlMenuAsync).mockRejectedValueOnce(new ControlPromptCancelledError());
|
||||
try {
|
||||
await createCommand(['--id', 'session-123']).runAsync();
|
||||
expect(process.exitCode).toBe(130);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
process.exitCode = previousExitCode;
|
||||
}
|
||||
});
|
||||
|
||||
it('detaches on SIGINT while the menu is idle and removes its handler', async () => {
|
||||
const previousExitCode = process.exitCode;
|
||||
const listeners = process.listenerCount('SIGINT');
|
||||
jest.mocked(runControlMenuAsync).mockImplementationOnce(async ({ signal }) => {
|
||||
const interrupted = new Promise<never>((_resolve, reject) => {
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
reject(signal.reason);
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
});
|
||||
process.emit('SIGINT');
|
||||
await interrupted;
|
||||
});
|
||||
try {
|
||||
await createCommand(['--id', 'session-123']).runAsync();
|
||||
expect(process.exitCode).toBe(130);
|
||||
expect(close).toHaveBeenCalled();
|
||||
expect(process.listenerCount('SIGINT')).toBe(listeners);
|
||||
expect(actionRequests()).toEqual([]);
|
||||
} finally {
|
||||
process.exitCode = previousExitCode;
|
||||
}
|
||||
});
|
||||
|
||||
it('reports connection loss while idle and restores its listeners', async () => {
|
||||
const listeners = process.listenerCount('SIGINT');
|
||||
const reason = new Error('Connection lost; the action may still have run.');
|
||||
jest.mocked(runControlMenuAsync).mockImplementationOnce(async ({ signal }) => {
|
||||
const lost = new Promise<never>((_resolve, reject) => {
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
reject(signal.reason);
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
});
|
||||
connectionController.abort(reason);
|
||||
await lost;
|
||||
});
|
||||
await expect(createCommand(['--id', 'session-123']).runAsync()).rejects.toBe(reason);
|
||||
expect(close).toHaveBeenCalled();
|
||||
expect(process.listenerCount('SIGINT')).toBe(listeners);
|
||||
expect(actionRequests()).toEqual([]);
|
||||
});
|
||||
|
||||
it('does not run an action when the socket closes immediately after catalog setup', async () => {
|
||||
const reason = new Error('Connection closed after catalog');
|
||||
requestAsync.mockImplementationOnce(async () => {
|
||||
queueMicrotask(() => {
|
||||
connectionController.abort(reason);
|
||||
});
|
||||
return ok(JSON.stringify(served));
|
||||
});
|
||||
jest.mocked(runControlMenuAsync).mockImplementationOnce(async ({ signal }) => {
|
||||
signal.throwIfAborted();
|
||||
});
|
||||
await expect(createCommand(['--id', 'session-123']).runAsync()).rejects.toBe(reason);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
expect(actionRequests()).toEqual([]);
|
||||
});
|
||||
|
||||
it('ends the idle menu on confirmed session completion without stopping the remote session', async () => {
|
||||
const watcher = new AbortController();
|
||||
const dispose = jest.fn();
|
||||
const watch = jest
|
||||
.spyOn(controlSession, 'watchControlSession')
|
||||
.mockReturnValueOnce({ signal: watcher.signal, dispose });
|
||||
const listeners = process.listenerCount('SIGINT');
|
||||
jest.mocked(runControlMenuAsync).mockImplementationOnce(async ({ signal }) => {
|
||||
const ended = new Promise<never>((_resolve, reject) => {
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
reject(signal.reason);
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
});
|
||||
watcher.abort(new controlSession.ControlSessionEndedError('session-123'));
|
||||
await ended;
|
||||
});
|
||||
try {
|
||||
await createCommand(['--id', 'session-123']).runAsync();
|
||||
expect(Log.log).toHaveBeenCalledWith('Simulator session session-123 has ended.');
|
||||
expect(dispose).toHaveBeenCalledTimes(1);
|
||||
expect(close).toHaveBeenCalled();
|
||||
expect(process.listenerCount('SIGINT')).toBe(listeners);
|
||||
expect(actionRequests()).toEqual([]);
|
||||
expect(mockByIdAsync).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
watch.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('propagates an errored session instead of reporting a successful end', async () => {
|
||||
jest
|
||||
.mocked(runControlMenuAsync)
|
||||
.mockRejectedValueOnce(
|
||||
new controlSession.ControlSessionEndedError('session-123', /* failed */ true)
|
||||
);
|
||||
await expect(createCommand(['--id', 'session-123']).runAsync()).rejects.toThrow(
|
||||
'session-123 errored'
|
||||
);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
expect(Log.log).not.toHaveBeenCalledWith('Simulator session session-123 has ended.');
|
||||
});
|
||||
|
||||
it('shows session and device details without terminal escape sequences', async () => {
|
||||
mockByIdAsync.mockResolvedValueOnce(
|
||||
makeDeviceRunSession({ name: '\x1b[31mCheckout QA\x1b[0m\nSpoofed\u202E' })
|
||||
);
|
||||
await createCommand(['--id', 'session-123']).runAsync();
|
||||
const text = jest
|
||||
.mocked(Log.log)
|
||||
.mock.calls.map(([value]) => String(value))
|
||||
.join('\n');
|
||||
expect(text).toContain('Checkout QA Spoofed');
|
||||
expect(text).toContain('@testuser/testapp');
|
||||
expect(text).toContain('iPhone 17 Pro · iOS 26.4');
|
||||
expect(text).toContain('session-123');
|
||||
expect(text).toContain('simulator-udid');
|
||||
expect(text).not.toContain('\x1b[31m');
|
||||
expect(text).not.toContain('\u202E');
|
||||
expect(text).not.toContain('preview-token');
|
||||
});
|
||||
|
||||
it('includes upload path help in the JSON action list', async () => {
|
||||
await createCommand(['--list', '--id', 'session-123', '--json']).runAsync();
|
||||
|
||||
expect(mockPrintJsonOnlyOutput).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
@@ -550,6 +985,105 @@ describe(SimulatorControl, () => {
|
||||
expect(actionRequests()).toEqual([]);
|
||||
});
|
||||
|
||||
it('shows fallback names when optional details are unavailable or blank', async () => {
|
||||
mockByIdAsync.mockResolvedValueOnce(makeDeviceRunSession({ name: ' \n ' }));
|
||||
jest.mocked(fetchHostActionDeviceAsync).mockResolvedValueOnce({ udid: 'simulator-udid' });
|
||||
await createCommand(['--id', 'session-123']).runAsync();
|
||||
expect(Log.log).toHaveBeenCalledWith(expect.stringContaining('Unnamed session'));
|
||||
expect(Log.log).toHaveBeenCalledWith(expect.stringContaining('Unavailable'));
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ importing: true, jsonFlag: false },
|
||||
{ importing: true, jsonFlag: true },
|
||||
{ importing: false, jsonFlag: true },
|
||||
])(
|
||||
'runs actions without display metadata (importing: $importing, json: $jsonFlag)',
|
||||
async ({ importing, jsonFlag }) => {
|
||||
jest
|
||||
.mocked(fetchHostActionDeviceAsync)
|
||||
.mockImplementationOnce(
|
||||
jest.requireActual('../../../simulator/hostActions').fetchHostActionDeviceAsync
|
||||
);
|
||||
const fetch = jest
|
||||
.spyOn(fetchModule, 'default')
|
||||
.mockRejectedValueOnce(new Error('Metadata request failed'));
|
||||
try {
|
||||
const filePath = await writeImportAsync([
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'off' } },
|
||||
]);
|
||||
await createCommand([
|
||||
...(importing ? ['--import', filePath] : ['hardwareKeyboard.set', 'off']),
|
||||
...(jsonFlag ? ['--json'] : []),
|
||||
'--id',
|
||||
'session-123',
|
||||
]).runAsync();
|
||||
expect(actionRequests()).toEqual([['hardwareKeyboard.set', { value: 'off' }]]);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
if (jsonFlag) {
|
||||
expect(mockPrintJsonOnlyOutput).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
session: expect.objectContaining({ device: { udid: 'simulator-udid' } }),
|
||||
})
|
||||
);
|
||||
} else {
|
||||
expect(Log.log).toHaveBeenCalledWith(expect.stringContaining('Unavailable'));
|
||||
}
|
||||
} finally {
|
||||
fetch.mockRestore();
|
||||
}
|
||||
}
|
||||
);
|
||||
it('closes the connection if the interactive controller fails unexpectedly', async () => {
|
||||
const reason = new Error('Terminal output failed');
|
||||
jest.mocked(runControlMenuAsync).mockRejectedValueOnce(reason);
|
||||
await expect(createCommand(['--id', 'session-123']).runAsync()).rejects.toBe(reason);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('requires a session ID before opening a connection', async () => {
|
||||
const previous = process.env[EAS_SIMULATOR_SESSION_ID];
|
||||
delete process.env[EAS_SIMULATOR_SESSION_ID];
|
||||
try {
|
||||
await expect(createCommand([]).runAsync()).rejects.toThrow(
|
||||
'No simulator session ID provided.'
|
||||
);
|
||||
expect(mockByIdAsync).not.toHaveBeenCalled();
|
||||
expect(mockConnectHostActionsAsync).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
if (previous === undefined) {
|
||||
delete process.env[EAS_SIMULATOR_SESSION_ID];
|
||||
} else {
|
||||
process.env[EAS_SIMULATOR_SESSION_ID] = previous;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('uses the session ID loaded into the simulator environment', async () => {
|
||||
const previous = process.env[EAS_SIMULATOR_SESSION_ID];
|
||||
process.env[EAS_SIMULATOR_SESSION_ID] = 'dotenv-session';
|
||||
try {
|
||||
await createCommand([]).runAsync();
|
||||
expect(mockByIdAsync).toHaveBeenCalledWith(graphqlClient, 'dotenv-session');
|
||||
expect(runControlMenuAsync).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
if (previous === undefined) {
|
||||
delete process.env[EAS_SIMULATOR_SESSION_ID];
|
||||
} else {
|
||||
process.env[EAS_SIMULATOR_SESSION_ID] = previous;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('refuses Android before an interactive prompt or connection', async () => {
|
||||
mockByIdAsync.mockResolvedValue(makeDeviceRunSession({ platform: AppPlatform.Android }));
|
||||
await expect(createCommand(['--id', 'session-123']).runAsync()).rejects.toThrow(
|
||||
'not supported yet'
|
||||
);
|
||||
expect(runControlMenuAsync).not.toHaveBeenCalled();
|
||||
expect(mockConnectHostActionsAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses a session that is not running', async () => {
|
||||
mockByIdAsync.mockResolvedValue(
|
||||
makeDeviceRunSession({ status: DeviceRunSessionStatus.Stopped })
|
||||
|
||||
@@ -33,11 +33,14 @@ import {
|
||||
resetSimulatorEnvAsync,
|
||||
} from '../../../simulator/env';
|
||||
import { resolveExpoGoSdkVersionAsync } from '../../../simulator/expoGo';
|
||||
import { applyStartConfigAsync } from '../../../simulator/startSetup';
|
||||
import { ControlConfigExecutionError } from '../../../simulator/controlConfig';
|
||||
import * as promiseUtils from '../../../utils/promise';
|
||||
import { enableJsonOutput, printJsonOnlyOutput } from '../../../utils/json';
|
||||
import Simulator from '../index';
|
||||
|
||||
jest.mock('fs-extra');
|
||||
jest.mock('../../../simulator/startSetup');
|
||||
jest.mock('../../../analytics/AnalyticsManager', () => ({
|
||||
...jest.requireActual('../../../analytics/AnalyticsManager'),
|
||||
isAnalyticsOptedOutAsync: jest.fn(),
|
||||
@@ -195,6 +198,7 @@ describe(Simulator, () => {
|
||||
beforeEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
jest.clearAllMocks();
|
||||
jest.mocked(applyStartConfigAsync).mockReset().mockResolvedValue([]);
|
||||
delete process.env[EAS_SIMULATOR_SESSION_ID];
|
||||
mockJobRunErrorsByIdAsync.mockResolvedValue(null);
|
||||
mockAvailabilityByAppIdAsync.mockResolvedValue({ accountName: 'testuser', available: true });
|
||||
@@ -203,7 +207,7 @@ describe(Simulator, () => {
|
||||
id: 'session-123',
|
||||
status: DeviceRunSessionStatus.Stopped,
|
||||
});
|
||||
mockByIdAsync.mockResolvedValue(makeDeviceRunSession());
|
||||
mockByIdAsync.mockReset().mockResolvedValue(makeDeviceRunSession());
|
||||
mockLoadSimulatorEnvAsync.mockResolvedValue();
|
||||
mockResetSimulatorEnvAsync.mockResolvedValue();
|
||||
mockResolveExpoGoSdkVersionAsync.mockResolvedValue('55.0.0');
|
||||
@@ -238,6 +242,804 @@ describe(Simulator, () => {
|
||||
return { command, getContextAsync };
|
||||
}
|
||||
|
||||
describe('imported session configuration', () => {
|
||||
const configPath = '/test/simulator.json';
|
||||
const localEgressSession = makeDeviceRunSession({
|
||||
remoteConfig: {
|
||||
__typename: 'WebPreviewOnlyRunSessionRemoteConfig',
|
||||
previewUrl: 'https://expo.dev/preview',
|
||||
previewApiUrl: 'https://sim.example.test',
|
||||
previewToken: 'private-token',
|
||||
egressUrl: 'https://egress.example.com',
|
||||
egressToken: 'token',
|
||||
egressFingerprint: 'fp',
|
||||
egressPort: 8899,
|
||||
},
|
||||
});
|
||||
function config(start: object = { platform: 'ios' }, actions?: object[]): void {
|
||||
jest
|
||||
.mocked(fs.readJson)
|
||||
.mockResolvedValue({ version: 1, start, ...(actions ? { actions } : {}) } as never);
|
||||
mockByIdAsync.mockResolvedValue(
|
||||
makeDeviceRunSession({
|
||||
remoteConfig: {
|
||||
__typename: 'WebPreviewOnlyRunSessionRemoteConfig',
|
||||
previewUrl: 'https://expo.dev/preview',
|
||||
previewApiUrl: 'https://sim.example.test',
|
||||
previewToken: 'private-token',
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
it('enables JSON output before import preflight can fail', async () => {
|
||||
config({ unknown: true });
|
||||
const { command, getContextAsync } = createCommand(['--import', configPath, '--json']);
|
||||
await expect(command.runAsync()).rejects.toThrow('Unknown or invocation-only');
|
||||
expect(mockEnableJsonOutput).toHaveBeenCalledTimes(1);
|
||||
expect(mockEnableJsonOutput.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
jest.mocked(fs.readJson).mock.invocationCallOrder[0]
|
||||
);
|
||||
expect(getContextAsync).not.toHaveBeenCalled();
|
||||
expect(mockCreateDeviceRunSessionAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('creates from saved flags with explicit CLI overrides and unchanged output without actions', async () => {
|
||||
config({
|
||||
platform: 'ios',
|
||||
name: 'Saved name',
|
||||
type: 'web-preview-only',
|
||||
device: 'Saved phone',
|
||||
tag: ['saved'],
|
||||
});
|
||||
const { command } = createCommand(['--import', configPath, '--name', 'CLI name', '--json']);
|
||||
await command.runAsync();
|
||||
expect(mockCreateDeviceRunSessionAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
expect.objectContaining({
|
||||
name: 'CLI name',
|
||||
type: DeviceRunSessionType.WebPreviewOnly,
|
||||
ios: { deviceIdentifier: 'Saved phone' },
|
||||
tags: ['saved'],
|
||||
})
|
||||
);
|
||||
expect(applyStartConfigAsync).not.toHaveBeenCalled();
|
||||
expect(jest.mocked(printJsonOnlyOutput)).toHaveBeenCalledWith(
|
||||
expect.not.objectContaining({ setup: expect.anything() })
|
||||
);
|
||||
});
|
||||
|
||||
it.each(
|
||||
(['ios', 'android'] as const).flatMap(platform =>
|
||||
(['attached', 'detached', 'json'] as const).flatMap(mode =>
|
||||
(['env', 'dotenv'] as const).flatMap(output =>
|
||||
[false, true].map(egress => ({ platform, mode, output, egress }))
|
||||
)
|
||||
)
|
||||
)
|
||||
)(
|
||||
'preserves ordinary startup with saved settings: $platform/$mode/$output, egress=$egress',
|
||||
async ({ platform, mode, output, egress }) => {
|
||||
const listeners = process.listeners('SIGINT');
|
||||
const start = {
|
||||
platform,
|
||||
type: 'web-preview-only',
|
||||
name: 'Startup regression',
|
||||
device: platform === 'ios' ? 'iPhone 17 Pro' : 'pixel_7',
|
||||
'out-config-type': output,
|
||||
...(egress ? { egress: 'local' } : {}),
|
||||
};
|
||||
const ready = makeDeviceRunSession({
|
||||
platform: platform === 'ios' ? AppPlatform.Ios : AppPlatform.Android,
|
||||
remoteConfig: {
|
||||
__typename: 'WebPreviewOnlyRunSessionRemoteConfig',
|
||||
previewUrl: 'https://expo.dev/preview',
|
||||
previewApiUrl: 'https://sim.example.test',
|
||||
previewToken: 'private-token',
|
||||
...(egress
|
||||
? {
|
||||
egressUrl: 'https://egress.example.com',
|
||||
egressToken: 'token',
|
||||
egressFingerprint: 'fp',
|
||||
egressPort: 8899,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
const runAsync = async (saved: boolean): Promise<object> => {
|
||||
jest.clearAllMocks();
|
||||
jest.mocked(fs.readJson).mockResolvedValue({ version: 1, start } as never);
|
||||
mockByIdAsync
|
||||
.mockReset()
|
||||
.mockResolvedValueOnce(ready)
|
||||
.mockResolvedValue({ ...ready, status: DeviceRunSessionStatus.Stopped });
|
||||
jest.mocked(runLocalEgressAsync).mockImplementation(async ({ signal, onConnected }) => {
|
||||
onConnected?.();
|
||||
await new Promise<void>(resolve => {
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
resolve();
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
});
|
||||
});
|
||||
const argv = saved
|
||||
? ['--import', configPath]
|
||||
: Object.entries(start).flatMap(([name, value]) => [`--${name}`, value]);
|
||||
if (mode !== 'attached') {
|
||||
argv.push(mode === 'json' ? '--json' : '--non-interactive');
|
||||
}
|
||||
await createCommand(argv).command.runAsync();
|
||||
expect(applyStartConfigAsync).not.toHaveBeenCalled();
|
||||
expect(fs.readJson).toHaveBeenCalledTimes(saved ? 1 : 0);
|
||||
expect(runLocalEgressAsync).toHaveBeenCalledTimes(egress && mode === 'attached' ? 1 : 0);
|
||||
expect(fs.writeFile).toHaveBeenCalledTimes(
|
||||
output === 'dotenv' ? (mode === 'json' ? 1 : 2) : 0
|
||||
);
|
||||
expect(process.listeners('SIGINT')).toEqual(listeners);
|
||||
return {
|
||||
create: mockCreateDeviceRunSessionAsync.mock.calls,
|
||||
output: jest.mocked(Log.log).mock.calls,
|
||||
warnings: jest.mocked(Log.warn).mock.calls,
|
||||
newLines: jest.mocked(Log.newLine).mock.calls,
|
||||
json: mockPrintJsonOnlyOutput.mock.calls,
|
||||
writes: jest.mocked(fs.writeFile).mock.calls,
|
||||
cleanup: mockResetSimulatorEnvAsync.mock.calls,
|
||||
stop: mockEnsureDeviceRunSessionStoppedAsync.mock.calls,
|
||||
egress: jest.mocked(runLocalEgressAsync).mock.calls.map(([options]) => ({
|
||||
url: options.url,
|
||||
port: options.port,
|
||||
platform: options.platform,
|
||||
aborted: options.signal.aborted,
|
||||
})),
|
||||
};
|
||||
};
|
||||
const ordinary = await runAsync(false);
|
||||
expect(await runAsync(true)).toEqual(ordinary);
|
||||
}
|
||||
);
|
||||
|
||||
it('applies actions after readiness and includes parsed setup results in one JSON object', async () => {
|
||||
config(undefined, [{ action: 'appearance.set', params: { value: 'dark' } }]);
|
||||
jest.mocked(applyStartConfigAsync).mockImplementationOnce(async () => {
|
||||
expect(fs.writeFile).not.toHaveBeenCalled();
|
||||
return [{ action: 'appearance.set', output: '{"value":"dark"}', file: null }];
|
||||
});
|
||||
const { command } = createCommand(['--import', configPath, '--json']);
|
||||
await command.runAsync();
|
||||
expect(jest.mocked(applyStartConfigAsync).mock.invocationCallOrder[0]).toBeGreaterThan(
|
||||
mockByIdAsync.mock.invocationCallOrder[0]
|
||||
);
|
||||
expect(applyStartConfigAsync).toHaveBeenCalledWith(
|
||||
{ apiUrl: 'https://sim.example.test', token: 'private-token' },
|
||||
expect.objectContaining({ path: configPath }),
|
||||
{ signal: expect.any(AbortSignal), onProgress: undefined }
|
||||
);
|
||||
expect(printJsonOnlyOutput).toHaveBeenCalledTimes(1);
|
||||
expect(printJsonOnlyOutput).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
id: 'session-123',
|
||||
setup: {
|
||||
config: configPath,
|
||||
results: [{ action: 'appearance.set', output: { value: 'dark' }, file: null }],
|
||||
},
|
||||
})
|
||||
);
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).not.toHaveBeenCalled();
|
||||
expect(fs.writeFile).toHaveBeenCalledTimes(1);
|
||||
expect(fs.writeFile).toHaveBeenCalledWith(
|
||||
simulatorDotenvPath,
|
||||
SIMULATOR_DOTENV_FILE_HEADER + `${EAS_SIMULATOR_SESSION_ID}='session-123'\n`
|
||||
);
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
'prints normal ready output before importing, detached=%s',
|
||||
async detached => {
|
||||
config({ platform: 'ios' }, [{ action: 'tap', params: { x: 0.5, y: 0.5 } }]);
|
||||
const ready = makeDeviceRunSession({
|
||||
remoteConfig: {
|
||||
__typename: 'WebPreviewOnlyRunSessionRemoteConfig',
|
||||
previewUrl: 'https://expo.dev/preview',
|
||||
previewApiUrl: 'https://sim.example.test',
|
||||
previewToken: 'private-token',
|
||||
},
|
||||
});
|
||||
mockByIdAsync
|
||||
.mockResolvedValueOnce(ready)
|
||||
.mockResolvedValueOnce({ ...ready, status: DeviceRunSessionStatus.Stopped });
|
||||
jest
|
||||
.mocked(applyStartConfigAsync)
|
||||
.mockImplementationOnce(async (_access, _config, options) => {
|
||||
expect(fs.writeFile).not.toHaveBeenCalled();
|
||||
const output = jest.mocked(Log.log).mock.calls.map(([line]) => String(line));
|
||||
const preview = output.findIndex(line => line.includes(deviceRunSessionPreviewUrl));
|
||||
const importing = output.findIndex(line => line.includes('Importing 1 action from'));
|
||||
expect(preview).toBeGreaterThanOrEqual(0);
|
||||
expect(importing).toBeGreaterThan(preview);
|
||||
options.onProgress?.({ step: 1, total: 1, action: 'tap', status: 'running' });
|
||||
const result = { action: 'tap', output: '', file: null };
|
||||
options.onProgress?.({ step: 1, total: 1, action: 'tap', status: 'completed', result });
|
||||
return [result];
|
||||
});
|
||||
await createCommand([
|
||||
'--import',
|
||||
configPath,
|
||||
...(detached ? ['--non-interactive'] : []),
|
||||
]).command.runAsync();
|
||||
expect(fs.writeFile).toHaveBeenCalledWith(
|
||||
simulatorDotenvPath,
|
||||
expect.stringContaining(`${EAS_SIMULATOR_SESSION_ID}='session-123'`)
|
||||
);
|
||||
const spinners = jest.mocked(ora).mock.results.map(result => result.value);
|
||||
expect(
|
||||
spinners.some(spinner =>
|
||||
spinner.succeed.mock.calls.some(([text]: [string]) => text === '[1/1] tap completed')
|
||||
)
|
||||
).toBe(true);
|
||||
}
|
||||
);
|
||||
|
||||
it('identifies failed and skipped imported steps after printing the preview', async () => {
|
||||
config({ platform: 'ios' }, [
|
||||
{ action: 'appearance.get' },
|
||||
{ action: 'tap' },
|
||||
{ action: 'clipboard.read' },
|
||||
]);
|
||||
jest
|
||||
.mocked(applyStartConfigAsync)
|
||||
.mockRejectedValueOnce(
|
||||
new ControlConfigExecutionError(
|
||||
2,
|
||||
'tap',
|
||||
[{ action: 'appearance.get', output: 'dark', file: null }],
|
||||
new Error('refused')
|
||||
)
|
||||
);
|
||||
await expect(
|
||||
createCommand(['--import', configPath, '--non-interactive']).command.runAsync()
|
||||
).rejects.toThrow('refused');
|
||||
expect(jest.mocked(Log.log)).toHaveBeenCalledWith('1 completed · 1 failed · 1 skipped');
|
||||
expect(jest.mocked(Log.log)).toHaveBeenCalledWith(' [3/3] clipboard.read skipped');
|
||||
const spinners = jest.mocked(ora).mock.results.map(result => result.value);
|
||||
expect(
|
||||
spinners.some(spinner =>
|
||||
spinner.fail.mock.calls.some(([text]: [string]) => text === '[2/3] tap failed')
|
||||
)
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('prints imported text and saved files after the ready preview URL', async () => {
|
||||
config(undefined, [{ action: 'appearance.get' }, { action: 'screenshot.capture' }]);
|
||||
jest
|
||||
.mocked(applyStartConfigAsync)
|
||||
.mockImplementationOnce(async (_access, _config, options) => {
|
||||
const results = [
|
||||
{ action: 'appearance.get', output: 'dark', file: null },
|
||||
{ action: 'screenshot.capture', output: '', file: '/test/screenshot.png' },
|
||||
];
|
||||
for (const [index, result] of results.entries()) {
|
||||
options.onProgress?.({
|
||||
step: index + 1,
|
||||
total: results.length,
|
||||
action: result.action,
|
||||
status: 'completed',
|
||||
result,
|
||||
});
|
||||
}
|
||||
return results;
|
||||
});
|
||||
await createCommand(['--import', configPath, '--non-interactive']).command.runAsync();
|
||||
const output = jest.mocked(Log.log).mock.calls.map(([line]) => String(line));
|
||||
const preview = output.findIndex(line => line.includes(deviceRunSessionPreviewUrl));
|
||||
expect(preview).toBeGreaterThanOrEqual(0);
|
||||
expect(output.indexOf('dark')).toBeGreaterThan(preview);
|
||||
expect(output.indexOf('Saved /test/screenshot.png')).toBeGreaterThan(preview);
|
||||
});
|
||||
|
||||
it('preserves the setup error when the stopped session dotenv cannot be cleaned up', async () => {
|
||||
config(undefined, [{ action: 'appearance.get' }]);
|
||||
jest.mocked(applyStartConfigAsync).mockRejectedValueOnce(new Error('native action refused'));
|
||||
mockResetSimulatorEnvAsync.mockRejectedValueOnce(new Error('read-only file'));
|
||||
const listeners = process.listeners('SIGINT');
|
||||
await expect(
|
||||
createCommand(['--import', configPath, '--non-interactive']).command.runAsync()
|
||||
).rejects.toThrow('native action refused');
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'session-123'
|
||||
);
|
||||
expect(Log.warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('could not be cleaned up: read-only file')
|
||||
);
|
||||
expect(process.listeners('SIGINT')).toEqual(listeners);
|
||||
});
|
||||
|
||||
it('stops only the newly created session on setup failure and retains completed JSON results', async () => {
|
||||
config(undefined, [{ action: 'appearance.set' }, { action: 'appearance.get' }]);
|
||||
process.env[EAS_SIMULATOR_SESSION_ID] = 'previous-session';
|
||||
jest
|
||||
.mocked(applyStartConfigAsync)
|
||||
.mockRejectedValue(
|
||||
new ControlConfigExecutionError(
|
||||
2,
|
||||
'appearance.get',
|
||||
[{ action: 'appearance.set', output: '"dark"', file: null }],
|
||||
new Error('refused')
|
||||
)
|
||||
);
|
||||
const prior = process.exitCode;
|
||||
const listeners = process.listenerCount('SIGINT');
|
||||
try {
|
||||
await createCommand(['--import', configPath, '--json']).command.runAsync();
|
||||
expect(process.exitCode).toBe(1);
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'session-123'
|
||||
);
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledTimes(1);
|
||||
expect(fs.writeFile).not.toHaveBeenCalled();
|
||||
expect(mockResetSimulatorEnvAsync).toHaveBeenCalledWith(projectDir, 'session-123');
|
||||
expect(printJsonOnlyOutput).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
id: 'session-123',
|
||||
stopped: true,
|
||||
setup: expect.objectContaining({
|
||||
results: [{ action: 'appearance.set', output: 'dark', file: null }],
|
||||
error: expect.objectContaining({ step: 2, action: 'appearance.get' }),
|
||||
}),
|
||||
})
|
||||
);
|
||||
expect(process.listenerCount('SIGINT')).toBe(listeners);
|
||||
} finally {
|
||||
process.exitCode = prior;
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ imported: false, jsonFlag: true },
|
||||
{ imported: true, jsonFlag: true },
|
||||
{ imported: true, jsonFlag: false },
|
||||
])(
|
||||
'stops startup interrupted during its final dotenv write, imported=$imported, json=$jsonFlag',
|
||||
async ({ imported, jsonFlag }) => {
|
||||
jest.spyOn(process, 'exit').mockImplementation(code => {
|
||||
throw new Error(`process.exit(${code})`);
|
||||
});
|
||||
config(undefined, imported ? [{ action: 'appearance.get' }] : undefined);
|
||||
jest.mocked(fs.writeFile).mockImplementationOnce(async () => {
|
||||
process.emit('SIGINT');
|
||||
});
|
||||
const listeners = process.listeners('SIGINT');
|
||||
await expect(
|
||||
createCommand([
|
||||
'--import',
|
||||
configPath,
|
||||
...(jsonFlag ? ['--json'] : ['--non-interactive']),
|
||||
]).command.runAsync()
|
||||
).rejects.toThrow('process.exit(130)');
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'session-123'
|
||||
);
|
||||
expect(mockResetSimulatorEnvAsync).toHaveBeenCalledWith(projectDir, 'session-123');
|
||||
expect(printJsonOnlyOutput).not.toHaveBeenCalled();
|
||||
expect(process.listeners('SIGINT')).toEqual(listeners);
|
||||
}
|
||||
);
|
||||
|
||||
it.each(
|
||||
['interactive', 'detached', 'json'].flatMap(mode =>
|
||||
['failure', 'interruption'].map(outcome => ({ mode, outcome }))
|
||||
)
|
||||
)(
|
||||
'keeps previous session credentials after imported $outcome in $mode mode',
|
||||
async ({ mode, outcome }) => {
|
||||
config(undefined, [{ action: 'appearance.set' }]);
|
||||
process.env[EAS_SIMULATOR_SESSION_ID] = 'previous-session';
|
||||
const previous =
|
||||
SIMULATOR_DOTENV_FILE_HEADER +
|
||||
"EAS_SIMULATOR_SESSION_ID='previous-session'\nEAS_SIMULATOR_EGRESS_TOKEN='previous-token'\n";
|
||||
let saved = previous;
|
||||
jest.mocked(fs.readFile).mockImplementation(async () => saved as never);
|
||||
jest.mocked(fs.writeFile).mockImplementation(async (_path, content) => {
|
||||
saved = String(content);
|
||||
});
|
||||
mockResetSimulatorEnvAsync.mockImplementationOnce(
|
||||
jest.requireActual('../../../simulator/env').resetSimulatorEnvAsync
|
||||
);
|
||||
jest
|
||||
.mocked(applyStartConfigAsync)
|
||||
.mockImplementationOnce(async (_access, _config, { signal }) => {
|
||||
if (outcome === 'interruption') {
|
||||
process.emit('SIGINT');
|
||||
signal.throwIfAborted();
|
||||
}
|
||||
throw new Error('setup failed');
|
||||
});
|
||||
jest.spyOn(process, 'exit').mockImplementation(() => {
|
||||
throw new Error('interrupted');
|
||||
});
|
||||
const priorExitCode = process.exitCode;
|
||||
const listeners = process.listeners('SIGINT');
|
||||
try {
|
||||
const command = createCommand([
|
||||
'--import',
|
||||
configPath,
|
||||
...(mode === 'json' ? ['--json'] : mode === 'detached' ? ['--non-interactive'] : []),
|
||||
]).command;
|
||||
if (mode === 'json' && outcome === 'failure') {
|
||||
await command.runAsync();
|
||||
expect(process.exitCode).toBe(1);
|
||||
} else {
|
||||
await expect(command.runAsync()).rejects.toThrow(
|
||||
outcome === 'interruption' ? 'interrupted' : 'setup failed'
|
||||
);
|
||||
}
|
||||
expect(saved).toBe(previous);
|
||||
expect(fs.writeFile).not.toHaveBeenCalled();
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledTimes(1);
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'session-123'
|
||||
);
|
||||
expect(process.listeners('SIGINT')).toEqual(listeners);
|
||||
} finally {
|
||||
process.exitCode = priorExitCode;
|
||||
jest.mocked(fs.readFile).mockReset();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
it('reports unconfirmed cleanup rather than implying the session stopped', async () => {
|
||||
config(undefined, [{ action: 'appearance.set' }]);
|
||||
jest.mocked(applyStartConfigAsync).mockRejectedValue(new Error('setup failed'));
|
||||
mockEnsureDeviceRunSessionStoppedAsync.mockRejectedValue(new Error('network failed'));
|
||||
const prior = process.exitCode;
|
||||
try {
|
||||
await createCommand(['--import', configPath, '--json']).command.runAsync();
|
||||
expect(printJsonOnlyOutput).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ stopped: false })
|
||||
);
|
||||
expect(mockResetSimulatorEnvAsync).not.toHaveBeenCalled();
|
||||
expect(Log.warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('simulator:stop --id session-123')
|
||||
);
|
||||
} finally {
|
||||
process.exitCode = prior;
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects Android actions and invalid files before creating a session', async () => {
|
||||
config({ platform: 'android' }, [{ action: 'appearance.set' }]);
|
||||
await expect(
|
||||
createCommand(['--import', configPath, '--non-interactive']).command.runAsync()
|
||||
).rejects.toThrow('not supported on Android');
|
||||
expect(mockCreateDeviceRunSessionAsync).not.toHaveBeenCalled();
|
||||
config({ typo: 'value' });
|
||||
const { command, getContextAsync } = createCommand(['--import', configPath]);
|
||||
await expect(command.runAsync()).rejects.toThrow('Unknown or invocation-only');
|
||||
expect(getContextAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects explicit capture fields when the CLI disables saved capture', async () => {
|
||||
config({ platform: 'ios', 'network-capture': true });
|
||||
await expect(
|
||||
createCommand([
|
||||
'--import',
|
||||
configPath,
|
||||
'--no-network-capture',
|
||||
'--network-capture-field',
|
||||
'header',
|
||||
]).command.runAsync()
|
||||
).rejects.toThrow('--network-capture-field requires --network-capture');
|
||||
expect(mockCreateDeviceRunSessionAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('allows Android start settings without actions', async () => {
|
||||
config({ platform: 'android' });
|
||||
await createCommand(['--import', configPath, '--json']).command.runAsync();
|
||||
expect(mockCreateDeviceRunSessionAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
expect.objectContaining({ platform: AppPlatform.Android })
|
||||
);
|
||||
expect(applyStartConfigAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses the existing platform prompt and attached-session lifecycle in interactive mode', async () => {
|
||||
config({}, [{ action: 'appearance.set' }]);
|
||||
const ready = makeDeviceRunSession({
|
||||
remoteConfig: {
|
||||
__typename: 'WebPreviewOnlyRunSessionRemoteConfig',
|
||||
previewUrl: 'https://expo.dev/preview',
|
||||
previewApiUrl: 'https://sim.example.test',
|
||||
previewToken: 'private-token',
|
||||
},
|
||||
});
|
||||
mockPromptAsync.mockResolvedValueOnce({ selectedPlatform: AppPlatform.Ios });
|
||||
mockByIdAsync
|
||||
.mockResolvedValueOnce(ready)
|
||||
.mockResolvedValueOnce({ ...ready, status: DeviceRunSessionStatus.Stopped });
|
||||
const listeners = process.listeners('SIGINT');
|
||||
await createCommand(['--import', configPath]).command.runAsync();
|
||||
expect(mockPromptAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ message: 'Select platform' })
|
||||
);
|
||||
expect(applyStartConfigAsync).toHaveBeenCalledTimes(1);
|
||||
expect(mockByIdAsync).toHaveBeenCalledTimes(2);
|
||||
expect(mockResetSimulatorEnvAsync).toHaveBeenCalledWith(projectDir, 'session-123');
|
||||
expect(process.listeners('SIGINT')).toEqual(listeners);
|
||||
expect(printJsonOnlyOutput).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([['--non-interactive'], ['--json']])(
|
||||
'refuses an incomplete platform without prompting: %j',
|
||||
async mode => {
|
||||
config({}, [{ action: 'appearance.set' }]);
|
||||
await expect(
|
||||
createCommand(['--import', configPath, mode]).command.runAsync()
|
||||
).rejects.toThrow('platform flag must be set');
|
||||
expect(mockPromptAsync).not.toHaveBeenCalled();
|
||||
expect(mockCreateDeviceRunSessionAsync).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
it.each(['CI', 'pipe'])('inherits non-interactive defaults for %s', async mode => {
|
||||
config({}, [{ action: 'appearance.set' }]);
|
||||
const priorCi = process.env.CI;
|
||||
const priorTty = process.stdin.isTTY;
|
||||
try {
|
||||
if (mode === 'CI') {
|
||||
process.env.CI = 'true';
|
||||
} else {
|
||||
Object.defineProperty(process.stdin, 'isTTY', { value: false, writable: true });
|
||||
}
|
||||
await expect(createCommand(['--import', configPath]).command.runAsync()).rejects.toThrow(
|
||||
'platform flag must be set'
|
||||
);
|
||||
expect(mockPromptAsync).not.toHaveBeenCalled();
|
||||
expect(mockCreateDeviceRunSessionAsync).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
if (priorCi === undefined) {
|
||||
delete process.env.CI;
|
||||
} else {
|
||||
process.env.CI = priorCi;
|
||||
}
|
||||
Object.defineProperty(process.stdin, 'isTTY', { value: priorTty, writable: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('connects interactive local egress before applying imported actions and closes it on session end', async () => {
|
||||
config({ platform: 'ios', egress: 'local' }, [{ action: 'appearance.set' }]);
|
||||
const ready = localEgressSession;
|
||||
mockByIdAsync
|
||||
.mockResolvedValueOnce(ready)
|
||||
.mockResolvedValueOnce({ ...ready, status: DeviceRunSessionStatus.Stopped });
|
||||
let connected = false;
|
||||
let tunnelSignal: AbortSignal | undefined;
|
||||
jest.mocked(runLocalEgressAsync).mockImplementationOnce(async ({ signal, onConnected }) => {
|
||||
tunnelSignal = signal;
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
connected = true;
|
||||
onConnected?.();
|
||||
await new Promise<void>(resolve => {
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
resolve();
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
});
|
||||
});
|
||||
jest.mocked(applyStartConfigAsync).mockImplementationOnce(async () => {
|
||||
expect(connected).toBe(true);
|
||||
return [];
|
||||
});
|
||||
await createCommand(['--import', configPath]).command.runAsync();
|
||||
expect(tunnelSignal?.aborted).toBe(true);
|
||||
});
|
||||
|
||||
it.each([['--non-interactive'], ['--json']])(
|
||||
'rejects actions with detached local egress before creating a session: %j',
|
||||
async mode => {
|
||||
config({ platform: 'ios', egress: 'local' }, [{ action: 'appearance.get' }]);
|
||||
await expect(
|
||||
createCommand(['--import', configPath, mode]).command.runAsync()
|
||||
).rejects.toThrow('Imported actions with local egress require interactive mode');
|
||||
expect(mockCreateDeviceRunSessionAsync).not.toHaveBeenCalled();
|
||||
expect(applyStartConfigAsync).not.toHaveBeenCalled();
|
||||
expect(runLocalEgressAsync).not.toHaveBeenCalled();
|
||||
expect(mockPromptAsync).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
it('cleans up and preserves an egress connection failure before setup', async () => {
|
||||
config({ platform: 'ios', egress: 'local' }, [{ action: 'appearance.get' }]);
|
||||
mockByIdAsync.mockResolvedValue(localEgressSession);
|
||||
const failure = new Error('egress could not bind');
|
||||
jest.mocked(runLocalEgressAsync).mockRejectedValueOnce(failure);
|
||||
const listeners = process.listeners('SIGINT');
|
||||
await expect(createCommand(['--import', configPath]).command.runAsync()).rejects.toBe(
|
||||
failure
|
||||
);
|
||||
expect(applyStartConfigAsync).not.toHaveBeenCalled();
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'session-123'
|
||||
);
|
||||
expect(process.listeners('SIGINT')).toEqual(listeners);
|
||||
});
|
||||
|
||||
it('stops setup instead of running without requested local egress settings', async () => {
|
||||
config({ platform: 'ios', egress: 'local' }, [{ action: 'appearance.get' }]);
|
||||
await expect(createCommand(['--import', configPath]).command.runAsync()).rejects.toThrow(
|
||||
'did not provide local egress connection settings'
|
||||
);
|
||||
expect(applyStartConfigAsync).not.toHaveBeenCalled();
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'session-123'
|
||||
);
|
||||
});
|
||||
|
||||
it.each(['action', 'egress'])(
|
||||
'preserves a %s failure during connected setup and closes the tunnel',
|
||||
async source => {
|
||||
config({ platform: 'ios', egress: 'local' }, [{ action: 'appearance.get' }]);
|
||||
mockByIdAsync.mockResolvedValue(localEgressSession);
|
||||
const failure = new Error(`${source} failed during setup`);
|
||||
let rejectTunnel: (error: Error) => void = () => {};
|
||||
let tunnelClosed = false;
|
||||
jest.mocked(runLocalEgressAsync).mockImplementationOnce(async ({ signal, onConnected }) => {
|
||||
onConnected?.();
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
rejectTunnel = reject;
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
resolve();
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
});
|
||||
} finally {
|
||||
tunnelClosed = true;
|
||||
}
|
||||
});
|
||||
jest
|
||||
.mocked(applyStartConfigAsync)
|
||||
.mockImplementationOnce(async (_access, _config, { signal }) => {
|
||||
if (source === 'action') {
|
||||
throw failure;
|
||||
}
|
||||
rejectTunnel(failure);
|
||||
await new Promise<void>((_resolve, reject) => {
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
reject(new Error('action aborted'));
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
});
|
||||
return [];
|
||||
});
|
||||
const listeners = process.listeners('SIGINT');
|
||||
await expect(createCommand(['--import', configPath]).command.runAsync()).rejects.toBe(
|
||||
failure
|
||||
);
|
||||
expect(tunnelClosed).toBe(true);
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'session-123'
|
||||
);
|
||||
expect(mockResetSimulatorEnvAsync).toHaveBeenCalledWith(projectDir, 'session-123');
|
||||
expect(printJsonOnlyOutput).not.toHaveBeenCalled();
|
||||
expect(process.listeners('SIGINT')).toEqual(listeners);
|
||||
}
|
||||
);
|
||||
|
||||
it('bounds the wait for local egress and closes the tunnel on timeout', async () => {
|
||||
config({ platform: 'ios', egress: 'local' }, [{ action: 'appearance.get' }]);
|
||||
mockByIdAsync.mockResolvedValue(localEgressSession);
|
||||
let tunnelSignal: AbortSignal | undefined;
|
||||
jest.mocked(runLocalEgressAsync).mockImplementationOnce(async ({ signal }) => {
|
||||
tunnelSignal = signal;
|
||||
await new Promise<void>(resolve => {
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
resolve();
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
});
|
||||
});
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const result = expect(
|
||||
createCommand(['--import', configPath]).command.runAsync()
|
||||
).rejects.toThrow('did not connect within 120 seconds');
|
||||
await jest.advanceTimersByTimeAsync(120_000);
|
||||
await result;
|
||||
expect(tunnelSignal?.aborted).toBe(true);
|
||||
expect(applyStartConfigAsync).not.toHaveBeenCalled();
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'session-123'
|
||||
);
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('closes local egress and stops the session on Ctrl-C before the tunnel connects', async () => {
|
||||
config({ platform: 'ios', egress: 'local' }, [{ action: 'appearance.get' }]);
|
||||
mockByIdAsync.mockResolvedValue(localEgressSession);
|
||||
const interrupted = new Error('exit 130');
|
||||
jest.spyOn(process, 'exit').mockImplementation(() => {
|
||||
throw interrupted;
|
||||
});
|
||||
let tunnelClosed = false;
|
||||
jest.mocked(runLocalEgressAsync).mockImplementationOnce(async ({ signal }) => {
|
||||
await new Promise<void>(resolve => {
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
resolve();
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
setImmediate(() => {
|
||||
process.emit('SIGINT');
|
||||
});
|
||||
});
|
||||
tunnelClosed = true;
|
||||
});
|
||||
const listeners = process.listeners('SIGINT');
|
||||
await expect(createCommand(['--import', configPath]).command.runAsync()).rejects.toBe(
|
||||
interrupted
|
||||
);
|
||||
expect(tunnelClosed).toBe(true);
|
||||
expect(applyStartConfigAsync).not.toHaveBeenCalled();
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'session-123'
|
||||
);
|
||||
expect(mockResetSimulatorEnvAsync).toHaveBeenCalledWith(projectDir, 'session-123');
|
||||
expect(process.listeners('SIGINT')).toEqual(listeners);
|
||||
});
|
||||
|
||||
it('stops on Ctrl-C during setup and removes the session handler', async () => {
|
||||
config(undefined, [{ action: 'appearance.set' }]);
|
||||
const interrupted = new Error('exit 130');
|
||||
const exit = jest.spyOn(process, 'exit').mockImplementation(() => {
|
||||
throw interrupted;
|
||||
});
|
||||
const listeners = process.listenerCount('SIGINT');
|
||||
jest
|
||||
.mocked(applyStartConfigAsync)
|
||||
.mockImplementation(async (_access, _config, { signal }) => {
|
||||
process.emit('SIGINT');
|
||||
signal.throwIfAborted();
|
||||
return [];
|
||||
});
|
||||
await expect(
|
||||
createCommand(['--import', configPath, '--non-interactive']).command.runAsync()
|
||||
).rejects.toBe(interrupted);
|
||||
expect(exit).toHaveBeenCalledWith(130);
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'session-123'
|
||||
);
|
||||
expect(process.listenerCount('SIGINT')).toBe(listeners);
|
||||
});
|
||||
});
|
||||
|
||||
it('fails with the waitlist link without creating a session when the account is gated', async () => {
|
||||
mockAvailabilityByAppIdAsync.mockResolvedValue({ accountName: 'testuser', available: false });
|
||||
|
||||
@@ -1831,7 +2633,14 @@ describe(Simulator, () => {
|
||||
'stops %s after an interactive egress failure and removes its interrupt handler',
|
||||
async (typeFlag, type, remoteConfig) => {
|
||||
const failure = new Error('listen EADDRINUSE');
|
||||
jest.mocked(runLocalEgressAsync).mockRejectedValueOnce(failure);
|
||||
jest.mocked(runLocalEgressAsync).mockImplementationOnce(async () => {
|
||||
expect(fs.writeFile).toHaveBeenCalledWith(
|
||||
simulatorDotenvPath,
|
||||
expect.stringContaining("EAS_SIMULATOR_EGRESS_TOKEN='pw'")
|
||||
);
|
||||
expect(Log.log).toHaveBeenCalledWith(expect.stringContaining(deviceRunSessionUrl));
|
||||
throw failure;
|
||||
});
|
||||
mockByIdAsync.mockResolvedValue(
|
||||
makeDeviceRunSession({
|
||||
type,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Args, Flags } from '@oclif/core';
|
||||
import chalk from 'chalk';
|
||||
import * as fs from 'fs-extra';
|
||||
import path from 'path';
|
||||
import path from 'node:path';
|
||||
import { stripVTControlCharacters } from 'node:util';
|
||||
|
||||
import EasCommand from '../../commandUtils/EasCommand';
|
||||
import {
|
||||
@@ -12,6 +12,23 @@ import { AppPlatform, DeviceRunSessionStatus } from '../../graphql/generated';
|
||||
import { DeviceRunSessionQuery } from '../../graphql/queries/DeviceRunSessionQuery';
|
||||
import Log from '../../log';
|
||||
import { ora } from '../../ora';
|
||||
import {
|
||||
ControlAction,
|
||||
executeControlActionAsync,
|
||||
parseControlActionOutput,
|
||||
prepareControlActionAsync,
|
||||
} from '../../simulator/controlActions';
|
||||
import {
|
||||
ControlConfigExecutionError,
|
||||
ControlConfigResult,
|
||||
PreparedControlConfig,
|
||||
executeControlConfigAsync,
|
||||
prepareControlConfigAsync,
|
||||
serializeControlConfigResults,
|
||||
} from '../../simulator/controlConfig';
|
||||
import { runControlMenuAsync } from '../../simulator/controlInteractive';
|
||||
import { ControlPromptCancelledError } from '../../simulator/controlPrompts';
|
||||
import { ControlSessionEndedError, watchControlSession } from '../../simulator/controlSession';
|
||||
import {
|
||||
EAS_SIMULATOR_SESSION_ID,
|
||||
SIMULATOR_DOTENV_FILE_NAME,
|
||||
@@ -21,28 +38,53 @@ import {
|
||||
HostActionCatalog,
|
||||
HostActionCatalogEntry,
|
||||
HostActionConnection,
|
||||
assertHostActionOutputAsync,
|
||||
HostActionDevice,
|
||||
buildHostActionParams,
|
||||
connectHostActionsAsync,
|
||||
fetchHostActionCatalogAsync,
|
||||
fetchHostActionDeviceAsync,
|
||||
formatHostActionUsage,
|
||||
saveHostActionOutputAsync,
|
||||
uploadFileAsync,
|
||||
} from '../../simulator/hostActions';
|
||||
import { PreviewApiAccess, getPreviewApiAccess } from '../../simulator/utils';
|
||||
import { enableJsonOutput, printJsonOnlyOutput } from '../../utils/json';
|
||||
import formatFields from '../../utils/formatFields';
|
||||
import { sanitizeTerminalText, truncate } from '../../utils/terminalText';
|
||||
import { formatMilliseconds } from '../../utils/timer';
|
||||
|
||||
type ControlSession = {
|
||||
id: string;
|
||||
name: string | null;
|
||||
project: string;
|
||||
status: DeviceRunSessionStatus;
|
||||
device: HostActionDevice;
|
||||
};
|
||||
|
||||
export default class SimulatorControl extends EasCommand {
|
||||
static override aliases = ['sim:control'];
|
||||
static override description =
|
||||
'[EXPERIMENTAL] run a serve-sim action on a remote iOS simulator session on EAS. Run without an action to list the actions the session supports. To save a screenshot locally, run `eas simulator:control screenshot.capture --output ./screenshot.png`';
|
||||
static override description = `[EXPERIMENTAL] control a remote iOS simulator session on EAS
|
||||
|
||||
Run without an action to open the menu, or use --list to see available actions. Use <action> --help for usage.
|
||||
|
||||
To save a screenshot locally, run \`eas simulator:control screenshot.capture --output ./screenshot.png\`.
|
||||
|
||||
Use --import to run saved actions from a JSON file:
|
||||
{
|
||||
"version": 1,
|
||||
"actions": [{"action": "appearance.set", "params": {"value": "dark"}}]
|
||||
}
|
||||
|
||||
The file is checked before any actions run. Actions run in order and stop on the first failure. Local paths are relative to the JSON file; paths in params refer to the simulator host.
|
||||
|
||||
Existing output files are overwritten. When saving to a directory, an existing file with the generated name causes the action to fail.`;
|
||||
static override strict = false;
|
||||
|
||||
static override examples = [
|
||||
'$ eas simulator:control',
|
||||
'$ eas simulator:control --list',
|
||||
'$ eas simulator:control --id <session-id>',
|
||||
'$ eas simulator:control screenshot.capture --help',
|
||||
'$ eas simulator:control clipboard.write -- --some-text',
|
||||
'$ eas simulator:control --import ./simulator-control.json',
|
||||
'$ eas simulator:control hardwareKeyboard.set off',
|
||||
'$ eas simulator:control permissions.set grant camera com.example.app',
|
||||
'$ eas simulator:control app.install ./MyApp.ipa',
|
||||
@@ -53,24 +95,26 @@ export default class SimulatorControl extends EasCommand {
|
||||
static override args = {
|
||||
action: Args.string({
|
||||
description:
|
||||
'Action to run, followed by its values in order or as name=value. Omit to list the actions. Put -- before values that start with --.',
|
||||
'Action name, followed by values or name=value pairs. Omit to open the menu. Use -- before values starting with --.',
|
||||
}),
|
||||
};
|
||||
|
||||
static override flags = {
|
||||
help: Flags.boolean({
|
||||
char: 'h',
|
||||
description: 'Show command help, or usage for the selected action from the session.',
|
||||
description: 'Show help for this command or the selected action',
|
||||
}),
|
||||
id: Flags.string({
|
||||
description: `Simulator session ID. Defaults to ${SIMULATOR_DOTENV_FILE_NAME}.`,
|
||||
}),
|
||||
list: Flags.boolean({
|
||||
description: 'List the actions the session supports.',
|
||||
description: 'List available actions',
|
||||
}),
|
||||
output: Flags.string({
|
||||
description:
|
||||
'Local path to save a returned file. For screenshots, --output ./screenshot.png sets the local filename; omit it to save with a generated filename in the current directory.',
|
||||
description: 'Local file or existing directory for saved output',
|
||||
}),
|
||||
import: Flags.string({
|
||||
description: 'Run saved actions from a JSON file',
|
||||
}),
|
||||
...EasNonInteractiveAndJsonFlags,
|
||||
};
|
||||
@@ -91,6 +135,21 @@ export default class SimulatorControl extends EasCommand {
|
||||
throw new Error('--id needs a simulator session ID.');
|
||||
}
|
||||
const action = flags.list && !flags.help ? undefined : args.action;
|
||||
const importing = flags.import !== undefined;
|
||||
if (importing && (args.action || flags.list || flags.output !== undefined)) {
|
||||
throw new Error('--import cannot be combined with an action, --list, or --output.');
|
||||
}
|
||||
const interactive = !flags.list && !action && !importing;
|
||||
if (!action && flags.output) {
|
||||
throw new Error(
|
||||
'--output requires an action. Choose an output path when selecting a file action in the interactive menu.'
|
||||
);
|
||||
}
|
||||
if (interactive && (nonInteractive || !process.stdin.isTTY)) {
|
||||
throw new Error(
|
||||
'No action provided. Run `eas simulator:control --list` to see the actions, then `eas simulator:control <action> [values...]`.'
|
||||
);
|
||||
}
|
||||
|
||||
const {
|
||||
projectDir,
|
||||
@@ -111,41 +170,219 @@ export default class SimulatorControl extends EasCommand {
|
||||
let connection: HostActionConnection | undefined;
|
||||
try {
|
||||
let catalog: HostActionCatalog;
|
||||
let controlSession: ControlSession;
|
||||
try {
|
||||
const session = await DeviceRunSessionQuery.byIdAsync(graphqlClient, sessionId);
|
||||
connection = await connectHostActionsAsync(assertControllableSession(session));
|
||||
const access = assertControllableSession(session);
|
||||
connection = await connectHostActionsAsync(access);
|
||||
catalog = await fetchHostActionCatalogAsync(connection);
|
||||
controlSession = {
|
||||
id: session.id,
|
||||
name: session.name ?? null,
|
||||
project: `@${session.app.ownerAccount.name}/${session.app.slug}`,
|
||||
status: session.status,
|
||||
device:
|
||||
interactive || importing || (jsonFlag && !flags.list && !flags.help)
|
||||
? await fetchHostActionDeviceAsync(access, connection.udid)
|
||||
: { udid: connection.udid },
|
||||
};
|
||||
spinner.succeed(`Connected to simulator session ${sessionId}`);
|
||||
} catch (err) {
|
||||
spinner.fail(`Failed to connect to simulator session ${sessionId}`);
|
||||
throw err;
|
||||
}
|
||||
if (!action) {
|
||||
if (flags.list && !flags.help) {
|
||||
this.printCatalog(catalog, jsonFlag);
|
||||
return;
|
||||
}
|
||||
const entry = Object.hasOwn(catalog, action) ? catalog[action] : undefined;
|
||||
if (!entry) {
|
||||
throw new Error(
|
||||
`Unknown simulator action "${action}". Run \`eas simulator:control\` to see the actions.`
|
||||
);
|
||||
}
|
||||
if (flags.help) {
|
||||
if (flags.help && action) {
|
||||
const entry = Object.hasOwn(catalog, action) ? catalog[action] : undefined;
|
||||
if (!entry) {
|
||||
throw new Error(
|
||||
`Unknown simulator action "${action}". Run \`eas simulator:control --list\` to see the actions.`
|
||||
);
|
||||
}
|
||||
this.printActionHelp(action, entry, jsonFlag);
|
||||
return;
|
||||
}
|
||||
await this.runActionAsync(connection, entry, {
|
||||
sessionId,
|
||||
action,
|
||||
values: argv.slice(1).map(String),
|
||||
outputPath: flags.output,
|
||||
jsonFlag,
|
||||
});
|
||||
const activeConnection = connection;
|
||||
const runActionAsync = async (selection: ControlAction): Promise<void> => {
|
||||
await this.runActionAsync(activeConnection, catalog, selection, {
|
||||
session: controlSession,
|
||||
jsonFlag,
|
||||
interactive,
|
||||
});
|
||||
};
|
||||
if (interactive) {
|
||||
this.printSessionHeader(controlSession);
|
||||
const controller = new AbortController();
|
||||
const onConnectionLost = (): void => {
|
||||
controller.abort(activeConnection.signal.reason);
|
||||
};
|
||||
const onInterrupt = (): void => {
|
||||
controller.abort(new ControlPromptCancelledError());
|
||||
};
|
||||
activeConnection.signal.addEventListener('abort', onConnectionLost, { once: true });
|
||||
if (activeConnection.signal.aborted) {
|
||||
onConnectionLost();
|
||||
}
|
||||
process.on('SIGINT', onInterrupt);
|
||||
const session = watchControlSession(graphqlClient, sessionId, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
const detach = (): void => {
|
||||
activeConnection.close();
|
||||
};
|
||||
session.signal.addEventListener('abort', detach, { once: true });
|
||||
try {
|
||||
await runControlMenuAsync({
|
||||
catalog,
|
||||
signal: session.signal,
|
||||
runActionAsync,
|
||||
});
|
||||
} catch (error) {
|
||||
const reason: unknown = session.signal.aborted ? session.signal.reason : error;
|
||||
if (reason instanceof ControlPromptCancelledError) {
|
||||
process.exitCode = 130;
|
||||
} else if (reason instanceof ControlSessionEndedError) {
|
||||
if (reason.failed) {
|
||||
throw reason;
|
||||
}
|
||||
Log.log(reason.message);
|
||||
} else {
|
||||
throw reason;
|
||||
}
|
||||
} finally {
|
||||
session.signal.removeEventListener('abort', detach);
|
||||
session.dispose();
|
||||
activeConnection.signal.removeEventListener('abort', onConnectionLost);
|
||||
process.removeListener('SIGINT', onInterrupt);
|
||||
}
|
||||
} else if (importing) {
|
||||
await this.importConfigAsync(activeConnection, catalog, flags.import!, {
|
||||
session: controlSession,
|
||||
jsonFlag,
|
||||
});
|
||||
} else {
|
||||
const entry = Object.hasOwn(catalog, action!) ? catalog[action!] : undefined;
|
||||
await runActionAsync({
|
||||
action: action!,
|
||||
params: entry ? buildHostActionParams(action!, entry, argv.slice(1).map(String)) : {},
|
||||
outputPath: flags.output,
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
connection?.close();
|
||||
}
|
||||
}
|
||||
|
||||
private async importConfigAsync(
|
||||
connection: HostActionConnection,
|
||||
catalog: HostActionCatalog,
|
||||
filePath: string,
|
||||
{ session, jsonFlag }: { session: ControlSession; jsonFlag: boolean }
|
||||
): Promise<void> {
|
||||
const spinner = jsonFlag ? undefined : ora(`Validating ${path.basename(filePath)}`).start();
|
||||
const startedAt = Date.now();
|
||||
let stepStartedAt = startedAt;
|
||||
let config: PreparedControlConfig | undefined;
|
||||
let results: ControlConfigResult[];
|
||||
try {
|
||||
config = await prepareControlConfigAsync(catalog, filePath, connection.udid);
|
||||
if (spinner) {
|
||||
spinner.succeed(`Validated ${formatActionCount(config.actions.length)}`);
|
||||
this.printSessionHeader(session);
|
||||
Log.log(chalk.bold(path.basename(config.path)));
|
||||
Log.gray(config.path);
|
||||
for (const { plan } of config.actions) {
|
||||
if (plan.localFile) {
|
||||
Log.gray(` Read: ${plan.localFile.path}`);
|
||||
}
|
||||
if (plan.outputPath) {
|
||||
Log.gray(` Output: ${plan.outputPath}`);
|
||||
}
|
||||
}
|
||||
if (config.actions.some(({ plan }) => plan.outputPath)) {
|
||||
Log.gray(
|
||||
'Explicit output files are overwritten; directory outputs use simulator filenames and fail if the file exists.'
|
||||
);
|
||||
}
|
||||
Log.newLine();
|
||||
}
|
||||
const prepared = config;
|
||||
results = await executeControlConfigAsync(connection, prepared, {
|
||||
onProgress: spinner
|
||||
? progress => {
|
||||
const label = `[${progress.step}/${progress.total}] ${progress.action}`;
|
||||
if (progress.status === 'running') {
|
||||
stepStartedAt = Date.now();
|
||||
spinner.start(label);
|
||||
} else {
|
||||
spinner.succeed(`${label} ${chalk.dim(formatElapsed(stepStartedAt))}`);
|
||||
this.printConfigResult(progress.result);
|
||||
}
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof ControlConfigExecutionError && config) {
|
||||
spinner?.fail(
|
||||
`[${error.step}/${config.actions.length}] ${error.action} ${chalk.dim(formatElapsed(stepStartedAt))}`
|
||||
);
|
||||
if (jsonFlag) {
|
||||
printJsonOnlyOutput({
|
||||
id: session.id,
|
||||
session,
|
||||
config: config.path,
|
||||
results: serializeControlConfigResults(error.completed),
|
||||
error: { step: error.step, action: error.action, message: error.message },
|
||||
});
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
const skipped = config.actions.length - error.step;
|
||||
Log.newLine();
|
||||
Log.log(`${error.completed.length} completed · 1 failed · ${skipped} skipped`);
|
||||
for (const [index, { plan }] of config.actions.entries()) {
|
||||
if (index >= error.step) {
|
||||
Log.gray(` [${index + 1}/${config.actions.length}] ${plan.action} skipped`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
spinner?.fail(config ? 'Import failed' : 'Validation failed. No actions were run.');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (jsonFlag) {
|
||||
printJsonOnlyOutput({
|
||||
id: session.id,
|
||||
session,
|
||||
config: config.path,
|
||||
results: serializeControlConfigResults(results),
|
||||
});
|
||||
} else {
|
||||
Log.newLine();
|
||||
Log.succeed(
|
||||
`Import complete · ${formatActionCount(results.length)} · ${formatElapsed(startedAt)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private printConfigResult(result: ControlConfigResult): void {
|
||||
if (result.file) {
|
||||
Log.log(` Saved: ${result.file}`);
|
||||
} else if (result.output) {
|
||||
const output = parseControlActionOutput(result.output);
|
||||
const text = typeof output === 'string' ? output : JSON.stringify(output, null, 2);
|
||||
Log.log(
|
||||
text
|
||||
.split('\n')
|
||||
.map(line => ` ${line}`)
|
||||
.join('\n')
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private printCatalog(catalog: HostActionCatalog, jsonFlag: boolean): void {
|
||||
if (jsonFlag) {
|
||||
printJsonOnlyOutput(
|
||||
@@ -210,71 +447,86 @@ export default class SimulatorControl extends EasCommand {
|
||||
Log.newLine();
|
||||
}
|
||||
|
||||
private printSessionHeader(session: ControlSession): void {
|
||||
const clean = (value: string): string =>
|
||||
sanitizeTerminalText(
|
||||
stripVTControlCharacters(value).replace(/[\u202A-\u202E\u2066-\u2069]/g, '')
|
||||
);
|
||||
const runtime = clean(session.device.runtime ?? '')
|
||||
.replace(/^([A-Za-z]+)-/, '$1 ')
|
||||
.replaceAll('-', '.');
|
||||
Log.newLine();
|
||||
Log.log(chalk.bold('Simulator controls'));
|
||||
Log.log(
|
||||
formatFields([
|
||||
{ label: 'Session', value: truncate(clean(session.name ?? '') || 'Unnamed session', 80) },
|
||||
{ label: 'Project', value: clean(session.project) },
|
||||
{
|
||||
label: 'Device',
|
||||
value: [truncate(clean(session.device.name ?? '') || 'Unavailable', 80), runtime]
|
||||
.filter(Boolean)
|
||||
.join(' · '),
|
||||
},
|
||||
{ label: 'State', value: session.status.toLowerCase().replaceAll('_', ' ') },
|
||||
{ label: 'Session ID', value: clean(session.id) },
|
||||
{ label: 'Device ID', value: clean(session.device.udid) },
|
||||
])
|
||||
);
|
||||
Log.newLine();
|
||||
}
|
||||
|
||||
private async runActionAsync(
|
||||
connection: HostActionConnection,
|
||||
entry: HostActionCatalogEntry,
|
||||
catalog: HostActionCatalog,
|
||||
selection: ControlAction,
|
||||
{
|
||||
sessionId,
|
||||
action,
|
||||
values,
|
||||
outputPath,
|
||||
session,
|
||||
jsonFlag,
|
||||
}: {
|
||||
sessionId: string;
|
||||
action: string;
|
||||
values: string[];
|
||||
outputPath: string | undefined;
|
||||
jsonFlag: boolean;
|
||||
}
|
||||
interactive,
|
||||
}: { session: ControlSession; jsonFlag: boolean; interactive: boolean }
|
||||
): Promise<void> {
|
||||
const params = buildHostActionParams(action, entry, values);
|
||||
await assertHostActionOutputAsync(action, entry, outputPath);
|
||||
const localFile = await findLocalUploadAsync(entry, params);
|
||||
|
||||
const spinner = ora(`Running ${action} on simulator session ${sessionId}`).start();
|
||||
let uploadId: string | undefined;
|
||||
let succeeded = false;
|
||||
const { action } = selection;
|
||||
const plan = await prepareControlActionAsync(catalog, selection);
|
||||
const startedAt = Date.now();
|
||||
const spinner = ora(
|
||||
interactive ? `Running ${action}` : `Running ${action} on simulator session ${session.id}`
|
||||
).start();
|
||||
let output: string;
|
||||
let savedFile: string | null;
|
||||
try {
|
||||
if (localFile) {
|
||||
spinner.text = `Uploading ${localFile.path}`;
|
||||
const upload = await uploadFileAsync(connection, localFile.path);
|
||||
uploadId = upload.uploadId;
|
||||
params[localFile.param] = entry.uploadAs === 'id' ? upload.uploadId : upload.path;
|
||||
spinner.text = `Running ${action} on simulator session ${sessionId}`;
|
||||
}
|
||||
const result = await connection.requestAsync(action, params);
|
||||
if (result.exitCode !== 0) {
|
||||
const detail = (result.stderr || result.stdout).trim() || `exit code ${result.exitCode}`;
|
||||
throw new Error(`The simulator could not run ${action}: ${detail}`);
|
||||
}
|
||||
succeeded = true;
|
||||
savedFile = await saveHostActionOutputAsync(connection, entry, result.stdout, outputPath);
|
||||
output = savedFile ? '' : result.stdout.trim();
|
||||
spinner.succeed(`Ran ${action} on simulator session ${sessionId}`);
|
||||
({ output, file: savedFile } = await executeControlActionAsync(connection, plan));
|
||||
spinner.succeed(
|
||||
interactive
|
||||
? `${action} complete · ${formatElapsed(startedAt)}`
|
||||
: `Ran ${action} on simulator session ${session.id}`
|
||||
);
|
||||
} catch (err) {
|
||||
spinner.fail(`Failed to run ${action} on simulator session ${sessionId}`);
|
||||
spinner.fail(
|
||||
interactive
|
||||
? `${action} failed`
|
||||
: `Failed to run ${action} on simulator session ${session.id}`
|
||||
);
|
||||
throw err;
|
||||
} finally {
|
||||
if (uploadId && (!entry.keepUpload || !succeeded)) {
|
||||
await connection.requestAsync('upload.remove', { uploadId }).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
if (jsonFlag) {
|
||||
printJsonOnlyOutput({
|
||||
id: sessionId,
|
||||
id: session.id,
|
||||
session,
|
||||
action,
|
||||
output: parseJsonOutput(output),
|
||||
output: parseControlActionOutput(output),
|
||||
file: savedFile,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (interactive && plan.localFile?.path) {
|
||||
Log.gray(`Source: ${plan.localFile.path}`);
|
||||
}
|
||||
if (savedFile) {
|
||||
Log.log(`Saved ${savedFile}`);
|
||||
} else if (output) {
|
||||
Log.log(output);
|
||||
const parsed = parseControlActionOutput(output);
|
||||
Log.log(interactive && typeof parsed !== 'string' ? JSON.stringify(parsed, null, 2) : output);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -295,45 +547,12 @@ function withUploadPathHelp(entry: HostActionCatalogEntry): HostActionCatalogEnt
|
||||
: entry;
|
||||
}
|
||||
|
||||
async function findLocalUploadAsync(
|
||||
{ upload: param, uploadWhen = {}, uploadAs }: HostActionCatalogEntry,
|
||||
params: Record<string, unknown>
|
||||
): Promise<{ param: string; path: string } | null> {
|
||||
const value = param ? params[param] : undefined;
|
||||
const applies = Object.entries(uploadWhen).every(([name, expected]) => params[name] === expected);
|
||||
if (!param || typeof value !== 'string' || !applies) {
|
||||
return null;
|
||||
}
|
||||
if (value.startsWith('host:')) {
|
||||
if (uploadAs === 'id') {
|
||||
throw new Error(
|
||||
'This action requires a local file to upload; host: paths are not supported.'
|
||||
);
|
||||
}
|
||||
const hostPath = value.slice('host:'.length);
|
||||
if (!path.posix.isAbsolute(hostPath)) {
|
||||
throw new Error(
|
||||
`A host: path must be absolute, for example host:/tmp/app.tar.gz. For a local filename beginning with host:, use ./${value}.`
|
||||
);
|
||||
}
|
||||
params[param] = hostPath;
|
||||
return null;
|
||||
}
|
||||
const stat = await fs.stat(value).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code === 'ENOENT' || error.code === 'ENOTDIR') {
|
||||
return null;
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
if (stat?.isDirectory()) {
|
||||
throw new Error(`${value} is a folder. Pass the path of a file.`);
|
||||
}
|
||||
if (!stat) {
|
||||
throw new Error(
|
||||
`${value} does not exist on this computer. Pass a local file, or prefix an absolute simulator-host path with host:.`
|
||||
);
|
||||
}
|
||||
return stat ? { param, path: value } : null;
|
||||
function formatElapsed(startedAt: number): string {
|
||||
return formatMilliseconds(Date.now() - startedAt) || '<1s';
|
||||
}
|
||||
|
||||
function formatActionCount(count: number): string {
|
||||
return `${count} action${count === 1 ? '' : 's'}`;
|
||||
}
|
||||
|
||||
function assertControllableSession(
|
||||
@@ -346,7 +565,7 @@ function assertControllableSession(
|
||||
}
|
||||
if (session.platform !== AppPlatform.Ios) {
|
||||
throw new Error(
|
||||
`Simulator session ${session.id} runs on ${session.platform.toLowerCase()}. Simulator actions are available only for iOS sessions.`
|
||||
`Simulator control on ${session.platform.toLowerCase()} is not supported yet. Simulator actions are available only for iOS sessions.`
|
||||
);
|
||||
}
|
||||
const access = session.remoteConfig ? getPreviewApiAccess(session.remoteConfig) : null;
|
||||
@@ -357,11 +576,3 @@ function assertControllableSession(
|
||||
}
|
||||
return access;
|
||||
}
|
||||
|
||||
function parseJsonOutput(output: string): unknown {
|
||||
try {
|
||||
return JSON.parse(output);
|
||||
} catch {
|
||||
return output;
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,12 @@ import { DeviceRunSessionQuery } from '../../graphql/queries/DeviceRunSessionQue
|
||||
import Log, { link } from '../../log';
|
||||
import { Ora, ora } from '../../ora';
|
||||
import { promptAsync } from '../../prompts';
|
||||
import {
|
||||
ControlConfigExecutionError,
|
||||
serializeControlConfigResults,
|
||||
} from '../../simulator/controlConfig';
|
||||
import { resolveStartConfigAsync } from '../../simulator/startConfig';
|
||||
import { applyStartConfigAsync } from '../../simulator/startSetup';
|
||||
import { parseEgressAllowList, runLocalEgressAsync } from '../../simulator/egress';
|
||||
import { parseCorsOriginList, parseFrameAncestorList } from '../../simulator/frameAncestors';
|
||||
import { parseNetworkCaptureFields } from '../../simulator/networkCapture';
|
||||
@@ -59,12 +65,15 @@ import {
|
||||
formatRemoteSessionInstructions,
|
||||
formatSimulatorUnavailableMessage,
|
||||
getLocalEgressConfig,
|
||||
getPreviewApiAccess,
|
||||
getRemoteSessionEnvironmentVariables,
|
||||
sanitizeRemoteConfigForJson,
|
||||
} from '../../simulator/utils';
|
||||
import { enableJsonOutput, printJsonOnlyOutput } from '../../utils/json';
|
||||
import { sleepAsync } from '../../utils/promise';
|
||||
|
||||
// Allow the cold-cache client download (up to 60s) and a further minute to connect.
|
||||
const EGRESS_SETUP_TIMEOUT_MS = 120_000;
|
||||
const POLL_INTERVAL_MS = 5_000; // 5 seconds
|
||||
const STARTUP_TIMEOUT_MS = 15 * 60 * 1_000; // 15 minutes, excluding time in the queue
|
||||
const OUT_CONFIG_TYPE_VALUES = {
|
||||
@@ -82,10 +91,30 @@ const APP_PLATFORM_BY_FLAG_VALUE: Record<PlatformFlagValue, AppPlatform> = {
|
||||
export default class Simulator extends EasCommand {
|
||||
static override aliases = ['simulator:start', 'sim:start'];
|
||||
static override hiddenAliases = ['sim'];
|
||||
static override description =
|
||||
'[EXPERIMENTAL] start a remote simulator session on EAS and get instructions to connect to it. The default browser preview link requires sign-in';
|
||||
static override description = `[EXPERIMENTAL] start a remote simulator session on EAS
|
||||
|
||||
Preview links require sign-in by default.
|
||||
|
||||
Use --import to load saved start options and actions. CLI flags override saved options, including lists:
|
||||
{
|
||||
"version": 1,
|
||||
"start": {"platform": "ios"},
|
||||
"actions": [{"action": "appearance.set", "params": {"value": "dark"}}]
|
||||
}
|
||||
|
||||
The start object uses CLI flag names. Saved actions run after the session is ready. Local action paths are relative to the JSON file. If an action fails, the CLI tries to stop the new session. Android supports saved start options, but not actions yet.
|
||||
|
||||
With local egress, actions wait for the connection and require interactive mode. In scripts, connect with simulator:egress, then run simulator:control --import separately.`;
|
||||
|
||||
static override examples = [
|
||||
'$ eas simulator:start --import ./simulator.json',
|
||||
'$ eas simulator:start --import ./simulator.json --device "iPhone 17 Pro" --json',
|
||||
];
|
||||
|
||||
static override flags = {
|
||||
import: Flags.string({
|
||||
description: 'Load start options and actions from a JSON file',
|
||||
}),
|
||||
platform: Flags.option({
|
||||
char: 'p',
|
||||
description: 'Device platform',
|
||||
@@ -151,6 +180,7 @@ export default class Simulator extends EasCommand {
|
||||
'Version of the package backing the simulator session (e.g. "0.1.3-alpha.3"). Defaults to "latest" when omitted.',
|
||||
}),
|
||||
'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.',
|
||||
}),
|
||||
@@ -208,6 +238,7 @@ export default class Simulator extends EasCommand {
|
||||
default: OUT_CONFIG_TYPE_VALUES.Dotenv,
|
||||
})(),
|
||||
'public-link': Flags.boolean({
|
||||
allowNo: true,
|
||||
description:
|
||||
'Enable the simulator preview Share button and print a shareable link containing an access token. Anyone with the link can control the simulator. With --json, include previewApiUrl and its token for API clients when available.',
|
||||
}),
|
||||
@@ -222,12 +253,13 @@ export default class Simulator extends EasCommand {
|
||||
};
|
||||
|
||||
async runAsync(): Promise<void> {
|
||||
const { flags } = await this.parse(Simulator);
|
||||
const { json: jsonFlag, nonInteractive } = resolveNonInteractiveAndJsonFlags(flags);
|
||||
|
||||
if (jsonFlag) {
|
||||
// Import preflight can fail before parsing; keep diagnostics off JSON stdout.
|
||||
if (this.argv.includes('--json')) {
|
||||
enableJsonOutput();
|
||||
}
|
||||
const imported = await resolveStartConfigAsync(this.argv, Simulator.flags);
|
||||
const { flags } = await this.parse(Simulator, imported.argv);
|
||||
const { json: jsonFlag, nonInteractive } = resolveNonInteractiveAndJsonFlags(flags);
|
||||
|
||||
const {
|
||||
projectId,
|
||||
@@ -297,6 +329,9 @@ export default class Simulator extends EasCommand {
|
||||
} catch (err) {
|
||||
throw new EasCommandError(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
if (networkCaptureFields.length && !flags['network-capture']) {
|
||||
throw new EasCommandError('--network-capture-field requires --network-capture.');
|
||||
}
|
||||
|
||||
const platform = await resolvePlatformAsync(flags.platform, nonInteractive);
|
||||
const egress = flags.egress === 'local' ? DeviceRunSessionEgress.Local : undefined;
|
||||
@@ -327,6 +362,18 @@ export default class Simulator extends EasCommand {
|
||||
);
|
||||
}
|
||||
|
||||
if (platform === AppPlatform.Android && imported.config?.actions?.length) {
|
||||
throw new EasCommandError(
|
||||
'Imported control actions are not supported on Android yet. Remove actions to import only start settings, or use --platform ios.'
|
||||
);
|
||||
}
|
||||
|
||||
if (nonInteractive && egress && imported.config?.actions?.length) {
|
||||
throw new EasCommandError(
|
||||
'Imported actions with local egress require interactive mode. Start without actions, connect eas simulator:egress, then run eas simulator:control --import with the same file.'
|
||||
);
|
||||
}
|
||||
|
||||
if (platform === AppPlatform.Android) {
|
||||
Log.warn(
|
||||
'Android emulator support in EAS Simulator is still in development. Some features available on iOS may not work on Android yet. Full parity with iOS is coming soon.'
|
||||
@@ -424,7 +471,9 @@ export default class Simulator extends EasCommand {
|
||||
);
|
||||
sessionInterrupt = registerSessionInterrupt(deviceRunSessionId);
|
||||
const simulatorEnvWritten =
|
||||
!jsonFlag && flags['out-config-type'] === OUT_CONFIG_TYPE_VALUES.Dotenv
|
||||
!jsonFlag &&
|
||||
!imported.config?.actions?.length &&
|
||||
flags['out-config-type'] === OUT_CONFIG_TYPE_VALUES.Dotenv
|
||||
? await writeSimulatorEnvSafelyAsync(projectDir, {
|
||||
[EAS_SIMULATOR_SESSION_ID]: deviceRunSessionId,
|
||||
})
|
||||
@@ -526,101 +575,270 @@ export default class Simulator extends EasCommand {
|
||||
);
|
||||
}
|
||||
|
||||
if (flags['out-config-type'] === OUT_CONFIG_TYPE_VALUES.Dotenv) {
|
||||
await writeSimulatorEnvSafelyAsync(projectDir, {
|
||||
...getRemoteSessionEnvironmentVariables(remoteConfig, { egressAllow, platform }),
|
||||
[EAS_SIMULATOR_SESSION_ID]: deviceRunSessionId,
|
||||
});
|
||||
}
|
||||
|
||||
if (sessionInterrupt.signal.aborted) {
|
||||
await stopDeviceRunSessionAfterInterruptAsync({
|
||||
graphqlClient,
|
||||
deviceRunSessionId,
|
||||
projectDir,
|
||||
spinner: pollSpinner,
|
||||
sessionInterrupt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (jsonFlag) {
|
||||
sessionInterrupt.dispose();
|
||||
printJsonOnlyOutput({
|
||||
id: deviceRunSessionId,
|
||||
name,
|
||||
type: flags.type,
|
||||
deviceRunSessionUrl,
|
||||
remoteConfig: sanitizeRemoteConfigForJson(
|
||||
remoteConfig,
|
||||
deviceRunSessionPreviewUrl,
|
||||
flags['public-link'],
|
||||
{ frameAncestors, corsOrigins }
|
||||
),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
Log.newLine();
|
||||
Log.log(
|
||||
formatRemoteSessionInstructions(remoteConfig, flags['out-config-type'], {
|
||||
egressAllow,
|
||||
egressClientRunsInline: !nonInteractive,
|
||||
sessionUrl: deviceRunSessionUrl,
|
||||
privatePreviewUrl: deviceRunSessionPreviewUrl,
|
||||
publicLink: flags['public-link'],
|
||||
frameAncestors,
|
||||
corsOrigins,
|
||||
platform,
|
||||
})
|
||||
);
|
||||
Log.newLine();
|
||||
|
||||
const localEgress = getLocalEgressConfig(remoteConfig, egressAllow, platform);
|
||||
|
||||
if (nonInteractive) {
|
||||
sessionInterrupt.dispose();
|
||||
// The instructions above already tell the reader to run eas simulator:egress.
|
||||
Log.log(
|
||||
`When you are done, stop the session with: eas simulator:stop --id ${deviceRunSessionId}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// In interactive mode the egress client runs right here, for as long as the
|
||||
// session does. A session with a disconnected tunnel still bills, so Ctrl+C stops both.
|
||||
let egressPromise: Promise<void> | undefined;
|
||||
let egressError: Error | undefined;
|
||||
const egressAbortController = new AbortController();
|
||||
if (localEgress) {
|
||||
sessionInterrupt.signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
egressAbortController.abort();
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
egressPromise = runLocalEgressAsync({
|
||||
...localEgress,
|
||||
signal: egressAbortController.signal,
|
||||
onConnected: () => {
|
||||
Log.succeed('Egress tunnel connected.');
|
||||
},
|
||||
onDisconnected: () => {
|
||||
Log.warn(
|
||||
'Egress tunnel disconnected; reconnecting. Proxied HTTP(S) requests are unavailable until it reconnects.'
|
||||
let markEgressReady: () => void;
|
||||
const egressReady = new Promise<void>(resolve => {
|
||||
markEgressReady = resolve;
|
||||
});
|
||||
const onSessionAbort = (): void => {
|
||||
egressAbortController.abort();
|
||||
};
|
||||
const startLocalEgress = (): void => {
|
||||
if (localEgress && !nonInteractive) {
|
||||
sessionInterrupt.signal.addEventListener('abort', onSessionAbort, { once: true });
|
||||
egressPromise = runLocalEgressAsync({
|
||||
...localEgress,
|
||||
signal: egressAbortController.signal,
|
||||
onConnected: () => {
|
||||
markEgressReady();
|
||||
Log.succeed('Egress tunnel connected.');
|
||||
},
|
||||
onDisconnected: () => {
|
||||
Log.warn(
|
||||
'Egress tunnel disconnected; reconnecting. Proxied HTTP(S) requests are unavailable until it reconnects.'
|
||||
);
|
||||
},
|
||||
}).catch(err => {
|
||||
egressError = err instanceof Error ? err : new Error(String(err));
|
||||
Log.error(
|
||||
`${err instanceof Error ? err.message : String(err)} Stopping the simulator session.`
|
||||
);
|
||||
},
|
||||
}).catch(err => {
|
||||
egressError = err instanceof Error ? err : new Error(String(err));
|
||||
Log.error(
|
||||
`${err instanceof Error ? err.message : String(err)} Stopping the simulator session.`
|
||||
);
|
||||
sessionInterrupt.abort();
|
||||
});
|
||||
}
|
||||
|
||||
sessionInterrupt.abort();
|
||||
});
|
||||
}
|
||||
};
|
||||
const writeReadySimulatorEnvAsync = async (): Promise<void> => {
|
||||
if (flags['out-config-type'] === OUT_CONFIG_TYPE_VALUES.Dotenv) {
|
||||
await writeSimulatorEnvSafelyAsync(projectDir, {
|
||||
...getRemoteSessionEnvironmentVariables(remoteConfig, { egressAllow, platform }),
|
||||
[EAS_SIMULATOR_SESSION_ID]: deviceRunSessionId,
|
||||
});
|
||||
}
|
||||
};
|
||||
try {
|
||||
if (!jsonFlag && !imported.config?.actions?.length) {
|
||||
await writeReadySimulatorEnvAsync();
|
||||
}
|
||||
|
||||
if (sessionInterrupt.signal.aborted && !egressError) {
|
||||
await stopDeviceRunSessionAfterInterruptAsync({
|
||||
graphqlClient,
|
||||
deviceRunSessionId,
|
||||
projectDir,
|
||||
spinner: pollSpinner,
|
||||
sessionInterrupt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!jsonFlag) {
|
||||
Log.newLine();
|
||||
Log.log(
|
||||
formatRemoteSessionInstructions(remoteConfig, flags['out-config-type'], {
|
||||
egressAllow,
|
||||
egressClientRunsInline: !nonInteractive,
|
||||
sessionUrl: deviceRunSessionUrl,
|
||||
privatePreviewUrl: deviceRunSessionPreviewUrl,
|
||||
publicLink: flags['public-link'],
|
||||
frameAncestors,
|
||||
corsOrigins,
|
||||
platform,
|
||||
})
|
||||
);
|
||||
Log.newLine();
|
||||
if (nonInteractive) {
|
||||
Log.log(
|
||||
`When you are done, stop the session with: eas simulator:stop --id ${deviceRunSessionId}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let setup:
|
||||
| { config: string; results: ReturnType<typeof serializeControlConfigResults> }
|
||||
| undefined;
|
||||
if (imported.config?.actions?.length) {
|
||||
const total = imported.config.actions.length;
|
||||
if (!jsonFlag) {
|
||||
Log.newLine();
|
||||
Log.log(
|
||||
`Importing ${total} action${total === 1 ? '' : 's'} from ${imported.config.path}`
|
||||
);
|
||||
}
|
||||
startLocalEgress();
|
||||
const setupSpinner = ora('Importing simulator configuration').start();
|
||||
try {
|
||||
if (egress && !localEgress) {
|
||||
throw new Error('The ready session did not provide local egress connection settings.');
|
||||
}
|
||||
if (egressPromise) {
|
||||
setupSpinner.text = 'Waiting for local egress before applying configuration';
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
try {
|
||||
await Promise.race([
|
||||
egressReady,
|
||||
egressPromise,
|
||||
sessionInterrupt.abortPromise,
|
||||
new Promise<never>((_resolve, reject) => {
|
||||
timer = setTimeout(() => {
|
||||
reject(new Error('Local egress did not connect within 120 seconds.'));
|
||||
}, EGRESS_SETUP_TIMEOUT_MS);
|
||||
timer.unref();
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
if (egressError) {
|
||||
throw egressError;
|
||||
}
|
||||
sessionInterrupt.signal.throwIfAborted();
|
||||
}
|
||||
const access = getPreviewApiAccess(remoteConfig);
|
||||
if (!access) {
|
||||
throw new Error(
|
||||
'This session does not expose an authenticated preview API for control actions.'
|
||||
);
|
||||
}
|
||||
const results = await applyStartConfigAsync(access, imported.config, {
|
||||
signal: sessionInterrupt.signal,
|
||||
onProgress: jsonFlag
|
||||
? undefined
|
||||
: progress => {
|
||||
const label = `[${progress.step}/${progress.total}] ${progress.action}`;
|
||||
if (progress.status === 'running') {
|
||||
setupSpinner.start(label);
|
||||
} else {
|
||||
setupSpinner.succeed(`${label} completed`);
|
||||
if (progress.result.file) {
|
||||
Log.log(`Saved ${progress.result.file}`);
|
||||
} else if (progress.result.output) {
|
||||
Log.log(progress.result.output);
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
sessionInterrupt.signal.throwIfAborted();
|
||||
setup = { config: imported.config.path, results: serializeControlConfigResults(results) };
|
||||
setupSpinner.succeed(
|
||||
`Import complete: ${total} action${total === 1 ? '' : 's'} completed`
|
||||
);
|
||||
} catch (caught) {
|
||||
egressAbortController.abort();
|
||||
await egressPromise;
|
||||
const error = egressError ?? caught;
|
||||
if (sessionInterrupt.signal.aborted && !egressError) {
|
||||
await stopDeviceRunSessionAfterInterruptAsync({
|
||||
graphqlClient,
|
||||
deviceRunSessionId,
|
||||
projectDir,
|
||||
spinner: setupSpinner,
|
||||
sessionInterrupt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (error instanceof ControlConfigExecutionError) {
|
||||
setupSpinner.fail(`[${error.step}/${total}] ${error.action} failed`);
|
||||
if (!jsonFlag) {
|
||||
const skipped = total - error.step;
|
||||
Log.log(`${error.completed.length} completed · 1 failed · ${skipped} skipped`);
|
||||
for (const [index, action] of imported.config.actions.entries()) {
|
||||
if (index >= error.step) {
|
||||
Log.log(` [${index + 1}/${total}] ${action.action} skipped`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
setupSpinner.fail('Simulator configuration import failed');
|
||||
}
|
||||
const stopped = await ensureDeviceRunSessionStoppedSafelyAsync(
|
||||
graphqlClient,
|
||||
deviceRunSessionId
|
||||
);
|
||||
if (stopped) {
|
||||
if (!jsonFlag) {
|
||||
Log.succeed('Stopped the simulator session after setup failed.');
|
||||
}
|
||||
await resetSimulatorEnvAsync(projectDir, deviceRunSessionId).catch(error => {
|
||||
Log.warn(
|
||||
`The session stopped, but ${SIMULATOR_DOTENV_FILE_NAME} could not be cleaned up: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
});
|
||||
} else {
|
||||
Log.warn(
|
||||
`Could not confirm cleanup. Run eas simulator:stop --id ${deviceRunSessionId} to stop the session.`
|
||||
);
|
||||
}
|
||||
sessionInterrupt.dispose();
|
||||
if (jsonFlag) {
|
||||
printJsonOnlyOutput({
|
||||
id: deviceRunSessionId,
|
||||
deviceRunSessionUrl,
|
||||
stopped,
|
||||
setup: {
|
||||
config: imported.config.path,
|
||||
results:
|
||||
error instanceof ControlConfigExecutionError
|
||||
? serializeControlConfigResults(error.completed)
|
||||
: [],
|
||||
error: {
|
||||
...(error instanceof ControlConfigExecutionError
|
||||
? { step: error.step, action: error.action }
|
||||
: {}),
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
},
|
||||
},
|
||||
});
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (jsonFlag || imported.config?.actions?.length) {
|
||||
// Keep the previous session's saved credentials until setup succeeds.
|
||||
await writeReadySimulatorEnvAsync();
|
||||
if (sessionInterrupt.signal.aborted) {
|
||||
await stopDeviceRunSessionAfterInterruptAsync({
|
||||
graphqlClient,
|
||||
deviceRunSessionId,
|
||||
projectDir,
|
||||
spinner: pollSpinner,
|
||||
sessionInterrupt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (jsonFlag) {
|
||||
sessionInterrupt.dispose();
|
||||
printJsonOnlyOutput({
|
||||
id: deviceRunSessionId,
|
||||
name,
|
||||
type: flags.type,
|
||||
deviceRunSessionUrl,
|
||||
...(setup ? { setup } : {}),
|
||||
remoteConfig: sanitizeRemoteConfigForJson(
|
||||
remoteConfig,
|
||||
deviceRunSessionPreviewUrl,
|
||||
flags['public-link'],
|
||||
{ frameAncestors, corsOrigins }
|
||||
),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (nonInteractive) {
|
||||
sessionInterrupt.dispose();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!imported.config?.actions?.length) {
|
||||
startLocalEgress();
|
||||
}
|
||||
|
||||
await waitForSessionEndOrInterruptAsync({
|
||||
graphqlClient,
|
||||
deviceRunSessionId,
|
||||
@@ -628,13 +846,14 @@ export default class Simulator extends EasCommand {
|
||||
projectDir,
|
||||
sessionInterrupt,
|
||||
});
|
||||
if (egressError) {
|
||||
throw egressError;
|
||||
}
|
||||
} finally {
|
||||
sessionInterrupt.signal.removeEventListener('abort', onSessionAbort);
|
||||
egressAbortController.abort();
|
||||
await egressPromise;
|
||||
}
|
||||
if (egressError) {
|
||||
throw egressError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -187,69 +187,6 @@ describe(syncCapabilityIdentifiersForEntitlementsAsync, () => {
|
||||
expect(bundleId.updateBundleIdCapabilityAsync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it(`keeps already linked capability identifiers when linking another one`, async () => {
|
||||
const Apple = require('@expo/apple-utils');
|
||||
mockCapabilities(Apple);
|
||||
const bundleId = {
|
||||
context: {},
|
||||
updateBundleIdCapabilityAsync: jest.fn(),
|
||||
id: 'XXX',
|
||||
} as any;
|
||||
|
||||
const result = await syncCapabilityIdentifiersForEntitlementsAsync(bundleId, {
|
||||
'com.apple.security.application-groups': ['group.expo', 'group.bacon'],
|
||||
});
|
||||
|
||||
expect(result).toStrictEqual({
|
||||
created: ['group.bacon'],
|
||||
linked: ['group.bacon'],
|
||||
});
|
||||
expect(bundleId.updateBundleIdCapabilityAsync).toHaveBeenCalledTimes(1);
|
||||
expect(bundleId.updateBundleIdCapabilityAsync).toHaveBeenLastCalledWith([
|
||||
{
|
||||
capabilityType: 'APP_GROUPS',
|
||||
option: 'ON',
|
||||
relationships: {
|
||||
appGroups: ['XXX-group-1', 'XXX-group-2'],
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it(`keeps already linked capability identifiers when linking an existing unlinked one`, async () => {
|
||||
const Apple = require('@expo/apple-utils');
|
||||
mockCapabilities(Apple);
|
||||
Apple.AppGroup.getAsync.mockResolvedValue([
|
||||
mockItems.appGroup.expo,
|
||||
{ id: 'XXX-group-2', attributes: { identifier: 'group.bacon' } },
|
||||
]);
|
||||
const bundleId = {
|
||||
context: {},
|
||||
updateBundleIdCapabilityAsync: jest.fn(),
|
||||
id: 'XXX',
|
||||
} as any;
|
||||
|
||||
const result = await syncCapabilityIdentifiersForEntitlementsAsync(bundleId, {
|
||||
'com.apple.security.application-groups': ['group.expo', 'group.bacon'],
|
||||
});
|
||||
|
||||
expect(result).toStrictEqual({
|
||||
created: [],
|
||||
linked: ['group.bacon'],
|
||||
});
|
||||
expect(Apple.AppGroup.createAsync).not.toHaveBeenCalled();
|
||||
expect(bundleId.updateBundleIdCapabilityAsync).toHaveBeenCalledTimes(1);
|
||||
expect(bundleId.updateBundleIdCapabilityAsync).toHaveBeenLastCalledWith([
|
||||
{
|
||||
capabilityType: 'APP_GROUPS',
|
||||
option: 'ON',
|
||||
relationships: {
|
||||
appGroups: ['XXX-group-1', 'XXX-group-2'],
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it(`doesn't perform duplicate CapabilityModel.getAsync calls`, async () => {
|
||||
const Apple = require('@expo/apple-utils');
|
||||
mockCapabilities(Apple);
|
||||
|
||||
@@ -94,8 +94,7 @@ export async function syncCapabilityIdentifiersForEntitlementsAsync(
|
||||
(remoteLinkedIds?.[CapabilityModel.type] ?? []).map(model => model.id)
|
||||
);
|
||||
|
||||
// A list of server IDs for linking. The update replaces the linked identifiers,
|
||||
// so this includes the ones that are already linked.
|
||||
// A list of server IDs for linking.
|
||||
const capabilityIdOpaqueIds: string[] = [];
|
||||
|
||||
// Iterate through all the local IDs and see if they exist on the server.
|
||||
@@ -107,8 +106,8 @@ export async function syncCapabilityIdentifiersForEntitlementsAsync(
|
||||
if (!alreadyLinkedOpaqueIds.has(remoteIdModel.id)) {
|
||||
// Link the existing identifier to this bundle.
|
||||
linkedIds.push(remoteIdModel.attributes.identifier);
|
||||
capabilityIdOpaqueIds.push(remoteIdModel.id);
|
||||
}
|
||||
capabilityIdOpaqueIds.push(remoteIdModel.id);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -134,9 +133,7 @@ export async function syncCapabilityIdentifiersForEntitlementsAsync(
|
||||
capabilityIdOpaqueIds.push(remoteIdModel.id);
|
||||
}
|
||||
|
||||
// The update replaces the linked identifiers, so it is sent only when one of them is not
|
||||
// linked yet. An identifier removed from the entitlements therefore stays linked.
|
||||
if (capabilityIdOpaqueIds.some(id => !alreadyLinkedOpaqueIds.has(id))) {
|
||||
if (capabilityIdOpaqueIds.length) {
|
||||
updateRequest.push({
|
||||
capabilityType: classifier.capability,
|
||||
option: CapabilityTypeOption.ON,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { OperationResult, OperationResultSource } from '@urql/core';
|
||||
import { OperationContext, OperationResult, OperationResultSource } from '@urql/core';
|
||||
import gql from 'graphql-tag';
|
||||
|
||||
import { ExpoGraphqlClient } from '../../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
@@ -96,110 +96,115 @@ export const DeviceRunSessionQuery = {
|
||||
deviceRunSessionId: string
|
||||
): Promise<DeviceRunSessionByIdQuery['deviceRunSessions']['byId']> {
|
||||
const data = await withErrorHandlingAsync(
|
||||
graphqlClient
|
||||
.query<DeviceRunSessionByIdQuery, DeviceRunSessionByIdQueryVariables>(
|
||||
gql`
|
||||
query DeviceRunSessionByIdQuery($deviceRunSessionId: ID!) {
|
||||
deviceRunSessions {
|
||||
byId(deviceRunSessionId: $deviceRunSessionId) {
|
||||
id
|
||||
name
|
||||
tags
|
||||
publicPreview
|
||||
status
|
||||
type
|
||||
platform
|
||||
createdAt
|
||||
startedAt
|
||||
finishedAt
|
||||
updatedAt
|
||||
app {
|
||||
id
|
||||
slug
|
||||
ownerAccount {
|
||||
id
|
||||
name
|
||||
}
|
||||
}
|
||||
artifacts {
|
||||
id
|
||||
name
|
||||
filename
|
||||
downloadUrl
|
||||
fileSizeBytes
|
||||
metadata
|
||||
createdAt
|
||||
updatedAt
|
||||
}
|
||||
remoteConfig {
|
||||
__typename
|
||||
... on AgentDeviceRunSessionRemoteConfig {
|
||||
agentDeviceRemoteSessionUrl
|
||||
agentDeviceRemoteSessionToken
|
||||
webPreviewUrl
|
||||
webPreviewToken
|
||||
previewApiUrl
|
||||
egressUrl
|
||||
egressToken
|
||||
egressFingerprint
|
||||
egressPort
|
||||
}
|
||||
... on ArgentRunSessionRemoteConfig {
|
||||
egressUrl
|
||||
egressToken
|
||||
egressFingerprint
|
||||
egressPort
|
||||
toolsUrl
|
||||
toolsAuthToken
|
||||
webPreviewUrl
|
||||
webPreviewToken
|
||||
previewApiUrl
|
||||
}
|
||||
... on AppiumRunSessionRemoteConfig {
|
||||
egressUrl
|
||||
egressToken
|
||||
egressFingerprint
|
||||
egressPort
|
||||
appiumUrl
|
||||
capabilities
|
||||
webPreviewUrl
|
||||
webPreviewToken
|
||||
previewApiUrl
|
||||
}
|
||||
... on ServeSimRunSessionRemoteConfig {
|
||||
egressUrl
|
||||
egressToken
|
||||
egressFingerprint
|
||||
egressPort
|
||||
previewUrl
|
||||
previewToken
|
||||
previewApiUrl
|
||||
}
|
||||
... on WebPreviewOnlyRunSessionRemoteConfig {
|
||||
egressUrl
|
||||
egressToken
|
||||
egressFingerprint
|
||||
egressPort
|
||||
previewUrl: webPreviewUrl
|
||||
previewToken: webPreviewToken
|
||||
previewApiUrl
|
||||
}
|
||||
}
|
||||
turtleJobRun {
|
||||
id
|
||||
status
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
{ deviceRunSessionId },
|
||||
{ requestPolicy: 'network-only' }
|
||||
)
|
||||
.toPromise()
|
||||
DeviceRunSessionQuery.byId(graphqlClient, deviceRunSessionId).toPromise()
|
||||
);
|
||||
return data.deviceRunSessions.byId;
|
||||
},
|
||||
byId(
|
||||
graphqlClient: ExpoGraphqlClient,
|
||||
deviceRunSessionId: string,
|
||||
context: Partial<OperationContext> = {}
|
||||
): OperationResultSource<OperationResult<DeviceRunSessionByIdQuery>> {
|
||||
return graphqlClient.query<DeviceRunSessionByIdQuery, DeviceRunSessionByIdQueryVariables>(
|
||||
gql`
|
||||
query DeviceRunSessionByIdQuery($deviceRunSessionId: ID!) {
|
||||
deviceRunSessions {
|
||||
byId(deviceRunSessionId: $deviceRunSessionId) {
|
||||
id
|
||||
name
|
||||
tags
|
||||
publicPreview
|
||||
status
|
||||
type
|
||||
platform
|
||||
createdAt
|
||||
startedAt
|
||||
finishedAt
|
||||
updatedAt
|
||||
app {
|
||||
id
|
||||
slug
|
||||
ownerAccount {
|
||||
id
|
||||
name
|
||||
}
|
||||
}
|
||||
artifacts {
|
||||
id
|
||||
name
|
||||
filename
|
||||
downloadUrl
|
||||
fileSizeBytes
|
||||
metadata
|
||||
createdAt
|
||||
updatedAt
|
||||
}
|
||||
remoteConfig {
|
||||
__typename
|
||||
... on AgentDeviceRunSessionRemoteConfig {
|
||||
agentDeviceRemoteSessionUrl
|
||||
agentDeviceRemoteSessionToken
|
||||
webPreviewUrl
|
||||
webPreviewToken
|
||||
previewApiUrl
|
||||
egressUrl
|
||||
egressToken
|
||||
egressFingerprint
|
||||
egressPort
|
||||
}
|
||||
... on ArgentRunSessionRemoteConfig {
|
||||
egressUrl
|
||||
egressToken
|
||||
egressFingerprint
|
||||
egressPort
|
||||
toolsUrl
|
||||
toolsAuthToken
|
||||
webPreviewUrl
|
||||
webPreviewToken
|
||||
previewApiUrl
|
||||
}
|
||||
... on AppiumRunSessionRemoteConfig {
|
||||
egressUrl
|
||||
egressToken
|
||||
egressFingerprint
|
||||
egressPort
|
||||
appiumUrl
|
||||
capabilities
|
||||
webPreviewUrl
|
||||
webPreviewToken
|
||||
previewApiUrl
|
||||
}
|
||||
... on ServeSimRunSessionRemoteConfig {
|
||||
egressUrl
|
||||
egressToken
|
||||
egressFingerprint
|
||||
egressPort
|
||||
previewUrl
|
||||
previewToken
|
||||
previewApiUrl
|
||||
}
|
||||
... on WebPreviewOnlyRunSessionRemoteConfig {
|
||||
egressUrl
|
||||
egressToken
|
||||
egressFingerprint
|
||||
egressPort
|
||||
previewUrl: webPreviewUrl
|
||||
previewToken: webPreviewToken
|
||||
previewApiUrl
|
||||
}
|
||||
}
|
||||
turtleJobRun {
|
||||
id
|
||||
status
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
{ deviceRunSessionId },
|
||||
{ requestPolicy: 'network-only', ...context }
|
||||
);
|
||||
},
|
||||
async listByAppIdAsync(
|
||||
graphqlClient: ExpoGraphqlClient,
|
||||
{
|
||||
|
||||
@@ -0,0 +1,408 @@
|
||||
import * as fs from 'fs-extra';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { executeControlActionAsync, prepareControlActionAsync } from '../controlActions';
|
||||
import { HostActionCatalog, HostActionConnection, HostActionResult } from '../hostActions';
|
||||
|
||||
const catalog: HostActionCatalog = {
|
||||
settings: { type: 'object' },
|
||||
install: { upload: 'uploadId', uploadAs: 'id' },
|
||||
media: { upload: 'path' },
|
||||
camera: { upload: 'target', uploadWhen: { source: 'file' }, keepUpload: true },
|
||||
screenshot: { output: 'path' },
|
||||
download: { output: 'base64' },
|
||||
};
|
||||
const ok = (stdout = ''): HostActionResult => ({ stdout, stderr: '', exitCode: 0 });
|
||||
|
||||
describe('control action preparation and execution', () => {
|
||||
let tmpDir: string;
|
||||
let controller: AbortController;
|
||||
let result: HostActionResult;
|
||||
let connection: HostActionConnection;
|
||||
let requestAsync: jest.Mock<Promise<HostActionResult>, [string, Record<string, unknown>?]>;
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'control-actions-'));
|
||||
controller = new AbortController();
|
||||
result = ok(' on\n');
|
||||
requestAsync = jest.fn(async (action: string, params: Record<string, unknown> = {}) => {
|
||||
if (action === 'upload.append') {
|
||||
return ok(`/remote/staging/${params.uploadId}\n`);
|
||||
}
|
||||
if (action === 'upload.remove') {
|
||||
return ok();
|
||||
}
|
||||
if (action === 'file.readBase64') {
|
||||
return ok(Buffer.from('download bytes').toString('base64'));
|
||||
}
|
||||
return result;
|
||||
});
|
||||
connection = {
|
||||
udid: '90858C9D-BC34-4A0A-93D4-E4939A681A72',
|
||||
signal: controller.signal,
|
||||
requestAsync,
|
||||
close: () => {
|
||||
controller.abort(new Error('closed'));
|
||||
},
|
||||
};
|
||||
await fs.writeFile(path.join(tmpDir, 'fixture.json'), 'file bytes');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await fs.remove(tmpDir);
|
||||
});
|
||||
|
||||
it('copies typed and empty values without parsing stdout', async () => {
|
||||
const params = { enabled: false, count: 0, text: '', nested: { values: ['original'] } };
|
||||
const plan = await prepareControlActionAsync(catalog, { action: 'settings', params });
|
||||
params.text = 'changed';
|
||||
expect(plan.params).toEqual({
|
||||
enabled: false,
|
||||
count: 0,
|
||||
text: '',
|
||||
nested: { values: ['original'] },
|
||||
});
|
||||
result = ok(' {"value":0}\n');
|
||||
|
||||
await expect(executeControlActionAsync(connection, plan)).resolves.toEqual({
|
||||
output: '{"value":0}',
|
||||
file: null,
|
||||
});
|
||||
expect(requestAsync).toHaveBeenCalledWith('settings', plan.params);
|
||||
result = ok('');
|
||||
await expect(executeControlActionAsync(connection, plan)).resolves.toEqual({
|
||||
output: '',
|
||||
file: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects unknown actions and inapplicable output before execution', async () => {
|
||||
await expect(
|
||||
prepareControlActionAsync(catalog, { action: 'toString', params: {} })
|
||||
).rejects.toThrow('Unknown simulator action');
|
||||
await expect(
|
||||
prepareControlActionAsync(catalog, { action: 'settings', params: {}, outputPath: './out' })
|
||||
).rejects.toThrow('does not return a file');
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('resolves explicit local files and outputs against the supplied directory', async () => {
|
||||
const plan = await prepareControlActionAsync(
|
||||
catalog,
|
||||
{
|
||||
action: 'install',
|
||||
params: {},
|
||||
file: 'fixture.json',
|
||||
},
|
||||
{ localFileMode: 'explicit', baseDir: tmpDir }
|
||||
);
|
||||
expect(plan.localFile).toEqual({ param: 'uploadId', path: path.join(tmpDir, 'fixture.json') });
|
||||
const output = await prepareControlActionAsync(
|
||||
catalog,
|
||||
{
|
||||
action: 'download',
|
||||
params: {},
|
||||
outputPath: 'result.json',
|
||||
},
|
||||
{ baseDir: tmpDir }
|
||||
);
|
||||
expect(output.outputPath).toBe(path.join(tmpDir, 'result.json'));
|
||||
});
|
||||
|
||||
it('preserves an explicitly requested output directory when resolving relative paths', async () => {
|
||||
await expect(
|
||||
prepareControlActionAsync(
|
||||
catalog,
|
||||
{
|
||||
action: 'download',
|
||||
params: {},
|
||||
outputPath: 'missing/',
|
||||
},
|
||||
{ baseDir: tmpDir }
|
||||
)
|
||||
).rejects.toThrow('does not exist');
|
||||
});
|
||||
|
||||
it('rejects ambiguous or inapplicable explicit uploads', async () => {
|
||||
for (const action of [
|
||||
{ action: 'settings', params: {} },
|
||||
{ action: 'camera', params: { source: 'webcam' } },
|
||||
{ action: 'install', params: { uploadId: 'already-supplied' } },
|
||||
]) {
|
||||
await expect(
|
||||
prepareControlActionAsync(catalog, {
|
||||
...action,
|
||||
file: path.join(tmpDir, 'fixture.json'),
|
||||
})
|
||||
).rejects.toThrow();
|
||||
}
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects missing, empty and directory inputs before execution', async () => {
|
||||
await fs.writeFile(path.join(tmpDir, 'empty'), '');
|
||||
for (const file of ['missing', 'empty', '.']) {
|
||||
await expect(
|
||||
prepareControlActionAsync(
|
||||
catalog,
|
||||
{
|
||||
action: 'install',
|
||||
params: {},
|
||||
file,
|
||||
},
|
||||
{ baseDir: tmpDir }
|
||||
)
|
||||
).rejects.toThrow();
|
||||
}
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses explicit host paths and does not infer uploads in explicit mode', async () => {
|
||||
const localFile = path.join(tmpDir, 'fixture.json');
|
||||
expect(
|
||||
(
|
||||
await prepareControlActionAsync(catalog, {
|
||||
action: 'media',
|
||||
params: { path: localFile },
|
||||
})
|
||||
).localFile?.path
|
||||
).toBe(localFile);
|
||||
const remotePath = path.join(tmpDir, 'remote-only');
|
||||
expect(
|
||||
(
|
||||
await prepareControlActionAsync(catalog, {
|
||||
action: 'media',
|
||||
params: { path: `host:${remotePath}` },
|
||||
})
|
||||
).localFile
|
||||
).toBeUndefined();
|
||||
await expect(
|
||||
prepareControlActionAsync(
|
||||
catalog,
|
||||
{
|
||||
action: 'media',
|
||||
params: { path: 'missing-relative' },
|
||||
},
|
||||
{ baseDir: tmpDir }
|
||||
)
|
||||
).rejects.toThrow('does not exist on this computer');
|
||||
expect(
|
||||
(
|
||||
await prepareControlActionAsync(
|
||||
catalog,
|
||||
{
|
||||
action: 'media',
|
||||
params: { path: localFile },
|
||||
},
|
||||
{ localFileMode: 'explicit' }
|
||||
)
|
||||
).localFile
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
(
|
||||
await prepareControlActionAsync(catalog, {
|
||||
action: 'camera',
|
||||
params: { source: 'webcam', target: 'Built-in Camera' },
|
||||
})
|
||||
).localFile
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it('resolves a direct relative upload against baseDir without rewriting caller parameters', async () => {
|
||||
const params = { path: './fixture.json' };
|
||||
const plan = await prepareControlActionAsync(
|
||||
catalog,
|
||||
{ action: 'media', params },
|
||||
{ baseDir: tmpDir }
|
||||
);
|
||||
expect(plan.localFile?.path).toBe(path.join(tmpDir, 'fixture.json'));
|
||||
await executeControlActionAsync(connection, plan);
|
||||
expect(requestAsync.mock.calls[1]).toEqual([
|
||||
'media',
|
||||
{ path: `/remote/staging/${requestAsync.mock.calls[0][1]?.uploadId}` },
|
||||
]);
|
||||
expect(params).toEqual({ path: './fixture.json' });
|
||||
});
|
||||
|
||||
(process.platform === 'win32' ? it.skip : it)(
|
||||
'rejects a named pipe before opening it for upload',
|
||||
async () => {
|
||||
const file = path.join(tmpDir, 'input.pipe');
|
||||
execFileSync('mkfifo', [file]);
|
||||
await expect(
|
||||
prepareControlActionAsync(catalog, {
|
||||
action: 'install',
|
||||
params: {},
|
||||
file,
|
||||
})
|
||||
).rejects.toThrow('not a regular file');
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
(process.platform === 'win32' || process.getuid?.() === 0 ? it.skip : it)(
|
||||
'rejects a local file that cannot be read before upload',
|
||||
async () => {
|
||||
const file = path.join(tmpDir, 'fixture.json');
|
||||
await fs.chmod(file, 0);
|
||||
try {
|
||||
await expect(
|
||||
prepareControlActionAsync(catalog, {
|
||||
action: 'install',
|
||||
params: {},
|
||||
file,
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'EACCES' });
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await fs.chmod(file, 0o600);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
it('substitutes an upload ID without changing the plan and removes staging after success', async () => {
|
||||
const plan = await prepareControlActionAsync(catalog, {
|
||||
action: 'install',
|
||||
params: {},
|
||||
file: path.join(tmpDir, 'fixture.json'),
|
||||
});
|
||||
await executeControlActionAsync(connection, plan);
|
||||
const uploadId = requestAsync.mock.calls[0][1]?.uploadId;
|
||||
expect(uploadId).toMatch(/^eas-cli-[0-9a-f-]{36}\.json$/);
|
||||
expect(requestAsync.mock.calls).toEqual([
|
||||
[
|
||||
'upload.append',
|
||||
{ uploadId, data: Buffer.from('file bytes').toString('base64'), first: true },
|
||||
],
|
||||
['install', { uploadId }],
|
||||
['upload.remove', { uploadId }],
|
||||
]);
|
||||
expect(plan.params).toEqual({});
|
||||
});
|
||||
|
||||
it('keeps a successful camera upload but cleans it after a failed action', async () => {
|
||||
const plan = await prepareControlActionAsync(catalog, {
|
||||
action: 'camera',
|
||||
params: { source: 'file' },
|
||||
file: path.join(tmpDir, 'fixture.json'),
|
||||
});
|
||||
await executeControlActionAsync(connection, plan);
|
||||
expect(requestAsync.mock.calls.map(([name]) => name)).toEqual(['upload.append', 'camera']);
|
||||
expect(requestAsync.mock.calls[1][1]).toEqual({
|
||||
source: 'file',
|
||||
target: `/remote/staging/${requestAsync.mock.calls[0][1]?.uploadId}`,
|
||||
});
|
||||
requestAsync.mockClear();
|
||||
result = { stdout: '', stderr: 'camera unavailable', exitCode: 1 };
|
||||
await expect(executeControlActionAsync(connection, plan)).rejects.toThrow('camera unavailable');
|
||||
expect(requestAsync.mock.calls.map(([name]) => name)).toEqual([
|
||||
'upload.append',
|
||||
'camera',
|
||||
'upload.remove',
|
||||
]);
|
||||
expect(controller.signal.aborted).toBe(false);
|
||||
});
|
||||
|
||||
it('cleans staging if validation rejects real uploaded parameters', async () => {
|
||||
const plan = await prepareControlActionAsync(catalog, {
|
||||
action: 'camera',
|
||||
params: { source: 'file' },
|
||||
file: path.join(tmpDir, 'fixture.json'),
|
||||
});
|
||||
const validateParams = jest.fn(() => {
|
||||
throw new Error('invalid uploaded path');
|
||||
});
|
||||
await expect(executeControlActionAsync(connection, plan, { validateParams })).rejects.toThrow(
|
||||
'invalid uploaded path'
|
||||
);
|
||||
expect(validateParams).toHaveBeenCalledWith({
|
||||
source: 'file',
|
||||
target: `/remote/staging/${requestAsync.mock.calls[0][1]?.uploadId}`,
|
||||
});
|
||||
expect(requestAsync.mock.calls.map(([name]) => name)).toEqual([
|
||||
'upload.append',
|
||||
'upload.remove',
|
||||
]);
|
||||
});
|
||||
|
||||
it('removes a failed upload without running the action', async () => {
|
||||
requestAsync.mockImplementation(async action =>
|
||||
action === 'upload.append' ? { stdout: '', stderr: 'staging full', exitCode: 1 } : ok()
|
||||
);
|
||||
const plan = await prepareControlActionAsync(catalog, {
|
||||
action: 'install',
|
||||
params: {},
|
||||
file: path.join(tmpDir, 'fixture.json'),
|
||||
});
|
||||
await expect(executeControlActionAsync(connection, plan)).rejects.toThrow('staging full');
|
||||
expect(requestAsync.mock.calls.map(([name]) => name)).toEqual([
|
||||
'upload.append',
|
||||
'upload.remove',
|
||||
]);
|
||||
});
|
||||
|
||||
it('saves an action output and returns the path instead of raw bytes', async () => {
|
||||
result = ok(Buffer.from('file content').toString('base64'));
|
||||
const outputPath = path.join(tmpDir, 'output');
|
||||
const plan = await prepareControlActionAsync(catalog, {
|
||||
action: 'download',
|
||||
params: {},
|
||||
outputPath,
|
||||
});
|
||||
await expect(executeControlActionAsync(connection, plan)).resolves.toEqual({
|
||||
output: '',
|
||||
file: outputPath,
|
||||
});
|
||||
expect(await fs.readFile(outputPath, 'utf8')).toBe('file content');
|
||||
});
|
||||
|
||||
it('removes staging if the output directory disappears after preparation', async () => {
|
||||
const outputDir = path.join(tmpDir, 'output');
|
||||
await fs.mkdir(outputDir);
|
||||
const plan = await prepareControlActionAsync(
|
||||
{
|
||||
snapshot: { upload: 'path', output: 'base64' },
|
||||
},
|
||||
{
|
||||
action: 'snapshot',
|
||||
params: {},
|
||||
file: path.join(tmpDir, 'fixture.json'),
|
||||
outputPath: path.join(outputDir, 'snapshot.png'),
|
||||
}
|
||||
);
|
||||
await fs.remove(outputDir);
|
||||
result = ok(Buffer.from('png').toString('base64'));
|
||||
await expect(executeControlActionAsync(connection, plan)).rejects.toMatchObject({
|
||||
code: 'ENOENT',
|
||||
});
|
||||
expect(requestAsync.mock.calls.map(([name]) => name)).toEqual([
|
||||
'upload.append',
|
||||
'snapshot',
|
||||
'upload.remove',
|
||||
]);
|
||||
expect(controller.signal.aborted).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ stdout: 'failure on stdout', stderr: '', exitCode: 1 }, 'failure on stdout'],
|
||||
[{ stdout: '', stderr: '', exitCode: 7 }, 'exit code 7'],
|
||||
])(
|
||||
'reports server failure details without closing a usable connection',
|
||||
async (failure, message) => {
|
||||
result = failure as HostActionResult;
|
||||
const plan = await prepareControlActionAsync(catalog, { action: 'settings', params: {} });
|
||||
await expect(executeControlActionAsync(connection, plan)).rejects.toThrow(message);
|
||||
expect(controller.signal.aborted).toBe(false);
|
||||
}
|
||||
);
|
||||
|
||||
it('does not send work after a terminal connection loss', async () => {
|
||||
const plan = await prepareControlActionAsync(catalog, { action: 'settings', params: {} });
|
||||
const error = new Error('connection lost');
|
||||
controller.abort(error);
|
||||
await expect(executeControlActionAsync(connection, plan)).rejects.toBe(error);
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,428 @@
|
||||
import fs from 'fs-extra';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { executeControlConfigAsync, prepareControlConfigAsync } from '../controlConfig';
|
||||
import { HostActionCatalog, HostActionConnection, HostActionResult } from '../hostActions';
|
||||
|
||||
const itWithChmod = process.platform === 'win32' || process.geteuid?.() === 0 ? it.skip : it;
|
||||
|
||||
const catalog: HostActionCatalog = {
|
||||
'keyboard.set': {
|
||||
type: 'object',
|
||||
properties: { udid: { type: 'string' }, value: { enum: ['on', 'off'] } },
|
||||
required: ['udid', 'value'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
'file.push': {
|
||||
type: 'object',
|
||||
properties: {
|
||||
udid: { type: 'string' },
|
||||
uploadId: { type: 'string', pattern: '^[A-Za-z0-9._-]+$' },
|
||||
destination: { type: 'string' },
|
||||
},
|
||||
required: ['udid', 'uploadId', 'destination'],
|
||||
additionalProperties: false,
|
||||
upload: 'uploadId',
|
||||
uploadAs: 'id',
|
||||
},
|
||||
'camera.set': {
|
||||
type: 'object',
|
||||
properties: {
|
||||
udid: { type: 'string' },
|
||||
source: { enum: ['file', 'webcam'] },
|
||||
path: { type: 'string' },
|
||||
},
|
||||
required: ['udid', 'source', 'path'],
|
||||
upload: 'path',
|
||||
uploadWhen: { source: 'file' },
|
||||
keepUpload: true,
|
||||
},
|
||||
screenshot: {
|
||||
type: 'object',
|
||||
properties: { udid: { type: 'string' } },
|
||||
required: ['udid'],
|
||||
additionalProperties: false,
|
||||
output: 'base64',
|
||||
},
|
||||
echo: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
udid: { type: 'string' },
|
||||
text: { type: 'string' },
|
||||
enabled: { type: 'boolean' },
|
||||
count: { type: 'number' },
|
||||
items: { type: 'array', items: { type: 'string' } },
|
||||
},
|
||||
required: ['udid'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
};
|
||||
|
||||
describe('simulator control configuration', () => {
|
||||
let folder: string;
|
||||
let filePath: string;
|
||||
const ok = (stdout = ''): HostActionResult => ({ stdout, stderr: '', exitCode: 0 });
|
||||
const requestAsync = jest.fn(async (action: string): Promise<HostActionResult> => {
|
||||
if (action === 'upload.append') {
|
||||
return ok('/remote/staged.txt\n');
|
||||
}
|
||||
if (action === 'screenshot') {
|
||||
return ok(Buffer.from('png').toString('base64'));
|
||||
}
|
||||
return ok('done\n');
|
||||
});
|
||||
const connection: HostActionConnection = {
|
||||
requestAsync,
|
||||
close: jest.fn(),
|
||||
signal: new AbortController().signal,
|
||||
udid: 'owned-udid',
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks();
|
||||
folder = await fs.mkdtemp(path.join(os.tmpdir(), 'control-config-'));
|
||||
filePath = path.join(folder, 'simulator.json');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await fs.remove(folder);
|
||||
});
|
||||
|
||||
async function writeConfig(actions: unknown[], rest = {}): Promise<void> {
|
||||
await fs.writeJson(filePath, { version: 1, actions, ...rest });
|
||||
}
|
||||
|
||||
it('preserves typed, omitted and empty values without changing the input', async () => {
|
||||
const params = { text: '', enabled: false, count: 0, items: ['first', 'second'] };
|
||||
await writeConfig([{ action: 'echo', params }, { action: 'echo' }]);
|
||||
const config = await prepareControlConfigAsync(catalog, filePath, connection.udid);
|
||||
const results = await executeControlConfigAsync(connection, config);
|
||||
expect(requestAsync.mock.calls).toEqual([
|
||||
['echo', params],
|
||||
['echo', {}],
|
||||
]);
|
||||
expect(results).toEqual([
|
||||
{ action: 'echo', output: 'done', file: null },
|
||||
{ action: 'echo', output: 'done', file: null },
|
||||
]);
|
||||
expect((await fs.readJson(filePath)).actions[0].params).toEqual(params);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ version: 2, actions: [{ action: 'echo' }] },
|
||||
{ version: 1, actions: [] },
|
||||
{ version: 1, actions: [{ action: 'echo', extra: true }] },
|
||||
{ version: 1, actions: [{ action: 'echo', params: [] }] },
|
||||
{ version: 1, actions: [{ action: 'echo', params: { udid: 'other-device' } }] },
|
||||
{ version: 1, actions: [{ action: 'echo' }], sessionId: 'other-session' },
|
||||
])('rejects an invalid config envelope: %j', async input => {
|
||||
await fs.writeJson(filePath, input);
|
||||
await expect(prepareControlConfigAsync(catalog, filePath, connection.udid)).rejects.toThrow();
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports invalid JSON with its config path', async () => {
|
||||
await fs.writeFile(filePath, '{ invalid');
|
||||
await expect(prepareControlConfigAsync(catalog, filePath, connection.udid)).rejects.toThrow(
|
||||
'simulator.json'
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects a missing config file', async () => {
|
||||
await expect(prepareControlConfigAsync(catalog, filePath, connection.udid)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('preflights later steps before running any action or upload', async () => {
|
||||
await fs.writeFile(path.join(folder, 'fixture.txt'), 'content');
|
||||
await writeConfig([
|
||||
{ action: 'file.push', params: { destination: 'data.txt' }, file: './fixture.txt' },
|
||||
{ action: 'keyboard.set', params: { value: 'invalid' } },
|
||||
]);
|
||||
await expect(prepareControlConfigAsync(catalog, filePath, connection.udid)).rejects.toThrow(
|
||||
/step 2.*keyboard\.set/i
|
||||
);
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects unknown actions before any execution', async () => {
|
||||
await writeConfig([{ action: 'echo' }, { action: 'missing' }]);
|
||||
await expect(prepareControlConfigAsync(catalog, filePath, connection.udid)).rejects.toThrow(
|
||||
/step 2.*missing/i
|
||||
);
|
||||
});
|
||||
|
||||
it('requires an explicit output for path downloads before executing earlier steps', async () => {
|
||||
const withDownload: HostActionCatalog = {
|
||||
...catalog,
|
||||
'screenshot.capture': { ...catalog.screenshot, output: 'path' },
|
||||
};
|
||||
await writeConfig([{ action: 'echo' }, { action: 'screenshot.capture' }]);
|
||||
await expect(
|
||||
prepareControlConfigAsync(withDownload, filePath, connection.udid)
|
||||
).rejects.toThrow(/step 2.*screenshot\.capture.*output/i);
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects mistyped parameters rather than coercing JSON', async () => {
|
||||
await writeConfig([{ action: 'echo', params: { count: '12' } }]);
|
||||
await expect(prepareControlConfigAsync(catalog, filePath, connection.udid)).rejects.toThrow(
|
||||
/count/i
|
||||
);
|
||||
});
|
||||
|
||||
it('uses JSON Schema 2020-12 and leaves schema defaults omitted', async () => {
|
||||
const withTuple: HostActionCatalog = {
|
||||
tuple: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
udid: { type: 'string' },
|
||||
value: {
|
||||
type: 'array',
|
||||
prefixItems: [{ type: 'number' }, { type: 'string' }],
|
||||
items: false,
|
||||
},
|
||||
enabled: { type: 'boolean', default: true },
|
||||
},
|
||||
required: ['udid', 'value'],
|
||||
},
|
||||
};
|
||||
await writeConfig([{ action: 'tuple', params: { value: [7, 'text'] } }]);
|
||||
const config = await prepareControlConfigAsync(withTuple, filePath, connection.udid);
|
||||
await executeControlConfigAsync(connection, config);
|
||||
expect(requestAsync).toHaveBeenCalledWith('tuple', { value: [7, 'text'] });
|
||||
await writeConfig([{ action: 'tuple', params: { value: ['wrong', 'text'] } }]);
|
||||
await expect(prepareControlConfigAsync(withTuple, filePath, connection.udid)).rejects.toThrow(
|
||||
/params\/value\/0/
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses to execute a plan checked for another simulator', async () => {
|
||||
await writeConfig([{ action: 'echo' }]);
|
||||
const config = await prepareControlConfigAsync(catalog, filePath, 'another-udid');
|
||||
await expect(executeControlConfigAsync(connection, config)).rejects.toThrow(
|
||||
'simulator changed'
|
||||
);
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('resolves explicit local files relative to the config and substitutes upload IDs', async () => {
|
||||
await fs.writeFile(path.join(folder, 'fixture.txt'), 'content');
|
||||
await writeConfig([
|
||||
{ action: 'file.push', params: { destination: 'data.txt' }, file: './fixture.txt' },
|
||||
]);
|
||||
const config = await prepareControlConfigAsync(catalog, filePath, connection.udid);
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
await executeControlConfigAsync(connection, config);
|
||||
expect(requestAsync).toHaveBeenCalledWith('upload.append', {
|
||||
uploadId: expect.stringMatching(/^eas-cli-.+\.txt$/),
|
||||
data: Buffer.from('content').toString('base64'),
|
||||
first: true,
|
||||
});
|
||||
const call = requestAsync.mock.calls.find(([action]) => action === 'file.push');
|
||||
expect(call).toEqual([
|
||||
'file.push',
|
||||
{ destination: 'data.txt', uploadId: expect.stringMatching(/^eas-cli-.+\.txt$/) },
|
||||
]);
|
||||
expect(requestAsync).toHaveBeenLastCalledWith('upload.remove', {
|
||||
uploadId: expect.stringMatching(/^eas-cli-.+\.txt$/),
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps remote paths unchanged even when a similarly named local file exists', async () => {
|
||||
const localPath = path.join(folder, 'fixture.txt');
|
||||
await fs.writeFile(localPath, 'local content');
|
||||
await writeConfig([{ action: 'camera.set', params: { source: 'file', path: localPath } }]);
|
||||
const config = await prepareControlConfigAsync(catalog, filePath, connection.udid);
|
||||
await executeControlConfigAsync(connection, config);
|
||||
expect(requestAsync.mock.calls).toEqual([['camera.set', { source: 'file', path: localPath }]]);
|
||||
});
|
||||
|
||||
it('resolves output paths relative to the config', async () => {
|
||||
await writeConfig([{ action: 'screenshot', output: './screen.png' }]);
|
||||
const config = await prepareControlConfigAsync(catalog, filePath, connection.udid);
|
||||
const results = await executeControlConfigAsync(connection, config);
|
||||
expect(await fs.readFile(path.join(folder, 'screen.png'), 'utf8')).toBe('png');
|
||||
expect(results[0].file).toBe(path.join(folder, 'screen.png'));
|
||||
});
|
||||
|
||||
itWithChmod.each(['existing file', 'new file', 'download directory'])(
|
||||
'rejects an unwritable %s before running earlier actions',
|
||||
async kind => {
|
||||
const destination = path.join(folder, 'read-only');
|
||||
const output = kind === 'new file' ? path.join(destination, 'screen.png') : destination;
|
||||
if (kind === 'existing file') {
|
||||
await fs.writeFile(destination, 'existing image');
|
||||
await fs.chmod(destination, 0o444);
|
||||
} else {
|
||||
await fs.mkdir(destination);
|
||||
await fs.chmod(destination, 0o555);
|
||||
}
|
||||
const action = kind === 'download directory' ? 'download' : 'screenshot';
|
||||
const withDownload: HostActionCatalog = {
|
||||
...catalog,
|
||||
download: { ...catalog.screenshot, output: 'path' },
|
||||
};
|
||||
try {
|
||||
await writeConfig([{ action: 'echo' }, { action, output }]);
|
||||
await expect(
|
||||
prepareControlConfigAsync(withDownload, filePath, connection.udid)
|
||||
).rejects.toThrow(/step 2.*(EACCES|permission)/i);
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await fs.chmod(destination, 0o755);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
it.each(['app.install', 'media.add'])(
|
||||
'rejects an explicit file combined with another source for %s',
|
||||
async action => {
|
||||
const realCatalog: HostActionCatalog = require('./fixtures/hostActionCatalog.json');
|
||||
await fs.writeFile(path.join(folder, 'new.ipa'), 'new bytes');
|
||||
await writeConfig([{ action, params: { uploadId: 'old.ipa' }, file: './new.ipa' }]);
|
||||
await expect(
|
||||
prepareControlConfigAsync(realCatalog, filePath, connection.udid)
|
||||
).rejects.toThrow(/file.*source/i);
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
itWithChmod(
|
||||
'rejects a new output in a write-only parent before running earlier actions',
|
||||
async () => {
|
||||
const destination = path.join(folder, 'write-only');
|
||||
await fs.mkdir(destination);
|
||||
await fs.chmod(destination, 0o222);
|
||||
try {
|
||||
await writeConfig([
|
||||
{ action: 'echo' },
|
||||
{ action: 'screenshot', output: path.join(destination, 'screen.png') },
|
||||
]);
|
||||
await expect(prepareControlConfigAsync(catalog, filePath, connection.udid)).rejects.toThrow(
|
||||
/step 2.*(EACCES|permission)/i
|
||||
);
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await fs.chmod(destination, 0o755);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
it('rejects a denied output permission check before running earlier actions', async () => {
|
||||
await writeConfig([
|
||||
{ action: 'echo' },
|
||||
{ action: 'screenshot', output: path.join(folder, 'screen.png') },
|
||||
]);
|
||||
const access = jest.spyOn(fs, 'access').mockImplementationOnce(async () => {
|
||||
throw Object.assign(new Error('Permission denied'), { code: 'EACCES' });
|
||||
});
|
||||
try {
|
||||
await expect(prepareControlConfigAsync(catalog, filePath, connection.udid)).rejects.toThrow(
|
||||
/step 2.*Permission denied/i
|
||||
);
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
access.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('accepts an explicit file as the only source of a union action', async () => {
|
||||
const realCatalog: HostActionCatalog = require('./fixtures/hostActionCatalog.json');
|
||||
await fs.writeFile(path.join(folder, 'new.ipa'), 'new bytes');
|
||||
await writeConfig([{ action: 'app.install', file: './new.ipa' }]);
|
||||
const config = await prepareControlConfigAsync(realCatalog, filePath, connection.udid);
|
||||
await executeControlConfigAsync(connection, config);
|
||||
expect(requestAsync).toHaveBeenCalledWith('app.install', { path: '/remote/staged.txt' });
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ action: 'echo', file: './fixture.txt' },
|
||||
{ action: 'file.push', params: { destination: 'data.txt' }, file: './missing.txt' },
|
||||
{ action: 'file.push', params: { destination: 'data.txt' }, file: '.' },
|
||||
{ action: 'camera.set', params: { source: 'webcam', path: 'camera' }, file: './fixture.txt' },
|
||||
{
|
||||
action: 'file.push',
|
||||
params: { destination: 'data.txt', uploadId: 'already-staged' },
|
||||
file: './fixture.txt',
|
||||
},
|
||||
{ action: 'screenshot', output: './missing/screen.png' },
|
||||
])('rejects invalid file/output plans before execution: %j', async action => {
|
||||
await fs.writeFile(path.join(folder, 'fixture.txt'), 'content');
|
||||
await writeConfig([action]);
|
||||
await expect(prepareControlConfigAsync(catalog, filePath, connection.udid)).rejects.toThrow();
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('stops on the first runtime error and reports completed steps', async () => {
|
||||
await writeConfig([
|
||||
{ action: 'echo', params: { text: 'first' } },
|
||||
{ action: 'keyboard.set', params: { value: 'off' } },
|
||||
{ action: 'echo', params: { text: 'third' } },
|
||||
]);
|
||||
const config = await prepareControlConfigAsync(catalog, filePath, connection.udid);
|
||||
requestAsync.mockResolvedValueOnce(ok('first')).mockResolvedValueOnce({
|
||||
stdout: '',
|
||||
stderr: 'device stopped',
|
||||
exitCode: 1,
|
||||
});
|
||||
const onProgress = jest.fn();
|
||||
await expect(
|
||||
executeControlConfigAsync(connection, config, { onProgress })
|
||||
).rejects.toMatchObject({
|
||||
step: 2,
|
||||
action: 'keyboard.set',
|
||||
completed: [{ action: 'echo', output: 'first', file: null }],
|
||||
});
|
||||
expect(requestAsync.mock.calls).toEqual([
|
||||
['echo', { text: 'first' }],
|
||||
['keyboard.set', { value: 'off' }],
|
||||
]);
|
||||
expect(onProgress.mock.calls.map(([progress]) => progress)).toEqual([
|
||||
{ step: 1, total: 3, action: 'echo', status: 'running' },
|
||||
{
|
||||
step: 1,
|
||||
total: 3,
|
||||
action: 'echo',
|
||||
status: 'completed',
|
||||
result: { action: 'echo', output: 'first', file: null },
|
||||
},
|
||||
{ step: 2, total: 3, action: 'keyboard.set', status: 'running' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('preserves a non-Error failure without retrying the action', async () => {
|
||||
await writeConfig([{ action: 'echo' }]);
|
||||
const config = await prepareControlConfigAsync(catalog, filePath, connection.udid);
|
||||
requestAsync.mockRejectedValueOnce('connection lost');
|
||||
await expect(executeControlConfigAsync(connection, config)).rejects.toMatchObject({
|
||||
step: 1,
|
||||
completed: [],
|
||||
message: expect.stringContaining('connection lost'),
|
||||
});
|
||||
expect(requestAsync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('validates the actual uploaded value before invoking an action', async () => {
|
||||
const strict: HostActionCatalog = {
|
||||
'file.push': {
|
||||
...catalog['file.push'],
|
||||
uploadAs: 'path',
|
||||
properties: {
|
||||
...catalog['file.push'].properties,
|
||||
uploadId: { type: 'string', pattern: '^/tmp/serve-sim-uploads/' },
|
||||
},
|
||||
},
|
||||
};
|
||||
await fs.writeFile(path.join(folder, 'fixture.txt'), 'content');
|
||||
await writeConfig([
|
||||
{ action: 'file.push', params: { destination: 'data.txt' }, file: './fixture.txt' },
|
||||
]);
|
||||
const config = await prepareControlConfigAsync(strict, filePath, connection.udid);
|
||||
await expect(executeControlConfigAsync(connection, config)).rejects.toThrow(/uploadId/);
|
||||
expect(requestAsync.mock.calls.map(([name]) => name)).toEqual([
|
||||
'upload.append',
|
||||
'upload.remove',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,441 @@
|
||||
import { PassThrough } from 'node:stream';
|
||||
|
||||
import Log from '../../log';
|
||||
import { promptControlActionAsync, runControlMenuAsync } from '../controlInteractive';
|
||||
import { ControlPromptCancelledError, promptControlValueAsync } from '../controlPrompts';
|
||||
import { HostActionCatalog } from '../hostActions';
|
||||
|
||||
jest.mock('../controlPrompts', () => ({
|
||||
...jest.requireActual('../controlPrompts'),
|
||||
promptControlValueAsync: jest.fn(),
|
||||
}));
|
||||
jest.mock('../../log');
|
||||
jest.unmock('prompts');
|
||||
|
||||
const prompt = jest.mocked(promptControlValueAsync);
|
||||
const catalog: HostActionCatalog = require('./fixtures/hostActionCatalog.json');
|
||||
const signal = new AbortController().signal;
|
||||
|
||||
function useTerminalPrompts(): { enterAsync(value: string): Promise<void>; output(): string } {
|
||||
const input = Object.assign(new PassThrough(), { isTTY: true, setRawMode: jest.fn() });
|
||||
const output = Object.assign(new PassThrough(), { columns: 80 });
|
||||
let text = '';
|
||||
output.on('data', chunk => {
|
||||
text += String(chunk);
|
||||
});
|
||||
const actual = jest.requireActual<typeof import('../controlPrompts')>('../controlPrompts');
|
||||
prompt.mockImplementation(
|
||||
async (question, signal) =>
|
||||
await actual.promptControlValueAsync({ ...question, stdin: input, stdout: output }, signal)
|
||||
);
|
||||
return {
|
||||
async enterAsync(value) {
|
||||
input.write(`\u0007${value}\r`);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
},
|
||||
output: () => text,
|
||||
};
|
||||
}
|
||||
|
||||
describe('catalog-driven control prompts', () => {
|
||||
beforeEach(() => jest.resetAllMocks());
|
||||
|
||||
it('asks for enum values without hardcoding the action name', async () => {
|
||||
prompt.mockResolvedValueOnce('off');
|
||||
await expect(
|
||||
promptControlActionAsync('future.toggle', catalog['hardwareKeyboard.set'], signal)
|
||||
).resolves.toEqual({ action: 'future.toggle', params: { value: 'off' } });
|
||||
expect(prompt.mock.calls[0][0]).toMatchObject({
|
||||
type: 'select',
|
||||
choices: [
|
||||
{ title: 'on', value: 'on' },
|
||||
{ title: 'off', value: 'off' },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('uses the exposed path branch instead of asking for an upload ID', async () => {
|
||||
prompt.mockResolvedValueOnce('./My App.ipa');
|
||||
await expect(
|
||||
promptControlActionAsync('app.install', catalog['app.install'], signal)
|
||||
).resolves.toEqual({ action: 'app.install', params: { path: './My App.ipa' } });
|
||||
expect(prompt).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('selects a discriminator branch and omits other branch fields', async () => {
|
||||
prompt.mockResolvedValueOnce('placeholder');
|
||||
await expect(
|
||||
promptControlActionAsync('camera.switch', catalog['camera.switch'], signal)
|
||||
).resolves.toEqual({ action: 'camera.switch', params: { source: 'placeholder' } });
|
||||
expect(prompt).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('leaves optional values omitted and preserves explicitly empty strings', async () => {
|
||||
const entry = {
|
||||
type: 'object',
|
||||
properties: { text: { type: 'string', default: 'server default' } },
|
||||
};
|
||||
prompt.mockResolvedValueOnce(false);
|
||||
await expect(promptControlActionAsync('clipboard.paste', entry, signal)).resolves.toEqual({
|
||||
action: 'clipboard.paste',
|
||||
params: {},
|
||||
});
|
||||
prompt.mockResolvedValueOnce(true).mockResolvedValueOnce('');
|
||||
await expect(promptControlActionAsync('clipboard.paste', entry, signal)).resolves.toEqual({
|
||||
action: 'clipboard.paste',
|
||||
params: { text: '' },
|
||||
});
|
||||
});
|
||||
|
||||
it('reads array values as JSON and prompts for file output before execution', async () => {
|
||||
const entry = {
|
||||
type: 'object',
|
||||
properties: { events: { type: 'array', items: { type: 'object' } } },
|
||||
required: ['events'],
|
||||
output: 'base64' as const,
|
||||
};
|
||||
prompt.mockResolvedValueOnce('[{"type":"begin"}]').mockResolvedValueOnce('./output.png');
|
||||
await expect(promptControlActionAsync('future.gesture', entry, signal)).resolves.toEqual({
|
||||
action: 'future.gesture',
|
||||
params: { events: [{ type: 'begin' }] },
|
||||
outputPath: './output.png',
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back to a JSON object when branches cannot be selected safely', async () => {
|
||||
const entry = {
|
||||
anyOf: [
|
||||
{ properties: { a: { type: 'string' } }, required: ['a'] },
|
||||
{ properties: { b: { type: 'string' } }, required: ['b'] },
|
||||
],
|
||||
};
|
||||
prompt.mockResolvedValueOnce('{"b":"value"}');
|
||||
await expect(promptControlActionAsync('future.union', entry, signal)).resolves.toEqual({
|
||||
action: 'future.union',
|
||||
params: { b: 'value' },
|
||||
});
|
||||
expect(prompt.mock.calls[0][0].message).toContain('JSON');
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ anyOf: [{ type: 'boolean' }, { type: 'null' }] }, 'false', false],
|
||||
[{ anyOf: [{ type: 'boolean' }, { type: 'null' }] }, 'null', null],
|
||||
[{ anyOf: [{ type: 'string' }, { type: 'object' }] }, '"hello"', 'hello'],
|
||||
])('accepts JSON values for mixed property unions %#', async (schema, input, expected) => {
|
||||
prompt.mockResolvedValueOnce(input);
|
||||
await expect(
|
||||
promptControlActionAsync(
|
||||
'future.union',
|
||||
{ type: 'object', properties: { value: schema }, required: ['value'] },
|
||||
signal
|
||||
)
|
||||
).resolves.toEqual({ action: 'future.union', params: { value: expected } });
|
||||
});
|
||||
|
||||
it('combines required fields from allOf and keeps optional defaults on the server', async () => {
|
||||
const entry = {
|
||||
type: 'object',
|
||||
properties: { precision: { type: 'integer', default: 4 } },
|
||||
allOf: [
|
||||
{ type: 'object', properties: { lat: { type: 'number' } }, required: ['lat'] },
|
||||
{ type: 'object', properties: { lng: { type: 'number' } }, required: ['lng'] },
|
||||
],
|
||||
args: ['lat', 'lng'],
|
||||
};
|
||||
prompt.mockResolvedValueOnce('37.5').mockResolvedValueOnce('-122').mockResolvedValueOnce(false);
|
||||
await expect(promptControlActionAsync('future.location', entry, signal)).resolves.toEqual({
|
||||
action: 'future.location',
|
||||
params: { lat: 37.5, lng: -122 },
|
||||
});
|
||||
expect(prompt.mock.calls[2][0]).toMatchObject({
|
||||
message: 'Set optional precision (default: 4)?',
|
||||
initial: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('uses a boolean toggle and supplies required constants without another question', async () => {
|
||||
const entry = {
|
||||
type: 'object',
|
||||
properties: { enabled: { type: 'boolean' }, mode: { const: 'fixed' } },
|
||||
required: ['enabled', 'mode'],
|
||||
};
|
||||
prompt.mockResolvedValueOnce(false);
|
||||
await expect(promptControlActionAsync('future.enabled', entry, signal)).resolves.toEqual({
|
||||
action: 'future.enabled',
|
||||
params: { enabled: false, mode: 'fixed' },
|
||||
});
|
||||
expect(prompt).toHaveBeenCalledTimes(1);
|
||||
expect(prompt.mock.calls[0][0]).toMatchObject({
|
||||
type: 'toggle',
|
||||
active: 'true',
|
||||
inactive: 'false',
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts either a named pose or numeric angle for the existing scalar union', async () => {
|
||||
prompt.mockResolvedValueOnce('half').mockResolvedValueOnce('90');
|
||||
await expect(
|
||||
promptControlActionAsync('hinge.set', catalog['hinge.set'], signal)
|
||||
).resolves.toEqual({ action: 'hinge.set', params: { value: 'half' } });
|
||||
await expect(
|
||||
promptControlActionAsync('hinge.set', catalog['hinge.set'], signal)
|
||||
).resolves.toEqual({ action: 'hinge.set', params: { value: 90 } });
|
||||
});
|
||||
|
||||
it('uses a JSON object for nested alternatives it cannot guide safely', async () => {
|
||||
const entry = {
|
||||
allOf: [
|
||||
{ type: 'object', properties: { common: { type: 'string' } }, required: ['common'] },
|
||||
{
|
||||
anyOf: [
|
||||
{ properties: { file: { type: 'string' } } },
|
||||
{ properties: { url: { type: 'string' } } },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
prompt.mockResolvedValueOnce('{"common":"test","file":"./file.txt"}');
|
||||
await expect(promptControlActionAsync('future.nested', entry, signal)).resolves.toEqual({
|
||||
action: 'future.nested',
|
||||
params: { common: 'test', file: './file.txt' },
|
||||
});
|
||||
expect(prompt).toHaveBeenCalledTimes(1);
|
||||
expect(prompt.mock.calls[0][0].message).toContain('JSON object');
|
||||
});
|
||||
|
||||
it('does not guess between branches that share the same discriminator value', async () => {
|
||||
const entry = {
|
||||
oneOf: [
|
||||
{ properties: { source: { const: 'file' }, path: { type: 'string' } } },
|
||||
{ properties: { source: { const: 'file' }, uploadId: { type: 'string' } } },
|
||||
],
|
||||
};
|
||||
prompt.mockResolvedValueOnce('{"source":"file","path":"./test"}');
|
||||
await expect(
|
||||
promptControlActionAsync('future.ambiguous', entry, signal)
|
||||
).resolves.toMatchObject({ params: { source: 'file', path: './test' } });
|
||||
expect(prompt.mock.calls[0][0].message).toContain('JSON object');
|
||||
});
|
||||
|
||||
it('keeps an invalid number in the real prompt until the user corrects it', async () => {
|
||||
const terminal = useTerminalPrompts();
|
||||
const result = promptControlActionAsync('location.set', catalog['location.set'], signal);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
await terminal.enterAsync('not a number');
|
||||
expect(terminal.output()).toContain('Enter a valid number.');
|
||||
await terminal.enterAsync('37.5');
|
||||
await terminal.enterAsync('-122');
|
||||
await expect(result).resolves.toEqual({
|
||||
action: 'location.set',
|
||||
params: { lat: 37.5, lng: -122 },
|
||||
});
|
||||
});
|
||||
|
||||
it('requires valid JSON with the right container type before accepting a complex field', async () => {
|
||||
const terminal = useTerminalPrompts();
|
||||
const entry = {
|
||||
type: 'object',
|
||||
properties: { events: { type: 'array' } },
|
||||
required: ['events'],
|
||||
};
|
||||
const result = promptControlActionAsync('future.gesture', entry, signal);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
await terminal.enterAsync('[broken');
|
||||
await terminal.enterAsync('{}');
|
||||
expect(terminal.output()).toContain('Enter a JSON value matching this parameter.');
|
||||
await terminal.enterAsync('[{"type":"begin"}]');
|
||||
await expect(result).resolves.toMatchObject({ params: { events: [{ type: 'begin' }] } });
|
||||
});
|
||||
|
||||
it('rejects malformed and non-object fallback JSON before accepting corrected parameters', async () => {
|
||||
const terminal = useTerminalPrompts();
|
||||
const entry = {
|
||||
anyOf: [{ properties: { a: { type: 'string' } } }, { properties: { b: { type: 'string' } } }],
|
||||
};
|
||||
const result = promptControlActionAsync('future.fallback', entry, signal);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
await terminal.enterAsync('invalid');
|
||||
await terminal.enterAsync('[]');
|
||||
expect(terminal.output()).toContain('Enter a JSON object.');
|
||||
await terminal.enterAsync('{"b":"corrected"}');
|
||||
await expect(result).resolves.toMatchObject({ params: { b: 'corrected' } });
|
||||
});
|
||||
|
||||
it('requires an output destination before returning a file action', async () => {
|
||||
const terminal = useTerminalPrompts();
|
||||
const result = promptControlActionAsync(
|
||||
'future.screenshot',
|
||||
{ type: 'object', output: 'base64' },
|
||||
signal
|
||||
);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
await terminal.enterAsync(' ');
|
||||
expect(terminal.output()).toContain('Enter a local output path.');
|
||||
await terminal.enterAsync('./image.png');
|
||||
await expect(result).resolves.toEqual({
|
||||
action: 'future.screenshot',
|
||||
params: {},
|
||||
outputPath: './image.png',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('interactive control loop', () => {
|
||||
beforeEach(() => jest.resetAllMocks());
|
||||
|
||||
it('searches friendly labels, action names and descriptions without losing catalog entries', async () => {
|
||||
prompt.mockResolvedValueOnce({ kind: 'exit' });
|
||||
await runControlMenuAsync({
|
||||
catalog: {
|
||||
'hardwareKeyboard.set': { description: 'Connect the physical keyboard' },
|
||||
'future.newAction': { description: 'A newly discovered capability' },
|
||||
},
|
||||
signal,
|
||||
runActionAsync: jest.fn(),
|
||||
});
|
||||
const question = prompt.mock.calls[0][0];
|
||||
const suggest = question.suggest as (
|
||||
input: string,
|
||||
choices: unknown[]
|
||||
) => Promise<{ value: unknown }[]>;
|
||||
expect((await suggest('HARDWARE keyboard', [])).map(choice => choice.value)).toEqual([
|
||||
{ kind: 'action', name: 'hardwareKeyboard.set' },
|
||||
]);
|
||||
expect((await suggest('future.newAction', [])).map(choice => choice.value)).toEqual([
|
||||
{ kind: 'action', name: 'future.newAction' },
|
||||
]);
|
||||
expect((await suggest('newly discovered', [])).map(choice => choice.value)).toEqual([
|
||||
{ kind: 'action', name: 'future.newAction' },
|
||||
]);
|
||||
expect(await suggest('no match', [])).toEqual([]);
|
||||
expect(await suggest('', [])).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('runs one selection at a time and returns to the picker until Exit', async () => {
|
||||
const runActionAsync = jest.fn().mockResolvedValue(undefined);
|
||||
prompt
|
||||
.mockResolvedValueOnce({ kind: 'action', name: 'hardwareKeyboard.set' })
|
||||
.mockResolvedValueOnce('on')
|
||||
.mockResolvedValueOnce({ kind: 'action', name: 'hardwareKeyboard.set' })
|
||||
.mockResolvedValueOnce('off')
|
||||
.mockResolvedValueOnce({ kind: 'exit' });
|
||||
await runControlMenuAsync({ catalog, signal, runActionAsync });
|
||||
expect(runActionAsync.mock.calls).toEqual([
|
||||
[{ action: 'hardwareKeyboard.set', params: { value: 'on' } }],
|
||||
[{ action: 'hardwareKeyboard.set', params: { value: 'off' } }],
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns to the picker after a normal action error without replay', async () => {
|
||||
const runActionAsync = jest.fn().mockRejectedValue(new Error('Permission denied'));
|
||||
prompt
|
||||
.mockResolvedValueOnce({ kind: 'action', name: 'future.action' })
|
||||
.mockResolvedValueOnce({ kind: 'exit' });
|
||||
await runControlMenuAsync({
|
||||
catalog: { 'future.action': { type: 'object' } },
|
||||
signal,
|
||||
runActionAsync,
|
||||
});
|
||||
expect(runActionAsync).toHaveBeenCalledTimes(1);
|
||||
expect(Log.error).toHaveBeenCalledWith('Permission denied');
|
||||
});
|
||||
|
||||
it('does not open another picker while an action is running', async () => {
|
||||
let complete!: () => void;
|
||||
const runActionAsync = jest.fn(
|
||||
() =>
|
||||
new Promise<void>(resolve => {
|
||||
complete = resolve;
|
||||
})
|
||||
);
|
||||
prompt
|
||||
.mockResolvedValueOnce({ kind: 'action', name: 'future.action' })
|
||||
.mockResolvedValueOnce({ kind: 'exit' });
|
||||
const running = runControlMenuAsync({
|
||||
catalog: { 'future.action': { type: 'object' } },
|
||||
signal,
|
||||
runActionAsync,
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(runActionAsync).toHaveBeenCalledTimes(1);
|
||||
expect(prompt).toHaveBeenCalledTimes(1);
|
||||
complete();
|
||||
await running;
|
||||
expect(prompt).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('stops after ambiguous transport loss and never opens the next picker', async () => {
|
||||
const controller = new AbortController();
|
||||
const error = new Error('The action may still have run');
|
||||
const runActionAsync = jest.fn(async () => {
|
||||
controller.abort(error);
|
||||
throw error;
|
||||
});
|
||||
prompt.mockResolvedValueOnce({ kind: 'action', name: 'future.action' });
|
||||
await expect(
|
||||
runControlMenuAsync({
|
||||
catalog: { 'future.action': { type: 'object' } },
|
||||
signal: controller.signal,
|
||||
runActionAsync,
|
||||
})
|
||||
).rejects.toBe(error);
|
||||
expect(prompt).toHaveBeenCalledTimes(1);
|
||||
expect(runActionAsync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('unwinds a user cancellation', async () => {
|
||||
prompt.mockRejectedValueOnce(new ControlPromptCancelledError());
|
||||
await expect(
|
||||
runControlMenuAsync({ catalog, signal, runActionAsync: jest.fn() })
|
||||
).rejects.toBeInstanceOf(ControlPromptCancelledError);
|
||||
});
|
||||
|
||||
it('keeps the menu open when autocomplete has no matching selection', async () => {
|
||||
const runActionAsync = jest.fn();
|
||||
prompt.mockResolvedValueOnce(undefined).mockResolvedValueOnce({ kind: 'exit' });
|
||||
await expect(runControlMenuAsync({ catalog, signal, runActionAsync })).resolves.toBeUndefined();
|
||||
expect(runActionAsync).not.toHaveBeenCalled();
|
||||
expect(prompt).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('runs a different action after an ordinary rejection', async () => {
|
||||
const runActionAsync = jest
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new Error('Permission denied'))
|
||||
.mockResolvedValueOnce(undefined);
|
||||
prompt
|
||||
.mockResolvedValueOnce({ kind: 'action', name: 'first' })
|
||||
.mockResolvedValueOnce({ kind: 'action', name: 'second' })
|
||||
.mockResolvedValueOnce({ kind: 'exit' });
|
||||
await runControlMenuAsync({
|
||||
catalog: { first: { type: 'object' }, second: { type: 'object' } },
|
||||
signal,
|
||||
runActionAsync,
|
||||
});
|
||||
expect(runActionAsync.mock.calls).toEqual([
|
||||
[{ action: 'first', params: {} }],
|
||||
[{ action: 'second', params: {} }],
|
||||
]);
|
||||
expect(Log.error).toHaveBeenCalledWith('Permission denied');
|
||||
});
|
||||
|
||||
it('does not send an action when Ctrl-C cancels its parameter prompt', async () => {
|
||||
const runActionAsync = jest.fn();
|
||||
prompt
|
||||
.mockResolvedValueOnce({ kind: 'action', name: 'hardwareKeyboard.set' })
|
||||
.mockRejectedValueOnce(new ControlPromptCancelledError());
|
||||
await expect(runControlMenuAsync({ catalog, signal, runActionAsync })).rejects.toBeInstanceOf(
|
||||
ControlPromptCancelledError
|
||||
);
|
||||
expect(runActionAsync).not.toHaveBeenCalled();
|
||||
expect(Log.error).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not open any prompt if initialization already lost the session', async () => {
|
||||
const error = new Error('Already disconnected');
|
||||
await expect(
|
||||
runControlMenuAsync({ catalog, signal: AbortSignal.abort(error), runActionAsync: jest.fn() })
|
||||
).rejects.toBe(error);
|
||||
expect(prompt).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import { PassThrough } from 'node:stream';
|
||||
|
||||
import { ControlPromptCancelledError, promptControlValueAsync } from '../controlPrompts';
|
||||
|
||||
jest.unmock('prompts');
|
||||
|
||||
function terminal(): {
|
||||
input: PassThrough & { isTTY: boolean; setRawMode: jest.Mock };
|
||||
output: PassThrough & { columns: number };
|
||||
} {
|
||||
const input = Object.assign(new PassThrough(), { isTTY: true, setRawMode: jest.fn() });
|
||||
const output = Object.assign(new PassThrough(), { columns: 80 });
|
||||
output.resume();
|
||||
return { input, output };
|
||||
}
|
||||
|
||||
describe('abortable simulator control prompts', () => {
|
||||
it('aborts the real idle prompt and restores the terminal', async () => {
|
||||
const { input, output } = terminal();
|
||||
const controller = new AbortController();
|
||||
const reason = new Error('Connection lost');
|
||||
const result = promptControlValueAsync(
|
||||
{ type: 'text', message: 'Value', stdin: input, stdout: output },
|
||||
controller.signal
|
||||
);
|
||||
controller.abort(reason);
|
||||
await expect(result).rejects.toBe(reason);
|
||||
expect(input.setRawMode.mock.calls).toEqual([[true], [false]]);
|
||||
expect(input.listenerCount('keypress')).toBe(0);
|
||||
});
|
||||
|
||||
it('handles cancellation during the first constructor render', async () => {
|
||||
const { input, output } = terminal();
|
||||
const controller = new AbortController();
|
||||
const reason = new Error('Session ended');
|
||||
await expect(
|
||||
promptControlValueAsync(
|
||||
{
|
||||
type: 'select',
|
||||
message: 'Action',
|
||||
choices: [{ title: 'Exit', value: null }],
|
||||
stdin: input,
|
||||
stdout: output,
|
||||
onRender() {
|
||||
controller.abort(reason);
|
||||
},
|
||||
},
|
||||
controller.signal
|
||||
)
|
||||
).rejects.toBe(reason);
|
||||
expect(input.listenerCount('keypress')).toBe(0);
|
||||
expect(input.setRawMode).toHaveBeenLastCalledWith(false);
|
||||
});
|
||||
|
||||
it('never opens a prompt for an already lost connection', async () => {
|
||||
const { input, output } = terminal();
|
||||
const signal = AbortSignal.abort(new Error('Already closed'));
|
||||
await expect(
|
||||
promptControlValueAsync(
|
||||
{ type: 'text', message: 'Value', stdin: input, stdout: output },
|
||||
signal
|
||||
)
|
||||
).rejects.toThrow('Already closed');
|
||||
expect(input.setRawMode).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('unwinds Ctrl-C instead of exiting the process', async () => {
|
||||
const { input, output } = terminal();
|
||||
const result = promptControlValueAsync(
|
||||
{ type: 'text', message: 'Value', stdin: input, stdout: output },
|
||||
new AbortController().signal
|
||||
);
|
||||
input.write('\u0003');
|
||||
await expect(result).rejects.toBeInstanceOf(ControlPromptCancelledError);
|
||||
expect(input.listenerCount('keypress')).toBe(0);
|
||||
expect(input.setRawMode).toHaveBeenLastCalledWith(false);
|
||||
});
|
||||
|
||||
it('preserves an explicitly empty string', async () => {
|
||||
const { input, output } = terminal();
|
||||
const result = promptControlValueAsync(
|
||||
{ type: 'text', message: 'Value', stdin: input, stdout: output },
|
||||
new AbortController().signal
|
||||
);
|
||||
input.write('\r');
|
||||
await expect(result).resolves.toBe('');
|
||||
expect(input.listenerCount('keypress')).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,453 @@
|
||||
import { createClient, fetchExchange } from '@urql/core';
|
||||
import { getEventListeners } from 'node:events';
|
||||
|
||||
import { DeviceRunSessionStatus, JobRunStatus } from '../../graphql/generated';
|
||||
import { DeviceRunSessionQuery } from '../../graphql/queries/DeviceRunSessionQuery';
|
||||
import Log from '../../log';
|
||||
import { ControlSessionEndedError, watchControlSession } from '../controlSession';
|
||||
|
||||
type SessionStatus = {
|
||||
status: DeviceRunSessionStatus;
|
||||
turtleJobRun?: { id: string; status: JobRunStatus } | null;
|
||||
};
|
||||
|
||||
type StatusSource = ReturnType<typeof DeviceRunSessionQuery.byId>;
|
||||
type StatusObserver = Parameters<StatusSource['subscribe']>[0];
|
||||
type StatusResult = Parameters<StatusObserver>[0];
|
||||
|
||||
type StatusRequest = {
|
||||
signal: AbortSignal;
|
||||
respond: (body: unknown) => void;
|
||||
fail: (error: Error) => void;
|
||||
};
|
||||
|
||||
function createStatusClient(): {
|
||||
client: ReturnType<typeof createClient>;
|
||||
fetch: jest.Mock<
|
||||
Promise<Response>,
|
||||
[url: Parameters<typeof globalThis.fetch>[0], options?: RequestInit]
|
||||
>;
|
||||
requests: StatusRequest[];
|
||||
activeRequests(): number;
|
||||
} {
|
||||
const requests: StatusRequest[] = [];
|
||||
let activeRequests = 0;
|
||||
const fetch = jest.fn((_url: Parameters<typeof globalThis.fetch>[0], options?: RequestInit) => {
|
||||
const signal = options!.signal!;
|
||||
activeRequests++;
|
||||
return new Promise<Response>((resolve, reject) => {
|
||||
let finished = false;
|
||||
const finish = (): boolean => {
|
||||
if (finished) {
|
||||
return false;
|
||||
}
|
||||
finished = true;
|
||||
activeRequests--;
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
return true;
|
||||
};
|
||||
const onAbort = (): void => {
|
||||
if (finish()) {
|
||||
reject(new Error('Request aborted'));
|
||||
}
|
||||
};
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
requests.push({
|
||||
signal,
|
||||
respond: body => {
|
||||
if (finish()) {
|
||||
resolve(
|
||||
new Response(JSON.stringify(body), {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
);
|
||||
}
|
||||
},
|
||||
fail: error => {
|
||||
if (finish()) {
|
||||
reject(error);
|
||||
}
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
const client = createClient({
|
||||
url: 'https://example.test/graphql',
|
||||
exchanges: [fetchExchange],
|
||||
fetch,
|
||||
fetchOptions: () => ({ headers: { authorization: 'Bearer session-token' } }),
|
||||
});
|
||||
return { client, fetch, requests, activeRequests: () => activeRequests };
|
||||
}
|
||||
|
||||
function sessionResponse(status: SessionStatus): unknown {
|
||||
return { data: { deviceRunSessions: { byId: { id: 'session-id', ...status } } } };
|
||||
}
|
||||
|
||||
describe(watchControlSession, () => {
|
||||
const disposers: (() => void)[] = [];
|
||||
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers();
|
||||
jest.spyOn(Log, 'debug').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const dispose of disposers.splice(0)) {
|
||||
dispose();
|
||||
}
|
||||
jest.clearAllTimers();
|
||||
jest.useRealTimers();
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
function watch(
|
||||
client: ReturnType<typeof createStatusClient>['client'],
|
||||
options: Parameters<typeof watchControlSession>[2] = {
|
||||
signal: new AbortController().signal,
|
||||
}
|
||||
): ReturnType<typeof watchControlSession> {
|
||||
const watcher = watchControlSession(client, 'session-id', options);
|
||||
disposers.push(watcher.dispose);
|
||||
return watcher;
|
||||
}
|
||||
|
||||
it('polls serially after each completed request and preserves authentication', async () => {
|
||||
const observed = createStatusClient();
|
||||
const query = jest.spyOn(observed.client, 'query');
|
||||
watch(observed.client);
|
||||
|
||||
await jest.advanceTimersByTimeAsync(4999);
|
||||
expect(observed.fetch).not.toHaveBeenCalled();
|
||||
await jest.advanceTimersByTimeAsync(1);
|
||||
expect(observed.fetch).toHaveBeenCalledTimes(1);
|
||||
expect(query).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
{ deviceRunSessionId: 'session-id' },
|
||||
{ requestPolicy: 'network-only', noRetry: true }
|
||||
);
|
||||
expect(observed.fetch.mock.calls[0][1]?.headers).toEqual(
|
||||
expect.objectContaining({ authorization: 'Bearer session-token' })
|
||||
);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
expect(observed.fetch).toHaveBeenCalledTimes(1);
|
||||
expect(observed.activeRequests()).toBe(1);
|
||||
|
||||
observed.requests[0].respond(sessionResponse({ status: DeviceRunSessionStatus.InProgress }));
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
await jest.advanceTimersByTimeAsync(4999);
|
||||
expect(observed.fetch).toHaveBeenCalledTimes(1);
|
||||
await jest.advanceTimersByTimeAsync(1);
|
||||
expect(observed.fetch).toHaveBeenCalledTimes(2);
|
||||
expect(observed.activeRequests()).toBe(1);
|
||||
});
|
||||
|
||||
it.each([DeviceRunSessionStatus.Stopped, DeviceRunSessionStatus.Errored])(
|
||||
'ends control when an idle session becomes %s',
|
||||
async status => {
|
||||
const observed = createStatusClient();
|
||||
const watcher = watch(observed.client);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
observed.requests[0].respond(sessionResponse({ status }));
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
|
||||
expect(watcher.signal.aborted).toBe(true);
|
||||
expect(watcher.signal.reason).toBeInstanceOf(ControlSessionEndedError);
|
||||
expect(watcher.signal.reason.message).toContain('session-id');
|
||||
expect(watcher.signal.reason.failed).toBe(status === DeviceRunSessionStatus.Errored);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
await jest.advanceTimersByTimeAsync(60_000);
|
||||
expect(observed.fetch).toHaveBeenCalledTimes(1);
|
||||
}
|
||||
);
|
||||
|
||||
it.each([JobRunStatus.Canceled, JobRunStatus.Finished, JobRunStatus.Errored])(
|
||||
'ends control when the worker job becomes %s before the session status catches up',
|
||||
async status => {
|
||||
const observed = createStatusClient();
|
||||
const watcher = watch(observed.client);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
observed.requests[0].respond(
|
||||
sessionResponse({
|
||||
status: DeviceRunSessionStatus.InProgress,
|
||||
turtleJobRun: { id: 'job-id', status },
|
||||
})
|
||||
);
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
|
||||
expect(watcher.signal.reason).toBeInstanceOf(ControlSessionEndedError);
|
||||
expect(watcher.signal.reason.failed).toBe(status === JobRunStatus.Errored);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
}
|
||||
);
|
||||
|
||||
it('keeps watching a session without a job and a job whose cancellation is pending', async () => {
|
||||
const observed = createStatusClient();
|
||||
const watcher = watch(observed.client);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
observed.requests[0].respond(
|
||||
sessionResponse({ status: DeviceRunSessionStatus.InProgress, turtleJobRun: null })
|
||||
);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
observed.requests[1].respond(
|
||||
sessionResponse({
|
||||
status: DeviceRunSessionStatus.InProgress,
|
||||
turtleJobRun: { id: 'job-id', status: JobRunStatus.PendingCancel },
|
||||
})
|
||||
);
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
|
||||
expect(watcher.signal.aborted).toBe(false);
|
||||
expect(jest.getTimerCount()).toBe(1);
|
||||
});
|
||||
|
||||
it('logs network and GraphQL failures, then retries without ending control', async () => {
|
||||
const observed = createStatusClient();
|
||||
const watcher = watch(observed.client);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
observed.requests[0].fail(new Error('Connection reset'));
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
observed.requests[1].respond({ errors: [{ message: 'Temporarily unavailable' }] });
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
|
||||
expect(watcher.signal.aborted).toBe(false);
|
||||
expect(Log.debug).toHaveBeenCalledTimes(2);
|
||||
expect(observed.activeRequests()).toBe(1);
|
||||
observed.requests[2].respond(sessionResponse({ status: DeviceRunSessionStatus.Stopped }));
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(watcher.signal.reason).toBeInstanceOf(ControlSessionEndedError);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ data: {} },
|
||||
{ data: { deviceRunSessions: null } },
|
||||
{ data: { deviceRunSessions: { byId: null } } },
|
||||
])('retries an empty session response %j without treating it as ended', async body => {
|
||||
const observed = createStatusClient();
|
||||
const watcher = watch(observed.client);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
observed.requests[0].respond(body);
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
|
||||
expect(watcher.signal.aborted).toBe(false);
|
||||
expect(Log.debug).toHaveBeenCalledWith(
|
||||
expect.stringContaining('session-id'),
|
||||
expect.objectContaining({ message: 'Session status response was empty.' })
|
||||
);
|
||||
expect(jest.getTimerCount()).toBe(1);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
expect(observed.fetch).toHaveBeenCalledTimes(2);
|
||||
observed.requests[1].respond(sessionResponse({ status: DeviceRunSessionStatus.Stopped }));
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(watcher.signal.reason).toBeInstanceOf(ControlSessionEndedError);
|
||||
});
|
||||
|
||||
it('waits for a successful response when GraphQL returns partial terminal data with an error', async () => {
|
||||
const observed = createStatusClient();
|
||||
const watcher = watch(observed.client);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
observed.requests[0].respond({
|
||||
...(sessionResponse({ status: DeviceRunSessionStatus.Stopped }) as object),
|
||||
errors: [{ message: 'Status temporarily unavailable', extensions: { isTransient: true } }],
|
||||
});
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
|
||||
expect(watcher.signal.aborted).toBe(false);
|
||||
expect(Log.debug).toHaveBeenCalledTimes(1);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
observed.requests[1].respond(sessionResponse({ status: DeviceRunSessionStatus.InProgress }));
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(watcher.signal.aborted).toBe(false);
|
||||
expect(jest.getTimerCount()).toBe(1);
|
||||
});
|
||||
|
||||
it('ignores stale and incomplete terminal results until the source confirms a final result', async () => {
|
||||
const observed = createStatusClient();
|
||||
const unsubscribe = jest.fn();
|
||||
let emit: StatusObserver | undefined;
|
||||
const subscribe = jest.fn((next: StatusObserver) => {
|
||||
emit = next;
|
||||
return { unsubscribe };
|
||||
});
|
||||
jest
|
||||
.spyOn(DeviceRunSessionQuery, 'byId')
|
||||
.mockReturnValue({ subscribe } as unknown as StatusSource);
|
||||
const watcher = watch(observed.client);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
const terminal = sessionResponse({ status: DeviceRunSessionStatus.Stopped }) as StatusResult;
|
||||
emit!({ ...terminal, stale: true, hasNext: false });
|
||||
emit!({ ...terminal, stale: false, hasNext: true });
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
|
||||
expect(watcher.signal.aborted).toBe(false);
|
||||
expect(subscribe).toHaveBeenCalledTimes(1);
|
||||
expect(unsubscribe).not.toHaveBeenCalled();
|
||||
expect(jest.getTimerCount()).toBe(1);
|
||||
emit!({ ...terminal, stale: false, hasNext: false });
|
||||
expect(watcher.signal.reason).toBeInstanceOf(ControlSessionEndedError);
|
||||
expect(unsubscribe).toHaveBeenCalledTimes(1);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
expect(Log.debug).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([DeviceRunSessionStatus.InProgress, DeviceRunSessionStatus.Stopped])(
|
||||
'unsubscribes a synchronously emitted %s response after subscribe returns its handle',
|
||||
async status => {
|
||||
const observed = createStatusClient();
|
||||
const unsubscribe = jest.fn();
|
||||
const subscribe = jest.fn((next: StatusObserver) => {
|
||||
next({ ...(sessionResponse({ status }) as StatusResult), stale: false, hasNext: false });
|
||||
return { unsubscribe };
|
||||
});
|
||||
jest
|
||||
.spyOn(DeviceRunSessionQuery, 'byId')
|
||||
.mockReturnValue({ subscribe } as unknown as StatusSource);
|
||||
const controller = new AbortController();
|
||||
const watcher = watch(observed.client, { signal: controller.signal });
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
|
||||
expect(unsubscribe).toHaveBeenCalledTimes(1);
|
||||
expect(watcher.signal.aborted).toBe(status === DeviceRunSessionStatus.Stopped);
|
||||
expect(jest.getTimerCount()).toBe(status === DeviceRunSessionStatus.Stopped ? 0 : 1);
|
||||
watcher.dispose();
|
||||
expect(unsubscribe).toHaveBeenCalledTimes(1);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0);
|
||||
expect(observed.fetch).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
it('recovers from a synchronous query setup failure without leaving its deadline running', async () => {
|
||||
const observed = createStatusClient();
|
||||
const failure = new Error('Could not initialize status request');
|
||||
jest.spyOn(DeviceRunSessionQuery, 'byId').mockImplementationOnce(() => {
|
||||
throw failure;
|
||||
});
|
||||
const watcher = watch(observed.client);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
|
||||
expect(watcher.signal.aborted).toBe(false);
|
||||
expect(Log.debug).toHaveBeenCalledWith(expect.stringContaining('session-id'), failure);
|
||||
expect(jest.getTimerCount()).toBe(1);
|
||||
expect(observed.fetch).not.toHaveBeenCalled();
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
expect(observed.fetch).toHaveBeenCalledTimes(1);
|
||||
observed.requests[0].respond(sessionResponse({ status: DeviceRunSessionStatus.InProgress }));
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(jest.getTimerCount()).toBe(1);
|
||||
});
|
||||
|
||||
it('unsubscribes and aborts the fetch at the request deadline before retrying', async () => {
|
||||
const observed = createStatusClient();
|
||||
const watcher = watch(observed.client, {
|
||||
signal: new AbortController().signal,
|
||||
pollIntervalMs: 100,
|
||||
requestTimeoutMs: 200,
|
||||
});
|
||||
await jest.advanceTimersByTimeAsync(100);
|
||||
expect(observed.activeRequests()).toBe(1);
|
||||
await jest.advanceTimersByTimeAsync(199);
|
||||
expect(observed.requests[0].signal.aborted).toBe(false);
|
||||
await jest.advanceTimersByTimeAsync(1);
|
||||
|
||||
expect(observed.requests[0].signal.aborted).toBe(true);
|
||||
expect(observed.activeRequests()).toBe(0);
|
||||
expect(watcher.signal.aborted).toBe(false);
|
||||
expect(Log.debug).toHaveBeenCalledTimes(1);
|
||||
await jest.advanceTimersByTimeAsync(100);
|
||||
expect(observed.fetch).toHaveBeenCalledTimes(2);
|
||||
expect(observed.activeRequests()).toBe(1);
|
||||
});
|
||||
|
||||
it('disposes an in-flight fetch and all timers without sending a stop mutation', async () => {
|
||||
const observed = createStatusClient();
|
||||
const mutation = jest.spyOn(observed.client, 'mutation');
|
||||
const watcher = watch(observed.client);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
watcher.dispose();
|
||||
watcher.dispose();
|
||||
|
||||
expect(observed.requests[0].signal.aborted).toBe(true);
|
||||
expect(observed.activeRequests()).toBe(0);
|
||||
expect(watcher.signal.aborted).toBe(true);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
await jest.advanceTimersByTimeAsync(60_000);
|
||||
expect(observed.fetch).toHaveBeenCalledTimes(1);
|
||||
expect(mutation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('propagates parent cancellation and tears down an in-flight request', async () => {
|
||||
const observed = createStatusClient();
|
||||
const controller = new AbortController();
|
||||
const watcher = watch(observed.client, { signal: controller.signal });
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
const reason = new Error('Control connection lost');
|
||||
controller.abort(reason);
|
||||
|
||||
expect(watcher.signal.reason).toBe(reason);
|
||||
expect(observed.requests[0].signal.aborted).toBe(true);
|
||||
expect(observed.activeRequests()).toBe(0);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
expect(Log.debug).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('clears an idle poll and never polls an already canceled parent', async () => {
|
||||
const observed = createStatusClient();
|
||||
const controller = new AbortController();
|
||||
const watcher = watch(observed.client, { signal: controller.signal });
|
||||
controller.abort();
|
||||
expect(watcher.signal.reason).toBe(controller.signal.reason);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
const alreadyCanceled = watch(observed.client, { signal: controller.signal });
|
||||
expect(alreadyCanceled.signal.reason).toBe(controller.signal.reason);
|
||||
expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0);
|
||||
await jest.advanceTimersByTimeAsync(60_000);
|
||||
expect(observed.fetch).not.toHaveBeenCalled();
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('disposes an idle retry and removes its parent listener before the next poll', async () => {
|
||||
const observed = createStatusClient();
|
||||
const controller = new AbortController();
|
||||
const watcher = watch(observed.client, { signal: controller.signal });
|
||||
expect(getEventListeners(controller.signal, 'abort')).toHaveLength(1);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
observed.requests[0].fail(new Error('Connection reset'));
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(jest.getTimerCount()).toBe(1);
|
||||
watcher.dispose();
|
||||
|
||||
expect(watcher.signal.aborted).toBe(true);
|
||||
expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
await jest.advanceTimersByTimeAsync(60_000);
|
||||
expect(observed.fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('preserves the existing byIdAsync result and default query context', async () => {
|
||||
const observed = createStatusClient();
|
||||
const query = jest.spyOn(observed.client, 'query');
|
||||
const result = DeviceRunSessionQuery.byIdAsync(observed.client, 'session-id');
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
observed.requests[0].respond(sessionResponse({ status: DeviceRunSessionStatus.InProgress }));
|
||||
|
||||
await expect(result).resolves.toEqual({
|
||||
id: 'session-id',
|
||||
status: DeviceRunSessionStatus.InProgress,
|
||||
});
|
||||
expect(query).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
{ deviceRunSessionId: 'session-id' },
|
||||
{ requestPolicy: 'network-only' }
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves byIdAsync rejection for a GraphQL error', async () => {
|
||||
const observed = createStatusClient();
|
||||
const result = DeviceRunSessionQuery.byIdAsync(observed.client, 'session-id');
|
||||
const rejected = expect(result).rejects.toThrow('Permission denied');
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
observed.requests[0].respond({ errors: [{ message: 'Permission denied' }] });
|
||||
await rejected;
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,11 @@
|
||||
import * as fs from 'fs-extra';
|
||||
import { once } from 'node:events';
|
||||
import { getEventListeners, once } from 'node:events';
|
||||
import http from 'node:http';
|
||||
import { AddressInfo } from 'node:net';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { Duplex } from 'node:stream';
|
||||
import { WebSocketServer } from 'ws';
|
||||
import WebSocket, { WebSocketServer } from 'ws';
|
||||
|
||||
import * as fetchModule from '../../fetch';
|
||||
import {
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
buildHostActionParams,
|
||||
connectHostActionsAsync,
|
||||
fetchHostActionCatalogAsync,
|
||||
fetchHostActionDeviceAsync,
|
||||
formatHostActionUsage,
|
||||
saveHostActionOutputAsync,
|
||||
uploadFileAsync,
|
||||
@@ -173,6 +174,108 @@ describe(formatHostActionUsage, () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe(fetchHostActionDeviceAsync, () => {
|
||||
afterEach(() => jest.restoreAllMocks());
|
||||
|
||||
it('selects the connected device from the authenticated metadata catalog', async () => {
|
||||
const fetch = jest.spyOn(fetchModule, 'default').mockResolvedValueOnce(
|
||||
new fetchModule.Response(
|
||||
JSON.stringify({
|
||||
devices: [
|
||||
{ device: 'other-device', name: 'Other Simulator' },
|
||||
{ device: UDID, name: 'iPhone 17 Pro', runtime: 'iOS-26-4' },
|
||||
],
|
||||
})
|
||||
)
|
||||
);
|
||||
await expect(
|
||||
fetchHostActionDeviceAsync(
|
||||
{ apiUrl: 'https://sim.example.test/preview/', token: TOKEN },
|
||||
UDID
|
||||
)
|
||||
).resolves.toEqual({
|
||||
udid: UDID,
|
||||
name: 'iPhone 17 Pro',
|
||||
runtime: 'iOS-26-4',
|
||||
});
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
'https://sim.example.test/preview/grid/api/catalog',
|
||||
expect.objectContaining({
|
||||
headers: { Authorization: `Bearer ${TOKEN}` },
|
||||
redirect: 'error',
|
||||
signal: expect.any(AbortSignal),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
new Error('Metadata request failed'),
|
||||
new fetchModule.RequestError(
|
||||
'Request failed: 404 (Not Found)',
|
||||
new fetchModule.Response(undefined, { status: 404 })
|
||||
),
|
||||
Object.assign(new Error('Request timed out'), { name: 'AbortError' }),
|
||||
])('keeps the connected device ID when metadata fails: %s', async error => {
|
||||
jest.spyOn(fetchModule, 'default').mockRejectedValueOnce(error);
|
||||
await expect(
|
||||
fetchHostActionDeviceAsync({ apiUrl: 'https://sim.example.test', token: TOKEN }, UDID)
|
||||
).resolves.toEqual({ udid: UDID });
|
||||
});
|
||||
|
||||
it.each(['not JSON', JSON.stringify({ devices: null })])(
|
||||
'keeps the connected device ID when metadata is invalid: %s',
|
||||
async body => {
|
||||
jest.spyOn(fetchModule, 'default').mockResolvedValueOnce(new fetchModule.Response(body));
|
||||
await expect(
|
||||
fetchHostActionDeviceAsync({ apiUrl: 'https://sim.example.test', token: TOKEN }, UDID)
|
||||
).resolves.toEqual({ udid: UDID });
|
||||
}
|
||||
);
|
||||
|
||||
it('rejects insecure metadata URLs before sending the session token', async () => {
|
||||
const fetch = jest.spyOn(fetchModule, 'default');
|
||||
await expect(
|
||||
fetchHostActionDeviceAsync({ apiUrl: 'http://sim.example.test', token: TOKEN }, UDID)
|
||||
).rejects.toThrow('Simulator actions require HTTPS');
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('allows a device catalog to take more than three seconds during cold startup', async () => {
|
||||
let responseTimer: NodeJS.Timeout | undefined;
|
||||
const server = http.createServer((_request, response) => {
|
||||
responseTimer = setTimeout(() => {
|
||||
response.end(JSON.stringify({ devices: [{ device: UDID, name: 'iPhone 17 Pro' }] }));
|
||||
}, 3500);
|
||||
});
|
||||
server.listen(0, '127.0.0.1');
|
||||
await once(server, 'listening');
|
||||
const { port } = server.address() as AddressInfo;
|
||||
try {
|
||||
await expect(
|
||||
fetchHostActionDeviceAsync({ apiUrl: `http://127.0.0.1:${port}`, token: TOKEN }, UDID)
|
||||
).resolves.toEqual({ udid: UDID, name: 'iPhone 17 Pro' });
|
||||
} finally {
|
||||
clearTimeout(responseTimer);
|
||||
server.closeAllConnections();
|
||||
server.close();
|
||||
await once(server, 'close');
|
||||
}
|
||||
});
|
||||
|
||||
it('does not borrow metadata from another device', async () => {
|
||||
jest
|
||||
.spyOn(fetchModule, 'default')
|
||||
.mockResolvedValueOnce(
|
||||
new fetchModule.Response(
|
||||
JSON.stringify({ devices: [{ device: 'other-device', name: 'Other Simulator' }] })
|
||||
)
|
||||
);
|
||||
await expect(
|
||||
fetchHostActionDeviceAsync({ apiUrl: 'https://sim.example.test', token: TOKEN }, UDID)
|
||||
).resolves.toEqual({ udid: UDID });
|
||||
});
|
||||
});
|
||||
|
||||
describe('host action transport policy', () => {
|
||||
afterEach(() => jest.restoreAllMocks());
|
||||
|
||||
@@ -223,6 +326,7 @@ describe('host action connection', () => {
|
||||
let received: { id: number; action: string; params: Record<string, unknown> }[];
|
||||
let requests: (string | undefined)[];
|
||||
let apiBody: string;
|
||||
let apiStatus: number;
|
||||
let uploads: Map<string, Buffer>;
|
||||
let reply: (message: {
|
||||
id: number;
|
||||
@@ -232,6 +336,8 @@ describe('host action connection', () => {
|
||||
let tmpDir: string;
|
||||
let connection: HostActionConnection | undefined;
|
||||
let closeBeforeReady: boolean;
|
||||
let sendReady: boolean;
|
||||
let refuseUpgrade: boolean;
|
||||
|
||||
function serveSim(message: {
|
||||
id: number;
|
||||
@@ -266,13 +372,16 @@ describe('host action connection', () => {
|
||||
requests = [];
|
||||
uploads = new Map();
|
||||
apiBody = JSON.stringify({ device: UDID });
|
||||
apiStatus = 200;
|
||||
reply = serveSim;
|
||||
closeBeforeReady = false;
|
||||
sendReady = true;
|
||||
refuseUpgrade = false;
|
||||
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'host-actions-'));
|
||||
server = http.createServer((req, res) => {
|
||||
requests.push(req.url);
|
||||
if (req.url === '/api' && req.headers.authorization === `Bearer ${TOKEN}`) {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.writeHead(apiStatus, { 'Content-Type': 'application/json' });
|
||||
res.end(apiBody);
|
||||
return;
|
||||
}
|
||||
@@ -282,6 +391,7 @@ describe('host action connection', () => {
|
||||
wss = new WebSocketServer({
|
||||
server,
|
||||
path: '/exec-ws',
|
||||
verifyClient: () => !refuseUpgrade,
|
||||
handleProtocols: offered =>
|
||||
offered.has(`serve-sim.token.${TOKEN}`) ? `serve-sim.token.${TOKEN}` : false,
|
||||
});
|
||||
@@ -290,7 +400,9 @@ describe('host action connection', () => {
|
||||
ws.close();
|
||||
return;
|
||||
}
|
||||
ws.send(JSON.stringify({ ready: true }));
|
||||
if (sendReady) {
|
||||
ws.send(JSON.stringify({ ready: true }));
|
||||
}
|
||||
ws.on('message', data => {
|
||||
const message = JSON.parse(data.toString());
|
||||
received.push(message);
|
||||
@@ -305,6 +417,51 @@ describe('host action connection', () => {
|
||||
apiUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
||||
});
|
||||
|
||||
it('does not open a connection when already canceled', async () => {
|
||||
const controller = new AbortController();
|
||||
const reason = new Error('canceled before setup');
|
||||
controller.abort(reason);
|
||||
await expect(
|
||||
connectHostActionsAsync({ apiUrl, token: TOKEN }, { signal: controller.signal })
|
||||
).rejects.toBe(reason);
|
||||
expect(requests).toEqual([]);
|
||||
});
|
||||
|
||||
it('cancels an upgrade waiting for readiness and releases the abort listener', async () => {
|
||||
sendReady = false;
|
||||
const controller = new AbortController();
|
||||
const accepted = once(wss, 'connection');
|
||||
const pending = connectHostActionsAsync(
|
||||
{ apiUrl, token: TOKEN },
|
||||
{ signal: controller.signal }
|
||||
);
|
||||
const [socket] = await accepted;
|
||||
const closed = once(socket, 'close');
|
||||
const reason = new Error('canceled during setup');
|
||||
const rejected = expect(pending).rejects.toBe(reason);
|
||||
controller.abort(reason);
|
||||
await rejected;
|
||||
await closed;
|
||||
expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('cancels a pending action on an established connection', async () => {
|
||||
const controller = new AbortController();
|
||||
connection = await connectHostActionsAsync(
|
||||
{ apiUrl, token: TOKEN },
|
||||
{ signal: controller.signal }
|
||||
);
|
||||
reply = () => null;
|
||||
const receivedRequest = once([...wss.clients][0], 'message');
|
||||
const pending = connection.requestAsync('appearance.get');
|
||||
const reason = new Error('canceled during action');
|
||||
const rejected = expect(pending).rejects.toBe(reason);
|
||||
await receivedRequest;
|
||||
controller.abort(reason);
|
||||
await rejected;
|
||||
expect(connection.signal.aborted).toBe(true);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
connection?.close();
|
||||
connection = undefined;
|
||||
@@ -324,6 +481,8 @@ describe('host action connection', () => {
|
||||
|
||||
it('sends several requests over one connection with the simulator udid', async () => {
|
||||
const hostActions = await connectAsync();
|
||||
expect(hostActions.udid).toBe(UDID);
|
||||
expect(hostActions.signal.aborted).toBe(false);
|
||||
|
||||
const results = await Promise.all([
|
||||
hostActions.requestAsync('hardwareKeyboard.get'),
|
||||
@@ -387,6 +546,69 @@ describe('host action connection', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('makes a timeout terminal, rejects every pending request and never sends another', async () => {
|
||||
reply = () => null;
|
||||
const hostActions = await connectAsync(50);
|
||||
const requests = [
|
||||
hostActions.requestAsync('memoryWarning'),
|
||||
hostActions.requestAsync('hardwareKeyboard.get'),
|
||||
];
|
||||
const results = await Promise.allSettled(requests);
|
||||
|
||||
expect(hostActions.signal.aborted).toBe(true);
|
||||
expect(results).toEqual([
|
||||
{ status: 'rejected', reason: hostActions.signal.reason },
|
||||
{ status: 'rejected', reason: hostActions.signal.reason },
|
||||
]);
|
||||
await expect(hostActions.requestAsync('memoryWarning')).rejects.toBe(hostActions.signal.reason);
|
||||
expect(received).toHaveLength(2);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect([...wss.clients].every(client => client.readyState !== 1)).toBe(true);
|
||||
});
|
||||
|
||||
it('aborts when the server closes an idle connection', async () => {
|
||||
const hostActions = await connectAsync();
|
||||
const aborted = once(hostActions.signal, 'abort');
|
||||
for (const client of wss.clients) {
|
||||
client.terminate();
|
||||
}
|
||||
await aborted;
|
||||
|
||||
await expect(hostActions.requestAsync('memoryWarning')).rejects.toBe(hostActions.signal.reason);
|
||||
expect(received).toEqual([]);
|
||||
});
|
||||
|
||||
it('aborts and immediately rejects pending work when its owner closes it', async () => {
|
||||
reply = () => null;
|
||||
const hostActions = await connectAsync();
|
||||
const request = hostActions.requestAsync('memoryWarning');
|
||||
const rejected = expect(request).rejects.toThrow('closed');
|
||||
hostActions.close();
|
||||
expect(hostActions.signal.aborted).toBe(true);
|
||||
await rejected;
|
||||
});
|
||||
|
||||
it('makes a transport write failure terminal without retrying the request', async () => {
|
||||
const hostActions = await connectAsync();
|
||||
const failure = new Error('socket write failed');
|
||||
const send = jest
|
||||
.spyOn(WebSocket.prototype, 'send')
|
||||
.mockImplementation((_data, callback: unknown) => {
|
||||
if (typeof callback === 'function') {
|
||||
callback(failure);
|
||||
}
|
||||
});
|
||||
try {
|
||||
await expect(hostActions.requestAsync('memoryWarning')).rejects.toBe(failure);
|
||||
expect(hostActions.signal.aborted).toBe(true);
|
||||
await expect(hostActions.requestAsync('memoryWarning')).rejects.toBe(failure);
|
||||
expect(send).toHaveBeenCalledTimes(1);
|
||||
expect(received).toEqual([]);
|
||||
} finally {
|
||||
send.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps a path on the API URL and drops its query', async () => {
|
||||
await expect(
|
||||
connectHostActionsAsync({ apiUrl: `${apiUrl}/preview?token=${TOKEN}`, token: TOKEN })
|
||||
@@ -401,6 +623,29 @@ describe('host action connection', () => {
|
||||
expect(wss.clients.size).toBe(0);
|
||||
});
|
||||
|
||||
it('explains an unavailable preview server instead of a raw HTTP 404', async () => {
|
||||
apiStatus = 404;
|
||||
await expect(connectHostActionsAsync({ apiUrl, token: TOKEN })).rejects.toThrow(
|
||||
'The simulator preview server is unavailable. The session may have ended or expired.'
|
||||
);
|
||||
expect(requests).toEqual(['/api']);
|
||||
expect(wss.clients.size).toBe(0);
|
||||
});
|
||||
|
||||
it('cleans up a WebSocket upgrade refused after the API accepted its token', async () => {
|
||||
refuseUpgrade = true;
|
||||
const upgraded = once(server, 'upgrade');
|
||||
const rejected = expect(connectHostActionsAsync({ apiUrl, token: TOKEN })).rejects.toThrow(
|
||||
'refused the connection (HTTP 401)'
|
||||
);
|
||||
const [, socket] = await upgraded;
|
||||
const closed = once(socket, 'close');
|
||||
await rejected;
|
||||
await closed;
|
||||
expect(wss.clients.size).toBe(0);
|
||||
expect(requests).toEqual(['/api']);
|
||||
});
|
||||
|
||||
it('does not send the session token to an API redirect target', async () => {
|
||||
server.removeAllListeners('request');
|
||||
server.on('request', (req, res) => {
|
||||
@@ -423,11 +668,30 @@ describe('host action connection', () => {
|
||||
closeBeforeReady = true;
|
||||
|
||||
await expect(connectHostActionsAsync({ apiUrl, token: TOKEN })).rejects.toThrow(
|
||||
/closed the connection during setup.*token.*eas simulator:get/
|
||||
'closed the connection during setup'
|
||||
);
|
||||
});
|
||||
|
||||
it.each([401, 403])(
|
||||
it('terminates its owned socket when setup never becomes ready', async () => {
|
||||
sendReady = false;
|
||||
jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate'] });
|
||||
try {
|
||||
const connected = once(wss, 'connection');
|
||||
const rejected = expect(connectHostActionsAsync({ apiUrl, token: TOKEN })).rejects.toThrow(
|
||||
'did not accept the connection within 30 seconds'
|
||||
);
|
||||
const [client] = await connected;
|
||||
const closed = once(client, 'close');
|
||||
jest.advanceTimersByTime(30_000);
|
||||
await rejected;
|
||||
await closed;
|
||||
expect(wss.clients.size).toBe(0);
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([401, 403, 404])(
|
||||
'closes a refused HTTP %i upgrade without waiting for its body',
|
||||
async status => {
|
||||
let rejectedSocket: Duplex | undefined;
|
||||
@@ -446,7 +710,9 @@ describe('host action connection', () => {
|
||||
|
||||
try {
|
||||
await expect(connectHostActionsAsync({ apiUrl, token: TOKEN })).rejects.toThrow(
|
||||
`refused the connection (HTTP ${status})`
|
||||
status === 404
|
||||
? 'The simulator preview server is unavailable. The session may have ended or expired.'
|
||||
: `refused the connection (HTTP ${status})`
|
||||
);
|
||||
await Promise.race([
|
||||
closed,
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
import { Parser } from '@oclif/core';
|
||||
import fs from 'fs-extra';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import Simulator from '../../commands/simulator';
|
||||
import { prepareControlConfigAsync } from '../controlConfig';
|
||||
import { resolveStartConfigAsync } from '../startConfig';
|
||||
|
||||
describe('simulator start configuration', () => {
|
||||
let folder: string;
|
||||
let file: string;
|
||||
beforeEach(async () => {
|
||||
folder = await fs.mkdtemp(path.join(os.tmpdir(), 'simulator-start-config-'));
|
||||
file = path.join(folder, 'simulator.json');
|
||||
});
|
||||
afterEach(async () => fs.remove(folder));
|
||||
|
||||
async function resolve(
|
||||
start: object,
|
||||
argv: string[] = [],
|
||||
actions?: object[]
|
||||
): Promise<
|
||||
Awaited<ReturnType<typeof resolveStartConfigAsync>> & {
|
||||
parsed: Awaited<ReturnType<typeof Parser.parse>>;
|
||||
}
|
||||
> {
|
||||
await fs.writeJson(file, { version: 1, start, ...(actions ? { actions } : {}) });
|
||||
const resolved = await resolveStartConfigAsync(['--import', file, ...argv], Simulator.flags);
|
||||
return { ...resolved, parsed: await Parser.parse(resolved.argv, { flags: Simulator.flags }) };
|
||||
}
|
||||
|
||||
it('uses saved values rather than command defaults and preserves explicit CLI overrides', async () => {
|
||||
const { parsed } = await resolve(
|
||||
{
|
||||
platform: 'ios',
|
||||
type: 'web-preview-only',
|
||||
force: false,
|
||||
device: 'Saved phone',
|
||||
tag: ['saved'],
|
||||
'public-link': true,
|
||||
},
|
||||
['--device', 'CLI phone', '--tag', 'one', '--tag', 'two', '--json']
|
||||
);
|
||||
expect(parsed.flags).toMatchObject({
|
||||
platform: 'ios',
|
||||
type: 'web-preview-only',
|
||||
force: false,
|
||||
device: 'CLI phone',
|
||||
tag: ['one', 'two'],
|
||||
'public-link': true,
|
||||
json: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('lets explicit CLI defaults override different saved values', async () => {
|
||||
const { parsed } = await resolve({ type: 'web-preview-only', force: false }, [
|
||||
'--type',
|
||||
'agent-device',
|
||||
'--force',
|
||||
]);
|
||||
expect(parsed.flags.type).toBe('agent-device');
|
||||
expect(parsed.flags.force).toBe(true);
|
||||
});
|
||||
|
||||
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'] },
|
||||
['--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();
|
||||
});
|
||||
|
||||
it('validates dependencies after merging and replaces array flags instead of appending', async () => {
|
||||
const { parsed } = await resolve(
|
||||
{ 'network-capture': true, 'network-capture-field': ['header'] },
|
||||
['--network-capture-field', 'request-body']
|
||||
);
|
||||
expect(parsed.flags['network-capture-field']).toEqual(['request-body']);
|
||||
});
|
||||
|
||||
it('lets an explicit app source replace a saved exclusive source and its Expo Go SDK', async () => {
|
||||
const expoGo = await resolve({ 'build-id': 'saved-build' }, ['--expo-go']);
|
||||
expect(expoGo.parsed.flags['expo-go']).toBe(true);
|
||||
expect(expoGo.parsed.flags['build-id']).toBeUndefined();
|
||||
const build = await resolve({ 'expo-go': true, 'sdk-version': '55.0.0' }, [
|
||||
'--build-id',
|
||||
'cli-build',
|
||||
]);
|
||||
expect(build.parsed.flags['build-id']).toBe('cli-build');
|
||||
expect(build.parsed.flags['expo-go']).toBeUndefined();
|
||||
expect(build.parsed.flags['sdk-version']).toBeUndefined();
|
||||
await expect(resolve({}, ['--build-id', 'cli-build', '--expo-go'])).rejects.toThrow(
|
||||
'cannot also be provided'
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects an empty import path instead of silently creating a default session', async () => {
|
||||
await expect(resolveStartConfigAsync(['--import='], Simulator.flags)).rejects.toThrow(
|
||||
'non-empty configuration file path'
|
||||
);
|
||||
});
|
||||
|
||||
it('honors short flags and negated CLI booleans', async () => {
|
||||
const { parsed } = await resolve({ platform: 'android', force: true }, [
|
||||
'-p',
|
||||
'ios',
|
||||
'--no-force',
|
||||
]);
|
||||
expect(parsed.flags.platform).toBe('ios');
|
||||
expect(parsed.flags.force).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ start: { unknown: 'x' }, message: 'Unknown or invocation-only' },
|
||||
{ start: { json: true }, message: 'invocation-only' },
|
||||
{ start: { 'non-interactive': true }, message: 'invocation-only' },
|
||||
{ start: { import: 'nested.json' }, message: 'invocation-only' },
|
||||
{ start: { 'expo-go': 'yes' }, message: 'must be a boolean' },
|
||||
{ start: { device: ['one', 'two'] }, message: 'multiple values' },
|
||||
{ start: { device: { name: 'phone' } }, message: 'string or number' },
|
||||
{ start: { platform: 'windows' }, message: 'ios' },
|
||||
{ start: { 'max-duration-minutes': -1 }, message: 'greater than or equal to 0' },
|
||||
{ start: { 'build-id': 'abc', 'expo-go': true }, message: 'cannot also be provided' },
|
||||
])('rejects invalid start values: $start', async ({ start, message }) => {
|
||||
await expect(resolve(start)).rejects.toThrow(message);
|
||||
});
|
||||
|
||||
it('rejects a missing local input before creating a session', async () => {
|
||||
await expect(
|
||||
resolve({ platform: 'ios' }, [], [{ action: 'app.install', file: './missing.ipa' }])
|
||||
).rejects.toThrow('does not exist on this computer');
|
||||
});
|
||||
|
||||
it('rejects invalid output parents and device overrides during local preflight', async () => {
|
||||
await expect(
|
||||
resolve({}, [], [{ action: 'screenshot.capture', output: './missing/shot.png' }])
|
||||
).rejects.toThrow('Config step 1');
|
||||
await expect(
|
||||
resolve({}, [], [{ action: 'appearance.get', params: { udid: 'other-device' } }])
|
||||
).rejects.toThrow('remove params.udid');
|
||||
});
|
||||
|
||||
it.each(['./missing/', './file.txt/'])(
|
||||
'rejects an output directory that does not exist: %s',
|
||||
async output => {
|
||||
await fs.writeFile(path.join(folder, 'file.txt'), 'existing file');
|
||||
await expect(resolve({}, [], [{ action: 'screenshot.capture', output }])).rejects.toThrow(
|
||||
'must be an existing directory'
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
it.each(['./screenshots/', './screen.png'])(
|
||||
'accepts an existing output directory or a new file: %s',
|
||||
async output => {
|
||||
await fs.mkdir(path.join(folder, 'screenshots'));
|
||||
await expect(
|
||||
resolve({}, [], [{ action: 'screenshot.capture', output }])
|
||||
).resolves.toBeDefined();
|
||||
}
|
||||
);
|
||||
|
||||
it('allows the same file in control import and resolves files relative to it', async () => {
|
||||
await fs.writeFile(path.join(folder, 'input.txt'), 'contents');
|
||||
const { config } = await resolve(
|
||||
{ platform: 'ios' },
|
||||
[],
|
||||
[{ action: 'upload', file: './input.txt' }]
|
||||
);
|
||||
const prepared = await prepareControlConfigAsync(
|
||||
{
|
||||
upload: {
|
||||
type: 'object',
|
||||
properties: { udid: { type: 'string' }, path: { type: 'string' } },
|
||||
required: ['udid', 'path'],
|
||||
upload: 'path',
|
||||
},
|
||||
},
|
||||
file,
|
||||
'device'
|
||||
);
|
||||
expect(prepared.actions[0].plan.localFile?.path).toBe(path.join(folder, 'input.txt'));
|
||||
expect(config?.actions?.[0].params).toEqual({});
|
||||
});
|
||||
|
||||
it('reports an unreadable file before trying to create a session', async () => {
|
||||
await expect(resolveStartConfigAsync(['--import', file], Simulator.flags)).rejects.toThrow(
|
||||
`Could not read simulator configuration ${file}`
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves no-import argv and reports malformed or unknown config fields', async () => {
|
||||
expect(await resolveStartConfigAsync(['--platform', 'ios'], Simulator.flags)).toEqual({
|
||||
argv: ['--platform', 'ios'],
|
||||
});
|
||||
await fs.writeJson(file, { version: 2, start: {} });
|
||||
await expect(resolveStartConfigAsync(['--import', file], Simulator.flags)).rejects.toThrow(
|
||||
'Invalid simulator configuration'
|
||||
);
|
||||
await fs.writeJson(file, { version: 1, typo: {} });
|
||||
await expect(resolveStartConfigAsync(['--import', file], Simulator.flags)).rejects.toThrow(
|
||||
'Invalid simulator configuration'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
import fs from 'fs-extra';
|
||||
import { once } from 'node:events';
|
||||
import http from 'node:http';
|
||||
import { AddressInfo } from 'node:net';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { WebSocketServer } from 'ws';
|
||||
|
||||
import { readSimulatorSessionConfigAsync } from '../sessionConfig';
|
||||
import { applyStartConfigAsync } from '../startSetup';
|
||||
|
||||
// Real HTTP/WebSocket transport and file IO verify the shared runner wiring, not just mocks.
|
||||
describe(applyStartConfigAsync, () => {
|
||||
let server: http.Server;
|
||||
let sockets: WebSocketServer;
|
||||
let folder: string;
|
||||
let apiUrl: string;
|
||||
let actions: { action: string; params: Record<string, unknown> }[];
|
||||
const catalog = {
|
||||
set: {
|
||||
type: 'object',
|
||||
properties: { udid: { type: 'string' }, value: { type: 'string' } },
|
||||
required: ['udid', 'value'],
|
||||
},
|
||||
screenshot: {
|
||||
type: 'object',
|
||||
properties: { udid: { type: 'string' } },
|
||||
required: ['udid'],
|
||||
output: 'base64',
|
||||
},
|
||||
};
|
||||
beforeEach(async () => {
|
||||
actions = [];
|
||||
folder = await fs.mkdtemp(path.join(os.tmpdir(), 'start-setup-'));
|
||||
server = http.createServer((req, res) => {
|
||||
if (req.url !== '/api' || req.headers.authorization !== 'Bearer token') {
|
||||
res.writeHead(401).end();
|
||||
return;
|
||||
}
|
||||
res.setHeader('content-type', 'application/json');
|
||||
res.end(JSON.stringify({ device: 'owned-device' }));
|
||||
});
|
||||
sockets = new WebSocketServer({
|
||||
server,
|
||||
path: '/exec-ws',
|
||||
handleProtocols: protocols =>
|
||||
protocols.has('serve-sim.token.token') ? 'serve-sim.token.token' : false,
|
||||
});
|
||||
sockets.on('connection', socket => {
|
||||
socket.send(JSON.stringify({ ready: true }));
|
||||
socket.on('message', bytes => {
|
||||
const message = JSON.parse(bytes.toString());
|
||||
actions.push(message);
|
||||
const stdout =
|
||||
message.action === 'actions.describe'
|
||||
? JSON.stringify(catalog)
|
||||
: message.action === 'screenshot'
|
||||
? Buffer.from('image bytes').toString('base64')
|
||||
: 'done';
|
||||
socket.send(JSON.stringify({ id: message.id, stdout, stderr: '', exitCode: 0 }));
|
||||
});
|
||||
});
|
||||
server.listen(0, '127.0.0.1');
|
||||
await once(server, 'listening');
|
||||
apiUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
||||
});
|
||||
afterEach(async () => {
|
||||
for (const socket of sockets.clients) {
|
||||
socket.terminate();
|
||||
}
|
||||
sockets.close();
|
||||
server.close();
|
||||
await once(server, 'close');
|
||||
await fs.remove(folder);
|
||||
});
|
||||
|
||||
it('runs the captured config after the file changes, writes outputs relative to it and closes transport', async () => {
|
||||
const file = path.join(folder, 'session.json');
|
||||
await fs.writeJson(file, {
|
||||
version: 1,
|
||||
start: { platform: 'ios' },
|
||||
actions: [
|
||||
{ action: 'set', params: { value: 'dark' } },
|
||||
{ action: 'screenshot', output: './screen.png' },
|
||||
],
|
||||
});
|
||||
const config = await readSimulatorSessionConfigAsync(file);
|
||||
await fs.writeJson(file, { version: 999 });
|
||||
const closed = new Promise<void>(resolve =>
|
||||
sockets.once('connection', socket => socket.once('close', resolve))
|
||||
);
|
||||
const progress = jest.fn();
|
||||
const results = await applyStartConfigAsync({ apiUrl, token: 'token' }, config, {
|
||||
signal: new AbortController().signal,
|
||||
onProgress: progress,
|
||||
});
|
||||
await closed;
|
||||
expect(results.map(result => result.action)).toEqual(['set', 'screenshot']);
|
||||
expect(await fs.readFile(path.join(folder, 'screen.png'), 'utf8')).toBe('image bytes');
|
||||
expect(actions.every(action => action.params.udid === 'owned-device')).toBe(true);
|
||||
expect(progress).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ step: 2, total: 2, status: 'completed' })
|
||||
);
|
||||
});
|
||||
|
||||
it('validates all actions before sending the first one and closes on validation failure', async () => {
|
||||
const file = path.join(folder, 'session.json');
|
||||
await fs.writeJson(file, {
|
||||
version: 1,
|
||||
actions: [{ action: 'set', params: { value: 'dark' } }, { action: 'unknown' }],
|
||||
});
|
||||
const config = await readSimulatorSessionConfigAsync(file);
|
||||
const closed = new Promise<void>(resolve =>
|
||||
sockets.once('connection', socket => socket.once('close', resolve))
|
||||
);
|
||||
await expect(
|
||||
applyStartConfigAsync({ apiUrl, token: 'token' }, config, {
|
||||
signal: new AbortController().signal,
|
||||
})
|
||||
).rejects.toThrow('Unknown simulator action');
|
||||
await closed;
|
||||
expect(actions.map(action => action.action)).toEqual(['actions.describe']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
import * as fs from 'fs-extra';
|
||||
import path from 'path';
|
||||
|
||||
import {
|
||||
HostActionCatalog,
|
||||
HostActionCatalogEntry,
|
||||
HostActionConnection,
|
||||
assertHostActionOutputAsync,
|
||||
saveHostActionOutputAsync,
|
||||
uploadFileAsync,
|
||||
} from './hostActions';
|
||||
|
||||
export type ControlAction = {
|
||||
action: string;
|
||||
params: Record<string, unknown>;
|
||||
outputPath?: string;
|
||||
file?: string;
|
||||
};
|
||||
|
||||
export type ControlActionResult = { output: string; file: string | null };
|
||||
|
||||
export type PreparedControlAction = Readonly<{
|
||||
action: string;
|
||||
entry: HostActionCatalogEntry;
|
||||
params: Readonly<Record<string, unknown>>;
|
||||
outputPath?: string;
|
||||
localFile?: Readonly<{ param: string; path: string }>;
|
||||
}>;
|
||||
|
||||
export function resolveControlActionPath(value: string, baseDir?: string): string {
|
||||
if (!baseDir) {
|
||||
return value;
|
||||
}
|
||||
const resolved = path.resolve(baseDir, value);
|
||||
return value.endsWith('/') || value.endsWith(path.sep) ? `${resolved}${path.sep}` : resolved;
|
||||
}
|
||||
|
||||
export async function prepareControlActionAsync(
|
||||
catalog: HostActionCatalog,
|
||||
action: ControlAction,
|
||||
{
|
||||
localFileMode = 'auto',
|
||||
baseDir,
|
||||
}: { localFileMode?: 'auto' | 'explicit'; baseDir?: string } = {}
|
||||
): Promise<PreparedControlAction> {
|
||||
const entry = Object.hasOwn(catalog, action.action) ? catalog[action.action] : undefined;
|
||||
if (!entry) {
|
||||
throw new Error(
|
||||
`Unknown simulator action "${action.action}". Run \`eas simulator:control --list\` to see the actions.`
|
||||
);
|
||||
}
|
||||
const params = { ...action.params };
|
||||
const outputPath = action.outputPath
|
||||
? resolveControlActionPath(action.outputPath, baseDir)
|
||||
: action.outputPath;
|
||||
await assertHostActionOutputAsync(action.action, entry, outputPath);
|
||||
|
||||
let localFile: PreparedControlAction['localFile'];
|
||||
const param = entry.upload;
|
||||
const applies = Object.entries(entry.uploadWhen ?? {}).every(
|
||||
([name, expected]) => params[name] === expected
|
||||
);
|
||||
if (action.file !== undefined) {
|
||||
if (!param || !applies) {
|
||||
throw new Error(`${action.action} does not accept a local file with these parameters.`);
|
||||
}
|
||||
if (Object.hasOwn(params, param)) {
|
||||
throw new Error(`${param} and file cannot both be supplied for ${action.action}.`);
|
||||
}
|
||||
localFile = { param, path: resolveControlActionPath(action.file, baseDir) };
|
||||
await assertLocalFileAsync(localFile.path);
|
||||
} else if (localFileMode === 'auto' && param && applies && typeof params[param] === 'string') {
|
||||
const value = params[param];
|
||||
if (value.startsWith('host:')) {
|
||||
if (entry.uploadAs === 'id') {
|
||||
throw new Error(
|
||||
'This action requires a local file to upload; host: paths are not supported.'
|
||||
);
|
||||
}
|
||||
const hostPath = value.slice('host:'.length);
|
||||
if (!path.posix.isAbsolute(hostPath)) {
|
||||
throw new Error(
|
||||
`A host: path must be absolute, for example host:/tmp/app.tar.gz. For a local filename beginning with host:, use ./${value}.`
|
||||
);
|
||||
}
|
||||
params[param] = hostPath;
|
||||
} else {
|
||||
const localPath = resolveControlActionPath(value, baseDir);
|
||||
const stat = await fs.stat(localPath).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code === 'ENOENT' || error.code === 'ENOTDIR') {
|
||||
return null;
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
if (!stat) {
|
||||
throw new Error(
|
||||
`${value} does not exist on this computer. Pass a local file, or prefix an absolute simulator-host path with host:.`
|
||||
);
|
||||
}
|
||||
await assertLocalFileAsync(localPath, stat);
|
||||
localFile = { param, path: localPath };
|
||||
}
|
||||
}
|
||||
return {
|
||||
action: action.action,
|
||||
entry,
|
||||
params,
|
||||
outputPath,
|
||||
...(localFile ? { localFile } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export async function assertLocalFileAsync(localPath: string, stats?: fs.Stats): Promise<void> {
|
||||
const stat = stats ?? (await fs.stat(localPath).catch(() => null));
|
||||
if (!stat) {
|
||||
throw new Error(`${localPath} does not exist on this computer.`);
|
||||
}
|
||||
if (stat.isDirectory()) {
|
||||
throw new Error(`${localPath} is a folder. Pass the path of a file.`);
|
||||
}
|
||||
if (!stat.isFile()) {
|
||||
throw new Error(`${localPath} is not a regular file.`);
|
||||
}
|
||||
if (stat.size === 0) {
|
||||
throw new Error(`${localPath} is empty. Pass a file with content.`);
|
||||
}
|
||||
await fs.access(localPath, fs.constants.R_OK);
|
||||
}
|
||||
|
||||
export async function executeControlActionAsync(
|
||||
connection: HostActionConnection,
|
||||
plan: PreparedControlAction,
|
||||
{ validateParams }: { validateParams?: (params: Record<string, unknown>) => void } = {}
|
||||
): Promise<ControlActionResult> {
|
||||
connection.signal.throwIfAborted();
|
||||
const params: Record<string, unknown> = { ...plan.params };
|
||||
let uploadId: string | undefined;
|
||||
let succeeded = false;
|
||||
try {
|
||||
if (plan.localFile) {
|
||||
const upload = await uploadFileAsync(connection, plan.localFile.path);
|
||||
uploadId = upload.uploadId;
|
||||
params[plan.localFile.param] = plan.entry.uploadAs === 'id' ? upload.uploadId : upload.path;
|
||||
}
|
||||
connection.signal.throwIfAborted();
|
||||
validateParams?.(params);
|
||||
const result = await connection.requestAsync(plan.action, params);
|
||||
if (result.exitCode !== 0) {
|
||||
const detail = (result.stderr || result.stdout).trim() || `exit code ${result.exitCode}`;
|
||||
throw new Error(`The simulator could not run ${plan.action}: ${detail}`);
|
||||
}
|
||||
succeeded = true;
|
||||
const file = await saveHostActionOutputAsync(
|
||||
connection,
|
||||
plan.entry,
|
||||
result.stdout,
|
||||
plan.outputPath
|
||||
);
|
||||
return { output: file ? '' : result.stdout.trim(), file };
|
||||
} finally {
|
||||
if (uploadId && (!plan.entry.keepUpload || !succeeded)) {
|
||||
await connection.requestAsync('upload.remove', { uploadId }).catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function parseControlActionOutput(output: string): unknown {
|
||||
try {
|
||||
return JSON.parse(output);
|
||||
} catch {
|
||||
return output;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
import Ajv2020, { AnySchema } from 'ajv/dist/2020';
|
||||
import addFormats from 'ajv-formats';
|
||||
import * as fs from 'fs-extra';
|
||||
import path from 'path';
|
||||
|
||||
import {
|
||||
ControlActionResult,
|
||||
PreparedControlAction,
|
||||
assertLocalFileAsync,
|
||||
executeControlActionAsync,
|
||||
parseControlActionOutput,
|
||||
prepareControlActionAsync,
|
||||
resolveControlActionPath,
|
||||
} from './controlActions';
|
||||
import { HostActionCatalog, HostActionConnection, createHostActionUploadId } from './hostActions';
|
||||
import { SimulatorSessionConfig, readSimulatorSessionConfigAsync } from './sessionConfig';
|
||||
|
||||
type ConfigAction = {
|
||||
readonly plan: PreparedControlAction;
|
||||
readonly validateParams: (params: Record<string, unknown>) => void;
|
||||
};
|
||||
|
||||
export type PreparedControlConfig = {
|
||||
readonly path: string;
|
||||
readonly udid: string;
|
||||
readonly actions: readonly ConfigAction[];
|
||||
};
|
||||
|
||||
export type ControlConfigResult = ControlActionResult & { action: string };
|
||||
|
||||
export type ControlConfigProgress = {
|
||||
step: number;
|
||||
total: number;
|
||||
action: string;
|
||||
} & ({ status: 'running' } | { status: 'completed'; result: ControlConfigResult });
|
||||
|
||||
export class ControlConfigExecutionError extends Error {
|
||||
constructor(
|
||||
readonly step: number,
|
||||
readonly action: string,
|
||||
readonly completed: readonly ControlConfigResult[],
|
||||
cause: unknown
|
||||
) {
|
||||
super(
|
||||
`Config step ${step} (${action}) failed after ${completed.length} completed actions: ${errorMessage(cause)}`,
|
||||
{ cause }
|
||||
);
|
||||
this.name = 'ControlConfigExecutionError';
|
||||
}
|
||||
}
|
||||
|
||||
export async function prepareControlConfigAsync(
|
||||
catalog: HostActionCatalog,
|
||||
filePath: string,
|
||||
udid: string,
|
||||
input?: SimulatorSessionConfig
|
||||
): Promise<PreparedControlConfig> {
|
||||
const config = input ?? (await readSimulatorSessionConfigAsync(filePath));
|
||||
const absolutePath = config.path;
|
||||
if (!config.actions?.length) {
|
||||
throw new Error(
|
||||
`Invalid simulator configuration ${absolutePath}: actions must contain at least one action.`
|
||||
);
|
||||
}
|
||||
|
||||
const ajv = addFormats(new Ajv2020({ strict: false, allErrors: true }));
|
||||
const actions: ConfigAction[] = [];
|
||||
for (const [index, action] of config.actions.entries()) {
|
||||
try {
|
||||
if (Object.hasOwn(action.params, 'udid')) {
|
||||
throw new Error('The simulator is selected by the session; remove params.udid.');
|
||||
}
|
||||
const plan = await prepareControlActionAsync(
|
||||
catalog,
|
||||
{ ...action, outputPath: action.output },
|
||||
{ localFileMode: 'explicit', baseDir: path.dirname(absolutePath) }
|
||||
);
|
||||
if (plan.entry.output) {
|
||||
if (!plan.outputPath) {
|
||||
throw new Error('Set output to a file or directory for this action.');
|
||||
}
|
||||
await assertWritableOutputAsync(plan.outputPath);
|
||||
}
|
||||
assertUnambiguousFileSource(ajv, plan, udid);
|
||||
const validate = ajv.compile(plan.entry as AnySchema);
|
||||
const validateParams = (params: Record<string, unknown>): void => {
|
||||
if (!validate({ ...params, udid })) {
|
||||
throw new Error(ajv.errorsText(validate.errors, { dataVar: 'params' }));
|
||||
}
|
||||
};
|
||||
const params = { ...plan.params };
|
||||
if (plan.localFile) {
|
||||
const uploadId = createHostActionUploadId(plan.localFile.path);
|
||||
params[plan.localFile.param] =
|
||||
plan.entry.uploadAs === 'id' ? uploadId : `/tmp/serve-sim-uploads/${uploadId}`;
|
||||
}
|
||||
validateParams(params);
|
||||
actions.push({ plan, validateParams });
|
||||
} catch (error) {
|
||||
throw new Error(`Config step ${index + 1} (${action.action}): ${errorMessage(error)}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
return { path: absolutePath, udid, actions };
|
||||
}
|
||||
|
||||
/** Check local inputs before requesting a paid session; runtime validation still uses the live catalog. */
|
||||
export async function preflightControlConfigFilesAsync(
|
||||
config: SimulatorSessionConfig
|
||||
): Promise<void> {
|
||||
for (const [index, action] of (config.actions ?? []).entries()) {
|
||||
try {
|
||||
if (Object.hasOwn(action.params, 'udid')) {
|
||||
throw new Error('The simulator is selected by the session; remove params.udid.');
|
||||
}
|
||||
if (action.file) {
|
||||
await assertLocalFileAsync(path.resolve(path.dirname(config.path), action.file));
|
||||
}
|
||||
if (action.output) {
|
||||
await assertWritableOutputAsync(
|
||||
resolveControlActionPath(action.output, path.dirname(config.path))
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error(`Config step ${index + 1} (${action.action}): ${errorMessage(error)}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function assertWritableOutputAsync(outputPath: string): Promise<void> {
|
||||
const stat = await fs.stat(outputPath).catch(() => null);
|
||||
if ((outputPath.endsWith('/') || outputPath.endsWith(path.sep)) && !stat?.isDirectory()) {
|
||||
throw new Error(`${outputPath} must be an existing directory.`);
|
||||
}
|
||||
if (stat && !stat.isFile() && !stat.isDirectory()) {
|
||||
throw new Error(`${outputPath} must be a regular file or directory.`);
|
||||
}
|
||||
await fs.access(
|
||||
stat ? outputPath : path.dirname(outputPath),
|
||||
fs.constants.W_OK | (stat?.isFile() ? 0 : fs.constants.X_OK)
|
||||
);
|
||||
}
|
||||
|
||||
function declaresParameter(schema: unknown, name: string): boolean {
|
||||
if (typeof schema !== 'object' || schema === null || Array.isArray(schema)) {
|
||||
return false;
|
||||
}
|
||||
const { properties, allOf } = schema as { properties?: object; allOf?: unknown[] };
|
||||
return (
|
||||
(properties !== undefined && Object.hasOwn(properties, name)) ||
|
||||
(Array.isArray(allOf) && allOf.some(child => declaresParameter(child, name)))
|
||||
);
|
||||
}
|
||||
|
||||
function assertUnambiguousFileSource(
|
||||
ajv: Ajv2020,
|
||||
plan: PreparedControlAction,
|
||||
udid: string
|
||||
): void {
|
||||
if (!plan.localFile) {
|
||||
return;
|
||||
}
|
||||
const { anyOf, oneOf, ...common } = plan.entry;
|
||||
for (const branch of anyOf ?? oneOf ?? []) {
|
||||
if (declaresParameter(branch, plan.localFile.param)) {
|
||||
continue;
|
||||
}
|
||||
const validate = ajv.compile({
|
||||
...common,
|
||||
allOf: [...(common.allOf ?? []), branch],
|
||||
} as AnySchema);
|
||||
if (validate({ ...plan.params, udid })) {
|
||||
throw new Error('file conflicts with another source in params. Supply only one file source.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function executeControlConfigAsync(
|
||||
connection: HostActionConnection,
|
||||
config: PreparedControlConfig,
|
||||
{ onProgress }: { onProgress?: (progress: ControlConfigProgress) => void } = {}
|
||||
): Promise<ControlConfigResult[]> {
|
||||
if (config.udid !== connection.udid) {
|
||||
throw new Error('The simulator changed after this configuration was checked. Import it again.');
|
||||
}
|
||||
const completed: ControlConfigResult[] = [];
|
||||
for (const [index, { plan, validateParams }] of config.actions.entries()) {
|
||||
const progress = { step: index + 1, total: config.actions.length, action: plan.action };
|
||||
onProgress?.({ ...progress, status: 'running' });
|
||||
let result: ControlActionResult;
|
||||
try {
|
||||
result = await executeControlActionAsync(connection, plan, { validateParams });
|
||||
} catch (error) {
|
||||
throw new ControlConfigExecutionError(index + 1, plan.action, completed, error);
|
||||
}
|
||||
const entry = { action: plan.action, ...result };
|
||||
completed.push(entry);
|
||||
onProgress?.({ ...progress, status: 'completed', result: entry });
|
||||
}
|
||||
return completed;
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
export function serializeControlConfigResults(
|
||||
results: readonly ControlConfigResult[]
|
||||
): { action: string; output: unknown; file: string | null }[] {
|
||||
return results.map(result => ({ ...result, output: parseControlActionOutput(result.output) }));
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
import chalk from 'chalk';
|
||||
|
||||
import { ControlAction } from './controlActions';
|
||||
import { ControlPromptCancelledError, promptControlValueAsync } from './controlPrompts';
|
||||
import { HostActionCatalog, HostActionCatalogEntry, NUMBER_PATTERN } from './hostActions';
|
||||
import Log from '../log';
|
||||
|
||||
type Schema = Record<string, unknown>;
|
||||
type Fields = { properties: Record<string, unknown>; required: Set<string> };
|
||||
|
||||
function isObject(value: unknown): value is Schema {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function getObjectFields(schema: Schema): Fields | null {
|
||||
if (schema.anyOf || schema.oneOf || (schema.type && schema.type !== 'object')) {
|
||||
return null;
|
||||
}
|
||||
const result: Fields = {
|
||||
properties: isObject(schema.properties) ? { ...schema.properties } : {},
|
||||
required: new Set(Array.isArray(schema.required) ? (schema.required as string[]) : []),
|
||||
};
|
||||
for (const child of Array.isArray(schema.allOf) ? schema.allOf : []) {
|
||||
const nested = isObject(child) ? getObjectFields(child) : null;
|
||||
if (!nested) {
|
||||
return null;
|
||||
}
|
||||
Object.assign(result.properties, nested.properties);
|
||||
nested.required.forEach(name => result.required.add(name));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function selectFieldsAsync(
|
||||
entry: HostActionCatalogEntry,
|
||||
signal: AbortSignal
|
||||
): Promise<{ fields: Fields; params: Schema } | null> {
|
||||
const alternatives = entry.oneOf ?? entry.anyOf;
|
||||
if (!alternatives) {
|
||||
const result = getObjectFields(entry);
|
||||
return result && { fields: result, params: {} };
|
||||
}
|
||||
const branches = alternatives.map(branch => (isObject(branch) ? getObjectFields(branch) : null));
|
||||
if (branches.some(branch => !branch)) {
|
||||
return null;
|
||||
}
|
||||
const available = branches as Fields[];
|
||||
let selected: number | undefined;
|
||||
const params: Schema = {};
|
||||
for (const name of Object.keys(available[0]?.properties ?? {})) {
|
||||
if (name === 'udid') {
|
||||
continue;
|
||||
}
|
||||
const values = available.map(branch => branch.properties[name]);
|
||||
if (!values.every(schema => isObject(schema) && Object.hasOwn(schema, 'const'))) {
|
||||
continue;
|
||||
}
|
||||
const constants = values.map(schema => (schema as Schema).const);
|
||||
if (new Set(constants.map(value => JSON.stringify(value))).size !== constants.length) {
|
||||
continue;
|
||||
}
|
||||
const value = await promptControlValueAsync(
|
||||
{
|
||||
type: 'select',
|
||||
message: name,
|
||||
choices: constants.map(value => ({ title: String(value), value })),
|
||||
},
|
||||
signal
|
||||
);
|
||||
selected = constants.findIndex(constant => constant === value);
|
||||
params[name] = value;
|
||||
break;
|
||||
}
|
||||
if (selected === undefined) {
|
||||
// Some upload actions expose a path to users but also accept an internal upload ID.
|
||||
const exposed = entry.args ?? (entry.upload ? [entry.upload] : []);
|
||||
const candidates = available
|
||||
.map((branch, index) => ({ branch, index }))
|
||||
.filter(
|
||||
({ branch }) =>
|
||||
exposed.length > 0 && exposed.every(name => Object.hasOwn(branch.properties, name))
|
||||
);
|
||||
if (candidates.length !== 1) {
|
||||
return null;
|
||||
}
|
||||
selected = candidates[0].index;
|
||||
}
|
||||
const common = getObjectFields({ ...entry, anyOf: undefined, oneOf: undefined });
|
||||
if (!common || !available[selected]) {
|
||||
return null;
|
||||
}
|
||||
const chosen = available[selected];
|
||||
return {
|
||||
fields: {
|
||||
properties: { ...common.properties, ...chosen.properties },
|
||||
required: new Set([...common.required, ...chosen.required]),
|
||||
},
|
||||
params,
|
||||
};
|
||||
}
|
||||
|
||||
function getSchemaTypes(schema: Schema): string[] {
|
||||
return [
|
||||
schema.type ?? [],
|
||||
...(Array.isArray(schema.anyOf) ? schema.anyOf : []),
|
||||
...(Array.isArray(schema.oneOf) ? schema.oneOf : []),
|
||||
].flatMap(value =>
|
||||
typeof value === 'string'
|
||||
? [value]
|
||||
: Array.isArray(value)
|
||||
? value.filter((item): item is string => typeof item === 'string')
|
||||
: isObject(value)
|
||||
? getSchemaTypes(value)
|
||||
: []
|
||||
);
|
||||
}
|
||||
|
||||
function parseValue(value: string, schema: Schema): unknown {
|
||||
const accepted = getSchemaTypes(schema);
|
||||
if (usesJson(accepted)) {
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
const type = parsed === null ? 'null' : Array.isArray(parsed) ? 'array' : typeof parsed;
|
||||
if (
|
||||
accepted.includes(type) ||
|
||||
(type === 'number' && accepted.includes('integer') && Number.isInteger(parsed))
|
||||
) {
|
||||
return parsed;
|
||||
}
|
||||
throw new Error('Enter a JSON value matching this parameter.');
|
||||
}
|
||||
if ((accepted.includes('number') || accepted.includes('integer')) && NUMBER_PATTERN.test(value)) {
|
||||
const number = Number(value);
|
||||
if (
|
||||
Number.isFinite(number) &&
|
||||
(!accepted.includes('integer') || accepted.includes('number') || Number.isInteger(number))
|
||||
) {
|
||||
return number;
|
||||
}
|
||||
}
|
||||
if (accepted.includes('string') || accepted.length === 0) {
|
||||
return value;
|
||||
}
|
||||
throw new Error('Enter a valid number.');
|
||||
}
|
||||
|
||||
function usesJson(accepted: string[]): boolean {
|
||||
return ['object', 'array', 'boolean', 'null'].some(type => accepted.includes(type));
|
||||
}
|
||||
|
||||
async function promptFieldAsync(name: string, raw: unknown, signal: AbortSignal): Promise<unknown> {
|
||||
const schema = isObject(raw) ? raw : {};
|
||||
if (Object.hasOwn(schema, 'const')) {
|
||||
return schema.const;
|
||||
}
|
||||
if (typeof schema.description === 'string') {
|
||||
Log.gray(schema.description);
|
||||
}
|
||||
if (Array.isArray(schema.enum)) {
|
||||
return await promptControlValueAsync(
|
||||
{
|
||||
type: 'select',
|
||||
message: name,
|
||||
choices: schema.enum.map(value => ({ title: String(value), value })),
|
||||
},
|
||||
signal
|
||||
);
|
||||
}
|
||||
const accepted = getSchemaTypes(schema);
|
||||
if (accepted.length === 1 && accepted[0] === 'boolean') {
|
||||
return await promptControlValueAsync(
|
||||
{ type: 'toggle', message: name, active: 'true', inactive: 'false', initial: false },
|
||||
signal
|
||||
);
|
||||
}
|
||||
const json = usesJson(accepted);
|
||||
const value = await promptControlValueAsync(
|
||||
{
|
||||
type: 'text',
|
||||
message: `${name}${json ? ' (JSON)' : ''}`,
|
||||
validate(value: string) {
|
||||
try {
|
||||
parseValue(value, schema);
|
||||
return true;
|
||||
} catch (error) {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
},
|
||||
},
|
||||
signal
|
||||
);
|
||||
return parseValue(String(value), schema);
|
||||
}
|
||||
|
||||
export async function promptControlActionAsync(
|
||||
action: string,
|
||||
entry: HostActionCatalogEntry,
|
||||
signal: AbortSignal
|
||||
): Promise<ControlAction> {
|
||||
const selected = await selectFieldsAsync(entry, signal);
|
||||
let params: Record<string, unknown>;
|
||||
if (!selected) {
|
||||
const value = await promptControlValueAsync(
|
||||
{
|
||||
type: 'text',
|
||||
message: 'Parameters (JSON object, without udid)',
|
||||
validate(value: string) {
|
||||
try {
|
||||
return isObject(JSON.parse(value)) || 'Enter a JSON object.';
|
||||
} catch {
|
||||
return 'Enter a JSON object.';
|
||||
}
|
||||
},
|
||||
},
|
||||
signal
|
||||
);
|
||||
params = JSON.parse(String(value));
|
||||
} else {
|
||||
params = selected.params;
|
||||
const names = [...new Set([...(entry.args ?? []), ...Object.keys(selected.fields.properties)])];
|
||||
for (const name of names) {
|
||||
if (
|
||||
name === 'udid' ||
|
||||
Object.hasOwn(params, name) ||
|
||||
!Object.hasOwn(selected.fields.properties, name)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const schema = selected.fields.properties[name];
|
||||
if (!selected.fields.required.has(name)) {
|
||||
const hint =
|
||||
isObject(schema) && Object.hasOwn(schema, 'default')
|
||||
? ` (default: ${JSON.stringify(schema.default)})`
|
||||
: '';
|
||||
const include = await promptControlValueAsync(
|
||||
{ type: 'confirm', message: `Set optional ${name}${hint}?`, initial: false },
|
||||
signal
|
||||
);
|
||||
if (!include) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
params[name] = await promptFieldAsync(name, schema, signal);
|
||||
}
|
||||
}
|
||||
const result: ControlAction = { action, params };
|
||||
if (entry.output) {
|
||||
const outputPath = await promptControlValueAsync(
|
||||
{
|
||||
type: 'text',
|
||||
message: 'Save file to',
|
||||
validate: (value: string) => value.trim().length > 0 || 'Enter a local output path.',
|
||||
},
|
||||
signal
|
||||
);
|
||||
result.outputPath = String(outputPath);
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function runControlMenuAsync({
|
||||
catalog,
|
||||
signal,
|
||||
runActionAsync,
|
||||
}: {
|
||||
catalog: HostActionCatalog;
|
||||
signal: AbortSignal;
|
||||
runActionAsync: (action: ControlAction) => Promise<void>;
|
||||
}): Promise<void> {
|
||||
const choices = [
|
||||
{ title: 'Exit', description: 'Close simulator controls', value: { kind: 'exit' as const } },
|
||||
...Object.keys(catalog)
|
||||
.sort()
|
||||
.map(name => ({
|
||||
title: name.split('.').map(actionLabel).join(' › '),
|
||||
description: name,
|
||||
value: { kind: 'action' as const, name },
|
||||
})),
|
||||
];
|
||||
signal.throwIfAborted();
|
||||
Log.gray(
|
||||
`${Object.keys(catalog).length} actions · Type to search · ↑/↓ to navigate · Enter to select · Ctrl-C to exit`
|
||||
);
|
||||
while (true) {
|
||||
signal.throwIfAborted();
|
||||
const choice = (await promptControlValueAsync(
|
||||
{
|
||||
type: 'autocomplete',
|
||||
message: 'Choose a simulator action',
|
||||
choices,
|
||||
limit: 8,
|
||||
suggest: (input: string) => {
|
||||
const words = input.toLowerCase().trim().split(/\s+/);
|
||||
return Promise.resolve(
|
||||
choices.filter(choice => {
|
||||
const description =
|
||||
choice.value.kind === 'action'
|
||||
? (catalog[choice.value.name].description ?? '')
|
||||
: '';
|
||||
const text = `${choice.title} ${choice.description} ${description}`.toLowerCase();
|
||||
return words.every(word => text.includes(word));
|
||||
})
|
||||
);
|
||||
},
|
||||
},
|
||||
signal
|
||||
)) as { kind: 'exit' } | { kind: 'action'; name: string };
|
||||
signal.throwIfAborted();
|
||||
if (!choice) {
|
||||
Log.error('Choose an action or Exit.');
|
||||
continue;
|
||||
}
|
||||
if (choice.kind === 'exit') {
|
||||
Log.gray('Simulator controls closed.');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Log.newLine();
|
||||
Log.log(chalk.bold(choice.name));
|
||||
if (catalog[choice.name].description) {
|
||||
Log.gray(catalog[choice.name].description);
|
||||
}
|
||||
await runActionAsync(
|
||||
await promptControlActionAsync(choice.name, catalog[choice.name], signal)
|
||||
);
|
||||
} catch (error) {
|
||||
signal.throwIfAborted();
|
||||
if (error instanceof ControlPromptCancelledError) {
|
||||
throw error;
|
||||
}
|
||||
Log.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
Log.newLine();
|
||||
}
|
||||
}
|
||||
|
||||
function actionLabel(value: string): string {
|
||||
const words = value
|
||||
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
||||
.replace(/[_-]/g, ' ')
|
||||
.toLowerCase();
|
||||
return words.charAt(0).toUpperCase() + words.slice(1);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { Question, promptAsync } from '../prompts';
|
||||
|
||||
export class ControlPromptCancelledError extends Error {
|
||||
constructor() {
|
||||
super('Simulator control interrupted.');
|
||||
this.name = 'ControlPromptCancelledError';
|
||||
}
|
||||
}
|
||||
|
||||
type ActivePrompt = { abort(): void; closed?: boolean; done?: boolean };
|
||||
|
||||
/** Unlike the default prompt cancellation, this unwinds through the connection's cleanup. */
|
||||
export async function promptControlValueAsync(
|
||||
question: Omit<Question<'value'>, 'name'>,
|
||||
signal: AbortSignal
|
||||
): Promise<unknown> {
|
||||
signal.throwIfAborted();
|
||||
let active: ActivePrompt | undefined;
|
||||
let abortQueued = false;
|
||||
const abort = (): void => {
|
||||
if (abortQueued) {
|
||||
return;
|
||||
}
|
||||
abortQueued = true;
|
||||
// The first render happens inside the prompt constructor, before its abort listener exists.
|
||||
queueMicrotask(() => {
|
||||
abortQueued = false;
|
||||
if (active && !active.closed && !active.done) {
|
||||
active.abort();
|
||||
}
|
||||
});
|
||||
};
|
||||
signal.addEventListener('abort', abort, { once: true });
|
||||
try {
|
||||
const result = await promptAsync(
|
||||
{
|
||||
...question,
|
||||
name: 'value',
|
||||
onRender(this: ActivePrompt, kleur) {
|
||||
active = this;
|
||||
question.onRender?.call(this, kleur);
|
||||
if (signal.aborted) {
|
||||
abort();
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
onCancel() {
|
||||
signal.throwIfAborted();
|
||||
throw new ControlPromptCancelledError();
|
||||
},
|
||||
}
|
||||
);
|
||||
signal.throwIfAborted();
|
||||
return result.value;
|
||||
} finally {
|
||||
signal.removeEventListener('abort', abort);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import { ExpoGraphqlClient } from '../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
import { DeviceRunSessionStatus, JobRunStatus } from '../graphql/generated';
|
||||
import { DeviceRunSessionQuery } from '../graphql/queries/DeviceRunSessionQuery';
|
||||
import Log from '../log';
|
||||
|
||||
export class ControlSessionEndedError extends Error {
|
||||
constructor(
|
||||
sessionId: string,
|
||||
readonly failed = false
|
||||
) {
|
||||
super(`Simulator session ${sessionId} ${failed ? 'errored' : 'has ended'}.`);
|
||||
this.name = 'ControlSessionEndedError';
|
||||
}
|
||||
}
|
||||
|
||||
/** Watches status without extending or stopping the remote session. */
|
||||
export function watchControlSession(
|
||||
graphqlClient: ExpoGraphqlClient,
|
||||
sessionId: string,
|
||||
{
|
||||
signal,
|
||||
pollIntervalMs = 5000,
|
||||
requestTimeoutMs = 30_000,
|
||||
}: { signal: AbortSignal; pollIntervalMs?: number; requestTimeoutMs?: number }
|
||||
): { signal: AbortSignal; dispose(): void } {
|
||||
const controller = new AbortController();
|
||||
let pollTimer: NodeJS.Timeout | undefined;
|
||||
let cancelRequest: (() => void) | undefined;
|
||||
|
||||
function stop(reason?: unknown): void {
|
||||
if (controller.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
clearTimeout(pollTimer);
|
||||
cancelRequest?.();
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
controller.abort(reason);
|
||||
}
|
||||
|
||||
function onAbort(): void {
|
||||
stop(signal.reason);
|
||||
}
|
||||
|
||||
function schedulePoll(): void {
|
||||
if (!controller.signal.aborted) {
|
||||
pollTimer = setTimeout(poll, pollIntervalMs);
|
||||
}
|
||||
}
|
||||
|
||||
function retry(error: unknown): void {
|
||||
Log.debug(`Could not check simulator session ${sessionId}:`, error);
|
||||
schedulePoll();
|
||||
}
|
||||
|
||||
function poll(): void {
|
||||
pollTimer = undefined;
|
||||
let subscription: { unsubscribe(): void } | undefined;
|
||||
let requestTimer: NodeJS.Timeout | undefined;
|
||||
let finished = false;
|
||||
|
||||
function finishRequest(): boolean {
|
||||
if (finished) {
|
||||
return false;
|
||||
}
|
||||
finished = true;
|
||||
clearTimeout(requestTimer);
|
||||
// urql tears down the operation and aborts the HTTP fetch on unsubscribe.
|
||||
subscription?.unsubscribe();
|
||||
cancelRequest = undefined;
|
||||
return true;
|
||||
}
|
||||
|
||||
cancelRequest = () => {
|
||||
finishRequest();
|
||||
};
|
||||
requestTimer = setTimeout(() => {
|
||||
if (finishRequest()) {
|
||||
retry(new Error('Session status request timed out.'));
|
||||
}
|
||||
}, requestTimeoutMs);
|
||||
|
||||
try {
|
||||
subscription = DeviceRunSessionQuery.byId(graphqlClient, sessionId, {
|
||||
requestPolicy: 'network-only',
|
||||
noRetry: true,
|
||||
}).subscribe(result => {
|
||||
if (result.stale || result.hasNext || !finishRequest()) {
|
||||
return;
|
||||
}
|
||||
const session = result.data?.deviceRunSessions?.byId;
|
||||
if (result.error || !session) {
|
||||
retry(result.error ?? new Error('Session status response was empty.'));
|
||||
return;
|
||||
}
|
||||
if (
|
||||
[DeviceRunSessionStatus.Stopped, DeviceRunSessionStatus.Errored].includes(
|
||||
session.status
|
||||
) ||
|
||||
(session.turtleJobRun &&
|
||||
[JobRunStatus.Canceled, JobRunStatus.Finished, JobRunStatus.Errored].includes(
|
||||
session.turtleJobRun.status
|
||||
))
|
||||
) {
|
||||
const failed =
|
||||
session.status === DeviceRunSessionStatus.Errored ||
|
||||
session.turtleJobRun?.status === JobRunStatus.Errored;
|
||||
stop(new ControlSessionEndedError(sessionId, failed));
|
||||
} else {
|
||||
schedulePoll();
|
||||
}
|
||||
});
|
||||
// A synchronous source may finish before subscribe returns its handle.
|
||||
if (finished) {
|
||||
subscription.unsubscribe();
|
||||
}
|
||||
} catch (error) {
|
||||
if (finishRequest()) {
|
||||
retry(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (signal.aborted) {
|
||||
stop(signal.reason);
|
||||
} else {
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
schedulePoll();
|
||||
}
|
||||
return { signal: controller.signal, dispose: stop };
|
||||
}
|
||||
@@ -14,6 +14,8 @@ export type HostActionResult = {
|
||||
};
|
||||
|
||||
export type HostActionConnection = {
|
||||
readonly signal: AbortSignal;
|
||||
readonly udid: string;
|
||||
requestAsync(action: string, params?: Record<string, unknown>): Promise<HostActionResult>;
|
||||
close(): void;
|
||||
};
|
||||
@@ -42,6 +44,8 @@ const Catalog = z.record(z.string(), CatalogEntry);
|
||||
export type HostActionCatalog = z.infer<typeof Catalog>;
|
||||
export type HostActionCatalogEntry = z.infer<typeof CatalogEntry>;
|
||||
|
||||
export type HostActionDevice = { udid: string; name?: string; runtime?: string };
|
||||
|
||||
const PreviewConfig = z.object({ device: z.string().min(1) });
|
||||
|
||||
const ReplyId = z.object({ id: z.number() });
|
||||
@@ -59,9 +63,11 @@ const SocketMessage = z.union([
|
||||
|
||||
const HOST_ACTION_TIMEOUT_MS = 130_000;
|
||||
const PREVIEW_API_TIMEOUT_MS = 30_000;
|
||||
const PREVIEW_UNAVAILABLE_MESSAGE =
|
||||
'The simulator preview server is unavailable. The session may have ended or expired. Check it with `eas simulator:get`, or start a new session with `eas simulator:start`.';
|
||||
const UPLOAD_CHUNK_BYTES = 2 * 1024 * 1024;
|
||||
const NAMED_VALUE = /^([A-Za-z][A-Za-z0-9]*)=(.*)$/s;
|
||||
const NUMBER = /^-?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i;
|
||||
export const NUMBER_PATTERN = /^-?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i;
|
||||
|
||||
function previewEndpoint(apiUrl: string, endpoint: string): URL {
|
||||
const base = new URL(apiUrl);
|
||||
@@ -82,16 +88,25 @@ function previewEndpoint(apiUrl: string, endpoint: string): URL {
|
||||
return new URL(endpoint, base);
|
||||
}
|
||||
|
||||
async function fetchSimulatorUdidAsync({ apiUrl, token }: PreviewApiAccess): Promise<string> {
|
||||
async function fetchSimulatorUdidAsync(
|
||||
{ apiUrl, token }: PreviewApiAccess,
|
||||
signal?: AbortSignal
|
||||
): Promise<string> {
|
||||
let text: string;
|
||||
try {
|
||||
const response = await fetch(previewEndpoint(apiUrl, 'api').toString(), {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(PREVIEW_API_TIMEOUT_MS),
|
||||
signal: signal
|
||||
? AbortSignal.any([signal, AbortSignal.timeout(PREVIEW_API_TIMEOUT_MS)])
|
||||
: AbortSignal.timeout(PREVIEW_API_TIMEOUT_MS),
|
||||
});
|
||||
text = await response.text();
|
||||
} catch (error) {
|
||||
signal?.throwIfAborted();
|
||||
if (error instanceof RequestError && error.response.status === 404) {
|
||||
throw new Error(PREVIEW_UNAVAILABLE_MESSAGE);
|
||||
}
|
||||
if (error instanceof RequestError && [401, 403].includes(error.response.status)) {
|
||||
throw new Error(
|
||||
`The simulator preview server refused the session token (HTTP ${error.response.status}). Run \`eas simulator:get\` to check that the session still runs, then try again.`
|
||||
@@ -117,6 +132,31 @@ async function fetchSimulatorUdidAsync({ apiUrl, token }: PreviewApiAccess): Pro
|
||||
return config.data.device;
|
||||
}
|
||||
|
||||
export async function fetchHostActionDeviceAsync(
|
||||
{ apiUrl, token }: PreviewApiAccess,
|
||||
udid: string
|
||||
): Promise<HostActionDevice> {
|
||||
const url = previewEndpoint(apiUrl, 'grid/api/catalog').toString();
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(PREVIEW_API_TIMEOUT_MS),
|
||||
});
|
||||
const catalog = z
|
||||
.object({
|
||||
devices: z.array(
|
||||
z.object({ device: z.string(), name: z.string(), runtime: z.string().optional() })
|
||||
),
|
||||
})
|
||||
.parse(await response.json());
|
||||
const device = catalog.devices.find(device => device.device === udid);
|
||||
return device ? { udid, name: device.name, runtime: device.runtime } : { udid };
|
||||
} catch {
|
||||
return { udid };
|
||||
}
|
||||
}
|
||||
|
||||
function refusedError(error: string): Error {
|
||||
return error.startsWith('unknown action')
|
||||
? new Error(
|
||||
@@ -127,9 +167,11 @@ function refusedError(error: string): Error {
|
||||
|
||||
export async function connectHostActionsAsync(
|
||||
access: PreviewApiAccess,
|
||||
{ timeoutMs = HOST_ACTION_TIMEOUT_MS }: { timeoutMs?: number } = {}
|
||||
{ timeoutMs = HOST_ACTION_TIMEOUT_MS, signal }: { timeoutMs?: number; signal?: AbortSignal } = {}
|
||||
): Promise<HostActionConnection> {
|
||||
const udid = await fetchSimulatorUdidAsync(access);
|
||||
signal?.throwIfAborted();
|
||||
const udid = await fetchSimulatorUdidAsync(access, signal);
|
||||
signal?.throwIfAborted();
|
||||
const socketUrl = previewEndpoint(access.apiUrl, 'exec-ws');
|
||||
socketUrl.protocol = socketUrl.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const ws = new WebSocket(
|
||||
@@ -144,6 +186,7 @@ export async function connectHostActionsAsync(
|
||||
timer: NodeJS.Timeout;
|
||||
};
|
||||
const pending = new Map<number, Pending>();
|
||||
const controller = new AbortController();
|
||||
let nextId = 1;
|
||||
let lost: Error | null = null;
|
||||
let ready = false;
|
||||
@@ -158,30 +201,39 @@ export async function connectHostActionsAsync(
|
||||
}
|
||||
|
||||
function loseConnection(error: Error): void {
|
||||
lost ??= error;
|
||||
if (lost) {
|
||||
return;
|
||||
}
|
||||
lost = error;
|
||||
controller.abort(error);
|
||||
for (const id of [...pending.keys()]) {
|
||||
settle(id)?.reject(error);
|
||||
}
|
||||
ws.terminate();
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
reject(
|
||||
fail(
|
||||
new Error(
|
||||
`The simulator preview server did not accept the connection within ${PREVIEW_API_TIMEOUT_MS / 1000} seconds. Check that the session still runs with \`eas simulator:get\`, then try again.`
|
||||
)
|
||||
);
|
||||
ws.terminate();
|
||||
}, PREVIEW_API_TIMEOUT_MS);
|
||||
const fail = (error: Error): void => {
|
||||
clearTimeout(timer);
|
||||
reject(error);
|
||||
loseConnection(error);
|
||||
if (!ready) {
|
||||
ws.terminate();
|
||||
}
|
||||
};
|
||||
|
||||
const onAbort = (): void => {
|
||||
fail(
|
||||
signal?.reason instanceof Error ? signal.reason : new Error('Simulator setup canceled.')
|
||||
);
|
||||
};
|
||||
signal?.addEventListener('abort', onAbort, { once: true });
|
||||
ws.once('close', () => signal?.removeEventListener('abort', onAbort));
|
||||
|
||||
ws.on('message', data => {
|
||||
let message: unknown;
|
||||
try {
|
||||
@@ -220,7 +272,9 @@ export async function connectHostActionsAsync(
|
||||
res.destroy();
|
||||
fail(
|
||||
new Error(
|
||||
`The simulator preview server refused the connection (HTTP ${res.statusCode}). The session token may be out of date. Run \`eas simulator:get\` to check the session, then try again.`
|
||||
res.statusCode === 404
|
||||
? PREVIEW_UNAVAILABLE_MESSAGE
|
||||
: `The simulator preview server refused the connection (HTTP ${res.statusCode}). The session token may be out of date. Run \`eas simulator:get\` to check the session, then try again.`
|
||||
)
|
||||
);
|
||||
});
|
||||
@@ -240,28 +294,42 @@ export async function connectHostActionsAsync(
|
||||
)
|
||||
);
|
||||
});
|
||||
if (signal?.aborted) {
|
||||
onAbort();
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
signal: controller.signal,
|
||||
udid,
|
||||
async requestAsync(action, params = {}) {
|
||||
if (lost) {
|
||||
throw lost;
|
||||
}
|
||||
const id = nextId++;
|
||||
const message = JSON.stringify({ id, action, params: { ...params, udid } });
|
||||
return await new Promise<HostActionResult>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
settle(id)?.reject(
|
||||
loseConnection(
|
||||
new Error(
|
||||
`The simulator did not answer within ${Math.round(timeoutMs / 1000)} seconds. The action may still have run. Check the session with \`eas simulator:get\` and the current state before you try again.`
|
||||
)
|
||||
);
|
||||
}, timeoutMs);
|
||||
pending.set(id, { resolve, reject, timer });
|
||||
ws.send(JSON.stringify({ id, action, params: { ...params, udid } }));
|
||||
try {
|
||||
ws.send(message, error => {
|
||||
if (error) {
|
||||
loseConnection(error);
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
loseConnection(error instanceof Error ? error : new Error(String(error)));
|
||||
}
|
||||
});
|
||||
},
|
||||
close() {
|
||||
ws.close();
|
||||
loseConnection(new Error('The simulator action connection was closed.'));
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -350,7 +418,10 @@ function coerce(value: string, schemas: unknown[]): unknown {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
if (NUMBER.test(value) && schemas.some(schema => acceptsType(schema, ['number', 'integer']))) {
|
||||
if (
|
||||
NUMBER_PATTERN.test(value) &&
|
||||
schemas.some(schema => acceptsType(schema, ['number', 'integer']))
|
||||
) {
|
||||
return Number(value);
|
||||
}
|
||||
if (
|
||||
@@ -447,12 +518,16 @@ export async function assertHostActionOutputAsync(
|
||||
}
|
||||
}
|
||||
|
||||
export function createHostActionUploadId(localPath: string): string {
|
||||
return `eas-cli-${randomUUID()}${path.extname(localPath).replace(/[^A-Za-z0-9.]/g, '')}`;
|
||||
}
|
||||
|
||||
export async function uploadFileAsync(
|
||||
connection: HostActionConnection,
|
||||
localPath: string,
|
||||
{ chunkBytes = UPLOAD_CHUNK_BYTES }: { chunkBytes?: number } = {}
|
||||
): Promise<{ uploadId: string; path: string }> {
|
||||
const uploadId = `eas-cli-${randomUUID()}${path.extname(localPath).replace(/[^A-Za-z0-9.]/g, '')}`;
|
||||
const uploadId = createHostActionUploadId(localPath);
|
||||
let remotePath = '';
|
||||
let first = true;
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import * as fs from 'fs-extra';
|
||||
import path from 'path';
|
||||
import { z } from 'zod';
|
||||
|
||||
const Action = z.strictObject({
|
||||
action: z.string().min(1),
|
||||
params: z.record(z.string(), z.json()).default({}),
|
||||
file: z.string().min(1).optional(),
|
||||
output: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
const Config = z.strictObject({
|
||||
version: z.literal(1),
|
||||
start: z.record(z.string(), z.json()).optional(),
|
||||
actions: z.array(Action).min(1).optional(),
|
||||
});
|
||||
|
||||
export type SimulatorSessionConfig = z.infer<typeof Config> & { path: string };
|
||||
|
||||
export async function readSimulatorSessionConfigAsync(
|
||||
filePath: string
|
||||
): Promise<SimulatorSessionConfig> {
|
||||
const absolutePath = path.resolve(filePath);
|
||||
let input: unknown;
|
||||
try {
|
||||
input = await fs.readJson(absolutePath);
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Could not read simulator configuration ${absolutePath}: ${error instanceof Error ? error.message : String(error)}`,
|
||||
{ cause: error }
|
||||
);
|
||||
}
|
||||
const parsed = Config.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
const detail = parsed.error.issues
|
||||
.map(issue => `${issue.path.join('.')}: ${issue.message}`)
|
||||
.join('; ');
|
||||
throw new Error(`Invalid simulator configuration ${absolutePath}: ${detail}`);
|
||||
}
|
||||
return { ...parsed.data, path: absolutePath };
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { Interfaces, Parser } from '@oclif/core';
|
||||
|
||||
import { preflightControlConfigFilesAsync } from './controlConfig';
|
||||
import { SimulatorSessionConfig, readSimulatorSessionConfigAsync } from './sessionConfig';
|
||||
|
||||
/** Reparse the effective values using the command's own validation, options and defaults. */
|
||||
export async function resolveStartConfigAsync(
|
||||
argv: string[],
|
||||
definitions: Interfaces.FlagInput
|
||||
): Promise<{ argv: string[]; config?: SimulatorSessionConfig }> {
|
||||
if (!argv.some(arg => arg === '--import' || arg.startsWith('--import='))) {
|
||||
return { argv };
|
||||
}
|
||||
// Relationships are checked after file values and explicit CLI overrides are combined.
|
||||
const relaxed = Object.fromEntries(
|
||||
Object.entries(definitions).map(([name, flag]) => [
|
||||
name,
|
||||
{
|
||||
...flag,
|
||||
dependsOn: undefined,
|
||||
exclusive: undefined,
|
||||
exactlyOne: undefined,
|
||||
atLeastOne: undefined,
|
||||
relationships: undefined,
|
||||
required: false,
|
||||
},
|
||||
])
|
||||
);
|
||||
const parsed = await Parser.parse(argv, { flags: relaxed });
|
||||
if (parsed.flags.import === undefined) {
|
||||
return { argv };
|
||||
}
|
||||
if (!parsed.flags.import.trim()) {
|
||||
throw new Error('--import requires a non-empty configuration file path.');
|
||||
}
|
||||
const config = await readSimulatorSessionConfigAsync(parsed.flags.import);
|
||||
const values: Record<string, unknown> = { ...config.start };
|
||||
for (const key of Object.keys(values)) {
|
||||
if (!Object.hasOwn(definitions, key) || ['import', 'json', 'non-interactive'].includes(key)) {
|
||||
throw new Error(`Unknown or invocation-only start setting "${key}" in ${config.path}.`);
|
||||
}
|
||||
}
|
||||
const explicit = Object.entries(parsed.flags).filter(
|
||||
([name, value]) => value !== undefined && !parsed.metadata.flags[name]?.setFromDefault
|
||||
);
|
||||
const explicitNames = new Set(explicit.map(([name]) => name));
|
||||
const removed = new Set<string>();
|
||||
for (const [name, value] of explicit) {
|
||||
for (const excluded of definitions[name].exclusive ?? []) {
|
||||
if (!explicitNames.has(excluded)) {
|
||||
delete values[excluded];
|
||||
removed.add(excluded);
|
||||
}
|
||||
}
|
||||
values[name] = value;
|
||||
}
|
||||
// SDK selection belongs to the saved Expo Go app source, not a replacement build.
|
||||
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'];
|
||||
}
|
||||
const effectiveArgv: string[] = [];
|
||||
for (const [name, value] of Object.entries(values)) {
|
||||
const flag = definitions[name];
|
||||
if (flag.type === 'boolean') {
|
||||
if (typeof value !== 'boolean') {
|
||||
throw new Error(`Start setting "${name}" must be a boolean.`);
|
||||
}
|
||||
if (value) {
|
||||
effectiveArgv.push(`--${name}`);
|
||||
} else if (flag.allowNo) {
|
||||
effectiveArgv.push(`--no-${name}`);
|
||||
}
|
||||
} else {
|
||||
const items = Array.isArray(value) ? value : [value];
|
||||
if (Array.isArray(value) && !flag.multiple) {
|
||||
throw new Error(`Start setting "${name}" does not accept multiple values.`);
|
||||
}
|
||||
for (const item of items) {
|
||||
if (typeof item !== 'string' && typeof item !== 'number') {
|
||||
throw new Error(`Start setting "${name}" must contain a string or number.`);
|
||||
}
|
||||
effectiveArgv.push(`--${name}=${item}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
await preflightControlConfigFilesAsync(config);
|
||||
return { argv: effectiveArgv, config };
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import {
|
||||
ControlConfigProgress,
|
||||
ControlConfigResult,
|
||||
executeControlConfigAsync,
|
||||
prepareControlConfigAsync,
|
||||
} from './controlConfig';
|
||||
import { connectHostActionsAsync, fetchHostActionCatalogAsync } from './hostActions';
|
||||
import { SimulatorSessionConfig } from './sessionConfig';
|
||||
import { PreviewApiAccess } from './utils';
|
||||
|
||||
export async function applyStartConfigAsync(
|
||||
access: PreviewApiAccess,
|
||||
config: SimulatorSessionConfig,
|
||||
{
|
||||
signal,
|
||||
onProgress,
|
||||
}: { signal: AbortSignal; onProgress?: (progress: ControlConfigProgress) => void }
|
||||
): Promise<ControlConfigResult[]> {
|
||||
const connection = await connectHostActionsAsync(access, { signal });
|
||||
try {
|
||||
const catalog = await fetchHostActionCatalogAsync(connection);
|
||||
const prepared = await prepareControlConfigAsync(catalog, config.path, connection.udid, config);
|
||||
signal.throwIfAborted();
|
||||
return await executeControlConfigAsync(connection, prepared, { onProgress });
|
||||
} finally {
|
||||
connection.close();
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,5 @@
|
||||
# @expo/eas-json
|
||||
|
||||
## 27.3.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.2.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.1.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/eas-json",
|
||||
"version": "27.3.0",
|
||||
"version": "27.1.0",
|
||||
"description": "A library for interacting with eas.json",
|
||||
"homepage": "https://github.com/expo/eas-cli",
|
||||
"bugs": "https://github.com/expo/eas-cli/issues",
|
||||
@@ -32,7 +32,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "7.23.5",
|
||||
"@expo/eas-build-job": "27.3.0",
|
||||
"@expo/eas-build-job": "27.1.0",
|
||||
"chalk": "4.1.2",
|
||||
"env-string": "1.0.1",
|
||||
"fs-extra": "11.2.0",
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
# eas-cli-local-build-plugin
|
||||
|
||||
## 27.3.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.2.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.1.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "eas-cli-local-build-plugin",
|
||||
"version": "27.3.0",
|
||||
"version": "27.1.0",
|
||||
"description": "Tool for running EAS compatible builds on a local machine.",
|
||||
"bugs": "https://github.com/expo/eas-cli/issues",
|
||||
"license": "BUSL-1.1",
|
||||
@@ -26,12 +26,12 @@
|
||||
"clean": "rimraf node_modules dist coverage \"*.tsbuildinfo\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@expo/build-tools": "27.3.0",
|
||||
"@expo/build-tools": "27.1.0",
|
||||
"@expo/bunyan": "^4.0.1",
|
||||
"@expo/eas-build-job": "27.3.0",
|
||||
"@expo/logger": "27.3.0",
|
||||
"@expo/eas-build-job": "27.1.0",
|
||||
"@expo/logger": "27.1.0",
|
||||
"@expo/spawn-async": "^1.7.2",
|
||||
"@expo/turtle-spawn": "27.3.0",
|
||||
"@expo/turtle-spawn": "27.1.0",
|
||||
"chalk": "4.1.2",
|
||||
"env-paths": "^2.2.1",
|
||||
"fs-extra": "^11.2.0",
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
# @expo/logger
|
||||
|
||||
## 27.3.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.2.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.1.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/logger",
|
||||
"version": "27.3.0",
|
||||
"version": "27.1.0",
|
||||
"bugs": "https://github.com/expo/eas-cli/issues",
|
||||
"license": "BUSL-1.1",
|
||||
"author": "Expo <[email protected]>",
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
# @expo/simulator-launcher
|
||||
|
||||
## 27.3.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.2.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- Accept a comma-separated list of warm Simulators in `EXPO_SIMULATOR_DEVICE`; the first is the default. One serve-sim serves every listed device on one port. After the default device is ready, warmup preinstalls the latest stable Expo Go from one download and tries to disable apsd on the other devices, until a job claims one. A claim can select any listed device and reports its preinstalled Expo Go. ([#4764](https://github.com/expo/eas-cli/pull/4764) by [@gwdp](https://github.com/gwdp))
|
||||
- Add `@expo/simulator-launcher`, which warms an iOS Simulator at VM boot and hands it to one EAS job (`start`, `claim`, `prepare-tools`, `stop`). ([#4722](https://github.com/expo/eas-cli/pull/4722) by [@gwdp](https://github.com/gwdp))
|
||||
@@ -1,80 +0,0 @@
|
||||
# @expo/simulator-launcher
|
||||
|
||||
Warm iOS Simulators before an EAS job arrives. Requires macOS.
|
||||
The image installs vm-tools and writes its startup script at
|
||||
`/usr/local/share/vm-tools/startup.sh`:
|
||||
|
||||
```sh
|
||||
export EXPO_SIMULATOR_STARTUP=1
|
||||
export EXPO_SIMULATOR_DEVICE="iPhone Duo,iPhone 18"
|
||||
exec bunx @expo/simulator-launcher@latest start
|
||||
```
|
||||
|
||||
## Commands
|
||||
|
||||
- `start`: run one orphan serve-sim for the configured devices. Its default device becomes ready
|
||||
first; additional devices warm in the background. Argent and agent-device prestart on the default.
|
||||
- `claim ENGINE [DEVICE]`: reserve one job and return its selected device plus the existing server's
|
||||
identity, port and credentials. Engines: `serve-sim`, `agent-device`, `argent`.
|
||||
No DEVICE means the first configured device. Claim does not boot the selected device or wait for
|
||||
its tool. Build-tools privately adopts that device on the existing serve-sim port.
|
||||
- `prepare-tools`: continue the consumed claim after adoption. Keep global Argent, reuse the default
|
||||
agent-device runner or prepare a runner for the selected device.
|
||||
- `stop`: permanently end warmup for this boot and wait for all owned resources to be cleaned up.
|
||||
|
||||
```sh
|
||||
# Build-tools reads LAUNCHER_VERSION from the version recorded by start.
|
||||
bun x --no-install "@expo/simulator-launcher@$LAUNCHER_VERSION" claim serve-sim
|
||||
# After private serve-sim adoption confirms the selected device and native ACK:
|
||||
bun x --no-install "@expo/simulator-launcher@$LAUNCHER_VERSION" prepare-tools
|
||||
bun x --no-install "@expo/simulator-launcher@$LAUNCHER_VERSION" stop
|
||||
```
|
||||
|
||||
There is no copied launcher bundle. Build-tools uses the recorded package version for claim/stop;
|
||||
Warmup primes Bun’s exact-version cache before ready, with two attempts of up to 30 seconds. Its claim/stop calls use `--no-install`, retrying
|
||||
once with the registry only when Bun cannot find that cached binary. Priming failures warn.
|
||||
Before start has run,
|
||||
stop uses the normal package-manager path and still disables later warmup for this boot.
|
||||
|
||||
This flow requires the serve-sim release supporting port-based device adoption.
|
||||
|
||||
One durable state file, `/tmp/expo-simulator-startup.json`, holds the lifecycle, launcher version,
|
||||
selected device, server credentials, claim and native identity. It is independent of HOME/TMPDIR. A short boot-scoped lock
|
||||
serializes updates; an abandoned lock fails closed. This private format requires a fresh VM.
|
||||
|
||||
## Environment
|
||||
|
||||
- `EXPO_SIMULATOR_STARTUP=1` enables warmup.
|
||||
- `EXPO_SIMULATOR_PREINSTALL_EXPO_GO=0` turns off the Expo Go preinstall.
|
||||
- `EXPO_SIMULATOR_DEVICE` is a comma-separated list of exact device names or UDIDs. Entries are
|
||||
trimmed and must each identify one available device. The first is the default. Unset keeps
|
||||
the shortest available iPhone name, as does an empty or blank value. Empty list entries, missing,
|
||||
ambiguous or duplicate devices fail clearly.
|
||||
- `SERVE_SIM_VERSION`, `AGENT_DEVICE_VERSION`, `ARGENT_VERSION`: each defaults to `latest`.
|
||||
- `AGENT_DEVICE_STATE_DIR`, `ARGENT_EVENT_LOG`: tool state/output locations.
|
||||
- Agent-device idle timers default to off. Override with `AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS`
|
||||
and `AGENT_DEVICE_IOS_RUNNER_IDLE_STOP_MS` (milliseconds).
|
||||
|
||||
## Boundaries
|
||||
|
||||
- Ready means the default device booted and serve-sim answers. The apsd step and the Expo Go
|
||||
preinstall run in the background on every listed device. A claim does not wait for them; stop
|
||||
joins them.
|
||||
The second device may not have started yet. Its startup failure leaves the default available.
|
||||
Claim reserves a device; it does not report that device ready. Private adoption must confirm
|
||||
the same server PID/port, selected-device readiness and native video/capture before tool setup
|
||||
and app actions. Job-time version and authentication checks remain authoritative.
|
||||
- Agent-device prestarts on the default device only. A secondary claim prepares its runner after
|
||||
adoption and old-runner cleanup finish. One device-independent Argent server is reused for the claimed device.
|
||||
- Warmup downloads/extracts the latest stable Expo Go once and reuses it for the second device.
|
||||
Each initial device gets a preinstall attempt; ordinary failures warn. Claim prevents new
|
||||
preinstalls. `prepare-tools` waits for an install still running on the claimed device and
|
||||
reports its version, because the job installs its app next. Installs on other devices continue;
|
||||
adoption may shut such a device down, and its install then fails with a warning. Terminal stop
|
||||
drains them and the download cleanup. Job app installs remain
|
||||
authoritative. Replacements do not preinstall again. The VM image provides ffmpeg.
|
||||
- One start attempt and one accepted claim per boot. Failed cleanup never permits another session.
|
||||
Stop's caller timeout is not a global cleanup deadline or proof that teardown completed.
|
||||
A build-tools claim timeout uses normal startup only after confirmed terminal cleanup.
|
||||
|
||||
Claim and tool JSON include credentials; capture them rather than streaming them to job logs.
|
||||
@@ -1,2 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
require('../dist/index').runCliAsync();
|
||||
@@ -1,13 +0,0 @@
|
||||
import type { Config } from '@jest/types';
|
||||
|
||||
import baseConfig from '../../jest/jest.shared.config';
|
||||
|
||||
const config: Config.InitialOptions = {
|
||||
...baseConfig,
|
||||
rootDir: 'src',
|
||||
testMatch: ['**/__tests__/*.test.ts'],
|
||||
setupFiles: ['<rootDir>/__tests__/fixturePids.ts'],
|
||||
clearMocks: true,
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -1,37 +0,0 @@
|
||||
{
|
||||
"name": "@expo/simulator-launcher",
|
||||
"version": "27.3.0",
|
||||
"description": "Launch and claim Simulator sessions on EAS workers",
|
||||
"bugs": "https://github.com/expo/eas-cli/issues",
|
||||
"license": "BUSL-1.1",
|
||||
"author": "Expo <[email protected]>",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/expo/eas-cli.git",
|
||||
"directory": "packages/simulator-launcher"
|
||||
},
|
||||
"bin": "bin/simulator-launcher",
|
||||
"files": [
|
||||
"bin",
|
||||
"dist/index.js"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "jest --config jest.config.ts",
|
||||
"build": "ncc build src/main.ts -o dist --no-cache --no-source-map-register",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"prepack": "yarn build",
|
||||
"rebuild": "yarn build"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.12",
|
||||
"@types/node": "22.20.5",
|
||||
"@vercel/ncc": "^0.38.1",
|
||||
"jest": "^29.7.0",
|
||||
"ts-jest": "^29.4.12",
|
||||
"typescript": "^6.0.3",
|
||||
"zod": "^4.3.5"
|
||||
}
|
||||
}
|
||||
@@ -1,190 +0,0 @@
|
||||
import { type ChildProcess } from 'node:child_process';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import fs from 'node:fs/promises';
|
||||
|
||||
import { createArgentTool } from '../utils/argent';
|
||||
import {
|
||||
commands,
|
||||
isProcessOwnedByServiceAsync,
|
||||
stopProcessAndDescendantsAsync,
|
||||
} from '../utils/processes';
|
||||
import { type WarmTool } from '../utils/tools';
|
||||
import { deferred, until } from './helpers';
|
||||
|
||||
jest.mock('node:fs/promises');
|
||||
jest.mock('../utils/processes');
|
||||
let child: ChildProcess;
|
||||
let result: ReturnType<typeof deferred<string>>;
|
||||
let controller: AbortController;
|
||||
let onFailure: jest.Mock;
|
||||
let tool: WarmTool;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
child = Object.assign(new EventEmitter(), {
|
||||
pid: 90001,
|
||||
exitCode: null,
|
||||
signalCode: null,
|
||||
}) as ChildProcess;
|
||||
result = deferred<string>();
|
||||
void result.promise.catch(() => {});
|
||||
controller = new AbortController();
|
||||
onFailure = jest.fn();
|
||||
// The old factory ignores this callback; its start also resolves without readiness.
|
||||
const createTool: (onFailure: (error: unknown) => void) => WarmTool = createArgentTool;
|
||||
tool = createTool(onFailure);
|
||||
jest.mocked(commands.start).mockReturnValue({ child, resultPromise: result.promise });
|
||||
jest.mocked(isProcessOwnedByServiceAsync).mockResolvedValue(true);
|
||||
jest.mocked(fs.readdir).mockResolvedValue(['tool-server.json'] as never);
|
||||
jest
|
||||
.mocked(fs.readFile)
|
||||
.mockResolvedValue(JSON.stringify({ pid: 90001, port: 3201, token: 'fixture-token' }));
|
||||
jest.spyOn(global, 'fetch').mockResolvedValue(new Response(JSON.stringify({ tools: [] })));
|
||||
jest.mocked(stopProcessAndDescendantsAsync).mockResolvedValue();
|
||||
});
|
||||
afterEach(() => {
|
||||
controller.abort();
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('does not report ready until its owned server answers the authenticated tools request', async () => {
|
||||
const response = deferred<Response>();
|
||||
jest.mocked(fetch).mockReturnValue(response.promise);
|
||||
let ready = false;
|
||||
const started = tool.startAsync('PHONE', controller.signal).then(() => {
|
||||
ready = true;
|
||||
});
|
||||
await until(() => jest.mocked(fetch).mock.calls.length > 0 || ready);
|
||||
expect(ready).toBe(false);
|
||||
response.resolve(new Response(JSON.stringify({ tools: [] })));
|
||||
await started;
|
||||
expect(commands.start).toHaveBeenCalledWith('bunx', expect.arrayContaining(['server', 'start']), {
|
||||
detached: true,
|
||||
});
|
||||
expect(fetch).toHaveBeenCalledWith('http://127.0.0.1:3201/tools', {
|
||||
headers: { Authorization: 'Bearer fixture-token' },
|
||||
signal: expect.any(AbortSignal),
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects an exit during the readiness request, even before the wrapper finishes closing', async () => {
|
||||
const response = deferred<Response>();
|
||||
jest.mocked(fetch).mockReturnValue(response.promise);
|
||||
const started = tool.startAsync('PHONE', controller.signal);
|
||||
await until(() => jest.mocked(fetch).mock.calls.length > 0);
|
||||
Object.assign(child, { exitCode: 1 });
|
||||
child.emit('exit', 1, null);
|
||||
response.resolve(new Response(JSON.stringify({ tools: [] })));
|
||||
await expect(started).rejects.toThrow('Argent exited before its server became ready');
|
||||
expect(onFailure).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('observes an unexpected exit after readiness exactly once', async () => {
|
||||
await tool.startAsync('PHONE', controller.signal);
|
||||
child.emit('exit', 1, null);
|
||||
result.reject(new Error('wrapper failed'));
|
||||
await Promise.resolve();
|
||||
expect(onFailure).toHaveBeenCalledTimes(1);
|
||||
expect(onFailure.mock.calls[0][0].message).toContain('Argent server exited unexpectedly');
|
||||
});
|
||||
|
||||
it('ignores a foreign state file without sending its token to the local port', async () => {
|
||||
jest.mocked(isProcessOwnedByServiceAsync).mockResolvedValue(false);
|
||||
const started = tool.startAsync('PHONE', controller.signal).catch(error => error);
|
||||
await until(() => jest.mocked(isProcessOwnedByServiceAsync).mock.calls.length > 0);
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
controller.abort(new Error('cancelled'));
|
||||
expect((await started).code).toBe('ABORT_ERR');
|
||||
});
|
||||
|
||||
it('retries an invalid tools response and does not notify for intentional stop', async () => {
|
||||
jest
|
||||
.mocked(fetch)
|
||||
.mockResolvedValueOnce(new Response('{}'))
|
||||
.mockImplementation(async () => new Response(JSON.stringify({ tools: [] })));
|
||||
await tool.startAsync('PHONE', controller.signal);
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
jest.mocked(stopProcessAndDescendantsAsync).mockImplementation(async () => {
|
||||
child.emit('exit', 0, null);
|
||||
});
|
||||
await tool.stopAsync();
|
||||
expect(onFailure).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not notify for cancelled tool teardown', async () => {
|
||||
await tool.startAsync('PHONE', controller.signal);
|
||||
controller.abort();
|
||||
child.emit('exit', 0, null);
|
||||
expect(onFailure).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('never publishes ready when cancellation arrives during the tools request', async () => {
|
||||
const response = deferred<Response>();
|
||||
jest.mocked(fetch).mockReturnValue(response.promise);
|
||||
const started = tool.startAsync('PHONE', controller.signal);
|
||||
await until(() => jest.mocked(fetch).mock.calls.length > 0);
|
||||
controller.abort(new Error('cancelled'));
|
||||
response.resolve(new Response(JSON.stringify({ tools: [] })));
|
||||
await expect(started).rejects.toThrow('cancelled');
|
||||
expect(onFailure).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('bounds readiness when the server never becomes available', async () => {
|
||||
const now = Date.now();
|
||||
jest
|
||||
.spyOn(Date, 'now')
|
||||
.mockReturnValueOnce(now)
|
||||
.mockReturnValue(now + 120_000);
|
||||
await expect(tool.startAsync('PHONE', controller.signal)).rejects.toThrow(
|
||||
'Timed out waiting for the Argent server'
|
||||
);
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('retries missing or incomplete state and transient HTTP failures before becoming ready', async () => {
|
||||
jest
|
||||
.mocked(fs.readdir)
|
||||
.mockRejectedValueOnce(
|
||||
Object.assign(new Error('state directory not written yet'), { code: 'ENOENT' })
|
||||
)
|
||||
.mockResolvedValue(['events.jsonl', 'tool-server-old.json', 'tool-server.json'] as never);
|
||||
jest
|
||||
.mocked(fs.readFile)
|
||||
.mockRejectedValueOnce(new Error('state disappeared during startup'))
|
||||
.mockResolvedValue(JSON.stringify({ pid: 90001, port: 3201, token: 'fixture-token' }));
|
||||
jest
|
||||
.mocked(fetch)
|
||||
.mockRejectedValueOnce(new Error('connection refused'))
|
||||
.mockResolvedValueOnce(new Response('unauthorized', { status: 401 }))
|
||||
.mockImplementation(async () => new Response(JSON.stringify({ tools: [] })));
|
||||
await tool.startAsync('PHONE', controller.signal);
|
||||
expect(fs.readdir).toHaveBeenCalledTimes(3);
|
||||
expect(fetch).toHaveBeenCalledTimes(3);
|
||||
expect(onFailure).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a successful wrapper exit while no state directory is available', async () => {
|
||||
jest.mocked(fs.readdir).mockImplementation(async () => {
|
||||
result.resolve('');
|
||||
throw new Error('state directory unavailable');
|
||||
});
|
||||
await expect(tool.startAsync('PHONE', controller.signal)).rejects.toThrow(
|
||||
'Argent exited before its server became ready'
|
||||
);
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(onFailure).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects an exit during the final ownership check before publishing readiness', async () => {
|
||||
const owned = deferred<boolean>();
|
||||
jest
|
||||
.mocked(isProcessOwnedByServiceAsync)
|
||||
.mockResolvedValueOnce(true)
|
||||
.mockReturnValue(owned.promise);
|
||||
const started = tool.startAsync('PHONE', controller.signal);
|
||||
await until(() => jest.mocked(isProcessOwnedByServiceAsync).mock.calls.length === 2);
|
||||
child.emit('error', new Error('server failed during validation'));
|
||||
owned.resolve(true);
|
||||
await expect(started).rejects.toThrow('Argent exited before its server became ready');
|
||||
expect(onFailure).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -1,87 +0,0 @@
|
||||
import { commands } from '../utils/processes';
|
||||
import { startOwnedWrapperAsync } from './fixtures/ownedWrapper';
|
||||
|
||||
it('an early claim survives unused-tool wrapper exit while the selected server and Simulator stay owned', async () => {
|
||||
const fixture = await startOwnedWrapperAsync();
|
||||
const environment = { ...process.env };
|
||||
let session:
|
||||
| ReturnType<typeof import('../commands/start').createWarmSimulatorSession>
|
||||
| undefined;
|
||||
try {
|
||||
const { createWarmSimulatorSession } = await import('../commands/start');
|
||||
const simulator = await import('../utils/simulator');
|
||||
const serveSim = await import('../utils/serveSim');
|
||||
const processes = await import('../utils/processes');
|
||||
const agentDevice = await import('../utils/agentDevice');
|
||||
const argent = await import('../utils/argent');
|
||||
const expoGo = await import('../utils/expoGo');
|
||||
const controller = new AbortController();
|
||||
const running = commands.runAsync.bind(commands);
|
||||
process.env.EXPO_SIMULATOR_DEVICE = 'DUO';
|
||||
process.env.AGENT_DEVICE_STATE_DIR = '/owned-wrapper-fixture/agent';
|
||||
process.env.ARGENT_EVENT_LOG = '/owned-wrapper-fixture/argent-events';
|
||||
jest
|
||||
.spyOn(commands, 'runAsync')
|
||||
.mockImplementation((file, args, signal) =>
|
||||
file === 'bun' || (file === 'ps' && args[1] === String(process.pid))
|
||||
? Promise.resolve('controller-start')
|
||||
: running(file, args, signal)
|
||||
);
|
||||
jest
|
||||
.spyOn(simulator, 'listAvailableSimulatorsAsync')
|
||||
.mockResolvedValue([{ udid: 'DUO', name: 'iPhone Duo' }]);
|
||||
jest.spyOn(simulator, 'waitForSimulatorBootAsync').mockResolvedValue();
|
||||
jest.spyOn(simulator, 'disableApsdAsync').mockResolvedValue();
|
||||
const shutdown = jest.spyOn(simulator, 'shutdownSimulatorAsync').mockResolvedValue();
|
||||
const stopServer = jest.spyOn(processes, 'stopProcessAndDescendantsAsync').mockResolvedValue();
|
||||
jest.spyOn(agentDevice, 'createAgentDeviceTool').mockReturnValue({
|
||||
name: 'agent-device',
|
||||
startAsync: async () => {},
|
||||
stopAsync: fixture.stopAsync,
|
||||
});
|
||||
jest
|
||||
.spyOn(argent, 'createArgentTool')
|
||||
.mockReturnValue({ name: 'argent', startAsync: async () => {}, stopAsync: async () => {} });
|
||||
jest.spyOn(expoGo, 'startExpoGoPreinstall').mockReturnValue({
|
||||
preinstallOnDeviceAsync: async () => {},
|
||||
claimAsync: async () => undefined,
|
||||
stopAsync: async () => {},
|
||||
});
|
||||
jest.spyOn(serveSim, 'startServeSim').mockReturnValue({
|
||||
child: { pid: 90001 } as import('node:child_process').ChildProcess,
|
||||
resultPromise: new Promise(() => {}),
|
||||
});
|
||||
jest.spyOn(serveSim, 'waitForServeSimReadyAsync').mockResolvedValue({
|
||||
startupDevice: 'DUO',
|
||||
pid: 90001,
|
||||
nativeStartTime: 'fixture-start',
|
||||
port: 3200,
|
||||
url: 'http://127.0.0.1:3200',
|
||||
token: 'fixture-token',
|
||||
});
|
||||
const onFailure = jest.fn(error => controller.abort(error));
|
||||
session = createWarmSimulatorSession({
|
||||
signal: controller.signal,
|
||||
throwIfStoppingAsync: async () => controller.signal.throwIfAborted(),
|
||||
onPreparationFailure: onFailure,
|
||||
});
|
||||
await session.prepareAsync();
|
||||
expect(await session.claimAsync({ engine: 'serve-sim' })).toMatchObject({
|
||||
device: { udid: 'DUO' },
|
||||
});
|
||||
await session.prepareToolsAsync();
|
||||
await fixture.stopAsync();
|
||||
expect(fixture.job.child.exitCode).toBe(23);
|
||||
expect(onFailure).not.toHaveBeenCalled();
|
||||
expect(controller.signal.aborted).toBe(false);
|
||||
expect(stopServer).not.toHaveBeenCalled();
|
||||
expect(shutdown).not.toHaveBeenCalled();
|
||||
await session.stopAsync();
|
||||
expect(shutdown).toHaveBeenCalledWith('DUO');
|
||||
} finally {
|
||||
await session?.stopAsync().catch(() => {});
|
||||
jest.restoreAllMocks();
|
||||
process.env = environment;
|
||||
await fixture.cleanupAsync();
|
||||
}
|
||||
}, 10_000);
|
||||
@@ -1,636 +0,0 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import { gzipSync } from 'node:zlib';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { startExpoGoPreinstall } from '../utils/expoGo';
|
||||
import { commands } from '../utils/processes';
|
||||
import { deferred, until } from './helpers';
|
||||
|
||||
const runCommandAsync = commands.runAsync.bind(commands);
|
||||
function createArchive(entries: { name: string; contents: Buffer }[]): Buffer {
|
||||
const blocks: Buffer[] = [];
|
||||
for (const { name, contents } of entries) {
|
||||
const header = Buffer.alloc(512);
|
||||
header.write(name);
|
||||
header.write('0000644\0', 100);
|
||||
header.write(contents.length.toString(8).padStart(11, '0') + '\0', 124);
|
||||
header.fill(32, 148, 156);
|
||||
header.write('0', 156);
|
||||
const checksum = header.reduce((sum, byte) => sum + byte, 0);
|
||||
header.write(checksum.toString(8).padStart(6, '0') + '\0 ', 148);
|
||||
blocks.push(header, contents, Buffer.alloc((512 - (contents.length % 512)) % 512));
|
||||
}
|
||||
return gzipSync(Buffer.concat([...blocks, Buffer.alloc(1024)]));
|
||||
}
|
||||
function installCalls() {
|
||||
return jest.mocked(commands.runAsync).mock.calls.filter(([file]) => file === 'xcrun');
|
||||
}
|
||||
|
||||
let directory: string;
|
||||
let archive: Buffer;
|
||||
let controller: AbortController;
|
||||
let warmup: ReturnType<typeof startOn> | undefined;
|
||||
const stableUrl = 'https://example.test/Expo-Go-stable.tar.gz';
|
||||
const sdkVersions = {
|
||||
'57.0.0': {
|
||||
releaseNoteUrl: 'https://example.test/57',
|
||||
iosClientUrl: 'https://example.test/old.tar.gz',
|
||||
},
|
||||
'58.0.0': { releaseNoteUrl: 'https://example.test/58', iosClientUrl: stableUrl },
|
||||
'59.0.0': {
|
||||
isBeta: true,
|
||||
releaseNoteUrl: 'https://example.test/beta',
|
||||
iosClientUrl: 'https://example.test/beta.tar.gz',
|
||||
},
|
||||
'60.0.0': { iosClientUrl: 'https://example.test/canary.tar.gz' },
|
||||
'61.1.0': {
|
||||
releaseNoteUrl: 'https://example.test/not-published',
|
||||
iosClientUrl: 'https://example.test/not-published.tar.gz',
|
||||
},
|
||||
};
|
||||
|
||||
/** Starts the shared download and preinstalls on one device, as warmup does for each device. */
|
||||
function startOn(udid: string, boot: Promise<unknown>) {
|
||||
const preinstall = startExpoGoPreinstall(controller.signal);
|
||||
return {
|
||||
...preinstall,
|
||||
resultPromise: preinstall.preinstallOnDeviceAsync(udid, boot, controller.signal),
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
directory = await fs.mkdtemp(path.join(os.tmpdir(), 'expo-go-unit-'));
|
||||
archive = createArchive([
|
||||
{ name: 'Info.plist', contents: Buffer.from('<plist>fixture</plist>') },
|
||||
]);
|
||||
jest.spyOn(os, 'tmpdir').mockReturnValue(directory);
|
||||
jest
|
||||
.spyOn(global, 'fetch')
|
||||
.mockImplementation(async url =>
|
||||
url === 'https://api.expo.dev/v2/versions'
|
||||
? Response.json({ iosUrl: 'https://example.test/legacy.tar.gz', sdkVersions })
|
||||
: new Response(Uint8Array.from(archive))
|
||||
);
|
||||
jest
|
||||
.spyOn(commands, 'runAsync')
|
||||
.mockImplementation(async (file, args, signal) =>
|
||||
file === '/usr/bin/tar' ? await runCommandAsync(file, args, signal) : ''
|
||||
);
|
||||
jest.spyOn(commands, 'throwIfCommandCloseTimedOut').mockImplementation(() => {});
|
||||
jest.spyOn(process.stderr, 'write').mockReturnValue(true);
|
||||
controller = new AbortController();
|
||||
warmup = undefined;
|
||||
});
|
||||
afterEach(async () => {
|
||||
controller.abort();
|
||||
await warmup?.stopAsync('UDID').catch(() => {});
|
||||
jest.restoreAllMocks();
|
||||
await fs.rm(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('uses the website stable release policy, extracts flat contents as .app and installs only after boot', async () => {
|
||||
const boot = deferred();
|
||||
warmup = startOn('UDID', boot.promise);
|
||||
try {
|
||||
await until(() => jest.mocked(fetch).mock.calls.length === 2);
|
||||
expect(fetch).toHaveBeenLastCalledWith(
|
||||
stableUrl,
|
||||
expect.objectContaining({
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'User-Agent': 'expo-simulator-launcher',
|
||||
},
|
||||
})
|
||||
);
|
||||
expect(installCalls()).toHaveLength(0);
|
||||
boot.resolve();
|
||||
await warmup.resultPromise;
|
||||
expect(installCalls()).toHaveLength(1);
|
||||
const [file, args, signal] = installCalls()[0];
|
||||
expect(file).toBe('xcrun');
|
||||
expect(args.slice(0, 3)).toEqual(['simctl', 'install', 'UDID']);
|
||||
expect(path.basename(args[3])).toBe('ExpoGo.app');
|
||||
expect(signal).toBeUndefined(); // Never cancel an in-flight installd transaction through simctl.
|
||||
// The shared download stays until a claim or stop releases it; stop waits for the removal.
|
||||
expect((await fs.stat(path.dirname(args[3]))).isDirectory()).toBe(true);
|
||||
await warmup.stopAsync('UDID');
|
||||
await expect(fs.stat(path.dirname(args[3]))).rejects.toMatchObject({ code: 'ENOENT' });
|
||||
} finally {
|
||||
boot.resolve();
|
||||
}
|
||||
});
|
||||
|
||||
it('claim aborts a pending download without waiting for it, and a late fetch cannot install', async () => {
|
||||
const pending = deferred<Response>();
|
||||
jest.mocked(fetch).mockReturnValueOnce(pending.promise);
|
||||
warmup = startOn('UDID', Promise.resolve());
|
||||
try {
|
||||
await until(() => jest.mocked(fetch).mock.calls.length > 0);
|
||||
await warmup.claimAsync('UDID');
|
||||
expect(jest.mocked(fetch).mock.calls[0][1]?.signal?.aborted).toBe(true);
|
||||
pending.resolve(Response.json({ sdkVersions })); // Even an uncooperative late fetch cannot install.
|
||||
await warmup.stopAsync('UDID');
|
||||
expect(installCalls()).toHaveLength(0);
|
||||
expect(
|
||||
(await fs.readdir(directory)).filter(name => name.startsWith('simulator-expo-go-'))
|
||||
).toEqual([]);
|
||||
} finally {
|
||||
pending.resolve(Response.json({ sdkVersions }));
|
||||
}
|
||||
});
|
||||
|
||||
it('claim only waits for the native install; terminal stop also drains temporary-file cleanup', async () => {
|
||||
const installation = deferred<string>();
|
||||
const cleanup = deferred();
|
||||
const remove = fs.rm.bind(fs);
|
||||
let cleanupStarted = false;
|
||||
jest.spyOn(fs, 'rm').mockImplementation(async (file, options) => {
|
||||
cleanupStarted = true;
|
||||
await cleanup.promise;
|
||||
return await remove(file, options);
|
||||
});
|
||||
jest
|
||||
.mocked(commands.runAsync)
|
||||
.mockImplementation(async (file, args) =>
|
||||
file === '/usr/bin/tar' ? await runCommandAsync(file, args) : await installation.promise
|
||||
);
|
||||
warmup = startOn('UDID', Promise.resolve());
|
||||
try {
|
||||
await until(() => installCalls().length > 0);
|
||||
let claimed = false;
|
||||
const claiming = warmup.claimAsync('UDID').then(() => {
|
||||
claimed = true;
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(claimed).toBe(false);
|
||||
installation.resolve('');
|
||||
await claiming;
|
||||
expect(claimed).toBe(true);
|
||||
await until(() => cleanupStarted);
|
||||
let stopped = false;
|
||||
const stopping = warmup.stopAsync('UDID').then(() => {
|
||||
stopped = true;
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(stopped).toBe(false);
|
||||
cleanup.resolve();
|
||||
await stopping;
|
||||
} finally {
|
||||
installation.resolve('');
|
||||
cleanup.resolve();
|
||||
}
|
||||
});
|
||||
|
||||
it('claim during extraction returns without waiting but cannot begin an install afterward', async () => {
|
||||
const extraction = deferred();
|
||||
let extracting = false;
|
||||
jest.mocked(commands.runAsync).mockImplementation(async (file, args) => {
|
||||
expect(file).toBe('/usr/bin/tar');
|
||||
extracting = true;
|
||||
await extraction.promise;
|
||||
return await runCommandAsync(file, args);
|
||||
});
|
||||
warmup = startOn('UDID', Promise.resolve());
|
||||
try {
|
||||
await until(() => extracting);
|
||||
await warmup.claimAsync('UDID');
|
||||
expect(installCalls()).toHaveLength(0);
|
||||
let stopped = false;
|
||||
const stopping = warmup.stopAsync('UDID').then(() => {
|
||||
stopped = true;
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(stopped).toBe(false);
|
||||
extraction.resolve();
|
||||
await stopping;
|
||||
expect(installCalls()).toHaveLength(0);
|
||||
} finally {
|
||||
extraction.resolve();
|
||||
}
|
||||
});
|
||||
|
||||
it.each(['metadata', 'archive', 'install'])(
|
||||
'warns on an ordinary %s failure without failing warmup',
|
||||
async phase => {
|
||||
if (phase === 'metadata') {
|
||||
jest.mocked(fetch).mockResolvedValueOnce(new Response('', { status: 403 }));
|
||||
}
|
||||
if (phase === 'archive') {
|
||||
jest
|
||||
.mocked(fetch)
|
||||
.mockResolvedValueOnce(Response.json({ sdkVersions }))
|
||||
.mockResolvedValueOnce(new Response('', { status: 503 }));
|
||||
}
|
||||
if (phase === 'install') {
|
||||
jest.mocked(commands.runAsync).mockImplementation(async (file, args) => {
|
||||
if (file === '/usr/bin/tar') {
|
||||
return await runCommandAsync(file, args);
|
||||
}
|
||||
throw Object.assign(new Error('install failed'), { code: 1 });
|
||||
});
|
||||
}
|
||||
warmup = startOn('UDID', Promise.resolve());
|
||||
await warmup.resultPromise;
|
||||
await warmup.claimAsync('UDID');
|
||||
await warmup.stopAsync('UDID');
|
||||
expect(process.stderr.write).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Could not preinstall Expo Go')
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
it.each(['signal', 'close timeout', 'temp removal'])(
|
||||
'fails closed on %s instead of treating it as optional installation failure',
|
||||
async kind => {
|
||||
const error = Object.assign(new Error(`uncertain ${kind}`), {
|
||||
code: kind === 'signal' ? null : 1,
|
||||
});
|
||||
if (kind === 'temp removal') {
|
||||
jest.spyOn(fs, 'rm').mockRejectedValueOnce(error);
|
||||
} else {
|
||||
jest.mocked(commands.runAsync).mockImplementation(async (file, args) => {
|
||||
if (file === '/usr/bin/tar') {
|
||||
return await runCommandAsync(file, args);
|
||||
}
|
||||
if (kind === 'close timeout') {
|
||||
jest.mocked(commands.throwIfCommandCloseTimedOut).mockImplementation(() => {
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
warmup = startOn('UDID', Promise.resolve());
|
||||
await warmup.resultPromise.catch(() => {});
|
||||
// The claim does not wait for the removal; stop does, and never confirms a failed one.
|
||||
await warmup.claimAsync('UDID').catch(() => {});
|
||||
await expect(warmup.stopAsync('UDID')).rejects.toBe(error);
|
||||
}
|
||||
);
|
||||
|
||||
it.each(['valid', 'traversal', 'malformed'] as const)(
|
||||
'drains the real owned extractor for a %s archive before removing temp files or settling stop',
|
||||
async kind => {
|
||||
const contents = Buffer.alloc(4 * 1024 * 1024, 97);
|
||||
archive =
|
||||
kind === 'malformed'
|
||||
? Buffer.from('not a gzip or tar archive')
|
||||
: createArchive([
|
||||
...(kind === 'traversal'
|
||||
? [{ name: '../escaped', contents: Buffer.from('unsafe') }]
|
||||
: []),
|
||||
{ name: 'Info.plist', contents: Buffer.from('<plist>fixture</plist>') },
|
||||
{ name: 'ordinary-file', contents },
|
||||
]);
|
||||
const start = commands.start.bind(commands);
|
||||
let extractor: ReturnType<typeof commands.start> | undefined;
|
||||
let extractorClosed = false;
|
||||
const remove = fs.rm.bind(fs);
|
||||
const removing = jest.spyOn(fs, 'rm').mockImplementation(async (file, options) => {
|
||||
expect(extractorClosed).toBe(true);
|
||||
if (kind === 'traversal') {
|
||||
await expect(fs.access(path.join(String(file), 'escaped'))).rejects.toMatchObject({
|
||||
code: 'ENOENT',
|
||||
});
|
||||
}
|
||||
if (kind !== 'malformed') {
|
||||
expect(
|
||||
(await fs.readFile(path.join(String(file), 'ExpoGo.app', 'ordinary-file'))).equals(
|
||||
contents
|
||||
)
|
||||
).toBe(true);
|
||||
}
|
||||
return await remove(file, options);
|
||||
});
|
||||
jest.spyOn(commands, 'start').mockImplementation((file, args, options) => {
|
||||
expect(file).toBe('/usr/bin/tar');
|
||||
expect(args).toEqual([
|
||||
'-xzf',
|
||||
expect.stringMatching(/\/expo-go.tar.gz$/),
|
||||
'-C',
|
||||
expect.stringMatching(/\/ExpoGo.app$/),
|
||||
]);
|
||||
expect(options?.signal).toBeUndefined();
|
||||
extractor = start(file, args, options);
|
||||
extractor.child.once('close', () => {
|
||||
extractorClosed = true;
|
||||
});
|
||||
expect(extractor.child.kill('SIGSTOP')).toBe(true);
|
||||
return extractor;
|
||||
});
|
||||
warmup = startOn('UDID', Promise.resolve());
|
||||
try {
|
||||
await until(() => extractor !== undefined);
|
||||
await warmup.claimAsync('UDID'); // Only forbids new install; extraction remains owned and pending.
|
||||
expect(extractorClosed).toBe(false);
|
||||
let stopped = false;
|
||||
const stopping = warmup.stopAsync('UDID').then(() => {
|
||||
stopped = true;
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(stopped).toBe(false);
|
||||
expect(removing).not.toHaveBeenCalled();
|
||||
extractor!.child.kill('SIGCONT');
|
||||
await stopping;
|
||||
expect(extractorClosed).toBe(true);
|
||||
expect(removing).toHaveBeenCalledTimes(1);
|
||||
expect(installCalls()).toHaveLength(0);
|
||||
expect(await fs.readdir(directory)).toEqual([]);
|
||||
if (kind !== 'valid') {
|
||||
const extractionError = await extractor!.resultPromise.catch(error => error);
|
||||
expect(extractionError.code).toBeGreaterThan(0);
|
||||
}
|
||||
} finally {
|
||||
// Reap only this test's owned child, including an assertion failure while it is stopped.
|
||||
if (extractor?.child.exitCode == null && extractor?.child.signalCode == null) {
|
||||
extractor?.child.kill('SIGCONT');
|
||||
extractor?.child.kill('SIGKILL');
|
||||
}
|
||||
await extractor?.resultPromise.catch(() => {});
|
||||
removing.mockRestore();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
it('keeps owned temp files and rejects terminal stop when extractor close is uncertain', async () => {
|
||||
const failure = new Error('extractor close not proved');
|
||||
const remove = jest.spyOn(fs, 'rm');
|
||||
jest.mocked(commands.runAsync).mockImplementationOnce(async file => {
|
||||
expect(file).toBe('/usr/bin/tar');
|
||||
jest.mocked(commands.throwIfCommandCloseTimedOut).mockImplementation(() => {
|
||||
throw failure;
|
||||
});
|
||||
throw failure;
|
||||
});
|
||||
warmup = startOn('UDID', Promise.resolve());
|
||||
await expect(warmup.resultPromise).rejects.toBe(failure);
|
||||
await expect(warmup.stopAsync('UDID')).rejects.toBe(failure);
|
||||
await expect(warmup.claimAsync('UDID')).rejects.toBe(failure);
|
||||
expect(remove).not.toHaveBeenCalled();
|
||||
expect((await fs.readdir(directory)).some(name => name.startsWith('simulator-expo-go-'))).toBe(
|
||||
true
|
||||
);
|
||||
expect(installCalls()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it.each(['traversal', 'malformed'] as const)(
|
||||
'never installs after a real %s archive failure without a claim',
|
||||
async kind => {
|
||||
archive =
|
||||
kind === 'malformed'
|
||||
? Buffer.from('not an archive')
|
||||
: createArchive([
|
||||
{ name: '../escaped', contents: Buffer.from('unsafe') },
|
||||
{ name: 'Info.plist', contents: Buffer.from('<plist>fixture</plist>') },
|
||||
]);
|
||||
warmup = startOn('UDID', Promise.resolve());
|
||||
await warmup.resultPromise;
|
||||
expect(installCalls()).toHaveLength(0);
|
||||
expect(process.stderr.write).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Could not preinstall Expo Go')
|
||||
);
|
||||
await warmup.stopAsync('UDID');
|
||||
expect(await fs.readdir(directory)).toEqual([]);
|
||||
}
|
||||
);
|
||||
|
||||
it('claim returns the identity read from the Expo Go it installed', async () => {
|
||||
const plist: Record<string, string> = {
|
||||
CFBundleIdentifier: 'host.exp.Exponent',
|
||||
CFBundleShortVersionString: '58.0.7',
|
||||
CFBundleVersion: '58.0.7',
|
||||
};
|
||||
jest
|
||||
.mocked(commands.runAsync)
|
||||
.mockImplementation(async (file, args, signal) =>
|
||||
file === '/usr/bin/tar'
|
||||
? await runCommandAsync(file, args, signal)
|
||||
: file === 'plutil'
|
||||
? `${plist[args[1]]}\n`
|
||||
: ''
|
||||
);
|
||||
warmup = startOn('UDID', Promise.resolve());
|
||||
await warmup.resultPromise;
|
||||
expect(await warmup.claimAsync('UDID')).toEqual({
|
||||
udid: 'UDID',
|
||||
bundleIdentifier: 'host.exp.Exponent',
|
||||
shortVersion: '58.0.7',
|
||||
version: '58.0.7',
|
||||
});
|
||||
const plistPath = jest
|
||||
.mocked(commands.runAsync)
|
||||
.mock.calls.find(([file]) => file === 'plutil')![1];
|
||||
expect(path.basename(path.dirname(plistPath[5]))).toBe('ExpoGo.app');
|
||||
});
|
||||
|
||||
it('claim returns no identity when the preinstall fails', async () => {
|
||||
jest
|
||||
.mocked(commands.runAsync)
|
||||
.mockImplementation(async (file, args, signal) =>
|
||||
file === '/usr/bin/tar'
|
||||
? await runCommandAsync(file, args, signal)
|
||||
: file === 'xcrun'
|
||||
? Promise.reject(Object.assign(new Error('install failed'), { code: 1 }))
|
||||
: ''
|
||||
);
|
||||
warmup = startOn('UDID', Promise.resolve());
|
||||
await warmup.resultPromise;
|
||||
expect(await warmup.claimAsync('UDID')).toBeUndefined();
|
||||
expect(jest.mocked(commands.runAsync).mock.calls.some(([file]) => file === 'plutil')).toBe(false);
|
||||
});
|
||||
|
||||
it('downloads and extracts once for two devices, then removes the shared app on stop', async () => {
|
||||
warmup = startOn('FIRST', Promise.resolve());
|
||||
await warmup.resultPromise;
|
||||
const app = installCalls()[0][1][3];
|
||||
expect((await fs.stat(app)).isDirectory()).toBe(true);
|
||||
await warmup.preinstallOnDeviceAsync('SECOND', Promise.resolve(), controller.signal);
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
expect(
|
||||
jest.mocked(commands.runAsync).mock.calls.filter(([file]) => file === '/usr/bin/tar')
|
||||
).toHaveLength(1);
|
||||
expect(installCalls().map(([, args]) => args.slice(2))).toEqual([
|
||||
['FIRST', app],
|
||||
['SECOND', app],
|
||||
]);
|
||||
const claimed = await warmup.claimAsync('SECOND');
|
||||
await warmup.stopAsync('SECOND');
|
||||
await expect(fs.stat(app)).rejects.toMatchObject({ code: 'ENOENT' });
|
||||
expect(claimed?.udid).toBe('SECOND');
|
||||
});
|
||||
it('a claim prevents secondary preinstall from starting and releases the retained archive', async () => {
|
||||
warmup = startOn('FIRST', Promise.resolve());
|
||||
await warmup.resultPromise;
|
||||
await warmup.claimAsync('FIRST');
|
||||
await warmup.preinstallOnDeviceAsync('SECOND', Promise.resolve(), controller.signal);
|
||||
await warmup.stopAsync('FIRST');
|
||||
expect(installCalls()).toHaveLength(1);
|
||||
expect(await fs.readdir(directory)).toEqual([]);
|
||||
});
|
||||
it('claim and stop drain a secondary native install without cancelling its transaction', async () => {
|
||||
const install = deferred<string>();
|
||||
const original = jest.mocked(commands.runAsync).getMockImplementation()!;
|
||||
warmup = startOn('FIRST', Promise.resolve());
|
||||
await warmup.resultPromise;
|
||||
jest
|
||||
.mocked(commands.runAsync)
|
||||
.mockImplementation((file, args, signal) =>
|
||||
file === 'xcrun' && args.includes('SECOND') ? install.promise : original(file, args, signal)
|
||||
);
|
||||
const secondary = warmup.preinstallOnDeviceAsync('SECOND', Promise.resolve(), controller.signal);
|
||||
let claimed = false;
|
||||
try {
|
||||
await until(() => installCalls().length === 2);
|
||||
const claiming = warmup.claimAsync('SECOND').then(() => {
|
||||
claimed = true;
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(claimed).toBe(false);
|
||||
expect(installCalls()[1][2]).toBeUndefined();
|
||||
install.resolve('');
|
||||
await claiming;
|
||||
await secondary;
|
||||
await warmup.stopAsync('FIRST');
|
||||
expect(await fs.readdir(directory)).toEqual([]);
|
||||
} finally {
|
||||
install.resolve('');
|
||||
await secondary;
|
||||
}
|
||||
});
|
||||
|
||||
it.each(['signal', 'close timeout'])(
|
||||
'isolates a secondary %s failure from the already-installed default',
|
||||
async kind => {
|
||||
warmup = startOn('FIRST', Promise.resolve());
|
||||
await warmup.resultPromise;
|
||||
const failure = Object.assign(new Error('secondary install failed'), { code: null });
|
||||
const original = jest.mocked(commands.runAsync).getMockImplementation()!;
|
||||
jest.mocked(commands.runAsync).mockImplementation((file, args, signal) => {
|
||||
if (file === 'xcrun' && args.includes('SECOND')) {
|
||||
if (kind === 'close timeout') {
|
||||
jest.mocked(commands.throwIfCommandCloseTimedOut).mockImplementation(() => {
|
||||
throw failure;
|
||||
});
|
||||
}
|
||||
return Promise.reject(failure);
|
||||
}
|
||||
return original(file, args, signal);
|
||||
});
|
||||
await expect(
|
||||
warmup.preinstallOnDeviceAsync('SECOND', Promise.resolve(), controller.signal)
|
||||
).rejects.toBe(failure);
|
||||
expect((await warmup.claimAsync('FIRST'))?.udid).toBe('FIRST');
|
||||
await expect(warmup.claimAsync('SECOND')).rejects.toBe(failure);
|
||||
if (kind === 'close timeout') {
|
||||
await expect(warmup.stopAsync('FIRST')).rejects.toBe(failure);
|
||||
} else {
|
||||
await expect(warmup.stopAsync('FIRST')).resolves.toBeUndefined();
|
||||
}
|
||||
await expect(warmup.stopAsync('SECOND')).rejects.toBe(failure);
|
||||
}
|
||||
);
|
||||
it('a concurrent stop cannot miss a secondary install failure while shared cleanup drains', async () => {
|
||||
warmup = startOn('FIRST', Promise.resolve());
|
||||
await warmup.resultPromise;
|
||||
const installation = deferred<string>();
|
||||
const original = jest.mocked(commands.runAsync).getMockImplementation()!;
|
||||
jest
|
||||
.mocked(commands.runAsync)
|
||||
.mockImplementation((file, args, signal) =>
|
||||
file === 'xcrun' && args.includes('SECOND')
|
||||
? installation.promise
|
||||
: original(file, args, signal)
|
||||
);
|
||||
const secondary = warmup.preinstallOnDeviceAsync('SECOND', Promise.resolve(), controller.signal);
|
||||
void secondary.catch(() => {});
|
||||
try {
|
||||
await until(() => installCalls().length === 2);
|
||||
const stopping = warmup.stopAsync('SECOND');
|
||||
void stopping.catch(() => {});
|
||||
const failure = Object.assign(new Error('secondary killed'), { code: null });
|
||||
installation.reject(failure);
|
||||
await expect(stopping).rejects.toBe(failure);
|
||||
await expect(secondary).rejects.toBe(failure);
|
||||
} finally {
|
||||
installation.resolve('');
|
||||
await secondary.catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
it('preinstalls all three configured devices from one shared archive through the session owner', async () => {
|
||||
const { createWarmSimulatorSession } = await import('../commands/start');
|
||||
const simulator = await import('../utils/simulator');
|
||||
const serveSim = await import('../utils/serveSim');
|
||||
const processes = await import('../utils/processes');
|
||||
const agentDevice = await import('../utils/agentDevice');
|
||||
const argent = await import('../utils/argent');
|
||||
const devices = ['FIRST', 'SECOND', 'THIRD'].map(udid => ({ udid, name: `iPhone ${udid}` }));
|
||||
const environment = { ...process.env };
|
||||
process.env.EXPO_SIMULATOR_DEVICE = devices.map(device => device.udid).join(',');
|
||||
process.env.AGENT_DEVICE_STATE_DIR = path.join(directory, 'agent');
|
||||
process.env.ARGENT_EVENT_LOG = path.join(directory, 'argent-events');
|
||||
jest.spyOn(simulator, 'listAvailableSimulatorsAsync').mockResolvedValue(devices);
|
||||
jest.spyOn(simulator, 'waitForSimulatorBootAsync').mockResolvedValue();
|
||||
jest.spyOn(simulator, 'disableApsdAsync').mockResolvedValue();
|
||||
jest.spyOn(simulator, 'shutdownSimulatorAsync').mockResolvedValue();
|
||||
jest.spyOn(processes, 'stopProcessAndDescendantsAsync').mockResolvedValue();
|
||||
jest.spyOn(agentDevice, 'createAgentDeviceTool').mockReturnValue({
|
||||
name: 'agent-device',
|
||||
startAsync: async () => {},
|
||||
stopAsync: async () => {},
|
||||
});
|
||||
jest
|
||||
.spyOn(argent, 'createArgentTool')
|
||||
.mockReturnValue({ name: 'argent', startAsync: async () => {}, stopAsync: async () => {} });
|
||||
jest.spyOn(serveSim, 'startServeSim').mockReturnValue({
|
||||
child: { pid: 90001 } as import('node:child_process').ChildProcess,
|
||||
resultPromise: new Promise(() => {}),
|
||||
});
|
||||
jest.spyOn(serveSim, 'waitForServeSimReadyAsync').mockResolvedValue({
|
||||
startupDevice: 'FIRST',
|
||||
pid: 90001,
|
||||
port: 3200,
|
||||
nativeStartTime: 'start-time',
|
||||
url: 'http://127.0.0.1:3200',
|
||||
token: 'fixture-token',
|
||||
});
|
||||
const original = jest.mocked(commands.runAsync).getMockImplementation()!;
|
||||
jest.mocked(commands.runAsync).mockImplementation(async (file, args, signal) => {
|
||||
if (file === 'ps') {
|
||||
return 'controller-start';
|
||||
}
|
||||
if (file === 'plutil') {
|
||||
return args.includes('CFBundleIdentifier') ? 'host.exp.Exponent' : '58.0.7';
|
||||
}
|
||||
return original(file, args, signal);
|
||||
});
|
||||
const onFailure = jest.fn();
|
||||
const session = createWarmSimulatorSession({
|
||||
signal: controller.signal,
|
||||
throwIfStoppingAsync: async () => controller.signal.throwIfAborted(),
|
||||
onPreparationFailure: onFailure,
|
||||
});
|
||||
try {
|
||||
await session.prepareAsync();
|
||||
await until(() => installCalls().length === 3);
|
||||
await session.claimAsync({ engine: 'serve-sim', requestedDevice: 'THIRD' });
|
||||
const prepared = await session.prepareToolsAsync();
|
||||
expect(prepared.preinstalledExpoGo).toEqual({
|
||||
udid: 'THIRD',
|
||||
bundleIdentifier: 'host.exp.Exponent',
|
||||
shortVersion: '58.0.7',
|
||||
version: '58.0.7',
|
||||
});
|
||||
expect(installCalls().map(([, args]) => args[2])).toEqual(['FIRST', 'SECOND', 'THIRD']);
|
||||
expect(new Set(installCalls().map(([, args]) => args[3])).size).toBe(1);
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
expect(
|
||||
jest.mocked(commands.runAsync).mock.calls.filter(([file]) => file === '/usr/bin/tar')
|
||||
).toHaveLength(1);
|
||||
expect(onFailure).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await session.stopAsync();
|
||||
process.env = environment;
|
||||
}
|
||||
});
|
||||
@@ -1,13 +0,0 @@
|
||||
// Test fixtures use these PIDs for fake child processes. Fail fast instead of letting a test
|
||||
// reach the real process.kill with one of them, where it could signal an unrelated process.
|
||||
const FIXTURE_PIDS = new Set([10, 11, 12, 20, 30, 40, 41]);
|
||||
const isFixturePid = (pid: number): boolean =>
|
||||
FIXTURE_PIDS.has(Math.abs(pid)) || (Math.abs(pid) >= 90000 && Math.abs(pid) < 90100);
|
||||
|
||||
const realKill = process.kill.bind(process);
|
||||
process.kill = ((pid: number, signal?: string | number) => {
|
||||
if (isFixturePid(pid)) {
|
||||
throw new Error(`A test tried to signal fixture PID ${pid} through the real process.kill.`);
|
||||
}
|
||||
return realKill(pid, signal);
|
||||
}) as typeof process.kill;
|
||||
@@ -1,56 +0,0 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { setTimeout as sleepAsync } from 'node:timers/promises';
|
||||
|
||||
import { commands, stopProcessAndDescendantsAsync } from '../../utils/processes';
|
||||
|
||||
export async function startOwnedWrapperAsync() {
|
||||
const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'launcher-owned-wrapper-'));
|
||||
const readyPath = path.join(directory, 'ready.json');
|
||||
const job = commands.start(
|
||||
process.execPath,
|
||||
[path.join(__dirname, 'stop-wrapper.cjs'), path.join(__dirname, 'stop-leaf.cjs'), readyPath],
|
||||
{ captureStdout: true, detached: true }
|
||||
);
|
||||
const realKill = process.kill.bind(process);
|
||||
const stop = stopProcessAndDescendantsAsync;
|
||||
let confirmed = false;
|
||||
let stopping: Promise<void> | undefined;
|
||||
const cleanupAsync = async () => {
|
||||
if (!confirmed && job.child.pid) {
|
||||
try {
|
||||
realKill(-job.child.pid, 'SIGKILL');
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error;
|
||||
}
|
||||
}
|
||||
await job.resultPromise.catch(() => {});
|
||||
await fs.rm(directory, { recursive: true, force: true });
|
||||
};
|
||||
try {
|
||||
let leaves: number[] = [];
|
||||
const deadline = Date.now() + 5_000;
|
||||
while (!leaves.length) {
|
||||
const ready = await fs.readFile(readyPath, 'utf8').catch(() => undefined);
|
||||
if (ready) leaves = JSON.parse(ready);
|
||||
else {
|
||||
if (Date.now() >= deadline) throw new Error('The disposable wrapper did not become ready.');
|
||||
await sleepAsync(10);
|
||||
}
|
||||
}
|
||||
return {
|
||||
job,
|
||||
leaves,
|
||||
realKill,
|
||||
cleanupAsync,
|
||||
stopAsync: () =>
|
||||
(stopping ??= stop(job).then(() => {
|
||||
confirmed = true;
|
||||
})),
|
||||
};
|
||||
} catch (error) {
|
||||
await cleanupAsync();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
process.on('SIGTERM', () => process.exit(23));
|
||||
setInterval(() => {}, 1000);
|
||||
process.send('ready');
|
||||
@@ -1,20 +0,0 @@
|
||||
const { spawn } = require('node:child_process');
|
||||
const fs = require('node:fs');
|
||||
const children = [0, 1].map(() =>
|
||||
spawn(process.execPath, [process.argv[2]], {
|
||||
stdio: ['ignore', 'inherit', 'inherit', 'ipc'],
|
||||
})
|
||||
);
|
||||
// Like a supervisor, forward parent termination and report the child's final status.
|
||||
process.on('SIGTERM', () => {
|
||||
for (const child of children) child.kill('SIGTERM');
|
||||
});
|
||||
let ready = 0;
|
||||
for (const child of children) {
|
||||
child.on('message', () => {
|
||||
if (++ready === children.length) {
|
||||
fs.writeFileSync(process.argv[3], JSON.stringify(children.map(child => child.pid)));
|
||||
}
|
||||
});
|
||||
child.on('exit', code => process.exit(code ?? 1));
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
export function deferred<T = void>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: unknown) => void;
|
||||
const promise = new Promise<T>((yes, no) => {
|
||||
resolve = yes;
|
||||
reject = no;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
/** Polls `predicate` for up to 2 seconds, then asserts it. */
|
||||
export async function until(predicate: () => boolean): Promise<void> {
|
||||
for (let i = 0; i < 400 && !predicate(); i++) {
|
||||
await new Promise(resolve => setTimeout(resolve, 5));
|
||||
}
|
||||
expect(predicate()).toBe(true);
|
||||
}
|
||||
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user