@9l/playwright 0.6.0-beta.4 → 0.6.1

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 CHANGED
@@ -10,7 +10,7 @@ completing does not verify that behavior.
10
10
  Published on [npm](https://www.npmjs.com/package/@9l/playwright):
11
11
 
12
12
  ```sh
13
- npm install --save-dev @9l/playwright@0.5.5 @playwright/test@1.64.1
13
+ npm install --save-dev @9l/playwright@0.6.1 @playwright/test@1.64.1
14
14
  npm exec playwright install chromium
15
15
  ```
16
16
 
@@ -59,15 +59,15 @@ and [SDK bridge](https://github.com/Quality-Max/9lives-runner/blob/main/docs/sdk
59
59
  Live provider accuracy, independent behavioral verification, verified replay,
60
60
  iOS and Android devices beyond those listed below are not qualified features.
61
61
 
62
- ## Android (experimental, 0.6.0-beta releases)
62
+ ## Android (experimental)
63
63
 
64
64
  The Android target drives an owned emulator or an attached phone through
65
65
  Appium 3.8.0 and UiAutomator2 8.7.0, with the same `app` fixture a web
66
66
  target uses. It is qualified on API 35 emulators and one Android 17 phone;
67
67
  see [Android setup and qualification limits](https://github.com/Quality-Max/9lives-runner/blob/main/docs/android-driver.md).
68
68
 
69
- 1. Install the matching beta CLI and `@9l/playwright` together (see
70
- [beta releases](https://github.com/Quality-Max/9lives-runner/blob/main/docs/releases.md#beta-releases)),
69
+ 1. Install the matching 0.6.1 CLI and `@9l/playwright` together (see
70
+ [installation](https://github.com/Quality-Max/9lives-runner/blob/main/docs/install.md)),
71
71
  and the pinned automation tooling once, outside your project:
72
72
 
73
73
  ```sh
package/dist/android.d.ts CHANGED
@@ -81,7 +81,7 @@ export type AndroidTargetOptions = {
81
81
  headless?: boolean;
82
82
  deviceSerial?: never;
83
83
  /** Owned emulator only: boot the named snapshot of a dedicated AVD that
84
- * scripts/prepare-biometric-avd.cjs prepared (a lock screen and an
84
+ * `npx 9l-prepare-biometric-avd` prepared (a lock screen and an
85
85
  * enrolled fingerprint, saved unlocked), still read-only, and offer
86
86
  * app.fingerprint(). The driver never sees, sets or enters a PIN; a
87
87
  * snapshot that boots locked or without an enrolled fingerprint is a
package/dist/android.js CHANGED
@@ -34,6 +34,8 @@ const matchers = ['text', 'accessibilityId', 'accessibilityIdSuffix', 'accessibi
34
34
  /** Test IDs: an app resource entry name, which Android reports as
35
35
  * `<package>:id/<id>`, or an identifier a framework reports bare (Flutter's
36
36
  * `Semantics(identifier:)`), which may also contain `.` and `-`. */
37
+ // Android's text-entry classes: a Flutter or Compose text field reports EditText.
38
+ const editableClasses = ['android.widget.EditText', 'android.widget.AutoCompleteTextView', 'android.widget.MultiAutoCompleteTextView', 'android.widget.SearchView$SearchAutoComplete', 'android.inputmethodservice.ExtractEditText'];
37
39
  const testIdPattern = /^[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,127}$/;
38
40
  // UiAutomator2's selector parser unescapes only \" inside a string
39
41
  // argument; every other backslash reaches the matcher as written. Text and
@@ -341,6 +343,19 @@ function androidTargetDriver(options) {
341
343
  return signer;
342
344
  };
343
345
  let versionCode = 'unknown', versionName = 'unknown', signer = 'unknown';
346
+ let apkNeeds;
347
+ // One `adb install` of the owned emulator's APK: undefined on success,
348
+ // else adb's INSTALL_FAILED_ code (or `unknown`). Its output stays in
349
+ // memory; only that fixed token is read from it.
350
+ const installOwned = (apk, c) => new Promise((yes, no) => (0, node_child_process_1.execFile)(adb, ['-s', serial, 'install', '--no-streaming', '-r', apk], {
351
+ signal: c.signal, timeout: timeout(c), maxBuffer: 64 * 1024, env,
352
+ }, (error, stdout, stderr) => {
353
+ if (interrupted(c))
354
+ return no(failure('device_command_failed'));
355
+ if (!error)
356
+ return yes(undefined);
357
+ yes(/\bINSTALL_FAILED_[A-Z_]{1,48}\b/.exec(`${stdout}\n${stderr}`)?.[0] ?? 'unknown');
358
+ }));
344
359
  // Version from the package manager; the signer from the local APK (owned
345
360
  // emulator) or, when declared, from the installed base APK pulled into the
346
361
  // attempt's private scratch directory and removed with it.
@@ -485,67 +500,96 @@ function androidTargetDriver(options) {
485
500
  throw failure(result.length ? 'ambiguous_resource_id' : 'missing_resource_id');
486
501
  return result[0];
487
502
  };
488
- const handle = (id) => ({
489
- tap: async (c) => { const ref = await resolveOne(id, c); await observeGesture(c); await endpoint(`/element/${ref}/click`, c, 'POST', {}); },
490
- fill: async (value, c) => {
491
- disarm();
492
- const ref = await resolveOne(id, c);
493
- await endpoint(`/element/${ref}/clear`, c, 'POST', {});
494
- await endpoint(`/element/${ref}/value`, c, 'POST', { text: value });
495
- },
496
- // A control that vanished since it was observed is not visible; two
497
- // matches are still ambiguous.
498
- visible: async (c) => {
499
- const found = await matches(id, c);
500
- if (found.length > 1)
501
- throw failure('ambiguous_resource_id');
502
- if (found.length === 0)
503
- return false;
504
- const value = await endpoint(`/element/${found[0]}/displayed`, c);
505
- if (typeof value !== 'boolean')
506
- throw failure('invalid_property');
507
- return value;
508
- },
509
- text: async (c) => {
510
- disarm();
511
- const value = await endpoint(`/element/${await resolveOne(id, c)}/text`, c);
512
- if (typeof value !== 'string' || Buffer.byteLength(value) > 4096)
513
- throw failure('invalid_property');
514
- return value;
515
- },
516
- state: async (name, c) => {
517
- disarm();
518
- const value = await endpoint(`/element/${await resolveOne(id, c)}/attribute/${name}`, c);
519
- if (value !== 'true' && value !== 'false' && typeof value !== 'boolean')
520
- throw failure('unavailable_state');
521
- return value === true || value === 'true';
522
- },
523
- // The node's content-invalid flag: an input reporting a validation
524
- // error. UiAutomator2 reads it only through its hierarchy, so the flag
525
- // is the set of nodes the same criteria match with it set, and no single
526
- // request returns both the control and its flag. The read is bracketed:
527
- // the control resolves to one element before and after it, the same
528
- // element both times (element IDs are stable per node), and a flagged
529
- // result is that element. A control that vanished, was replaced or
530
- // became ambiguous in between is a failed read, never a state.
531
- invalid: async (c) => {
532
- disarm();
533
- const before = await resolveOne(id, c);
534
- const flagged = elements(await endpoint('/elements', c, 'POST', { using: 'xpath', value: `${xpathOf(id)}[@content-invalid="true"]` }));
535
- const after = await resolveOne(id, c);
536
- if (after !== before || flagged.some(ref => ref !== before))
537
- throw failure('stale_element_reference');
538
- return flagged.length === 1;
539
- },
540
- // One supported UiAutomator2 gesture inside the resolved element; the
541
- // driver reports whether more content exists, which is not retained.
542
- scroll: async (direction, percent, c) => {
543
- const ref = await resolveOne(id, c);
544
- await observeGesture(c);
545
- await endpoint('/execute/sync', c, 'POST', { script: 'mobile: scrollGesture', args: [{ elementId: ref, direction, percent }] });
546
- },
547
- bounds: async (c) => { disarm(); return rect(await endpoint(`/element/${await resolveOne(id, c)}/rect`, c)); },
548
- });
503
+ // The element a fill resolved, kept for its submit: a text alias no longer
504
+ // matches once the fill replaced that text.
505
+ const handle = (id) => {
506
+ let filledRef;
507
+ return {
508
+ tap: async (c) => { const ref = await resolveOne(id, c); await observeGesture(c); await endpoint(`/element/${ref}/click`, c, 'POST', {}); },
509
+ // A user's fill: a touch focuses the field (so checks an app runs on
510
+ // focus changes run), then its text is replaced. Setting text alone
511
+ // never focused it.
512
+ fill: async (value, c) => {
513
+ disarm();
514
+ filledRef = undefined;
515
+ const ref = await resolveOne(id, c);
516
+ // Only a text field is tapped: a tap on a control a selector wrongly
517
+ // named (a button) would run its action before the fill could fail.
518
+ // A text field reports an EditText class, or an input type in the
519
+ // hierarchy (UiAutomator2 reads it only there) on this same element.
520
+ const kind = await endpoint(`/element/${ref}/attribute/class`, c);
521
+ if (!(typeof kind === 'string' && editableClasses.includes(kind)) &&
522
+ !elements(await endpoint('/elements', c, 'POST', { using: 'xpath', value: `${xpathOf(id)}[@input-type and @input-type!="0"]` })).includes(ref))
523
+ throw failure('not_editable');
524
+ await endpoint(`/element/${ref}/click`, c, 'POST', {});
525
+ await endpoint(`/element/${ref}/clear`, c, 'POST', {});
526
+ await endpoint(`/element/${ref}/value`, c, 'POST', { text: value });
527
+ filledRef = ref;
528
+ },
529
+ // The input method's done action goes to whichever field has focus, so
530
+ // it is sent only while this field reports focus, never to another one.
531
+ submit: async (c) => {
532
+ disarm();
533
+ const ref = filledRef ?? await resolveOne(id, c);
534
+ const focused = await endpoint(`/element/${ref}/attribute/focused`, c);
535
+ if (focused !== true && focused !== 'true')
536
+ throw failure('field_not_focused');
537
+ await endpoint('/execute/sync', c, 'POST', { script: 'mobile: performEditorAction', args: [{ action: 'done' }] });
538
+ },
539
+ // A control that vanished since it was observed is not visible; two
540
+ // matches are still ambiguous.
541
+ visible: async (c) => {
542
+ const found = await matches(id, c);
543
+ if (found.length > 1)
544
+ throw failure('ambiguous_resource_id');
545
+ if (found.length === 0)
546
+ return false;
547
+ const value = await endpoint(`/element/${found[0]}/displayed`, c);
548
+ if (typeof value !== 'boolean')
549
+ throw failure('invalid_property');
550
+ return value;
551
+ },
552
+ text: async (c) => {
553
+ disarm();
554
+ const value = await endpoint(`/element/${await resolveOne(id, c)}/text`, c);
555
+ if (typeof value !== 'string' || Buffer.byteLength(value) > 4096)
556
+ throw failure('invalid_property');
557
+ return value;
558
+ },
559
+ state: async (name, c) => {
560
+ disarm();
561
+ const value = await endpoint(`/element/${await resolveOne(id, c)}/attribute/${name}`, c);
562
+ if (value !== 'true' && value !== 'false' && typeof value !== 'boolean')
563
+ throw failure('unavailable_state');
564
+ return value === true || value === 'true';
565
+ },
566
+ // The node's content-invalid flag: an input reporting a validation
567
+ // error. UiAutomator2 reads it only through its hierarchy, so the flag
568
+ // is the set of nodes the same criteria match with it set, and no single
569
+ // request returns both the control and its flag. The read is bracketed:
570
+ // the control resolves to one element before and after it, the same
571
+ // element both times (element IDs are stable per node), and a flagged
572
+ // result is that element. A control that vanished, was replaced or
573
+ // became ambiguous in between is a failed read, never a state.
574
+ invalid: async (c) => {
575
+ disarm();
576
+ const before = await resolveOne(id, c);
577
+ const flagged = elements(await endpoint('/elements', c, 'POST', { using: 'xpath', value: `${xpathOf(id)}[@content-invalid="true"]` }));
578
+ const after = await resolveOne(id, c);
579
+ if (after !== before || flagged.some(ref => ref !== before))
580
+ throw failure('stale_element_reference');
581
+ return flagged.length === 1;
582
+ },
583
+ // One supported UiAutomator2 gesture inside the resolved element; the
584
+ // driver reports whether more content exists, which is not retained.
585
+ scroll: async (direction, percent, c) => {
586
+ const ref = await resolveOne(id, c);
587
+ await observeGesture(c);
588
+ await endpoint('/execute/sync', c, 'POST', { script: 'mobile: scrollGesture', args: [{ elementId: ref, direction, percent }] });
589
+ },
590
+ bounds: async (c) => { disarm(); return rect(await endpoint(`/element/${await resolveOne(id, c)}/rect`, c)); },
591
+ };
592
+ };
549
593
  const pixel = (value) => Number.isInteger(value) && value >= 0 && value <= 65_535;
550
594
  const offset = (value) => Number.isInteger(value) && value >= -65_535 && value <= 65_535;
551
595
  // Only finite numbers are rounded: a null or boolean field is a malformed
@@ -672,6 +716,13 @@ function androidTargetDriver(options) {
672
716
  const badging = await command(sdkTools.aapt2, ['dump', 'badging', installedAPK], c, env);
673
717
  if (/^package: name='([^']+)'/.exec(badging)?.[1] !== options.appPackage)
674
718
  throw failure('apk_package_mismatch');
719
+ // What the device must offer: checked against it before install,
720
+ // so a build that cannot run there is a setup mismatch, not an
721
+ // install error.
722
+ // aapt2 prints `minSdkVersion:'N'`; older tools printed `sdkVersion:'N'`.
723
+ const minSdk = /^(?:minSdkVersion|sdkVersion):'([0-9]{1,3})'/m.exec(badging)?.[1];
724
+ apkNeeds = { minSdk: minSdk === undefined ? 1 : Number(minSdk),
725
+ abis: [...(/^native-code:(.*)$/m.exec(badging)?.[1] ?? '').matchAll(/'([a-z0-9_-]{1,32})'/g)].map(m => m[1]) };
675
726
  }
676
727
  await (0, promises_1.writeFile)((0, node_path_1.join)(directory, 'package.json'), JSON.stringify({ private: true, dependencies: { appium: android_runtime_1.androidVersions.appium, 'appium-uiautomator2-driver': android_runtime_1.androidVersions.uiautomator2 } }));
677
728
  // The emulator atomically reserves its own available console port.
@@ -784,7 +835,30 @@ function androidTargetDriver(options) {
784
835
  stage = 'displays';
785
836
  await readDisplays(c);
786
837
  stage = 'apk_install';
787
- await adbRun(['install', '--no-streaming', '-r', installedAPK], c);
838
+ if (apkNeeds) {
839
+ // An unreadable property decides nothing; the install itself is the check then.
840
+ const sdk = await adbRun(['shell', 'getprop', 'ro.build.version.sdk'], c);
841
+ if (/^[0-9]{1,3}$/.test(sdk) && apkNeeds.minSdk > Number(sdk))
842
+ throw new targets_1.TargetSetupError({ classification: 'mismatch', reason: 'build-sdk', stage: 'open' });
843
+ const abis = (await adbRun(['shell', 'getprop', 'ro.product.cpu.abilist'], c)).split(',').map(abi => abi.trim()).filter(Boolean);
844
+ if (apkNeeds.abis.length > 0 && abis.length > 0 && !apkNeeds.abis.some(abi => abis.includes(abi)))
845
+ throw new targets_1.TargetSetupError({ classification: 'mismatch', reason: 'build-abi', stage: 'open' });
846
+ }
847
+ // The AVD may already hold the package: a newer build (a
848
+ // downgrade) or one with another signer cannot be updated in
849
+ // place. On this read-only, discarded emulator it is uninstalled
850
+ // and the declared APK installed fresh; the AVD is unchanged.
851
+ let code = await installOwned(installedAPK, c);
852
+ if (code === 'INSTALL_FAILED_VERSION_DOWNGRADE' || code === 'INSTALL_FAILED_UPDATE_INCOMPATIBLE') {
853
+ await adbRun(['uninstall', options.appPackage], c);
854
+ code = await installOwned(installedAPK, c);
855
+ }
856
+ // Only adb's own failure code is named; nothing else it printed is kept.
857
+ if (code !== undefined) {
858
+ if (code !== 'unknown')
859
+ stage = `apk_install_${code.slice('INSTALL_FAILED_'.length).toLowerCase()}`;
860
+ throw failure('apk_install_failed');
861
+ }
788
862
  stage = 'build_identity';
789
863
  await buildIdentity(c, installedAPK);
790
864
  }
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ /** Runs the preparation; resolves to the process exit code (0, 1 failed, 2 refused). */
3
+ export declare function prepareBiometricAvd(args: string[]): Promise<number>;
@@ -0,0 +1,181 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.prepareBiometricAvd = prepareBiometricAvd;
8
+ // Prepare a dedicated AVD for biometric specs: wipe it, set a random lock
9
+ // PIN that is never printed or stored, enroll fingerprint 1 through
10
+ // Settings with the emulator's virtual sensor, and save the unlocked state
11
+ // as a named snapshot. androidTargetDriver({biometrics: {snapshot}}) then
12
+ // boots that snapshot read-only, so the driver never sees, sets or enters a
13
+ // PIN, and every test starts from the same state. The AVD's own data is
14
+ // erased: use one only for this. Its PIN is unrecoverable by design; run
15
+ // this again (it wipes again) when the snapshot stops loading.
16
+ //
17
+ // npx 9l-prepare-biometric-avd --avd 9l_biometric_API_35 --wipe [--snapshot 9l-biometric]
18
+ const node_child_process_1 = require("node:child_process");
19
+ const node_crypto_1 = require("node:crypto");
20
+ const node_fs_1 = __importDefault(require("node:fs"));
21
+ const node_os_1 = __importDefault(require("node:os"));
22
+ const node_path_1 = __importDefault(require("node:path"));
23
+ const android_env_1 = require("./android-env");
24
+ /** Runs the preparation; resolves to the process exit code (0, 1 failed, 2 refused). */
25
+ async function prepareBiometricAvd(args) {
26
+ const option = (name) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined; };
27
+ const avd = option('--avd'), snapshot = option('--snapshot') ?? '9l-biometric';
28
+ // Both name directories this script deletes inside: a name starts with a
29
+ // letter or digit, so `.` and `..` (and hidden names) are refused.
30
+ const name = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
31
+ if (!avd || !name.test(avd) || !name.test(snapshot)) {
32
+ console.error('usage: npx 9l-prepare-biometric-avd --avd <dedicated AVD> --wipe [--snapshot <name>]');
33
+ return 2;
34
+ }
35
+ if (!args.includes('--wipe')) {
36
+ console.error(`This erases all data of the AVD "${avd}" and gives it a lock PIN no one knows. Pass --wipe to confirm it is dedicated to biometric specs.`);
37
+ return 2;
38
+ }
39
+ const sdk = (0, android_env_1.androidDefaults)().sdkRoot;
40
+ if (!sdk) {
41
+ console.error('No Android SDK found: set ANDROID_HOME, or run 9l doctor --android');
42
+ return 2;
43
+ }
44
+ const { adb, emulator } = (0, android_env_1.androidToolPaths)(node_path_1.default.resolve(sdk));
45
+ // The AVD's directory, as the emulator finds it: its snapshots live there,
46
+ // and the console (through adb) does not relay what it saved.
47
+ const avdHome = process.env.ANDROID_AVD_HOME ?? node_path_1.default.join(process.env.ANDROID_USER_HOME ?? process.env.ANDROID_EMULATOR_HOME ?? node_path_1.default.join(node_os_1.default.homedir(), '.android'), 'avd');
48
+ const ini = node_path_1.default.join(avdHome, `${avd}.ini`);
49
+ const avdDir = node_fs_1.default.existsSync(ini) ? /^path=(.+)$/m.exec(node_fs_1.default.readFileSync(ini, 'utf8'))?.[1]?.trim() : undefined;
50
+ if (!avdDir || !node_fs_1.default.existsSync(avdDir)) {
51
+ console.error(`AVD "${avd}" not found under ${avdHome}`);
52
+ return 2;
53
+ }
54
+ const snapshots = node_path_1.default.join(avdDir, 'snapshots'), snapshotDir = node_path_1.default.join(snapshots, snapshot);
55
+ // Deleted only when it is a direct child of the AVD's snapshot directory.
56
+ if (node_path_1.default.dirname(snapshotDir) !== snapshots) {
57
+ console.error('invalid snapshot name');
58
+ return 2;
59
+ }
60
+ // A snapshot from before the wipe would resume the old data and PIN.
61
+ node_fs_1.default.rmSync(snapshotDir, { recursive: true, force: true });
62
+ const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
63
+ const devices = () => (0, node_child_process_1.execFileSync)(adb, ['devices'], { encoding: 'utf8', timeout: 30000 });
64
+ const port = [...Array(40).keys()].map(i => 5600 + i * 2).find(p => !devices().includes(`emulator-${p}`));
65
+ if (port === undefined) {
66
+ console.error('no free emulator port between 5600 and 5678');
67
+ return 2;
68
+ }
69
+ const serial = `emulator-${port}`;
70
+ // Device output stays in memory; only progress lines are printed. A failed
71
+ // command's own error names its arguments, which include the PIN, so it is
72
+ // replaced by a fixed message before anything can print it.
73
+ const run = (...a) => {
74
+ try {
75
+ return (0, node_child_process_1.execFileSync)(adb, ['-s', serial, ...a], { encoding: 'utf8', timeout: 60000, stdio: ['ignore', 'pipe', 'pipe'] });
76
+ }
77
+ catch {
78
+ throw new Error('a device command failed');
79
+ }
80
+ };
81
+ const child = (0, node_child_process_1.spawn)(emulator, ['-avd', avd, '-wipe-data', '-no-snapshot-load', '-no-audio', '-no-window', '-gpu', 'swiftshader_indirect', '-port', String(port)], { stdio: 'ignore' });
82
+ let failed = '';
83
+ try {
84
+ for (let i = 0;; i++) {
85
+ if (i > 150)
86
+ throw new Error('the AVD did not finish booting in 5 minutes');
87
+ try {
88
+ if (run('shell', 'getprop', 'sys.boot_completed').trim() === '1')
89
+ break;
90
+ }
91
+ catch { }
92
+ sleep(2000);
93
+ }
94
+ console.log(`booted ${avd} wiped`);
95
+ const pin = String((0, node_crypto_1.randomInt)(100000, 1000000));
96
+ run('shell', 'locksettings', 'set-pin', pin);
97
+ run('shell', 'am', 'start', '-W', '-a', 'android.settings.FINGERPRINT_ENROLL');
98
+ sleep(2000);
99
+ const buttons = ['more', 'i agree', 'agree', 'next', 'start', 'continue', 'ok', 'done'];
100
+ let added = false;
101
+ for (let step = 0; step < 60 && !added; step++) {
102
+ let xml;
103
+ try {
104
+ run('shell', 'uiautomator', 'dump', '/sdcard/9l-enroll.xml');
105
+ xml = run('shell', 'cat', '/sdcard/9l-enroll.xml');
106
+ }
107
+ catch {
108
+ sleep(1000);
109
+ continue;
110
+ }
111
+ const nodes = [...xml.matchAll(/<node [^>]*>/g)].map(m => m[0]);
112
+ const screen = nodes.map(n => /text="([^"]*)"/.exec(n)?.[1] ?? '').filter(Boolean).join(' | ');
113
+ const target = nodes.find(n => /clickable="true"/.test(n) && buttons.includes((/text="([^"]*)"/.exec(n)?.[1] ?? '').toLowerCase()));
114
+ if (/enter your pin|re-enter your pin|confirm your pin/i.test(screen)) {
115
+ run('shell', 'input', 'text', pin);
116
+ run('shell', 'input', 'keyevent', '66');
117
+ sleep(2500);
118
+ }
119
+ else if (target) {
120
+ const [, x1, y1, x2, y2] = /bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"/.exec(target).map(Number);
121
+ const label = /text="([^"]*)"/.exec(target)[1].toLowerCase();
122
+ run('shell', 'input', 'tap', String((x1 + x2) >> 1), String((y1 + y2) >> 1));
123
+ added = label === 'done' && /fingerprint added/i.test(screen);
124
+ sleep(1500);
125
+ }
126
+ else if (/touch the sensor|lift|put your finger|touch and hold|keep lifting|again/i.test(screen)) {
127
+ run('emu', 'finger', 'touch', '1');
128
+ sleep(800);
129
+ run('emu', 'finger', 'remove', '1');
130
+ sleep(800);
131
+ }
132
+ else
133
+ sleep(1500);
134
+ }
135
+ run('shell', 'rm', '-f', '/sdcard/9l-enroll.xml');
136
+ const enrolled = [...run('shell', 'dumpsys', 'fingerprint').matchAll(/"count":([0-9]{1,4})/g)].reduce((sum, m) => sum + Number(m[1]), 0);
137
+ if (!added || enrolled < 1)
138
+ throw new Error('fingerprint enrollment did not complete; the Settings flow of this image may differ');
139
+ console.log('fingerprint 1 enrolled');
140
+ run('shell', 'input', 'keyevent', '3');
141
+ sleep(2000);
142
+ run('emu', 'avd', 'snapshot', 'save', snapshot);
143
+ for (let i = 0; i < 60 && !node_fs_1.default.existsSync(node_path_1.default.join(snapshotDir, 'snapshot.pb')); i++)
144
+ sleep(1000);
145
+ if (!node_fs_1.default.existsSync(node_path_1.default.join(snapshotDir, 'snapshot.pb')))
146
+ throw new Error('the snapshot was not saved');
147
+ console.log(`saved snapshot ${snapshot}: use androidTargetDriver({avd: '${avd}', biometrics: {snapshot: '${snapshot}'}, ...})`);
148
+ }
149
+ catch (error) {
150
+ // Only this script's own messages: run() never passes a command's text.
151
+ failed = error instanceof Error ? error.message : 'preparation failed';
152
+ }
153
+ finally {
154
+ try {
155
+ run('emu', 'kill');
156
+ }
157
+ catch {
158
+ child.kill('SIGKILL');
159
+ }
160
+ // Wait for the emulator to exit, so the AVD is free for the first test;
161
+ // the exit event needs the event loop, so this wait yields to it.
162
+ const exited = (ms) => new Promise(resolve => {
163
+ if (child.exitCode !== null || child.signalCode !== null)
164
+ return resolve(true);
165
+ const timer = setTimeout(() => resolve(false), ms);
166
+ child.once('exit', () => { clearTimeout(timer); resolve(true); });
167
+ });
168
+ if (!await exited(60000)) {
169
+ child.kill('SIGKILL');
170
+ if (!await exited(10000) && !failed)
171
+ failed = 'the emulator did not stop';
172
+ }
173
+ }
174
+ if (failed) {
175
+ console.error(`9l biometric AVD: ${failed}`);
176
+ return 1;
177
+ }
178
+ return 0;
179
+ }
180
+ if (require.main === module)
181
+ void prepareBiometricAvd(process.argv.slice(2)).then(code => { process.exitCode = code; });
@@ -13,7 +13,7 @@ exports.setupReasons = {
13
13
  blocked: ['device-locked', 'screen-off'],
14
14
  dirty: ['extra-window', 'foreign-focus', 'ime-showing'],
15
15
  /** The device is not in the posture or width the spec declared. */
16
- mismatch: ['posture', 'display-width', 'build-digest', 'build-version', 'build-signer', 'biometrics-unavailable'],
16
+ mismatch: ['posture', 'display-width', 'build-digest', 'build-version', 'build-signer', 'biometrics-unavailable', 'build-sdk', 'build-abi'],
17
17
  /** The accessibility snapshot still reported an element whose window the
18
18
  * window manager no longer lists: observer staleness, not the app. */
19
19
  observer: ['window-gone-element-displayed'],
package/dist/targets.d.ts CHANGED
@@ -46,6 +46,11 @@ export interface TargetHandle {
46
46
  /** Whether the control reports a validation error. A handle without it
47
47
  * fails `toHaveState('invalid', …)` as unsupported_state. */
48
48
  invalid?(context: TargetContext): Promise<boolean>;
49
+ /** Press the keyboard's action key in this field, as a user finishing it
50
+ * would: Enter on the web, the input method's done action on Android. A
51
+ * handle without it fails `fill(value, {submit: true})` as
52
+ * unsupported_operation. */
53
+ submit?(context: TargetContext): Promise<void>;
49
54
  /** One bounded scroll gesture inside this element; percent of its size. */
50
55
  scroll?(direction: ScrollDirection, percent: number, context: TargetContext): Promise<void>;
51
56
  bounds?(context: TargetContext): Promise<TargetRect>;
@@ -191,8 +196,13 @@ export declare class TargetApp {
191
196
  * Not a device operation and never recorded. Android only. */
192
197
  deviceSerial(): string;
193
198
  getByTestId(id: string): {
194
- tap: (options?: TargetOperationOptions) => Promise<any>;
195
- fill: (value: string, options?: TargetOperationOptions) => Promise<void>;
199
+ tap: (options?: TargetOperationOptions) => Promise<void>;
200
+ /** Focus the field, replace its text and, with `submit`, press the
201
+ * keyboard's action key in it, as a user would: checks an app runs
202
+ * when the field gains or loses focus, or on its done action, run. */
203
+ fill: (value: string, options?: TargetOperationOptions & {
204
+ submit?: boolean;
205
+ }) => Promise<void>;
196
206
  /** One bounded scroll gesture inside this control, by a fraction of its size. */
197
207
  scroll: (direction: ScrollDirection, options?: TargetOperationOptions & {
198
208
  percent?: number;
package/dist/targets.js CHANGED
@@ -432,11 +432,22 @@ class TargetApp {
432
432
  throw stopped('invalid_property');
433
433
  return matches[0];
434
434
  };
435
+ // An action waits, within its own bound, for its control to appear (a
436
+ // screen still loading after a navigating tap), as Playwright's web
437
+ // actions do, then acts once. Only the read-only lookup repeats; the
438
+ // action itself is never retried. Ambiguity, invalid input and failed
439
+ // lookups end the wait at once; a control still absent before the bound
440
+ // is missing_test_id, unless Go's worker deadline cut the wait short:
441
+ // that is `deadline`, as for a query, since the wait never ran its course.
435
442
  const required = async (context) => {
436
- const handle = await observe(context);
437
- if (!handle)
438
- throw stopped('missing_test_id');
439
- return handle;
443
+ let found;
444
+ const result = await this.poll(context, async (context) => {
445
+ found = await observe(context);
446
+ return found !== undefined;
447
+ }, Math.max(1, context.deadlineMs - Date.now()), maxObservations, () => { }, true);
448
+ if (!result.held || !found)
449
+ throw stopped(context.deadlineMs >= this.options.deadlineMs ? 'deadline' : 'missing_test_id');
450
+ return found;
440
451
  };
441
452
  // A missing control is a completed false observation, except for a
442
453
  // hidden assertion, where absence is exactly what it asserts.
@@ -448,10 +459,18 @@ class TargetApp {
448
459
  }, timeoutMs, id);
449
460
  return {
450
461
  tap: (options = {}) => step('tap', async (context) => (await required(context)).tap(context), options.timeoutMs),
462
+ /** Focus the field, replace its text and, with `submit`, press the
463
+ * keyboard's action key in it, as a user would: checks an app runs
464
+ * when the field gains or loses focus, or on its done action, run. */
451
465
  fill: (value, options = {}) => step('fill', async (context) => {
452
- if (!boundedText(value, 4096))
466
+ if (!boundedText(value, 4096) || (options.submit !== undefined && typeof options.submit !== 'boolean'))
453
467
  throw stopped('invalid_value');
454
- await (await required(context)).fill(value, context);
468
+ const handle = await required(context);
469
+ if (options.submit && typeof handle.submit !== 'function')
470
+ throw stopped('unsupported_operation');
471
+ await handle.fill(value, context);
472
+ if (options.submit)
473
+ await handle.submit(context);
455
474
  }, options.timeoutMs),
456
475
  /** One bounded scroll gesture inside this control, by a fraction of its size. */
457
476
  scroll: (direction, options = {}) => step('scroll', async (context) => {
@@ -544,6 +563,7 @@ function locatorHandle(locator) {
544
563
  return {
545
564
  tap: async (context) => { await locator.click({ timeout: remaining(context) }); },
546
565
  fill: async (value, context) => { await locator.fill(value, { timeout: remaining(context) }); },
566
+ submit: async (context) => { await locator.press('Enter', { timeout: remaining(context) }); },
547
567
  visible: async (context) => { remaining(context); return locator.isVisible(); },
548
568
  text: async (context) => await locator.textContent({ timeout: remaining(context) }) ?? '',
549
569
  state: async (name, context) => name === 'enabled' ? locator.isEnabled({ timeout: remaining(context) }) : locator.isChecked({ timeout: remaining(context) }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@9l/playwright",
3
- "version": "0.6.0-beta.4",
3
+ "version": "0.6.1",
4
4
  "description": "Playwright fixtures and the versioned 9lives Go engine bridge",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/Quality-Max/9lives-runner#local-playwright-sdk",
@@ -12,6 +12,7 @@
12
12
  "bugs": {"url": "https://github.com/Quality-Max/9lives-runner/issues"},
13
13
  "type": "commonjs",
14
14
  "main": "dist/index.js",
15
+ "bin": {"9l-prepare-biometric-avd": "dist/prepare-biometric-avd.js"},
15
16
  "types": "dist/index.d.ts",
16
17
  "exports": {
17
18
  ".": {"types": "./dist/index.d.ts", "default": "./dist/index.js"},