@humanjs/playwright 0.4.0 → 0.6.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/index.js CHANGED
@@ -63,6 +63,73 @@ async function dispatchKey(page, key) {
63
63
  await page.keyboard.insertText(key);
64
64
  }
65
65
  }
66
+ async function executePaste(target, value, ctx) {
67
+ if (value.length === 0) return { characters: 0 };
68
+ const locator = typeof target === "string" ? ctx.page.locator(target) : target;
69
+ await locator.focus();
70
+ await ctx.page.keyboard.insertText(value);
71
+ return { characters: value.length };
72
+ }
73
+ async function executePress(key, ctx) {
74
+ const dispatched = resolveChord(key);
75
+ await ctx.page.keyboard.press(dispatched);
76
+ return { dispatched };
77
+ }
78
+ function resolveChord(key) {
79
+ const parts = key.split("+").map((p) => p.trim()).filter((p) => p.length > 0);
80
+ if (parts.length === 0) {
81
+ throw new Error(`Invalid key: ${JSON.stringify(key)} \u2014 empty or only separators`);
82
+ }
83
+ const keyToken = parts[parts.length - 1];
84
+ if (keyToken === void 0) {
85
+ throw new Error(`Invalid key: ${JSON.stringify(key)} \u2014 missing key`);
86
+ }
87
+ const modifierTokens = parts.slice(0, -1);
88
+ const modifiers = [];
89
+ for (const token of modifierTokens) {
90
+ const resolved = resolveModifier(token);
91
+ if (resolved === null) {
92
+ throw new Error(
93
+ `Invalid key modifier: ${JSON.stringify(token)} in ${JSON.stringify(key)}. Use one of: Mod/CmdOrCtrl/CommandOrControl, Cmd/Command/Meta/Win/Super, Ctrl/Control, Alt/Option/Opt, Shift.`
94
+ );
95
+ }
96
+ modifiers.push(resolved);
97
+ }
98
+ return [...modifiers, normalizeKey(keyToken)].join("+");
99
+ }
100
+ function resolveModifier(token) {
101
+ const lower = token.toLowerCase();
102
+ switch (lower) {
103
+ case "mod":
104
+ case "cmdorctrl":
105
+ case "commandorcontrol":
106
+ return isMac() ? "Meta" : "Control";
107
+ case "cmd":
108
+ case "command":
109
+ case "meta":
110
+ case "win":
111
+ case "super":
112
+ return "Meta";
113
+ case "ctrl":
114
+ case "control":
115
+ return "Control";
116
+ case "alt":
117
+ case "option":
118
+ case "opt":
119
+ return "Alt";
120
+ case "shift":
121
+ return "Shift";
122
+ default:
123
+ return null;
124
+ }
125
+ }
126
+ function normalizeKey(key) {
127
+ if (key.length === 1) return key.toUpperCase();
128
+ return key.charAt(0).toUpperCase() + key.slice(1);
129
+ }
130
+ function isMac() {
131
+ return process.platform === "darwin";
132
+ }
66
133
 
67
134
  // src/internal/mouse-walk.ts
68
135
  async function walkMouseAlongPath(page, path, durationMs) {
@@ -77,31 +144,198 @@ async function walkMouseAlongPath(page, path, durationMs) {
77
144
  }
78
145
  }
79
146
  }
147
+ var RESERVED_TARGETS = /* @__PURE__ */ new Set(["natural", "end", "top"]);
148
+ async function executeScroll(target, ctx, options = {}) {
149
+ const { page, personality, rng, speed } = ctx;
150
+ const speedFactor = speedModeFactor(speed);
151
+ const axis = options.axis ?? "y";
152
+ const container = resolveWithin(options.within, ctx);
153
+ const geom = container ? await readContainerGeometry(container, axis) : await readWindowGeometry(page, axis);
154
+ if (!geom) {
155
+ return { from: 0, to: 0, distance: 0, durationMs: 0 };
156
+ }
157
+ const from = geom.current;
158
+ const targetPos = await resolveTarget(target, ctx, geom, container, axis, options.block);
159
+ const to = clamp(targetPos, 0, Math.max(0, geom.total - geom.viewport));
160
+ const distance = to - from;
161
+ if (distance === 0) {
162
+ return { from, to, distance: 0, durationMs: 0 };
163
+ }
164
+ if (speed === "instant") {
165
+ if (container) {
166
+ await container.evaluate(
167
+ (el, args) => {
168
+ const a = args;
169
+ if (a.axis === "x") el.scrollTo(a.pos, el.scrollTop);
170
+ else el.scrollTo(el.scrollLeft, a.pos);
171
+ },
172
+ { axis, pos: to }
173
+ );
174
+ } else {
175
+ await page.evaluate(
176
+ (args) => {
177
+ if (args.axis === "x") window.scrollTo(args.pos, window.scrollY);
178
+ else window.scrollTo(window.scrollX, args.pos);
179
+ },
180
+ { axis, pos: to }
181
+ );
182
+ }
183
+ return { from, to, distance, durationMs: 0 };
184
+ }
185
+ const segments = planScroll(from, to, personality.scroll, rng, {
186
+ forceOvershoot: options.overshoot,
187
+ withPauses: options.withPauses,
188
+ personalitySpeed: personality.speed,
189
+ speedFactor
190
+ });
191
+ if (container && geom.hover) {
192
+ await page.mouse.move(geom.hover.x, geom.hover.y);
193
+ }
194
+ const startedAt = Date.now();
195
+ await walkSegments(page, segments, axis, container);
196
+ const durationMs = Date.now() - startedAt;
197
+ return { from, to, distance, durationMs };
198
+ }
199
+ function resolveWithin(within, ctx) {
200
+ if (!within) return null;
201
+ return typeof within === "string" ? ctx.page.locator(within) : within;
202
+ }
203
+ async function readWindowGeometry(page, axis) {
204
+ const g = await page.evaluate((a) => {
205
+ if (a === "x") {
206
+ return {
207
+ current: window.scrollX,
208
+ viewport: window.innerWidth,
209
+ total: Math.max(document.documentElement.scrollWidth, document.body?.scrollWidth ?? 0)
210
+ };
211
+ }
212
+ return {
213
+ current: window.scrollY,
214
+ viewport: window.innerHeight,
215
+ total: Math.max(document.documentElement.scrollHeight, document.body?.scrollHeight ?? 0)
216
+ };
217
+ }, axis);
218
+ return { current: g.current, viewport: g.viewport, total: g.total };
219
+ }
220
+ async function readContainerGeometry(container, axis) {
221
+ return container.evaluate((el, a) => {
222
+ const rect = el.getBoundingClientRect();
223
+ const isX = a === "x";
224
+ return {
225
+ current: isX ? el.scrollLeft : el.scrollTop,
226
+ viewport: isX ? el.clientWidth : el.clientHeight,
227
+ total: isX ? el.scrollWidth : el.scrollHeight,
228
+ hover: {
229
+ x: rect.left + rect.width / 2,
230
+ y: rect.top + rect.height / 2
231
+ }
232
+ };
233
+ }, axis).catch(() => null);
234
+ }
235
+ async function resolveTarget(target, ctx, geom, container, axis, block = "start") {
236
+ if (target === void 0 || target === "natural") return geom.current + geom.viewport;
237
+ if (target === "end") return geom.total;
238
+ if (target === "top") return 0;
239
+ if (typeof target === "object" && "by" in target) return geom.current + target.by;
240
+ if (typeof target === "object" && "to" in target) return target.to;
241
+ const elementLocator = typeof target === "string" && !RESERVED_TARGETS.has(target) ? ctx.page.locator(target) : typeof target === "string" ? null : target;
242
+ if (!elementLocator) return geom.current + geom.viewport;
243
+ return container ? resolveElementWithinContainer(elementLocator, container, geom, axis, block) : resolveElementInWindow(elementLocator, geom, axis, block);
244
+ }
245
+ async function resolveElementInWindow(elementLocator, geom, axis, block) {
246
+ const rect = await elementLocator.boundingBox().catch(() => null);
247
+ if (!rect) return geom.current;
248
+ const relStart = axis === "x" ? rect.x : rect.y;
249
+ const length = axis === "x" ? rect.width : rect.height;
250
+ const absoluteStart = geom.current + relStart;
251
+ const absoluteEnd = absoluteStart + length;
252
+ if (block === "start") return absoluteStart;
253
+ if (block === "end") return absoluteEnd - geom.viewport;
254
+ if (block === "nearest") {
255
+ if (relStart >= 0 && relStart + length <= geom.viewport) return geom.current;
256
+ if (relStart < 0) return absoluteStart;
257
+ return absoluteEnd - geom.viewport;
258
+ }
259
+ return absoluteStart - (geom.viewport - length) / 2;
260
+ }
261
+ async function resolveElementWithinContainer(elementLocator, container, geom, axis, block) {
262
+ const rects = await container.evaluate(
263
+ (containerEl, args) => {
264
+ const elementEl = args.sel ? document.querySelector(args.sel) : null;
265
+ const targetEl = elementEl ?? containerEl.querySelector(":scope > *");
266
+ if (!targetEl) return null;
267
+ const cRect = containerEl.getBoundingClientRect();
268
+ const eRect = targetEl.getBoundingClientRect();
269
+ return args.axis === "x" ? { relStart: eRect.left - cRect.left, length: eRect.width } : { relStart: eRect.top - cRect.top, length: eRect.height };
270
+ },
271
+ { sel: await locatorSelector(elementLocator), axis }
272
+ ).catch(() => null);
273
+ if (!rects) return geom.current;
274
+ const offsetStart = rects.relStart + geom.current;
275
+ const offsetEnd = offsetStart + rects.length;
276
+ if (block === "start") return offsetStart;
277
+ if (block === "end") return offsetEnd - geom.viewport;
278
+ if (block === "nearest") {
279
+ if (rects.relStart >= 0 && rects.relStart + rects.length <= geom.viewport) {
280
+ return geom.current;
281
+ }
282
+ if (rects.relStart < 0) return offsetStart;
283
+ return offsetEnd - geom.viewport;
284
+ }
285
+ return offsetStart - (geom.viewport - rects.length) / 2;
286
+ }
287
+ async function locatorSelector(locator) {
288
+ const s = locator.toString?.();
289
+ if (typeof s !== "string") return null;
290
+ const match = /locator\(['"](.+?)['"]/.exec(s);
291
+ if (!match) return null;
292
+ const raw = match[1] ?? "";
293
+ const eq = raw.indexOf("=");
294
+ return eq > 0 && /^[a-z]+$/.test(raw.slice(0, eq)) ? raw.slice(eq + 1) : raw;
295
+ }
296
+ async function walkSegments(page, segments, axis, container) {
297
+ for (const segment of segments) {
298
+ if (segment.delayBeforeMs > 0) await sleep(segment.delayBeforeMs);
299
+ if (segment.delta === 0) continue;
300
+ if (container) {
301
+ await container.evaluate(
302
+ (el, args) => {
303
+ const a = args;
304
+ if (a.axis === "x") el.scrollLeft += a.delta;
305
+ else el.scrollTop += a.delta;
306
+ },
307
+ { axis, delta: segment.delta }
308
+ );
309
+ } else if (axis === "x") {
310
+ await page.mouse.wheel(segment.delta, 0);
311
+ } else {
312
+ await page.mouse.wheel(0, segment.delta);
313
+ }
314
+ }
315
+ }
316
+ function clamp(value, min, max) {
317
+ return value < min ? min : value > max ? max : value;
318
+ }
80
319
 
81
320
  // src/mouse/index.ts
82
- async function executeClick(target, ctx) {
83
- const locator = typeof target === "string" ? ctx.page.locator(target) : target;
321
+ async function executeClick(target, ctx, options = {}) {
322
+ const button = options.button ?? "left";
84
323
  if (ctx.speed === "instant") {
324
+ if (isPoint(target)) {
325
+ await ctx.page.mouse.click(target.x, target.y, { button });
326
+ ctx.setMousePosition(target);
327
+ return { target };
328
+ }
329
+ const locator = typeof target === "string" ? ctx.page.locator(target) : target;
85
330
  const box2 = await locator.boundingBox();
86
- await locator.click();
331
+ await locator.click({ button });
87
332
  const center = box2 ? { x: box2.x + box2.width / 2, y: box2.y + box2.height / 2 } : ctx.getMousePosition();
88
333
  ctx.setMousePosition(center);
89
334
  return { target: center };
90
335
  }
91
- const box = await locator.boundingBox();
92
- if (!box) {
93
- throw new Error(
94
- `Cannot click: element not found or has no bounding box (target: ${describeTarget(target)})`
95
- );
96
- }
97
- const targetPoint = pickClickPoint(box, ctx.rng);
98
- const startPoint = ctx.getMousePosition();
99
- const rawPath = bezierPath(startPoint, targetPoint, ctx.rng, {
100
- curvature: ctx.personality.mouse.curvature
101
- });
102
- const path = humanizePath(rawPath, ctx.rng);
103
- const travelMs = computeTravelTime(path, ctx.personality, ctx.speed, ctx.rng);
104
- await walkMouseAlongPath(ctx.page, path, travelMs);
336
+ const { point: targetPoint, box } = await resolveTargetPointAndBox(target, ctx, "click");
337
+ await maybeMisclickBeat(ctx, box, targetPoint);
338
+ await walkBezierTo(targetPoint, ctx);
105
339
  const preClickMs = computeDwellTime(
106
340
  ctx.personality.dwell.preClickMs,
107
341
  ctx.personality.dwell.preClickJitter,
@@ -111,7 +345,7 @@ async function executeClick(target, ctx) {
111
345
  );
112
346
  if (preClickMs > 0) await sleep(preClickMs);
113
347
  ctx.setMousePosition(targetPoint);
114
- await ctx.page.mouse.click(targetPoint.x, targetPoint.y);
348
+ await ctx.page.mouse.click(targetPoint.x, targetPoint.y, { button });
115
349
  const postActionMs = computeDwellTime(
116
350
  ctx.personality.dwell.postActionMs,
117
351
  ctx.personality.dwell.postActionJitter,
@@ -122,11 +356,248 @@ async function executeClick(target, ctx) {
122
356
  if (postActionMs > 0) await sleep(postActionMs);
123
357
  return { target: targetPoint };
124
358
  }
125
- function pickClickPoint(box, rng) {
359
+ async function executeHover(target, ctx) {
360
+ if (ctx.speed === "instant") {
361
+ const box = await readBoxWithAutoScroll(target, ctx, "hover");
362
+ const center = { x: box.x + box.width / 2, y: box.y + box.height / 2 };
363
+ await ctx.page.mouse.move(center.x, center.y);
364
+ ctx.setMousePosition(center);
365
+ return { target: center };
366
+ }
367
+ const targetPoint = await moveToTarget(target, ctx);
368
+ const dwellMs = computeDwellTime(
369
+ ctx.personality.dwell.preClickMs,
370
+ ctx.personality.dwell.preClickJitter,
371
+ ctx.personality,
372
+ ctx.speed,
373
+ ctx.rng
374
+ );
375
+ if (dwellMs > 0) await sleep(dwellMs);
376
+ ctx.setMousePosition(targetPoint);
377
+ return { target: targetPoint };
378
+ }
379
+ async function executeDrag(from, to, ctx) {
380
+ const scrollYBeforeResolve = await readScrollY(ctx.page);
381
+ let { point: fromPoint, box: fromBox } = await resolveTargetPointAndBox(from, ctx, "drag");
382
+ let { point: toPoint, box: toBox } = await resolveTargetPointAndBox(to, ctx, "drag");
383
+ const resolveScrollDelta = await readScrollY(ctx.page) - scrollYBeforeResolve;
384
+ if (resolveScrollDelta !== 0) {
385
+ if (isPoint(from)) fromPoint = { x: fromPoint.x, y: fromPoint.y - resolveScrollDelta };
386
+ if (isPoint(to)) toPoint = { x: toPoint.x, y: toPoint.y - resolveScrollDelta };
387
+ }
388
+ if (ctx.speed === "instant") {
389
+ await ctx.page.mouse.move(fromPoint.x, fromPoint.y);
390
+ await ctx.page.mouse.down();
391
+ await ctx.page.mouse.move(toPoint.x, toPoint.y);
392
+ await ctx.page.mouse.up();
393
+ ctx.setMousePosition(toPoint);
394
+ return { from: fromPoint, to: toPoint };
395
+ }
396
+ if (fromBox && toBox) {
397
+ const scrollDelta = computeCurveScrollDelta(
398
+ fromPoint,
399
+ toPoint,
400
+ ctx.page.viewportSize(),
401
+ ctx.personality.mouse.curvature
402
+ );
403
+ if (scrollDelta !== 0) {
404
+ await executeScroll({ by: scrollDelta }, ctx, {});
405
+ const refreshedFrom = await resolveTargetPointAndBox(from, ctx, "drag");
406
+ fromPoint = refreshedFrom.point;
407
+ fromBox = refreshedFrom.box;
408
+ const refreshedTo = await resolveTargetPointAndBox(to, ctx, "drag");
409
+ toPoint = refreshedTo.point;
410
+ toBox = refreshedTo.box;
411
+ }
412
+ }
413
+ await maybeMisclickBeat(ctx, fromBox, fromPoint);
414
+ await walkBezierTo(fromPoint, ctx);
415
+ ctx.setMousePosition(fromPoint);
416
+ const preDragMs = computeDwellTime(
417
+ ctx.personality.dwell.preClickMs,
418
+ ctx.personality.dwell.preClickJitter,
419
+ ctx.personality,
420
+ ctx.speed,
421
+ ctx.rng
422
+ );
423
+ if (preDragMs > 0) await sleep(preDragMs);
424
+ await ctx.page.mouse.down();
425
+ await maybeMisclickBeat(ctx, toBox, toPoint);
426
+ await walkBezierTo(toPoint, ctx);
427
+ await ctx.page.mouse.up();
428
+ ctx.setMousePosition(toPoint);
429
+ const postActionMs = computeDwellTime(
430
+ ctx.personality.dwell.postActionMs,
431
+ ctx.personality.dwell.postActionJitter,
432
+ ctx.personality,
433
+ ctx.speed,
434
+ ctx.rng
435
+ );
436
+ if (postActionMs > 0) await sleep(postActionMs);
437
+ return { from: fromPoint, to: toPoint };
438
+ }
439
+ async function executeMove(target, ctx) {
440
+ const point = await resolveTargetPoint(target, ctx, "move");
441
+ if (ctx.speed === "instant") {
442
+ await ctx.page.mouse.move(point.x, point.y);
443
+ ctx.setMousePosition(point);
444
+ return { target: point };
445
+ }
446
+ await walkBezierTo(point, ctx);
447
+ ctx.setMousePosition(point);
448
+ return { target: point };
449
+ }
450
+ async function moveToTarget(target, ctx) {
451
+ const box = await readBoxWithAutoScroll(target, ctx, "hover");
452
+ const targetPoint = pickClickPoint(box, ctx.rng, ctx.personality.mouse.clickSpread);
453
+ await walkBezierTo(targetPoint, ctx);
454
+ return targetPoint;
455
+ }
456
+ async function walkBezierTo(to, ctx) {
457
+ const startPoint = ctx.getMousePosition();
458
+ const rawPath = bezierPath(startPoint, to, ctx.rng, {
459
+ curvature: ctx.personality.mouse.curvature
460
+ });
461
+ const path = humanizePath(rawPath, ctx.rng);
462
+ const travelMs = computeTravelTime(path, ctx.personality, ctx.speed, ctx.rng);
463
+ await walkMouseAlongPath(ctx.page, path, travelMs);
464
+ }
465
+ async function resolveTargetPoint(target, ctx, action) {
466
+ if (isPoint(target)) return target;
467
+ return resolveLocatorPoint(target, ctx, action);
468
+ }
469
+ async function resolveTargetPointAndBox(target, ctx, action) {
470
+ if (isPoint(target)) return { point: target, box: null };
471
+ const box = await readBoxWithAutoScroll(target, ctx, action);
472
+ const point = pickClickPoint(box, ctx.rng, ctx.personality.mouse.clickSpread);
473
+ return { point, box };
474
+ }
475
+ async function resolveLocatorPoint(target, ctx, action) {
476
+ const box = await readBoxWithAutoScroll(target, ctx, action);
477
+ return pickClickPoint(box, ctx.rng, ctx.personality.mouse.clickSpread);
478
+ }
479
+ async function readBoxWithAutoScroll(target, ctx, action) {
480
+ const locator = typeof target === "string" ? ctx.page.locator(target) : target;
481
+ let box = await locator.boundingBox();
482
+ if (!box) {
483
+ throw new Error(
484
+ `Cannot ${action}: element not found or has no bounding box (target: ${describeTarget(target)})`
485
+ );
486
+ }
487
+ const viewport = ctx.page.viewportSize();
488
+ if (viewport && !isBoxCenterInViewport(box, viewport)) {
489
+ if (ctx.speed === "instant") {
490
+ await locator.scrollIntoViewIfNeeded();
491
+ } else {
492
+ await executeScroll(locator, ctx, { block: "center" });
493
+ }
494
+ box = await locator.boundingBox();
495
+ if (!box) {
496
+ throw new Error(
497
+ `Cannot ${action}: element disappeared after scrolling into view (target: ${describeTarget(target)})`
498
+ );
499
+ }
500
+ }
501
+ return box;
502
+ }
503
+ function isBoxCenterInViewport(box, viewport) {
504
+ const cx = box.x + box.width / 2;
505
+ const cy = box.y + box.height / 2;
506
+ return cx >= 0 && cx <= viewport.width && cy >= 0 && cy <= viewport.height;
507
+ }
508
+ async function readScrollY(page) {
509
+ if (typeof page.evaluate !== "function") return 0;
510
+ return page.evaluate(() => window.scrollY);
511
+ }
512
+ var CURVE_VIEWPORT_MARGIN = 20;
513
+ function computeCurveScrollDelta(from, to, viewport, curvature) {
514
+ if (!viewport) return 0;
515
+ const distance = Math.hypot(to.x - from.x, to.y - from.y);
516
+ const perpendicularExtent = distance * curvature;
517
+ const minY = Math.min(from.y, to.y) - perpendicularExtent;
518
+ const maxY = Math.max(from.y, to.y) + perpendicularExtent;
519
+ const topOverflow = -minY + CURVE_VIEWPORT_MARGIN;
520
+ const bottomOverflow = maxY + CURVE_VIEWPORT_MARGIN - viewport.height;
521
+ if (bottomOverflow > 0 && bottomOverflow >= topOverflow) return bottomOverflow;
522
+ if (topOverflow > 0) return -topOverflow;
523
+ return 0;
524
+ }
525
+ function isPoint(target) {
526
+ return typeof target === "object" && target !== null && !("boundingBox" in target) && typeof target.x === "number" && typeof target.y === "number";
527
+ }
528
+ var MISCLICK_OFFSET_MIN = 5;
529
+ var MISCLICK_OFFSET_MAX = 15;
530
+ async function maybeMisclickBeat(ctx, box, targetPoint) {
531
+ if (!ctx.rng.chance(ctx.personality.mouse.misclickProbability)) return;
532
+ if (cursorAlreadyOnTarget(ctx.getMousePosition(), box, targetPoint)) return;
533
+ const viewport = ctx.page.viewportSize();
534
+ const misclickPoint = box ? pickMisclickOutsideBox(box, ctx.rng, viewport) : pickMisclickAroundPoint(targetPoint, ctx.rng, viewport);
535
+ if (misclickPoint === null) return;
536
+ await walkBezierTo(misclickPoint, ctx);
537
+ ctx.setMousePosition(misclickPoint);
538
+ const realizeMs = computeDwellTime(
539
+ ctx.personality.dwell.preClickMs,
540
+ ctx.personality.dwell.preClickJitter,
541
+ ctx.personality,
542
+ ctx.speed,
543
+ ctx.rng
544
+ );
545
+ if (realizeMs > 0) await sleep(realizeMs);
546
+ }
547
+ function cursorAlreadyOnTarget(current, box, targetPoint) {
548
+ if (box) {
549
+ return current.x >= box.x && current.x <= box.x + box.width && current.y >= box.y && current.y <= box.y + box.height;
550
+ }
551
+ const dx = current.x - targetPoint.x;
552
+ const dy = current.y - targetPoint.y;
553
+ return Math.hypot(dx, dy) < MISCLICK_OFFSET_MIN;
554
+ }
555
+ function pickMisclickOutsideBox(box, rng, viewport) {
556
+ const edge = rng.nextInt(0, 4);
557
+ const offset = rng.nextFloat(MISCLICK_OFFSET_MIN, MISCLICK_OFFSET_MAX);
558
+ const along = rng.nextFloat(0.2, 0.8);
559
+ let x;
560
+ let y;
561
+ if (edge === 0) {
562
+ x = box.x + box.width * along;
563
+ y = box.y - offset;
564
+ } else if (edge === 1) {
565
+ x = box.x + box.width + offset;
566
+ y = box.y + box.height * along;
567
+ } else if (edge === 2) {
568
+ x = box.x + box.width * along;
569
+ y = box.y + box.height + offset;
570
+ } else {
571
+ x = box.x - offset;
572
+ y = box.y + box.height * along;
573
+ }
574
+ if (viewport) {
575
+ x = clamp2(x, 0, viewport.width - 1);
576
+ y = clamp2(y, 0, viewport.height - 1);
577
+ }
578
+ const insideBox = x >= box.x && x <= box.x + box.width && y >= box.y && y <= box.y + box.height;
579
+ if (insideBox) return null;
580
+ return { x, y };
581
+ }
582
+ function pickMisclickAroundPoint(target, rng, viewport) {
583
+ const angle = rng.nextFloat(0, Math.PI * 2);
584
+ const distance = rng.nextFloat(MISCLICK_OFFSET_MIN, MISCLICK_OFFSET_MAX);
585
+ let x = target.x + Math.cos(angle) * distance;
586
+ let y = target.y + Math.sin(angle) * distance;
587
+ if (viewport) {
588
+ x = clamp2(x, 0, viewport.width - 1);
589
+ y = clamp2(y, 0, viewport.height - 1);
590
+ }
591
+ if (x === target.x && y === target.y) return null;
592
+ return { x, y };
593
+ }
594
+ function pickClickPoint(box, rng, clickSpread) {
126
595
  const cx = box.x + box.width / 2;
127
596
  const cy = box.y + box.height / 2;
128
- const x = clamp(cx + rng.nextGaussian(0, box.width / 8), box.x, box.x + box.width);
129
- const y = clamp(cy + rng.nextGaussian(0, box.height / 8), box.y, box.y + box.height);
597
+ const sigmaX = box.width * clickSpread;
598
+ const sigmaY = box.height * clickSpread;
599
+ const x = clamp2(cx + rng.nextGaussian(0, sigmaX), box.x, box.x + box.width);
600
+ const y = clamp2(cy + rng.nextGaussian(0, sigmaY), box.y, box.y + box.height);
130
601
  return { x, y };
131
602
  }
132
603
  function computeTravelTime(path, personality, speed, rng) {
@@ -144,9 +615,10 @@ function computeTravelTime(path, personality, speed, rng) {
144
615
  return Math.max(0, total);
145
616
  }
146
617
  function describeTarget(target) {
618
+ if (isPoint(target)) return `point(${target.x}, ${target.y})`;
147
619
  return typeof target === "string" ? target : target.toString?.() ?? "locator";
148
620
  }
149
- function clamp(value, min, max) {
621
+ function clamp2(value, min, max) {
150
622
  return value < min ? min : value > max ? max : value;
151
623
  }
152
624
  async function executeRead(target, ctx, options = {}) {
@@ -630,178 +1102,6 @@ async function startCapture(page, options = {}) {
630
1102
  }
631
1103
  };
632
1104
  }
633
- var RESERVED_TARGETS = /* @__PURE__ */ new Set(["natural", "end", "top"]);
634
- async function executeScroll(target, ctx, options = {}) {
635
- const { page, personality, rng, speed } = ctx;
636
- const speedFactor = speedModeFactor(speed);
637
- const axis = options.axis ?? "y";
638
- const container = resolveWithin(options.within, ctx);
639
- const geom = container ? await readContainerGeometry(container, axis) : await readWindowGeometry(page, axis);
640
- if (!geom) {
641
- return { from: 0, to: 0, distance: 0, durationMs: 0 };
642
- }
643
- const from = geom.current;
644
- const targetPos = await resolveTarget(target, ctx, geom, container, axis, options.block);
645
- const to = clamp2(targetPos, 0, Math.max(0, geom.total - geom.viewport));
646
- const distance = to - from;
647
- if (distance === 0) {
648
- return { from, to, distance: 0, durationMs: 0 };
649
- }
650
- if (speed === "instant") {
651
- if (container) {
652
- await container.evaluate(
653
- (el, args) => {
654
- const a = args;
655
- if (a.axis === "x") el.scrollTo(a.pos, el.scrollTop);
656
- else el.scrollTo(el.scrollLeft, a.pos);
657
- },
658
- { axis, pos: to }
659
- );
660
- } else {
661
- await page.evaluate(
662
- (args) => {
663
- if (args.axis === "x") window.scrollTo(args.pos, window.scrollY);
664
- else window.scrollTo(window.scrollX, args.pos);
665
- },
666
- { axis, pos: to }
667
- );
668
- }
669
- return { from, to, distance, durationMs: 0 };
670
- }
671
- const segments = planScroll(from, to, personality.scroll, rng, {
672
- forceOvershoot: options.overshoot,
673
- withPauses: options.withPauses,
674
- personalitySpeed: personality.speed,
675
- speedFactor
676
- });
677
- if (container && geom.hover) {
678
- await page.mouse.move(geom.hover.x, geom.hover.y);
679
- }
680
- const startedAt = Date.now();
681
- await walkSegments(page, segments, axis, container);
682
- const durationMs = Date.now() - startedAt;
683
- return { from, to, distance, durationMs };
684
- }
685
- function resolveWithin(within, ctx) {
686
- if (!within) return null;
687
- return typeof within === "string" ? ctx.page.locator(within) : within;
688
- }
689
- async function readWindowGeometry(page, axis) {
690
- const g = await page.evaluate((a) => {
691
- if (a === "x") {
692
- return {
693
- current: window.scrollX,
694
- viewport: window.innerWidth,
695
- total: Math.max(document.documentElement.scrollWidth, document.body?.scrollWidth ?? 0)
696
- };
697
- }
698
- return {
699
- current: window.scrollY,
700
- viewport: window.innerHeight,
701
- total: Math.max(document.documentElement.scrollHeight, document.body?.scrollHeight ?? 0)
702
- };
703
- }, axis);
704
- return { current: g.current, viewport: g.viewport, total: g.total };
705
- }
706
- async function readContainerGeometry(container, axis) {
707
- return container.evaluate((el, a) => {
708
- const rect = el.getBoundingClientRect();
709
- const isX = a === "x";
710
- return {
711
- current: isX ? el.scrollLeft : el.scrollTop,
712
- viewport: isX ? el.clientWidth : el.clientHeight,
713
- total: isX ? el.scrollWidth : el.scrollHeight,
714
- hover: {
715
- x: rect.left + rect.width / 2,
716
- y: rect.top + rect.height / 2
717
- }
718
- };
719
- }, axis).catch(() => null);
720
- }
721
- async function resolveTarget(target, ctx, geom, container, axis, block = "start") {
722
- if (target === void 0 || target === "natural") return geom.current + geom.viewport;
723
- if (target === "end") return geom.total;
724
- if (target === "top") return 0;
725
- if (typeof target === "object" && "by" in target) return geom.current + target.by;
726
- if (typeof target === "object" && "to" in target) return target.to;
727
- const elementLocator = typeof target === "string" && !RESERVED_TARGETS.has(target) ? ctx.page.locator(target) : typeof target === "string" ? null : target;
728
- if (!elementLocator) return geom.current + geom.viewport;
729
- return container ? resolveElementWithinContainer(elementLocator, container, geom, axis, block) : resolveElementInWindow(elementLocator, geom, axis, block);
730
- }
731
- async function resolveElementInWindow(elementLocator, geom, axis, block) {
732
- const rect = await elementLocator.boundingBox().catch(() => null);
733
- if (!rect) return geom.current;
734
- const relStart = axis === "x" ? rect.x : rect.y;
735
- const length = axis === "x" ? rect.width : rect.height;
736
- const absoluteStart = geom.current + relStart;
737
- const absoluteEnd = absoluteStart + length;
738
- if (block === "start") return absoluteStart;
739
- if (block === "end") return absoluteEnd - geom.viewport;
740
- if (block === "nearest") {
741
- if (relStart >= 0 && relStart + length <= geom.viewport) return geom.current;
742
- if (relStart < 0) return absoluteStart;
743
- return absoluteEnd - geom.viewport;
744
- }
745
- return absoluteStart - (geom.viewport - length) / 2;
746
- }
747
- async function resolveElementWithinContainer(elementLocator, container, geom, axis, block) {
748
- const rects = await container.evaluate(
749
- (containerEl, args) => {
750
- const elementEl = args.sel ? document.querySelector(args.sel) : null;
751
- const targetEl = elementEl ?? containerEl.querySelector(":scope > *");
752
- if (!targetEl) return null;
753
- const cRect = containerEl.getBoundingClientRect();
754
- const eRect = targetEl.getBoundingClientRect();
755
- return args.axis === "x" ? { relStart: eRect.left - cRect.left, length: eRect.width } : { relStart: eRect.top - cRect.top, length: eRect.height };
756
- },
757
- { sel: await locatorSelector(elementLocator), axis }
758
- ).catch(() => null);
759
- if (!rects) return geom.current;
760
- const offsetStart = rects.relStart + geom.current;
761
- const offsetEnd = offsetStart + rects.length;
762
- if (block === "start") return offsetStart;
763
- if (block === "end") return offsetEnd - geom.viewport;
764
- if (block === "nearest") {
765
- if (rects.relStart >= 0 && rects.relStart + rects.length <= geom.viewport) {
766
- return geom.current;
767
- }
768
- if (rects.relStart < 0) return offsetStart;
769
- return offsetEnd - geom.viewport;
770
- }
771
- return offsetStart - (geom.viewport - rects.length) / 2;
772
- }
773
- async function locatorSelector(locator) {
774
- const s = locator.toString?.();
775
- if (typeof s !== "string") return null;
776
- const match = /locator\(['"](.+?)['"]/.exec(s);
777
- if (!match) return null;
778
- const raw = match[1] ?? "";
779
- const eq = raw.indexOf("=");
780
- return eq > 0 && /^[a-z]+$/.test(raw.slice(0, eq)) ? raw.slice(eq + 1) : raw;
781
- }
782
- async function walkSegments(page, segments, axis, container) {
783
- for (const segment of segments) {
784
- if (segment.delayBeforeMs > 0) await sleep(segment.delayBeforeMs);
785
- if (segment.delta === 0) continue;
786
- if (container) {
787
- await container.evaluate(
788
- (el, args) => {
789
- const a = args;
790
- if (a.axis === "x") el.scrollLeft += a.delta;
791
- else el.scrollTop += a.delta;
792
- },
793
- { axis, delta: segment.delta }
794
- );
795
- } else if (axis === "x") {
796
- await page.mouse.wheel(segment.delta, 0);
797
- } else {
798
- await page.mouse.wheel(0, segment.delta);
799
- }
800
- }
801
- }
802
- function clamp2(value, min, max) {
803
- return value < min ? min : value > max ? max : value;
804
- }
805
1105
 
806
1106
  // src/mouse-helper/index.ts
807
1107
  var CURSOR_PATH = "M 0 0 L 16 6 L 8 9.5 L 5 19 Z";
@@ -966,6 +1266,23 @@ async function createHuman(page, options = {}) {
966
1266
  }
967
1267
  }
968
1268
  let lastMousePosition = options.initialMousePosition ?? { x: 0, y: 0 };
1269
+ const mouseCtx = () => ({
1270
+ page,
1271
+ personality,
1272
+ rng,
1273
+ speed,
1274
+ getMousePosition: () => lastMousePosition,
1275
+ setMousePosition: (point) => {
1276
+ lastMousePosition = point;
1277
+ }
1278
+ });
1279
+ const describeMouseTarget = (target) => {
1280
+ if (typeof target === "string") return target;
1281
+ if ("x" in target && "y" in target && typeof target.x === "number") {
1282
+ return `point(${target.x}, ${target.y})`;
1283
+ }
1284
+ return target.toString?.() ?? "locator";
1285
+ };
969
1286
  return {
970
1287
  personality,
971
1288
  speed,
@@ -975,29 +1292,65 @@ async function createHuman(page, options = {}) {
975
1292
  });
976
1293
  },
977
1294
  async click(target) {
978
- const description = typeof target === "string" ? target : target.toString?.() ?? "locator";
1295
+ const description = describeMouseTarget(target);
979
1296
  await performAction({ type: "click", params: { target: description } }, async () => {
980
- await executeClick(target, {
981
- page,
982
- personality,
983
- rng,
984
- speed,
985
- getMousePosition: () => lastMousePosition,
986
- setMousePosition: (point) => {
987
- lastMousePosition = point;
988
- }
989
- });
1297
+ await executeClick(target, mouseCtx());
1298
+ });
1299
+ },
1300
+ async rightClick(target) {
1301
+ const description = describeMouseTarget(target);
1302
+ await performAction({ type: "rightClick", params: { target: description } }, async () => {
1303
+ await executeClick(target, mouseCtx(), { button: "right" });
1304
+ });
1305
+ },
1306
+ async hover(target) {
1307
+ const description = describeMouseTarget(target);
1308
+ await performAction({ type: "hover", params: { target: description } }, async () => {
1309
+ await executeHover(target, mouseCtx());
1310
+ });
1311
+ },
1312
+ async move(target) {
1313
+ const description = describeMouseTarget(target);
1314
+ await performAction({ type: "move", params: { target: description } }, async () => {
1315
+ await executeMove(target, mouseCtx());
1316
+ });
1317
+ },
1318
+ async drag(from, to) {
1319
+ const fromDesc = describeMouseTarget(from);
1320
+ const toDesc = describeMouseTarget(to);
1321
+ await performAction({ type: "drag", params: { from: fromDesc, to: toDesc } }, async () => {
1322
+ await executeDrag(from, to, mouseCtx());
990
1323
  });
991
1324
  },
992
1325
  async type(target, value) {
993
- const description = typeof target === "string" ? target : target.toString?.() ?? "locator";
1326
+ const description = describeMouseTarget(target);
994
1327
  await performAction(
995
1328
  { type: "type", params: { target: description, length: value.length } },
996
1329
  async () => {
1330
+ if (speed !== "instant" && value.length > 0) {
1331
+ await executeClick(target, mouseCtx());
1332
+ }
997
1333
  await executeType(target, value, { page, personality, rng, speed });
998
1334
  }
999
1335
  );
1000
1336
  },
1337
+ async paste(target, value) {
1338
+ const description = describeMouseTarget(target);
1339
+ await performAction(
1340
+ { type: "paste", params: { target: description, length: value.length } },
1341
+ async () => {
1342
+ if (speed !== "instant" && value.length > 0) {
1343
+ await executeClick(target, mouseCtx());
1344
+ }
1345
+ await executePaste(target, value, { page, personality, rng, speed });
1346
+ }
1347
+ );
1348
+ },
1349
+ async press(key) {
1350
+ await performAction({ type: "press", params: { key } }, async () => {
1351
+ await executePress(key, { page, personality, rng, speed });
1352
+ });
1353
+ },
1001
1354
  async read(target, options2) {
1002
1355
  const description = describeReadTarget(target);
1003
1356
  return performAction(
@@ -1081,6 +1434,52 @@ async function createHuman(page, options = {}) {
1081
1434
  speed,
1082
1435
  events
1083
1436
  });
1437
+ },
1438
+ // ────────────────────────────────────────────────────────────────────
1439
+ // Thin re-exports of common Playwright `Page` methods. See the `Human`
1440
+ // interface for the rationale; implementations forward unchanged.
1441
+ // ────────────────────────────────────────────────────────────────────
1442
+ screenshot(opts) {
1443
+ return page.screenshot(opts);
1444
+ },
1445
+ pageText() {
1446
+ return page.innerText("body");
1447
+ },
1448
+ content() {
1449
+ return page.content();
1450
+ },
1451
+ url() {
1452
+ return page.url();
1453
+ },
1454
+ title() {
1455
+ return page.title();
1456
+ },
1457
+ async reload(opts) {
1458
+ await performAction({ type: "reload", params: {} }, async () => {
1459
+ await page.reload(opts);
1460
+ });
1461
+ },
1462
+ async goBack(opts) {
1463
+ await performAction({ type: "goBack", params: {} }, async () => {
1464
+ await page.goBack(opts);
1465
+ });
1466
+ },
1467
+ async goForward(opts) {
1468
+ await performAction({ type: "goForward", params: {} }, async () => {
1469
+ await page.goForward(opts);
1470
+ });
1471
+ },
1472
+ waitForLoadState(state, opts) {
1473
+ return page.waitForLoadState(state, opts);
1474
+ },
1475
+ waitForURL(url, opts) {
1476
+ return page.waitForURL(url, opts);
1477
+ },
1478
+ setViewportSize(size) {
1479
+ return page.setViewportSize(size);
1480
+ },
1481
+ pdf(opts) {
1482
+ return page.pdf(opts);
1084
1483
  }
1085
1484
  };
1086
1485
  }