diff --git a/lib/services/android-project-service.ts b/lib/services/android-project-service.ts index d4ba573a08..5dcbe96af0 100644 --- a/lib/services/android-project-service.ts +++ b/lib/services/android-project-service.ts @@ -46,6 +46,14 @@ import { } from "../definitions/gradle"; import { IInjector } from "../common/definitions/yok"; import { injector } from "../common/yok"; +import { IProjectChangesInfo } from "../definitions/project-changes"; +import { + DEV_CLEARTEXT_MARKER, + devCleartextManifest, + hasDevCleartext, + needsDevCleartext, + withDevCleartext, +} from "./android/dev-cleartext-manifest"; import { INotConfiguredEnvOptions } from "../common/definitions/commands"; interface NativeDependency { @@ -845,8 +853,64 @@ export class AndroidProjectService await adb.executeShellCommand(["rm", "-rf", deviceRootPath]); } - public async checkForChanges(): Promise { - // Nothing android specific to check yet. + public async checkForChanges( + changesInfo: IProjectChangesInfo, + prepareData: IPrepareData, + projectData: IProjectData, + ): Promise { + // Native prepare skips `prepareDevServerAccess` for a host project. + if (this.$options.hostProjectPath) { + return; + } + const manifestPath = this.getDebugManifestPath(projectData); + const current = this.$fs.exists(manifestPath) + ? this.$fs.readText(manifestPath) + : null; + // The build is what carries the permission, so a change has to rebuild. + if ( + needsDevCleartext(projectData, prepareData) !== hasDevCleartext(current) + ) { + changesInfo.appResourcesChanged = true; + } + } + + /** + * Lets a Vite HMR debug build fetch its code from the dev server over + * plain HTTP, through the debug source set's manifest in the native + * project. Runs after `prepareAppResources`, which restores the app's own + * debug manifest, if any, from App_Resources. + */ + public prepareDevServerAccess( + projectData: IProjectData, + prepareData: IPrepareData, + ): void { + const manifestPath = this.getDebugManifestPath(projectData); + const current = this.$fs.exists(manifestPath) + ? this.$fs.readText(manifestPath) + : null; + if (!needsDevCleartext(projectData, prepareData)) { + if (current !== null && current.includes(DEV_CLEARTEXT_MARKER)) { + this.$fs.deleteFile(manifestPath); + } + return; + } + if (hasDevCleartext(current)) { + return; + } + this.$fs.writeFile( + manifestPath, + current === null ? devCleartextManifest() : withDevCleartext(current), + ); + } + + private getDebugManifestPath(projectData: IProjectData): string { + return path.join( + this.getPlatformData(projectData).projectRoot, + this.$options.hostProjectModuleName, + constants.SRC_DIR, + "debug", + constants.MANIFEST_FILE_NAME, + ); } public getDeploymentTarget(projectData: IProjectData): semver.SemVer { diff --git a/lib/services/android/dev-cleartext-manifest.ts b/lib/services/android/dev-cleartext-manifest.ts new file mode 100644 index 0000000000..347078ccd1 --- /dev/null +++ b/lib/services/android/dev-cleartext-manifest.ts @@ -0,0 +1,99 @@ +import { IProjectData } from "../../definitions/project"; + +/** + * Identifies a debug manifest whose cleartext permission the CLI wrote, so a + * later prepare that doesn't need it can take it out again. + */ +export const DEV_CLEARTEXT_MARKER = + "nativescript-cli: cleartext HTTP to the Vite dev server (debug HMR runs only)"; + +const TOOLS_NS = 'xmlns:tools="http://schemas.android.com/tools"'; +const CLEARTEXT_ATTRIBUTE = "android:usesCleartextTraffic"; + +/** + * A Vite HMR app loads its code from the dev server over plain HTTP, which + * Android blocks by default from API 28. + */ +export function needsDevCleartext( + projectData: Pick, + prepareData: { hmr?: boolean; release?: boolean }, +): boolean { + return ( + projectData.bundler === "vite" && !!prepareData.hmr && !prepareData.release + ); +} + +export function hasDevCleartext(manifest: string | null): boolean { + return !!manifest && manifest.includes(DEV_CLEARTEXT_MARKER); +} + +/** The debug source set's manifest when the app ships none of its own. */ +export function devCleartextManifest(): string { + return [ + '', + ``, + ``, + `\t`, + "", + "", + ].join("\n"); +} + +/** + * The app's own debug manifest with the permission added. `tools:replace` + * lets it win over a main manifest that sets the attribute itself. + */ +export function withDevCleartext(manifest: string): string { + let result = manifest; + const manifestTag = /]*>/.exec(result); + if (!manifestTag) { + return result; + } + if (!manifestTag[0].includes("xmlns:tools=")) { + const withTools = manifestTag[0].replace( + /^]*?(\/?)>/.exec(result); + if (!applicationTag) { + result = result.replace( + /<\/manifest>/, + `\t\n`, + ); + } else { + let tag = applicationTag[0]; + const value = new RegExp(`${CLEARTEXT_ATTRIBUTE}\\s*=\\s*"[^"]*"`); + tag = value.test(tag) + ? tag.replace(value, `${CLEARTEXT_ATTRIBUTE}="true"`) + : tag.replace( + /^ name.trim()) + .includes(CLEARTEXT_ATTRIBUTE) + ) { + tag = tag.replace( + replace[0], + `tools:replace="${replace[1]},${CLEARTEXT_ATTRIBUTE}"`, + ); + } + result = result.replace(applicationTag[0], tag); + } + + return result.replace( + /(\n$1`, + ); +} diff --git a/lib/services/bundler/bundler-compiler-service.ts b/lib/services/bundler/bundler-compiler-service.ts index c7bfbbe5c6..3914be69a2 100644 --- a/lib/services/bundler/bundler-compiler-service.ts +++ b/lib/services/bundler/bundler-compiler-service.ts @@ -66,6 +66,30 @@ const BUNDLER_STOP_TIMEOUT_MS = 5000; */ const VITE_APP_RESTART_MESSAGE_TYPE = "nativescript:restart"; +/** + * Set to "1" on `vite serve` when it runs alone: `@nativescript/vite` then + * writes `bundle.mjs` and the app's static files itself and sends the build + * messages a `vite build --watch` would. "0" in the CLI's environment keeps + * the build process. + */ +const VITE_SINGLE_PROCESS_ENV = "NS_VITE_SINGLE_PROCESS"; + +function isViteBuildMessage(message: unknown): message is IBundlerEmitMessage { + return ( + !!message && + typeof message === "object" && + Array.isArray((message as IBundlerEmitMessage).emittedFiles) + ); +} + +interface ViteDevServerHooks { + singleProcess?: boolean; + /** Runs right after the spawn, before any event of the child can arrive. */ + onSpawn?: (childProcess: child_process.ChildProcess) => void; + onMessage?: (message: unknown) => void; + onExit?: (code: number) => void; +} + export class BundlerCompilerService extends EventEmitter implements IBundlerCompilerService @@ -148,6 +172,17 @@ export class BundlerCompilerService let isFirstBundlerWatchCompilation = true; prepareData.watch = true; + if ( + this.isViteSingleProcessSession(platformData, projectData, prepareData) + ) { + this.watchWithViteDevServer( + platformData, + projectData, + prepareData, + ).then(resolve, reject); + return; + } + // Bring up the Vite HMR dev server the device fetches modules / // HMR updates from. No-op unless bundler is vite + hmr + watch. // Fired in parallel with the build watcher; both child processes @@ -201,38 +236,13 @@ export class BundlerCompilerService console.log("Received Vite IPC message:", message); } - // Copy Vite output files directly to platform destination - const { distOutput, destDir } = this.getViteBuildPaths( + this.applyViteBuildMessage( + message, platformData, projectData, + isFirstBundlerWatchCompilation, ); - if (debugLog) { - console.log(`Copying from ${distOutput} to ${destDir}.`); - } - - // Determine which files to copy based on build type and changes - if ( - message.buildType === "incremental" && - message.emittedFiles && - message.emittedFiles.length > 0 - ) { - // Incremental builds: only copy files that are likely affected by the changes - const filesToCopy = this.getIncrementalFilesToCopy( - message.emittedFiles, - ); - if (debugLog) { - console.log("Incremental build - files to copy:", filesToCopy); - } - - this.copyViteBundleToNative(distOutput, destDir, filesToCopy); - } else { - if (debugLog) { - console.log("Full build - copying all files."); - } - this.copyViteBundleToNative(distOutput, destDir); - } - // Resolve the promise on first build completion — gated on // the HMR dev server being reachable (no-op resolve for // non-HMR runs). `startViteDevServer` never rejects and its @@ -247,39 +257,7 @@ export class BundlerCompilerService ); } viteDevServerStartup.then(() => resolve(childProcess)); - return; - } - - // Transform Vite message to match webpack format - const files = (message as IBundlerEmitMessage).emittedFiles.map( - (file) => - path.join( - platformData.appDestinationDirectoryPath, - this.$options.hostProjectModuleName, - file, - ), - ); - - const data = { - files, - hasOnlyHotUpdateFiles: message.isHMR || false, - hmrData: { - hash: (message as IBundlerEmitMessage).hash || "", - fallbackFiles: [] as string[], - }, - platform: platformData.platformNameLowerCase, - }; - - this.$logger.info( - `Vite build completed! Files copied to native platform.`, - ); - - if (debugLog) { - console.log( - "Emitting BUNDLER_COMPILATION_COMPLETE for full build.", - ); } - this.emit(BUNDLER_COMPILATION_COMPLETE, data); return; } @@ -430,6 +408,154 @@ export class BundlerCompilerService }); } + /** + * Copies a Vite build message's files into the native app and, for every + * message but the initial build's, emits the live sync event for them. + */ + private applyViteBuildMessage( + message: IBundlerEmitMessage, + platformData: IPlatformData, + projectData: IProjectData, + isInitialBuild: boolean, + ): void { + const { distOutput, destDir } = this.getViteBuildPaths( + platformData, + projectData, + ); + + if (debugLog) { + console.log(`Copying from ${distOutput} to ${destDir}.`); + } + + const removedFiles = message.removedFiles || []; + this.removeViteFilesFromNative(destDir, removedFiles); + + if ( + message.buildType === "incremental" && + (message.emittedFiles.length > 0 || removedFiles.length > 0) + ) { + // Incremental builds: only copy files that are likely affected by the changes + const filesToCopy = this.getIncrementalFilesToCopy(message.emittedFiles); + if (debugLog) { + console.log("Incremental build - files to copy:", filesToCopy); + } + + this.copyViteBundleToNative(distOutput, destDir, filesToCopy); + } else { + if (debugLog) { + console.log("Full build - copying all files."); + } + this.copyViteBundleToNative(distOutput, destDir); + } + + // Live sync only adds and replaces files on the device, so a removal + // alone has nothing to sync. + if ( + isInitialBuild || + (message.emittedFiles.length === 0 && removedFiles.length > 0) + ) { + return; + } + + // Transform Vite message to match webpack format + const files = message.emittedFiles.map((file) => + path.join( + platformData.appDestinationDirectoryPath, + this.$options.hostProjectModuleName, + file, + ), + ); + + const data = { + files, + hasOnlyHotUpdateFiles: message.isHMR || false, + hmrData: { + hash: message.hash || "", + fallbackFiles: [] as string[], + }, + platform: platformData.platformNameLowerCase, + }; + + this.$logger.info(`Vite build completed! Files copied to native platform.`); + + if (debugLog) { + console.log("Emitting BUNDLER_COMPILATION_COMPLETE for full build."); + } + this.emit(BUNDLER_COMPILATION_COMPLETE, data); + } + + private removeViteFilesFromNative(destDir: string, files: string[]): void { + for (const file of files) { + const target = path.resolve(destDir, file); + if (!target.startsWith(destDir + path.sep)) { + continue; + } + try { + if (this.$fs.exists(target)) { + this.$fs.deleteFile(target); + } + } catch (error) { + this.$logger.warn( + `Failed to remove ${file} from the native app: ${error instanceof Error ? error.message : error}`, + ); + } + } + } + + /** + * Runs a Vite HMR session on `vite serve` alone: it writes the app's + * bundle and static files itself and sends the messages `vite build + * --watch` would. Resolves on the first, which it sends once it listens + * with the app's boot modules transformed. + */ + private watchWithViteDevServer( + platformData: IPlatformData, + projectData: IProjectData, + prepareData: IPrepareData, + ): Promise { + const platform = platformData.platformNameLowerCase; + return new Promise((resolve, reject) => { + let childProcess: child_process.ChildProcess; + let isInitialBuild = true; + this.spawnViteDevServer(platformData, projectData, prepareData, { + singleProcess: true, + onSpawn: (spawned) => { + childProcess = spawned; + this.bundlerProcesses[platform] = spawned; + }, + onMessage: (message) => { + if (!isViteBuildMessage(message)) { + return; + } + if (debugLog) { + console.log("Received Vite IPC message:", message); + } + this.applyViteBuildMessage( + message, + platformData, + projectData, + isInitialBuild, + ); + if (isInitialBuild) { + isInitialBuild = false; + this.$logger.info(`Vite dev server ready (HMR for ${platform}).`); + resolve(childProcess); + } + }, + onExit: (code) => { + this.forgetBundlerProcess(platform, childProcess); + if (isInitialBuild) { + reject( + new Error( + `The Vite dev server exited with code ${code} before it wrote the app's bundle.`, + ), + ); + } + }, + }).catch(reject); + }); + } + public async compileWithoutWatch( platformData: IPlatformData, projectData: IProjectData, @@ -657,6 +783,48 @@ export class BundlerCompilerService ); } + /** + * Whether the installed `@nativescript/vite` can run the session on + * `vite serve` alone for `platform`: its package.json lists the platform + * under `nativescriptCli.singleProcessDev`. + */ + private supportsViteSingleProcess( + platform: string, + projectData: IProjectData, + ): boolean { + if (process.env[VITE_SINGLE_PROCESS_ENV] === "0") { + return false; + } + try { + const packageJSONPath = resolvePackageJSONPath( + this.getBundlerPackageName(), + { paths: [projectData.projectDir] }, + ); + if (!packageJSONPath) { + return false; + } + const platforms = + this.$fs.readJson(packageJSONPath)?.nativescriptCli?.singleProcessDev; + return Array.isArray(platforms) && platforms.includes(platform); + } catch { + return false; + } + } + + private isViteSingleProcessSession( + platformData: IPlatformData, + projectData: IProjectData, + prepareData: IPrepareData, + ): boolean { + return ( + this.isViteHmrSession(prepareData) && + this.supportsViteSingleProcess( + platformData.platformNameLowerCase, + projectData, + ) + ); + } + /** * Environment both Vite children (the build watcher and the dev server) * must share for a platform: the staging directory, and — for HMR @@ -713,84 +881,12 @@ export class BundlerCompilerService return; } - const viteEnv = await this.getViteChildEnv(key, prepareData); - const port = Number(viteEnv.NS_HMR_PORT); - - const envData = this.buildEnvData( - platformData.platformNameLowerCase, - projectData, - prepareData, - ); - const cliArgs = await this.buildEnvCommandLineParams( - envData, + const { port } = await this.spawnViteDevServer( platformData, projectData, prepareData, ); - const additionalNodeArgs = - semver.major(process.version) <= 8 ? ["--harmony"] : []; - if (await this.shouldUsePreserveSymlinksOption()) { - additionalNodeArgs.push("--preserve-symlinks"); - } - - // `vite serve` (not `build`): runs the dev server and watches on - // its own — no `--watch`. Env flags (`--env.android --env.hmr …`) - // go after `--` so vite's CLI doesn't choke on unknown options. - const args = [ - ...additionalNodeArgs, - this.getBundlerExecutablePath(projectData), - "serve", - `--config=${projectData.bundlerConfigPath}`, - `--mode=development`, - "--", - ...cliArgs, - ].filter(Boolean); - - const options: { [key: string]: any } = { - cwd: projectData.projectDir, - // Logs stream straight to the user. The IPC channel only carries - // app-restart requests; a server that never sends one behaves as - // with plain "inherit". - stdio: ["inherit", "inherit", "inherit", "ipc"], - env: { - ...process.env, - NATIVESCRIPT_BUNDLER_ENV: JSON.stringify(envData), - ...viteEnv, - }, - }; - if (this.$hostInfo.isWindows) { - Object.assign(options.env, { APPDATA: process.env.appData }); - } - - this.$logger.info( - `Starting Vite dev server (HMR) for ${key} on port ${port}…`, - ); - - const childProcess = this.$childProcess.spawn( - process.execPath, - args, - options, - ); - this.viteServeProcesses[key] = childProcess; - await this.$cleanupService.addKillProcess(childProcess.pid.toString()); - - childProcess.on("message", (message: unknown) => - this.handleViteServeMessage(message, key, projectData.projectDir), - ); - - childProcess.once("exit", (code: number) => { - if (this.viteServeProcesses[key] === childProcess) { - delete this.viteServeProcesses[key]; - this.cancelAppRestart(key); - } - if (code) { - this.$logger.warn( - `Vite dev server for ${key} exited with code ${code}.`, - ); - } - }); - // Bounded readiness probe so we can surface a clear log once the // device can actually reach modules. const ready = await this.waitForPort(port, 30000); @@ -814,6 +910,100 @@ export class BundlerCompilerService } } + private async spawnViteDevServer( + platformData: IPlatformData, + projectData: IProjectData, + prepareData: IPrepareData, + hooks: ViteDevServerHooks = {}, + ): Promise<{ childProcess: child_process.ChildProcess; port: number }> { + const key = platformData.platformNameLowerCase; + const viteEnv = await this.getViteChildEnv(key, prepareData); + const port = Number(viteEnv.NS_HMR_PORT); + + const envData = this.buildEnvData( + platformData.platformNameLowerCase, + projectData, + prepareData, + ); + const cliArgs = await this.buildEnvCommandLineParams( + envData, + platformData, + projectData, + prepareData, + ); + + const additionalNodeArgs = + semver.major(process.version) <= 8 ? ["--harmony"] : []; + if (await this.shouldUsePreserveSymlinksOption()) { + additionalNodeArgs.push("--preserve-symlinks"); + } + + // `vite serve` (not `build`): runs the dev server and watches on + // its own — no `--watch`. Env flags (`--env.android --env.hmr …`) + // go after `--` so vite's CLI doesn't choke on unknown options. + const args = [ + ...additionalNodeArgs, + this.getBundlerExecutablePath(projectData), + "serve", + `--config=${projectData.bundlerConfigPath}`, + `--mode=development`, + "--", + ...cliArgs, + ].filter(Boolean); + + const options: { [key: string]: any } = { + cwd: projectData.projectDir, + // Logs stream straight to the user. The IPC channel carries + // app-restart requests, and the build messages when the server + // runs alone; a server that sends neither behaves as with plain + // "inherit". + stdio: ["inherit", "inherit", "inherit", "ipc"], + env: { + ...process.env, + NATIVESCRIPT_BUNDLER_ENV: JSON.stringify(envData), + ...viteEnv, + ...(hooks.singleProcess ? { [VITE_SINGLE_PROCESS_ENV]: "1" } : {}), + }, + }; + if (this.$hostInfo.isWindows) { + Object.assign(options.env, { APPDATA: process.env.appData }); + } + + this.$logger.info( + `Starting Vite dev server (HMR) for ${key} on port ${port}…`, + ); + + const childProcess = this.$childProcess.spawn( + process.execPath, + args, + options, + ); + this.viteServeProcesses[key] = childProcess; + hooks.onSpawn?.(childProcess); + + childProcess.on("message", (message: unknown) => { + hooks.onMessage?.(message); + this.handleViteServeMessage(message, key, projectData.projectDir); + }); + + childProcess.once("exit", (code: number) => { + if (this.viteServeProcesses[key] === childProcess) { + delete this.viteServeProcesses[key]; + this.cancelAppRestart(key); + } + if (code) { + this.$logger.warn( + `Vite dev server for ${key} exited with code ${code}.`, + ); + } + hooks.onExit?.(code); + }); + + await this.$cleanupService.addKillProcess(childProcess.pid.toString()); + + return { childProcess, port }; + } + /** * Unknown message shapes are ignored without a log, so a newer * `@nativescript/vite` can add message types without breaking this CLI. @@ -1116,7 +1306,10 @@ export class BundlerCompilerService if (viteServeProcess) { viteServeProcess.removeAllListeners("message"); this.cancelAppRestart(platform); - await this.terminate(viteServeProcess); + // Already stopped above when it is the session's only process. + if (viteServeProcess !== bundlerProcess) { + await this.terminate(viteServeProcess); + } if (this.viteServeProcesses[platform] === viteServeProcess) { delete this.viteServeProcesses[platform]; } diff --git a/lib/services/bundler/bundler.ts b/lib/services/bundler/bundler.ts index 6fbee35c26..0b6d2997cd 100644 --- a/lib/services/bundler/bundler.ts +++ b/lib/services/bundler/bundler.ts @@ -88,6 +88,8 @@ declare global { isHMR?: boolean; filesToCopy?: string[]; buildType?: string; + /** Output-relative files the build deleted (`@nativescript/vite`'s dev server). */ + removedFiles?: string[]; } interface IPlatformProjectService< @@ -154,6 +156,14 @@ declare global { */ prepareAppResources(projectData: IProjectData): void; + /** + * Lets a dev build reach the bundler's dev server. Runs after `prepareAppResources`. + */ + prepareDevServerAccess?( + projectData: IProjectData, + prepareData: TPrepareData, + ): void; + /** * Defines if current platform is prepared (i.e. if /platforms/ dir exists). * @param {string} projectRoot The project directory (path where root's package.json is located). diff --git a/lib/services/livesync/android-device-livesync-sockets-service.ts b/lib/services/livesync/android-device-livesync-sockets-service.ts index 0902faca53..6fc9d31e69 100644 --- a/lib/services/livesync/android-device-livesync-sockets-service.ts +++ b/lib/services/livesync/android-device-livesync-sockets-service.ts @@ -14,6 +14,22 @@ import { ICleanupService } from "../../definitions/cleanup-service"; import { ISpawnCommandInfo } from "../../detached-processes/cleanup-process-definitions"; import { ITempService } from "../../definitions/temp-service"; +/** + * Whether a file sync asks the app to refresh itself in place. Never under + * Vite HMR: the dev server updates the app, and every file the CLI syncs + * there is applied by restarting it, while the in-app refresh runs + * `__onLiveSync`, which can't reload an app served by Vite. + */ +export function refreshesInPlaceOnSync( + liveSyncInfo: Pick, + projectData: Pick, +): boolean { + return ( + !liveSyncInfo.isFullSync && + !(liveSyncInfo.useHotModuleReload && projectData.bundler === "vite") + ); +} + export class AndroidDeviceSocketsLiveSyncService extends AndroidDeviceLiveSyncServiceBase implements @@ -127,7 +143,7 @@ export class AndroidDeviceSocketsLiveSyncService if (liveSyncInfo.modifiedFilesData.length) { const canExecuteFastSync = - !liveSyncInfo.isFullSync && + refreshesInPlaceOnSync(liveSyncInfo, projectData) && this.canExecuteFastSyncForPaths( liveSyncInfo, liveSyncInfo.modifiedFilesData, diff --git a/lib/services/platform/prepare-native-platform-service.ts b/lib/services/platform/prepare-native-platform-service.ts index a2e7703ddb..a6b740605e 100644 --- a/lib/services/platform/prepare-native-platform-service.ts +++ b/lib/services/platform/prepare-native-platform-service.ts @@ -50,6 +50,10 @@ export class PrepareNativePlatformService if (!this.$options.hostProjectPath) { platformData.platformProjectService.prepareAppResources(projectData); + platformData.platformProjectService.prepareDevServerAccess?.( + projectData, + prepareData + ); } if (hasChangesRequirePrepare || this.$options.hostProjectPath) { diff --git a/test/services/android/dev-cleartext-manifest.ts b/test/services/android/dev-cleartext-manifest.ts new file mode 100644 index 0000000000..69cc656959 --- /dev/null +++ b/test/services/android/dev-cleartext-manifest.ts @@ -0,0 +1,100 @@ +import { assert } from "chai"; +import { + DEV_CLEARTEXT_MARKER, + devCleartextManifest, + hasDevCleartext, + needsDevCleartext, + withDevCleartext, +} from "../../../lib/services/android/dev-cleartext-manifest"; + +describe("dev-cleartext-manifest", () => { + describe("needsDevCleartext", () => { + it("is true only for Vite debug HMR runs", () => { + assert.isTrue( + needsDevCleartext({ bundler: "vite" }, { hmr: true, release: false }), + ); + assert.isFalse( + needsDevCleartext({ bundler: "vite" }, { hmr: true, release: true }), + ); + assert.isFalse( + needsDevCleartext({ bundler: "vite" }, { hmr: false, release: false }), + ); + assert.isFalse( + needsDevCleartext( + { bundler: "webpack" }, + { hmr: true, release: false }, + ), + ); + }); + }); + + describe("devCleartextManifest", () => { + it("permits cleartext and overrides a main manifest's value", () => { + const manifest = devCleartextManifest(); + assert.include(manifest, 'android:usesCleartextTraffic="true"'); + assert.include(manifest, 'tools:replace="android:usesCleartextTraffic"'); + assert.include( + manifest, + 'xmlns:tools="http://schemas.android.com/tools"', + ); + assert.isTrue(hasDevCleartext(manifest)); + }); + }); + + describe("hasDevCleartext", () => { + it("only recognizes a manifest the CLI marked", () => { + assert.isFalse(hasDevCleartext(null)); + assert.isFalse( + hasDevCleartext( + '', + ), + ); + }); + }); + + describe("withDevCleartext", () => { + it("adds the attribute, tools:replace and the tools namespace to the app's debug manifest", () => { + const result = withDevCleartext( + [ + '', + '', + '\t', + '\t\t', + "\t", + "", + ].join("\n"), + ); + assert.include(result, 'xmlns:tools="http://schemas.android.com/tools"'); + assert.match( + result, + //, + ); + assert.include(result, ''); + assert.include(result, DEV_CLEARTEXT_MARKER); + assert.match(result, /^<\?xml/); + }); + + it("turns an explicit false into true and extends an existing tools:replace", () => { + const result = withDevCleartext( + '', + ); + assert.include(result, 'android:usesCleartextTraffic="true"'); + assert.notInclude(result, 'usesCleartextTraffic="false"'); + assert.include( + result, + 'tools:replace="android:label,android:usesCleartextTraffic"', + ); + assert.equal(result.match(/xmlns:tools=/g).length, 1); + }); + + it("adds an application element when the manifest has none", () => { + const result = withDevCleartext( + '\n\t\n', + ); + assert.match( + result, + /\n<\/manifest>/, + ); + }); + }); +}); diff --git a/test/services/bundler/bundler-compiler-service.ts b/test/services/bundler/bundler-compiler-service.ts index ef5d94c745..85d70658f3 100644 --- a/test/services/bundler/bundler-compiler-service.ts +++ b/test/services/bundler/bundler-compiler-service.ts @@ -2,6 +2,8 @@ import { Yok } from "../../../lib/common/yok"; import { BundlerCompilerService } from "../../../lib/services/bundler/bundler-compiler-service"; import { assert } from "chai"; import { EventEmitter } from "events"; +import * as fs from "fs"; +import * as os from "os"; import * as path from "path"; import { ErrorsStub } from "../../stubs"; import { IInjector } from "../../../lib/common/definitions/yok"; @@ -670,6 +672,239 @@ describe("BundlerCompilerService", () => { }); }); + describe("vite single-process dev server", () => { + const platformData = { + platformNameLowerCase: "ios", + appDestinationDirectoryPath: "/platform/app", + }; + const projectData = { + projectDir: "/project", + bundler: "vite", + bundlerConfigPath: "/project/vite.config.ts", + }; + + let serveProcess: FakeChildProcess = null; + let spawnOptions: any = null; + let copies: any[][] = null; + let removals: any[][] = null; + let syncEvents: any[] = null; + let buildProcessStarted = false; + + beforeEach(() => { + serveProcess = fakeChildProcess(789); + spawnOptions = null; + copies = []; + removals = []; + syncEvents = []; + buildProcessStarted = false; + + testInjector.resolve("options").hostProjectModuleName = "app"; + const service = bundlerCompilerService; + service.getBundler = () => "vite"; + service.getBundlerExecutablePath = () => "/project/vite.js"; + service.buildEnvData = () => ({}); + service.buildEnvCommandLineParams = async (): Promise => []; + service.supportsViteSingleProcess = () => true; + service.startBundleProcess = async () => { + buildProcessStarted = true; + return fakeChildProcess(1); + }; + service.copyViteBundleToNative = (...args: any[]) => copies.push(args); + service.removeViteFilesFromNative = (...args: any[]) => + removals.push(args); + testInjector.resolve("childProcess").spawn = ( + _command: string, + _args: string[], + options: any, + ) => { + spawnOptions = options; + return serveProcess; + }; + bundlerCompilerService.on(BUNDLER_COMPILATION_COMPLETE, (data) => + syncEvents.push(data), + ); + }); + + const compile = (prepareData: any = { hmr: true }) => + bundlerCompilerService.compileWithWatch( + platformData, + projectData, + prepareData, + ); + + it("runs vite serve alone and starts the app on its first build message", async () => { + const compiling = compile(); + await flush(); + + assert.isFalse(buildProcessStarted); + assert.strictEqual(spawnOptions.env.NS_VITE_SINGLE_PROCESS, "1"); + assert.strictEqual( + (bundlerCompilerService).bundlerProcesses.ios, + serveProcess, + ); + + serveProcess.emit("message", { + emittedFiles: ["bundle.mjs", "package.json", "assets/logo.png"], + chunkFiles: [], + hash: "1", + isHMR: false, + buildType: "initial", + }); + + assert.strictEqual(await compiling, serveProcess); + assert.deepStrictEqual(copies, [ + ["/project/.ns-vite-build/ios", "/platform/app/app"], + ]); + assert.lengthOf(syncEvents, 0); + }); + + it("syncs the files of later messages and only removes a removed file", async () => { + const compiling = compile(); + await flush(); + serveProcess.emit("message", { + emittedFiles: ["bundle.mjs"], + buildType: "initial", + }); + await compiling; + copies = []; + removals = []; + + serveProcess.emit("message", { + emittedFiles: ["assets/logo.png"], + hash: "2", + isHMR: false, + buildType: "incremental", + }); + serveProcess.emit("message", { + emittedFiles: [], + removedFiles: ["assets/old.png"], + hash: "3", + isHMR: false, + buildType: "incremental", + }); + + assert.deepStrictEqual(copies, [ + [ + "/project/.ns-vite-build/ios", + "/platform/app/app", + ["assets/logo.png"], + ], + ["/project/.ns-vite-build/ios", "/platform/app/app", []], + ]); + assert.deepStrictEqual(removals, [ + ["/platform/app/app", []], + ["/platform/app/app", ["assets/old.png"]], + ]); + assert.deepStrictEqual(syncEvents, [ + { + files: ["/platform/app/app/assets/logo.png"], + hasOnlyHotUpdateFiles: false, + hmrData: { hash: "2", fallbackFiles: [] }, + platform: "ios", + }, + ]); + }); + + it("fails the run when the dev server exits before its first build message", async () => { + const compiling = compile(); + await flush(); + serveProcess.emit("exit", 1); + + await assert.isRejected(compiling, "exited with code 1"); + assert.isUndefined((bundlerCompilerService).bundlerProcesses.ios); + }); + + it("stops the dev server once", async () => { + const compiling = compile(); + await flush(); + serveProcess.emit("message", { + emittedFiles: ["bundle.mjs"], + buildType: "initial", + }); + await compiling; + + const stopping = bundlerCompilerService.stopBundlerCompiler("ios"); + await flush(); + serveProcess.emit("exit", 0); + serveProcess.emit("close", 0); + await stopping; + + assert.deepStrictEqual(serveProcess.killSignals, ["SIGINT"]); + assert.isUndefined((bundlerCompilerService).bundlerProcesses.ios); + assert.isUndefined((bundlerCompilerService).viteServeProcesses.ios); + }); + + it("keeps the build process when the package does not support it", async () => { + (bundlerCompilerService).supportsViteSingleProcess = () => false; + (bundlerCompilerService).waitForPort = async () => true; + void compile(); + await flush(); + + assert.isTrue(buildProcessStarted); + assert.isUndefined(spawnOptions.env.NS_VITE_SINGLE_PROCESS); + }); + }); + + describe("supportsViteSingleProcess", () => { + let projectDir: string; + const originalEnv = process.env.NS_VITE_SINGLE_PROCESS; + + const writeVitePackage = (pkg: object) => { + const dir = path.join( + projectDir, + "node_modules", + "@nativescript", + "vite", + ); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, "package.json"), JSON.stringify(pkg)); + }; + const supports = (platform: string) => + (bundlerCompilerService).supportsViteSingleProcess(platform, { + projectDir, + }); + + beforeEach(() => { + projectDir = fs.mkdtempSync(path.join(os.tmpdir(), "ns-vite-sp-")); + (bundlerCompilerService).getBundler = () => "vite"; + testInjector.resolve("fs").readJson = (file: string) => + JSON.parse(fs.readFileSync(file, "utf8")); + delete process.env.NS_VITE_SINGLE_PROCESS; + }); + + afterEach(() => { + fs.rmSync(projectDir, { recursive: true, force: true }); + if (originalEnv === undefined) { + delete process.env.NS_VITE_SINGLE_PROCESS; + } else { + process.env.NS_VITE_SINGLE_PROCESS = originalEnv; + } + }); + + it("reads the platforms the installed @nativescript/vite declares", () => { + writeVitePackage({ + name: "@nativescript/vite", + nativescriptCli: { singleProcessDev: ["ios", "visionos"] }, + }); + + assert.isTrue(supports("ios")); + assert.isTrue(supports("visionos")); + assert.isFalse(supports("android")); + }); + + it("is off for a package that declares nothing, or when the user opts out", () => { + writeVitePackage({ name: "@nativescript/vite" }); + assert.isFalse(supports("ios")); + + writeVitePackage({ + name: "@nativescript/vite", + nativescriptCli: { singleProcessDev: ["ios"] }, + }); + process.env.NS_VITE_SINGLE_PROCESS = "0"; + assert.isFalse(supports("ios")); + }); + }); + describe("stopBundlerCompiler", () => { const platformData = { platformNameLowerCase: "ios", diff --git a/test/services/livesync/android-device-livesync-sockets-service.ts b/test/services/livesync/android-device-livesync-sockets-service.ts new file mode 100644 index 0000000000..4077b3a020 --- /dev/null +++ b/test/services/livesync/android-device-livesync-sockets-service.ts @@ -0,0 +1,34 @@ +import { assert } from "chai"; +import { refreshesInPlaceOnSync } from "../../../lib/services/livesync/android-device-livesync-sockets-service"; + +describe("refreshesInPlaceOnSync", () => { + it("refreshes an incremental sync", () => { + assert.isTrue( + refreshesInPlaceOnSync( + { isFullSync: false, useHotModuleReload: true }, + { bundler: "webpack" }, + ), + ); + assert.isTrue( + refreshesInPlaceOnSync( + { isFullSync: false, useHotModuleReload: false }, + { bundler: "vite" }, + ), + ); + }); + + it("never refreshes a full sync or a Vite HMR session", () => { + assert.isFalse( + refreshesInPlaceOnSync( + { isFullSync: true, useHotModuleReload: false }, + { bundler: "webpack" }, + ), + ); + assert.isFalse( + refreshesInPlaceOnSync( + { isFullSync: false, useHotModuleReload: true }, + { bundler: "vite" }, + ), + ); + }); +});