Skip to content

Commit acb5ec6

Browse files
committed
feat(vite): restart the app when the Vite dev server asks for it
`vite serve` is now spawned with an IPC channel. When it sends `{ type: 'nativescript:restart', reason }`, the CLI logs the reason and restarts the app on that platform's devices in the running session, without rebuilding or syncing. Requests that arrive within 300 ms collapse into one restart. The restart joins the session's action chain, so it runs after any sync or build already in progress. It reuses RunController.restartApplication, which keeps debug sessions attached. Other message shapes are ignored, and dev servers that never send one behave as before.
1 parent bae5b1c commit acb5ec6

6 files changed

Lines changed: 371 additions & 4 deletions

File tree

‎lib/constants.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,8 @@ export const FILES_CHANGE_EVENT_NAME = "filesChangeEvent";
241241
export const INITIAL_SYNC_EVENT_NAME = "initialSyncEvent";
242242
export const PREPARE_READY_EVENT_NAME = "prepareReadyEvent";
243243
export const BUNDLER_COMPILATION_COMPLETE = "bundlerCompilationComplete";
244+
/** Payload: `IBundlerAppRestartRequest`. */
245+
export const BUNDLER_APP_RESTART_REQUESTED = "bundlerAppRestartRequested";
244246

245247
export class DebugCommandErrors {
246248
public static UNABLE_TO_USE_FOR_DEVICE_AND_EMULATOR =

‎lib/controllers/run-controller.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { HmrConstants, DeviceDiscoveryEventNames } from "../common/constants";
22
import {
3+
BUNDLER_APP_RESTART_REQUESTED,
34
PREPARE_READY_EVENT_NAME,
45
TrackActionNames,
56
DEBUGGER_DETACHED_EVENT_NAME,
@@ -28,6 +29,9 @@ import { injector } from "../common/yok";
2829

2930
export class RunController extends EventEmitter implements IRunController {
3031
private prepareReadyEventHandler: any = null;
32+
private appRestartRequestHandler: (
33+
request: IBundlerAppRestartRequest,
34+
) => void = null;
3135
private _syncInProgress = false;
3236
private _pendingSyncs: Map<
3337
string,
@@ -41,6 +45,7 @@ export class RunController extends EventEmitter implements IRunController {
4145
constructor(
4246
protected $analyticsService: IAnalyticsService,
4347
private $buildController: IBuildController,
48+
private $bundlerCompilerService: IBundlerCompilerService,
4449
private $debugController: IDebugController,
4550
private $deviceInstallAppService: IDeviceInstallAppService,
4651
protected $devicesService: Mobile.IDevicesService,
@@ -124,6 +129,14 @@ export class RunController extends EventEmitter implements IRunController {
124129
this.prepareReadyEventHandler,
125130
);
126131
}
132+
if (!this.appRestartRequestHandler) {
133+
this.appRestartRequestHandler = (request) =>
134+
this.restartApplicationOnPlatform(request);
135+
this.$bundlerCompilerService.on(
136+
BUNDLER_APP_RESTART_REQUESTED,
137+
this.appRestartRequestHandler,
138+
);
139+
}
127140
await this.syncInitialDataOnDevices(
128141
projectData,
129142
liveSyncInfo,
@@ -198,6 +211,14 @@ export class RunController extends EventEmitter implements IRunController {
198211
this.prepareReadyEventHandler = null;
199212
}
200213

214+
if (this.appRestartRequestHandler) {
215+
this.$bundlerCompilerService.removeListener(
216+
BUNDLER_APP_RESTART_REQUESTED,
217+
this.appRestartRequestHandler,
218+
);
219+
this.appRestartRequestHandler = null;
220+
}
221+
201222
const projectData = this.$projectDataService.getProjectData(projectDir);
202223
await this.$hooksService.executeAfterHooks("watch", {
203224
hookArgs: {
@@ -346,6 +367,36 @@ export class RunController extends EventEmitter implements IRunController {
346367
);
347368
}
348369

370+
private async restartApplicationOnPlatform(
371+
request: IBundlerAppRestartRequest,
372+
): Promise<void> {
373+
const { projectDir, platform, reason } = request;
374+
const onPlatform = this.$devicesService
375+
.getDevicesForPlatform(platform)
376+
.map((device) => device.deviceInfo.identifier);
377+
const deviceIdentifiers = this.$liveSyncProcessDataService
378+
.getDeviceDescriptors(projectDir)
379+
.map((descriptor) => descriptor.identifier)
380+
.filter((identifier) => onPlatform.includes(identifier));
381+
382+
// An empty list would mean "every device" to `restartApplication`.
383+
if (!deviceIdentifiers.length) {
384+
this.$logger.trace(
385+
`Ignoring the ${platform} app restart request (${reason}): no ${platform} device in the session.`,
386+
);
387+
return;
388+
}
389+
390+
this.$logger.info(`Restarting the app on ${platform}: ${reason}`);
391+
try {
392+
await this.restartApplication({ projectDir, deviceIdentifiers });
393+
} catch (err) {
394+
this.$logger.warn(
395+
`Unable to restart the app on ${platform}: ${err.message || err}`,
396+
);
397+
}
398+
}
399+
349400
protected async refreshApplication(
350401
projectData: IProjectData,
351402
liveSyncResultInfo: ILiveSyncResultInfo,

‎lib/services/bundler/bundler-compiler-service.ts‎

Lines changed: 86 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { performanceLog } from "../../common/decorators";
88
import {
99
WEBPACK_PLUGIN_NAME,
1010
BUNDLER_COMPILATION_COMPLETE,
11+
BUNDLER_APP_RESTART_REQUESTED,
1112
PackageManagers,
1213
CONFIG_FILE_NAME_DISPLAY,
1314
VITE_DIST_FOLDER_NAME,
@@ -60,6 +61,12 @@ const debugLog = false;
6061
/** Grace period a bundler child gets to honour SIGINT before it is killed. */
6162
const BUNDLER_STOP_TIMEOUT_MS = 5000;
6263

64+
/**
65+
* IPC message `vite serve` (`@nativescript/vite`) sends when a change can only
66+
* be applied by restarting the app process.
67+
*/
68+
const VITE_APP_RESTART_MESSAGE_TYPE = "nativescript:restart";
69+
6370
export class BundlerCompilerService
6471
extends EventEmitter
6572
implements IBundlerCompilerService
@@ -69,6 +76,12 @@ export class BundlerCompilerService
6976
// modules and HMR updates from. Keyed by platform, managed by this CLI
7077
// so users no longer need a separate `concurrently`/`wait-on` process.
7178
private viteServeProcesses: IDictionary<child_process.ChildProcess> = {};
79+
private pendingAppRestarts: IDictionary<{
80+
reasons: string[];
81+
timer: NodeJS.Timeout;
82+
}> = {};
83+
/** Restart requests within this window collapse into one restart. */
84+
private appRestartDebounceMs = 300;
7285
private expectedHashes: IStringDictionary = {};
7386

7487
constructor(
@@ -737,16 +750,17 @@ export class BundlerCompilerService
737750

738751
const options: { [key: string]: any } = {
739752
cwd: projectData.projectDir,
740-
// Output is inherited so the dev server's URLs/logs stream to the
741-
// user. No IPC needed here — the build watcher provides the
742-
// bundle-complete IPC; the dev server is fetched over HTTP/ws.
753+
// Logs stream straight to the user. The IPC channel only carries
754+
// app-restart requests; a server that never sends one behaves as
755+
// with plain "inherit".
743756
// Vite reads a terminal stdin for shortcuts of its own, which would
744757
// take the keys meant for the CLI's; otherwise its shortcuts are the
745758
// only ones the terminal has.
746759
stdio: [
747760
commandShortcutsOwnTerminal() ? "ignore" : "inherit",
748761
"inherit",
749762
"inherit",
763+
"ipc",
750764
],
751765
env: {
752766
...process.env,
@@ -770,9 +784,14 @@ export class BundlerCompilerService
770784
this.viteServeProcesses[key] = childProcess;
771785
await this.$cleanupService.addKillProcess(childProcess.pid.toString());
772786

787+
childProcess.on("message", (message: unknown) =>
788+
this.handleViteServeMessage(message, key, projectData.projectDir),
789+
);
790+
773791
childProcess.once("exit", (code: number) => {
774792
if (this.viteServeProcesses[key] === childProcess) {
775793
delete this.viteServeProcesses[key];
794+
this.cancelAppRestart(key);
776795
}
777796
if (code) {
778797
this.$logger.warn(
@@ -804,6 +823,68 @@ export class BundlerCompilerService
804823
}
805824
}
806825

826+
/**
827+
* Unknown message shapes are ignored without a log, so a newer
828+
* `@nativescript/vite` can add message types without breaking this CLI.
829+
*/
830+
private handleViteServeMessage(
831+
message: unknown,
832+
platform: string,
833+
projectDir: string,
834+
): void {
835+
if (
836+
!message ||
837+
typeof message !== "object" ||
838+
(message as { type?: unknown }).type !== VITE_APP_RESTART_MESSAGE_TYPE
839+
) {
840+
return;
841+
}
842+
843+
const { reason } = message as { reason?: unknown };
844+
this.requestAppRestart(
845+
platform,
846+
projectDir,
847+
typeof reason === "string" && reason
848+
? reason
849+
: "the Vite dev server requested it",
850+
);
851+
}
852+
853+
private requestAppRestart(
854+
platform: string,
855+
projectDir: string,
856+
reason: string,
857+
): void {
858+
const pending = this.pendingAppRestarts[platform] || {
859+
reasons: [],
860+
timer: null,
861+
};
862+
if (!pending.reasons.includes(reason)) {
863+
pending.reasons.push(reason);
864+
}
865+
clearTimeout(pending.timer);
866+
pending.timer = setTimeout(() => {
867+
delete this.pendingAppRestarts[platform];
868+
const request: IBundlerAppRestartRequest = {
869+
projectDir,
870+
platform,
871+
reason: pending.reasons.join("; "),
872+
};
873+
this.emit(BUNDLER_APP_RESTART_REQUESTED, request);
874+
}, this.appRestartDebounceMs);
875+
// A pending timer must not be what keeps the CLI alive.
876+
pending.timer.unref?.();
877+
this.pendingAppRestarts[platform] = pending;
878+
}
879+
880+
private cancelAppRestart(platform: string): void {
881+
const pending = this.pendingAppRestarts[platform];
882+
if (pending) {
883+
clearTimeout(pending.timer);
884+
delete this.pendingAppRestarts[platform];
885+
}
886+
}
887+
807888
/**
808889
* Resolve true once `127.0.0.1:<port>` accepts a TCP connection, or
809890
* false after `timeoutMs`. Used to detect the Vite dev server is up.
@@ -1042,6 +1123,8 @@ export class BundlerCompilerService
10421123
// Tear down the Vite dev server we manage alongside the build watcher.
10431124
const viteServeProcess = this.viteServeProcesses[platform];
10441125
if (viteServeProcess) {
1126+
viteServeProcess.removeAllListeners("message");
1127+
this.cancelAppRestart(platform);
10451128
await this.terminate(viteServeProcess);
10461129
if (this.viteServeProcesses[platform] === viteServeProcess) {
10471130
delete this.viteServeProcesses[platform];

‎lib/services/bundler/bundler.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,18 @@ declare global {
3232
stopBundlerCompiler(platform: string): Promise<void>;
3333
}
3434

35+
/**
36+
* The bundler's dev server asked for the app process to be restarted,
37+
* because a change cannot be applied as a hot update.
38+
*/
39+
interface IBundlerAppRestartRequest {
40+
projectDir: string;
41+
/** Lowercase platform name. */
42+
platform: string;
43+
/** Human-readable; may combine several requests. */
44+
reason: string;
45+
}
46+
3547
interface IBundlerEnvOptions {
3648
sourceMap?: boolean;
3749
uglify?: boolean;

‎test/controllers/run-controller.ts‎

Lines changed: 96 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,11 @@ import { LiveSyncServiceResolver } from "../../lib/resolvers/livesync-service-re
44
import { MobileHelper } from "../../lib/common/mobile/mobile-helper";
55
import { assert } from "chai";
66
import * as _ from "lodash";
7-
import { RunOnDeviceEvents } from "../../lib/constants";
7+
import { EventEmitter } from "events";
8+
import {
9+
BUNDLER_APP_RESTART_REQUESTED,
10+
RunOnDeviceEvents,
11+
} from "../../lib/constants";
812
import { PrepareData } from "../../lib/data/prepare-data";
913
import { PrepareDataService } from "../../lib/services/prepare-data-service";
1014
import { BuildDataService } from "../../lib/services/build-data-service";
@@ -124,6 +128,7 @@ function createTestInjector() {
124128
});
125129
injector.register("prepareNativePlatformService", {});
126130
injector.register("projectChangesService", {});
131+
injector.register("bundlerCompilerService", new EventEmitter());
127132
injector.register("runController", RunController);
128133
injector.register("prepareDataService", PrepareDataService);
129134
injector.register("buildDataService", BuildDataService);
@@ -423,6 +428,96 @@ describe("RunController", () => {
423428
{ device: "myiOSDevice", isFullSync: false },
424429
]);
425430
});
431+
432+
describe("requested by the bundler", () => {
433+
let bundlerCompilerService: EventEmitter = null;
434+
435+
beforeEach(async () => {
436+
bundlerCompilerService = injector.resolve("bundlerCompilerService");
437+
mockDevicesService(injector, []);
438+
await runController.run({ liveSyncInfo, deviceDescriptors: [] });
439+
440+
startSession(
441+
[iOSDeviceDescriptor, androidDeviceDescriptor],
442+
[iOSDevice, androidDevice],
443+
);
444+
injector.resolve("devicesService").getDevicesForPlatform = (
445+
platform: string,
446+
) =>
447+
[iOSDevice, androidDevice].filter(
448+
(device) => device.deviceInfo.platform === platform,
449+
);
450+
infoMessages = [];
451+
});
452+
453+
async function requestRestart(platform: string, reason: string) {
454+
bundlerCompilerService.emit(BUNDLER_APP_RESTART_REQUESTED, {
455+
projectDir,
456+
platform,
457+
reason,
458+
});
459+
await injector
460+
.resolve("liveSyncProcessDataService")
461+
.getPersistedData(projectDir).actionsChain;
462+
}
463+
464+
it("restarts the app only on the session's devices of that platform", async () => {
465+
await requestRestart("android", "vite.config.ts changed");
466+
467+
assert.deepStrictEqual(restartedApps, [
468+
{ device: "myAndroidDevice", isFullSync: false },
469+
]);
470+
assert.deepStrictEqual(infoMessages, [
471+
"Restarting the app on android: vite.config.ts changed",
472+
]);
473+
});
474+
475+
it("restarts nothing when the session has no device of that platform", async () => {
476+
const persisted = injector
477+
.resolve("liveSyncProcessDataService")
478+
.getPersistedData(projectDir);
479+
_.remove(
480+
persisted.deviceDescriptors,
481+
(descriptor: ILiveSyncDeviceDescriptor) =>
482+
descriptor.identifier === "myAndroidDevice",
483+
);
484+
485+
await requestRestart("android", "vite.config.ts changed");
486+
487+
assert.lengthOf(restartedApps, 0);
488+
assert.lengthOf(infoMessages, 0);
489+
});
490+
491+
it("waits for the action already running on the session", async () => {
492+
const persisted = injector
493+
.resolve("liveSyncProcessDataService")
494+
.getPersistedData(projectDir);
495+
let release: () => void;
496+
persisted.actionsChain = new Promise<void>((resolve) => {
497+
release = resolve;
498+
});
499+
500+
const restarting = requestRestart("ios", "app.ts changed");
501+
await new Promise((resolve) => setImmediate(resolve));
502+
assert.lengthOf(restartedApps, 0);
503+
504+
release();
505+
await restarting;
506+
507+
assert.deepStrictEqual(restartedApps, [
508+
{ device: "myiOSDevice", isFullSync: false },
509+
]);
510+
});
511+
512+
it("stops listening once the session stops", async () => {
513+
await runController.stop({ projectDir });
514+
515+
assert.strictEqual(
516+
bundlerCompilerService.listenerCount(BUNDLER_APP_RESTART_REQUESTED),
517+
0,
518+
);
519+
});
520+
});
426521
});
427522

428523
describe("stopRunOnDevices", () => {

0 commit comments

Comments
 (0)