Skip to content

Commit 976eaed

Browse files
committed
fix(android): edit real debug manifest tags and multi-line tools:replace
withDevCleartext skips tags inside XML comments, so a commented-out <application> or <manifest> before the real one is left alone, and its tools:replace match spans newlines, so a multi-line value is extended instead of getting a second, duplicate attribute. Adds specs for prepareDevServerAccess and checkForChanges: which prepares write, keep or remove the CLI-marked manifest, that the app's own manifest is never removed, and the host-project skip.
1 parent 8bfe499 commit 976eaed

3 files changed

Lines changed: 246 additions & 20 deletions

File tree

‎lib/services/android/dev-cleartext-manifest.ts‎

Lines changed: 54 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -39,49 +39,81 @@ export function devCleartextManifest(): string {
3939
].join("\n");
4040
}
4141

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+
4272
/**
4373
* The app's own debug manifest with the permission added. `tools:replace`
4474
* lets it win over a main manifest that sets the attribute itself.
4575
*/
4676
export function withDevCleartext(manifest: string): string {
4777
let result = manifest;
48-
const manifestTag = /<manifest\b[^>]*>/.exec(result);
78+
const manifestTag = findTag(result, /<manifest\b[^>]*>/);
4979
if (!manifestTag) {
5080
return result;
5181
}
52-
if (!manifestTag[0].includes("xmlns:tools=")) {
53-
const withTools = manifestTag[0].replace(
54-
/^<manifest\b/,
55-
`<manifest ${TOOLS_NS}`,
82+
if (!manifestTag.text.includes("xmlns:tools=")) {
83+
result = replaceTag(
84+
result,
85+
manifestTag,
86+
manifestTag.text.replace(/^<manifest\b/, `<manifest ${TOOLS_NS}`),
5687
);
57-
result = result.replace(manifestTag[0], withTools);
5888
}
5989

60-
const applicationTag = /<application\b[^>]*?(\/?)>/.exec(result);
90+
const applicationTag = findTag(result, /<application\b[^>]*?\/?>/);
6191
if (!applicationTag) {
6292
const application = `\t<application ${CLEARTEXT_ATTRIBUTE}="true" tools:replace="${CLEARTEXT_ATTRIBUTE}" />`;
63-
const root = /<manifest\b[^>]*>/.exec(result)[0];
64-
if (root.endsWith("/>")) {
65-
result = result.replace(
93+
const root = findTag(result, /<manifest\b[^>]*>/);
94+
const closing = findTag(result, /<\/manifest>/);
95+
if (root.text.endsWith("/>")) {
96+
result = replaceTag(
97+
result,
6698
root,
67-
`${root.slice(0, -2).trimEnd()}>\n${application}\n</manifest>`,
99+
`${root.text.slice(0, -2).trimEnd()}>\n${application}\n</manifest>`,
68100
);
69-
} else if (/<\/manifest>/.test(result)) {
70-
result = result.replace(/<\/manifest>/, `${application}\n</manifest>`);
101+
} else if (closing) {
102+
result = replaceTag(result, closing, `${application}\n</manifest>`);
71103
} else {
72104
// Without the marker, the next prepare tries again.
73105
return manifest;
74106
}
75107
} else {
76-
let tag = applicationTag[0];
108+
let tag = applicationTag.text;
77109
const value = /android:usesCleartextTraffic\s*=\s*(?:"[^"]*"|'[^']*')/;
78110
tag = value.test(tag)
79111
? tag.replace(value, `${CLEARTEXT_ATTRIBUTE}="true"`)
80112
: tag.replace(
81113
/^<application\b/,
82114
`<application ${CLEARTEXT_ATTRIBUTE}="true"`,
83115
);
84-
const replace = /tools:replace\s*=\s*(["'])(.*?)\1/.exec(tag);
116+
const replace = /tools:replace\s*=\s*(["'])([\s\S]*?)\1/.exec(tag);
85117
if (!replace) {
86118
tag = tag.replace(
87119
/^<application\b/,
@@ -96,14 +128,16 @@ export function withDevCleartext(manifest: string): string {
96128
const [, quote, names] = replace;
97129
tag = tag.replace(
98130
replace[0],
99-
`tools:replace=${quote}${names},${CLEARTEXT_ATTRIBUTE}${quote}`,
131+
`tools:replace=${quote}${names.trimEnd()},${CLEARTEXT_ATTRIBUTE}${quote}`,
100132
);
101133
}
102-
result = result.replace(applicationTag[0], tag);
134+
result = replaceTag(result, applicationTag, tag);
103135
}
104136

105-
return result.replace(
106-
/(<manifest\b)/,
107-
`<!-- ${DEV_CLEARTEXT_MARKER} -->\n$1`,
137+
const root = findTag(result, /<manifest\b/);
138+
return replaceTag(
139+
result,
140+
root,
141+
`<!-- ${DEV_CLEARTEXT_MARKER} -->\n<manifest`,
108142
);
109143
}

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

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ import { GradleCommandService } from "../../lib/services/android/gradle-command-
1515
import { GradleBuildService } from "../../lib/services/android/gradle-build-service";
1616
import { GradleBuildArgsService } from "../../lib/services/android/gradle-build-args-service";
1717
import { IBuildConfig, IProjectData } from "../../lib/definitions/project";
18+
import { DEV_CLEARTEXT_MARKER } from "../../lib/services/android/dev-cleartext-manifest";
19+
import { IPlatformData } from "../../lib/definitions/platform";
20+
import { IProjectChangesInfo } from "../../lib/definitions/project-changes";
1821
import {
1922
IAndroidToolsInfo,
2023
IAndroidToolsInfoData,
@@ -420,6 +423,149 @@ describe("androidProjectService", () => {
420423
});
421424
});
422425

426+
describe("androidProjectService dev server cleartext", () => {
427+
const projectRoot = path.join("project", "platforms", "android");
428+
const debugManifest = path.join(
429+
projectRoot,
430+
"app",
431+
"src",
432+
"debug",
433+
"AndroidManifest.xml",
434+
);
435+
const appOwnManifest =
436+
'<manifest xmlns:android="http://schemas.android.com/apk/res/android">\n\t<application android:label="own"/>\n</manifest>\n';
437+
const viteHmrDebug = { hmr: true, release: false };
438+
439+
let injector: IInjector;
440+
let service: AndroidProjectService;
441+
let projectData: IProjectData;
442+
let options: { hostProjectModuleName: string; hostProjectPath?: string };
443+
let files: IDictionary<string>;
444+
let writes: string[];
445+
let deletes: string[];
446+
447+
beforeEach(() => {
448+
injector = createTestInjector();
449+
options = injector.resolve("options");
450+
options.hostProjectPath = undefined;
451+
files = {};
452+
writes = [];
453+
deletes = [];
454+
const fs = injector.resolve<IFileSystem>("fs");
455+
fs.exists = (p: string) => p in files;
456+
fs.readText = (p: string) => files[p];
457+
fs.writeFile = (p: string, content: string) => {
458+
files[p] = content;
459+
writes.push(p);
460+
};
461+
fs.deleteFile = (p: string) => {
462+
delete files[p];
463+
deletes.push(p);
464+
};
465+
service = injector.resolve("androidProjectService");
466+
sinon
467+
.stub(service, "getPlatformData")
468+
.returns(<IPlatformData>{ projectRoot });
469+
projectData = injector.resolve("projectData");
470+
projectData.bundler = "vite";
471+
});
472+
473+
const prepare = (prepareData: { hmr?: boolean; release?: boolean }) =>
474+
service.prepareDevServerAccess(projectData, <IPrepareData>prepareData);
475+
476+
const changesFor = async (prepareData: {
477+
hmr?: boolean;
478+
release?: boolean;
479+
}) => {
480+
const changes = <IProjectChangesInfo>{ appResourcesChanged: false };
481+
await service.checkForChanges(
482+
changes,
483+
<IPrepareData>prepareData,
484+
projectData,
485+
);
486+
return changes.appResourcesChanged;
487+
};
488+
489+
describe("prepareDevServerAccess", () => {
490+
it("writes a marked debug manifest for a Vite debug HMR run without one", () => {
491+
prepare(viteHmrDebug);
492+
assert.deepEqual(writes, [debugManifest]);
493+
assert.include(files[debugManifest], DEV_CLEARTEXT_MARKER);
494+
assert.include(
495+
files[debugManifest],
496+
'android:usesCleartextTraffic="true"',
497+
);
498+
});
499+
500+
it("adds the permission to the app's own debug manifest and keeps its content", () => {
501+
files[debugManifest] = appOwnManifest;
502+
prepare(viteHmrDebug);
503+
assert.include(files[debugManifest], DEV_CLEARTEXT_MARKER);
504+
assert.include(files[debugManifest], 'android:label="own"');
505+
});
506+
507+
it("leaves a manifest it already marked alone", () => {
508+
prepare(viteHmrDebug);
509+
writes = [];
510+
prepare(viteHmrDebug);
511+
assert.deepEqual(writes, []);
512+
});
513+
514+
for (const [name, prepareData] of [
515+
["a release build", { hmr: true, release: true }],
516+
["a run without HMR", { hmr: false, release: false }],
517+
] as const) {
518+
it(`removes the marked manifest for ${name}`, () => {
519+
prepare(viteHmrDebug);
520+
prepare(prepareData);
521+
assert.deepEqual(deletes, [debugManifest]);
522+
assert.notProperty(files, debugManifest);
523+
});
524+
525+
it(`never touches the app's own manifest for ${name}`, () => {
526+
files[debugManifest] = appOwnManifest;
527+
prepare(prepareData);
528+
assert.deepEqual(writes, []);
529+
assert.deepEqual(deletes, []);
530+
assert.equal(files[debugManifest], appOwnManifest);
531+
});
532+
}
533+
534+
it("does nothing for a webpack project", () => {
535+
projectData.bundler = "webpack";
536+
prepare(viteHmrDebug);
537+
assert.deepEqual(writes, []);
538+
assert.deepEqual(deletes, []);
539+
});
540+
});
541+
542+
describe("checkForChanges", () => {
543+
it("asks for a rebuild when the permission is needed but missing", async () => {
544+
assert.isTrue(await changesFor(viteHmrDebug));
545+
});
546+
547+
it("asks for a rebuild when the CLI's permission must go", async () => {
548+
prepare(viteHmrDebug);
549+
assert.isTrue(await changesFor({ hmr: true, release: true }));
550+
});
551+
552+
it("asks for nothing when the manifest already matches", async () => {
553+
prepare(viteHmrDebug);
554+
assert.isFalse(await changesFor(viteHmrDebug));
555+
});
556+
557+
it("asks for nothing on a release build with only the app's own manifest", async () => {
558+
files[debugManifest] = appOwnManifest;
559+
assert.isFalse(await changesFor({ hmr: true, release: true }));
560+
});
561+
562+
it("skips host projects, whose native prepare writes no manifest", async () => {
563+
options.hostProjectPath = "host";
564+
assert.isFalse(await changesFor(viteHmrDebug));
565+
});
566+
});
567+
});
568+
423569
describe("androidProjectService plugin aar names", () => {
424570
let fs: IFileSystem;
425571
let service: AndroidProjectService;

‎test/services/android/dev-cleartext-manifest.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,5 +126,51 @@ describe("dev-cleartext-manifest", () => {
126126
"tools:replace='android:label,android:usesCleartextTraffic'",
127127
);
128128
});
129+
130+
it("extends a tools:replace that spans several lines instead of adding another", () => {
131+
const result = withDevCleartext(
132+
[
133+
'<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">',
134+
"\t<application",
135+
'\t\ttools:replace="android:label,',
136+
'\t\t\tandroid:icon"',
137+
'\t\tandroid:label="x">',
138+
"\t</application>",
139+
"</manifest>",
140+
].join("\n"),
141+
);
142+
assert.equal(result.match(/tools:replace=/g).length, 1);
143+
assert.include(
144+
result,
145+
'tools:replace="android:label,\n\t\t\tandroid:icon,android:usesCleartextTraffic"',
146+
);
147+
assert.include(result, 'android:usesCleartextTraffic="true"');
148+
});
149+
150+
it("edits the real elements, not commented-out ones before them", () => {
151+
const commentedApplication =
152+
'<!-- <application android:usesCleartextTraffic="false"> -->';
153+
const result = withDevCleartext(
154+
[
155+
'<?xml version="1.0" encoding="utf-8"?>',
156+
'<!-- <manifest package="old"> -->',
157+
'<manifest xmlns:android="http://schemas.android.com/apk/res/android">',
158+
`\t${commentedApplication}`,
159+
'\t<application android:label="x">',
160+
"\t</application>",
161+
"</manifest>",
162+
].join("\n"),
163+
);
164+
assert.include(result, commentedApplication);
165+
assert.include(result, '<!-- <manifest package="old"> -->');
166+
assert.match(
167+
result,
168+
/<application tools:replace="android:usesCleartextTraffic" android:usesCleartextTraffic="true" android:label="x">/,
169+
);
170+
assert.include(
171+
result,
172+
`<!-- ${DEV_CLEARTEXT_MARKER} -->\n<manifest xmlns:tools=`,
173+
);
174+
});
129175
});
130176
});

0 commit comments

Comments
 (0)