@monoes/monobrowse 1.0.26 → 1.0.28

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.
Files changed (101) hide show
  1. package/dist/src/__tests__/disconnect-session.test.d.ts +13 -0
  2. package/dist/src/__tests__/disconnect-session.test.d.ts.map +1 -0
  3. package/dist/src/__tests__/disconnect-session.test.js +37 -0
  4. package/dist/src/__tests__/disconnect-session.test.js.map +1 -0
  5. package/dist/src/__tests__/profile-cleanup-close.test.d.ts +16 -0
  6. package/dist/src/__tests__/profile-cleanup-close.test.d.ts.map +1 -0
  7. package/dist/src/__tests__/profile-cleanup-close.test.js +250 -0
  8. package/dist/src/__tests__/profile-cleanup-close.test.js.map +1 -0
  9. package/dist/src/__tests__/profile-dir.test.d.ts +10 -0
  10. package/dist/src/__tests__/profile-dir.test.d.ts.map +1 -0
  11. package/dist/src/__tests__/profile-dir.test.js +160 -0
  12. package/dist/src/__tests__/profile-dir.test.js.map +1 -0
  13. package/dist/src/__tests__/setup/isolated-tmpdir.global.d.ts +2 -0
  14. package/dist/src/__tests__/setup/isolated-tmpdir.global.d.ts.map +1 -0
  15. package/dist/src/__tests__/setup/isolated-tmpdir.global.js +30 -0
  16. package/dist/src/__tests__/setup/isolated-tmpdir.global.js.map +1 -0
  17. package/dist/src/browser/actions-eval.d.ts +8 -0
  18. package/dist/src/browser/actions-eval.d.ts.map +1 -0
  19. package/dist/src/browser/actions-eval.js +72 -0
  20. package/dist/src/browser/actions-eval.js.map +1 -0
  21. package/dist/src/browser/actions-form.d.ts +10 -0
  22. package/dist/src/browser/actions-form.d.ts.map +1 -0
  23. package/dist/src/browser/actions-form.js +133 -0
  24. package/dist/src/browser/actions-form.js.map +1 -0
  25. package/dist/src/browser/actions-keyboard.d.ts +7 -0
  26. package/dist/src/browser/actions-keyboard.d.ts.map +1 -0
  27. package/dist/src/browser/actions-keyboard.js +131 -0
  28. package/dist/src/browser/actions-keyboard.js.map +1 -0
  29. package/dist/src/browser/actions-mouse.d.ts +11 -0
  30. package/dist/src/browser/actions-mouse.d.ts.map +1 -0
  31. package/dist/src/browser/actions-mouse.js +105 -0
  32. package/dist/src/browser/actions-mouse.js.map +1 -0
  33. package/dist/src/browser/actions.d.ts +12 -28
  34. package/dist/src/browser/actions.d.ts.map +1 -1
  35. package/dist/src/browser/actions.js +12 -434
  36. package/dist/src/browser/actions.js.map +1 -1
  37. package/dist/src/browser/browser-discovery.d.ts +26 -0
  38. package/dist/src/browser/browser-discovery.d.ts.map +1 -0
  39. package/dist/src/browser/browser-discovery.js +113 -0
  40. package/dist/src/browser/browser-discovery.js.map +1 -0
  41. package/dist/src/browser/browser-launch.d.ts +3 -0
  42. package/dist/src/browser/browser-launch.d.ts.map +1 -0
  43. package/dist/src/browser/browser-launch.js +341 -0
  44. package/dist/src/browser/browser-launch.js.map +1 -0
  45. package/dist/src/browser/browser-lifecycle.d.ts +57 -0
  46. package/dist/src/browser/browser-lifecycle.d.ts.map +1 -0
  47. package/dist/src/browser/browser-lifecycle.js +245 -0
  48. package/dist/src/browser/browser-lifecycle.js.map +1 -0
  49. package/dist/src/browser/browser-page.d.ts +13 -0
  50. package/dist/src/browser/browser-page.d.ts.map +1 -0
  51. package/dist/src/browser/browser-page.js +179 -0
  52. package/dist/src/browser/browser-page.js.map +1 -0
  53. package/dist/src/browser/browser-state.d.ts +11 -0
  54. package/dist/src/browser/browser-state.d.ts.map +1 -0
  55. package/dist/src/browser/browser-state.js +27 -0
  56. package/dist/src/browser/browser-state.js.map +1 -0
  57. package/dist/src/browser/browser.d.ts +5 -68
  58. package/dist/src/browser/browser.d.ts.map +1 -1
  59. package/dist/src/browser/browser.js +9 -849
  60. package/dist/src/browser/browser.js.map +1 -1
  61. package/dist/src/browser/profile-dir.d.ts +88 -0
  62. package/dist/src/browser/profile-dir.d.ts.map +1 -0
  63. package/dist/src/browser/profile-dir.js +242 -0
  64. package/dist/src/browser/profile-dir.js.map +1 -0
  65. package/dist/src/browser/ref-cache.d.ts +4 -0
  66. package/dist/src/browser/ref-cache.d.ts.map +1 -1
  67. package/dist/src/browser/ref-cache.js +2 -0
  68. package/dist/src/browser/ref-cache.js.map +1 -1
  69. package/dist/src/browser/types.d.ts +6 -0
  70. package/dist/src/browser/types.d.ts.map +1 -1
  71. package/dist/src/browser/types.js.map +1 -1
  72. package/dist/src/cli/commands.d.ts +1 -0
  73. package/dist/src/cli/commands.d.ts.map +1 -1
  74. package/dist/src/cli/commands.js +2 -0
  75. package/dist/src/cli/commands.js.map +1 -1
  76. package/dist/src/cli/session.d.ts +9 -0
  77. package/dist/src/cli/session.d.ts.map +1 -1
  78. package/dist/src/cli/session.js +21 -4
  79. package/dist/src/cli/session.js.map +1 -1
  80. package/dist/tsconfig.tsbuildinfo +1 -1
  81. package/package.json +1 -1
  82. package/src/__tests__/disconnect-session.test.ts +42 -0
  83. package/src/__tests__/profile-cleanup-close.test.ts +285 -0
  84. package/src/__tests__/profile-dir.test.ts +196 -0
  85. package/src/__tests__/setup/isolated-tmpdir.global.ts +28 -0
  86. package/src/browser/actions-eval.ts +118 -0
  87. package/src/browser/actions-form.ts +218 -0
  88. package/src/browser/actions-keyboard.ts +171 -0
  89. package/src/browser/actions-mouse.ts +212 -0
  90. package/src/browser/actions.ts +37 -712
  91. package/src/browser/browser-discovery.ts +116 -0
  92. package/src/browser/browser-launch.ts +375 -0
  93. package/src/browser/browser-lifecycle.ts +248 -0
  94. package/src/browser/browser-page.ts +213 -0
  95. package/src/browser/browser-state.ts +30 -0
  96. package/src/browser/browser.ts +21 -917
  97. package/src/browser/profile-dir.ts +249 -0
  98. package/src/browser/ref-cache.ts +7 -0
  99. package/src/browser/types.ts +6 -0
  100. package/src/cli/commands.ts +2 -0
  101. package/src/cli/session.ts +22 -4
@@ -1,712 +1,37 @@
1
- import { resolve } from 'node:path';
2
- import type { CdpClient } from './cdp.js';
3
- import { getElementBox, getObjectIdForRef } from './snapshot.js';
4
- import type { ClickOptions, ElementRef } from './types.js';
5
-
6
- export async function clickElement(
7
- client: CdpClient,
8
- sessionId: string,
9
- ref: ElementRef,
10
- options: ClickOptions = {},
11
- ): Promise<void> {
12
- const box = await getElementBox(client, sessionId, ref);
13
-
14
- if (box) {
15
- await clickPoint(client, sessionId, box.x, box.y, options);
16
- return;
17
- }
18
-
19
- // Fallback: use JS click via objectId
20
- const objectId = await getObjectIdForRef(client, sessionId, ref);
21
- if (objectId) {
22
- await client.send(
23
- 'Runtime.callFunctionOn',
24
- {
25
- functionDeclaration: 'function() { this.click(); }',
26
- objectId,
27
- returnByValue: true,
28
- },
29
- sessionId,
30
- );
31
- return;
32
- }
33
-
34
- throw new Error(`Cannot click ref @${ref.ref}: element not found in DOM`);
35
- }
36
-
37
- export async function clickPoint(
38
- client: CdpClient,
39
- sessionId: string,
40
- x: number,
41
- y: number,
42
- options: ClickOptions = {},
43
- ): Promise<void> {
44
- const button = options.button ?? 'left';
45
- // Cap clickCount to prevent unbounded loop DoS
46
- const clickCount = Math.min(Math.max(1, Math.floor(options.clickCount ?? 1)), 100);
47
- const modifiers = options.modifiers ?? 0;
48
-
49
- const shared = { x, y, button, modifiers };
50
- const buttonsMask = button === 'right' ? 2 : button === 'middle' ? 4 : 1;
51
-
52
- for (let i = 0; i < clickCount; i++) {
53
- const count = i + 1;
54
- await client.send(
55
- 'Input.dispatchMouseEvent',
56
- { ...shared, type: 'mousePressed', buttons: buttonsMask, clickCount: count },
57
- sessionId,
58
- );
59
- await client.send(
60
- 'Input.dispatchMouseEvent',
61
- {
62
- ...shared,
63
- type: 'mouseReleased',
64
- buttons: i < clickCount - 1 ? buttonsMask : 0,
65
- clickCount: count,
66
- },
67
- sessionId,
68
- );
69
- }
70
- }
71
-
72
- export async function fillElement(
73
- client: CdpClient,
74
- sessionId: string,
75
- ref: ElementRef,
76
- value: string,
77
- ): Promise<void> {
78
- const box = await getElementBox(client, sessionId, ref);
79
-
80
- if (box) {
81
- // Click to focus
82
- await clickPoint(client, sessionId, box.x, box.y);
83
- }
84
-
85
- // Select all and replace
86
- const objectId = await getObjectIdForRef(client, sessionId, ref);
87
- if (objectId) {
88
- const fillSelectResult = await client.send<{
89
- result: unknown;
90
- exceptionDetails?: { text: string; exception?: { description?: string } };
91
- }>(
92
- 'Runtime.callFunctionOn',
93
- {
94
- functionDeclaration: `function() {
95
- this.focus();
96
- if (this.tagName === 'INPUT' || this.tagName === 'TEXTAREA') {
97
- this.select();
98
- } else if (this.isContentEditable) {
99
- const range = document.createRange();
100
- range.selectNodeContents(this);
101
- const sel = window.getSelection();
102
- if (sel) { sel.removeAllRanges(); sel.addRange(range); }
103
- }
104
- }`,
105
- objectId,
106
- returnByValue: true,
107
- },
108
- sessionId,
109
- );
110
- if (fillSelectResult.exceptionDetails) {
111
- throw new Error(
112
- `fillElement select-all failed: ${fillSelectResult.exceptionDetails.exception?.description ?? fillSelectResult.exceptionDetails.text}`,
113
- );
114
- }
115
- } else if (box) {
116
- // Fallback for elements without a resolvable objectId: keyboard select-all clears existing content
117
- const mod = process.platform === 'darwin' ? 4 : 2;
118
- await pressKeyCombo(client, sessionId, 'a', mod);
119
- }
120
-
121
- if (!objectId && !box) throw new Error(`Cannot fill ref @${ref.ref}: element not found in DOM`);
122
-
123
- // Type the value character by character for natural input
124
- await typeText(client, sessionId, value);
125
- }
126
-
127
- export async function typeText(client: CdpClient, sessionId: string, text: string): Promise<void> {
128
- // Cap to 100 KB to prevent OOM in CDP message serializer
129
- const safeText = text.length > 102_400 ? text.slice(0, 102_400) : text;
130
- await client.send('Input.insertText', { text: safeText }, sessionId);
131
- }
132
-
133
- export async function pressKeyCombo(
134
- client: CdpClient,
135
- sessionId: string,
136
- key: string,
137
- modifiers: number,
138
- ): Promise<void> {
139
- const { text: _text, ...keyInfo } = resolveKey(key);
140
- // rawKeyDown prevents Chrome from inserting the character text; only the shortcut fires
141
- await client.send(
142
- 'Input.dispatchKeyEvent',
143
- { type: 'rawKeyDown', ...keyInfo, modifiers },
144
- sessionId,
145
- );
146
- await client.send('Input.dispatchKeyEvent', { type: 'keyUp', ...keyInfo, modifiers }, sessionId);
147
- }
148
-
149
- export async function pressKey(client: CdpClient, sessionId: string, key: string): Promise<void> {
150
- const { text, ...keyInfo } = resolveKey(key);
151
-
152
- // rawKeyDown does not insert text; the explicit char event handles insertion
153
- await client.send(
154
- 'Input.dispatchKeyEvent',
155
- {
156
- type: 'rawKeyDown',
157
- ...keyInfo,
158
- },
159
- sessionId,
160
- );
161
-
162
- if (text) {
163
- await client.send(
164
- 'Input.dispatchKeyEvent',
165
- {
166
- type: 'char',
167
- text,
168
- },
169
- sessionId,
170
- );
171
- }
172
-
173
- await client.send(
174
- 'Input.dispatchKeyEvent',
175
- {
176
- type: 'keyUp',
177
- ...keyInfo,
178
- },
179
- sessionId,
180
- );
181
- }
182
-
183
- function resolveKey(key: string): {
184
- key: string;
185
- code: string;
186
- text?: string;
187
- windowsVirtualKeyCode?: number;
188
- } {
189
- const keyMap: Record<
190
- string,
191
- { key: string; code: string; text?: string; windowsVirtualKeyCode?: number }
192
- > = {
193
- Enter: { key: 'Enter', code: 'Enter', text: '\r', windowsVirtualKeyCode: 13 },
194
- Tab: { key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 },
195
- Escape: { key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 },
196
- Backspace: { key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8 },
197
- Delete: { key: 'Delete', code: 'Delete', windowsVirtualKeyCode: 46 },
198
- ArrowUp: { key: 'ArrowUp', code: 'ArrowUp', windowsVirtualKeyCode: 38 },
199
- ArrowDown: { key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40 },
200
- ArrowLeft: { key: 'ArrowLeft', code: 'ArrowLeft', windowsVirtualKeyCode: 37 },
201
- ArrowRight: { key: 'ArrowRight', code: 'ArrowRight', windowsVirtualKeyCode: 39 },
202
- Home: { key: 'Home', code: 'Home', windowsVirtualKeyCode: 36 },
203
- End: { key: 'End', code: 'End', windowsVirtualKeyCode: 35 },
204
- PageUp: { key: 'PageUp', code: 'PageUp', windowsVirtualKeyCode: 33 },
205
- PageDown: { key: 'PageDown', code: 'PageDown', windowsVirtualKeyCode: 34 },
206
- Space: { key: ' ', code: 'Space', text: ' ', windowsVirtualKeyCode: 32 },
207
- ' ': { key: ' ', code: 'Space', text: ' ', windowsVirtualKeyCode: 32 },
208
- Shift: { key: 'Shift', code: 'ShiftLeft', windowsVirtualKeyCode: 16 },
209
- Control: { key: 'Control', code: 'ControlLeft', windowsVirtualKeyCode: 17 },
210
- Alt: { key: 'Alt', code: 'AltLeft', windowsVirtualKeyCode: 18 },
211
- Meta: { key: 'Meta', code: 'MetaLeft', windowsVirtualKeyCode: 91 },
212
- F1: { key: 'F1', code: 'F1', windowsVirtualKeyCode: 112 },
213
- F2: { key: 'F2', code: 'F2', windowsVirtualKeyCode: 113 },
214
- F3: { key: 'F3', code: 'F3', windowsVirtualKeyCode: 114 },
215
- F4: { key: 'F4', code: 'F4', windowsVirtualKeyCode: 115 },
216
- F5: { key: 'F5', code: 'F5', windowsVirtualKeyCode: 116 },
217
- F6: { key: 'F6', code: 'F6', windowsVirtualKeyCode: 117 },
218
- F7: { key: 'F7', code: 'F7', windowsVirtualKeyCode: 118 },
219
- F8: { key: 'F8', code: 'F8', windowsVirtualKeyCode: 119 },
220
- F9: { key: 'F9', code: 'F9', windowsVirtualKeyCode: 120 },
221
- F10: { key: 'F10', code: 'F10', windowsVirtualKeyCode: 121 },
222
- F11: { key: 'F11', code: 'F11', windowsVirtualKeyCode: 122 },
223
- F12: { key: 'F12', code: 'F12', windowsVirtualKeyCode: 123 },
224
- };
225
-
226
- if (keyMap[key]) return keyMap[key];
227
-
228
- // Single printable character — windowsVirtualKeyCode required for rawKeyDown shortcut dispatch
229
- if (key.length === 1) {
230
- const charCode = key.charCodeAt(0);
231
- if (charCode >= 48 && charCode <= 57) {
232
- return { key, code: `Digit${key}`, text: key, windowsVirtualKeyCode: charCode };
233
- }
234
- if ((charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122)) {
235
- return {
236
- key,
237
- code: `Key${key.toUpperCase()}`,
238
- text: key,
239
- windowsVirtualKeyCode: key.toUpperCase().charCodeAt(0),
240
- };
241
- }
242
- // Symbol keys: map to the physical key's code and Windows virtual key code
243
- const symbolMap: Record<string, { code: string; windowsVirtualKeyCode: number }> = {
244
- '!': { code: 'Digit1', windowsVirtualKeyCode: 49 },
245
- '@': { code: 'Digit2', windowsVirtualKeyCode: 50 },
246
- '#': { code: 'Digit3', windowsVirtualKeyCode: 51 },
247
- $: { code: 'Digit4', windowsVirtualKeyCode: 52 },
248
- '%': { code: 'Digit5', windowsVirtualKeyCode: 53 },
249
- '^': { code: 'Digit6', windowsVirtualKeyCode: 54 },
250
- '&': { code: 'Digit7', windowsVirtualKeyCode: 55 },
251
- '*': { code: 'Digit8', windowsVirtualKeyCode: 56 },
252
- '(': { code: 'Digit9', windowsVirtualKeyCode: 57 },
253
- ')': { code: 'Digit0', windowsVirtualKeyCode: 48 },
254
- '-': { code: 'Minus', windowsVirtualKeyCode: 189 },
255
- _: { code: 'Minus', windowsVirtualKeyCode: 189 },
256
- '=': { code: 'Equal', windowsVirtualKeyCode: 187 },
257
- '+': { code: 'Equal', windowsVirtualKeyCode: 187 },
258
- '[': { code: 'BracketLeft', windowsVirtualKeyCode: 219 },
259
- '{': { code: 'BracketLeft', windowsVirtualKeyCode: 219 },
260
- ']': { code: 'BracketRight', windowsVirtualKeyCode: 221 },
261
- '}': { code: 'BracketRight', windowsVirtualKeyCode: 221 },
262
- '\\': { code: 'Backslash', windowsVirtualKeyCode: 220 },
263
- '|': { code: 'Backslash', windowsVirtualKeyCode: 220 },
264
- ';': { code: 'Semicolon', windowsVirtualKeyCode: 186 },
265
- ':': { code: 'Semicolon', windowsVirtualKeyCode: 186 },
266
- "'": { code: 'Quote', windowsVirtualKeyCode: 222 },
267
- '"': { code: 'Quote', windowsVirtualKeyCode: 222 },
268
- '`': { code: 'Backquote', windowsVirtualKeyCode: 192 },
269
- '~': { code: 'Backquote', windowsVirtualKeyCode: 192 },
270
- ',': { code: 'Comma', windowsVirtualKeyCode: 188 },
271
- '<': { code: 'Comma', windowsVirtualKeyCode: 188 },
272
- '.': { code: 'Period', windowsVirtualKeyCode: 190 },
273
- '>': { code: 'Period', windowsVirtualKeyCode: 190 },
274
- '/': { code: 'Slash', windowsVirtualKeyCode: 191 },
275
- '?': { code: 'Slash', windowsVirtualKeyCode: 191 },
276
- };
277
- const sym = symbolMap[key];
278
- if (sym)
279
- return { key, code: sym.code, text: key, windowsVirtualKeyCode: sym.windowsVirtualKeyCode };
280
- // Unknown/non-ASCII character — omit code since no valid DOM KeyboardEvent.code exists
281
- return { key, code: '', text: key };
282
- }
283
-
284
- return { key, code: key };
285
- }
286
-
287
- export async function scrollElement(
288
- client: CdpClient,
289
- sessionId: string,
290
- direction: 'up' | 'down' | 'left' | 'right',
291
- amount = 300,
292
- ref?: ElementRef,
293
- ): Promise<void> {
294
- // Cap scroll amount to prevent extreme delta values
295
- amount = Math.min(Math.max(1, Math.floor(amount)), 100_000);
296
- let x = 0;
297
- let y = 0;
298
- let deltaX = 0;
299
- let deltaY = 0;
300
-
301
- if (ref) {
302
- const box = await getElementBox(client, sessionId, ref);
303
- if (!box) throw new Error(`Cannot scroll: ref @${ref.ref} not found in DOM`);
304
- x = box.x;
305
- y = box.y;
306
- } else {
307
- // Center of viewport
308
- const vp = await client.send<{ result: { value: string } }>(
309
- 'Runtime.evaluate',
310
- {
311
- expression: 'JSON.stringify({w: window.innerWidth, h: window.innerHeight})',
312
- returnByValue: true,
313
- },
314
- sessionId,
315
- );
316
- const dims = JSON.parse(vp.result?.value ?? '{"w":1280,"h":720}');
317
- x = dims.w / 2;
318
- y = dims.h / 2;
319
- }
320
-
321
- switch (direction) {
322
- case 'down':
323
- deltaY = amount;
324
- break;
325
- case 'up':
326
- deltaY = -amount;
327
- break;
328
- case 'right':
329
- deltaX = amount;
330
- break;
331
- case 'left':
332
- deltaX = -amount;
333
- break;
334
- }
335
-
336
- await client.send(
337
- 'Input.dispatchMouseEvent',
338
- {
339
- type: 'mouseWheel',
340
- x,
341
- y,
342
- deltaX,
343
- deltaY,
344
- },
345
- sessionId,
346
- );
347
- }
348
-
349
- export async function hoverElement(
350
- client: CdpClient,
351
- sessionId: string,
352
- ref: ElementRef,
353
- ): Promise<void> {
354
- const box = await getElementBox(client, sessionId, ref);
355
- if (!box) throw new Error(`Cannot hover ref @${ref.ref}: element not found in DOM`);
356
-
357
- await client.send(
358
- 'Input.dispatchMouseEvent',
359
- {
360
- type: 'mouseMoved',
361
- x: box.x,
362
- y: box.y,
363
- },
364
- sessionId,
365
- );
366
- }
367
-
368
- export async function selectOption(
369
- client: CdpClient,
370
- sessionId: string,
371
- ref: ElementRef,
372
- value: string,
373
- ): Promise<void> {
374
- const objectId = await getObjectIdForRef(client, sessionId, ref);
375
- if (!objectId) throw new Error(`Cannot select: ref @${ref.ref} not found in DOM`);
376
-
377
- const selectResult = await client.send<{
378
- result: unknown;
379
- exceptionDetails?: { text: string; exception?: { description?: string } };
380
- }>(
381
- 'Runtime.callFunctionOn',
382
- {
383
- functionDeclaration: `function(value) {
384
- if (this.tagName !== 'SELECT') throw new Error('Not a select element');
385
- for (const opt of this.options) {
386
- if (opt.value === value || opt.textContent.trim() === value) {
387
- this.value = opt.value;
388
- this.dispatchEvent(new Event('change', { bubbles: true }));
389
- return;
390
- }
391
- }
392
- throw new Error('Option not found: ' + value);
393
- }`,
394
- objectId,
395
- arguments: [{ value }],
396
- returnByValue: true,
397
- },
398
- sessionId,
399
- );
400
- if (selectResult.exceptionDetails) {
401
- throw new Error(
402
- `selectOption failed: ${selectResult.exceptionDetails.exception?.description ?? selectResult.exceptionDetails.text}`,
403
- );
404
- }
405
- }
406
-
407
- export async function checkElement(
408
- client: CdpClient,
409
- sessionId: string,
410
- ref: ElementRef,
411
- checked = true,
412
- ): Promise<void> {
413
- const objectId = await getObjectIdForRef(client, sessionId, ref);
414
- if (!objectId) throw new Error(`Cannot check: ref @${ref.ref} not found in DOM`);
415
-
416
- const checkResult = await client.send<{
417
- result: unknown;
418
- exceptionDetails?: { text: string; exception?: { description?: string } };
419
- }>(
420
- 'Runtime.callFunctionOn',
421
- {
422
- functionDeclaration: `function(checked) {
423
- if (this.checked !== checked) {
424
- this.click();
425
- }
426
- }`,
427
- objectId,
428
- arguments: [{ value: checked }],
429
- returnByValue: true,
430
- },
431
- sessionId,
432
- );
433
- if (checkResult.exceptionDetails) {
434
- throw new Error(
435
- `checkElement failed: ${checkResult.exceptionDetails.exception?.description ?? checkResult.exceptionDetails.text}`,
436
- );
437
- }
438
- }
439
-
440
- export async function focusElement(
441
- client: CdpClient,
442
- sessionId: string,
443
- ref: ElementRef,
444
- ): Promise<void> {
445
- const objectId = await getObjectIdForRef(client, sessionId, ref);
446
- if (objectId) {
447
- await client.send(
448
- 'Runtime.callFunctionOn',
449
- {
450
- functionDeclaration: 'function() { this.focus(); }',
451
- objectId,
452
- returnByValue: true,
453
- },
454
- sessionId,
455
- );
456
- return;
457
- }
458
- const box = await getElementBox(client, sessionId, ref);
459
- if (box) {
460
- await clickPoint(client, sessionId, box.x, box.y);
461
- } else {
462
- throw new Error(`Cannot focus ref @${ref.ref}: element not found in DOM`);
463
- }
464
- }
465
-
466
- export async function typeIntoElement(
467
- client: CdpClient,
468
- sessionId: string,
469
- ref: ElementRef,
470
- text: string,
471
- ): Promise<void> {
472
- await focusElement(client, sessionId, ref);
473
- await typeText(client, sessionId, text);
474
- }
475
-
476
- export async function keyDown(client: CdpClient, sessionId: string, key: string): Promise<void> {
477
- const { text: _text, ...keyInfo } = resolveKey(key);
478
- await client.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', ...keyInfo }, sessionId);
479
- }
480
-
481
- export async function keyUp(client: CdpClient, sessionId: string, key: string): Promise<void> {
482
- const { text: _text, ...keyInfo } = resolveKey(key);
483
- await client.send('Input.dispatchKeyEvent', { type: 'keyUp', ...keyInfo }, sessionId);
484
- }
485
-
486
- export async function mouseMove(
487
- client: CdpClient,
488
- sessionId: string,
489
- x: number,
490
- y: number,
491
- ): Promise<void> {
492
- await client.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y }, sessionId);
493
- }
494
-
495
- export async function mouseDown(
496
- client: CdpClient,
497
- sessionId: string,
498
- x: number,
499
- y: number,
500
- button: 'left' | 'right' | 'middle' = 'left',
501
- ): Promise<void> {
502
- const buttonsMask = button === 'right' ? 2 : button === 'middle' ? 4 : 1;
503
- await client.send(
504
- 'Input.dispatchMouseEvent',
505
- { type: 'mousePressed', x, y, button, buttons: buttonsMask, clickCount: 1 },
506
- sessionId,
507
- );
508
- }
509
-
510
- export async function mouseUp(
511
- client: CdpClient,
512
- sessionId: string,
513
- x: number,
514
- y: number,
515
- button: 'left' | 'right' | 'middle' = 'left',
516
- ): Promise<void> {
517
- await client.send(
518
- 'Input.dispatchMouseEvent',
519
- { type: 'mouseReleased', x, y, button, buttons: 0, clickCount: 1 },
520
- sessionId,
521
- );
522
- }
523
-
524
- export async function mouseWheel(
525
- client: CdpClient,
526
- sessionId: string,
527
- x: number,
528
- y: number,
529
- deltaY: number,
530
- deltaX = 0,
531
- ): Promise<void> {
532
- await client.send(
533
- 'Input.dispatchMouseEvent',
534
- { type: 'mouseWheel', x, y, deltaX, deltaY },
535
- sessionId,
536
- );
537
- }
538
-
539
- export async function dragAndDrop(
540
- client: CdpClient,
541
- sessionId: string,
542
- src: ElementRef,
543
- tgt: ElementRef,
544
- ): Promise<void> {
545
- const srcBox = await getElementBox(client, sessionId, src);
546
- const tgtBox = await getElementBox(client, sessionId, tgt);
547
- if (!srcBox || !tgtBox) throw new Error('Cannot drag: one or both elements not found in DOM');
548
-
549
- await client.send(
550
- 'Input.dispatchMouseEvent',
551
- { type: 'mousePressed', x: srcBox.x, y: srcBox.y, button: 'left', buttons: 1, clickCount: 1 },
552
- sessionId,
553
- );
554
- await client.send(
555
- 'Input.dispatchMouseEvent',
556
- { type: 'mouseMoved', x: srcBox.x, y: srcBox.y, button: 'left', buttons: 1 },
557
- sessionId,
558
- );
559
-
560
- // Move in steps for smooth drag
561
- const steps = 10;
562
- for (let i = 1; i <= steps; i++) {
563
- const x = srcBox.x + (tgtBox.x - srcBox.x) * (i / steps);
564
- const y = srcBox.y + (tgtBox.y - srcBox.y) * (i / steps);
565
- await client.send(
566
- 'Input.dispatchMouseEvent',
567
- { type: 'mouseMoved', x, y, button: 'left', buttons: 1 },
568
- sessionId,
569
- );
570
- }
571
-
572
- await client.send(
573
- 'Input.dispatchMouseEvent',
574
- { type: 'mouseReleased', x: tgtBox.x, y: tgtBox.y, button: 'left', buttons: 0, clickCount: 1 },
575
- sessionId,
576
- );
577
- }
578
-
579
- export async function uploadFile(
580
- client: CdpClient,
581
- sessionId: string,
582
- ref: ElementRef,
583
- filePaths: string[],
584
- ): Promise<void> {
585
- if (!ref.backendDOMNodeId) throw new Error(`Cannot upload: ref @${ref.ref} has no DOM node`);
586
-
587
- await client.send(
588
- 'DOM.setFileInputFiles',
589
- {
590
- files: filePaths.map((f) => resolve(f)),
591
- backendNodeId: ref.backendDOMNodeId,
592
- },
593
- sessionId,
594
- );
595
- }
596
-
597
- export async function readClipboard(client: CdpClient, sessionId: string): Promise<string> {
598
- const result = await evaluateJs(client, sessionId, 'navigator.clipboard.readText()');
599
- return result as string;
600
- }
601
-
602
- export async function writeClipboard(
603
- client: CdpClient,
604
- sessionId: string,
605
- text: string,
606
- ): Promise<void> {
607
- // Cap to 100 KB to prevent OOM when serializing the CDP expression
608
- const safeText = text.length > 102_400 ? text.slice(0, 102_400) : text;
609
- await evaluateJs(client, sessionId, `navigator.clipboard.writeText(${JSON.stringify(safeText)})`);
610
- }
611
-
612
- export async function pushState(client: CdpClient, sessionId: string, url: string): Promise<void> {
613
- // Try Next.js router first, then fallback to history.pushState
614
- await evaluateJs(
615
- client,
616
- sessionId,
617
- `
618
- (function() {
619
- const url = ${JSON.stringify(url)};
620
- if (window.next && window.next.router) {
621
- window.next.router.push(url).catch(function() {});
622
- return;
623
- } else {
624
- history.pushState({}, '', url);
625
- window.dispatchEvent(new PopStateEvent('popstate'));
626
- }
627
- })()
628
- `,
629
- );
630
- }
631
-
632
- export async function addInitScript(
633
- client: CdpClient,
634
- sessionId: string,
635
- script: string,
636
- ): Promise<string> {
637
- const result = await client.send<{ identifier: string }>(
638
- 'Page.addScriptToEvaluateOnNewDocument',
639
- {
640
- source: script,
641
- },
642
- sessionId,
643
- );
644
- return result.identifier;
645
- }
646
-
647
- export async function removeInitScript(
648
- client: CdpClient,
649
- sessionId: string,
650
- identifier: string,
651
- ): Promise<void> {
652
- await client.send('Page.removeScriptToEvaluateOnNewDocument', { identifier }, sessionId);
653
- }
654
-
655
- // Default cap on how long an evaluateJs() call waits for Runtime.evaluate to
656
- // resolve. Because this always passes `awaitPromise: true`, an expression
657
- // like `new Promise(() => {})` never settles — the underlying CdpClient.send()
658
- // has no timeout of its own (the CDP_RESPONSE_SIZE_LIMIT in cdp.ts only guards
659
- // the HTTP /json/* endpoints, not WebSocket command responses), so without
660
- // this the caller (e.g. the `eval` CLI command) would hang forever with
661
- // nothing to kill it.
662
- const DEFAULT_EVAL_TIMEOUT_MS = 30_000;
663
-
664
- export async function evaluateJs(
665
- client: CdpClient,
666
- sessionId: string,
667
- expression: string,
668
- timeoutMs: number = DEFAULT_EVAL_TIMEOUT_MS,
669
- ): Promise<unknown> {
670
- const evalPromise = client.send<{
671
- result: { value?: unknown; type: string; description?: string };
672
- exceptionDetails?: { text: string; exception?: { description?: string } };
673
- }>(
674
- 'Runtime.evaluate',
675
- {
676
- expression,
677
- returnByValue: true,
678
- awaitPromise: true,
679
- },
680
- sessionId,
681
- );
682
-
683
- // Not unref'd (same rule as CdpClient.send): this timer settles the awaited
684
- // race, so it has to hold the event loop open while the evaluation is in
685
- // flight. Cleared in the finally so a fast evaluation does not keep the
686
- // process alive for the rest of timeoutMs.
687
- let evalTimer: ReturnType<typeof setTimeout> | undefined;
688
- let result: Awaited<typeof evalPromise>;
689
- try {
690
- result = await (timeoutMs > 0
691
- ? Promise.race([
692
- evalPromise,
693
- new Promise<never>((_, reject) => {
694
- evalTimer = setTimeout(
695
- () => reject(new Error(`JS evaluation timed out after ${timeoutMs}ms`)),
696
- timeoutMs,
697
- );
698
- }),
699
- ])
700
- : evalPromise);
701
- } finally {
702
- clearTimeout(evalTimer);
703
- }
704
-
705
- if (result.exceptionDetails) {
706
- throw new Error(
707
- `JS evaluation error: ${result.exceptionDetails.exception?.description ?? result.exceptionDetails.text}`,
708
- );
709
- }
710
-
711
- return result.result?.value;
712
- }
1
+ /**
2
+ * Browser action helpers (click, type, scroll, drag, JS evaluation, ...).
3
+ *
4
+ * File-size sweep: split into sibling modules (actions-keyboard.ts,
5
+ * actions-mouse.ts, actions-form.ts, actions-eval.ts). This file remains the
6
+ * entry point and re-exports everything that used to live here so every
7
+ * existing import keeps working.
8
+ */
9
+
10
+ export {
11
+ addInitScript,
12
+ evaluateJs,
13
+ pushState,
14
+ readClipboard,
15
+ removeInitScript,
16
+ writeClipboard,
17
+ } from './actions-eval.js';
18
+ export {
19
+ checkElement,
20
+ clickElement,
21
+ fillElement,
22
+ focusElement,
23
+ selectOption,
24
+ typeIntoElement,
25
+ uploadFile,
26
+ } from './actions-form.js';
27
+ export { keyDown, keyUp, pressKey, pressKeyCombo, typeText } from './actions-keyboard.js';
28
+ export {
29
+ clickPoint,
30
+ dragAndDrop,
31
+ hoverElement,
32
+ mouseDown,
33
+ mouseMove,
34
+ mouseUp,
35
+ mouseWheel,
36
+ scrollElement,
37
+ } from './actions-mouse.js';