Skip to content

Commit 5256370

Browse files
committed
refactor(ios): build the USB tunnel service on the DI contract
IOSDeviceTunnelServiceImpl extends the IOSDeviceTunnelService contract and injects its dependencies as fields instead of through $-constructor parameters. Bootstrap registers it with provideLazy() under the contract token, replacing injector.require() and the module's self-registration; the contract name keeps string lookups resolving. RunController and BundlerCompilerService inject the contract rather than taking it as a constructor parameter.
1 parent 86e54d9 commit 5256370

5 files changed

Lines changed: 54 additions & 47 deletions

File tree

‎lib/bootstrap.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { injector } from "./common/yok";
2+
import { provideLazy } from "./common/di/providers";
23
import { registerBuiltInCommand } from "./common/services/command-definition-adapter";
4+
import { IOSDeviceTunnelService } from "./contracts/ios-device-tunnel-service";
35
import type { fontsCommandDefinition } from "./commands/fonts";
46

57
require("./common/bootstrap");
@@ -676,9 +678,13 @@ injector.require(
676678
"viteHmrPortService",
677679
"./services/bundler/vite-hmr-port-service",
678680
);
679-
injector.require(
680-
"iOSDeviceTunnelService",
681-
"./services/ios/ios-device-tunnel-service",
681+
injector.register(
682+
provideLazy(
683+
IOSDeviceTunnelService,
684+
(): typeof import("./services/ios/ios-device-tunnel-service").IOSDeviceTunnelServiceImpl =>
685+
require("./services/ios/ios-device-tunnel-service")
686+
.IOSDeviceTunnelServiceImpl,
687+
),
682688
);
683689

684690
injector.require(

‎lib/controllers/run-controller.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,10 @@ import { IInjector } from "../common/definitions/yok";
2727
import { ViteHmrPortService } from "../contracts/vite-hmr-port-service";
2828
import { IOSDeviceTunnelService } from "../contracts/ios-device-tunnel-service";
2929
import { injector } from "../common/yok";
30+
import { inject } from "../common/di/inject";
3031

3132
export class RunController extends EventEmitter implements IRunController {
33+
private iOSDeviceTunnelService = inject(IOSDeviceTunnelService);
3234
private prepareReadyEventHandler: any = null;
3335
private appRestartRequestHandler: (
3436
request: IBundlerAppRestartRequest,
@@ -67,7 +69,6 @@ export class RunController extends EventEmitter implements IRunController {
6769
protected $projectDataService: IProjectDataService,
6870
private $staticConfig: Config.IStaticConfig,
6971
private $viteHmrPortService: ViteHmrPortService,
70-
private $iOSDeviceTunnelService: IOSDeviceTunnelService,
7172
) {
7273
super();
7374
}
@@ -170,7 +171,7 @@ export class RunController extends EventEmitter implements IRunController {
170171
).map((descriptor) => descriptor.identifier);
171172

172173
for (const deviceIdentifier of removedDeviceIdentifiers) {
173-
await this.$iOSDeviceTunnelService.close(deviceIdentifier);
174+
await this.iOSDeviceTunnelService.close(deviceIdentifier);
174175
}
175176

176177
// Handle the case when no more devices left for any of the persisted platforms
@@ -896,7 +897,7 @@ export class RunController extends EventEmitter implements IRunController {
896897
return;
897898
}
898899

899-
await this.$iOSDeviceTunnelService.open(device);
900+
await this.iOSDeviceTunnelService.open(device);
900901
}
901902

902903
/**

‎lib/services/bundler/bundler-compiler-service.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import { ICleanupService } from "../../definitions/cleanup-service";
3737
import { ViteHmrPortService } from "../../contracts/vite-hmr-port-service";
3838
import { IOSDeviceTunnelService } from "../../contracts/ios-device-tunnel-service";
3939
import { injector } from "../../common/yok";
40+
import { inject } from "../../common/di/inject";
4041
import {
4142
resolvePackagePath,
4243
resolvePackageJSONPath,
@@ -95,6 +96,7 @@ export class BundlerCompilerService
9596
extends EventEmitter
9697
implements IBundlerCompilerService
9798
{
99+
private iOSDeviceTunnelService = inject(IOSDeviceTunnelService);
98100
private bundlerProcesses: IDictionary<child_process.ChildProcess> = {};
99101
// Vite-only: the long-lived `vite serve` dev server the device fetches
100102
// modules and HMR updates from. Keyed by platform, managed by this CLI
@@ -122,7 +124,6 @@ export class BundlerCompilerService
122124
private $packageInstallationManager: IPackageInstallationManager, // private $sharedEventBus: ISharedEventBus
123125
private $projectConfigService: IProjectConfigService,
124126
private $viteHmrPortService: ViteHmrPortService,
125-
private $iOSDeviceTunnelService: IOSDeviceTunnelService,
126127
) {
127128
super();
128129
}
@@ -866,7 +867,7 @@ export class BundlerCompilerService
866867
env.NS_HMR_PORT = String(
867868
await this.$viteHmrPortService.getPort(platform),
868869
);
869-
const tunnelHost = this.$iOSDeviceTunnelService.getHostAddress(platform);
870+
const tunnelHost = this.iOSDeviceTunnelService.getHostAddress(platform);
870871
if (tunnelHost && !process.env.NS_HMR_HOST) {
871872
env.NS_HMR_HOST = tunnelHost;
872873
}

‎lib/services/ios/ios-device-tunnel-service.ts‎

Lines changed: 32 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
import * as os from "os";
22
import * as semver from "semver";
3-
import {
4-
IChildProcess,
5-
IDictionary,
6-
IFileSystem,
7-
IHostInfo,
8-
} from "../../common/declarations";
9-
import { injector } from "../../common/yok";
3+
import { IDictionary } from "../../common/declarations";
4+
import { inject } from "../../common/di/inject";
5+
import { ChildProcess } from "../../contracts/child-process";
6+
import { FileSystem } from "../../contracts/file-system";
7+
import { HostInfo } from "../../contracts/host-info";
108
import { IOSDeviceTunnelService } from "../../contracts/ios-device-tunnel-service";
9+
import { Logger } from "../../contracts/logger";
10+
import { TempService } from "../../contracts/temp-service";
1111
import { ICleanupService } from "../../definitions/cleanup-service";
12-
import { ITempService } from "../../definitions/temp-service";
1312
import { DeviceConnectionType } from "../../constants";
1413
import type * as child_process from "child_process";
1514

@@ -29,22 +28,20 @@ interface ITunnel {
2928
closed: boolean;
3029
}
3130

32-
export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService {
31+
export class IOSDeviceTunnelServiceImpl extends IOSDeviceTunnelService {
32+
private childProcess = inject(ChildProcess);
33+
private cleanupService = inject<ICleanupService>("cleanupService");
34+
private fs = inject(FileSystem);
35+
private hostInfo = inject(HostInfo);
36+
private logger = inject(Logger);
37+
private mobileHelper = inject<Mobile.IMobileHelper>("mobileHelper");
38+
private tempService = inject(TempService);
39+
3340
private tunnels: IDictionary<ITunnel> = {};
3441
private hostAddresses: IDictionary<string> = {};
3542
private tunnelReadyTimeoutMs = 10000;
3643
private tunnelPollIntervalMs = 500;
3744

38-
constructor(
39-
private $childProcess: IChildProcess,
40-
private $cleanupService: ICleanupService,
41-
private $fs: IFileSystem,
42-
private $hostInfo: IHostInfo,
43-
private $logger: ILogger,
44-
private $mobileHelper: Mobile.IMobileHelper,
45-
private $tempService: ITempService,
46-
) {}
47-
4845
public open(device: Mobile.IDevice): Promise<string | null> {
4946
const id = device.deviceInfo.identifier;
5047
if (!this.tunnels[id]) {
@@ -55,7 +52,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService {
5552
};
5653
this.tunnels[id] = tunnel;
5754
tunnel.address = this.openCore(device, tunnel).catch((err): null => {
58-
this.$logger.trace(`Unable to open the USB tunnel to ${id}: ${err}`);
55+
this.logger.trace(`Unable to open the USB tunnel to ${id}: ${err}`);
5956
this.stopHolder(tunnel);
6057
return null;
6158
});
@@ -88,17 +85,17 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService {
8885
const id = device.deviceInfo.identifier;
8986
const ineligible = this.getIneligibilityReason(device);
9087
if (ineligible) {
91-
this.$logger.trace(`Not using a USB tunnel for ${id}: ${ineligible}.`);
88+
this.logger.trace(`Not using a USB tunnel for ${id}: ${ineligible}.`);
9289
return null;
9390
}
9491

95-
const jsonPath = await this.$tempService.path({
92+
const jsonPath = await this.tempService.path({
9693
prefix: "ns-devicectl-",
9794
suffix: ".json",
9895
});
9996
const connection = await this.getConnection(id, jsonPath);
10097
if (connection?.transportType !== "wired") {
101-
this.$logger.trace(
98+
this.logger.trace(
10299
`Not using a USB tunnel for ${id}: devicectl reports ${connection ? `transport ${connection.transportType}` : "no such device"}.`,
103100
);
104101
return null;
@@ -109,7 +106,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService {
109106
const hostAddress =
110107
deviceAddress && this.findLocalTunnelAddress(deviceAddress);
111108
if (!hostAddress) {
112-
this.$logger.trace(
109+
this.logger.trace(
113110
`Not using a USB tunnel for ${id}: ${deviceAddress ? `no local address on the tunnel to ${deviceAddress}` : "the tunnel did not come up"}.`,
114111
);
115112
this.stopHolder(tunnel);
@@ -120,15 +117,15 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService {
120117
}
121118

122119
this.hostAddresses[tunnel.platform] = hostAddress;
123-
this.$logger.info(
120+
this.logger.info(
124121
`Using the USB tunnel to ${device.deviceInfo.displayName} (Mac address ${hostAddress}) for the Vite dev server.`,
125122
);
126123
return hostAddress;
127124
}
128125

129126
private getIneligibilityReason(device: Mobile.IDevice): string | null {
130127
const { deviceInfo } = device;
131-
if (!this.$hostInfo.isDarwin) {
128+
if (!this.hostInfo.isDarwin) {
132129
return "not on macOS";
133130
}
134131
if (device.isEmulator) {
@@ -139,7 +136,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService {
139136
}
140137
const version = semver.coerce(deviceInfo.version);
141138
if (
142-
this.$mobileHelper.isiOSPlatform(deviceInfo.platform) &&
139+
this.mobileHelper.isiOSPlatform(deviceInfo.platform) &&
143140
(!version || semver.major(version) < 17)
144141
) {
145142
return `iOS ${deviceInfo.version} has no CoreDevice tunnel`;
@@ -151,18 +148,18 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService {
151148
deviceIdentifier: string,
152149
jsonPath: string,
153150
): Promise<ICoreDeviceConnection | null> {
154-
const result = await this.$childProcess.trySpawnFromCloseEvent("xcrun", [
151+
const result = await this.childProcess.trySpawnFromCloseEvent("xcrun", [
155152
"devicectl",
156153
"list",
157154
"devices",
158155
"--quiet",
159156
"--json-output",
160157
jsonPath,
161158
]);
162-
if (result.exitCode !== 0 || !this.$fs.exists(jsonPath)) {
159+
if (result.exitCode !== 0 || !this.fs.exists(jsonPath)) {
163160
return null;
164161
}
165-
const devices: any[] = this.$fs.readJson(jsonPath)?.result?.devices || [];
162+
const devices: any[] = this.fs.readJson(jsonPath)?.result?.devices || [];
166163
const match = devices.find(
167164
(d) => d?.hardwareProperties?.udid === deviceIdentifier,
168165
);
@@ -173,7 +170,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService {
173170
deviceIdentifier: string,
174171
tunnel: ITunnel,
175172
): child_process.ChildProcess {
176-
const holder = this.$childProcess.spawn(
173+
const holder = this.childProcess.spawn(
177174
"xcrun",
178175
[
179176
"devicectl",
@@ -193,26 +190,26 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService {
193190
{ stdio: "ignore" },
194191
);
195192
holder.on("error", (err: Error) =>
196-
this.$logger.trace(`USB tunnel holder for ${deviceIdentifier}: ${err}`),
193+
this.logger.trace(`USB tunnel holder for ${deviceIdentifier}: ${err}`),
197194
);
198195
holder.once("exit", () => {
199196
if (holder.pid) {
200-
this.$cleanupService.removeKillProcess(holder.pid.toString());
197+
this.cleanupService.removeKillProcess(holder.pid.toString());
201198
}
202199
if (tunnel.closed || tunnel.holder !== holder) {
203200
return;
204201
}
205202
tunnel.holder = undefined;
206203
tunnel.address.then((address) => {
207204
if (address && !tunnel.closed) {
208-
this.$logger.warn(
205+
this.logger.warn(
209206
`The USB tunnel to ${deviceIdentifier} closed, so the app can no longer reach the Vite dev server at ${address}. Restart the run to reconnect.`,
210207
);
211208
}
212209
});
213210
});
214211
if (holder.pid) {
215-
this.$cleanupService.addKillProcess(holder.pid.toString());
212+
this.cleanupService.addKillProcess(holder.pid.toString());
216213
}
217214
return holder;
218215
}
@@ -308,5 +305,3 @@ function parseIPv6(address: string): number[] | null {
308305
? groups
309306
: null;
310307
}
311-
312-
injector.register("iOSDeviceTunnelService", IOSDeviceTunnelServiceImpl);

‎test/services/ios/ios-device-tunnel-service.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@ import { assert } from "chai";
22
import { EventEmitter } from "events";
33
import { Yok } from "../../../lib/common/yok";
44
import { IInjector } from "../../../lib/common/definitions/yok";
5+
import { provide } from "../../../lib/common/di";
56
import { MobileHelper } from "../../../lib/common/mobile/mobile-helper";
67
import { DevicePlatformsConstants } from "../../../lib/common/mobile/device-platforms-constants";
78
import { DeviceConnectionType } from "../../../lib/constants";
9+
import { IOSDeviceTunnelService } from "../../../lib/contracts/ios-device-tunnel-service";
810
import { IOSDeviceTunnelServiceImpl } from "../../../lib/services/ios/ios-device-tunnel-service";
911
import { ErrorsStub, LoggerStub, TempServiceStub } from "../../stubs";
1012

@@ -149,9 +151,11 @@ describe("IOSDeviceTunnelService", () => {
149151
injector.register("devicePlatformsConstants", DevicePlatformsConstants);
150152
injector.register("mobileHelper", MobileHelper);
151153
injector.register("tempService", TempServiceStub);
152-
injector.register("iOSDeviceTunnelService", IOSDeviceTunnelServiceImpl);
154+
injector.register(
155+
provide(IOSDeviceTunnelService, IOSDeviceTunnelServiceImpl),
156+
);
153157

154-
service = injector.resolve("iOSDeviceTunnelService");
158+
service = <IOSDeviceTunnelServiceImpl>injector.get(IOSDeviceTunnelService);
155159
(<any>service).tunnelReadyTimeoutMs = 200;
156160
(<any>service).tunnelPollIntervalMs = 1;
157161
(<any>service).getNetworkInterfaces = () => macInterfaces;

0 commit comments

Comments
 (0)