@querying/sneaky 0.0.0-stage → 0.2.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.
Files changed (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +171 -2
  3. package/bin/sneaky-mcp.mjs +5 -0
  4. package/bin/sneaky.mjs +51 -0
  5. package/dist/agent/index.d.ts +277 -0
  6. package/dist/agent/index.js +319 -0
  7. package/dist/agent/index.js.map +1 -0
  8. package/dist/browser/index.d.ts +69 -0
  9. package/dist/browser/index.js +326 -0
  10. package/dist/browser/index.js.map +1 -0
  11. package/dist/cli/index.d.ts +51 -0
  12. package/dist/cli/index.js +189 -0
  13. package/dist/cli/index.js.map +1 -0
  14. package/dist/driver/cdp.d.ts +36 -0
  15. package/dist/driver/cdp.js +240 -0
  16. package/dist/driver/cdp.js.map +1 -0
  17. package/dist/driver/frame.d.ts +229 -0
  18. package/dist/driver/frame.js +794 -0
  19. package/dist/driver/frame.js.map +1 -0
  20. package/dist/driver/index.d.ts +13 -0
  21. package/dist/driver/index.js +6 -0
  22. package/dist/driver/index.js.map +1 -0
  23. package/dist/driver/keys.d.ts +9 -0
  24. package/dist/driver/keys.js +65 -0
  25. package/dist/driver/keys.js.map +1 -0
  26. package/dist/driver/launcher.d.ts +49 -0
  27. package/dist/driver/launcher.js +251 -0
  28. package/dist/driver/launcher.js.map +1 -0
  29. package/dist/driver/page.d.ts +391 -0
  30. package/dist/driver/page.js +1594 -0
  31. package/dist/driver/page.js.map +1 -0
  32. package/dist/index.d.ts +501 -0
  33. package/dist/index.js +688 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/mcp/server.d.ts +35 -0
  36. package/dist/mcp/server.js +548 -0
  37. package/dist/mcp/server.js.map +1 -0
  38. package/dist/repl/cli.d.ts +1 -0
  39. package/dist/repl/cli.js +246 -0
  40. package/dist/repl/cli.js.map +1 -0
  41. package/dist/repl/host.d.ts +46 -0
  42. package/dist/repl/host.js +167 -0
  43. package/dist/repl/host.js.map +1 -0
  44. package/dist/repl/index.d.ts +246 -0
  45. package/dist/repl/index.js +923 -0
  46. package/dist/repl/index.js.map +1 -0
  47. package/dist/repl/transform.d.ts +19 -0
  48. package/dist/repl/transform.js +590 -0
  49. package/dist/repl/transform.js.map +1 -0
  50. package/dist/request/index.d.ts +265 -0
  51. package/dist/request/index.js +898 -0
  52. package/dist/request/index.js.map +1 -0
  53. package/package.json +83 -4
package/dist/index.js ADDED
@@ -0,0 +1,688 @@
1
+ import { DEFAULT_LOCAL_URL, DEFAULT_REMOTE_URL, SneakyError, parseTarget, } from "./agent/index.js";
2
+ import { buildArgs, buildEnv, deriveAcceptLanguage, formatProxyUrl, profileSeed, } from "./browser/index.js";
3
+ import { PLATFORM_PACKAGES, resolveBinaryPath, startDaemon, } from "./cli/index.js";
4
+ export { DEFAULT_LOCAL_URL, DEFAULT_REMOTE_URL, PLATFORM_PACKAGES, SneakyError, buildArgs, buildEnv, deriveAcceptLanguage, formatProxyUrl, parseTarget, profileSeed, resolveBinaryPath, startDaemon, };
5
+ function toWirePersona(p) {
6
+ if (!p)
7
+ return undefined;
8
+ const anyP = p;
9
+ return {
10
+ seed: p.seed,
11
+ platform: p.platform,
12
+ hardware_concurrency: (anyP.hardware_concurrency ?? anyP.hardwareConcurrency),
13
+ screen: p.screen,
14
+ timezone: p.timezone,
15
+ locale: p.locale,
16
+ webrtc_ip: (anyP.webrtc_ip ?? anyP.webrtcIp),
17
+ voices: p.voices,
18
+ host_gpu: (anyP.host_gpu ?? anyP.hostGpu),
19
+ gpu_draw: (anyP.gpu_draw ?? anyP.gpuDraw),
20
+ webauthn: p.webauthn,
21
+ color_scheme: (anyP.color_scheme ?? anyP.colorScheme),
22
+ reduced_motion: (anyP.reduced_motion ?? anyP.reducedMotion),
23
+ bluetooth: p.bluetooth,
24
+ software_webgpu: (anyP.software_webgpu ?? anyP.softwareWebgpu),
25
+ passthrough: p.passthrough,
26
+ tls_profile: (anyP.tls_profile ?? anyP.tlsProfile),
27
+ user_agent: (anyP.user_agent ?? anyP.userAgent),
28
+ proxy: p.proxy,
29
+ fallback_font_dirs: (anyP.fallback_font_dirs ?? anyP.fallbackFontDirs),
30
+ extra_args: (anyP.extra_args ?? anyP.args),
31
+ };
32
+ }
33
+ function encodeFetchPayload(url, options = {}) {
34
+ const payload = { url };
35
+ if (options.method)
36
+ payload.method = options.method;
37
+ if (options.headers) {
38
+ if (Array.isArray(options.headers)) {
39
+ payload.headers = options.headers.map(([k, v]) => [k, v]);
40
+ }
41
+ else {
42
+ payload.header_map = options.headers;
43
+ }
44
+ }
45
+ if (options.body !== undefined) {
46
+ if (typeof options.body === "string") {
47
+ payload.body = options.body;
48
+ }
49
+ else {
50
+ payload.body_base64 = Buffer.from(options.body).toString("base64");
51
+ }
52
+ }
53
+ if (options.priority)
54
+ payload.priority = options.priority;
55
+ if (options.timeoutMs !== undefined)
56
+ payload.timeout_ms = options.timeoutMs;
57
+ if (options.followRedirects !== undefined)
58
+ payload.follow_redirects = options.followRedirects;
59
+ if (options.escalateOnStatus?.length)
60
+ payload.escalate_on_status = options.escalateOnStatus;
61
+ if (options.escalateMode)
62
+ payload.escalate_mode = options.escalateMode;
63
+ return payload;
64
+ }
65
+ /**
66
+ * Unified client for Sneaky: use Chrome-stack HTTP (`fetch`), sneaky-browser (`createSession` + `goto`/`act`),
67
+ * bidirectional Cookie Bridge (`syncCookies`), or cloud `querying.ai Browser` from one API.
68
+ */
69
+ export class Sneaky {
70
+ baseUrl;
71
+ mcpUrl;
72
+ isCloud;
73
+ captcha;
74
+ apiKey;
75
+ authToken;
76
+ timeoutMs;
77
+ fetchImpl;
78
+ managedDaemon;
79
+ constructor(options = {}, managedDaemon) {
80
+ this.apiKey = options.apiKey;
81
+ this.authToken = options.authToken ?? options.apiKey;
82
+ this.captcha = options.captcha;
83
+ this.managedDaemon = managedDaemon;
84
+ this.baseUrl = (managedDaemon?.url ?? options.baseUrl ?? (this.apiKey ? DEFAULT_REMOTE_URL : DEFAULT_LOCAL_URL)).replace(/\/+$/, "");
85
+ this.mcpUrl = `${this.baseUrl}/mcp`;
86
+ this.isCloud = Boolean(this.apiKey) && !options.baseUrl && !managedDaemon;
87
+ this.timeoutMs = options.timeoutMs ?? 60_000;
88
+ this.fetchImpl = options.fetch ?? globalThis.fetch;
89
+ }
90
+ /** Returns the Bearer token configured on this client, if any. */
91
+ get bearerToken() {
92
+ return this.authToken;
93
+ }
94
+ /** Spawns a managed local `sneaky serve` daemon on a free port and returns a ready Sneaky client. */
95
+ static async start(options = {}) {
96
+ const daemon = await startDaemon(options);
97
+ return new Sneaky({
98
+ baseUrl: daemon.url,
99
+ captcha: options.captcha,
100
+ timeoutMs: options.timeoutMs,
101
+ fetch: options.fetch,
102
+ }, daemon);
103
+ }
104
+ /** Stops the managed local daemon if this client was created via `Sneaky.start()`. */
105
+ async stop() {
106
+ await this.managedDaemon?.stop();
107
+ }
108
+ async [Symbol.asyncDispose]() {
109
+ await this.stop();
110
+ }
111
+ async request(method, path, options = {}) {
112
+ const url = new URL(this.baseUrl + path);
113
+ for (const [k, v] of Object.entries(options.query ?? {})) {
114
+ if (v !== undefined)
115
+ url.searchParams.set(k, String(v));
116
+ }
117
+ const headers = {};
118
+ if (this.authToken)
119
+ headers.authorization = `Bearer ${this.authToken}`;
120
+ if (options.body !== undefined)
121
+ headers["content-type"] = "application/json";
122
+ const res = await this.fetchImpl(url, {
123
+ method,
124
+ headers,
125
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
126
+ signal: AbortSignal.timeout(this.timeoutMs),
127
+ });
128
+ const text = await res.text();
129
+ const parsed = text ? JSON.parse(text) : undefined;
130
+ if (!res.ok) {
131
+ const msg = typeof parsed?.message === "string" ? parsed.message : `HTTP ${res.status}`;
132
+ const code = typeof parsed?.code === "string" ? parsed.code : `HTTP_${res.status}`;
133
+ throw new SneakyError(msg, res.status, code, parsed);
134
+ }
135
+ return parsed;
136
+ }
137
+ health() {
138
+ return this.request("GET", "/healthz");
139
+ }
140
+ /** Standalone one-shot HTTP request via tfrd (zero browser launched). */
141
+ fetch(url, options = {}) {
142
+ const payload = encodeFetchPayload(url, options);
143
+ if (options.persona)
144
+ payload.persona = toWirePersona(options.persona);
145
+ if (options.proxyServer)
146
+ payload.proxy_server = options.proxyServer;
147
+ if (options.ignoreCertErrors)
148
+ payload.ignore_cert_errors = true;
149
+ return this.request("POST", "/fetch", { body: payload });
150
+ }
151
+ /** Creates a unified composable session (defaults to lazy "auto" mode locally, or "/browsers" in cloud mode). */
152
+ async createSession(options = {}) {
153
+ if (this.isCloud) {
154
+ const body = {
155
+ headless: options.headless ?? true,
156
+ stealth: options.stealth ?? true,
157
+ };
158
+ if (options.country)
159
+ body.proxy = { type: "residential", config: { country: options.country } };
160
+ if (options.viewport)
161
+ body.viewport = options.viewport;
162
+ const info = await this.request("POST", "/browsers", { body });
163
+ const sess = new SneakySession(this, info.session_id, info, "/browsers");
164
+ if (options.url)
165
+ await sess.goto(options.url);
166
+ return sess;
167
+ }
168
+ const body = {
169
+ mode: options.mode ?? "auto",
170
+ headless: options.headless ?? true,
171
+ stealth: options.stealth ?? true,
172
+ };
173
+ if (options.persona)
174
+ body.persona = toWirePersona(options.persona);
175
+ if (options.proxyServer)
176
+ body.proxy_server = options.proxyServer;
177
+ if (options.binary)
178
+ body.binary = options.binary;
179
+ if (options.userDataDir)
180
+ body.user_data_dir = options.userDataDir;
181
+ if (options.viewport)
182
+ body.viewport = options.viewport;
183
+ if (options.remote)
184
+ body.remote = true;
185
+ if (options.country)
186
+ body.country = options.country;
187
+ if (options.cdpWsUrl)
188
+ body.cdp_ws_url = options.cdpWsUrl;
189
+ if (options.ignoreCertErrors)
190
+ body.ignore_cert_errors = true;
191
+ if (options.autoSyncCookies !== undefined)
192
+ body.auto_sync_cookies = options.autoSyncCookies;
193
+ if (options.url)
194
+ body.url = options.url;
195
+ const info = await this.request("POST", "/sessions", { body });
196
+ return new SneakySession(this, info.session_id, info, "/sessions");
197
+ }
198
+ attachSession(sessionId) {
199
+ return new SneakySession(this, sessionId, undefined, this.isCloud ? "/browsers" : "/sessions");
200
+ }
201
+ listSessions() {
202
+ return this.request("GET", this.isCloud ? "/browsers" : "/sessions");
203
+ }
204
+ async closeSession(sessionId) {
205
+ await this.request("DELETE", `${this.isCloud ? "/browsers" : "/sessions"}/${encodeURIComponent(sessionId)}`);
206
+ }
207
+ profiles() {
208
+ return this.request("GET", "/profiles");
209
+ }
210
+ createProfile(options) {
211
+ return this.request("POST", "/profiles", {
212
+ body: {
213
+ id: options.id,
214
+ name: options.name,
215
+ headless: options.headless,
216
+ stealth: options.stealth,
217
+ persona: toWirePersona(options.persona),
218
+ },
219
+ });
220
+ }
221
+ getProfile(id) {
222
+ return this.request("GET", `/profiles/${encodeURIComponent(id)}`);
223
+ }
224
+ async deleteProfile(id) {
225
+ await this.request("DELETE", `/profiles/${encodeURIComponent(id)}`);
226
+ }
227
+ startProfile(id, options = {}) {
228
+ return this.request("POST", `/profiles/${encodeURIComponent(id)}/start`, {
229
+ body: {
230
+ headless: options.headless,
231
+ headful: options.headful,
232
+ stealth: options.stealth,
233
+ proxy_server: options.proxyServer,
234
+ binary: options.binary,
235
+ url: options.url,
236
+ restart: options.restart,
237
+ },
238
+ });
239
+ }
240
+ stopProfile(id) {
241
+ return this.request("POST", `/profiles/${encodeURIComponent(id)}/stop`, {
242
+ body: {},
243
+ });
244
+ }
245
+ profileTabs(id) {
246
+ return this.request("GET", `/profiles/${encodeURIComponent(id)}/tabs`);
247
+ }
248
+ /** Lazily starts or attaches to a persistent profile's browser session and returns a ready SneakySession. */
249
+ async ensureProfileSession(id = "default", options = {}) {
250
+ const res = await this.startProfile(id, options);
251
+ const sess = new SneakySession(this, res.session.session_id, res.session, "/sessions");
252
+ return { profile: res.profile, session: sess, tabs: res.tabs ?? [] };
253
+ }
254
+ }
255
+ export class SneakySession {
256
+ client;
257
+ id;
258
+ initialInfo;
259
+ routePrefix;
260
+ network;
261
+ rpcWs;
262
+ rpcSeq = 0;
263
+ rpcPending = new Map();
264
+ constructor(client, id, initialInfo, routePrefix = "/sessions") {
265
+ this.client = client;
266
+ this.id = id;
267
+ this.initialInfo = initialInfo;
268
+ this.routePrefix = routePrefix;
269
+ this.network = new UnifiedNetwork(client, id, routePrefix, (method, params) => this.tryCallRPC(method, params));
270
+ }
271
+ root(sub = "") {
272
+ const base = `${this.routePrefix}/${encodeURIComponent(this.id)}`;
273
+ return sub ? `${base}/${sub}` : base;
274
+ }
275
+ agent(sub) {
276
+ return `${this.root("agent")}/${sub}`;
277
+ }
278
+ /** Open a multiplexed WebSocket RPC channel for both HTTP fetch/cookie calls and browser agent calls. */
279
+ async connectRPC() {
280
+ if (this.rpcWs && this.rpcWs.readyState === WebSocket.OPEN)
281
+ return;
282
+ const wsBase = this.client.baseUrl.replace(/^http/, "ws");
283
+ const tokenQuery = this.client.bearerToken ? `?token=${encodeURIComponent(this.client.bearerToken)}` : "";
284
+ const wsUrl = wsBase + this.agent("rpc") + tokenQuery;
285
+ await new Promise((resolve, reject) => {
286
+ const ws = new WebSocket(wsUrl);
287
+ ws.addEventListener("open", () => {
288
+ this.rpcWs = ws;
289
+ resolve();
290
+ });
291
+ ws.addEventListener("error", () => reject(new Error("failed to open sneaky RPC WebSocket")));
292
+ ws.addEventListener("message", (ev) => {
293
+ try {
294
+ const msg = JSON.parse(String(ev.data));
295
+ if (typeof msg.id !== "number")
296
+ return;
297
+ const pending = this.rpcPending.get(msg.id);
298
+ if (!pending)
299
+ return;
300
+ this.rpcPending.delete(msg.id);
301
+ if (msg.error) {
302
+ pending.reject(new SneakyError(msg.error.message ?? "RPC error", msg.error.status ?? 500, msg.error.code ?? "rpc_error", msg.error.extra));
303
+ }
304
+ else {
305
+ pending.resolve(msg.result);
306
+ }
307
+ }
308
+ catch {
309
+ // Ignore malformed frames.
310
+ }
311
+ });
312
+ ws.addEventListener("close", () => {
313
+ this.rpcWs = undefined;
314
+ for (const [, p] of this.rpcPending)
315
+ p.reject(new Error("RPC WebSocket closed"));
316
+ this.rpcPending.clear();
317
+ });
318
+ });
319
+ }
320
+ tryCallRPC(method, params) {
321
+ const ws = this.rpcWs;
322
+ if (!ws || ws.readyState !== WebSocket.OPEN)
323
+ return undefined;
324
+ const id = ++this.rpcSeq;
325
+ return new Promise((resolve, reject) => {
326
+ this.rpcPending.set(id, { resolve: resolve, reject });
327
+ ws.send(JSON.stringify({ id, method, params }));
328
+ });
329
+ }
330
+ invokeAgent(rpcMethod, httpMethod, sub, body) {
331
+ const rpc = this.tryCallRPC(rpcMethod, body);
332
+ if (rpc)
333
+ return rpc;
334
+ return this.client.request(httpMethod, this.agent(sub), body === undefined ? {} : { body });
335
+ }
336
+ info() {
337
+ return this.client.request("GET", this.root());
338
+ }
339
+ /** Sends an HTTP request through the session's tfrd lane using its shared Persona, Proxy, and CookieJar. */
340
+ fetch(url, options = {}) {
341
+ const payload = encodeFetchPayload(url, options);
342
+ const rpc = this.tryCallRPC("fetch", payload);
343
+ if (rpc)
344
+ return rpc;
345
+ return this.client.request("POST", this.root("fetch"), { body: payload });
346
+ }
347
+ /** Lazily promotes the session to a Browser lane (auto-injecting existing HTTP cookies) and optionally navigates. */
348
+ promote(url, waitUntil) {
349
+ const body = {};
350
+ if (url)
351
+ body.url = url;
352
+ if (waitUntil)
353
+ body.wait_until = waitUntil;
354
+ const rpc = this.tryCallRPC("promote", body);
355
+ if (rpc)
356
+ return rpc;
357
+ return this.client.request("POST", this.root("promote"), { body });
358
+ }
359
+ /** Reads cookies from the unified session ("all", "http", or "browser"). */
360
+ async cookies(source = "all", urls) {
361
+ const rpc = this.tryCallRPC("cookies.get", { source, urls });
362
+ if (rpc)
363
+ return (await rpc).cookies;
364
+ const res = await this.client.request("GET", this.root("cookies"), {
365
+ query: { source, urls: urls?.join(",") },
366
+ });
367
+ return res.cookies;
368
+ }
369
+ /** Injects cookies into "both", "http", or "browser". */
370
+ setCookies(cookies, target = "both") {
371
+ const body = { cookies, target };
372
+ const rpc = this.tryCallRPC("cookies.set", body);
373
+ if (rpc)
374
+ return rpc;
375
+ return this.client.request("POST", this.root("cookies"), { body });
376
+ }
377
+ /** Synchronizes cookies between Browser (CDP) and HTTP (tfrd) lanes. */
378
+ syncCookies(direction = "both", urls) {
379
+ const body = { direction, urls };
380
+ const rpc = this.tryCallRPC("cookies.sync", body);
381
+ if (rpc)
382
+ return rpc;
383
+ return this.client.request("POST", this.root("cookies/sync"), { body });
384
+ }
385
+ syncBrowserToHttp(urls) {
386
+ return this.syncCookies("browser_to_http", urls);
387
+ }
388
+ syncHttpToBrowser() {
389
+ return this.syncCookies("http_to_browser");
390
+ }
391
+ /** Invokes either the caller-configured CaptchaPlugin or the daemon's optional captcha sidecar. */
392
+ solveCaptcha(task) {
393
+ if (this.client.captcha) {
394
+ return this.client.captcha.solve(task);
395
+ }
396
+ return this.client.request("POST", this.root("captcha/solve"), { body: { task } });
397
+ }
398
+ goto(url, options = {}) {
399
+ return this.invokeAgent("navigate", "POST", "navigate", {
400
+ url,
401
+ wait_until: options.waitUntil,
402
+ timeout_ms: options.timeoutMs,
403
+ return_snapshot: options.returnSnapshot,
404
+ snapshot_mode: options.snapshotMode,
405
+ });
406
+ }
407
+ snapshot(options = {}) {
408
+ return this.invokeAgent("snapshot", "POST", "snapshot", {
409
+ mode: options.mode,
410
+ source: options.source,
411
+ diff_from: options.diffFrom,
412
+ include_tree_with_diff: options.includeTreeWithDiff,
413
+ show_hidden: options.showHidden,
414
+ ref: options.ref,
415
+ selector: options.selector,
416
+ max_nodes: options.maxNodes,
417
+ max_chars: options.maxChars,
418
+ screenshot: options.screenshot,
419
+ });
420
+ }
421
+ screenshot(options = {}) {
422
+ const target = options.target ? parseTarget(options.target) : undefined;
423
+ return this.invokeAgent("screenshot", "POST", "screenshot", {
424
+ format: options.format,
425
+ quality: options.quality,
426
+ full_page: options.fullPage,
427
+ annotate: options.annotate,
428
+ target,
429
+ });
430
+ }
431
+ pdf(options = {}) {
432
+ return this.invokeAgent("pdf", "POST", "pdf", {
433
+ landscape: options.landscape,
434
+ print_background: options.printBackground,
435
+ scale: options.scale,
436
+ paper_width: options.paperWidth,
437
+ paper_height: options.paperHeight,
438
+ margin_top: options.marginTop,
439
+ margin_bottom: options.marginBottom,
440
+ margin_left: options.marginLeft,
441
+ margin_right: options.marginRight,
442
+ page_ranges: options.pageRanges,
443
+ prefer_css_page_size: options.preferCSSPageSize,
444
+ });
445
+ }
446
+ setViewport(options) {
447
+ return this.invokeAgent("viewport", "POST", "viewport", {
448
+ width: options.width,
449
+ height: options.height,
450
+ device_scale_factor: options.deviceScaleFactor,
451
+ mobile: options.mobile,
452
+ });
453
+ }
454
+ eval(expression, options = {}) {
455
+ return this.invokeAgent("eval", "POST", "eval", {
456
+ expression,
457
+ world: options.world,
458
+ await_promise: options.awaitPromise,
459
+ });
460
+ }
461
+ query(target, op, arg) {
462
+ return this.invokeAgent("query", "POST", "query", {
463
+ target: parseTarget(target),
464
+ op,
465
+ arg,
466
+ });
467
+ }
468
+ act(actions, options = {}) {
469
+ const list = (Array.isArray(actions) ? actions : [actions]).map((a) => ({
470
+ ...a,
471
+ speed: a.speed ?? options.speed,
472
+ humanize: a.humanize ?? options.humanize,
473
+ timeout_ms: a.timeout_ms ?? options.timeoutMs,
474
+ }));
475
+ return this.invokeAgent("act", "POST", "act", {
476
+ actions: list,
477
+ return_snapshot: options.returnSnapshot,
478
+ snapshot_mode: options.snapshotMode,
479
+ snapshot_source: options.snapshotSource,
480
+ diff_from: options.diffFrom,
481
+ diff_from_last: options.diffFromLast,
482
+ settle_ms: options.settleMs,
483
+ screenshot: options.screenshot,
484
+ });
485
+ }
486
+ click(target, options = {}) {
487
+ return this.act({ type: "click", target: parseTarget(target) }, options);
488
+ }
489
+ fill(target, text, options = {}) {
490
+ return this.act({ type: "fill", target: parseTarget(target), text, clear: options.clear }, options);
491
+ }
492
+ press(key, options = {}) {
493
+ return this.act({ type: "press", key }, options);
494
+ }
495
+ extract(options = {}) {
496
+ return this.invokeAgent("extract", "POST", "extract", {
497
+ kind: options.kind ?? "markdown",
498
+ target: options.target ? parseTarget(options.target) : undefined,
499
+ max_chars: options.maxChars,
500
+ });
501
+ }
502
+ locator(selectorOrRef) {
503
+ return new UnifiedLocator(this, parseTarget(selectorOrRef));
504
+ }
505
+ getByRole(role, options = {}) {
506
+ return new UnifiedLocator(this, { role, name: options.name, exact: options.exact });
507
+ }
508
+ getByText(text, options = {}) {
509
+ return new UnifiedLocator(this, { text, exact: options.exact });
510
+ }
511
+ getByLabel(label, options = {}) {
512
+ return new UnifiedLocator(this, { label, exact: options.exact });
513
+ }
514
+ getByPlaceholder(placeholder, options = {}) {
515
+ return new UnifiedLocator(this, { placeholder, exact: options.exact });
516
+ }
517
+ tabs() {
518
+ return this.invokeAgent("tabs.list", "GET", "tabs");
519
+ }
520
+ openTab(url = "") {
521
+ return this.invokeAgent("tabs.open", "POST", "tabs", { url });
522
+ }
523
+ activateTab(targetId) {
524
+ return this.invokeAgent("tabs.activate", "POST", "tabs/activate", { target_id: targetId });
525
+ }
526
+ closeTab(targetId) {
527
+ const rpc = this.tryCallRPC("tabs.close", { target_id: targetId });
528
+ if (rpc)
529
+ return rpc;
530
+ return this.client.request("DELETE", this.agent(`tabs/${encodeURIComponent(targetId)}`));
531
+ }
532
+ close() {
533
+ if (this.rpcWs) {
534
+ try {
535
+ this.rpcWs.close();
536
+ }
537
+ catch {
538
+ // Ignore close errors.
539
+ }
540
+ this.rpcWs = undefined;
541
+ }
542
+ return this.client.closeSession(this.id);
543
+ }
544
+ }
545
+ export class UnifiedLocator {
546
+ session;
547
+ target;
548
+ constructor(session, target) {
549
+ this.session = session;
550
+ this.target = target;
551
+ }
552
+ first() {
553
+ return new UnifiedLocator(this.session, { ...this.target, nth: 0 });
554
+ }
555
+ last() {
556
+ return new UnifiedLocator(this.session, { ...this.target, nth: -1 });
557
+ }
558
+ nth(index) {
559
+ return new UnifiedLocator(this.session, { ...this.target, nth: index });
560
+ }
561
+ click(options) {
562
+ return this.session.act({ type: "click", target: this.target, button: options?.button, click_count: options?.clickCount }, options);
563
+ }
564
+ dblclick(options) {
565
+ return this.session.act({ type: "dblclick", target: this.target }, options);
566
+ }
567
+ hover(options) {
568
+ return this.session.act({ type: "hover", target: this.target }, options);
569
+ }
570
+ fill(text, options) {
571
+ return this.session.fill(this.target, text, options);
572
+ }
573
+ type(text, options) {
574
+ return this.session.act({ type: "type", target: this.target, text }, options);
575
+ }
576
+ press(key, options) {
577
+ return this.session.act([
578
+ { type: "click", target: this.target, speed: "fast" },
579
+ { type: "press", key },
580
+ ], options);
581
+ }
582
+ selectOption(valueOrOpt, options) {
583
+ const spec = typeof valueOrOpt === "string" ? { value: valueOrOpt } : valueOrOpt;
584
+ return this.session.act({ type: "select", target: this.target, value: spec.value, label: spec.label }, options);
585
+ }
586
+ waitFor(options) {
587
+ return this.session.act({ type: "wait", target: this.target, timeout_ms: options?.timeout });
588
+ }
589
+ async textContent() {
590
+ const res = await this.session.query(this.target, "textContent");
591
+ return res.value;
592
+ }
593
+ async innerText() {
594
+ const res = await this.session.query(this.target, "innerText");
595
+ return res.value;
596
+ }
597
+ async inputValue() {
598
+ const res = await this.session.query(this.target, "inputValue");
599
+ return res.value;
600
+ }
601
+ async getAttribute(name) {
602
+ const res = await this.session.query(this.target, "getAttribute", name);
603
+ return res.value;
604
+ }
605
+ async isVisible() {
606
+ const res = await this.session.query(this.target, "isVisible");
607
+ return Boolean(res.value);
608
+ }
609
+ async isEnabled() {
610
+ const res = await this.session.query(this.target, "isEnabled");
611
+ return Boolean(res.value);
612
+ }
613
+ async isChecked() {
614
+ const res = await this.session.query(this.target, "isChecked");
615
+ return Boolean(res.value);
616
+ }
617
+ async count() {
618
+ const res = await this.session.query(this.target, "count");
619
+ return Number(res.value ?? 0);
620
+ }
621
+ async boundingBox() {
622
+ const res = await this.session.query(this.target, "boundingBox");
623
+ return res.value;
624
+ }
625
+ async allTextContents() {
626
+ const res = await this.session.query(this.target, "allTextContents");
627
+ return Array.isArray(res.value) ? res.value : [];
628
+ }
629
+ async allInnerTexts() {
630
+ const res = await this.session.query(this.target, "allInnerTexts");
631
+ return Array.isArray(res.value) ? res.value : [];
632
+ }
633
+ }
634
+ export class UnifiedNetwork {
635
+ client;
636
+ sessionId;
637
+ routePrefix;
638
+ tryRPC;
639
+ constructor(client, sessionId, routePrefix, tryRPC) {
640
+ this.client = client;
641
+ this.sessionId = sessionId;
642
+ this.routePrefix = routePrefix;
643
+ this.tryRPC = tryRPC;
644
+ }
645
+ p(sub) {
646
+ return `${this.routePrefix}/${encodeURIComponent(this.sessionId)}/agent/network/${sub}`;
647
+ }
648
+ capture(options = {}) {
649
+ const body = {
650
+ enabled: options.enabled,
651
+ resource_types: options.resourceTypes,
652
+ url_contains: options.urlContains,
653
+ capture_bodies: options.captureBodies,
654
+ block_resource_types: options.blockResourceTypes,
655
+ };
656
+ const rpc = this.tryRPC?.("network.capture", body);
657
+ if (rpc)
658
+ return rpc;
659
+ return this.client.request("POST", this.p("capture"), { body });
660
+ }
661
+ list(filter = {}) {
662
+ const params = {
663
+ resource_type: filter.resourceType,
664
+ method: filter.method,
665
+ url_contains: filter.urlContains,
666
+ limit: filter.limit,
667
+ };
668
+ const rpc = this.tryRPC?.("network.list", params);
669
+ if (rpc)
670
+ return rpc;
671
+ return this.client.request("GET", this.p("requests"), {
672
+ query: params,
673
+ });
674
+ }
675
+ get(requestId) {
676
+ const rpc = this.tryRPC?.("network.get", { request_id: requestId });
677
+ if (rpc)
678
+ return rpc;
679
+ return this.client.request("GET", this.p(`requests/${encodeURIComponent(requestId)}`));
680
+ }
681
+ clear() {
682
+ const rpc = this.tryRPC?.("network.clear", {});
683
+ if (rpc)
684
+ return rpc;
685
+ return this.client.request("DELETE", this.p("requests"));
686
+ }
687
+ }
688
+ //# sourceMappingURL=index.js.map