@9l/playwright 0.6.0-beta.1 → 0.6.0-beta.3

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,29 +1,50 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TargetApp = exports.targetCapabilities = void 0;
3
+ exports.TargetApp = exports.controlPattern = 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',
18
+ 'foreground', 'device-serial', 'fingerprint'];
11
19
  const defaultOperationMs = 5_000;
12
20
  const defaultAssertionMs = 5_000;
13
21
  const maxOperationMs = 60_000;
22
+ // An emulator relaunches an app, clears its data or settles a cold start in
23
+ // tens of seconds: Android lifecycle operations default to a minute, and
24
+ // every Android operation and assertion accepts up to the open bound.
25
+ const androidLifecycleMs = 60_000;
26
+ const androidMaxMs = 180_000;
14
27
  const maxObservations = 200;
15
28
  // An operation is aborted and rejected at its deadline. If it is still pending
16
29
  // after this grace, the session closes its driver to cancel it.
17
30
  const settleMs = 250;
18
31
  const stepLocation = { file: protocol_1.targetStepFile, line: 1, column: 1 };
32
+ /** A test ID that names its control in the step title, and from there in
33
+ * receipts: an identifier, never free text. Other IDs (with spaces, `@` or
34
+ * other characters that could carry data) name no control. */
35
+ exports.controlPattern = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/;
19
36
  class TargetStopped extends Error {
20
37
  reason;
21
- constructor(reason, cause) {
22
- super(`9lives target stopped: ${reason}`, cause === undefined ? undefined : { cause });
38
+ constructor(reason, cause, detail) {
39
+ super(`9lives target stopped: ${reason}${detail ? ` (${detail})` : ''}`, cause === undefined ? undefined : { cause });
23
40
  this.reason = reason;
24
41
  }
25
42
  }
26
- const stopped = (reason, cause) => new TargetStopped(reason, cause);
43
+ const stopped = (reason, cause, detail) => new TargetStopped(reason, cause, detail);
44
+ const recheckMs = 5_000;
45
+ // A closed metadata record; the reporter forwards it as one target_setup frame.
46
+ const attachSetup = (record) => test_1.test.info().attach('9l.target-setup', { body: Buffer.from(JSON.stringify(record)), contentType: target_setup_1.targetSetupType });
47
+ const attachDiagnostic = (record) => test_1.test.info().attach('9l.target-diagnostic', { body: Buffer.from(JSON.stringify(record)), contentType: target_setup_1.targetDiagnosticType });
27
48
  const boundedText = (value, max) => typeof value === 'string' && Buffer.byteLength(value) <= max;
28
49
  /** Deterministic shared operations; browser/device handles stay in the worker. */
29
50
  class TargetApp {
@@ -34,6 +55,7 @@ class TargetApp {
34
55
  busy = false;
35
56
  reason = 'canceled';
36
57
  closing;
58
+ diagnosed = false;
37
59
  externalAbort = () => this.stop('canceled');
38
60
  constructor(driver, expected, options) {
39
61
  this.driver = driver;
@@ -80,9 +102,43 @@ class TargetApp {
80
102
  }
81
103
  /** Permanently stop this session, including a pending mutation. */
82
104
  cancel() { this.stop('canceled'); }
83
- async perform(operation, body, timeoutMs = defaultOperationMs, maxTimeoutMs = maxOperationMs, deadlineReason = () => 'deadline') {
84
- // The SDK location marks this as a typed target step for the reporter.
85
- return test_1.test.step(`9l target ${operation}`, async () => {
105
+ /** Opt-in failure diagnostics: ask the driver once per test, while it is
106
+ * still open, and attach only a validated record. Never changes the outcome. */
107
+ async diagnose(operation, reason, startedAt, point) {
108
+ // A released driver (an Android deadline or cancellation) still answers
109
+ // with what it knows; the driver decides what it can read.
110
+ if (this.diagnosed || !this.driver.diagnose)
111
+ return;
112
+ this.diagnosed = true;
113
+ // Bounded like the recheck: a hook still running at the bound is
114
+ // abandoned and its late record discarded, so the failure reports on time.
115
+ const bound = Math.min(this.options.deadlineMs, Date.now() + recheckMs);
116
+ const signal = AbortSignal.timeout(Math.max(1, bound - Date.now()));
117
+ const late = Symbol('late');
118
+ let record;
119
+ try {
120
+ record = await Promise.race([
121
+ this.driver.diagnose({ operation, reason, elapsedMs: Math.max(0, Date.now() - startedAt), ...(point ? { point } : {}) }, { signal, deadlineMs: bound }),
122
+ new Promise(resolve => signal.addEventListener('abort', () => resolve(late), { once: true })),
123
+ ]);
124
+ }
125
+ catch {
126
+ record = undefined;
127
+ }
128
+ if (record === late)
129
+ return;
130
+ if (record !== undefined && (0, target_setup_1.validTargetDiagnostic)(record))
131
+ await attachDiagnostic(record);
132
+ }
133
+ get maxMs() { return this.driver.kind === 'android' ? androidMaxMs : maxOperationMs; }
134
+ /** The stop reason for a bound that ran out: operation_timeout for the
135
+ * call's own bound, deadline for the attempt's (Go's worker deadline). */
136
+ boundReason(deadlineMs) { return deadlineMs < this.options.deadlineMs ? 'operation_timeout' : 'deadline'; }
137
+ async perform(operation, body, timeoutMs = defaultOperationMs, maxTimeoutMs = this.maxMs, deadlineReason = () => 'operation_timeout', point, control) {
138
+ // The SDK location marks this as a typed target step for the reporter;
139
+ // an identifier-shaped test ID after the operation names its control.
140
+ const named = control !== undefined && exports.controlPattern.test(control) ? ` ${control}` : '';
141
+ return test_1.test.step(`9l target ${operation}${named}`, async () => {
86
142
  if (this.controller.signal.aborted)
87
143
  throw stopped(this.reason);
88
144
  if (this.busy) {
@@ -90,11 +146,13 @@ class TargetApp {
90
146
  throw stopped(this.reason);
91
147
  }
92
148
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > maxTimeoutMs) {
149
+ // The accepted range is named locally; only the reason crosses the bridge.
93
150
  this.stop('invalid_timeout', false);
94
- throw stopped(this.reason);
151
+ throw stopped(this.reason, undefined, `accepted 1-${maxTimeoutMs} ms`);
95
152
  }
96
153
  this.busy = true;
97
154
  const deadlineMs = Math.min(this.options.deadlineMs, Date.now() + timeoutMs);
155
+ const startedAt = Date.now();
98
156
  const signal = this.controller.signal;
99
157
  const work = Promise.resolve().then(() => { signal.throwIfAborted(); return body({ signal, deadlineMs }); });
100
158
  let settled = false;
@@ -134,9 +192,24 @@ class TargetApp {
134
192
  // and the local cause. Neither crosses the engine bridge.
135
193
  if (!signal.aborted && Date.now() >= deadlineMs)
136
194
  expire();
137
- if (signal.aborted)
195
+ // The operation is over: its timer must not fire while diagnostics
196
+ // or a recheck run, or it would release the driver under them.
197
+ clearTimeout(timer);
198
+ if (signal.aborted) {
199
+ // The driver may already be released (an Android deadline closes
200
+ // it); the driver answers with what it still knows, or nothing.
201
+ await this.diagnose(operation, this.reason, startedAt, point);
138
202
  throw error instanceof TargetStopped ? error : stopped(this.reason, error);
203
+ }
204
+ if (error instanceof target_setup_1.TargetSetupError) {
205
+ // The driver classified the device/app state before the operation
206
+ // could establish anything about the application.
207
+ this.stop(`setup_${error.record.classification}`, false);
208
+ await attachSetup(error.record);
209
+ throw stopped(this.reason, error);
210
+ }
139
211
  this.stop(error instanceof TargetStopped ? error.reason : 'operation_failed', false);
212
+ await this.diagnose(operation, this.reason, startedAt, point);
140
213
  throw error instanceof TargetStopped ? error : stopped(this.reason, error);
141
214
  }
142
215
  finally {
@@ -155,9 +228,196 @@ class TargetApp {
155
228
  throw stopped('missing_android_runtime');
156
229
  await test_1.test.info().attach('9l.android-runtime', { body: Buffer.from(JSON.stringify(runtime)), contentType: android_runtime_1.androidRuntimeType });
157
230
  }
158
- }, options.timeoutMs ?? (this.driver.kind === 'android' ? 180_000 : undefined), this.driver.kind === 'android' ? 180_000 : maxOperationMs);
231
+ const recovered = this.driver.setup?.();
232
+ if (recovered !== undefined) {
233
+ if (!(0, target_setup_1.validTargetSetup)(recovered) || !recovered.recovery?.restored)
234
+ throw stopped('invalid_setup_record');
235
+ await attachSetup(recovered);
236
+ }
237
+ }, options.timeoutMs === undefined && this.driver.kind === 'android' ? androidMaxMs : options.timeoutMs);
238
+ }
239
+ // Defaults apply only to an omitted timeout; any other non-integer,
240
+ // including null, stops as invalid_timeout.
241
+ reset(options = {}) { return this.perform('reset', context => this.driver.reset(context), options.timeoutMs === undefined ? this.lifecycleMs : options.timeoutMs); }
242
+ get lifecycleMs() { return this.driver.kind === 'android' ? androidLifecycleMs : defaultOperationMs; }
243
+ /** Poll a check until it holds or the next read could overrun the bound.
244
+ * Held, or not held after at least one completed observation (with the
245
+ * last failed read, if any); failed reads alone throw their own error, and
246
+ * a bound reached before any completed read is a deadline. Ambiguity,
247
+ * invalid input and cancellation are never transient. */
248
+ async poll(context, attempt, timeoutMs, observations = maxObservations, falseSeen = () => { }, strict = false) {
249
+ const interval = Math.max(25, Math.ceil(timeoutMs / maxObservations));
250
+ let last, slowest = 0, observedFalse = false;
251
+ for (let poll = 0; poll < observations; poll++) {
252
+ context.signal.throwIfAborted();
253
+ const started = Date.now();
254
+ try {
255
+ if (await attempt(context))
256
+ return { held: true };
257
+ observedFalse = true;
258
+ falseSeen();
259
+ }
260
+ catch (error) {
261
+ // A query answers only from reads that completed: any failed read
262
+ // (a lost transport, a driver-level ambiguity) ends it.
263
+ if (strict || error instanceof TargetStopped || context.signal.aborted)
264
+ throw error;
265
+ last = error;
266
+ }
267
+ // Stop while the next observation, half again as slow as the slowest
268
+ // so far, would still finish in time. A last read that overran the
269
+ // bound would end the operation by its deadline, which on Android
270
+ // releases the driver before diagnostics or the recheck can read
271
+ // the device; native read times vary on a loaded host.
272
+ slowest = Math.max(slowest, Date.now() - started);
273
+ if (poll + 1 >= observations || Date.now() + interval + slowest * 1.5 >= context.deadlineMs)
274
+ break;
275
+ await (0, promises_1.setTimeout)(interval, undefined, { signal: context.signal });
276
+ }
277
+ if (observedFalse)
278
+ return { held: false, last };
279
+ // Failed reads alone establish nothing. Keep their operation failure
280
+ // distinct from an executed false comparison.
281
+ if (last !== undefined)
282
+ throw last;
283
+ throw stopped(this.boundReason(context.deadlineMs));
284
+ }
285
+ /** Poll a check to its bound. A completed false observation is an assertion
286
+ * failure even if a later read stalls; a bound reached before any completed
287
+ * check is a deadline; failed reads alone keep their own operation error.
288
+ * After a completed failure, the driver may reclassify the device state. */
289
+ async assertLoop(operation, attempt, timeoutMs = defaultAssertionMs, control) {
290
+ let observedFalse = false;
291
+ try {
292
+ return await this.perform(operation, async (context) => {
293
+ const result = await this.poll(context, attempt, timeoutMs, maxObservations, () => { observedFalse = true; });
294
+ if (!result.held)
295
+ throw stopped('assertion_failed', result.last);
296
+ }, timeoutMs, this.maxMs, () => observedFalse ? 'assertion_failed' : 'operation_timeout', undefined, control);
297
+ }
298
+ catch (error) {
299
+ // A completed mismatch on a device the driver can still read: ask it
300
+ // whether the device became unavailable (locked, screen off) during
301
+ // the readiness poll. A positive answer reclassifies the failure as
302
+ // setup; the assertion step stays failed and the test still fails.
303
+ if (!(error instanceof TargetStopped) || error.reason !== 'assertion_failed' || !this.driver.recheck || this.closing)
304
+ throw error;
305
+ // The hook gets a bounded signal; a stalled hook cannot keep the
306
+ // assertion pending, and a result after the bound, cancellation or
307
+ // close is discarded so it never rewrites the recorded failure.
308
+ const bound = Math.min(this.options.deadlineMs, Date.now() + recheckMs);
309
+ const signal = AbortSignal.timeout(Math.max(1, bound - Date.now()));
310
+ let record;
311
+ try {
312
+ record = await Promise.race([
313
+ this.driver.recheck({ signal, deadlineMs: bound }, { operation }),
314
+ new Promise(resolve => signal.addEventListener('abort', () => resolve(undefined), { once: true })),
315
+ ]);
316
+ }
317
+ catch {
318
+ record = undefined;
319
+ }
320
+ if (record === undefined || signal.aborted || this.closing)
321
+ throw error;
322
+ if (!(0, target_setup_1.validTargetSetup)(record) || record.stage !== 'recheck' || record.recovery)
323
+ throw error;
324
+ this.reason = `setup_${record.classification}`;
325
+ await attachSetup(record);
326
+ throw stopped(this.reason, error);
327
+ }
328
+ }
329
+ optional(name) {
330
+ const method = this.driver[name];
331
+ if (typeof method !== 'function')
332
+ throw stopped('unsupported_operation');
333
+ return method.bind(this.driver);
334
+ }
335
+ /** Platform back: Android's Back key, the browser's history. */
336
+ back(options = {}) { return this.perform('back', context => this.optional('back')(context), options.timeoutMs); }
337
+ /** Dismiss the software keyboard, keeping the selected input method. Android only. */
338
+ hideKeyboard(options = {}) { return this.perform('hide-keyboard', context => this.optional('hideKeyboard')(context), options.timeoutMs); }
339
+ /** Android only: assert the software keyboard is shown or hidden. */
340
+ toHaveKeyboard(visible, timeoutMs) {
341
+ if (typeof visible !== 'boolean')
342
+ return this.assertLoop('assert-keyboard', async () => { throw stopped('invalid_value'); }, timeoutMs);
343
+ return this.assertLoop('assert-keyboard', async (context) => await this.optional('keyboardShown')(context) === visible, timeoutMs);
344
+ }
345
+ /** One touch down/up at device coordinates, for example outside a pane.
346
+ * Coordinates are integers inside the viewport, checked against the
347
+ * driver's viewport when it reports one; nothing is retried. */
348
+ tapAt(point, options = {}) {
349
+ return this.perform('tap-at', async (context) => {
350
+ if (!validPoint(point))
351
+ throw stopped('invalid_point');
352
+ if (typeof this.driver.viewport === 'function') {
353
+ const size = await this.driver.viewport(context);
354
+ if (!validSize(size))
355
+ throw stopped('invalid_property');
356
+ if (point.x >= size.width || point.y >= size.height)
357
+ throw stopped('invalid_point');
358
+ }
359
+ await this.optional('tapAt')({ x: point.x, y: point.y }, context);
360
+ }, options.timeoutMs, this.maxMs, () => 'operation_timeout', validPoint(point) ? { x: point.x, y: point.y } : undefined);
361
+ }
362
+ viewport(options = {}) {
363
+ return this.perform('viewport', async (context) => {
364
+ const size = await this.optional('viewport')(context);
365
+ if (!validSize(size))
366
+ throw stopped('invalid_property');
367
+ return { width: size.width, height: size.height };
368
+ }, options.timeoutMs);
369
+ }
370
+ /** A digest of the active display's current image, for settling checks
371
+ * (two equal digests mean nothing moved). The image is never retained. */
372
+ screenDigest(options = {}) {
373
+ return this.perform('screen-digest', async (context) => {
374
+ const digest = await this.optional('screenDigest')(context);
375
+ if (typeof digest !== 'string' || !/^[a-f0-9]{64}$/.test(digest))
376
+ throw stopped('invalid_property');
377
+ return digest;
378
+ }, options.timeoutMs);
379
+ }
380
+ /** Stop the configured app without clearing its data. Android only. */
381
+ terminate(options = {}) { return this.perform('terminate', context => this.optional('terminate')(context), options.timeoutMs === undefined ? this.lifecycleMs : options.timeoutMs); }
382
+ /** Bring the configured app back to the foreground. Android only. */
383
+ activate(options = {}) { return this.perform('activate', context => this.optional('activate')(context), options.timeoutMs === undefined ? this.lifecycleMs : options.timeoutMs); }
384
+ /** Which window has input focus: the app's, another package's (a system
385
+ * dialog, permission prompt or Settings) or none. Read-only; package
386
+ * scoping of every action is unchanged. Recorded as an executed action,
387
+ * never an assertion. Android only. */
388
+ foreground(options = {}) {
389
+ return this.perform('foreground', async (context) => {
390
+ const value = await this.optional('foreground')(context);
391
+ if (value !== 'app' && value !== 'foreign' && value !== 'none')
392
+ throw stopped('invalid_property');
393
+ return value;
394
+ }, options.timeoutMs);
395
+ }
396
+ /** Touch the emulator's fingerprint sensor with finger 1-10, as a person
397
+ * would at a biometric prompt. Only an owned emulator whose driver
398
+ * declares biometrics has a sensor to touch; elsewhere this fails as
399
+ * unsupported_operation before touching the device. Recorded as an
400
+ * executed action: a biometric sign-in still needs an assertion. */
401
+ fingerprint(finger, options = {}) {
402
+ return this.perform('fingerprint', async (context) => {
403
+ if (!Number.isInteger(finger) || finger < 1 || finger > 10)
404
+ throw stopped('invalid_value');
405
+ await this.optional('fingerprint')(finger, context);
406
+ }, options.timeoutMs);
407
+ }
408
+ /** The serial of the device the open session targets, for adb commands a
409
+ * spec issues itself; those are outside the driver's cleanup and evidence.
410
+ * Not a device operation and never recorded. Android only. */
411
+ deviceSerial() {
412
+ if (this.controller.signal.aborted)
413
+ throw stopped(this.reason);
414
+ if (typeof this.driver.deviceSerial !== 'function')
415
+ throw stopped('unsupported_operation');
416
+ const serial = this.driver.deviceSerial();
417
+ if (typeof serial !== 'string' || !/^[a-zA-Z0-9_.:-]{1,128}$/.test(serial))
418
+ throw stopped('session_unavailable');
419
+ return serial;
159
420
  }
160
- reset(options = {}) { return this.perform('reset', context => this.driver.reset(context), options.timeoutMs); }
161
421
  getByTestId(id) {
162
422
  const observe = async (context) => {
163
423
  if (!boundedText(id, 128) || !id || /[\x00-\x1f]/.test(id))
@@ -166,6 +426,10 @@ class TargetApp {
166
426
  context.signal.throwIfAborted();
167
427
  if (!Array.isArray(matches) || matches.length > 1)
168
428
  throw stopped('ambiguous_test_id');
429
+ // Only an empty observation is absence; a reported match without a
430
+ // handle (null, undefined, a hole) is malformed lookup evidence.
431
+ if (matches.length === 1 && (!(0 in matches) || typeof matches[0] !== 'object' || matches[0] === null))
432
+ throw stopped('invalid_property');
169
433
  return matches[0];
170
434
  };
171
435
  const required = async (context) => {
@@ -174,51 +438,64 @@ class TargetApp {
174
438
  throw stopped('missing_test_id');
175
439
  return handle;
176
440
  };
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.
182
- const interval = Math.max(25, Math.ceil(timeoutMs / maxObservations));
183
- let last;
184
- for (let poll = 0; poll < maxObservations; poll++) {
185
- context.signal.throwIfAborted();
186
- 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.
193
- observedFalse = true;
194
- }
195
- catch (error) {
196
- // Ambiguity, invalid input and cancellation are not transient.
197
- if (error instanceof TargetStopped || context.signal.aborted)
198
- throw error;
199
- last = error;
200
- }
201
- if (Date.now() + interval >= context.deadlineMs)
202
- break;
203
- await (0, promises_1.setTimeout)(interval, undefined, { signal: context.signal });
204
- }
205
- if (observedFalse)
206
- throw stopped('assertion_failed', last);
207
- // Failed reads alone establish no business mismatch. Keep their
208
- // operation failure distinct from an executed false comparison.
209
- if (last !== undefined)
210
- throw last;
211
- throw stopped('deadline');
212
- }, timeoutMs, maxOperationMs, () => observedFalse ? 'assertion_failed' : 'deadline');
213
- };
441
+ // A missing control is a completed false observation, except for a
442
+ // hidden assertion, where absence is exactly what it asserts.
443
+ // Every operation on this control names it.
444
+ const step = (operation, body, timeoutMs) => this.perform(operation, body, timeoutMs, undefined, undefined, undefined, id);
445
+ const assertion = (operation, check, timeoutMs, absent = false) => this.assertLoop(operation, async (context) => {
446
+ const handle = await observe(context);
447
+ return handle ? check(handle, context) : absent;
448
+ }, timeoutMs, id);
214
449
  return {
215
- tap: (options = {}) => this.perform('tap', async (context) => (await required(context)).tap(context), options.timeoutMs),
216
- fill: (value, options = {}) => this.perform('fill', async (context) => {
450
+ tap: (options = {}) => step('tap', async (context) => (await required(context)).tap(context), options.timeoutMs),
451
+ fill: (value, options = {}) => step('fill', async (context) => {
217
452
  if (!boundedText(value, 4096))
218
453
  throw stopped('invalid_value');
219
454
  await (await required(context)).fill(value, context);
220
455
  }, options.timeoutMs),
221
- toBeVisible: (timeoutMs) => assertion('assert-visible', (handle, context) => handle.visible(context), timeoutMs),
456
+ /** One bounded scroll gesture inside this control, by a fraction of its size. */
457
+ scroll: (direction, options = {}) => step('scroll', async (context) => {
458
+ const percent = options.percent ?? 0.5;
459
+ if (!['up', 'down', 'left', 'right'].includes(direction) || typeof percent !== 'number' || !(percent > 0 && percent <= 1))
460
+ throw stopped('invalid_value');
461
+ const handle = await required(context);
462
+ if (typeof handle.scroll !== 'function')
463
+ throw stopped('unsupported_operation');
464
+ await handle.scroll(direction, percent, context);
465
+ }, options.timeoutMs),
466
+ /** The control's rectangle in device coordinates. */
467
+ bounds: (options = {}) => step('bounds', async (context) => {
468
+ const handle = await required(context);
469
+ if (typeof handle.bounds !== 'function')
470
+ throw stopped('unsupported_operation');
471
+ const rect = await handle.bounds(context);
472
+ if (!validRect(rect))
473
+ throw stopped('invalid_property');
474
+ return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
475
+ }, options.timeoutMs),
476
+ /** Whether the control is visible, without ending the session when it
477
+ * is not: one observation, or with timeoutMs a poll until it appears.
478
+ * Absent counts as not visible; ambiguity and reads that never
479
+ * complete still fail. Recorded as an executed action, never an
480
+ * assertion, so it cannot stand in for one. */
481
+ isVisible: (options = {}) => {
482
+ const polling = options.timeoutMs !== undefined;
483
+ const bound = polling ? options.timeoutMs : defaultOperationMs;
484
+ return step('query-visible', async (context) => {
485
+ const result = await this.poll(context, async (context) => {
486
+ const handle = await observe(context);
487
+ return handle ? visibility(handle, context) : false;
488
+ }, bound, polling ? maxObservations : 1, () => { }, true);
489
+ // A poll that Go's worker deadline cut short has not answered:
490
+ // the requested wait never ran to its end.
491
+ if (!result.held && polling && context.deadlineMs >= this.options.deadlineMs)
492
+ throw stopped('deadline');
493
+ return result.held;
494
+ }, bound);
495
+ },
496
+ toBeVisible: (timeoutMs) => assertion('assert-visible', async (handle, context) => await visibility(handle, context), timeoutMs),
497
+ /** Passes when the control is absent or not displayed. */
498
+ toBeHidden: (timeoutMs) => assertion('assert-hidden', async (handle, context) => !await visibility(handle, context), timeoutMs, true),
222
499
  toHaveText: (value, timeoutMs) => {
223
500
  if (!boundedText(value, 4096))
224
501
  return assertion('assert-text', async () => { throw stopped('invalid_value'); }, timeoutMs);
@@ -228,14 +505,38 @@ class TargetApp {
228
505
  }, timeoutMs);
229
506
  },
230
507
  toHaveState: (name, value, timeoutMs) => {
231
- if (!['enabled', 'checked'].includes(name) || typeof value !== 'boolean')
508
+ if (!['enabled', 'checked', 'invalid'].includes(name) || typeof value !== 'boolean')
232
509
  return assertion('assert-state', async () => { throw stopped('unsupported_state'); }, timeoutMs);
233
- return assertion('assert-state', async (handle, context) => await handle.state(name, context) === value, timeoutMs);
510
+ return assertion('assert-state', async (handle, context) => {
511
+ if (name !== 'invalid')
512
+ return await handle.state(name, context) === value;
513
+ if (typeof handle.invalid !== 'function')
514
+ throw stopped('unsupported_state');
515
+ const invalid = await handle.invalid(context);
516
+ if (typeof invalid !== 'boolean')
517
+ throw stopped('invalid_property');
518
+ return invalid === value;
519
+ }, timeoutMs);
234
520
  },
235
521
  };
236
522
  }
237
523
  }
238
524
  exports.TargetApp = TargetApp;
525
+ // A driver's visibility answer counts only as a boolean: a missing or
526
+ // malformed return proves neither visible nor hidden.
527
+ const visibility = async (handle, context) => {
528
+ const visible = await handle.visible(context);
529
+ if (typeof visible !== 'boolean')
530
+ throw stopped('invalid_property');
531
+ return visible;
532
+ };
533
+ const coordinate = (value) => Number.isInteger(value) && value >= 0 && value <= 65_535;
534
+ // A rectangle origin may be negative: a control scrolled partly above or
535
+ // left of the viewport still has geometry. Tap coordinates and sizes do not.
536
+ const offset = (value) => Number.isInteger(value) && value >= -65_535 && value <= 65_535;
537
+ const validPoint = (value) => !!value && typeof value === 'object' && coordinate(value.x) && coordinate(value.y);
538
+ const validSize = (value) => !!value && typeof value === 'object' && coordinate(value.width) && coordinate(value.height) && value.width > 0 && value.height > 0;
539
+ const validRect = (value) => !!value && typeof value === 'object' && offset(value.x) && offset(value.y) && coordinate(value.width) && coordinate(value.height);
239
540
  const remaining = (context) => { context.signal.throwIfAborted(); return Math.max(1, context.deadlineMs - Date.now()); };
240
541
  function locatorHandle(locator) {
241
542
  // Strict locators re-resolve a replaced node (re-renders, hydration) but
@@ -246,6 +547,24 @@ function locatorHandle(locator) {
246
547
  visible: async (context) => { remaining(context); return locator.isVisible(); },
247
548
  text: async (context) => await locator.textContent({ timeout: remaining(context) }) ?? '',
248
549
  state: async (name, context) => name === 'enabled' ? locator.isEnabled({ timeout: remaining(context) }) : locator.isChecked({ timeout: remaining(context) }),
550
+ invalid: async (context) => locator.evaluate(element => {
551
+ const aria = element.getAttribute('aria-invalid');
552
+ return (aria !== null && aria !== '' && aria !== 'false') || element.matches(':invalid');
553
+ }, undefined, { timeout: remaining(context) }),
554
+ scroll: async (direction, percent, context) => {
555
+ remaining(context);
556
+ await locator.evaluate((element, { direction, percent }) => {
557
+ const dx = direction === 'left' ? -1 : direction === 'right' ? 1 : 0;
558
+ const dy = direction === 'up' ? -1 : direction === 'down' ? 1 : 0;
559
+ element.scrollBy({ left: dx * element.clientWidth * percent, top: dy * element.clientHeight * percent, behavior: 'instant' });
560
+ }, { direction, percent }, { timeout: remaining(context) });
561
+ },
562
+ bounds: async (context) => {
563
+ const box = await locator.boundingBox({ timeout: remaining(context) });
564
+ if (!box)
565
+ throw new Error('control has no box');
566
+ return { x: Math.round(box.x), y: Math.round(box.y), width: Math.round(box.width), height: Math.round(box.height) };
567
+ },
249
568
  };
250
569
  }
251
570
  /** Ordinary Playwright handles implement the web side of the shared contract. */
@@ -254,6 +573,15 @@ function webTargetDriver(page, appId, lifecycle) {
254
573
  version: protocol_1.targetVersion, capabilities: exports.targetCapabilities, kind: 'web', appId,
255
574
  open: context => lifecycle.open(page, context), reset: context => lifecycle.reset(page, context),
256
575
  close: () => page.close({ runBeforeUnload: false }),
576
+ back: async (context) => { await page.goBack({ timeout: remaining(context) }); },
577
+ tapAt: async (point, context) => { remaining(context); await page.mouse.click(point.x, point.y); },
578
+ viewport: async (context) => {
579
+ // viewport: null disables emulation; the page still has a real size.
580
+ remaining(context);
581
+ const size = page.viewportSize() ?? await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
582
+ return { width: Math.round(size.width), height: Math.round(size.height) };
583
+ },
584
+ screenDigest: async (context) => (0, node_crypto_1.createHash)('sha256').update(await page.screenshot({ timeout: remaining(context), animations: 'allow', caret: 'initial' })).digest('hex'),
257
585
  observeTestId: async (id, context) => {
258
586
  remaining(context);
259
587
  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.1",
3
+ "version": "0.6.0-beta.3",
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",