@ohos-ports/playwright-browser-chromium 1.61.1-beta.1 → 1.65.1-beta.0

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
@@ -2,9 +2,79 @@
2
2
 
3
3
  This package automatically installs [Chromium](https://www.chromium.org/) browser for [Playwright](http://github.com/microsoft/playwright) library. If you want to write end-to-end tests, we recommend [@playwright/test](https://playwright.dev/docs/intro).
4
4
 
5
- > **OpenHarmony (OHOS) port** (@ohos-ports): ships `ohos-shim/` (LD_PRELOAD
6
- > interposer `sigsys_diag30.so` fixing seccomp SIGSYS / musl dl* crashes /
7
- > HongMeng uname CHECK, plus `run-chromium.sh`) and a postinstall script that
8
- > patches `playwright-core`'s platform registry for `openharmony` (with
9
- > `CHROMIUM_PATH` fallback). On non-OHOS platforms it behaves exactly like
10
- > upstream `@playwright/browser-chromium`.
5
+ ## OpenHarmony (OHOS) port
6
+
7
+ This is an `@ohos-ports` port of `@playwright/browser-chromium` for HarmonyOS (OpenHarmony, musl/aarch64).
8
+
9
+ ### Installation
10
+
11
+ ```sh
12
+ npm install @ohos-ports/playwright-browser-chromium
13
+ ```
14
+
15
+ On `openharmony` the postinstall script (`install.js`) patches the installed
16
+ `playwright-core@1.65.1` in place (platform registry: openharmony → linux cache
17
+ directories, hostPlatform `debian12-<arch>`, `CHROMIUM_PATH` support, and the
18
+ `chromium.launch()` CDP interception described below). Without this patch,
19
+ `require('playwright-core')` throws `Unsupported platform: openharmony` at
20
+ module init on OpenHarmony.
21
+
22
+ The Playwright CDN browser download is **skipped** on `openharmony` unless
23
+ `CHROMIUM_PATH` points to an executable (CDN builds are glibc binaries whose
24
+ interpreter `/lib/ld-linux-aarch64.so.1` does not exist on musl-only
25
+ HarmonyOS, `execve` fails with `ENOENT`). The browser runtime is instead
26
+ provided by the **on-device browser (Haitai browser, `com.haitai.htbrowser`,
27
+ Chrome/132 kernel)** driven over CDP.
28
+
29
+ ### Environment variables
30
+
31
+ | Variable | Default | Meaning |
32
+ |---|---|---|
33
+ | `CHROMIUM_PATH` | – | Path to a native musl Chromium executable. When executable, `chromium.launch()` uses the native launch path with the `ohos-shim` LD_PRELOAD interposer; otherwise the launch is routed to the CDP adapter. Also gates the CDN download in `install.js`. |
34
+ | `OHOS_CDP_PORT` | `9333` | Remote debugging port of the on-device browser. |
35
+ | `OHOS_CDP_HOST` | `127.0.0.1` | Host of the CDP endpoint. |
36
+ | `OHOS_CDP_ATTACH_PROBE_MS` | `2500` | Fast-path probe timeout for `GET /json/version`. `0` disables fast-path attach. |
37
+ | `OHOS_CDP_START_TIMEOUT` | `30000` | How long to wait for the CDP endpoint after an `ohos-aa` start. |
38
+ | `HARMONY_BROWSER` | `haitai` | Browser profile: `haitai` or `chrome`. |
39
+ | `OHOS_BROWSER_BUNDLENAME` / `OHOS_BROWSER_ABILITYNAME` / `OHOS_BROWSER_PROCESS_HINT` | – | Override the bundle name / ability name / `ps` process-match keyword. |
40
+ | `OHOS_AA` / `OHOS_BM` | `/system/bin/cli_tool/executable/ohos-aa` / `ohos-bm` | Paths to the OHOS CLI tools. |
41
+
42
+ ### Fast-path attach and ohos-aa permissions
43
+
44
+ `chromium.launch()` on `openharmony` first **fast-path attaches**: it probes
45
+ `http://127.0.0.1:9333/json/version` and, when the on-device browser is
46
+ already serving CDP (e.g. started by the desktop with
47
+ `--remote-debugging-port=9333`), connects via
48
+ `chromium.connectOverCDP(wsUrl)` **without invoking `ohos-aa`/`ohos-bm` at
49
+ all** — no special permissions are required in this mode. `browser.close()`
50
+ in attach mode only disconnects; the shared system browser is never stopped.
51
+
52
+ When no endpoint answers, the launcher falls back to starting the browser via
53
+ `ohos-aa` (launcher mode): this requires the CLI tools under
54
+ `/system/bin/cli_tool/executable/` and weak-sandbox permission, which is
55
+ **denied from headless CLI processes** (`OHOS_AA_PERMISSION_DENIED`,
56
+ `err.deferredToHap = true`). In launcher mode `browser.close()` maps to
57
+ `ohos-aa force-stop` with a `kill -9` fallback.
58
+
59
+ ### Included OHOS runtime shim
60
+
61
+ `ohos-shim/` ships an `LD_PRELOAD` interposer (`sigsys_diag30.so`, built from
62
+ the bundled `sigsys_diag30.c` via `clang -shared -fPIC -O2`) used by the native
63
+ `CHROMIUM_PATH` launch path: seccomp `SIGSYS` emulation (`eventfd2`/`landlock`),
64
+ musl `dlsym`/`dladdr1` NULL-deref fixes, and `uname()` spoof of the HongMeng
65
+ kernel release (Chromium `SysInfo` CHECK crash), plus `run-chromium.sh`.
66
+
67
+ ### Known limitations
68
+
69
+ - The glibc CDN Chromium builds cannot run on musl-only HarmonyOS; the
70
+ supported runtime is the on-device Haitai browser over CDP (or a musl
71
+ Chromium via `CHROMIUM_PATH` + `ohos-shim`).
72
+ - `ohos-aa` launcher-mode browser start requires weak-sandbox permission and
73
+ fails (`EACCES`) from headless CLI environments; start the browser with
74
+ `--remote-debugging-port=9333` from a desktop/hap environment instead and
75
+ rely on fast-path attach.
76
+ - Coordinate values (`boundingBox`, `quadToRect`) are rounded with
77
+ `Math.round()` on openharmony to work around non-integer CDP geometry of the
78
+ Haitai browser.
79
+ - On non-OHOS platforms the package behaves exactly like upstream
80
+ `@playwright/browser-chromium`.
package/install.js CHANGED
@@ -16,12 +16,17 @@
16
16
 
17
17
  const path = require('path');
18
18
 
19
- // OpenHarmony: playwright-core@1.61.x has no "openharmony" platform entry, so
19
+ // OpenHarmony: playwright-core@1.65.1 has no "openharmony" platform entry, so
20
20
  // require('playwright-core/lib/coreBundle') would throw
21
- // "Unsupported platform: openharmony" at module init and the browser install
22
- // would be silently skipped. Apply the platform patch (openharmony -> linux
23
- // registry, hostPlatform debian12-<arch>, CHROMIUM_PATH + ohos-shim launch
24
- // support) before loading coreBundle. Idempotent, non-fatal.
21
+ // "Unsupported platform: openharmony" at module init (computeDefaultCacheDirectory
22
+ // in lib/coreBundle.js) and the browser install would be silently skipped.
23
+ // Apply the platform patch (openharmony -> linux cache dirs, hostPlatform
24
+ // debian12-<arch>, CHROMIUM_PATH + ohos-shim launch support, and — since
25
+ // patch v3 — the chromium.launch() ohos CDP interception: fast-path attach to
26
+ // an already-serving endpoint such as the Haitai browser started by the hap
27
+ // desktop, or device-local `ohos-aa` start) before loading coreBundle.
28
+ // Idempotent, non-fatal.
29
+ let skipBrowserDownload = false;
25
30
  try {
26
31
  if (process.platform === 'openharmony') {
27
32
  const { apply, ensureShimBinary } = require('./scripts/patch-playwright-core');
@@ -29,6 +34,27 @@ try {
29
34
  require.resolve('playwright-core/package.json', { paths: [__dirname] }));
30
35
  apply({ playwrightRoot });
31
36
  ensureShimBinary(path.join(__dirname, 'ohos-shim'));
37
+
38
+ // The chromium builds downloaded from the Playwright CDN are glibc
39
+ // binaries (interp /lib/ld-linux-aarch64.so.1) that cannot be executed on
40
+ // musl-only HarmonyOS (execve ENOENT). Skip the download unless
41
+ // CHROMIUM_PATH points to a real executable (e.g. an HMMAC-signed musl
42
+ // chromium); chromium.launch() then goes through the ohos CDP adapter
43
+ // (fast-path attach to the running Haitai browser, falling back to an
44
+ // ohos-aa start) injected by patch-playwright-core v3.
45
+ const fs = require('fs');
46
+ const chromiumPath = process.env.CHROMIUM_PATH;
47
+ let nativeExecutable = false;
48
+ if (chromiumPath) {
49
+ try {
50
+ const st = fs.statSync(chromiumPath);
51
+ nativeExecutable = st.isFile() && (st.mode & 0o111) !== 0;
52
+ } catch (e) { /* keep false */ }
53
+ }
54
+ if (!nativeExecutable) {
55
+ skipBrowserDownload = true;
56
+ console.log('ohos-ports: CHROMIUM_PATH does not point to an executable — skipping Playwright CDN browser download (glibc builds are unusable on musl-only HarmonyOS). chromium.launch() will be routed to the ohos CDP adapter (fast-path attach to the running Haitai browser, falling back to ohos-aa start).');
57
+ }
32
58
  }
33
59
  } catch (e) {
34
60
  // Non-fatal: patching must never break package installation.
@@ -37,7 +63,7 @@ try {
37
63
  let install;
38
64
 
39
65
  try {
40
- if (!require('playwright-core/lib/coreBundle').utils.isLikelyNpxGlobal())
66
+ if (!skipBrowserDownload && !require('playwright-core/lib/coreBundle').utils.isLikelyNpxGlobal())
41
67
  install = require('playwright-core/lib/coreBundle').registry.installBrowsersForNpmInstall;
42
68
  } catch (e) {
43
69
  // Dev build, don't install browsers by default.
package/package.json CHANGED
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "@ohos-ports/playwright-browser-chromium",
3
- "version": "1.61.1-beta.1",
4
- "description": "Playwright package that automatically installs Chromium - OpenHarmony (OHOS) port with musl Chromium shim (sigsys_diag30.so) and playwright-core openharmony platform patch (postinstall mechanism)",
3
+ "version": "1.65.1-beta.0",
4
+ "description": "Playwright package that automatically installs Chromium - OpenHarmony (OHOS) port: CDP attach/launch for the on-device Haitai browser, playwright-core openharmony platform patch (postinstall mechanism), fast-path attach to an already-serving CDP endpoint, musl Chromium shim (sigsys_diag30.so)",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/ohos-ports/ohos-ports.git",
8
- "directory": "ports/playwright-browser-chromium/1.61.1"
8
+ "directory": "ports/playwright-browser-chromium/1.65.1"
9
9
  },
10
10
  "homepage": "https://playwright.dev",
11
11
  "engines": {
12
- "node": ">=18"
12
+ "node": ">=20"
13
13
  },
14
14
  "author": {
15
15
  "name": "Microsoft Corporation"
@@ -28,7 +28,7 @@
28
28
  "install": "node install.js"
29
29
  },
30
30
  "dependencies": {
31
- "playwright-core": "1.61.1"
31
+ "playwright-core": "1.65.1"
32
32
  },
33
33
  "bugs": {
34
34
  "url": "https://github.com/ohos-ports/ohos-ports/issues"
@@ -0,0 +1,453 @@
1
+ /**
2
+ * OpenHarmony CDP browser launcher — brings playwright-core's
3
+ * `chromium.launch()` to musl-only HarmonyOS devices where the glibc chromium
4
+ * builds downloaded from the Playwright CDN cannot be executed.
5
+ *
6
+ * Two launch modes, probed in this order:
7
+ *
8
+ * 1. fast-path attach (v3 addition, preferred): if a CDP endpoint is
9
+ * already serving at `http://<host>:<port>/json/version` — e.g. the
10
+ * Haitai browser (`com.haitai.htbrowser`, Chrome/132 kernel) started by
11
+ * the hap desktop with `--remote-debugging-port` — attach to it after a
12
+ * short probe and return `attached: true`. No ohos-bm verification, no
13
+ * leftover-process cleanup and no ohos-aa call happens in this mode.
14
+ * The browser is shared with the system, so the returned mock process
15
+ * never stops it: `kill()`/`close()` only mark it killed and emit
16
+ * `exit`; the CDP connection itself is torn down by the caller through
17
+ * the original browserProcess.close() (WebSocket disconnect).
18
+ *
19
+ * 2. ohos-aa start (original path): verify the browser bundle via
20
+ * `ohos-bm dump -a`, clean leftover browser processes, start the browser
21
+ * through the device-local `ohos-aa` CLI with CDP flags, then poll the
22
+ * CDP endpoint. `browser.close()` maps to `ohos-aa force-stop` with a
23
+ * `kill -9` fallback (mockProcess).
24
+ *
25
+ * Reference: harmonyos-nodejs-validate/references/browser-cdp-adaptation.md
26
+ * (1.61.1 precedent: @ohos-ports/playwright-browser-chromium@1.61.1-beta.1)
27
+ *
28
+ * Environment variables (all optional):
29
+ * OHOS_AA path to the ohos-aa CLI
30
+ * (default /system/bin/cli_tool/executable/ohos-aa)
31
+ * OHOS_BM path to the ohos-bm CLI
32
+ * (default /system/bin/cli_tool/executable/ohos-bm)
33
+ * HARMONY_BROWSER browser profile: "haitai" (default) or "chrome"
34
+ * OHOS_BROWSER_BUNDLENAME override bundle name (e.g. com.haitai.htbrowser)
35
+ * OHOS_BROWSER_ABILITYNAME override ability name (e.g. EntryAbility)
36
+ * OHOS_BROWSER_PROCESS_HINT override the `ps -ef` process match keyword
37
+ * OHOS_CDP_PORT remote debugging port (default 9333)
38
+ * OHOS_CDP_HOST debugging endpoint host (default 127.0.0.1)
39
+ * OHOS_CDP_START_TIMEOUT ms to wait for the CDP endpoint after an ohos-aa
40
+ * start (default 30000)
41
+ * OHOS_CDP_ATTACH_PROBE_MS fast-path probe timeout for /json/version
42
+ * (default 2500; set 0 to disable fast-path attach)
43
+ *
44
+ * All ohos-aa / ohos-bm failures throw an `OhosCdpError` carrying a stable
45
+ * `code` (e.g. `OHOS_AA_PERMISSION_DENIED`) so that callers can degrade
46
+ * gracefully. `*_PERMISSION_DENIED` errors additionally set
47
+ * `err.deferredToHap = true`: ohos-aa requires weak-sandbox permission and is
48
+ * denied from a headless CLI, so launcher-mode live CDP round-trips must be
49
+ * re-verified inside a hap environment.
50
+ */
51
+ 'use strict';
52
+
53
+ const { spawnSync } = require('child_process');
54
+ const http = require('http');
55
+ const EventEmitter = require('events');
56
+
57
+ const DEFAULT_AA_PATH = '/system/bin/cli_tool/executable/ohos-aa';
58
+ const DEFAULT_BM_PATH = '/system/bin/cli_tool/executable/ohos-bm';
59
+ const DEFAULT_CDP_PORT = 9333;
60
+ const DEFAULT_CDP_HOST = '127.0.0.1';
61
+ const DEFAULT_START_TIMEOUT_MS = 30000;
62
+ const DEFAULT_ATTACH_PROBE_MS = 2500;
63
+ const HAP_DEFERRED_HINT =
64
+ 'ohos-aa/ohos-bm require weak-sandbox permission; they work inside a hap ' +
65
+ '(e.g. the OpenDesk desktop app) but are denied from a headless CLI. ' +
66
+ 'Live browser CDP round-trips must be verified in a hap environment.';
67
+
68
+ const BROWSER_PROFILES = {
69
+ haitai: {
70
+ bundleName: 'com.haitai.htbrowser',
71
+ abilityName: 'EntryAbility',
72
+ processHint: 'htbrowser'
73
+ },
74
+ chrome: {
75
+ bundleName: 'com.google.chrome',
76
+ abilityName: 'EntryAbility',
77
+ processHint: 'chrome'
78
+ }
79
+ };
80
+
81
+ class OhosCdpError extends Error {
82
+ constructor(code, message, details) {
83
+ super(message);
84
+ this.name = 'OhosCdpError';
85
+ this.code = code;
86
+ if (details !== undefined)
87
+ this.details = details;
88
+ if (code === 'OHOS_AA_PERMISSION_DENIED' || code === 'OHOS_BM_PERMISSION_DENIED')
89
+ this.deferredToHap = true;
90
+ }
91
+ }
92
+
93
+ function config(overrides = {}) {
94
+ const env = process.env;
95
+ const browser = String(
96
+ overrides.browser || env.HARMONY_BROWSER || 'haitai').toLowerCase();
97
+ const profile = BROWSER_PROFILES[browser] || BROWSER_PROFILES.haitai;
98
+ const port = Number(overrides.port || env.OHOS_CDP_PORT || DEFAULT_CDP_PORT);
99
+ return {
100
+ aaPath: overrides.aaPath || env.OHOS_AA || DEFAULT_AA_PATH,
101
+ bmPath: overrides.bmPath || env.OHOS_BM || DEFAULT_BM_PATH,
102
+ browser,
103
+ bundleName: env.OHOS_BROWSER_BUNDLENAME || profile.bundleName,
104
+ abilityName: env.OHOS_BROWSER_ABILITYNAME || profile.abilityName,
105
+ processHint: env.OHOS_BROWSER_PROCESS_HINT || profile.processHint,
106
+ port,
107
+ host: env.OHOS_CDP_HOST || DEFAULT_CDP_HOST,
108
+ startTimeout: Number(env.OHOS_CDP_START_TIMEOUT || DEFAULT_START_TIMEOUT_MS),
109
+ // 0 disables the fast-path attach probe (forces the ohos-aa launch path).
110
+ attachProbeMs: Number(
111
+ overrides.attachProbeMs !== undefined ? overrides.attachProbeMs :
112
+ (env.OHOS_CDP_ATTACH_PROBE_MS !== undefined ? env.OHOS_CDP_ATTACH_PROBE_MS : DEFAULT_ATTACH_PROBE_MS))
113
+ };
114
+ }
115
+
116
+ /**
117
+ * Run a device-local CLI tool. Never throws raw spawn errors — every failure
118
+ * is normalized to an OhosCdpError with a stable code.
119
+ */
120
+ function runTool(binPath, args, errPrefix) {
121
+ let res;
122
+ try {
123
+ res = spawnSync(binPath, args, { encoding: 'utf8', timeout: 30000 });
124
+ } catch (e) {
125
+ throw new OhosCdpError(`${errPrefix}_EXEC_FAILED`,
126
+ `failed to execute ${binPath}: ${e.message}`);
127
+ }
128
+ if (res.error) {
129
+ const err = res.error;
130
+ if (err.code === 'EACCES') {
131
+ throw new OhosCdpError(`${errPrefix}_PERMISSION_DENIED`,
132
+ `permission denied executing ${binPath} (EACCES). ${HAP_DEFERRED_HINT}`);
133
+ }
134
+ if (err.code === 'ENOENT') {
135
+ throw new OhosCdpError(`${errPrefix}_NOT_FOUND`,
136
+ `tool not found at ${binPath} (ENOENT); set ${errPrefix.replace('OHOS_', 'OHOS_')} to the correct path`);
137
+ }
138
+ throw new OhosCdpError(`${errPrefix}_EXEC_FAILED`,
139
+ `failed to execute ${binPath}: ${err.message}`);
140
+ }
141
+ return res;
142
+ }
143
+
144
+ /** Step 1: verify the browser bundle is installed via `ohos-bm dump -a`. */
145
+ function verifyBrowserInstalled(cfg, log) {
146
+ const res = runTool(cfg.bmPath, ['dump', '-a'], 'OHOS_BM');
147
+ const out = `${res.stdout || ''}\n${res.stderr || ''}`;
148
+ if (!out.includes(cfg.bundleName)) {
149
+ throw new OhosCdpError('OHOS_BROWSER_NOT_INSTALLED',
150
+ `browser bundle ${cfg.bundleName} not found via "${cfg.bmPath} dump -a" (profile "${cfg.browser}"); ` +
151
+ `install the browser first or set HARMONY_BROWSER/OHOS_BROWSER_BUNDLENAME`);
152
+ }
153
+ log(`ohos-cdp: ${cfg.bundleName} is installed (verified via ohos-bm)`);
154
+ }
155
+
156
+ function findBrowserPids(cfg) {
157
+ const res = spawnSync('ps', ['-ef'], { encoding: 'utf8', timeout: 15000 });
158
+ const out = res.stdout || '';
159
+ const pids = [];
160
+ for (const line of out.split('\n')) {
161
+ if (!line.includes(cfg.processHint) || line.includes('grep'))
162
+ continue;
163
+ const fields = line.trim().split(/\s+/);
164
+ const pid = Number(fields[1]);
165
+ if (Number.isFinite(pid) && pid > 0 && pid !== process.pid)
166
+ pids.push({ pid, line });
167
+ }
168
+ return pids;
169
+ }
170
+
171
+ /** Step 2: clean leftover browser processes for a deterministic launch. */
172
+ function cleanLeftoverProcesses(cfg, log) {
173
+ try {
174
+ const leftovers = findBrowserPids(cfg);
175
+ for (const { pid } of leftovers) {
176
+ for (const sig of ['SIGTERM', 'SIGKILL']) {
177
+ try {
178
+ process.kill(pid, sig);
179
+ break;
180
+ } catch (e) {
181
+ /* already dead */
182
+ }
183
+ }
184
+ }
185
+ if (leftovers.length)
186
+ log(`ohos-cdp: cleaned ${leftovers.length} leftover browser process(es)`);
187
+ } catch (e) {
188
+ log(`ohos-cdp: WARNING leftover-process cleanup failed: ${e.message}`);
189
+ }
190
+ }
191
+
192
+ /**
193
+ * Step 3: start the browser via ohos-aa with CDP flags, validating that the
194
+ * CLI reports {"status": "success"}.
195
+ */
196
+ function startBrowserViaAa(cfg, log) {
197
+ const cmdArgs = `--remote-debugging-port=${cfg.port} --no-first-run --disable-extensions`;
198
+ const args = [
199
+ 'start',
200
+ '--bundlename', cfg.bundleName,
201
+ '--abilityname', cfg.abilityName,
202
+ '--ps', JSON.stringify({ cmdArgs })
203
+ ];
204
+ const res = runTool(cfg.aaPath, args, 'OHOS_AA');
205
+ const out = `${res.stdout || ''}\n${res.stderr || ''}`.trim();
206
+ let status = null;
207
+ try {
208
+ const json = JSON.parse(out);
209
+ status = json.status || null;
210
+ } catch (e) {
211
+ status = out.includes('"success"') ? 'success' : null;
212
+ }
213
+ if (status !== 'success') {
214
+ throw new OhosCdpError('OHOS_AA_START_FAILED',
215
+ `"${cfg.aaPath} start --bundlename ${cfg.bundleName}" did not report success ` +
216
+ `(status=${JSON.stringify(status)}, exit=${res.status}). Output: ${out.slice(0, 500)}`);
217
+ }
218
+ log(`ohos-cdp: ohos-aa start ok (${cfg.bundleName}/${cfg.abilityName}, port ${cfg.port})`);
219
+ }
220
+
221
+ /** Step 4: resolve the browser PID from local `ps -ef`. */
222
+ function findBrowserPid(cfg, log) {
223
+ const matches = findBrowserPids(cfg);
224
+ if (!matches.length) {
225
+ log('ohos-cdp: WARNING could not resolve browser PID from ps -ef; kill() will rely on ohos-aa force-stop only');
226
+ return null;
227
+ }
228
+ const pid = matches[matches.length - 1].pid;
229
+ log(`ohos-cdp: browser pid=${pid}`);
230
+ return pid;
231
+ }
232
+
233
+ function fetchJson(url, timeoutMs) {
234
+ return new Promise((resolve, reject) => {
235
+ const req = http.get(url, { timeout: timeoutMs }, (resp) => {
236
+ let body = '';
237
+ resp.setEncoding('utf8');
238
+ resp.on('data', (chunk) => { body += chunk; });
239
+ resp.on('end', () => {
240
+ if (resp.statusCode !== 200) {
241
+ reject(new OhosCdpError('OHOS_CDP_ENDPOINT_BAD_STATUS',
242
+ `HTTP ${resp.statusCode} from ${url}`));
243
+ return;
244
+ }
245
+ try {
246
+ resolve(JSON.parse(body));
247
+ } catch (e) {
248
+ reject(new OhosCdpError('OHOS_CDP_ENDPOINT_BAD_RESPONSE',
249
+ `non-JSON response from ${url}: ${body.slice(0, 200)}`));
250
+ }
251
+ });
252
+ });
253
+ req.on('timeout', () => {
254
+ req.destroy();
255
+ reject(new OhosCdpError('OHOS_CDP_ENDPOINT_TIMEOUT', `request timeout for ${url}`));
256
+ });
257
+ req.on('error', (e) => {
258
+ reject(new OhosCdpError('OHOS_CDP_ENDPOINT_UNREACHABLE',
259
+ `cannot reach ${url}: ${e.message}`));
260
+ });
261
+ });
262
+ }
263
+
264
+ /**
265
+ * Fast-path probe: single short-timeout fetch of /json/version. Resolves with
266
+ * the version object (when the endpoint already answers and carries a
267
+ * webSocketDebuggerUrl) or rejects with an OhosCdpError.
268
+ */
269
+ async function probeCdpEndpoint(cfg) {
270
+ const url = `http://${cfg.host}:${cfg.port}/json/version`;
271
+ const version = await fetchJson(url, cfg.attachProbeMs);
272
+ if (version && version.webSocketDebuggerUrl)
273
+ return version;
274
+ throw new OhosCdpError('OHOS_CDP_ENDPOINT_BAD_RESPONSE',
275
+ `/json/version at ${url} has no webSocketDebuggerUrl`);
276
+ }
277
+
278
+ /** Step 5: poll http://127.0.0.1:<port>/json/version until the CDP endpoint answers. */
279
+ async function waitForCdpEndpoint(cfg, log) {
280
+ const url = `http://${cfg.host}:${cfg.port}/json/version`;
281
+ const deadline = Date.now() + cfg.startTimeout;
282
+ let lastError = null;
283
+ while (Date.now() < deadline) {
284
+ try {
285
+ const version = await fetchJson(url, 2000);
286
+ if (version && version.webSocketDebuggerUrl) {
287
+ log(`ohos-cdp: CDP endpoint ready (browser: ${version.Browser || 'unknown'})`);
288
+ return version;
289
+ }
290
+ lastError = new OhosCdpError('OHOS_CDP_ENDPOINT_BAD_RESPONSE',
291
+ `/json/version at ${url} has no webSocketDebuggerUrl`);
292
+ } catch (e) {
293
+ lastError = e;
294
+ }
295
+ await new Promise((r) => setTimeout(r, 250));
296
+ }
297
+ throw new OhosCdpError('OHOS_CDP_ENDPOINT_TIMEOUT',
298
+ `CDP endpoint ${url} not ready within ${cfg.startTimeout}ms: ${lastError ? lastError.message : 'no response'}`);
299
+ }
300
+
301
+ /**
302
+ * Stop the browser: `ohos-aa force-stop` first; per device quirks it may
303
+ * report status:failed without killing the process, so fall back to
304
+ * `kill -9 <pid>`.
305
+ */
306
+ async function stopBrowser(cfg, pid, log) {
307
+ let stopped = false;
308
+ try {
309
+ const res = runTool(cfg.aaPath, ['force-stop', '--bundlename', cfg.bundleName], 'OHOS_AA');
310
+ const out = `${res.stdout || ''}\n${res.stderr || ''}`.trim();
311
+ let ok = out.includes('"success"');
312
+ if (!ok) {
313
+ try {
314
+ ok = JSON.parse(out).status === 'success';
315
+ } catch (e) { /* keep */ }
316
+ }
317
+ if (ok) {
318
+ stopped = true;
319
+ } else if (!findBrowserPids(cfg).length) {
320
+ // force-stop reported failure but the process is gone — success.
321
+ stopped = true;
322
+ } else {
323
+ log(`ohos-cdp: WARNING ohos-aa force-stop did not stop the browser (${out.slice(0, 200)}); falling back to kill -9`);
324
+ }
325
+ } catch (e) {
326
+ log(`ohos-cdp: WARNING ohos-aa force-stop failed: ${e.message}${e.deferredToHap ? ' — using kill -9 fallback' : ''}`);
327
+ }
328
+ if (!stopped && pid) {
329
+ try {
330
+ process.kill(pid, 'SIGKILL');
331
+ stopped = true;
332
+ log(`ohos-cdp: killed browser pid=${pid} (SIGKILL fallback)`);
333
+ } catch (e) {
334
+ log(`ohos-cdp: WARNING kill -9 ${pid} failed: ${e.message}`);
335
+ }
336
+ }
337
+ return stopped;
338
+ }
339
+
340
+ /**
341
+ * A child_process-like object so that playwright's `browser.close()` /
342
+ * `browser.process()` surfaces map onto the launch mode:
343
+ *
344
+ * - attached === false (launcher mode, ohos-aa start): kill()/close() map
345
+ * onto `ohos-aa force-stop` with a `kill -9` fallback.
346
+ * - attached === true (fast-path attach to a pre-existing, system-shared
347
+ * browser): kill()/close() must NOT stop the browser — they only mark
348
+ * the pseudo process killed and emit `exit`; the CDP connection itself
349
+ * is disconnected by the caller through the original browserProcess.
350
+ */
351
+ function createMockProcess(cfg, pid, log, attached = false) {
352
+ class OhosMockProcess extends EventEmitter {
353
+ constructor() {
354
+ super();
355
+ this.pid = pid;
356
+ this.spawnargs = [cfg.bundleName];
357
+ this.killed = false;
358
+ this.attached = attached;
359
+ }
360
+ async _stop() {
361
+ this.killed = true;
362
+ if (this.attached) {
363
+ log('ohos-cdp: attached to pre-existing browser — not stopping it');
364
+ try {
365
+ this.emit('exit', 0, null);
366
+ } catch (e) { /* listener errors must not break close() */ }
367
+ return true;
368
+ }
369
+ const ok = await stopBrowser(cfg, pid, log);
370
+ try {
371
+ this.emit('exit', 0, null);
372
+ } catch (e) { /* listener errors must not break close() */ }
373
+ return ok;
374
+ }
375
+ kill() { return this._stop(); }
376
+ async close() { return this._stop(); }
377
+ }
378
+ return new OhosMockProcess();
379
+ }
380
+
381
+ /**
382
+ * Bring up a CDP-capable on-device browser and resolve the CDP endpoint.
383
+ *
384
+ * Fast-path first: when the CDP endpoint at http://<host>:<port>/json/version
385
+ * already answers within `attachProbeMs` (default 2500ms, env
386
+ * OHOS_CDP_ATTACH_PROBE_MS, 0 disables), attach to the pre-existing browser
387
+ * without any ohos-bm / ohos-aa interaction and return `attached: true`.
388
+ * Otherwise fall through to the original ohos-aa launch path
389
+ * (verifyBrowserInstalled → cleanLeftoverProcesses → startBrowserViaAa →
390
+ * findBrowserPid → waitForCdpEndpoint) and return `attached: false`.
391
+ *
392
+ * @returns {{wsUrl: string, pid: number|null, mockProcess: object,
393
+ * browserVersion: string, endpoint: string, attached: boolean}}
394
+ */
395
+ async function launchViaOhosAa(opts = {}) {
396
+ const cfg = config(opts);
397
+ const log = opts.log || (() => {});
398
+ const endpoint = `http://${cfg.host}:${cfg.port}`;
399
+
400
+ if (cfg.attachProbeMs !== 0) {
401
+ try {
402
+ const version = await probeCdpEndpoint(cfg);
403
+ // Pre-existing browser is serving CDP — attach. PID resolution from
404
+ // `ps -ef` is best-effort (may be null); no ohos-bm verify, no
405
+ // leftover cleanup, no ohos-aa call happens in this mode.
406
+ const pid = findBrowserPid(cfg, log);
407
+ log(`ohos-cdp: CDP endpoint already serving (browser: ${version.Browser || 'unknown'}) — attaching without ohos-aa start`);
408
+ const mockProcess = createMockProcess(cfg, pid, log, true);
409
+ return {
410
+ wsUrl: version.webSocketDebuggerUrl,
411
+ pid,
412
+ mockProcess,
413
+ browserVersion: version.Browser || 'unknown',
414
+ endpoint,
415
+ attached: true
416
+ };
417
+ } catch (e) {
418
+ log(`ohos-cdp: no pre-existing CDP endpoint at ${endpoint}/json/version (${e.code || 'ERROR'}: ${e.message}) — starting browser "${cfg.browser}" (${cfg.bundleName}) via ${cfg.aaPath}`);
419
+ }
420
+ } else {
421
+ log(`ohos-cdp: fast-path attach disabled (attachProbeMs=0) — starting browser "${cfg.browser}" (${cfg.bundleName}) via ${cfg.aaPath}`);
422
+ }
423
+
424
+ verifyBrowserInstalled(cfg, log);
425
+ cleanLeftoverProcesses(cfg, log);
426
+ startBrowserViaAa(cfg, log);
427
+ const pid = findBrowserPid(cfg, log);
428
+ const version = await waitForCdpEndpoint(cfg, log);
429
+ const mockProcess = createMockProcess(cfg, pid, log, false);
430
+ return {
431
+ wsUrl: version.webSocketDebuggerUrl,
432
+ pid,
433
+ mockProcess,
434
+ browserVersion: version.Browser || 'unknown',
435
+ endpoint,
436
+ attached: false
437
+ };
438
+ }
439
+
440
+ module.exports = {
441
+ OhosCdpError,
442
+ BROWSER_PROFILES,
443
+ config,
444
+ launchViaOhosAa,
445
+ verifyBrowserInstalled,
446
+ cleanLeftoverProcesses,
447
+ startBrowserViaAa,
448
+ findBrowserPid,
449
+ probeCdpEndpoint,
450
+ waitForCdpEndpoint,
451
+ stopBrowser,
452
+ createMockProcess
453
+ };
@@ -1,35 +1,60 @@
1
1
  /**
2
2
  * OpenHarmony platform patch for playwright-core (idempotent, anchor based).
3
3
  *
4
- * playwright-core@1.61.x-1.63.x have no "openharmony" entry in their platform
5
- * registry:
6
- * - utils/hostPlatform.ts calculatePlatform() returns hostPlatform "<unknown>"
7
- * - cache-directory helpers throw `Unsupported platform: openharmony` at module
8
- * init (lib/coreBundle.js defaultCacheDirectory etc.), which breaks both
9
- * @playwright/browser-chromium install.js and browserType.launch().
4
+ * playwright-core@1.65.1 has no "openharmony" entry in its platform registry
5
+ * (single-bundle layout: everything relevant lives in lib/coreBundle.js):
6
+ * - packages/utils/hostPlatform.ts calculatePlatform() is inlined at ~:9452
7
+ * and returns hostPlatform "<unknown>" for openharmony;
8
+ * - computeDefaultCacheDirectory (~:34362) and computeDefaultCacheDirectory2
9
+ * (~:54253, the inlined serverRegistry copy) throw
10
+ * `Unsupported platform: openharmony` at module init, which breaks both
11
+ * @playwright/browser-chromium install.js and `require('playwright-core')`
12
+ * (defaultCacheDirectory -> defaultRegistryDirectory -> registry init).
10
13
  *
11
- * This patch (v1):
12
- * 1. treats process.platform === "openharmony" like "linux" in all platform checks
13
- * 2. maps hostPlatform for openharmony to "debian12-<arch>" (-> shortPlatform
14
- * "linux-arm64", whose chromium builds are the ones usable via the ohos-shim)
14
+ * This patch (v3, ported from the 1.61.1 precedent @ohos-ports/
15
+ * playwright-browser-chromium@1.61.1-beta.1 patch-playwright-core.js v2):
16
+ * 1. treats process.platform === "openharmony" like "linux" in all platform
17
+ * checks (cache dirs, daemon dirs, ...) — both computeDefaultCacheDirectory
18
+ * occurrences and computeBaseDaemonDir are covered by this transform
19
+ * 2. maps hostPlatform for openharmony to "debian12-<arch>" (registry /
20
+ * cache-directory compatibility only — chromium.launch() never picks
21
+ * the debian12 linux artifact, it goes through the CDP adapter)
15
22
  * 3. honours CHROMIUM_PATH as a default executablePath on openharmony
16
- * 4. injects the ohos-shim LD_PRELOAD/LD_LIBRARY_PATH env into launched browsers
23
+ * (native launch path has priority when it points to an executable)
24
+ * 4. injects the ohos-shim LD_PRELOAD/LD_LIBRARY_PATH env into launched
25
+ * browsers
26
+ * 5. chromium.launch() interception on openharmony (BrowserType.launch at
27
+ * ~:41480): when CHROMIUM_PATH does not point to an executable, route the
28
+ * launch through the ohos-cdp launcher — fast-path attach to an
29
+ * already-serving CDP endpoint (e.g. the Haitai browser started by the
30
+ * hap desktop) or device-local `ohos-aa` start — and connect with
31
+ * playwright-core's own chromium.connectOverCDP(wsUrl). browser.close()
32
+ * in attach mode only disconnects (shared system browser is never
33
+ * stopped); in launcher mode it maps to `ohos-aa force-stop` with a
34
+ * `kill -9` fallback (mockProcess)
35
+ * 6. coordinate rounding for the Haitai browser, which returns fractional
36
+ * coordinates: Math.round() in quadToRect() (~:21298) /
37
+ * quadMiddlePoint() (~:21311) / ElementHandle.boundingBox() (~:22112)
38
+ * (openharmony only)
17
39
  *
18
- * Anchors are written as regexes covering both the 1.61 bundle layout
19
- * (executablePath destructure in _prepareToLaunch) and the 1.63 layout
20
- * (resolveExecutablePath).
40
+ * Anchors for _prepareToLaunch cover both the 1.61 bundle layout (Variant A:
41
+ * executablePath destructure) and the 1.63+/1.65 layout (Variant B:
42
+ * resolveExecutablePath); the calculatePlatform anchor covers both the
43
+ * 1.61-style parenthesised call and the 1.65-style plain call. Anchors that
44
+ * cannot be found fail loudly with the file name and the anchor text.
21
45
  *
22
- * Idempotent: a `__ohosPlatformPatch__` marker prevents double application.
46
+ * Idempotency: a `__ohosPlatformPatch__ v3` marker is appended once the full
47
+ * transform set has been applied; an already-marked bundle is skipped.
23
48
  */
24
49
  'use strict';
25
50
 
26
51
  const fs = require('fs');
27
52
  const path = require('path');
28
53
 
29
- const MARKER = '/* __ohosPlatformPatch__ v1 */';
54
+ const MARKER_V3 = '/* __ohosPlatformPatch__ v3 */';
30
55
 
31
56
  const HELPERS = `
32
- // __ohosPlatformPatch__ v1: OHOS shim env injection helpers
57
+ // __ohosPlatformPatch__ v3: OHOS shim env injection helpers
33
58
  function ohosShimAssets(executable) {
34
59
  if (process.platform !== "openharmony")
35
60
  return null;
@@ -72,84 +97,315 @@ function amendOhosShimEnv(env, executable) {
72
97
  }
73
98
  `;
74
99
 
100
+ /**
101
+ * CDP adapter helpers, appended to the module scope of lib/coreBundle.js.
102
+ * __OHOS_CDP_LAUNCHER_PATH__ is replaced with the JSON-encoded absolute path
103
+ * of this package's scripts/ohos-cdp-launcher.js at apply() time.
104
+ */
105
+ const HELPERS_CDP_TEMPLATE = `
106
+ // __ohosPlatformPatch__ v3: ohos CDP adaptation helpers (Haitai browser)
107
+ const OHOS_CDP_LAUNCHER_PATH = __OHOS_CDP_LAUNCHER_PATH__;
108
+ function ohosRequireCdpLauncher() {
109
+ const pathMod = require("path");
110
+ const fsMod = require("fs");
111
+ const candidates = [];
112
+ if (process.env.OHOS_CDP_LAUNCHER)
113
+ candidates.push(process.env.OHOS_CDP_LAUNCHER);
114
+ if (OHOS_CDP_LAUNCHER_PATH)
115
+ candidates.push(OHOS_CDP_LAUNCHER_PATH);
116
+ try {
117
+ const corePkgPath = require.resolve("playwright-core/package.json");
118
+ let dir = pathMod.dirname(pathMod.dirname(corePkgPath));
119
+ while (dir && dir !== pathMod.dirname(dir)) {
120
+ if (pathMod.basename(dir) === "node_modules") {
121
+ candidates.push(pathMod.join(dir, "@ohos-ports", "playwright-browser-chromium", "scripts", "ohos-cdp-launcher.js"));
122
+ candidates.push(pathMod.join(dir, "@playwright", "browser-chromium", "scripts", "ohos-cdp-launcher.js"));
123
+ }
124
+ dir = pathMod.dirname(dir);
125
+ }
126
+ } catch (e) {
127
+ }
128
+ for (const candidate of candidates) {
129
+ try {
130
+ if (fsMod.existsSync(candidate))
131
+ return require(candidate);
132
+ } catch (e) {
133
+ }
134
+ }
135
+ const notFound = new Error("playwright-browser-chromium (ohos-ports): ohos-cdp-launcher module not found; set OHOS_CDP_LAUNCHER to its path");
136
+ notFound.code = "OHOS_CDP_LAUNCHER_NOT_FOUND";
137
+ throw notFound;
138
+ }
139
+ async function ohosCdpAdaptedLaunch(browserType, progress2, options, protocolLogger) {
140
+ const fsMod = require("fs");
141
+ const chromiumPath = process.env.CHROMIUM_PATH;
142
+ if (chromiumPath) {
143
+ let nativeExecutable = false;
144
+ try {
145
+ const st = fsMod.statSync(chromiumPath);
146
+ nativeExecutable = st.isFile() && (st.mode & 0o111) !== 0;
147
+ } catch (e) {
148
+ }
149
+ if (nativeExecutable)
150
+ return void 0;
151
+ }
152
+ const launcher = ohosRequireCdpLauncher();
153
+ let info;
154
+ try {
155
+ info = await launcher.launchViaOhosAa({ log: (m) => progress2.log(m) });
156
+ } catch (e) {
157
+ const code = e && e.code ? e.code : "OHOS_CDP_LAUNCH_FAILED";
158
+ const deferred = e && e.deferredToHap;
159
+ const err = new Error(
160
+ "playwright-browser-chromium (ohos-ports): failed to reach a CDP-capable browser via the ohos CDP adapter [" + code + "]: " +
161
+ ((e && e.message) || String(e)) +
162
+ (deferred ? " (ohos-aa requires weak-sandbox permission and is denied from a headless CLI; live CDP round-trips must be verified inside a hap environment)" : ""));
163
+ err.code = code;
164
+ err.deferredToHap = deferred;
165
+ err.cause = e;
166
+ throw err;
167
+ }
168
+ const browser = await browserType.connectOverCDP(progress2, {
169
+ endpointURL: info.wsUrl,
170
+ slowMo: options.slowMo,
171
+ timeout: options.timeout
172
+ });
173
+ const originalBrowserProcess = browser.options.browserProcess;
174
+ const mockProcess = info.mockProcess;
175
+ browser.options.browserProcess = {
176
+ pid: mockProcess.pid,
177
+ process: mockProcess,
178
+ close: async () => {
179
+ await mockProcess.close();
180
+ await originalBrowserProcess.close().catch(() => {
181
+ });
182
+ },
183
+ kill: async () => {
184
+ await mockProcess.kill();
185
+ await originalBrowserProcess.kill().catch(() => {
186
+ });
187
+ }
188
+ };
189
+ try {
190
+ browser.process = () => mockProcess;
191
+ } catch (e) {
192
+ }
193
+ progress2.log("<ohos-cdp> connected over CDP" + (info.attached ? " (attached to pre-existing browser" : "") + " (pid " + info.pid + ")" + (info.attached ? "; browser.close() will only disconnect, not stop the shared browser)" : ""));
194
+ return browser;
195
+ }
196
+ `;
197
+
198
+ // 1.65.1 bundles everything the package entry points need into
199
+ // lib/coreBundle.js; the 1.61.1 TARGET_FILES additions (serverRegistry.js,
200
+ // utilsBundle.js, tools/cli-client/registry.js) are not on the require path of
201
+ // require('playwright-core') / install.js in 1.65.1 and are NOT patched.
75
202
  const TARGET_FILES = [
76
- 'lib/coreBundle.js',
77
- 'lib/serverRegistry.js',
78
- 'lib/utilsBundle.js',
79
- 'lib/tools/cli-client/registry.js'
203
+ 'lib/coreBundle.js'
80
204
  ];
81
205
 
82
- function apply({ playwrightRoot, log = console.log } = {}) {
206
+ /** Anchor definitions: { [name]: anchor text or regex } for error reporting. */
207
+ const ANCHORS = {
208
+ hostPlatform: [
209
+ // Variant A (1.61.x bundle): parenthesised platform() call.
210
+ /\n const platform = (import_os(\d+)\.default\.platform\(\));\n if \(platform === "darwin"\) \{/,
211
+ // Variant B (1.63+/1.65 bundle): plain platform() call, e.g. import_os3.
212
+ /\n const platform = (import_os\d+)\.default\.platform\(\);\n if \(platform === "darwin"\) \{/
213
+ ],
214
+ prepareToLaunch: [
215
+ // Variant A (1.61.x): executablePath destructure in _prepareToLaunch.
216
+ /(const \{\n(\s+)ignoreDefaultArgs,\n\s+ignoreAllDefaultArgs,\n\s+args = \[\],\n\s+)executablePath = null(\n\s+\} = options;)/,
217
+ // Variant B (1.63.x/1.65.x): resolveExecutablePath in _prepareToLaunch.
218
+ /(let executable;\n(\s+))const customExecutablePath = await this\.resolveExecutablePath\(options\);/
219
+ ],
220
+ launchEnv: /(const env = options\.env \? envArrayToObject\(options\.env\) : process\.env;\n(\s+))const prepared = await progress2\.race\(this\._prepareToLaunch\(options, isPersistent, userDataDir\)\);/,
221
+ browserLaunch: [
222
+ ' async launch(progress2, options, protocolLogger) {\n' +
223
+ ' options = this._validateLaunchOptions(options);\n' +
224
+ ' const seleniumHubUrl = options.__testHookSeleniumRemoteURL || process.env.SELENIUM_REMOTE_URL;'
225
+ ],
226
+ quadToRect: 'function quadToRect(quad) {\n' +
227
+ ' let minX = Infinity;\n' +
228
+ ' let minY = Infinity;\n' +
229
+ ' let maxX = -Infinity;\n' +
230
+ ' let maxY = -Infinity;\n' +
231
+ ' for (const point of quad) {\n' +
232
+ ' minX = Math.min(minX, point.x);\n' +
233
+ ' minY = Math.min(minY, point.y);\n' +
234
+ ' maxX = Math.max(maxX, point.x);\n' +
235
+ ' maxY = Math.max(maxY, point.y);\n' +
236
+ ' }\n' +
237
+ ' return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n' +
238
+ '}',
239
+ quadMiddlePoint: 'function quadMiddlePoint(quad) {\n' +
240
+ ' const result2 = { x: 0, y: 0 };\n' +
241
+ ' for (const point of quad) {\n' +
242
+ ' result2.x += point.x / 4;\n' +
243
+ ' result2.y += point.y / 4;\n' +
244
+ ' }\n' +
245
+ ' return result2;\n' +
246
+ '}',
247
+ boundingBox: ' async boundingBox(progress2) {\n' +
248
+ ' return await progress2.race(this._page.delegate.getBoundingBox(this));\n' +
249
+ ' }'
250
+ };
251
+
252
+ function describeAnchor(anchor) {
253
+ if (anchor instanceof RegExp)
254
+ return String(anchor);
255
+ return JSON.stringify(anchor.length > 160 ? anchor.slice(0, 160) + '…' : anchor);
256
+ }
257
+
258
+ function findAnchor(src, name, variants) {
259
+ const list = Array.isArray(variants) ? variants : [variants];
260
+ for (const anchor of list) {
261
+ if (typeof anchor === 'string' ? src.includes(anchor) : anchor.test(src))
262
+ return anchor;
263
+ }
264
+ throw new Error(`patch-playwright-core: ${name} anchor not found in lib/coreBundle.js (unexpected playwright-core build); anchor: ${list.map(describeAnchor).join(' | ')}`);
265
+ }
266
+
267
+ /** Full v3 transform set. `src` must be a pristine coreBundle. */
268
+ function applyTransforms(src, launcherPath, rel) {
269
+ // 1) Generic: treat "openharmony" like "linux" everywhere (cache dirs,
270
+ // daemon dirs, ...). Covers computeDefaultCacheDirectory (~:34362),
271
+ // computeDefaultCacheDirectory2 (~:54253) and computeBaseDaemonDir
272
+ // (~:73739) — all use `process.platform === "linux"` first branches.
273
+ src = src.split('process.platform === "linux"')
274
+ .join('(process.platform === "linux" || process.platform === "openharmony")');
275
+
276
+ // 2) hostPlatform detection: openharmony -> debian12-<arch>.
277
+ // (registry / cache-directory compatibility only; chromium.launch() on
278
+ // openharmony goes through the CDP adapter and never downloads the
279
+ // debian12 linux artifact because of it.)
280
+ const hostA = ANCHORS.hostPlatform[0];
281
+ const hostB = ANCHORS.hostPlatform[1];
282
+ if (hostA.test(src)) {
283
+ src = src.replace(hostA,
284
+ '\n const platform = $1;\n' +
285
+ ' if (platform === "openharmony")\n' +
286
+ ' return { hostPlatform: "debian12-" + import_os$2.default.arch(), isOfficiallySupportedPlatform: false };\n' +
287
+ ' if (platform === "darwin") {');
288
+ } else if (hostB.test(src)) {
289
+ src = src.replace(hostB,
290
+ '\n const platform = $1.default.platform();\n' +
291
+ ' if (platform === "openharmony")\n' +
292
+ ' return { hostPlatform: "debian12-" + $1.default.arch(), isOfficiallySupportedPlatform: false };\n' +
293
+ ' if (platform === "darwin") {');
294
+ } else {
295
+ throw new Error(`patch-playwright-core: hostPlatform anchor not found in ${rel} (unexpected playwright-core build); anchor: ${describeAnchor(hostB)}`);
296
+ }
297
+
298
+ // 3) CHROMIUM_PATH as default executablePath on openharmony (native launch
299
+ // path has priority when it points to a real executable).
300
+ const prepA = ANCHORS.prepareToLaunch[0];
301
+ const prepB = ANCHORS.prepareToLaunch[1];
302
+ if (prepA.test(src)) {
303
+ src = src.replace(prepA,
304
+ '$1executablePath: optionExecutablePath = null$3\n' +
305
+ '$2let executablePath = optionExecutablePath;\n' +
306
+ '$2if (!executablePath && process.platform === "openharmony" && process.env.CHROMIUM_PATH)\n' +
307
+ '$2 executablePath = process.env.CHROMIUM_PATH;');
308
+ } else if (prepB.test(src)) {
309
+ src = src.replace(prepB,
310
+ '$1let customExecutablePath = await this.resolveExecutablePath(options);\n' +
311
+ '$2if (!customExecutablePath && process.platform === "openharmony" && process.env.CHROMIUM_PATH)\n' +
312
+ '$2 customExecutablePath = process.env.CHROMIUM_PATH;');
313
+ } else {
314
+ throw new Error(`patch-playwright-core: _prepareToLaunch anchor not found in ${rel} (unexpected playwright-core build); anchors: ${describeAnchor(prepA)} | ${describeAnchor(prepB)}`);
315
+ }
316
+
317
+ // 4) Inject ohos-shim env (LD_PRELOAD=sigsys_diag30.so, ...) into the
318
+ // browser process environment for every launched chromium.
319
+ const envAnchor = findAnchor(src, '_launchProcess env', ANCHORS.launchEnv);
320
+ src = src.replace(envAnchor,
321
+ '$1amendOhosShimEnv(env, options.executablePath || process.env.CHROMIUM_PATH || null);\n' +
322
+ '$2const prepared = await progress2.race(this._prepareToLaunch(options, isPersistent, userDataDir));');
323
+
324
+ // 5) Server-side BrowserType.launch interception. When running on
325
+ // openharmony with chromium, ohosCdpAdaptedLaunch() either returns a
326
+ // Browser connected over CDP (fast-path attach or ohos-aa start) or
327
+ // undefined to keep the native launch path (CHROMIUM_PATH executable).
328
+ const launchAnchor = findAnchor(src, 'BrowserType.launch', ANCHORS.browserLaunch);
329
+ src = src.replace(launchAnchor,
330
+ ' async launch(progress2, options, protocolLogger) {\n' +
331
+ ' if (process.platform === "openharmony" && this._name === "chromium") {\n' +
332
+ ' const ohosBrowser = await ohosCdpAdaptedLaunch(this, progress2, options, protocolLogger);\n' +
333
+ ' if (ohosBrowser !== void 0)\n' +
334
+ ' return ohosBrowser;\n' +
335
+ ' }\n' +
336
+ ' options = this._validateLaunchOptions(options);\n' +
337
+ ' const seleniumHubUrl = options.__testHookSeleniumRemoteURL || process.env.SELENIUM_REMOTE_URL;');
338
+
339
+ // 6) Haitai returns fractional coordinates: round the quad-derived box.
340
+ const rectAnchor = findAnchor(src, 'quadToRect', ANCHORS.quadToRect);
341
+ src = src.replace(rectAnchor, rectAnchor.replace(
342
+ ' return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };',
343
+ ' if (process.platform === "openharmony") {\n' +
344
+ ' /* __ohosPlatformPatch__ v3: Haitai browser reports fractional coordinates */\n' +
345
+ ' return { x: Math.round(minX), y: Math.round(minY), width: Math.round(maxX - minX), height: Math.round(maxY - minY) };\n' +
346
+ ' }\n' +
347
+ ' return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };'));
348
+
349
+ // 7) Round the middle point used for clicks.
350
+ const midAnchor = findAnchor(src, 'quadMiddlePoint', ANCHORS.quadMiddlePoint);
351
+ src = src.replace(midAnchor, midAnchor.replace(
352
+ ' return result2;',
353
+ ' if (process.platform === "openharmony") {\n' +
354
+ ' /* __ohosPlatformPatch__ v3: Haitai browser reports fractional coordinates */\n' +
355
+ ' result2.x = Math.round(result2.x);\n' +
356
+ ' result2.y = Math.round(result2.y);\n' +
357
+ ' }\n' +
358
+ ' return result2;'));
359
+
360
+ // 8) Round ElementHandle.boundingBox() results (some code paths bypass quads).
361
+ const bbAnchor = findAnchor(src, 'ElementHandle.boundingBox', ANCHORS.boundingBox);
362
+ src = src.replace(bbAnchor,
363
+ ' async boundingBox(progress2) {\n' +
364
+ ' const box = await progress2.race(this._page.delegate.getBoundingBox(this));\n' +
365
+ ' if (box && process.platform === "openharmony")\n' +
366
+ ' return { x: Math.round(box.x), y: Math.round(box.y), width: Math.round(box.width), height: Math.round(box.height) };\n' +
367
+ ' /* __ohosPlatformPatch__ v3: Haitai browser reports fractional coordinates */\n' +
368
+ ' return box;\n' +
369
+ ' }');
370
+
371
+ // 9) Helper functions (module scope of the bundle), with the absolute
372
+ // path of this package's ohos-cdp-launcher baked in.
373
+ const helpers = HELPERS_CDP_TEMPLATE.replace(
374
+ '__OHOS_CDP_LAUNCHER_PATH__',
375
+ JSON.stringify(launcherPath));
376
+ src = src.replace(/\n*$/, '\n') + HELPERS;
377
+ src = src.replace(/\n*$/, '\n') + helpers;
378
+ return src;
379
+ }
380
+
381
+ function apply({ playwrightRoot, launcherPath, log = console.log } = {}) {
83
382
  if (!playwrightRoot)
84
383
  throw new Error('patch-playwright-core: playwrightRoot is required');
384
+ const launcher = launcherPath || path.join(__dirname, 'ohos-cdp-launcher.js');
85
385
  const pkg = JSON.parse(fs.readFileSync(path.join(playwrightRoot, 'package.json'), 'utf8'));
86
386
  log(`ohos-patch: patching playwright-core@${pkg.version} at ${playwrightRoot}`);
87
387
  const changed = [];
88
388
  for (const rel of TARGET_FILES) {
89
389
  const file = path.join(playwrightRoot, rel);
90
- if (!fs.existsSync(file))
390
+ if (!fs.existsSync(file)) {
391
+ log(`ohos-patch: ${rel} not present in this playwright-core layout, skipping`);
91
392
  continue;
393
+ }
92
394
  let src = fs.readFileSync(file, 'utf8');
93
- if (src.includes('__ohosPlatformPatch__')) {
94
- log(`ohos-patch: ${rel} already patched, skipping`);
395
+ if (src.includes('__ohosPlatformPatch__ v3')) {
396
+ log(`ohos-patch: ${rel} already patched (v3), skipping`);
95
397
  continue;
96
398
  }
97
-
98
- // 1) Generic: treat "openharmony" like "linux" everywhere (cache dirs, spawn
99
- // behaviour, daemon dirs, cli registry, ...).
100
- src = src.split('process.platform === "linux"')
101
- .join('(process.platform === "linux" || process.platform === "openharmony")');
102
-
103
- if (rel === 'lib/coreBundle.js') {
104
- // 2) hostPlatform detection: openharmony -> debian12-<arch>
105
- // (shortPlatform resolves to linux-arm64, whose chromium builds run
106
- // on HarmonyOS through the ohos-shim). First occurrence = hostPlatform.ts.
107
- const hostRe = /\n const platform = (import_os(\d+)\.default\.platform\(\));\n if \(platform === "darwin"\) \{/;
108
- if (!hostRe.test(src))
109
- throw new Error(`patch-playwright-core: hostPlatform anchor not found in ${rel} (unexpected playwright-core build)`);
110
- src = src.replace(hostRe,
111
- '\n const platform = $1;\n' +
112
- ' if (platform === "openharmony")\n' +
113
- ' return { hostPlatform: "debian12-" + import_os$2.default.arch(), isOfficiallySupportedPlatform: false };\n' +
114
- ' if (platform === "darwin") {');
115
-
116
- // 3) CHROMIUM_PATH as default executablePath on openharmony.
117
- // Variant A (1.61.x): executablePath destructure in _prepareToLaunch.
118
- const prepA = /(const \{\n(\s+)ignoreDefaultArgs,\n\s+ignoreAllDefaultArgs,\n\s+args = \[\],\n\s+)executablePath = null(\n\s+\} = options;)/;
119
- // Variant B (1.63.x): resolveExecutablePath in _prepareToLaunch.
120
- const prepB = /(let executable;\n(\s+))const customExecutablePath = await this\.resolveExecutablePath\(options\);/;
121
- if (prepA.test(src)) {
122
- src = src.replace(prepA,
123
- '$1executablePath: optionExecutablePath = null$3\n' +
124
- '$2let executablePath = optionExecutablePath;\n' +
125
- '$2if (!executablePath && process.platform === "openharmony" && process.env.CHROMIUM_PATH)\n' +
126
- '$2 executablePath = process.env.CHROMIUM_PATH;');
127
- } else if (prepB.test(src)) {
128
- src = src.replace(prepB,
129
- '$1let customExecutablePath = await this.resolveExecutablePath(options);\n' +
130
- '$2if (!customExecutablePath && process.platform === "openharmony" && process.env.CHROMIUM_PATH)\n' +
131
- '$2 customExecutablePath = process.env.CHROMIUM_PATH;');
132
- } else {
133
- throw new Error(`patch-playwright-core: _prepareToLaunch anchor not found in ${rel} (unexpected playwright-core build)`);
134
- }
135
-
136
- // 4) Inject ohos-shim env (LD_PRELOAD=sigsys_diag30.so, ...) into the
137
- // browser process environment for every launched chromium.
138
- const envRe = /(const env = options\.env \? envArrayToObject\(options\.env\) : process\.env;\n(\s+))const prepared = await progress2\.race\(this\._prepareToLaunch\(options, isPersistent, userDataDir\)\);/;
139
- if (!envRe.test(src))
140
- throw new Error(`patch-playwright-core: _launchProcess env anchor not found in ${rel}`);
141
- src = src.replace(envRe,
142
- '$1amendOhosShimEnv(env, options.executablePath || process.env.CHROMIUM_PATH || null);\n' +
143
- '$2const prepared = await progress2.race(this._prepareToLaunch(options, isPersistent, userDataDir));');
144
-
145
- // 5) Helper functions (module scope of the bundle).
146
- src = src.replace(/\n*$/, '\n') + HELPERS;
399
+ if (src.includes('__ohosPlatformPatch__ v1') || src.includes('__ohosPlatformPatch__ v2')) {
400
+ // A bundle patched by the 1.61.1-era script cannot be v3-transformed
401
+ // in place; refuse rather than double-patching.
402
+ throw new Error(`patch-playwright-core: ${rel} carries a legacy v1/v2 marker from the 1.61.1-era patch; restore a pristine playwright-core before applying v3`);
147
403
  }
148
-
149
- src += '\n' + MARKER + '\n';
404
+ src = applyTransforms(src, launcher, rel);
405
+ src = src.replace(/\n*$/, '\n') + '\n' + MARKER_V3 + '\n';
150
406
  fs.writeFileSync(file, src);
151
407
  changed.push(rel);
152
- log(`ohos-patch: patched ${rel}`);
408
+ log(`ohos-patch: patched ${rel} (v3)`);
153
409
  }
154
410
  return changed;
155
411
  }
@@ -171,4 +427,4 @@ function ensureShimBinary(shimDir, log = console.log) {
171
427
  return null;
172
428
  }
173
429
 
174
- module.exports = { apply, ensureShimBinary, TARGET_FILES };
430
+ module.exports = { apply, ensureShimBinary, TARGET_FILES, MARKER_V3 };