omowright 0.1.0 → 0.3.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 (165) hide show
  1. package/README.md +33 -23
  2. package/TOOLS.md +140 -19
  3. package/dist/agent-tabs.d.ts +56 -0
  4. package/dist/aria-hidden.d.ts +1 -0
  5. package/dist/aside/cli-binary.d.ts +7 -0
  6. package/dist/aside/cli-contract.d.ts +9 -0
  7. package/dist/aside/errors.d.ts +8 -0
  8. package/dist/aside/line-transport.d.ts +11 -0
  9. package/dist/aside/mcp-transport.d.ts +11 -0
  10. package/dist/aside/onboard.d.ts +76 -0
  11. package/dist/aside/session-types.d.ts +68 -0
  12. package/dist/aside/session.d.ts +20 -0
  13. package/{bin/omowright-cloak.mjs → dist/bin/omowright-cloak.js} +28 -31
  14. package/dist/bridge-schemas.d.ts +326 -0
  15. package/dist/bridge-transport.d.ts +144 -0
  16. package/dist/browser-context.d.ts +4024 -0
  17. package/dist/browser-process.d.ts +10 -0
  18. package/dist/bsk/browser-signals.d.ts +23 -0
  19. package/dist/bsk/browsers.d.ts +46 -0
  20. package/dist/bsk/connect.d.ts +23 -0
  21. package/dist/bsk/daemon-info.d.ts +16 -0
  22. package/dist/bsk/external-extension.d.ts +74 -0
  23. package/dist/bsk/identify-browser.d.ts +48 -0
  24. package/dist/bsk/install-cli.d.ts +37 -0
  25. package/dist/bsk/ipc-client.d.ts +45 -0
  26. package/dist/bsk/onboard.d.ts +96 -0
  27. package/dist/bsk/reply-fields.d.ts +3 -0
  28. package/dist/bsk/screenshot.d.ts +24 -0
  29. package/dist/bsk/session.d.ts +142 -0
  30. package/dist/bsk/snapshot.d.ts +16 -0
  31. package/dist/bsk/targets.d.ts +20 -0
  32. package/dist/captcha-wait.d.ts +17 -0
  33. package/dist/captcha.d.ts +46 -0
  34. package/dist/cdp-errors.d.ts +38 -0
  35. package/dist/cdp-methods.d.ts +10 -0
  36. package/dist/cdp-protocol.d.ts +459 -0
  37. package/dist/chrome-profile.d.ts +77 -0
  38. package/dist/chrome.d.ts +130 -0
  39. package/dist/cloak-profile.d.ts +43 -0
  40. package/dist/connection.d.ts +4024 -0
  41. package/dist/console-events.d.ts +22 -0
  42. package/dist/cookies.d.ts +42 -0
  43. package/dist/core.d.ts +10810 -0
  44. package/dist/cua.d.ts +56 -0
  45. package/dist/dialog-policy.d.ts +43 -0
  46. package/dist/ego/bindings.d.ts +68 -0
  47. package/dist/ego/cdp-client.d.ts +28 -0
  48. package/dist/ego/client.d.ts +8 -0
  49. package/dist/ego/errors.d.ts +7 -0
  50. package/dist/emulate.d.ts +62 -0
  51. package/dist/engines.d.ts +59 -0
  52. package/dist/events.d.ts +93 -0
  53. package/dist/frames-snapshot.d.ts +58 -0
  54. package/dist/har.d.ts +88 -0
  55. package/dist/human-handoff.d.ts +30 -0
  56. package/{src/index.js → dist/index.d.ts} +12 -53
  57. package/dist/index.js +39262 -0
  58. package/dist/injected.d.ts +1 -0
  59. package/dist/instance-lock.d.ts +5 -0
  60. package/dist/instances.d.ts +45 -0
  61. package/dist/internal-capability.d.ts +1 -0
  62. package/dist/launch-endpoint.d.ts +34 -0
  63. package/dist/layers.d.ts +31 -0
  64. package/dist/llm.d.ts +1349 -0
  65. package/dist/lock-backend-win32-xbcm60vz.js +57 -0
  66. package/dist/lock-backend-win32.d.ts +3 -0
  67. package/dist/lock-backend.d.ts +6 -0
  68. package/dist/native-host-win32.d.ts +38 -0
  69. package/dist/network-events.d.ts +66 -0
  70. package/dist/network-snoop.d.ts +56 -0
  71. package/dist/nul-frames.d.ts +4 -0
  72. package/dist/open-shadow-query.d.ts +1 -0
  73. package/dist/owner-only.d.ts +15 -0
  74. package/dist/page-bundle.js +1587 -0
  75. package/dist/page-events.d.ts +25 -0
  76. package/dist/page-routes.d.ts +30 -0
  77. package/dist/page-setup.d.ts +55 -0
  78. package/dist/pipe.d.ts +71 -0
  79. package/dist/process-start-time.d.ts +2 -0
  80. package/dist/read-property.d.ts +2 -0
  81. package/dist/routes.d.ts +60 -0
  82. package/dist/running-browser.d.ts +39 -0
  83. package/dist/scroll-collect.d.ts +36 -0
  84. package/dist/serial-emitter.d.ts +5 -0
  85. package/dist/shared-connections.d.ts +11 -0
  86. package/dist/snapshot-diff.d.ts +57 -0
  87. package/dist/text-matching.d.ts +21 -0
  88. package/dist/trace.d.ts +59 -0
  89. package/dist/url-match.d.ts +7 -0
  90. package/dist/viewport.d.ts +26 -0
  91. package/dist/ws.d.ts +62 -0
  92. package/package.json +47 -26
  93. package/presets/agent-events/SKILL.md +1 -1
  94. package/presets/captcha/SKILL.md +1 -3
  95. package/presets/chrome/SKILL.md +11 -7
  96. package/presets/cloak-bridge/SKILL.md +11 -11
  97. package/presets/network/SKILL.md +15 -13
  98. package/presets/visual-browse/SKILL.md +14 -10
  99. package/skills/omowright/SKILL.md +77 -47
  100. package/skills/omowright/references/aside.md +50 -0
  101. package/skills/omowright/references/browserskill.md +39 -33
  102. package/skills/omowright/references/ego.md +24 -0
  103. package/skills/omowright/references/eval-kernel.md +44 -23
  104. package/skills/omowright/references/frames-layers-human.md +16 -7
  105. package/skills/omowright/references/quickstart.md +17 -4
  106. package/skills/omowright/references/stealth.md +7 -7
  107. package/src/agent-tabs.js +0 -160
  108. package/src/bridge-schemas.js +0 -44
  109. package/src/bridge-transport.js +0 -57
  110. package/src/browser-process.js +0 -122
  111. package/src/bsk/browser-signals.js +0 -90
  112. package/src/bsk/browsers.js +0 -114
  113. package/src/bsk/connect.js +0 -45
  114. package/src/bsk/daemon-info.js +0 -100
  115. package/src/bsk/external-extension.js +0 -110
  116. package/src/bsk/identify-browser.js +0 -88
  117. package/src/bsk/install-cli.js +0 -81
  118. package/src/bsk/ipc-client.js +0 -236
  119. package/src/bsk/onboard.js +0 -133
  120. package/src/bsk/screenshot.js +0 -49
  121. package/src/bsk/session.js +0 -131
  122. package/src/bsk/snapshot.js +0 -56
  123. package/src/bsk/targets.js +0 -25
  124. package/src/captcha-wait.js +0 -74
  125. package/src/captcha.js +0 -142
  126. package/src/cdp-errors.js +0 -23
  127. package/src/cdp-methods.js +0 -61
  128. package/src/chrome-profile.js +0 -176
  129. package/src/chrome.js +0 -192
  130. package/src/cloak-profile.js +0 -266
  131. package/src/connection.js +0 -135
  132. package/src/cookies.js +0 -29
  133. package/src/core.js +0 -1710
  134. package/src/cua.js +0 -74
  135. package/src/dialog-policy.js +0 -80
  136. package/src/emulate.js +0 -127
  137. package/src/events.js +0 -111
  138. package/src/frames-snapshot.js +0 -138
  139. package/src/har.js +0 -103
  140. package/src/human-handoff.js +0 -122
  141. package/src/injected.js +0 -3
  142. package/src/instance-lock.js +0 -230
  143. package/src/instances.js +0 -493
  144. package/src/internal-capability.js +0 -1
  145. package/src/launch-endpoint.js +0 -185
  146. package/src/layers.js +0 -138
  147. package/src/llm.js +0 -201
  148. package/src/lock-file.js +0 -130
  149. package/src/native-host-win32.js +0 -201
  150. package/src/network-events.js +0 -201
  151. package/src/network-snoop.js +0 -229
  152. package/src/open-shadow-query.js +0 -22
  153. package/src/owner-only.js +0 -109
  154. package/src/page-bundle.js +0 -1397
  155. package/src/page-routes.js +0 -94
  156. package/src/pipe.js +0 -391
  157. package/src/routes.js +0 -256
  158. package/src/running-browser.js +0 -85
  159. package/src/scroll-collect.js +0 -73
  160. package/src/serial-emitter.js +0 -17
  161. package/src/shared-connections.js +0 -278
  162. package/src/snapshot-diff.js +0 -75
  163. package/src/trace.js +0 -183
  164. package/src/url-match.js +0 -148
  165. package/src/viewport.js +0 -12
package/src/core.js DELETED
@@ -1,1710 +0,0 @@
1
- import { CdpSessionDetachedError } from "./cdp-errors.js";
2
- import WebSocket from "ws";
3
- import { acquireNetwork, subscribePageNetworkEvents, disposeNetwork, networkPredicate, networkReady } from "./network-events.js";
4
- import * as z from "zod";
5
- import path from "node:path";
6
- import { mkdir, writeFile } from "node:fs/promises";
7
- import { createReadStream, promises } from "node:fs";
8
- import * as fs$16 from "node:fs/promises";
9
- import { text as readProcessStream } from "node:stream/consumers";
10
- import { tmpdir } from "node:os";
11
- import { pageBundle } from "./injected.js";
12
- import { queryOpenShadowAll } from "./open-shadow-query.js";
13
- import { snapshotResult } from "./snapshot-diff.js";
14
- import { targetCreationCapability } from "./internal-capability.js";
15
- import { Dialog, answerWithPolicy, normalizeDialogPolicy } from "./dialog-policy.js";
16
- import { pageRoute, pageUnroute, pageUnrouteAll } from "./page-routes.js";
17
- import { urlMatches } from "./url-match.js";
18
-
19
- const __defProp = Object.defineProperty;
20
- const __exportAll = (definitions, namespace) => {
21
- const exports = {};
22
- for (const name in definitions) __defProp(exports, name, { get: definitions[name], enumerable: true });
23
- if (!namespace) __defProp(exports, Symbol.toStringTag, { value: "Module" });
24
- return exports;
25
- };
26
-
27
- const __esmMin = (factory, value, error) => () => {
28
- if (error) throw error[0];
29
- try {
30
- return factory && (value = factory(factory = 0)), value;
31
- } catch (caught) {
32
- error = [caught];
33
- throw caught;
34
- }
35
- };
36
-
37
- if (!Promise.withResolvers) {
38
- Promise.withResolvers = () => {
39
- let resolve, reject;
40
- const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
41
- return { promise, resolve, reject };
42
- };
43
- }
44
-
45
- class Emittery {
46
- #listeners = new Map();
47
- on(name, listener) {
48
- const listeners = this.#listeners.get(name) ?? new Set();
49
- listeners.add(listener);
50
- this.#listeners.set(name, listeners);
51
- return () => { listeners.delete(listener); };
52
- }
53
- async emit(name, data) {
54
- const event = { data, eventName: name };
55
- await Promise.all([...this.#listeners.get(name) ?? []].map(listener => listener(event)));
56
- }
57
- clearListeners() { this.#listeners.clear(); }
58
- }
59
-
60
- const { object, string: string$2, number: number$2, array, union: union$1, unknown: unknown$1, null: _null } = z;
61
- const SESSION_ARTIFACTS_DIR = path.join(tmpdir(), "omowright-artifacts");
62
-
63
- const noop = () => {};
64
- const init_emittery = noop, init_zod = noop, init_context = noop, init_utils$13 = noop,
65
- init_config = noop, init_extension_bridge = noop, init_commands$1 = noop,
66
- init_directory = noop, init_process = noop,
67
- init_event_bus = noop, init_state_db = noop, init_schema = noop, init_store$1 = noop,
68
- init_drizzle_orm = noop, init_types$8 = noop, init_agent_session_server = noop,
69
- init_nanoid = noop;
70
-
71
- function sleep$12(ms, signal) {
72
- return new Promise((resolve, reject) => {
73
- if (signal?.aborted) return reject(signal.reason ?? Error("Aborted"));
74
- const onAbort = () => { clearTimeout(timer); reject(signal.reason ?? Error("Aborted")); };
75
- const timer = setTimeout(() => { signal?.removeEventListener("abort", onAbort); resolve(); }, ms);
76
- signal?.addEventListener("abort", onAbort, { once: true });
77
- });
78
- }
79
- function getCurrentReplAbortSignal() { return undefined; }
80
- function withCurrentReplAbort(fn) { return fn(); }
81
- function withoutReplContext(fn) { return fn(); }
82
- function replPrint(...values) { console.warn(...values); }
83
- async function sendCommandToExtension(command) {
84
- throw new UnsupportedOperationError(`Extension command is unavailable: ${command.method}`);
85
- }
86
- class UnsupportedOperationError extends Error {
87
- constructor(message) { super(message); this.name = "UnsupportedOperationError"; }
88
- }
89
- const EventBus = { emit: async () => {} };
90
- const SessionStore = { get: () => undefined, update: () => undefined };
91
- function spawnCommand() { throw new UnsupportedOperationError("Video recording is unavailable"); }
92
- async function waitForExitCode() { return 1; }
93
- function writeProcessChunk(stdin, chunk) {
94
- return new Promise((resolve, reject) => stdin.write(chunk, error => error ? reject(error) : resolve()));
95
- }
96
- function endProcessInput(stdin) {
97
- return new Promise((resolve, reject) => stdin.end(error => error ? reject(error) : resolve()));
98
- }
99
- function isWebSocketUrl(xn){return xn.startsWith(`ws://`)||xn.startsWith(`wss://`)}function isAuthorizationError(xn){let jn=xn instanceof Error?xn.message:String(xn),Vn=xn;return jn.includes(`401`)||jn.includes(`403`)||jn.includes(`Missing or invalid Authorization header.`)||jn.includes(`Unauthorized`)||jn.includes(`Forbidden`)||typeof Vn.status==`number`&&(Vn.status===401||Vn.status===403)||typeof Vn.response?.status==`number`&&(Vn.response.status===401||Vn.response.status===403)||typeof Vn.error?.status==`number`&&(Vn.error.status===401||Vn.error.status===403)||typeof Vn.cause?.status==`number`&&(Vn.cause.status===401||Vn.cause.status===403)||String(Vn.error?.message??``).includes(`Missing or invalid Authorization header.`)||String(Vn.cause?.message??``).includes(`Missing or invalid Authorization header.`)}function normalizeBaseUrl(xn){return xn.replace(/\/$/,``)}function createAbortError$1(){let xn=Error(`Operation aborted`);return xn.name=`AbortError`,xn}var DEFAULT_COMMAND_TIMEOUT_MS,DEFAULT_RECONNECT_DELAYS_MS,jsonVersionSchema,jsonTargetSchema,cdpWireMessageSchema,BrowserCdpCommandError,CdpClient,init_client$6=__esmMin((()=>{init_emittery(),init_zod(),init_context(),init_utils$13(),init_config(),init_extension_bridge(),init_commands$1(),DEFAULT_COMMAND_TIMEOUT_MS=3e4,DEFAULT_RECONNECT_DELAYS_MS=[0,250,750,1500,3e3],jsonVersionSchema=object({Browser:string$2().optional(),"Protocol-Version":string$2().optional(),"User-Agent":string$2().optional(),"V8-Version":string$2().optional(),"WebKit-Version":string$2().optional(),webSocketDebuggerUrl:string$2()}).loose(),jsonTargetSchema=object({description:string$2().optional(),devtoolsFrontendUrl:string$2().optional(),faviconUrl:string$2().optional(),id:string$2(),parentId:string$2().optional(),title:string$2().default(``),type:string$2(),url:string$2().default(``),webSocketDebuggerUrl:string$2().optional()}).loose(),cdpWireMessageSchema=union$1([object({id:number$2(),sessionId:string$2().optional(),error:object({code:number$2().optional(),data:unknown$1().optional(),message:string$2()}).loose().optional(),result:unknown$1().optional()}).loose(),object({method:string$2(),params:unknown$1().optional(),sessionId:string$2().optional()}).loose(),_null()]),BrowserCdpCommandError=class extends Error{method;code;data;constructor(xn,jn,Vn,qn){super(qn??`CDP command failed: ${xn}`),this.method=xn,this.code=jn,this.data=Vn}},CdpClient=class{cdpUrl;logId;#dialogPolicy;#e;#t;#n;#r=null;#i=null;#a=null;#o=!1;#s=1;#c=new Map;#closedSessions=new Set;#l=new Emittery;#u=!1;#closedEpoch=0;transportEvents=new Emittery;constructor(xn={}){if(typeof xn.cdpUrl!=`string`||xn.cdpUrl===``)throw TypeError(`CdpClient requires a cdpUrl: there is no default endpoint, so a missing URL can never reach a browser on 127.0.0.1:9222`);this.cdpUrl=normalizeBaseUrl(xn.cdpUrl),this.logId=xn.logId??`cdp-${Date.now()}`,this.#e=xn.authorizer,this.#t=xn.commandTimeoutMs??DEFAULT_COMMAND_TIMEOUT_MS,this.#n=xn.reconnectDelaysMs??DEFAULT_RECONNECT_DELAYS_MS,this.#dialogPolicy=normalizeDialogPolicy(xn.dialogPolicy)}get dialogPolicy(){return this.#dialogPolicy}setDialogPolicy(xn){this.#dialogPolicy=normalizeDialogPolicy(xn)}get isConnected(){return this.#r?.readyState===WebSocket.OPEN}start(){let Kn=this.#closedEpoch;this.#o||(this.#o=!0,this.ensureConnected().catch(xn=>{this.#closedEpoch===Kn&&(console.warn(`[${this.logId}] Initial CDP connect failed`,xn),this.#b())}))}async discoverVersion(xn={}){return await this.#f(this.#d(`/json/version`),jsonVersionSchema,xn)}async discoverTargets(xn={}){return await this.#f(this.#d(`/json/list`),array(jsonTargetSchema),xn)}async ensureConnected(){if(this.#o=!0,this.isConnected)return;if(this.#i){await this.#i;return}let xn=this.#g();this.#i=xn;try{await xn}finally{this.#i===xn&&(this.#i=null)}}async send(xn,jn,Vn,qn={}){if(xn===`Target.createTarget`&&qn.capability!==targetCreationCapability)throw Error(`Target.createTarget is reserved for createAgentTabs`);let Jn=getCurrentReplAbortSignal();if(Jn?.aborted)throw createAbortError$1();if(xn.startsWith(`OmO.`)){let Vn=await sendCommandToExtension({method:xn,params:jn},{...qn.extensionBridge,signal:Jn});if(Jn?.aborted)throw createAbortError$1();return Vn}await this.ensureConnected();if(this.#closedSessions.has(Vn)&&xn!==`Page.close`)throw new CdpSessionDetachedError(`Page closed: ${xn}`,{method:xn,sessionId:Vn});let Yn=this.#r;if(!Yn||Yn.readyState!==WebSocket.OPEN)throw Error(`CDP websocket is not connected`);let Zn=this.#s++,Qn={id:Zn,method:xn};jn!==void 0&&(Qn.params=jn),Vn&&(Qn.sessionId=Vn);let{promise:ei,reject:ti,resolve:ni}=Promise.withResolvers(),ri=qn.timeoutMs??this.#t,ii=ri>0?setTimeout(()=>{this.#c.delete(Zn),ti(Error(`CDP command timeout: ${String(xn)}`))},ri):void 0,ai=Jn?()=>{ii&&clearTimeout(ii),this.#c.delete(Zn),ti(createAbortError$1())}:void 0;if(this.#c.set(Zn,{method:String(xn),sessionId:Vn,reject:ti,resolve:ni,timeout:ii}),Jn?.addEventListener(`abort`,ai,{once:!0}),Jn?.aborted)return ai?.(),await ei;try{Yn.send(JSON.stringify(Qn))}catch(xn){throw ii&&clearTimeout(ii),this.#c.delete(Zn),ai&&Jn?.removeEventListener(`abort`,ai),xn instanceof Error?xn:Error(String(xn))}try{return await ei}finally{ai&&Jn?.removeEventListener(`abort`,ai)}}closeSession(sessionId){this.#closedSessions.add(sessionId);for(const[id,entry]of this.#c){if(entry.sessionId!==sessionId)continue;clearTimeout(entry.timeout);this.#c.delete(id);entry.reject(new CdpSessionDetachedError(`Page closed: ${entry.method}`,{method:entry.method,sessionId}));}}on(xn,jn){return this.#l.on(xn,({data:xn})=>jn(xn.payload,xn.meta))}async close(){this.#o=!1,this.#closedEpoch++,this.#i=null,this.#a&&=(clearTimeout(this.#a),null);let xn=this.#r;if(this.#r=null,this.#x(Error(`CDP client closed`)),xn&&xn.readyState<=WebSocket.OPEN)try{xn.close(1e3,`client closing`)}catch{}}#d(xn){let jn=new URL(this.cdpUrl);return isWebSocketUrl(this.cdpUrl)?(jn.protocol=jn.protocol===`wss:`?`https:`:`http:`,jn.pathname=xn,jn.search=``,jn.toString()):(jn.pathname=xn,jn.search=``,jn.toString())}async#f(xn,jn,Vn={}){let qn=await this.#p(Vn),Jn=await fetch(xn,{headers:qn});if((Jn.status===401||Jn.status===403)&&this.#e&&!Vn.forceRefresh)return await this.#f(xn,jn,{forceRefresh:!0});if(!Jn.ok)throw Error(`CDP discovery request failed (${Jn.status} ${Jn.statusText})`);return jn.parse(await Jn.json())}async#p(xn={}){return this.#e?{Authorization:await this.#e.resolveAuthorization(xn)}:{}}async#m(xn={}){let jn=await this.#p(xn);return isWebSocketUrl(this.cdpUrl)?{headers:jn,wsUrl:this.cdpUrl}:{headers:jn,wsUrl:(await this.discoverVersion(xn)).webSocketDebuggerUrl}}async#g(){let xn=null,jn=!1,Kn=this.#closedEpoch;for(let Vn of this.#n){if(Vn>0&&await sleep$12(Vn),this.#closedEpoch!==Kn)throw Error(`CDP client closed`);try{await this.#_({forceRefresh:jn},Kn);return}catch(Vn){if(this.#closedEpoch!==Kn)throw Error(`CDP client closed`);let qn=Vn??Error(`Unknown error`);xn=qn,isAuthorizationError(qn)&&(jn=!0)}}throw xn instanceof Error?xn:Error(String(xn??`Failed to connect CDP websocket`))}async#_(xn={},Kn=this.#closedEpoch){let{headers:jn,wsUrl:Vn}=await this.#m(xn);if(this.#closedEpoch!==Kn)throw Error(`CDP client closed`);await new Promise((xn,qn)=>{let Jn=new WebSocket(Vn,{headers:jn}),Yn=!1,Zn=xn=>{Yn||(Yn=!0,qn(xn))};Jn.addEventListener(`open`,()=>{if(!Yn){if(Yn=!0,this.#closedEpoch!==Kn){try{Jn.close(1e3,`client closed`)}catch{}qn(Error(`CDP client closed`));return}this.#v(Jn),xn()}}),Jn.addEventListener(`message`,xn=>{this.#r===Jn&&this.#S(xn.data).catch(()=>{})}),Jn.addEventListener(`close`,xn=>{this.#r===Jn&&this.#y(Jn),Yn||Zn(Error(`CDP websocket closed during connect (${xn.code} ${xn.reason||`no reason`})`))}),Jn.addEventListener(`error`,()=>{Zn(Error(`Failed to connect CDP websocket: ${Vn}`))})})}#v(xn){this.#a&&=(clearTimeout(this.#a),null);let jn=this.#r;if(this.#r=xn,this.send(`Target.setDiscoverTargets`,{discover:!0}).catch(()=>{}),this.transportEvents.emit(this.#u?`reconnected`:`connected`).catch(xn=>{console.warn(`[${this.logId}] CDP transport listener failed`,xn)}),this.#u=!0,jn&&jn!==xn&&jn.readyState<=WebSocket.OPEN)try{jn.close(1e3,`replaced`)}catch{}}#y(xn){let Kn=this.#closedEpoch;this.#r===xn&&(this.#r=null,this.#x(Error(`CDP websocket disconnected`)),this.transportEvents.emit(`disconnected`).catch(xn=>{console.warn(`[${this.logId}] CDP disconnect listener failed`,xn)}),this.#o&&this.ensureConnected().catch(xn=>{this.#closedEpoch===Kn&&(console.warn(`[${this.logId}] CDP reconnect failed`,xn),this.#b())}))}#b(){if(!this.#o||this.isConnected||this.#i||this.#a)return;let xn=this.#n[this.#n.length-1]??3e3;let Kn=this.#closedEpoch;this.#a=setTimeout(()=>{this.#a=null,this.ensureConnected().catch(xn=>{this.#closedEpoch===Kn&&(console.warn(`[${this.logId}] Scheduled CDP reconnect failed`,xn),this.#b())})},xn)}#x(xn){for(let jn of this.#c.values())jn.timeout&&clearTimeout(jn.timeout),jn.reject(xn);this.#c.clear()}async#S(xn){let jn=typeof xn==`string`?xn:xn instanceof Blob?await xn.text():new TextDecoder().decode(xn),{data:Vn}=cdpWireMessageSchema.safeParse(JSON.parse(jn));if(Vn){if(typeof Vn.id==`number`){let xn=this.#c.get(Vn.id);if(!xn)return;if(this.#c.delete(Vn.id),xn.timeout&&clearTimeout(xn.timeout),Vn.error){let jn=Vn.error;xn.reject(new BrowserCdpCommandError(xn.method,jn.code,jn.data,jn.message??`CDP command failed: ${xn.method}`));return}xn.resolve(Vn.result);return}if(typeof Vn.method==`string`){let xn=Vn.method,jn={payload:Vn.params,meta:{sessionId:Vn.sessionId}};if(xn===`Page.javascriptDialogOpening`&&Vn.sessionId){let dialogSessionId=Vn.sessionId;jn.meta.dialog=new Dialog(Vn.params,dialogAction=>this.send(`Page.handleJavaScriptDialog`,dialogAction,dialogSessionId))}let dialog=jn.meta.dialog,emitted=this.#l.emit(xn,jn).catch(jn=>{console.warn(`[${this.logId}] CDP event listener failed for ${xn}`,jn)});dialog&&emitted.then(()=>answerWithPolicy(dialog,this.#dialogPolicy,Vn.params)).catch(()=>{})}}}}})),SessionManager,init_session_manager=__esmMin((()=>{init_client$6(),SessionManager=class{#e;#t=new Map;#n=new Map;#r=new Map;#i=new Set;#a;constructor(xn){this.#e=xn,this.#a=[this.#e.on(`Target.attachedToTarget`,xn=>{let jn=xn.targetInfo.targetId;jn&&this.#s(jn,xn.sessionId)}),this.#e.on(`Target.detachedFromTarget`,xn=>{let jn=xn.targetId??this.#n.get(xn.sessionId);this.#n.delete(xn.sessionId),jn&&this.#t.get(jn)===xn.sessionId&&this.#t.delete(jn)})]}clear(){this.#t.clear(),this.#n.clear(),this.#r.clear()}async dispose(){for(let xn of this.#a)xn();await Promise.allSettled([...this.#i].map(xn=>this.#e.send(`Target.detachFromTarget`,{sessionId:xn}).catch(()=>{}))),this.#i.clear(),this.clear()}async discoverTargets(){return await this.#e.discoverTargets()}async getPageTarget(xn){return(await this.discoverTargets()).find(jn=>jn.id===xn&&jn.type===`page`)??null}hasTargetSession(xn,jn){return this.#t.get(xn)===jn}getTargetSession(xn){return this.#t.get(xn)}async resolvePageSession(xn,jn){if(jn&&this.hasTargetSession(xn,jn))return jn;let Vn=this.#t.get(xn);if(Vn)return Vn;let qn=this.#r.get(xn);if(qn)return await qn;let Jn=this.#o(xn).finally(()=>{this.#r.delete(xn)});return this.#r.set(xn,Jn),await Jn}async#o(xn){if(!await this.getPageTarget(xn))throw Error(`Tab ${xn} is no longer available.`);let jn=await this.#e.send(`Target.attachToTarget`,{targetId:xn,flatten:!0});return this.#i.add(jn.sessionId),this.#s(xn,jn.sessionId),jn.sessionId}#s(xn,jn){this.#t.set(xn,jn),this.#n.set(jn,xn)}}})),init_cdp=__esmMin((()=>{init_client$6(),init_session_manager()})),BUNDLE$1,init_omowright_world_bundle=__esmMin((()=>{BUNDLE$1=pageBundle})),MAX_BUFFER_SIZE,CONSOLE_INTERCEPTOR_SCRIPT,PageConsole,init_console_capture=__esmMin((()=>{MAX_BUFFER_SIZE=1e3,CONSOLE_INTERCEPTOR_SCRIPT=`(function(){
100
- if(window.__omowrightConsole)return;
101
- var logs=[];
102
- var orig={log:console.log,info:console.info,warn:console.warn,error:console.error,debug:console.debug};
103
- function ser(a){
104
- var r=[];
105
- for(var i=0;i<a.length;i++){
106
- var v=a[i];
107
- try{
108
- if(v===null){r.push('null');continue}
109
- if(v===void 0){r.push('undefined');continue}
110
- if(typeof v==='string'){r.push(v);continue}
111
- if(v instanceof Error){r.push(v.name+': '+v.message);continue}
112
- r.push(JSON.stringify(v));
113
- }catch(e){r.push(String(v))}
114
- }
115
- return r.join(' ');
116
- }
117
- function cap(level,args){
118
- if(logs.length>=${MAX_BUFFER_SIZE})logs.shift();
119
- logs.push({level:level,message:ser(args),timestamp:new Date().toISOString()});
120
- }
121
- ['log','info','warn','error','debug'].forEach(function(l){
122
- console[l]=function(){cap(l,arguments);return orig[l].apply(console,arguments)};
123
- });
124
- window.__omowrightConsole={
125
- logs:logs,
126
- drain:function(o){
127
- o=o||{};
128
- var r=logs;
129
- if(o.levels&&o.levels.length)r=r.filter(function(e){return o.levels.indexOf(e.level)>=0});
130
- if(o.filter)r=r.filter(function(e){return e.message.indexOf(o.filter)>=0});
131
- if(o.limit)r=r.slice(-o.limit);
132
- return r;
133
- },
134
- clear:function(){logs.length=0}
135
- };
136
- })();`,PageConsole=class{#e;constructor(xn){this.#e=xn}async logs(xn={}){return await this.#e.evaluate(xn=>window.__omowrightConsole?.drain(xn)??[],xn)}async clear(){await this.#e.evaluate(`(window).__omowrightConsole?.clear()`)}}}));function isContextDestroyedError(xn){let jn=xn instanceof Error?xn.message:String(xn);return jn.includes(`Cannot find context with specified id`)||jn.includes(`Execution context was destroyed`)}var ISOLATED_WORLD_NAME,FrameManager,init_frame_manager=__esmMin((()=>{init_client$6(),init_omowright_world_bundle(),init_console_capture(),ISOLATED_WORLD_NAME=`__omowright_utility`,FrameManager=class{cdp;targetId;frames=new Map;#e=new Set;#t=new Set;#n=new Map;#r=null;#i=null;#a;#o=null;#s=null;#c=[];onSessionInitialized;constructor(xn,jn,Vn){this.cdp=xn,this.targetId=jn,this.#a=Vn}#l(xn,jn){return this.cdp.on(xn,(xn,Vn)=>{this.#v(Vn.sessionId)&&jn(xn)})}async initialize(){this.#c.push(this.#l(`Target.attachedToTarget`,xn=>{if(xn.targetInfo.type!==`iframe`)return;let jn=xn.targetInfo.targetId,Vn=this.frames.get(jn)??{frameId:jn,parentFrameId:xn.targetInfo.parentFrameId??null,url:xn.targetInfo.url??``,name:xn.targetInfo.title??``,sessionId:xn.sessionId};this.frames.set(jn,Vn),Vn.sessionId=xn.sessionId,this.#p(xn.sessionId).then(async()=>{this.onSessionInitialized?.(xn.sessionId);let jn=await this.#m(xn.sessionId,Vn.parentFrameId??xn.targetInfo.parentFrameId??null);await this.ensureInjected(jn)}).catch(()=>{})}));await this.#p(this.#a);let{identifier:xn}=await this.#f(`Page.addScriptToEvaluateOnNewDocument`,{source:BUNDLE$1,worldName:ISOLATED_WORLD_NAME,runImmediately:!0});this.#o=xn;let{identifier:jn}=await this.#f(`Page.addScriptToEvaluateOnNewDocument`,{source:CONSOLE_INTERCEPTOR_SCRIPT,runImmediately:!0});this.#s=jn,this.#c.push(this.#l(`Page.frameAttached`,xn=>{let jn=this.frames.get(xn.frameId);this.frames.set(xn.frameId,{frameId:xn.frameId,parentFrameId:xn.parentFrameId,url:jn?.url??``,name:jn?.name??``,sessionId:jn?.sessionId??this.#a,isolatedContextId:jn?.isolatedContextId})})),this.#c.push(this.#l(`Page.frameNavigated`,xn=>{let jn=xn.frame,Vn=this.frames.get(jn.id);for(let{frameId:qn}of this.collectDescendantFrames(jn.id).slice(1)){let Jn=this.frames.get(qn);this.#_(Jn),this.#n.delete(qn),this.frames.delete(qn),Jn.sessionId!==this.#a&&!this.hasSession(Jn.sessionId)&&this.#t.delete(Jn.sessionId)}Vn?.isolatedContextId&&this.#e.delete(Vn.isolatedContextId),this.#n.delete(jn.id),this.frames.set(jn.id,{frameId:jn.id,parentFrameId:jn.parentId??null,url:jn.url,name:jn.name??``,sessionId:Vn?.sessionId??this.#a,isolatedContextId:void 0}),jn.parentId||(this.#i=jn.id),this.ensureInjected(jn.id)})),this.#c.push(this.#l(`Page.frameDetached`,xn=>{let jn=this.frames.get(xn.frameId);if(jn?.isolatedContextId&&this.#e.delete(jn.isolatedContextId),this.#n.delete(xn.frameId),xn.reason===`swap`){jn&&delete jn.isolatedContextId;return}jn?.sessionId&&this.#t.delete(jn.sessionId),this.frames.delete(xn.frameId),this.#i===xn.frameId&&(this.#i=null)}));let{frameTree:Vn}=await this.#f(`Page.getFrameTree`);this.#d(Vn,null),await this.#u()}async#u(){await Promise.all([...this.frames.keys()].map(xn=>this.ensureInjected(xn)))}get mainFrameId(){return this.#i}getFrame(xn){return this.frames.get(xn)??null}hasSession(xn){if(this.#a===xn)return!0;for(let jn of this.frames.values())if(jn.sessionId===xn)return!0;return!1}async ensureInjected(xn){let jn=this.frames.get(xn);if(!jn)return null;if(jn.isolatedContextId&&this.#e.has(jn.isolatedContextId))return jn.isolatedContextId;let Vn=this.#n.get(xn);if(Vn)return await Vn;let qn=this.#h(xn);this.#n.set(xn,qn);try{return await qn}finally{this.#n.get(xn)===qn&&this.#n.delete(xn)}}collectDescendantFrames(xn){if(!this.frames.has(xn))return[];let jn=new Map;for(let xn of this.frames.values()){if(!xn.parentFrameId)continue;let Vn=jn.get(xn.parentFrameId)??[];Vn.push(xn.frameId),jn.set(xn.parentFrameId,Vn)}let Vn=[],qn=[{frameId:xn,parentFrameId:this.frames.get(xn)?.parentFrameId??null,depth:0}],Jn=new Set;for(;qn.length>0;){let xn=qn.shift();if(Jn.has(xn.frameId))continue;Jn.add(xn.frameId),Vn.push(xn);let Yn=jn.get(xn.frameId)??[];for(let jn of Yn)qn.push({frameId:jn,parentFrameId:xn.frameId,depth:xn.depth+1})}return Vn}resolveFrameIdForSnapshotPrefix(xn){if(this.#r){let jn=this.#r.get(xn);if(jn&&this.frames.has(jn))return jn;if(xn)return null}return!xn&&this.#i&&this.frames.has(this.#i)?this.#i:null}setSnapshotFramePrefixMap(xn){this.#r=xn}invalidateContext(xn){let jn=this.frames.get(xn);jn&&this.#_(jn)}async dispose(){for(let xn of this.#c)xn();this.#c=[];for(let xn of[this.#o,this.#s])xn&&await this.cdp.send(`Page.removeScriptToEvaluateOnNewDocument`,{identifier:xn},this.#a).catch(()=>{});this.#o=null,this.#s=null}async reconnect(xn){await this.dispose(),this.frames.clear(),this.#e.clear(),this.#t.clear(),this.#n.clear(),this.#r=null,this.#i=null,this.#a=xn,await this.initialize()}#d(xn,jn){let{frame:Vn}=xn,qn=this.frames.get(Vn.id);this.frames.set(Vn.id,{frameId:Vn.id,parentFrameId:jn,url:Vn.url,name:Vn.name??``,sessionId:qn?.sessionId??this.#a,isolatedContextId:qn?.isolatedContextId}),jn||(this.#i=Vn.id);for(let jn of xn.childFrames??[])this.#d(jn,Vn.id)}async#f(xn,jn){return await this.cdp.send(xn,jn,this.#a)}async#p(xn){this.#t.has(xn)||(await this.cdp.send(`Page.enable`,void 0,xn),await this.cdp.send(`DOM.enable`,void 0,xn),await this.cdp.send(`Inspector.enable`,void 0,xn).catch(()=>{}),await this.cdp.send(`Page.setWebLifecycleState`,{state:`active`},xn).catch(()=>{}),await this.cdp.send(`Emulation.setFocusEmulationEnabled`,{enabled:!0},xn).catch(()=>{}),await this.cdp.send(`Target.setAutoAttach`,{autoAttach:!0,waitForDebuggerOnStart:!1,flatten:!0},xn),this.#t.add(xn))}async#m(xn,jn){let{frameTree:Vn}=await this.cdp.send(`Page.getFrameTree`,void 0,xn),qn=Vn.frame.parentId??jn??null;return this.#d(Vn,qn),Vn.frame.id}async#h(xn){let jn=this.frames.get(xn);if(!jn)return null;if(jn.isolatedContextId){if(await this.#g(jn))return this.#e.add(jn.isolatedContextId),jn.isolatedContextId;this.#_(jn)}try{let{executionContextId:Vn}=await this.cdp.send(`Page.createIsolatedWorld`,{frameId:xn,worldName:ISOLATED_WORLD_NAME},jn.sessionId||this.#a);jn.isolatedContextId=Vn}catch{return null}try{await this.cdp.send(`Runtime.evaluate`,{expression:BUNDLE$1,contextId:jn.isolatedContextId},jn.sessionId||this.#a)}catch(xn){if(isContextDestroyedError(xn))return this.#_(jn),null}return await this.#g(jn)?(this.#e.add(jn.isolatedContextId),jn.isolatedContextId):(this.#_(jn),null)}async#g(xn){if(!xn.isolatedContextId)return!1;let{result:jn}=await this.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`function() { return typeof globalThis.__omowright; }`,executionContextId:xn.isolatedContextId,returnByValue:!0},xn.sessionId||this.#a).catch(()=>({result:{value:`error`}}));return jn.value===`object`}#_(xn){xn.isolatedContextId&&(this.#e.delete(xn.isolatedContextId),delete xn.isolatedContextId)}#v(xn){if(!xn)return!1;if(xn===this.#a)return!0;for(let jn of this.frames.values())if(jn.sessionId===xn)return!0;return!1}}}));var omowrightNotificationPermissionValues,init_notification_grants=__esmMin((()=>{init_drizzle_orm(),init_schema(),init_state_db(),omowrightNotificationPermissionValues=[`allow_for_ai`,`allow`,`deny`,`default`]}));function formatCallFrame(xn){let jn=xn.url?`${xn.url}:${(xn.lineNumber??0)+1}:${(xn.columnNumber??0)+1}`:null;if(!jn)return null;let Vn=xn.functionName?.trim();return Vn?`at ${Vn} (${jn})`:`at ${jn}`}function formatRuntimeException(xn,jn){if(!xn)return jn;let Vn=typeof xn.exception?.description==`string`&&xn.exception.description.trim()||typeof xn.exception?.value==`string`&&xn.exception.value.trim()||typeof xn.text==`string`&&xn.text.trim()||jn,qn=xn.stackTrace?.callFrames?.map(formatCallFrame).filter(xn=>!!xn)??[],Jn=qn.some(xn=>Vn.includes(xn));return qn.length>0&&!Jn?`${Vn}\n${qn.join(`
137
- `)}`:Vn}var init_errors$3=__esmMin((()=>{})),TRACKING_PARAMS,init_tracking_params=__esmMin((()=>{TRACKING_PARAMS=new Set([`utm_source`,`utm_medium`,`utm_campaign`,`utm_term`,`utm_content`,`gclid`,`gclsrc`,`fbclid`,`mc_cid`,`mc_eid`,`msclkid`,`twclid`,`li_fat_id`,`_ga`,`_gl`,`_t`,`_ts`,`_nc`])}));function truncateUrlForLLM(xn,jn){let Vn=jn?.maxLength??128,qn;try{qn=new URL(xn)}catch{return xn.length>Vn?xn.slice(0,Vn)+`…`:xn}for(let xn of qn.searchParams.keys())TRACKING_PARAMS.has(xn.toLowerCase())&&qn.searchParams.delete(xn);if(jn?.currentOrigin)try{let xn=new URL(jn.currentOrigin);if(qn.origin===xn.origin){let xn=qn.pathname+qn.search+qn.hash;return xn.length>Vn?truncateQuery(xn,Vn):xn}}catch{}let Jn=qn.toString();return Jn.length<=Vn?Jn:truncateQuery(Jn,Vn)}function truncateQuery(xn,jn){let Vn=xn.indexOf(`?`);return Vn===-1||Vn>=jn?xn.length>jn?xn.slice(0,jn)+`…`:xn:xn.slice(0,jn)+`…`}var init_utils$4=__esmMin((()=>{init_tracking_params()}));async function ensureDirForFile$1(xn){await promises.mkdir(path.dirname(xn),{recursive:!0})}var OmODownload,init_download=__esmMin((()=>{init_directory(),OmODownload=class{#e;#t;#n;#r;#i;#a=null;#o=!1;constructor(xn,jn){this.#e=xn,this.#t=jn.guid,this.#n=jn.startedAfterMs,this.#r=jn.suggestedFilename,this.#i=jn.url,this.#a=jn.sourcePath?Promise.resolve(jn.sourcePath):null}page(){return this.#e}suggestedFilename(){return this.#r}url(){return this.#i}async path(){return this.#c(),await this.#s()}async saveAs(xn){this.#c();let jn=await this.#s(),Vn=path.isAbsolute(xn)?xn:path.join(SESSION_ARTIFACTS_DIR,xn),qn=await this.#e.browser.ensurePath(Vn,`write`,`download.saveAs`);path.resolve(jn)!==path.resolve(qn)&&(await ensureDirForFile$1(qn),await promises.copyFile(jn,qn))}async createReadStream(){return this.#c(),createReadStream(await this.#s())}async failure(){try{return await this.#s(),null}catch(xn){return xn instanceof Error?xn.message:String(xn)}}async cancel(){}async delete(){this.#c(),this.#o=!0}async#s(){return this.#a||=this.#e.cdp.send(`OmO.waitForDownload`,{startedAfterMs:this.#n,expectedFilename:this.#r,referrerUrl:this.#e.url()},void 0,{extensionBridge:this.#e.browser.extensionBridgeRoute}).then(xn=>xn.absolutePath),this.#e.browser.registerReadableDownloadPath(await this.#a)}#c(){if(this.#o)throw Error(`Download has been deleted.`)}get guid(){return this.#t}}})),RefStaleError,init_types$4=__esmMin((()=>{RefStaleError=class extends Error{constructor(xn){super(`Ref "${xn}" is stale — the element was removed or the page changed. Take a new snapshot and retry.`),this.name=`RefStaleError`}}}));function resolveSmartModifierString(xn){if(xn.length===1)return xn;let jn=xn.trim();return jn.toLowerCase()===`controlormeta`?process.platform===`darwin`?`Meta`:`Control`:jn}function setKey(xn,jn){KEYBOARD_LAYOUT[xn]=jn}function addKey(xn,jn=[]){setKey(xn.key,xn),xn.code!==xn.key&&setKey(xn.code,xn);for(let Vn of jn)setKey(Vn,xn)}function addCodeOnlyKey(xn,jn=[]){setKey(xn.code,xn);for(let Vn of jn)setKey(Vn,xn)}function linkShifted(xn,jn){let Vn={...xn,key:jn,text:jn};return{...xn,shifted:Vn}}function keyCommands(xn,jn){if(process.platform!==`darwin`)return[];let Vn=[...[`Shift`,`Control`,`Alt`,`Meta`].filter(xn=>jn.includes(xn)),xn].join(`+`),qn=MAC_EDITING_COMMANDS.get(Vn);return(Array.isArray(qn)?qn:qn?[qn]:[]).filter(xn=>!xn.startsWith(`insert`)).map(xn=>xn.replace(/:$/,``))}function lookupKeyDescriptor(xn){let jn=resolveSmartModifierString(xn);return KEYBOARD_LAYOUT[jn]??KEYBOARD_LAYOUT[jn.toLowerCase()]??KEYBOARD_LAYOUT[jn.toUpperCase()]}function resolveKeyDescriptor(xn,jn={}){let Vn=lookupKeyDescriptor(xn);if(!Vn)throw Error(`Unknown key: ${xn}`);let qn=new Set([...jn.modifiers??[]].map(xn=>resolveSmartModifierString(xn)).filter(xn=>MODIFIER_KEYS.has(xn))),Jn=qn.has(`Shift`)&&Vn.shifted?Vn.shifted:Vn;return Jn.text.length===0||qn.size===0||qn.size===1&&qn.has(`Shift`)?Jn:{...Jn,text:``}}function splitKeyCombo(xn){if(xn.length===1&&KEYBOARD_LAYOUT[xn])return[xn];let jn=xn.trim();if(!jn)return[];let Vn=[],qn=``;for(let xn of jn){if(xn!==`+`){qn+=xn;continue}if(qn.trim()){Vn.push(qn.trim()),qn=``;continue}Vn.push(`+`)}return qn.trim()&&Vn.push(qn.trim()),Vn}async function shouldUseDomInputFallback(xn){return await xn.evaluate(()=>document.visibilityState!==`visible`||!document.hasFocus())}var KEYBOARD_LAYOUT,MODIFIER_KEYS,BUTTON_MASKS,MAC_EDITING_COMMANDS,shiftedDigits,ModifierState,OmOKeyboard,init_keyboard=__esmMin((()=>{init_utils$13(),KEYBOARD_LAYOUT={},MODIFIER_KEYS=new Set([`Alt`,`Control`,`Meta`,`Shift`]),BUTTON_MASKS=new Map([[`left`,1],[`right`,2],[`middle`,4],[`back`,8],[`forward`,16]]),MAC_EDITING_COMMANDS=new Map([[`Meta+KeyA`,`selectAll:`],[`Meta+KeyC`,`copy:`],[`Meta+KeyV`,`paste:`],[`Meta+KeyX`,`cut:`],[`Meta+KeyZ`,`undo:`],[`Shift+Meta+KeyZ`,`redo:`]]);for(let xn=0;xn<26;xn+=1){let jn=String.fromCharCode(97+xn),Vn=jn.toUpperCase(),qn=65+xn,Jn=linkShifted({key:jn,code:`Key${Vn}`,keyCode:qn,keyCodeWithoutLocation:qn,text:jn,location:0},Vn);addKey(Jn),setKey(Vn,Jn.shifted)}shiftedDigits=[` )`,`!`,`@`,`#`,`$`,`%`,`^`,`&`,`*`,`(`].map(xn=>xn.trimStart());for(let xn=0;xn<10;xn+=1){let jn=String(xn),Vn=48+xn,qn=linkShifted({key:jn,code:`Digit${jn}`,keyCode:Vn,keyCodeWithoutLocation:Vn,text:jn,location:0},shiftedDigits[xn]);addKey(qn),setKey(qn.shifted.key,qn.shifted)}for(let{key:xn,shifted:jn,code:Vn,keyCode:qn}of[{key:"`",shifted:`~`,code:`Backquote`,keyCode:192},{key:`-`,shifted:`_`,code:`Minus`,keyCode:189},{key:`=`,shifted:`+`,code:`Equal`,keyCode:187},{key:`[`,shifted:`{`,code:`BracketLeft`,keyCode:219},{key:`]`,shifted:`}`,code:`BracketRight`,keyCode:221},{key:`\\`,shifted:`|`,code:`Backslash`,keyCode:220},{key:`;`,shifted:`:`,code:`Semicolon`,keyCode:186},{key:`'`,shifted:`"`,code:`Quote`,keyCode:222},{key:`,`,shifted:`<`,code:`Comma`,keyCode:188},{key:`.`,shifted:`>`,code:`Period`,keyCode:190},{key:`/`,shifted:`?`,code:`Slash`,keyCode:191}]){let Jn=linkShifted({key:xn,code:Vn,keyCode:qn,keyCodeWithoutLocation:qn,text:xn,location:0},jn);addKey(Jn),setKey(jn,Jn.shifted)}for(let[xn,jn]of[[{key:`Backspace`,code:`Backspace`,keyCode:8,keyCodeWithoutLocation:8,text:``,location:0}],[{key:`Tab`,code:`Tab`,keyCode:9,keyCodeWithoutLocation:9,text:` `,location:0},[` `]],[{key:`Enter`,code:`Enter`,keyCode:13,keyCodeWithoutLocation:13,text:`\r`,location:0},[`Return`,`
138
- `,`\r`]],[{key:`Escape`,code:`Escape`,keyCode:27,keyCodeWithoutLocation:27,text:``,location:0},[`Esc`]],[{key:`Delete`,code:`Delete`,keyCode:46,keyCodeWithoutLocation:46,text:``,location:0},[`Del`]],[{key:`Insert`,code:`Insert`,keyCode:45,keyCodeWithoutLocation:45,text:``,location:0},[`Ins`]],[{key:`Home`,code:`Home`,keyCode:36,keyCodeWithoutLocation:36,text:``,location:0}],[{key:`End`,code:`End`,keyCode:35,keyCodeWithoutLocation:35,text:``,location:0}],[{key:`PageUp`,code:`PageUp`,keyCode:33,keyCodeWithoutLocation:33,text:``,location:0}],[{key:`PageDown`,code:`PageDown`,keyCode:34,keyCodeWithoutLocation:34,text:``,location:0}],[{key:`ArrowUp`,code:`ArrowUp`,keyCode:38,keyCodeWithoutLocation:38,text:``,location:0},[`Up`]],[{key:`ArrowDown`,code:`ArrowDown`,keyCode:40,keyCodeWithoutLocation:40,text:``,location:0},[`Down`]],[{key:`ArrowLeft`,code:`ArrowLeft`,keyCode:37,keyCodeWithoutLocation:37,text:``,location:0},[`Left`]],[{key:`ArrowRight`,code:`ArrowRight`,keyCode:39,keyCodeWithoutLocation:39,text:``,location:0},[`Right`]],[{key:`Shift`,code:`ShiftLeft`,keyCode:16,keyCodeWithoutLocation:16,text:``,location:1}],[{key:`Control`,code:`ControlLeft`,keyCode:17,keyCodeWithoutLocation:17,text:``,location:1},[`Ctrl`]],[{key:`Alt`,code:`AltLeft`,keyCode:18,keyCodeWithoutLocation:18,text:``,location:1},[`Option`]],[{key:`Meta`,code:`MetaLeft`,keyCode:91,keyCodeWithoutLocation:91,text:``,location:1},[`Command`,`Cmd`,`OS`]],[{key:`ContextMenu`,code:`ContextMenu`,keyCode:93,keyCodeWithoutLocation:93,text:``,location:0}],[{key:`CapsLock`,code:`CapsLock`,keyCode:20,keyCodeWithoutLocation:20,text:``,location:0}],[{key:`NumLock`,code:`NumLock`,keyCode:144,keyCodeWithoutLocation:144,text:``,location:0}],[{key:`ScrollLock`,code:`ScrollLock`,keyCode:145,keyCodeWithoutLocation:145,text:``,location:0}],[{key:`Pause`,code:`Pause`,keyCode:19,keyCodeWithoutLocation:19,text:``,location:0}],[{key:`PrintScreen`,code:`PrintScreen`,keyCode:44,keyCodeWithoutLocation:44,text:``,location:0}],[{key:`Space`,code:`Space`,keyCode:32,keyCodeWithoutLocation:32,text:` `,location:0},[` `]]])addKey(xn,jn);for(let xn=1;xn<=12;xn+=1){let jn=`F${xn}`;addKey({key:jn,code:jn,keyCode:111+xn,keyCodeWithoutLocation:111+xn,text:``,location:0})}for(let xn=0;xn<=9;xn+=1)addCodeOnlyKey({key:String(xn),code:`Numpad${xn}`,keyCode:96+xn,keyCodeWithoutLocation:48+xn,text:String(xn),location:3});for(let[xn,jn,Vn,qn]of[[`NumpadMultiply`,106,56,`*`],[`NumpadAdd`,107,187,`+`],[`NumpadSubtract`,109,189,`-`],[`NumpadDecimal`,110,190,`.`],[`NumpadDivide`,111,191,`/`],[`NumpadEnter`,13,13,`\r`]])addCodeOnlyKey({key:qn||xn,code:xn,keyCode:jn,keyCodeWithoutLocation:Vn,text:qn,location:3});ModifierState=class{#e=new Set;#t=new Set;down(xn){MODIFIER_KEYS.has(xn)&&this.#e.add(xn)}up(xn){this.#e.delete(xn)}has(xn){return this.#e.has(xn)}modifiers(){return[...this.#e]}mouseDown(xn){this.#t.add(xn)}mouseUp(xn){this.#t.delete(xn)}toModifiersMask(){let xn=0;return this.#e.has(`Alt`)&&(xn|=1),this.#e.has(`Control`)&&(xn|=2),this.#e.has(`Meta`)&&(xn|=4),this.#e.has(`Shift`)&&(xn|=8),xn}toButtonsMask(){let xn=0;for(let jn of this.#t)xn|=BUTTON_MASKS.get(jn)??0;return xn}},OmOKeyboard=class{context;modifierState;#e=new Set;constructor(xn,jn){this.context=xn,this.modifierState=jn}async down(xn){await this.#n(xn)}async up(xn){await this.#r(xn)}async insertText(xn){await this.#t(xn)}async press(xn,jn={},Vn){let qn=splitKeyCombo(xn);if(qn.length===0)throw Error(`Key combo is empty`);let Jn=qn.slice(0,-1),Yn=qn[qn.length-1],Zn=[],Qn;try{for(let xn of Jn)await this.#n(xn,Vn),Zn.push(xn);await this.#n(Yn,Vn),(jn.delay??0)>0&&await sleep$12(jn.delay),await this.#r(Yn,Vn)}catch(xn){Qn=xn}let ei;for(let xn=Zn.length-1;xn>=0;--xn)try{await this.#r(Zn[xn],Vn)}catch(xn){ei??=xn}if(Qn)throw Qn;if(ei)throw ei}async type(xn,jn,Vn){let qn=jn?.delay??0;for(let jn of xn){if(jn===`
139
- `||jn===`\r`||!lookupKeyDescriptor(jn)){qn>0&&await sleep$12(qn),await this.#t(jn,Vn);continue}await this.#a(jn,qn,Vn)}}async#t(xn,jn){await this.context._sendToTarget(`Input.insertText`,{text:xn},this.#i(jn))}async#n(xn,jn){let Vn=resolveKeyDescriptor(xn,{modifiers:this.modifierState.modifiers()}),qn=this.#e.has(Vn.code),Jn=this.modifierState.has(Vn.key);this.#e.add(Vn.code),this.modifierState.down(Vn.key);let Yn=keyCommands(Vn.code,this.modifierState.modifiers());try{await this.context._sendToTarget(`Input.dispatchKeyEvent`,{type:Vn.text?`keyDown`:`rawKeyDown`,key:Vn.key,code:Vn.code,commands:Yn,text:Vn.text,unmodifiedText:Vn.text,windowsVirtualKeyCode:Vn.keyCodeWithoutLocation,autoRepeat:qn,location:Vn.location,isKeypad:Vn.location===3,modifiers:this.modifierState.toModifiersMask()},this.#i(jn))}catch(xn){throw qn||this.#e.delete(Vn.code),Jn||this.modifierState.up(Vn.key),xn}return Vn}async#r(xn,jn){let Vn=resolveKeyDescriptor(xn,{modifiers:this.modifierState.modifiers()}),qn=this.#e.has(Vn.code),Jn=this.modifierState.has(Vn.key);this.#e.delete(Vn.code),this.modifierState.up(Vn.key);try{await this.context._sendToTarget(`Input.dispatchKeyEvent`,{type:`keyUp`,key:Vn.key,code:Vn.code,windowsVirtualKeyCode:Vn.keyCodeWithoutLocation,location:Vn.location,modifiers:this.modifierState.toModifiersMask()},this.#i(jn))}catch(xn){throw qn&&this.#e.add(Vn.code),Jn&&this.modifierState.down(Vn.key),xn}}#i(xn){return xn===void 0?void 0:{preferredSessionId:xn}}async#a(xn,jn,Vn){await this.#n(xn,Vn),jn>0&&await sleep$12(jn),await this.#r(xn,Vn)}}}));function isTransientEvaluationError(xn){if(!(xn instanceof Error))return!1;let jn=xn.message.toLowerCase();return jn.includes(`execution context was destroyed`)||jn.includes(`cannot find context with specified id`)||jn.includes(`cannot find object with given id`)||jn.includes(`most likely because of a navigation`)||jn.includes(`inspected target navigated or closed`)||jn.includes(`target page, context or browser has been closed`)}function isDomReadyTimeoutError(xn){return xn instanceof Error&&xn.message.includes(`Timed out waiting for document readiness`)}function isPdfViewerUrl(xn){return xn.startsWith(PDF_VIEWER_EXTENSION_PREFIX)||xn.endsWith(`.pdf`)}function getProbeState(xn){return xn.bodyExists?xn.interactiveCount>0||xn.landmarkCount>0||xn.textChars>=MIN_PROBE_TEXT_CHARS||xn.frameset&&xn.documentComplete?`ready`:`sparse`:`missing-body`}function getNaiveRegistrableDomain(xn){try{let jn=new URL(xn).hostname.toLowerCase(),Vn=jn.split(`.`).filter(Boolean);return Vn.length<=2?jn:Vn.slice(-2).join(`.`)}catch{return``}}function isSameSite(xn,jn){return jn?xn===jn||xn.endsWith(`.${jn}`):!1}async function waitForDomReady(xn,jn=DOM_READY_TIMEOUT_MS){let Vn=Date.now()+jn;for(;Date.now()<Vn;){try{if(await xn.evaluate(`document.readyState`)!==`loading`)return}catch(xn){if(!isTransientEvaluationError(xn))throw xn}await sleep$12(50)}throw Error(`Timed out waiting for document readiness after ${jn}ms`)}async function takePageProbe(xn){let jn=await xn.evaluate(`(() => {
140
- const isVisibleElement = (element) => {
141
- const style = window.getComputedStyle(element);
142
- if (
143
- style.display === 'none' ||
144
- style.visibility === 'hidden' ||
145
- style.visibility === 'collapse' ||
146
- Number.parseFloat(style.opacity || '1') === 0
147
- ) {
148
- return false;
149
- }
150
-
151
- const rect = element.getBoundingClientRect();
152
- return rect.width > 0 && rect.height > 0;
153
- }
154
-
155
- const body = document.body;
156
- if (!body) {
157
- return {
158
- bodyExists: false,
159
- interactiveCount: 0,
160
- landmarkCount: 0,
161
- textChars: 0,
162
- };
163
- }
164
-
165
- const interactiveSelector = [
166
- 'a[href]',
167
- 'button',
168
- 'input:not([type="hidden"])',
169
- 'textarea',
170
- 'select',
171
- 'summary',
172
- '[role="button"]',
173
- '[role="link"]',
174
- '[role="menuitem"]',
175
- '[role="option"]',
176
- '[tabindex]:not([tabindex="-1"])',
177
- '[contenteditable="true"]',
178
- ].join(',');
179
- const landmarkSelector = [
180
- 'main',
181
- 'nav',
182
- 'header',
183
- 'footer',
184
- 'aside',
185
- 'form',
186
- '[role="main"]',
187
- '[role="navigation"]',
188
- '[role="banner"]',
189
- '[role="contentinfo"]',
190
- '[role="complementary"]',
191
- '[role="form"]',
192
- ].join(',');
193
-
194
- return {
195
- bodyExists: true,
196
- interactiveCount: Array.from(document.querySelectorAll(interactiveSelector))
197
- .filter((element) => isVisibleElement(element))
198
- .slice(0, 25).length,
199
- landmarkCount: Array.from(document.querySelectorAll(landmarkSelector))
200
- .filter((element) => isVisibleElement(element))
201
- .slice(0, 10).length,
202
- textChars: body.innerText.replace(/\\s+/g, ' ').trim().length,
203
- documentComplete: document.readyState === 'complete',
204
- frameset: body.tagName === 'FRAMESET',
205
- };
206
- })()`);return{...jn,state:getProbeState(jn)}}async function ensureDomMonitor(xn){await xn.evaluate(`(() => {
207
- const key = ${JSON.stringify(DOM_MONITOR_KEY)};
208
- const target = globalThis;
209
- if (target[key]) {
210
- return;
211
- }
212
-
213
- let mutationCount = 0;
214
- const observer = new MutationObserver((mutations) => {
215
- mutationCount += mutations.length;
216
- });
217
-
218
- observer.observe(document, {
219
- subtree: true,
220
- childList: true,
221
- attributes: true,
222
- });
223
-
224
- target[key] = {
225
- observer,
226
- takeSnapshot() {
227
- const snapshot = {
228
- mutationCount,
229
- totalNodes: Math.max(document.getElementsByTagName('*').length, 1),
230
- };
231
- mutationCount = 0;
232
- return snapshot;
233
- },
234
- };
235
- })()`)}async function readDomMonitor(xn){return await xn.evaluate(`(() => {
236
- const key = ${JSON.stringify(DOM_MONITOR_KEY)};
237
- const target = globalThis;
238
- const monitor = target[key];
239
-
240
- if (!monitor?.takeSnapshot) {
241
- return {
242
- mutationCount: 0,
243
- totalNodes: Math.max(document.getElementsByTagName('*').length, 1),
244
- };
245
- }
246
-
247
- return monitor.takeSnapshot();
248
- })()`)}function collectTrackedSessionIds(xn,jn){let Vn=new Set;jn&&Vn.add(jn);for(let jn of xn.frameManager.frames.values())Vn.add(jn.sessionId);return Vn}async function waitForNavigationReadiness(xn,jn=`interactive`,Vn=ACTION_MAX_WAIT_MS){return await Promise.race([waitForNavigationReadinessInner(xn,jn,Vn),sleep$12(Vn+1e3).then(()=>{throw new NavigationReadinessTimeoutError(jn,Vn)})])}async function waitForNavigationReadinessInner(xn,jn,Vn){if(isPdfViewerUrl(xn.url()))return await waitForDomReady(xn,Math.min(DOM_READY_TIMEOUT_MS,Vn)).catch(()=>{}),{bodyExists:!0,interactiveCount:0,landmarkCount:0,textChars:0,state:`ready`};let qn=Date.now()+Vn,Jn=0,Yn=collectTrackedSessionIds(xn,await xn.resolveSessionId().catch(()=>void 0)),Zn=new NetworkTracker(xn.cdp,Yn),Qn=null,ei=!1,ti=null,ni=null,si=null;try{for(await waitForDomReady(xn,Math.min(DOM_READY_TIMEOUT_MS,Vn)).catch(()=>{}),jn===`stable`&&await ensureDomMonitor(xn).catch(()=>{}),ni=xn.cdp.on(`Page.frameNavigated`,(xn,jn)=>{!jn.sessionId||!Yn.has(jn.sessionId)||xn.frame.parentId||(ei=!0)});Date.now()<qn;){await sleep$12(PROBE_INTERVAL_MS);try{if(ei){ei=!1,Jn=0,Qn=null,ti=null,si=null,await waitForDomReady(xn,Math.min(DOM_READY_TIMEOUT_MS,Math.max(qn-Date.now(),0))).catch(()=>{}),jn===`stable`&&await ensureDomMonitor(xn).catch(()=>{});continue}let Vn=await takePageProbe(xn);if(Vn.state!==`ready`){if(Vn.state===`sparse`&&Vn.documentComplete){if(si??=Date.now(),Date.now()-si>=SPARSE_COMPLETE_GRACE_MS)return Vn}else si=null;Jn=0,Qn=null,ti=null;continue}if(Zn.captureTrackedRequests(xn.url()).size>0&&(Qn||=Date.now(),Date.now()-Qn<NAVIGATION_NETWORK_BUDGET_MS)){Jn=0;continue}if(Vn.interactiveCount===0&&(ti||=Date.now(),Date.now()-ti<REDIRECT_GUARD_MS))continue;if(jn===`interactive`)return Vn;let Yn=await readDomMonitor(xn);if(Jn=Yn.mutationCount/Yn.totalNodes<=QUIET_MUTATION_RATIO?Jn+1:0,Jn>=QUIET_SAMPLE_COUNT)return Vn}catch(jn){if(!isTransientEvaluationError(jn))throw jn;Jn=0,Qn=null,ti=null;let Vn=Math.max(qn-Date.now(),0);await waitForDomReady(xn,Math.min(DOM_READY_TIMEOUT_MS,Vn))}}throw new NavigationReadinessTimeoutError(jn,Vn)}finally{ni?.(),Zn.dispose()}}async function waitForDomQuiet(xn,jn={}){let Vn=jn.budgetMs??QUIET_WINDOW_MS,qn=jn.sampleIntervalMs??QUIET_SAMPLE_INTERVAL_MS,Jn=jn.quietMutationRatio??QUIET_MUTATION_RATIO,Yn=jn.quietSampleCount??QUIET_SAMPLE_COUNT,Zn=Date.now()+Vn,Qn=0;try{for(await waitForDomReady(xn,Math.min(DOM_READY_TIMEOUT_MS,Vn)).catch(()=>{}),await ensureDomMonitor(xn).catch(()=>{});Date.now()<Zn;){await sleep$12(qn);let jn=await readDomMonitor(xn);if(Qn=jn.mutationCount/jn.totalNodes<=Jn?Qn+1:0,Qn>=Yn)return!0}}catch(xn){if(!isTransientEvaluationError(xn))throw xn}return!1}async function performActionAndWait(xn,jn,Vn={}){let qn=Vn.timeoutMs??ACTION_MAX_WAIT_MS,Jn=Date.now()+qn,Yn=collectTrackedSessionIds(xn,Vn.frameSessionId?await xn.resolveSessionId(Vn.frameSessionId):await xn.resolveSessionId()),Zn=new NetworkTracker(xn.cdp,Yn),Qn=!1,ei,ti=await xn.evaluate(()=>location.href).catch(()=>xn.url()),ni=xn.cdp.on(`Page.frameNavigated`,(xn,jn)=>{!jn.sessionId||!Yn.has(jn.sessionId)||xn.frame.parentId||(Qn=!0)});try{await Zn.ready;ei=await jn();try{let jn=Math.max(Jn-Date.now(),0);await waitForDomReady(xn,Math.min(DOM_READY_TIMEOUT_MS,jn))}catch(xn){if(!isTransientEvaluationError(xn)&&!isDomReadyTimeoutError(xn))throw xn}await sleep$12(Vn.hookWindowMs??ACTION_HOOK_WINDOW_MS);let qn=Zn.captureTrackedRequests(xn.url()),Yn=Math.min(Date.now()+(Vn.requestTrackingBudgetMs??ACTION_REQUEST_TRACKING_BUDGET_MS),Jn);for(;qn.size>0&&Date.now()<Yn&&!Qn;){for(let xn of qn)Zn.isFinished(xn)&&qn.delete(xn);qn.size>0&&await sleep$12(NETWORK_TRACK_POLL_MS)}if(Qn)return await waitForNavigationReadiness(xn,`interactive`,Math.max(Jn-Date.now(),DOM_READY_TIMEOUT_MS)),ei;let ni=await xn.evaluate(()=>location.href).catch(()=>xn.url())!==ti,ri=Math.min(Vn.postSettleMs??(ni?SPA_URL_CHANGE_POST_SETTLE_MS:ACTION_POST_SETTLE_MS),Math.max(Jn-Date.now(),0));if(ri>0){let jn=ni?Math.min(SPA_URL_CHANGE_MIN_DWELL_MS,ri):0;ni&&await sleep$12(jn);let Vn=Math.max(ri-jn,0);await waitForDomQuiet(xn,{budgetMs:Vn,sampleIntervalMs:50,quietSampleCount:1}).catch(()=>!1)||await sleep$12(Vn)}return ei}finally{ni(),Zn.dispose()}}var DOM_READY_TIMEOUT_MS,PROBE_INTERVAL_MS,QUIET_MUTATION_RATIO,QUIET_WINDOW_MS,QUIET_SAMPLE_INTERVAL_MS,QUIET_SAMPLE_COUNT,MIN_PROBE_TEXT_CHARS,ACTION_HOOK_WINDOW_MS,ACTION_REQUEST_TRACKING_BUDGET_MS,ACTION_POST_SETTLE_MS,SPA_URL_CHANGE_MIN_DWELL_MS,SPA_URL_CHANGE_POST_SETTLE_MS,ACTION_MAX_WAIT_MS,NETWORK_TRACK_POLL_MS,NAVIGATION_NETWORK_BUDGET_MS,REDIRECT_GUARD_MS,SPARSE_COMPLETE_GRACE_MS,DOM_MONITOR_KEY,REQUEST_SKIP_TYPES,NavigationReadinessTimeoutError,PDF_VIEWER_EXTENSION_PREFIX,NetworkTracker,init_wait=__esmMin((()=>{init_utils$13(),DOM_READY_TIMEOUT_MS=2e3,PROBE_INTERVAL_MS=100,QUIET_MUTATION_RATIO=.01,QUIET_WINDOW_MS=350,QUIET_SAMPLE_INTERVAL_MS=100,QUIET_SAMPLE_COUNT=2,MIN_PROBE_TEXT_CHARS=20,ACTION_HOOK_WINDOW_MS=150,ACTION_REQUEST_TRACKING_BUDGET_MS=1200,ACTION_POST_SETTLE_MS=300,SPA_URL_CHANGE_MIN_DWELL_MS=500,SPA_URL_CHANGE_POST_SETTLE_MS=750,ACTION_MAX_WAIT_MS=8e3,NETWORK_TRACK_POLL_MS=50,NAVIGATION_NETWORK_BUDGET_MS=1500,REDIRECT_GUARD_MS=1e3,SPARSE_COMPLETE_GRACE_MS=1500,DOM_MONITOR_KEY=`__omowrightWaitDomMonitor`,REQUEST_SKIP_TYPES=new Set([`WebSocket`,`EventSource`,`Ping`,`Prefetch`,`CSPViolationReport`]),NavigationReadinessTimeoutError=class extends Error{mode;timeoutMs;constructor(xn,jn){super(`Timed out waiting for ${xn} page after ${jn}ms`),this.name=`NavigationReadinessTimeoutError`,this.mode=xn,this.timeoutMs=jn}},PDF_VIEWER_EXTENSION_PREFIX=`chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai`,NetworkTracker=class{#e=new Map;#t=[];#n;constructor(xn,jn){for(let sessionId of jn)this.#t.push(acquireNetwork(xn,sessionId));this.ready=Promise.all(this.#t.map(off=>off.ready));this.#n=new Set(jn),this.#t.push(xn.on(`Network.requestWillBeSent`,(xn,jn)=>{if(!jn.sessionId||!this.#n.has(jn.sessionId))return;let Vn=``;try{Vn=new URL(xn.request.url).hostname.toLowerCase()}catch{return}this.#e.set(xn.requestId,{hostname:Vn,resourceType:xn.type??`Other`,finished:!1,startedAt:Date.now()})}));let Vn=xn=>{let jn=this.#e.get(xn);jn&&(jn.finished=!0)};this.#t.push(xn.on(`Network.loadingFinished`,(xn,jn)=>{jn.sessionId&&this.#n.has(jn.sessionId)&&Vn(xn.requestId)})),this.#t.push(xn.on(`Network.loadingFailed`,(xn,jn)=>{jn.sessionId&&this.#n.has(jn.sessionId)&&Vn(xn.requestId)}))}captureTrackedRequests(xn){let jn=new Set,Vn=getNaiveRegistrableDomain(xn);for(let[xn,qn]of this.#e)qn.finished||isSameSite(qn.hostname,Vn)&&(REQUEST_SKIP_TYPES.has(qn.resourceType)||jn.add(xn));return jn}isFinished(xn){return this.#e.get(xn)?.finished??!0}dispose(){for(let xn of this.#t)xn();this.#t.length=0}}}));function contentEditableValueMatches(xn,jn){if(xn===jn)return!0;let Vn=xn=>xn.replace(/\u00a0/g,` `).replace(/\r\n/g,`
249
- `).replace(/\n+$/g,``);return Vn(xn)===Vn(jn)}function isStaleObjectError(xn){let jn=xn instanceof Error?xn.message:String(xn);return jn.includes(`Cannot find object with given id`)||jn.includes(`Cannot find context with specified id`)||jn.includes(`Object reference chain is too long`)}function quadArea(xn){if(xn.length!==8)return 0;let jn=[{x:xn[0],y:xn[1]},{x:xn[2],y:xn[3]},{x:xn[4],y:xn[5]},{x:xn[6],y:xn[7]}],Vn=0;for(let xn=0;xn<jn.length;xn+=1){let qn=jn[xn],Jn=jn[(xn+1)%jn.length];Vn+=qn.x*Jn.y-Jn.x*qn.y}return Math.abs(Vn/2)}function quadCenter(xn){return{x:(xn[0]+xn[2]+xn[4]+xn[6])/4,y:(xn[1]+xn[3]+xn[5]+xn[7])/4}}async function resolveActionSessionId(xn,jn){return await xn.resolveSessionId(jn?.frameSessionId)}async function callOnElement(xn,jn,Vn,...qn){try{let Jn=qn.map(xn=>({value:xn})),Yn=await resolveActionSessionId(xn,jn),{result:Zn,exceptionDetails:Qn}=await xn.cdp.send(`Runtime.callFunctionOn`,{objectId:jn.objectId,functionDeclaration:Vn,arguments:Jn,returnByValue:!0,awaitPromise:!0,userGesture:!0},Yn);if(Qn)throw Error(formatRuntimeException(Qn,`Runtime.callFunctionOn failed`));return Zn.value}catch(xn){throw isStaleObjectError(xn)?new RefStaleError(jn.objectId):xn}}async function callOnElementSync(xn,jn,Vn,...qn){try{let Jn=qn.map(xn=>({value:xn})),Yn=await resolveActionSessionId(xn,jn),{result:Zn,exceptionDetails:Qn}=await xn.cdp.send(`Runtime.callFunctionOn`,{objectId:jn.objectId,functionDeclaration:Vn,arguments:Jn,returnByValue:!0,awaitPromise:!1,userGesture:!0},Yn);if(Qn)throw Error(formatRuntimeException(Qn,`Runtime.callFunctionOn failed`));return Zn.value}catch(xn){throw isStaleObjectError(xn)?new RefStaleError(jn.objectId):xn}}async function callOnElementHandle(xn,jn,Vn,...qn){try{let Jn=qn.map(xn=>({value:xn})),Yn=await resolveActionSessionId(xn,jn),{result:Zn,exceptionDetails:Qn}=await xn.cdp.send(`Runtime.callFunctionOn`,{objectId:jn.objectId,functionDeclaration:Vn,arguments:Jn,returnByValue:!1,awaitPromise:!0,userGesture:!0},Yn);if(Qn)throw Error(formatRuntimeException(Qn,`Runtime.callFunctionOn failed`));if(!Zn.objectId)throw Error(`Runtime.callFunctionOn did not return an object handle`);return{objectId:Zn.objectId,frameId:jn.frameId,frameSessionId:jn.frameSessionId,contextId:jn.contextId}}catch(xn){throw isStaleObjectError(xn)?new RefStaleError(jn.objectId):xn}}async function resolveClickTarget(xn,jn){return await callOnElementHandle(xn,jn,`function() {
250
- const root = globalThis.__omowright?.retarget(this, 'none') || this;
251
-
252
- // Some sites expose refs that point at semantic wrappers while the actual hit
253
- // target lives on an inner combobox-like trigger. Resolve that trigger once here so the click path stays generic.
254
- const triggerSelector = '[role="combobox"], [aria-haspopup="listbox"], summary';
255
- if (root.matches?.(triggerSelector)) {
256
- return root;
257
- }
258
-
259
- const nestedTrigger = root.querySelector?.(triggerSelector);
260
- if (nestedTrigger) {
261
- return nestedTrigger;
262
- }
263
-
264
- return globalThis.__omowright?.resolvePointerTarget?.(root) || root;
265
- }`)}async function readClickTargetState(xn,jn){return await callOnElementSync(xn,jn,`function() {
266
- const isComboboxLike = !!this.matches?.('[role="combobox"], [aria-haspopup="listbox"], summary');
267
- const isLink = this.tagName?.toUpperCase() === 'A';
268
- const href = isLink ? (this.getAttribute?.('href') || '') : '';
269
- const role = String(this.getAttribute?.('role') || '').toLowerCase();
270
- const nativeCheckable = this instanceof HTMLInputElement
271
- ? this
272
- : this instanceof HTMLLabelElement
273
- ? this.control
274
- : null;
275
- const nativeType = nativeCheckable instanceof HTMLInputElement ? String(nativeCheckable.type || '').toLowerCase() : '';
276
- const isNativeCheckable = nativeType === 'checkbox' || nativeType === 'radio';
277
- const ariaChecked = this.getAttribute?.('aria-checked');
278
- const checked = isNativeCheckable
279
- ? !!nativeCheckable.checked
280
- : ariaChecked === 'true'
281
- ? true
282
- : ariaChecked === 'false'
283
- ? false
284
- : null;
285
- // Use JS .click() for <a> links with real hrefs — coordinate-based CDP
286
- // dispatch can miss the link when a child element (icon span, image) at
287
- // the click point absorbs the event without triggering default navigation.
288
- const prefersDomActivation =
289
- (isLink && !!href && !href.startsWith('#') && !href.startsWith('javascript:')) ||
290
- // Native checkbox/radio filters frequently hide the real state carrier
291
- // behind labels or framework wrappers. DOM activation plus post-check
292
- // verification is more reliable than CDP coordinates for these controls.
293
- isNativeCheckable;
294
- return {
295
- checked,
296
- isComboboxLike,
297
- isCheckable: isNativeCheckable || checked !== null,
298
- isRadio: nativeType === 'radio' || role === 'radio',
299
- prefersDomActivation,
300
- expanded: isComboboxLike ? this.getAttribute?.('aria-expanded') ?? null : null,
301
- };
302
- }`)}async function domClickTarget(xn,jn){await callOnElementSync(xn,jn,`function() {
303
- if (typeof this.click === 'function') {
304
- this.click();
305
- }
306
- }`)}async function ensurePointerActionable(xn,jn){for(let Vn of ACTIONABILITY_RETRY_DELAYS_MS){Vn>0&&await sleep$12(Vn);let qn=await callOnElement(xn,jn,`function(checks) {
307
- return globalThis.__omowright.waitForReady(this, checks);
308
- }`,[`attached`,`visible`,`stable`,`enabled`]);if(!qn.ok){if((qn.error?.includes(`moving`)||qn.error?.includes(`obscured`))&&Vn!==ACTIONABILITY_RETRY_DELAYS_MS[ACTIONABILITY_RETRY_DELAYS_MS.length-1])continue;throw Error(qn.error||`Element is not ready for click`)}let Jn=await getLocalClickPoint(xn,jn),Yn=await callOnElementSync(xn,jn,`function(clickPoint) {
309
- return globalThis.__omowright.checkHitTarget(this, clickPoint);
310
- }`,Jn);if(Yn.ok)return await resolvePointerDispatchTarget(xn,jn,Jn);if(!(Yn.error?.includes(`obscured`)&&Vn!==ACTIONABILITY_RETRY_DELAYS_MS[ACTIONABILITY_RETRY_DELAYS_MS.length-1]))throw Error(Yn.error||`Element is not receiving pointer events`)}throw Error(`Element did not become clickable in time`)}async function resolvePointerDispatchTarget(xn,jn,Vn){let qn=await findFrameOwnerContentOffset(xn,jn.frameId);return qn?{point:{x:Vn.x+qn.x,y:Vn.y+qn.y},sessionId:await xn.resolveSessionId()}:{point:Vn,sessionId:await resolveActionSessionId(xn,jn)}}async function findFrameOwnerContentOffset(xn,jn){let Vn=await xn.resolveSessionId(),{root:qn}=await xn.cdp.send(`DOM.getDocument`,{depth:-1,pierce:!0},Vn),{nodeIds:Jn}=await xn.cdp.send(`DOM.querySelectorAll`,{nodeId:qn.nodeId,selector:`iframe,frame`},Vn);for(let qn of Jn){let{node:Jn}=await xn.cdp.send(`DOM.describeNode`,{nodeId:qn},Vn);if(Jn.frameId!==jn)continue;let{object:Yn}=await xn.cdp.send(`DOM.resolveNode`,{nodeId:qn},Vn);if(Yn.objectId)try{let{result:jn,exceptionDetails:qn}=await xn.cdp.send(`Runtime.callFunctionOn`,{objectId:Yn.objectId,functionDeclaration:`function() {
311
- const rect = this.getBoundingClientRect();
312
- return { x: rect.left, y: rect.top };
313
- }`,returnByValue:!0,awaitPromise:!0,userGesture:!1},Vn);if(qn)throw Error(formatRuntimeException(qn,`Unable to read frame owner rect`));let Jn=jn.value;if(Number.isFinite(Jn.x)&&Number.isFinite(Jn.y))return{x:Jn.x,y:Jn.y}}finally{await xn.cdp.send(`Runtime.releaseObject`,{objectId:Yn.objectId},Vn).catch(()=>{})}}return null}async function getLocalClickPoint(xn,jn){let Vn=await resolveActionSessionId(xn,jn);try{await xn.cdp.send(`DOM.scrollIntoViewIfNeeded`,{objectId:jn.objectId},Vn)}catch{await callOnElementSync(xn,jn,`function() {
314
- if (this && this.scrollIntoView) {
315
- this.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
316
- }
317
- }`).catch(()=>{})}let qn=await callOnElementSync(xn,jn,`function() {
318
- const rect = this.getBoundingClientRect();
319
- const ok = rect.width > 0 && rect.height > 0;
320
- return {
321
- ok,
322
- x: rect.left + rect.width / 2,
323
- y: rect.top + rect.height / 2,
324
- };
325
- }`);if(qn.ok)return{x:qn.x,y:qn.y};let{quads:Jn}=await xn.cdp.send(`DOM.getContentQuads`,{objectId:jn.objectId},Vn);for(let xn of Jn??[])if(!(quadArea(xn)<.99))return quadCenter(xn);throw Error(`No valid clickable point found for element`)}async function getPointerDispatchTarget(xn,jn){return await resolvePointerDispatchTarget(xn,jn,await getLocalClickPoint(xn,jn))}async function keyDown(xn,jn,Vn,qn){let Jn=resolveKeyDescriptor(Vn,{modifiers:qn.modifiers()}),Yn=qn.has(Jn.key);qn.down(Jn.key);try{await xn.cdp.send(`Input.dispatchKeyEvent`,{type:Jn.text?`keyDown`:`rawKeyDown`,key:Jn.key,code:Jn.code,commands:keyCommands(Jn.code,qn.modifiers()),text:Jn.text,unmodifiedText:Jn.text,windowsVirtualKeyCode:Jn.keyCodeWithoutLocation,location:Jn.location,isKeypad:Jn.location===3,modifiers:qn.toModifiersMask()},jn)}catch(xn){throw Yn||qn.up(Jn.key),xn}}async function keyUp(xn,jn,Vn,qn){let Jn=resolveKeyDescriptor(Vn,{modifiers:qn.modifiers()}),Yn=qn.has(Jn.key);qn.up(Jn.key);try{await xn.cdp.send(`Input.dispatchKeyEvent`,{type:`keyUp`,key:Jn.key,code:Jn.code,windowsVirtualKeyCode:Jn.keyCodeWithoutLocation,location:Jn.location,modifiers:qn.toModifiersMask()},jn)}catch(xn){throw Yn&&qn.down(Jn.key),xn}}async function focusElement(xn,jn,Vn=!1){await callOnElementSync(xn,jn,`function(resetSelection) {
326
- const target = globalThis.__omowright?.retarget(this, 'follow-label') || this;
327
- const wasFocused = target?.ownerDocument?.activeElement === target;
328
- if (target && 'focus' in target && typeof target.focus === 'function') {
329
- target.focus();
330
- }
331
- // Playwright resets a newly-focused input so sequential typing starts at the beginning.
332
- if (resetSelection && !wasFocused && target?.tagName === 'INPUT') {
333
- try {
334
- target.setSelectionRange(0, 0);
335
- } catch {
336
- // Some input types do not support text selection.
337
- }
338
- }
339
- }`,Vn)}async function blurElement(xn,jn){await callOnElementSync(xn,jn,`function() {
340
- const target = globalThis.__omowright?.retarget(this, 'follow-label') || this;
341
- if (target && 'blur' in target && typeof target.blur === 'function') {
342
- target.blur();
343
- }
344
- }`)}async function readComboboxState(xn,jn){let Vn=await readClickTargetState(xn,jn);return{hasComboboxTarget:Vn.isComboboxLike,expanded:Vn.expanded}}async function clickComboboxFallback(xn,jn){await domClickTarget(xn,jn)}async function clickElement(xn,jn,Vn={},qn=defaultModifierState){let Jn=await resolveClickTarget(xn,jn),Yn=Vn.modifiers??[],Zn=[],Qn=await xn.resolveSessionId(),ei=await readComboboxState(xn,Jn).catch(()=>({hasComboboxTarget:!1,expanded:null})),ti=await readClickTargetState(xn,Jn).catch(()=>({expanded:null,checked:null,isComboboxLike:!1,isCheckable:!1,isRadio:!1,prefersDomActivation:!1}));try{let jn=async()=>{let jn=async()=>!ti.isCheckable||ti.checked===null||ti.isRadio&&ti.checked?!0:(await readClickTargetState(xn,Jn).catch(()=>null))?.checked!==ti.checked,ni=async()=>{await domClickTarget(xn,Jn)};if(ti.prefersDomActivation){if(await ni(),!await jn())throw Error(`Checkbox click did not change checked state`);return}let ri;try{let jn=Vn.force?await getPointerDispatchTarget(xn,Jn):await ensurePointerActionable(xn,Jn);ri=jn.point,Qn=jn.sessionId}catch(qn){let Yn=qn instanceof Error?qn.message:String(qn);if(ti.isCheckable&&(await jn()||(await ni(),await jn())))return;if(!Vn.force&&Yn.includes(`obscured`)){await domClickTarget(xn,Jn);return}throw qn}let{x:ii,y:ai}=ri;try{for(let jn of Yn)await keyDown(xn,Qn,jn,qn),Zn.push(jn);Vn.moveBeforeClick!==!1&&await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:ii,y:ai,button:`none`,modifiers:qn.toModifiersMask()},Qn);let jn=Vn.dblClick?2:1;await xn.prepareForPotentialFileChooser?.();for(let Vn=1;Vn<=jn;Vn+=1)await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:ii,y:ai,button:`left`,buttons:1,clickCount:Vn,modifiers:qn.toModifiersMask()},Qn),await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:ii,y:ai,button:`left`,buttons:0,clickCount:Vn,modifiers:qn.toModifiersMask()},Qn)}catch(xn){if(ti.isCheckable&&(await jn()||(await ni(),await jn())))return;throw xn}ei.hasComboboxTarget&&ei.expanded===`false`&&await sleep$12(80);let oi=await readComboboxState(xn,Jn).catch(()=>({hasComboboxTarget:!1,expanded:null}));if(ei.hasComboboxTarget&&ei.expanded===`false`&&oi.expanded===`false`&&await clickComboboxFallback(xn,Jn),!await jn()&&(await ni(),!await jn()))throw Error(`Checkbox click did not change checked state`)};if(Vn.waitAfter===!1)await jn();else try{await performActionAndWait(xn,jn,{frameSessionId:Jn.frameSessionId})}catch(xn){if(xn instanceof NavigationReadinessTimeoutError&&xn.mode===`interactive`){replPrint(`[warning] Waited ${xn.timeoutMs}ms for the page to become ready after the click.`);return}throw xn}}finally{for(let jn=Zn.length-1;jn>=0;--jn)await keyUp(xn,Qn,Zn[jn],qn).catch(()=>{})}}async function fillElement(xn,jn,Vn){let qn=await resolveActionSessionId(xn,jn),Jn=await callOnElementSync(xn,jn,`function(nextValue, setValueTypes, typeIntoTypes) {
345
- const target = globalThis.__omowright?.retarget(this, 'follow-label');
346
- if (!target) {
347
- return { mode: 'needsinput', kind: 'input', expectedValue: '', error: 'Unable to retarget element' };
348
- }
349
-
350
- const editable = globalThis.__omowright?.checkEditable(target);
351
- if (!editable?.ok) {
352
- return {
353
- mode: 'needsinput',
354
- kind: 'input',
355
- expectedValue: '',
356
- error: editable?.error || 'Element is not editable',
357
- };
358
- }
359
-
360
- const tagName = target.tagName.toUpperCase();
361
- if (tagName === 'INPUT') {
362
- const inputType = String(target.type || '').toLowerCase();
363
- if (!setValueTypes.includes(inputType) && !typeIntoTypes.includes(inputType)) {
364
- return {
365
- mode: 'needsinput',
366
- kind: 'input',
367
- expectedValue: '',
368
- error: 'Input of type "' + inputType + '" cannot be filled',
369
- };
370
- }
371
-
372
- let expectedValue = String(nextValue ?? '');
373
- if (inputType === 'number') {
374
- expectedValue = expectedValue.trim();
375
- if (Number.isNaN(Number(expectedValue))) {
376
- return {
377
- mode: 'needsinput',
378
- kind: 'input',
379
- expectedValue,
380
- error: 'Cannot type text into input[type=number]',
381
- };
382
- }
383
- }
384
- if (inputType === 'color') expectedValue = expectedValue.toLowerCase();
385
-
386
- if (setValueTypes.includes(inputType)) {
387
- expectedValue = expectedValue.trim();
388
- target.focus();
389
- target.value = expectedValue;
390
- if (target.value !== expectedValue) {
391
- return { mode: 'setvalue', kind: 'input', expectedValue, error: 'Malformed value' };
392
- }
393
- target.dispatchEvent(new Event('input', { bubbles: true, composed: true }));
394
- target.dispatchEvent(new Event('change', { bubbles: true }));
395
- return { mode: 'setvalue', kind: 'input', expectedValue };
396
- }
397
-
398
- target.select();
399
- target.focus();
400
- return { mode: 'needsinput', kind: 'input', expectedValue };
401
- }
402
-
403
- if (tagName === 'TEXTAREA') {
404
- target.selectionStart = 0;
405
- target.selectionEnd = target.value.length;
406
- target.focus();
407
- return { mode: 'needsinput', kind: 'textarea', expectedValue: String(nextValue ?? '') };
408
- }
409
-
410
- if (target.isContentEditable) {
411
- target.focus();
412
- const selection = target.ownerDocument.getSelection();
413
- if (selection) {
414
- const range = target.ownerDocument.createRange();
415
- range.selectNodeContents(target);
416
- selection.removeAllRanges();
417
- selection.addRange(range);
418
- }
419
- return { mode: 'needsinput', kind: 'contenteditable', expectedValue: String(nextValue ?? '') };
420
- }
421
-
422
- return {
423
- mode: 'needsinput',
424
- kind: 'input',
425
- expectedValue: '',
426
- error: 'Element is not an <input>, <textarea> or [contenteditable] element',
427
- };
428
- }`,Vn,kSetValueInputTypes,kTypeIntoInputTypes);if(Jn.error)throw Error(Jn.error);if(Jn.mode===`setvalue`)return;Jn.expectedValue?await xn.cdp.send(`Input.insertText`,{text:Jn.expectedValue},qn):(await keyDown(xn,qn,`Delete`,defaultModifierState),await keyUp(xn,qn,`Delete`,defaultModifierState));let Yn=async()=>await callOnElementSync(xn,jn,`function(kind) {
429
- const target = globalThis.__omowright?.retarget(this, 'follow-label') || this;
430
- if (kind === 'contenteditable') return target.innerText || '';
431
- return typeof target.value === 'string' ? target.value : '';
432
- }`,Jn.kind),Zn=await Yn();if(Zn!==Jn.expectedValue&&!(Jn.kind===`contenteditable`&&contentEditableValueMatches(Zn,Jn.expectedValue))){if(Jn.kind===`contenteditable`)throw Error(`Fill did not set the expected contenteditable value`);if(!await callOnElementSync(xn,jn,`function(nextValue) {
433
- const target = globalThis.__omowright?.retarget(this, 'follow-label') || this;
434
- const tagName = target.tagName ? target.tagName.toUpperCase() : '';
435
- if (tagName !== 'INPUT' && tagName !== 'TEXTAREA') return false;
436
-
437
- const previousValue = target.value;
438
- let prototype = Object.getPrototypeOf(target);
439
- let descriptor;
440
- while (prototype && !descriptor) {
441
- descriptor = Object.getOwnPropertyDescriptor(prototype, 'value');
442
- prototype = Object.getPrototypeOf(prototype);
443
- }
444
- if (!descriptor || typeof descriptor.set !== 'function') return false;
445
-
446
- descriptor.set.call(target, String(nextValue ?? ''));
447
- const tracker = target._valueTracker;
448
- if (tracker && typeof tracker.setValue === 'function') tracker.setValue(String(previousValue));
449
- target.dispatchEvent(new Event('input', { bubbles: true, composed: true }));
450
- return true;
451
- }`,Jn.expectedValue))throw Error(`Fill fallback could not update the target`);if(await Yn()!==Jn.expectedValue)throw Error(`Fill did not set the expected value`)}}async function selectOptionElement(xn,jn,Vn){return await performActionAndWait(xn,async()=>await callOnElementSync(xn,jn,`function(requested) {
452
- const target = globalThis.__omowright?.retarget(this, 'follow-label') || this;
453
- if (!target || !target.tagName || target.tagName.toUpperCase() !== 'SELECT') {
454
- throw new Error('Element is not a <select>');
455
- }
456
-
457
- const select = target;
458
- const wanted = Array.isArray(requested) ? requested : [requested];
459
- const matched = new Set();
460
-
461
- for (let index = 0; index < select.options.length; index += 1) {
462
- const option = select.options[index];
463
- const matches = wanted.some((token) => {
464
- if (token && typeof token === 'object') {
465
- if (typeof token.value === 'string' && token.value === option.value) return true;
466
- if (typeof token.label === 'string' && token.label === option.label) return true;
467
- if (typeof token.index === 'number' && token.index === index) return true;
468
- return false;
469
- }
470
- const candidate = String(token);
471
- return candidate === option.value || candidate === option.label || candidate === String(index);
472
- });
473
- if (matches) {
474
- matched.add(option.value);
475
- }
476
- option.selected = matches;
477
- }
478
-
479
- if (!select.multiple && matched.size > 1) {
480
- const first = Array.from(select.options).find((option) => matched.has(option.value));
481
- for (const option of select.options) {
482
- option.selected = option === first;
483
- }
484
- }
485
-
486
- select.dispatchEvent(new Event('input', { bubbles: true }));
487
- select.dispatchEvent(new Event('change', { bubbles: true }));
488
- return Array.from(select.selectedOptions).map((option) => option.value);
489
- }`,Vn),{frameSessionId:jn.frameSessionId})}async function checkElement(xn,jn,Vn=!0){let qn=await callOnElementSync(xn,jn,`function() {
490
- const target = globalThis.__omowright?.retarget(this, 'follow-label') || this;
491
- const role = String(target.getAttribute?.('role') || '').toLowerCase();
492
- const isNativeInput = target.tagName?.toUpperCase() === 'INPUT';
493
- const type = String(target.type || '').toLowerCase();
494
- const prefersLabelClick = isNativeInput &&
495
- (type === 'checkbox' || type === 'radio') &&
496
- Array.from(target.labels ?? []).some((label) => {
497
- const style = label.ownerDocument?.defaultView?.getComputedStyle?.(label);
498
- if (style && (style.display === 'none' || style.visibility === 'hidden')) {
499
- return false;
500
- }
501
- const rect = label.getBoundingClientRect();
502
- return rect.width > 0 && rect.height > 0;
503
- });
504
-
505
- const nativeChecked = isNativeInput && (type === 'checkbox' || type === 'radio')
506
- ? !!target.checked
507
- : null;
508
- const ariaChecked = target.getAttribute?.('aria-checked');
509
-
510
- if (nativeChecked !== null) {
511
- return { checked: nativeChecked, isRadio: type === 'radio', prefersLabelClick };
512
- }
513
- if (ariaChecked === 'true') {
514
- return { checked: true, isRadio: role === 'radio', prefersLabelClick };
515
- }
516
- if (ariaChecked === 'false') {
517
- return { checked: false, isRadio: role === 'radio', prefersLabelClick };
518
- }
519
- return { checked: null, isRadio: role === 'radio', prefersLabelClick };
520
- }`);if(qn.checked!==Vn){if(qn.isRadio&&Vn===!1)throw Error(`Radio buttons cannot be unchecked directly`);try{await clickElement(xn,jn)}catch(Vn){if(!qn.prefersLabelClick||!await callOnElementSync(xn,jn,`function() {
521
- const target = globalThis.__omowright?.retarget(this, 'follow-label') || this;
522
- if (!(target instanceof HTMLInputElement) || (target.type !== 'checkbox' && target.type !== 'radio')) {
523
- return false;
524
- }
525
-
526
- const label = Array.from(target.labels ?? []).find((candidate) => {
527
- const style = candidate.ownerDocument?.defaultView?.getComputedStyle?.(candidate);
528
- if (style && (style.display === 'none' || style.visibility === 'hidden')) {
529
- return false;
530
- }
531
- const rect = candidate.getBoundingClientRect();
532
- return rect.width > 0 && rect.height > 0;
533
- });
534
-
535
- if (!label) {
536
- return false;
537
- }
538
-
539
- label.click();
540
- return true;
541
- }`))throw Vn}try{if(await callOnElementSync(xn,jn,`function() {
542
- const target = globalThis.__omowright?.retarget(this, 'follow-label') || this;
543
- if (target.tagName?.toUpperCase() === 'INPUT') {
544
- const type = String(target.type || '').toLowerCase();
545
- if (type === 'checkbox' || type === 'radio') {
546
- return !!target.checked;
547
- }
548
- }
549
- const ariaChecked = target.getAttribute?.('aria-checked');
550
- if (ariaChecked === 'true') return true;
551
- if (ariaChecked === 'false') return false;
552
- return null;
553
- }`)!==Vn)throw Error(`Element checked state did not change to ${Vn}`)}catch(xn){if(xn instanceof RefStaleError)return;throw xn}}}function requireResolvedFrameSession(xn,jn){if(!jn.frameSessionId||!xn.frameManager.hasSession(jn.frameSessionId))throw Error(`Frame is stale or detached: CDP session ${jn.frameSessionId??`missing`} is unavailable`);return jn.frameSessionId}async function pressElement(xn,jn,Vn,qn){let Jn=requireResolvedFrameSession(xn,jn);await focusElement(xn,jn,!0),await qn.press(Vn,{},Jn)}async function focusResolvedElement(xn,jn){await focusElement(xn,jn)}async function blurResolvedElement(xn,jn){await blurElement(xn,jn)}async function pressSequentiallyElement(xn,jn,Vn,qn,Jn){let Yn=requireResolvedFrameSession(xn,jn);await focusElement(xn,jn,!0),await Jn.type(Vn,{delay:qn},Yn)}async function hoverElement(xn,jn){let Vn=await callOnElement(xn,jn,`function() {
554
- return globalThis.__omowright.waitForReady(this, ['visible']);
555
- }`);if(!Vn.ok)throw Error(Vn.error||`Element is not visible`);let qn=await getPointerDispatchTarget(xn,jn),{x:Jn,y:Yn}=qn.point;await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:Jn,y:Yn,button:`none`,modifiers:defaultModifierState.toModifiersMask()},qn.sessionId)}async function tapElement(xn,jn){await clickElement(xn,jn)}async function scrollIntoViewElement(xn,jn){let Vn=await resolveActionSessionId(xn,jn);try{await xn.cdp.send(`DOM.scrollIntoViewIfNeeded`,{objectId:jn.objectId},Vn)}catch{await callOnElementSync(xn,jn,`function() {
556
- if (this && this.scrollIntoView) {
557
- this.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
558
- }
559
- }`)}}async function evaluateOnElement(xn,jn,Vn,qn){let Jn=`function(...__args) { return (${Vn}).call(this, this, ...__args); }`;return qn===void 0?await callOnElementSync(xn,jn,Jn):await callOnElementSync(xn,jn,Jn,qn)}async function boundingBoxElement(xn,jn){try{let Vn=await callOnElementSync(xn,jn,`function() {
560
- const rect = this.getBoundingClientRect();
561
- if (rect.width <= 0 || rect.height <= 0) {
562
- return null;
563
- }
564
- return {
565
- x: rect.left,
566
- y: rect.top,
567
- width: rect.width,
568
- height: rect.height,
569
- };
570
- }`);if(Vn)return Vn;let qn=await resolveActionSessionId(xn,jn),{model:Jn}=await xn.cdp.send(`DOM.getBoxModel`,{objectId:jn.objectId},qn),Yn=Jn.border;if(!Yn||Yn.length!==8)return null;let Zn=[Yn[0],Yn[2],Yn[4],Yn[6]],Qn=[Yn[1],Yn[3],Yn[5],Yn[7]],ei=Math.min(...Zn),ti=Math.max(...Zn),ni=Math.min(...Qn),ri=Math.max(...Qn);return{x:ei,y:ni,width:ti-ei,height:ri-ni}}catch{return null}}async function isCheckedElement(xn,jn){return await evaluateOnElement(xn,jn,`function() {
571
- return !!this.checked;
572
- }`)}async function inputValueElement(xn,jn){return await evaluateOnElement(xn,jn,`function() {
573
- return this.value || '';
574
- }`)}async function innerHTMLElement(xn,jn){return await evaluateOnElement(xn,jn,`function() {
575
- return this.innerHTML;
576
- }`)}async function innerTextElement(xn,jn){return await evaluateOnElement(xn,jn,`function() {
577
- if (typeof this.innerText === 'string') {
578
- return this.innerText;
579
- }
580
- return this.textContent || '';
581
- }`)}async function textContentElement(xn,jn){return await evaluateOnElement(xn,jn,`function() {
582
- return this.textContent ?? null;
583
- }`)}async function getAttributeElement(xn,jn,Vn){return await evaluateOnElement(xn,jn,`function(_, attributeName) {
584
- return this.getAttribute(attributeName);
585
- }`,Vn)}async function isDisabledElement(xn,jn){return await evaluateOnElement(xn,jn,`function() {
586
- const formControls = ['BUTTON', 'INPUT', 'SELECT', 'TEXTAREA', 'OPTION', 'OPTGROUP'];
587
- if (formControls.includes(this.tagName)) {
588
- if (this.disabled) return true;
589
- const fieldset = this.closest?.('fieldset:disabled');
590
- if (fieldset) {
591
- const legend = fieldset.querySelector?.(':scope > legend');
592
- if (!legend || !legend.contains(this)) return true;
593
- }
594
- }
595
-
596
- let current = this;
597
- while (current) {
598
- if (current.getAttribute?.('aria-disabled') === 'true') return true;
599
- current = current.parentElement;
600
- }
601
- return false;
602
- }`)}async function isEnabledElement(xn,jn){return!await isDisabledElement(xn,jn)}async function isVisibleElement(xn,jn){return await evaluateOnElement(xn,jn,`function() {
603
- if (!this.isConnected) return false;
604
- const rect = this.getBoundingClientRect();
605
- return (
606
- this.checkVisibility?.({ checkOpacity: false, checkVisibilityCSS: true }) !== false &&
607
- rect.width > 0 &&
608
- rect.height > 0
609
- );
610
- }`)}async function isHiddenElement(xn,jn){return!await isVisibleElement(xn,jn)}async function isEditableElement(xn,jn){return await evaluateOnElement(xn,jn,`function() {
611
- const target = globalThis.__omowright?.retarget(this, 'follow-label') || this;
612
- return globalThis.__omowright?.checkEditable(target).ok === true;
613
- }`)}async function dispatchEventElement(xn,jn,Vn,qn){await callOnElementSync(xn,jn,`function(eventType, init) {
614
- const name = String(eventType || '').toLowerCase();
615
- const constructors = {
616
- click: 'MouseEvent',
617
- dblclick: 'MouseEvent',
618
- mousedown: 'MouseEvent',
619
- mouseup: 'MouseEvent',
620
- mousemove: 'MouseEvent',
621
- mouseenter: 'MouseEvent',
622
- mouseleave: 'MouseEvent',
623
- mouseover: 'MouseEvent',
624
- mouseout: 'MouseEvent',
625
- contextmenu: 'MouseEvent',
626
- auxclick: 'MouseEvent',
627
- keydown: 'KeyboardEvent',
628
- keyup: 'KeyboardEvent',
629
- keypress: 'KeyboardEvent',
630
- focus: 'FocusEvent',
631
- blur: 'FocusEvent',
632
- focusin: 'FocusEvent',
633
- focusout: 'FocusEvent',
634
- input: 'InputEvent',
635
- beforeinput: 'InputEvent',
636
- pointerdown: 'PointerEvent',
637
- pointerup: 'PointerEvent',
638
- pointermove: 'PointerEvent',
639
- pointerenter: 'PointerEvent',
640
- pointerleave: 'PointerEvent',
641
- pointerover: 'PointerEvent',
642
- pointerout: 'PointerEvent',
643
- pointercancel: 'PointerEvent',
644
- wheel: 'WheelEvent',
645
- drag: 'DragEvent',
646
- dragstart: 'DragEvent',
647
- dragend: 'DragEvent',
648
- dragenter: 'DragEvent',
649
- dragexit: 'DragEvent',
650
- dragleave: 'DragEvent',
651
- dragover: 'DragEvent',
652
- drop: 'DragEvent',
653
- touchstart: 'TouchEvent',
654
- touchmove: 'TouchEvent',
655
- touchend: 'TouchEvent',
656
- touchcancel: 'TouchEvent',
657
- };
658
- const constructorName = constructors[name] || 'Event';
659
- const Constructor = globalThis[constructorName] || Event;
660
- const event = new Constructor(eventType, init || undefined);
661
- this.dispatchEvent(event);
662
- }`,Vn,qn)}async function setInputFilesElement(xn,jn,Vn){let qn=await callOnElementHandle(xn,jn,`function() {
663
- const target = globalThis.__omowright?.retarget(this, 'follow-label') || this;
664
- if (target?.tagName?.toUpperCase() === 'INPUT' && String(target.type || '').toLowerCase() === 'file') {
665
- return target;
666
- }
667
- const label = this.closest('label');
668
- const nearby = label?.querySelector('input[type=file]')
669
- || this.parentElement?.querySelector('input[type=file]')
670
- || this.closest('[role=dialog], [role=region], section, form, main')?.querySelector('input[type=file]');
671
- if (nearby) return nearby;
672
- throw new Error('Element is not an <input type="file">');
673
- }`);try{if(Vn.length===0||typeof Vn[0]==`string`){let jn=await resolveActionSessionId(xn,qn);await xn.cdp.send(`DOM.setFileInputFiles`,{objectId:qn.objectId,files:Vn},jn);return}await callOnElementSync(xn,qn,`function(payloads) {
674
- const input = this;
675
- const transfer = new DataTransfer();
676
- for (const payload of payloads) {
677
- const binary = atob(payload.base64);
678
- const bytes = new Uint8Array(binary.length);
679
- for (let index = 0; index < binary.length; index += 1) {
680
- bytes[index] = binary.charCodeAt(index);
681
- }
682
- transfer.items.add(new File([bytes], payload.name, { type: payload.mimeType || '' }));
683
- }
684
- input.files = transfer.files;
685
- input.dispatchEvent(new Event('input', { bubbles: true }));
686
- input.dispatchEvent(new Event('change', { bubbles: true }));
687
- }`,Vn)}finally{let jn=await resolveActionSessionId(xn,qn).catch(()=>null);jn&&await xn.cdp.send(`Runtime.releaseObject`,{objectId:qn.objectId},jn).catch(()=>{})}}async function dragToElement(xn,jn,Vn,qn={}){let Jn=qn.force?await getPointerDispatchTarget(xn,jn):await ensurePointerActionable(xn,jn),Yn=qn.force?await getPointerDispatchTarget(xn,Vn):await ensurePointerActionable(xn,Vn),Zn=Jn.sessionId===Yn.sessionId?Jn.sessionId:await xn.resolveSessionId(),Qn=Jn.point,ei=Yn.point,ti=qn.sourcePosition?{x:Qn.x+qn.sourcePosition.x,y:Qn.y+qn.sourcePosition.y}:Qn,ni=qn.targetPosition?{x:ei.x+qn.targetPosition.x,y:ei.y+qn.targetPosition.y}:ei;if(qn.trial)return;let ri=Math.max(qn.steps??1,1);await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:ti.x,y:ti.y,button:`none`,buttons:0,modifiers:defaultModifierState.toModifiersMask()},Zn),await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:ti.x,y:ti.y,button:`left`,buttons:1,clickCount:1,modifiers:defaultModifierState.toModifiersMask()},Zn);for(let jn=1;jn<=ri;jn+=1){let Vn=jn/ri;await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:ti.x+(ni.x-ti.x)*Vn,y:ti.y+(ni.y-ti.y)*Vn,button:`left`,buttons:1,modifiers:defaultModifierState.toModifiersMask()},Zn)}await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:ni.x,y:ni.y,button:`left`,buttons:0,clickCount:1,modifiers:defaultModifierState.toModifiersMask()},Zn),jn.frameSessionId===Vn.frameSessionId&&(await callOnElementSync(xn,jn,`function() {
688
- const dataTransfer = new DataTransfer();
689
- globalThis.__omowrightDragDataTransfer = dataTransfer;
690
- this.dispatchEvent(new DragEvent('dragstart', { bubbles: true, cancelable: true, dataTransfer }));
691
- this.dispatchEvent(new DragEvent('drag', { bubbles: true, cancelable: true, dataTransfer }));
692
- }`).catch(()=>{}),await callOnElementSync(xn,Vn,`function() {
693
- const dataTransfer = globalThis.__omowrightDragDataTransfer;
694
- if (!dataTransfer) {
695
- return;
696
- }
697
- this.dispatchEvent(new DragEvent('dragenter', { bubbles: true, cancelable: true, dataTransfer }));
698
- this.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, dataTransfer }));
699
- this.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer }));
700
- }`).catch(()=>{}),await callOnElementSync(xn,jn,`function() {
701
- const dataTransfer = globalThis.__omowrightDragDataTransfer;
702
- if (!dataTransfer) {
703
- return;
704
- }
705
- this.dispatchEvent(new DragEvent('dragend', { bubbles: true, cancelable: true, dataTransfer }));
706
- delete globalThis.__omowrightDragDataTransfer;
707
- }`).catch(()=>{}))}var defaultModifierState,kSetValueInputTypes,kTypeIntoInputTypes,ACTIONABILITY_RETRY_DELAYS_MS,init_actions=__esmMin((()=>{init_context(),init_utils$13(),init_errors$3(),init_types$4(),init_keyboard(),init_wait(),defaultModifierState=new ModifierState,kSetValueInputTypes=[`color`,`date`,`datetime-local`,`month`,`range`,`time`,`week`],kTypeIntoInputTypes=[``,`email`,`number`,`password`,`search`,`tel`,`text`,`url`],ACTIONABILITY_RETRY_DELAYS_MS=[0,100,200]})),frame_exports=__exportAll({OmOFrame:()=>OmOFrame,FrameLocator:()=>FrameLocator}),OmOFrame,FrameLocator,init_frame=__esmMin((()=>{init_locator(),OmOFrame=class xn{#e;frameId;constructor(xn,jn){this.#e=xn,this.frameId=jn}async resolveFrameId(){return this.frameId}label(){let xn=this.#t();return`frame ${xn.name||xn.url||xn.frameId}`}locator(xn,jn={}){return new Locator(this.#e,xn,this).filter(jn)}getByRole(xn,jn={}){return this.locator(Locator.createRoleSelector(xn,jn))}getByLabel(xn,jn={}){if(xn instanceof RegExp)return this.locator(`internal:label=/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return this.locator(jn.exact?`internal:label:exact:${Vn}`:`internal:label:${Vn}`)}getByText(xn,jn={}){if(xn instanceof RegExp)return this.locator(`text:/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return this.locator(jn.exact?`text:exact:${Vn}`:`text:${Vn}`)}frameLocator(xn){return new FrameLocator(this.#e,this,xn)}async evaluate(xn,jn){return await this.#e.evaluateInFrame(this.frameId,xn,jn)}async $$eval(xn,jn,Vn){return await this.locator(xn).evaluateAll(jn,Vn)}url(){return this.#t().url}name(){return this.#t().name}parentFrame(){let jn=this.#t().parentFrameId;return jn?new xn(this.#e,jn):null}#t(){let xn=this.#e.frameManager.getFrame(this.frameId);if(!xn)throw Error(`Frame is no longer available: ${this.frameId}`);return xn}},FrameLocator=class xn{#e;#t;#n;constructor(xn,jn,Vn){this.#e=xn,this.#t=jn,this.#n=Vn}async resolveFrameId(){let xn=await this.#t.resolveFrameId(),jn=await new OmOFrame(this.#e,xn).locator(this.#n).elementHandle().then(xn=>xn.contentFrame());if(!jn)throw Error(`Frame locator "${this.#n}" did not resolve to an iframe`);return jn.frameId}label(){return`frameLocator(${this.#n})`}locator(xn,jn={}){return new Locator(this.#e,xn,this).filter(jn)}getByRole(xn,jn={}){return this.locator(Locator.createRoleSelector(xn,jn))}getByLabel(xn,jn={}){if(xn instanceof RegExp)return this.locator(`internal:label=/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return this.locator(jn.exact?`internal:label:exact:${Vn}`:`internal:label:${Vn}`)}getByText(xn,jn={}){if(xn instanceof RegExp)return this.locator(`text:/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return this.locator(jn.exact?`text:exact:${Vn}`:`text:${Vn}`)}frameLocator(jn){return new xn(this.#e,this,jn)}owner(){return new Locator(this.#e,this.#n,this.#t)}first(){return this.nth(0)}nth(jn){return new xn(this.#e,this.#t,`${this.#n}:nth(${jn})`)}last(){return new xn(this.#e,this.#t,`${this.#n}:nth(last)`)}}}));function parseBackendNodeSelector(xn){if(!xn.startsWith(BACKEND_NODE_SELECTOR_PREFIX))return null;let jn=xn.slice(25),Vn=jn.indexOf(`:`);if(Vn<=0)throw Error(`Invalid backend node selector: ${xn}`);let qn=jn.slice(0,Vn),Jn=Number(jn.slice(Vn+1));if(!Number.isInteger(Jn)||Jn<=0)throw Error(`Invalid backend node selector: ${xn}`);return{frameId:qn,backendNodeId:Jn}}function createBackendNodeLocatorSelector(xn,jn){return`${BACKEND_NODE_SELECTOR_PREFIX}${xn}:${jn}`}function isLocatorResolutionMiss(xn){return xn instanceof RefStaleError?!0:xn instanceof Error?xn.message.startsWith(`Selector "`)||xn.message.startsWith(`Role selector not found: `):!1}var REF_PATTERN,REF_SELECTOR_ALIAS_PATTERN,BACKEND_NODE_SELECTOR_PREFIX,DEFAULT_SCREENSHOT_MARGIN,DEFAULT_LOCATOR_WAIT_TIMEOUT_MS,LOCATOR_WAIT_POLL_INTERVALS,LOCATOR_WAIT_STATES,NTH_SELECTOR_PATTERN,isRef,isRoleSelector,isTextSelector,Locator,ElementHandle,init_locator=__esmMin((()=>{init_utils$13(),init_errors$3(),init_types$4(),init_actions(),REF_PATTERN=/^(f\d+)?e\d+$/,REF_SELECTOR_ALIAS_PATTERN=/^\[ref=((?:f\d+)?e\d+)\]$/,BACKEND_NODE_SELECTOR_PREFIX=`internal:backend-node-id:`,DEFAULT_SCREENSHOT_MARGIN=8,DEFAULT_LOCATOR_WAIT_TIMEOUT_MS=3e3,LOCATOR_WAIT_POLL_INTERVALS=[0,20,50,100,100,500],LOCATOR_WAIT_STATES=[`attached`,`detached`,`visible`,`hidden`],NTH_SELECTOR_PATTERN=/:nth\((\d+|last)\)$/,isRef=xn=>/^(f\d+)?e\d+$/.test(xn),isRoleSelector=xn=>xn.startsWith(`role:`),isTextSelector=xn=>xn.startsWith(`text:`),Locator=class xn{#e;#t;#n;#composition;constructor(xn,jn,Vn,composition){if(typeof jn!=`string`||jn.trim().length===0)throw Error(`Locator selector must be a non-empty string. Take a fresh snapshot and verify the ref exists.`);this.#e=xn,this.#n=Vn;let qn=jn.trim();this.#t=qn.replace(REF_SELECTOR_ALIAS_PATTERN,`$1`);this.#composition=composition;for(const name of Object.getOwnPropertyNames(Object.getPrototypeOf(xn))){if(name.startsWith(`getBy`)&&typeof xn[name]===`function`)this[name]=(...args)=>{const child=xn[name](...args);return this.locator(child.#t)}}}static createRoleSelector(xn,jn={}){let Vn=`role:${xn}`,qn=(xn,jn)=>{Vn+=`[${xn}=${jn}]`};if(jn.checked!==void 0&&qn(`checked`,String(jn.checked)),jn.disabled!==void 0&&qn(`disabled`,String(jn.disabled)),jn.expanded!==void 0&&qn(`expanded`,String(jn.expanded)),jn.includeHidden!==void 0&&qn(`include-hidden`,String(jn.includeHidden)),jn.level!==void 0&&qn(`level`,String(jn.level)),jn.pressed!==void 0&&qn(`pressed`,String(jn.pressed)),jn.selected!==void 0&&qn(`selected`,String(jn.selected)),jn.name!==void 0){let xn=jn.name;if(Object.prototype.toString.call(xn)===`[object RegExp]`){let jn=xn;qn(`name-regex`,encodeURIComponent(jn.source)),jn.flags&&qn(`name-regex-flags`,encodeURIComponent(jn.flags))}else qn(jn.exact?`name`:`name*`,encodeURIComponent(String(xn)))}return Vn}async#r(){if(this.#composition){const nodes=await this.#collect();if(!nodes.length)throw Error(`Selector "${this.#t}" not found`);return nodes[0]}let xn=parseBackendNodeSelector(this.#t);return xn?await this.#o(xn):isRef(this.#t)?await this.#a(this.#t):isRoleSelector(this.#t)?await this.#l(this.#t):await this.#c(this.#t)}async#i(xn){try{let jn=await this.#r();if(xn===`attached`)return!0;if(xn===`detached`)return!1;let Vn=await isVisibleElement(this.#e,jn);return xn===`visible`?Vn:!Vn}catch(jn){if(!isLocatorResolutionMiss(jn))throw jn;return xn===`detached`||xn===`hidden`}}async click(xn){let jn=await this.#r();await clickElement(this.#e,jn,xn,this.#e.modifierState)}async fill(xn){let jn=await this.#r();await fillElement(this.#e,jn,xn)}async selectOption(xn){let jn=await this.#r();return await selectOptionElement(this.#e,jn,xn)}async check(xn){let jn=await this.#r();await checkElement(this.#e,jn,xn?.checked)}async scrollIntoViewIfNeeded(){let xn=await this.#r();await scrollIntoViewElement(this.#e,xn)}async press(xn){let jn=await this.#r();await pressElement(this.#e,jn,xn,this.#e.keyboard)}async pressSequentially(xn,jn={}){let Vn=await this.#r();await pressSequentiallyElement(this.#e,Vn,xn,jn.delay,this.#e.keyboard)}async hover(){let xn=await this.#r();await hoverElement(this.#e,xn)}async dblclick(xn){let jn=await this.#r();await clickElement(this.#e,jn,{...xn,dblClick:!0},this.#e.modifierState)}async focus(){let xn=await this.#r();await focusResolvedElement(this.#e,xn)}async blur(){let xn=await this.#r();await blurResolvedElement(this.#e,xn)}async tap(){let xn=await this.#r();await tapElement(this.#e,xn)}async clear(){await this.fill(``)}async type(xn,jn={}){await this.pressSequentially(xn,jn)}async uncheck(){let xn=await this.#r();await checkElement(this.#e,xn,!1)}async setChecked(xn){if(xn){await this.check();return}await this.uncheck()}async setInputFiles(xn){let jn=await this.#r();if(xn===null){await setInputFilesElement(this.#e,jn,[]);return}if(typeof xn==`string`){let Vn=await this.#e.browser.ensurePath(xn,`read`,`locator.setInputFiles`);await setInputFilesElement(this.#e,jn,[Vn]);return}if(xn.length===0){await setInputFilesElement(this.#e,jn,[]);return}if(typeof xn[0]==`string`){let Vn=await Promise.all(xn.map(xn=>this.#e.browser.ensurePath(xn,`read`,`locator.setInputFiles`)));await setInputFilesElement(this.#e,jn,Vn);return}await setInputFilesElement(this.#e,jn,xn.map(xn=>({name:xn.name,mimeType:xn.mimeType,base64:Buffer.from(xn.buffer).toString(`base64`)})))}async dragTo(xn,jn={}){let Vn=await this.#r(),qn=await xn.#r();await dragToElement(this.#e,Vn,qn,jn)}async evaluate(xn,jn){let Vn=await this.#r(),qn=typeof xn==`function`?xn.toString():xn;return await evaluateOnElement(this.#e,Vn,qn,jn)}async evaluateAll(xn,jn){if(!this.#composition&&isRoleSelector(this.#t))throw Error(`locator.evaluateAll() does not support role selectors yet; use a CSS selector.`);let Vn=this.#composition?[]:isRef(this.#t)||parseBackendNodeSelector(this.#t)?[this]:await this.all(),qn=this.#composition?await this.#collect():await Promise.all(Vn.map(xn=>xn.#r())),Jn=qn[0]??await this.#s();if(qn.some(xn=>xn.contextId!==Jn.contextId))throw Error(`locator.evaluateAll() cannot pass elements from multiple frames to one page function.`);let Yn=typeof xn==`function`?xn.toString():xn,Zn=[{value:jn},...qn.map(xn=>({objectId:xn.objectId}))],{result:Qn,exceptionDetails:ei}=await this.#e.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`async function(arg, ...elements) {
708
- var __name = (target) => target;
709
- const pageFunction = (${Yn});
710
- if (typeof pageFunction !== 'function') {
711
- throw new Error('$$eval pageFunction must evaluate to a function');
712
- }
713
- return await pageFunction(elements, arg);
714
- }`,arguments:Zn,executionContextId:Jn.contextId,returnByValue:!0,awaitPromise:!0,userGesture:!1},await this.#e.resolveSessionId(Jn.frameSessionId));if(ei)throw Error(formatRuntimeException(ei,`$$eval failed`));return Qn.value}async boundingBox(){let xn=await this.#r();return await boundingBoxElement(this.#e,xn)}async screenshot(xn={}){let jn=xn.margin??DEFAULT_SCREENSHOT_MARGIN;if(!Number.isFinite(jn)||jn<0)throw Error(`locator.screenshot: margin must be a non-negative number`);let Vn=await this.#r(),qn=await evaluateOnElement(this.#e,Vn,`function(_, margin) {
715
- const rect = this.getBoundingClientRect();
716
- if (rect.width <= 0 || rect.height <= 0) {
717
- return null;
718
- }
719
-
720
- const left = Math.max(0, rect.left - margin);
721
- const top = Math.max(0, rect.top - margin);
722
- const right = Math.min(window.innerWidth, rect.right + margin);
723
- const bottom = Math.min(window.innerHeight, rect.bottom + margin);
724
- const width = right - left;
725
- const height = bottom - top;
726
- if (width <= 0 || height <= 0) {
727
- return null;
728
- }
729
-
730
- return {
731
- x: left,
732
- y: top,
733
- width,
734
- height,
735
- };
736
- }`,jn);if(!qn)throw Error(`locator.screenshot: element is not visible in the viewport`);let{path:Jn,quality:Yn,timeout:Zn,type:Qn=`webp`}=xn;return await this.#e.screenshot({path:Jn,quality:Yn,timeout:Zn,type:Qn,clip:qn})}async isChecked(){let xn=await this.#r();return await isCheckedElement(this.#e,xn)}async inputValue(){let xn=await this.#r();return await inputValueElement(this.#e,xn)}async innerHTML(){let xn=await this.#r();return await innerHTMLElement(this.#e,xn)}async innerText(){let xn=await this.#r();return await innerTextElement(this.#e,xn)}async textContent(){let xn=await this.#r();return await textContentElement(this.#e,xn)}async elementHandle(){return new ElementHandle(this.#e,await this.#r())}async count(){if(this.#composition)return(await this.#collect()).length;if(isRef(this.#t))try{return await this.#a(this.#t),1}catch(xn){if(xn instanceof RefStaleError)return 0;throw xn}if(isRoleSelector(this.#t)){let xn=NTH_SELECTOR_PATTERN.test(this.#t),{nth:jn,...Vn}=this.#p(this.#t),qn=await this.#d(),Jn=0;for(let{frameId:xn}of qn){let jn=this.#e.frameManager.getFrame(xn);jn?.isolatedContextId&&(Jn+=await this.#m(await this.#e.resolveSessionId(jn.sessionId),jn.isolatedContextId,Vn))}return xn?+(Jn>0&&(jn===`last`||jn<Jn)):Jn}let xn=NTH_SELECTOR_PATTERN.test(this.#t),jn=this.#f(this.#t),Vn=await this.#u();return await this.#e.evaluateInFrame(Vn,`function(query) {
737
- const normalizeText = (value) => String(value ?? '').replace(/\\s+/g, ' ').trim();
738
- const parseTextMatcher = (raw) => {
739
- if (!raw) return null;
740
- if (raw.startsWith('/') && raw.lastIndexOf('/') > 0) {
741
- const lastSlash = raw.lastIndexOf('/');
742
- return new RegExp(raw.slice(1, lastSlash), raw.slice(lastSlash + 1));
743
- }
744
- const parseLiteral = (value) => {
745
- try {
746
- return JSON.parse(value);
747
- } catch {
748
- return value;
749
- }
750
- };
751
- if (raw.startsWith('exact:')) {
752
- return { exact: parseLiteral(raw.slice(6)) };
753
- }
754
- return { contains: parseLiteral(raw) };
755
- };
756
- const matchesText = (node, matcher) => {
757
- const text = normalizeText(node.textContent);
758
- if (matcher instanceof RegExp) return matcher.test(text);
759
- if ('exact' in matcher) return text === matcher.exact;
760
- return text.includes(matcher.contains);
761
- };
762
- // getByPlaceholder/AltText/Title/TestId match like Playwright: a RegExp tests the raw attribute value,
763
- // "..."s is the whole case-sensitive value and "..."i a case-insensitive substring.
764
- const parseAttributeMatcher = (raw) => {
765
- if (raw.startsWith('/') && raw.lastIndexOf('/') > 0) {
766
- const lastSlash = raw.lastIndexOf('/');
767
- return new RegExp(raw.slice(1, lastSlash), raw.slice(lastSlash + 1));
768
- }
769
- return { value: JSON.parse(raw.slice(0, -1)), exact: raw.endsWith('s') };
770
- };
771
- const matchesAttribute = (node, attribute) => {
772
- const value = node.getAttribute(attribute.name);
773
- if (value === null) return false;
774
- const matcher = attribute.matcher;
775
- if (matcher instanceof RegExp) {
776
- matcher.lastIndex = 0;
777
- return matcher.test(value);
778
- }
779
- return matcher.exact ? value === matcher.value : value.toLowerCase().includes(matcher.value.toLowerCase());
780
- };
781
- const splitSteps = (value) => value.split(/\\s*>>\\s*/).map((step) => step.trim()).filter(Boolean);
782
- const parseStep = (rawStep) => {
783
- const nthMatch = rawStep.match(/^(.*):nth\\((\\d+|last)\\)$/s);
784
- const rawBase = nthMatch ? (nthMatch[1] || '').trim() || '*' : rawStep;
785
- const nth = nthMatch ? nthMatch[2] === 'last' ? 'last' : Number.parseInt(nthMatch[2], 10) : null;
786
- const hasTextMatch = rawBase.match(/^(.*):has-text\\((.*)\\)$/s);
787
- const base = hasTextMatch ? (hasTextMatch[1] || '').trim() || '*' : rawBase;
788
- const hasText = hasTextMatch ? parseTextMatcher((hasTextMatch[2] || '').trim()) : null;
789
- if (base.startsWith('text:')) {
790
- return {
791
- kind: 'text',
792
- matcher: parseTextMatcher(base.slice(5)),
793
- hasText,
794
- nth,
795
- };
796
- }
797
- if (base.startsWith('internal:label:')) {
798
- return {
799
- kind: 'label',
800
- matcher: parseTextMatcher(base.slice(15)),
801
- hasText,
802
- nth,
803
- };
804
- }
805
- const attributeMatch = base.match(/^internal:attr=\\[([^=\\]]+)=(.*)\\]$/s);
806
- if (attributeMatch) {
807
- return {
808
- kind: 'attribute',
809
- selector: '[' + CSS.escape(attributeMatch[1]) + ']',
810
- attribute: { name: attributeMatch[1], matcher: parseAttributeMatcher(attributeMatch[2]) },
811
- hasText,
812
- nth,
813
- };
814
- }
815
- return {
816
- kind: 'css',
817
- selector: base,
818
- hasText,
819
- nth,
820
- };
821
- };
822
- const queryOpenShadowAll = (${queryOpenShadowAll.toString()});
823
- const descendants = (root) => queryOpenShadowAll(root, '*');
824
- const textMatches = (root, matcher) => {
825
- const matches = descendants(root).filter((node) => matcher && matchesText(node, matcher));
826
- return matches.filter((node) => !Array.from(node.children).some((child) => matchesText(child, matcher)));
827
- };
828
- // Some sites duplicate the same visible label onto hidden or zero-sized inputs.
829
- // Prefer the actionable associated control so getByLabel() doesn't latch onto
830
- // an inert duplicate and fail later in the actionability pipeline.
831
- const labelMatches = (root, matcher) => {
832
- const labels = queryOpenShadowAll(root, 'label')
833
- .filter((label) => matcher && matchesText(label, matcher));
834
- const controlSelector = 'input:not([type="hidden"]), textarea, select';
835
- const seen = new Set();
836
- const controls = [];
837
- for (const label of labels) {
838
- const explicitControl = label.control || (label.htmlFor ? label.getRootNode().getElementById(label.htmlFor) : null);
839
- // Virginia DMV's Bootstrap form uses a label with no htmlFor, followed
840
- // immediately by its input in the same row.
841
- const siblingControl = label.nextElementSibling?.matches?.(controlSelector) ? label.nextElementSibling : null;
842
- const control = explicitControl || siblingControl;
843
- if (!control || seen.has(control)) continue;
844
- seen.add(control);
845
- controls.push(control);
846
- }
847
- controls.sort((a, b) => {
848
- const rank = (node) => {
849
- let score = 0;
850
- if (node.isConnected) score += 100;
851
- const style = node.ownerDocument?.defaultView?.getComputedStyle?.(node);
852
- if (style && style.display !== 'none' && style.visibility !== 'hidden') {
853
- score += 10;
854
- }
855
- const rect = typeof node.getBoundingClientRect === 'function' ? node.getBoundingClientRect() : null;
856
- if (rect && rect.width > 0 && rect.height > 0) {
857
- score += 1;
858
- }
859
- return score;
860
- };
861
- return rank(b) - rank(a);
862
- });
863
- return controls;
864
- };
865
- const queryAll = (value) => {
866
- const steps = splitSteps(value);
867
- let roots = [document];
868
- for (const rawStep of steps) {
869
- const step = parseStep(rawStep);
870
- const next = [];
871
- const seen = new Set();
872
- for (const root of roots) {
873
- let matches = step.kind === 'attribute'
874
- ? queryOpenShadowAll(root, step.selector).filter((node) => matchesAttribute(node, step.attribute))
875
- : step.kind === 'text'
876
- ? textMatches(root, step.matcher)
877
- : step.kind === 'label'
878
- ? labelMatches(root, step.matcher)
879
- : Array.from((root instanceof Document ? root : root).querySelectorAll(step.selector));
880
- if (step.hasText) {
881
- matches = matches.filter((node) => matchesText(node, step.hasText));
882
- }
883
- if (step.nth !== null) {
884
- const index = step.nth === 'last' ? matches.length - 1 : step.nth;
885
- matches = matches[index] ? [matches[index]] : [];
886
- }
887
- for (const node of matches) {
888
- if (seen.has(node)) continue;
889
- seen.add(node);
890
- next.push(node);
891
- }
892
- }
893
- roots = next;
894
- }
895
- return roots;
896
- };
897
- const nodes = queryAll(query.selector);
898
- const index = query.nth === 'last' ? nodes.length - 1 : query.nth;
899
- return query.hasNth ? (nodes[index] ? 1 : 0) : nodes.length;
900
- }`,{selector:jn.selector,nth:jn.nth,hasNth:xn})}async getAttribute(xn){let jn=await this.#r();return await getAttributeElement(this.#e,jn,xn)}async isDisabled(){let xn=await this.#r();return await isDisabledElement(this.#e,xn)}async isEditable(){let xn=await this.#r();return await isEditableElement(this.#e,xn)}async isEnabled(){let xn=await this.#r();return await isEnabledElement(this.#e,xn)}async isHidden(){let xn=await this.#r();return await isHiddenElement(this.#e,xn)}async isVisible(){let xn=await this.#r();return await isVisibleElement(this.#e,xn)}async dispatchEvent(xn,jn){let Vn=await this.#r();await dispatchEventElement(this.#e,Vn,xn,jn)}async waitFor(xn={}){let jn=xn.state??`visible`;if(!LOCATOR_WAIT_STATES.includes(jn))throw Error(`locator.waitFor: invalid state "${jn}"`);let Vn=xn.timeout??DEFAULT_LOCATOR_WAIT_TIMEOUT_MS;if(!Number.isFinite(Vn)||Vn<0)throw Error(`locator.waitFor: timeout must be a non-negative number`);let qn=Date.now(),Jn=0;for(;;){if(await this.#i(jn))return;if(Date.now()-qn>=Vn)throw Error(`locator.waitFor: timed out after ${Vn}ms waiting for ${this} to be ${jn}`);await sleep$12(LOCATOR_WAIT_POLL_INTERVALS[Math.min(Jn++,LOCATOR_WAIT_POLL_INTERVALS.length-1)])}}first(){return this.nth(0)}
901
- nth(index){return this.#composition?new xn(this.#e,this.#t,this.#n,{source:this,index}):new xn(this.#e,`${this.#t}:nth(${index})`,this.#n)}
902
- last(){return this.#composition?new xn(this.#e,this.#t,this.#n,{source:this,index:-1}):new xn(this.#e,isRef(this.#t)||parseBackendNodeSelector(this.#t)?this.#t:`${this.#t}:nth(last)`,this.#n)}
903
- locator(selector,options={}){const child=new xn(this.#e,selector,this.#n);return new xn(this.#e,selector,this.#n,{source:this,child}).filter(options)}
904
- filter(options={}){
905
- for(const key of Object.keys(options))if(!['has','hasNot','hasText','hasNotText','visible'].includes(key))throw Error(`Unknown locator.filter option: ${key}`);
906
- for(const key of ['has','hasNot'])if(options[key]!==undefined&&(!(options[key] instanceof xn)||options[key].#e!==this.#e||options[key].#n!==this.#n))throw Error(`locator.filter ${key} must be a locator in the same frame`);
907
- return Object.keys(options).length?new xn(this.#e,this.#t,this.#n,{source:this,filters:{...options}}):this;
908
- }
909
- async #collect(scope){
910
- let nodes;
911
- const plan=this.#composition;
912
- if(!plan&&scope!==undefined&&NTH_SELECTOR_PATTERN.test(this.#t)){
913
- const {selector,nth}=this.#f(this.#t);
914
- const matches=await new xn(this.#e,selector,this.#n).#collect(scope);
915
- const node=matches.at(nth==='last'?-1:nth);
916
- return node?[node]:[];
917
- }
918
- if(plan){
919
- nodes=await plan.source.#collect(scope);
920
- if(plan.child)return plan.child.#collect(nodes);
921
- if(plan.index!==undefined){const node=nodes.at(plan.index);return node?[node]:[]}
922
- const options=plan.filters;
923
- const filtered=[];
924
- for(const node of nodes){
925
- const textOptions={};
926
- for(const key of ['hasText','hasNotText'])if(options[key]!==undefined){const value=options[key];textOptions[key]=Object.prototype.toString.call(value)==='[object RegExp]'?{source:value.source,flags:value.flags}:String(value)}
927
- const matches=await evaluateOnElement(this.#e,node,`function(_, options){
928
- const text=this.textContent||'';
929
- const matchesText=(matcher)=>typeof matcher==='string'
930
- ?text.replace(/\\s+/g,' ').trim().toLowerCase().includes(matcher.toLowerCase())
931
- :new RegExp(matcher.source,matcher.flags).test(text);
932
- if(options.hasText!==undefined&&!matchesText(options.hasText))return false;
933
- if(options.hasNotText!==undefined&&matchesText(options.hasNotText))return false;
934
- return true;
935
- }`,textOptions);
936
- if(!matches)continue;
937
- if(options.visible!==undefined&&await isVisibleElement(this.#e,node)!==options.visible)continue;
938
- if(options.has&&(await options.has.#collect([node])).length===0)continue;
939
- if(options.hasNot&&(await options.hasNot.#collect([node])).length!==0)continue;
940
- filtered.push(node);
941
- }
942
- return filtered;
943
- }
944
- if(isRef(this.#t)||parseBackendNodeSelector(this.#t)){
945
- try{nodes=[await this.#r()]}catch(error){if(!isLocatorResolutionMiss(error))throw error;nodes=[]}
946
- }else{
947
- const count=await this.count();nodes=[];
948
- for(let index=0;index<count;index++){
949
- const locator=NTH_SELECTOR_PATTERN.test(this.#t)?this:new xn(this.#e,`${this.#t}:nth(${index})`,this.#n);
950
- nodes.push(await locator.#r());
951
- }
952
- }
953
- if(scope===undefined)return nodes;
954
- const scoped=[];
955
- for(const node of nodes){
956
- for(const root of scope){
957
- if(root.contextId!==node.contextId||root.frameSessionId!==node.frameSessionId)continue;
958
- const {result,exceptionDetails}=await this.#e.cdp.send('Runtime.callFunctionOn',{
959
- objectId:root.objectId,functionDeclaration:`function(node){
960
- if(node===this)return false;
961
- for(let parent=node.parentNode||node.host;parent;parent=parent.parentNode||parent.host)if(parent===this)return true;
962
- return false;
963
- }`,arguments:[{objectId:node.objectId}],returnByValue:true,
964
- },await this.#e.resolveSessionId(root.frameSessionId));
965
- if(exceptionDetails)throw Error(formatRuntimeException(exceptionDetails,'Locator scope evaluation failed'));
966
- if(result.value){scoped.push(node);break}
967
- }
968
- }
969
- return scoped;
970
- }
971
- async all(){if(this.#composition)return Array.from({length:await this.count()},(_,index)=>this.nth(index));if(isRef(this.#t)||isRoleSelector(this.#t)||isTextSelector(this.#t)||parseBackendNodeSelector(this.#t))return[this];let xn=await this.#u(),jn=await this.#e.evaluateInFrame(xn,`function(selector) {
972
- const normalizeText = (value) => String(value ?? '').replace(/\\s+/g, ' ').trim();
973
- const parseTextMatcher = (raw) => {
974
- if (!raw) return null;
975
- if (raw.startsWith('/') && raw.lastIndexOf('/') > 0) {
976
- const lastSlash = raw.lastIndexOf('/');
977
- return new RegExp(raw.slice(1, lastSlash), raw.slice(lastSlash + 1));
978
- }
979
- const parseLiteral = (value) => {
980
- try {
981
- return JSON.parse(value);
982
- } catch {
983
- return value;
984
- }
985
- };
986
- if (raw.startsWith('exact:')) {
987
- return { exact: parseLiteral(raw.slice(6)) };
988
- }
989
- return { contains: parseLiteral(raw) };
990
- };
991
- const matchesText = (node, matcher) => {
992
- const text = normalizeText(node.textContent);
993
- if (matcher instanceof RegExp) return matcher.test(text);
994
- if ('exact' in matcher) return text === matcher.exact;
995
- return text.includes(matcher.contains);
996
- };
997
- // getByPlaceholder/AltText/Title/TestId match like Playwright: a RegExp tests the raw attribute value,
998
- // "..."s is the whole case-sensitive value and "..."i a case-insensitive substring.
999
- const parseAttributeMatcher = (raw) => {
1000
- if (raw.startsWith('/') && raw.lastIndexOf('/') > 0) {
1001
- const lastSlash = raw.lastIndexOf('/');
1002
- return new RegExp(raw.slice(1, lastSlash), raw.slice(lastSlash + 1));
1003
- }
1004
- return { value: JSON.parse(raw.slice(0, -1)), exact: raw.endsWith('s') };
1005
- };
1006
- const matchesAttribute = (node, attribute) => {
1007
- const value = node.getAttribute(attribute.name);
1008
- if (value === null) return false;
1009
- const matcher = attribute.matcher;
1010
- if (matcher instanceof RegExp) {
1011
- matcher.lastIndex = 0;
1012
- return matcher.test(value);
1013
- }
1014
- return matcher.exact ? value === matcher.value : value.toLowerCase().includes(matcher.value.toLowerCase());
1015
- };
1016
- const splitSteps = (value) => value.split(/\\s*>>\\s*/).map((step) => step.trim()).filter(Boolean);
1017
- const parseStep = (rawStep) => {
1018
- const nthMatch = rawStep.match(/^(.*):nth\\((\\d+|last)\\)$/s);
1019
- const rawBase = nthMatch ? (nthMatch[1] || '').trim() || '*' : rawStep;
1020
- const nth = nthMatch ? nthMatch[2] === 'last' ? 'last' : Number.parseInt(nthMatch[2], 10) : null;
1021
- const hasTextMatch = rawBase.match(/^(.*):has-text\\((.*)\\)$/s);
1022
- const base = hasTextMatch ? (hasTextMatch[1] || '').trim() || '*' : rawBase;
1023
- const hasText = hasTextMatch ? parseTextMatcher((hasTextMatch[2] || '').trim()) : null;
1024
- if (base.startsWith('text:')) {
1025
- return {
1026
- kind: 'text',
1027
- matcher: parseTextMatcher(base.slice(5)),
1028
- hasText,
1029
- nth,
1030
- };
1031
- }
1032
- if (base.startsWith('internal:label:')) {
1033
- return {
1034
- kind: 'label',
1035
- matcher: parseTextMatcher(base.slice(15)),
1036
- hasText,
1037
- nth,
1038
- };
1039
- }
1040
- const attributeMatch = base.match(/^internal:attr=\\[([^=\\]]+)=(.*)\\]$/s);
1041
- if (attributeMatch) {
1042
- return {
1043
- kind: 'attribute',
1044
- selector: '[' + CSS.escape(attributeMatch[1]) + ']',
1045
- attribute: { name: attributeMatch[1], matcher: parseAttributeMatcher(attributeMatch[2]) },
1046
- hasText,
1047
- nth,
1048
- };
1049
- }
1050
- return {
1051
- kind: 'css',
1052
- selector: base,
1053
- hasText,
1054
- nth,
1055
- };
1056
- };
1057
- const queryOpenShadowAll = (${queryOpenShadowAll.toString()});
1058
- const descendants = (root) => queryOpenShadowAll(root, '*');
1059
- const textMatches = (root, matcher) => {
1060
- const matches = descendants(root).filter((node) => matcher && matchesText(node, matcher));
1061
- return matches.filter((node) => !Array.from(node.children).some((child) => matchesText(child, matcher)));
1062
- };
1063
- // Keep label-based locators resilient when one label name points at both
1064
- // hidden template inputs and the visible live control.
1065
- const labelMatches = (root, matcher) => {
1066
- const labels = queryOpenShadowAll(root, 'label')
1067
- .filter((label) => matcher && matchesText(label, matcher));
1068
- const controlSelector = 'input:not([type="hidden"]), textarea, select';
1069
- const seen = new Set();
1070
- const controls = [];
1071
- for (const label of labels) {
1072
- const explicitControl = label.control || (label.htmlFor ? label.getRootNode().getElementById(label.htmlFor) : null);
1073
- // Virginia DMV's Bootstrap form uses a label with no htmlFor, followed
1074
- // immediately by its input in the same row.
1075
- const siblingControl = label.nextElementSibling?.matches?.(controlSelector) ? label.nextElementSibling : null;
1076
- const control = explicitControl || siblingControl;
1077
- if (!control || seen.has(control)) continue;
1078
- seen.add(control);
1079
- controls.push(control);
1080
- }
1081
- controls.sort((a, b) => {
1082
- const rank = (node) => {
1083
- let score = 0;
1084
- if (node.isConnected) score += 100;
1085
- const style = node.ownerDocument?.defaultView?.getComputedStyle?.(node);
1086
- if (style && style.display !== 'none' && style.visibility !== 'hidden') {
1087
- score += 10;
1088
- }
1089
- const rect = typeof node.getBoundingClientRect === 'function' ? node.getBoundingClientRect() : null;
1090
- if (rect && rect.width > 0 && rect.height > 0) {
1091
- score += 1;
1092
- }
1093
- return score;
1094
- };
1095
- return rank(b) - rank(a);
1096
- });
1097
- return controls;
1098
- };
1099
- const queryAll = (value) => {
1100
- const steps = splitSteps(value);
1101
- let roots = [document];
1102
- for (const rawStep of steps) {
1103
- const step = parseStep(rawStep);
1104
- const next = [];
1105
- const seen = new Set();
1106
- for (const root of roots) {
1107
- let matches = step.kind === 'attribute'
1108
- ? queryOpenShadowAll(root, step.selector).filter((node) => matchesAttribute(node, step.attribute))
1109
- : step.kind === 'text'
1110
- ? textMatches(root, step.matcher)
1111
- : step.kind === 'label'
1112
- ? labelMatches(root, step.matcher)
1113
- : Array.from((root instanceof Document ? root : root).querySelectorAll(step.selector));
1114
- if (step.hasText) {
1115
- matches = matches.filter((node) => matchesText(node, step.hasText));
1116
- }
1117
- if (step.nth !== null) {
1118
- const index = step.nth === 'last' ? matches.length - 1 : step.nth;
1119
- matches = matches[index] ? [matches[index]] : [];
1120
- }
1121
- for (const node of matches) {
1122
- if (seen.has(node)) continue;
1123
- seen.add(node);
1124
- next.push(node);
1125
- }
1126
- }
1127
- roots = next;
1128
- }
1129
- return roots;
1130
- };
1131
- return queryAll(selector).length;
1132
- }`,this.#t);return Array.from({length:jn},(xn,jn)=>this.nth(jn))}toString(){return`Locator@${this.#t}`}async#a(xn){if(this.#n)throw Error(`Snapshot refs already include frame identity; use page.locator(ref) instead of frame.locator(ref).`);let jn=xn.match(REF_PATTERN);if(!jn)throw Error(`Invalid ref format: ${xn}`);let Vn=jn[1]??``,qn=this.#e.frameManager.resolveFrameIdForSnapshotPrefix(Vn);if(!qn)throw new RefStaleError(xn);let Jn=Vn?3:1;for(let jn=0;jn<Jn;jn++){jn>0&&await new Promise(xn=>setTimeout(xn,50*jn));let Vn=this.#e.frameManager.getFrame(qn);if(!Vn||!Vn.isolatedContextId&&(await this.#e.frameManager.ensureInjected(qn),!Vn.isolatedContextId))throw new RefStaleError(xn);try{let{result:jn}=await this.#e.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(refId) { return globalThis.__omowright?.deref(refId) ?? null; }`,arguments:[{value:xn}],executionContextId:Vn.isolatedContextId,returnByValue:!1,awaitPromise:!1,userGesture:!1},await this.#e.resolveSessionId(Vn.sessionId));if(jn.objectId)return{objectId:jn.objectId,frameId:qn,frameSessionId:Vn.sessionId,contextId:Vn.isolatedContextId}}catch{this.#e.frameManager.invalidateContext(qn)}}throw new RefStaleError(xn)}async#o(xn){let jn=this.#e.frameManager.getFrame(xn.frameId),Vn=await this.#e.frameManager.ensureInjected(xn.frameId);if(!jn||!Vn)throw Error(`File chooser element is no longer available`);let qn=await this.#e.resolveSessionId(jn.sessionId),{object:Jn}=await this.#e.cdp.send(`DOM.resolveNode`,{backendNodeId:xn.backendNodeId,executionContextId:Vn},qn);if(!Jn.objectId)throw Error(`File chooser element is no longer available`);return{objectId:Jn.objectId,frameId:xn.frameId,frameSessionId:jn.sessionId,contextId:Vn}}async#s(){let xn=await this.#u(),jn=this.#e.frameManager.getFrame(xn),Vn=await this.#e.frameManager.ensureInjected(xn);if(!jn||!Vn)throw Error(`${this.#n?.label()??`Main frame`} isolated world is not ready`);return{contextId:Vn,frameSessionId:jn.sessionId}}async#c(xn){let jn=await this.#u(),Vn=this.#e.frameManager.getFrame(jn),qn=await this.#e.frameManager.ensureInjected(jn);if(!Vn||!qn)throw Error(`${this.#n?.label()??`Main frame`} isolated world is not ready`);let Jn=this.#f(xn),{result:Yn}=await this.#e.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(query) {
1133
- const normalizeText = (value) => String(value ?? '').replace(/\\s+/g, ' ').trim();
1134
- const parseTextMatcher = (raw) => {
1135
- if (!raw) return null;
1136
- if (raw.startsWith('/') && raw.lastIndexOf('/') > 0) {
1137
- const lastSlash = raw.lastIndexOf('/');
1138
- return new RegExp(raw.slice(1, lastSlash), raw.slice(lastSlash + 1));
1139
- }
1140
- const parseLiteral = (value) => {
1141
- try {
1142
- return JSON.parse(value);
1143
- } catch {
1144
- return value;
1145
- }
1146
- };
1147
- if (raw.startsWith('exact:')) {
1148
- return { exact: parseLiteral(raw.slice(6)) };
1149
- }
1150
- return { contains: parseLiteral(raw) };
1151
- };
1152
- const matchesText = (node, matcher, useInnerText = false) => {
1153
- const text = normalizeText(useInnerText ? node.innerText : node.textContent);
1154
- if (matcher instanceof RegExp) return matcher.test(text);
1155
- if ('exact' in matcher) return text === matcher.exact;
1156
- return text.includes(matcher.contains);
1157
- };
1158
- // getByPlaceholder/AltText/Title/TestId match like Playwright: a RegExp tests the raw attribute value,
1159
- // "..."s is the whole case-sensitive value and "..."i a case-insensitive substring.
1160
- const parseAttributeMatcher = (raw) => {
1161
- if (raw.startsWith('/') && raw.lastIndexOf('/') > 0) {
1162
- const lastSlash = raw.lastIndexOf('/');
1163
- return new RegExp(raw.slice(1, lastSlash), raw.slice(lastSlash + 1));
1164
- }
1165
- return { value: JSON.parse(raw.slice(0, -1)), exact: raw.endsWith('s') };
1166
- };
1167
- const matchesAttribute = (node, attribute) => {
1168
- const value = node.getAttribute(attribute.name);
1169
- if (value === null) return false;
1170
- const matcher = attribute.matcher;
1171
- if (matcher instanceof RegExp) {
1172
- matcher.lastIndex = 0;
1173
- return matcher.test(value);
1174
- }
1175
- return matcher.exact ? value === matcher.value : value.toLowerCase().includes(matcher.value.toLowerCase());
1176
- };
1177
- const splitSteps = (selector) => selector.split(/\\s*>>\\s*/).map((step) => step.trim()).filter(Boolean);
1178
- const parseStep = (rawStep) => {
1179
- const nthMatch = rawStep.match(/^(.*):nth\\((\\d+|last)\\)$/s);
1180
- const rawBase = nthMatch ? (nthMatch[1] || '').trim() || '*' : rawStep;
1181
- const nth = nthMatch ? nthMatch[2] === 'last' ? 'last' : Number.parseInt(nthMatch[2], 10) : null;
1182
- const hasTextMatch = rawBase.match(/^(.*):has-text\\((.*)\\)$/s);
1183
- const base = hasTextMatch ? (hasTextMatch[1] || '').trim() || '*' : rawBase;
1184
- const hasText = hasTextMatch ? parseTextMatcher((hasTextMatch[2] || '').trim()) : null;
1185
- if (base.startsWith('text:')) {
1186
- return {
1187
- kind: 'text',
1188
- matcher: parseTextMatcher(base.slice(5)),
1189
- hasText,
1190
- nth,
1191
- };
1192
- }
1193
- if (base.startsWith('internal:label:')) {
1194
- return {
1195
- kind: 'label',
1196
- matcher: parseTextMatcher(base.slice(15)),
1197
- hasText,
1198
- nth,
1199
- };
1200
- }
1201
- const attributeMatch = base.match(/^internal:attr=\\[([^=\\]]+)=(.*)\\]$/s);
1202
- if (attributeMatch) {
1203
- return {
1204
- kind: 'attribute',
1205
- selector: '[' + CSS.escape(attributeMatch[1]) + ']',
1206
- attribute: { name: attributeMatch[1], matcher: parseAttributeMatcher(attributeMatch[2]) },
1207
- hasText,
1208
- nth,
1209
- };
1210
- }
1211
- return {
1212
- kind: 'css',
1213
- selector: base,
1214
- hasText,
1215
- nth,
1216
- };
1217
- };
1218
- const queryOpenShadowAll = (${queryOpenShadowAll.toString()});
1219
- const descendants = (root) => queryOpenShadowAll(root, '*');
1220
- const textMatches = (root, matcher) => {
1221
- const matches = descendants(root).filter((node) => matcher && matchesText(node, matcher));
1222
- // Text selectors should resolve to the innermost visible text element,
1223
- // not broad ancestors like <body>; click actionability depends on that.
1224
- return matches.filter((node) => !Array.from(node.children).some((child) => matchesText(child, matcher)));
1225
- };
1226
- // Keep label selectors aligned with what a human can actually click when
1227
- // pages duplicate label text across hidden template controls.
1228
- const labelMatches = (root, matcher) => {
1229
- const labels = queryOpenShadowAll(root, 'label')
1230
- .filter((label) => matcher && matchesText(label, matcher));
1231
- const controlSelector = 'input:not([type="hidden"]), textarea, select';
1232
- const seen = new Set();
1233
- const controls = [];
1234
- for (const label of labels) {
1235
- const explicitControl = label.control || (label.htmlFor ? label.getRootNode().getElementById(label.htmlFor) : null);
1236
- // Virginia DMV's Bootstrap form uses a label with no htmlFor, followed
1237
- // immediately by its input in the same row.
1238
- const siblingControl = label.nextElementSibling?.matches?.(controlSelector) ? label.nextElementSibling : null;
1239
- const control = explicitControl || siblingControl;
1240
- if (!control || seen.has(control)) continue;
1241
- seen.add(control);
1242
- controls.push(control);
1243
- }
1244
- controls.sort((a, b) => {
1245
- const rank = (node) => {
1246
- let score = 0;
1247
- if (node.isConnected) score += 100;
1248
- const style = node.ownerDocument?.defaultView?.getComputedStyle?.(node);
1249
- if (style && style.display !== 'none' && style.visibility !== 'hidden') {
1250
- score += 10;
1251
- }
1252
- const rect = typeof node.getBoundingClientRect === 'function' ? node.getBoundingClientRect() : null;
1253
- if (rect && rect.width > 0 && rect.height > 0) {
1254
- score += 1;
1255
- }
1256
- return score;
1257
- };
1258
- return rank(b) - rank(a);
1259
- });
1260
- return controls;
1261
- };
1262
- const queryAll = (selector) => {
1263
- const steps = splitSteps(selector);
1264
- let roots = [document];
1265
- for (const rawStep of steps) {
1266
- const step = parseStep(rawStep);
1267
- const next = [];
1268
- const seen = new Set();
1269
- for (const root of roots) {
1270
- let matches = step.kind === 'attribute'
1271
- ? queryOpenShadowAll(root, step.selector).filter((node) => matchesAttribute(node, step.attribute))
1272
- : step.kind === 'text'
1273
- ? textMatches(root, step.matcher)
1274
- : step.kind === 'label'
1275
- ? labelMatches(root, step.matcher)
1276
- : Array.from((root instanceof Document ? root : root).querySelectorAll(step.selector));
1277
- if (step.hasText) {
1278
- matches = matches.filter((node) => matchesText(node, step.hasText));
1279
- }
1280
- if (step.nth !== null) {
1281
- const index = step.nth === 'last' ? matches.length - 1 : step.nth;
1282
- matches = matches[index] ? [matches[index]] : [];
1283
- }
1284
- for (const node of matches) {
1285
- if (seen.has(node)) continue;
1286
- seen.add(node);
1287
- next.push(node);
1288
- }
1289
- }
1290
- roots = next;
1291
- }
1292
- return roots;
1293
- };
1294
- const nodes = queryAll(query.selector);
1295
- const index = query.nth === 'last' ? nodes.length - 1 : query.nth;
1296
- return nodes[index] ?? null;
1297
- }`,arguments:[{value:Jn}],executionContextId:qn,returnByValue:!1,awaitPromise:!1,userGesture:!1},await this.#e.resolveSessionId(Vn.sessionId));if(!Yn.objectId)throw Error(`Selector "${xn}" not found`);return{objectId:Yn.objectId,frameId:jn,frameSessionId:Vn.sessionId,contextId:qn}}async#l(xn){let jn=this.#p(xn),Vn=await this.#d(),{nth:qn,...Jn}=jn,Yn;if(qn===`last`){Yn=0;for(let{frameId:xn}of Vn){let jn=this.#e.frameManager.getFrame(xn);jn?.isolatedContextId&&(Yn+=await this.#m(await this.#e.resolveSessionId(jn.sessionId),jn.isolatedContextId,Jn))}--Yn}else Yn=qn;if(Yn<0)throw Error(`Role selector not found: ${xn}`);for(let{frameId:xn}of Vn){let Vn=this.#e.frameManager.getFrame(xn);if(!Vn?.isolatedContextId)continue;let qn=await this.#e.resolveSessionId(Vn.sessionId),Zn=await this.#m(qn,Vn.isolatedContextId,Jn);if(Zn<=0)continue;if(Yn>=Zn){Yn-=Zn;continue}let{result:Qn}=await this.#e.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(query) {
1298
- const normalizeText = (value) => String(value || '').replace(/\\s+/g, ' ').trim();
1299
- const getRole = (node) => {
1300
- const explicit = node.getAttribute?.('role');
1301
- if (explicit) {
1302
- return explicit.split(/\\s+/)[0] || 'generic';
1303
- }
1304
-
1305
- const tag = String(node.tagName || '').toLowerCase();
1306
- if (tag === 'input') {
1307
- const type = String(node.getAttribute?.('type') || '').toLowerCase();
1308
- if (type === 'checkbox') return 'checkbox';
1309
- if (type === 'radio') return 'radio';
1310
- if (type === 'range') return 'slider';
1311
- if (type === 'button' || type === 'submit' || type === 'reset') return 'button';
1312
- return 'textbox';
1313
- }
1314
- if (tag === 'button') return 'button';
1315
- if (tag === 'a' && node.hasAttribute?.('href')) return 'link';
1316
- if (tag === 'select') return node.multiple || node.size > 1 ? 'listbox' : 'combobox';
1317
- if (tag === 'textarea') return 'textbox';
1318
- if (tag === 'img') return 'img';
1319
- if (tag === 'option') return 'option';
1320
- if (tag === 'summary') return 'button';
1321
- return 'generic';
1322
- };
1323
-
1324
- const getAccessibleName = (node) => {
1325
- const ariaLabel = normalizeText(node.getAttribute?.('aria-label'));
1326
- if (ariaLabel) return ariaLabel;
1327
-
1328
- const labelledBy = normalizeText(node.getAttribute?.('aria-labelledby'));
1329
- if (labelledBy) {
1330
- const labelText = labelledBy
1331
- .split(/\\s+/)
1332
- .map((id) => normalizeText(node.getRootNode().getElementById?.(id)?.textContent))
1333
- .filter(Boolean)
1334
- .join(' ');
1335
- if (labelText) return labelText;
1336
- }
1337
-
1338
- if (typeof node.labels?.length === 'number' && node.labels.length > 0) {
1339
- const labelText = Array.from(node.labels)
1340
- .map((label) => normalizeText(label.textContent))
1341
- .filter(Boolean)
1342
- .join(' ');
1343
- if (labelText) return labelText;
1344
- }
1345
-
1346
- const title = normalizeText(node.getAttribute?.('title'));
1347
- if (title) return title;
1348
-
1349
- const alt = normalizeText(node.getAttribute?.('alt'));
1350
- if (alt) return alt;
1351
-
1352
- const placeholder = normalizeText(node.getAttribute?.('placeholder'));
1353
- if (placeholder) return placeholder;
1354
-
1355
- const value = normalizeText(node.value);
1356
- if (value) return value;
1357
-
1358
- return normalizeText(node.textContent).slice(0, 100);
1359
- };
1360
-
1361
- const isHidden = (node) => {
1362
- if (!node.isConnected) return true;
1363
- if (node.getAttribute?.('hidden') !== null) return true;
1364
- if (node.getAttribute?.('aria-hidden') === 'true') return true;
1365
- const style = node.ownerDocument?.defaultView?.getComputedStyle?.(node);
1366
- if (!style) return false;
1367
- return style.display === 'none' || style.visibility === 'hidden';
1368
- };
1369
-
1370
- const getAriaBoolean = (value) => {
1371
- if (value === 'true') return true;
1372
- if (value === 'false') return false;
1373
- return null;
1374
- };
1375
-
1376
- const getDisabled = (node) => {
1377
- if ('disabled' in node && typeof node.disabled === 'boolean') {
1378
- return node.disabled;
1379
- }
1380
- let current = node;
1381
- while (current) {
1382
- if (current.getAttribute?.('aria-disabled') === 'true') {
1383
- return true;
1384
- }
1385
- current = current.parentElement;
1386
- }
1387
- return false;
1388
- };
1389
-
1390
- const getChecked = (node) => {
1391
- const tag = String(node.tagName || '').toLowerCase();
1392
- if (tag === 'input') {
1393
- const type = String(node.getAttribute?.('type') || '').toLowerCase();
1394
- if (type === 'checkbox' || type === 'radio') {
1395
- return !!node.checked;
1396
- }
1397
- }
1398
- return getAriaBoolean(node.getAttribute?.('aria-checked'));
1399
- };
1400
-
1401
- const getExpanded = (node) => getAriaBoolean(node.getAttribute?.('aria-expanded'));
1402
- const getPressed = (node) => getAriaBoolean(node.getAttribute?.('aria-pressed'));
1403
- const getSelected = (node) => {
1404
- const tag = String(node.tagName || '').toLowerCase();
1405
- if (tag === 'option') {
1406
- return !!node.selected;
1407
- }
1408
- return getAriaBoolean(node.getAttribute?.('aria-selected'));
1409
- };
1410
-
1411
- const getLevel = (node) => {
1412
- const ariaLevel = Number.parseInt(String(node.getAttribute?.('aria-level') || ''), 10);
1413
- if (!Number.isNaN(ariaLevel)) {
1414
- return ariaLevel;
1415
- }
1416
- const tag = String(node.tagName || '').toLowerCase();
1417
- const headingMatch = tag.match(/^h([1-6])$/);
1418
- return headingMatch ? Number.parseInt(headingMatch[1], 10) : null;
1419
- };
1420
-
1421
- const nameMatches = (name) => {
1422
- if (query.regexSource) {
1423
- const re = new RegExp(query.regexSource, query.regexFlags ?? '');
1424
- return re.test(name);
1425
- }
1426
- if (query.name === undefined) {
1427
- return true;
1428
- }
1429
- return query.exact ? name === query.name : name.includes(query.name);
1430
- };
1431
-
1432
- const matchesState = (node) => {
1433
- if (query.includeHidden !== true && isHidden(node)) {
1434
- return false;
1435
- }
1436
- if (query.checked !== undefined && getChecked(node) !== query.checked) {
1437
- return false;
1438
- }
1439
- if (query.disabled !== undefined && getDisabled(node) !== query.disabled) {
1440
- return false;
1441
- }
1442
- if (query.expanded !== undefined && getExpanded(node) !== query.expanded) {
1443
- return false;
1444
- }
1445
- if (query.level !== undefined && getLevel(node) !== query.level) {
1446
- return false;
1447
- }
1448
- if (query.pressed !== undefined && getPressed(node) !== query.pressed) {
1449
- return false;
1450
- }
1451
- if (query.selected !== undefined && getSelected(node) !== query.selected) {
1452
- return false;
1453
- }
1454
- return true;
1455
- };
1456
-
1457
- const matches = [];
1458
- for (const current of (${queryOpenShadowAll.toString()})(document, '*')) {
1459
- if (matchesState(current) && getRole(current) === query.role) {
1460
- const name = getAccessibleName(current);
1461
- if (nameMatches(name)) {
1462
- matches.push(current);
1463
- }
1464
- }
1465
- }
1466
-
1467
- return matches[query.nth] ?? null;
1468
- }`,arguments:[{value:{...jn,nth:Yn}}],executionContextId:Vn.isolatedContextId,returnByValue:!1,awaitPromise:!1,userGesture:!1},qn);if(Qn.objectId)return{objectId:Qn.objectId,frameId:xn,frameSessionId:Vn.sessionId,contextId:Vn.isolatedContextId}}throw Error(`Role selector not found: ${xn}`)}async#u(){return this.#n?await this.#n.resolveFrameId():this.#e.frameManager.mainFrameId}async#d(){if(this.#n){let xn=await this.#n.resolveFrameId(),jn=this.#e.frameManager.getFrame(xn);return jn?[{frameId:xn,parentFrameId:jn.parentFrameId,depth:0}]:[]}return this.#e.frameManager.collectDescendantFrames(this.#e.frameManager.mainFrameId)}#f(xn){let jn=xn.match(/^(.*):nth\((\d+|last)\)$/);if(!jn)return{selector:xn,nth:0};let Vn=jn[2];return{selector:jn[1].trim(),nth:Vn===`last`?`last`:Number.parseInt(Vn,10)}}#p(xn){let jn=xn.match(NTH_SELECTOR_PATTERN),Vn=jn?.[1],qn=Vn===`last`?`last`:Vn?Number.parseInt(Vn,10):0,Jn=jn?xn.slice(0,jn.index):xn,Yn=Jn.match(/^role:([^[]+)/);if(!Yn)throw Error(`Invalid role selector: ${xn}`);let Zn={role:Yn[1].trim(),nth:qn},Qn=Jn.slice(Yn[0].length),ei=/\[([a-z-]+)(\*?)=(.*?)\]/g,ti;for(;ti=ei.exec(Qn);){let[,xn,jn,Vn]=ti,qn=xn,Jn=Vn.trim();if(qn===`name-regex`){Zn.regexSource=decodeURIComponent(Jn);continue}if(qn===`name-regex-flags`){Zn.regexFlags=decodeURIComponent(Jn);continue}if(qn===`name`){Zn.name=decodeURIComponent(Jn),Zn.exact=jn!==`*`;continue}qn===`checked`&&(Zn.checked=Jn===`true`),qn===`disabled`&&(Zn.disabled=Jn===`true`),qn===`expanded`&&(Zn.expanded=Jn===`true`),qn===`include-hidden`&&(Zn.includeHidden=Jn===`true`),qn===`level`&&(Zn.level=Number.parseInt(Jn,10)),qn===`pressed`&&(Zn.pressed=Jn===`true`),qn===`selected`&&(Zn.selected=Jn===`true`)}return Zn}async#m(xn,jn,Vn){let{result:qn,exceptionDetails:Jn}=await this.#e.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(query) {
1469
- const normalizeText = (value) => String(value || '').replace(/\\s+/g, ' ').trim();
1470
- const getRole = (node) => {
1471
- const explicit = node.getAttribute?.('role');
1472
- if (explicit) {
1473
- return explicit.split(/\\s+/)[0] || 'generic';
1474
- }
1475
-
1476
- const tag = String(node.tagName || '').toLowerCase();
1477
- if (tag === 'input') {
1478
- const type = String(node.getAttribute?.('type') || '').toLowerCase();
1479
- if (type === 'checkbox') return 'checkbox';
1480
- if (type === 'radio') return 'radio';
1481
- if (type === 'range') return 'slider';
1482
- if (type === 'button' || type === 'submit' || type === 'reset') return 'button';
1483
- return 'textbox';
1484
- }
1485
- if (tag === 'button') return 'button';
1486
- if (tag === 'a' && node.hasAttribute?.('href')) return 'link';
1487
- if (tag === 'select') return node.multiple || node.size > 1 ? 'listbox' : 'combobox';
1488
- if (tag === 'textarea') return 'textbox';
1489
- if (tag === 'img') return 'img';
1490
- if (tag === 'option') return 'option';
1491
- if (tag === 'summary') return 'button';
1492
- return 'generic';
1493
- };
1494
-
1495
- const getAccessibleName = (node) => {
1496
- const ariaLabel = normalizeText(node.getAttribute?.('aria-label'));
1497
- if (ariaLabel) return ariaLabel;
1498
-
1499
- const labelledBy = normalizeText(node.getAttribute?.('aria-labelledby'));
1500
- if (labelledBy) {
1501
- const labelText = labelledBy
1502
- .split(/\\s+/)
1503
- .map((id) => normalizeText(node.getRootNode().getElementById?.(id)?.textContent))
1504
- .filter(Boolean)
1505
- .join(' ');
1506
- if (labelText) return labelText;
1507
- }
1508
-
1509
- if (typeof node.labels?.length === 'number' && node.labels.length > 0) {
1510
- const labelText = Array.from(node.labels)
1511
- .map((label) => normalizeText(label.textContent))
1512
- .filter(Boolean)
1513
- .join(' ');
1514
- if (labelText) return labelText;
1515
- }
1516
-
1517
- const title = normalizeText(node.getAttribute?.('title'));
1518
- if (title) return title;
1519
-
1520
- const alt = normalizeText(node.getAttribute?.('alt'));
1521
- if (alt) return alt;
1522
-
1523
- const placeholder = normalizeText(node.getAttribute?.('placeholder'));
1524
- if (placeholder) return placeholder;
1525
-
1526
- const value = normalizeText(node.value);
1527
- if (value) return value;
1528
-
1529
- return normalizeText(node.textContent).slice(0, 100);
1530
- };
1531
-
1532
- const isHidden = (node) => {
1533
- if (!node.isConnected) return true;
1534
- if (node.getAttribute?.('hidden') !== null) return true;
1535
- if (node.getAttribute?.('aria-hidden') === 'true') return true;
1536
- const style = node.ownerDocument?.defaultView?.getComputedStyle?.(node);
1537
- if (!style) return false;
1538
- return style.display === 'none' || style.visibility === 'hidden';
1539
- };
1540
-
1541
- const getAriaBoolean = (value) => {
1542
- if (value === 'true') return true;
1543
- if (value === 'false') return false;
1544
- return null;
1545
- };
1546
-
1547
- const getDisabled = (node) => {
1548
- if ('disabled' in node && typeof node.disabled === 'boolean') {
1549
- return node.disabled;
1550
- }
1551
- let current = node;
1552
- while (current) {
1553
- if (current.getAttribute?.('aria-disabled') === 'true') {
1554
- return true;
1555
- }
1556
- current = current.parentElement;
1557
- }
1558
- return false;
1559
- };
1560
-
1561
- const getChecked = (node) => {
1562
- const tag = String(node.tagName || '').toLowerCase();
1563
- if (tag === 'input') {
1564
- const type = String(node.getAttribute?.('type') || '').toLowerCase();
1565
- if (type === 'checkbox' || type === 'radio') {
1566
- return !!node.checked;
1567
- }
1568
- }
1569
- return getAriaBoolean(node.getAttribute?.('aria-checked'));
1570
- };
1571
-
1572
- const getExpanded = (node) => getAriaBoolean(node.getAttribute?.('aria-expanded'));
1573
- const getPressed = (node) => getAriaBoolean(node.getAttribute?.('aria-pressed'));
1574
- const getSelected = (node) => {
1575
- const tag = String(node.tagName || '').toLowerCase();
1576
- if (tag === 'option') {
1577
- return !!node.selected;
1578
- }
1579
- return getAriaBoolean(node.getAttribute?.('aria-selected'));
1580
- };
1581
-
1582
- const getLevel = (node) => {
1583
- const ariaLevel = Number.parseInt(String(node.getAttribute?.('aria-level') || ''), 10);
1584
- if (!Number.isNaN(ariaLevel)) {
1585
- return ariaLevel;
1586
- }
1587
- const tag = String(node.tagName || '').toLowerCase();
1588
- const headingMatch = tag.match(/^h([1-6])$/);
1589
- return headingMatch ? Number.parseInt(headingMatch[1], 10) : null;
1590
- };
1591
-
1592
- const nameMatches = (name) => {
1593
- if (query.regexSource) {
1594
- const re = new RegExp(query.regexSource, query.regexFlags ?? '');
1595
- return re.test(name);
1596
- }
1597
- if (query.name === undefined) {
1598
- return true;
1599
- }
1600
- return query.exact ? name === query.name : name.includes(query.name);
1601
- };
1602
-
1603
- const matchesState = (node) => {
1604
- if (query.includeHidden !== true && isHidden(node)) {
1605
- return false;
1606
- }
1607
- if (query.checked !== undefined && getChecked(node) !== query.checked) {
1608
- return false;
1609
- }
1610
- if (query.disabled !== undefined && getDisabled(node) !== query.disabled) {
1611
- return false;
1612
- }
1613
- if (query.expanded !== undefined && getExpanded(node) !== query.expanded) {
1614
- return false;
1615
- }
1616
- if (query.level !== undefined && getLevel(node) !== query.level) {
1617
- return false;
1618
- }
1619
- if (query.pressed !== undefined && getPressed(node) !== query.pressed) {
1620
- return false;
1621
- }
1622
- if (query.selected !== undefined && getSelected(node) !== query.selected) {
1623
- return false;
1624
- }
1625
- return true;
1626
- };
1627
-
1628
- let count = 0;
1629
- for (const current of (${queryOpenShadowAll.toString()})(document, '*')) {
1630
- if (matchesState(current) && getRole(current) === query.role) {
1631
- const name = getAccessibleName(current);
1632
- if (nameMatches(name)) {
1633
- count += 1;
1634
- }
1635
- }
1636
- }
1637
-
1638
- return count;
1639
- }`,arguments:[{value:Vn}],executionContextId:jn,returnByValue:!0,awaitPromise:!1,userGesture:!1},xn);if(Jn)throw Error(Jn.text??`Role selector count failed`);return Number(qn.value??0)}},ElementHandle=class{#e;#t;constructor(xn,jn){this.#e=xn,this.#t=jn}async contentFrame(){let{node:xn}=await this.#e.cdp.send(`DOM.describeNode`,{objectId:this.#t.objectId,depth:0},await this.#e.resolveSessionId(this.#t.frameSessionId));if(!xn.frameId||!this.#e.frameManager.getFrame(xn.frameId))return null;let{OmOFrame:jn}=await Promise.resolve().then(()=>(init_frame(),frame_exports));return new jn(this.#e,xn.frameId)}}})),FileChooser,init_file_chooser=__esmMin((()=>{init_locator(),FileChooser=class{page;#e;#t;#n;#r=null;constructor(xn,jn,Vn,qn){this.page=xn,this.#e=jn,this.#t=Vn,this.#n=qn}element(){return this.#r??=new Locator(this.page,createBackendNodeLocatorSelector(this.#e,this.#t)),this.#r}isMultiple(){return this.#n}async setFiles(xn){await this.element().setInputFiles(Array.isArray(xn)||typeof xn==`string`?xn:[xn])}}})),OmOMouse,init_mouse=__esmMin((()=>{init_utils$13(),init_keyboard(),OmOMouse=class{context;modifierState;#e=0;#t=0;#n=`none`;constructor(xn,jn){this.context=xn,this.modifierState=jn}async move(xn,jn,Vn={}){let qn=this.#e,Jn=this.#t,Yn=Math.max(Vn.steps??1,1),Zn=this.modifierState.toButtonsMask(),Qn=await shouldUseDomInputFallback(this.context);for(let Vn=1;Vn<=Yn;Vn+=1){let ei=qn+(xn-qn)*(Vn/Yn),ti=Jn+(jn-Jn)*(Vn/Yn);if(Qn){await this.#i(`move`,{x:ei,y:ti,button:this.#n,buttons:Zn});continue}await this.#r(`mouseMoved`,{x:ei,y:ti,button:this.#n,buttons:Zn,modifiers:this.modifierState.toModifiersMask(),force:Zn>0?.5:0})}this.#e=xn,this.#t=jn}async down(xn={}){let jn=xn.button??`left`,Vn=xn.clickCount??1;if(this.#n=jn,this.modifierState.mouseDown(jn),await shouldUseDomInputFallback(this.context)){await this.#i(`down`,{x:this.#e,y:this.#t,button:jn,buttons:this.modifierState.toButtonsMask(),clickCount:Vn});return}await this.#r(`mousePressed`,{button:jn,buttons:this.modifierState.toButtonsMask(),clickCount:Vn,modifiers:this.modifierState.toModifiersMask(),force:this.modifierState.toButtonsMask()>0?.5:0})}async up(xn={}){let jn=xn.button??`left`,Vn=xn.clickCount??1;if(this.#n=`none`,this.modifierState.mouseUp(jn),await shouldUseDomInputFallback(this.context)){await this.#i(`up`,{x:this.#e,y:this.#t,button:jn,buttons:this.modifierState.toButtonsMask(),clickCount:Vn});return}await this.#r(`mouseReleased`,{button:jn,buttons:this.modifierState.toButtonsMask(),clickCount:Vn,modifiers:this.modifierState.toModifiersMask()})}async click(xn,jn,Vn={}){let qn=Vn.button??`left`,Jn=Vn.clickCount??1,Yn=Vn.delay??0;await this.move(xn,jn,{steps:Vn.steps}),await this.context.prepareForPotentialFileChooser?.();for(let xn=1;xn<=Jn;xn+=1)await this.down({button:qn,clickCount:xn}),Yn>0&&await sleep$12(Yn),await this.up({button:qn,clickCount:xn}),Yn>0&&xn<Jn&&await sleep$12(Yn)}async dblclick(xn,jn,Vn={}){await this.click(xn,jn,{button:Vn.button??`left`,clickCount:2,delay:Vn.delay??0,steps:Vn.steps})}async wheel(xn,jn){if(await shouldUseDomInputFallback(this.context)){await this.#i(`wheel`,{x:this.#e,y:this.#t,deltaX:xn,deltaY:jn});return}await this.#r(`mouseWheel`,{deltaX:xn,deltaY:jn,modifiers:this.modifierState.toModifiersMask()})}async#r(xn,jn){await this.context._sendToTarget(`Input.dispatchMouseEvent`,{type:xn,x:Math.floor(jn.x??this.#e),y:Math.floor(jn.y??this.#t),button:jn.button,buttons:jn.buttons,clickCount:jn.clickCount,deltaX:jn.deltaX,deltaY:jn.deltaY,force:jn.force,modifiers:jn.modifiers??this.modifierState.toModifiersMask()})}async#i(xn,jn){await this.context.evaluate(xn=>{let{eventType:jn,x:Vn,y:qn,button:Jn,buttons:Yn,clickCount:Zn,deltaX:Qn,deltaY:ei}=xn,ti=document.elementFromPoint(Vn,qn)??document.scrollingElement??document.documentElement??document.body,ni=Jn===`right`?2:+(Jn===`middle`);if(jn===`wheel`){ti.dispatchEvent(new WheelEvent(`wheel`,{clientX:Vn,clientY:qn,deltaX:Qn??0,deltaY:ei??0,bubbles:!0,cancelable:!0,composed:!0})),window.scrollBy(Qn??0,ei??0);return}let ri=jn===`move`?`mousemove`:jn===`down`?`mousedown`:`mouseup`;ti.dispatchEvent(new MouseEvent(ri,{clientX:Vn,clientY:qn,button:ni,buttons:Yn??0,detail:Zn??0,bubbles:!0,cancelable:!0,composed:!0,view:window})),jn===`up`&&(ti.dispatchEvent(new MouseEvent(`click`,{clientX:Vn,clientY:qn,button:ni,buttons:Yn??0,detail:Zn??1,bubbles:!0,cancelable:!0,composed:!0,view:window})),(Zn??0)===2&&ti.dispatchEvent(new MouseEvent(`dblclick`,{clientX:Vn,clientY:qn,button:ni,buttons:Yn??0,detail:2,bubbles:!0,cancelable:!0,composed:!0,view:window})))},{eventType:xn,...jn})}}})),AGENT_MANAGER_EXTENSION_ID,PASSWORD_MANAGER_EXTENSION_ID,AGENT_MANAGER_EXTENSION_ORIGIN,PASSWORD_MANAGER_EXTENSION_ORIGIN,init_extension_ids=__esmMin((()=>{AGENT_MANAGER_EXTENSION_ID=`fjdhphbdlfjogobdofoaagnlnkoibdge`,PASSWORD_MANAGER_EXTENSION_ID=`clcdgiameigmljcbkkcbjiljinmfkncl`,AGENT_MANAGER_EXTENSION_ORIGIN=`chrome-extension://${AGENT_MANAGER_EXTENSION_ID}`,PASSWORD_MANAGER_EXTENSION_ORIGIN=`chrome-extension://${PASSWORD_MANAGER_EXTENSION_ID}`}));function getKnownIframeOriginLabel(xn){return KNOWN_IFRAME_ORIGINS.find(({urlPrefix:jn})=>xn.startsWith(jn))?.label??null}function formatIframeOriginLabel(xn){return xn?` [origin="${xn.replace(/"/g,`\\"`)}"]`:``}function tagIframeLine(xn,jn,Vn){return xn.split(`
1640
- `).map(xn=>{let qn=xn.match(/^(\s*)- iframe(?:.*? )?\[ref=([^\]]*)\]/);return!qn||qn[2]!==jn||xn.includes(` [origin=`)?xn:xn.replace(/^(\s*)- iframe/,`$1- iframe${formatIframeOriginLabel(Vn)}`)}).join(`
1641
- `)}function getCdpNodeAttribute(xn,jn){if(!xn)return null;for(let Vn=0;Vn<xn.length;Vn+=2)if(xn[Vn]===jn)return xn[Vn+1]??``;return null}function inlineChildTree(xn,jn,Vn){return xn.split(`
1642
- `).flatMap(xn=>{let qn=xn.match(/^(\s*)- iframe(?:.*? )?\[ref=([^\]]*)\]/);if(!qn||qn[2]!==jn)return[xn];let Jn=qn[1]??``,Yn=Vn.split(`
1643
- `).map(xn=>`${Jn} ${xn}`);return[Vn.length>0?`${xn}:`:xn,...Yn]}).join(`
1644
- `)}function appendOrphanChildTree(xn,jn,Vn){if(!jn)return xn;let qn=jn.split(`
1645
- `).map(xn=>` ${xn}`);return`${xn}\n- iframe${formatIframeOriginLabel(Vn)}:\n${qn.join(`
1646
- `)}`}function getRefPrefix(xn){return xn.match(/^(f\d+)?e\d+$/)?.[1]??``}async function takeSnapshot(xn,jn,Vn={}){let qn=jn.mainFrameId,Jn=jn.collectDescendantFrames(qn),Yn=new Map,Zn=new Map,Qn=1;for(let xn of Jn){let jn=xn.frameId===qn?``:`f${Qn++}`;Yn.set(xn.frameId,jn),Zn.set(jn,xn.frameId)}jn.setSnapshotFramePrefixMap(Zn);let ei=(()=>{if(!Vn.ref)return qn;let xn=getRefPrefix(Vn.ref);return Jn.find(({frameId:jn})=>(Yn.get(jn)??``)===xn)?.frameId??null})();if(!ei)throw Error(`Ref "${Vn.ref}" points to a frame that is no longer available. Take a new snapshot.`);let ti=jn.collectDescendantFrames(ei),ni=new Map,ri;await Promise.all(ti.map(async({frameId:qn})=>{let Jn=qn===ei,Zn=Jn?SNAPSHOT_MAX_RETRIES:1,Qn;for(let ti=0;ti<Zn;ti++){ti>0&&await sleep$12(SNAPSHOT_RETRY_DELAY_MS);let ii=await jn.ensureInjected(qn).catch(xn=>(Qn=xn,null));if(!ii){if(Jn&&ti<Zn-1)continue;Jn&&(ri=Qn);return}let ai={interactive:Vn.interactive,maxDepth:Vn.maxDepth,maxChars:Vn.maxChars,refId:qn===ei?Vn.ref:void 0,selector:qn===ei?Vn.selector:void 0,showHidden:Vn.showHidden,refPrefix:Yn.get(qn)??``};try{let{result:Vn}=await xn.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(opts) {
1647
- return globalThis.__omowright.takeSnapshot(opts);
1648
- }`,arguments:[{value:ai}],executionContextId:ii,returnByValue:!0,awaitPromise:!1,userGesture:!1},jn.getFrame(qn)?.sessionId),Yn=Vn.value;if(Yn){if(Yn.error){Jn&&(ri=Yn.error);return}ni.set(qn,Yn);return}}catch(xn){Qn=xn,isContextDestroyedError(xn)&&jn.invalidateContext(qn)}Jn&&Zn-1}Jn&&(ri=Qn)}));let ii=ni.get(ei);if(!ii){let xn=ri;throw xn instanceof Error?xn:typeof xn==`string`&&xn.length>0?Error(xn):Error(ei===qn?`Main frame snapshot failed`:`Ref subtree snapshot failed`)}let ai=new Map,oi=new Map;await Promise.all(ti.map(async({frameId:Vn})=>{let qn=ni.get(Vn),Jn=jn.getFrame(Vn);if(!qn||!Jn?.isolatedContextId)return;let Yn=Object.entries(qn.refs).filter(([,xn])=>xn.tagName.toLowerCase()===`iframe`).map(([xn])=>xn);if(Yn.length===0)return;let Zn=await Promise.all(Yn.map(async qn=>{let{result:Yn}=await xn.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(ref) {
1649
- return globalThis.__omowright.elementRegistry.get(ref);
1650
- }`,arguments:[{value:qn}],executionContextId:Jn.isolatedContextId,returnByValue:!1},Jn.sessionId).catch(xn=>(isContextDestroyedError(xn)&&jn.invalidateContext(Vn),{result:{}})),Zn=typeof Yn==`object`&&Yn&&`objectId`in Yn?Yn.objectId:void 0;if(!Zn)return null;try{let{node:Vn}=await xn.send(`DOM.describeNode`,{objectId:Zn},Jn.sessionId),Yn=Vn.frameId?jn.getFrame(Vn.frameId)?.url:null,Qn=getCdpNodeAttribute(Vn.attributes,`src`),ei=getKnownIframeOriginLabel(Yn??``)??getKnownIframeOriginLabel(Qn??``);return{childFrameId:Vn.frameId,iframeRef:qn,originLabel:ei}}catch{return null}finally{await xn.send(`Runtime.releaseObject`,{objectId:Zn},Jn.sessionId).catch(()=>{})}})),Qn=new Map,ei=new Map;for(let xn of Zn)xn&&(xn.childFrameId&&Qn.set(xn.childFrameId,xn.iframeRef),xn.originLabel&&ei.set(xn.iframeRef,xn.originLabel));ai.set(Vn,Qn),ei.size>0&&oi.set(Vn,ei)}));let si=[...ti].sort((xn,jn)=>jn.depth-xn.depth),ci={};for(let xn of ni.values())Object.assign(ci,xn.refs);for(let[xn,jn]of oi){let Vn=ni.get(xn);if(Vn)for(let[xn,qn]of jn)Vn.tree=tagIframeLine(Vn.tree,xn,qn)}for(let xn of si){if(xn.frameId===qn||!xn.parentFrameId)continue;let Vn=ni.get(xn.frameId),Jn=ni.get(xn.parentFrameId);if(!Vn||!Jn||!Vn.tree)continue;let Yn=ai.get(xn.parentFrameId)?.get(xn.frameId),Zn=getKnownIframeOriginLabel(jn.getFrame(xn.frameId)?.url??``);Jn.tree=Yn?inlineChildTree(Jn.tree,Yn,Vn.tree):appendOrphanChildTree(Jn.tree,Vn.tree,Zn)}return snapshotResult(jn,Vn,{tree:ii.tree,refs:ci})}var KNOWN_IFRAME_ORIGINS,SNAPSHOT_RETRY_DELAY_MS,SNAPSHOT_MAX_RETRIES,init_snapshot=__esmMin((()=>{init_extension_ids(),init_utils$13(),init_client$6(),init_frame_manager(),KNOWN_IFRAME_ORIGINS=[{urlPrefix:`chrome-extension://aeblfdkhhhdcdjpifhhbdiojplfjncoa/`,label:`1Password`},{urlPrefix:`chrome-extension://nngceckbapebfimnlniiiahkandclblb/`,label:`Bitwarden`},{urlPrefix:`chrome-extension://fdjamakpfbbddfjaooikfcpapjohcfmg/`,label:`Dashlane`},{urlPrefix:`chrome-extension://hdokiejnpimakedhajhdlcegeplioahd/`,label:`LastPass`},{urlPrefix:`${PASSWORD_MANAGER_EXTENSION_ORIGIN}/`,label:`OmO Password Manager`}],SNAPSHOT_RETRY_DELAY_MS=300,SNAPSHOT_MAX_RETRIES=3}));var init_session_tab_queries=__esmMin((()=>{init_drizzle_orm(),init_event_bus(),init_extension_bridge(),init_schema(),init_state_db(),init_nanoid(),init_utils$13(),init_store$1()}));var ANNOTATION_OVERLAY_ID,init_annotate_screenshot=__esmMin((()=>{ANNOTATION_OVERLAY_ID=`__omowright_annotations__`}));var AI_TAB_STABLE_VIEWPORT,init_browser=__esmMin((()=>{init_context(),init_cdp(),init_directory(),init_event_bus(),init_extension_bridge(),init_utils$13(),init_session_tab_queries(),init_store$1(),init_types$8(),init_utils$4(),init_annotate_screenshot(),init_frame_manager(),init_page(),init_snapshot(),AI_TAB_STABLE_VIEWPORT={width:1440,height:900}}));function defaultVideoSize(xn){let jn=Math.min(1,DEFAULT_VIDEO_MAX_EDGE/xn.width,DEFAULT_VIDEO_MAX_EDGE/xn.height),Vn=Math.max(2,Math.round(xn.width*jn)),qn=Math.max(2,Math.round(xn.height*jn));return{height:qn%2==0?qn:qn+1,width:Vn%2==0?Vn:Vn+1}}function inferVideoFormat(xn){return xn.format?xn.format:xn.path?.toLowerCase().endsWith(`.mp4`)?`mp4`:DEFAULT_VIDEO_FORMAT}async function ensureDirForFile(xn){await fs$16.mkdir(path.dirname(xn),{recursive:!0})}async function readProcessStderr(xn){return await readProcessStream(xn.stderr).catch(()=>``)}var DEFAULT_VIDEO_FORMAT,DEFAULT_VIDEO_FRAMERATE,DEFAULT_VIDEO_JPEG_QUALITY,DEFAULT_VIDEO_MAX_EDGE,FfmpegVideoRecorder,OmOVideo,init_video=__esmMin((()=>{init_context(),init_process(),init_browser(),DEFAULT_VIDEO_FORMAT=`webm`,DEFAULT_VIDEO_FRAMERATE=25,DEFAULT_VIDEO_JPEG_QUALITY=90,DEFAULT_VIDEO_MAX_EDGE=800,FfmpegVideoRecorder=class{#e;#t;#n=0;#r=!1;#i=null;#a=Promise.resolve();#o=0;#s=[];constructor(xn,jn,Vn,qn){this.#e=Vn;let Jn=qn===`mp4`?[`-c:v`,`libx264`,`-movflags`,`+faststart`]:[`-c:v`,`libvpx`,`-qmin`,`0`,`-qmax`,`50`,`-crf`,`8`,`-deadline`,`realtime`,`-speed`,`8`,`-b:v`,`1M`];this.#t=spawnCommand([`ffmpeg`,`-loglevel`,`error`,`-f`,`image2pipe`,`-avioflags`,`direct`,`-fpsprobesize`,`0`,`-probesize`,`32`,`-analyzeduration`,`0`,`-c:v`,`mjpeg`,`-i`,`pipe:0`,`-y`,`-an`,`-r`,String(Vn),...Jn,`-threads`,`1`,`-vf`,`scale=${jn.width}:${jn.height}:force_original_aspect_ratio=decrease,pad=${jn.width}:${jn.height}:(ow-iw)/2:(oh-ih)/2:gray`,`-pix_fmt`,`yuv420p`,xn],{stdio:[`pipe`,`ignore`,`pipe`]})}writeFrame(xn,jn){if(this.#r)return;this.#n||=jn;let Vn=Math.floor((jn-this.#n)*this.#e);if(this.#i){let xn=Vn-this.#i.frameNumber;for(let jn=0;jn<xn;jn+=1)this.#s.push(this.#i.buffer);this.#a=this.#a.then(()=>this.#c())}this.#i={buffer:xn,frameNumber:Vn,timestamp:jn},this.#o=Date.now()}async stop(xn){if(this.#r)return;if(!this.#i){if(!xn)throw Error(`Video recorder did not capture any frames.`);this.writeFrame(xn,Date.now()/1e3)}let jn=this.#i;if(!jn)throw Error(`Video recorder did not capture any frames.`);let Vn=Math.max((Date.now()-this.#o)/1e3,1);if(this.writeFrame(Buffer.from([]),jn.timestamp+Vn),this.#r=!0,await withCurrentReplAbort(async()=>await this.#a),!this.#t.stdin)throw Error(`ffmpeg stdin is unavailable.`);let qn=this.#t.stdin;await withCurrentReplAbort(async()=>await endProcessInput(qn));let Jn=await withCurrentReplAbort(async()=>await waitForExitCode(this.#t));if(Jn!==0){let xn=await readProcessStderr(this.#t);throw Error(xn.trim()||`ffmpeg exited with code ${Jn}`)}}async#c(){if(!this.#t.stdin)throw Error(`ffmpeg stdin is unavailable.`);let xn=this.#t.stdin;for(;this.#s.length>0;){let jn=this.#s.shift();if(!(!jn||jn.length===0))try{await withCurrentReplAbort(async()=>await writeProcessChunk(xn,jn))}catch(xn){let jn=(await readProcessStderr(this.#t)).trim();throw Error(jn.length>0?`ffmpeg rejected video frame input: ${jn}`:xn instanceof Error?xn.message:String(xn))}}}},OmOVideo=class{#e;#t=null;#n=null;constructor(xn){this.#e=xn}async start(xn={}){return await withCurrentReplAbort(async()=>{if(this.#t)throw Error(`Video recording is already active.`);let jn=await this.#e.resolveSessionId(),Vn=this.#e.viewportSize()??await this.#e.refreshViewportSize().catch(()=>null)??AI_TAB_STABLE_VIEWPORT,qn=inferVideoFormat(xn),Jn=xn.size??defaultVideoSize(Vn),Yn=await this.#e.browser.ensurePath(xn.path??`video-${Date.now()}.${qn}`,`write`,`page.video.start`),Zn=xn.quality??DEFAULT_VIDEO_JPEG_QUALITY,Qn=xn.framerate??DEFAULT_VIDEO_FRAMERATE;await ensureDirForFile(Yn);let ei=new FfmpegVideoRecorder(Yn,Jn,Qn,qn),{promise:ti,resolve:ni,reject:ri}=Promise.withResolvers(),ii=this.#e.cdp.on(`Page.screencastFrame`,(xn,Vn)=>{if(Vn.sessionId!==jn)return;let qn=Buffer.from(xn.data,`base64`),Jn=xn.metadata?.timestamp??Date.now()/1e3;ei.writeFrame(qn,Jn),this.#e.cdp.send(`Page.screencastFrameAck`,{sessionId:xn.sessionId},jn).catch(()=>{})});this.#t={completion:ti,format:qn,outputPath:Yn,pendingCopies:new Set,recorder:ei,rejectCompletion:ri,resolveCompletion:ni,sessionId:jn,unsubscribe:ii},this.#n=Yn;try{await this.#e.cdp.send(`Page.startScreencast`,{everyNthFrame:1,format:`jpeg`,maxHeight:Jn.height,maxWidth:Jn.width,quality:Zn},jn)}catch(xn){throw ii(),this.#t=null,this.#n=null,ri(xn),xn}})}async stop(xn={}){return await withCurrentReplAbort(async()=>{let jn=this.#t;if(!jn)throw Error(`Video recording has not been started.`);this.#t=null,jn.unsubscribe(),await this.#e.cdp.send(`Page.stopScreencast`,void 0,jn.sessionId).catch(()=>{});try{let Vn=await this.#e.screenshot({type:`jpeg`}).catch(()=>void 0),qn=xn.path?await this.#e.browser.ensurePath(xn.path,`write`,`page.video.stop`):jn.outputPath;await jn.recorder.stop(Vn),qn!==jn.outputPath&&(await ensureDirForFile(qn),await fs$16.copyFile(jn.outputPath,qn)),this.#n=qn;for(let xn of jn.pendingCopies){let jn=await this.#e.browser.ensurePath(xn,`write`,`page.video.saveAs`);jn!==qn&&(await ensureDirForFile(jn),await fs$16.copyFile(qn,jn))}jn.resolveCompletion(qn)}catch(xn){throw jn.rejectCompletion(xn),xn}})}async path(){if(this.#t)return this.#t.outputPath;if(this.#n)return this.#n;throw Error(`Video recording has not been started.`)}async saveAs(xn){return await withCurrentReplAbort(async()=>{let jn=await this.#e.browser.ensurePath(xn,`write`,`page.video.saveAs`);if(this.#t){this.#t.pendingCopies.add(xn),await this.#t.completion;return}if(!this.#n)throw Error(`Video recording has not been started.`);await ensureDirForFile(jn),await fs$16.copyFile(this.#n,jn)})}async delete(){return await withCurrentReplAbort(async()=>{if(this.#t&&await this.stop(),!this.#n)throw Error(`Video recording has not been started.`);let xn=this.#n;this.#n=null,await fs$16.unlink(xn).catch(()=>{})})}}}));function isOmOEvaluateOptions(xn){if(typeof xn!=`object`||!xn||Array.isArray(xn))return!1;let jn=Object.keys(xn);return jn.length===1&&jn[0]===`userGesture`}function resolveEvaluateCall(xn,jn,Vn){if(Vn!==void 0&&!isOmOEvaluateOptions(Vn))throw Error(`page.evaluate() accepts a single optional argument. Pass multiple values as one object or array, e.g. page.evaluate(fn, [a, b]).`);return typeof xn==`string`&&isOmOEvaluateOptions(jn)?{actualArg:void 0,evaluateOptions:jn}:{actualArg:jn,evaluateOptions:Vn??{}}}function clampScreenshotClipToTextureLimit(xn,jn){let Vn=Math.max(1,Math.floor(MAX_SCREENSHOT_TEXTURE_SIZE/(Number.isFinite(jn)&&jn>0?jn:1)));return{...xn,width:Math.max(1,Math.min(xn.width,Vn)),height:Math.max(1,Math.min(xn.height,Vn))}}function normalizeScreenshotTimeout(xn){if(xn!==void 0){if(!Number.isFinite(xn)||xn<0)throw Error(`page.screenshot: timeout must be a non-negative number`);return xn}}function screenshotCaptureLabel(xn){return xn.clip?`clipped screenshot`:xn.fullPage?`full-page screenshot`:`viewport screenshot`}function formatScreenshotError(xn){return xn instanceof Error?xn.message:String(xn)}function rewriteCaptureScreenshotError(xn,jn,Vn){let qn=formatScreenshotError(xn);if(qn!==`CDP command timeout: Page.captureScreenshot`)return xn instanceof Error?xn:Error(qn);let Jn=jn===void 0?`the default screenshot timeout`:jn===0?`a disabled page.screenshot timeout`:`the requested ${jn}ms page.screenshot timeout`;return Error(`page.screenshot: browser CDP command timed out while capturing ${Vn} before ${Jn} completed`)}function isCaptureScreenshotTimeout(xn){let jn=formatScreenshotError(xn);return jn===`CDP command timeout: Page.captureScreenshot`||jn.startsWith(`page.screenshot: browser CDP command timed out while capturing `)}function formatPdfLength(xn){if(xn!==void 0)return typeof xn==`number`?`${xn}px`:xn}var DEFAULT_WAIT_TIMEOUT_MS,NETWORK_IDLE_MS,MAX_SCREENSHOT_TEXTURE_SIZE,FILECHOOSER_OOPIF_FALLBACK_MS,OmOPage,init_page=__esmMin((()=>{init_emittery(),init_context(),init_extension_bridge(),init_notification_grants(),init_utils$13(),init_client$6(),init_errors$3(),init_utils$4(),init_console_capture(),init_download(),init_file_chooser(),init_frame(),init_frame_manager(),init_keyboard(),init_locator(),init_mouse(),init_snapshot(),init_video(),init_wait(),DEFAULT_WAIT_TIMEOUT_MS=3e4,NETWORK_IDLE_MS=500,MAX_SCREENSHOT_TEXTURE_SIZE=16384,FILECHOOSER_OOPIF_FALLBACK_MS=2e3,OmOPage=class{#networkCount=0;#networkOff=null;cdp;frameManager;targetId;modifierState;mouse;keyboard;events=new Emittery;browser;#e=new Map;#t=null;#n;#r=``;#i=null;#a=[];#o=null;#s=!1;#c=0;constructor(xn,jn,Vn,qn,Jn){this.cdp=xn,this.frameManager=jn,this.targetId=Vn,this.modifierState=new ModifierState,this.mouse=new OmOMouse(this,this.modifierState),this.keyboard=new OmOKeyboard(this,this.modifierState),this.browser=Jn,this.#n=qn,this.#r=this.frameManager.getFrame(this.frameManager.mainFrameId)?.url??``,this.#l()}#l(){this.#networkCount>0&&(this.#networkOff=subscribePageNetworkEvents(this));let xn=new Set,jn=xn=>{replPrint(`[error] page event listener threw: ${xn instanceof Error?xn.message:xn}`)};this.#u(`Page.frameNavigated`,xn=>{xn.frame.parentId||(this.#r=xn.frame.url)}),this.#u(`Page.loadEventFired`,()=>{this.events.emit(`load`).catch(jn)}),this.#u(`Page.domContentEventFired`,()=>{this.events.emit(`domcontentloaded`).catch(jn)}),this.#a.push(this.cdp.on(`Page.javascriptDialogOpening`,(xn,Vn)=>{if(Vn.sessionId===this.#n)return this.events.emit(`dialog`,Vn.dialog??new Dialog(xn,dialogAction=>this.cdp.send(`Page.handleJavaScriptDialog`,dialogAction,this.#n))).catch(jn)})),this.#a.push(this.cdp.on(`Page.fileChooserOpened`,(xn,Vn)=>{!Vn.sessionId||!xn.backendNodeId||this.events.emit(`filechooser`,new FileChooser(this,xn.frameId,xn.backendNodeId,xn.mode===`selectMultiple`)).catch(jn)})),this.#u(`Page.frameAttached`,xn=>{this.events.emit(`frameattached`,{frameId:xn.frameId,parentFrameId:xn.parentFrameId}).catch(jn)}),this.#u(`Page.frameDetached`,xn=>{this.events.emit(`framedetached`,{frameId:xn.frameId}).catch(jn)}),this.#u(`Page.frameNavigated`,xn=>{this.events.emit(`framenavigated`,{frameId:xn.frame.id,url:xn.frame.url,name:xn.frame.name??``}).catch(jn)});let Vn=Vn=>{xn.has(Vn.guid)||this.frameManager.getFrame(Vn.frameId)&&(xn.add(Vn.guid),this.events.emit(`download`,new OmODownload(this,{guid:Vn.guid,startedAfterMs:Date.now(),suggestedFilename:Vn.suggestedFilename,url:Vn.url})).catch(jn))};this.#a.push(this.cdp.on(`Browser.downloadWillBegin`,xn=>Vn(xn))),this.#u(`Page.downloadWillBegin`,xn=>{Vn(xn)}),this.#a.push(this.cdp.on(`Page.windowOpen`,(xn,Vn)=>{!Vn.sessionId||!this.frameManager.hasSession(Vn.sessionId)||this.events.emit(`popup`,{url:xn.url,windowName:xn.windowName}).catch(jn)})),this.#u(`Inspector.targetCrashed`,()=>{this.events.emit(`crash`).catch(jn)}),this.frameManager.onSessionInitialized=xn=>{this.#c>0&&this.#p(!0,[xn])}}#u(xn,jn){this.#a.push(this.cdp.on(xn,(xn,Vn)=>{Vn.sessionId===this.#n&&jn(xn)}))}on(xn,jn){let Vn=this.#e.get(xn)??new WeakMap,qn=this.events.on(xn,({data:xn})=>jn(xn)),active=true,isNetwork=xn===`request`||xn===`response`;if(isNetwork&&this.#networkCount++===0)this.#networkOff=subscribePageNetworkEvents(this);xn===`filechooser`&&this.#m();const off=()=>{if(!active)return;active=false;qn();Vn.delete(jn);if(isNetwork&&--this.#networkCount===0){this.#networkOff?.();this.#networkOff=null}xn===`filechooser`&&this.#h()};Vn.set(jn,off);this.#e.set(xn,Vn);return off}off(xn,jn){this.#e.get(xn)?.get(jn)?.()}waitForResponse(match,options={}){return this.waitForEvent(`response`,{...options,predicate:networkPredicate(match)})}waitForRequest(match,options={}){return this.waitForEvent(`request`,{...options,predicate:networkPredicate(match)})}async waitForEvent(xn,jn={}){let Vn=jn.timeout??DEFAULT_WAIT_TIMEOUT_MS;if(xn===`download`){let qn=Date.now();return await new Promise((Jn,Yn)=>{let Zn=!1,Qn=()=>{ri(),clearTimeout(ni)},ei=xn=>{Zn||(Zn=!0,Qn(),xn())},ti=xn=>{(async()=>{try{if(jn.predicate&&!await jn.predicate(xn))return;ei(()=>Jn(xn))}catch(xn){ei(()=>Yn(xn instanceof Error?xn:Error(String(xn))))}})()},ni=setTimeout(()=>{ei(()=>Yn(Error(`Timed out waiting for page event "${String(xn)}"`)))},Vn),ri=this.on(`download`,ti);this.cdp.send(`OmO.waitForDownload`,{startedAfterMs:qn,timeoutMs:Vn},void 0,{extensionBridge:this.browser.extensionBridgeRoute}).then(xn=>{ti(new OmODownload(this,{guid:String(xn.downloadId),sourcePath:xn.absolutePath,startedAfterMs:qn,suggestedFilename:path.basename(xn.absolutePath),url:this.url()}))}).catch(()=>{})})}return await new Promise((qn,Jn)=>{let Yn=!1,Zn=null,Qn=()=>{ni(),clearTimeout(ti),Zn&&clearTimeout(Zn)},ei=xn=>{Yn||(Yn=!0,Qn(),xn())},ti=setTimeout(()=>{ei(()=>Jn(Error(`Timed out waiting for page event "${String(xn)}"`)))},Vn);xn===`filechooser`&&Vn>FILECHOOSER_OOPIF_FALLBACK_MS&&(Zn=setTimeout(()=>{Yn||this.#g().then(xn=>{xn&&!Yn&&ei(()=>qn(xn))})},FILECHOOSER_OOPIF_FALLBACK_MS));let ni=this.on(xn,xn=>{(async()=>{try{if(jn.predicate&&!await jn.predicate(xn))return;ei(()=>qn(xn))}catch(xn){ei(()=>Jn(xn instanceof Error?xn:Error(String(xn))))}})()})})}#d(){this.#networkOff?.();this.#networkOff=null;disposeNetwork(this);for(let xn of this.#a)xn();this.#a=[]}async dispose(){this.#s||(this.#s=!0,await this.#o?.stop().catch(()=>{}),this.#d(),this.#c=0,await this.events.emit(`close`),this.events.clearListeners(),this.#e.clear())}reconnect(xn){this.#n=xn,this.#s=!1,this.#d(),this.#l(),this.#r=this.frameManager.getFrame(this.frameManager.mainFrameId)?.url??this.#r,this.#c>0&&this.#p(!0)}#f(){return[...new Set([this.#n,...[...this.frameManager.frames.values()].map(xn=>xn.sessionId)])]}async prepareForPotentialFileChooser(){this.#c!==0&&await this.#p(!0)}#p(xn,jn=this.#f()){return withoutReplContext(async()=>{await Promise.allSettled(jn.map(jn=>this.cdp.send(`Page.setInterceptFileChooserDialog`,{enabled:xn},jn)))})}#m(){this.#c+=1,this.#c===1&&this.#p(!0)}#h(){this.#c!==0&&(--this.#c,this.#c===0&&this.#p(!1))}async#g(){for(let xn of this.frameManager.frames.values())if(xn.sessionId!==this.#n)try{let{root:jn}=await this.cdp.send(`DOM.getDocument`,{depth:0},xn.sessionId),{nodeIds:Vn}=await this.cdp.send(`DOM.querySelectorAll`,{nodeId:jn.nodeId,selector:`input[type=file]`},xn.sessionId);if(Vn.length===0)continue;let qn=Vn[Vn.length-1],{node:Jn}=await this.cdp.send(`DOM.describeNode`,{nodeId:qn},xn.sessionId),Yn=(Jn.attributes??[]).includes(`multiple`);return new FileChooser(this,xn.frameId,Jn.backendNodeId,Yn)}catch{}return null}async resolveSessionId(xn){if(xn&&this.frameManager.hasSession(xn))return xn;let jn=await this.browser.resolvePageSession(this.targetId,this.#n);return jn!==this.#n&&(this.#n=jn),jn}async goto(xn,jn={}){await networkReady(this);const releaseNetwork=[`interactive`,`stable`,`networkidle`].includes(jn.waitUntil??`interactive`)?acquireNetwork(this.cdp,await this.resolveSessionId()):null;try{await releaseNetwork?.ready;let Vn=jn.waitUntil??`interactive`,qn=await this.resolveSessionId(this.#n),Jn=()=>{},Yn=Vn===`commit`?null:Vn===`interactive`||Vn===`stable`?waitForNavigationReadiness(this,Vn,DEFAULT_WAIT_TIMEOUT_MS).then(()=>{}):Vn===`networkidle`?this.#S(DEFAULT_WAIT_TIMEOUT_MS):new Promise((xn,jn)=>{let Yn=!1,Zn,Qn=()=>{},ei=xn=>{Yn||(Yn=!0,clearTimeout(Zn),Qn(),xn())};Zn=setTimeout(()=>{ei(()=>jn(Error(`Timed out waiting for "${Vn}" after goto`)))},DEFAULT_WAIT_TIMEOUT_MS);let ti=Vn===`load`?`Page.loadEventFired`:`Page.domContentEventFired`;Qn=this.cdp.on(ti,(jn,Vn)=>{Vn.sessionId===qn&&ei(xn)}),Jn=()=>ei(xn)}),Zn=await this.cdp.send(`Page.navigate`,{url:xn},qn);if(Zn.errorText)throw Error(Zn.errorText);if(this.#r=xn,Vn===`domcontentloaded`&&Yn){if(!Zn.loaderId){Jn(),await this.#v(`Timed out waiting for "${Vn}" after goto`);return}try{await Yn}catch(xn){if(await this.#_())return;throw xn}return}Yn&&await Yn}finally{releaseNetwork?.()}}async goBack(){let xn=await this._sendToTarget(`Page.getNavigationHistory`),jn=xn.currentIndex-1;if(jn<0)return;let Vn=xn.entries[jn];if(!Vn)return;let qn=this.#C();await this._sendToTarget(`Page.navigateToHistoryEntry`,{entryId:Vn.id}),await qn}async goForward(){let xn=await this._sendToTarget(`Page.getNavigationHistory`),jn=xn.currentIndex+1;if(jn>=xn.entries.length)return;let Vn=xn.entries[jn];if(!Vn)return;let qn=this.#C();await this._sendToTarget(`Page.navigateToHistoryEntry`,{entryId:Vn.id}),await qn}async reload(){let xn=this.#C();await this._sendToTarget(`Page.reload`),await xn}async waitForLoadState(state=`interactive`,options=DEFAULT_WAIT_TIMEOUT_MS){let timeout=typeof options==`number`?options:options?.timeout??DEFAULT_WAIT_TIMEOUT_MS;if(state===`interactive`||state===`stable`){await waitForNavigationReadiness(this,state,timeout);return}if(state===`commit`)return;if(state===`networkidle`){await this.#S(timeout);return}if(state!==`load`&&state!==`domcontentloaded`)throw Error(`waitForLoadState: unsupported state "${state}"; expected load, domcontentloaded, networkidle, commit, interactive or stable`);let sessionId=await this.resolveSessionId(this.#n),reached=state===`load`?xn=>xn===`complete`:xn=>xn!==`loading`,unsubscribe=()=>{},timer;try{await new Promise((resolve,reject)=>{timer=setTimeout(()=>reject(Error(`Timed out waiting for load state "${state}"`)),timeout),unsubscribe=this.cdp.on(state===`load`?`Page.loadEventFired`:`Page.domContentEventFired`,(xn,meta)=>{meta.sessionId===sessionId&&resolve()}),this.evaluate(`document.readyState`).then(xn=>{reached(xn)&&resolve()},()=>{})})}finally{clearTimeout(timer),unsubscribe()}}async#_(){return await this.evaluate(`document.readyState`).catch(()=>`loading`)!==`loading`}async#v(xn,jn=DEFAULT_WAIT_TIMEOUT_MS){let Vn=Date.now();for(;Date.now()-Vn<jn;){if(await this.#_())return;await sleep$12(50)}throw Error(xn)}async waitForURL(match,options={}){let timeout=options.timeout??DEFAULT_WAIT_TIMEOUT_MS,start=Date.now();for(;Date.now()-start<timeout;){if(await urlMatches(this.url(),match)){options.waitUntil&&await this.waitForLoadState(options.waitUntil,{timeout:Math.max(0,timeout-(Date.now()-start))});return}await sleep$12(100)}throw Error(`Timed out waiting for URL match: ${String(match)}`)}async waitForSelector(xn,jn={}){let Vn=jn.state??`visible`,qn=jn.timeout??3e3,Jn=[0,20,50,100,100,500],Yn=Date.now(),Zn=0;for(;;){if(Date.now()-Yn>=qn)throw Error(`waitForSelector: timed out after ${qn}ms waiting for "${xn}" to be ${Vn}`);let jn=await this.evaluate(xn=>{let jn=document.querySelector(xn);if(!jn)return{attached:!1,visible:!1};let Vn=jn.getBoundingClientRect(),qn=window.getComputedStyle(jn);return{attached:!0,visible:qn.visibility!==`hidden`&&qn.display!==`none`&&parseFloat(qn.opacity)!==0&&Vn.width>0&&Vn.height>0}},xn);if(Vn===`attached`?jn.attached:Vn===`detached`?!jn.attached:Vn===`visible`?jn.visible:!jn.visible)return;let Qn=Jn[Math.min(Zn++,Jn.length-1)];await sleep$12(Qn)}}locator(xn,jn={}){return new Locator(this,xn).filter(jn)}async click(xn,jn){await this.locator(xn).click(jn)}async fill(xn,jn){await this.locator(xn).fill(jn)}async $(xn){return replPrint(`warn`,`page.$() is deprecated in OmOWright — use page.locator(selector).first() instead`),this.locator(xn).first()}async $$(xn){return replPrint(`warn`,`page.$$() is deprecated in OmOWright — use page.locator(selector).all() instead`),await this.locator(xn).all()}async $$eval(xn,jn,Vn){return await this.locator(xn).evaluateAll(jn,Vn)}getByRole(xn,jn={}){return new Locator(this,Locator.createRoleSelector(xn,jn))}getByLabel(xn,jn={}){if(xn instanceof RegExp)return new Locator(this,`internal:label=/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return new Locator(this,jn.exact?`internal:label:exact:${Vn}`:`internal:label:${Vn}`)}getByText(xn,jn={}){if(xn instanceof RegExp)return new Locator(this,`text:/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return new Locator(this,jn.exact?`text:exact:${Vn}`:`text:${Vn}`)}frameLocator(xn){return new FrameLocator(this,this.mainFrame(),xn)}async evaluate(xn,jn,Vn){let{actualArg:qn,evaluateOptions:Jn}=resolveEvaluateCall(xn,jn,Vn);if(typeof xn==`string`&&qn===void 0){let{result:jn,exceptionDetails:Vn}=await this._sendToTarget(`Runtime.evaluate`,{expression:xn,returnByValue:!0,awaitPromise:!0,userGesture:Jn.userGesture});if(Vn)throw Error(formatRuntimeException(Vn,`Evaluation failed`));return jn.value}let Yn=typeof xn==`function`?xn.toString():xn,Zn=await this.#x();try{let{result:xn,exceptionDetails:jn}=await this._sendToTarget(`Runtime.callFunctionOn`,{objectId:Zn,functionDeclaration:`function(arg) { var __name = (t) => t; return (${Yn})(arg); }`,arguments:[{value:qn}],returnByValue:!0,awaitPromise:!0,userGesture:Jn.userGesture});if(jn)throw Error(formatRuntimeException(jn,`Evaluation failed`));return xn.value}finally{await this._sendToTarget(`Runtime.releaseObject`,{objectId:Zn}).catch(()=>{})}}async evaluateInFrame(xn,jn,Vn,qn){let Jn=this.frameManager.getFrame(xn);if(!Jn)throw Error(`Frame is not available: ${xn}`);let{actualArg:Yn,evaluateOptions:Zn}=resolveEvaluateCall(jn,Vn,qn),Qn=await this.resolveSessionId(Jn.sessionId);if(typeof jn==`string`&&Yn===void 0){let Vn=await this.frameManager.ensureInjected(xn);if(!Vn)throw Error(`Frame isolated world is not ready: ${xn}`);let{result:qn,exceptionDetails:Jn}=await this.cdp.send(`Runtime.evaluate`,{expression:jn,contextId:Vn,returnByValue:!0,awaitPromise:!0,userGesture:Zn.userGesture},Qn);if(Jn)throw Error(formatRuntimeException(Jn,`Evaluation failed`));return qn.value}let ei=typeof jn==`function`?jn.toString():jn,ti=await this.frameManager.ensureInjected(xn);if(!ti)throw Error(`Frame isolated world is not ready: ${xn}`);let{result:ni,exceptionDetails:ri}=await this.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(arg) { var __name = (t) => t; return (${ei})(arg); }`,arguments:[{value:Yn}],executionContextId:ti,returnByValue:!0,awaitPromise:!0,userGesture:Zn.userGesture},Qn);if(ri)throw Error(formatRuntimeException(ri,`Evaluation failed`));return ni.value}async grantNotificationPermission(){await sendCommandToExtension({method:`OmO.grantNotificationPermission`,params:{targetId:this.targetId}},this.browser.extensionBridgeRoute);}url({truncate:xn=!1}={}){return xn?truncateUrlForLLM(this.#r):this.#r}async title(){return await this.evaluate(`document.title`).catch(()=>``)}async content(){return await this.evaluate(`document.documentElement.outerHTML`)}async screenshot(xn={}){let jn=normalizeScreenshotTimeout(xn.timeout),Vn=jn&&jn>0?Date.now()+jn:void 0,qn;if(xn.clip)qn={x:xn.clip.x,y:xn.clip.y,width:xn.clip.width,height:xn.clip.height,scale:1};else if(xn.fullPage){let xn=await this._sendToTarget(`Page.getLayoutMetrics`),jn=xn.cssContentSize??xn.contentSize;qn={x:0,y:0,width:jn.width,height:jn.height,scale:1}}qn&&=clampScreenshotClipToTextureLimit(qn,await this.#y());let Jn={format:xn.type??`png`,captureBeyondViewport:!!xn.fullPage,quality:xn.quality,...qn?{clip:qn}:{}},Yn;try{({data:Yn}=await this.#b(Jn,jn,screenshotCaptureLabel(xn)))}catch(jn){if(!xn.fullPage||xn.clip||!isCaptureScreenshotTimeout(jn))throw jn;let qn=Vn?Math.max(0,Vn-Date.now()):void 0;if(qn===0)throw jn;let Jn={format:xn.type??`png`,captureBeyondViewport:!1,quality:xn.quality};try{({data:Yn}=await this.#b(Jn,qn,`viewport fallback screenshot`)),replPrint(`[system] full-page screenshot failed; returned viewport fallback. ${formatScreenshotError(jn)}`)}catch(xn){throw Error(`${formatScreenshotError(jn)}\nViewport fallback also failed: ${formatScreenshotError(xn)}`)}}let Zn=Buffer.from(Yn,`base64`);if(xn.path)if(xn.path.startsWith(`/tmp`)){let jn=this.browser.resolvePath(`tmp`),Vn=path.join(jn,path.basename(xn.path));await mkdir(path.dirname(Vn),{recursive:!0}),await writeFile(Vn,Zn),replPrint(`[WARN] Use ${jn} instead of /tmp. Saved it to ${Vn}`)}else{let jn=this.browser.resolvePath(xn.path);await mkdir(path.dirname(jn),{recursive:!0}),await writeFile(jn,Zn)}return Zn}async#y(){return await this.evaluate(`window.devicePixelRatio`).catch(()=>1)}async#b(xn,jn,Vn){try{return await this._sendToTarget(`Page.captureScreenshot`,xn,{timeoutMs:jn})}catch(xn){throw rewriteCaptureScreenshotError(xn,jn,Vn)}}async snapshot(xn={}){return await takeSnapshot(this.cdp,this.frameManager,xn)}frames(){return this.frameManager.collectDescendantFrames(this.frameManager.mainFrameId).map(({frameId:xn})=>new OmOFrame(this,xn))}mainFrame(){let xn=this.frameManager.getFrame(this.frameManager.mainFrameId);if(!xn)throw Error(`Main frame is not available`);return new OmOFrame(this,xn.frameId)}async bringToFront(){this.browser.page=this,replPrint(`page is now [${await this.title().catch(()=>``)}](${this.url()})`)}async openPopupUrl(xn){await this.browser.openPopupTab(xn,this.targetId)}get console(){return this.#t??=new PageConsole(this)}video(){return this.#w()}viewportSize(){return this.#i?{...this.#i}:null}async refreshViewportSize(){let xn=await this.evaluate(()=>({width:Math.round(globalThis.visualViewport?.width??globalThis.innerWidth??0),height:Math.round(globalThis.visualViewport?.height??globalThis.innerHeight??0)}));if(xn.width<=0||xn.height<=0)throw Error(`Measured viewport size is invalid: ${JSON.stringify(xn)}`);return this.#i=xn,xn}setCachedViewportSize(xn){this.#i=xn?{...xn}:null}async pdf(xn={}){let jn=xn.path?await this.browser.ensurePath(xn.path,`write`,`page.pdf`):void 0,Vn={...xn,height:formatPdfLength(xn.height),margin:xn.margin?{bottom:formatPdfLength(xn.margin.bottom),left:formatPdfLength(xn.margin.left),right:formatPdfLength(xn.margin.right),top:formatPdfLength(xn.margin.top)}:void 0,printBackground:xn.printBackground??!0,transferMode:`ReturnAsBase64`,width:formatPdfLength(xn.width)},{data:qn}=await this._sendToTarget(`Page.printToPDF`,Vn),Jn=Buffer.from(qn,`base64`);return jn&&(await mkdir(path.dirname(jn),{recursive:!0}).catch(()=>{}),await writeFile(jn,Jn)),Jn}async close(xn={}){for(const sessionId of this.#f())this.cdp.closeSession?.(sessionId);if(await this.#w().stop().catch(()=>{}),xn.runBeforeUnload){let jn=await this.resolveSessionId(this.#n);await this.cdp.send(`Page.close`,void 0,jn).catch(async()=>{await this.browser.closeTab(this,xn)});return}await this.browser.closeTab(this,xn)}async#x(){let{result:xn,exceptionDetails:jn}=await this._sendToTarget(`Runtime.evaluate`,{expression:`globalThis`,serializationOptions:{serialization:`idOnly`}});if(jn)throw Error(formatRuntimeException(jn,`Failed to resolve main world`));if(!xn.objectId)throw Error(`Main world object is not available`);return xn.objectId}async#S(xn){let jn=await this.resolveSessionId(this.#n),releaseNetwork=acquireNetwork(this.cdp,jn);await releaseNetwork.ready;await new Promise((Vn,qn)=>{let Jn=new Set,Yn=null,Zn=null,Qn=()=>{ti(),ri(),ii(),releaseNetwork(),Yn&&=(clearTimeout(Yn),null),Zn&&=(clearTimeout(Zn),null)},ei=()=>{Yn&&clearTimeout(Yn),Jn.size===0&&(Yn=setTimeout(()=>{Qn(),Vn()},NETWORK_IDLE_MS))},ti=this.cdp.on(`Network.requestWillBeSent`,(xn,Vn)=>{Vn.sessionId===jn&&(xn.request.url.startsWith(`data:`)||Jn.add(xn.requestId))}),ni=xn=>{Jn.delete(xn),ei()},ri=this.cdp.on(`Network.loadingFinished`,(xn,Vn)=>{Vn.sessionId===jn&&ni(xn.requestId)}),ii=this.cdp.on(`Network.loadingFailed`,(xn,Vn)=>{Vn.sessionId===jn&&ni(xn.requestId)});Zn=setTimeout(()=>{Qn(),qn(Error(`Timed out waiting for load state "networkidle"`))},xn),ei()})}async#C(){let xn=await this.resolveSessionId(this.#n);await new Promise((jn,Vn)=>{let qn=setTimeout(()=>{Jn(),Vn(Error(`Timed out waiting for navigation`))},DEFAULT_WAIT_TIMEOUT_MS),Jn=this.cdp.on(`Page.frameNavigated`,(Vn,Yn)=>{Yn.sessionId===xn&&(Vn.frame.parentId||(clearTimeout(qn),Jn(),jn()))})})}async _sendToTarget(xn,jn,Vn={}){await networkReady(this);if(this.#s)throw Error(`Page ${this.targetId} is disposed`);let{preferredSessionId:qn,...Jn}=Vn;if(qn!==void 0){if(!this.frameManager.hasSession(qn))throw Error(`Frame is stale or detached: CDP session ${qn} is unavailable`);return await this.cdp.send(xn,jn,qn,Jn)}let Yn=await this.resolveSessionId(this.#n);return await this.cdp.send(xn,jn,Yn,Jn)}#w(){return this.#o??=new OmOVideo(this),this.#o}}}));
1651
-
1652
- init_client$6();
1653
- init_session_manager();
1654
- init_frame_manager();
1655
- init_page();
1656
- // Playwright's attribute locators. Like getByText/getByLabel they only build a selector: the injected query resolves
1657
- // `internal:attr=[name=value]` as a `[name]` query through open shadow roots, filtered by the value (parseAttributeMatcher).
1658
- let testIdAttributeName = "data-testid";
1659
- const selectors = {
1660
- // Playwright's selectors.setTestIdAttribute(): getByTestId() locators created afterwards match this attribute.
1661
- setTestIdAttribute(attributeName) {
1662
- if (typeof attributeName !== "string" || !/^[^\s"'>/=[\]]+$/.test(attributeName)) {
1663
- throw new TypeError(`selectors.setTestIdAttribute: invalid attribute name ${JSON.stringify(attributeName)}`);
1664
- }
1665
- testIdAttributeName = attributeName;
1666
- },
1667
- };
1668
- function attributeSelector(name, value, exact) {
1669
- // `>>` chains locator steps, so a value never carries it: `>` is written as an escape the matcher decodes.
1670
- if (Object.prototype.toString.call(value) === "[object RegExp]") return `internal:attr=[${name}=/${value.source.replaceAll(">>", ">\\x3e")}/${value.flags}]`;
1671
- return `internal:attr=[${name}=${JSON.stringify(String(value)).replaceAll(">", "\\u003e")}${exact ? "s" : "i"}]`;
1672
- }
1673
- class AttributeLocatorGetters {
1674
- getByAltText(text, options = {}) { return this.locator(attributeSelector("alt", text, options.exact)); }
1675
- getByPlaceholder(text, options = {}) { return this.locator(attributeSelector("placeholder", text, options.exact)); }
1676
- getByTestId(testId) { return this.locator(attributeSelector(testIdAttributeName, testId, true)); }
1677
- getByTitle(text, options = {}) { return this.locator(attributeSelector("title", text, options.exact)); }
1678
- }
1679
- for (const Container of [OmOPage, OmOFrame, FrameLocator]) {
1680
- for (const name of Object.getOwnPropertyNames(AttributeLocatorGetters.prototype)) {
1681
- if (name !== "constructor") Object.defineProperty(Container.prototype, name, Object.getOwnPropertyDescriptor(AttributeLocatorGetters.prototype, name));
1682
- }
1683
- }
1684
-
1685
- OmOPage.prototype.route = function (url, handler, options) {
1686
- return pageRoute(this, url, handler, options);
1687
- };
1688
- OmOPage.prototype.unroute = function (url, handler) {
1689
- return pageUnroute(this, url, handler);
1690
- };
1691
- OmOPage.prototype.unrouteAll = function () {
1692
- return pageUnrouteAll(this);
1693
- };
1694
-
1695
- export {
1696
- OmOKeyboard,
1697
- OmOMouse,
1698
- OmOPage,
1699
- BrowserCdpCommandError,
1700
- CdpClient,
1701
- ElementHandle,
1702
- FrameLocator,
1703
- FrameManager,
1704
- Locator,
1705
- ModifierState,
1706
- SessionManager,
1707
- UnsupportedOperationError,
1708
- takeSnapshot,
1709
- selectors,
1710
- };