From 00889942d296cce2d63d8b42862da9957234f4d0 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 05:22:03 -0300 Subject: [PATCH 1/4] feat(ios): serve Vite dev over the USB CoreDevice tunnel A USB-connected iOS 17+ / visionOS device reaches the Mac over a CoreDevice tunnel (a utun with an fdXX::/64 ULA pair) without Wi-Fi and without the Local Network prompt. The tunnel only exists while a client holds it, and every new tunnel gets a new address. For a Vite HMR session whose only target of a platform is such a device, the run controller now opens the tunnel before prepare: it holds it with `devicectl device notification observe` for the session, reads the device's end from `devicectl list devices`, and takes the Mac's address in the same subnet from the local interfaces. The bundler passes that address to both Vite children as NS_HMR_HOST, so bundle.mjs and the dev server use the tunnel origin. The holder is killed when the device leaves the session or the CLI exits; if it dies on its own the CLI warns that the app lost the dev server. Only an @nativescript/vite that lists the platform under nativescriptCli.singleProcessDev gets the tunnel: older releases bind the dev server to NS_HMR_HOST and put an IPv6 literal into URLs unbracketed. A user-set NS_HMR_HOST, simulators, Wi-Fi or network-paired devices, iOS < 17, a missing devicectl, a tunnel that does not come up and sessions with more than one device of the platform also keep the LAN host from @nativescript/vite, with one trace line. --- lib/bootstrap.ts | 4 + lib/contracts/index.ts | 1 + lib/contracts/ios-device-tunnel-service.ts | 25 ++ lib/controllers/run-controller.ts | 71 ++++ .../bundler/bundler-compiler-service.ts | 33 +- lib/services/bundler/bundler.ts | 5 + lib/services/ios/ios-device-tunnel-service.ts | 312 ++++++++++++++++++ test/contracts.ts | 2 + test/controllers/run-controller.ts | 148 +++++++++ .../bundler/bundler-compiler-service.ts | 70 ++++ .../services/ios/ios-device-tunnel-service.ts | 282 ++++++++++++++++ 11 files changed, 950 insertions(+), 3 deletions(-) create mode 100644 lib/contracts/ios-device-tunnel-service.ts create mode 100644 lib/services/ios/ios-device-tunnel-service.ts create mode 100644 test/services/ios/ios-device-tunnel-service.ts diff --git a/lib/bootstrap.ts b/lib/bootstrap.ts index 154a325910..21481063a2 100644 --- a/lib/bootstrap.ts +++ b/lib/bootstrap.ts @@ -676,6 +676,10 @@ injector.require( "viteHmrPortService", "./services/bundler/vite-hmr-port-service", ); +injector.require( + "iOSDeviceTunnelService", + "./services/ios/ios-device-tunnel-service", +); injector.require( "applePortalSessionService", diff --git a/lib/contracts/index.ts b/lib/contracts/index.ts index 1c9bcf72f1..f2ee7df42f 100644 --- a/lib/contracts/index.ts +++ b/lib/contracts/index.ts @@ -42,6 +42,7 @@ export { Errors } from "./errors"; export { FileSystem } from "./file-system"; export { HostInfo } from "./host-info"; export { HttpClient } from "./http-client"; +export { IOSDeviceTunnelService } from "./ios-device-tunnel-service"; export { Logger } from "./logger"; export { PackageManager } from "./package-manager"; export { ProjectData } from "./project-data"; diff --git a/lib/contracts/ios-device-tunnel-service.ts b/lib/contracts/ios-device-tunnel-service.ts new file mode 100644 index 0000000000..099b14f5ed --- /dev/null +++ b/lib/contracts/ios-device-tunnel-service.ts @@ -0,0 +1,25 @@ +import { Contract } from "../common/di/contract"; + +/** + * Holds the CoreDevice tunnel of a USB-connected iOS 17+ / visionOS device + * so an app can reach the Vite dev server on the Mac over the cable, without + * Wi-Fi or the Local Network prompt. + */ +@Contract({ name: "iOSDeviceTunnelService" }) +export abstract class IOSDeviceTunnelService { + /** + * Opens the device's CoreDevice tunnel and keeps it up until `close` or + * the CLI exits. Resolves the Mac's address on the tunnel, or null when + * the device has no usable USB tunnel. A tunnel gets a new address every + * time it is re-established. + */ + abstract open(device: Mobile.IDevice): Promise; + + /** + * The Mac's tunnel address for the single device of `platform` that has + * an open tunnel, if any. + */ + abstract getHostAddress(platform: string): string | undefined; + + abstract close(deviceIdentifier: string): Promise; +} diff --git a/lib/controllers/run-controller.ts b/lib/controllers/run-controller.ts index c92302a224..8b4695d93a 100644 --- a/lib/controllers/run-controller.ts +++ b/lib/controllers/run-controller.ts @@ -25,6 +25,7 @@ import { } from "../common/declarations"; import { IInjector } from "../common/definitions/yok"; import { ViteHmrPortService } from "../contracts/vite-hmr-port-service"; +import { IOSDeviceTunnelService } from "../contracts/ios-device-tunnel-service"; import { injector } from "../common/yok"; export class RunController extends EventEmitter implements IRunController { @@ -66,6 +67,7 @@ export class RunController extends EventEmitter implements IRunController { protected $projectDataService: IProjectDataService, private $staticConfig: Config.IStaticConfig, private $viteHmrPortService: ViteHmrPortService, + private $iOSDeviceTunnelService: IOSDeviceTunnelService, ) { super(); } @@ -167,6 +169,10 @@ export class RunController extends EventEmitter implements IRunController { _.includes(deviceIdentifiersToRemove, descriptor.identifier), ).map((descriptor) => descriptor.identifier); + for (const deviceIdentifier of removedDeviceIdentifiers) { + await this.$iOSDeviceTunnelService.close(deviceIdentifier); + } + // Handle the case when no more devices left for any of the persisted platforms for (let i = 0; i < liveSyncProcessInfo.platforms.length; i++) { @@ -647,6 +653,13 @@ export class RunController extends EventEmitter implements IRunController { platform: string; isEmulator: boolean; }> = {}; + // Snapshot before any device action: a device whose sync fails leaves + // the session but must still count as a target of its platform. + const sessionDeviceDescriptors = [ + ...this.$liveSyncProcessDataService.getDeviceDescriptors( + projectData.projectDir, + ), + ]; const deviceAction = async (device: Mobile.IDevice) => { const deviceDescriptor = _.find( @@ -679,6 +692,12 @@ export class RunController extends EventEmitter implements IRunController { liveSyncInfo, "pre-build", ); + await this.openIOSViteHmrTunnel( + device, + projectData, + liveSyncInfo, + sessionDeviceDescriptors, + ); const prepareResultData = await this.$prepareController.prepare(prepareData); @@ -819,6 +838,58 @@ export class RunController extends EventEmitter implements IRunController { ); } + /** + * Serves Vite HMR to a USB-connected iOS / visionOS device over its + * CoreDevice tunnel. One dev server bakes one origin into `bundle.mjs` + * and a tunnel address is reachable only from its own device, so this + * applies only when the device is the session's only target of its + * platform. Must run before `prepare` spawns the Vite children. + */ + private async openIOSViteHmrTunnel( + device: Mobile.IDevice, + projectData: IProjectData, + liveSyncInfo: ILiveSyncInfo, + sessionDeviceDescriptors: ILiveSyncDeviceDescriptor[], + ): Promise { + const { platform, identifier } = device.deviceInfo; + if ( + !this.$mobileHelper.isApplePlatform(platform) || + projectData.bundler !== "vite" || + liveSyncInfo.skipWatcher || + !liveSyncInfo.useHotModuleReload || + liveSyncInfo.release || + process.env.NS_HMR_HOST + ) { + return; + } + if ( + !this.$bundlerCompilerService.acceptsIPv6DevHost(platform, projectData) + ) { + this.$logger.trace( + `Not using a USB tunnel for ${identifier}: the installed @nativescript/vite does not accept an IPv6 dev host.`, + ); + return; + } + + const platformTargets = sessionDeviceDescriptors.filter((descriptor) => { + const target = this.$devicesService.getDeviceByIdentifier( + descriptor.identifier, + ); + return ( + !target || + target.deviceInfo.platform.toLowerCase() === platform.toLowerCase() + ); + }); + if (platformTargets.length !== 1) { + this.$logger.trace( + `Not using a USB tunnel for ${identifier}: the session has ${platformTargets.length} ${platform} targets.`, + ); + return; + } + + await this.$iOSDeviceTunnelService.open(device); + } + /** * Set up `adb reverse tcp: tcp:` for an Android device * when the project bundles with Vite in HMR/watch mode, then export diff --git a/lib/services/bundler/bundler-compiler-service.ts b/lib/services/bundler/bundler-compiler-service.ts index 3914be69a2..aaa1066a56 100644 --- a/lib/services/bundler/bundler-compiler-service.ts +++ b/lib/services/bundler/bundler-compiler-service.ts @@ -35,6 +35,7 @@ import { } from "../../common/declarations"; import { ICleanupService } from "../../definitions/cleanup-service"; import { ViteHmrPortService } from "../../contracts/vite-hmr-port-service"; +import { IOSDeviceTunnelService } from "../../contracts/ios-device-tunnel-service"; import { injector } from "../../common/yok"; import { resolvePackagePath, @@ -121,6 +122,7 @@ export class BundlerCompilerService private $packageInstallationManager: IPackageInstallationManager, // private $sharedEventBus: ISharedEventBus private $projectConfigService: IProjectConfigService, private $viteHmrPortService: ViteHmrPortService, + private $iOSDeviceTunnelService: IOSDeviceTunnelService, ) { super(); } @@ -795,19 +797,38 @@ export class BundlerCompilerService if (process.env[VITE_SINGLE_PROCESS_ENV] === "0") { return false; } + return this.getViteSingleProcessPlatforms(projectData).includes(platform); + } + + /** + * Older `@nativescript/vite` releases bind the dev server to + * `NS_HMR_HOST` and put an IPv6 literal into URLs unbracketed. The fix + * shipped together with single-process dev, so its platform list is the + * capability marker. + */ + public acceptsIPv6DevHost( + platform: string, + projectData: IProjectData, + ): boolean { + return this.getViteSingleProcessPlatforms(projectData).includes( + platform.toLowerCase(), + ); + } + + private getViteSingleProcessPlatforms(projectData: IProjectData): string[] { try { const packageJSONPath = resolvePackageJSONPath( this.getBundlerPackageName(), { paths: [projectData.projectDir] }, ); if (!packageJSONPath) { - return false; + return []; } const platforms = this.$fs.readJson(packageJSONPath)?.nativescriptCli?.singleProcessDev; - return Array.isArray(platforms) && platforms.includes(platform); + return Array.isArray(platforms) ? platforms : []; } catch { - return false; + return []; } } @@ -831,6 +852,8 @@ export class BundlerCompilerService * sessions — the dev-server port. The port is resolved here, once, and * handed to `@nativescript/vite` as `NS_HMR_PORT`, so the URLs baked into * `bundle.mjs`, the server's bind and the `adb reverse` tunnel all match. + * When the platform's only device has a USB tunnel open, its Mac address + * becomes `NS_HMR_HOST`, unless the user set one. */ private async getViteChildEnv( platform: string, @@ -843,6 +866,10 @@ export class BundlerCompilerService env.NS_HMR_PORT = String( await this.$viteHmrPortService.getPort(platform), ); + const tunnelHost = this.$iOSDeviceTunnelService.getHostAddress(platform); + if (tunnelHost && !process.env.NS_HMR_HOST) { + env.NS_HMR_HOST = tunnelHost; + } } return env; } diff --git a/lib/services/bundler/bundler.ts b/lib/services/bundler/bundler.ts index 0b6d2997cd..b9ac76c92b 100644 --- a/lib/services/bundler/bundler.ts +++ b/lib/services/bundler/bundler.ts @@ -30,6 +30,11 @@ declare global { prepareData: IPrepareData, ): Promise; stopBundlerCompiler(platform: string): Promise; + /** + * Whether the installed `@nativescript/vite` accepts a bare IPv6 + * address as `NS_HMR_HOST` for `platform`. + */ + acceptsIPv6DevHost(platform: string, projectData: IProjectData): boolean; } /** diff --git a/lib/services/ios/ios-device-tunnel-service.ts b/lib/services/ios/ios-device-tunnel-service.ts new file mode 100644 index 0000000000..66b370f8f3 --- /dev/null +++ b/lib/services/ios/ios-device-tunnel-service.ts @@ -0,0 +1,312 @@ +import * as os from "os"; +import * as semver from "semver"; +import { + IChildProcess, + IDictionary, + IFileSystem, + IHostInfo, +} from "../../common/declarations"; +import { injector } from "../../common/yok"; +import { IOSDeviceTunnelService } from "../../contracts/ios-device-tunnel-service"; +import { ICleanupService } from "../../definitions/cleanup-service"; +import { ITempService } from "../../definitions/temp-service"; +import { DeviceConnectionType } from "../../constants"; +import type * as child_process from "child_process"; + +/** Long enough to outlive any dev session; devicectl's default is 300 s. */ +const HOLD_SECONDS = 365 * 24 * 60 * 60; + +interface ICoreDeviceConnection { + transportType?: string; + tunnelState?: string; + tunnelIPAddress?: string; +} + +interface ITunnel { + platform: string; + holder?: child_process.ChildProcess; + address: Promise; + closed: boolean; +} + +export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { + private tunnels: IDictionary = {}; + private hostAddresses: IDictionary = {}; + private tunnelReadyTimeoutMs = 10000; + private tunnelPollIntervalMs = 500; + + constructor( + private $childProcess: IChildProcess, + private $cleanupService: ICleanupService, + private $fs: IFileSystem, + private $hostInfo: IHostInfo, + private $logger: ILogger, + private $mobileHelper: Mobile.IMobileHelper, + private $tempService: ITempService, + ) {} + + public open(device: Mobile.IDevice): Promise { + const id = device.deviceInfo.identifier; + if (!this.tunnels[id]) { + const tunnel: ITunnel = { + platform: device.deviceInfo.platform.toLowerCase(), + address: null, + closed: false, + }; + this.tunnels[id] = tunnel; + tunnel.address = this.openCore(device, tunnel).catch((err): null => { + this.$logger.trace(`Unable to open the USB tunnel to ${id}: ${err}`); + this.stopHolder(tunnel); + return null; + }); + } + return this.tunnels[id].address; + } + + public getHostAddress(platform: string): string | undefined { + return this.hostAddresses[platform.toLowerCase()]; + } + + public async close(deviceIdentifier: string): Promise { + const tunnel = this.tunnels[deviceIdentifier]; + if (!tunnel) { + return; + } + delete this.tunnels[deviceIdentifier]; + tunnel.closed = true; + const address = await tunnel.address; + if (address && this.hostAddresses[tunnel.platform] === address) { + delete this.hostAddresses[tunnel.platform]; + } + this.stopHolder(tunnel); + } + + private async openCore( + device: Mobile.IDevice, + tunnel: ITunnel, + ): Promise { + const id = device.deviceInfo.identifier; + const ineligible = this.getIneligibilityReason(device); + if (ineligible) { + this.$logger.trace(`Not using a USB tunnel for ${id}: ${ineligible}.`); + return null; + } + + const jsonPath = await this.$tempService.path({ + prefix: "ns-devicectl-", + suffix: ".json", + }); + const connection = await this.getConnection(id, jsonPath); + if (connection?.transportType !== "wired") { + this.$logger.trace( + `Not using a USB tunnel for ${id}: devicectl reports ${connection ? `transport ${connection.transportType}` : "no such device"}.`, + ); + return null; + } + + tunnel.holder = this.startHolder(id, tunnel); + const deviceAddress = await this.waitForTunnel(id, jsonPath, tunnel); + const hostAddress = + deviceAddress && this.findLocalTunnelAddress(deviceAddress); + if (!hostAddress) { + this.$logger.trace( + `Not using a USB tunnel for ${id}: ${deviceAddress ? `no local address on the tunnel to ${deviceAddress}` : "the tunnel did not come up"}.`, + ); + this.stopHolder(tunnel); + return null; + } + if (tunnel.closed) { + return null; + } + + this.hostAddresses[tunnel.platform] = hostAddress; + this.$logger.info( + `Using the USB tunnel to ${device.deviceInfo.displayName} (Mac address ${hostAddress}) for the Vite dev server.`, + ); + return hostAddress; + } + + private getIneligibilityReason(device: Mobile.IDevice): string | null { + const { deviceInfo } = device; + if (!this.$hostInfo.isDarwin) { + return "not on macOS"; + } + if (device.isEmulator) { + return "it is a simulator"; + } + if (!deviceInfo.connectionTypes?.includes(DeviceConnectionType.USB)) { + return "it is not connected over USB"; + } + const version = semver.coerce(deviceInfo.version); + if ( + this.$mobileHelper.isiOSPlatform(deviceInfo.platform) && + (!version || semver.major(version) < 17) + ) { + return `iOS ${deviceInfo.version} has no CoreDevice tunnel`; + } + return null; + } + + private async getConnection( + deviceIdentifier: string, + jsonPath: string, + ): Promise { + const result = await this.$childProcess.trySpawnFromCloseEvent("xcrun", [ + "devicectl", + "list", + "devices", + "--quiet", + "--json-output", + jsonPath, + ]); + if (result.exitCode !== 0 || !this.$fs.exists(jsonPath)) { + return null; + } + const devices: any[] = this.$fs.readJson(jsonPath)?.result?.devices || []; + const match = devices.find( + (d) => d?.hardwareProperties?.udid === deviceIdentifier, + ); + return match ? match.connectionProperties || {} : null; + } + + private startHolder( + deviceIdentifier: string, + tunnel: ITunnel, + ): child_process.ChildProcess { + const holder = this.$childProcess.spawn( + "xcrun", + [ + "devicectl", + "device", + "notification", + "observe", + "--device", + deviceIdentifier, + "--name", + "org.nativescript.cli.usb-tunnel", + "--session-timeout", + String(HOLD_SECONDS), + "--timeout", + String(HOLD_SECONDS + 60), + "--quiet", + ], + { stdio: "ignore" }, + ); + holder.on("error", (err: Error) => + this.$logger.trace(`USB tunnel holder for ${deviceIdentifier}: ${err}`), + ); + holder.once("exit", () => { + if (holder.pid) { + this.$cleanupService.removeKillProcess(holder.pid.toString()); + } + if (tunnel.closed || tunnel.holder !== holder) { + return; + } + tunnel.holder = undefined; + tunnel.address.then((address) => { + if (address && !tunnel.closed) { + this.$logger.warn( + `The USB tunnel to ${deviceIdentifier} closed, so the app can no longer reach the Vite dev server at ${address}. Restart the run to reconnect.`, + ); + } + }); + }); + if (holder.pid) { + this.$cleanupService.addKillProcess(holder.pid.toString()); + } + return holder; + } + + private async waitForTunnel( + deviceIdentifier: string, + jsonPath: string, + tunnel: ITunnel, + ): Promise { + const deadline = Date.now() + this.tunnelReadyTimeoutMs; + while (tunnel.holder && !tunnel.closed && Date.now() < deadline) { + const connection = await this.getConnection(deviceIdentifier, jsonPath); + if ( + connection?.tunnelState === "connected" && + connection.tunnelIPAddress + ) { + return connection.tunnelIPAddress; + } + await new Promise((resolve) => + setTimeout(resolve, this.tunnelPollIntervalMs), + ); + } + return null; + } + + /** + * devicectl reports the device's end of the tunnel; the Mac's end is the + * local interface address in the same subnet. + */ + private findLocalTunnelAddress(deviceAddress: string): string | null { + const device = parseIPv6(deviceAddress); + if (!device) { + return null; + } + for (const entries of Object.values(this.getNetworkInterfaces())) { + for (const entry of entries || []) { + const local = parseIPv6(entry.address); + const mask = parseIPv6(entry.netmask); + if ( + !local || + !mask || + entry.address.includes("%") || + local.every((group, i) => group === device[i]) + ) { + continue; + } + if ( + local.every((group, i) => (group & mask[i]) === (device[i] & mask[i])) + ) { + return entry.address; + } + } + } + return null; + } + + protected getNetworkInterfaces(): NodeJS.Dict { + return os.networkInterfaces(); + } + + private stopHolder(tunnel: ITunnel): void { + const holder = tunnel.holder; + tunnel.holder = undefined; + if (holder && holder.exitCode === null && holder.signalCode === null) { + holder.kill(); + } + } +} + +/** The eight 16-bit groups of an IPv6 address, or null for anything else. */ +function parseIPv6(address: string): number[] | null { + if (!address || !address.includes(":") || address.includes(".")) { + return null; + } + const [head, tail, ...rest] = address.split("%")[0].split("::"); + if (rest.length) { + return null; + } + const toGroups = (part: string) => + part ? part.split(":").map((g) => parseInt(g, 16)) : []; + const left = toGroups(head); + const right = toGroups(tail); + const missing = 8 - left.length - right.length; + if (tail === undefined ? missing !== 0 : missing < 1) { + return null; + } + const groups = [ + ...left, + ...new Array(Math.max(missing, 0)).fill(0), + ...right, + ]; + return groups.every((g) => Number.isInteger(g) && g >= 0 && g <= 0xffff) + ? groups + : null; +} + +injector.register("iOSDeviceTunnelService", IOSDeviceTunnelServiceImpl); diff --git a/test/contracts.ts b/test/contracts.ts index e07581e01e..a970529f1b 100644 --- a/test/contracts.ts +++ b/test/contracts.ts @@ -9,6 +9,7 @@ import { FileSystem, HostInfo, HttpClient, + IOSDeviceTunnelService, Logger, PackageManager, ProjectData, @@ -34,6 +35,7 @@ const tranche: [ProviderToken, string][] = [ [FileSystem, "fs"], [HostInfo, "hostInfo"], [HttpClient, "httpClient"], + [IOSDeviceTunnelService, "iOSDeviceTunnelService"], [Logger, "logger"], [PackageManager, "packageManager"], [ProjectData, "projectData"], diff --git a/test/controllers/run-controller.ts b/test/controllers/run-controller.ts index e8d419eb3b..0f048b05a4 100644 --- a/test/controllers/run-controller.ts +++ b/test/controllers/run-controller.ts @@ -142,6 +142,11 @@ function createTestInjector() { injector.register("viteHmrPortService", { getPort: async () => 5173, }); + injector.register("iOSDeviceTunnelService", { + open: async (): Promise => null, + getHostAddress: (): string => undefined, + close: async () => ({}), + }); const devicesService = injector.resolve("devicesService"); devicesService.getDevicesForPlatform = () => @@ -266,6 +271,149 @@ describe("RunController", () => { }); }); + describe("USB tunnel for Vite HMR", () => { + const secondIOSDevice = { + deviceInfo: { identifier: "mySecondiOSDevice", platform: "ios" }, + }; + const secondIOSDeviceDescriptor = { + identifier: "mySecondiOSDevice", + buildAction: async () => buildOutputPath, + buildData: {}, + }; + const hmrLiveSyncInfo = { ...liveSyncInfo, useHotModuleReload: true }; + let openedFor: string[] = null; + let closed: string[] = null; + let events: string[] = null; + let previousHost: string = undefined; + let acceptsIPv6DevHost: boolean; + + beforeEach(() => { + acceptsIPv6DevHost = true; + injector.resolve("bundlerCompilerService").acceptsIPv6DevHost = () => + acceptsIPv6DevHost; + openedFor = []; + closed = []; + events = []; + previousHost = process.env.NS_HMR_HOST; + delete process.env.NS_HMR_HOST; + map.mySecondiOSDevice = { + device: secondIOSDevice, + descriptor: secondIOSDeviceDescriptor, + }; + + const projectDataService = injector.resolve("projectDataService"); + const getProjectData = + projectDataService.getProjectData.bind(projectDataService); + projectDataService.getProjectData = (dir: string) => { + const projectData = getProjectData(dir); + projectData.bundler = "vite"; + return projectData; + }; + injector.resolve("devicesService").getDeviceByIdentifier = ( + identifier: string, + ) => map[identifier]?.device; + const tunnelService = injector.resolve("iOSDeviceTunnelService"); + tunnelService.open = async (device: Mobile.IDevice) => { + openedFor.push(device.deviceInfo.identifier); + events.push("tunnel"); + return "fd00::2"; + }; + tunnelService.close = async (identifier: string) => { + closed.push(identifier); + }; + const prepareController = injector.resolve("prepareController"); + prepareController.prepare = async (currentPrepareData: PrepareData) => { + events.push(`prepare ${currentPrepareData.platform}`); + return { + platform: currentPrepareData.platform, + hasNativeChanges: false, + }; + }; + }); + + afterEach(() => { + delete map.mySecondiOSDevice; + if (previousHost === undefined) { + delete process.env.NS_HMR_HOST; + } else { + process.env.NS_HMR_HOST = previousHost; + } + }); + + it("opens the tunnel of the session's only iOS device before preparing", async () => { + mockDevicesService(injector, [iOSDevice, androidDevice]); + + await runController.run({ + liveSyncInfo: hmrLiveSyncInfo, + deviceDescriptors: [iOSDeviceDescriptor, androidDeviceDescriptor], + }); + + assert.deepStrictEqual(openedFor, ["myiOSDevice"]); + assert.isBelow(events.indexOf("tunnel"), events.indexOf("prepare ios")); + }); + + it("does not open a tunnel when the session has two iOS devices", async () => { + mockDevicesService(injector, [iOSDevice, secondIOSDevice]); + + await runController.run({ + liveSyncInfo: hmrLiveSyncInfo, + deviceDescriptors: [iOSDeviceDescriptor, secondIOSDeviceDescriptor], + }); + + assert.deepStrictEqual(openedFor, []); + }); + + it("does not open a tunnel when the user set NS_HMR_HOST", async () => { + process.env.NS_HMR_HOST = "192.168.1.10"; + mockDevicesService(injector, [iOSDevice]); + + await runController.run({ + liveSyncInfo: hmrLiveSyncInfo, + deviceDescriptors: [iOSDeviceDescriptor], + }); + + assert.deepStrictEqual(openedFor, []); + }); + + it("does not open a tunnel for a @nativescript/vite without IPv6 dev hosts", async () => { + acceptsIPv6DevHost = false; + mockDevicesService(injector, [iOSDevice]); + + await runController.run({ + liveSyncInfo: hmrLiveSyncInfo, + deviceDescriptors: [iOSDeviceDescriptor], + }); + + assert.deepStrictEqual(openedFor, []); + }); + + it("does not open a tunnel without HMR", async () => { + mockDevicesService(injector, [iOSDevice]); + + await runController.run({ + liveSyncInfo, + deviceDescriptors: [iOSDeviceDescriptor], + }); + + assert.deepStrictEqual(openedFor, []); + }); + + it("closes the tunnel of a device that stops", async () => { + mockDevicesService(injector, [iOSDevice]); + await runController.run({ + liveSyncInfo: hmrLiveSyncInfo, + deviceDescriptors: [iOSDeviceDescriptor], + }); + + await runController.stop({ + projectDir, + deviceIdentifiers: ["myiOSDevice"], + }); + + assert.deepStrictEqual(closed, ["myiOSDevice"]); + }); + }); + describe("restartApplication", () => { let restartedApps: Array<{ device: string; isFullSync: boolean }> = null; let infoMessages: string[] = null; diff --git a/test/services/bundler/bundler-compiler-service.ts b/test/services/bundler/bundler-compiler-service.ts index 85d70658f3..9cf4714c3a 100644 --- a/test/services/bundler/bundler-compiler-service.ts +++ b/test/services/bundler/bundler-compiler-service.ts @@ -92,6 +92,9 @@ function createTestInjector( testInjector.register("viteHmrPortService", { getPort: async () => 5173, }); + testInjector.register("iOSDeviceTunnelService", { + getHostAddress: (): string => undefined, + }); return testInjector; } @@ -374,6 +377,56 @@ describe("BundlerCompilerService", () => { { NS_VITE_DIST_DIR: ".ns-vite-build/ios" }, ); }); + + describe("with a USB tunnel open", () => { + let previousHost: string; + beforeEach(() => { + previousHost = process.env.NS_HMR_HOST; + delete process.env.NS_HMR_HOST; + testInjector.resolve("iOSDeviceTunnelService").getHostAddress = ( + platform: string, + ) => (platform === "ios" ? "fd6f:72e:8d34::2" : undefined); + }); + afterEach(() => { + if (previousHost === undefined) { + delete process.env.NS_HMR_HOST; + } else { + process.env.NS_HMR_HOST = previousHost; + } + }); + + it("hands the tunnel's Mac address to that platform only", async () => { + assert.deepEqual( + await (bundlerCompilerService).getViteChildEnv("ios", { + watch: true, + hmr: true, + }), + { + NS_VITE_DIST_DIR: ".ns-vite-build/ios", + NS_HMR_PORT: "5173", + NS_HMR_HOST: "fd6f:72e:8d34::2", + }, + ); + assert.notProperty( + await (bundlerCompilerService).getViteChildEnv("android", { + watch: true, + hmr: true, + }), + "NS_HMR_HOST", + ); + }); + + it("leaves a user-set NS_HMR_HOST alone", async () => { + process.env.NS_HMR_HOST = "192.168.1.10"; + assert.notProperty( + await (bundlerCompilerService).getViteChildEnv("ios", { + watch: true, + hmr: true, + }), + "NS_HMR_HOST", + ); + }); + }); }); describe("compileWithWatch", () => { @@ -903,6 +956,23 @@ describe("BundlerCompilerService", () => { process.env.NS_VITE_SINGLE_PROCESS = "0"; assert.isFalse(supports("ios")); }); + + it("marks the packages that accept an IPv6 dev host, opted out or not", () => { + const accepts = (platform: string) => + bundlerCompilerService.acceptsIPv6DevHost(platform, { + projectDir, + }); + writeVitePackage({ name: "@nativescript/vite" }); + assert.isFalse(accepts("iOS")); + + writeVitePackage({ + name: "@nativescript/vite", + nativescriptCli: { singleProcessDev: ["ios"] }, + }); + process.env.NS_VITE_SINGLE_PROCESS = "0"; + assert.isTrue(accepts("iOS")); + assert.isFalse(accepts("visionOS")); + }); }); describe("stopBundlerCompiler", () => { diff --git a/test/services/ios/ios-device-tunnel-service.ts b/test/services/ios/ios-device-tunnel-service.ts new file mode 100644 index 0000000000..b7c59b8945 --- /dev/null +++ b/test/services/ios/ios-device-tunnel-service.ts @@ -0,0 +1,282 @@ +import { assert } from "chai"; +import { EventEmitter } from "events"; +import { Yok } from "../../../lib/common/yok"; +import { IInjector } from "../../../lib/common/definitions/yok"; +import { MobileHelper } from "../../../lib/common/mobile/mobile-helper"; +import { DevicePlatformsConstants } from "../../../lib/common/mobile/device-platforms-constants"; +import { DeviceConnectionType } from "../../../lib/constants"; +import { IOSDeviceTunnelServiceImpl } from "../../../lib/services/ios/ios-device-tunnel-service"; +import { ErrorsStub, LoggerStub, TempServiceStub } from "../../stubs"; + +const UDID = "00008030-000408D42692802E"; + +class FakeHolder extends EventEmitter { + public pid = 4242; + public exitCode: number = null; + public signalCode: string = null; + public killed = false; + + public kill(): boolean { + this.killed = true; + this.signalCode = "SIGTERM"; + this.emit("exit", null, "SIGTERM"); + return true; + } +} + +function coreDevice(connectionProperties: object, udid = UDID) { + return { + identifier: "3E4C6519-03DF-5CEB-9EA3-E027A81E52FC", + hardwareProperties: { udid, platform: "iOS", reality: "physical" }, + connectionProperties, + }; +} + +const wiredDisconnected = { + transportType: "wired", + tunnelState: "disconnected", +}; +const wiredConnected = { + transportType: "wired", + tunnelState: "connected", + tunnelIPAddress: "fd6f:72e:8d34::1", +}; + +const macInterfaces = { + lo0: [ + { + address: "::1", + netmask: "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", + family: "IPv6", + }, + ], + en0: [ + { address: "192.168.1.10", netmask: "255.255.255.0", family: "IPv4" }, + { + address: "fe80::1c2b:3a4d:5e6f:7081", + netmask: "ffff:ffff:ffff:ffff::", + family: "IPv6", + }, + ], + utun4: [ + { + address: "fd58:5467:5f7b::2", + netmask: "ffff:ffff:ffff:ffff::", + family: "IPv6", + }, + ], + utun6: [ + { + address: "fe80::35c1:eb2f:dbab:733", + netmask: "ffff:ffff:ffff:ffff::", + family: "IPv6", + }, + { + address: "fd6f:72e:8d34::2", + netmask: "ffff:ffff:ffff:ffff::", + family: "IPv6", + }, + ], +}; + +function iPhone( + overrides: Partial = {}, + isEmulator = false, +) { + return ({ + isEmulator, + deviceInfo: { + identifier: UDID, + displayName: "iPhone", + platform: "iOS", + version: "26.0.1", + connectionTypes: [DeviceConnectionType.USB], + ...overrides, + }, + }); +} + +describe("IOSDeviceTunnelService", () => { + let devicectlListings: object[][]; + let listCalls: number; + let spawned: { args: string[]; holder: FakeHolder }[]; + let warnings: string[]; + let isDarwin: boolean; + let service: IOSDeviceTunnelServiceImpl; + + beforeEach(() => { + devicectlListings = []; + listCalls = 0; + spawned = []; + warnings = []; + isDarwin = true; + let lastListing: object[] = []; + + const injector: IInjector = new Yok(); + injector.register("childProcess", { + trySpawnFromCloseEvent: async () => { + listCalls++; + if (devicectlListings.length) { + lastListing = devicectlListings.shift(); + } + return { exitCode: lastListing ? 0 : 1 }; + }, + spawn: (command: string, args: string[]) => { + const holder = new FakeHolder(); + spawned.push({ args: [command, ...args], holder }); + return holder; + }, + }); + injector.register("cleanupService", { + addKillProcess: async () => ({}), + removeKillProcess: async () => ({}), + }); + injector.register("fs", { + exists: () => true, + readJson: () => ({ result: { devices: lastListing } }), + }); + injector.register("hostInfo", { + get isDarwin() { + return isDarwin; + }, + }); + const logger = new LoggerStub(); + logger.warn = (message: string) => { + warnings.push(message); + }; + injector.register("logger", logger); + injector.register("errors", ErrorsStub); + injector.register("devicePlatformsConstants", DevicePlatformsConstants); + injector.register("mobileHelper", MobileHelper); + injector.register("tempService", TempServiceStub); + injector.register("iOSDeviceTunnelService", IOSDeviceTunnelServiceImpl); + + service = injector.resolve("iOSDeviceTunnelService"); + (service).tunnelReadyTimeoutMs = 200; + (service).tunnelPollIntervalMs = 1; + (service).getNetworkInterfaces = () => macInterfaces; + }); + + it("holds the tunnel and resolves the Mac's address on it", async () => { + devicectlListings = [ + [coreDevice(wiredDisconnected)], + [coreDevice({ ...wiredConnected, tunnelState: "connecting" })], + [coreDevice(wiredConnected)], + ]; + + const address = await service.open(iPhone()); + + assert.equal(address, "fd6f:72e:8d34::2"); + assert.equal(service.getHostAddress("ios"), "fd6f:72e:8d34::2"); + assert.lengthOf(spawned, 1); + assert.includeMembers(spawned[0].args, [ + "xcrun", + "devicectl", + "notification", + "observe", + UDID, + ]); + assert.isFalse(spawned[0].holder.killed); + }); + + it("opens one tunnel per device however often it is asked", async () => { + devicectlListings = [[coreDevice(wiredConnected)]]; + + const [first, second] = await Promise.all([ + service.open(iPhone()), + service.open(iPhone()), + ]); + + assert.equal(first, "fd6f:72e:8d34::2"); + assert.equal(second, first); + assert.lengthOf(spawned, 1); + }); + + const ineligible: { + name: string; + device: Mobile.IDevice; + darwin?: boolean; + }[] = [ + { name: "a simulator", device: iPhone({}, true) }, + { + name: "a Wi-Fi-only device", + device: iPhone({ connectionTypes: [DeviceConnectionType.Wifi] }), + }, + { name: "a device on iOS 16", device: iPhone({ version: "16.7.10" }) }, + { name: "a device on a non-macOS host", device: iPhone(), darwin: false }, + ]; + for (const testCase of ineligible) { + it(`does not ask devicectl about ${testCase.name}`, async () => { + isDarwin = testCase.darwin ?? true; + + assert.isNull(await service.open(testCase.device)); + assert.equal(listCalls, 0); + assert.lengthOf(spawned, 0); + }); + } + + it("does not hold a tunnel for a network-paired device", async () => { + devicectlListings = [ + [coreDevice({ ...wiredConnected, transportType: "localNetwork" })], + ]; + + assert.isNull(await service.open(iPhone())); + assert.lengthOf(spawned, 0); + }); + + it("falls back when devicectl is unavailable", async () => { + devicectlListings = [null]; + + assert.isNull(await service.open(iPhone())); + assert.lengthOf(spawned, 0); + }); + + it("falls back when devicectl does not know the device", async () => { + devicectlListings = [ + [coreDevice(wiredConnected, "00008112-000128D1022A201E")], + ]; + + assert.isNull(await service.open(iPhone())); + assert.lengthOf(spawned, 0); + }); + + it("releases the holder when the tunnel never comes up", async () => { + devicectlListings = [[coreDevice(wiredDisconnected)]]; + + assert.isNull(await service.open(iPhone())); + assert.lengthOf(spawned, 1); + assert.isTrue(spawned[0].holder.killed); + assert.isUndefined(service.getHostAddress("ios")); + }); + + it("releases the holder when no Mac interface is on the tunnel", async () => { + devicectlListings = [ + [coreDevice({ ...wiredConnected, tunnelIPAddress: "fd11:2233:4455::1" })], + ]; + + assert.isNull(await service.open(iPhone())); + assert.isTrue(spawned[0].holder.killed); + }); + + it("releases the holder and the host on close", async () => { + devicectlListings = [[coreDevice(wiredConnected)]]; + await service.open(iPhone()); + + await service.close(UDID); + + assert.isTrue(spawned[0].holder.killed); + assert.isUndefined(service.getHostAddress("ios")); + assert.isEmpty(warnings); + }); + + it("warns when the tunnel closes on its own", async () => { + devicectlListings = [[coreDevice(wiredConnected)]]; + await service.open(iPhone()); + + spawned[0].holder.emit("exit", 1, null); + await new Promise((resolve) => setImmediate(resolve)); + + assert.lengthOf(warnings, 1); + assert.include(warnings[0], "fd6f:72e:8d34::2"); + }); +}); From 86e54d99d220539c8f330e5ea0a0f1b2ae02cd9c Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 19:34:45 -0300 Subject: [PATCH 2/4] fix(ios): count only the --device selection when deciding on the USB tunnel Session descriptors include every discovered device, so a booted simulator or a second iOS device on the network turned the tunnel off even when --device picked a single USB iPhone. --- lib/controllers/run-controller.ts | 9 +++++++++ test/controllers/run-controller.ts | 18 ++++++++++++++++++ test/stubs.ts | 1 + 3 files changed, 28 insertions(+) diff --git a/lib/controllers/run-controller.ts b/lib/controllers/run-controller.ts index 8b4695d93a..d29f9aa4ce 100644 --- a/lib/controllers/run-controller.ts +++ b/lib/controllers/run-controller.ts @@ -871,7 +871,16 @@ export class RunController extends EventEmitter implements IRunController { return; } + // Descriptors cover every discovered device; `--device` narrows the + // session to one of them. + const selected = this.$devicesService.getDeviceByDeviceOption(); const platformTargets = sessionDeviceDescriptors.filter((descriptor) => { + if ( + selected && + descriptor.identifier !== selected.deviceInfo.identifier + ) { + return false; + } const target = this.$devicesService.getDeviceByIdentifier( descriptor.identifier, ); diff --git a/test/controllers/run-controller.ts b/test/controllers/run-controller.ts index 0f048b05a4..d57afc6fd2 100644 --- a/test/controllers/run-controller.ts +++ b/test/controllers/run-controller.ts @@ -363,6 +363,24 @@ describe("RunController", () => { assert.deepStrictEqual(openedFor, []); }); + it("opens the tunnel of the --device selection when another iOS device is attached", async () => { + const devicesService = injector.resolve("devicesService"); + devicesService.getDeviceByDeviceOption = () => iOSDevice; + mockDevicesService(injector, [iOSDevice]); + + try { + await runController.run({ + liveSyncInfo: hmrLiveSyncInfo, + deviceDescriptors: [iOSDeviceDescriptor, secondIOSDeviceDescriptor], + }); + } finally { + devicesService.getDeviceByDeviceOption = (): Mobile.IDevice => + undefined; + } + + assert.deepStrictEqual(openedFor, ["myiOSDevice"]); + }); + it("does not open a tunnel when the user set NS_HMR_HOST", async () => { process.env.NS_HMR_HOST = "192.168.1.10"; mockDevicesService(injector, [iOSDevice]); diff --git a/test/stubs.ts b/test/stubs.ts index c21b07ce22..fc946ee31c 100644 --- a/test/stubs.ts +++ b/test/stubs.ts @@ -1540,6 +1540,7 @@ export class InjectorStub extends Yok implements IInjector { this.register("devicesService", { getDevice: (): Mobile.IDevice => undefined, getDeviceByIdentifier: (): Mobile.IDevice => undefined, + getDeviceByDeviceOption: (): Mobile.IDevice => undefined, }); this.register("terminalSpinnerService", TerminalSpinnerServiceStub); } From 5256370b9dbc0004750702f36a1199398a67044a Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 24 Nov 2026 15:54:38 -0300 Subject: [PATCH 3/4] 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. --- lib/bootstrap.ts | 12 +++- lib/controllers/run-controller.ts | 7 +- .../bundler/bundler-compiler-service.ts | 5 +- lib/services/ios/ios-device-tunnel-service.ts | 69 +++++++++---------- .../services/ios/ios-device-tunnel-service.ts | 8 ++- 5 files changed, 54 insertions(+), 47 deletions(-) diff --git a/lib/bootstrap.ts b/lib/bootstrap.ts index 21481063a2..36f645eb84 100644 --- a/lib/bootstrap.ts +++ b/lib/bootstrap.ts @@ -1,5 +1,7 @@ import { injector } from "./common/yok"; +import { provideLazy } from "./common/di/providers"; import { registerBuiltInCommand } from "./common/services/command-definition-adapter"; +import { IOSDeviceTunnelService } from "./contracts/ios-device-tunnel-service"; import type { fontsCommandDefinition } from "./commands/fonts"; require("./common/bootstrap"); @@ -676,9 +678,13 @@ injector.require( "viteHmrPortService", "./services/bundler/vite-hmr-port-service", ); -injector.require( - "iOSDeviceTunnelService", - "./services/ios/ios-device-tunnel-service", +injector.register( + provideLazy( + IOSDeviceTunnelService, + (): typeof import("./services/ios/ios-device-tunnel-service").IOSDeviceTunnelServiceImpl => + require("./services/ios/ios-device-tunnel-service") + .IOSDeviceTunnelServiceImpl, + ), ); injector.require( diff --git a/lib/controllers/run-controller.ts b/lib/controllers/run-controller.ts index d29f9aa4ce..00ddf0556d 100644 --- a/lib/controllers/run-controller.ts +++ b/lib/controllers/run-controller.ts @@ -27,8 +27,10 @@ import { IInjector } from "../common/definitions/yok"; import { ViteHmrPortService } from "../contracts/vite-hmr-port-service"; import { IOSDeviceTunnelService } from "../contracts/ios-device-tunnel-service"; import { injector } from "../common/yok"; +import { inject } from "../common/di/inject"; export class RunController extends EventEmitter implements IRunController { + private iOSDeviceTunnelService = inject(IOSDeviceTunnelService); private prepareReadyEventHandler: any = null; private appRestartRequestHandler: ( request: IBundlerAppRestartRequest, @@ -67,7 +69,6 @@ export class RunController extends EventEmitter implements IRunController { protected $projectDataService: IProjectDataService, private $staticConfig: Config.IStaticConfig, private $viteHmrPortService: ViteHmrPortService, - private $iOSDeviceTunnelService: IOSDeviceTunnelService, ) { super(); } @@ -170,7 +171,7 @@ export class RunController extends EventEmitter implements IRunController { ).map((descriptor) => descriptor.identifier); for (const deviceIdentifier of removedDeviceIdentifiers) { - await this.$iOSDeviceTunnelService.close(deviceIdentifier); + await this.iOSDeviceTunnelService.close(deviceIdentifier); } // 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 { return; } - await this.$iOSDeviceTunnelService.open(device); + await this.iOSDeviceTunnelService.open(device); } /** diff --git a/lib/services/bundler/bundler-compiler-service.ts b/lib/services/bundler/bundler-compiler-service.ts index aaa1066a56..d9d91e1361 100644 --- a/lib/services/bundler/bundler-compiler-service.ts +++ b/lib/services/bundler/bundler-compiler-service.ts @@ -37,6 +37,7 @@ import { ICleanupService } from "../../definitions/cleanup-service"; import { ViteHmrPortService } from "../../contracts/vite-hmr-port-service"; import { IOSDeviceTunnelService } from "../../contracts/ios-device-tunnel-service"; import { injector } from "../../common/yok"; +import { inject } from "../../common/di/inject"; import { resolvePackagePath, resolvePackageJSONPath, @@ -95,6 +96,7 @@ export class BundlerCompilerService extends EventEmitter implements IBundlerCompilerService { + private iOSDeviceTunnelService = inject(IOSDeviceTunnelService); private bundlerProcesses: IDictionary = {}; // Vite-only: the long-lived `vite serve` dev server the device fetches // modules and HMR updates from. Keyed by platform, managed by this CLI @@ -122,7 +124,6 @@ export class BundlerCompilerService private $packageInstallationManager: IPackageInstallationManager, // private $sharedEventBus: ISharedEventBus private $projectConfigService: IProjectConfigService, private $viteHmrPortService: ViteHmrPortService, - private $iOSDeviceTunnelService: IOSDeviceTunnelService, ) { super(); } @@ -866,7 +867,7 @@ export class BundlerCompilerService env.NS_HMR_PORT = String( await this.$viteHmrPortService.getPort(platform), ); - const tunnelHost = this.$iOSDeviceTunnelService.getHostAddress(platform); + const tunnelHost = this.iOSDeviceTunnelService.getHostAddress(platform); if (tunnelHost && !process.env.NS_HMR_HOST) { env.NS_HMR_HOST = tunnelHost; } diff --git a/lib/services/ios/ios-device-tunnel-service.ts b/lib/services/ios/ios-device-tunnel-service.ts index 66b370f8f3..31976028fa 100644 --- a/lib/services/ios/ios-device-tunnel-service.ts +++ b/lib/services/ios/ios-device-tunnel-service.ts @@ -1,15 +1,14 @@ import * as os from "os"; import * as semver from "semver"; -import { - IChildProcess, - IDictionary, - IFileSystem, - IHostInfo, -} from "../../common/declarations"; -import { injector } from "../../common/yok"; +import { IDictionary } from "../../common/declarations"; +import { inject } from "../../common/di/inject"; +import { ChildProcess } from "../../contracts/child-process"; +import { FileSystem } from "../../contracts/file-system"; +import { HostInfo } from "../../contracts/host-info"; import { IOSDeviceTunnelService } from "../../contracts/ios-device-tunnel-service"; +import { Logger } from "../../contracts/logger"; +import { TempService } from "../../contracts/temp-service"; import { ICleanupService } from "../../definitions/cleanup-service"; -import { ITempService } from "../../definitions/temp-service"; import { DeviceConnectionType } from "../../constants"; import type * as child_process from "child_process"; @@ -29,22 +28,20 @@ interface ITunnel { closed: boolean; } -export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { +export class IOSDeviceTunnelServiceImpl extends IOSDeviceTunnelService { + private childProcess = inject(ChildProcess); + private cleanupService = inject("cleanupService"); + private fs = inject(FileSystem); + private hostInfo = inject(HostInfo); + private logger = inject(Logger); + private mobileHelper = inject("mobileHelper"); + private tempService = inject(TempService); + private tunnels: IDictionary = {}; private hostAddresses: IDictionary = {}; private tunnelReadyTimeoutMs = 10000; private tunnelPollIntervalMs = 500; - constructor( - private $childProcess: IChildProcess, - private $cleanupService: ICleanupService, - private $fs: IFileSystem, - private $hostInfo: IHostInfo, - private $logger: ILogger, - private $mobileHelper: Mobile.IMobileHelper, - private $tempService: ITempService, - ) {} - public open(device: Mobile.IDevice): Promise { const id = device.deviceInfo.identifier; if (!this.tunnels[id]) { @@ -55,7 +52,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { }; this.tunnels[id] = tunnel; tunnel.address = this.openCore(device, tunnel).catch((err): null => { - this.$logger.trace(`Unable to open the USB tunnel to ${id}: ${err}`); + this.logger.trace(`Unable to open the USB tunnel to ${id}: ${err}`); this.stopHolder(tunnel); return null; }); @@ -88,17 +85,17 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { const id = device.deviceInfo.identifier; const ineligible = this.getIneligibilityReason(device); if (ineligible) { - this.$logger.trace(`Not using a USB tunnel for ${id}: ${ineligible}.`); + this.logger.trace(`Not using a USB tunnel for ${id}: ${ineligible}.`); return null; } - const jsonPath = await this.$tempService.path({ + const jsonPath = await this.tempService.path({ prefix: "ns-devicectl-", suffix: ".json", }); const connection = await this.getConnection(id, jsonPath); if (connection?.transportType !== "wired") { - this.$logger.trace( + this.logger.trace( `Not using a USB tunnel for ${id}: devicectl reports ${connection ? `transport ${connection.transportType}` : "no such device"}.`, ); return null; @@ -109,7 +106,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { const hostAddress = deviceAddress && this.findLocalTunnelAddress(deviceAddress); if (!hostAddress) { - this.$logger.trace( + this.logger.trace( `Not using a USB tunnel for ${id}: ${deviceAddress ? `no local address on the tunnel to ${deviceAddress}` : "the tunnel did not come up"}.`, ); this.stopHolder(tunnel); @@ -120,7 +117,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { } this.hostAddresses[tunnel.platform] = hostAddress; - this.$logger.info( + this.logger.info( `Using the USB tunnel to ${device.deviceInfo.displayName} (Mac address ${hostAddress}) for the Vite dev server.`, ); return hostAddress; @@ -128,7 +125,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { private getIneligibilityReason(device: Mobile.IDevice): string | null { const { deviceInfo } = device; - if (!this.$hostInfo.isDarwin) { + if (!this.hostInfo.isDarwin) { return "not on macOS"; } if (device.isEmulator) { @@ -139,7 +136,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { } const version = semver.coerce(deviceInfo.version); if ( - this.$mobileHelper.isiOSPlatform(deviceInfo.platform) && + this.mobileHelper.isiOSPlatform(deviceInfo.platform) && (!version || semver.major(version) < 17) ) { return `iOS ${deviceInfo.version} has no CoreDevice tunnel`; @@ -151,7 +148,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { deviceIdentifier: string, jsonPath: string, ): Promise { - const result = await this.$childProcess.trySpawnFromCloseEvent("xcrun", [ + const result = await this.childProcess.trySpawnFromCloseEvent("xcrun", [ "devicectl", "list", "devices", @@ -159,10 +156,10 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { "--json-output", jsonPath, ]); - if (result.exitCode !== 0 || !this.$fs.exists(jsonPath)) { + if (result.exitCode !== 0 || !this.fs.exists(jsonPath)) { return null; } - const devices: any[] = this.$fs.readJson(jsonPath)?.result?.devices || []; + const devices: any[] = this.fs.readJson(jsonPath)?.result?.devices || []; const match = devices.find( (d) => d?.hardwareProperties?.udid === deviceIdentifier, ); @@ -173,7 +170,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { deviceIdentifier: string, tunnel: ITunnel, ): child_process.ChildProcess { - const holder = this.$childProcess.spawn( + const holder = this.childProcess.spawn( "xcrun", [ "devicectl", @@ -193,11 +190,11 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { { stdio: "ignore" }, ); holder.on("error", (err: Error) => - this.$logger.trace(`USB tunnel holder for ${deviceIdentifier}: ${err}`), + this.logger.trace(`USB tunnel holder for ${deviceIdentifier}: ${err}`), ); holder.once("exit", () => { if (holder.pid) { - this.$cleanupService.removeKillProcess(holder.pid.toString()); + this.cleanupService.removeKillProcess(holder.pid.toString()); } if (tunnel.closed || tunnel.holder !== holder) { return; @@ -205,14 +202,14 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { tunnel.holder = undefined; tunnel.address.then((address) => { if (address && !tunnel.closed) { - this.$logger.warn( + this.logger.warn( `The USB tunnel to ${deviceIdentifier} closed, so the app can no longer reach the Vite dev server at ${address}. Restart the run to reconnect.`, ); } }); }); if (holder.pid) { - this.$cleanupService.addKillProcess(holder.pid.toString()); + this.cleanupService.addKillProcess(holder.pid.toString()); } return holder; } @@ -308,5 +305,3 @@ function parseIPv6(address: string): number[] | null { ? groups : null; } - -injector.register("iOSDeviceTunnelService", IOSDeviceTunnelServiceImpl); diff --git a/test/services/ios/ios-device-tunnel-service.ts b/test/services/ios/ios-device-tunnel-service.ts index b7c59b8945..d96818f9f7 100644 --- a/test/services/ios/ios-device-tunnel-service.ts +++ b/test/services/ios/ios-device-tunnel-service.ts @@ -2,9 +2,11 @@ import { assert } from "chai"; import { EventEmitter } from "events"; import { Yok } from "../../../lib/common/yok"; import { IInjector } from "../../../lib/common/definitions/yok"; +import { provide } from "../../../lib/common/di"; import { MobileHelper } from "../../../lib/common/mobile/mobile-helper"; import { DevicePlatformsConstants } from "../../../lib/common/mobile/device-platforms-constants"; import { DeviceConnectionType } from "../../../lib/constants"; +import { IOSDeviceTunnelService } from "../../../lib/contracts/ios-device-tunnel-service"; import { IOSDeviceTunnelServiceImpl } from "../../../lib/services/ios/ios-device-tunnel-service"; import { ErrorsStub, LoggerStub, TempServiceStub } from "../../stubs"; @@ -149,9 +151,11 @@ describe("IOSDeviceTunnelService", () => { injector.register("devicePlatformsConstants", DevicePlatformsConstants); injector.register("mobileHelper", MobileHelper); injector.register("tempService", TempServiceStub); - injector.register("iOSDeviceTunnelService", IOSDeviceTunnelServiceImpl); + injector.register( + provide(IOSDeviceTunnelService, IOSDeviceTunnelServiceImpl), + ); - service = injector.resolve("iOSDeviceTunnelService"); + service = injector.get(IOSDeviceTunnelService); (service).tunnelReadyTimeoutMs = 200; (service).tunnelPollIntervalMs = 1; (service).getNetworkInterfaces = () => macInterfaces; From a87b885c7a2d32752d6c940525998cd772b6386b Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 24 Nov 2026 15:57:27 -0300 Subject: [PATCH 4/4] test(ios): register the USB tunnel service and its stubs by contract token The tunnel spec provides the service and the contracted stubs it injects (ChildProcess, FileSystem, HostInfo, Logger, Errors, TempService) by token; the RunController and BundlerCompilerService specs provide and look up the tunnel stub through the IOSDeviceTunnelService contract. --- test/controllers/run-controller.ts | 14 ++-- .../bundler/bundler-compiler-service.ts | 8 ++- .../services/ios/ios-device-tunnel-service.ts | 67 ++++++++++++------- 3 files changed, 57 insertions(+), 32 deletions(-) diff --git a/test/controllers/run-controller.ts b/test/controllers/run-controller.ts index d57afc6fd2..25c3bcd93c 100644 --- a/test/controllers/run-controller.ts +++ b/test/controllers/run-controller.ts @@ -16,6 +16,7 @@ import { PrepareController } from "../../lib/controllers/prepare-controller"; import { LiveSyncProcessDataService } from "../../lib/services/livesync-process-data-service"; import { IDictionary } from "../../lib/common/declarations"; import { IInjector } from "../../lib/common/definitions/yok"; +import { IOSDeviceTunnelService } from "../../lib/contracts/ios-device-tunnel-service"; let isAttachToHmrStatusCalled = false; let prepareData: IPrepareData = null; @@ -142,10 +143,13 @@ function createTestInjector() { injector.register("viteHmrPortService", { getPort: async () => 5173, }); - injector.register("iOSDeviceTunnelService", { - open: async (): Promise => null, - getHostAddress: (): string => undefined, - close: async () => ({}), + injector.register({ + provide: IOSDeviceTunnelService, + useValue: { + open: async (): Promise => null, + getHostAddress: (): string => undefined, + close: async () => ({}), + }, }); const devicesService = injector.resolve("devicesService"); @@ -312,7 +316,7 @@ describe("RunController", () => { injector.resolve("devicesService").getDeviceByIdentifier = ( identifier: string, ) => map[identifier]?.device; - const tunnelService = injector.resolve("iOSDeviceTunnelService"); + const tunnelService = injector.get(IOSDeviceTunnelService); tunnelService.open = async (device: Mobile.IDevice) => { openedFor.push(device.deviceInfo.identifier); events.push("tunnel"); diff --git a/test/services/bundler/bundler-compiler-service.ts b/test/services/bundler/bundler-compiler-service.ts index 9cf4714c3a..fa33f4d509 100644 --- a/test/services/bundler/bundler-compiler-service.ts +++ b/test/services/bundler/bundler-compiler-service.ts @@ -7,6 +7,7 @@ import * as os from "os"; import * as path from "path"; import { ErrorsStub } from "../../stubs"; import { IInjector } from "../../../lib/common/definitions/yok"; +import { IOSDeviceTunnelService } from "../../../lib/contracts/ios-device-tunnel-service"; import { BUNDLER_APP_RESTART_REQUESTED, BUNDLER_COMPILATION_COMPLETE, @@ -92,8 +93,9 @@ function createTestInjector( testInjector.register("viteHmrPortService", { getPort: async () => 5173, }); - testInjector.register("iOSDeviceTunnelService", { - getHostAddress: (): string => undefined, + testInjector.register({ + provide: IOSDeviceTunnelService, + useValue: { getHostAddress: (): string => undefined }, }); return testInjector; @@ -383,7 +385,7 @@ describe("BundlerCompilerService", () => { beforeEach(() => { previousHost = process.env.NS_HMR_HOST; delete process.env.NS_HMR_HOST; - testInjector.resolve("iOSDeviceTunnelService").getHostAddress = ( + testInjector.get(IOSDeviceTunnelService).getHostAddress = ( platform: string, ) => (platform === "ios" ? "fd6f:72e:8d34::2" : undefined); }); diff --git a/test/services/ios/ios-device-tunnel-service.ts b/test/services/ios/ios-device-tunnel-service.ts index d96818f9f7..bdbae10698 100644 --- a/test/services/ios/ios-device-tunnel-service.ts +++ b/test/services/ios/ios-device-tunnel-service.ts @@ -6,7 +6,15 @@ import { provide } from "../../../lib/common/di"; import { MobileHelper } from "../../../lib/common/mobile/mobile-helper"; import { DevicePlatformsConstants } from "../../../lib/common/mobile/device-platforms-constants"; import { DeviceConnectionType } from "../../../lib/constants"; -import { IOSDeviceTunnelService } from "../../../lib/contracts/ios-device-tunnel-service"; +import { + ChildProcess, + Errors, + FileSystem, + HostInfo, + IOSDeviceTunnelService, + Logger, + TempService, +} from "../../../lib/contracts"; import { IOSDeviceTunnelServiceImpl } from "../../../lib/services/ios/ios-device-tunnel-service"; import { ErrorsStub, LoggerStub, TempServiceStub } from "../../stubs"; @@ -115,45 +123,56 @@ describe("IOSDeviceTunnelService", () => { let lastListing: object[] = []; const injector: IInjector = new Yok(); - injector.register("childProcess", { - trySpawnFromCloseEvent: async () => { - listCalls++; - if (devicectlListings.length) { - lastListing = devicectlListings.shift(); - } - return { exitCode: lastListing ? 0 : 1 }; - }, - spawn: (command: string, args: string[]) => { - const holder = new FakeHolder(); - spawned.push({ args: [command, ...args], holder }); - return holder; + injector.register({ + provide: ChildProcess, + useValue: { + trySpawnFromCloseEvent: async () => { + listCalls++; + if (devicectlListings.length) { + lastListing = devicectlListings.shift(); + } + return { exitCode: lastListing ? 0 : 1 }; + }, + spawn: (command: string, args: string[]) => { + const holder = new FakeHolder(); + spawned.push({ args: [command, ...args], holder }); + return holder; + }, }, }); injector.register("cleanupService", { addKillProcess: async () => ({}), removeKillProcess: async () => ({}), }); - injector.register("fs", { - exists: () => true, - readJson: () => ({ result: { devices: lastListing } }), + injector.register({ + provide: FileSystem, + useValue: { + exists: () => true, + readJson: () => ({ result: { devices: lastListing } }), + }, }); - injector.register("hostInfo", { - get isDarwin() { - return isDarwin; + injector.register({ + provide: HostInfo, + useValue: { + get isDarwin() { + return isDarwin; + }, }, }); const logger = new LoggerStub(); logger.warn = (message: string) => { warnings.push(message); }; - injector.register("logger", logger); - injector.register("errors", ErrorsStub); + injector.register([ + { provide: Logger, useValue: logger }, + { provide: Errors, useClass: ErrorsStub }, + ]); injector.register("devicePlatformsConstants", DevicePlatformsConstants); injector.register("mobileHelper", MobileHelper); - injector.register("tempService", TempServiceStub); - injector.register( + injector.register([ + { provide: TempService, useClass: TempServiceStub }, provide(IOSDeviceTunnelService, IOSDeviceTunnelServiceImpl), - ); + ]); service = injector.get(IOSDeviceTunnelService); (service).tunnelReadyTimeoutMs = 200;