Skip to content

Commit b4c2654

Browse files
authored
feat(vite): single-process HMR dev and debug cleartext for Android (#6209)
When the installed @nativescript/vite lists the platform under nativescriptCli.singleProcessDev, an HMR session spawns only `vite serve` with NS_VITE_SINGLE_PROCESS=1. The dev server writes bundle.mjs, package.json and the app's static files and sends the build messages `vite build --watch` sent. The CLI copies, syncs and launches on them, and deletes a message's optional removedFiles from the native app folder. A package without the field, or NS_VITE_SINGLE_PROCESS=0, keeps the two-process session. For a debug Vite HMR build, Android native prepare writes a CLI-marked debug source set manifest with android:usesCleartextTraffic="true" (tools:replace), or adds the attribute to the app's own debug manifest, so the app can reach the dev server over HTTP. App_Resources is never modified, any other prepare removes only the CLI-marked file, and the change check rebuilds when the wanted state differs. Host projects are skipped. Android HMR syncs skip the in-app refresh before a restart.
1 parent 8bffb04 commit b4c2654

10 files changed

Lines changed: 1177 additions & 143 deletions

‎lib/services/android-project-service.ts‎

Lines changed: 66 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,14 @@ import { inject } from "../common/di";
5656
import { injector } from "../common/yok";
5757
import { AndroidPluginMirrorService } from "../contracts/internal/android-plugin-mirror-service";
5858
import { NativeFileHashesMemo } from "../contracts/internal/native-file-hashes-memo";
59+
import { IProjectChangesInfo } from "../definitions/project-changes";
60+
import {
61+
DEV_CLEARTEXT_MARKER,
62+
devCleartextManifest,
63+
hasDevCleartext,
64+
needsDevCleartext,
65+
withDevCleartext,
66+
} from "./android/dev-cleartext-manifest";
5967
import { INotConfiguredEnvOptions } from "../common/definitions/commands";
6068

6169
interface NativeDependency {
@@ -1321,8 +1329,64 @@ export class AndroidProjectService
13211329
await adb.executeShellCommand(["rm", "-rf", deviceRootPath]);
13221330
}
13231331

1324-
public async checkForChanges(): Promise<void> {
1325-
// Nothing android specific to check yet.
1332+
public async checkForChanges(
1333+
changesInfo: IProjectChangesInfo,
1334+
prepareData: IPrepareData,
1335+
projectData: IProjectData,
1336+
): Promise<void> {
1337+
// Native prepare skips `prepareDevServerAccess` for a host project.
1338+
if (this.$options.hostProjectPath) {
1339+
return;
1340+
}
1341+
const manifestPath = this.getDebugManifestPath(projectData);
1342+
const current = this.$fs.exists(manifestPath)
1343+
? this.$fs.readText(manifestPath)
1344+
: null;
1345+
// The build is what carries the permission, so a change has to rebuild.
1346+
if (
1347+
needsDevCleartext(projectData, prepareData) !== hasDevCleartext(current)
1348+
) {
1349+
changesInfo.appResourcesChanged = true;
1350+
}
1351+
}
1352+
1353+
/**
1354+
* Lets a Vite HMR debug build fetch its code from the dev server over
1355+
* plain HTTP, through the debug source set's manifest in the native
1356+
* project. Runs after `prepareAppResources`, which restores the app's own
1357+
* debug manifest, if any, from App_Resources.
1358+
*/
1359+
public prepareDevServerAccess(
1360+
projectData: IProjectData,
1361+
prepareData: IPrepareData,
1362+
): void {
1363+
const manifestPath = this.getDebugManifestPath(projectData);
1364+
const current = this.$fs.exists(manifestPath)
1365+
? this.$fs.readText(manifestPath)
1366+
: null;
1367+
if (!needsDevCleartext(projectData, prepareData)) {
1368+
if (current !== null && current.includes(DEV_CLEARTEXT_MARKER)) {
1369+
this.$fs.deleteFile(manifestPath);
1370+
}
1371+
return;
1372+
}
1373+
if (hasDevCleartext(current)) {
1374+
return;
1375+
}
1376+
this.$fs.writeFile(
1377+
manifestPath,
1378+
current === null ? devCleartextManifest() : withDevCleartext(current),
1379+
);
1380+
}
1381+
1382+
private getDebugManifestPath(projectData: IProjectData): string {
1383+
return path.join(
1384+
this.getPlatformData(projectData).projectRoot,
1385+
this.$options.hostProjectModuleName,
1386+
constants.SRC_DIR,
1387+
"debug",
1388+
constants.MANIFEST_FILE_NAME,
1389+
);
13261390
}
13271391

13281392
public getDeploymentTarget(projectData: IProjectData): semver.SemVer {
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
import { IProjectData } from "../../definitions/project";
2+
3+
/**
4+
* Identifies a debug manifest whose cleartext permission the CLI wrote, so a
5+
* later prepare that doesn't need it can take it out again.
6+
*/
7+
export const DEV_CLEARTEXT_MARKER =
8+
"nativescript-cli: cleartext HTTP to the Vite dev server (debug HMR runs only)";
9+
10+
const TOOLS_NS = 'xmlns:tools="http://schemas.android.com/tools"';
11+
const CLEARTEXT_ATTRIBUTE = "android:usesCleartextTraffic";
12+
13+
/**
14+
* A Vite HMR app loads its code from the dev server over plain HTTP, which
15+
* Android blocks by default from API 28.
16+
*/
17+
export function needsDevCleartext(
18+
projectData: Pick<IProjectData, "bundler">,
19+
prepareData: { hmr?: boolean; release?: boolean },
20+
): boolean {
21+
return (
22+
projectData.bundler === "vite" && !!prepareData.hmr && !prepareData.release
23+
);
24+
}
25+
26+
export function hasDevCleartext(manifest: string | null): boolean {
27+
return !!manifest && manifest.includes(DEV_CLEARTEXT_MARKER);
28+
}
29+
30+
/** The debug source set's manifest when the app ships none of its own. */
31+
export function devCleartextManifest(): string {
32+
return [
33+
'<?xml version="1.0" encoding="utf-8"?>',
34+
`<!-- ${DEV_CLEARTEXT_MARKER} -->`,
35+
`<manifest xmlns:android="http://schemas.android.com/apk/res/android" ${TOOLS_NS}>`,
36+
`\t<application ${CLEARTEXT_ATTRIBUTE}="true" tools:replace="${CLEARTEXT_ATTRIBUTE}" />`,
37+
"</manifest>",
38+
"",
39+
].join("\n");
40+
}
41+
42+
interface Tag {
43+
index: number;
44+
text: string;
45+
}
46+
47+
/** The first match of `pattern` outside an XML comment. */
48+
function findTag(source: string, pattern: RegExp): Tag | null {
49+
const comments: Array<[number, number]> = [];
50+
const comment = /<!--[\s\S]*?-->/g;
51+
for (let m = comment.exec(source); m; m = comment.exec(source)) {
52+
comments.push([m.index, m.index + m[0].length]);
53+
}
54+
const search = new RegExp(pattern.source, "g");
55+
for (let m = search.exec(source); m; m = search.exec(source)) {
56+
const at = m.index;
57+
if (!comments.some(([from, to]) => at >= from && at < to)) {
58+
return { index: at, text: m[0] };
59+
}
60+
}
61+
return null;
62+
}
63+
64+
function replaceTag(source: string, tag: Tag, replacement: string): string {
65+
return (
66+
source.slice(0, tag.index) +
67+
replacement +
68+
source.slice(tag.index + tag.text.length)
69+
);
70+
}
71+
72+
/**
73+
* The app's own debug manifest with the permission added. `tools:replace`
74+
* lets it win over a main manifest that sets the attribute itself.
75+
*/
76+
export function withDevCleartext(manifest: string): string {
77+
let result = manifest;
78+
const manifestTag = findTag(result, /<manifest\b[^>]*>/);
79+
if (!manifestTag) {
80+
return result;
81+
}
82+
if (!manifestTag.text.includes("xmlns:tools=")) {
83+
result = replaceTag(
84+
result,
85+
manifestTag,
86+
manifestTag.text.replace(/^<manifest\b/, `<manifest ${TOOLS_NS}`),
87+
);
88+
}
89+
90+
const applicationTag = findTag(result, /<application\b[^>]*?\/?>/);
91+
if (!applicationTag) {
92+
const application = `\t<application ${CLEARTEXT_ATTRIBUTE}="true" tools:replace="${CLEARTEXT_ATTRIBUTE}" />`;
93+
const root = findTag(result, /<manifest\b[^>]*>/);
94+
const closing = findTag(result, /<\/manifest>/);
95+
if (root.text.endsWith("/>")) {
96+
result = replaceTag(
97+
result,
98+
root,
99+
`${root.text.slice(0, -2).trimEnd()}>\n${application}\n</manifest>`,
100+
);
101+
} else if (closing) {
102+
result = replaceTag(result, closing, `${application}\n</manifest>`);
103+
} else {
104+
// Without the marker, the next prepare tries again.
105+
return manifest;
106+
}
107+
} else {
108+
let tag = applicationTag.text;
109+
const value = /android:usesCleartextTraffic\s*=\s*(?:"[^"]*"|'[^']*')/;
110+
tag = value.test(tag)
111+
? tag.replace(value, `${CLEARTEXT_ATTRIBUTE}="true"`)
112+
: tag.replace(
113+
/^<application\b/,
114+
`<application ${CLEARTEXT_ATTRIBUTE}="true"`,
115+
);
116+
const replace = /tools:replace\s*=\s*(["'])([\s\S]*?)\1/.exec(tag);
117+
if (!replace) {
118+
tag = tag.replace(
119+
/^<application\b/,
120+
`<application tools:replace="${CLEARTEXT_ATTRIBUTE}"`,
121+
);
122+
} else if (
123+
!replace[2]
124+
.split(",")
125+
.map((name) => name.trim())
126+
.includes(CLEARTEXT_ATTRIBUTE)
127+
) {
128+
const [, quote, names] = replace;
129+
tag = tag.replace(
130+
replace[0],
131+
`tools:replace=${quote}${names.trimEnd()},${CLEARTEXT_ATTRIBUTE}${quote}`,
132+
);
133+
}
134+
result = replaceTag(result, applicationTag, tag);
135+
}
136+
137+
const root = findTag(result, /<manifest\b/);
138+
return replaceTag(
139+
result,
140+
root,
141+
`<!-- ${DEV_CLEARTEXT_MARKER} -->\n<manifest`,
142+
);
143+
}

0 commit comments

Comments
 (0)