ohos-playwright 0.2.13 → 0.3.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/dist/fixture.mjs CHANGED
@@ -1,9 +1,10 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { test as base, chromium } from '@playwright/test';
3
3
  import { INFO_PATH } from "./info-path.mjs";
4
- function readEndpoint() {
5
- return JSON.parse(readFileSync(INFO_PATH, 'utf8')).endpoint;
4
+ function readInfo() {
5
+ return JSON.parse(readFileSync(INFO_PATH, 'utf8'));
6
6
  }
7
+ function readEndpoint() { return readInfo().endpoint; }
7
8
  export const test = base.extend({
8
9
  browser: [
9
10
  async ({}, use) => {
@@ -46,7 +47,14 @@ export const test = base.extend({
46
47
  const pages = context.pages();
47
48
  if (pages.length === 0)
48
49
  throw new Error('No pages in ArkWeb CDP context. Open a tab first.');
49
- const page = pages.find((p) => p.url().startsWith('http://localhost')) ?? pages[0];
50
+ const info = readInfo();
51
+ // If globalSetup opened a fresh tab for the test, use it — this avoids
52
+ // disturbing user tabs that were open when the test suite started.
53
+ // The new tab is identified by its launchUrl (default: about:blank); if
54
+ // multiple tabs match, pick the last one (most recently opened).
55
+ const page = info.openedNewTab
56
+ ? ([...pages].reverse().find((p) => p.url() === (info.launchUrl ?? 'about:blank')) ?? pages[pages.length - 1])
57
+ : (pages.find((p) => p.url().startsWith('http://localhost')) ?? pages[0]);
50
58
  const ctxEmit = context.emit.bind(context);
51
59
  // Patch baseURL
52
60
  const baseURL = testInfo.project.use.baseURL;
@@ -134,6 +142,14 @@ export const test = base.extend({
134
142
  finally {
135
143
  clearInterval(popupPoller);
136
144
  page.evaluate = savedEvaluate;
145
+ // Close the tab we opened so the user's browser is left clean.
146
+ // page.close() sends Target.closeTarget via CDP; non-fatal if it fails.
147
+ if (info.openedNewTab) {
148
+ try {
149
+ await page.close();
150
+ }
151
+ catch { }
152
+ }
137
153
  }
138
154
  },
139
155
  emulateDevice: async ({ page }, use) => {
@@ -4,4 +4,6 @@ export interface CdpInfo {
4
4
  pid: number;
5
5
  socket: string;
6
6
  endpoint: string;
7
+ openedNewTab: boolean;
8
+ launchUrl: string;
7
9
  }
package/dist/setup.d.mts CHANGED
@@ -5,6 +5,7 @@ interface RetryOptions {
5
5
  }
6
6
  export declare function retry<T>(fn: () => T | Promise<T>, { max, interval, label }?: RetryOptions): Promise<T>;
7
7
  export declare function findBrowserPid(): number | null;
8
+ export declare function countCdpPages(listJson: string): number;
8
9
  export declare function hasDeviceConnected(): boolean;
9
10
  export declare function discoverDevices(): string[];
10
11
  export declare function tryLocalDevice(): boolean;
package/dist/setup.mjs CHANGED
@@ -115,9 +115,9 @@ function setupForward(port, socketName) {
115
115
  catch { }
116
116
  hdc(['fport', 'tcp:' + port, 'localabstract:' + socketName]);
117
117
  }
118
- function probeCdp(port) {
118
+ function cdpGet(port, path) {
119
119
  return new Promise((res) => {
120
- const req = http.get(`http://127.0.0.1:${port}/json/version`, (r) => {
120
+ const req = http.get(`http://127.0.0.1:${port}${path}`, (r) => {
121
121
  let b = '';
122
122
  r.on('data', (c) => (b += c));
123
123
  r.on('end', () => res({ ok: r.statusCode === 200, body: b }));
@@ -126,6 +126,16 @@ function probeCdp(port) {
126
126
  req.setTimeout(2000, () => { req.destroy(); res({ ok: false, err: 'TIMEOUT' }); });
127
127
  });
128
128
  }
129
+ function probeCdp(port) { return cdpGet(port, '/json/version'); }
130
+ export function countCdpPages(listJson) {
131
+ try {
132
+ const targets = JSON.parse(listJson);
133
+ return targets.filter((t) => t.type === 'page').length;
134
+ }
135
+ catch {
136
+ return 0;
137
+ }
138
+ }
129
139
  const IP_PORT_RE = /^(\d{1,3}\.){3}\d{1,3}:\d+$/;
130
140
  function listTargets() { return hdc(['list', 'targets']); }
131
141
  export function hasDeviceConnected() {
@@ -282,6 +292,7 @@ export default async function globalSetup() {
282
292
  console.log(`[ohos-playwright] locating ${BUNDLE}...`);
283
293
  // Batch ps + /proc/net/unix into a single hdc call.
284
294
  let pid = findBrowserPid();
295
+ const browserWasRunning = !!pid;
285
296
  if (!pid) {
286
297
  console.log('[ohos-playwright] browser not running, launching...');
287
298
  launchBrowser();
@@ -307,7 +318,23 @@ export default async function globalSetup() {
307
318
  throw new Error(`CDP response is not valid JSON (body preview: ${probe.body?.slice(0, 300) ?? '(empty)'})`);
308
319
  }
309
320
  console.log(`[ohos-playwright] CDP ready: ${info.Browser}`);
321
+ // If browser was already running with user tabs, open a fresh tab so tests
322
+ // don't disturb the user's browsing session.
323
+ let openedNewTab = false;
324
+ if (browserWasRunning) {
325
+ const listBefore = await cdpGet(port, '/json/list');
326
+ const countBefore = countCdpPages(listBefore.body ?? '[]');
327
+ if (countBefore > 0) {
328
+ launchBrowser();
329
+ console.log(`[ohos-playwright] opened new tab (${countBefore} existing page(s))`);
330
+ await retry(async () => {
331
+ const r = await cdpGet(port, '/json/list');
332
+ return countCdpPages(r.body ?? '[]') > countBefore ? true : null;
333
+ }, { max: 10, interval: 500, label: 'new tab did not appear in CDP' });
334
+ openedNewTab = true;
335
+ }
336
+ }
310
337
  mkdirSync(dirname(INFO_PATH), { recursive: true });
311
- writeFileSync(INFO_PATH, JSON.stringify({ port, pid, socket, endpoint: `http://127.0.0.1:${port}` }, null, 2));
338
+ writeFileSync(INFO_PATH, JSON.stringify({ port, pid, socket, endpoint: `http://127.0.0.1:${port}`, openedNewTab, launchUrl: LAUNCH_URL }, null, 2));
312
339
  console.log(`[ohos-playwright] wrote ${INFO_PATH}`);
313
340
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ohos-playwright",
3
- "version": "0.2.13",
3
+ "version": "0.3.0",
4
4
  "description": "Playwright adapter for OpenHarmony / ArkWeb via hdc + CDP",
5
5
  "license": "MIT",
6
6
  "author": "social4hyq",