@9l/playwright 0.6.0-beta → 0.6.0-beta.2

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/targets.js CHANGED
@@ -1,13 +1,20 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TargetApp = exports.targetCapabilities = void 0;
3
+ exports.TargetApp = exports.targetCapabilities = exports.validTargetDiagnostic = exports.validTargetSetup = exports.TargetSetupError = void 0;
4
4
  exports.webTargetDriver = webTargetDriver;
5
5
  exports.createTargetTest = createTargetTest;
6
6
  const test_1 = require("@playwright/test");
7
7
  const promises_1 = require("node:timers/promises");
8
+ const node_crypto_1 = require("node:crypto");
8
9
  const protocol_1 = require("./protocol");
9
10
  const android_runtime_1 = require("./android-runtime");
10
- exports.targetCapabilities = ['open', 'reset', 'test-id', 'tap', 'fill', 'visible', 'text', 'state'];
11
+ const target_setup_1 = require("./target-setup");
12
+ var target_setup_2 = require("./target-setup");
13
+ Object.defineProperty(exports, "TargetSetupError", { enumerable: true, get: function () { return target_setup_2.TargetSetupError; } });
14
+ Object.defineProperty(exports, "validTargetSetup", { enumerable: true, get: function () { return target_setup_2.validTargetSetup; } });
15
+ Object.defineProperty(exports, "validTargetDiagnostic", { enumerable: true, get: function () { return target_setup_2.validTargetDiagnostic; } });
16
+ exports.targetCapabilities = ['open', 'reset', 'test-id', 'tap', 'fill', 'visible', 'text', 'state',
17
+ 'back', 'keyboard', 'scroll', 'tap-at', 'bounds', 'viewport', 'terminate', 'activate', 'screen-digest'];
11
18
  const defaultOperationMs = 5_000;
12
19
  const defaultAssertionMs = 5_000;
13
20
  const maxOperationMs = 60_000;
@@ -24,6 +31,10 @@ class TargetStopped extends Error {
24
31
  }
25
32
  }
26
33
  const stopped = (reason, cause) => new TargetStopped(reason, cause);
34
+ const recheckMs = 5_000;
35
+ // A closed metadata record; the reporter forwards it as one target_setup frame.
36
+ const attachSetup = (record) => test_1.test.info().attach('9l.target-setup', { body: Buffer.from(JSON.stringify(record)), contentType: target_setup_1.targetSetupType });
37
+ const attachDiagnostic = (record) => test_1.test.info().attach('9l.target-diagnostic', { body: Buffer.from(JSON.stringify(record)), contentType: target_setup_1.targetDiagnosticType });
27
38
  const boundedText = (value, max) => typeof value === 'string' && Buffer.byteLength(value) <= max;
28
39
  /** Deterministic shared operations; browser/device handles stay in the worker. */
29
40
  class TargetApp {
@@ -34,6 +45,7 @@ class TargetApp {
34
45
  busy = false;
35
46
  reason = 'canceled';
36
47
  closing;
48
+ diagnosed = false;
37
49
  externalAbort = () => this.stop('canceled');
38
50
  constructor(driver, expected, options) {
39
51
  this.driver = driver;
@@ -80,7 +92,35 @@ class TargetApp {
80
92
  }
81
93
  /** Permanently stop this session, including a pending mutation. */
82
94
  cancel() { this.stop('canceled'); }
83
- async perform(operation, body, timeoutMs = defaultOperationMs, maxTimeoutMs = maxOperationMs, deadlineReason = () => 'deadline') {
95
+ /** Opt-in failure diagnostics: ask the driver once per test, while it is
96
+ * still open, and attach only a validated record. Never changes the outcome. */
97
+ async diagnose(operation, reason, startedAt, point) {
98
+ // A released driver (an Android deadline or cancellation) still answers
99
+ // with what it knows; the driver decides what it can read.
100
+ if (this.diagnosed || !this.driver.diagnose)
101
+ return;
102
+ this.diagnosed = true;
103
+ // Bounded like the recheck: a hook still running at the bound is
104
+ // abandoned and its late record discarded, so the failure reports on time.
105
+ const bound = Math.min(this.options.deadlineMs, Date.now() + recheckMs);
106
+ const signal = AbortSignal.timeout(Math.max(1, bound - Date.now()));
107
+ const late = Symbol('late');
108
+ let record;
109
+ try {
110
+ record = await Promise.race([
111
+ this.driver.diagnose({ operation, reason, elapsedMs: Math.max(0, Date.now() - startedAt), ...(point ? { point } : {}) }, { signal, deadlineMs: bound }),
112
+ new Promise(resolve => signal.addEventListener('abort', () => resolve(late), { once: true })),
113
+ ]);
114
+ }
115
+ catch {
116
+ record = undefined;
117
+ }
118
+ if (record === late)
119
+ return;
120
+ if (record !== undefined && (0, target_setup_1.validTargetDiagnostic)(record))
121
+ await attachDiagnostic(record);
122
+ }
123
+ async perform(operation, body, timeoutMs = defaultOperationMs, maxTimeoutMs = maxOperationMs, deadlineReason = () => 'deadline', point) {
84
124
  // The SDK location marks this as a typed target step for the reporter.
85
125
  return test_1.test.step(`9l target ${operation}`, async () => {
86
126
  if (this.controller.signal.aborted)
@@ -95,6 +135,7 @@ class TargetApp {
95
135
  }
96
136
  this.busy = true;
97
137
  const deadlineMs = Math.min(this.options.deadlineMs, Date.now() + timeoutMs);
138
+ const startedAt = Date.now();
98
139
  const signal = this.controller.signal;
99
140
  const work = Promise.resolve().then(() => { signal.throwIfAborted(); return body({ signal, deadlineMs }); });
100
141
  let settled = false;
@@ -134,9 +175,24 @@ class TargetApp {
134
175
  // and the local cause. Neither crosses the engine bridge.
135
176
  if (!signal.aborted && Date.now() >= deadlineMs)
136
177
  expire();
137
- if (signal.aborted)
178
+ // The operation is over: its timer must not fire while diagnostics
179
+ // or a recheck run, or it would release the driver under them.
180
+ clearTimeout(timer);
181
+ if (signal.aborted) {
182
+ // The driver may already be released (an Android deadline closes
183
+ // it); the driver answers with what it still knows, or nothing.
184
+ await this.diagnose(operation, this.reason, startedAt, point);
138
185
  throw error instanceof TargetStopped ? error : stopped(this.reason, error);
186
+ }
187
+ if (error instanceof target_setup_1.TargetSetupError) {
188
+ // The driver classified the device/app state before the operation
189
+ // could establish anything about the application.
190
+ this.stop(`setup_${error.record.classification}`, false);
191
+ await attachSetup(error.record);
192
+ throw stopped(this.reason, error);
193
+ }
139
194
  this.stop(error instanceof TargetStopped ? error.reason : 'operation_failed', false);
195
+ await this.diagnose(operation, this.reason, startedAt, point);
140
196
  throw error instanceof TargetStopped ? error : stopped(this.reason, error);
141
197
  }
142
198
  finally {
@@ -155,41 +211,31 @@ class TargetApp {
155
211
  throw stopped('missing_android_runtime');
156
212
  await test_1.test.info().attach('9l.android-runtime', { body: Buffer.from(JSON.stringify(runtime)), contentType: android_runtime_1.androidRuntimeType });
157
213
  }
214
+ const recovered = this.driver.setup?.();
215
+ if (recovered !== undefined) {
216
+ if (!(0, target_setup_1.validTargetSetup)(recovered) || !recovered.recovery?.restored)
217
+ throw stopped('invalid_setup_record');
218
+ await attachSetup(recovered);
219
+ }
158
220
  }, options.timeoutMs ?? (this.driver.kind === 'android' ? 180_000 : undefined), this.driver.kind === 'android' ? 180_000 : maxOperationMs);
159
221
  }
160
222
  reset(options = {}) { return this.perform('reset', context => this.driver.reset(context), options.timeoutMs); }
161
- getByTestId(id) {
162
- const observe = async (context) => {
163
- if (!boundedText(id, 128) || !id || /[\x00-\x1f]/.test(id))
164
- throw stopped('invalid_test_id');
165
- const matches = await this.driver.observeTestId(id, context);
166
- context.signal.throwIfAborted();
167
- if (!Array.isArray(matches) || matches.length > 1)
168
- throw stopped('ambiguous_test_id');
169
- return matches[0];
170
- };
171
- const required = async (context) => {
172
- const handle = await observe(context);
173
- if (!handle)
174
- throw stopped('missing_test_id');
175
- return handle;
176
- };
177
- const assertion = (operation, check, timeoutMs = defaultAssertionMs) => {
178
- let observedFalse = false;
179
- return this.perform(operation, async (context) => {
180
- // A completed mismatch is an assertion failure at this polling bound,
181
- // even if a later read stalls. Without one, a deadline is inconclusive.
223
+ /** Poll a check to its bound. A completed false observation is an assertion
224
+ * failure even if a later read stalls; a bound reached before any completed
225
+ * check is a deadline; failed reads alone keep their own operation error.
226
+ * After a completed failure, the driver may reclassify the device state. */
227
+ async assertLoop(operation, attempt, timeoutMs = defaultAssertionMs) {
228
+ let observedFalse = false;
229
+ try {
230
+ return await this.perform(operation, async (context) => {
182
231
  const interval = Math.max(25, Math.ceil(timeoutMs / maxObservations));
183
- let last;
232
+ let last, slowest = 0;
184
233
  for (let poll = 0; poll < maxObservations; poll++) {
185
234
  context.signal.throwIfAborted();
235
+ const started = Date.now();
186
236
  try {
187
- const handle = await observe(context);
188
- if (handle) {
189
- if (await check(handle, context))
190
- return;
191
- }
192
- // A completed empty observation is also a failed assertion.
237
+ if (await attempt(context))
238
+ return;
193
239
  observedFalse = true;
194
240
  }
195
241
  catch (error) {
@@ -198,7 +244,13 @@ class TargetApp {
198
244
  throw error;
199
245
  last = error;
200
246
  }
201
- if (Date.now() + interval >= context.deadlineMs)
247
+ // Stop while the next observation, half again as slow as the slowest
248
+ // so far, would still finish in time. A last read that overran the
249
+ // bound would end the assertion by its deadline, which on Android
250
+ // releases the driver before diagnostics or the recheck can read
251
+ // the device; native read times vary on a loaded host.
252
+ slowest = Math.max(slowest, Date.now() - started);
253
+ if (Date.now() + interval + slowest * 1.5 >= context.deadlineMs)
202
254
  break;
203
255
  await (0, promises_1.setTimeout)(interval, undefined, { signal: context.signal });
204
256
  }
@@ -210,7 +262,119 @@ class TargetApp {
210
262
  throw last;
211
263
  throw stopped('deadline');
212
264
  }, timeoutMs, maxOperationMs, () => observedFalse ? 'assertion_failed' : 'deadline');
265
+ }
266
+ catch (error) {
267
+ // A completed mismatch on a device the driver can still read: ask it
268
+ // whether the device became unavailable (locked, screen off) during
269
+ // the readiness poll. A positive answer reclassifies the failure as
270
+ // setup; the assertion step stays failed and the test still fails.
271
+ if (!(error instanceof TargetStopped) || error.reason !== 'assertion_failed' || !this.driver.recheck || this.closing)
272
+ throw error;
273
+ // The hook gets a bounded signal; a stalled hook cannot keep the
274
+ // assertion pending, and a result after the bound, cancellation or
275
+ // close is discarded so it never rewrites the recorded failure.
276
+ const bound = Math.min(this.options.deadlineMs, Date.now() + recheckMs);
277
+ const signal = AbortSignal.timeout(Math.max(1, bound - Date.now()));
278
+ let record;
279
+ try {
280
+ record = await Promise.race([
281
+ this.driver.recheck({ signal, deadlineMs: bound }, { operation }),
282
+ new Promise(resolve => signal.addEventListener('abort', () => resolve(undefined), { once: true })),
283
+ ]);
284
+ }
285
+ catch {
286
+ record = undefined;
287
+ }
288
+ if (record === undefined || signal.aborted || this.closing)
289
+ throw error;
290
+ if (!(0, target_setup_1.validTargetSetup)(record) || record.stage !== 'recheck' || record.recovery)
291
+ throw error;
292
+ this.reason = `setup_${record.classification}`;
293
+ await attachSetup(record);
294
+ throw stopped(this.reason, error);
295
+ }
296
+ }
297
+ optional(name) {
298
+ const method = this.driver[name];
299
+ if (typeof method !== 'function')
300
+ throw stopped('unsupported_operation');
301
+ return method.bind(this.driver);
302
+ }
303
+ /** Platform back: Android's Back key, the browser's history. */
304
+ back(options = {}) { return this.perform('back', context => this.optional('back')(context), options.timeoutMs); }
305
+ /** Dismiss the software keyboard, keeping the selected input method. Android only. */
306
+ hideKeyboard(options = {}) { return this.perform('hide-keyboard', context => this.optional('hideKeyboard')(context), options.timeoutMs); }
307
+ /** Android only: assert the software keyboard is shown or hidden. */
308
+ toHaveKeyboard(visible, timeoutMs) {
309
+ if (typeof visible !== 'boolean')
310
+ return this.assertLoop('assert-keyboard', async () => { throw stopped('invalid_value'); }, timeoutMs);
311
+ return this.assertLoop('assert-keyboard', async (context) => await this.optional('keyboardShown')(context) === visible, timeoutMs);
312
+ }
313
+ /** One touch down/up at device coordinates, for example outside a pane.
314
+ * Coordinates are integers inside the viewport, checked against the
315
+ * driver's viewport when it reports one; nothing is retried. */
316
+ tapAt(point, options = {}) {
317
+ return this.perform('tap-at', async (context) => {
318
+ if (!validPoint(point))
319
+ throw stopped('invalid_point');
320
+ if (typeof this.driver.viewport === 'function') {
321
+ const size = await this.driver.viewport(context);
322
+ if (!validSize(size))
323
+ throw stopped('invalid_property');
324
+ if (point.x >= size.width || point.y >= size.height)
325
+ throw stopped('invalid_point');
326
+ }
327
+ await this.optional('tapAt')({ x: point.x, y: point.y }, context);
328
+ }, options.timeoutMs, maxOperationMs, () => 'deadline', validPoint(point) ? { x: point.x, y: point.y } : undefined);
329
+ }
330
+ viewport(options = {}) {
331
+ return this.perform('viewport', async (context) => {
332
+ const size = await this.optional('viewport')(context);
333
+ if (!validSize(size))
334
+ throw stopped('invalid_property');
335
+ return { width: size.width, height: size.height };
336
+ }, options.timeoutMs);
337
+ }
338
+ /** A digest of the active display's current image, for settling checks
339
+ * (two equal digests mean nothing moved). The image is never retained. */
340
+ screenDigest(options = {}) {
341
+ return this.perform('screen-digest', async (context) => {
342
+ const digest = await this.optional('screenDigest')(context);
343
+ if (typeof digest !== 'string' || !/^[a-f0-9]{64}$/.test(digest))
344
+ throw stopped('invalid_property');
345
+ return digest;
346
+ }, options.timeoutMs);
347
+ }
348
+ /** Stop the configured app without clearing its data. Android only. */
349
+ terminate(options = {}) { return this.perform('terminate', context => this.optional('terminate')(context), options.timeoutMs); }
350
+ /** Bring the configured app back to the foreground. Android only. */
351
+ activate(options = {}) { return this.perform('activate', context => this.optional('activate')(context), options.timeoutMs); }
352
+ getByTestId(id) {
353
+ const observe = async (context) => {
354
+ if (!boundedText(id, 128) || !id || /[\x00-\x1f]/.test(id))
355
+ throw stopped('invalid_test_id');
356
+ const matches = await this.driver.observeTestId(id, context);
357
+ context.signal.throwIfAborted();
358
+ if (!Array.isArray(matches) || matches.length > 1)
359
+ throw stopped('ambiguous_test_id');
360
+ // Only an empty observation is absence; a reported match without a
361
+ // handle (null, undefined, a hole) is malformed lookup evidence.
362
+ if (matches.length === 1 && (!(0 in matches) || typeof matches[0] !== 'object' || matches[0] === null))
363
+ throw stopped('invalid_property');
364
+ return matches[0];
365
+ };
366
+ const required = async (context) => {
367
+ const handle = await observe(context);
368
+ if (!handle)
369
+ throw stopped('missing_test_id');
370
+ return handle;
213
371
  };
372
+ // A missing control is a completed false observation, except for a
373
+ // hidden assertion, where absence is exactly what it asserts.
374
+ const assertion = (operation, check, timeoutMs, absent = false) => this.assertLoop(operation, async (context) => {
375
+ const handle = await observe(context);
376
+ return handle ? check(handle, context) : absent;
377
+ }, timeoutMs);
214
378
  return {
215
379
  tap: (options = {}) => this.perform('tap', async (context) => (await required(context)).tap(context), options.timeoutMs),
216
380
  fill: (value, options = {}) => this.perform('fill', async (context) => {
@@ -218,7 +382,29 @@ class TargetApp {
218
382
  throw stopped('invalid_value');
219
383
  await (await required(context)).fill(value, context);
220
384
  }, options.timeoutMs),
221
- toBeVisible: (timeoutMs) => assertion('assert-visible', (handle, context) => handle.visible(context), timeoutMs),
385
+ /** One bounded scroll gesture inside this control, by a fraction of its size. */
386
+ scroll: (direction, options = {}) => this.perform('scroll', async (context) => {
387
+ const percent = options.percent ?? 0.5;
388
+ if (!['up', 'down', 'left', 'right'].includes(direction) || typeof percent !== 'number' || !(percent > 0 && percent <= 1))
389
+ throw stopped('invalid_value');
390
+ const handle = await required(context);
391
+ if (typeof handle.scroll !== 'function')
392
+ throw stopped('unsupported_operation');
393
+ await handle.scroll(direction, percent, context);
394
+ }, options.timeoutMs),
395
+ /** The control's rectangle in device coordinates. */
396
+ bounds: (options = {}) => this.perform('bounds', async (context) => {
397
+ const handle = await required(context);
398
+ if (typeof handle.bounds !== 'function')
399
+ throw stopped('unsupported_operation');
400
+ const rect = await handle.bounds(context);
401
+ if (!validRect(rect))
402
+ throw stopped('invalid_property');
403
+ return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
404
+ }, options.timeoutMs),
405
+ toBeVisible: (timeoutMs) => assertion('assert-visible', async (handle, context) => await visibility(handle, context), timeoutMs),
406
+ /** Passes when the control is absent or not displayed. */
407
+ toBeHidden: (timeoutMs) => assertion('assert-hidden', async (handle, context) => !await visibility(handle, context), timeoutMs, true),
222
408
  toHaveText: (value, timeoutMs) => {
223
409
  if (!boundedText(value, 4096))
224
410
  return assertion('assert-text', async () => { throw stopped('invalid_value'); }, timeoutMs);
@@ -236,6 +422,21 @@ class TargetApp {
236
422
  }
237
423
  }
238
424
  exports.TargetApp = TargetApp;
425
+ // A driver's visibility answer counts only as a boolean: a missing or
426
+ // malformed return proves neither visible nor hidden.
427
+ const visibility = async (handle, context) => {
428
+ const visible = await handle.visible(context);
429
+ if (typeof visible !== 'boolean')
430
+ throw stopped('invalid_property');
431
+ return visible;
432
+ };
433
+ const coordinate = (value) => Number.isInteger(value) && value >= 0 && value <= 65_535;
434
+ // A rectangle origin may be negative: a control scrolled partly above or
435
+ // left of the viewport still has geometry. Tap coordinates and sizes do not.
436
+ const offset = (value) => Number.isInteger(value) && value >= -65_535 && value <= 65_535;
437
+ const validPoint = (value) => !!value && typeof value === 'object' && coordinate(value.x) && coordinate(value.y);
438
+ const validSize = (value) => !!value && typeof value === 'object' && coordinate(value.width) && coordinate(value.height) && value.width > 0 && value.height > 0;
439
+ const validRect = (value) => !!value && typeof value === 'object' && offset(value.x) && offset(value.y) && coordinate(value.width) && coordinate(value.height);
239
440
  const remaining = (context) => { context.signal.throwIfAborted(); return Math.max(1, context.deadlineMs - Date.now()); };
240
441
  function locatorHandle(locator) {
241
442
  // Strict locators re-resolve a replaced node (re-renders, hydration) but
@@ -246,6 +447,20 @@ function locatorHandle(locator) {
246
447
  visible: async (context) => { remaining(context); return locator.isVisible(); },
247
448
  text: async (context) => await locator.textContent({ timeout: remaining(context) }) ?? '',
248
449
  state: async (name, context) => name === 'enabled' ? locator.isEnabled({ timeout: remaining(context) }) : locator.isChecked({ timeout: remaining(context) }),
450
+ scroll: async (direction, percent, context) => {
451
+ remaining(context);
452
+ await locator.evaluate((element, { direction, percent }) => {
453
+ const dx = direction === 'left' ? -1 : direction === 'right' ? 1 : 0;
454
+ const dy = direction === 'up' ? -1 : direction === 'down' ? 1 : 0;
455
+ element.scrollBy({ left: dx * element.clientWidth * percent, top: dy * element.clientHeight * percent, behavior: 'instant' });
456
+ }, { direction, percent }, { timeout: remaining(context) });
457
+ },
458
+ bounds: async (context) => {
459
+ const box = await locator.boundingBox({ timeout: remaining(context) });
460
+ if (!box)
461
+ throw new Error('control has no box');
462
+ return { x: Math.round(box.x), y: Math.round(box.y), width: Math.round(box.width), height: Math.round(box.height) };
463
+ },
249
464
  };
250
465
  }
251
466
  /** Ordinary Playwright handles implement the web side of the shared contract. */
@@ -254,6 +469,15 @@ function webTargetDriver(page, appId, lifecycle) {
254
469
  version: protocol_1.targetVersion, capabilities: exports.targetCapabilities, kind: 'web', appId,
255
470
  open: context => lifecycle.open(page, context), reset: context => lifecycle.reset(page, context),
256
471
  close: () => page.close({ runBeforeUnload: false }),
472
+ back: async (context) => { await page.goBack({ timeout: remaining(context) }); },
473
+ tapAt: async (point, context) => { remaining(context); await page.mouse.click(point.x, point.y); },
474
+ viewport: async (context) => {
475
+ // viewport: null disables emulation; the page still has a real size.
476
+ remaining(context);
477
+ const size = page.viewportSize() ?? await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
478
+ return { width: Math.round(size.width), height: Math.round(size.height) };
479
+ },
480
+ screenDigest: async (context) => (0, node_crypto_1.createHash)('sha256').update(await page.screenshot({ timeout: remaining(context), animations: 'allow', caret: 'initial' })).digest('hex'),
257
481
  observeTestId: async (id, context) => {
258
482
  remaining(context);
259
483
  const locator = page.getByTestId(id);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@9l/playwright",
3
- "version": "0.6.0-beta",
3
+ "version": "0.6.0-beta.2",
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",
@@ -24,7 +24,7 @@
24
24
  "engines": {"node": ">=22"},
25
25
  "9l": {
26
26
  "protocol": "9l.engine/1",
27
- "capabilities": ["steps", "artifact-metadata", "terminal-outcomes"],
27
+ "capabilities": ["steps", "artifact-metadata", "terminal-outcomes", "declared-outcomes"],
28
28
  "faults": ["abort", "http-500", "empty-json", "http-401", "http-403", "http-429", "malformed-json", "redirect-cross-origin", "delay"]
29
29
  },
30
30
  "publishConfig": {"access": "public"}