-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathdispatch-resolve.ts
More file actions
214 lines (197 loc) · 7.3 KB
/
dispatch-resolve.ts
File metadata and controls
214 lines (197 loc) · 7.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import { AsyncLocalStorage } from 'node:async_hooks';
import { AppError } from '../utils/errors.ts';
import {
normalizePlatformSelector,
resolveDevice,
resolveAppleSimulatorSetPathForSelector,
type DeviceInfo,
type DeviceTarget,
type PlatformSelector,
} from '../utils/device.ts';
import { listAndroidDevices } from '../platforms/android/devices.ts';
import { ensureAdb } from '../platforms/android/index.ts';
import { findBootableIosSimulator, listAppleDevices } from '../platforms/ios/devices.ts';
import { listLinuxDevices } from '../platforms/linux/devices.ts';
import { withDiagnosticTimer } from '../utils/diagnostics.ts';
import {
resolveAndroidSerialAllowlist,
resolveIosSimulatorDeviceSetPath,
} from '../utils/device-isolation.ts';
import type { CliFlags } from '../utils/command-schema.ts';
type ResolveDeviceFlags = Pick<
CliFlags,
| 'platform'
| 'target'
| 'device'
| 'udid'
| 'serial'
| 'iosSimulatorDeviceSet'
| 'androidDeviceAllowlist'
>;
const resolveTargetDeviceCacheScope = new AsyncLocalStorage<Map<string, DeviceInfo>>();
type AppleDeviceSelector = {
platform?: Exclude<PlatformSelector, 'android'>;
target?: DeviceTarget;
deviceName?: string;
udid?: string;
serial?: string;
};
/**
* Resolves the best iOS device given pre-fetched candidates. When no explicit
* device selector was used, physical devices are rejected in favour of a
* bootable simulator discovered via `findBootableSimulator`.
*
* Exported for testing; production callers should use `resolveTargetDevice`.
*/
async function resolveAppleDevice(
devices: DeviceInfo[],
selector: AppleDeviceSelector,
context: { simulatorSetPath?: string },
): Promise<DeviceInfo> {
const hasExplicitSelector = !!(selector.udid || selector.serial || selector.deviceName);
let selected: DeviceInfo | undefined;
try {
selected = await resolveDevice(devices, selector, context);
} catch (err) {
// When resolveDevice throws DEVICE_NOT_FOUND and no explicit device
// selector was used, attempt the simulator fallback before giving up.
if (hasExplicitSelector || !(err instanceof AppError) || err.code !== 'DEVICE_NOT_FOUND') {
throw err;
}
}
// When no explicit device selector was used and auto-selection either
// picked a physical device or found nothing at all, try to find an
// available simulator instead. Physical devices should only be used
// when explicitly targeted.
const shouldUseSimulatorFallback =
!hasExplicitSelector &&
(!selector.platform || selector.platform === 'apple' || selector.platform === 'ios') &&
selector.target !== 'desktop';
if (shouldUseSimulatorFallback && (!selected || selected.kind === 'device')) {
const simulator = await findBootableIosSimulator({
simulatorSetPath: context.simulatorSetPath,
target: selector.target,
});
if (simulator) return simulator;
}
if (selected) return selected;
throw new AppError('DEVICE_NOT_FOUND', 'No devices found', { selector });
}
export async function resolveIosDevice(
devices: DeviceInfo[],
selector: AppleDeviceSelector,
context: { simulatorSetPath?: string },
): Promise<DeviceInfo> {
return await resolveAppleDevice(devices, selector, context);
}
export async function resolveTargetDevice(flags: ResolveDeviceFlags): Promise<DeviceInfo> {
const normalizedPlatform = normalizePlatformSelector(flags.platform);
const iosSimulatorSetPath = resolveAppleSimulatorSetPathForSelector({
simulatorSetPath: resolveIosSimulatorDeviceSetPath(flags.iosSimulatorDeviceSet),
platform: normalizedPlatform,
target: flags.target,
});
const androidSerialAllowlist = resolveAndroidSerialAllowlist(flags.androidDeviceAllowlist);
const cacheKey = buildResolveTargetDeviceCacheKey({
flags,
normalizedPlatform,
iosSimulatorSetPath,
androidSerialAllowlist,
});
const diagnosticData = {
platform: normalizedPlatform,
target: flags.target,
cacheHit: false,
};
return await withDiagnosticTimer(
'resolve_target_device',
async () => {
const cached = readResolveTargetDeviceCache(cacheKey);
if (cached) {
diagnosticData.cacheHit = true;
return cached;
}
const selector = {
platform: normalizedPlatform,
target: flags.target,
deviceName: flags.device,
udid: flags.udid,
serial: flags.serial,
};
if (selector.target && !selector.platform) {
throw new AppError(
'INVALID_ARGS',
'Device target selector requires --platform. Use --platform ios|macos|android|linux|apple with --target mobile|tv|desktop.',
);
}
if (selector.platform === 'linux') {
const devices = await listLinuxDevices();
return cacheResolvedTargetDevice(cacheKey, await resolveDevice(devices, selector));
}
if (selector.platform === 'android') {
await ensureAdb();
const devices = await listAndroidDevices({ serialAllowlist: androidSerialAllowlist });
return cacheResolvedTargetDevice(cacheKey, await resolveDevice(devices, selector));
}
if (selector.platform) {
const devices = await listAppleDevices({ simulatorSetPath: iosSimulatorSetPath });
return cacheResolvedTargetDevice(
cacheKey,
await resolveAppleDevice(devices, selector as AppleDeviceSelector, {
simulatorSetPath: iosSimulatorSetPath,
}),
);
}
const devices: DeviceInfo[] = [];
try {
devices.push(...(await listAndroidDevices({ serialAllowlist: androidSerialAllowlist })));
} catch {}
try {
devices.push(...(await listAppleDevices({ simulatorSetPath: iosSimulatorSetPath })));
} catch {}
// Linux local device is appended last so it does not displace
// connected Android/Apple devices in implicit auto-selection.
try {
devices.push(...(await listLinuxDevices()));
} catch {}
return cacheResolvedTargetDevice(
cacheKey,
await resolveDevice(devices, selector, { simulatorSetPath: iosSimulatorSetPath }),
);
},
diagnosticData,
);
}
export async function withResolveTargetDeviceCacheScope<T>(task: () => Promise<T>): Promise<T> {
if (resolveTargetDeviceCacheScope.getStore()) return await task();
return await resolveTargetDeviceCacheScope.run(new Map(), task);
}
function readResolveTargetDeviceCache(cacheKey: string): DeviceInfo | undefined {
const cache = resolveTargetDeviceCacheScope.getStore();
const cached = cache?.get(cacheKey);
if (!cached) return undefined;
return { ...cached };
}
function cacheResolvedTargetDevice(cacheKey: string, device: DeviceInfo): DeviceInfo {
resolveTargetDeviceCacheScope.getStore()?.set(cacheKey, { ...device });
return device;
}
function buildResolveTargetDeviceCacheKey(params: {
flags: ResolveDeviceFlags;
normalizedPlatform?: PlatformSelector;
iosSimulatorSetPath?: string;
androidSerialAllowlist?: ReadonlySet<string>;
}): string {
const { flags, normalizedPlatform, iosSimulatorSetPath, androidSerialAllowlist } = params;
return JSON.stringify({
platform: normalizedPlatform,
target: flags.target,
device: flags.device,
udid: flags.udid,
serial: flags.serial,
iosSimulatorSetPath,
androidSerialAllowlist: androidSerialAllowlist
? Array.from(androidSerialAllowlist).sort()
: undefined,
});
}