-
-
Notifications
You must be signed in to change notification settings - Fork 202
Expand file tree
/
Copy pathrun-controller.ts
More file actions
1160 lines (1064 loc) · 36.3 KB
/
Copy pathrun-controller.ts
File metadata and controls
1160 lines (1064 loc) · 36.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
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { HmrConstants, DeviceDiscoveryEventNames } from "../common/constants";
import {
PREPARE_READY_EVENT_NAME,
TrackActionNames,
DEBUGGER_DETACHED_EVENT_NAME,
RunOnDeviceEvents,
USER_INTERACTION_NEEDED_EVENT_NAME,
} from "../constants";
import { cache, performanceLog } from "../common/decorators";
import { EventEmitter } from "events";
import * as util from "util";
import * as _ from "lodash";
import { IProjectDataService, IProjectData } from "../definitions/project";
import { IBuildController } from "../definitions/build";
import { IPlatformsDataService } from "../definitions/platform";
import { IDebugController } from "../definitions/debug";
import { IPluginsService } from "../definitions/plugins";
import {
IAnalyticsService,
IErrors,
IHooksService,
IDictionary,
} from "../common/declarations";
import { IInjector } from "../common/definitions/yok";
import { injector } from "../common/yok";
export class RunController extends EventEmitter implements IRunController {
private prepareReadyEventHandler: any = null;
private _syncInProgress = false;
private _pendingSyncs: Map<
string,
{
data: IFilesChangeEventData;
projectData: IProjectData;
liveSyncInfo: ILiveSyncInfo;
}
> = new Map();
constructor(
protected $analyticsService: IAnalyticsService,
private $buildController: IBuildController,
private $debugController: IDebugController,
private $deviceInstallAppService: IDeviceInstallAppService,
protected $devicesService: Mobile.IDevicesService,
protected $errors: IErrors,
protected $injector: IInjector,
private $hmrStatusService: IHmrStatusService,
public $hooksService: IHooksService,
private $liveSyncServiceResolver: ILiveSyncServiceResolver,
private $liveSyncProcessDataService: ILiveSyncProcessDataService,
protected $logger: ILogger,
protected $mobileHelper: Mobile.IMobileHelper,
private $platformsDataService: IPlatformsDataService,
private $pluginsService: IPluginsService,
private $prepareController: IPrepareController,
private $prepareDataService: IPrepareDataService,
private $prepareNativePlatformService: IPrepareNativePlatformService,
private $projectChangesService: IProjectChangesService,
protected $projectDataService: IProjectDataService,
private $staticConfig: Config.IStaticConfig,
) {
super();
}
public async run(runData: IRunData): Promise<void> {
const { liveSyncInfo, deviceDescriptors } = runData;
const { projectDir } = liveSyncInfo;
const projectData = this.$projectDataService.getProjectData(projectDir);
await this.initializeSetup(projectData);
const deviceDescriptorsForInitialSync =
this.getDeviceDescriptorsForInitialSync(projectDir, deviceDescriptors);
const newPlatforms =
this.$devicesService.getPlatformsFromDeviceDescriptors(deviceDescriptors);
const oldPlatforms =
this.$liveSyncProcessDataService.getPlatforms(projectDir);
const platforms = _.uniq(_.concat(newPlatforms, oldPlatforms));
this.$liveSyncProcessDataService.persistData(
projectDir,
deviceDescriptors,
platforms,
);
const shouldStartWatcher =
!liveSyncInfo.skipWatcher &&
this.$liveSyncProcessDataService.hasDeviceDescriptors(projectDir);
if (shouldStartWatcher && liveSyncInfo.useHotModuleReload) {
this.$hmrStatusService.attachToHmrStatusEvent();
}
if (!this.prepareReadyEventHandler) {
const handler = async (data: IFilesChangeEventData) => {
if (data.hasNativeChanges) {
const platformData = this.$platformsDataService.getPlatformData(
data.platform,
projectData,
);
const prepareData = this.$prepareDataService.getPrepareData(
liveSyncInfo.projectDir,
data.platform,
{ ...liveSyncInfo, watch: !liveSyncInfo.skipWatcher },
);
const changesInfo = await this.$projectChangesService.checkForChanges(
platformData,
projectData,
prepareData,
);
if (!changesInfo.hasChanges) {
return;
}
}
this.scheduleSyncOnDevices(data, projectData, liveSyncInfo);
};
this.prepareReadyEventHandler = handler.bind(this);
this.$prepareController.on(
PREPARE_READY_EVENT_NAME,
this.prepareReadyEventHandler,
);
}
await this.syncInitialDataOnDevices(
projectData,
liveSyncInfo,
deviceDescriptorsForInitialSync,
);
this.attachDeviceLostHandler();
}
public async stop(data: IStopRunData): Promise<void> {
const { projectDir, deviceIdentifiers, stopOptions } = data;
const liveSyncProcessInfo =
this.$liveSyncProcessDataService.getPersistedData(projectDir);
if (liveSyncProcessInfo && !liveSyncProcessInfo.isStopped) {
// In case we are coming from error during livesync, the current action is the one that erred (but we are still executing it),
// so we cannot await it as this will cause infinite loop.
const shouldAwaitPendingOperation =
!stopOptions || stopOptions.shouldAwaitAllActions;
const deviceIdentifiersToRemove =
deviceIdentifiers && deviceIdentifiers.length
? deviceIdentifiers
: _.map(liveSyncProcessInfo.deviceDescriptors, (d) => d.identifier);
const removedDeviceIdentifiers = _.remove(
liveSyncProcessInfo.deviceDescriptors,
(descriptor) =>
_.includes(deviceIdentifiersToRemove, descriptor.identifier),
).map((descriptor) => descriptor.identifier);
// Handle the case when no more devices left for any of the persisted platforms
for (let i = 0; i < liveSyncProcessInfo.platforms.length; i++) {
const platform = liveSyncProcessInfo.platforms[i];
const devices = this.$devicesService.getDevicesForPlatform(platform);
if (!devices || !devices.length) {
await this.$prepareController.stopWatchers(projectDir, platform);
}
}
// In case deviceIdentifiers are not passed, we should stop the whole LiveSync.
if (
!deviceIdentifiers ||
!deviceIdentifiers.length ||
!liveSyncProcessInfo.deviceDescriptors ||
!liveSyncProcessInfo.deviceDescriptors.length
) {
if (liveSyncProcessInfo.timer) {
clearTimeout(liveSyncProcessInfo.timer as unknown as number);
}
for (let k = 0; k < liveSyncProcessInfo.platforms.length; k++) {
await this.$prepareController.stopWatchers(
projectDir,
liveSyncProcessInfo.platforms[k],
);
}
liveSyncProcessInfo.isStopped = true;
if (liveSyncProcessInfo.actionsChain && shouldAwaitPendingOperation) {
await liveSyncProcessInfo.actionsChain;
}
liveSyncProcessInfo.deviceDescriptors = [];
if (this.prepareReadyEventHandler) {
this.$prepareController.removeListener(
PREPARE_READY_EVENT_NAME,
this.prepareReadyEventHandler,
);
this.prepareReadyEventHandler = null;
}
const projectData = this.$projectDataService.getProjectData(projectDir);
await this.$hooksService.executeAfterHooks("watch", {
hookArgs: {
projectData,
},
});
} else if (
liveSyncProcessInfo.currentSyncAction &&
shouldAwaitPendingOperation
) {
await liveSyncProcessInfo.currentSyncAction;
}
// Emit RunOnDevice stopped when we've really stopped.
_.each(removedDeviceIdentifiers, (deviceIdentifier) => {
this.emitCore(RunOnDeviceEvents.runOnDeviceStopped, {
projectDir,
deviceIdentifier,
keepProcessAlive: stopOptions?.keepProcessAlive,
});
});
if (stopOptions?.keepProcessAlive) {
this.removeAllListeners(RunOnDeviceEvents.runOnDeviceStopped);
}
}
}
public getDeviceDescriptors(data: {
projectDir: string;
}): ILiveSyncDeviceDescriptor[] {
return this.$liveSyncProcessDataService.getDeviceDescriptors(
data.projectDir,
);
}
protected async refreshApplication(
projectData: IProjectData,
liveSyncResultInfo: ILiveSyncResultInfo,
filesChangeEventData: IFilesChangeEventData,
deviceDescriptor: ILiveSyncDeviceDescriptor,
fullSyncAction?: () => Promise<void>,
): Promise<IRestartApplicationInfo> {
const result = deviceDescriptor.debuggingEnabled
? await this.refreshApplicationWithDebug(
projectData,
liveSyncResultInfo,
filesChangeEventData,
deviceDescriptor,
)
: await this.refreshApplicationWithoutDebug(
projectData,
liveSyncResultInfo,
filesChangeEventData,
deviceDescriptor,
undefined,
fullSyncAction,
);
const device = liveSyncResultInfo.deviceAppData.device;
this.emitCore(RunOnDeviceEvents.runOnDeviceExecuted, {
projectDir: projectData.projectDir,
deviceIdentifier: device.deviceInfo.identifier,
applicationIdentifier:
projectData.projectIdentifiers[
device.deviceInfo.platform.toLowerCase()
],
syncedFiles: liveSyncResultInfo.modifiedFilesData.map((m) =>
m.getLocalPath(),
),
isFullSync: liveSyncResultInfo.isFullSync,
});
return result;
}
protected async refreshApplicationWithDebug(
projectData: IProjectData,
liveSyncResultInfo: ILiveSyncResultInfo,
filesChangeEventData: IFilesChangeEventData,
deviceDescriptor: ILiveSyncDeviceDescriptor,
): Promise<IRestartApplicationInfo> {
const debugOptions = deviceDescriptor.debugOptions || {};
liveSyncResultInfo.waitForDebugger = !!debugOptions.debugBrk;
liveSyncResultInfo.forceRefreshWithSocket = true;
const refreshInfo = await this.refreshApplicationWithoutDebug(
projectData,
liveSyncResultInfo,
filesChangeEventData,
deviceDescriptor,
{
shouldSkipEmitLiveSyncNotification: true,
shouldCheckDeveloperDiscImage: true,
},
);
// we do not stop the application when debugBrk is false, so we need to attach, instead of launch
// if we try to send the launch request, the debugger port will not be printed and the command will timeout
debugOptions.start = !debugOptions.debugBrk;
debugOptions.forceDebuggerAttachedEvent = refreshInfo.didRestart;
await this.$debugController.enableDebuggingCoreWithoutWaitingCurrentAction(
projectData.projectDir,
deviceDescriptor.identifier,
debugOptions,
);
return refreshInfo;
}
@performanceLog()
protected async refreshApplicationWithoutDebug(
projectData: IProjectData,
liveSyncResultInfo: ILiveSyncResultInfo,
filesChangeEventData: IFilesChangeEventData,
deviceDescriptor: ILiveSyncDeviceDescriptor,
settings?: IRefreshApplicationSettings,
fullSyncAction?: () => Promise<void>,
): Promise<IRestartApplicationInfo> {
const result = { didRestart: false };
const platform = liveSyncResultInfo.deviceAppData.platform;
const applicationIdentifier =
projectData.projectIdentifiers[platform.toLowerCase()];
const platformLiveSyncService =
this.$liveSyncServiceResolver.resolveLiveSyncService(platform);
try {
const isFullSync =
filesChangeEventData &&
(filesChangeEventData.hasNativeChanges ||
!filesChangeEventData.hasOnlyHotUpdateFiles);
let shouldRestart = isFullSync;
if (!shouldRestart) {
shouldRestart = await platformLiveSyncService.shouldRestart(
projectData,
liveSyncResultInfo,
);
}
if (!shouldRestart) {
shouldRestart = !(await platformLiveSyncService.tryRefreshApplication(
projectData,
liveSyncResultInfo,
));
}
if (!isFullSync && shouldRestart && fullSyncAction) {
this.$logger.trace(
`Syncing all files as the current app state does not support hot updates.`,
);
liveSyncResultInfo.didRecover = true;
await fullSyncAction();
}
if (shouldRestart) {
this.emit(DEBUGGER_DETACHED_EVENT_NAME, {
deviceIdentifier:
liveSyncResultInfo.deviceAppData.device.deviceInfo.identifier,
});
await platformLiveSyncService.restartApplication(
projectData,
liveSyncResultInfo,
);
result.didRestart = true;
}
} catch (err) {
this.$logger.info(
`Error while trying to start application ${applicationIdentifier} on device ${
liveSyncResultInfo.deviceAppData.device.deviceInfo.identifier
}. Error is: ${err.message || err}`,
);
const msg = `Unable to start application ${applicationIdentifier} on device ${liveSyncResultInfo.deviceAppData.device.deviceInfo.identifier}. Try starting it manually.`;
this.$logger.warn(msg);
const device = liveSyncResultInfo.deviceAppData.device;
const deviceIdentifier = device.deviceInfo.identifier;
if (!settings || !settings.shouldSkipEmitLiveSyncNotification) {
this.emitCore(RunOnDeviceEvents.runOnDeviceNotification, {
projectDir: projectData.projectDir,
deviceIdentifier: device.deviceInfo.identifier,
applicationIdentifier:
projectData.projectIdentifiers[
device.deviceInfo.platform.toLowerCase()
],
notification: msg,
});
}
if (
settings &&
settings.shouldCheckDeveloperDiscImage &&
(err.message || err) === "Could not find developer disk image"
) {
const attachDebuggerOptions: IAttachDebuggerData = {
platform: device.deviceInfo.platform,
isEmulator: device.isEmulator,
projectDir: projectData.projectDir,
deviceIdentifier,
debugOptions: deviceDescriptor.debugOptions,
outputPath: deviceDescriptor.buildData.outputPath,
};
this.emit(USER_INTERACTION_NEEDED_EVENT_NAME, attachDebuggerOptions);
}
}
return result;
}
private getDeviceDescriptorsForInitialSync(
projectDir: string,
deviceDescriptors: ILiveSyncDeviceDescriptor[],
) {
const currentRunData =
this.$liveSyncProcessDataService.getPersistedData(projectDir);
const isAlreadyLiveSyncing = currentRunData && !currentRunData.isStopped;
// Prevent cases where liveSync is called consecutive times with the same device, for example [ A, B, C ] and then [ A, B, D ] - we want to execute initialSync only for D.
const deviceDescriptorsForInitialSync = isAlreadyLiveSyncing
? _.differenceBy(
deviceDescriptors,
currentRunData.deviceDescriptors,
"identifier",
)
: deviceDescriptors;
return deviceDescriptorsForInitialSync;
}
private async initializeSetup(projectData: IProjectData): Promise<void> {
try {
await this.$pluginsService.ensureAllDependenciesAreInstalled(projectData);
} catch (err) {
this.$logger.trace(err);
this.$errors.fail(
`Unable to install dependencies. Make sure your package.json is valid and all dependencies are correct. Error is: ${err.message}`,
);
}
}
@cache()
private attachDeviceLostHandler(): void {
this.$devicesService.on(
DeviceDiscoveryEventNames.DEVICE_LOST,
async (device: Mobile.IDevice) => {
this.$logger.trace(
`Received ${DeviceDiscoveryEventNames.DEVICE_LOST} event in LiveSync service for ${device.deviceInfo.identifier}. Will stop LiveSync operation for this device.`,
);
for (const projectDir in this.$liveSyncProcessDataService.getAllPersistedData()) {
try {
const deviceDescriptors = this.getDeviceDescriptors({ projectDir });
if (
_.find(
deviceDescriptors,
(d) => d.identifier === device.deviceInfo.identifier,
)
) {
await this.stop({
projectDir,
deviceIdentifiers: [device.deviceInfo.identifier],
});
}
} catch (err) {
this.$logger.warn(
`Unable to stop LiveSync operation for ${device.deviceInfo.identifier}.`,
err,
);
}
}
},
);
}
private async syncInitialDataOnDevices(
projectData: IProjectData,
liveSyncInfo: ILiveSyncInfo,
deviceDescriptors: ILiveSyncDeviceDescriptor[],
): Promise<void> {
const rebuiltInformation: IDictionary<{
packageFilePath: string;
platform: string;
isEmulator: boolean;
}> = {};
const deviceAction = async (device: Mobile.IDevice) => {
const deviceDescriptor = _.find(
deviceDescriptors,
(dd) => dd.identifier === device.deviceInfo.identifier,
);
const prepareData = this.$prepareDataService.getPrepareData(
liveSyncInfo.projectDir,
device.deviceInfo.platform,
{
...liveSyncInfo,
...deviceDescriptor.buildData,
nativePrepare: {
skipNativePrepare: !!deviceDescriptor.skipNativePrepare,
},
watch: !liveSyncInfo.skipWatcher,
},
);
// For Android + Vite HMR, own the `adb reverse` ourselves —
// with our SDK-resolved adb, scoped to this exact serial, and
// only after the device is up — then hand the bundler the
// result via env vars. This MUST run before `prepare` (which
// spawns the Vite bundler that inherits `process.env`) so the
// bundler trusts the tunnel instead of racing us to spawn its
// own adb during config-load. See packages/vite hardening.
await this.setupAndroidViteHmrReverse(
device,
projectData,
liveSyncInfo,
"pre-build",
);
const prepareResultData =
await this.$prepareController.prepare(prepareData);
const buildData = {
...deviceDescriptor.buildData,
buildForDevice: !device.isEmulator,
};
const platformData = this.$platformsDataService.getPlatformData(
device.deviceInfo.platform,
projectData,
);
try {
let packageFilePath: string = null;
// Case where we have three devices attached, a change that requires build is found,
// we'll rebuild the app only for the first device, but we should install new package on all three devices.
if (
rebuiltInformation[platformData.platformNameLowerCase] &&
(this.$mobileHelper.isAndroidPlatform(
platformData.platformNameLowerCase,
) ||
rebuiltInformation[platformData.platformNameLowerCase]
.isEmulator === device.isEmulator)
) {
packageFilePath =
rebuiltInformation[platformData.platformNameLowerCase]
.packageFilePath;
await this.$deviceInstallAppService.installOnDevice(
device,
buildData,
packageFilePath,
);
} else {
const shouldBuild =
prepareResultData.hasNativeChanges ||
buildData.nativePrepare.forceRebuildNativeApp ||
(await this.$buildController.shouldBuild(buildData));
if (shouldBuild) {
packageFilePath = await deviceDescriptor.buildAction();
rebuiltInformation[platformData.platformNameLowerCase] = {
isEmulator: device.isEmulator,
platform: platformData.platformNameLowerCase,
packageFilePath,
};
} else {
await this.$analyticsService.trackEventActionInGoogleAnalytics({
action: TrackActionNames.LiveSync,
device,
projectDir: projectData.projectDir,
});
}
await this.$deviceInstallAppService.installOnDeviceIfNeeded(
device,
buildData,
packageFilePath,
);
}
const platformLiveSyncService =
this.$liveSyncServiceResolver.resolveLiveSyncService(
platformData.platformNameLowerCase,
);
const { force, useHotModuleReload, skipWatcher } = liveSyncInfo;
const liveSyncResultInfo = await platformLiveSyncService.fullSync({
force,
useHotModuleReload,
projectData,
device,
watch: !skipWatcher,
liveSyncDeviceData: deviceDescriptor,
});
// Re-establish the adb reverse on the CURRENT transport right
// before launch — the transport can change during build/install
// and drop the mapping set in `pre-build`, which would leave the
// app unable to reach the Vite dev server at 127.0.0.1.
await this.setupAndroidViteHmrReverse(
device,
projectData,
liveSyncInfo,
"pre-launch",
);
await this.refreshApplication(
projectData,
liveSyncResultInfo,
null,
deviceDescriptor,
);
this.$logger.info(
`Successfully synced application ${liveSyncResultInfo.deviceAppData.appIdentifier} on device ${liveSyncResultInfo.deviceAppData.device.deviceInfo.identifier}.`,
);
this.emitCore(RunOnDeviceEvents.runOnDeviceStarted, {
projectDir: projectData.projectDir,
deviceIdentifier: device.deviceInfo.identifier,
applicationIdentifier:
projectData.projectIdentifiers[
device.deviceInfo.platform.toLowerCase()
],
});
} catch (err) {
this.$logger.warn(
`Unable to apply changes on device: ${device.deviceInfo.identifier}. Error is: ${err.message}.`,
);
this.$logger.trace(err);
this.emitCore(RunOnDeviceEvents.runOnDeviceError, {
projectDir: projectData.projectDir,
deviceIdentifier: device.deviceInfo.identifier,
applicationIdentifier:
projectData.projectIdentifiers[
device.deviceInfo.platform.toLowerCase()
],
error: err,
});
await this.stop({
projectDir: projectData.projectDir,
deviceIdentifiers: [device.deviceInfo.identifier],
stopOptions: { shouldAwaitAllActions: false },
});
}
};
await this.addActionToChain(projectData.projectDir, () =>
this.$devicesService.execute(deviceAction, (device: Mobile.IDevice) =>
_.some(
deviceDescriptors,
(deviceDescriptor) =>
deviceDescriptor.identifier === device.deviceInfo.identifier,
),
),
);
}
/**
* Set up `adb reverse tcp:<port> tcp:<port>` for an Android device
* when the project bundles with Vite in HMR/watch mode, then export
* the result to the bundler subprocess via environment variables.
*
* The Vite dev-host helper prefers an ADB tunnel (device-side
* `127.0.0.1:<port>` → host) over the emulator's flaky slirp NAT
* (`10.0.2.2`). Historically the bundler tried to wire that tunnel
* itself at config-load time, racing this CLI's device discovery
* over the single global adb daemon and intermittently freezing the
* run at "Searching for devices…". The CLI is the right owner: it
* knows the exact target serial and when the device is ready, and it
* already drives a single, version-matched adb. We do the reverse
* here and signal the bundler with `NS_ADB_REVERSE_READY=1` so it
* never spawns adb on its own.
*
* Best-effort: any failure is logged at trace level and swallowed.
* The bundler then falls back to its own (now hardened) adb path, or
* ultimately to `10.0.2.2`, so a reverse hiccup never fails the run.
*/
private async setupAndroidViteHmrReverse(
device: Mobile.IDevice,
projectData: IProjectData,
liveSyncInfo: ILiveSyncInfo,
phase: "pre-build" | "pre-launch",
): Promise<void> {
try {
if (!this.$mobileHelper.isAndroidPlatform(device.deviceInfo.platform)) {
return;
}
if (projectData.bundler !== "vite") {
return;
}
// HMR over the tunnel only matters for a live watch session.
if (liveSyncInfo.skipWatcher || !liveSyncInfo.useHotModuleReload) {
return;
}
// Respect the user's explicit opt-out — they want the
// `10.0.2.2` / LAN path, so don't create a tunnel or claim one
// exists.
if (this.isTruthyEnvFlag(process.env.NS_HMR_NO_ADB_REVERSE)) {
return;
}
// `NS_HMR_PREFER_LAN_HOST` means the dev wants LAN routing
// (physical device over Wi-Fi); the dev-host resolver suppresses
// the adb-reverse path for it, so don't bother wiring one.
if (this.isTruthyEnvFlag(process.env.NS_HMR_PREFER_LAN_HOST)) {
return;
}
const serial = device.deviceInfo.identifier;
const port = this.getViteHmrPort();
if (phase === "pre-build") {
// Decide the origin baked into bundle.mjs. Hand the bundler our
// exact adb (so any self-managed fallback can't version-mismatch
// the daemon) and, if the tunnel comes up, tell it to emit
// `127.0.0.1` and skip adb entirely.
process.env.NS_ADB_PATH = await this.$staticConfig.getAdbFilePath();
process.env.NS_DEVICE_SERIAL = serial;
const ok = await this.ensureAndroidReverse(device, serial, port);
if (ok) {
process.env.NS_ADB_REVERSE_READY = "1";
this.$logger.info(
`Set up adb reverse tcp:${port} tcp:${port} for ${serial} (Vite HMR routes device-side 127.0.0.1:${port} through ADB).`,
);
} else {
this.$logger.warn(
`Could not confirm 'adb reverse tcp:${port}' on ${serial} (device adbd slow/unresponsive). Vite HMR will fall back to 10.0.2.2. If this persists, cold-boot/wipe the emulator, or set NS_HMR_NO_ADB_REVERSE=1.`,
);
}
return;
}
// phase === "pre-launch": re-establish the mapping right before the
// app boots. `adb reverse` mappings are bound to the device's adb
// transport, and that transport can change during the (long) build
// + install (fresh emulators reconnect as they settle), silently
// dropping the early mapping. We only bother when we actually told
// the bundle to use `127.0.0.1` (READY set during pre-build).
if (!this.isTruthyEnvFlag(process.env.NS_ADB_REVERSE_READY)) {
return;
}
const ok = await this.ensureAndroidReverse(device, serial, port);
if (!ok) {
this.$logger.warn(
`adb reverse tcp:${port} was not active before launch on ${serial}; the app may fail to reach the Vite dev server at 127.0.0.1:${port}.`,
);
}
} catch (err) {
this.$logger.trace(
`Setting up adb reverse for Vite HMR (${phase}) failed; leaving it to the bundler fallback. Error: ${err}`,
);
}
}
/**
* Apply `adb reverse tcp:<port> tcp:<port>` to the device and confirm
* via `adb reverse --list` that it actually landed, retrying a few
* times. Every device-side call is bounded with a Node `spawn` timeout
* + `SIGKILL` so a wedged/slow adbd (observed blocking 90s+ on some
* fresh-boot / API-36 arm64 emulators) can never hang the run — the
* hung adb child is reaped, not orphaned. Returns whether the mapping
* is confirmed present.
*/
private async ensureAndroidReverse(
device: Mobile.IDevice,
serial: string,
port: number,
): Promise<boolean> {
const adb = (device as Mobile.IAndroidDevice).adb;
const ADB_WAIT_MS = 15000;
const ADB_REVERSE_MS = 20000;
const bounded = (timeout: number) => ({
deviceIdentifier: serial,
treatErrorsAsWarnings: true,
childProcessOptions: { timeout, killSignal: "SIGKILL" },
});
// `wait-for-device` only blocks until the transport is up; bounded so a
// never-ready device can't stall us.
await adb.executeCommand(["wait-for-device"], bounded(ADB_WAIT_MS));
for (let attempt = 1; attempt <= 3; attempt++) {
await adb.executeCommand(
["reverse", `tcp:${port}`, `tcp:${port}`],
bounded(ADB_REVERSE_MS),
);
// Verify it landed (a SIGKILL'd-on-timeout reverse resolves rather
// than throws, so success of the call isn't proof).
const list =
(
await adb.executeCommand(["reverse", "--list"], bounded(ADB_WAIT_MS))
)?.toString?.() ?? "";
if (list.includes(`tcp:${port}`)) {
return true;
}
}
return false;
}
private getViteHmrPort(): number {
// The Vite dev server defaults to 5173; the bundler reads the same
// default. If a project runs Vite on a different port, the dev sets
// `NS_HMR_PORT` so the CLI reverses the matching port.
const fromEnv = Number(process.env.NS_HMR_PORT);
return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : 5173;
}
private isTruthyEnvFlag(value: string | undefined): boolean {
if (typeof value !== "string") {
return false;
}
const v = value.trim().toLowerCase();
return !!v && v !== "0" && v !== "false" && v !== "off" && v !== "no";
}
private async syncChangedDataOnDevices(
data: IFilesChangeEventData,
projectData: IProjectData,
liveSyncInfo: ILiveSyncInfo,
): Promise<void> {
const successfullySyncedMessageFormat = `Successfully synced application %s on device %s.`;
const rebuiltInformation: IDictionary<{
packageFilePath: string;
platform: string;
isEmulator: boolean;
}> = {};
const deviceAction = async (device: Mobile.IDevice) => {
const deviceDescriptors =
this.$liveSyncProcessDataService.getDeviceDescriptors(
projectData.projectDir,
);
const deviceDescriptor = _.find(
deviceDescriptors,
(dd) => dd.identifier === device.deviceInfo.identifier,
);
const platformData = this.$platformsDataService.getPlatformData(
data.platform,
projectData,
);
const prepareData = this.$prepareDataService.getPrepareData(
liveSyncInfo.projectDir,
device.deviceInfo.platform,
{
...liveSyncInfo,
...deviceDescriptor.buildData,
nativePrepare: {
skipNativePrepare: !!deviceDescriptor.skipNativePrepare,
},
watch: !liveSyncInfo.skipWatcher,
},
);
try {
const platformLiveSyncService =
this.$liveSyncServiceResolver.resolveLiveSyncService(
device.deviceInfo.platform,
);
const allAppFiles = data.hmrData?.fallbackFiles?.length
? data.hmrData.fallbackFiles
: data.files;
const filesToSync = data.hasOnlyHotUpdateFiles
? data.files
: allAppFiles;
const watchInfo = {
liveSyncDeviceData: deviceDescriptor,
projectData,
// todo: remove stale files once everything is stable
// currently, watcher fires multiple times & may clean up unsynced files
// filesToRemove: data.staleFiles ?? [],
filesToRemove: [] as string[],
filesToSync,
hmrData: data.hmrData,
useHotModuleReload: liveSyncInfo.useHotModuleReload,
force: liveSyncInfo.force,
connectTimeout: 1000,
};
const deviceAppData = await platformLiveSyncService.getAppData(
_.merge({ device, watch: true }, watchInfo),
);
if (data.hasNativeChanges) {
const rebuiltInfo =
rebuiltInformation[platformData.platformNameLowerCase] &&
(this.$mobileHelper.isAndroidPlatform(
platformData.platformNameLowerCase,
) ||
rebuiltInformation[platformData.platformNameLowerCase]
.isEmulator === device.isEmulator);
if (!rebuiltInfo) {
await this.$prepareNativePlatformService.prepareNativePlatform(
platformData,
projectData,
prepareData,
);
await deviceDescriptor.buildAction();
rebuiltInformation[platformData.platformNameLowerCase] = {
isEmulator: device.isEmulator,
platform: platformData.platformNameLowerCase,
packageFilePath: null,
};
}
await this.$deviceInstallAppService.installOnDevice(
device,
deviceDescriptor.buildData,
rebuiltInformation[platformData.platformNameLowerCase]
.packageFilePath,
);
await platformLiveSyncService.syncAfterInstall(device, watchInfo);
await this.refreshApplication(
projectData,
{
deviceAppData,
modifiedFilesData: [],
isFullSync: false,
useHotModuleReload: liveSyncInfo.useHotModuleReload,
},
data,
deviceDescriptor,
);
this.$logger.info(
util.format(
successfullySyncedMessageFormat,
deviceAppData.appIdentifier,
device.deviceInfo.identifier,
),
);
} else {
const isInHMRMode =
liveSyncInfo.useHotModuleReload &&
data.hmrData &&
data.hmrData.hash;
if (isInHMRMode) {
this.$hmrStatusService.watchHmrStatus(
device.deviceInfo.identifier,
data.hmrData.hash,
);
}
const watchAction = async (): Promise<void> => {
const liveSyncResultInfo =
await platformLiveSyncService.liveSyncWatchAction(
device,
watchInfo,
);
const fullSyncAction = async () => {
watchInfo.filesToSync = allAppFiles;
const fullLiveSyncResultInfo =
await platformLiveSyncService.liveSyncWatchAction(
device,
watchInfo,
);
// IMPORTANT: keep the same instance as we rely on side effects
_.assign(liveSyncResultInfo, fullLiveSyncResultInfo);
};
await this.$hooksService.executeBeforeHooks("watchAction", {
hookArgs: {
liveSyncResultInfo,
filesToSync,
allAppFiles,
isInHMRMode,
filesChangedEvent: data,
},
});
await this.refreshApplication(
projectData,
liveSyncResultInfo,
data,
deviceDescriptor,
fullSyncAction,
);
if (!liveSyncResultInfo.didRecover && isInHMRMode) {
const status = await this.$hmrStatusService.getHmrStatus(
device.deviceInfo.identifier,
data.hmrData.hash,
);
// the timeout is assumed OK as the app could be blocked on a breakpoint
if (status === HmrConstants.HMR_ERROR_STATUS) {
await fullSyncAction();
liveSyncResultInfo.isFullSync = true;
await this.refreshApplication(
projectData,
liveSyncResultInfo,
data,
deviceDescriptor,
);
}
}
await this.$hooksService.executeAfterHooks("watchAction", {
liveSyncResultInfo,
filesToSync,
allAppFiles,
filesChangedEvent: data,
isInHMRMode,
});
this.$logger.info(
util.format(
successfullySyncedMessageFormat,