codeplay-common 4.11.37 → 4.11.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -1
- package/files/buildCodeplay/codeplayBeforeBuild.js +2 -2
- package/files/buildCodeplay/ensure-current-build.cjs +70 -42
- package/files/scripts-common/collect-startup-profile.js +134 -0
- package/files/scripts-common/generate-baseline-profile.js +218 -46
- package/files/take-screen-image.js +103 -64
- package/package.json +1 -1
- package/scripts/baseline-profile.test.cjs +189 -0
- package/scripts/ensure-current-build.test.cjs +176 -76
|
@@ -467,7 +467,7 @@ function getNextNumberedFileName(selectedProfiles) {
|
|
|
467
467
|
const highestInDirectory = fs.readdirSync(directory, { withFileTypes: true })
|
|
468
468
|
.filter((entry) => entry.isFile())
|
|
469
469
|
.reduce((highest, entry) => {
|
|
470
|
-
const match = entry.name.match(
|
|
470
|
+
const match = entry.name.match(/^(\d+)\.(?:png|jpe?g)$/i);
|
|
471
471
|
return match ? Math.max(highest, Number(match[1])) : highest;
|
|
472
472
|
}, 0);
|
|
473
473
|
|
|
@@ -479,13 +479,14 @@ function getNextNumberedFileName(selectedProfiles) {
|
|
|
479
479
|
|
|
480
480
|
function getUniqueFileName(prefix, selectedProfiles) {
|
|
481
481
|
const extension = selectedProfiles[0]?.outputExtension || 'png';
|
|
482
|
-
const outputDirectories = getSelectedOutputDirectories(selectedProfiles);
|
|
483
482
|
let fileName = `${prefix}.${extension}`;
|
|
484
483
|
let duplicateNumber = 2;
|
|
485
484
|
|
|
486
|
-
while (
|
|
487
|
-
|
|
488
|
-
|
|
485
|
+
while (selectedProfiles.some((profile) => {
|
|
486
|
+
const profileFileName = getProfileScreenshotFileName(fileName, profile);
|
|
487
|
+
return fs.existsSync(path.join(screenshotDirectory, profile.outputDirectory, profileFileName))
|
|
488
|
+
|| (!profile.screenshotOnly && fs.existsSync(path.join(inFrameDirectory, profile.outputDirectory, profileFileName)));
|
|
489
|
+
})) {
|
|
489
490
|
fileName = `${prefix}-${duplicateNumber}.${extension}`;
|
|
490
491
|
duplicateNumber += 1;
|
|
491
492
|
}
|
|
@@ -493,6 +494,10 @@ function getUniqueFileName(prefix, selectedProfiles) {
|
|
|
493
494
|
return fileName;
|
|
494
495
|
}
|
|
495
496
|
|
|
497
|
+
function getProfileScreenshotFileName(fileName, profile) {
|
|
498
|
+
return `${path.parse(fileName).name}.${profile.outputExtension || path.extname(fileName).slice(1)}`;
|
|
499
|
+
}
|
|
500
|
+
|
|
496
501
|
function getScreenshotFileName(fileNameInput, selectedProfiles) {
|
|
497
502
|
const inputWithoutExtension = fileNameInput.trim().replace(/\.(png|jpe?g)$/i, '');
|
|
498
503
|
|
|
@@ -893,16 +898,17 @@ function selectProfiles(input) {
|
|
|
893
898
|
}
|
|
894
899
|
|
|
895
900
|
class CdpClient {
|
|
896
|
-
constructor(webSocketUrl) {
|
|
901
|
+
constructor(webSocketUrl, label = 'app WebView') {
|
|
897
902
|
this.nextId = 1;
|
|
898
903
|
this.pendingCommands = new Map();
|
|
904
|
+
this.label = label;
|
|
899
905
|
this.socket = new WebSocket(webSocketUrl);
|
|
900
906
|
}
|
|
901
907
|
|
|
902
908
|
connect() {
|
|
903
909
|
return new Promise((resolve, reject) => {
|
|
904
910
|
const timeout = setTimeout(() => {
|
|
905
|
-
reject(new Error(
|
|
911
|
+
reject(new Error(`Timed out while connecting to the ${this.label}.`));
|
|
906
912
|
}, 10000);
|
|
907
913
|
|
|
908
914
|
this.socket.addEventListener('open', () => {
|
|
@@ -912,7 +918,7 @@ class CdpClient {
|
|
|
912
918
|
|
|
913
919
|
this.socket.addEventListener('error', () => {
|
|
914
920
|
clearTimeout(timeout);
|
|
915
|
-
reject(new Error(
|
|
921
|
+
reject(new Error(`Could not connect to the ${this.label} debugging socket.`));
|
|
916
922
|
}, { once: true });
|
|
917
923
|
|
|
918
924
|
this.socket.addEventListener('message', (event) => {
|
|
@@ -924,6 +930,7 @@ class CdpClient {
|
|
|
924
930
|
|
|
925
931
|
const pendingCommand = this.pendingCommands.get(message.id);
|
|
926
932
|
this.pendingCommands.delete(message.id);
|
|
933
|
+
clearTimeout(pendingCommand.timeout);
|
|
927
934
|
|
|
928
935
|
if (message.error) {
|
|
929
936
|
pendingCommand.reject(new Error(message.error.message));
|
|
@@ -934,7 +941,8 @@ class CdpClient {
|
|
|
934
941
|
|
|
935
942
|
this.socket.addEventListener('close', () => {
|
|
936
943
|
for (const pendingCommand of this.pendingCommands.values()) {
|
|
937
|
-
pendingCommand.
|
|
944
|
+
clearTimeout(pendingCommand.timeout);
|
|
945
|
+
pendingCommand.reject(new Error(`The ${this.label} debugging connection closed.`));
|
|
938
946
|
}
|
|
939
947
|
|
|
940
948
|
this.pendingCommands.clear();
|
|
@@ -943,11 +951,24 @@ class CdpClient {
|
|
|
943
951
|
}
|
|
944
952
|
|
|
945
953
|
send(method, params = {}) {
|
|
954
|
+
if (this.socket.readyState !== WebSocket.OPEN) {
|
|
955
|
+
return Promise.reject(new Error(`The ${this.label} debugging connection is closed.`));
|
|
956
|
+
}
|
|
946
957
|
return new Promise((resolve, reject) => {
|
|
947
958
|
const id = this.nextId;
|
|
948
959
|
this.nextId += 1;
|
|
949
|
-
|
|
950
|
-
|
|
960
|
+
const timeout = setTimeout(() => {
|
|
961
|
+
this.pendingCommands.delete(id);
|
|
962
|
+
reject(new Error(`${method} timed out in the ${this.label}.`));
|
|
963
|
+
}, 60000);
|
|
964
|
+
this.pendingCommands.set(id, { resolve, reject, timeout });
|
|
965
|
+
try {
|
|
966
|
+
this.socket.send(JSON.stringify({ id, method, params }));
|
|
967
|
+
} catch (error) {
|
|
968
|
+
clearTimeout(timeout);
|
|
969
|
+
this.pendingCommands.delete(id);
|
|
970
|
+
reject(error);
|
|
971
|
+
}
|
|
951
972
|
});
|
|
952
973
|
}
|
|
953
974
|
|
|
@@ -1027,10 +1048,12 @@ async function capturePageSnapshot(client) {
|
|
|
1027
1048
|
|
|
1028
1049
|
if (!width || !height) return '';
|
|
1029
1050
|
|
|
1051
|
+
const renderedSize = Math.max(element.clientWidth, element.clientHeight) || 800;
|
|
1052
|
+
const scale = Math.min(1, 2400 / Math.max(width, height), renderedSize * 3 / Math.max(width, height));
|
|
1030
1053
|
const canvas = document.createElement('canvas');
|
|
1031
|
-
canvas.width = width;
|
|
1032
|
-
canvas.height = height;
|
|
1033
|
-
canvas.getContext('2d').drawImage(element, 0, 0, width, height);
|
|
1054
|
+
canvas.width = Math.max(1, Math.round(width * scale));
|
|
1055
|
+
canvas.height = Math.max(1, Math.round(height * scale));
|
|
1056
|
+
canvas.getContext('2d').drawImage(element, 0, 0, canvas.width, canvas.height);
|
|
1034
1057
|
return canvas.toDataURL('image/png');
|
|
1035
1058
|
};
|
|
1036
1059
|
|
|
@@ -1389,6 +1412,9 @@ async function capturePageSnapshot(client) {
|
|
|
1389
1412
|
} catch {
|
|
1390
1413
|
clone.setAttribute('poster', original.poster || '');
|
|
1391
1414
|
}
|
|
1415
|
+
} else if (tagName === 'img' && (!original.clientWidth || !original.clientHeight)) {
|
|
1416
|
+
clone.removeAttribute('src');
|
|
1417
|
+
clone.removeAttribute('srcset');
|
|
1392
1418
|
} else if (tagName === 'img' && original.complete) {
|
|
1393
1419
|
try {
|
|
1394
1420
|
clone.setAttribute('src', imageToDataUrl(original) || original.currentSrc || original.src);
|
|
@@ -1570,7 +1596,7 @@ async function launchReplayBrowser() {
|
|
|
1570
1596
|
const [port] = fs.readFileSync(activePortPath, 'utf8').trim().split(/\r?\n/);
|
|
1571
1597
|
const versionResponse = await fetch(`http://127.0.0.1:${port}/json/version`);
|
|
1572
1598
|
const version = await versionResponse.json();
|
|
1573
|
-
const client = new CdpClient(version.webSocketDebuggerUrl);
|
|
1599
|
+
const client = new CdpClient(version.webSocketDebuggerUrl, 'local screenshot browser');
|
|
1574
1600
|
await client.connect();
|
|
1575
1601
|
|
|
1576
1602
|
return {
|
|
@@ -1593,7 +1619,7 @@ async function createReplayPage(browser) {
|
|
|
1593
1619
|
const target = targets.find((candidate) => candidate.id === createdTarget.targetId);
|
|
1594
1620
|
|
|
1595
1621
|
if (target && target.webSocketDebuggerUrl) {
|
|
1596
|
-
const client = new CdpClient(target.webSocketDebuggerUrl);
|
|
1622
|
+
const client = new CdpClient(target.webSocketDebuggerUrl, 'local screenshot page');
|
|
1597
1623
|
await client.connect();
|
|
1598
1624
|
await client.send('Page.enable');
|
|
1599
1625
|
await client.send('Runtime.enable');
|
|
@@ -3672,7 +3698,8 @@ async function captureProfile(client, snapshot, profile, screenshotFileName) {
|
|
|
3672
3698
|
});
|
|
3673
3699
|
|
|
3674
3700
|
const profileDirectory = path.join(screenshotDirectory, profile.outputDirectory);
|
|
3675
|
-
const
|
|
3701
|
+
const profileFileName = getProfileScreenshotFileName(screenshotFileName, profile);
|
|
3702
|
+
const screenshotPath = path.join(profileDirectory, profileFileName);
|
|
3676
3703
|
const screenshotBuffer = Buffer.from(screenshot.data, 'base64');
|
|
3677
3704
|
validateStoreImage(
|
|
3678
3705
|
profile,
|
|
@@ -3689,7 +3716,7 @@ async function captureProfile(client, snapshot, profile, screenshotFileName) {
|
|
|
3689
3716
|
client,
|
|
3690
3717
|
screenshotBuffer,
|
|
3691
3718
|
profile,
|
|
3692
|
-
|
|
3719
|
+
profileFileName,
|
|
3693
3720
|
);
|
|
3694
3721
|
}
|
|
3695
3722
|
|
|
@@ -3702,10 +3729,16 @@ async function captureScreenshotSet(
|
|
|
3702
3729
|
console.log('Capturing the current rendered page and resolved native data...');
|
|
3703
3730
|
const snapshot = await capturePageSnapshot(deviceClient);
|
|
3704
3731
|
const screenshotFileName = getScreenshotFileName(fileNameInput, selectedProfiles);
|
|
3705
|
-
|
|
3732
|
+
let completedProfiles = 0;
|
|
3706
3733
|
|
|
3707
|
-
|
|
3708
|
-
|
|
3734
|
+
try {
|
|
3735
|
+
for (const profile of selectedProfiles) {
|
|
3736
|
+
console.log(`Capturing ${profile.label} (${completedProfiles + 1}/${selectedProfiles.length})...`);
|
|
3737
|
+
await captureProfile(replayClient, snapshot, profile, screenshotFileName);
|
|
3738
|
+
completedProfiles += 1;
|
|
3739
|
+
}
|
|
3740
|
+
} finally {
|
|
3741
|
+
if (completedProfiles) saveScreenshotInfo(screenshotFileName, snapshot.screenInfo);
|
|
3709
3742
|
}
|
|
3710
3743
|
|
|
3711
3744
|
console.log(`Responsive screenshot set completed: ${screenshotFileName}`);
|
|
@@ -3941,9 +3974,7 @@ async function createOppoAssetsFromExistingScreenshots() {
|
|
|
3941
3974
|
}
|
|
3942
3975
|
|
|
3943
3976
|
async function runInteractiveCaptureLoop(
|
|
3944
|
-
|
|
3945
|
-
replayClient,
|
|
3946
|
-
selectedProfiles,
|
|
3977
|
+
capture,
|
|
3947
3978
|
) {
|
|
3948
3979
|
const terminal = readline.createInterface({
|
|
3949
3980
|
input: process.stdin,
|
|
@@ -3959,12 +3990,7 @@ async function runInteractiveCaptureLoop(
|
|
|
3959
3990
|
|
|
3960
3991
|
for await (const fileNameInput of terminal) {
|
|
3961
3992
|
try {
|
|
3962
|
-
await
|
|
3963
|
-
deviceClient,
|
|
3964
|
-
replayClient,
|
|
3965
|
-
selectedProfiles,
|
|
3966
|
-
fileNameInput,
|
|
3967
|
-
);
|
|
3993
|
+
await capture(fileNameInput);
|
|
3968
3994
|
} catch (error) {
|
|
3969
3995
|
console.error(`Responsive screenshot failed: ${error.message}`);
|
|
3970
3996
|
}
|
|
@@ -4314,25 +4340,47 @@ async function main() {
|
|
|
4314
4340
|
const interactiveMode = process.stdin.isTTY && !options.prefix && !options.dryRun;
|
|
4315
4341
|
const deviceId = getConnectedDevice();
|
|
4316
4342
|
const appId = getAppId();
|
|
4317
|
-
|
|
4318
|
-
const localPort = runAdb([
|
|
4319
|
-
'-s',
|
|
4320
|
-
deviceId,
|
|
4321
|
-
'forward',
|
|
4322
|
-
'tcp:0',
|
|
4323
|
-
`localabstract:${socketName}`,
|
|
4324
|
-
]);
|
|
4325
|
-
|
|
4343
|
+
let localPort;
|
|
4326
4344
|
let deviceClient;
|
|
4327
4345
|
let replayBrowser;
|
|
4328
4346
|
let replayClient;
|
|
4329
4347
|
|
|
4330
|
-
|
|
4348
|
+
async function closeCaptureSession() {
|
|
4349
|
+
if (replayClient) {
|
|
4350
|
+
replayClient.close();
|
|
4351
|
+
replayClient = undefined;
|
|
4352
|
+
}
|
|
4353
|
+
if (replayBrowser) {
|
|
4354
|
+
const browser = replayBrowser;
|
|
4355
|
+
replayBrowser = undefined;
|
|
4356
|
+
await closeReplayBrowser(browser);
|
|
4357
|
+
}
|
|
4358
|
+
if (deviceClient) {
|
|
4359
|
+
deviceClient.close();
|
|
4360
|
+
deviceClient = undefined;
|
|
4361
|
+
}
|
|
4362
|
+
if (localPort) {
|
|
4363
|
+
try {
|
|
4364
|
+
runAdb(['-s', deviceId, 'forward', '--remove', `tcp:${localPort}`]);
|
|
4365
|
+
} catch {
|
|
4366
|
+
// ADB may already have removed the temporary forwarding rule.
|
|
4367
|
+
}
|
|
4368
|
+
localPort = undefined;
|
|
4369
|
+
}
|
|
4370
|
+
}
|
|
4371
|
+
|
|
4372
|
+
async function openCaptureSession() {
|
|
4373
|
+
const socketName = getWebViewSocket(deviceId, appId);
|
|
4374
|
+
localPort = runAdb(['-s', deviceId, 'forward', 'tcp:0', `localabstract:${socketName}`]);
|
|
4331
4375
|
const target = await getWebViewTarget(localPort);
|
|
4332
4376
|
deviceClient = new CdpClient(target.webSocketDebuggerUrl);
|
|
4333
4377
|
await deviceClient.connect();
|
|
4334
4378
|
await deviceClient.send('Page.enable');
|
|
4335
4379
|
await deviceClient.send('Runtime.enable');
|
|
4380
|
+
}
|
|
4381
|
+
|
|
4382
|
+
try {
|
|
4383
|
+
await openCaptureSession();
|
|
4336
4384
|
|
|
4337
4385
|
const pageDetails = await getPageDetails(deviceClient);
|
|
4338
4386
|
console.log(`Connected device: ${deviceId}`);
|
|
@@ -4372,11 +4420,20 @@ async function main() {
|
|
|
4372
4420
|
);
|
|
4373
4421
|
|
|
4374
4422
|
if (interactiveMode) {
|
|
4375
|
-
await runInteractiveCaptureLoop(
|
|
4376
|
-
|
|
4377
|
-
|
|
4378
|
-
|
|
4379
|
-
|
|
4423
|
+
await runInteractiveCaptureLoop(async (fileNameInput) => {
|
|
4424
|
+
try {
|
|
4425
|
+
if (!deviceClient || deviceClient.socket.readyState !== WebSocket.OPEN
|
|
4426
|
+
|| !replayClient || replayClient.socket.readyState !== WebSocket.OPEN) {
|
|
4427
|
+
await closeCaptureSession();
|
|
4428
|
+
await openCaptureSession();
|
|
4429
|
+
replayBrowser = await launchReplayBrowser();
|
|
4430
|
+
replayClient = await createReplayPage(replayBrowser);
|
|
4431
|
+
}
|
|
4432
|
+
await captureScreenshotSet(deviceClient, replayClient, selectedProfiles, fileNameInput);
|
|
4433
|
+
} finally {
|
|
4434
|
+
await closeCaptureSession();
|
|
4435
|
+
}
|
|
4436
|
+
});
|
|
4380
4437
|
} else {
|
|
4381
4438
|
await captureScreenshotSet(
|
|
4382
4439
|
deviceClient,
|
|
@@ -4386,25 +4443,7 @@ async function main() {
|
|
|
4386
4443
|
);
|
|
4387
4444
|
}
|
|
4388
4445
|
} finally {
|
|
4389
|
-
|
|
4390
|
-
replayClient.close();
|
|
4391
|
-
}
|
|
4392
|
-
|
|
4393
|
-
if (replayBrowser) {
|
|
4394
|
-
await closeReplayBrowser(replayBrowser);
|
|
4395
|
-
}
|
|
4396
|
-
|
|
4397
|
-
if (deviceClient) {
|
|
4398
|
-
deviceClient.close();
|
|
4399
|
-
}
|
|
4400
|
-
|
|
4401
|
-
if (localPort) {
|
|
4402
|
-
try {
|
|
4403
|
-
runAdb(['-s', deviceId, 'forward', '--remove', `tcp:${localPort}`]);
|
|
4404
|
-
} catch {
|
|
4405
|
-
// ADB may already have removed the temporary forwarding rule.
|
|
4406
|
-
}
|
|
4407
|
-
}
|
|
4446
|
+
await closeCaptureSession();
|
|
4408
4447
|
}
|
|
4409
4448
|
}
|
|
4410
4449
|
|
package/package.json
CHANGED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
const { test } = require('node:test');
|
|
2
|
+
const assert = require('node:assert/strict');
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const vm = require('node:vm');
|
|
6
|
+
const { EventEmitter } = require('node:events');
|
|
7
|
+
const { install } = require('./sync-files.js');
|
|
8
|
+
|
|
9
|
+
const templateDir = path.resolve(__dirname, '../files/scripts-common');
|
|
10
|
+
const generator = fs.readFileSync(path.join(templateDir, 'generate-baseline-profile.js'), 'utf8');
|
|
11
|
+
const collector = fs.readFileSync(path.join(templateDir, 'collect-startup-profile.js'), 'utf8');
|
|
12
|
+
const appId = 'org.example.notes';
|
|
13
|
+
|
|
14
|
+
function fixture(t) {
|
|
15
|
+
const base = path.resolve(__dirname, '../agent-temp/baseline-profile-tests');
|
|
16
|
+
fs.mkdirSync(base, { recursive: true });
|
|
17
|
+
const root = fs.mkdtempSync(path.join(base, 'case-'));
|
|
18
|
+
t.after(() => {
|
|
19
|
+
assert.ok(path.resolve(root).startsWith(base + path.sep));
|
|
20
|
+
fs.rmSync(root, { recursive: true, force: true });
|
|
21
|
+
});
|
|
22
|
+
const write = (name, content) => {
|
|
23
|
+
const file = path.join(root, name);
|
|
24
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
25
|
+
fs.writeFileSync(file, typeof content === 'string' ? content : JSON.stringify(content));
|
|
26
|
+
};
|
|
27
|
+
const nativeConfig = 'android/app/src/main/assets/capacitor.config.json';
|
|
28
|
+
write('package.json', { name: 'baseline-consumer', scripts: {}, dependencies: {} });
|
|
29
|
+
write('capacitor.config.json', { appId, plugins: {}, appOwned: 'preserve' });
|
|
30
|
+
write(nativeConfig, `{"appId":"${appId}","server":{"url":"http://192.0.2.1:5173","hostname":"localhost"}}\r\n`);
|
|
31
|
+
write('android/app/src/main/assets/public/index.html', '<script src="./assets/app.js"></script>');
|
|
32
|
+
return { root, write, nativeConfig, read: name => fs.readFileSync(path.join(root, name), 'utf8') };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
test('package updates distribute both scripts and preserve per-app config, commands and profiles', t => {
|
|
36
|
+
const f = fixture(t);
|
|
37
|
+
f.write('package.json', { name: 'consumer', scripts: { 'baseline-profile:generate': 'cd android && gradlew.bat :app:generateBaselineProfile --console=plain' } });
|
|
38
|
+
f.write('scripts-common/generate-baseline-profile.js', '// previous generator');
|
|
39
|
+
f.write('baselineProfiles/baseline-prof.txt', 'Lorg/example/notes/Existing;\n');
|
|
40
|
+
const originalNative = f.read(f.nativeConfig);
|
|
41
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
42
|
+
install({ projectRoot: f.root });
|
|
43
|
+
assert.equal(f.read('scripts-common/generate-baseline-profile.js'), generator);
|
|
44
|
+
assert.equal(f.read('scripts-common/collect-startup-profile.js'), collector);
|
|
45
|
+
assert.equal(f.read('scripts-common/setup-baseline-profile.js'), fs.readFileSync(path.join(templateDir, 'setup-baseline-profile.js'), 'utf8'));
|
|
46
|
+
assert.equal(f.read(f.nativeConfig), originalNative);
|
|
47
|
+
assert.equal(JSON.parse(f.read('capacitor.config.json')).appId, appId);
|
|
48
|
+
assert.equal(JSON.parse(f.read('capacitor.config.json')).appOwned, 'preserve');
|
|
49
|
+
assert.equal(f.read('baselineProfiles/baseline-prof.txt'), 'Lorg/example/notes/Existing;\n');
|
|
50
|
+
assert.equal(JSON.parse(f.read('package.json')).scripts['baseline-profile:generate'], 'node scripts-common/generate-baseline-profile.js');
|
|
51
|
+
}
|
|
52
|
+
f.write('package.json', { name: 'consumer', scripts: { 'baseline-profile:generate': 'node custom-profile.cjs' } });
|
|
53
|
+
install({ projectRoot: f.root });
|
|
54
|
+
assert.equal(JSON.parse(f.read('package.json')).scripts['baseline-profile:generate'], 'node custom-profile.cjs');
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
async function runGenerator(f, mode) {
|
|
58
|
+
const state = { collected: 0, synced: [], tasks: [] };
|
|
59
|
+
const proc = { env: {}, argv: ['node', 'generator', ...(mode === 'host' ? ['--host'] : [])], platform: 'win32' };
|
|
60
|
+
const code = generator.slice(0, generator.lastIndexOf('main().catch'));
|
|
61
|
+
const context = {
|
|
62
|
+
__dirname: path.join(f.root, 'scripts-common'), Buffer, process: proc,
|
|
63
|
+
console: { log() {}, error() {} }, setTimeout, clearTimeout, setInterval, clearInterval,
|
|
64
|
+
executeGradle: async args => {
|
|
65
|
+
state.tasks.push(args);
|
|
66
|
+
if (mode === 'frozen' || mode === 'failed') {
|
|
67
|
+
const error = new Error('simulated Gradle failure');
|
|
68
|
+
error.code = mode === 'frozen' ? 'BASELINE_TEST_FROZEN' : 'OTHER_FAILURE';
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
return 0;
|
|
72
|
+
},
|
|
73
|
+
require: id => {
|
|
74
|
+
if (id === 'child_process') return { ...require(id), execFileSync: () => 'List of devices attached\nSERIAL\tdevice\n' };
|
|
75
|
+
if (id === './setup-baseline-profile.js') return { syncGeneratedProfileBackup: options => state.synced.push(options?.backupOnly ?? false) };
|
|
76
|
+
if (id === './collect-startup-profile.js') return { collectStartupProfile: async options => {
|
|
77
|
+
state.collected += 1;
|
|
78
|
+
assert.equal(options.appId, appId);
|
|
79
|
+
assert.equal(options.serial, 'SERIAL');
|
|
80
|
+
assert.ok(options.deadline > Date.now());
|
|
81
|
+
const config = JSON.parse(f.read(f.nativeConfig));
|
|
82
|
+
assert.equal(config.server.url, undefined);
|
|
83
|
+
assert.equal(config.server.hostname, 'localhost');
|
|
84
|
+
} };
|
|
85
|
+
return require(id);
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
const promise = vm.runInNewContext(code + '\nrunGradle = executeGradle; main();', context);
|
|
89
|
+
if (mode === 'failed') await assert.rejects(promise, /simulated Gradle failure/);
|
|
90
|
+
else await promise;
|
|
91
|
+
return state;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
for (const mode of ['normal', 'frozen', 'host', 'failed']) {
|
|
95
|
+
test(`${mode} generation preserves config and selects the correct collection path`, async t => {
|
|
96
|
+
const f = fixture(t);
|
|
97
|
+
const original = f.read(f.nativeConfig);
|
|
98
|
+
const result = await runGenerator(f, mode);
|
|
99
|
+
assert.equal(f.read(f.nativeConfig), original);
|
|
100
|
+
assert.equal(fs.existsSync(path.join(f.root, 'agent-temp/baseline-profile/capacitor.config.original.json')), false);
|
|
101
|
+
assert.equal(result.collected, mode === 'frozen' || mode === 'host' ? 1 : 0);
|
|
102
|
+
assert.deepEqual(result.synced, mode === 'failed' ? [] : [mode === 'normal']);
|
|
103
|
+
assert.equal(result.tasks[0][0], mode === 'host' ? ':app:assembleNonMinifiedRelease' : ':app:generateBaselineProfile');
|
|
104
|
+
assert.ok(result.tasks[0].includes('--no-daemon'));
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function loadCollector(f, options = {}) {
|
|
109
|
+
const commands = [];
|
|
110
|
+
const proc = new EventEmitter();
|
|
111
|
+
let launches = 0;
|
|
112
|
+
const goodProfile = `SPLorg/example/notes/Launcher;->onCreate(Landroid/os/Bundle;)V\nLcom/getcapacitor/Bridge;\n`;
|
|
113
|
+
const execute = async (_command, args, settings = {}) => {
|
|
114
|
+
if (settings.signal?.aborted) throw settings.signal.reason;
|
|
115
|
+
commands.push(args);
|
|
116
|
+
const command = args.slice(2).join(' ');
|
|
117
|
+
let stdout = '';
|
|
118
|
+
if (command.includes('ro.build.version.sdk')) stdout = String(options.sdk ?? 35);
|
|
119
|
+
else if (command.startsWith('install ')) stdout = 'Success';
|
|
120
|
+
else if (command.includes('resolve-activity')) stdout = `${appId}/.Launcher`;
|
|
121
|
+
else if (command.includes('WRITE_SKIP_FILE')) stdout = 'Broadcast completed: result=10';
|
|
122
|
+
else if (command.includes('DELETE_SKIP_FILE')) stdout = 'Broadcast completed: result=11';
|
|
123
|
+
else if (command.includes('clear-app-profiles')) stdout = 'Profiles cleared';
|
|
124
|
+
else if (command.includes('package compile')) stdout = 'Success';
|
|
125
|
+
else if (command.includes('am start')) { launches += 1; stdout = 'Status: ok'; }
|
|
126
|
+
else if (command.includes('SAVE_PROFILE')) stdout = `Broadcast completed: result=${options.saveFails ? 0 : 12}`;
|
|
127
|
+
else if (command.includes('screencap')) stdout = Buffer.from('diagnostic screenshot');
|
|
128
|
+
else if (command.includes('exec-out cat')) stdout = options.missingActivity ? 'Lcom/getcapacitor/Bridge;' :
|
|
129
|
+
goodProfile + (options.unstable ? `HLorg/example/notes/Changing;->iteration${launches}()V\n` : '');
|
|
130
|
+
return { stdout, stderr: '' };
|
|
131
|
+
};
|
|
132
|
+
const module = { exports: {} };
|
|
133
|
+
vm.runInNewContext(collector, {
|
|
134
|
+
module, Buffer, AbortController, process: proc, console: { log() {}, error() {} },
|
|
135
|
+
setTimeout: (callback, milliseconds) => { if (options.expired) { assert.equal(milliseconds, 0); callback(); } return 1; },
|
|
136
|
+
clearTimeout() {},
|
|
137
|
+
require: id => {
|
|
138
|
+
if (id === 'child_process') return {};
|
|
139
|
+
if (id === 'util') return { promisify: () => execute };
|
|
140
|
+
if (id === 'timers/promises') return { setTimeout: async () => { if (options.cancel) proc.emit('SIGINT'); } };
|
|
141
|
+
if (id === 'adm-zip') return class {
|
|
142
|
+
readAsText() { return JSON.stringify({ appId, server: options.liveUrl ? { url: 'http://192.0.2.1:5173' } : {} }); }
|
|
143
|
+
getEntry() { return true; }
|
|
144
|
+
};
|
|
145
|
+
return require(id);
|
|
146
|
+
},
|
|
147
|
+
});
|
|
148
|
+
return { ...module.exports, commands, proc, launches: () => launches };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
test('host collection saves stable app-specific profiles and cleans up profile installation', async t => {
|
|
152
|
+
const f = fixture(t);
|
|
153
|
+
const host = loadCollector(f);
|
|
154
|
+
await host.collectStartupProfile({ serial: 'SERIAL', appId, rootDir: f.root, apkPath: 'fixture.apk', timeoutMinutes: 20 });
|
|
155
|
+
assert.equal(host.launches(), 3);
|
|
156
|
+
assert.equal(f.read('baselineProfiles/baseline-prof.txt'), f.read('baselineProfiles/startup-prof.txt'));
|
|
157
|
+
assert.match(f.read('baselineProfiles/baseline-prof.txt'), /Lorg\/example\/notes\/Launcher;/);
|
|
158
|
+
assert.ok(host.commands.every(args => args[0] === '-s' && args[1] === 'SERIAL'));
|
|
159
|
+
assert.ok(host.commands.some(args => args.includes('DELETE_SKIP_FILE')));
|
|
160
|
+
assert.equal(host.proc.listenerCount('SIGINT'), 0);
|
|
161
|
+
assert.equal(host.proc.listenerCount('SIGTERM'), 0);
|
|
162
|
+
assert.equal(host.normalizeProfile('[Lbad/Array;\nHLbad/Cache;->call()V+inline\nLgood/A;\nLgood/A;'), 'Lgood/A;');
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
for (const [options, message] of [
|
|
166
|
+
[{ sdk: 33 }, /Android 14/],
|
|
167
|
+
[{ liveUrl: true }, /no server.url/],
|
|
168
|
+
[{ missingActivity: true }, /missing the app launch activity/],
|
|
169
|
+
[{ unstable: true }, /did not stabilize/],
|
|
170
|
+
[{ saveFails: true }, /did not return 12/],
|
|
171
|
+
[{ cancel: true }, /cancelled/],
|
|
172
|
+
[{ expired: true }, /exceeded 20 minutes/],
|
|
173
|
+
]) {
|
|
174
|
+
test(`host failure ${JSON.stringify(options)} preserves existing profiles`, async t => {
|
|
175
|
+
const f = fixture(t);
|
|
176
|
+
f.write('baselineProfiles/baseline-prof.txt', 'original baseline');
|
|
177
|
+
f.write('baselineProfiles/startup-prof.txt', 'original startup');
|
|
178
|
+
const host = loadCollector(f, options);
|
|
179
|
+
await assert.rejects(host.collectStartupProfile({ serial: 'SERIAL', appId, rootDir: f.root,
|
|
180
|
+
apkPath: 'fixture.apk', timeoutMinutes: 20, ...(options.expired ? { deadline: 1 } : {}) }), message);
|
|
181
|
+
assert.equal(f.read('baselineProfiles/baseline-prof.txt'), 'original baseline');
|
|
182
|
+
assert.equal(f.read('baselineProfiles/startup-prof.txt'), 'original startup');
|
|
183
|
+
if (host.commands.some(args => args.includes('WRITE_SKIP_FILE'))) {
|
|
184
|
+
assert.ok(host.commands.some(args => args.includes('DELETE_SKIP_FILE')));
|
|
185
|
+
}
|
|
186
|
+
assert.equal(host.proc.listenerCount('SIGINT'), 0);
|
|
187
|
+
assert.equal(host.proc.listenerCount('SIGTERM'), 0);
|
|
188
|
+
});
|
|
189
|
+
}
|