Skip to content

Commit fb53797

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 100d250 commit fb53797

5 files changed

Lines changed: 53 additions & 47 deletions

File tree

‎lib/bootstrap.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { provideLazy } from "./common/di";
22
import { injector } from "./common/yok";
33
import { registerBuiltInCommand } from "./common/services/command-definition-adapter";
4+
import { IOSDeviceTunnelService } from "./contracts/ios-device-tunnel-service";
45
import type { fontsCommandDefinition } from "./commands/fonts";
56
import { AndroidPluginMirrorService } from "./contracts/internal/android-plugin-mirror-service";
67
import { NativeFileHashesMemo } from "./contracts/internal/native-file-hashes-memo";
@@ -694,9 +695,13 @@ injector.require(
694695
"viteHmrPortService",
695696
"./services/bundler/vite-hmr-port-service",
696697
);
697-
injector.require(
698-
"iOSDeviceTunnelService",
699-
"./services/ios/ios-device-tunnel-service",
698+
injector.register(
699+
provideLazy(
700+
IOSDeviceTunnelService,
701+
(): typeof import("./services/ios/ios-device-tunnel-service").IOSDeviceTunnelServiceImpl =>
702+
require("./services/ios/ios-device-tunnel-service")
703+
.IOSDeviceTunnelServiceImpl,
704+
),
700705
);
701706

702707
injector.require(

‎lib/controllers/run-controller.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,10 @@ import { ViteHmrPortService } from "../contracts/vite-hmr-port-service";
2828
import { IOSDeviceTunnelService } from "../contracts/ios-device-tunnel-service";
2929
import { injector } from "../common/yok";
3030
import { isIOSMacDevice } from "../common/mobile/ios/mac/ios-mac-constants";
31+
import { inject } from "../common/di/inject";
3132

3233
export class RunController extends EventEmitter implements IRunController {
34+
private iOSDeviceTunnelService = inject(IOSDeviceTunnelService);
3335
private prepareReadyEventHandler: any = null;
3436
private appRestartRequestHandler: (
3537
request: IBundlerAppRestartRequest,
@@ -68,7 +70,6 @@ export class RunController extends EventEmitter implements IRunController {
6870
protected $projectDataService: IProjectDataService,
6971
private $staticConfig: Config.IStaticConfig,
7072
private $viteHmrPortService: ViteHmrPortService,
71-
private $iOSDeviceTunnelService: IOSDeviceTunnelService,
7273
) {
7374
super();
7475
}
@@ -171,7 +172,7 @@ export class RunController extends EventEmitter implements IRunController {
171172
).map((descriptor) => descriptor.identifier);
172173

173174
for (const deviceIdentifier of removedDeviceIdentifiers) {
174-
await this.$iOSDeviceTunnelService.close(deviceIdentifier);
175+
await this.iOSDeviceTunnelService.close(deviceIdentifier);
175176
}
176177

177178
// Handle the case when no more devices left for any of the persisted platforms
@@ -898,7 +899,7 @@ export class RunController extends EventEmitter implements IRunController {
898899
return;
899900
}
900901

901-
await this.$iOSDeviceTunnelService.open(device);
902+
await this.iOSDeviceTunnelService.open(device);
902903
}
903904

904905
/**

‎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,
@@ -96,6 +97,7 @@ export class BundlerCompilerService
9697
extends EventEmitter
9798
implements IBundlerCompilerService
9899
{
100+
private iOSDeviceTunnelService = inject(IOSDeviceTunnelService);
99101
private bundlerProcesses: IDictionary<child_process.ChildProcess> = {};
100102
// Vite-only: the long-lived `vite serve` dev server the device fetches
101103
// modules and HMR updates from. Keyed by platform, managed by this CLI
@@ -123,7 +125,6 @@ export class BundlerCompilerService
123125
private $packageInstallationManager: IPackageInstallationManager, // private $sharedEventBus: ISharedEventBus
124126
private $projectConfigService: IProjectConfigService,
125127
private $viteHmrPortService: ViteHmrPortService,
126-
private $iOSDeviceTunnelService: IOSDeviceTunnelService,
127128
) {
128129
super();
129130
}
@@ -867,7 +868,7 @@ export class BundlerCompilerService
867868
env.NS_HMR_PORT = String(
868869
await this.$viteHmrPortService.getPort(platform),
869870
);
870-
const tunnelHost = this.$iOSDeviceTunnelService.getHostAddress(platform);
871+
const tunnelHost = this.iOSDeviceTunnelService.getHostAddress(platform);
871872
if (tunnelHost && !process.env.NS_HMR_HOST) {
872873
env.NS_HMR_HOST = tunnelHost;
873874
}

‎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)