diff --git a/lib/bootstrap.ts b/lib/bootstrap.ts index 4251bb5e95..f347efbba7 100644 --- a/lib/bootstrap.ts +++ b/lib/bootstrap.ts @@ -1,6 +1,8 @@ import { provideLazy } from "./common/di"; import { injector } from "./common/yok"; import { registerBuiltInCommand } from "./common/services/command-definition-adapter"; +import { DevServerOriginService } from "./contracts/internal/dev-server-origin-service"; +import { IOSDeviceTunnelService } from "./contracts/internal/ios-device-tunnel-service"; import type { fontsCommandDefinition } from "./commands/fonts"; import { AndroidPluginMirrorService } from "./contracts/internal/android-plugin-mirror-service"; import { NativeFileHashesMemo } from "./contracts/internal/native-file-hashes-memo"; @@ -694,6 +696,22 @@ injector.require( "viteHmrPortService", "./services/bundler/vite-hmr-port-service", ); +injector.register( + provideLazy( + IOSDeviceTunnelService, + () => + require("./services/ios/ios-device-tunnel-service") + .IOSDeviceTunnelServiceImpl, + ), +); +injector.register( + provideLazy( + DevServerOriginService, + () => + require("./services/bundler/dev-server-origin-service") + .DevServerOriginServiceImpl, + ), +); injector.require( "applePortalSessionService", diff --git a/lib/constants.ts b/lib/constants.ts index aa6fb3f8c7..8e6dfc796c 100644 --- a/lib/constants.ts +++ b/lib/constants.ts @@ -23,6 +23,12 @@ export const RSPACK_PLUGIN_NAME = "@nativescript/rspack"; // and tells `@nativescript/vite` where via `NS_VITE_DIST_DIR`; the package's // own fallback (`.ns-vite-build`) only applies to standalone `vite` runs. export const VITE_DIST_FOLDER_NAME = ".ns-vite-build"; +/** + * Per-device file next to `bundle.mjs` that tells a Vite HMR app the dev + * server's origin and token. Never part of the shared platforms app folder: + * the origin differs between devices. + */ +export const DEV_SERVER_FILE_NAME = "dev-server.json"; export const TNS_CORE_MODULES_WIDGETS_NAME = "tns-core-modules-widgets"; export const UI_MOBILE_BASE_NAME = "@nativescript/ui-mobile-base"; export const TNS_ANDROID_RUNTIME_NAME = "tns-android"; diff --git a/lib/contracts/internal/dev-server-origin-service.ts b/lib/contracts/internal/dev-server-origin-service.ts new file mode 100644 index 0000000000..494b2a7b12 --- /dev/null +++ b/lib/contracts/internal/dev-server-origin-service.ts @@ -0,0 +1,42 @@ +import { Contract } from "../../common/di/contract"; + +export interface IDevServerOriginOptions { + /** Android: `adb reverse tcp: tcp:` is confirmed for the device. */ + adbReverse?: boolean; +} + +/** + * Decides, per device, the origin an app uses to reach the platform's Vite + * dev server, and the content of the `dev-server.json` file that hands the + * origin and the dev server's token to the app. + */ +@Contract() +export abstract class DevServerOriginService { + /** + * The token of the platform's dev server. Generated on first use and kept + * for the life of the process, so a restarted dev server still accepts the + * files already on the devices. + */ + abstract getToken(platform: string): string; + + /** + * Chooses the device's origin from what the CLI knows about how it reaches + * this machine, records it and resolves it. A physical iOS / visionOS + * device uses its USB tunnel only while one is open. + */ + abstract chooseOrigin( + device: Mobile.IDevice, + options?: IDevServerOriginOptions, + ): Promise; + + /** The device's last chosen origin, if any. */ + abstract getOrigin(deviceIdentifier: string): string | undefined; + + /** + * The `dev-server.json` content for the device, or null when no origin was + * chosen for it, in which case nothing is delivered. + */ + abstract getDevServerFile(deviceIdentifier: string): string | null; + + abstract forget(deviceIdentifier: string): void; +} diff --git a/lib/contracts/internal/ios-device-tunnel-service.ts b/lib/contracts/internal/ios-device-tunnel-service.ts new file mode 100644 index 0000000000..f3ebe96b92 --- /dev/null +++ b/lib/contracts/internal/ios-device-tunnel-service.ts @@ -0,0 +1,30 @@ +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() +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 address on the device's tunnel while the tunnel is up. + */ + abstract getHostAddress(deviceIdentifier: string): string | undefined; + + abstract close(deviceIdentifier: string): Promise; + + /** + * Calls `listener` with the device's identifier when an open tunnel goes + * down without `close`, after `getHostAddress` stopped returning it. + */ + abstract onTunnelLost(listener: (deviceIdentifier: string) => void): void; +} diff --git a/lib/contracts/vite-hmr-port-service.ts b/lib/contracts/vite-hmr-port-service.ts index 8cab600139..ccf1a6c0a3 100644 --- a/lib/contracts/vite-hmr-port-service.ts +++ b/lib/contracts/vite-hmr-port-service.ts @@ -9,9 +9,8 @@ export abstract class ViteHmrPortService { * Resolves the port the Vite dev server for `platform` listens on: the * first free port at or above `NS_HMR_PORT` (default 5173) that no other * platform in this process holds. Resolved once per platform and stable - * for the life of the process, so the build watcher (which bakes the port - * into `bundle.mjs`), the dev server and the Android `adb reverse` tunnel - * all agree on it. + * for the life of the process, so the dev server, the origin each device + * is given and the Android `adb reverse` tunnel all agree on it. * * With `NS_HMR_STRICT_PORT` set, a busy preferred port fails instead of * moving to the next one. diff --git a/lib/controllers/run-controller.ts b/lib/controllers/run-controller.ts index 6d24fab353..afafcbe0c1 100644 --- a/lib/controllers/run-controller.ts +++ b/lib/controllers/run-controller.ts @@ -25,10 +25,15 @@ import { } from "../common/declarations"; import { IInjector } from "../common/definitions/yok"; import { ViteHmrPortService } from "../contracts/vite-hmr-port-service"; +import { IOSDeviceTunnelService } from "../contracts/internal/ios-device-tunnel-service"; +import { DevServerOriginService } from "../contracts/internal/dev-server-origin-service"; import { injector } from "../common/yok"; import { isIOSMacDevice } from "../common/mobile/ios/mac/ios-mac-constants"; +import { inject } from "../common/di"; export class RunController extends EventEmitter implements IRunController { + private devServerOriginService = inject(DevServerOriginService); + private iOSDeviceTunnelService = inject(IOSDeviceTunnelService); private prepareReadyEventHandler: any = null; private appRestartRequestHandler: ( request: IBundlerAppRestartRequest, @@ -145,6 +150,7 @@ export class RunController extends EventEmitter implements IRunController { ); this.attachDeviceLostHandler(); + this.attachTunnelLostHandler(); } public async stop(data: IStopRunData): Promise { @@ -168,6 +174,11 @@ export class RunController extends EventEmitter implements IRunController { _.includes(deviceIdentifiersToRemove, descriptor.identifier), ).map((descriptor) => descriptor.identifier); + for (const deviceIdentifier of removedDeviceIdentifiers) { + this.devServerOriginService.forget(deviceIdentifier); + 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++) { @@ -638,6 +649,73 @@ export class RunController extends EventEmitter implements IRunController { ); } + @cache() + private attachTunnelLostHandler(): void { + this.iOSDeviceTunnelService.onTunnelLost((deviceIdentifier) => + this.switchDevServerOrigin(deviceIdentifier), + ); + } + + /** + * Points the device's `dev-server.json` at the origin it can use now and + * restarts only its app, so it reconnects there. + */ + private async switchDevServerOrigin(deviceIdentifier: string): Promise { + const previous = this.devServerOriginService.getOrigin(deviceIdentifier); + if (!previous) { + return; + } + for (const projectDir in this.$liveSyncProcessDataService.getAllPersistedData()) { + const descriptor = _.find( + this.$liveSyncProcessDataService.getDeviceDescriptors(projectDir), + (d) => d.identifier === deviceIdentifier, + ); + if (!descriptor) { + continue; + } + const switched = await this.addActionToChain(projectDir, async () => { + try { + if (!this.devServerOriginService.getOrigin(deviceIdentifier)) { + return false; + } + const device = + this.$devicesService.getDeviceByIdentifier(deviceIdentifier); + const origin = await this.devServerOriginService.chooseOrigin(device); + if (origin === previous) { + return false; + } + const platformLiveSyncService = + this.$liveSyncServiceResolver.resolveLiveSyncService( + device.deviceInfo.platform, + ); + if (!platformLiveSyncService.syncDevServerFile) { + return false; + } + this.$logger.info( + `Switching ${device.deviceInfo.displayName || deviceIdentifier} to the Vite dev server at ${origin} and restarting the app.`, + ); + await platformLiveSyncService.syncDevServerFile( + device, + this.$projectDataService.getProjectData(projectDir), + descriptor, + ); + return true; + } catch (err) { + this.$logger.warn( + `Unable to point ${deviceIdentifier} at another Vite dev server origin: ${err.message || err}. Restart the run to reconnect.`, + ); + return false; + } + }); + if (switched) { + await this.restartApplication({ + projectDir, + deviceIdentifiers: [deviceIdentifier], + }); + } + } + } + private async syncInitialDataOnDevices( projectData: IProjectData, liveSyncInfo: ILiveSyncInfo, @@ -648,7 +726,6 @@ export class RunController extends EventEmitter implements IRunController { platform: string; isEmulator: boolean; }> = {}; - const deviceAction = async (device: Mobile.IDevice) => { const deviceDescriptor = _.find( deviceDescriptors, @@ -667,19 +744,26 @@ export class RunController extends EventEmitter implements IRunController { }, ); - // For Android + Vite HMR, own the `adb reverse` ourselves — - // with our SDK-resolved adb, scoped to this exact serial, and - // only after the device is up — then hand the bundler the - // result via env vars. This MUST run before `prepare` (which - // spawns the Vite bundler that inherits `process.env`) so the - // bundler trusts the tunnel instead of racing us to spawn its - // own adb during config-load. See packages/vite hardening. - await this.setupAndroidViteHmrReverse( + const usesDevServerFile = this.usesDevServerFile( device, projectData, liveSyncInfo, - "pre-build", ); + if (!usesDevServerFile) { + // For Android + Vite HMR, own the `adb reverse` ourselves — + // with our SDK-resolved adb, scoped to this exact serial, and + // only after the device is up — then hand the bundler the + // result via env vars. This MUST run before `prepare` (which + // spawns the Vite bundler that inherits `process.env`) so the + // bundler trusts the tunnel instead of racing us to spawn its + // own adb during config-load. See packages/vite hardening. + await this.setupAndroidViteHmrReverse( + device, + projectData, + liveSyncInfo, + "pre-build", + ); + } const prepareResultData = await this.$prepareController.prepare(prepareData); @@ -746,6 +830,10 @@ export class RunController extends EventEmitter implements IRunController { this.$liveSyncServiceResolver.resolveLiveSyncService( platformData.platformNameLowerCase, ); + if (usesDevServerFile) { + await this.chooseDevServerOrigin(device); + } + const { force, useHotModuleReload, skipWatcher } = liveSyncInfo; const liveSyncResultInfo = await platformLiveSyncService.fullSync({ force, @@ -756,16 +844,18 @@ export class RunController extends EventEmitter implements IRunController { liveSyncDeviceData: deviceDescriptor, }); - // Re-establish the adb reverse on the CURRENT transport right - // before launch — the transport can change during build/install - // and drop the mapping set in `pre-build`, which would leave the - // app unable to reach the Vite dev server at 127.0.0.1. - await this.setupAndroidViteHmrReverse( - device, - projectData, - liveSyncInfo, - "pre-launch", - ); + if (!usesDevServerFile) { + // Re-establish the adb reverse on the CURRENT transport right + // before launch — the transport can change during build/install + // and drop the mapping set in `pre-build`, which would leave the + // app unable to reach the Vite dev server at 127.0.0.1. + await this.setupAndroidViteHmrReverse( + device, + projectData, + liveSyncInfo, + "pre-launch", + ); + } await this.refreshApplication( projectData, @@ -821,10 +911,81 @@ export class RunController extends EventEmitter implements IRunController { ); } + /** + * Whether the device reads its dev server origin from a `dev-server.json` + * the CLI delivers, rather than from the bundle. + */ + private usesDevServerFile( + device: Mobile.IDevice, + projectData: IProjectData, + liveSyncInfo: ILiveSyncInfo, + ): boolean { + return ( + projectData.bundler === "vite" && + !liveSyncInfo.skipWatcher && + !!liveSyncInfo.useHotModuleReload && + !liveSyncInfo.release && + this.$bundlerCompilerService.usesDevServerFile( + device.deviceInfo.platform, + projectData, + ) + ); + } + + /** + * Sets up the device's route to the dev server and records the origin its + * `dev-server.json` carries. Must run before the full sync: that sync + * delivers the file, and on Android it launches the app. + */ + private async chooseDevServerOrigin(device: Mobile.IDevice): Promise { + const { platform, identifier } = device.deviceInfo; + const preferLan = isTruthyEnvFlag(process.env.NS_HMR_PREFER_LAN_HOST); + let adbReverse = false; + let port: number; + if (this.$mobileHelper.isAndroidPlatform(platform)) { + if (!isTruthyEnvFlag(process.env.NS_HMR_NO_ADB_REVERSE) && !preferLan) { + port = await this.$viteHmrPortService.getPort(platform); + try { + adbReverse = await this.ensureAndroidReverse( + device, + identifier, + port, + ); + } catch (err) { + this.$logger.trace( + `Setting up adb reverse tcp:${port} on ${identifier} failed: ${err}`, + ); + } + } + } else if ( + !device.isEmulator && + !preferLan && + !process.env.NS_HMR_HOST?.trim() + ) { + await this.iOSDeviceTunnelService.open(device); + } + + const origin = await this.devServerOriginService.chooseOrigin(device, { + adbReverse, + }); + if (port && !adbReverse) { + this.$logger.warn( + `Could not confirm 'adb reverse tcp:${port}' on ${identifier}, so the app uses the Vite dev server at ${origin}. If this persists, cold-boot or wipe the emulator, or set NS_HMR_NO_ADB_REVERSE=1.`, + ); + } else { + this.$logger.info( + `${device.deviceInfo.displayName || identifier} uses the Vite dev server at ${origin}.`, + ); + } + } + /** * Set up `adb reverse tcp: tcp:` for an Android device * when the project bundles with Vite in HMR/watch mode, then export * the result to the bundler subprocess via environment variables. + * Only for a `@nativescript/vite` that bakes the origin into + * `bundle.mjs`; see `chooseDevServerOrigin` for one that reads + * `dev-server.json`. * * The Vite dev-host helper prefers an ADB tunnel (device-side * `127.0.0.1:` → host) over the emulator's flaky slirp NAT @@ -1176,10 +1337,17 @@ export class RunController extends EventEmitter implements IRunController { } } - await this.$deviceInstallAppService.installOnDeviceIfNeeded( - device, - deviceDescriptor.buildData, - ); + const reinstalled = + await this.$deviceInstallAppService.installOnDeviceIfNeeded( + device, + deviceDescriptor.buildData, + ); + if ( + reinstalled && + this.usesDevServerFile(device, projectData, liveSyncInfo) + ) { + await platformLiveSyncService.syncAfterInstall(device, watchInfo); + } watchInfo.connectTimeout = null; await watchAction(); } diff --git a/lib/definitions/livesync.d.ts b/lib/definitions/livesync.d.ts index 5def3b3910..def8886a2b 100644 --- a/lib/definitions/livesync.d.ts +++ b/lib/definitions/livesync.d.ts @@ -311,6 +311,15 @@ declare global { device: Mobile.IDevice, liveSyncInfo: ILiveSyncWatchInfo, ): Promise; + /** + * Writes the device's current `dev-server.json` into the app already on + * it, outside a full sync. The app reads it when it next starts. + */ + syncDevServerFile?( + device: Mobile.IDevice, + projectData: IProjectData, + liveSyncDeviceData: ILiveSyncDeviceDescriptor, + ): Promise; } interface IRestartApplicationInfo { @@ -413,6 +422,14 @@ declare global { * @returns {Promise} */ sendFile(filePath: string): Promise; + /** + * Sends `content` as the file at `relativeFilePath` in the app directory + * on the device. The runtime writes it before it handles the next operation. + */ + sendFileFromBuffer( + relativeFilePath: string, + content: Buffer, + ): Promise; /** * Sends files through the socket. * @param filePaths - Array of files that will be send by the socket. diff --git a/lib/definitions/run.d.ts b/lib/definitions/run.d.ts index 7a5af896a2..2c54798dd1 100644 --- a/lib/definitions/run.d.ts +++ b/lib/definitions/run.d.ts @@ -41,11 +41,12 @@ declare global { buildData: IBuildData, packageFile?: string, ): Promise; + /** Resolves whether it installed the app. */ installOnDeviceIfNeeded( device: Mobile.IDevice, buildData: IBuildData, packageFile?: string, - ): Promise; + ): Promise; shouldInstall( device: Mobile.IDevice, buildData: IBuildData, diff --git a/lib/services/bundler/bundler-compiler-service.ts b/lib/services/bundler/bundler-compiler-service.ts index 010ab95181..1c9b79440e 100644 --- a/lib/services/bundler/bundler-compiler-service.ts +++ b/lib/services/bundler/bundler-compiler-service.ts @@ -35,7 +35,9 @@ import { } from "../../common/declarations"; import { ICleanupService } from "../../definitions/cleanup-service"; import { ViteHmrPortService } from "../../contracts/vite-hmr-port-service"; +import { DevServerOriginService } from "../../contracts/internal/dev-server-origin-service"; import { injector } from "../../common/yok"; +import { inject } from "../../common/di"; import { resolvePackagePath, resolvePackageJSONPath, @@ -95,6 +97,7 @@ export class BundlerCompilerService extends EventEmitter implements IBundlerCompilerService { + private devServerOriginService = inject(DevServerOriginService); 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 @@ -740,6 +743,7 @@ export class BundlerCompilerService ? await this.getViteChildEnv( platformData.platformNameLowerCase, prepareData, + projectData, ) : {}), }; @@ -796,19 +800,45 @@ export class BundlerCompilerService if (process.env[VITE_SINGLE_PROCESS_ENV] === "0") { return false; } + return this.getViteCliCapabilityPlatforms( + "singleProcessDev", + projectData, + ).includes(platform); + } + + public usesDevServerFile( + platform: string, + projectData: IProjectData, + ): boolean { + return ( + this.getBundler() === "vite" && + this.getViteCliCapabilityPlatforms("devServerFile", projectData).includes( + platform.toLowerCase(), + ) + ); + } + + /** + * The platforms the installed `@nativescript/vite` lists under + * `nativescriptCli.` in its package.json. + */ + private getViteCliCapabilityPlatforms( + capability: "singleProcessDev" | "devServerFile", + 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); + this.$fs.readJson(packageJSONPath)?.nativescriptCli?.[capability]; + return Array.isArray(platforms) ? platforms : []; } catch { - return false; + return []; } } @@ -830,12 +860,16 @@ export class BundlerCompilerService * Environment both Vite children (the build watcher and the dev server) * must share for a platform: the staging directory, and — for HMR * 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. + * handed to `@nativescript/vite` as `NS_HMR_PORT`, so the server's bind, + * the device origins and the `adb reverse` tunnel all match. When the + * devices read their origin from `dev-server.json`, the server also gets + * the token the CLI writes into that file; otherwise the package bakes + * the origin into `bundle.mjs`. */ private async getViteChildEnv( platform: string, prepareData: IPrepareData, + projectData: IProjectData, ): Promise { const env: IStringDictionary = { NS_VITE_DIST_DIR: this.getViteDistRelativeDir(platform), @@ -844,6 +878,9 @@ export class BundlerCompilerService env.NS_HMR_PORT = String( await this.$viteHmrPortService.getPort(platform), ); + if (this.usesDevServerFile(platform, projectData)) { + env.NS_HMR_TOKEN = this.devServerOriginService.getToken(platform); + } } return env; } @@ -858,11 +895,11 @@ export class BundlerCompilerService * baked into the app. Historically users wired this up themselves with * `concurrently`/`wait-on`, which left two uncoordinated processes both * touching adb during cold start (the source of the Android - * "Searching for devices…" freeze). By spawning it here as a child of - * the CLI, the dev server inherits the CLI's environment — crucially - * `NS_ADB_REVERSE_READY`/`NS_DEVICE_SERIAL`/`NS_ADB_PATH` set by the - * run-controller — so the CLI is the single adb owner and the dev - * server never spawns adb itself. + * "Searching for devices…" freeze). The CLI is the single adb owner. A + * `@nativescript/vite` that reads `dev-server.json` knows no device + * origin and never runs adb; an older one inherits the + * `NS_ADB_REVERSE_READY`/`NS_DEVICE_SERIAL`/`NS_ADB_PATH` the + * run-controller sets, so it doesn't spawn adb either. * * No-op unless bundler is vite, HMR is on, watch mode, and not release. * Best-effort: failures are logged, never thrown — a dev-server hiccup @@ -918,7 +955,7 @@ export class BundlerCompilerService hooks: ViteDevServerHooks = {}, ): Promise<{ childProcess: child_process.ChildProcess; port: number }> { const key = platformData.platformNameLowerCase; - const viteEnv = await this.getViteChildEnv(key, prepareData); + const viteEnv = await this.getViteChildEnv(key, prepareData, projectData); const port = Number(viteEnv.NS_HMR_PORT); const envData = this.buildEnvData( diff --git a/lib/services/bundler/bundler.ts b/lib/services/bundler/bundler.ts index 0b6d2997cd..485e08e500 100644 --- a/lib/services/bundler/bundler.ts +++ b/lib/services/bundler/bundler.ts @@ -30,6 +30,12 @@ declare global { prepareData: IPrepareData, ): Promise; stopBundlerCompiler(platform: string): Promise; + /** + * Whether the installed `@nativescript/vite` reads each device's dev + * server origin from a `dev-server.json` the CLI delivers for + * `platform`, instead of baking one origin into the bundle. + */ + usesDevServerFile(platform: string, projectData: IProjectData): boolean; } /** diff --git a/lib/services/bundler/dev-server-origin-service.ts b/lib/services/bundler/dev-server-origin-service.ts new file mode 100644 index 0000000000..2d7e1939bf --- /dev/null +++ b/lib/services/bundler/dev-server-origin-service.ts @@ -0,0 +1,223 @@ +import * as crypto from "crypto"; +import * as net from "net"; +import * as os from "os"; +import { IDictionary } from "../../common/declarations"; +import { isTruthyEnvFlag } from "../../common/helpers"; +import { inject } from "../../common/di"; +import { + DevServerOriginService, + IDevServerOriginOptions, +} from "../../contracts/internal/dev-server-origin-service"; +import { IOSDeviceTunnelService } from "../../contracts/internal/ios-device-tunnel-service"; +import { Logger } from "../../contracts/logger"; +import { ViteHmrPortService } from "../../contracts/vite-hmr-port-service"; + +const LOOPBACK = "127.0.0.1"; +const ANDROID_EMULATOR_HOST = "10.0.2.2"; + +export interface IDevServerOriginInputs { + port: number; + /** The dev server serves https. */ + https?: boolean; + /** `NS_HMR_HOST` as the user set it. */ + envHost?: string; + /** `NS_HMR_PREFER_LAN_HOST`: the LAN address wins over every route but `NS_HMR_HOST`. */ + preferLan?: boolean; + isAndroid: boolean; + isEmulator: boolean; + adbReverse?: boolean; + /** The Mac's address on the device's USB tunnel. */ + tunnelAddress?: string; + lanAddress?: string; +} + +/** + * The origin a device uses for the dev server. The app uses the string + * verbatim as module identity, so it is assembled here rather than + * serialized through a URL parser. + */ +export function chooseDevServerOrigin(inputs: IDevServerOriginInputs): string { + const scheme = inputs.https ? "https" : "http"; + const envHost = inputs.envHost?.trim(); + if (envHost) { + return formatDevServerOrigin(envHost, inputs.port, scheme); + } + return formatDevServerOrigin( + chooseDevServerHost(inputs), + inputs.port, + scheme, + ); +} + +/** Mirrors how `@nativescript/vite` decides to serve https. */ +export function isDevServerHttps(env: NodeJS.ProcessEnv): boolean { + return env.NS_HTTPS === "1" || env.NS_HTTPS === "true"; +} + +function chooseDevServerHost(inputs: IDevServerOriginInputs): string { + if (inputs.preferLan && inputs.lanAddress) { + return inputs.lanAddress; + } + if (inputs.isAndroid) { + if (inputs.adbReverse) { + return LOOPBACK; + } + if (inputs.isEmulator) { + return ANDROID_EMULATOR_HOST; + } + } else { + if (inputs.isEmulator) { + return LOOPBACK; + } + if (inputs.tunnelAddress) { + return inputs.tunnelAddress; + } + } + return inputs.lanAddress || LOOPBACK; +} + +/** + * `://:`, with an IPv6 host bracketed. `host` may carry + * its own port (`host:port`, `[v6]:port`), which then wins over `port`. + */ +export function formatDevServerOrigin( + host: string, + port: number, + scheme: "http" | "https" = "http", +): string { + if (host.startsWith("[")) { + const closing = host.indexOf("]"); + if (closing !== -1) { + const bracketed = host.slice(0, closing + 1); + const explicitPort = parsePort(host.slice(closing + 1)); + return `${scheme}://${bracketed}:${explicitPort ?? port}`; + } + } + if (net.isIPv6(host)) { + return `${scheme}://[${host}]:${port}`; + } + const colon = host.indexOf(":"); + if (colon !== -1 && colon === host.lastIndexOf(":")) { + const explicitPort = parsePort(host.slice(colon)); + if (explicitPort !== undefined) { + return `${scheme}://${host.slice(0, colon)}:${explicitPort}`; + } + } + return `${scheme}://${host}:${port}`; +} + +function parsePort(suffix: string): number | undefined { + if (!/^:\d+$/.test(suffix)) { + return undefined; + } + const port = Number(suffix.slice(1)); + return port > 0 && port <= 65535 ? port : undefined; +} + +/** + * The first external IPv4 address, skipping link-local ones: macOS lists + * 169.254.x.x on AWDL and idle USB interfaces, which other devices can't + * reliably reach. + */ +export function guessLanAddress( + interfaces: NodeJS.Dict, +): string | undefined { + for (const entries of Object.values(interfaces)) { + for (const entry of entries || []) { + const family = entry?.family as string | number; + if ( + !entry || + entry.internal || + (family !== "IPv4" && family !== 4) || + !entry.address || + entry.address.startsWith("169.254.") + ) { + continue; + } + return entry.address; + } + } + return undefined; +} + +export class DevServerOriginServiceImpl implements DevServerOriginService { + private iOSDeviceTunnelService = inject(IOSDeviceTunnelService); + private logger = inject(Logger); + private mobileHelper = inject("mobileHelper"); + private viteHmrPortService = inject(ViteHmrPortService); + + private tokens: IDictionary = {}; + private devices: IDictionary<{ platform: string; origin: string }> = {}; + + public getToken(platform: string): string { + const key = platform.toLowerCase(); + if (!this.tokens[key]) { + this.tokens[key] = crypto.randomBytes(24).toString("base64url"); + } + return this.tokens[key]; + } + + public async chooseOrigin( + device: Mobile.IDevice, + options: IDevServerOriginOptions = {}, + ): Promise { + const { identifier } = device.deviceInfo; + const platform = device.deviceInfo.platform.toLowerCase(); + const isAndroid = this.mobileHelper.isAndroidPlatform(platform); + const inputs: IDevServerOriginInputs = { + port: await this.viteHmrPortService.getPort(platform), + https: isDevServerHttps(process.env), + envHost: process.env.NS_HMR_HOST, + preferLan: isTruthyEnvFlag(process.env.NS_HMR_PREFER_LAN_HOST), + isAndroid, + isEmulator: device.isEmulator, + adbReverse: options.adbReverse, + tunnelAddress: isAndroid + ? undefined + : this.iOSDeviceTunnelService.getHostAddress(identifier), + lanAddress: guessLanAddress(this.getNetworkInterfaces()), + }; + const origin = chooseDevServerOrigin(inputs); + this.devices[identifier] = { platform, origin }; + this.logger.trace( + `Vite dev server origin for ${identifier}: ${origin}`, + inputs, + ); + const reachesLoopback = + device.isEmulator || (isAndroid && options.adbReverse); + if ( + !reachesLoopback && + !inputs.envHost?.trim() && + !inputs.tunnelAddress && + !inputs.lanAddress + ) { + this.logger.warn( + `Found no LAN address on this machine, so ${device.deviceInfo.displayName || identifier} may not reach the Vite dev server at ${origin}. Set NS_HMR_HOST to an address the device can reach.`, + ); + } + return origin; + } + + public getOrigin(deviceIdentifier: string): string | undefined { + return this.devices[deviceIdentifier]?.origin; + } + + public getDevServerFile(deviceIdentifier: string): string | null { + const device = this.devices[deviceIdentifier]; + if (!device) { + return null; + } + return JSON.stringify({ + origin: device.origin, + token: this.getToken(device.platform), + }); + } + + public forget(deviceIdentifier: string): void { + delete this.devices[deviceIdentifier]; + } + + protected getNetworkInterfaces(): NodeJS.Dict { + return os.networkInterfaces(); + } +} diff --git a/lib/services/device/device-install-app-service.ts b/lib/services/device/device-install-app-service.ts index c071d562c0..d21232ca3a 100644 --- a/lib/services/device/device-install-app-service.ts +++ b/lib/services/device/device-install-app-service.ts @@ -97,11 +97,12 @@ export class DeviceInstallAppService implements IDeviceInstallAppService { device: Mobile.IDevice, buildData: IBuildData, packageFile?: string, - ): Promise { + ): Promise { const shouldInstall = await this.shouldInstall(device, buildData); if (shouldInstall) { await this.installOnDevice(device, buildData, packageFile); } + return shouldInstall; } public async shouldInstall( 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..7b1ff23b8e --- /dev/null +++ b/lib/services/ios/ios-device-tunnel-service.ts @@ -0,0 +1,317 @@ +import * as os from "os"; +import * as semver from "semver"; +import { IDictionary } from "../../common/declarations"; +import { inject } from "../../common/di"; +import { ChildProcess } from "../../contracts/child-process"; +import { FileSystem } from "../../contracts/file-system"; +import { HostInfo } from "../../contracts/host-info"; +import { IOSDeviceTunnelService } from "../../contracts/internal/ios-device-tunnel-service"; +import { Logger } from "../../contracts/logger"; +import { TempService } from "../../contracts/temp-service"; +import { ICleanupService } from "../../definitions/cleanup-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 { + holder?: child_process.ChildProcess; + address: Promise; + closed: boolean; +} + +export class IOSDeviceTunnelServiceImpl implements 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 tunnelLostListeners: ((deviceIdentifier: string) => void)[] = []; + private tunnelReadyTimeoutMs = 10000; + private tunnelPollIntervalMs = 500; + private listTimeoutMs = 10000; + + public open(device: Mobile.IDevice): Promise { + const id = device.deviceInfo.identifier; + if (!this.tunnels[id]) { + const tunnel: ITunnel = { + 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(deviceIdentifier: string): string | undefined { + return this.hostAddresses[deviceIdentifier]; + } + + public onTunnelLost(listener: (deviceIdentifier: string) => void): void { + this.tunnelLostListeners.push(listener); + } + + public async close(deviceIdentifier: string): Promise { + const tunnel = this.tunnels[deviceIdentifier]; + if (!tunnel) { + return; + } + delete this.tunnels[deviceIdentifier]; + delete this.hostAddresses[deviceIdentifier]; + tunnel.closed = true; + this.stopHolder(tunnel); + await tunnel.address; + } + + 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[id] = 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 { + // A wedged CoreDevice service can leave devicectl running indefinitely. + const result = await this.childProcess.trySpawnFromCloseEvent( + "xcrun", + ["devicectl", "list", "devices", "--quiet", "--json-output", jsonPath], + {}, + { throwError: false, timeout: this.listTimeoutMs }, + ); + 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) { + return; + } + tunnel.closed = true; + if (this.tunnels[deviceIdentifier] === tunnel) { + delete this.tunnels[deviceIdentifier]; + delete this.hostAddresses[deviceIdentifier]; + } + this.logger.warn( + `The USB tunnel to ${deviceIdentifier} closed, so the app can no longer reach the Vite dev server at ${address}.`, + ); + for (const listener of this.tunnelLostListeners) { + listener(deviceIdentifier); + } + }); + }); + 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; +} diff --git a/lib/services/livesync/android-device-livesync-sockets-service.ts b/lib/services/livesync/android-device-livesync-sockets-service.ts index 6fc9d31e69..8b64c67857 100644 --- a/lib/services/livesync/android-device-livesync-sockets-service.ts +++ b/lib/services/livesync/android-device-livesync-sockets-service.ts @@ -13,6 +13,9 @@ import { IInjector } from "../../common/definitions/yok"; import { ICleanupService } from "../../definitions/cleanup-service"; import { ISpawnCommandInfo } from "../../detached-processes/cleanup-process-definitions"; import { ITempService } from "../../definitions/temp-service"; +import { inject } from "../../common/di"; +import { DevServerOriginService } from "../../contracts/internal/dev-server-origin-service"; +import { DEV_SERVER_FILE_NAME } from "../../constants"; /** * Whether a file sync asks the app to refresh itself in place. Never under @@ -36,6 +39,7 @@ export class AndroidDeviceSocketsLiveSyncService IAndroidNativeScriptDeviceLiveSyncService, INativeScriptDeviceLiveSyncService { + private devServerOriginService = inject(DevServerOriginService); private livesyncTool: IAndroidLivesyncTool; private static STATUS_UPDATE_INTERVAL = 10000; private static MINIMAL_VERSION_LONG_LIVING_CONNECTION = "0.2.0"; @@ -141,7 +145,21 @@ export class AndroidDeviceSocketsLiveSyncService let result = { operationId, didRefresh: true }; - if (liveSyncInfo.modifiedFilesData.length) { + const devServerFile = liveSyncInfo.isFullSync + ? this.devServerOriginService.getDevServerFile( + this.device.deviceInfo.identifier, + ) + : null; + if (devServerFile) { + await this.livesyncTool.sendFileFromBuffer( + DEV_SERVER_FILE_NAME, + Buffer.from(devServerFile), + ); + } + + // The runtime acknowledges only DO_SYNC, after it has written every + // file sent before it. + if (liveSyncInfo.modifiedFilesData.length || devServerFile) { const canExecuteFastSync = refreshesInPlaceOnSync(liveSyncInfo, projectData) && this.canExecuteFastSyncForPaths( diff --git a/lib/services/livesync/android-livesync-service.ts b/lib/services/livesync/android-livesync-service.ts index 8ff185ca0d..54cfd2c3d6 100644 --- a/lib/services/livesync/android-livesync-service.ts +++ b/lib/services/livesync/android-livesync-service.ts @@ -14,12 +14,15 @@ import { import { IInjector } from "../../common/definitions/yok"; import { injector } from "../../common/yok"; import { IOptions } from "../../declarations"; +import { inject } from "../../common/di"; +import { DevServerOriginService } from "../../contracts/internal/dev-server-origin-service"; export class AndroidLiveSyncService extends PlatformLiveSyncServiceBase implements IPlatformLiveSyncService { private static MIN_SOCKETS_LIVESYNC_RUNTIME_VERSION = "4.2.0-2018-07-20-02"; + private devServerOriginService = inject(DevServerOriginService); constructor( protected $platformsDataService: IPlatformsDataService, protected $projectFilesManager: IProjectFilesManager, @@ -27,7 +30,7 @@ export class AndroidLiveSyncService $devicePathProvider: IDevicePathProvider, $fs: IFileSystem, $logger: ILogger, - $options: IOptions + $options: IOptions, ) { super( $fs, @@ -35,46 +38,46 @@ export class AndroidLiveSyncService $platformsDataService, $projectFilesManager, $devicePathProvider, - $options + $options, ); } protected _getDeviceLiveSyncService( device: Mobile.IDevice, data: IProjectDir, - frameworkVersion: string + frameworkVersion: string, ): INativeScriptDeviceLiveSyncService { if ( semver.gt( frameworkVersion, - AndroidLiveSyncService.MIN_SOCKETS_LIVESYNC_RUNTIME_VERSION + AndroidLiveSyncService.MIN_SOCKETS_LIVESYNC_RUNTIME_VERSION, ) ) { return this.$injector.resolve( AndroidDeviceSocketsLiveSyncService, - { device, data } + { device, data }, ); } return this.$injector.resolve( AndroidDeviceLiveSyncService, - { device, data } + { device, data }, ); } @performanceLog() public async liveSyncWatchAction( device: Mobile.IDevice, - liveSyncInfo: ILiveSyncWatchInfo + liveSyncInfo: ILiveSyncWatchInfo, ): Promise { const liveSyncResult = await super.liveSyncWatchAction( device, - liveSyncInfo + liveSyncInfo, ); const result = await this.finalizeSync( device, liveSyncInfo.projectData, - liveSyncResult + liveSyncResult, ); return result; @@ -82,28 +85,52 @@ export class AndroidLiveSyncService @performanceLog() public async fullSync( - syncInfo: IFullSyncInfo + syncInfo: IFullSyncInfo, ): Promise { const liveSyncResult = await super.fullSync(syncInfo); const result = await this.finalizeSync( syncInfo.device, syncInfo.projectData, - liveSyncResult + liveSyncResult, ); return result; } + /** + * The first launch of a new APK replaces the app directory with the + * APK's, which drops `dev-server.json`, so it is synced again. + */ + public async syncAfterInstall( + device: Mobile.IDevice, + liveSyncInfo: ILiveSyncWatchInfo, + ): Promise { + if ( + !this.devServerOriginService.getDevServerFile( + device.deviceInfo.identifier, + ) + ) { + return; + } + await this.fullSync({ + projectData: liveSyncInfo.projectData, + device, + liveSyncDeviceData: liveSyncInfo.liveSyncDeviceData, + watch: true, + useHotModuleReload: liveSyncInfo.useHotModuleReload, + }); + } + private async finalizeSync( device: Mobile.IDevice, projectData: IProjectData, - liveSyncResult: ILiveSyncResultInfo + liveSyncResult: ILiveSyncResultInfo, ): Promise { const liveSyncService = ( this.getDeviceLiveSyncService(device, projectData) ); const finalizeResult = await liveSyncService.finalizeSync( liveSyncResult, - projectData + projectData, ); const result = _.extend(liveSyncResult, finalizeResult); return result; diff --git a/lib/services/livesync/android-livesync-tool.ts b/lib/services/livesync/android-livesync-tool.ts index 9057a64c79..cce307d954 100644 --- a/lib/services/livesync/android-livesync-tool.ts +++ b/lib/services/livesync/android-livesync-tool.ts @@ -103,10 +103,25 @@ export class AndroidLivesyncTool implements IAndroidLivesyncTool { } public async sendFile(filePath: string): Promise { - await this.sendFileHeader(filePath); + this.verifyActiveConnection(); + const stats = this.$fs.getFsStats(filePath); + await this.sendFileHeader(this.resolveRelativePath(filePath), stats.size); await this.sendFileContent(filePath); } + public async sendFileFromBuffer( + relativeFilePath: string, + content: Buffer, + ): Promise { + this.verifyActiveConnection(); + await this.sendFileHeader( + this.$mobileHelper.buildDevicePath(relativeFilePath), + content.length, + ); + await this.writeToSocket(content); + await this.writeToSocket(crypto.createHash("md5").update(content).digest()); + } + public async sendFiles(filePaths: string[]) { for (const filePath of filePaths) { if (this.$fs.getLsStats(filePath).isFile()) { @@ -245,11 +260,12 @@ export class AndroidLivesyncTool implements IAndroidLivesyncTool { return !!this.socketConnection; } - private async sendFileHeader(filePath: string): Promise { + private async sendFileHeader( + relativeFilePath: string, + fileContentLengthBytes: number, + ): Promise { this.verifyActiveConnection(); - const filePathData = this.getFilePathData(filePath); - const stats = this.$fs.getFsStats(filePathData.filePath); - const fileContentLengthBytes = stats.size; + const filePathData = this.getRelativePathData(relativeFilePath); const fileContentLengthString = fileContentLengthBytes.toString(); const fileContentLengthSize = Buffer.byteLength(fileContentLengthString); const headerBuffer = Buffer.alloc( @@ -572,9 +588,16 @@ export class AndroidLivesyncTool implements IAndroidLivesyncTool { filePathLengthBytes: number; filePathLengthString: string; filePathLengthSize: number; - filePath: string; } { - const relativeFilePath = this.resolveRelativePath(filePath); + return this.getRelativePathData(this.resolveRelativePath(filePath)); + } + + private getRelativePathData(relativeFilePath: string): { + relativeFilePath: string; + filePathLengthBytes: number; + filePathLengthString: string; + filePathLengthSize: number; + } { const filePathLengthBytes = Buffer.byteLength(relativeFilePath); const filePathLengthString = filePathLengthBytes.toString(); const filePathLengthSize = Buffer.byteLength(filePathLengthString); @@ -584,7 +607,6 @@ export class AndroidLivesyncTool implements IAndroidLivesyncTool { filePathLengthBytes, filePathLengthString, filePathLengthSize, - filePath, }; } diff --git a/lib/services/livesync/ios-livesync-service.ts b/lib/services/livesync/ios-livesync-service.ts index cedcf2b5c2..f64cb2fc12 100644 --- a/lib/services/livesync/ios-livesync-service.ts +++ b/lib/services/livesync/ios-livesync-service.ts @@ -2,10 +2,11 @@ import * as path from "path"; import { IOSDeviceLiveSyncService } from "./ios-device-livesync-service"; import { PlatformLiveSyncServiceBase } from "./platform-livesync-service-base"; -import { APP_FOLDER_NAME } from "../../constants"; +import { APP_FOLDER_NAME, DEV_SERVER_FILE_NAME } from "../../constants"; import { LiveSyncPaths } from "../../common/constants"; import { performanceLog } from "../../common/decorators"; import { IPlatformsDataService } from "../../definitions/platform"; +import { IProjectData } from "../../definitions/project"; import { IFileSystem, IProjectFilesManager, @@ -15,11 +16,15 @@ import { IInjector } from "../../common/definitions/yok"; import { injector } from "../../common/yok"; import { ITempService } from "../../definitions/temp-service"; import { IOptions } from "../../declarations"; +import { inject } from "../../common/di"; +import { DevServerOriginService } from "../../contracts/internal/dev-server-origin-service"; export class IOSLiveSyncService extends PlatformLiveSyncServiceBase implements IPlatformLiveSyncService { + private devServerOriginService = inject(DevServerOriginService); + constructor( protected $fs: IFileSystem, protected $platformsDataService: IPlatformsDataService, @@ -45,7 +50,9 @@ export class IOSLiveSyncService const device = syncInfo.device; if (device.isEmulator) { - return super.fullSync(syncInfo); + const result = await super.fullSync(syncInfo); + await this.writeDevServerFile(result.deviceAppData); + return result; } const projectData = syncInfo.projectData; const platformData = this.$platformsDataService.getPlatformData( @@ -66,10 +73,18 @@ export class IOSLiveSyncService const filesToTransfer = this.$fs.enumerateFilesInDirectorySync(projectFilesPath); + const devServerFile = await this.createDevServerFile( + device.deviceInfo.identifier, + ); - await this.$fs.zipFiles(tempZip, filesToTransfer, (res) => { - return path.join(APP_FOLDER_NAME, path.relative(projectFilesPath, res)); - }); + await this.$fs.zipFiles( + tempZip, + devServerFile ? [...filesToTransfer, devServerFile] : filesToTransfer, + (res) => + res === devServerFile + ? path.join(APP_FOLDER_NAME, DEV_SERVER_FILE_NAME) + : path.join(APP_FOLDER_NAME, path.relative(projectFilesPath, res)), + ); const deviceProjectRootPath = await deviceAppData.getDeviceProjectRootPath(); @@ -234,7 +249,17 @@ export class IOSLiveSyncService device: Mobile.IDevice, liveSyncInfo: ILiveSyncWatchInfo, ): Promise { - if (!device.isEmulator) { + if (device.isEmulator) { + await this.writeDevServerFile( + await this.getAppData({ + projectData: liveSyncInfo.projectData, + device, + liveSyncDeviceData: liveSyncInfo.liveSyncDeviceData, + watch: true, + useHotModuleReload: liveSyncInfo.useHotModuleReload, + }), + ); + } else { // In this case we should execute fullsync because iOS Runtime requires the full content of app dir to be extracted in the root of sync dir. await this.fullSync({ projectData: liveSyncInfo.projectData, @@ -246,6 +271,62 @@ export class IOSLiveSyncService } } + public async syncDevServerFile( + device: Mobile.IDevice, + projectData: IProjectData, + liveSyncDeviceData: ILiveSyncDeviceDescriptor, + ): Promise { + await this.writeDevServerFile( + await this.getAppData({ + projectData, + device, + liveSyncDeviceData, + watch: true, + useHotModuleReload: true, + }), + ); + } + + /** + * Writes the device's `dev-server.json` next to `bundle.mjs` in the + * installed app (a simulator) or the synced one (a device). + */ + private async writeDevServerFile( + deviceAppData: Mobile.IDeviceAppData, + ): Promise { + const localPath = await this.createDevServerFile( + deviceAppData.device.deviceInfo.identifier, + ); + if (!localPath) { + return; + } + const devicePath = path.join( + await deviceAppData.getDeviceProjectRootPath(), + DEV_SERVER_FILE_NAME, + ); + await deviceAppData.device.fileSystem.putFile( + localPath, + devicePath, + deviceAppData.appIdentifier, + ); + } + + private async createDevServerFile( + deviceIdentifier: string, + ): Promise { + const content = + this.devServerOriginService.getDevServerFile(deviceIdentifier); + if (!content) { + return null; + } + const localPath = await this.$tempService.path({ + prefix: "dev-server", + suffix: ".json", + }); + this.$fs.writeFile(localPath, content); + return localPath; + } + protected _getDeviceLiveSyncService( device: Mobile.IDevice, data: IProjectDir, diff --git a/test/controllers/run-controller.ts b/test/controllers/run-controller.ts index e8d419eb3b..d5ff0675fc 100644 --- a/test/controllers/run-controller.ts +++ b/test/controllers/run-controller.ts @@ -16,6 +16,9 @@ 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/internal/ios-device-tunnel-service"; +import { DevServerOriginService } from "../../lib/contracts/internal/dev-server-origin-service"; +import { DevServerOriginServiceImpl } from "../../lib/services/bundler/dev-server-origin-service"; let isAttachToHmrStatusCalled = false; let prepareData: IPrepareData = null; @@ -142,6 +145,19 @@ function createTestInjector() { injector.register("viteHmrPortService", { getPort: async () => 5173, }); + injector.register({ + provide: IOSDeviceTunnelService, + useValue: { + open: async (): Promise => null, + getHostAddress: (): string => undefined, + close: async () => ({}), + onTunnelLost: (): void => undefined, + }, + }); + injector.register({ + provide: DevServerOriginService, + useClass: DevServerOriginServiceImpl, + }); const devicesService = injector.resolve("devicesService"); devicesService.getDevicesForPlatform = () => @@ -266,6 +282,513 @@ describe("RunController", () => { }); }); + describe("Vite dev server origin", () => { + const secondIOSDevice = { + deviceInfo: { identifier: "mySecondiOSDevice", platform: "ios" }, + }; + const secondIOSDeviceDescriptor = { + identifier: "mySecondiOSDevice", + buildAction: async () => buildOutputPath, + buildData: {}, + }; + const iOSSimulator = { + deviceInfo: { identifier: "myiOSSimulator", platform: "ios" }, + isEmulator: true, + }; + const iOSSimulatorDescriptor = { + identifier: "myiOSSimulator", + buildAction: async () => buildOutputPath, + buildData: {}, + }; + const adbCalls: string[][] = []; + const androidEmulator = { + deviceInfo: { identifier: "emulator-5554", platform: "android" }, + isEmulator: true, + adb: { + executeCommand: async (args: string[]) => { + adbCalls.push(args); + events.push(`adb ${args.join(" ")}`); + return args.join(" ") === "reverse --list" && reverseWorks + ? "emulator-5554 tcp:5173 tcp:5173" + : ""; + }, + }, + }; + const androidEmulatorDescriptor = { + identifier: "emulator-5554", + buildAction: async () => buildOutputPath, + buildData: {}, + }; + const androidPhone = { + deviceInfo: { identifier: "R5CT21", platform: "android" }, + isEmulator: false, + adb: androidEmulator.adb, + }; + const lanAddress = "192.168.1.20"; + const hmrLiveSyncInfo = { ...liveSyncInfo, useHotModuleReload: true }; + const envNames = [ + "NS_HMR_HOST", + "NS_HMR_NO_ADB_REVERSE", + "NS_HMR_PREFER_LAN_HOST", + "NS_ADB_REVERSE_READY", + "NS_DEVICE_SERIAL", + "NS_ADB_PATH", + ]; + let previousEnv: IDictionary = null; + let tunnelAddresses: IDictionary = null; + let openedFor: string[] = null; + let closed: string[] = null; + let events: string[] = null; + let filesAtFullSync: IDictionary = null; + let devServerFilePlatforms: string[]; + let reverseWorks: boolean; + let tunnelLost: (deviceIdentifier: string) => Promise; + let rewritten: { device: string; file: string }[]; + let restarted: string[]; + + let syncFailures: string[]; + + const run = async (devices: any[], info: any = hmrLiveSyncInfo) => { + mockDevicesService(injector, devices); + await runController.run({ + liveSyncInfo: info, + deviceDescriptors: devices.map((device) => ({ + ...map[device.deviceInfo.identifier].descriptor, + buildData: { nativePrepare: {} }, + })), + }); + assert.deepStrictEqual(syncFailures, []); + }; + + beforeEach(() => { + devServerFilePlatforms = ["ios", "android"]; + reverseWorks = true; + injector.resolve("bundlerCompilerService").usesDevServerFile = ( + platform: string, + ) => devServerFilePlatforms.includes(platform.toLowerCase()); + tunnelAddresses = {}; + openedFor = []; + closed = []; + events = []; + adbCalls.length = 0; + filesAtFullSync = {}; + previousEnv = {}; + for (const name of envNames) { + previousEnv[name] = process.env[name]; + delete process.env[name]; + } + map.mySecondiOSDevice = { + device: secondIOSDevice, + descriptor: secondIOSDeviceDescriptor, + }; + map.myiOSSimulator = { + device: iOSSimulator, + descriptor: iOSSimulatorDescriptor, + }; + map["emulator-5554"] = { + device: androidEmulator, + descriptor: androidEmulatorDescriptor, + }; + map.R5CT21 = { + device: androidPhone, + descriptor: { ...androidEmulatorDescriptor, identifier: "R5CT21" }, + }; + + const projectDataService = injector.resolve("projectDataService"); + const getProjectData = + projectDataService.getProjectData.bind(projectDataService); + projectDataService.getProjectData = (dir: string) => { + const projectData = getProjectData(dir); + projectData.bundler = "vite"; + return projectData; + }; + const tunnelService = injector.get(IOSDeviceTunnelService); + tunnelService.open = async (device: Mobile.IDevice) => { + const id = device.deviceInfo.identifier; + openedFor.push(id); + events.push(`tunnel ${id}`); + tunnelAddresses[id] = `fd00::${openedFor.length}`; + return tunnelAddresses[id]; + }; + tunnelService.getHostAddress = (id: string) => tunnelAddresses[id]; + tunnelLost = null; + tunnelService.onTunnelLost = (listener: any) => { + tunnelLost = listener; + }; + rewritten = []; + restarted = []; + injector.resolve("devicesService").getDeviceByIdentifier = ( + identifier: string, + ) => map[identifier]?.device; + 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, + }; + }; + syncFailures = []; + injector.resolve("logger").warn = (message: string) => { + if (/^Unable to /.test(message)) { + syncFailures.push(message); + } + }; + injector.resolve("buildController").shouldBuild = async () => false; + injector.resolve("platformsDataService").getPlatformData = ( + platform: string, + ) => ({ platformNameLowerCase: platform.toLowerCase() }); + injector.resolve("analyticsService").trackEventActionInGoogleAnalytics = + async (): Promise => undefined; + const devServerOriginService = injector.get(DevServerOriginService); + (devServerOriginService).getNetworkInterfaces = () => ({ + en0: [{ address: lanAddress, family: "IPv4", internal: false }], + }); + for (const name of ["iOSLiveSyncService", "androidLiveSyncService"]) { + const liveSyncService = injector.resolve(name); + liveSyncService.fullSync = async (syncInfo: IFullSyncInfo) => { + const id = syncInfo.device.deviceInfo.identifier; + events.push(`fullSync ${id}`); + filesAtFullSync[id] = devServerOriginService.getDevServerFile(id); + return { + ...getFullSyncResult(), + deviceAppData: { + appIdentifier, + device: syncInfo.device, + platform: syncInfo.device.deviceInfo.platform, + }, + }; + }; + liveSyncService.shouldRestart = async () => true; + liveSyncService.restartApplication = async ( + _projectData: any, + result: ILiveSyncResultInfo, + ) => { + restarted.push(result.deviceAppData.device.deviceInfo.identifier); + }; + liveSyncService.getAppData = async (syncInfo: IFullSyncInfo) => ({ + appIdentifier, + device: syncInfo.device, + platform: syncInfo.device.deviceInfo.platform, + }); + } + injector.resolve("iOSLiveSyncService").syncDevServerFile = async ( + device: Mobile.IDevice, + ) => { + rewritten.push({ + device: device.deviceInfo.identifier, + file: devServerOriginService.getDevServerFile( + device.deviceInfo.identifier, + ), + }); + }; + }); + + afterEach(() => { + delete map.mySecondiOSDevice; + delete map.myiOSSimulator; + delete map["emulator-5554"]; + delete map.R5CT21; + for (const name of envNames) { + if (previousEnv[name] === undefined) { + delete process.env[name]; + } else { + process.env[name] = previousEnv[name]; + } + } + }); + + it("gives each physical iOS device its own tunnel origin", async () => { + await run([iOSDevice, secondIOSDevice]); + + assert.deepStrictEqual(openedFor, ["myiOSDevice", "mySecondiOSDevice"]); + const token = injector.get(DevServerOriginService).getToken("ios"); + assert.deepStrictEqual( + _.mapValues(filesAtFullSync, (file) => JSON.parse(file)), + { + myiOSDevice: { origin: "http://[fd00::1]:5173", token }, + mySecondiOSDevice: { origin: "http://[fd00::2]:5173", token }, + }, + ); + }); + + it("opens a device's tunnel before its full sync, after preparing", async () => { + await run([iOSDevice]); + + assert.deepStrictEqual(events, [ + "prepare ios", + "tunnel myiOSDevice", + "fullSync myiOSDevice", + ]); + }); + + it("points a simulator at the loopback without a tunnel", async () => { + await run([iOSSimulator]); + + assert.deepStrictEqual(openedFor, []); + assert.equal( + JSON.parse(filesAtFullSync.myiOSSimulator).origin, + "http://127.0.0.1:5173", + ); + }); + + it("uses a user-set NS_HMR_HOST for every device and opens no tunnel", async () => { + process.env.NS_HMR_HOST = "dev.example.test:8443"; + + await run([iOSDevice, iOSSimulator]); + + assert.deepStrictEqual(openedFor, []); + assert.deepStrictEqual( + _.mapValues(filesAtFullSync, (file) => JSON.parse(file).origin), + { + myiOSDevice: "http://dev.example.test:8443", + myiOSSimulator: "http://dev.example.test:8443", + }, + ); + }); + + it("sets up adb reverse before the Android full sync and uses the loopback", async () => { + await run([androidEmulator]); + + assert.equal( + JSON.parse(filesAtFullSync["emulator-5554"]).origin, + "http://127.0.0.1:5173", + ); + assert.isBelow( + events.indexOf("adb reverse tcp:5173 tcp:5173"), + events.indexOf("fullSync emulator-5554"), + ); + assert.isBelow( + events.indexOf("prepare android"), + events.indexOf("adb reverse tcp:5173 tcp:5173"), + ); + assert.isUndefined(process.env.NS_ADB_REVERSE_READY); + assert.isUndefined(process.env.NS_DEVICE_SERIAL); + assert.isUndefined(process.env.NS_ADB_PATH); + }); + + it("falls back to 10.0.2.2 on an emulator whose reverse fails", async () => { + reverseWorks = false; + + await run([androidEmulator]); + + assert.equal( + JSON.parse(filesAtFullSync["emulator-5554"]).origin, + "http://10.0.2.2:5173", + ); + }); + + it("gives a physical Android device without adb reverse the LAN origin", async () => { + process.env.NS_HMR_NO_ADB_REVERSE = "1"; + + await run([androidPhone]); + + assert.deepStrictEqual(adbCalls, []); + assert.equal( + JSON.parse(filesAtFullSync.R5CT21).origin, + `http://${lanAddress}:5173`, + ); + }); + + it("gives every device the LAN origin when the user prefers it", async () => { + process.env.NS_HMR_PREFER_LAN_HOST = "1"; + + await run([androidEmulator, iOSDevice, iOSSimulator]); + + assert.deepStrictEqual(adbCalls, []); + assert.deepStrictEqual(openedFor, []); + assert.deepStrictEqual( + _.mapValues(filesAtFullSync, (file) => JSON.parse(file).origin), + { + "emulator-5554": `http://${lanAddress}:5173`, + myiOSDevice: `http://${lanAddress}:5173`, + myiOSSimulator: `http://${lanAddress}:5173`, + }, + ); + }); + + describe("when a failed fast sync reinstalls the app", () => { + let watchActions: number; + let afterInstall: string[]; + let reinstalls: boolean; + + const syncChange = async (device: any) => { + const projectData = injector + .resolve("projectDataService") + .getProjectData(projectDir); + await (runController).syncChangedDataOnDevices( + { + files: ["/project/platforms/app/bundle.mjs"], + staleFiles: [], + hasOnlyHotUpdateFiles: false, + hasNativeChanges: false, + hmrData: null, + platform: device.deviceInfo.platform, + }, + projectData, + hmrLiveSyncInfo, + ); + }; + + beforeEach(() => { + watchActions = 0; + afterInstall = []; + reinstalls = true; + injector.resolve("deviceInstallAppService").installOnDeviceIfNeeded = + async () => reinstalls; + for (const name of ["iOSLiveSyncService", "androidLiveSyncService"]) { + const liveSyncService = injector.resolve(name); + liveSyncService.liveSyncWatchAction = async ( + device: Mobile.IDevice, + ) => { + if (++watchActions === 1) { + throw new Error("app not running"); + } + return { + modifiedFilesData: [], + isFullSync: false, + useHotModuleReload: true, + deviceAppData: { + appIdentifier, + device, + platform: device.deviceInfo.platform, + }, + }; + }; + liveSyncService.syncAfterInstall = async (device: Mobile.IDevice) => { + afterInstall.push(device.deviceInfo.identifier); + }; + } + }); + + for (const target of [androidEmulator, iOSSimulator, iOSDevice]) { + it(`delivers dev-server.json again to ${target.deviceInfo.identifier}`, async () => { + await run([target]); + + await syncChange(target); + + assert.deepStrictEqual(afterInstall, [target.deviceInfo.identifier]); + assert.equal(watchActions, 2); + }); + } + + it("delivers nothing when nothing was reinstalled", async () => { + reinstalls = false; + await run([iOSSimulator]); + + await syncChange(iOSSimulator); + + assert.deepStrictEqual(afterInstall, []); + }); + + it("delivers nothing for a @nativescript/vite without dev-server.json", async () => { + devServerFilePlatforms = []; + await run([iOSSimulator]); + + await syncChange(iOSSimulator); + + assert.deepStrictEqual(afterInstall, []); + }); + }); + + it("skips adb reverse when the user opts out", async () => { + process.env.NS_HMR_NO_ADB_REVERSE = "1"; + + await run([androidEmulator]); + + assert.deepStrictEqual(adbCalls, []); + assert.equal( + JSON.parse(filesAtFullSync["emulator-5554"]).origin, + "http://10.0.2.2:5173", + ); + }); + + it("keeps the bundle's origin and the bundler env for a @nativescript/vite without dev-server.json", async () => { + devServerFilePlatforms = []; + + await run([iOSDevice, androidEmulator]); + + assert.deepStrictEqual(openedFor, []); + assert.deepStrictEqual(filesAtFullSync, { + myiOSDevice: null, + "emulator-5554": null, + }); + assert.equal(process.env.NS_ADB_REVERSE_READY, "1"); + assert.equal(process.env.NS_DEVICE_SERIAL, "emulator-5554"); + assert.equal(process.env.NS_ADB_PATH, "adb"); + assert.isBelow( + events.indexOf("adb reverse tcp:5173 tcp:5173"), + events.indexOf("prepare android"), + ); + }); + + it("chooses no origin without HMR", async () => { + await run([iOSDevice], liveSyncInfo); + + assert.deepStrictEqual(openedFor, []); + assert.deepStrictEqual(filesAtFullSync, { myiOSDevice: null }); + }); + + it("rewrites the file of a device whose tunnel drops and restarts only its app", async () => { + await run([iOSDevice, secondIOSDevice]); + restarted = []; + const before = injector + .get(DevServerOriginService) + .getOrigin("mySecondiOSDevice"); + + delete tunnelAddresses.myiOSDevice; + await tunnelLost("myiOSDevice"); + + assert.lengthOf(rewritten, 1); + assert.equal(rewritten[0].device, "myiOSDevice"); + assert.notInclude(JSON.parse(rewritten[0].file).origin, "fd00::1"); + assert.deepStrictEqual(restarted, ["myiOSDevice"]); + assert.equal( + injector.get(DevServerOriginService).getOrigin("mySecondiOSDevice"), + before, + ); + }); + + it("leaves a device alone when its origin does not change", async () => { + process.env.NS_HMR_HOST = "dev.example.test"; + await run([iOSDevice]); + restarted = []; + + await tunnelLost("myiOSDevice"); + + assert.deepStrictEqual(rewritten, []); + assert.deepStrictEqual(restarted, []); + }); + + it("ignores a tunnel loss for a device on the bundle-baked origin", async () => { + devServerFilePlatforms = []; + await run([iOSDevice]); + restarted = []; + + await tunnelLost("myiOSDevice"); + + assert.deepStrictEqual(rewritten, []); + assert.deepStrictEqual(restarted, []); + }); + + it("forgets the origin and closes the tunnel of a device that stops", async () => { + await run([iOSDevice]); + + await runController.stop({ + projectDir, + deviceIdentifiers: ["myiOSDevice"], + }); + + assert.deepStrictEqual(closed, ["myiOSDevice"]); + assert.isNull( + injector.get(DevServerOriginService).getDevServerFile("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 dea9e43b01..671c9390c8 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 { DevServerOriginService } from "../../../lib/contracts/internal/dev-server-origin-service"; import { BUNDLER_APP_RESTART_REQUESTED, BUNDLER_COMPILATION_COMPLETE, @@ -92,6 +93,10 @@ function createTestInjector( testInjector.register("viteHmrPortService", { getPort: async () => 5173, }); + testInjector.register({ + provide: DevServerOriginService, + useValue: { getToken: (): string => "token" }, + }); return testInjector; } @@ -374,6 +379,95 @@ describe("BundlerCompilerService", () => { { NS_VITE_DIST_DIR: ".ns-vite-build/ios" }, ); }); + + describe("when the devices read dev-server.json", () => { + let projectDir: string; + beforeEach(() => { + projectDir = fs.mkdtempSync(path.join(os.tmpdir(), "ns-vite-dsf-")); + const dir = path.join( + projectDir, + "node_modules", + "@nativescript", + "vite", + ); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync( + path.join(dir, "package.json"), + JSON.stringify({ + name: "@nativescript/vite", + nativescriptCli: { devServerFile: ["ios"] }, + }), + ); + testInjector.resolve("fs").readJson = (file: string) => + JSON.parse(fs.readFileSync(file, "utf8")); + testInjector.get(DevServerOriginService).getToken = ( + platform: string, + ) => `token-${platform}`; + }); + afterEach(() => { + fs.rmSync(projectDir, { recursive: true, force: true }); + }); + + it("hands the dev server the platform's token", async () => { + assert.deepEqual( + await (bundlerCompilerService).getViteChildEnv( + "ios", + { watch: true, hmr: true }, + { projectDir }, + ), + { + NS_VITE_DIST_DIR: ".ns-vite-build/ios", + NS_HMR_PORT: "5173", + NS_HMR_TOKEN: "token-ios", + }, + ); + }); + + it("hands over the token in two-process mode too", async () => { + const previous = process.env.NS_VITE_SINGLE_PROCESS; + process.env.NS_VITE_SINGLE_PROCESS = "0"; + try { + assert.equal( + ( + await (bundlerCompilerService).getViteChildEnv( + "ios", + { watch: true, hmr: true }, + { projectDir }, + ) + ).NS_HMR_TOKEN, + "token-ios", + ); + } finally { + if (previous === undefined) { + delete process.env.NS_VITE_SINGLE_PROCESS; + } else { + process.env.NS_VITE_SINGLE_PROCESS = previous; + } + } + }); + + it("passes no token for a platform the package does not list", async () => { + assert.notProperty( + await (bundlerCompilerService).getViteChildEnv( + "android", + { watch: true, hmr: true }, + { projectDir }, + ), + "NS_HMR_TOKEN", + ); + }); + + it("passes no token to a build that runs no dev server", async () => { + assert.notProperty( + await (bundlerCompilerService).getViteChildEnv( + "ios", + { watch: true, hmr: true, release: true }, + { projectDir }, + ), + "NS_HMR_TOKEN", + ); + }); + }); }); describe("startViteDevServer", () => { @@ -988,6 +1082,42 @@ describe("BundlerCompilerService", () => { process.env.NS_VITE_SINGLE_PROCESS = "0"; assert.isFalse(supports("ios")); }); + + it("reads the platforms whose devices use dev-server.json, opted out of single-process or not", () => { + const uses = (platform: string) => + bundlerCompilerService.usesDevServerFile(platform, { + projectDir, + }); + writeVitePackage({ + name: "@nativescript/vite", + nativescriptCli: { singleProcessDev: ["ios"] }, + }); + assert.isFalse(uses("iOS")); + + writeVitePackage({ + name: "@nativescript/vite", + nativescriptCli: { + singleProcessDev: ["ios"], + devServerFile: ["ios", "android"], + }, + }); + process.env.NS_VITE_SINGLE_PROCESS = "0"; + assert.isTrue(uses("iOS")); + assert.isTrue(uses("android")); + assert.isFalse(uses("visionOS")); + }); + + it("never applies to webpack", () => { + writeVitePackage({ + name: "@nativescript/vite", + nativescriptCli: { devServerFile: ["ios"] }, + }); + (bundlerCompilerService).getBundler = () => "webpack"; + + assert.isFalse( + bundlerCompilerService.usesDevServerFile("ios", { projectDir }), + ); + }); }); describe("stopBundlerCompiler", () => { diff --git a/test/services/bundler/dev-server-origin-service.ts b/test/services/bundler/dev-server-origin-service.ts new file mode 100644 index 0000000000..14dff934e1 --- /dev/null +++ b/test/services/bundler/dev-server-origin-service.ts @@ -0,0 +1,392 @@ +import { assert } from "chai"; +import { Yok } from "../../../lib/common/yok"; +import { IInjector } from "../../../lib/common/definitions/yok"; +import { provide } from "../../../lib/common/di"; +import { Errors, Logger } from "../../../lib/contracts"; +import { DevServerOriginService } from "../../../lib/contracts/internal/dev-server-origin-service"; +import { IOSDeviceTunnelService } from "../../../lib/contracts/internal/ios-device-tunnel-service"; +import { + chooseDevServerOrigin, + DevServerOriginServiceImpl, + formatDevServerOrigin, + guessLanAddress, + isDevServerHttps, + IDevServerOriginInputs, +} from "../../../lib/services/bundler/dev-server-origin-service"; +import { ErrorsStub, LoggerStub } from "../../stubs"; + +const lan = "192.168.1.10"; + +function origin(inputs: Partial): string { + return chooseDevServerOrigin({ + port: 5173, + isAndroid: false, + isEmulator: false, + lanAddress: lan, + ...inputs, + }); +} + +describe("chooseDevServerOrigin", () => { + describe("with NS_HMR_HOST", () => { + const cases: [string, string][] = [ + ["dev.example.test", "http://dev.example.test:5173"], + ["dev.example.test:8443", "http://dev.example.test:8443"], + ["10.0.0.5", "http://10.0.0.5:5173"], + ["fd6f:72e:8d34::2", "http://[fd6f:72e:8d34::2]:5173"], + ["[fd6f:72e:8d34::2]", "http://[fd6f:72e:8d34::2]:5173"], + ["[fd6f:72e:8d34::2]:8080", "http://[fd6f:72e:8d34::2]:8080"], + [" dev.example.test ", "http://dev.example.test:5173"], + ]; + for (const [envHost, expected] of cases) { + it(`uses "${envHost}" for every kind of device`, () => { + for (const isAndroid of [true, false]) { + for (const isEmulator of [true, false]) { + assert.equal( + origin({ + envHost, + isAndroid, + isEmulator, + adbReverse: true, + tunnelAddress: "fd00::2", + }), + expected, + ); + } + } + }); + } + + it("ignores an empty or blank value", () => { + assert.equal( + origin({ envHost: "", isAndroid: true, adbReverse: true }), + "http://127.0.0.1:5173", + ); + assert.equal( + origin({ envHost: " ", isAndroid: true, adbReverse: true }), + "http://127.0.0.1:5173", + ); + }); + }); + + it("uses the loopback on Android when adb reverse works", () => { + assert.equal( + origin({ isAndroid: true, isEmulator: false, adbReverse: true }), + "http://127.0.0.1:5173", + ); + assert.equal( + origin({ isAndroid: true, isEmulator: true, adbReverse: true }), + "http://127.0.0.1:5173", + ); + }); + + it("uses 10.0.2.2 on an Android emulator without adb reverse", () => { + assert.equal( + origin({ isAndroid: true, isEmulator: true }), + "http://10.0.2.2:5173", + ); + }); + + it("uses the loopback on an iOS simulator", () => { + assert.equal( + origin({ isEmulator: true, tunnelAddress: "fd00::2" }), + "http://127.0.0.1:5173", + ); + }); + + it("uses the Mac's tunnel address, bracketed, on a physical iOS device", () => { + assert.equal( + origin({ tunnelAddress: "fd6f:72e:8d34::2" }), + "http://[fd6f:72e:8d34::2]:5173", + ); + }); + + it("uses the LAN address on a physical device with no other route", () => { + assert.equal(origin({}), `http://${lan}:5173`); + assert.equal(origin({ isAndroid: true }), `http://${lan}:5173`); + }); + + it("falls back to the loopback without a LAN address", () => { + assert.equal(origin({ lanAddress: undefined }), "http://127.0.0.1:5173"); + }); + + describe("when the user prefers the LAN address", () => { + it("gives it to every device, whatever route it has", () => { + for (const inputs of [ + { isAndroid: true, isEmulator: true, adbReverse: true }, + { isAndroid: true, isEmulator: true }, + { isEmulator: true }, + { tunnelAddress: "fd00::2" }, + ]) { + assert.equal( + origin({ ...inputs, preferLan: true }), + `http://${lan}:5173`, + ); + } + }); + + it("still yields to NS_HMR_HOST", () => { + assert.equal( + origin({ preferLan: true, envHost: "dev.example.test" }), + "http://dev.example.test:5173", + ); + }); + + it("falls back to the usual route without a LAN address", () => { + assert.equal( + origin({ + preferLan: true, + lanAddress: undefined, + isAndroid: true, + isEmulator: true, + }), + "http://10.0.2.2:5173", + ); + }); + }); + + it("uses https when the dev server serves it", () => { + assert.equal( + origin({ https: true, tunnelAddress: "fd00::2" }), + "https://[fd00::2]:5173", + ); + assert.equal( + origin({ https: true, envHost: "dev.example.test:8443" }), + "https://dev.example.test:8443", + ); + }); + + it("uses the platform's port", () => { + assert.equal( + origin({ port: 5174, isEmulator: true }), + "http://127.0.0.1:5174", + ); + }); +}); + +describe("formatDevServerOrigin", () => { + it("uses the platform's port when a bracketed host's suffix is not a port", () => { + assert.equal( + formatDevServerOrigin("[::1]:notaport", 5173), + "http://[::1]:5173", + ); + }); + + it("brackets a bare IPv6 address with an embedded IPv4 part", () => { + assert.equal( + formatDevServerOrigin("::ffff:192.168.1.10", 5173), + "http://[::ffff:192.168.1.10]:5173", + ); + }); +}); + +describe("isDevServerHttps", () => { + it("follows NS_HTTPS the way @nativescript/vite reads it", () => { + assert.isTrue(isDevServerHttps({ NS_HTTPS: "1" })); + assert.isTrue(isDevServerHttps({ NS_HTTPS: "true" })); + assert.isFalse(isDevServerHttps({ NS_HTTPS: "yes" })); + assert.isFalse(isDevServerHttps({ NS_HTTPS: "0" })); + assert.isFalse(isDevServerHttps({})); + }); +}); + +describe("guessLanAddress", () => { + it("returns the first external, non-link-local IPv4 address", () => { + assert.equal( + guessLanAddress({ + lo0: [{ address: "127.0.0.1", family: "IPv4", internal: true }], + awdl0: [{ address: "169.254.10.2", family: "IPv4", internal: false }], + utun4: [{ address: "fd00::2", family: "IPv6", internal: false }], + en0: [{ address: "192.168.1.10", family: 4, internal: false }], + en1: [{ address: "10.0.0.7", family: "IPv4", internal: false }], + }), + "192.168.1.10", + ); + }); + + it("returns nothing when no interface qualifies", () => { + assert.isUndefined( + guessLanAddress({ + lo0: [{ address: "127.0.0.1", family: "IPv4", internal: true }], + utun4: [{ address: "fd00::2", family: "IPv6", internal: false }], + }), + ); + }); +}); + +describe("DevServerOriginService", () => { + const previousHost = process.env.NS_HMR_HOST; + const previousHttps = process.env.NS_HTTPS; + const previousPreferLan = process.env.NS_HMR_PREFER_LAN_HOST; + let service: DevServerOriginServiceImpl; + let tunnelAddresses: Record; + let interfaces: object; + let warnings: string[]; + + const device = ( + identifier: string, + platform: string, + isEmulator = false, + ): Mobile.IDevice => + { + deviceInfo: { identifier, platform, displayName: identifier }, + isEmulator, + }; + + beforeEach(() => { + delete process.env.NS_HMR_HOST; + delete process.env.NS_HTTPS; + delete process.env.NS_HMR_PREFER_LAN_HOST; + tunnelAddresses = {}; + warnings = []; + interfaces = { + en0: [{ address: lan, family: "IPv4", internal: false }], + }; + + const injector: IInjector = new Yok(); + const logger = new LoggerStub(); + logger.warn = (message: string) => { + warnings.push(message); + }; + injector.register([ + { provide: Logger, useValue: logger }, + { provide: Errors, useClass: ErrorsStub }, + ]); + injector.register("mobileHelper", { + isAndroidPlatform: (platform: string) => + platform.toLowerCase() === "android", + }); + injector.register("viteHmrPortService", { + getPort: async (platform: string) => + platform === "android" ? 5174 : 5173, + }); + injector.register({ + provide: IOSDeviceTunnelService, + useValue: { + getHostAddress: (id: string) => tunnelAddresses[id], + }, + }); + injector.register( + provide(DevServerOriginService, DevServerOriginServiceImpl), + ); + service = injector.get(DevServerOriginService); + (service).getNetworkInterfaces = () => interfaces; + }); + + afterEach(() => { + if (previousHost === undefined) { + delete process.env.NS_HMR_HOST; + } else { + process.env.NS_HMR_HOST = previousHost; + } + if (previousHttps === undefined) { + delete process.env.NS_HTTPS; + } else { + process.env.NS_HTTPS = previousHttps; + } + if (previousPreferLan === undefined) { + delete process.env.NS_HMR_PREFER_LAN_HOST; + } else { + process.env.NS_HMR_PREFER_LAN_HOST = previousPreferLan; + } + }); + + it("reads NS_HMR_PREFER_LAN_HOST from the environment", async () => { + process.env.NS_HMR_PREFER_LAN_HOST = "1"; + + assert.equal( + await service.chooseOrigin(device("emulator-5554", "Android", true), { + adbReverse: true, + }), + `http://${lan}:5174`, + ); + }); + + it("writes an https origin when NS_HTTPS is set", async () => { + process.env.NS_HTTPS = "1"; + + assert.equal( + await service.chooseOrigin(device("sim", "iOS", true)), + "https://127.0.0.1:5173", + ); + }); + + it("keeps one URL-safe token per platform", () => { + const ios = service.getToken("ios"); + + assert.match(ios, /^[A-Za-z0-9_-]{32}$/); + assert.equal(service.getToken("iOS"), ios); + assert.notEqual(service.getToken("android"), ios); + }); + + it("writes the chosen origin and the platform's token into the device's file", async () => { + tunnelAddresses.phone = "fd6f:72e:8d34::2"; + + const chosen = await service.chooseOrigin(device("phone", "iOS")); + + assert.equal(chosen, "http://[fd6f:72e:8d34::2]:5173"); + assert.equal(service.getOrigin("phone"), chosen); + assert.deepEqual(JSON.parse(service.getDevServerFile("phone")), { + origin: "http://[fd6f:72e:8d34::2]:5173", + token: service.getToken("ios"), + }); + }); + + it("keeps each device's origin apart", async () => { + tunnelAddresses.first = "fd00::1"; + tunnelAddresses.second = "fd00::2"; + + await service.chooseOrigin(device("first", "iOS")); + await service.chooseOrigin(device("second", "iOS")); + await service.chooseOrigin(device("emulator-5554", "Android", true), { + adbReverse: true, + }); + + assert.equal(service.getOrigin("first"), "http://[fd00::1]:5173"); + assert.equal(service.getOrigin("second"), "http://[fd00::2]:5173"); + assert.equal(service.getOrigin("emulator-5554"), "http://127.0.0.1:5174"); + }); + + it("follows the tunnel's current state when chosen again", async () => { + tunnelAddresses.phone = "fd00::1"; + await service.chooseOrigin(device("phone", "iOS")); + + delete tunnelAddresses.phone; + + assert.equal( + await service.chooseOrigin(device("phone", "iOS")), + `http://${lan}:5173`, + ); + }); + + it("uses NS_HMR_HOST from the environment", async () => { + process.env.NS_HMR_HOST = "dev.example.test"; + tunnelAddresses.phone = "fd00::1"; + + assert.equal( + await service.chooseOrigin(device("phone", "iOS")), + "http://dev.example.test:5173", + ); + }); + + it("has no file for a device it chose nothing for, or forgot", async () => { + assert.isNull(service.getDevServerFile("phone")); + + await service.chooseOrigin(device("sim", "iOS", true)); + service.forget("sim"); + + assert.isNull(service.getDevServerFile("sim")); + assert.isUndefined(service.getOrigin("sim")); + }); + + it("warns when a physical device has no route but a missing LAN address", async () => { + interfaces = {}; + + await service.chooseOrigin(device("sim", "iOS", true)); + assert.isEmpty(warnings); + + await service.chooseOrigin(device("phone", "iOS")); + assert.lengthOf(warnings, 1); + assert.include(warnings[0], "NS_HMR_HOST"); + }); +}); 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..10cc853d7d --- /dev/null +++ b/test/services/ios/ios-device-tunnel-service.ts @@ -0,0 +1,378 @@ +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 { + ChildProcess, + Errors, + FileSystem, + HostInfo, + Logger, + TempService, +} from "../../../lib/contracts"; +import { IOSDeviceTunnelService } from "../../../lib/contracts/internal/ios-device-tunnel-service"; +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 listTimeouts: number[]; + let spawned: { args: string[]; holder: FakeHolder }[]; + let warnings: string[]; + let isDarwin: boolean; + let service: IOSDeviceTunnelServiceImpl; + + beforeEach(() => { + devicectlListings = []; + listCalls = 0; + listTimeouts = []; + spawned = []; + warnings = []; + isDarwin = true; + let lastListing: object[] = []; + + const injector: IInjector = new Yok(); + injector.register({ + provide: ChildProcess, + useValue: { + trySpawnFromCloseEvent: async ( + _command: string, + _args: string[], + _options: object, + spawnFromEventOptions?: { timeout?: number }, + ) => { + listCalls++; + listTimeouts.push(spawnFromEventOptions?.timeout); + 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({ + provide: FileSystem, + useValue: { + exists: () => true, + readJson: () => ({ result: { devices: lastListing } }), + }, + }); + injector.register({ + provide: HostInfo, + useValue: { + get isDarwin() { + return isDarwin; + }, + }, + }); + const logger = new LoggerStub(); + logger.warn = (message: string) => { + warnings.push(message); + }; + injector.register([ + { provide: Logger, useValue: logger }, + { provide: Errors, useClass: ErrorsStub }, + ]); + injector.register("devicePlatformsConstants", DevicePlatformsConstants); + injector.register("mobileHelper", MobileHelper); + injector.register([ + { provide: TempService, useClass: TempServiceStub }, + provide(IOSDeviceTunnelService, IOSDeviceTunnelServiceImpl), + ]); + + service = injector.get(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(UDID), "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("bounds every devicectl listing", async () => { + devicectlListings = [ + [coreDevice(wiredDisconnected)], + [coreDevice({ ...wiredConnected, tunnelState: "connecting" })], + [coreDevice(wiredConnected)], + ]; + + await service.open(iPhone()); + + assert.equal(listCalls, 3); + for (const timeout of listTimeouts) { + assert.isAbove(timeout, 0); + } + }); + + 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(UDID)); + }); + + 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(UDID)); + 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"); + }); + + it("tells listeners about a tunnel that closed on its own, not about a closed one", async () => { + const lost: string[] = []; + service.onTunnelLost((id) => lost.push(id)); + devicectlListings = [[coreDevice(wiredConnected)]]; + await service.open(iPhone()); + await service.close(UDID); + await service.open(iPhone()); + + spawned[1].holder.emit("exit", 1, null); + await new Promise((resolve) => setImmediate(resolve)); + + assert.deepEqual(lost, [UDID]); + }); + + it("forgets a tunnel that closed on its own, so the next open holds a new one", async () => { + devicectlListings = [[coreDevice(wiredConnected)]]; + await service.open(iPhone()); + + spawned[0].holder.emit("exit", 1, null); + await new Promise((resolve) => setImmediate(resolve)); + + assert.isUndefined(service.getHostAddress(UDID)); + assert.equal(await service.open(iPhone()), "fd6f:72e:8d34::2"); + assert.lengthOf(spawned, 2); + }); + + it("keeps each device's tunnel address apart", async () => { + const secondUDID = "00008112-000128D1022A201E"; + devicectlListings = [ + [ + coreDevice(wiredConnected), + coreDevice( + { ...wiredConnected, tunnelIPAddress: "fd58:5467:5f7b::1" }, + secondUDID, + ), + ], + ]; + + await service.open(iPhone()); + await service.open(iPhone({ identifier: secondUDID })); + + assert.equal(service.getHostAddress(UDID), "fd6f:72e:8d34::2"); + assert.equal(service.getHostAddress(secondUDID), "fd58:5467:5f7b::2"); + + await service.close(UDID); + + assert.isUndefined(service.getHostAddress(UDID)); + assert.equal(service.getHostAddress(secondUDID), "fd58:5467:5f7b::2"); + }); +}); diff --git a/test/services/livesync/android-device-livesync-sockets-service.ts b/test/services/livesync/android-device-livesync-sockets-service.ts index 4077b3a020..c6cbac5bfc 100644 --- a/test/services/livesync/android-device-livesync-sockets-service.ts +++ b/test/services/livesync/android-device-livesync-sockets-service.ts @@ -1,5 +1,12 @@ import { assert } from "chai"; -import { refreshesInPlaceOnSync } from "../../../lib/services/livesync/android-device-livesync-sockets-service"; +import { Yok } from "../../../lib/common/yok"; +import { IInjector } from "../../../lib/common/definitions/yok"; +import { DevServerOriginService } from "../../../lib/contracts/internal/dev-server-origin-service"; +import { + AndroidDeviceSocketsLiveSyncService, + refreshesInPlaceOnSync, +} from "../../../lib/services/livesync/android-device-livesync-sockets-service"; +import { LoggerStub } from "../../stubs"; describe("refreshesInPlaceOnSync", () => { it("refreshes an incremental sync", () => { @@ -32,3 +39,109 @@ describe("refreshesInPlaceOnSync", () => { ); }); }); + +describe("AndroidDeviceSocketsLiveSyncService dev-server.json delivery", () => { + const appIdentifier = "org.nativescript.devserver"; + const devServerFile = '{"origin":"http://127.0.0.1:5173","token":"t"}'; + let devServerFiles: Record; + let operations: string[]; + let sentBuffers: { relativePath: string; content: string }[]; + let doSyncOptions: IDoSyncOperationOptions[]; + let service: AndroidDeviceSocketsLiveSyncService; + + const device = { + deviceInfo: { identifier: "emulator-5554", platform: "Android" }, + fileSystem: { + deleteFile: async (): Promise => undefined, + }, + }; + + beforeEach(() => { + devServerFiles = {}; + operations = []; + sentBuffers = []; + doSyncOptions = []; + + const injector: IInjector = new Yok(); + injector.register("injector", injector); + injector.register("logger", LoggerStub); + injector.register("errors", {}); + injector.register("fs", {}); + injector.register("mobileHelper", {}); + injector.register("androidProcessService", {}); + injector.register("platformsDataService", {}); + injector.register("staticConfig", { + getAdbFilePath: async () => "adb", + }); + injector.register("options", {}); + injector.register("cleanupService", { + addCleanupCommand: async (): Promise => undefined, + removeCleanupCommand: async (): Promise => undefined, + }); + injector.register("devicePlatformsConstants", {}); + injector.register("tempService", {}); + injector.register("filesHashService", {}); + injector.register({ + provide: DevServerOriginService, + useValue: { + getDevServerFile: (id: string) => devServerFiles[id] ?? null, + }, + }); + service = injector.resolve(AndroidDeviceSocketsLiveSyncService, { + device, + data: {}, + }); + (service).livesyncTool = { + protocolVersion: "0.2.0", + generateOperationIdentifier: () => "operation", + isOperationInProgress: () => false, + sendFileFromBuffer: async (relativePath: string, content: Buffer) => { + operations.push("file"); + sentBuffers.push({ relativePath, content: content.toString() }); + }, + sendDoSyncOperation: async (options: IDoSyncOperationOptions) => { + operations.push("doSync"); + doSyncOptions.push(options); + return { operationId: options.operationId, didRefresh: false }; + }, + end: (): void => undefined, + }; + }); + + const finalize = (isFullSync: boolean, modifiedFilesData: any[] = []) => + service.finalizeSync( + { + isFullSync, + modifiedFilesData, + useHotModuleReload: true, + deviceAppData: { appIdentifier, device }, + }, + { bundler: "vite" }, + ); + + it("sends the file before DO_SYNC on a full sync, even when no file changed", async () => { + devServerFiles["emulator-5554"] = devServerFile; + + await finalize(true); + + assert.deepEqual(operations, ["file", "doSync"]); + assert.deepEqual(sentBuffers, [ + { relativePath: "dev-server.json", content: devServerFile }, + ]); + assert.isFalse(doSyncOptions[0].doRefresh); + }); + + it("does not send it on an incremental sync", async () => { + devServerFiles["emulator-5554"] = devServerFile; + + await finalize(false); + + assert.deepEqual(operations, []); + }); + + it("leaves a full sync without an origin as it was", async () => { + await finalize(true); + + assert.deepEqual(operations, []); + }); +}); diff --git a/test/services/livesync/android-livesync-service.ts b/test/services/livesync/android-livesync-service.ts new file mode 100644 index 0000000000..46b9e2d1c2 --- /dev/null +++ b/test/services/livesync/android-livesync-service.ts @@ -0,0 +1,62 @@ +import { assert } from "chai"; +import { Yok } from "../../../lib/common/yok"; +import { IInjector } from "../../../lib/common/definitions/yok"; +import { DevServerOriginService } from "../../../lib/contracts/internal/dev-server-origin-service"; +import { AndroidLiveSyncService } from "../../../lib/services/livesync/android-livesync-service"; +import { LoggerStub } from "../../stubs"; + +describe("AndroidLiveSyncService", () => { + describe("syncAfterInstall", () => { + let devServerFiles: Record; + let fullSyncs: IFullSyncInfo[]; + let service: AndroidLiveSyncService; + const device = { + deviceInfo: { identifier: "emulator-5554", platform: "Android" }, + }; + const watchInfo = { + projectData: { projectDir: "/project" }, + liveSyncDeviceData: { identifier: "emulator-5554" }, + useHotModuleReload: true, + }; + + beforeEach(() => { + devServerFiles = {}; + fullSyncs = []; + const injector: IInjector = new Yok(); + injector.register("injector", injector); + injector.register("platformsDataService", {}); + injector.register("projectFilesManager", {}); + injector.register("devicePathProvider", {}); + injector.register("fs", {}); + injector.register("logger", LoggerStub); + injector.register("options", {}); + injector.register({ + provide: DevServerOriginService, + useValue: { + getDevServerFile: (id: string) => devServerFiles[id] ?? null, + }, + }); + service = injector.resolve(AndroidLiveSyncService); + service.fullSync = async (syncInfo: IFullSyncInfo) => { + fullSyncs.push(syncInfo); + return {}; + }; + }); + + it("syncs fully again so the new APK's first launch gets dev-server.json back", async () => { + devServerFiles["emulator-5554"] = "{}"; + + await service.syncAfterInstall(device, watchInfo); + + assert.lengthOf(fullSyncs, 1); + assert.strictEqual(fullSyncs[0].device, device); + assert.isTrue(fullSyncs[0].useHotModuleReload); + }); + + it("does nothing for a device without an origin", async () => { + await service.syncAfterInstall(device, watchInfo); + + assert.deepEqual(fullSyncs, []); + }); + }); +}); diff --git a/test/services/livesync/android-livesync-tool.ts b/test/services/livesync/android-livesync-tool.ts index 712cecd59f..3f3f142d5d 100644 --- a/test/services/livesync/android-livesync-tool.ts +++ b/test/services/livesync/android-livesync-tool.ts @@ -504,6 +504,58 @@ describe("AndroidLivesyncTool", () => { }); }); + describe("sendFileFromBuffer", () => { + it("sends the content under the given app-relative path", async () => { + const content = '{"origin":"http://127.0.0.1:5173","token":"t"}'; + + await livesyncTool.sendFileFromBuffer( + "dev-server.json", + Buffer.from(content), + ); + + const sendFileData = getSendFileData( + (testSocket as TestSocket).accomulatedData, + ); + assert.equal(sendFileData.fileName, "dev-server.json"); + assert.equal(sendFileData.fileContent, content); + assert(sendFileData.headerHashMatch); + assert(sendFileData.fileHashMatch); + assert.equal( + sendFileData.operation, + AndroidLivesyncTool.CREATE_FILE_OPERATION, + ); + }); + + it("writes the same bytes as sendFile for the same file", async () => { + const filePath = path.join(testAppPlatformPath, nestedJsFilePath); + await livesyncTool.sendFile(filePath); + const fromFile = Buffer.concat( + (testSocket as TestSocket).accomulatedData.splice(0), + ); + + await livesyncTool.sendFileFromBuffer( + nestedJsFilePath, + Buffer.from(fileContents[nestedJsFilePath]), + ); + const fromBuffer = Buffer.concat( + (testSocket as TestSocket).accomulatedData, + ); + + assert.isTrue(fromBuffer.equals(fromFile)); + }); + + it("rejects if no connection", () => { + livesyncTool.end(); + + return assert.isRejected( + livesyncTool.sendFileFromBuffer( + "dev-server.json", + Buffer.from("{}"), + ), + ); + }); + }); + describe("remove file", () => { it("sends correct information", async () => { //arrange diff --git a/test/services/livesync/ios-livesync-service.ts b/test/services/livesync/ios-livesync-service.ts new file mode 100644 index 0000000000..2fba977ab4 --- /dev/null +++ b/test/services/livesync/ios-livesync-service.ts @@ -0,0 +1,196 @@ +import { assert } from "chai"; +import * as path from "path"; +import * as sinon from "sinon"; +import { Yok } from "../../../lib/common/yok"; +import { IInjector } from "../../../lib/common/definitions/yok"; +import { DevServerOriginService } from "../../../lib/contracts/internal/dev-server-origin-service"; +import { IOSLiveSyncService } from "../../../lib/services/livesync/ios-livesync-service"; +import { PlatformLiveSyncServiceBase } from "../../../lib/services/livesync/platform-livesync-service-base"; +import { LoggerStub } from "../../stubs"; + +const appIdentifier = "org.nativescript.devserver"; +const appDestination = "/project/platforms/ios/App/app-dest"; +const appFolder = path.join(appDestination, "app"); +const bundlePath = path.join(appFolder, "bundle.mjs"); +const simulatorAppRoot = "/Simulator/Containers/App.app/app"; +const deviceAppRoot = "Library/Application Support/LiveSync/app"; +const devServerFile = '{"origin":"http://127.0.0.1:5173","token":"t"}'; + +describe("IOSLiveSyncService dev-server.json delivery", () => { + let sandbox: sinon.SinonSandbox; + let service: IOSLiveSyncService; + let devServerFiles: Record; + let written: Record; + let zipped: { files: string[]; entries: string[] }; + let transferredAppFiles: string[]; + let putFiles: { localPath: string; devicePath: string; appId: string }[]; + + const projectData = { + projectDir: "/project", + projectIdentifiers: { ios: appIdentifier }, + }; + + const device = (identifier: string, isEmulator: boolean): Mobile.IDevice => + { + isEmulator, + deviceInfo: { identifier, platform: "iOS" }, + fileSystem: { + putFile: async ( + localPath: string, + devicePath: string, + appId: string, + ) => { + putFiles.push({ localPath, devicePath, appId }); + }, + transferFiles: async (): Promise => undefined, + }, + applicationManager: { + setTransferredAppFiles: async (files: string[]) => { + transferredAppFiles = files; + }, + }, + }; + + beforeEach(() => { + sandbox = sinon.createSandbox(); + devServerFiles = {}; + written = {}; + zipped = null; + transferredAppFiles = null; + putFiles = []; + let tempFiles = 0; + + const injector: IInjector = new Yok(); + injector.register("injector", injector); + injector.register("fs", { + enumerateFilesInDirectorySync: () => [bundlePath], + writeFile: (filePath: string, content: string) => { + written[filePath] = content; + }, + zipFiles: async ( + _zip: string, + files: string[], + mapper: (file: string) => string, + ) => { + zipped = { files, entries: files.map(mapper) }; + }, + }); + injector.register("platformsDataService", { + getPlatformData: () => ({ + appDestinationDirectoryPath: appDestination, + platformProjectService: { getFrameworkVersion: () => "8.9.0" }, + }), + }); + injector.register("projectFilesManager", {}); + injector.register("tempService", { + path: async (options: { prefix: string; suffix: string }) => + `/tmp/${options.prefix}-${++tempFiles}${options.suffix}`, + }); + injector.register("devicePathProvider", { + getDeviceProjectRootPath: async (target: Mobile.IDevice) => + target.isEmulator ? simulatorAppRoot : deviceAppRoot, + getDeviceSyncZipPath: (target: Mobile.IDevice) => + target.isEmulator + ? undefined + : "Library/Application Support/LiveSync/sync.zip", + }); + injector.register("logger", LoggerStub); + injector.register("options", { hostProjectModuleName: "app" }); + injector.register({ + provide: DevServerOriginService, + useValue: { + getDevServerFile: (id: string) => devServerFiles[id] ?? null, + }, + }); + service = injector.resolve(IOSLiveSyncService); + + sandbox + .stub(PlatformLiveSyncServiceBase.prototype, "fullSync") + .callsFake(async function ( + this: PlatformLiveSyncServiceBase, + syncInfo: IFullSyncInfo, + ) { + return { + deviceAppData: await this.getAppData(syncInfo), + isFullSync: true, + modifiedFilesData: [], + useHotModuleReload: true, + }; + }); + }); + + afterEach(() => { + sandbox.restore(); + }); + + const fullSync = (target: Mobile.IDevice) => + service.fullSync({ + projectData, + device: target, + watch: true, + useHotModuleReload: true, + liveSyncDeviceData: {}, + }); + + describe("on a simulator", () => { + it("writes the file next to bundle.mjs in the installed app after the sync", async () => { + devServerFiles.sim = devServerFile; + + await fullSync(device("sim", true)); + + assert.lengthOf(putFiles, 1); + assert.equal( + putFiles[0].devicePath, + path.join(simulatorAppRoot, "dev-server.json"), + ); + assert.equal(putFiles[0].appId, appIdentifier); + assert.equal(written[putFiles[0].localPath], devServerFile); + }); + + it("writes nothing for a device without an origin", async () => { + await fullSync(device("sim", true)); + + assert.deepEqual(putFiles, []); + }); + + it("writes the file again into a reinstalled app", async () => { + devServerFiles.sim = devServerFile; + + await service.syncAfterInstall(device("sim", true), { + projectData, + liveSyncDeviceData: {}, + useHotModuleReload: true, + }); + + assert.lengthOf(putFiles, 1); + assert.equal( + putFiles[0].devicePath, + path.join(simulatorAppRoot, "dev-server.json"), + ); + }); + }); + + describe("on a physical device", () => { + it("adds the file to that device's sync.zip next to bundle.mjs", async () => { + devServerFiles.phone = devServerFile; + + await fullSync(device("phone", false)); + + assert.deepEqual(zipped.entries, [ + "app/bundle.mjs", + "app/dev-server.json", + ]); + assert.equal(written[zipped.files[1]], devServerFile); + assert.deepEqual(transferredAppFiles, [bundlePath]); + assert.deepEqual(putFiles, []); + }); + + it("zips only the app for a device without an origin", async () => { + devServerFiles.other = devServerFile; + + await fullSync(device("phone", false)); + + assert.deepEqual(zipped.entries, ["app/bundle.mjs"]); + }); + }); +}); diff --git a/test/stubs.ts b/test/stubs.ts index c8b9bf3663..b797ea7fad 100644 --- a/test/stubs.ts +++ b/test/stubs.ts @@ -1557,6 +1557,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); }