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"); + }); +});