clearcote 0.48.0 → 0.50.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/humanize.js CHANGED
@@ -26,9 +26,12 @@
26
26
  // ./forms.ts (shared test vectors with Python and .NET), HOW comes from this file. Every DOM read
27
27
  // goes through the isolated world (./isolated.ts) or Playwright's utility-world queries, never
28
28
  // page.evaluate / locator.evaluate.
29
+ import { errors as pwErrors } from "playwright-core";
29
30
  import { makePersona, planMove, dragDwell, clickHold, keyDwell, clickPoint, planAmbient, gaussFrom, rolloverRate, wheelNotches, platformFromNavigator, WHEEL_NOTCH_PX, } from "./motion.js";
30
- import { COVER_CHECK_MS, COVER_RETRY_MS, ISO_ACTIVE_FIELD, ISO_ACTIVE_VALUE, ISO_CSS_BOX, ISO_DESCRIBE, ISO_FORM_CONTROL, ISO_HIT_IN_BOX, ISO_LISTBOX_ROW, ISO_PLATFORM, ISO_SCROLL_BY, ISO_VIEWPORT, worldFor, } from "./isolated.js";
31
- import { DEFAULT_TYPO_RATE, NEARBY_LETTERS, classifyField, datetimeEqual, enginePathOk, formattedEqual, matchOption, normalizeClickOptions, numericEqual, planDatetime, planSelect, planTypo, pyFloat, rangeAttrs, rangeFraction, rangeNudge, rangePoint, rangeSanitize, rangeValueOk, segmentNodesFromTree, typoEligible, typosAllowed, } from "./forms.js";
31
+ import { keepInView, trimTo, walk } from "./pacing.js";
32
+ import { pressAndHold } from "./hold.js";
33
+ import { COVER_CHECK_MS, COVER_RETRY_MS, ISO_ACTIVE_FIELD, ISO_ACTIVE_VALUE, ISO_CSS_BOX, ISO_DESCRIBE, ISO_FORM_CONTROL, ISO_HIT_IN_BOX, ISO_LISTBOX_ROW, ISO_PLATFORM, ISO_SCROLL_BY, ISO_VIEWPORT, roundHalfEven, worldFor, } from "./isolated.js";
34
+ import { DEFAULT_TYPO_RATE, NEARBY_LETTERS, classifyField, datetimeEqual, enginePathOk, fitMaxlength, formattedEqual, maskKept, matchOption, normalizeClickOptions, numericEqual, planDatetime, planSelect, planTypo, prePressMs, pyFloat, rangeAttrs, rangeFraction, rangeNudge, rangePoint, rangeSanitize, rangeValueOk, segmentNodesFromTree, typoEligible, typosAllowed, } from "./forms.js";
32
35
  /** Overlay: a red dot that follows real mousemove events. Idempotent IIFE so it works both as
33
36
  * an addInitScript source string AND when passed to page.evaluate. */
34
37
  export const CURSOR_OVERLAY = `(() => {
@@ -55,22 +58,24 @@ const ROLL_KEYS = new Set("abcdefghijklmnopqrstuvwxyz0123456789 ,.;'/-=");
55
58
  /** The persona platform when the page cannot say: the SDK's default persona follows the host. */
56
59
  const hostWheelPlatform = () => process.platform === "win32" ? "windows" : process.platform === "darwin" ? "macos" : "linux";
57
60
  // The engine's pointer-path command. r34 renamed Browser.humanizedClick to Browser.dispatchPointerPath:
58
- // the old name was listed in /json/protocol for anyone who asked, and "humanizedClick" is known
59
- // vocabulary, so the method list alone said what the build was for. r33 and older only know the old
61
+ // "humanizedClick" is known vocabulary. The served /json/protocol still lists the old name (measured on
62
+ // r38, SC 210); r40 keeps the new one out of it. r33 and older only know the old
60
63
  // name, so the new one goes first and the old one is the fallback for a method-not-found only.
61
64
  /** @internal exported for tests */
62
65
  export const POINTER_PATH = "Browser.dispatchPointerPath";
63
66
  /** @internal exported for tests */
64
67
  export const POINTER_PATH_LEGACY = "Browser.humanizedClick";
65
- // Which name each browser answered to, so only its first call can pay for a miss.
68
+ // Which name each browser answered to, so only its first call can pay for a miss. NO_ENGINE_PATH: the
69
+ // engine knew neither name -- remembered too, so a new page of that browser does not probe both again.
66
70
  const engineMethodNames = new WeakMap();
71
+ const NO_ENGINE_PATH = "";
67
72
  // A CDP method-not-found: the engine predates the name. A raw CDP client sees code -32601;
68
73
  // Playwright's CDPSession keeps only the message ("Protocol error (X): 'X' wasn't found").
69
74
  const isMethodNotFound = (e) => e?.code === -32601 || /-32601|wasn't found|method not found/i.test(String(e?.message ?? e));
70
75
  /** @internal exported for tests. Send `method`, or `legacy` when the engine predates the rename, and
71
- * remember per `cacheKey` (a Browser, or the context when there is none) which one answered. Any
72
- * error other than method-not-found propagates as-is: retrying a real failure under the old name
73
- * would only replay it. */
76
+ * remember per `cacheKey` (a Browser, or the context when there is none) which one answered -- or that
77
+ * neither did, after which every call fails at once without a round trip. Any error other than
78
+ * method-not-found propagates as-is: retrying a real failure under the old name would only replay it. */
74
79
  export async function sendEngineCommand(session, cacheKey, method, legacy, params) {
75
80
  let names = engineMethodNames.get(cacheKey);
76
81
  if (!names) {
@@ -78,6 +83,8 @@ export async function sendEngineCommand(session, cacheKey, method, legacy, param
78
83
  engineMethodNames.set(cacheKey, names);
79
84
  }
80
85
  const known = names.get(method);
86
+ if (known === NO_ENGINE_PATH)
87
+ throw Object.assign(new Error(`'${method}' wasn't found`), { code: -32601 });
81
88
  if (known)
82
89
  return session.send(known, params);
83
90
  try {
@@ -89,10 +96,42 @@ export async function sendEngineCommand(session, cacheKey, method, legacy, param
89
96
  if (!isMethodNotFound(e))
90
97
  throw e;
91
98
  }
92
- const r = await session.send(legacy, params);
99
+ let r;
100
+ try {
101
+ r = await session.send(legacy, params);
102
+ }
103
+ catch (e) {
104
+ if (isMethodNotFound(e))
105
+ names.set(method, NO_ENGINE_PATH);
106
+ throw e;
107
+ }
93
108
  names.set(method, legacy);
94
109
  return r;
95
110
  }
111
+ /** @internal exported for tests. Did this browser's engine already say it has no pointer-path command? */
112
+ export function engineHasNoPointerPath(cacheKey) {
113
+ return !!cacheKey && engineMethodNames.get(cacheKey)?.get(POINTER_PATH) === NO_ENGINE_PATH;
114
+ }
115
+ /** @internal exported for tests. The page's default action timeout (setDefaultTimeout, else the
116
+ * context's, else Playwright's 30 s). */
117
+ export function defaultTimeoutMs(page) {
118
+ try {
119
+ const t = page?._timeoutSettings?.timeout({});
120
+ if (typeof t === "number" && Number.isFinite(t))
121
+ return t;
122
+ }
123
+ catch { /* not this Playwright's shape */ }
124
+ return 30_000;
125
+ }
126
+ /** @internal exported for tests. A Playwright TimeoutError for a trial whose checks never passed,
127
+ * worded like Playwright's. */
128
+ export function trialTimeoutError(selector, ms, why) {
129
+ const msg = `Timeout ${Math.round(ms)}ms exceeded.\nCall log:\n - waiting for locator('${selector}')\n - ${why}`;
130
+ const E = pwErrors?.TimeoutError;
131
+ if (typeof E === "function")
132
+ return Object.assign(new E(msg), { [SDK_PW_ERROR]: true });
133
+ return Object.assign(new Error(msg), { name: "TimeoutError", [SDK_PW_ERROR]: true });
134
+ }
96
135
  // The characters a US-layout keyboard (Playwright's, and the engine's keyboard.getLayoutMap())
97
136
  // types with Shift held: capitals and the shifted symbols.
98
137
  const SHIFTED_SYMBOLS = new Set('~!@#$%^&*()_+{}|:"<>?');
@@ -125,6 +164,52 @@ export function typoRate() {
125
164
  export function isTimeout(err) {
126
165
  return err?.name === "TimeoutError";
127
166
  }
167
+ // Playwright words every error after the API the caller used: "page.click: Timeout 800ms exceeded.",
168
+ // "locator.check: Error: Not a checkbox or radio button". A humanized call rejected with the error of
169
+ // whatever Playwright call it made inside (locator.waitFor, locator.isChecked; verifier B, SC 210) --
170
+ // the same class, but a message a caller matching on it would not recognise. Pre-existing in 0.48.0.
171
+ const API_PREFIX = /^[A-Za-z_]+\.[A-Za-z_]+: /;
172
+ /** Marks an error the SDK raises in Playwright's place (a trial that never passed, a checkbox that would
173
+ * not change): it gets the caller's API prefix too. */
174
+ const SDK_PW_ERROR = Symbol.for("clearcote.playwrightError");
175
+ /** @internal exported for tests. `err` worded as Playwright words an error of `api` ("page.click",
176
+ * "locator.setChecked"): the inner call's "locator.waitFor: " prefix replaced (or, for an error the SDK
177
+ * raised in Playwright's place, added), in the message and the stack's first line. The object, and so
178
+ * its class, is kept. Anything else is returned as it is. */
179
+ export function asApiError(err, api) {
180
+ const e = err;
181
+ if (!(e instanceof Error) || typeof e.message !== "string")
182
+ return err;
183
+ const m = API_PREFIX.exec(e.message);
184
+ if (!m && !err[SDK_PW_ERROR] && e.name !== "TimeoutError")
185
+ return err;
186
+ const msg = api + ": " + (m ? e.message.slice(m[0].length) : e.message);
187
+ if (msg === e.message)
188
+ return err;
189
+ const old = e.message;
190
+ try {
191
+ e.message = msg;
192
+ if (typeof e.stack === "string")
193
+ e.stack = e.stack.replace(old, msg);
194
+ }
195
+ catch { /* a frozen error keeps its words */ }
196
+ return err;
197
+ }
198
+ /** @internal `fn`, with every Playwright error it rejects with worded as `api`'s (asApiError). */
199
+ export function apiErrors(api, fn) {
200
+ return async (...a) => {
201
+ try {
202
+ return await fn(...a);
203
+ }
204
+ catch (e) {
205
+ throw asApiError(e, api);
206
+ }
207
+ };
208
+ }
209
+ /** @internal An Error the SDK raises where Playwright would, worded by the caller's API (apiErrors). */
210
+ export function sdkPlaywrightError(message) {
211
+ return Object.assign(new Error(message), { [SDK_PW_ERROR]: true });
212
+ }
128
213
  /** Internal: the humane route cannot apply here; run the native Playwright call instead. */
129
214
  class NativeSignal extends Error {
130
215
  constructor() { super("clearcote humanize: native route"); this.name = "NativeSignal"; }
@@ -144,6 +229,22 @@ export function createInputLock() {
144
229
  };
145
230
  }
146
231
  /** Wrap a single page's input methods + (optionally) inject the cursor overlay. */
232
+ /** Which clicks the engine pointer path (Browser.dispatchPointerPath) may walk, from
233
+ * CLEARCOTE_HUMANIZE_ENGINE_CLICKS: "off" (also 0/false/no) never; "all" (also "selector") coordinate
234
+ * clicks AND targeted page.click(selector) / locator.click() clicks; anything else (the default)
235
+ * coordinate clicks only, as before.
236
+ *
237
+ * Targeted clicks stay on the SDK planner by default (SC 210 lane S, measured on r38): the engine
238
+ * presses 9 ms after its last move (the planner's press waits 40-130 ms), and it walks from its own last
239
+ * position, which an SDK glide does not update. Same values as Python `_engine_clicks_mode`. */
240
+ export function engineClicksMode() {
241
+ const v = (process.env.CLEARCOTE_HUMANIZE_ENGINE_CLICKS || "").trim().toLowerCase();
242
+ if (["0", "off", "false", "no", "none"].includes(v))
243
+ return "off";
244
+ if (["all", "selector", "selectors"].includes(v))
245
+ return "all";
246
+ return "coords";
247
+ }
147
248
  export async function attachHumanize(browser, page, opts) {
148
249
  // IDEMPOTENCY GUARD — do not remove.
149
250
  //
@@ -193,22 +294,37 @@ export async function attachHumanize(browser, page, opts) {
193
294
  // Walk a planned trajectory (motion.ts) with native (trusted) mouse.move + off-protocol sleeps.
194
295
  // Native input carries the button state, so a button pressed via mouse.down() stays held across
195
296
  // the whole path — the same code powers a free move AND a held-button drag.
297
+ //
298
+ // Paced against a WALL CLOCK (pacing.ts): each sample goes out at its planned time and late ones
299
+ // are skipped (never the last, and no skip hops more than 40 px, or 20 px once nothing has been
300
+ // dispatched for 40 ms: MAX_JUMP_PX / IDLE_HOP_PX). "Move, then sleep the planned gap" added the
301
+ // ~27 ms mouse.move round trip to every 6-8 ms sample: a 1.05 s planned glide took 3.5-5.4 s on
302
+ // PRO r38 (SC 209), ambient motion 5.7x as long.
196
303
  const dispatch = async (steps) => {
197
- for (const s of steps) {
304
+ const vp = await viewBounds();
305
+ await walk(vp ? keepInView(steps, vp.width, vp.height) : steps, async (x, y) => { await nativeMove(x, y); st.placed = true; });
306
+ };
307
+ // The viewport a planned path is kept inside (keepInView: the planner's overshoot arcs left the window
308
+ // near its edges, verifier B), read in the isolated world at most every 2 s; null when it cannot be read.
309
+ let vb = null;
310
+ const viewBounds = async () => {
311
+ const now = Date.now();
312
+ if (vb === null || now - vb.t > 2000) {
313
+ let vp = null;
198
314
  try {
199
- await nativeMove(s.x, s.y);
315
+ const wh = await worldFor(page).evaluate(ISO_VIEWPORT);
316
+ if (wh && wh[0] && wh[1])
317
+ vp = { width: Number(wh[0]), height: Number(wh[1]) };
200
318
  }
201
- catch {
202
- break;
203
- }
204
- st.placed = true;
205
- await sleep(s.sleepMs);
319
+ catch { /* detached / navigating / no CDP: no clamp */ }
320
+ vb = { t: now, vp };
206
321
  }
322
+ return vb.vp;
207
323
  };
208
324
  // Move to (x, y) as a minimum-jerk sum-of-submovements path (primary ballistic + corrective homing)
209
325
  // with colored sub-pixel noise and Fitts-scaled duration. `settle` adds a seating jiggle (drag).
210
326
  const glide = async (x, y, o = {}) => {
211
- await dispatch(planMove(st, { x, y }, persona, { settle: o.settle, targetW: o.targetW }));
327
+ await dispatch(planMove(st, { x, y }, persona, { settle: o.settle, targetW: o.targetW, held: o.held }));
212
328
  st.x = x;
213
329
  st.y = y;
214
330
  };
@@ -217,11 +333,23 @@ export async function attachHumanize(browser, page, opts) {
217
333
  // recorded human paths for PRO, engine bezier for free, tiered by the engine license gate).
218
334
  // Held-button DRAGS stay native; falls back to the SDK bezier if the method is unavailable
219
335
  // (older engine / no browser session).
220
- const eng = { session: null, key: null, tid: null, ok: true };
336
+ const eng = { session: null, key: null, tid: null, ok: true, at: null };
337
+ // The engine walks from ITS OWN last position on this page, not from where an SDK glide left the
338
+ // pointer. Measured on r38 (SC 210): an engine click at (300,300), an SDK glide to (800,550), then
339
+ // mouse.click(400,200) through the engine -- its first sample was at (300,300), a 559 px teleport
340
+ // from where the pointer was. So the engine walks only while nothing else has moved the pointer
341
+ // since its own last walk (before its first walk: while nothing has moved it at all).
342
+ const engineInSync = () => (eng.at === null ? !st.placed : st.x === eng.at.x && st.y === eng.at.y);
221
343
  const engineGlide = async (x, y, noClick) => {
222
- if (!eng.ok)
344
+ if (!eng.ok || !engineInSync())
223
345
  return false;
224
346
  try {
347
+ // This browser's engine already said it has neither command: no sessions, no probe.
348
+ const ctx0 = page.context();
349
+ if (engineHasNoPointerPath((ctx0.browser ? ctx0.browser() : null) ?? ctx0)) {
350
+ eng.ok = false;
351
+ return false;
352
+ }
225
353
  if (eng.session === null) {
226
354
  const ctx = page.context();
227
355
  const tsession = await ctx.newCDPSession(page);
@@ -234,13 +362,17 @@ export async function attachHumanize(browser, page, opts) {
234
362
  const dx = x - st.x, dy = y - st.y;
235
363
  const dist = Math.sqrt(dx * dx + dy * dy);
236
364
  const dur = Math.min(1.10, Math.max(0.28, 0.30 + dist / 1700)) * (0.85 + 0.30 * Math.random());
365
+ const tSend = Date.now();
237
366
  await sendEngineCommand(eng.session, eng.key, POINTER_PATH, POINTER_PATH_LEGACY, { targetId: eng.tid, x, y, duration: dur, noClick });
238
367
  // The engine walks the trajectory in the BROWSER process and answers this command before it
239
368
  // has finished. Without waiting, a following mouse.down() fires at the cursor's STALE
240
369
  // position — measured: a move to (110,58) then a press landed at (981,629), on <body>
241
370
  // instead of the target, so every move-then-press sequence (drag, press-and-hold,
242
371
  // drag-and-drop) acted on the wrong element.
243
- await sleep(dur * 1000);
372
+ // r38 answers only after the walk AND the click (send returned 772 ms after a 600 ms walk, 2 ms
373
+ // after the release, SC 210): wait only for what is left of `dur`, so an engine that answers
374
+ // late does not add a second, idle `dur` after every click.
375
+ await sleep(Math.max(0, dur * 1000 - (Date.now() - tSend)));
244
376
  try {
245
377
  await nativeMove(x, y);
246
378
  }
@@ -248,6 +380,7 @@ export async function attachHumanize(browser, page, opts) {
248
380
  st.x = x;
249
381
  st.y = y;
250
382
  st.placed = true;
383
+ eng.at = { x, y };
251
384
  return true;
252
385
  }
253
386
  catch {
@@ -283,7 +416,9 @@ export async function attachHumanize(browser, page, opts) {
283
416
  // an action needs one but names no coordinates.
284
417
  const ambient = async (ms) => {
285
418
  try {
286
- const steps = planAmbient(st, await viewport(), persona, ms);
419
+ // planAmbient overruns its budget (whole excursions, rests drawn at 0.9-1.4x a frame): cut the
420
+ // plan at a slow sample near ms so ambientMotion(ms) lasts about ms.
421
+ const steps = trimTo(planAmbient(st, await viewport(), persona, ms), ms);
287
422
  await dispatch(steps);
288
423
  if (steps.length) {
289
424
  st.x = steps[steps.length - 1].x;
@@ -328,7 +463,9 @@ export async function attachHumanize(browser, page, opts) {
328
463
  // mouse.click keeps engine routing: it performs move+click entirely engine-side, where nothing
329
464
  // races the trajectory. glide() is still fully humanized (minimum-jerk, colored noise, Fitts).
330
465
  mouse.move = async (x, y) => {
331
- await glide(x, y);
466
+ // A move while the button is held is a DRAG leg: planDrag keeps it on the line between grab and
467
+ // drop (an aimed reach's arc took a slider handle 47 px off a 40 px track, SC 209).
468
+ await glide(x, y, { held: st.held });
332
469
  };
333
470
  // down/up are wrapped to TRACK the held state mouse.move needs, and — critically — to make the
334
471
  // press position DETERMINISTIC. The engine answers its pointer path before the trajectory has
@@ -336,6 +473,29 @@ export async function attachHumanize(browser, page, opts) {
336
473
  // enough: measured on Node, a move to (110,58) was still mid-flight at (416,504) when the press
337
474
  // fired, landing on <body>. Re-issuing a native move to the tracked target immediately before
338
475
  // the press pins the cursor to where the caller asked, whatever the trajectory is doing.
476
+ // The pause between the pointer coming to rest and the button going down (forms.prePressMs: 40-250
477
+ // ms, right-skewed, centred per identity). Measured on r38 before it: the focus click before typing
478
+ // pressed ~4 ms after the last pointermove, a drag grab ~21 ms.
479
+ const prePress = async () => { await sleep(prePressMs(persona.seed)); };
480
+ // What is left of a button hold once mouse.down() has returned: the hold runs from when the press was
481
+ // SENT. mouse.down() returns only after the page handled the press, and a <select> opens its popup
482
+ // inside that, so a hold slept afterwards reached the page ~30-80 ms longer than planned.
483
+ const holdRest = (holdMs, t0) => Math.max(0, holdMs - (Date.now() - t0));
484
+ // Press and release the left button where the last glide left the pointer, after the pre-press
485
+ // pause. Native down/up, so nothing moves: Playwright's mouse.click(x, y) sends one more mouseMoved
486
+ // first, and THAT was the last pointermove the page saw, ~4 ms before the press.
487
+ const pressHere = async (x, y, holdMs) => {
488
+ const hold = holdMs ?? clickHold(persona);
489
+ await prePress();
490
+ const t0 = Date.now();
491
+ await nativeDown();
492
+ try {
493
+ await sleep(holdRest(hold, t0));
494
+ }
495
+ finally {
496
+ await nativeUp();
497
+ } // never leave the button down
498
+ };
339
499
  mouse.down = async (...a) => {
340
500
  // DELIBERATELY NO PLACEMENT WHEN THE POINTER HAS NEVER MOVED.
341
501
  //
@@ -354,6 +514,9 @@ export async function attachHumanize(browser, page, opts) {
354
514
  await nativeMove(st.x, st.y);
355
515
  }
356
516
  catch { /* best effort: keep the press on target */ }
517
+ // The hand has arrived; it confirms the target before the button goes down. The pin is itself
518
+ // a pointermove, so the pause comes after it. A down() with no move before it stays instant.
519
+ await prePress();
357
520
  }
358
521
  st.held = true;
359
522
  try {
@@ -375,12 +538,12 @@ export async function attachHumanize(browser, page, opts) {
375
538
  // dropped those options and always left-clicked once.
376
539
  const hclick = async (x, y, options = {}) => {
377
540
  const o = normalizeClickOptions(options);
378
- if (enginePathOk(o) && await engineGlide(x, y, false))
541
+ if (enginePathOk(o) && engineClicksMode() !== "off" && await engineGlide(x, y, false))
379
542
  return;
380
543
  await glide(x, y);
381
544
  try {
382
545
  if (o.modifiers.length && !(nativeKbDown && nativeKbUp)) {
383
- await sleep(rand(40, 130)); // brief dwell before pressing, like a human
546
+ await prePress(); // the hand confirms the target before it presses
384
547
  // delay = the mousedown→mouseup HOLD (human ~60–150 ms); without it Playwright releases in ~2 ms.
385
548
  await nativeClick(x, y, { delay: o.delay ?? clickHold(persona), button: o.button, clickCount: o.clickCount });
386
549
  return;
@@ -499,6 +662,8 @@ export async function attachHumanize(browser, page, opts) {
499
662
  const keyboard = page.keyboard;
500
663
  const nativeKbType = keyboard.type.bind(keyboard);
501
664
  const nativeKbPress = keyboard.press.bind(keyboard);
665
+ // A bulk fill's paste (Input.insertText).
666
+ const nativeKbInsert = typeof keyboard.insertText === "function" ? keyboard.insertText.bind(keyboard) : undefined;
502
667
  // A page-like keyboard without down/up still gets every other humanization; it just types
503
668
  // capitals without the Shift key, as before.
504
669
  const nativeKbDown = typeof keyboard.down === "function" ? keyboard.down.bind(keyboard) : undefined;
@@ -527,8 +692,8 @@ export async function attachHumanize(browser, page, opts) {
527
692
  };
528
693
  // Press at the point the last glide ended, the way the options ask: the button, the click count (a
529
694
  // double click is two presses with a human gap, not one event), the caller's hold (`delay`) or the
530
- // persona's, and modifiers held around the whole press with a lead before it (80-240 ms: 40-110 ms
531
- // per modifier plus the 40-130 ms pre-press dwell) and a 20-80 ms lag after, as fingers do. Native
695
+ // persona's, and modifiers held around the whole press with a lead before it (80-360 ms: 40-110 ms
696
+ // per modifier plus the 40-250 ms pre-press pause) and a 20-80 ms lag after, as fingers do. Native
532
697
  // down/up, so nothing moves.
533
698
  const pressAt = async (o) => {
534
699
  const held = [];
@@ -538,13 +703,14 @@ export async function attachHumanize(browser, page, opts) {
538
703
  held.push(m);
539
704
  await sleep(rand(40, 110));
540
705
  }
541
- await sleep(rand(40, 130)); // brief dwell before pressing, like a human
706
+ await prePress(); // the hand confirms the target before it presses
542
707
  const n = o.clickCount;
543
708
  for (let i = 1; i <= n; i++) {
544
709
  const hold = o.delay ?? clickHold(persona);
710
+ const t0 = Date.now();
545
711
  await nativeDown({ button: o.button, clickCount: i });
546
712
  try {
547
- await sleep(hold);
713
+ await sleep(holdRest(hold, t0));
548
714
  }
549
715
  finally {
550
716
  await nativeUp({ button: o.button, clickCount: i }); // never leave the button down
@@ -862,18 +1028,24 @@ export async function attachHumanize(browser, page, opts) {
862
1028
  return width > 0 && height > 0 ? { x, y, width, height } : null;
863
1029
  };
864
1030
  // Does a press at viewport (x, y) reach the element filling `box`? true / false, or null when it
865
- // cannot be told here: the point lies in a child frame, or CDP is unavailable.
866
- const hitInBox = async (box, x, y) => {
1031
+ // cannot be told here (CDP is unavailable). A point inside a child frame is answered by the <iframe>
1032
+ // element that holds it (IsolatedWorld.nodeAt).
1033
+ // `sel`: a plain-CSS selector for the element, when the caller has one: whether the hit is THAT
1034
+ // element (ISO_HIT_IN_BOX), not just one that fills the box.
1035
+ const hitInBox = async (box, x, y, sel = null) => {
867
1036
  const w = worldFor(page);
868
1037
  const nid = await w.nodeAt(x, y);
869
1038
  if (nid === undefined)
870
1039
  return null;
871
- const res = await w.callOnNode(nid, ISO_HIT_IN_BOX, { x: box.x, y: box.y, width: box.width, height: box.height });
1040
+ const b = { x: box.x, y: box.y, width: box.width, height: box.height };
1041
+ if (sel)
1042
+ b.sel = sel;
1043
+ const res = await w.callOnNode(nid, ISO_HIT_IN_BOX, b);
872
1044
  return res === undefined || res === null ? null : Boolean(res);
873
1045
  };
874
1046
  // Does the element filling `box` own its centre -- not clipped by a scrolling container, not
875
1047
  // covered? The browser's own hit test, read in the isolated world.
876
- const hitOk = async (box) => (await hitInBox(box, box.x + box.width / 2, box.y + box.height / 2)) === true;
1048
+ const hitOk = async (box, sel = null) => (await hitInBox(box, box.x + box.width / 2, box.y + box.height / 2, sel)) === true;
877
1049
  // The box of a plain-CSS selector's first match, read (and scrolled into view) in the isolated
878
1050
  // world: not even the one boundingBox() handle, and its textContent preview, is made. Used only
879
1051
  // when Playwright counts exactly the elements the browser's own querySelectorAll finds --
@@ -894,7 +1066,7 @@ export async function attachHumanize(browser, page, opts) {
894
1066
  return null;
895
1067
  }
896
1068
  let box = rectBox(r);
897
- if (box && !((await inView(box)) && (await hitOk(box)))) {
1069
+ if (box && !((await inView(box)) && (await hitOk(box, selector)))) {
898
1070
  // scrollIntoViewIfNeeded also scrolls a scrolling container that clips it, and does nothing
899
1071
  // when it already shows (then the cover is an overlay: the click's own check)
900
1072
  box = rectBox(await w.evaluate(ISO_CSS_BOX, { sel: selector, scroll: true }));
@@ -938,12 +1110,12 @@ export async function attachHumanize(browser, page, opts) {
938
1110
  if (css)
939
1111
  return css;
940
1112
  let box = await loc.boundingBox();
941
- if (box && !((await inView(box)) && (await hitOk(box)))) {
1113
+ if (box && !((await inView(box)) && (await hitOk(box, selector)))) {
942
1114
  // Off-screen: scroll the window to it and prove it shows there (hit test), with no new handle.
943
1115
  // Clipped by a scrolling container, covered, or the window scroll did not bring it out:
944
1116
  // Playwright's scroll, which also scrolls containers, and a fresh box.
945
1117
  const moved = !(await inView(box)) ? await scrollWindowTo(box) : null;
946
- if (moved && (await inView(moved)) && (await hitOk(moved)))
1118
+ if (moved && (await inView(moved)) && (await hitOk(moved, selector)))
947
1119
  return moved;
948
1120
  await loc.scrollIntoViewIfNeeded({ timeout });
949
1121
  box = await loc.boundingBox();
@@ -1002,10 +1174,10 @@ export async function attachHumanize(browser, page, opts) {
1002
1174
  else if (info.disabled) {
1003
1175
  return false;
1004
1176
  }
1005
- const pt = at ? { x: at[0], y: at[1] } : clickPoint(box, st, persona); // 2D gaussian toward the centre
1177
+ const p0 = at ? { x: at[0], y: at[1] } : clickPoint(box, st, persona); // 2D gaussian toward the centre
1178
+ const pt = { x: roundHalfEven(p0.x), y: roundHalfEven(p0.y) }; // the pixel the hit test answered for
1006
1179
  await glide(pt.x, pt.y);
1007
- await sleep(rand(40, 130));
1008
- await nativeClick(pt.x, pt.y, { delay: clickHold(persona) });
1180
+ await pressHere(pt.x, pt.y);
1009
1181
  return true;
1010
1182
  };
1011
1183
  // Ctrl+A (Cmd+A on a Mac engine) the way a hand does it: the modifier goes down a moment before the
@@ -1083,16 +1255,30 @@ export async function attachHumanize(browser, page, opts) {
1083
1255
  // outside the try: a native call that raises must raise ONCE, not be retried by the handler
1084
1256
  return nativeType(selector, text, options);
1085
1257
  };
1086
- page.type = (selector, text, options = {}) => locked(() => htype(selector, text, options));
1258
+ page.type = apiErrors("page.type", (selector, text, options = {}) => locked(() => htype(selector, text, options)));
1087
1259
  // Type `value` into a text control and PROVE it landed. The value is read through Playwright's
1088
1260
  // utility world (`inputValue`): it sees the control the locator means, wherever focus is, and the page
1089
1261
  // cannot observe it. A field whose value cannot be read, or a click that did not put the caret in it
1090
1262
  // (an overlay took it), is left to Playwright -- "could not check" is never treated as success.
1091
1263
  const fillText = async (loc, box, value, info, selector = null) => {
1092
- if (Array.from(value).length > 200)
1093
- return false; // bulk values: keep fill fast/atomic
1094
1264
  const isCe = Boolean(info && info.ce)
1095
1265
  || (info === null && ((await loc.getAttribute("contenteditable")) || "false") !== "false");
1266
+ // What the field can hold: a maxlength keeps the first N characters (what Playwright's insertText
1267
+ // leaves too), and a person types only those -- the field stops taking keys.
1268
+ let want = value;
1269
+ let limit = [null, null, null];
1270
+ if (!isCe) {
1271
+ limit = info
1272
+ ? [info.maxlength, info.tag, info.type]
1273
+ : [await loc.getAttribute("maxlength"),
1274
+ (await loc.locator("xpath=self::textarea").count()) ? "textarea" : "input", (await loc.getAttribute("type")) || ""];
1275
+ want = fitMaxlength(value, ...limit);
1276
+ }
1277
+ // Bulk values (over 200 characters) are still inserted at once -- typing thousands of keys would
1278
+ // crawl -- but the way a person pastes: glide to the field, click into it, then insert.
1279
+ const bulk = Array.from(want).length > 200; // what the field holds: a 300-character value cut to 5 is typed
1280
+ if (bulk && !nativeKbInsert)
1281
+ return false;
1096
1282
  if (!(await focusClick(box, box ? provenPoint(box, info) : null, loc, selector)))
1097
1283
  return false;
1098
1284
  await sleep(rand(40, 120));
@@ -1106,11 +1292,20 @@ export async function attachHumanize(browser, page, opts) {
1106
1292
  return null;
1107
1293
  }
1108
1294
  };
1295
+ const put = async (text, typos = true) => {
1296
+ if (bulk) {
1297
+ await sleep(rand(120, 320)); // the paste shortcut, after the click
1298
+ await nativeKbInsert(text);
1299
+ }
1300
+ else {
1301
+ await humanTypeText(text, info, typos);
1302
+ }
1303
+ };
1109
1304
  if (isCe) {
1110
1305
  const cur = info ? info.value : null;
1111
1306
  if (cur)
1112
1307
  await clearFocused();
1113
- await humanTypeText(value, info);
1308
+ await put(want);
1114
1309
  return true; // contenteditable: Playwright's fill sets text the same way; no value to read
1115
1310
  }
1116
1311
  const cur = await read();
@@ -1118,18 +1313,22 @@ export async function attachHumanize(browser, page, opts) {
1118
1313
  return false;
1119
1314
  if (cur)
1120
1315
  await clearFocused(read); // a person does not select-all an empty field
1121
- await humanTypeText(value, info);
1316
+ await put(want);
1122
1317
  let got = await read();
1123
1318
  if (got === null)
1124
1319
  return false;
1125
- if (got === value || formattedEqual(got, value))
1126
- return true; // exact, or a mask that only re-punctuated it
1320
+ // exact; a mask that only re-punctuated what was typed (a phone format); or one that re-punctuated it
1321
+ // and then stopped taking keys (MM/YY on maxlength 5): no wipe and retype (maskKept)
1322
+ if (got === want || formattedEqual(got, want) || maskKept(got, want, ...limit))
1323
+ return true;
1324
+ if (bulk)
1325
+ return false; // an inserted value that did not land: Playwright's fill, not a second paste
1127
1326
  // Wrong value (an autocompleter interfered, a key was lost): one clean retry without slips, then
1128
1327
  // give the field to Playwright -- a correct value beats pretty input.
1129
1328
  await clearFocused(read);
1130
- await humanTypeText(value, info, false);
1329
+ await put(want, false);
1131
1330
  got = await read();
1132
- return got !== null && (got === value || formattedEqual(got, value));
1331
+ return got !== null && (got === want || formattedEqual(got, want) || maskKept(got, want, ...limit));
1133
1332
  };
1134
1333
  // A range input: drag the thumb (or click the track) to the value, then arrow-nudge to it exactly.
1135
1334
  // Typing digits into a slider -- what fill() did before -- changes nothing, and the click before it
@@ -1162,7 +1361,7 @@ export async function attachHumanize(browser, page, opts) {
1162
1361
  let [cx, cy] = rangePoint(box, rangeFraction(cur, lo, hi), rtl);
1163
1362
  cy += gauss() * box.height * 0.08;
1164
1363
  await glide(cx, cy, { targetW: 16 });
1165
- await sleep(rand(60, 160));
1364
+ await prePress();
1166
1365
  const { grabMs, releaseMs } = dragDwell(persona);
1167
1366
  await nativeDown();
1168
1367
  st.held = true;
@@ -1178,8 +1377,7 @@ export async function attachHumanize(browser, page, opts) {
1178
1377
  }
1179
1378
  else {
1180
1379
  await glide(tx, ty, { targetW: 16 });
1181
- await sleep(rand(40, 130));
1182
- await nativeClick(tx, ty, { delay: clickHold(persona) });
1380
+ await pressHere(tx, ty);
1183
1381
  }
1184
1382
  for (let round = 0; round < 3; round++) {
1185
1383
  const v = await now();
@@ -1232,17 +1430,15 @@ export async function attachHumanize(browser, page, opts) {
1232
1430
  py = box.y + box.height / 2;
1233
1431
  }
1234
1432
  await glide(px, py, { targetW: fw });
1235
- await sleep(rand(40, 130));
1236
- await nativeClick(px, py, { delay: clickHold(persona) });
1433
+ await pressHere(px, py);
1237
1434
  await sleep(rand(150, 350));
1238
1435
  for (const a of plan) {
1239
1436
  if (a[0] === "type") {
1240
- const digits = Array.from(a[1]);
1241
- for (let j = 0; j < digits.length; j++) {
1242
- await nativeKbPress(digits[j], { delay: keyDwell(persona) });
1243
- if (j < digits.length - 1)
1244
- await sleep(Math.max(30, 110 + gauss() * 40));
1245
- }
1437
+ // The same typing model as text (persona dwell, gaussian gaps, thinking pauses, rollover): the
1438
+ // old flat 60-150 ms gap had a CV of 0.24 and no rollover. A segment moves on by itself after
1439
+ // its last digit and keys go down in order, so a rolled-over digit still lands in the right
1440
+ // field (checked on r38, all five types). No typos: a slip in a date is a wrong date.
1441
+ await humanTypeText(a[1], null, false);
1246
1442
  }
1247
1443
  else {
1248
1444
  await key(a[1], a.length > 2 ? a[2] : 1, [70, 170]);
@@ -1292,13 +1488,13 @@ export async function attachHumanize(browser, page, opts) {
1292
1488
  // raises, as before humanize), and anything the humane route could not prove it did right.
1293
1489
  return nativePageFill(selector, value, options);
1294
1490
  };
1295
- page.fill = (selector, value, options = {}) => locked(() => hfill(selector, value, options));
1296
- page.dblclick = (selector, options = {}) => locked(() => {
1491
+ page.fill = apiErrors("page.fill", (selector, value, options = {}) => locked(() => hfill(selector, value, options)));
1492
+ page.dblclick = apiErrors("page.dblclick", (selector, options = {}) => locked(() => {
1297
1493
  const o = { ...(options ?? {}) };
1298
1494
  if (o.clickCount === undefined)
1299
1495
  o.clickCount = 2;
1300
1496
  return targetedClick(nativePageDblclick, selector, o, false, options ?? {});
1301
- });
1497
+ }));
1302
1498
  const hpress = async (selector, key, options) => {
1303
1499
  try {
1304
1500
  // Click into text fields only: a press on a button or a link that is not focused yet is
@@ -1316,7 +1512,7 @@ export async function attachHumanize(browser, page, opts) {
1316
1512
  }
1317
1513
  return nativePagePress(selector, key, options);
1318
1514
  };
1319
- page.press = (selector, key, options = {}) => locked(() => hpress(selector, key, options));
1515
+ page.press = apiErrors("page.press", (selector, key, options = {}) => locked(() => hpress(selector, key, options)));
1320
1516
  // ------------------------------------------------------------------------- selectOption
1321
1517
  // Open the drop-down with a click, move its highlight with the planned keys, commit with Enter: one
1322
1518
  // trusted input+change, the sequence a mouse-and-keyboard user produces. While the popup is open its
@@ -1465,8 +1661,7 @@ export async function attachHumanize(browser, page, opts) {
1465
1661
  await pressAt(normalizeClickOptions({ modifiers: ["ControlOrMeta"] }));
1466
1662
  }
1467
1663
  else {
1468
- await sleep(rand(40, 130));
1469
- await nativeClick(px, py, { delay: clickHold(persona) });
1664
+ await pressHere(px, py);
1470
1665
  }
1471
1666
  await sleep(rand(150, 350));
1472
1667
  }
@@ -1537,35 +1732,39 @@ export async function attachHumanize(browser, page, opts) {
1537
1732
  }
1538
1733
  return nativePageSelect(selector, values, options);
1539
1734
  };
1540
- page.selectOption = (selector, values, options = {}) => locked(() => hselect(selector, values, options));
1735
+ page.selectOption = apiErrors("page.selectOption", (selector, values, options = {}) => locked(() => hselect(selector, values, options)));
1541
1736
  }
1542
1737
  // ------------------------------------------------------------------ check / uncheck / setChecked
1543
1738
  // A humanized click when the state must change, then the state verified. `trial` performs no action:
1544
- // Playwright's own trial runs. Errors propagate as Playwright's own (not a checkbox, timed out): the
1739
+ // the state is read (a non-checkbox raises, as in Playwright) and, when a click would be needed, its
1740
+ // checks run here (trial) -- not Playwright's trial, which moves the pointer and presses. Errors propagate as Playwright's own (not a checkbox, timed out): the
1545
1741
  // click owns its native fallback, so nothing here may click a second time -- and when one click did
1546
1742
  // not change the state (a page that cancels it), this raises like Playwright's check instead of
1547
1743
  // clicking again.
1548
1744
  const setChecked = async (orig, selector, checked, options) => {
1549
1745
  const opts = options ?? {};
1550
- if (opts.trial)
1551
- return orig(selector, opts);
1552
1746
  const loc = page.locator(selector).first();
1747
+ if (opts.trial) {
1748
+ if ((await loc.isChecked({ timeout: opts.timeout })) === checked)
1749
+ return;
1750
+ return trial(selector, opts, false);
1751
+ }
1553
1752
  if ((await loc.isChecked({ timeout: opts.timeout })) === checked)
1554
1753
  return;
1555
1754
  await targetedClick(nativePageClick, selector, { ...opts }, false, null);
1556
1755
  if ((await loc.isChecked()) === checked)
1557
1756
  return;
1558
- throw new Error("Clicking the checkbox did not change its state");
1757
+ throw sdkPlaywrightError("Clicking the checkbox did not change its state");
1559
1758
  };
1560
1759
  for (const [name, want] of [["check", true], ["uncheck", false]]) {
1561
1760
  if (typeof page[name] === "function") {
1562
1761
  const orig = page[name].bind(page);
1563
- page[name] = (selector, options = {}) => locked(() => setChecked(orig, selector, want, options));
1762
+ page[name] = apiErrors("page." + name, (selector, options = {}) => locked(() => setChecked(orig, selector, want, options)));
1564
1763
  }
1565
1764
  }
1566
1765
  if (typeof page.setChecked === "function") {
1567
1766
  const origSc = page.setChecked.bind(page);
1568
- page.setChecked = (selector, checked, options = {}) => locked(() => setChecked((s, o) => origSc(s, checked, o), selector, Boolean(checked), options));
1767
+ page.setChecked = apiErrors("page.setChecked", (selector, checked, options = {}) => locked(() => setChecked((s, o) => origSc(s, checked, o), selector, Boolean(checked), options)));
1569
1768
  }
1570
1769
  // ------------------------------------------------------------------------- click / hover
1571
1770
  // The covered-point check, through the browser's own hit test read in the isolated world: nothing is
@@ -1574,35 +1773,61 @@ export async function attachHumanize(browser, page, opts) {
1574
1773
  // saw, before every humanized click since 0.46.0, a mousemove inside the target, a 450-500 px jump
1575
1774
  // back, then the glide, and a pointerdown/pointerup/click (left, even for a right click) that window
1576
1775
  // capture listeners could see. A covered point is looked at again for COVER_CHECK_MS (an overlay
1577
- // fading out).
1578
- const reachesPoint = async (orig, selector, box, x, y) => {
1776
+ // fading out). A point inside a child frame is answered by the <iframe> element that holds it
1777
+ // (IsolatedWorld.nodeAt), so no Playwright trial runs for it either. false when covered; null when
1778
+ // the hit test cannot run (no CDP): the caller goes native.
1779
+ const reachesPoint = async (box, x, y, sel = null) => {
1579
1780
  const deadline = Date.now() + COVER_CHECK_MS;
1580
- let hit = await hitInBox(box, x, y);
1781
+ let hit = await hitInBox(box, x, y, sel);
1581
1782
  while (hit === false && Date.now() < deadline) {
1582
1783
  await sleep(80);
1583
- hit = await hitInBox(box, x, y);
1584
- }
1585
- if (hit !== null)
1586
- return hit;
1587
- // Only Playwright's trial can look inside a child frame. It moves the pointer: the cost of a point
1588
- // the isolated world cannot see, never of an ordinary click.
1589
- const at = { x: x - box.x, y: y - box.y };
1590
- try {
1591
- await orig(selector, { trial: true, timeout: COVER_CHECK_MS, position: at });
1592
- return true;
1593
- }
1594
- catch (e) {
1595
- if (!isTimeout(e) || String(e?.message ?? e).includes("intercepts pointer events"))
1596
- return false;
1597
- }
1598
- try {
1599
- // Not covered, just not "stable" yet: on the first page of a fresh headless browser Playwright's
1600
- // animation-frame wait can outlast the first look. One longer look.
1601
- await orig(selector, { trial: true, timeout: COVER_RETRY_MS, position: at });
1602
- return true;
1784
+ hit = await hitInBox(box, x, y, sel);
1785
+ }
1786
+ return hit;
1787
+ };
1788
+ // The viewport point of Playwright's `position` (relative to the PADDING box: the border widths are added).
1789
+ const positionPoint = async (box, pos) => {
1790
+ const info = await describe(box, null);
1791
+ const bl = info ? info.bl || 0 : 0, bt = info ? info.bt || 0 : 0;
1792
+ return { x: box.x + bl + pos.x, y: box.y + bt + pos.y };
1793
+ };
1794
+ // `trial: true`, answered by the SDK: Playwright's actionability checks -- visible, enabled (not for
1795
+ // hover), stable, and the click point receives the press (the browser's own hit test, read in the
1796
+ // isolated world) -- retried until the caller's timeout (or the page default), then a Playwright
1797
+ // TimeoutError. NO pointer move and NO press: Playwright's own trial moves the real pointer onto the
1798
+ // target and dispatches pointerdown/pointerup/click that page listeners registered before its blocker
1799
+ // see (SC 209: 6/6). The point checked is Playwright's: `position`, else the centre. Scrolling the
1800
+ // element into view is part of the checks, as in Playwright. With `force` only the element must exist.
1801
+ const trial = async (selector, options, noClick) => {
1802
+ const opts = options ?? {};
1803
+ const o = normalizeClickOptions(opts);
1804
+ const ms = typeof opts.timeout === "number" ? opts.timeout : defaultTimeoutMs(page);
1805
+ const end = ms > 0 ? Date.now() + ms : null;
1806
+ const left = () => (end === null ? 0 : Math.max(1, Math.round(end - Date.now())));
1807
+ const loc = page.locator(selector).first();
1808
+ if (o.force) {
1809
+ await loc.waitFor({ state: "attached", timeout: left() });
1810
+ return;
1603
1811
  }
1604
- catch {
1605
- return false;
1812
+ for (;;) {
1813
+ let why = "element is not visible";
1814
+ const box = await boxOf(loc, left(), false, selector); // waits for visible; throws Playwright's timeout
1815
+ if (box) {
1816
+ if (!noClick && !(await loc.isEnabled())) {
1817
+ why = "element is not enabled";
1818
+ }
1819
+ else {
1820
+ const { x, y } = o.position ? await positionPoint(box, o.position)
1821
+ : { x: box.x + box.width / 2, y: box.y + box.height / 2 };
1822
+ await sleep(50); // stable: 50 ms on, the element still fills `box` (ISO_HIT_IN_BOX)
1823
+ if ((await hitInBox(box, x, y, selector)) !== false)
1824
+ return; // null: the hit test cannot run -- nothing to add
1825
+ why = `element is not stable, or another element would receive the pointer at (${Math.round(x)}, ${Math.round(y)})`;
1826
+ }
1827
+ }
1828
+ if (end !== null && Date.now() >= end)
1829
+ throw trialTimeoutError(selector, ms, why);
1830
+ await sleep(end === null ? 100 : Math.max(0, Math.min(100, end - Date.now())));
1606
1831
  }
1607
1832
  };
1608
1833
  // The humanized form of page.click / dblclick / hover (and the click inside check/uncheck and the
@@ -1610,12 +1835,13 @@ export async function attachHumanize(browser, page, opts) {
1610
1835
  //
1611
1836
  // Every Playwright option is honoured: `button`, `clickCount`, `delay` (the hold) and `modifiers`
1612
1837
  // shape the press; `position` replaces the persona's point; `force` skips the covered-point check
1613
- // (and, as in Playwright, every wait); `trial` performs NO action (it runs Playwright's own trial, as
1614
- // documented). The caller's `timeout` is passed through unchanged. No Playwright trial runs before a
1615
- // humanized press (reachesPoint): only a point inside a child frame still needs one.
1838
+ // (and, as in Playwright, every wait); `trial` performs NO action: its checks run here (trial), with
1839
+ // no pointer move and no press. The caller's `timeout` is passed through unchanged. No Playwright
1840
+ // trial runs before a humanized press either (reachesPoint).
1616
1841
  const targetedClick = async (orig, selector, options, noClick, nativeOpts) => {
1617
1842
  const opts = options ?? {};
1618
1843
  const o = normalizeClickOptions(opts);
1844
+ let aim = null; // where Playwright's own click lands, once the box is known (native)
1619
1845
  const native = async () => {
1620
1846
  if (!orig)
1621
1847
  throw new Error("humanized click could not run");
@@ -1624,12 +1850,19 @@ export async function attachHumanize(browser, page, opts) {
1624
1850
  }
1625
1851
  finally {
1626
1852
  // Native click/hover genuinely move the browser pointer to the element. Leaving `placed`
1627
- // false afterwards made the next wheel anchor believe the pointer was still unplaced.
1853
+ // false afterwards made the next wheel anchor believe the pointer was still unplaced -- and the
1854
+ // engine path walked again from its own stale point (engineInSync; verifier A #6). The next
1855
+ // SDK glide starts where Playwright pressed: `position`, else the centre of the box.
1628
1856
  st.placed = true;
1857
+ eng.at = null;
1858
+ if (aim) {
1859
+ st.x = aim.x;
1860
+ st.y = aim.y;
1861
+ }
1629
1862
  }
1630
1863
  };
1631
1864
  if (o.trial)
1632
- return native();
1865
+ return trial(selector, opts, noClick);
1633
1866
  try {
1634
1867
  const timeout = opts.timeout; // undefined: the page's default, as Playwright would use
1635
1868
  const loc = page.locator(selector).first();
@@ -1638,29 +1871,38 @@ export async function attachHumanize(browser, page, opts) {
1638
1871
  const box = await boxOf(loc, timeout, o.force, selector);
1639
1872
  if (!box)
1640
1873
  throw new NativeSignal();
1874
+ aim = { x: box.x + box.width / 2, y: box.y + box.height / 2 };
1641
1875
  if (!o.force && !(await loc.isEnabled()))
1642
1876
  throw new NativeSignal();
1643
1877
  let x, y;
1644
1878
  if (o.position) {
1645
- // Playwright's position is relative to the PADDING box: add the border widths.
1646
- const info = await describe(box, null);
1647
- const bl = info ? info.bl || 0 : 0, bt = info ? info.bt || 0 : 0;
1648
- x = box.x + bl + o.position.x;
1649
- y = box.y + bt + o.position.y;
1879
+ ({ x, y } = await positionPoint(box, o.position));
1880
+ aim = { x, y };
1650
1881
  }
1651
1882
  else {
1652
1883
  ({ x, y } = clickPoint(box, st, persona));
1653
1884
  }
1885
+ // Whole pixels: the hit test below answers for the pixel DOM.getNodeForLocation rounds to, so the
1886
+ // press goes to that pixel too. A press at 971.6 next to a badge ending at 972 was proven at 972 and
1887
+ // landed on the badge, reported as a success (verifier B, SC 210).
1888
+ x = roundHalfEven(x);
1889
+ y = roundHalfEven(y);
1654
1890
  if (!o.force && orig) {
1655
1891
  // Stability, then covered-by: 50 ms on, the element must still fill `box` (an animation in
1656
1892
  // flight does not) and own the click point -- no trusted press at a point some overlay owns.
1657
1893
  // Either failing goes native: Playwright waits for it.
1658
1894
  await sleep(50);
1659
- if (!(await reachesPoint(orig, selector, box, x, y)))
1895
+ if (!(await reachesPoint(box, x, y, selector)))
1660
1896
  throw new NativeSignal();
1661
1897
  }
1662
1898
  if (o.modifiers.length && !(nativeKbDown && nativeKbUp))
1663
1899
  throw new NativeSignal();
1900
+ if (!noClick && !o.force && orig && engineClicksMode() === "all" && enginePathOk(o) && await engineGlide(x, y, false)) {
1901
+ // Opt-in (CLEARCOTE_HUMANIZE_ENGINE_CLICKS=all): the engine walks the approach and clicks the
1902
+ // point the hit test above proved; plain left single clicks only, and only while the engine
1903
+ // knows where the pointer is (engineInSync). Otherwise: the planner.
1904
+ return;
1905
+ }
1664
1906
  if (noClick && o.modifiers.length) {
1665
1907
  // hover with modifiers: Playwright holds them across the move
1666
1908
  const held = [];
@@ -1695,8 +1937,23 @@ export async function attachHumanize(browser, page, opts) {
1695
1937
  // outside the try, so a native call that raises is not run a second time by the handler
1696
1938
  return native();
1697
1939
  };
1698
- page.click = (selector, options = {}) => locked(() => targetedClick(nativePageClick, selector, options, false, null));
1699
- page.hover = (selector, options = {}) => locked(() => targetedClick(nativePageHover, selector, options, true, null));
1940
+ page.click = apiErrors("page.click", (selector, options = {}) => locked(() => targetedClick(nativePageClick, selector, options, false, null)));
1941
+ page.hover = apiErrors("page.hover", (selector, options = {}) => locked(() => targetedClick(nativePageHover, selector, options, true, null)));
1942
+ // Locator.dragTo({ trial: true }) answers its checks here too (see the Locator patch).
1943
+ page._clearcoteTrial = (selector, options, noClick) => locked(() => trial(selector, options, noClick));
1944
+ // pressAndHold (hold.ts): the hooks it reads off the page. It holds the page lock for the whole hold
1945
+ // (one action at a time); inside it uses page.mouse (not locked) and these hooks. _clearcoteNudge is
1946
+ // the tremor step: a native move (no glide) that keeps the tracked position where the pointer is.
1947
+ page._clearcoteBoxOf = (loc, timeout, selector = null) => boxOf(loc, timeout, false, selector);
1948
+ page._clearcotePointer = () => ({ x: st.x, y: st.y });
1949
+ page._clearcoteNudge = async (x, y) => {
1950
+ await nativeMove(x, y);
1951
+ st.x = x;
1952
+ st.y = y;
1953
+ st.placed = true;
1954
+ };
1955
+ page._clearcoteHold = (loc, o) => locked(() => pressAndHold(loc, o));
1956
+ page.pressAndHold = apiErrors("page.pressAndHold", (selector, o) => page._clearcoteHold(page.locator(selector).first(), o));
1700
1957
  // Marker the Locator-class patch keys off: humanize is active for THIS page.
1701
1958
  page._clearcoteHumanized = true;
1702
1959
  patchLocatorClass(page.locator("html"));
@@ -1817,66 +2074,109 @@ function patchLocatorClass(sample) {
1817
2074
  return [true, await fn()];
1818
2075
  return [false, undefined];
1819
2076
  };
1820
- proto.fill = async function (value, kw = {}) {
2077
+ // Every routed method words its errors as Playwright words the Locator method (asApiError): through
2078
+ // page.*, an error read "page.click: ..." or "locator.waitFor: ...".
2079
+ const apiMethod = (api, fn) => async function (...a) {
2080
+ try {
2081
+ return await fn.apply(this, a);
2082
+ }
2083
+ catch (e) {
2084
+ throw asApiError(e, api);
2085
+ }
2086
+ };
2087
+ // Playwright's tap rejects at once in a context without hasTouch ("The page does not support tap");
2088
+ // routed as a click it clicked instead (SC 210 error parity). A context it cannot read is routed.
2089
+ const noTouch = (self) => {
2090
+ try {
2091
+ return self.page().context()._options.hasTouch !== true;
2092
+ }
2093
+ catch {
2094
+ return false;
2095
+ }
2096
+ };
2097
+ proto.fill = apiMethod("locator.fill", async function (value, kw = {}) {
1821
2098
  const [done, r] = await route(this, () => this.page().fill(sel(this), value, pickOptions(kw, FILL_OPTS)));
1822
2099
  return done ? r : oFill.call(this, value, kw);
1823
- };
1824
- proto.click = async function (kw = {}) {
2100
+ });
2101
+ proto.click = apiMethod("locator.click", async function (kw = {}) {
1825
2102
  const [done, r] = await route(this, () => this.page().click(sel(this), pickOptions(kw, CLICK_OPTS)));
1826
2103
  return done ? r : oClick.call(this, kw);
1827
- };
1828
- proto.type = async function (text, kw = {}) {
2104
+ });
2105
+ proto.type = apiMethod("locator.type", async function (text, kw = {}) {
1829
2106
  const [done, r] = await route(this, () => this.page().type(sel(this), text, pickOptions(kw, TYPE_OPTS)));
1830
2107
  return done ? r : oType.call(this, text, kw);
1831
- };
1832
- proto.dblclick = async function (kw = {}) {
2108
+ });
2109
+ proto.dblclick = apiMethod("locator.dblclick", async function (kw = {}) {
1833
2110
  const [done, r] = await route(this, () => this.page().dblclick(sel(this), pickOptions(kw, DBL_OPTS)));
1834
2111
  return done ? r : oDbl.call(this, kw);
1835
- };
1836
- proto.hover = async function (kw = {}) {
2112
+ });
2113
+ proto.hover = apiMethod("locator.hover", async function (kw = {}) {
1837
2114
  const [done, r] = await route(this, () => this.page().hover(sel(this), pickOptions(kw, HOVER_OPTS)));
1838
2115
  return done ? r : oHover.call(this, kw);
1839
- };
1840
- proto.press = async function (key, kw = {}) {
2116
+ });
2117
+ proto.press = apiMethod("locator.press", async function (key, kw = {}) {
1841
2118
  const [done, r] = await route(this, () => this.page().press(sel(this), key, pickOptions(kw, PRESS_OPTS)));
1842
2119
  return done ? r : oPress.call(this, key, kw);
1843
- };
1844
- proto.pressSequentially = async function (text, kw = {}) {
2120
+ });
2121
+ proto.pressSequentially = apiMethod("locator.pressSequentially", async function (text, kw = {}) {
1845
2122
  const [done, r] = await route(this, () => this.page().type(sel(this), text, pickOptions(kw, TYPE_OPTS)));
1846
2123
  return done ? r : oPressSeq.call(this, text, kw);
1847
- };
1848
- proto.clear = async function (kw = {}) {
2124
+ });
2125
+ proto.clear = apiMethod("locator.clear", async function (kw = {}) {
1849
2126
  const [done, r] = await route(this, () => this.page().fill(sel(this), "", pickOptions(kw, FILL_OPTS)));
1850
2127
  return done ? r : oClear.call(this, kw);
1851
- };
1852
- proto.tap = async function (kw = {}) {
2128
+ });
2129
+ proto.tap = apiMethod("locator.tap", async function (kw = {}) {
2130
+ if (noTouch(this))
2131
+ return oTap.call(this, kw);
1853
2132
  const [done, r] = await route(this, () => this.page().click(sel(this), pickOptions(kw, HOVER_OPTS)));
1854
2133
  return done ? r : oTap.call(this, kw);
1855
- };
1856
- proto.check = async function (kw = {}) {
2134
+ });
2135
+ proto.check = apiMethod("locator.check", async function (kw = {}) {
1857
2136
  const [done, r] = await route(this, () => this.page().check(sel(this), pickOptions(kw, CHECK_OPTS)));
1858
2137
  return done ? r : oCheck.call(this, kw);
1859
- };
1860
- proto.uncheck = async function (kw = {}) {
2138
+ });
2139
+ proto.uncheck = apiMethod("locator.uncheck", async function (kw = {}) {
1861
2140
  const [done, r] = await route(this, () => this.page().uncheck(sel(this), pickOptions(kw, CHECK_OPTS)));
1862
2141
  return done ? r : oUncheck.call(this, kw);
1863
- };
2142
+ });
1864
2143
  if (typeof oSetChecked === "function") {
1865
- proto.setChecked = async function (checked, kw = {}) {
2144
+ proto.setChecked = apiMethod("locator.setChecked", async function (checked, kw = {}) {
1866
2145
  const [done, r] = await route(this, () => this.page().setChecked(sel(this), checked, pickOptions(kw, CHECK_OPTS)));
1867
2146
  return done ? r : oSetChecked.call(this, checked, kw);
1868
- };
2147
+ });
1869
2148
  }
1870
2149
  // Delegate to the humanized page.selectOption, like every other method here: one implementation
1871
2150
  // behind the page method is what stops the two entry points drifting apart.
1872
2151
  if (typeof oSelectOption === "function") {
1873
- proto.selectOption = async function (values, kw = {}) {
2152
+ proto.selectOption = apiMethod("locator.selectOption", async function (values, kw = {}) {
1874
2153
  const [done, r] = await route(this, () => this.page().selectOption(sel(this), values, pickOptions(kw, SELECT_OPTS)));
1875
2154
  return done ? r : oSelectOption.call(this, values, kw);
1876
- };
2155
+ });
1877
2156
  }
1878
- proto.dragTo = async function (target, kw = {}) {
1879
- if (on(this)) {
2157
+ // New, not a Playwright method: press and hold this element (hold.ts), under the page lock when the
2158
+ // page is humanized. Works on frame locators and non-humanized pages too: it presses at viewport
2159
+ // coordinates through page.mouse.
2160
+ proto.pressAndHold = apiMethod("locator.pressAndHold", async function (kw) {
2161
+ const hold = this.page()._clearcoteHold;
2162
+ return typeof hold === "function" ? hold(this, kw) : pressAndHold(this, kw);
2163
+ });
2164
+ proto.dragTo = apiMethod("locator.dragTo", async function (target, kw = {}) {
2165
+ if (kw?.trial && on(this) && on(target) && await strict(this) && await strict(target)) {
2166
+ // Playwright's drag trial moves the pointer onto the source and presses there (SC 209); the SDK
2167
+ // runs the checks of both ends instead: visible, stable, receives the pointer.
2168
+ const t = this.page()._clearcoteTrial;
2169
+ if (typeof t === "function") {
2170
+ for (const [loc, pos] of [[this, kw.sourcePosition], [target, kw.targetPosition]]) {
2171
+ const o = pickOptions(kw, ["force", "timeout"]);
2172
+ if (pos)
2173
+ o.position = pos;
2174
+ await t(sel(loc), o, true);
2175
+ }
2176
+ return;
2177
+ }
2178
+ }
2179
+ if (on(this) && !kw?.trial) {
1880
2180
  try {
1881
2181
  const pg = this.page();
1882
2182
  const sb = await this.boundingBox();
@@ -1889,9 +2189,8 @@ function patchLocatorClass(sample) {
1889
2189
  const persona = pg._clearcotePersona;
1890
2190
  const { grabMs, releaseMs } = persona ? dragDwell(persona) : { grabMs: rand(130, 360), releaseMs: rand(90, 230) };
1891
2191
  await pg.mouse.move(sx, sy);
1892
- await sleep(rand(100, 200));
1893
2192
  await pg.mouse.down();
1894
- await sleep(grabMs); // grab hesitation (native -> button held across glide)
2193
+ await sleep(grabMs); // pre-press pause inside down(); then the grab hesitation
1895
2194
  const heldGlide = pg._clearcoteHeldGlide; // humanized held-button drag + seating jiggle (settle)
1896
2195
  if (heldGlide)
1897
2196
  await heldGlide(tx, ty);
@@ -1905,7 +2204,7 @@ function patchLocatorClass(sample) {
1905
2204
  catch { /* fall back */ }
1906
2205
  }
1907
2206
  return oDragTo.call(this, target, kw);
1908
- };
2207
+ });
1909
2208
  }
1910
2209
  /** Install humanize/showCursor on a browser: wraps newPage/newContext so every page is covered. */
1911
2210
  export function installHumanize(browser, opts) {
@@ -1924,7 +2223,14 @@ export function installHumanize(browser, opts) {
1924
2223
  return ctx;
1925
2224
  };
1926
2225
  }
1927
- /** Install humanize/showCursor on a single context (used for launchPersistentContext). */
2226
+ /** Install humanize/showCursor on a single context (used for launchPersistentContext).
2227
+ *
2228
+ * Attaches whether or not the context has a Browser. A persistent context has none on older
2229
+ * playwright-core (context.browser() is null on 1.49.x), and launch() is a persistent context by
2230
+ * default: this used to attach only when a Browser was found, so on those versions humanize was
2231
+ * silently off. attachHumanize needs only the page; the engine route takes the browser from the
2232
+ * page's context when there is one and uses the page's own CDP session when there is not (there the
2233
+ * engine answers only to the pre-r34 name, POINTER_PATH_LEGACY: one miss per context, measured on r38). */
1928
2234
  export function installHumanizeOnContext(context, opts, browser) {
1929
2235
  if (!opts.humanize && !opts.showCursor)
1930
2236
  return;
@@ -1932,10 +2238,8 @@ export function installHumanizeOnContext(context, opts, browser) {
1932
2238
  if (opts.showCursor) {
1933
2239
  context.addInitScript(CURSOR_OVERLAY).catch(() => { });
1934
2240
  }
1935
- if (b) {
1936
- context.on("page", (p) => { attachHumanize(b, p, opts).catch(() => { }); });
1937
- for (const p of context.pages())
1938
- attachHumanize(b, p, opts).catch(() => { });
1939
- }
2241
+ context.on("page", (p) => { attachHumanize(b, p, opts).catch(() => { }); });
2242
+ for (const p of context.pages())
2243
+ attachHumanize(b, p, opts).catch(() => { });
1940
2244
  }
1941
2245
  //# sourceMappingURL=humanize.js.map