-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathdispatch-resolve.ts
More file actions
285 lines (259 loc) · 8.92 KB
/
Copy pathdispatch-resolve.ts
File metadata and controls
285 lines (259 loc) · 8.92 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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import { AsyncLocalStorage } from 'node:async_hooks';
import { AppError } from '../utils/errors.ts';
import {
isApplePlatform,
normalizePlatformSelector,
resolveDevice,
resolveAppleSimulatorSetPathForSelector,
type DeviceInfo,
type DeviceTarget,
type PlatformSelector,
} from '../utils/device.ts';
import { withDiagnosticTimer } from '../utils/diagnostics.ts';
import {
resolveAndroidSerialAllowlist,
resolveIosSimulatorDeviceSetPath,
} from '../utils/device-isolation.ts';
import type { CliFlags } from '../utils/cli-flags.ts';
import { listLocalDeviceInventory, type DeviceInventoryRequest } from './platform-inventory.ts';
type ResolveDeviceFlags = Pick<
CliFlags,
| 'platform'
| 'target'
| 'device'
| 'udid'
| 'serial'
| 'iosSimulatorDeviceSet'
| 'androidDeviceAllowlist'
>;
const resolveTargetDeviceCacheScope = new AsyncLocalStorage<Map<string, DeviceInfo>>();
const deviceInventoryProviderScope = new AsyncLocalStorage<DeviceInventoryProvider>();
export type { DeviceInventoryRequest };
export type DeviceInventoryProvider = (
request: DeviceInventoryRequest,
) => Promise<DeviceInfo[] | null | undefined>;
type AppleDeviceSelector = {
platform?: 'ios' | 'macos' | 'apple';
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 selected = await resolveAppleDeviceCandidate(devices, selector, context);
if (shouldUseAppleSimulatorFallback(selector, selected)) {
const { findBootableIosSimulator } = await import('../platforms/ios/devices.ts');
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 });
}
async function resolveAppleDeviceCandidate(
devices: DeviceInfo[],
selector: AppleDeviceSelector,
context: { simulatorSetPath?: string },
): Promise<DeviceInfo | undefined> {
try {
return await resolveDevice(devices, selector, context);
} catch (error) {
if (canFallbackAfterAppleDeviceNotFound(error, selector)) return undefined;
throw error;
}
}
function canFallbackAfterAppleDeviceNotFound(
error: unknown,
selector: AppleDeviceSelector,
): boolean {
return (
!hasExplicitAppleDeviceSelector(selector) &&
error instanceof AppError &&
error.code === 'DEVICE_NOT_FOUND'
);
}
function shouldUseAppleSimulatorFallback(
selector: AppleDeviceSelector,
selected: DeviceInfo | undefined,
): boolean {
return (
!hasExplicitAppleDeviceSelector(selector) &&
(!selector.platform || selector.platform === 'apple' || selector.platform === 'ios') &&
selector.target !== 'desktop' &&
(!selected || selected.kind === 'device')
);
}
function hasExplicitAppleDeviceSelector(selector: AppleDeviceSelector): boolean {
return Boolean(selector.udid || selector.serial || selector.deviceName);
}
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.',
);
}
const injectedDevices = await readInjectedDeviceInventory({
...selector,
iosSimulatorSetPath,
androidSerialAllowlist: androidSerialAllowlist
? Array.from(androidSerialAllowlist).sort()
: undefined,
});
if (injectedDevices) {
if (isAppleResolutionSelector(selector)) {
return cacheResolvedTargetDevice(
cacheKey,
await resolveAppleDevice(injectedDevices, selector as AppleDeviceSelector, {
simulatorSetPath: iosSimulatorSetPath,
}),
);
}
return cacheResolvedTargetDevice(
cacheKey,
await resolveDevice(injectedDevices, selector, { simulatorSetPath: iosSimulatorSetPath }),
);
}
const devices = await listLocalDeviceInventory({
...selector,
iosSimulatorSetPath,
androidSerialAllowlist: androidSerialAllowlist
? Array.from(androidSerialAllowlist).sort()
: undefined,
});
if (isAppleResolutionSelector(selector)) {
return cacheResolvedTargetDevice(
cacheKey,
await resolveAppleDevice(devices, selector as AppleDeviceSelector, {
simulatorSetPath: iosSimulatorSetPath,
}),
);
}
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);
}
export async function withDeviceInventoryProvider<T>(
provider: DeviceInventoryProvider | undefined,
task: () => Promise<T>,
): Promise<T> {
if (!provider) return await task();
return await deviceInventoryProviderScope.run(provider, task);
}
export async function withTargetDeviceResolutionScope<T>(
provider: DeviceInventoryProvider | undefined,
task: () => Promise<T>,
): Promise<T> {
return await withDeviceInventoryProvider(
provider,
async () => await withResolveTargetDeviceCacheScope(task),
);
}
export async function listDeviceInventory(request: DeviceInventoryRequest): Promise<DeviceInfo[]> {
return (await readInjectedDeviceInventory(request)) ?? (await listLocalDeviceInventory(request));
}
async function readInjectedDeviceInventory(
request: DeviceInventoryRequest,
): Promise<DeviceInfo[] | null> {
const provider = deviceInventoryProviderScope.getStore();
if (!provider) return null;
const devices = await provider(request);
if (devices === undefined || devices === null) return null;
return devices.map((device) => ({ ...device }));
}
function isAppleResolutionSelector(selector: {
platform?: PlatformSelector;
target?: DeviceTarget;
}): boolean {
return isApplePlatform(selector.platform);
}
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,
});
}