clearcote 0.64.2 → 0.65.1

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
@@ -35,8 +35,8 @@ import { keepInView, trimTo, walk } from "./pacing.js";
35
35
  import { record as traceRecord, traceEnabled } from "./trace.js";
36
36
  import { pressAndHold } from "./hold.js";
37
37
  import { BLANK_POINT, FOCUSABLE, SEARCH_SLIP_RATE, SELECTION_STATE, TAB_DISTANCE, WORD_FIX_RATE, flightMs, modifierLagMs, modifierLeadMs, planGap, planRepeat, splitChord, submitPauseMs, tabPauseMs, typingTraits, } from "./keys.js";
38
- import { COVER_CHECK_MS, COVER_RETRY_MS, ISO_ACTIVE_FIELD, ISO_ACTIVE_VALUE, ISO_CSS_BOX, ISO_DESCRIBE, ISO_FORM_CONTROL, ISO_FRAMES, ISO_HIT_IN_BOX, ISO_LABEL_BY_SEL, ISO_LABEL_OF, ISO_LISTBOX_ROW, ISO_PLATFORM, ISO_SCROLL_BY, ISO_VIEWPORT, roundHalfEven, worldFor, } from "./isolated.js";
39
- import { NATIVE, frameLocatorOf, frameRoute, humanized as frameHumanized } from "./frames.js";
38
+ import { COVER_CHECK_MS, COVER_RETRY_MS, SETTLE_MS, SETTLE_TRIES, ISO_COVER, ISO_ACTIVE_FIELD, ISO_ACTIVE_VALUE, ISO_CSS_BOX, ISO_DESCRIBE, ISO_FORM_CONTROL, ISO_FRAMES, ISO_HIT_IN_BOX, ISO_LABEL_BY_SEL, ISO_LABEL_OF, ISO_LISTBOX_ROW, ISO_PLATFORM, ISO_SCROLL_BY, ISO_VIEWPORT, roundHalfEven, worldFor, } from "./isolated.js";
39
+ import { NATIVE, frameLocatorOf, frameRoute, handleAsLocator, humanized as frameHumanized } from "./frames.js";
40
40
  export { reportFallback, strictMode } from "./frames.js";
41
41
  /** The error a strict-mode tap raises on a touch context (lane F, SC 232). */
42
42
  export const TAP_NOT_HUMANIZED = "tap is not humanized for touch contexts yet";
@@ -58,7 +58,7 @@ export function labelDraw(persona, rng = Math.random) {
58
58
  return rng() < labelShare(persona);
59
59
  }
60
60
  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, ENGINE_KEY_SEQUENCE, engineClickParams, engineHeldBits, engineKeyPlan, } from "./forms.js";
61
- import { applyToPersona, engineModeFor, optionsOf, reportFallback, resolveHumanize, typoRateFor, withCallerApi, } from "./hzoptions.js";
61
+ import { applyToPersona, callerApi, engineModeFor, inHumanizedCall, optionsOf, reportFallback, resolveHumanize, typoRateFor, withCallerApi, } from "./hzoptions.js";
62
62
  export { ClearcoteStrictError } from "./hzoptions.js";
63
63
  /** Overlay: a red dot that follows real mousemove events. Idempotent IIFE so it works both as
64
64
  * an addInitScript source string AND when passed to page.evaluate. */
@@ -344,6 +344,7 @@ export async function attachHumanize(browser, page, opts) {
344
344
  const tempo = hz.tempo; // preset: every planned duration x1.4 / x1.0 / x0.7
345
345
  // The stock methods, for per-call { humanize: false } (wired at the end of attach).
346
346
  const stockPage = {}, stockMouse = {}, stockKb = {};
347
+ patchPageClass(page); // before the stock methods are taken: they are the scoped prototype methods
347
348
  for (const n of PAGE_METHODS)
348
349
  if (typeof page[n] === "function")
349
350
  stockPage[n] = page[n].bind(page);
@@ -932,6 +933,7 @@ export async function attachHumanize(browser, page, opts) {
932
933
  traceRecord("wheel", wrec, { device, dx, dy });
933
934
  }
934
935
  };
936
+ const wheelHuman = mouse.wheel; // unlocked: for use inside a locked action
935
937
  const wheelRun = async (device, dx, dy, sendWheel) => {
936
938
  if (device === "trackpad") {
937
939
  // A trackpad persona swipes the exact distance: 2-40 px events at the persona's 60-120/s on a min-jerk
@@ -2833,6 +2835,60 @@ export async function attachHumanize(browser, page, opts) {
2833
2835
  }
2834
2836
  return hit;
2835
2837
  };
2838
+ // The element's box once it has stopped moving: two reads ~100 ms apart within 1 px, for up to SETTLE_MS.
2839
+ // null when it never settles or has no box. Read like boxOf (the isolated CSS read, else boundingBox),
2840
+ // with the wheel, so a target the settling scroll left out of view is brought back in.
2841
+ const sameBox = (a, b) => Math.abs(a.x - b.x) <= 1 && Math.abs(a.y - b.y) <= 1
2842
+ && Math.abs(a.width - b.width) <= 1 && Math.abs(a.height - b.height) <= 1;
2843
+ const settledBox = async (loc, timeout, selector) => {
2844
+ const deadline = Date.now() + SETTLE_MS;
2845
+ let prev = await boxOf(loc, timeout, false, selector);
2846
+ while (prev && Date.now() < deadline) {
2847
+ await sleep(100);
2848
+ const next = await boxOf(loc, timeout, false, selector);
2849
+ if (!next)
2850
+ return null;
2851
+ if (sameBox(prev, next))
2852
+ return next;
2853
+ prev = next;
2854
+ }
2855
+ return null;
2856
+ };
2857
+ // A target that is not moving yet fails the hit test is covered. Two covers a person deals with without
2858
+ // thinking, which used to send the click to Playwright (r53 /audit, seed 2, 2026-10-28):
2859
+ // - something the pointer itself opened: it rested on a header link and a hover menu dropped over the
2860
+ // target. The hand moves off it (below it where there is room, else above) and the menu closes;
2861
+ // - a fixed or sticky bar (a site header) over a target the scroll left under it: the wheel brings the
2862
+ // target down into the band a reader looks at.
2863
+ // true when it did one of them (the caller re-reads the box and hit-tests again).
2864
+ const uncover = async (box, x, y) => {
2865
+ const c = await worldFor(page).evaluate(ISO_COVER, { x, y, b: { x: box.x, y: box.y, width: box.width, height: box.height } });
2866
+ if (!c || !Array.isArray(c.rect))
2867
+ return false;
2868
+ const [cx, cy, cw, ch] = c.rect.map(Number);
2869
+ const vp = await viewport();
2870
+ if (st.x >= cx && st.x <= cx + cw && st.y >= cy && st.y <= cy + ch) {
2871
+ // Off its edge by 6-80 px where the viewport has room (a mega menu can leave only a strip), below first.
2872
+ const roomBelow = vp.height - 4 - (cy + ch + 6), roomAbove = cy - 6 - 4;
2873
+ const ty = roomBelow >= 0 ? cy + ch + 6 + rand(0, Math.min(74, roomBelow))
2874
+ : roomAbove >= 0 ? cy - 6 - rand(0, Math.min(74, roomAbove)) : null;
2875
+ if (ty === null)
2876
+ return false;
2877
+ const tx = Math.min(vp.width - 8, Math.max(8, box.x + box.width / 2 + rand(-60, 60)));
2878
+ await glide(tx, ty);
2879
+ await sleep(rand(250, 450)); // a hover menu's close transition
2880
+ return true;
2881
+ }
2882
+ // A cover filling most of the viewport is a modal or a cookie wall, not a bar to scroll out from under.
2883
+ if (c.fixed && cw * ch <= 0.8 * vp.width * vp.height) {
2884
+ const dy = box.y + box.height / 2 - vp.height * rand(0.3, 0.5);
2885
+ if (Math.abs(dy) < 1)
2886
+ return false;
2887
+ await wheelHuman(0, dy);
2888
+ return true;
2889
+ }
2890
+ return false;
2891
+ };
2836
2892
  // The viewport point of Playwright's `position` (relative to the PADDING box: the border widths are added).
2837
2893
  const positionPoint = async (box, pos) => {
2838
2894
  const info = await describe(box, null);
@@ -2918,31 +2974,55 @@ export async function attachHumanize(browser, page, opts) {
2918
2974
  const loc = page.locator(selector).first();
2919
2975
  // Playwright skips actionability with force: no wait then -- a target it would click hidden goes
2920
2976
  // native at once instead of timing out first.
2921
- const box = await boxOf(loc, timeout, o.force, selector);
2977
+ let box = await boxOf(loc, timeout, o.force, selector);
2922
2978
  if (!box)
2923
2979
  throw new NativeSignal("the element has no box");
2924
- aim = { x: box.x + box.width / 2, y: box.y + box.height / 2 };
2925
2980
  if (!o.force && !(await loc.isEnabled()))
2926
2981
  throw new NativeSignal("the element is not enabled");
2927
- let x, y;
2928
- if (o.position) {
2929
- ({ x, y } = await positionPoint(box, o.position));
2930
- aim = { x, y };
2931
- }
2932
- else {
2933
- ({ x, y } = clickPoint(box, st, persona));
2934
- }
2935
- // Whole pixels: the hit test below answers for the pixel DOM.getNodeForLocation rounds to, so the
2936
- // press goes to that pixel too. A press at 971.6 next to a badge ending at 972 was proven at 972 and
2937
- // landed on the badge, reported as a success (verifier B, SC 210).
2938
- x = roundHalfEven(x);
2939
- y = roundHalfEven(y);
2982
+ let x = 0, y = 0;
2983
+ const aimAt = async (b) => {
2984
+ aim = { x: b.x + b.width / 2, y: b.y + b.height / 2 };
2985
+ if (o.position) {
2986
+ ({ x, y } = await positionPoint(b, o.position));
2987
+ aim = { x, y };
2988
+ }
2989
+ else {
2990
+ ({ x, y } = clickPoint(b, st, persona));
2991
+ }
2992
+ // Whole pixels: the hit test below answers for the pixel DOM.getNodeForLocation rounds to, so the
2993
+ // press goes to that pixel too. A press at 971.6 next to a badge ending at 972 was proven at 972 and
2994
+ // landed on the badge, reported as a success (verifier B, SC 210).
2995
+ x = roundHalfEven(x);
2996
+ y = roundHalfEven(y);
2997
+ };
2998
+ await aimAt(box);
2940
2999
  if (!o.force && orig) {
2941
3000
  // Stability, then covered-by: 50 ms on, the element must still fill `box` (an animation in
2942
3001
  // flight does not) and own the click point -- no trusted press at a point some overlay owns.
2943
3002
  // Either failing goes native: Playwright waits for it.
2944
3003
  await sleep(50);
2945
- const hit = await reachesPoint(box, x, y, selector);
3004
+ let hit = await reachesPoint(box, x, y, selector);
3005
+ // A target still moving (the scroll that brought it in settling, a layout shift) fails the test with
3006
+ // the box it had. Re-aim at the box it settles at rather than hand the click to Playwright, whose
3007
+ // press and release land in the same millisecond with a one-report jump from rest (/audit
3008
+ // pointer-press-dwell-duration, pointer-jump-from-rest; r53 seed 2, 2026-10-28).
3009
+ // A target that is covered rather than moving is uncovered first (uncover); what stays covered is
3010
+ // handled below.
3011
+ for (let tries = 0; hit === false && tries < SETTLE_TRIES; tries++) {
3012
+ let next = await settledBox(loc, timeout, selector);
3013
+ if (!next)
3014
+ break;
3015
+ if (sameBox(next, box)) {
3016
+ if (!(await uncover(next, x, y)))
3017
+ break;
3018
+ next = await settledBox(loc, timeout, selector);
3019
+ if (!next)
3020
+ break;
3021
+ }
3022
+ box = next;
3023
+ await aimAt(box);
3024
+ hit = await reachesPoint(box, x, y, selector);
3025
+ }
2946
3026
  if (hit === false && !o.position) {
2947
3027
  // The persona's point is covered (a badge, an icon, a floating label over the centre). Before
2948
3028
  // giving the click to Playwright -- which waited out its timeout on 5-7 of 16 badge-covered
@@ -3491,6 +3571,8 @@ export async function attachHumanize(browser, page, opts) {
3491
3571
  // Marker the Locator-class patch keys off: humanize is active for THIS page.
3492
3572
  page._clearcoteHumanized = true;
3493
3573
  patchLocatorClass(page.locator("html"));
3574
+ patchFrameClass(page.mainFrame());
3575
+ await patchHandleClass(page);
3494
3576
  }
3495
3577
  /** @internal exported for tests. Playwright's selectOption values -> the wanted options, or null when
3496
3578
  * the humane route does not apply (nothing asked, an ElementHandle, an option object naming more than
@@ -3987,6 +4069,144 @@ function patchLocatorClass(sample) {
3987
4069
  proto[name] = perCallOff(stock, proto[name]);
3988
4070
  }
3989
4071
  }
4072
+ // --------------------------------------------------------------------------- frame + element handle patch
4073
+ // The Frame API (frame.click(selector), page.mainFrame().fill(...)) and ElementHandle actions went straight to
4074
+ // Playwright: a 0.2 ms press, one teleporting move, 1-4 ms key holds, with no fallback report even in strict mode
4075
+ // (measured 2026-10-28, SC 295). Both now take the humanized routes the locators take.
4076
+ const FRAME_ACTIONS = ["click", "dblclick", "hover", "fill", "type", "press", "selectOption", "check", "uncheck", "setChecked", "tap", "focus"];
4077
+ const HANDLE_ACTIONS = ["click", "dblclick", "hover", "fill", "type", "press", "selectOption", "check", "uncheck", "setChecked"];
4078
+ /** ElementHandle actions whose first argument is not the options object (fill(value, options), ...). */
4079
+ const HANDLE_VALUE_FIRST = new Set(["fill", "type", "press", "selectOption", "setChecked"]);
4080
+ let framePatched = false;
4081
+ let handlePatching = null;
4082
+ let pagePatched = false;
4083
+ /** Playwright's own page.<action> is `this._mainFrame.<action>(...)`: run it as an SDK call so the Frame patch below
4084
+ * leaves it to Playwright. The stock call (`{ humanize: false }`, a native fallback, a caller reaching the
4085
+ * prototype) stays Playwright's, worded "page.<action>: ...". */
4086
+ function patchPageClass(sample) {
4087
+ if (pagePatched)
4088
+ return;
4089
+ const proto = sample && Object.getPrototypeOf(sample);
4090
+ if (!proto)
4091
+ return;
4092
+ pagePatched = true;
4093
+ for (const name of FRAME_ACTIONS) {
4094
+ const orig = proto[name];
4095
+ if (typeof orig !== "function")
4096
+ continue;
4097
+ proto[name] = function (...a) { return withCallerApi("page." + name, () => orig.apply(this, a)); };
4098
+ }
4099
+ }
4100
+ /** frame.<action>(selector, ...) on a humanized page runs as the locator action: `frame.locator(selector)`
4101
+ * (`.first()` unless the call asked for `strict`, Playwright's frame default), so a main-frame selector takes
4102
+ * the page route and a child frame's the frame route. Inside the SDK's own calls (Locator.click calls
4103
+ * frame.click; a native fallback) and on other pages, Playwright's own method. */
4104
+ function patchFrameClass(sample) {
4105
+ if (framePatched)
4106
+ return;
4107
+ const proto = sample && Object.getPrototypeOf(sample);
4108
+ if (!proto)
4109
+ return;
4110
+ framePatched = true;
4111
+ for (const name of FRAME_ACTIONS) {
4112
+ const orig = proto[name];
4113
+ if (typeof orig !== "function")
4114
+ continue;
4115
+ const api = "frame." + name;
4116
+ // Playwright words an error after the API the caller's code called, read off the stack: with this wrapper on
4117
+ // it, page.check's own error read "frame.check: ...". Worded after the SDK entry point running instead.
4118
+ const native = async (self, a) => {
4119
+ try {
4120
+ return await orig.apply(self, a);
4121
+ }
4122
+ catch (e) {
4123
+ const c = callerApi();
4124
+ throw c ? asApiError(e, c) : e;
4125
+ }
4126
+ };
4127
+ const routed = async function (selector, ...rest) {
4128
+ let pg = null;
4129
+ try {
4130
+ pg = this.page();
4131
+ }
4132
+ catch { /* a detached frame: Playwright's own call raises */ }
4133
+ if (!pg?._clearcoteHumanized || inHumanizedCall() || typeof selector !== "string")
4134
+ return native(this, [selector, ...rest]);
4135
+ return withCallerApi(api, async () => {
4136
+ const last = rest[rest.length - 1];
4137
+ let strict = false;
4138
+ if (last && typeof last === "object" && !Array.isArray(last) && "strict" in last) {
4139
+ const { strict: s, ...o } = last;
4140
+ strict = s === true;
4141
+ rest = [...rest.slice(0, -1), o];
4142
+ }
4143
+ const loc = strict ? this.locator(selector) : this.locator(selector).first();
4144
+ try {
4145
+ return await loc[name](...rest);
4146
+ }
4147
+ catch (e) {
4148
+ throw asApiError(e, api);
4149
+ }
4150
+ });
4151
+ };
4152
+ proto[name] = perCallOff(function (...a) { return native(this, a); }, routed);
4153
+ }
4154
+ }
4155
+ /** elementHandle.<action>(...) on a humanized page: the frame route (frames.ts) with the handle as its target --
4156
+ * the browser's own hit test proves the press lands on it, then the page's humanized mouse and keyboard. Where the
4157
+ * route does not apply it reports the fallback (strict mode throws) and Playwright's own method runs. The prototype
4158
+ * is read off one `:root` handle (a utility-world query; nothing runs in the page). */
4159
+ function patchHandleClass(page) {
4160
+ handlePatching ??= (async () => {
4161
+ let h = null;
4162
+ try {
4163
+ h = await page.mainFrame().$(":root");
4164
+ }
4165
+ catch { /* a closing page: the next page patches */ }
4166
+ const proto = h && Object.getPrototypeOf(h);
4167
+ if (h)
4168
+ h.dispose().catch(() => { });
4169
+ if (!proto) {
4170
+ handlePatching = null;
4171
+ return false;
4172
+ }
4173
+ for (const name of HANDLE_ACTIONS) {
4174
+ const orig = proto[name];
4175
+ if (typeof orig !== "function")
4176
+ continue;
4177
+ const api = "elementHandle." + name;
4178
+ const routed = async function (...a) {
4179
+ if (inHumanizedCall())
4180
+ return orig.apply(this, a);
4181
+ let frame = null;
4182
+ try {
4183
+ frame = await this.ownerFrame();
4184
+ }
4185
+ catch { /* disposed: Playwright's own call raises */ }
4186
+ let pg = null;
4187
+ try {
4188
+ pg = frame?.page();
4189
+ }
4190
+ catch { /* detached */ }
4191
+ if (!pg?._clearcoteHumanized)
4192
+ return orig.apply(this, a);
4193
+ return withCallerApi(api, async () => {
4194
+ const n = HANDLE_VALUE_FIRST.has(name) ? 1 : 0;
4195
+ try {
4196
+ const r = await frameRoute(handleAsLocator(this, frame, pg), name, a.slice(0, n), a[n] ?? {}, "elementHandle");
4197
+ return r === NATIVE ? await orig.apply(this, a) : r;
4198
+ }
4199
+ catch (e) {
4200
+ throw asApiError(e, api);
4201
+ }
4202
+ });
4203
+ };
4204
+ proto[name] = perCallOff(orig, routed);
4205
+ }
4206
+ return true;
4207
+ })();
4208
+ return handlePatching;
4209
+ }
3990
4210
  /** Install humanize/showCursor on a browser: wraps newPage/newContext so every page is covered. */
3991
4211
  export function installHumanize(browser, opts0) {
3992
4212
  // true | "strict" | HumanizeOptions: validated now (an unknown option throws), resolved once