oh-my-opencode 5.1.81 → 5.1.83
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/index.js +443 -276
- package/dist/cli-node/index.js +443 -276
- package/dist/hooks/claude-code-hooks/handlers/empty-hook-config.fixture.d.ts +1 -0
- package/dist/index.js +650 -431
- package/dist/shared/opencode-message-dir.d.ts +1 -1
- package/dist/skills/browser/references/owned-engine/README.md +4 -2
- package/dist/skills/browser/references/owned-engine/frames-and-humans.md +9 -3
- package/dist/skills/browser/runtime/omowright/index.js +8 -8
- package/dist/skills/browser/runtime/omowright/manifest.json +4 -4
- package/dist/skills/frontend/SKILL.md +4 -2
- package/dist/skills/frontend/references/perfection/state-and-flow.md +120 -0
- package/dist/skills/visual-qa/AGENTS.md +2 -1
- package/dist/skills/visual-qa/SKILL.md +43 -11
- package/dist/skills/visual-qa/references/behaviour-evidence.md +189 -0
- package/dist/tui.js +15 -15
- package/package.json +15 -15
- package/packages/lsp-core/src/lsp/client-key.ts +14 -0
- package/packages/lsp-core/src/lsp/client-startup.ts +139 -0
- package/packages/lsp-core/src/lsp/client-wrapper.ts +4 -4
- package/packages/lsp-core/src/lsp/config-loader.ts +15 -0
- package/packages/lsp-core/src/lsp/directory-diagnostics-group-scan.test.ts +388 -0
- package/packages/lsp-core/src/lsp/directory-diagnostics-mixed-typescript.test.ts +124 -0
- package/packages/lsp-core/src/lsp/directory-diagnostics.test.ts +4 -4
- package/packages/lsp-core/src/lsp/directory-diagnostics.ts +38 -41
- package/packages/lsp-core/src/lsp/directory-group-scan.ts +124 -0
- package/packages/lsp-core/src/lsp/directory-server-groups.ts +84 -0
- package/packages/lsp-core/src/lsp/manager-acquisition.test.ts +115 -0
- package/packages/lsp-core/src/lsp/manager-lifecycle.test.ts +9 -9
- package/packages/lsp-core/src/lsp/manager-max-clients.test.ts +41 -16
- package/packages/lsp-core/src/lsp/manager-reaping.test.ts +119 -0
- package/packages/lsp-core/src/lsp/manager-test-support.ts +108 -0
- package/packages/lsp-core/src/lsp/manager.ts +80 -249
- package/packages/lsp-core/src/lsp/native-typescript.ts +88 -0
- package/packages/lsp-core/src/lsp/server-installation.ts +15 -7
- package/packages/lsp-core/src/lsp/server-resolution-typescript-native.test.ts +327 -0
- package/packages/lsp-core/src/lsp/server-resolution.ts +28 -2
- package/packages/lsp-core/src/lsp/timer-provider.ts +17 -0
- package/packages/lsp-core/src/lsp/typescript-project-test-support.ts +52 -0
- package/packages/lsp-daemon/dist/cli.js +486 -310
- package/packages/lsp-daemon/dist/client.js +472 -296
- package/packages/lsp-daemon/dist/index.js +476 -300
- package/packages/lsp-tools-mcp/dist/cli.js +467 -291
- package/packages/lsp-tools-mcp/dist/lsp/manager.js +160 -193
- package/packages/lsp-tools-mcp/dist/mcp.js +467 -291
- package/packages/lsp-tools-mcp/dist/tools.js +467 -291
- package/packages/omo-codex/plugin/.codex-plugin/plugin.json +1 -1
- package/packages/omo-codex/plugin/components/bootstrap/hooks/hooks.json +1 -1
- package/packages/omo-codex/plugin/components/bootstrap/package.json +1 -1
- package/packages/omo-codex/plugin/components/comment-checker/hooks/hooks.json +1 -1
- package/packages/omo-codex/plugin/components/comment-checker/package.json +1 -1
- package/packages/omo-codex/plugin/components/git-bash/hooks/hooks.json +2 -2
- package/packages/omo-codex/plugin/components/git-bash/package.json +1 -1
- package/packages/omo-codex/plugin/components/lazycodex-executor-verify/hooks/hooks.json +1 -1
- package/packages/omo-codex/plugin/components/lazycodex-executor-verify/package.json +1 -1
- package/packages/omo-codex/plugin/components/lsp/dist/.omo-runtime-manifest.json +3 -3
- package/packages/omo-codex/plugin/components/lsp/dist/cli.js +478 -313
- package/packages/omo-codex/plugin/components/lsp/hooks/hooks.json +2 -2
- package/packages/omo-codex/plugin/components/lsp/package.json +1 -1
- package/packages/omo-codex/plugin/components/rules/hooks/hooks.json +4 -4
- package/packages/omo-codex/plugin/components/rules/package.json +1 -1
- package/packages/omo-codex/plugin/components/teammode/hooks/hooks.json +1 -1
- package/packages/omo-codex/plugin/components/teammode/package.json +1 -1
- package/packages/omo-codex/plugin/components/telemetry/hooks/hooks.json +1 -1
- package/packages/omo-codex/plugin/components/telemetry/package.json +1 -1
- package/packages/omo-codex/plugin/components/ultrawork/hooks/hooks.json +1 -1
- package/packages/omo-codex/plugin/components/ultrawork/package.json +1 -1
- package/packages/omo-codex/plugin/components/ulw-execute-continuation/hooks/hooks.json +1 -1
- package/packages/omo-codex/plugin/components/ulw-execute-continuation/package.json +1 -1
- package/packages/omo-codex/plugin/components/ulw-loop/hooks/hooks.json +5 -5
- package/packages/omo-codex/plugin/components/ulw-loop/package.json +1 -1
- package/packages/omo-codex/plugin/hooks/post-compact-resetting-git-bash-mcp-reminder.json +1 -1
- package/packages/omo-codex/plugin/hooks/post-compact-resetting-lsp-diagnostics-cache.json +1 -1
- package/packages/omo-codex/plugin/hooks/post-compact-resetting-project-rule-cache.json +1 -1
- package/packages/omo-codex/plugin/hooks/post-tool-use-checking-comments.json +1 -1
- package/packages/omo-codex/plugin/hooks/post-tool-use-checking-lsp-diagnostics.json +1 -1
- package/packages/omo-codex/plugin/hooks/post-tool-use-checking-thread-title-hygiene.json +1 -1
- package/packages/omo-codex/plugin/hooks/post-tool-use-matching-project-rules.json +1 -1
- package/packages/omo-codex/plugin/hooks/post-tool-use-recording-spawn-admission.json +1 -1
- package/packages/omo-codex/plugin/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json +1 -1
- package/packages/omo-codex/plugin/hooks/pre-tool-use-guarding-ulw-loop-spawns.json +1 -1
- package/packages/omo-codex/plugin/hooks/pre-tool-use-recommending-git-bash-mcp.json +1 -1
- package/packages/omo-codex/plugin/hooks/session-start-checking-auto-update.json +1 -1
- package/packages/omo-codex/plugin/hooks/session-start-checking-bootstrap-provisioning.json +1 -1
- package/packages/omo-codex/plugin/hooks/session-start-loading-project-rules.json +1 -1
- package/packages/omo-codex/plugin/hooks/session-start-recording-session-telemetry.json +1 -1
- package/packages/omo-codex/plugin/hooks/stop-checking-ulw-execute-continuation.json +1 -1
- package/packages/omo-codex/plugin/hooks/stop-checking-ulw-loop-resume.json +1 -1
- package/packages/omo-codex/plugin/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json +1 -1
- package/packages/omo-codex/plugin/hooks/user-prompt-submit-checking-ultrawork-trigger.json +1 -1
- package/packages/omo-codex/plugin/hooks/user-prompt-submit-checking-ulw-loop-steering.json +1 -1
- package/packages/omo-codex/plugin/hooks/user-prompt-submit-loading-project-rules.json +1 -1
- package/packages/omo-codex/plugin/package-lock.json +12 -12
- package/packages/omo-codex/plugin/package.json +1 -1
- package/packages/omo-codex/plugin/skills/browser/references/owned-engine/README.md +4 -2
- package/packages/omo-codex/plugin/skills/browser/references/owned-engine/frames-and-humans.md +9 -3
- package/packages/omo-codex/plugin/skills/browser/runtime/omowright/index.js +8 -8
- package/packages/omo-codex/plugin/skills/browser/runtime/omowright/manifest.json +4 -4
- package/packages/omo-codex/plugin/skills/frontend/SKILL.md +4 -2
- package/packages/omo-codex/plugin/skills/frontend/references/perfection/state-and-flow.md +120 -0
- package/packages/omo-codex/plugin/skills/visual-qa/AGENTS.md +2 -1
- package/packages/omo-codex/plugin/skills/visual-qa/SKILL.md +43 -11
- package/packages/omo-codex/plugin/skills/visual-qa/references/behaviour-evidence.md +189 -0
- package/packages/omo-codex/scripts/install-dist/install-local.mjs +2 -2
- package/packages/shared-skills/skills/browser/references/owned-engine/README.md +4 -2
- package/packages/shared-skills/skills/browser/references/owned-engine/frames-and-humans.md +9 -3
- package/packages/shared-skills/skills/browser/runtime/omowright/index.js +8 -8
- package/packages/shared-skills/skills/browser/runtime/omowright/manifest.json +4 -4
- package/packages/shared-skills/skills/frontend/SKILL.md +4 -2
- package/packages/shared-skills/skills/frontend/references/perfection/state-and-flow.md +120 -0
- package/packages/shared-skills/skills/visual-qa/AGENTS.md +2 -1
- package/packages/shared-skills/skills/visual-qa/SKILL.md +43 -11
- package/packages/shared-skills/skills/visual-qa/references/behaviour-evidence.md +189 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};import path from"node:path";async function openNtdll(){const{dlopen,ptr}=await import("bun:ffi");const systemRoot=process.env["SystemRoot"]||process.env["windir"]||"C:\\Windows";const{symbols}=dlopen(path.win32.join(systemRoot,"System32","ntdll.dll"),{NtCreateFile:{args:["buffer","u32","buffer","buffer","ptr","u32","u32","u32","u32","ptr","u32"],returns:"u32"},NtClose:{args:["u64"],returns:"u32"},RtlNtStatusToDosError:{args:["u32"],returns:"u32"}});return{symbols,ptr}}function loadNtdll(){ntdll??=openNtdll().catch((error)=>{ntdll=undefined;throw error});return ntdll}function nativeError(symbols,operation,lockPath,status){const error=symbols.RtlNtStatusToDosError(status);return Object.assign(new Error(`instance lock ${operation} failed for ${lockPath} (Windows error ${error}, NTSTATUS 0x${status.toString(16)})`),{code:"ERR_INSTANCE_LOCK"})}async function tryAcquireWindows(lockPath){const{symbols,ptr}=await loadNtdll();const filename=Buffer.from(`${path.toNamespacedPath(path.resolve(lockPath)).replace(/^\\\\\?\\/,"\\??\\")}\x00`,"utf16le");const name=Buffer.alloc(16);name.writeUInt16LE(filename.length-2,0);name.writeUInt16LE(filename.length,2);name.writeBigUInt64LE(BigInt(ptr(filename)),8);const attributes=Buffer.alloc(48);attributes.writeUInt32LE(48,0);attributes.writeBigUInt64LE(BigInt(ptr(name)),16);attributes.writeUInt32LE(64,24);const handleOut=Buffer.alloc(8);const ioStatus=Buffer.alloc(16);const status=symbols.NtCreateFile(handleOut,3222274048,attributes,ioStatus,null,128,0,3,96,null,0);if(status===3221225539)return null;if(status>=2147483648)throw nativeError(symbols,"NtCreateFile",lockPath,status);const handle=handleOut.readBigUInt64LE();return{release(){const closeStatus=symbols.NtClose(handle);if(closeStatus>=2147483648)throw nativeError(symbols,"NtClose",lockPath,closeStatus)}}}var ntdll;var init_lock_backend_win32_xbcm60vz=()=>{};import{createRequire}from"node:module";import path3 from"node:path";import{mkdir as mkdir4}from"node:fs/promises";import path2 from"node:path";import{mkdir,writeFile}from"node:fs/promises";import{createReadStream,promises}from"node:fs";import*as fs$16 from"node:fs/promises";import{spawn}from"node:child_process";import{tmpdir}from"node:os";import{readFileSync}from"node:fs";import{readFile}from"node:fs/promises";import{readFile as readFile2}from"node:fs/promises";import{randomUUID}from"node:crypto";import{isDeepStrictEqual}from"node:util";import{mkdir as mkdir3,writeFile as writeFile2}from"node:fs/promises";import path22 from"node:path";import{spawn as spawn3}from"node:child_process";import{finished}from"node:stream/promises";import{mkdirSync,readFileSync as readFileSync2,rmSync,writeFileSync}from"node:fs";import path5 from"node:path";import{setTimeout as sleep2}from"node:timers/promises";import{unlink as unlink2}from"node:fs/promises";import{setTimeout as sleep}from"node:timers/promises";import{spawn as spawn2}from"node:child_process";import{constants}from"node:fs";import{open as open2}from"node:fs/promises";import{execFile}from"node:child_process";import{readFile as readFile3}from"node:fs/promises";import path4 from"node:path";import{promisify}from"node:util";import{spawn as spawn4}from"node:child_process";import{createHash,randomUUID as randomUUID2}from"node:crypto";import{mkdir as mkdir5,open as open3,readFile as readFile6,readdir,rename,unlink as unlink3}from"node:fs/promises";import os from"node:os";import path8 from"node:path";import{watch}from"node:fs";import{readFile as readFile4,stat}from"node:fs/promises";import path6 from"node:path";import{execFile as execFile2}from"node:child_process";import{chmod,mkdtemp,readFile as readFile5,rm,stat as stat2}from"node:fs/promises";import{tmpdir as tmpdir2}from"node:os";import path7 from"node:path";import{promisify as promisify2}from"node:util";import{readFile as readFile7}from"node:fs/promises";import{connect as connectTcp}from"node:net";import path10 from"node:path";import{existsSync}from"node:fs";import{homedir}from"node:os";import path9 from"node:path";import{randomInt}from"node:crypto";import{mkdir as mkdir6,open as open4,readFile as readFile8,unlink as unlink4}from"node:fs/promises";import{globSync}from"node:fs";import os2 from"node:os";import path11 from"node:path";import{spawn as spawn5}from"node:child_process";import{mkdtempSync,writeFileSync as writeFileSync2,rmSync as rmSync2}from"node:fs";import{tmpdir as tmpdir3}from"node:os";import path12 from"node:path";import{randomUUID as randomUUID3}from"node:crypto";import path16 from"node:path";import{mkdir as mkdir8,open as open5,readFile as readFile9,readlink,realpath,rename as rename2,lstat,chmod as chmod2}from"node:fs/promises";import{homedir as homedir2}from"node:os";import{TextDecoder as TextDecoder2}from"node:util";import{mkdirSync as mkdirSync2}from"node:fs";import path14 from"node:path";import{tmpdir as tmpdir4}from"node:os";import{existsSync as existsSync2,readFileSync as readFileSync3}from"node:fs";import path13 from"node:path";import{execFile as execFile3}from"node:child_process";import{existsSync as existsSync3}from"node:fs";import{mkdir as mkdir7,rmdir,unlink as unlink5}from"node:fs/promises";import path15 from"node:path";import{mkdir as mkdir9,writeFile as writeFile3}from"node:fs/promises";import path17 from"node:path";import{connect as connect2}from"node:net";import{existsSync as existsSync5,readdirSync}from"node:fs";import path19 from"node:path";import{randomBytes}from"node:crypto";import{existsSync as existsSync4,readFileSync as readFileSync4}from"node:fs";import{homedir as homedir3}from"node:os";import path18 from"node:path";import{spawn as spawn6}from"node:child_process";import{createHash as createHash2}from"node:crypto";import{spawn as spawnChild}from"node:child_process";import{randomBytes as randomBytes2}from"node:crypto";import{existsSync as existsSync8,readFileSync as readFileSync6}from"node:fs";import{homedir as homedir6}from"node:os";import path222 from"node:path";import{spawn as spawn8}from"node:child_process";import{existsSync as existsSync6,readFileSync as readFileSync5,rmSync as rmSync3,writeFileSync as writeFileSync3}from"node:fs";import{homedir as homedir4}from"node:os";import path20 from"node:path";import{spawn as spawn7}from"node:child_process";import{existsSync as existsSync7}from"node:fs";import{homedir as homedir5}from"node:os";import path21 from"node:path";import{randomInt as randomInt2}from"node:crypto";import{existsSync as existsSync9,mkdirSync as mkdirSync3,readFileSync as readFileSync7,rmSync as rmSync4,writeFileSync as writeFileSync4}from"node:fs";import{spawn as spawn9}from"node:child_process";import path23 from"node:path";import{execFile as execFile4}from"node:child_process";import{statSync}from"node:fs";import{homedir as homedir7}from"node:os";import path24 from"node:path";import{homedir as homedir8}from"node:os";import{existsSync as existsSync10,readFileSync as readFileSync8}from"node:fs";var __create=Object.create;var __getProtoOf=Object.getPrototypeOf;var __defProp=Object.defineProperty;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node;var __toESMCache_esm;var __toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap;var cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};const to=isNodeMode||!mod||!mod.__esModule||!__hasOwnProp.call(mod,"default")?__defProp(target,"default",{value:mod,enumerable:true}):target;if(mod&&typeof mod==="object"||typeof mod==="function"){for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:true})}if(canCache)cache.set(mod,to);return to};var __commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true,configurable:true,set:__exportSetter.bind(all,name)})};var __require=createRequire(import.meta.url);var require_constants=__commonJS(function(exports,module){var BINARY_TYPES=["nodebuffer","arraybuffer","fragments"];var hasBlob=typeof Blob!=="undefined";if(hasBlob)BINARY_TYPES.push("blob");module.exports={BINARY_TYPES,CLOSE_TIMEOUT:30000,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var require_buffer_util=__commonJS(function(exports,module){var{EMPTY_BUFFER}=require_constants();var FastBuffer=Buffer[Symbol.species];function concat(list,totalLength){if(list.length===0)return EMPTY_BUFFER;if(list.length===1)return list[0];const target=Buffer.allocUnsafe(totalLength);let offset=0;for(let i=0;i<list.length;i++){const buf=list[i];target.set(buf,offset);offset+=buf.length}if(offset<totalLength){return new FastBuffer(target.buffer,target.byteOffset,offset)}return target}function _mask(source,mask,output,offset,length){for(let i=0;i<length;i++){output[offset+i]=source[i]^mask[i&3]}}function _unmask(buffer,mask){for(let i=0;i<buffer.length;i++){buffer[i]^=mask[i&3]}}function toArrayBuffer(buf){if(buf.length===buf.buffer.byteLength){return buf.buffer}return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.length)}function toBuffer(data){toBuffer.readOnly=true;if(Buffer.isBuffer(data))return data;let buf;if(data instanceof ArrayBuffer){buf=new FastBuffer(data)}else if(ArrayBuffer.isView(data)){buf=new FastBuffer(data.buffer,data.byteOffset,data.byteLength)}else{buf=Buffer.from(data);toBuffer.readOnly=false}return buf}module.exports={concat,mask:_mask,toArrayBuffer,toBuffer,unmask:_unmask};if(!process.env.WS_NO_BUFFER_UTIL){try{const bufferUtil=(()=>{throw new Error("Cannot require module "+"bufferutil")})();module.exports.mask=function(source,mask2,output,offset,length){if(length<48)_mask(source,mask2,output,offset,length);else bufferUtil.mask(source,mask2,output,offset,length)};module.exports.unmask=function(buffer,mask){if(buffer.length<32)_unmask(buffer,mask);else bufferUtil.unmask(buffer,mask)}}catch(e){}}});var require_limiter=__commonJS(function(exports,module){var kDone=Symbol("kDone");var kRun=Symbol("kRun");class Limiter{constructor(concurrency){this[kDone]=()=>{this.pending--;this[kRun]()};this.concurrency=concurrency||Infinity;this.jobs=[];this.pending=0}add(job){this.jobs.push(job);this[kRun]()}[kRun](){if(this.pending===this.concurrency)return;if(this.jobs.length){const job=this.jobs.shift();this.pending++;job(this[kDone])}}}module.exports=Limiter});var require_permessage_deflate=__commonJS(function(exports,module){var zlib=__require("zlib");var bufferUtil=require_buffer_util();var Limiter=require_limiter();var{kStatusCode}=require_constants();var FastBuffer=Buffer[Symbol.species];var TRAILER=Buffer.from([0,0,255,255]);var kPerMessageDeflate=Symbol("permessage-deflate");var kTotalLength=Symbol("total-length");var kCallback=Symbol("callback");var kBuffers=Symbol("buffers");var kError=Symbol("error");var zlibLimiter;class PerMessageDeflate{constructor(options){this._options=options||{};this._threshold=this._options.threshold!==undefined?this._options.threshold:1024;this._maxPayload=this._options.maxPayload|0;this._isServer=!!this._options.isServer;this._deflate=null;this._inflate=null;this.params=null;if(!zlibLimiter){const concurrency=this._options.concurrencyLimit!==undefined?this._options.concurrencyLimit:10;zlibLimiter=new Limiter(concurrency)}}static get extensionName(){return"permessage-deflate"}offer(){const params={};if(this._options.serverNoContextTakeover){params.server_no_context_takeover=true}if(this._options.clientNoContextTakeover){params.client_no_context_takeover=true}if(this._options.serverMaxWindowBits){params.server_max_window_bits=this._options.serverMaxWindowBits}if(this._options.clientMaxWindowBits){params.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits==null){params.client_max_window_bits=true}return params}accept(configurations){configurations=this.normalizeParams(configurations);this.params=this._isServer?this.acceptAsServer(configurations):this.acceptAsClient(configurations);return this.params}cleanup(){if(this._inflate){this._inflate.close();this._inflate=null}if(this._deflate){const callback=this._deflate[kCallback];this._deflate.close();this._deflate=null;if(callback){callback(new Error("The deflate stream was closed while data was being processed"))}}}acceptAsServer(offers){const opts=this._options;const accepted=offers.find((params)=>{if(opts.serverNoContextTakeover===false&¶ms.server_no_context_takeover||params.server_max_window_bits&&(opts.serverMaxWindowBits===false||typeof opts.serverMaxWindowBits==="number"&&opts.serverMaxWindowBits>params.server_max_window_bits)||typeof opts.clientMaxWindowBits==="number"&&(typeof params.client_max_window_bits==="number"?opts.clientMaxWindowBits>params.client_max_window_bits:!params.client_max_window_bits)){return false}return true});if(!accepted){throw new Error("None of the extension offers can be accepted")}if(opts.serverNoContextTakeover){accepted.server_no_context_takeover=true}if(opts.clientNoContextTakeover){accepted.client_no_context_takeover=true}if(typeof opts.serverMaxWindowBits==="number"){accepted.server_max_window_bits=opts.serverMaxWindowBits}if(typeof opts.clientMaxWindowBits==="number"){accepted.client_max_window_bits=opts.clientMaxWindowBits}else if(accepted.client_max_window_bits===true||opts.clientMaxWindowBits===false){delete accepted.client_max_window_bits}return accepted}acceptAsClient(response){const params=response[0];if(this._options.clientNoContextTakeover===false&¶ms.client_no_context_takeover){throw new Error('Unexpected parameter "client_no_context_takeover"')}if(!params.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number"){params.client_max_window_bits=this._options.clientMaxWindowBits}}else if(this._options.clientMaxWindowBits===false||typeof this._options.clientMaxWindowBits==="number"&¶ms.client_max_window_bits>this._options.clientMaxWindowBits){throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}return params}normalizeParams(configurations){configurations.forEach((params)=>{Object.keys(params).forEach((key)=>{let value=params[key];if(value.length>1){throw new Error(`Parameter "${key}" must have only a single value`)}value=value[0];if(key==="client_max_window_bits"){if(value!==true){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(!this._isServer){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else if(key==="server_max_window_bits"){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(key==="client_no_context_takeover"||key==="server_no_context_takeover"){if(value!==true){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else{throw new Error(`Unknown parameter "${key}"`)}params[key]=value})});return configurations}decompress(data,fin,callback){zlibLimiter.add((done)=>{this._decompress(data,fin,(err,result)=>{done();callback(err,result)})})}compress(data,fin,callback){zlibLimiter.add((done)=>{this._compress(data,fin,(err,result)=>{done();callback(err,result)})})}_decompress(data,fin,callback){const endpoint=this._isServer?"client":"server";if(!this._inflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._inflate=zlib.createInflateRaw({...this._options.zlibInflateOptions,windowBits});this._inflate[kPerMessageDeflate]=this;this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];this._inflate.on("error",inflateOnError);this._inflate.on("data",inflateOnData)}this._inflate[kCallback]=callback;this._inflate.write(data);if(fin)this._inflate.write(TRAILER);this._inflate.flush(()=>{const err=this._inflate[kError];if(err){this._inflate.close();this._inflate=null;callback(err);return}const data=bufferUtil.concat(this._inflate[kBuffers],this._inflate[kTotalLength]);if(this._inflate._readableState.endEmitted){this._inflate.close();this._inflate=null}else{this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._inflate.reset()}}callback(null,data)})}_compress(data,fin,callback){const endpoint=this._isServer?"server":"client";if(!this._deflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._deflate=zlib.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits});this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];this._deflate.on("data",deflateOnData)}this._deflate[kCallback]=callback;this._deflate.write(data);this._deflate.flush(zlib.Z_SYNC_FLUSH,()=>{if(!this._deflate){return}let data=bufferUtil.concat(this._deflate[kBuffers],this._deflate[kTotalLength]);if(fin){data=new FastBuffer(data.buffer,data.byteOffset,data.length-4)}this._deflate[kCallback]=null;this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._deflate.reset()}callback(null,data)})}}module.exports=PerMessageDeflate;function deflateOnData(chunk){this[kBuffers].push(chunk);this[kTotalLength]+=chunk.length}function inflateOnData(chunk){this[kTotalLength]+=chunk.length;if(this[kPerMessageDeflate]._maxPayload<1||this[kTotalLength]<=this[kPerMessageDeflate]._maxPayload){this[kBuffers].push(chunk);return}this[kError]=new RangeError("Max payload size exceeded");this[kError].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";this[kError][kStatusCode]=1009;this.removeListener("data",inflateOnData);this.reset()}function inflateOnError(err){this[kPerMessageDeflate]._inflate=null;if(this[kError]){this[kCallback](this[kError]);return}err[kStatusCode]=1007;this[kCallback](err)}});var require_validation=__commonJS(function(exports,module){var{isUtf8}=__require("buffer");var{hasBlob}=require_constants();var tokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function isValidStatusCode(code){return code>=1000&&code<=1014&&code!==1004&&code!==1005&&code!==1006||code>=3000&&code<=4999}function _isValidUTF8(buf){const len=buf.length;let i=0;while(i<len){if((buf[i]&128)===0){i++}else if((buf[i]&224)===192){if(i+1===len||(buf[i+1]&192)!==128||(buf[i]&254)===192){return false}i+=2}else if((buf[i]&240)===224){if(i+2>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||buf[i]===224&&(buf[i+1]&224)===128||buf[i]===237&&(buf[i+1]&224)===160){return false}i+=3}else if((buf[i]&248)===240){if(i+3>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||(buf[i+3]&192)!==128||buf[i]===240&&(buf[i+1]&240)===128||buf[i]===244&&buf[i+1]>143||buf[i]>244){return false}i+=4}else{return false}}return true}function isBlob(value){return hasBlob&&typeof value==="object"&&typeof value.arrayBuffer==="function"&&typeof value.type==="string"&&typeof value.stream==="function"&&(value[Symbol.toStringTag]==="Blob"||value[Symbol.toStringTag]==="File")}module.exports={isBlob,isValidStatusCode,isValidUTF8:_isValidUTF8,tokenChars};if(isUtf8){module.exports.isValidUTF8=function(buf){return buf.length<24?_isValidUTF8(buf):isUtf8(buf)}}else if(!process.env.WS_NO_UTF_8_VALIDATE){try{const isValidUTF8=(()=>{throw new Error("Cannot require module "+"utf-8-validate")})();module.exports.isValidUTF8=function(buf){return buf.length<32?_isValidUTF8(buf):isValidUTF8(buf)}}catch(e){}}});var require_receiver=__commonJS(function(exports,module){var{Writable}=__require("stream");var PerMessageDeflate=require_permessage_deflate();var{BINARY_TYPES,EMPTY_BUFFER,kStatusCode,kWebSocket}=require_constants();var{concat,toArrayBuffer,unmask}=require_buffer_util();var{isValidStatusCode,isValidUTF8}=require_validation();var FastBuffer=Buffer[Symbol.species];var GET_INFO=0;var GET_PAYLOAD_LENGTH_16=1;var GET_PAYLOAD_LENGTH_64=2;var GET_MASK=3;var GET_DATA=4;var INFLATING=5;var DEFER_EVENT=6;class Receiver extends Writable{constructor(options={}){super();this._allowSynchronousEvents=options.allowSynchronousEvents!==undefined?options.allowSynchronousEvents:true;this._binaryType=options.binaryType||BINARY_TYPES[0];this._extensions=options.extensions||{};this._isServer=!!options.isServer;this._maxBufferedChunks=options.maxBufferedChunks|0;this._maxFragments=options.maxFragments|0;this._maxPayload=options.maxPayload|0;this._skipUTF8Validation=!!options.skipUTF8Validation;this[kWebSocket]=undefined;this._bufferedBytes=0;this._buffers=[];this._compressed=false;this._payloadLength=0;this._mask=undefined;this._fragmented=0;this._masked=false;this._fin=false;this._opcode=0;this._totalPayloadLength=0;this._messageLength=0;this._numFragments=0;this._fragments=[];this._errored=false;this._loop=false;this._state=GET_INFO}_write(chunk,encoding,cb){if(this._opcode===8&&this._state==GET_INFO)return cb();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){cb(this.createError(RangeError,"Too many buffered chunks",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=chunk.length;this._buffers.push(chunk);this.startLoop(cb)}consume(n){this._bufferedBytes-=n;if(n===this._buffers[0].length)return this._buffers.shift();if(n<this._buffers[0].length){const buf=this._buffers[0];this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n);return new FastBuffer(buf.buffer,buf.byteOffset,n)}const dst=Buffer.allocUnsafe(n);do{const buf=this._buffers[0];const offset=dst.length-n;if(n>=buf.length){dst.set(this._buffers.shift(),offset)}else{dst.set(new Uint8Array(buf.buffer,buf.byteOffset,n),offset);this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n)}n-=buf.length}while(n>0);return dst}startLoop(cb){this._loop=true;do{switch(this._state){case GET_INFO:this.getInfo(cb);break;case GET_PAYLOAD_LENGTH_16:this.getPayloadLength16(cb);break;case GET_PAYLOAD_LENGTH_64:this.getPayloadLength64(cb);break;case GET_MASK:this.getMask();break;case GET_DATA:this.getData(cb);break;case INFLATING:case DEFER_EVENT:this._loop=false;return}}while(this._loop);if(!this._errored)cb()}getInfo(cb){if(this._bufferedBytes<2){this._loop=false;return}const buf=this.consume(2);if((buf[0]&48)!==0){const error=this.createError(RangeError,"RSV2 and RSV3 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_2_3");cb(error);return}const compressed=(buf[0]&64)===64;if(compressed&&!this._extensions[PerMessageDeflate.extensionName]){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}this._fin=(buf[0]&128)===128;this._opcode=buf[0]&15;this._payloadLength=buf[1]&127;if(this._opcode===0){if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(!this._fragmented){const error=this.createError(RangeError,"invalid opcode 0",true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._compressed=compressed}else if(this._opcode>7&&this._opcode<11){if(!this._fin){const error=this.createError(RangeError,"FIN must be set",true,1002,"WS_ERR_EXPECTED_FIN");cb(error);return}if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){const error=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,true,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");cb(error);return}}else{const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;this._masked=(buf[1]&128)===128;if(this._isServer){if(!this._masked){const error=this.createError(RangeError,"MASK must be set",true,1002,"WS_ERR_EXPECTED_MASK");cb(error);return}}else if(this._masked){const error=this.createError(RangeError,"MASK must be clear",true,1002,"WS_ERR_UNEXPECTED_MASK");cb(error);return}if(this._payloadLength===126)this._state=GET_PAYLOAD_LENGTH_16;else if(this._payloadLength===127)this._state=GET_PAYLOAD_LENGTH_64;else this.haveLength(cb)}getPayloadLength16(cb){if(this._bufferedBytes<2){this._loop=false;return}this._payloadLength=this.consume(2).readUInt16BE(0);this.haveLength(cb)}getPayloadLength64(cb){if(this._bufferedBytes<8){this._loop=false;return}const buf=this.consume(8);const num=buf.readUInt32BE(0);if(num>Math.pow(2,53-32)-1){const error=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",false,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");cb(error);return}this._payloadLength=num*Math.pow(2,32)+buf.readUInt32BE(4);this.haveLength(cb)}haveLength(cb){if(this._payloadLength&&this._opcode<8){this._totalPayloadLength+=this._payloadLength;if(this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}}if(this._masked)this._state=GET_MASK;else this._state=GET_DATA}getMask(){if(this._bufferedBytes<4){this._loop=false;return}this._mask=this.consume(4);this._state=GET_DATA}getData(cb){let data=EMPTY_BUFFER;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=false;return}data=this.consume(this._payloadLength);if(this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0){unmask(data,this._mask)}}if(this._opcode>7){this.controlMessage(data,cb);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){const error=this.createError(RangeError,"Too many message fragments",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");cb(error);return}if(this._compressed){this._state=INFLATING;this.decompress(data,cb);return}if(data.length){this._messageLength=this._totalPayloadLength;this._fragments.push(data)}this.dataMessage(cb)}decompress(data,cb){const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];perMessageDeflate.decompress(data,this._fin,(err,buf)=>{if(err)return cb(err);if(buf.length){this._messageLength+=buf.length;if(this._messageLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}this._fragments.push(buf)}this.dataMessage(cb);if(this._state===GET_INFO)this.startLoop(cb)})}dataMessage(cb){if(!this._fin){this._state=GET_INFO;return}const messageLength=this._messageLength;const fragments=this._fragments;this._totalPayloadLength=0;this._messageLength=0;this._fragmented=0;this._numFragments=0;this._fragments=[];if(this._opcode===2){let data;if(this._binaryType==="nodebuffer"){data=concat(fragments,messageLength)}else if(this._binaryType==="arraybuffer"){data=toArrayBuffer(concat(fragments,messageLength))}else if(this._binaryType==="blob"){data=new Blob(fragments)}else{data=fragments}if(this._allowSynchronousEvents){this.emit("message",data,true);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",data,true);this._state=GET_INFO;this.startLoop(cb)})}}else{const buf=concat(fragments,messageLength);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}if(this._state===INFLATING||this._allowSynchronousEvents){this.emit("message",buf,false);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",buf,false);this._state=GET_INFO;this.startLoop(cb)})}}}controlMessage(data,cb){if(this._opcode===8){if(data.length===0){this._loop=false;this.emit("conclude",1005,EMPTY_BUFFER);this.end()}else{const code=data.readUInt16BE(0);if(!isValidStatusCode(code)){const error=this.createError(RangeError,`invalid status code ${code}`,true,1002,"WS_ERR_INVALID_CLOSE_CODE");cb(error);return}const buf=new FastBuffer(data.buffer,data.byteOffset+2,data.length-2);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}this._loop=false;this.emit("conclude",code,buf);this.end()}this._state=GET_INFO;return}if(this._allowSynchronousEvents){this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO;this.startLoop(cb)})}}createError(ErrorCtor,message,prefix,statusCode,errorCode){this._loop=false;this._errored=true;const err=new ErrorCtor(prefix?`Invalid WebSocket frame: ${message}`:message);Error.captureStackTrace(err,this.createError);err.code=errorCode;err[kStatusCode]=statusCode;return err}}module.exports=Receiver});var require_sender=__commonJS(function(exports,module){var{Duplex}=__require("stream");var{randomFillSync}=__require("crypto");var{types:{isUint8Array}}=__require("util");var PerMessageDeflate=require_permessage_deflate();var{EMPTY_BUFFER,kWebSocket,NOOP}=require_constants();var{isBlob,isValidStatusCode}=require_validation();var{mask:applyMask,toBuffer}=require_buffer_util();var kByteLength=Symbol("kByteLength");var maskBuffer=Buffer.alloc(4);var RANDOM_POOL_SIZE=8*1024;var randomPool;var randomPoolPointer=RANDOM_POOL_SIZE;var DEFAULT=0;var DEFLATING=1;var GET_BLOB_DATA=2;class Sender{constructor(socket,extensions,generateMask){this._extensions=extensions||{};if(generateMask){this._generateMask=generateMask;this._maskBuffer=Buffer.alloc(4)}this._socket=socket;this._firstFragment=true;this._compress=false;this._bufferedBytes=0;this._queue=[];this._state=DEFAULT;this.onerror=NOOP;this[kWebSocket]=undefined}static frame(data,options){let mask;let merge=false;let offset=2;let skipMasking=false;if(options.mask){mask=options.maskBuffer||maskBuffer;if(options.generateMask){options.generateMask(mask)}else{if(randomPoolPointer===RANDOM_POOL_SIZE){if(randomPool===undefined){randomPool=Buffer.alloc(RANDOM_POOL_SIZE)}randomFillSync(randomPool,0,RANDOM_POOL_SIZE);randomPoolPointer=0}mask[0]=randomPool[randomPoolPointer++];mask[1]=randomPool[randomPoolPointer++];mask[2]=randomPool[randomPoolPointer++];mask[3]=randomPool[randomPoolPointer++]}skipMasking=(mask[0]|mask[1]|mask[2]|mask[3])===0;offset=6}let dataLength;if(typeof data==="string"){if((!options.mask||skipMasking)&&options[kByteLength]!==undefined){dataLength=options[kByteLength]}else{data=Buffer.from(data);dataLength=data.length}}else{dataLength=data.length;merge=options.mask&&options.readOnly&&!skipMasking}let payloadLength=dataLength;if(dataLength>=65536){offset+=8;payloadLength=127}else if(dataLength>125){offset+=2;payloadLength=126}const target=Buffer.allocUnsafe(merge?dataLength+offset:offset);target[0]=options.fin?options.opcode|128:options.opcode;if(options.rsv1)target[0]|=64;target[1]=payloadLength;if(payloadLength===126){target.writeUInt16BE(dataLength,2)}else if(payloadLength===127){target[2]=target[3]=0;target.writeUIntBE(dataLength,4,6)}if(!options.mask)return[target,data];target[1]|=128;target[offset-4]=mask[0];target[offset-3]=mask[1];target[offset-2]=mask[2];target[offset-1]=mask[3];if(skipMasking)return[target,data];if(merge){applyMask(data,mask,target,offset,dataLength);return[target]}applyMask(data,mask,data,0,dataLength);return[target,data]}close(code,data,mask,cb){let buf;if(code===undefined){buf=EMPTY_BUFFER}else if(typeof code!=="number"||!isValidStatusCode(code)){throw new TypeError("First argument must be a valid error code number")}else if(data===undefined||!data.length){buf=Buffer.allocUnsafe(2);buf.writeUInt16BE(code,0)}else{const length=Buffer.byteLength(data);if(length>123){throw new RangeError("The message must not be greater than 123 bytes")}buf=Buffer.allocUnsafe(2+length);buf.writeUInt16BE(code,0);if(typeof data==="string"){buf.write(data,2)}else if(isUint8Array(data)){buf.set(data,2)}else{throw new TypeError("Second argument must be a string or a Uint8Array")}}const options={[kByteLength]:buf.length,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:8,readOnly:false,rsv1:false};if(this._state!==DEFAULT){this.enqueue([this.dispatch,buf,false,options,cb])}else{this.sendFrame(Sender.frame(buf,options),cb)}}ping(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:9,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(Sender.frame(data,options),cb)}}pong(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:10,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(Sender.frame(data,options),cb)}}send(data,options,cb){const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];let opcode=options.binary?2:1;let rsv1=options.compress;let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(this._firstFragment){this._firstFragment=false;if(rsv1&&perMessageDeflate&&perMessageDeflate.params[perMessageDeflate._isServer?"server_no_context_takeover":"client_no_context_takeover"]){rsv1=byteLength>=perMessageDeflate._threshold}this._compress=rsv1}else{rsv1=false;opcode=0}if(options.fin)this._firstFragment=true;const opts={[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,this._compress,opts,cb])}else{this.getBlobData(data,this._compress,opts,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,this._compress,opts,cb])}else{this.dispatch(data,this._compress,opts,cb)}}getBlobData(blob,compress,options,cb){this._bufferedBytes+=options[kByteLength];this._state=GET_BLOB_DATA;blob.arrayBuffer().then((arrayBuffer)=>{if(this._socket.destroyed){const err=new Error("The socket was closed while the blob was being read");process.nextTick(callCallbacks,this,err,cb);return}this._bufferedBytes-=options[kByteLength];const data=toBuffer(arrayBuffer);if(!compress){this._state=DEFAULT;this.sendFrame(Sender.frame(data,options),cb);this.dequeue()}else{this.dispatch(data,compress,options,cb)}}).catch((err)=>{process.nextTick(onError,this,err,cb)})}dispatch(data,compress,options,cb){if(!compress){this.sendFrame(Sender.frame(data,options),cb);return}const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];this._bufferedBytes+=options[kByteLength];this._state=DEFLATING;perMessageDeflate.compress(data,options.fin,(_,buf)=>{if(this._socket.destroyed){const err=new Error("The socket was closed while data was being compressed");callCallbacks(this,err,cb);return}this._bufferedBytes-=options[kByteLength];this._state=DEFAULT;options.readOnly=false;this.sendFrame(Sender.frame(buf,options),cb);this.dequeue()})}dequeue(){while(this._state===DEFAULT&&this._queue.length){const params=this._queue.shift();this._bufferedBytes-=params[3][kByteLength];Reflect.apply(params[0],this,params.slice(1))}}enqueue(params){this._bufferedBytes+=params[3][kByteLength];this._queue.push(params)}sendFrame(list,cb){if(list.length===2){this._socket.cork();this._socket.write(list[0]);this._socket.write(list[1],cb);this._socket.uncork()}else{this._socket.write(list[0],cb)}}}module.exports=Sender;function callCallbacks(sender,err,cb){if(typeof cb==="function")cb(err);for(let i=0;i<sender._queue.length;i++){const params=sender._queue[i];const callback=params[params.length-1];if(typeof callback==="function")callback(err)}}function onError(sender,err,cb){callCallbacks(sender,err,cb);sender.onerror(err)}});var require_event_target=__commonJS(function(exports,module){var{kForOnEventAttribute,kListener}=require_constants();var kCode=Symbol("kCode");var kData=Symbol("kData");var kError=Symbol("kError");var kMessage=Symbol("kMessage");var kReason=Symbol("kReason");var kTarget=Symbol("kTarget");var kType=Symbol("kType");var kWasClean=Symbol("kWasClean");class Event{constructor(type){this[kTarget]=null;this[kType]=type}get target(){return this[kTarget]}get type(){return this[kType]}}Object.defineProperty(Event.prototype,"target",{enumerable:true});Object.defineProperty(Event.prototype,"type",{enumerable:true});class CloseEvent extends Event{constructor(type,options={}){super(type);this[kCode]=options.code===undefined?0:options.code;this[kReason]=options.reason===undefined?"":options.reason;this[kWasClean]=options.wasClean===undefined?false:options.wasClean}get code(){return this[kCode]}get reason(){return this[kReason]}get wasClean(){return this[kWasClean]}}Object.defineProperty(CloseEvent.prototype,"code",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"reason",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"wasClean",{enumerable:true});class ErrorEvent extends Event{constructor(type,options={}){super(type);this[kError]=options.error===undefined?null:options.error;this[kMessage]=options.message===undefined?"":options.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent.prototype,"error",{enumerable:true});Object.defineProperty(ErrorEvent.prototype,"message",{enumerable:true});class MessageEvent extends Event{constructor(type,options={}){super(type);this[kData]=options.data===undefined?null:options.data}get data(){return this[kData]}}Object.defineProperty(MessageEvent.prototype,"data",{enumerable:true});var EventTarget={addEventListener(type,handler,options={}){for(const listener of this.listeners(type)){if(!options[kForOnEventAttribute]&&listener[kListener]===handler&&!listener[kForOnEventAttribute]){return}}let wrapper;if(type==="message"){wrapper=function onMessage(data,isBinary){const event=new MessageEvent("message",{data:isBinary?data:data.toString()});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="close"){wrapper=function onClose(code,message){const event=new CloseEvent("close",{code,reason:message.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="error"){wrapper=function onError(error){const event=new ErrorEvent("error",{error,message:error.message});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="open"){wrapper=function onOpen(){const event=new Event("open");event[kTarget]=this;callListener(handler,this,event)}}else{return}wrapper[kForOnEventAttribute]=!!options[kForOnEventAttribute];wrapper[kListener]=handler;if(options.once){this.once(type,wrapper)}else{this.on(type,wrapper)}},removeEventListener(type,handler){for(const listener of this.listeners(type)){if(listener[kListener]===handler&&!listener[kForOnEventAttribute]){this.removeListener(type,listener);break}}}};module.exports={CloseEvent,ErrorEvent,Event,EventTarget,MessageEvent};function callListener(listener,thisArg,event){if(typeof listener==="object"&&listener.handleEvent){listener.handleEvent.call(listener,event)}else{listener.call(thisArg,event)}}});var require_extension=__commonJS(function(exports,module){var{tokenChars}=require_validation();function push(dest,name,elem){if(dest[name]===undefined)dest[name]=[elem];else dest[name].push(elem)}function parse(header){const offers=Object.create(null);let params=Object.create(null);let mustUnescape=false;let isEscaping=false;let inQuotes=false;let extensionName;let paramName;let start=-1;let code=-1;let end=-1;let i=0;for(;i<header.length;i++){code=header.charCodeAt(i);if(extensionName===undefined){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;const name=header.slice(start,end);if(code===44){push(offers,name,params);params=Object.create(null)}else{extensionName=name}start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(paramName===undefined){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(code===32||code===9){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;push(params,header.slice(start,end),true);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=undefined}start=end=-1}else if(code===61&&start!==-1&&end===-1){paramName=header.slice(start,i);start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else{if(isEscaping){if(tokenChars[code]!==1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(start===-1)start=i;else if(!mustUnescape)mustUnescape=true;isEscaping=false}else if(inQuotes){if(tokenChars[code]===1){if(start===-1)start=i}else if(code===34&&start!==-1){inQuotes=false;end=i}else if(code===92){isEscaping=true}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(code===34&&header.charCodeAt(i-1)===61){inQuotes=true}else if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(start!==-1&&(code===32||code===9)){if(end===-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;let value=header.slice(start,end);if(mustUnescape){value=value.replace(/\\/g,"");mustUnescape=false}push(params,paramName,value);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=undefined}paramName=undefined;start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}}if(start===-1||inQuotes||code===32||code===9){throw new SyntaxError("Unexpected end of input")}if(end===-1)end=i;const token=header.slice(start,end);if(extensionName===undefined){push(offers,token,params)}else{if(paramName===undefined){push(params,token,true)}else if(mustUnescape){push(params,paramName,token.replace(/\\/g,""))}else{push(params,paramName,token)}push(offers,extensionName,params)}return offers}function format(extensions){return Object.keys(extensions).map((extension)=>{let configurations=extensions[extension];if(!Array.isArray(configurations))configurations=[configurations];return configurations.map((params)=>{return[extension].concat(Object.keys(params).map((k)=>{let values=params[k];if(!Array.isArray(values))values=[values];return values.map((v)=>v===true?k:`${k}=${v}`).join("; ")})).join("; ")}).join(", ")}).join(", ")}module.exports={format,parse}});var require_websocket=__commonJS(function(exports,module){var EventEmitter=__require("events");var https=__require("https");var http=__require("http");var net=__require("net");var tls=__require("tls");var{randomBytes,createHash}=__require("crypto");var{Duplex,Readable}=__require("stream");var{URL:URL2}=__require("url");var PerMessageDeflate=require_permessage_deflate();var Receiver=require_receiver();var Sender=require_sender();var{isBlob}=require_validation();var{BINARY_TYPES,CLOSE_TIMEOUT,EMPTY_BUFFER,GUID,kForOnEventAttribute,kListener,kStatusCode,kWebSocket,NOOP}=require_constants();var{EventTarget:{addEventListener,removeEventListener}}=require_event_target();var{format,parse}=require_extension();var{toBuffer}=require_buffer_util();var kAborted=Symbol("kAborted");var protocolVersions=[8,13];var readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"];var subprotocolRegex=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class WebSocket extends EventEmitter{constructor(address,protocols,options){super();this._binaryType=BINARY_TYPES[0];this._closeCode=1006;this._closeFrameReceived=false;this._closeFrameSent=false;this._closeMessage=EMPTY_BUFFER;this._closeTimer=null;this._errorEmitted=false;this._extensions={};this._paused=false;this._protocol="";this._readyState=WebSocket.CONNECTING;this._receiver=null;this._sender=null;this._socket=null;if(address!==null){this._bufferedAmount=0;this._isServer=false;this._redirects=0;if(protocols===undefined){protocols=[]}else if(!Array.isArray(protocols)){if(typeof protocols==="object"&&protocols!==null){options=protocols;protocols=[]}else{protocols=[protocols]}}initAsClient(this,address,protocols,options)}else{this._autoPong=options.autoPong;this._closeTimeout=options.closeTimeout;this._isServer=true}}get binaryType(){return this._binaryType}set binaryType(type){if(!BINARY_TYPES.includes(type))return;this._binaryType=type;if(this._receiver)this._receiver._binaryType=type}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(socket,head,options){const receiver=new Receiver({allowSynchronousEvents:options.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:options.maxBufferedChunks,maxFragments:options.maxFragments,maxPayload:options.maxPayload,skipUTF8Validation:options.skipUTF8Validation});const sender=new Sender(socket,this._extensions,options.generateMask);this._receiver=receiver;this._sender=sender;this._socket=socket;receiver[kWebSocket]=this;sender[kWebSocket]=this;socket[kWebSocket]=this;receiver.on("conclude",receiverOnConclude);receiver.on("drain",receiverOnDrain);receiver.on("error",receiverOnError);receiver.on("message",receiverOnMessage);receiver.on("ping",receiverOnPing);receiver.on("pong",receiverOnPong);sender.onerror=senderOnError;if(socket.setTimeout)socket.setTimeout(0);if(socket.setNoDelay)socket.setNoDelay();if(head.length>0)socket.unshift(head);socket.on("close",socketOnClose);socket.on("data",socketOnData);socket.on("end",socketOnEnd);socket.on("error",socketOnError);this._readyState=WebSocket.OPEN;this.emit("open")}emitClose(){if(!this._socket){this._readyState=WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[PerMessageDeflate.extensionName]){this._extensions[PerMessageDeflate.extensionName].cleanup()}this._receiver.removeAllListeners();this._readyState=WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage)}close(code,data){if(this.readyState===WebSocket.CLOSED)return;if(this.readyState===WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this.readyState===WebSocket.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)){this._socket.end()}return}this._readyState=WebSocket.CLOSING;this._sender.close(code,data,!this._isServer,(err)=>{if(err)return;this._closeFrameSent=true;if(this._closeFrameReceived||this._receiver._writableState.errorEmitted){this._socket.end()}});setCloseTimer(this)}pause(){if(this.readyState===WebSocket.CONNECTING||this.readyState===WebSocket.CLOSED){return}this._paused=true;this._socket.pause()}ping(data,mask,cb){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=undefined}else if(typeof mask==="function"){cb=mask;mask=undefined}if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===undefined)mask=!this._isServer;this._sender.ping(data||EMPTY_BUFFER,mask,cb)}pong(data,mask,cb){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=undefined}else if(typeof mask==="function"){cb=mask;mask=undefined}if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===undefined)mask=!this._isServer;this._sender.pong(data||EMPTY_BUFFER,mask,cb)}resume(){if(this.readyState===WebSocket.CONNECTING||this.readyState===WebSocket.CLOSED){return}this._paused=false;if(!this._receiver._writableState.needDrain)this._socket.resume()}send(data,options,cb){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof options==="function"){cb=options;options={}}if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,data,cb);return}const opts={binary:typeof data!=="string",mask:!this._isServer,compress:true,fin:true,...options};if(!this._extensions[PerMessageDeflate.extensionName]){opts.compress=false}this._sender.send(data||EMPTY_BUFFER,opts,cb)}terminate(){if(this.readyState===WebSocket.CLOSED)return;if(this.readyState===WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this._socket){this._readyState=WebSocket.CLOSING;this._socket.destroy()}}}Object.defineProperty(WebSocket,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket.prototype,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket.prototype,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket.prototype,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});Object.defineProperty(WebSocket.prototype,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((property)=>{Object.defineProperty(WebSocket.prototype,property,{enumerable:true})});["open","error","close","message"].forEach((method)=>{Object.defineProperty(WebSocket.prototype,`on${method}`,{enumerable:true,get(){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute])return listener[kListener]}return null},set(handler){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute]){this.removeListener(method,listener);break}}if(typeof handler!=="function")return;this.addEventListener(method,handler,{[kForOnEventAttribute]:true})}})});WebSocket.prototype.addEventListener=addEventListener;WebSocket.prototype.removeEventListener=removeEventListener;module.exports=WebSocket;function initAsClient(websocket,address,protocols,options){const opts={allowSynchronousEvents:true,autoPong:true,closeTimeout:CLOSE_TIMEOUT,protocolVersion:protocolVersions[1],maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:true,followRedirects:false,maxRedirects:10,...options,socketPath:undefined,hostname:undefined,protocol:undefined,timeout:undefined,method:"GET",host:undefined,path:undefined,port:undefined};websocket._autoPong=opts.autoPong;websocket._closeTimeout=opts.closeTimeout;if(!protocolVersions.includes(opts.protocolVersion)){throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} `+`(supported versions: ${protocolVersions.join(", ")})`)}let parsedUrl;if(address instanceof URL2){parsedUrl=address}else{try{parsedUrl=new URL2(address)}catch{throw new SyntaxError(`Invalid URL: ${address}`)}}if(parsedUrl.protocol==="http:"){parsedUrl.protocol="ws:"}else if(parsedUrl.protocol==="https:"){parsedUrl.protocol="wss:"}websocket._url=parsedUrl.href;const isSecure=parsedUrl.protocol==="wss:";const isIpcUrl=parsedUrl.protocol==="ws+unix:";let invalidUrlMessage;if(parsedUrl.protocol!=="ws:"&&!isSecure&&!isIpcUrl){invalidUrlMessage=`The URL's protocol must be one of "ws:", "wss:", `+'"http:", "https:", or "ws+unix:"'}else if(isIpcUrl&&!parsedUrl.pathname){invalidUrlMessage="The URL's pathname is empty"}else if(parsedUrl.hash){invalidUrlMessage="The URL contains a fragment identifier"}if(invalidUrlMessage){const err=new SyntaxError(invalidUrlMessage);if(websocket._redirects===0){throw err}else{emitErrorAndClose(websocket,err);return}}const defaultPort=isSecure?443:80;const key=randomBytes(16).toString("base64");const request3=isSecure?https.request:http.request;const protocolSet=new Set;let perMessageDeflate;opts.createConnection=opts.createConnection||(isSecure?tlsConnect:netConnect);opts.defaultPort=opts.defaultPort||defaultPort;opts.port=parsedUrl.port||defaultPort;opts.host=parsedUrl.hostname.startsWith("[")?parsedUrl.hostname.slice(1,-1):parsedUrl.hostname;opts.headers={...opts.headers,"Sec-WebSocket-Version":opts.protocolVersion,"Sec-WebSocket-Key":key,Connection:"Upgrade",Upgrade:"websocket"};opts.path=parsedUrl.pathname+parsedUrl.search;opts.timeout=opts.handshakeTimeout;if(opts.perMessageDeflate){perMessageDeflate=new PerMessageDeflate({...opts.perMessageDeflate,isServer:false,maxPayload:opts.maxPayload});opts.headers["Sec-WebSocket-Extensions"]=format({[PerMessageDeflate.extensionName]:perMessageDeflate.offer()})}if(protocols.length){for(const protocol of protocols){if(typeof protocol!=="string"||!subprotocolRegex.test(protocol)||protocolSet.has(protocol)){throw new SyntaxError("An invalid or duplicated subprotocol was specified")}protocolSet.add(protocol)}opts.headers["Sec-WebSocket-Protocol"]=protocols.join(",")}if(opts.origin){if(opts.protocolVersion<13){opts.headers["Sec-WebSocket-Origin"]=opts.origin}else{opts.headers.Origin=opts.origin}}if(parsedUrl.username||parsedUrl.password){opts.auth=`${parsedUrl.username}:${parsedUrl.password}`}if(isIpcUrl){const parts=opts.path.split(":");opts.socketPath=parts[0];opts.path=parts[1]}let req;if(opts.followRedirects){if(websocket._redirects===0){websocket._originalIpc=isIpcUrl;websocket._originalSecure=isSecure;websocket._originalHostOrSocketPath=isIpcUrl?opts.socketPath:parsedUrl.host;const headers=options&&options.headers;options={...options,headers:{}};if(headers){for(const[key,value]of Object.entries(headers)){options.headers[key.toLowerCase()]=value}}}else if(websocket.listenerCount("redirect")===0){const isSameHost=isIpcUrl?websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:false:websocket._originalIpc?false:parsedUrl.host===websocket._originalHostOrSocketPath;if(!isSameHost||websocket._originalSecure&&!isSecure){delete opts.headers.authorization;delete opts.headers.cookie;if(!isSameHost)delete opts.headers.host;opts.auth=undefined}}if(opts.auth&&!options.headers.authorization){options.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64")}req=websocket._req=request3(opts);if(websocket._redirects){websocket.emit("redirect",websocket.url,req)}}else{req=websocket._req=request3(opts)}if(opts.timeout){req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")})}req.on("error",(err)=>{if(req===null||req[kAborted])return;req=websocket._req=null;emitErrorAndClose(websocket,err)});req.on("response",(res)=>{const location2=res.headers.location;const statusCode=res.statusCode;if(location2&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL2(location2,address)}catch(e){const err=new SyntaxError(`Invalid URL: ${location2}`);emitErrorAndClose(websocket,err);return}initAsClient(websocket,addr,protocols,options)}else if(!websocket.emit("unexpected-response",req,res)){abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}});req.on("upgrade",(res,socket,head)=>{websocket.emit("upgrade",res);if(websocket.readyState!==WebSocket.CONNECTING)return;req=websocket._req=null;const upgrade=res.headers.upgrade;if(upgrade===undefined||upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}const digest=createHash("sha1").update(key+GUID).digest("base64");if(res.headers["sec-websocket-accept"]!==digest){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}const serverProt=res.headers["sec-websocket-protocol"];let protError;if(serverProt!==undefined){if(!protocolSet.size){protError="Server sent a subprotocol but none was requested"}else if(!protocolSet.has(serverProt)){protError="Server sent an invalid subprotocol"}}else if(protocolSet.size){protError="Server sent no subprotocol"}if(protError){abortHandshake(websocket,socket,protError);return}if(serverProt)websocket._protocol=serverProt;const secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==undefined){if(!perMessageDeflate){const message="Server sent a Sec-WebSocket-Extensions header but no extension "+"was requested";abortHandshake(websocket,socket,message);return}let extensions;try{extensions=parse(secWebSocketExtensions)}catch(err){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}const extensionNames=Object.keys(extensions);if(extensionNames.length!==1||extensionNames[0]!==PerMessageDeflate.extensionName){const message="Server indicated an extension that was not requested";abortHandshake(websocket,socket,message);return}try{perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName])}catch(err){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}websocket._extensions[PerMessageDeflate.extensionName]=perMessageDeflate}websocket.setSocket(socket,head,{allowSynchronousEvents:opts.allowSynchronousEvents,generateMask:opts.generateMask,maxBufferedChunks:opts.maxBufferedChunks,maxFragments:opts.maxFragments,maxPayload:opts.maxPayload,skipUTF8Validation:opts.skipUTF8Validation})});if(opts.finishRequest){opts.finishRequest(req,websocket)}else{req.end()}}function emitErrorAndClose(websocket,err){websocket._readyState=WebSocket.CLOSING;websocket._errorEmitted=true;websocket.emit("error",err);websocket.emitClose()}function netConnect(options){options.path=options.socketPath;return net.connect(options)}function tlsConnect(options){options.path=undefined;if(!options.servername&&options.servername!==""){options.servername=net.isIP(options.host)?"":options.host}return tls.connect(options)}function abortHandshake(websocket,stream,message){websocket._readyState=WebSocket.CLOSING;const err=new Error(message);Error.captureStackTrace(err,abortHandshake);if(stream.setHeader){stream[kAborted]=true;stream.abort();if(stream.socket&&!stream.socket.destroyed){stream.socket.destroy()}process.nextTick(emitErrorAndClose,websocket,err)}else{stream.destroy(err);stream.once("error",websocket.emit.bind(websocket,"error"));stream.once("close",websocket.emitClose.bind(websocket))}}function sendAfterClose(websocket,data,cb){if(data){const length=isBlob(data)?data.size:toBuffer(data).length;if(websocket._socket)websocket._sender._bufferedBytes+=length;else websocket._bufferedAmount+=length}if(cb){const err=new Error(`WebSocket is not open: readyState ${websocket.readyState} `+`(${readyStates[websocket.readyState]})`);process.nextTick(cb,err)}}function receiverOnConclude(code,reason){const websocket=this[kWebSocket];websocket._closeFrameReceived=true;websocket._closeMessage=reason;websocket._closeCode=code;if(websocket._socket[kWebSocket]===undefined)return;websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);if(code===1005)websocket.close();else websocket.close(code,reason)}function receiverOnDrain(){const websocket=this[kWebSocket];if(!websocket.isPaused)websocket._socket.resume()}function receiverOnError(err){const websocket=this[kWebSocket];if(websocket._socket[kWebSocket]!==undefined){websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);websocket.close(err[kStatusCode])}if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err)}}function receiverOnFinish(){this[kWebSocket].emitClose()}function receiverOnMessage(data,isBinary){this[kWebSocket].emit("message",data,isBinary)}function receiverOnPing(data){const websocket=this[kWebSocket];if(websocket._autoPong)websocket.pong(data,!this._isServer,NOOP);websocket.emit("ping",data)}function receiverOnPong(data){this[kWebSocket].emit("pong",data)}function resume(stream){stream.resume()}function senderOnError(err){const websocket=this[kWebSocket];if(websocket.readyState===WebSocket.CLOSED)return;if(websocket.readyState===WebSocket.OPEN){websocket._readyState=WebSocket.CLOSING;setCloseTimer(websocket)}this._socket.end();if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err)}}function setCloseTimer(websocket){websocket._closeTimer=setTimeout(websocket._socket.destroy.bind(websocket._socket),websocket._closeTimeout)}function socketOnClose(){const websocket=this[kWebSocket];this.removeListener("close",socketOnClose);this.removeListener("data",socketOnData);this.removeListener("end",socketOnEnd);websocket._readyState=WebSocket.CLOSING;if(!this._readableState.endEmitted&&!websocket._closeFrameReceived&&!websocket._receiver._writableState.errorEmitted&&this._readableState.length!==0){const chunk=this.read(this._readableState.length);websocket._receiver.write(chunk)}websocket._receiver.end();this[kWebSocket]=undefined;clearTimeout(websocket._closeTimer);if(websocket._receiver._writableState.finished||websocket._receiver._writableState.errorEmitted){websocket.emitClose()}else{websocket._receiver.on("error",receiverOnFinish);websocket._receiver.on("finish",receiverOnFinish)}}function socketOnData(chunk){if(!this[kWebSocket]._receiver.write(chunk)){this.pause()}}function socketOnEnd(){const websocket=this[kWebSocket];websocket._readyState=WebSocket.CLOSING;websocket._receiver.end();this.end()}function socketOnError(){const websocket=this[kWebSocket];this.removeListener("error",socketOnError);this.on("error",NOOP);if(websocket){websocket._readyState=WebSocket.CLOSING;this.destroy()}}});var require_stream=__commonJS(function(exports,module){var WebSocket=require_websocket();var{Duplex}=__require("stream");function emitClose(stream){stream.emit("close")}function duplexOnEnd(){if(!this.destroyed&&this._writableState.finished){this.destroy()}}function duplexOnError(err){this.removeListener("error",duplexOnError);this.destroy();if(this.listenerCount("error")===0){this.emit("error",err)}}function createWebSocketStream(ws,options){let terminateOnDestroy=true;const duplex=new Duplex({...options,autoDestroy:false,emitClose:false,objectMode:false,writableObjectMode:false});ws.on("message",function message(msg,isBinary){const data=!isBinary&&duplex._readableState.objectMode?msg.toString():msg;if(!duplex.push(data))ws.pause()});ws.once("error",function error(err){if(duplex.destroyed)return;terminateOnDestroy=false;duplex.destroy(err)});ws.once("close",function close(){if(duplex.destroyed)return;duplex.push(null)});duplex._destroy=function(err,callback){if(ws.readyState===ws.CLOSED){callback(err);process.nextTick(emitClose,duplex);return}let called=false;ws.once("error",function error(err){called=true;callback(err)});ws.once("close",function close(){if(!called)callback(err);process.nextTick(emitClose,duplex)});if(terminateOnDestroy)ws.terminate()};duplex._final=function(callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._final(callback)});return}if(ws._socket===null)return;if(ws._socket._writableState.finished){callback();if(duplex._readableState.endEmitted)duplex.destroy()}else{ws._socket.once("finish",function finish(){callback()});ws.close()}};duplex._read=function(){if(ws.isPaused)ws.resume()};duplex._write=function(chunk,encoding,callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._write(chunk,encoding,callback)});return}ws.send(chunk,callback)};duplex.on("end",duplexOnEnd);duplex.on("error",duplexOnError);return duplex}module.exports=createWebSocketStream});var require_subprotocol=__commonJS(function(exports,module){var{tokenChars}=require_validation();function parse(header){const protocols=new Set;let start=-1;let end=-1;let i=0;for(i;i<header.length;i++){const code=header.charCodeAt(i);if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;const protocol=header.slice(start,end);if(protocols.has(protocol)){throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`)}protocols.add(protocol);start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}if(start===-1||end!==-1){throw new SyntaxError("Unexpected end of input")}const protocol=header.slice(start,i);if(protocols.has(protocol)){throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`)}protocols.add(protocol);return protocols}module.exports={parse}});var require_websocket_server=__commonJS(function(exports,module){var EventEmitter=__require("events");var http=__require("http");var{Duplex}=__require("stream");var{createHash}=__require("crypto");var extension=require_extension();var PerMessageDeflate=require_permessage_deflate();var subprotocol=require_subprotocol();var WebSocket=require_websocket();var{CLOSE_TIMEOUT,GUID,kWebSocket}=require_constants();var keyRegex=/^[+/0-9A-Za-z]{22}==$/;var RUNNING=0;var CLOSING=1;var CLOSED=2;class WebSocketServer extends EventEmitter{constructor(options,callback){super();options={allowSynchronousEvents:true,autoPong:true,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:false,handleProtocols:null,clientTracking:true,closeTimeout:CLOSE_TIMEOUT,verifyClient:null,noServer:false,backlog:null,server:null,host:null,path:null,port:null,WebSocket,...options};if(options.port==null&&!options.server&&!options.noServer||options.port!=null&&(options.server||options.noServer)||options.server&&options.noServer){throw new TypeError('One and only one of the "port", "server", or "noServer" options '+"must be specified")}if(options.port!=null){this._server=http.createServer((req,res)=>{const body=http.STATUS_CODES[426];res.writeHead(426,{"Content-Length":body.length,"Content-Type":"text/plain"});res.end(body)});this._server.listen(options.port,options.host,options.backlog,callback)}else if(options.server){this._server=options.server}if(this._server){const emitConnection=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)}})}if(options.perMessageDeflate===true)options.perMessageDeflate={};if(options.clientTracking){this.clients=new Set;this._shouldEmitClose=false}this.options=options;this._state=RUNNING}address(){if(this.options.noServer){throw new Error('The server is operating in "noServer" mode')}if(!this._server)return null;return this._server.address()}close(cb){if(this._state===CLOSED){if(cb){this.once("close",()=>{cb(new Error("The server is not running"))})}process.nextTick(emitClose,this);return}if(cb)this.once("close",cb);if(this._state===CLOSING)return;this._state=CLOSING;if(this.options.noServer||this.options.server){if(this._server){this._removeListeners();this._removeListeners=this._server=null}if(this.clients){if(!this.clients.size){process.nextTick(emitClose,this)}else{this._shouldEmitClose=true}}else{process.nextTick(emitClose,this)}}else{const server=this._server;this._removeListeners();this._removeListeners=this._server=null;server.close(()=>{emitClose(this)})}}shouldHandle(req){if(this.options.path){const index=req.url.indexOf("?");const pathname=index!==-1?req.url.slice(0,index):req.url;if(pathname!==this.options.path)return false}return true}handleUpgrade(req,socket,head,cb){socket.on("error",socketOnError);const key=req.headers["sec-websocket-key"];const upgrade=req.headers.upgrade;const version=+req.headers["sec-websocket-version"];if(req.method!=="GET"){const message="Invalid HTTP method";abortHandshakeOrEmitwsClientError(this,req,socket,405,message);return}if(upgrade===undefined||upgrade.toLowerCase()!=="websocket"){const message="Invalid Upgrade header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(key===undefined||!keyRegex.test(key)){const message="Missing or invalid Sec-WebSocket-Key header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(version!==13&&version!==8){const message="Missing or invalid Sec-WebSocket-Version header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message,{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(req)){abortHandshake(socket,400);return}const secWebSocketProtocol=req.headers["sec-websocket-protocol"];let protocols=new Set;if(secWebSocketProtocol!==undefined){try{protocols=subprotocol.parse(secWebSocketProtocol)}catch(err){const message="Invalid Sec-WebSocket-Protocol header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}const secWebSocketExtensions=req.headers["sec-websocket-extensions"];const extensions={};if(this.options.perMessageDeflate&&secWebSocketExtensions!==undefined){const perMessageDeflate=new PerMessageDeflate({...this.options.perMessageDeflate,isServer:true,maxPayload:this.options.maxPayload});try{const offers=extension.parse(secWebSocketExtensions);if(offers[PerMessageDeflate.extensionName]){perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);extensions[PerMessageDeflate.extensionName]=perMessageDeflate}}catch(err){const message="Invalid or unacceptable Sec-WebSocket-Extensions header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}if(this.options.verifyClient){const info={origin:req.headers[`${version===8?"sec-websocket-origin":"origin"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info,(verified,code,message,headers)=>{if(!verified){return abortHandshake(socket,code||401,message,headers)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info))return abortHandshake(socket,401)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)}completeUpgrade(extensions,key,protocols,req,socket,head,cb){if(!socket.readable||!socket.writable)return socket.destroy();if(socket[kWebSocket]){throw new Error("server.handleUpgrade() was called more than once with the same "+"socket, possibly due to a misconfiguration")}if(this._state>RUNNING)return abortHandshake(socket,503);const digest=createHash("sha1").update(key+GUID).digest("base64");const headers=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${digest}`];const ws=new this.options.WebSocket(null,undefined,this.options);if(protocols.size){const protocol=this.options.handleProtocols?this.options.handleProtocols(protocols,req):protocols.values().next().value;if(protocol){headers.push(`Sec-WebSocket-Protocol: ${protocol}`);ws._protocol=protocol}}if(extensions[PerMessageDeflate.extensionName]){const params=extensions[PerMessageDeflate.extensionName].params;const value=extension.format({[PerMessageDeflate.extensionName]:[params]});headers.push(`Sec-WebSocket-Extensions: ${value}`);ws._extensions=extensions}this.emit("headers",headers,req);socket.write(headers.concat(`\r
|
|
1
|
+
var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};import path from"node:path";async function openNtdll(){const{dlopen,ptr}=await import("bun:ffi");const systemRoot=process.env["SystemRoot"]||process.env["windir"]||"C:\\Windows";const{symbols}=dlopen(path.win32.join(systemRoot,"System32","ntdll.dll"),{NtCreateFile:{args:["buffer","u32","buffer","buffer","ptr","u32","u32","u32","u32","ptr","u32"],returns:"u32"},NtClose:{args:["u64"],returns:"u32"},RtlNtStatusToDosError:{args:["u32"],returns:"u32"}});return{symbols,ptr}}function loadNtdll(){ntdll??=openNtdll().catch((error)=>{ntdll=undefined;throw error});return ntdll}function nativeError(symbols,operation,lockPath,status){const error=symbols.RtlNtStatusToDosError(status);return Object.assign(new Error(`instance lock ${operation} failed for ${lockPath} (Windows error ${error}, NTSTATUS 0x${status.toString(16)})`),{code:"ERR_INSTANCE_LOCK"})}async function tryAcquireWindows(lockPath){const{symbols,ptr}=await loadNtdll();const filename=Buffer.from(`${path.toNamespacedPath(path.resolve(lockPath)).replace(/^\\\\\?\\/,"\\??\\")}\x00`,"utf16le");const name=Buffer.alloc(16);name.writeUInt16LE(filename.length-2,0);name.writeUInt16LE(filename.length,2);name.writeBigUInt64LE(BigInt(ptr(filename)),8);const attributes=Buffer.alloc(48);attributes.writeUInt32LE(48,0);attributes.writeBigUInt64LE(BigInt(ptr(name)),16);attributes.writeUInt32LE(64,24);const handleOut=Buffer.alloc(8);const ioStatus=Buffer.alloc(16);const status=symbols.NtCreateFile(handleOut,3222274048,attributes,ioStatus,null,128,0,3,96,null,0);if(status===3221225539)return null;if(status>=2147483648)throw nativeError(symbols,"NtCreateFile",lockPath,status);const handle=handleOut.readBigUInt64LE();return{release(){const closeStatus=symbols.NtClose(handle);if(closeStatus>=2147483648)throw nativeError(symbols,"NtClose",lockPath,closeStatus)}}}var ntdll;var init_lock_backend_win32_xbcm60vz=()=>{};import{createRequire}from"node:module";import path3 from"node:path";import{mkdir as mkdir4}from"node:fs/promises";import path2 from"node:path";import{mkdir,writeFile}from"node:fs/promises";import{createReadStream,promises}from"node:fs";import*as fs$16 from"node:fs/promises";import{spawn}from"node:child_process";import{tmpdir}from"node:os";import{readFileSync}from"node:fs";import{readFile}from"node:fs/promises";import{readFile as readFile2}from"node:fs/promises";import{randomUUID}from"node:crypto";import{isDeepStrictEqual}from"node:util";import{mkdir as mkdir3,writeFile as writeFile2}from"node:fs/promises";import path22 from"node:path";import{spawn as spawn3}from"node:child_process";import{finished}from"node:stream/promises";import{mkdirSync,readFileSync as readFileSync2,rmSync,writeFileSync}from"node:fs";import path5 from"node:path";import{setTimeout as sleep2}from"node:timers/promises";import{unlink as unlink2}from"node:fs/promises";import{setTimeout as sleep}from"node:timers/promises";import{spawn as spawn2}from"node:child_process";import{constants}from"node:fs";import{open as open2}from"node:fs/promises";import{execFile}from"node:child_process";import{readFile as readFile3}from"node:fs/promises";import path4 from"node:path";import{promisify}from"node:util";import{spawn as spawn4}from"node:child_process";import{createHash,randomUUID as randomUUID2}from"node:crypto";import{mkdir as mkdir5,open as open3,readFile as readFile6,readdir,rename,unlink as unlink3}from"node:fs/promises";import os from"node:os";import path8 from"node:path";import{watch}from"node:fs";import{readFile as readFile4,stat}from"node:fs/promises";import path6 from"node:path";import{execFile as execFile2}from"node:child_process";import{chmod,mkdtemp,readFile as readFile5,rm,stat as stat2}from"node:fs/promises";import{tmpdir as tmpdir2}from"node:os";import path7 from"node:path";import{promisify as promisify2}from"node:util";import{readFile as readFile7}from"node:fs/promises";import{connect as connectTcp}from"node:net";import path10 from"node:path";import{existsSync}from"node:fs";import{homedir}from"node:os";import path9 from"node:path";import{randomInt}from"node:crypto";import{mkdir as mkdir6,open as open4,readFile as readFile8,unlink as unlink4}from"node:fs/promises";import{globSync}from"node:fs";import os2 from"node:os";import path11 from"node:path";import{spawn as spawn5}from"node:child_process";import{mkdtempSync,writeFileSync as writeFileSync2,rmSync as rmSync2}from"node:fs";import{tmpdir as tmpdir3}from"node:os";import path12 from"node:path";import{randomUUID as randomUUID3}from"node:crypto";import path16 from"node:path";import{mkdir as mkdir8,open as open5,readFile as readFile9,readlink,realpath,rename as rename2,lstat,chmod as chmod2}from"node:fs/promises";import{homedir as homedir2}from"node:os";import{TextDecoder as TextDecoder2}from"node:util";import{mkdirSync as mkdirSync2}from"node:fs";import path14 from"node:path";import{tmpdir as tmpdir4}from"node:os";import{existsSync as existsSync2,readFileSync as readFileSync3}from"node:fs";import path13 from"node:path";import{execFile as execFile3}from"node:child_process";import{existsSync as existsSync3}from"node:fs";import{mkdir as mkdir7,rmdir,unlink as unlink5}from"node:fs/promises";import path15 from"node:path";import{mkdir as mkdir9,writeFile as writeFile3}from"node:fs/promises";import path17 from"node:path";import{connect as connect2}from"node:net";import{existsSync as existsSync6,readdirSync}from"node:fs";import path20 from"node:path";import{randomBytes}from"node:crypto";import{existsSync as existsSync5,readFileSync as readFileSync5}from"node:fs";import{homedir as homedir4}from"node:os";import path19 from"node:path";import{spawn as spawn7}from"node:child_process";import{createHash as createHash2}from"node:crypto";import{existsSync as existsSync4,readFileSync as readFileSync4,rmSync as rmSync3,writeFileSync as writeFileSync3}from"node:fs";import{homedir as homedir3}from"node:os";import path18 from"node:path";import{spawn as spawn6}from"node:child_process";import{spawn as spawnChild}from"node:child_process";import{randomBytes as randomBytes2}from"node:crypto";import{existsSync as existsSync8,readFileSync as readFileSync6}from"node:fs";import{homedir as homedir6}from"node:os";import path222 from"node:path";import{spawn as spawn8}from"node:child_process";import{existsSync as existsSync7}from"node:fs";import{homedir as homedir5}from"node:os";import path21 from"node:path";import{randomInt as randomInt2}from"node:crypto";import{existsSync as existsSync9,mkdirSync as mkdirSync3,readFileSync as readFileSync7,rmSync as rmSync4,writeFileSync as writeFileSync4}from"node:fs";import{spawn as spawn9}from"node:child_process";import path23 from"node:path";import{execFile as execFile4}from"node:child_process";import{statSync}from"node:fs";import{homedir as homedir7}from"node:os";import path24 from"node:path";import{homedir as homedir8}from"node:os";import{existsSync as existsSync10,readFileSync as readFileSync8}from"node:fs";var __create=Object.create;var __getProtoOf=Object.getPrototypeOf;var __defProp=Object.defineProperty;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node;var __toESMCache_esm;var __toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap;var cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};const to=isNodeMode||!mod||!mod.__esModule||!__hasOwnProp.call(mod,"default")?__defProp(target,"default",{value:mod,enumerable:true}):target;if(mod&&typeof mod==="object"||typeof mod==="function"){for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:true})}if(canCache)cache.set(mod,to);return to};var __commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true,configurable:true,set:__exportSetter.bind(all,name)})};var __require=createRequire(import.meta.url);var require_constants=__commonJS(function(exports,module){var BINARY_TYPES=["nodebuffer","arraybuffer","fragments"];var hasBlob=typeof Blob!=="undefined";if(hasBlob)BINARY_TYPES.push("blob");module.exports={BINARY_TYPES,CLOSE_TIMEOUT:30000,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var require_buffer_util=__commonJS(function(exports,module){var{websocketMask,websocketUnmask}=__require("http");var{EMPTY_BUFFER}=require_constants();var FastBuffer=Buffer[Symbol.species];function concat(list,totalLength){if(list.length===0)return EMPTY_BUFFER;if(list.length===1)return list[0];const target=Buffer.allocUnsafe(totalLength);let offset=0;for(let i=0;i<list.length;i++){const buf=list[i];target.set(buf,offset);offset+=buf.length}if(offset<totalLength){return new FastBuffer(target.buffer,target.byteOffset,offset)}return target}function _mask(source,mask,output,offset,length){for(let i=0;i<length;i++){output[offset+i]=source[i]^mask[i&3]}}function _unmask(buffer,mask){for(let i=0;i<buffer.length;i++){buffer[i]^=mask[i&3]}}function toArrayBuffer(buf){if(buf.length===buf.buffer.byteLength){return buf.buffer}return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.length)}function toBuffer(data){toBuffer.readOnly=true;if(Buffer.isBuffer(data))return data;let buf;if(data instanceof ArrayBuffer){buf=new FastBuffer(data)}else if(ArrayBuffer.isView(data)){buf=new FastBuffer(data.buffer,data.byteOffset,data.byteLength)}else{buf=Buffer.from(data);toBuffer.readOnly=false}return buf}module.exports={concat,mask:_mask,toArrayBuffer,toBuffer,unmask:_unmask};if(websocketMask){module.exports.mask=function(source,mask,output,offset,length){if(length<24)_mask(source,mask,output,offset,length);else websocketMask(source,mask,output,offset,length)};module.exports.unmask=function(buffer,mask){if(buffer.length<24)_unmask(buffer,mask);else websocketUnmask(buffer,mask)}}else if(!process.env.WS_NO_BUFFER_UTIL){try{const bufferUtil=(()=>{throw new Error("Cannot require module "+"bufferutil")})();module.exports.mask=function(source,mask2,output,offset,length){if(length<48)_mask(source,mask2,output,offset,length);else bufferUtil.mask(source,mask2,output,offset,length)};module.exports.unmask=function(buffer,mask){if(buffer.length<32)_unmask(buffer,mask);else bufferUtil.unmask(buffer,mask)}}catch(e){}}});var require_limiter=__commonJS(function(exports,module){var kDone=Symbol("kDone");var kRun=Symbol("kRun");class Limiter{constructor(concurrency){this[kDone]=()=>{this.pending--;this[kRun]()};this.concurrency=concurrency||Infinity;this.jobs=[];this.pending=0}add(job){this.jobs.push(job);this[kRun]()}[kRun](){if(this.pending===this.concurrency)return;if(this.jobs.length){const job=this.jobs.shift();this.pending++;job(this[kDone])}}}module.exports=Limiter});var require_permessage_deflate=__commonJS(function(exports,module){var zlib=__require("zlib");var bufferUtil=require_buffer_util();var Limiter=require_limiter();var{kStatusCode}=require_constants();var FastBuffer=Buffer[Symbol.species];var TRAILER=Buffer.from([0,0,255,255]);var kPerMessageDeflate=Symbol("permessage-deflate");var kTotalLength=Symbol("total-length");var kCallback=Symbol("callback");var kBuffers=Symbol("buffers");var kError=Symbol("error");var zlibLimiter;class PerMessageDeflate{constructor(options){this._options=options||{};this._threshold=this._options.threshold!==undefined?this._options.threshold:1024;this._maxPayload=this._options.maxPayload|0;this._isServer=!!this._options.isServer;this._deflate=null;this._inflate=null;this.params=null;if(!zlibLimiter){const concurrency=this._options.concurrencyLimit!==undefined?this._options.concurrencyLimit:10;zlibLimiter=new Limiter(concurrency)}}static get extensionName(){return"permessage-deflate"}offer(){const params={};if(this._options.serverNoContextTakeover){params.server_no_context_takeover=true}if(this._options.clientNoContextTakeover){params.client_no_context_takeover=true}if(this._options.serverMaxWindowBits){params.server_max_window_bits=this._options.serverMaxWindowBits}if(this._options.clientMaxWindowBits){params.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits==null){params.client_max_window_bits=true}return params}accept(configurations){configurations=this.normalizeParams(configurations);this.params=this._isServer?this.acceptAsServer(configurations):this.acceptAsClient(configurations);return this.params}cleanup(){if(this._inflate){this._inflate.close();this._inflate=null}if(this._deflate){const callback=this._deflate[kCallback];this._deflate.close();this._deflate=null;if(callback){callback(new Error("The deflate stream was closed while data was being processed"))}}}acceptAsServer(offers){const opts=this._options;const accepted=offers.find((params)=>{if(opts.serverNoContextTakeover===false&¶ms.server_no_context_takeover||params.server_max_window_bits&&(opts.serverMaxWindowBits===false||typeof opts.serverMaxWindowBits==="number"&&opts.serverMaxWindowBits>params.server_max_window_bits)||typeof opts.clientMaxWindowBits==="number"&&(typeof params.client_max_window_bits==="number"?opts.clientMaxWindowBits>params.client_max_window_bits:!params.client_max_window_bits)){return false}return true});if(!accepted){throw new Error("None of the extension offers can be accepted")}if(opts.serverNoContextTakeover){accepted.server_no_context_takeover=true}if(opts.clientNoContextTakeover){accepted.client_no_context_takeover=true}if(typeof opts.serverMaxWindowBits==="number"){accepted.server_max_window_bits=opts.serverMaxWindowBits}if(typeof opts.clientMaxWindowBits==="number"){accepted.client_max_window_bits=opts.clientMaxWindowBits}else if(accepted.client_max_window_bits===true||opts.clientMaxWindowBits===false){delete accepted.client_max_window_bits}return accepted}acceptAsClient(response){const params=response[0];if(this._options.clientNoContextTakeover===false&¶ms.client_no_context_takeover){throw new Error('Unexpected parameter "client_no_context_takeover"')}if(!params.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number"){params.client_max_window_bits=this._options.clientMaxWindowBits}}else if(this._options.clientMaxWindowBits===false||typeof this._options.clientMaxWindowBits==="number"&¶ms.client_max_window_bits>this._options.clientMaxWindowBits){throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}return params}normalizeParams(configurations){configurations.forEach((params)=>{Object.keys(params).forEach((key)=>{let value=params[key];if(value.length>1){throw new Error(`Parameter "${key}" must have only a single value`)}value=value[0];if(key==="client_max_window_bits"){if(value!==true){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(!this._isServer){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else if(key==="server_max_window_bits"){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(key==="client_no_context_takeover"||key==="server_no_context_takeover"){if(value!==true){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else{throw new Error(`Unknown parameter "${key}"`)}params[key]=value})});return configurations}decompress(data,fin,callback){zlibLimiter.add((done)=>{this._decompress(data,fin,(err,result)=>{done();callback(err,result)})})}compress(data,fin,callback){zlibLimiter.add((done)=>{this._compress(data,fin,(err,result)=>{done();callback(err,result)})})}_decompress(data,fin,callback){const endpoint=this._isServer?"client":"server";if(!this._inflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._inflate=zlib.createInflateRaw({...this._options.zlibInflateOptions,windowBits});this._inflate[kPerMessageDeflate]=this;this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];this._inflate.on("error",inflateOnError);this._inflate.on("data",inflateOnData)}this._inflate[kCallback]=callback;this._inflate.write(data);if(fin)this._inflate.write(TRAILER);this._inflate.flush(()=>{const err=this._inflate[kError];if(err){this._inflate.close();this._inflate=null;callback(err);return}const data=bufferUtil.concat(this._inflate[kBuffers],this._inflate[kTotalLength]);if(this._inflate._readableState.endEmitted){this._inflate.close();this._inflate=null}else{this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._inflate.reset()}}callback(null,data)})}_compress(data,fin,callback){const endpoint=this._isServer?"server":"client";if(!this._deflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._deflate=zlib.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits});this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];this._deflate.on("data",deflateOnData)}this._deflate[kCallback]=callback;this._deflate.write(data);this._deflate.flush(zlib.Z_SYNC_FLUSH,()=>{if(!this._deflate){return}let data=bufferUtil.concat(this._deflate[kBuffers],this._deflate[kTotalLength]);if(fin){data=new FastBuffer(data.buffer,data.byteOffset,data.length-4)}this._deflate[kCallback]=null;this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._deflate.reset()}callback(null,data)})}}module.exports=PerMessageDeflate;function deflateOnData(chunk){this[kBuffers].push(chunk);this[kTotalLength]+=chunk.length}function inflateOnData(chunk){this[kTotalLength]+=chunk.length;if(this[kPerMessageDeflate]._maxPayload<1||this[kTotalLength]<=this[kPerMessageDeflate]._maxPayload){this[kBuffers].push(chunk);return}this[kError]=new RangeError("Max payload size exceeded");this[kError].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";this[kError][kStatusCode]=1009;this.removeListener("data",inflateOnData);this.reset()}function inflateOnError(err){this[kPerMessageDeflate]._inflate=null;if(this[kError]){this[kCallback](this[kError]);return}err[kStatusCode]=1007;this[kCallback](err)}});var require_validation=__commonJS(function(exports,module){var{isUtf8}=__require("buffer");var{hasBlob}=require_constants();var tokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function isValidStatusCode(code){return code>=1000&&code<=1014&&code!==1004&&code!==1005&&code!==1006||code>=3000&&code<=4999}function _isValidUTF8(buf){const len=buf.length;let i=0;while(i<len){if((buf[i]&128)===0){i++}else if((buf[i]&224)===192){if(i+1===len||(buf[i+1]&192)!==128||(buf[i]&254)===192){return false}i+=2}else if((buf[i]&240)===224){if(i+2>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||buf[i]===224&&(buf[i+1]&224)===128||buf[i]===237&&(buf[i+1]&224)===160){return false}i+=3}else if((buf[i]&248)===240){if(i+3>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||(buf[i+3]&192)!==128||buf[i]===240&&(buf[i+1]&240)===128||buf[i]===244&&buf[i+1]>143||buf[i]>244){return false}i+=4}else{return false}}return true}function isBlob(value){return hasBlob&&typeof value==="object"&&typeof value.arrayBuffer==="function"&&typeof value.type==="string"&&typeof value.stream==="function"&&(value[Symbol.toStringTag]==="Blob"||value[Symbol.toStringTag]==="File")}module.exports={isBlob,isValidStatusCode,isValidUTF8:_isValidUTF8,tokenChars};if(isUtf8){module.exports.isValidUTF8=function(buf){return buf.length<24?_isValidUTF8(buf):isUtf8(buf)}}else if(!process.env.WS_NO_UTF_8_VALIDATE){try{const isValidUTF8=(()=>{throw new Error("Cannot require module "+"utf-8-validate")})();module.exports.isValidUTF8=function(buf){return buf.length<32?_isValidUTF8(buf):isValidUTF8(buf)}}catch(e){}}});var require_receiver=__commonJS(function(exports,module){var{Writable}=__require("stream");var PerMessageDeflate=require_permessage_deflate();var{BINARY_TYPES,EMPTY_BUFFER,kStatusCode,kWebSocket}=require_constants();var{concat,toArrayBuffer,unmask}=require_buffer_util();var{isValidStatusCode,isValidUTF8}=require_validation();var FastBuffer=Buffer[Symbol.species];var GET_INFO=0;var GET_PAYLOAD_LENGTH_16=1;var GET_PAYLOAD_LENGTH_64=2;var GET_MASK=3;var GET_DATA=4;var INFLATING=5;var DEFER_EVENT=6;class Receiver extends Writable{constructor(options={}){super();this._allowSynchronousEvents=options.allowSynchronousEvents!==undefined?options.allowSynchronousEvents:true;this._binaryType=options.binaryType||BINARY_TYPES[0];this._extensions=options.extensions||{};this._isServer=!!options.isServer;this._maxBufferedChunks=options.maxBufferedChunks|0;this._maxFragments=options.maxFragments|0;this._maxPayload=options.maxPayload|0;this._skipUTF8Validation=!!options.skipUTF8Validation;this[kWebSocket]=undefined;this._bufferedBytes=0;this._buffers=[];this._compressed=false;this._payloadLength=0;this._mask=undefined;this._fragmented=0;this._masked=false;this._fin=false;this._opcode=0;this._totalPayloadLength=0;this._messageLength=0;this._numFragments=0;this._fragments=[];this._errored=false;this._loop=false;this._state=GET_INFO}_write(chunk,encoding,cb){if(this._opcode===8&&this._state==GET_INFO)return cb();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){cb(this.createError(RangeError,"Too many buffered chunks",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=chunk.length;this._buffers.push(chunk);this.startLoop(cb)}consume(n){this._bufferedBytes-=n;if(n===this._buffers[0].length)return this._buffers.shift();if(n<this._buffers[0].length){const buf=this._buffers[0];this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n);return new FastBuffer(buf.buffer,buf.byteOffset,n)}const dst=Buffer.allocUnsafe(n);do{const buf=this._buffers[0];const offset=dst.length-n;if(n>=buf.length){dst.set(this._buffers.shift(),offset)}else{dst.set(new Uint8Array(buf.buffer,buf.byteOffset,n),offset);this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n)}n-=buf.length}while(n>0);return dst}startLoop(cb){this._loop=true;do{switch(this._state){case GET_INFO:this.getInfo(cb);break;case GET_PAYLOAD_LENGTH_16:this.getPayloadLength16(cb);break;case GET_PAYLOAD_LENGTH_64:this.getPayloadLength64(cb);break;case GET_MASK:this.getMask();break;case GET_DATA:this.getData(cb);break;case INFLATING:case DEFER_EVENT:this._loop=false;return}}while(this._loop);if(!this._errored)cb()}getInfo(cb){if(this._bufferedBytes<2){this._loop=false;return}const buf=this.consume(2);if((buf[0]&48)!==0){const error=this.createError(RangeError,"RSV2 and RSV3 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_2_3");cb(error);return}const compressed=(buf[0]&64)===64;if(compressed&&!this._extensions[PerMessageDeflate.extensionName]){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}this._fin=(buf[0]&128)===128;this._opcode=buf[0]&15;this._payloadLength=buf[1]&127;if(this._opcode===0){if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(!this._fragmented){const error=this.createError(RangeError,"invalid opcode 0",true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._compressed=compressed}else if(this._opcode>7&&this._opcode<11){if(!this._fin){const error=this.createError(RangeError,"FIN must be set",true,1002,"WS_ERR_EXPECTED_FIN");cb(error);return}if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){const error=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,true,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");cb(error);return}}else{const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;this._masked=(buf[1]&128)===128;if(this._isServer){if(!this._masked){const error=this.createError(RangeError,"MASK must be set",true,1002,"WS_ERR_EXPECTED_MASK");cb(error);return}}else if(this._masked){const error=this.createError(RangeError,"MASK must be clear",true,1002,"WS_ERR_UNEXPECTED_MASK");cb(error);return}if(this._payloadLength===126)this._state=GET_PAYLOAD_LENGTH_16;else if(this._payloadLength===127)this._state=GET_PAYLOAD_LENGTH_64;else this.haveLength(cb)}getPayloadLength16(cb){if(this._bufferedBytes<2){this._loop=false;return}this._payloadLength=this.consume(2).readUInt16BE(0);this.haveLength(cb)}getPayloadLength64(cb){if(this._bufferedBytes<8){this._loop=false;return}const buf=this.consume(8);const num=buf.readUInt32BE(0);if(num>Math.pow(2,53-32)-1){const error=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",false,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");cb(error);return}this._payloadLength=num*Math.pow(2,32)+buf.readUInt32BE(4);this.haveLength(cb)}haveLength(cb){if(this._payloadLength&&this._opcode<8){this._totalPayloadLength+=this._payloadLength;if(this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}}if(this._masked)this._state=GET_MASK;else this._state=GET_DATA}getMask(){if(this._bufferedBytes<4){this._loop=false;return}this._mask=this.consume(4);this._state=GET_DATA}getData(cb){let data=EMPTY_BUFFER;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=false;return}data=this.consume(this._payloadLength);if(this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0){unmask(data,this._mask)}}this._mask=undefined;if(this._opcode>7){this.controlMessage(data,cb);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){const error=this.createError(RangeError,"Too many message fragments",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");cb(error);return}if(this._compressed){this._state=INFLATING;this.decompress(data,cb);return}if(data.length){this._messageLength=this._totalPayloadLength;this._fragments.push(data)}this.dataMessage(cb)}decompress(data,cb){const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];perMessageDeflate.decompress(data,this._fin,(err,buf)=>{if(err)return cb(err);if(buf.length){this._messageLength+=buf.length;if(this._messageLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}this._fragments.push(buf)}this.dataMessage(cb);if(this._state===GET_INFO)this.startLoop(cb)})}dataMessage(cb){if(!this._fin){this._state=GET_INFO;return}const messageLength=this._messageLength;const fragments=this._fragments;this._totalPayloadLength=0;this._messageLength=0;this._fragmented=0;this._numFragments=0;this._fragments=[];if(this._opcode===2){let data;if(this._binaryType==="nodebuffer"){data=concat(fragments,messageLength)}else if(this._binaryType==="arraybuffer"){data=toArrayBuffer(concat(fragments,messageLength))}else if(this._binaryType==="blob"){data=new Blob(fragments)}else{data=fragments}if(this._allowSynchronousEvents){this.emit("message",data,true);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",data,true);this._state=GET_INFO;this.startLoop(cb)})}}else{const buf=concat(fragments,messageLength);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}if(this._state===INFLATING||this._allowSynchronousEvents){this.emit("message",buf,false);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",buf,false);this._state=GET_INFO;this.startLoop(cb)})}}}controlMessage(data,cb){if(this._opcode===8){if(data.length===0){this._loop=false;this.emit("conclude",1005,EMPTY_BUFFER);this.end()}else{const code=data.readUInt16BE(0);if(!isValidStatusCode(code)){const error=this.createError(RangeError,`invalid status code ${code}`,true,1002,"WS_ERR_INVALID_CLOSE_CODE");cb(error);return}const buf=new FastBuffer(data.buffer,data.byteOffset+2,data.length-2);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}this._loop=false;this.emit("conclude",code,buf);this.end()}this._state=GET_INFO;return}if(this._allowSynchronousEvents){this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO;this.startLoop(cb)})}}createError(ErrorCtor,message,prefix,statusCode,errorCode){this._loop=false;this._errored=true;const err=new ErrorCtor(prefix?`Invalid WebSocket frame: ${message}`:message);Error.captureStackTrace(err,this.createError);err.code=errorCode;err[kStatusCode]=statusCode;return err}}module.exports=Receiver});var require_sender=__commonJS(function(exports,module){var{Duplex}=__require("stream");var{randomFillSync}=__require("crypto");var{types:{isUint8Array}}=__require("util");var PerMessageDeflate=require_permessage_deflate();var{EMPTY_BUFFER,kWebSocket,NOOP}=require_constants();var{isBlob,isValidStatusCode}=require_validation();var{mask:applyMask,toBuffer}=require_buffer_util();var kByteLength=Symbol("kByteLength");var maskBuffer=Buffer.alloc(4);var RANDOM_POOL_SIZE=8*1024;var randomPool;var randomPoolPointer=RANDOM_POOL_SIZE;var DEFAULT=0;var DEFLATING=1;var GET_BLOB_DATA=2;class Sender{constructor(socket,extensions,generateMask){this._extensions=extensions||{};if(generateMask){this._generateMask=generateMask;this._maskBuffer=Buffer.alloc(4)}this._socket=socket;this._firstFragment=true;this._compress=false;this._bufferedBytes=0;this._queue=[];this._state=DEFAULT;this.onerror=NOOP;this[kWebSocket]=undefined}static frame(data,options){let mask;let merge=false;let offset=2;let skipMasking=false;if(options.mask){mask=options.maskBuffer||maskBuffer;if(options.generateMask){options.generateMask(mask)}else{if(randomPoolPointer===RANDOM_POOL_SIZE){if(randomPool===undefined){randomPool=Buffer.alloc(RANDOM_POOL_SIZE)}randomFillSync(randomPool,0,RANDOM_POOL_SIZE);randomPoolPointer=0}mask[0]=randomPool[randomPoolPointer++];mask[1]=randomPool[randomPoolPointer++];mask[2]=randomPool[randomPoolPointer++];mask[3]=randomPool[randomPoolPointer++]}skipMasking=(mask[0]|mask[1]|mask[2]|mask[3])===0;offset=6}let dataLength;if(typeof data==="string"){if((!options.mask||skipMasking)&&options[kByteLength]!==undefined){dataLength=options[kByteLength]}else{data=Buffer.from(data);dataLength=data.length}}else{dataLength=data.length;merge=options.mask&&options.readOnly&&!skipMasking}let payloadLength=dataLength;if(dataLength>=65536){offset+=8;payloadLength=127}else if(dataLength>125){offset+=2;payloadLength=126}const target=Buffer.allocUnsafe(merge?dataLength+offset:offset);target[0]=options.fin?options.opcode|128:options.opcode;if(options.rsv1)target[0]|=64;target[1]=payloadLength;if(payloadLength===126){target.writeUInt16BE(dataLength,2)}else if(payloadLength===127){target[2]=target[3]=0;target.writeUIntBE(dataLength,4,6)}if(!options.mask){return dataLength?[target,data]:[target]}target[1]|=128;target[offset-4]=mask[0];target[offset-3]=mask[1];target[offset-2]=mask[2];target[offset-1]=mask[3];if(!dataLength)return[target];if(skipMasking)return[target,data];if(merge){applyMask(data,mask,target,offset,dataLength);return[target]}applyMask(data,mask,data,0,dataLength);return[target,data]}close(code,data,mask,cb){let buf;if(code===undefined){buf=EMPTY_BUFFER}else if(typeof code!=="number"||!isValidStatusCode(code)){throw new TypeError("First argument must be a valid error code number")}else if(data===undefined||!data.length){buf=Buffer.allocUnsafe(2);buf.writeUInt16BE(code,0)}else{const length=Buffer.byteLength(data);if(length>123){throw new RangeError("The message must not be greater than 123 bytes")}buf=Buffer.allocUnsafe(2+length);buf.writeUInt16BE(code,0);if(typeof data==="string"){buf.write(data,2)}else if(isUint8Array(data)){buf.set(data,2)}else{throw new TypeError("Second argument must be a string or a Uint8Array")}}const options={[kByteLength]:buf.length,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:8,readOnly:false,rsv1:false};if(this._state!==DEFAULT){this.enqueue([this.dispatch,buf,false,options,cb])}else{this.sendFrame(Sender.frame(buf,options),cb)}}ping(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:9,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(Sender.frame(data,options),cb)}}pong(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:10,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(Sender.frame(data,options),cb)}}send(data,options,cb){const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];let opcode=options.binary?2:1;let rsv1=options.compress;let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(this._firstFragment){this._firstFragment=false;if(rsv1&&perMessageDeflate&&perMessageDeflate.params[perMessageDeflate._isServer?"server_no_context_takeover":"client_no_context_takeover"]){rsv1=byteLength>=perMessageDeflate._threshold}this._compress=rsv1}else{rsv1=false;opcode=0}if(options.fin)this._firstFragment=true;const opts={[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,this._compress,opts,cb])}else{this.getBlobData(data,this._compress,opts,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,this._compress,opts,cb])}else{this.dispatch(data,this._compress,opts,cb)}}getBlobData(blob,compress,options,cb){this._bufferedBytes+=options[kByteLength];this._state=GET_BLOB_DATA;blob.arrayBuffer().then((arrayBuffer)=>{if(this._socket.destroyed){const err=new Error("The socket was closed while the blob was being read");process.nextTick(callCallbacks,this,err,cb);return}this._bufferedBytes-=options[kByteLength];const data=toBuffer(arrayBuffer);if(!compress){this._state=DEFAULT;this.sendFrame(Sender.frame(data,options),cb);this.dequeue()}else{this.dispatch(data,compress,options,cb)}}).catch((err)=>{process.nextTick(onError,this,err,cb)})}dispatch(data,compress,options,cb){if(!compress){this.sendFrame(Sender.frame(data,options),cb);return}const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];this._bufferedBytes+=options[kByteLength];this._state=DEFLATING;perMessageDeflate.compress(data,options.fin,(_,buf)=>{if(this._socket.destroyed){const err=new Error("The socket was closed while data was being compressed");callCallbacks(this,err,cb);return}this._bufferedBytes-=options[kByteLength];this._state=DEFAULT;options.readOnly=false;this.sendFrame(Sender.frame(buf,options),cb);this.dequeue()})}dequeue(){while(this._state===DEFAULT&&this._queue.length){const params=this._queue.shift();this._bufferedBytes-=params[3][kByteLength];Reflect.apply(params[0],this,params.slice(1))}}enqueue(params){this._bufferedBytes+=params[3][kByteLength];this._queue.push(params)}sendFrame(list,cb){if(list.length===2){this._socket.cork();this._socket.write(list[0]);this._socket.write(list[1],cb);this._socket.uncork()}else{this._socket.write(list[0],cb)}}}module.exports=Sender;function callCallbacks(sender,err,cb){if(typeof cb==="function")cb(err);for(let i=0;i<sender._queue.length;i++){const params=sender._queue[i];const callback=params[params.length-1];if(typeof callback==="function")callback(err)}}function onError(sender,err,cb){callCallbacks(sender,err,cb);sender.onerror(err)}});var require_event_target=__commonJS(function(exports,module){var{kForOnEventAttribute,kListener}=require_constants();var kCode=Symbol("kCode");var kData=Symbol("kData");var kError=Symbol("kError");var kMessage=Symbol("kMessage");var kReason=Symbol("kReason");var kTarget=Symbol("kTarget");var kType=Symbol("kType");var kWasClean=Symbol("kWasClean");class Event{constructor(type){this[kTarget]=null;this[kType]=type}get target(){return this[kTarget]}get type(){return this[kType]}}Object.defineProperty(Event.prototype,"target",{enumerable:true});Object.defineProperty(Event.prototype,"type",{enumerable:true});class CloseEvent extends Event{constructor(type,options={}){super(type);this[kCode]=options.code===undefined?0:options.code;this[kReason]=options.reason===undefined?"":options.reason;this[kWasClean]=options.wasClean===undefined?false:options.wasClean}get code(){return this[kCode]}get reason(){return this[kReason]}get wasClean(){return this[kWasClean]}}Object.defineProperty(CloseEvent.prototype,"code",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"reason",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"wasClean",{enumerable:true});class ErrorEvent extends Event{constructor(type,options={}){super(type);this[kError]=options.error===undefined?null:options.error;this[kMessage]=options.message===undefined?"":options.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent.prototype,"error",{enumerable:true});Object.defineProperty(ErrorEvent.prototype,"message",{enumerable:true});class MessageEvent extends Event{constructor(type,options={}){super(type);this[kData]=options.data===undefined?null:options.data}get data(){return this[kData]}}Object.defineProperty(MessageEvent.prototype,"data",{enumerable:true});var EventTarget={addEventListener(type,handler,options={}){for(const listener of this.listeners(type)){if(!options[kForOnEventAttribute]&&listener[kListener]===handler&&!listener[kForOnEventAttribute]){return}}let wrapper;if(type==="message"){wrapper=function onMessage(data,isBinary){const event=new MessageEvent("message",{data:isBinary?data:data.toString()});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="close"){wrapper=function onClose(code,message){const event=new CloseEvent("close",{code,reason:message.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="error"){wrapper=function onError(error){const event=new ErrorEvent("error",{error,message:error.message});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="open"){wrapper=function onOpen(){const event=new Event("open");event[kTarget]=this;callListener(handler,this,event)}}else{return}wrapper[kForOnEventAttribute]=!!options[kForOnEventAttribute];wrapper[kListener]=handler;if(options.once){this.once(type,wrapper)}else{this.on(type,wrapper)}},removeEventListener(type,handler){for(const listener of this.listeners(type)){if(listener[kListener]===handler&&!listener[kForOnEventAttribute]){this.removeListener(type,listener);break}}}};module.exports={CloseEvent,ErrorEvent,Event,EventTarget,MessageEvent};function callListener(listener,thisArg,event){if(typeof listener==="object"&&listener.handleEvent){listener.handleEvent.call(listener,event)}else{listener.call(thisArg,event)}}});var require_extension=__commonJS(function(exports,module){var{tokenChars}=require_validation();function push(dest,name,elem){if(dest[name]===undefined)dest[name]=[elem];else dest[name].push(elem)}function parse(header){const offers=Object.create(null);let params=Object.create(null);let mustUnescape=false;let isEscaping=false;let inQuotes=false;let extensionName;let paramName;let start=-1;let code=-1;let end=-1;let i=0;for(;i<header.length;i++){code=header.charCodeAt(i);if(extensionName===undefined){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;const name=header.slice(start,end);if(code===44){push(offers,name,params);params=Object.create(null)}else{extensionName=name}start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(paramName===undefined){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(code===32||code===9){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;push(params,header.slice(start,end),true);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=undefined}start=end=-1}else if(code===61&&start!==-1&&end===-1){paramName=header.slice(start,i);start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else{if(isEscaping){if(tokenChars[code]!==1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(start===-1)start=i;else if(!mustUnescape)mustUnescape=true;isEscaping=false}else if(inQuotes){if(tokenChars[code]===1){if(start===-1)start=i}else if(code===34&&start!==-1){inQuotes=false;end=i}else if(code===92){isEscaping=true}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(code===34&&header.charCodeAt(i-1)===61){inQuotes=true}else if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(start!==-1&&(code===32||code===9)){if(end===-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;let value=header.slice(start,end);if(mustUnescape){value=value.replace(/\\/g,"");mustUnescape=false}push(params,paramName,value);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=undefined}paramName=undefined;start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}}if(start===-1||inQuotes||code===32||code===9){throw new SyntaxError("Unexpected end of input")}if(end===-1)end=i;const token=header.slice(start,end);if(extensionName===undefined){push(offers,token,params)}else{if(paramName===undefined){push(params,token,true)}else if(mustUnescape){push(params,paramName,token.replace(/\\/g,""))}else{push(params,paramName,token)}push(offers,extensionName,params)}return offers}function format(extensions){return Object.keys(extensions).map((extension)=>{let configurations=extensions[extension];if(!Array.isArray(configurations))configurations=[configurations];return configurations.map((params)=>{return[extension].concat(Object.keys(params).map((k)=>{let values=params[k];if(!Array.isArray(values))values=[values];return values.map((v)=>v===true?k:`${k}=${v}`).join("; ")})).join("; ")}).join(", ")}).join(", ")}module.exports={format,parse}});var require_websocket=__commonJS(function(exports,module){var EventEmitter=__require("events");var https=__require("https");var http=__require("http");var net=__require("net");var querystring=__require("querystring");var tls=__require("tls");var{randomBytes,createHash}=__require("crypto");var{Duplex,Readable}=__require("stream");var{URL:URL2}=__require("url");var PerMessageDeflate=require_permessage_deflate();var Receiver=require_receiver();var Sender=require_sender();var{isBlob}=require_validation();var{BINARY_TYPES,CLOSE_TIMEOUT,EMPTY_BUFFER,GUID,kForOnEventAttribute,kListener,kStatusCode,kWebSocket,NOOP}=require_constants();var{EventTarget:{addEventListener,removeEventListener}}=require_event_target();var{format,parse}=require_extension();var{toBuffer}=require_buffer_util();var kAborted=Symbol("kAborted");var protocolVersions=[8,13];var readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"];var subprotocolRegex=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class WebSocket extends EventEmitter{constructor(address,protocols,options){super();this._binaryType=BINARY_TYPES[0];this._closeCode=1006;this._closeFrameReceived=false;this._closeFrameSent=false;this._closeMessage=EMPTY_BUFFER;this._closeTimer=null;this._errorEmitted=false;this._extensions={};this._paused=false;this._protocol="";this._readyState=WebSocket.CONNECTING;this._receiver=null;this._sender=null;this._socket=null;if(address!==null){this._bufferedAmount=0;this._isServer=false;this._redirects=0;if(protocols===undefined){if(!options||options.protocols===undefined){protocols=[]}else if(Array.isArray(options.protocols)){protocols=options.protocols}else{protocols=[options.protocols]}}else if(!Array.isArray(protocols)){if(typeof protocols==="object"&&protocols!==null){options=protocols;if(options.protocols===undefined){protocols=[]}else if(Array.isArray(options.protocols)){protocols=options.protocols}else{protocols=[options.protocols]}}else{protocols=[protocols]}}options=initAsClient(this,address,protocols,options)}else{this._isServer=true}if(options.autoPong){this._autoPong=true;this._autoPongComplete=()=>autoPongComplete(this);this._pendingAutoPongs=0;this._maxPendingAutoPongs=options.maxPendingAutoPongs|0}this._closeTimeout=options.closeTimeout}get binaryType(){return this._binaryType}set binaryType(type){if(!BINARY_TYPES.includes(type))return;this._binaryType=type;if(this._receiver)this._receiver._binaryType=type}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(socket,head,options){const receiver=new Receiver({allowSynchronousEvents:options.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:options.maxBufferedChunks,maxFragments:options.maxFragments,maxPayload:options.maxPayload,skipUTF8Validation:options.skipUTF8Validation});const sender=new Sender(socket,this._extensions,options.generateMask);this._receiver=receiver;this._sender=sender;this._socket=socket;receiver[kWebSocket]=this;sender[kWebSocket]=this;socket[kWebSocket]=this;receiver.on("conclude",receiverOnConclude);receiver.on("drain",receiverOnDrain);receiver.on("error",receiverOnError);receiver.on("message",receiverOnMessage);receiver.on("ping",receiverOnPing);receiver.on("pong",receiverOnPong);sender.onerror=senderOnError;if(socket.setTimeout)socket.setTimeout(0);if(socket.setNoDelay)socket.setNoDelay();if(head.length>0)socket.unshift(head);socket.on("close",socketOnClose);socket.on("data",socketOnData);socket.on("end",socketOnEnd);socket.on("error",socketOnError);this._readyState=WebSocket.OPEN;this.emit("open")}emitClose(){if(!this._socket){this._readyState=WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[PerMessageDeflate.extensionName]){this._extensions[PerMessageDeflate.extensionName].cleanup()}this._receiver.removeAllListeners();this._readyState=WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage)}close(code,data){if(this.readyState===WebSocket.CLOSED)return;if(this.readyState===WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this.readyState===WebSocket.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)){this._socket.end()}return}this._sender.close(code,data,!this._isServer,(err)=>{if(err)return;this._closeFrameSent=true;if(this._closeFrameReceived||this._receiver._writableState.errorEmitted){this._socket.end()}});this._readyState=WebSocket.CLOSING;setCloseTimer(this)}pause(){if(this.readyState===WebSocket.CONNECTING||this.readyState===WebSocket.CLOSED){return}this._paused=true;this._socket.pause()}ping(data,mask,cb){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=undefined}else if(typeof mask==="function"){cb=mask;mask=undefined}if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===undefined)mask=!this._isServer;this._sender.ping(data||EMPTY_BUFFER,mask,cb)}pong(data,mask,cb){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=undefined}else if(typeof mask==="function"){cb=mask;mask=undefined}if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===undefined)mask=!this._isServer;this._sender.pong(data||EMPTY_BUFFER,mask,cb)}resume(){if(this.readyState===WebSocket.CONNECTING||this.readyState===WebSocket.CLOSED){return}this._paused=false;if(!this._receiver._writableState.needDrain)this._socket.resume()}send(data,options,cb){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof options==="function"){cb=options;options={}}if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,data,cb);return}const opts={binary:typeof data!=="string",mask:!this._isServer,compress:true,fin:true,...options};if(!this._extensions[PerMessageDeflate.extensionName]){opts.compress=false}this._sender.send(data||EMPTY_BUFFER,opts,cb)}terminate(){if(this.readyState===WebSocket.CLOSED)return;if(this.readyState===WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this._socket){this._readyState=WebSocket.CLOSING;this._socket.destroy()}}}Object.defineProperty(WebSocket,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket.prototype,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket.prototype,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket.prototype,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});Object.defineProperty(WebSocket.prototype,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((property)=>{Object.defineProperty(WebSocket.prototype,property,{enumerable:true})});["open","error","close","message"].forEach((method)=>{Object.defineProperty(WebSocket.prototype,`on${method}`,{enumerable:true,get(){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute])return listener[kListener]}return null},set(handler){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute]){this.removeListener(method,listener);break}}if(typeof handler!=="function")return;this.addEventListener(method,handler,{[kForOnEventAttribute]:true})}})});WebSocket.prototype.addEventListener=addEventListener;WebSocket.prototype.removeEventListener=removeEventListener;module.exports=WebSocket;function initAsClient(websocket,address,protocols,options){const opts={allowSynchronousEvents:true,autoPong:true,closeTimeout:CLOSE_TIMEOUT,protocolVersion:protocolVersions[1],maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,maxPendingAutoPongs:60,skipUTF8Validation:false,perMessageDeflate:true,followRedirects:false,maxRedirects:10,...options,socketPath:undefined,hostname:undefined,protocol:undefined,protocols:undefined,timeout:undefined,method:"GET",host:undefined,path:undefined,port:undefined};if(!protocolVersions.includes(opts.protocolVersion)){throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} `+`(supported versions: ${protocolVersions.join(", ")})`)}let parsedUrl;if(address instanceof URL2){parsedUrl=address}else{try{parsedUrl=new URL2(address)}catch{throw new SyntaxError(`Invalid URL: ${address}`)}}if(parsedUrl.protocol==="http:"||parsedUrl.protocol==="https:"){parsedUrl=new URL2(parsedUrl);parsedUrl.protocol=parsedUrl.protocol==="http:"?"ws:":"wss:"}websocket._url=parsedUrl.href;const isSecure=parsedUrl.protocol==="wss:";const isIpcUrl=parsedUrl.protocol==="ws+unix:";let invalidUrlMessage;if(parsedUrl.protocol!=="ws:"&&!isSecure&&!isIpcUrl){invalidUrlMessage=`The URL's protocol must be one of "ws:", "wss:", `+'"http:", "https:", or "ws+unix:"'}else if(isIpcUrl&&!parsedUrl.pathname){invalidUrlMessage="The URL's pathname is empty"}else if(parsedUrl.hash){invalidUrlMessage="The URL contains a fragment identifier"}if(invalidUrlMessage){const err=new SyntaxError(invalidUrlMessage);if(websocket._redirects===0){throw err}else{emitErrorAndClose(websocket,err);return}}const defaultPort=isSecure?443:80;const key=randomBytes(16).toString("base64");const request3=isSecure?https.request:http.request;const protocolSet=new Set;let perMessageDeflate;opts.createConnection=opts.createConnection||(isSecure?tlsConnect:netConnect);opts.defaultPort=opts.defaultPort||defaultPort;opts.port=parsedUrl.port||defaultPort;opts.host=parsedUrl.hostname.startsWith("[")?parsedUrl.hostname.slice(1,-1):parsedUrl.hostname;opts.headers={...opts.headers,"Sec-WebSocket-Version":opts.protocolVersion,"Sec-WebSocket-Key":key,Connection:"Upgrade",Upgrade:"websocket"};opts.path=parsedUrl.pathname+parsedUrl.search;opts.timeout=opts.handshakeTimeout;if(opts.perMessageDeflate){perMessageDeflate=new PerMessageDeflate({...opts.perMessageDeflate,isServer:false,maxPayload:opts.maxPayload});opts.headers["Sec-WebSocket-Extensions"]=format({[PerMessageDeflate.extensionName]:perMessageDeflate.offer()})}if(protocols.length){for(const protocol of protocols){if(typeof protocol!=="string"||!subprotocolRegex.test(protocol)||protocolSet.has(protocol)){throw new SyntaxError("An invalid or duplicated subprotocol was specified")}protocolSet.add(protocol)}opts.headers["Sec-WebSocket-Protocol"]=protocols.join(",")}if(opts.origin){if(opts.protocolVersion<13){opts.headers["Sec-WebSocket-Origin"]=opts.origin}else{opts.headers.Origin=opts.origin}}if(parsedUrl.username||parsedUrl.password){const username=querystring.unescape(parsedUrl.username);const password=querystring.unescape(parsedUrl.password);opts.auth=`${username}:${password}`}if(isIpcUrl){const i=opts.path.indexOf(":");if(i===-1){opts.socketPath=opts.path;opts.path=""}else{opts.socketPath=opts.path.slice(0,i);opts.path=opts.path.slice(i+1)}}let req;if(opts.followRedirects){if(websocket._redirects===0){websocket._originalIpc=isIpcUrl;websocket._originalSecure=isSecure;websocket._originalHostOrSocketPath=isIpcUrl?opts.socketPath:parsedUrl.host;const headers=options&&options.headers;options={...options,headers:{}};if(headers){for(const[key,value]of Object.entries(headers)){options.headers[key.toLowerCase()]=value}}}else if(websocket.listenerCount("redirect")===0){const isSameHost=isIpcUrl?websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:false:websocket._originalIpc?false:parsedUrl.host===websocket._originalHostOrSocketPath;if(!isSameHost||websocket._originalSecure&&!isSecure){delete opts.headers.authorization;delete opts.headers.cookie;if(!isSameHost)delete opts.headers.host;opts.auth=undefined}}if(opts.auth&&!options.headers.authorization){options.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64")}req=websocket._req=request3(opts);if(websocket._redirects){websocket.emit("redirect",websocket.url,req)}}else{req=websocket._req=request3(opts)}if(opts.timeout){req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")})}req.on("error",(err)=>{if(req===null||req[kAborted])return;req=websocket._req=null;emitErrorAndClose(websocket,err)});req.on("response",(res)=>{const location2=res.headers.location;const statusCode=res.statusCode;if(location2&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL2(location2,address)}catch(e){const err=new SyntaxError(`Invalid URL: ${location2}`);emitErrorAndClose(websocket,err);return}initAsClient(websocket,addr,protocols,options)}else if(!websocket.emit("unexpected-response",req,res)){abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}});req.on("upgrade",(res,socket,head)=>{websocket.emit("upgrade",res);if(websocket.readyState!==WebSocket.CONNECTING)return;req=websocket._req=null;const upgrade=res.headers.upgrade;if(upgrade===undefined||upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}const digest=createHash("sha1").update(key+GUID).digest("base64");if(res.headers["sec-websocket-accept"]!==digest){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}const serverProt=res.headers["sec-websocket-protocol"];let protError;if(serverProt!==undefined){if(!protocolSet.size){protError="Server sent a subprotocol but none was requested"}else if(!protocolSet.has(serverProt)){protError="Server sent an invalid subprotocol"}}else if(protocolSet.size){protError="Server sent no subprotocol"}if(protError){abortHandshake(websocket,socket,protError);return}if(serverProt)websocket._protocol=serverProt;const secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==undefined){if(!perMessageDeflate){const message="Server sent a Sec-WebSocket-Extensions header but no extension "+"was requested";abortHandshake(websocket,socket,message);return}let extensions;try{extensions=parse(secWebSocketExtensions)}catch(err){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}const extensionNames=Object.keys(extensions);if(extensionNames.length!==1||extensionNames[0]!==PerMessageDeflate.extensionName){const message="Server indicated an extension that was not requested";abortHandshake(websocket,socket,message);return}try{perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName])}catch(err){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}websocket._extensions[PerMessageDeflate.extensionName]=perMessageDeflate}websocket.setSocket(socket,head,{allowSynchronousEvents:opts.allowSynchronousEvents,generateMask:opts.generateMask,maxBufferedChunks:opts.maxBufferedChunks,maxFragments:opts.maxFragments,maxPayload:opts.maxPayload,skipUTF8Validation:opts.skipUTF8Validation})});if(opts.finishRequest){opts.finishRequest(req,websocket)}else{req.end()}return opts}function emitErrorAndClose(websocket,err){websocket._readyState=WebSocket.CLOSING;websocket._errorEmitted=true;websocket.emit("error",err);websocket.emitClose()}function netConnect(options){options.path=options.socketPath;return net.connect(options)}function tlsConnect(options){options.path=undefined;if(!options.servername&&options.servername!==""){options.servername=net.isIP(options.host)?"":options.host}return tls.connect(options)}function abortHandshake(websocket,stream,message){websocket._readyState=WebSocket.CLOSING;const err=new Error(message);Error.captureStackTrace(err,abortHandshake);if(stream.setHeader){stream[kAborted]=true;stream.abort();if(stream.socket&&!stream.socket.destroyed){stream.socket.destroy()}process.nextTick(emitErrorAndClose,websocket,err)}else{stream.destroy(err);stream.once("error",websocket.emit.bind(websocket,"error"));stream.once("close",websocket.emitClose.bind(websocket))}}function sendAfterClose(websocket,data,cb){if(data){const length=isBlob(data)?data.size:toBuffer(data).length;if(websocket._socket)websocket._sender._bufferedBytes+=length;else websocket._bufferedAmount+=length}if(cb){const err=new Error(`WebSocket is not open: readyState ${websocket.readyState} `+`(${readyStates[websocket.readyState]})`);process.nextTick(cb,err)}}function receiverOnConclude(code,reason){const websocket=this[kWebSocket];websocket._closeFrameReceived=true;websocket._closeCode=code;if(reason.length===0){websocket._closeMessage=EMPTY_BUFFER}else{websocket._closeMessage=Buffer.allocUnsafeSlow(reason.length);websocket._closeMessage.set(reason)}if(websocket._socket[kWebSocket]===undefined)return;websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);if(code===1005)websocket.close();else websocket.close(code,reason)}function receiverOnDrain(){const websocket=this[kWebSocket];if(!websocket.isPaused)websocket._socket.resume()}function receiverOnError(err){const websocket=this[kWebSocket];if(websocket._socket[kWebSocket]!==undefined){websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);websocket.close(err[kStatusCode])}if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err)}}function receiverOnFinish(){this[kWebSocket].emitClose()}function receiverOnMessage(data,isBinary){this[kWebSocket].emit("message",data,isBinary)}function receiverOnPing(data){const websocket=this[kWebSocket];if(websocket._autoPong&&websocket.readyState===WebSocket.OPEN){if(websocket._maxPendingAutoPongs>0&&websocket._pendingAutoPongs>=websocket._maxPendingAutoPongs){websocket.terminate()}else{websocket._pendingAutoPongs++;websocket.pong(data,!this._isServer,websocket._autoPongComplete)}}websocket.emit("ping",data)}function autoPongComplete(websocket){websocket._pendingAutoPongs--}function receiverOnPong(data){this[kWebSocket].emit("pong",data)}function resume(stream){stream.resume()}function senderOnError(err){const websocket=this[kWebSocket];if(websocket.readyState===WebSocket.CLOSED)return;if(websocket.readyState===WebSocket.OPEN){websocket._readyState=WebSocket.CLOSING;setCloseTimer(websocket)}this._socket.end();if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err)}}function setCloseTimer(websocket){websocket._closeTimer=setTimeout(websocket._socket.destroy.bind(websocket._socket),websocket._closeTimeout)}function socketOnClose(){const websocket=this[kWebSocket];this.removeListener("close",socketOnClose);this.removeListener("data",socketOnData);this.removeListener("end",socketOnEnd);websocket._readyState=WebSocket.CLOSING;if(!this._readableState.endEmitted&&!websocket._closeFrameReceived&&!websocket._receiver._writableState.errorEmitted&&this._readableState.length!==0){const chunk=this.read(this._readableState.length);websocket._receiver.write(chunk)}websocket._receiver.end();this[kWebSocket]=undefined;clearTimeout(websocket._closeTimer);if(websocket._receiver._writableState.finished||websocket._receiver._writableState.errorEmitted){websocket.emitClose()}else{websocket._receiver.on("error",receiverOnFinish);websocket._receiver.on("finish",receiverOnFinish)}}function socketOnData(chunk){if(!this[kWebSocket]._receiver.write(chunk)){this.pause()}}function socketOnEnd(){const websocket=this[kWebSocket];websocket._readyState=WebSocket.CLOSING;websocket._receiver.end();this.end()}function socketOnError(){const websocket=this[kWebSocket];this.removeListener("error",socketOnError);this.on("error",NOOP);if(websocket){websocket._readyState=WebSocket.CLOSING;this.destroy()}}});var require_stream=__commonJS(function(exports,module){var WebSocket=require_websocket();var{Duplex}=__require("stream");function emitClose(stream){stream.emit("close")}function duplexOnEnd(){if(!this.destroyed&&this._writableState.finished){this.destroy()}}function duplexOnError(err){this.removeListener("error",duplexOnError);this.destroy();if(this.listenerCount("error")===0){this.emit("error",err)}}function createWebSocketStream(ws,options){let terminateOnDestroy=true;const duplex=new Duplex({...options,autoDestroy:false,emitClose:false,objectMode:false,writableObjectMode:false});ws.on("message",function message(msg,isBinary){const data=!isBinary&&duplex._readableState.objectMode?msg.toString():msg;if(!duplex.push(data))ws.pause()});ws.once("error",function error(err){if(duplex.destroyed)return;terminateOnDestroy=false;duplex.destroy(err)});ws.once("close",function close(){if(duplex.destroyed)return;duplex.push(null)});duplex._destroy=function(err,callback){if(ws.readyState===ws.CLOSED){callback(err);process.nextTick(emitClose,duplex);return}let called=false;ws.once("error",function error(err){called=true;callback(err)});ws.once("close",function close(){if(!called)callback(err);process.nextTick(emitClose,duplex)});if(terminateOnDestroy)ws.terminate()};duplex._final=function(callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._final(callback)});return}if(ws._socket===null)return;if(ws._socket._writableState.finished){callback();if(duplex._readableState.endEmitted)duplex.destroy()}else{ws._socket.once("finish",function finish(){callback()});ws.close()}};duplex._read=function(){if(ws.isPaused)ws.resume()};duplex._write=function(chunk,encoding,callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._write(chunk,encoding,callback)});return}ws.send(chunk,callback)};duplex.on("end",duplexOnEnd);duplex.on("error",duplexOnError);return duplex}module.exports=createWebSocketStream});var require_subprotocol=__commonJS(function(exports,module){var{tokenChars}=require_validation();function parse(header){const protocols=new Set;let start=-1;let end=-1;let i=0;for(i;i<header.length;i++){const code=header.charCodeAt(i);if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;const protocol=header.slice(start,end);if(protocols.has(protocol)){throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`)}protocols.add(protocol);start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}if(start===-1||end!==-1){throw new SyntaxError("Unexpected end of input")}const protocol=header.slice(start,i);if(protocols.has(protocol)){throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`)}protocols.add(protocol);return protocols}module.exports={parse}});var require_websocket_server=__commonJS(function(exports,module){var EventEmitter=__require("events");var http=__require("http");var{Duplex}=__require("stream");var{createHash}=__require("crypto");var extension=require_extension();var PerMessageDeflate=require_permessage_deflate();var subprotocol=require_subprotocol();var WebSocket=require_websocket();var{CLOSE_TIMEOUT,GUID,kWebSocket}=require_constants();var keyRegex=/^[+/0-9A-Za-z]{22}==$/;var RUNNING=0;var CLOSING=1;var CLOSED=2;class WebSocketServer extends EventEmitter{constructor(options,callback){super();options={allowSynchronousEvents:true,autoPong:true,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,maxPendingAutoPongs:60,skipUTF8Validation:false,perMessageDeflate:false,handleProtocols:null,clientTracking:true,closeTimeout:CLOSE_TIMEOUT,verifyClient:null,noServer:false,backlog:null,server:null,host:null,path:null,port:null,WebSocket,...options};if(options.port==null&&!options.server&&!options.noServer||options.port!=null&&(options.server||options.noServer)||options.server&&options.noServer){throw new TypeError('One and only one of the "port", "server", or "noServer" options '+"must be specified")}if(options.port!=null){this._server=http.createServer((req,res)=>{const body=http.STATUS_CODES[426];res.writeHead(426,{"Content-Length":body.length,"Content-Type":"text/plain"});res.end(body)});this._server.listen(options.port,options.host,options.backlog,callback)}else if(options.server){this._server=options.server}if(this._server){const emitConnection=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)}})}if(options.perMessageDeflate===true)options.perMessageDeflate={};if(options.clientTracking){this.clients=new Set;this._shouldEmitClose=false}this.options=options;this._state=RUNNING}address(){if(this.options.noServer){throw new Error('The server is operating in "noServer" mode')}if(!this._server)return null;return this._server.address()}close(cb){if(this._state===CLOSED){if(cb){this.once("close",()=>{cb(new Error("The server is not running"))})}process.nextTick(emitClose,this);return}if(cb)this.once("close",cb);if(this._state===CLOSING)return;this._state=CLOSING;if(this.options.noServer||this.options.server){if(this._server){this._removeListeners();this._removeListeners=this._server=null}if(this.clients){if(!this.clients.size){process.nextTick(emitClose,this)}else{this._shouldEmitClose=true}}else{process.nextTick(emitClose,this)}}else{const server=this._server;this._removeListeners();this._removeListeners=this._server=null;server.close(()=>{emitClose(this)})}}shouldHandle(req){if(this.options.path){const index=req.url.indexOf("?");const pathname=index!==-1?req.url.slice(0,index):req.url;if(pathname!==this.options.path)return false}return true}handleUpgrade(req,socket,head,cb){socket.on("error",socketOnError);const key=req.headers["sec-websocket-key"];const upgrade=req.headers.upgrade;const version=+req.headers["sec-websocket-version"];if(req.method!=="GET"){const message="Invalid HTTP method";abortHandshakeOrEmitwsClientError(this,req,socket,405,message);return}if(upgrade===undefined||upgrade.toLowerCase()!=="websocket"){const message="Invalid Upgrade header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(key===undefined||!keyRegex.test(key)){const message="Missing or invalid Sec-WebSocket-Key header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(version!==13&&version!==8){const message="Missing or invalid Sec-WebSocket-Version header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message,{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(req)){abortHandshake(socket,400);return}const secWebSocketProtocol=req.headers["sec-websocket-protocol"];let protocols=new Set;if(secWebSocketProtocol!==undefined){try{protocols=subprotocol.parse(secWebSocketProtocol)}catch(err){const message="Invalid Sec-WebSocket-Protocol header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}const secWebSocketExtensions=req.headers["sec-websocket-extensions"];const extensions={};if(this.options.perMessageDeflate&&secWebSocketExtensions!==undefined){const perMessageDeflate=new PerMessageDeflate({...this.options.perMessageDeflate,isServer:true,maxPayload:this.options.maxPayload});try{const offers=extension.parse(secWebSocketExtensions);if(offers[PerMessageDeflate.extensionName]){perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);extensions[PerMessageDeflate.extensionName]=perMessageDeflate}}catch(err){const message="Invalid or unacceptable Sec-WebSocket-Extensions header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}if(this.options.verifyClient){const info={origin:req.headers[`${version===8?"sec-websocket-origin":"origin"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info,(verified,code,message,headers)=>{if(!verified){return abortHandshake(socket,code||401,message,headers)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info))return abortHandshake(socket,401)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)}completeUpgrade(extensions,key,protocols,req,socket,head,cb){if(!socket.readable||!socket.writable)return socket.destroy();if(socket[kWebSocket]){throw new Error("server.handleUpgrade() was called more than once with the same "+"socket, possibly due to a misconfiguration")}if(this._state>RUNNING)return abortHandshake(socket,503);const digest=createHash("sha1").update(key+GUID).digest("base64");const headers=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${digest}`];const ws=new this.options.WebSocket(null,undefined,this.options);if(protocols.size){const protocol=this.options.handleProtocols?this.options.handleProtocols(protocols,req):protocols.values().next().value;if(protocol){headers.push(`Sec-WebSocket-Protocol: ${protocol}`);ws._protocol=protocol}}if(extensions[PerMessageDeflate.extensionName]){const params=extensions[PerMessageDeflate.extensionName].params;const value=extension.format({[PerMessageDeflate.extensionName]:[params]});headers.push(`Sec-WebSocket-Extensions: ${value}`);ws._extensions=extensions}this.emit("headers",headers,req);socket.write(headers.concat(`\r
|
|
2
2
|
`).join(`\r
|
|
3
3
|
`));socket.removeListener("error",socketOnError);ws.setSocket(socket,head,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation});if(this.clients){this.clients.add(ws);ws.on("close",()=>{this.clients.delete(ws);if(this._shouldEmitClose&&!this.clients.size){process.nextTick(emitClose,this)}})}cb(ws,req)}}module.exports=WebSocketServer;function addListeners(server,map){for(const event of Object.keys(map))server.on(event,map[event]);return function removeListeners(){for(const event of Object.keys(map)){server.removeListener(event,map[event])}}}function emitClose(server){server._state=CLOSED;server.emit("close")}function socketOnError(){this.destroy()}function abortHandshake(socket,code,message,headers){message=message||http.STATUS_CODES[code];headers={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(message),...headers};socket.once("finish",socket.destroy);socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
|
|
4
4
|
`+Object.keys(headers).map((h)=>`${h}: ${headers[h]}`).join(`\r
|
|
@@ -1323,7 +1323,7 @@ ${qn.join(`
|
|
|
1323
1323
|
return globalThis.__omowright.elementRegistry.get(ref);
|
|
1324
1324
|
}`,arguments:[{value:qn}],executionContextId:Jn.isolatedContextId,returnByValue:false},Jn.sessionId).catch((xn)=>(isContextDestroyedError(xn)&&jn.invalidateContext(Vn),{result:{}})),Zn=typeof Yn==`object`&&Yn&&`objectId`in Yn?Yn.objectId:undefined;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].toSorted((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;var SNAPSHOT_RETRY_DELAY_MS;var SNAPSHOT_MAX_RETRIES;var 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 init_annotate_screenshot=__esmMin(()=>{});var AI_TAB_STABLE_VIEWPORT;var 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 errorMessageOf(error){const message=readProperty(error,`message`);return message===undefined?undefined:String(message)}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(path2.dirname(xn),{recursive:true})}async function readProcessStderr(xn){return xn.stderr}function createFfmpegVideoRecorderClass(){return class FfmpegVideoRecorder{#e;#t;#n=0;#r=false;#i=null;#a=Promise.resolve();#o=0;#s=[];#failure=null;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`]})}async ready(){await this.#t.ready;if(this.#t.error){await this.dispose();throw new VideoRecordingError(this.#t.error.message,{cause:this.#t.error})}}async dispose(){await disposeProcess(this.#t)}writeFrame(xn,jn){if(this.#r||this.#failure)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()).catch(async(error)=>{this.#failure??=error;await this.dispose()})}this.#i={buffer:xn,frameNumber:Vn,timestamp:jn},this.#o=Date.now()}async stop(xn){try{if(this.#r)return;if(this.#failure)throw this.#failure;if(!this.#i){if(!xn)throw Error(`Video recorder did not capture any frames.`);this.writeFrame(xn,Date.now()/1000)}let jn=this.#i;if(!jn)throw Error(`Video recorder did not capture any frames.`);let Vn=Math.max((Date.now()-this.#o)/1000,1);if(this.writeFrame(Buffer.from([]),jn.timestamp+Vn),this.#r=true,await withCurrentReplAbort(async()=>await this.#a),this.#failure)throw this.#failure;if(!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,ENCODER_EXIT_TIMEOUT_MS));if(Jn!==0){let xn=await readProcessStderr(this.#t);throw Error(xn.trim()||`ffmpeg exited with code ${Jn}`)}}catch(error){throw new VideoRecordingError(errorMessageOf(error),{cause:error})}finally{await this.dispose()}}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))}}}}}function createOmOVideoClass(){return class OmOVideo{#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);await ei.ready();let{promise:ti,resolve:ni}=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()/1000;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:(error)=>ni({error}),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,await ei.dispose(),ni({error: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`,undefined,jn.sessionId).catch(()=>{});try{let Vn=await this.#e.screenshot({type:`jpeg`}).catch(()=>{return}),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({path:qn})}catch(xn){throw this.#n=null,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);let result=await this.#t.completion;if(result.error)throw result.error;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(()=>{})})}}}var DEFAULT_VIDEO_FORMAT;var DEFAULT_VIDEO_FRAMERATE;var DEFAULT_VIDEO_JPEG_QUALITY;var DEFAULT_VIDEO_MAX_EDGE;var FfmpegVideoRecorder;var OmOVideo;var 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=createFfmpegVideoRecorderClass(),OmOVideo=createOmOVideoClass()});function isOmOEvaluateOptions(xn){if(typeof xn!=`object`||!xn||Array.isArray(xn))return false;let jn=Object.keys(xn);return jn.length===1&&jn[0]===`userGesture`}function resolveEvaluateCall(xn,jn,Vn){if(Vn!==undefined&&!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:undefined,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!==undefined){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===undefined?`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!==undefined)return typeof xn==`number`?`${xn}px`:xn}function createOmOPageClass(){return class OmOPage{#networkCount=0;#networkOff=null;#closeRequested=false;cdp;frameManager;targetId;modifierState;mouse;keyboard;events=new Emittery;browser;#e=new Map;#t=null;#n;#r=``;#i=null;#a=[];#o=null;#s=false;#c=0;#runtimeListeners=0;#runtimeEpoch=0;#runtimeReady=Promise.resolve();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));this.#a.push(subscribeConsoleEvents(this),subscribePageErrors(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.listenerCount(`popup`)||this.browser.resolvePopup(xn).then((xn)=>xn&&this.events.emit(`popup`,xn)).catch((xn)=>this.events.emit(`popupError`,xn).catch(jn))})),this.#u(`Inspector.targetCrashed`,()=>{this.events.emit(`crash`).catch(jn)}),this.#a.push(this.cdp.on(`Target.targetDestroyed`,(xn)=>{xn.targetId===this.targetId&&this.dispose().catch(jn)}),this.cdp.on(`Target.detachedFromTarget`,(xn)=>{xn.targetId===this.targetId&&this.cdp.send(`Target.getTargetInfo`,{targetId:this.targetId}).then(()=>{},()=>this.dispose()).catch(jn)})),this.frameManager.onSessionInitialized=(xn)=>{this.#c>0&&this.#p(true,[xn]),this.#runtimeListeners>0&&this.#setRuntimeCapture(true,[xn])}}#u(xn,jn){this.#a.push(this.cdp.on(xn,(xn,Vn)=>{Vn.sessionId===this.#n&&jn(xn)}))}on(xn,jn){assertPageEvent(xn);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();RUNTIME_PAGE_EVENTS.has(xn)&&this.#addRuntimeListener();const off=()=>{if(!active)return;active=false;qn();Vn.get(jn)===off&&Vn.delete(jn);if(isNetwork&&--this.#networkCount===0){this.#networkOff?.();this.#networkOff=null}xn===`filechooser`&&this.#h();RUNTIME_PAGE_EVENTS.has(xn)&&this.#removeRuntimeListener()};Vn.set(jn,off);this.#e.set(xn,Vn);return off}off(xn,jn){assertPageEvent(xn);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={}){if(typeof jn===`function`)jn={predicate:jn};assertPageEvent(xn);let Vn=jn.timeout??DEFAULT_WAIT_TIMEOUT_MS;if(xn===`download`){let qn=Date.now();return await new Promise((Jn,Yn)=>{let Zn=false,Qn=()=>{ri(),clearTimeout(ni)},ei=(xn)=>{Zn||(Zn=true,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},undefined,{extensionBridge:this.browser.extensionBridgeRoute}).then((xn)=>{ti(new OmODownload(this,{guid:String(xn.downloadId),sourcePath:xn.absolutePath,startedAfterMs:qn,suggestedFilename:path2.basename(xn.absolutePath),url:this.url()}))}).catch(()=>{})})}return await new Promise((qn,Jn)=>{let Yn=false,Zn=null,ri=()=>{},Qn=()=>{ni(),ri(),clearTimeout(ti),Zn&&clearTimeout(Zn)},ei=(xn)=>{Yn||(Yn=true,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))))}})()});xn===`popup`&&(ri=this.events.on(`popupError`,({data:xn})=>ei(()=>Jn(xn))))})}#d(){this.#networkOff?.();this.#networkOff=null;disposeNetwork(this);for(let xn of this.#a)xn();this.#a=[]}async dispose(){this.#s||(this.#s=true,await this.#o?.stop().catch(()=>{}),++this.#runtimeEpoch,this.#runtimeListeners>0&&await this.#setRuntimeCapture(false),this.#runtimeListeners=0,this.#d(),this.#c=0,await this.events.emit(`close`),this.events.clearListeners(),this.#e.clear())}reconnect(xn){this.#n=xn,this.#s=false,++this.#runtimeEpoch,this.#d(),this.#l(),this.#r=this.frameManager.getFrame(this.frameManager.mainFrameId)?.url??this.#r,this.#c>0&&this.#p(true),this.#runtimeListeners>0&&this.#setRuntimeCapture(true,undefined,true)}#f(){return[...new Set([this.#n,...[...this.frameManager.frames.values()].map((xn)=>xn.sessionId)])]}async prepareForPotentialFileChooser(){this.#c!==0&&await this.#p(true)}#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(true)}#h(){this.#c!==0&&(--this.#c,this.#c===0&&this.#p(false))}#setRuntimeCapture(enabled,sessions=this.#f(),clearEntries=false){const epoch=this.#runtimeEpoch;return this.#runtimeReady=this.#runtimeReady.then(()=>withoutReplContext(async()=>{await Promise.allSettled(sessions.map(async(session)=>{if(enabled){if(clearEntries)await this.cdp.send(`Runtime.discardConsoleEntries`,undefined,session).catch(()=>{});if(epoch!==this.#runtimeEpoch||this.#runtimeListeners===0)return}await this.cdp.send(enabled||hasPageBindings(this)?`Runtime.enable`:`Runtime.disable`,undefined,session)}))}))}#addRuntimeListener(){this.#runtimeListeners+=1,this.#runtimeListeners===1&&(++this.#runtimeEpoch,this.#setRuntimeCapture(true,undefined,true))}#removeRuntimeListener(){this.#runtimeListeners!==0&&(--this.#runtimeListeners,this.#runtimeListeners===0&&(++this.#runtimeEpoch,this.#setRuntimeCapture(false)))}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(this.#runtimeListeners>0)await this.#runtimeReady;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;const documents=trackDocumentResponses(this,this.frameManager.mainFrameId);const readinessController=new AbortController;let readiness;try{await releaseNetwork?.ready;await documents.ready;let Vn=jn.waitUntil??`interactive`,qn=await this.resolveSessionId(this.#n),Jn=()=>{},Yn=Vn===`commit`?null:Vn===`interactive`||Vn===`stable`?readiness=waitForNavigationReadiness(this,Vn,DEFAULT_WAIT_TIMEOUT_MS,readinessController.signal).then(()=>{}):Vn===`networkidle`?this.#S(DEFAULT_WAIT_TIMEOUT_MS):new Promise((xn,jn)=>{let Yn=false,Zn,Qn=()=>{},ei=(xn)=>{Yn||(Yn=true,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)});Yn?.catch(()=>{});const Zn=await this.cdp.send(`Page.navigate`,{url:xn},qn);if(Zn.errorText)throw Error(Zn.errorText);this.#r=(await this.cdp.send(`Page.getFrameTree`,{},qn)).frameTree.frame.url;if(Vn===`domcontentloaded`&&Yn){if(!Zn.loaderId){Jn(),await this.#v(`Timed out waiting for "${Vn}" after goto`);return null}try{await Yn}catch(xn){if(!await this.#_())throw xn}return documents.response(Zn.loaderId)}Yn&&await Yn;return documents.response(Zn.loaderId)}finally{readinessController.abort();await readiness?.catch(()=>{});documents.dispose(),releaseNetwork?.()}}async goBack(){return await this.#historyStep(-1)}async goForward(){return await this.#historyStep(1)}async#historyStep(delta){let history=await this._sendToTarget(`Page.getNavigationHistory`),entry=history.entries[history.currentIndex+delta];if(!entry)return null;return await this.#navigationResponse(()=>this._sendToTarget(`Page.navigateToHistoryEntry`,{entryId:entry.id}))}async reload(){return await this.#navigationResponse(()=>this._sendToTarget(`Page.reload`))}async waitForTimeout(timeout){await sleep$12(timeout)}async setContent(html,options={}){const waitUntil=options.waitUntil??`load`,timeout=options.timeout??DEFAULT_WAIT_TIMEOUT_MS;if(![`load`,`domcontentloaded`,`networkidle`,`commit`].includes(waitUntil))throw Error(`page.setContent: waitUntil must be one of load, domcontentloaded, networkidle, commit; got "${waitUntil}"`);let timer;const deadline=new Promise((_,reject)=>{if(timeout>0)timer=setTimeout(()=>reject(Error(`page.setContent: Timeout ${timeout}ms exceeded waiting for "${waitUntil}"`)),timeout)});const idle=waitUntil===`networkidle`?this.#S(timeout>0?timeout:2147483647):null;idle?.catch(()=>{});try{await Promise.race([deadline,(async()=>{await this.evaluate(({html,waitUntil})=>{document.open();const ready=waitUntil===`commit`?null:new Promise((resolve)=>waitUntil===`domcontentloaded`?document.addEventListener(`DOMContentLoaded`,()=>resolve(),{once:true}):window.addEventListener(`load`,()=>resolve(),{once:true}));document.write(html);document.close();return ready},{html,waitUntil});await idle})()])}finally{clearTimeout(timer)}}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 waitForFunction(xn,jn,Vn){let qn=Vn?.polling??`raf`,Jn=Vn?.timeout??DEFAULT_WAIT_TIMEOUT_MS;if(qn!==`raf`&&!(typeof qn==`number`&&Number.isFinite(qn)&&qn>0))throw Error(`page.waitForFunction: polling must be "raf" or a positive number of milliseconds`);if(!(typeof Jn==`number`&&Number.isFinite(Jn)&&Jn>=0))throw Error(`page.waitForFunction: timeout must be a non-negative number of milliseconds (0 waits forever)`);let Yn=typeof xn==`function`?xn.toString():String(xn),Zn=Jn>0?Date.now()+Jn:1/0,Qn=`async function(arg, polling, remainingMs) { var __name = (t) => t; const predicate = (a) => { const value = (${Yn}); return typeof value === 'function' ? value(a) : value; }; const start = performance.now(); const next = () => new Promise((resolve) => { if (polling !== 'raf') { setTimeout(resolve, polling); return; } let frame; const fallback = setTimeout(() => { resolve(); cancelAnimationFrame(frame); }, ${WAIT_FOR_FUNCTION_RAF_FALLBACK_MS}); frame = requestAnimationFrame(() => { clearTimeout(fallback); resolve(); }); }); for (;;) { const value = await predicate(arg); if (value) return { done: true, value }; if (remainingMs > 0 && performance.now() - start >= remainingMs) return { done: false }; await next(); } }`,Cn,$n=new Promise((jn,qn)=>{Cn=this.events.on(`close`,()=>qn(Error(`page.waitForFunction: the page closed while waiting`)))});$n.catch(()=>{});try{for(;;){let xn=Zn-Date.now();if(xn<=0)throw new WaitForFunctionTimeoutError(Yn,Jn);let Vn,Xn=new Promise((jn,qn)=>{Number.isFinite(xn)&&(Vn=setTimeout(()=>qn(new WaitForFunctionTimeoutError(Yn,Jn)),xn))}),ei=(async()=>{let Vn=await this.#x(),{result:Jn,exceptionDetails:Zn}=await this._sendToTarget(`Runtime.callFunctionOn`,{objectId:Vn,functionDeclaration:Qn,arguments:[{value:jn},{value:qn},{value:Number.isFinite(xn)?xn:0}],returnByValue:true,awaitPromise:true},{timeoutMs:Number.isFinite(xn)?xn+WAIT_FOR_FUNCTION_CALL_MARGIN_MS:0});if(Zn)throw Error(formatRuntimeException(Zn,`page.waitForFunction: the page function threw`));return Jn.value})();ei.catch(()=>{});try{let xn=await Promise.race([ei,Xn,$n]);if(readOptionalProperty(xn,`done`))return readProperty(xn,`value`)}catch(xn){if(isUnserializableResultError(xn))return true;if(this.#s||this.#closeRequested&&isSessionDetachedError(xn))throw Error(`page.waitForFunction: the page closed while waiting`);if(!isNavigationInterruptedError(xn))throw xn;await Promise.race([sleep$12(20),$n])}finally{clearTimeout(Vn)}}}finally{definedOrThrow(Cn)()}}async waitForSelector(xn,jn={}){let Vn=jn.state??`visible`,qn=jn.timeout??3000,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:false,visible:false};let Vn=jn.getBoundingClientRect(),qn=window.getComputedStyle(jn);return{attached:true,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.replaceAll(">>",">\\x3e")}/${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===undefined){let{result:jn,exceptionDetails:Vn}=await this._sendToTarget(`Runtime.evaluate`,{expression:xn,returnByValue:true,awaitPromise:true,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:true,awaitPromise:true,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===undefined){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:true,awaitPromise:true,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:true,awaitPromise:true,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=false}={}){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:undefined,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()):undefined;if(qn===0)throw jn;let Jn={format:xn.type??`png`,captureBeyondViewport:false,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)}
|
|
1325
1325
|
Viewport 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=path2.join(jn,path2.basename(xn.path));await mkdir(path2.dirname(Vn),{recursive:true}),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(path2.dirname(jn),{recursive:true}),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`):undefined,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)}:undefined,printBackground:xn.printBackground??true,transferMode:`ReturnAsBase64`,width:formatPdfLength(xn.width)},{data:qn}=await this._sendToTarget(`Page.printToPDF`,Vn),Jn=Buffer.from(qn,`base64`);return jn&&(await mkdir(path2.dirname(jn),{recursive:true}).catch(()=>{}),await writeFile(jn,Jn)),Jn}async close(xn={}){this.#closeRequested=true;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`,undefined,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#navigationResponse(trigger){let frameId=this.frameManager.mainFrameId,documents=trackDocumentResponses(this,frameId),offs=[],timer;try{await documents.ready;let sessionId=await this.resolveSessionId(this.#n),deadline=new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error(`Timed out waiting for navigation`)),DEFAULT_WAIT_TIMEOUT_MS)}),committed=new Promise((resolve)=>{offs.push(this.cdp.on(`Page.frameNavigated`,(params,meta)=>{meta.sessionId===sessionId&&!params.frame.parentId&&resolve(params.frame.loaderId)}),this.cdp.on(`Page.navigatedWithinDocument`,(params,meta)=>{meta.sessionId===sessionId&¶ms.frameId===frameId&&resolve(null)}))});deadline.catch(()=>{});let[,loaderId]=await Promise.race([Promise.all([trigger(),committed]),deadline]);if(!loaderId)return null;await Promise.race([this.cdp.send(`Page.getFrameTree`,undefined,sessionId),deadline]);return documents.response(loaderId)}finally{clearTimeout(timer);for(let off of offs)off();documents.dispose()}}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!==undefined){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}}}var DEFAULT_WAIT_TIMEOUT_MS;var NETWORK_IDLE_MS;var MAX_SCREENSHOT_TEXTURE_SIZE;var FILECHOOSER_OOPIF_FALLBACK_MS;var OmOPage;var 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=30000,NETWORK_IDLE_MS=500,MAX_SCREENSHOT_TEXTURE_SIZE=16384,FILECHOOSER_OOPIF_FALLBACK_MS=2000,OmOPage=createOmOPageClass()});init_client$6();init_session_manager();init_frame_manager();init_page();Object.assign(initialized(()=>OmOPage).prototype,{addInitScript,exposeFunction,exposeBinding,setExtraHTTPHeaders,setViewportSize,emulateMedia});var testIdAttributeName="data-testid";var selectors={setTestIdAttribute(attributeName){if(typeof attributeName!=="string"||!/^[^\s"'>/=[\]]+$/.test(attributeName)){throw new TypeError(`selectors.setTestIdAttribute: invalid attribute name ${JSON.stringify(attributeName)}`)}testIdAttributeName=attributeName}};function isRegExpValue(value){return Object.prototype.toString.call(value)==="[object RegExp]"}function attributeSelector(name,value,exact){if(isRegExpValue(value))return`internal:attr=[${name}=/${value.source.replaceAll(">>",">\\x3e")}/${value.flags}]`;return`internal:attr=[${name}=${JSON.stringify(String(value)).replaceAll(">","\\u003e")}${exact?"s":"i"}]`}class AttributeLocatorGetters{getByAltText(text,options={}){return this.locator(attributeSelector("alt",text,options.exact))}getByPlaceholder(text,options={}){return this.locator(attributeSelector("placeholder",text,options.exact))}getByTestId(testId){return this.locator(attributeSelector(testIdAttributeName,testId,true))}getByTitle(text,options={}){return this.locator(attributeSelector("title",text,options.exact))}}for(const Container of[initialized(()=>OmOPage),initialized(()=>OmOFrame),initialized(()=>FrameLocator)]){for(const name of Object.getOwnPropertyNames(AttributeLocatorGetters.prototype)){if(name!=="constructor")Object.defineProperty(Container.prototype,name,definedOrThrow(Object.getOwnPropertyDescriptor(AttributeLocatorGetters.prototype,name)))}}initialized(()=>OmOPage).prototype.route=function(url,handler,options){return pageRoute(this,url,handler,options)};initialized(()=>OmOPage).prototype.unroute=function(url,handler){return pageUnroute(this,url,handler)};initialized(()=>OmOPage).prototype.unrouteAll=function(){return pageUnrouteAll(this)};var shared=new Map;function withinTimeout(pending,timeoutMs,message){let timer;return Promise.race([pending,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(message)),timeoutMs)})]).finally(()=>clearTimeout(timer))}function release(key,entry){entry.refs-=1;if(entry.refs>0)return Promise.resolve();if(shared.get(key)===entry)shared.delete(key);return entry.ready.then((connection)=>connection.close(),()=>{})}function bindTo(target,value){return typeof value==="function"?value.bind(target):value}class SharedConnectionError extends Error{constructor(){super("this browser connection is shared; pass dialogPolicy to connect()/connectNamed() so this holder gets its own connection");this.name="SharedConnectionError";this.code="shared_connection"}}var RESERVED=new Set(["cdp","close","setDialogPolicy"]);function refuse(what){return(_target,property)=>{throw new TypeError(`cannot change ${String(property)} on ${what} through a handle: every holder of this connection uses it`)}}function readOnly(what,get){return{get,set:refuse(what),defineProperty:refuse(what),deleteProperty:refuse(what)}}function lease(key,entry,connection){let closed;const overlay=Object.create(null);const subscriptions=new Set;const transportSubscriptions=new Set;const unsubscribeAll=(set)=>{for(const unsubscribe of[...set])unsubscribe()};const ensureOpen=(property)=>{if(closed&&typeof property==="string"&&property!=="then"){throw new Error("this browser connection handle was closed")}};const close=()=>{if(!closed){unsubscribeAll(subscriptions);closed=release(key,entry)}return closed};const setDialogPolicy=(policy)=>{ensureOpen("setDialogPolicy");if(entry.refs>1)throw new SharedConnectionError;if(shared.get(key)===entry)shared.delete(key);return connection.setDialogPolicy(policy)};const tracked=(subscribe,...sets)=>(...args)=>{const remove=subscribe(...args);let removed=false;const unsubscribe=()=>{if(removed)return;removed=true;for(const set of sets)set.delete(unsubscribe);remove()};for(const set of sets)set.add(unsubscribe);return unsubscribe};const client=connection.cdp;const sharedTransportEvents=client.transportEvents;if(sharedTransportEvents===undefined)throw new TypeError("Cannot create proxy with a non-object as target or handler");const transportEvents=new Proxy(sharedTransportEvents,readOnly("the shared transport events",(target,property)=>{ensureOpen(property);if(property==="on"){const on=(name,listener)=>target.on(name,(event)=>listener(event));return tracked(on,subscriptions,transportSubscriptions)}if(property==="clearListeners")return()=>unsubscribeAll(transportSubscriptions);if(property==="emit"){return()=>{throw new TypeError("cannot emit transport events through a handle: every holder of this connection hears them")}}return bindTo(target,Reflect.get(target,property,target))}));const clientView=new Proxy(client,readOnly("the shared CDP client",(target,property)=>{ensureOpen(property);if(property==="setDialogPolicy")return setDialogPolicy;if(property==="close")return close;if(property==="on")return tracked(target.on.bind(target),subscriptions);if(property==="transportEvents")return transportEvents;return bindTo(target,Reflect.get(target,property,target))}));return new Proxy(connection,{get(target,property){if(property==="close"||property===Symbol.asyncDispose)return close;ensureOpen(property);if(property==="setDialogPolicy")return setDialogPolicy;if(property==="cdp")return clientView;if(Object.hasOwn(overlay,property))return overlay[property];return bindTo(target,Reflect.get(target,property,target))},set(target,property,value){ensureOpen(property);if(RESERVED.has(property))return refuse("a handle")(target,property);return Reflect.set(overlay,property,value)},defineProperty(target,property,descriptor){ensureOpen(property);if(RESERVED.has(property))return refuse("a handle")(target,property);if(descriptor.configurable!==true)return false;return Reflect.defineProperty(overlay,property,descriptor)},deleteProperty(target,property){ensureOpen(property);if(Object.hasOwn(overlay,property))return Reflect.deleteProperty(overlay,property);return refuse("the shared connection")(target,property)},has(target,property){return Object.hasOwn(overlay,property)||Reflect.has(target,property)},ownKeys(target){return[...new Set([...Reflect.ownKeys(target),...Reflect.ownKeys(overlay)])]},getOwnPropertyDescriptor(target,property){return Object.hasOwn(overlay,property)?Reflect.getOwnPropertyDescriptor(overlay,property):Reflect.getOwnPropertyDescriptor(target,property)}})}function isPlainData(value,path=new Set){if(typeof value==="function"||value===null||typeof value!=="object")return true;if(path.has(value))return false;const prototype=Object.getPrototypeOf(value);const isArray=Array.isArray(value);if(isArray?prototype!==Array.prototype:prototype!==Object.prototype&&prototype!==null){return false}path.add(value);try{for(const key of Reflect.ownKeys(value)){if(isArray&&key==="length")continue;if(typeof key==="symbol")return false;const descriptor=Object.getOwnPropertyDescriptor(value,key);if(!readProperty(descriptor,"enumerable")||descriptor===undefined||!("value"in descriptor))return false;if(!isPlainData(descriptor.value,path))return false}return true}finally{path.delete(value)}}function frozenCopy(value){if(value===null||typeof value!=="object")return value;let copy;if(Array.isArray(value)){const sparse=[];sparse.length=value.length;copy=sparse}else copy=Object.create(Object.getPrototypeOf(value));for(const key of Object.keys(value)){Object.defineProperty(copy,key,{value:frozenCopy(readProperty(value,key)),enumerable:true})}return Object.freeze(copy)}function openingOptions(snapshot){if(snapshot?.dialogPolicy!=null||snapshot?.client?.dialogPolicy!=null)return snapshot;return Object.freeze({...snapshot,dialogPolicy:Object.freeze({accept:true})})}function canShareConnection(options){return options?.client?.authorizer===undefined&&isPlainData(options)}async function acquireSharedConnection(webSocketDebuggerUrl,options,{open,timeoutMs}){if(!canShareConnection(options))return open(options);const snapshot=frozenCopy(options);let entry=shared.get(webSocketDebuggerUrl);if(entry&&!isDeepStrictEqual(entry.options,snapshot))return open(openingOptions(snapshot));if(!entry){entry={options:snapshot,refs:0,ready:open(openingOptions(snapshot))};shared.set(webSocketDebuggerUrl,entry)}entry.refs+=1;try{const connection=await entry.ready;const reconnected=connection.cdp.ensureConnected();await(timeoutMs===undefined?reconnected:withinTimeout(reconnected,timeoutMs,`timed out after ${timeoutMs}ms reconnecting the CDP session on ${webSocketDebuggerUrl}`));return lease(webSocketDebuggerUrl,entry,connection)}catch(error){if(shared.get(webSocketDebuggerUrl)===entry)shared.delete(webSocketDebuggerUrl);await release(webSocketDebuggerUrl,entry);throw error}}var managers=new WeakMap;var CAPABILITY=targetCreationCapability;function optionsKey(options={}){return JSON.stringify({viewport:{...DEFAULT_AGENT_VIEWPORT,...options.viewport},closeTimeoutMs:options.closeTimeoutMs??5000})}class AgentTabManager{#connection;#owned=new Map;#unsubscribers=[];#disposed=false;#closing=new Map;viewport;closeTimeoutMs;ready;constructor(connection,options={}){if(!connection?.cdp)throw new TypeError("createAgentTabs requires a browser connection");this.#connection=connection;this.viewport=Object.freeze({...DEFAULT_AGENT_VIEWPORT,...options.viewport});this.closeTimeoutMs=options.closeTimeoutMs??5000;this.#unsubscribers.push(connection.cdp.on("Target.targetDestroyed",(info)=>this.#destroyed(info?.targetId)));this.#unsubscribers.push(connection.cdp.on("Target.targetCrashed",(info)=>this.#destroyed(info?.targetId)));this.#unsubscribers.push(connection.cdp.transportEvents?.on?.("disconnected",()=>{for(const id of[...this.#owned.keys()])this.#destroyed(id,Error("Browser transport disconnected"))}));this.ready=Promise.resolve(connection.cdp.ensureConnected?.())}async create(url="about:blank",options={}){if(this.#disposed)throw Error("Agent tab manager is disposed");await this.ready;const viewport={...this.viewport,...options.viewport};const result=await this.#connection.cdp.send("Target.createTarget",{url:"about:blank",background:true,newWindow:true,...options.browserContextId?{browserContextId:options.browserContextId}:{}},undefined,{capability:CAPABILITY});const targetId=result.targetId;if(await this.#isHeadless())await this.#connection.cdp.send("Target.activateTarget",{targetId});const tab=await this.adopt(targetId,{viewport});if(tab.page===null)throw new TypeError(`Target ${targetId} is still being adopted`);if(url!=="about:blank")await tab.page.goto(url);return Object.freeze({...tab,page:tab.page})}async adopt(targetId,options={}){if(this.#disposed)throw Error("Agent tab manager is disposed");const existing=this.#owned.get(targetId);if(existing)return this.#public(existing);const viewport={...this.viewport,...options.viewport};const record={targetId,page:null,viewport:Object.freeze({...viewport}),repinQueue:Promise.resolve()};this.#owned.set(targetId,record);try{const page=await this.#connection.attachPage(targetId);record.page=page;await repinViewport(page,record.viewport);record.navigationOff=page.on?.("framenavigated",(event)=>{if(!event.parentFrameId)this.#repin(record)});return this.#public(record,page)}catch(error){await this.#connection.cdp.send("Target.closeTarget",{targetId}).catch(()=>{});throw error}}#public(record,page=record.page){return Object.freeze({targetId:record.targetId,page,viewport:{...record.viewport},close:(options)=>this.close(record.targetId,options)})}get(targetId){const record=targetId===undefined?undefined:this.#owned.get(targetId);return record?this.#public(record):null}list(){return[...this.#owned.values()].map((record)=>this.#public(record))}async#isHeadless(){if(typeof this.#connection.cdp.isHeadless==="boolean")return this.#connection.cdp.isHeadless;const version=await this.#connection.cdp.send("Browser.getVersion").catch(()=>null);return/Headless/i.test(version?.product??"")}#queueRepin(record,viewport,reportErrors=false){const size={...viewport};const operation=record.repinQueue.then(async()=>{try{if(record.page===null)throw new TypeError("Cannot read properties of null (reading 'resolveSessionId')");await repinViewport(record.page,size)}catch(error){if(reportErrors)console.warn(`[agent-tabs] viewport repin failed for ${record.targetId}`,error);else throw error}record.viewport=Object.freeze(size);return{...size}});record.repinQueue=operation.catch(()=>{});return operation}async#repin(record){await this.#queueRepin(record,record.viewport,true)}async repin(tabOrTargetId,viewport=this.viewport){const id=typeof tabOrTargetId==="string"?tabOrTargetId:tabOrTargetId?.targetId;const record=id===undefined?undefined:this.#owned.get(id);if(!record)throw Error(`Target ${id} is not owned by this manager`);return this.#queueRepin(record,viewport)}async close(tabOrTargetId,options={}){const id=typeof tabOrTargetId==="string"?tabOrTargetId:tabOrTargetId?.targetId;const record=id===undefined?undefined:this.#owned.get(id);if(!record||id===undefined)throw Error(`Target ${id} is not owned by this manager`);const existing=this.#closing.get(id);if(existing)return existing.promise;const{promise,resolve:resolveOperation,reject:rejectOperation}=Promise.withResolvers();const entry={promise,reject:rejectOperation};this.#closing.set(id,entry);this.#close(record,options).then(resolveOperation,rejectOperation).finally(()=>{if(this.#closing.get(id)===entry)this.#closing.delete(id)});return promise}async#close(record,options){const{promise:destroyed,resolve:resolveDestroy,reject:rejectDestroy}=Promise.withResolvers();const timeout=setTimeout(()=>rejectDestroy(Error(`Timed out waiting for target ${record.targetId} to close`)),options.timeoutMs??this.closeTimeoutMs);const off=this.#connection.cdp.on("Target.targetDestroyed",(info)=>{if(info?.targetId===record.targetId)resolveDestroy()});const offDisconnect=this.#connection.cdp.transportEvents?.on?.("disconnected",()=>rejectDestroy(Error("Browser transport disconnected")));try{if(options.runBeforeUnload&&record.page)await record.page.cdp.send("Page.close",undefined,await record.page.resolveSessionId()).catch(()=>this.#connection.cdp.send("Target.closeTarget",{targetId:record.targetId}));else await this.#connection.cdp.send("Target.closeTarget",{targetId:record.targetId});if(this.#owned.has(record.targetId))await destroyed}finally{clearTimeout(timeout);off();offDisconnect?.();if(!this.#owned.has(record.targetId))record.navigationOff?.()}}#destroyed(id,error){if(id===undefined)return;const record=this.#owned.get(id);if(!record)return;record.navigationOff?.();this.#owned.delete(id);if(error)this.#closing.get(id)?.reject(error)}async closeAll(options={}){const results=await Promise.allSettled([...this.#owned.keys()].map((id)=>this.close(id,options)));const failures=results.filter((result)=>result.status==="rejected").map((result)=>result.reason);if(failures.length)throw new AggregateError(failures,"Failed to close one or more agent tabs")}async dispose(options={closeOwned:true}){if(this.#disposed)return;let failure;if(options.closeOwned!==false)try{await this.closeAll(options)}catch(error){failure=error}this.#disposed=true;for(const off of this.#unsubscribers){if(off===undefined)throw new TypeError("off is not a function");off()}this.#unsubscribers=[];if(failure)throw failure}}function getAgentTabs(connection){return managers.get(connection)}function createAgentTabs(connection,options={}){const current=managers.get(connection);if(current){if(current._optionsKey!==optionsKey(options))throw new TypeError("Conflicting AgentTabManager options");return current}const manager=new AgentTabManager(connection,options);Object.defineProperty(manager,"_optionsKey",{value:optionsKey(options)});managers.set(connection,manager);return manager}function cookieToCdp(cookie){const{name,value,url,domain,path,httpOnly,secure,sameSite}=cookie;const out={name,value,url,domain,path,httpOnly,secure,sameSite};if(cookie.expires!==undefined&&cookie.expires!==-1)out.expires=cookie.expires;if(cookie.partitionKey!==undefined){out.partitionKey={topLevelSite:cookie.partitionKey,hasCrossSiteAncestor:true}}return out}function sanitizeCookies(cookies){const byKey=new Map;for(const cookie of cookies){const out={name:cookie.name,value:cookie.value,path:cookie.path||"/",secure:Boolean(cookie.secure),httpOnly:Boolean(cookie.httpOnly)};if(cookie.name.startsWith("__Host-")){out.secure=true;out.path="/";out.url=`https://${cookie.domain.replace(/^\./,"")}`}else{out.domain=cookie.domain}if(cookie.expires&&cookie.expires>0)out.expires=cookie.expires;if(cookie.sameSite&&(cookie.sameSite!=="None"||out.secure))out.sameSite=cookie.sameSite;const key=`${out.name}|${out.domain??out.url}`;const prev=byKey.get(key);if(!prev||(out.expires??0)>(prev.expires??0))byKey.set(key,out)}return[...byKey.values()]}async function injectCookies(page,cookies){await page._sendToTarget("Network.setCookies",{cookies:sanitizeCookies(cookies).map(cookieToCdp)})}var isCookieFilterKey=(key)=>["name","domain","path"].includes(key);class BrowserContext{#connection;#scope;#origins=new Set;constructor(connection,browserContextId){this.#connection=connection;this.#scope=browserContextId?{browserContextId}:{}}trackOrigin(url){if(!/^https?:\/\//.test(url??""))return;this.#origins.add(new URL(url).origin)}async cookies(urls=[]){const{cookies}=await this.#connection.cdp.send("Storage.getCookies",this.#scope);const parsed=(typeof urls==="string"?[urls]:urls).map((url)=>new URL(url));return cookies.filter((cookie)=>!parsed.length||parsed.some((url)=>{const domain=cookie.domain.startsWith(".")?cookie.domain.slice(1):cookie.domain;if(url.hostname!==domain&&!(cookie.domain.startsWith(".")&&url.hostname.endsWith(`.${domain}`)))return false;if(cookie.secure&&url.protocol!=="https:"&&url.hostname!=="localhost")return false;const pathname=cookie.path.endsWith("/")?cookie.path:`${cookie.path}/`;return url.pathname===cookie.path||`${url.pathname}/`.startsWith(pathname)})).map((cookie)=>{const{name,value,domain,path:cookiePath,expires,httpOnly,secure}=cookie;const out={name,value,domain,path:cookiePath,expires,httpOnly,secure,sameSite:cookie.sameSite??"Lax"};if(cookie.partitionKey)out.partitionKey=cookie.partitionKey.topLevelSite;return out})}async addCookies(cookies){const normalized=cookies.map((cookie)=>{if(typeof cookie.name!=="string"||typeof cookie.value!=="string"){throw new TypeError("Cookie name and value must be strings")}if(cookie.url!==undefined){if(cookie.domain!==undefined||cookie.path!==undefined)throw new Error("Cookie must have either url or domain and path");const url=new URL(cookie.url);if(!/^https?:$/.test(url.protocol))throw new Error("Cookie url must be HTTP or HTTPS");return cookieToCdp({...cookie,domain:url.hostname,path:url.pathname.slice(0,url.pathname.lastIndexOf("/")+1),secure:cookie.secure??url.protocol==="https:"})}if(!cookie.domain||!cookie.path)throw new Error("Cookie must have either url or domain and path");return cookieToCdp(cookie)});await this.#connection.cdp.send("Storage.setCookies",{...this.#scope,cookies:normalized})}async clearCookies(options={}){const filters=Object.entries(options).filter((entry)=>isCookieFilterKey(entry[0]));if(!filters.length){await this.#connection.cdp.send("Storage.clearCookies",this.#scope);return}const survivors=(await this.cookies()).filter((cookie)=>!filters.every(([key,filter])=>filter instanceof RegExp?new RegExp(filter.source,filter.flags.replace(/[gy]/g,"")).test(cookie[key]):cookie[key]===filter));await this.#connection.cdp.send("Storage.clearCookies",this.#scope);await this.addCookies(survivors)}async newPage(){return(await(getAgentTabs(this.#connection)??createAgentTabs(this.#connection)).create("about:blank",this.#scope)).page}async storageState(options={}){const state={cookies:await this.cookies(),origins:[]};if(this.#origins.size){const page=await this.newPage();try{await page.route("**/*",(route)=>route.fulfill({contentType:"text/html",body:"<html></html>"}));for(const origin of this.#origins){await page.goto(origin,{waitUntil:"domcontentloaded"});const{entries}=await page._sendToTarget("DOMStorage.getDOMStorageItems",{storageId:{securityOrigin:origin,isLocalStorage:true}});if(entries.length)state.origins.push({origin,localStorage:entries.map(([name,value])=>({name,value}))})}}finally{await page.close()}}if(options.path!==undefined){await mkdir3(path22.dirname(path22.resolve(options.path)),{recursive:true});await writeFile2(options.path,JSON.stringify(state,null,2))}return state}}class TabRepository{#client;constructor(client){this.#client=client}async listTargets(){return this.#client.discoverTargets()}}class BrowserConnection{#client;#sessions;#pages=new Map;#contexts=new Map;#storageRoot;#popups=new Map;#popupTargets=new Map;#attachingPopups=new Map;#ownedPopups=new Set;#popupOff=[];tabs;constructor(client,options={}){this.#client=client;this.#sessions=new SessionManager(client);this.tabs=new TabRepository(client);this.#storageRoot=path3.resolve(options.storageRoot??process.cwd());this.#popupOff.push(client.on("Target.targetCreated",({targetInfo})=>{const openerId=targetInfo?.openerId;if(targetInfo?.type!=="page"||!this.#acceptsPopup(openerId))return;const targets=this.#popupTargets.get(openerId)??[];targets.push({targetId:targetInfo.targetId});this.#popupTargets.set(openerId,targets);this.#matchPopups(openerId)}));this.#popupOff.push(client.on("Target.targetDestroyed",({targetId})=>{this.#ownedPopups.delete(targetId);const error=Error("Popup closed before attachment completed");this.#attachingPopups.get(targetId)?.reject(error);for(const targets of this.#popupTargets.values()){const target=targets.find((candidate)=>candidate.targetId===targetId);if(target)target.error=error}}))}async initialize(){await this.#client.ensureConnected();return this}get cdp(){return this.#client}setDialogPolicy(policy){if(typeof this.#client.setDialogPolicy!=="function"){throw new Error("dialog policy is not supported by this transport")}this.#client.setDialogPolicy(policy)}async listTargets(){return this.tabs.listTargets()}async newTab(url="about:blank"){return(await(getAgentTabs(this)??createAgentTabs(this)).create(url)).page}#acceptsPopup(openerId){return openerId!==undefined&&!!getAgentTabs(this)?.get(openerId)&&(this.#pages.get(openerId)?.page.events.listenerCount("popup")??0)>0}#matchPopups(openerId){const targets=this.#popupTargets.get(openerId);const queue=this.#popups.get(openerId);while(targets?.length&&queue?.length){const target=targets.shift();const pending=queue.shift();if(target===undefined||pending===undefined)break;if(target.error)pending.reject(target.error);else{this.#attachingPopups.set(target.targetId,pending);this.#ownedPopups.add(target.targetId);pending.operation=this.#attachPopup(target.targetId,pending).catch(pending.reject).finally(()=>{this.#attachingPopups.delete(target.targetId)})}}if(!targets?.length)this.#popupTargets.delete(openerId);if(!queue?.length)this.#popups.delete(openerId)}async#attachPopup(targetId,pending){const tabs=getAgentTabs(this)??createAgentTabs(this);const{page}=await tabs.adopt(targetId);if(page===null)throw new TypeError(`Popup target ${targetId} is still being adopted`);Object.assign(page,{popupMetadata:Object.freeze(pending.metadata)});await page.waitForLoadState("interactive");pending.resolve(page)}async attachPage(targetId){const attached=this.#pages.get(targetId);if(attached)return attached.page;const sessionId=await this.#sessions.resolvePageSession(targetId);const frames=new FrameManager(this.#client,targetId,sessionId);await frames.initialize();const entry={frames,page:null};const host=this.#createPageHost(targetId,entry);const page=new OmOPage(this.#client,frames,targetId,sessionId,host);const{targetInfo}=await this.#client.send("Target.getTargetInfo",{targetId});const contextId=targetInfo.browserContextId;let context=this.#contexts.get(contextId);if(!context){context=new BrowserContext(this,contextId);this.#contexts.set(contextId,context)}const pageContext=context;Object.assign(page,{context:()=>pageContext});for(const frame of frames.frames.values())pageContext.trackOrigin(frame.url);page.on("framenavigated",(frame)=>pageContext.trackOrigin(frame.url));const attachedEntry=Object.assign(entry,{page});this.#pages.set(targetId,attachedEntry);return page}#createPageHost(targetId,entry){return{daemonSession:{accountId:0,id:"standalone"},extensionBridgeRoute:{},page:null,resolvePageSession:(id,preferred)=>this.#sessions.resolvePageSession(id,preferred),setViewportSize:async(size)=>{const tabs=getAgentTabs(this);if(tabs?.get(targetId))await tabs.repin(targetId,size);else{if(entry.page===null)throw new TypeError("Cannot read properties of null (reading 'resolveSessionId')");await repinViewport(entry.page,size)}},resolvePath:(value)=>path3.resolve(this.#storageRoot,value),ensurePath:async(value)=>{const resolved=path3.resolve(this.#storageRoot,value);await mkdir4(path3.dirname(resolved),{recursive:true});return resolved},registerReadableDownloadPath:(value)=>value,isReadableDownload:()=>false,resolvePopup:async(metadata)=>{if(!this.#acceptsPopup(targetId))return;const queue=this.#popups.get(targetId)??[];const promise=new Promise((resolve,reject)=>queue.push({resolve,reject,metadata:{url:metadata.url,windowName:metadata.windowName}}));this.#popups.set(targetId,queue);this.#matchPopups(targetId);return promise},openPopupTab:async()=>{throw Error("Popup tab control requires the extension bridge")},closeTab:async(_page,options={})=>{if(options.runBeforeUnload){await this.#client.send("Page.close",undefined,await this.#sessions.resolvePageSession(targetId))}else{await this.#client.send("Target.closeTarget",{targetId})}await entry.page?.dispose();await entry.frames.dispose();this.#pages.delete(targetId)}}}async close(){for(const off of this.#popupOff)off();for(const queue of this.#popups.values()){for(const pending of queue)pending.reject(Error("Browser connection closed"))}this.#popups.clear();this.#popupTargets.clear();for(const pending of this.#attachingPopups.values())pending.reject(Error("Browser connection closed"));await Promise.all([...this.#attachingPopups.values()].map((pending)=>pending.operation));const tabs=getAgentTabs(this);if(tabs){await Promise.all([...this.#ownedPopups].filter((id)=>tabs.get(id)).map((id)=>tabs.close(id)));await tabs.dispose({closeOwned:false})}for(const[targetId,entry]of[...this.#pages]){await entry.page.dispose().catch(()=>{});await entry.frames.dispose().catch(()=>{});this.#pages.delete(targetId)}await this.#sessions.dispose();await this.#client.close()}async[Symbol.asyncDispose](){await this.close()}}async function browserKey(client,cdpUrl){if(/^wss?:\/\//.test(cdpUrl))return cdpUrl;return(await client.discoverVersion()).webSocketDebuggerUrl}function createClient(cdpHttpUrl,options){if(typeof cdpHttpUrl!=="string"||cdpHttpUrl.length===0){throw new TypeError("connect(cdpHttpUrl) requires a Chromium CDP HTTP URL")}return new CdpClient({cdpUrl:cdpHttpUrl,...options.client,dialogPolicy:options.dialogPolicy??options.client?.dialogPolicy})}async function openConnection(cdpHttpUrl,options={}){return new BrowserConnection(createClient(cdpHttpUrl,options),options).initialize()}async function connect(cdpHttpUrl,options={}){const client=createClient(cdpHttpUrl,options);if(!canShareConnection(options))return new BrowserConnection(client,options).initialize();const key=await browserKey(client,cdpHttpUrl);return acquireSharedConnection(key,options,{open:(snapshot)=>openConnection(key,snapshot)})}var OMOWRIGHT_PAGE_CDP_METHODS=Object.freeze(["Browser.getVersion","DOM.describeNode","DOM.enable","DOM.getBoxModel","DOM.getContentQuads","DOM.getDocument","DOM.querySelectorAll","DOM.resolveNode","DOM.scrollIntoViewIfNeeded","DOM.setFileInputFiles","Emulation.setDeviceMetricsOverride","Emulation.setFocusEmulationEnabled","Emulation.setEmulatedMedia","Input.dispatchKeyEvent","Input.dispatchMouseEvent","Input.insertText","Inspector.enable","Network.disable","Network.enable","Network.getResponseBody","Network.setExtraHTTPHeaders","Page.addScriptToEvaluateOnNewDocument","Page.captureScreenshot","Page.close","Page.createIsolatedWorld","Page.enable","Page.getFrameTree","Page.getLayoutMetrics","Page.getNavigationHistory","Page.handleJavaScriptDialog","Page.navigate","Page.navigateToHistoryEntry","Page.printToPDF","Page.reload","Page.removeScriptToEvaluateOnNewDocument","Page.screencastFrameAck","Page.setInterceptFileChooserDialog","Page.setWebLifecycleState","Page.startScreencast","Page.stopScreencast","Runtime.callFunctionOn","Runtime.addBinding","Runtime.disable","Runtime.discardConsoleEntries","Runtime.enable","Runtime.evaluate","Runtime.releaseObject","Runtime.removeBinding","Runtime.runIfWaitingForDebugger","Target.activateTarget","Target.attachToTarget","Target.closeTarget","Target.createTarget","Target.detachFromTarget","Target.getTargetInfo","Target.getTargets","Target.setAutoAttach","Target.setDiscoverTargets"]);var DARWIN_EXCLUSIVE_NONBLOCK=32|4;var WINDOWS_EXCLUSIVE=268435456;var probedPaths=new Set;var DARWIN_BUSY_CODES=new Set(["EAGAIN","EWOULDBLOCK"]);async function lockLinux(fd){return new Promise((resolve,reject)=>{const child=spawn2("flock",["-n","3"],{stdio:["ignore","ignore","pipe",fd]});let stderr="";const stderrStream=child.stderr;if(stderrStream===null)throw new TypeError("flock child has no stderr pipe");stderrStream.setEncoding("utf8");stderrStream.on("data",(chunk)=>{stderr+=chunk});child.once("error",(error)=>{reject(error.code==="ENOENT"?new Error(`instance lock needs the flock utility (util-linux or busybox) on Linux: ${error.message}`,{cause:error}):error)});child.once("close",(code,signal)=>{if(code===0)resolve(true);else if(code===1&&stderr.trim()==="")resolve(false);else reject(Object.assign(new Error(`instance lock flock failed (${signal??code}): ${stderr.trim()}`),{code:"ERR_INSTANCE_LOCK"}))})})}async function tryAcquire(lockPath){const platform=process.platform;if(platform==="win32"&&process.versions.bun){await Promise.resolve().then(() => init_lock_backend_win32_xbcm60vz());return tryAcquireWindows(lockPath)}let flags=constants.O_RDWR|constants.O_CREAT;if(platform==="darwin")flags|=DARWIN_EXCLUSIVE_NONBLOCK;else if(platform==="win32")flags|=WINDOWS_EXCLUSIVE;else if(platform!=="linux")throw new Error(`instance lock is unsupported on ${platform}`);let handle;try{handle=await open2(lockPath,flags,384)}catch(error){if(platform==="darwin"&&DARWIN_BUSY_CODES.has(readProperty(error,"code")))return null;if(platform==="win32"&&readProperty(error,"code")==="EBUSY")return null;throw error}try{if(platform==="linux"&&!await lockLinux(handle.fd)){await handle.close();return null}}catch(error){await handle.close();throw error}return{release:()=>handle.close()}}async function probeOnce(lockPath){if(probedPaths.has(lockPath))return;const second=await tryAcquire(lockPath);if(second!==null){await second.release();throw new Error(`instance lock is not enforced for ${lockPath} on this runtime and filesystem`)}probedPaths.add(lockPath)}var localLocks=new Map;function errorCode(error){return error===null||error===undefined?undefined:readProperty(error,"code")}function isPidAlive(pid){try{process.kill(pid,0);return true}catch(error){if(errorCode(error)==="EPERM")return true;if(errorCode(error)==="ESRCH")return false;throw error}}async function unlinkIfPresent(target){await unlink2(target).catch((error)=>{if(errorCode(error)!=="ENOENT")throw error})}async function acquireLock(lockPath,timeoutMs){const deadline=performance.now()+timeoutMs;let delay=10;for(;;){const held=await tryAcquire(lockPath);if(held){try{await probeOnce(lockPath);return held}catch(error){await held.release();throw error}}const remaining=deadline-performance.now();if(remaining<=0)throw new Error(`timed out waiting for instance lock ${lockPath}`);await sleep(Math.min(remaining,delay*(0.75+Math.random()*0.5)));delay=Math.min(delay*2,250)}}async function acquireLocalLock(key){const previous=localLocks.get(key)??Promise.resolve();let releaseCurrent;const current=new Promise((resolve)=>{releaseCurrent=resolve});const tail=previous.then(()=>current);localLocks.set(key,tail);await previous;return()=>{releaseCurrent();if(localLocks.get(key)===tail)localLocks.delete(key)}}async function withLock(lockPath,{timeoutMs},run){const releaseLocal=await acquireLocalLock(lockPath);try{const held=await acquireLock(lockPath,timeoutMs);try{return await run()}finally{await held.release()}}finally{releaseLocal()}}var execFileAsync=promisify(execFile);var WINDOWS_START_TIME_TIMEOUT_MS=15000;var ownStartTime;async function processStartTime(pid){if(process.platform==="win32"){if(!Number.isInteger(pid)||pid<=0)return null;const systemRoot=process.env["SystemRoot"]||process.env["windir"]||"C:\\Windows";try{const{stdout}=await execFileAsync(path4.win32.join(systemRoot,"System32","WindowsPowerShell","v1.0","powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",`(Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId=${pid}').CreationDate.ToFileTimeUtc()`],{timeout:WINDOWS_START_TIME_TIMEOUT_MS,windowsHide:true});const ticks=String(stdout).trim();return/^\d+$/.test(ticks)?ticks:null}catch{return null}}if(process.platform==="linux"){try{const text=await readFile3(`/proc/${pid}/stat`,"utf8");return text.slice(text.lastIndexOf(")")+2).split(" ")[19]??null}catch{return null}}try{const{stdout}=await execFileAsync("ps",["-o","lstart=","-p",String(pid)],{env:{...process.env,LC_ALL:"C",TZ:"UTC"}});return stdout.trim()||null}catch{return null}}function ownProcessStartTime(){ownStartTime??=processStartTime(process.pid);return ownStartTime}var TERM_GRACE_MS=5000;var PID_FILE_NAME="omowright-browser.pid";var REAP_POLL_MS=50;var browserSpawnDetached=process.platform!=="win32";function profileDirFromArgs(browserArgs){for(const[index,argument]of browserArgs.entries()){const next=browserArgs[index+1];if(argument==="--user-data-dir"&&next)return path5.resolve(next);if(argument.startsWith("--user-data-dir="))return path5.resolve(argument.slice("--user-data-dir=".length))}return null}var signalsCanAskToQuit=process.platform!=="win32";async function terminateChild(child,{quitRequested=false}={}){if(child.pid===undefined)return;if(child.exitCode!==null||child.signalCode!==null)return;const exited=new Promise((resolve)=>child.once("exit",resolve));if(signalsCanAskToQuit){try{child.kill("SIGTERM")}catch{}}if(signalsCanAskToQuit||quitRequested){let timer;const graceOver=new Promise((resolve)=>{timer=setTimeout(resolve,TERM_GRACE_MS)});await Promise.race([exited,graceOver]);clearTimeout(timer)}if(child.exitCode===null&&child.signalCode===null){try{child.kill("SIGKILL")}catch{}await exited}}function pidFilePath(profileDir){return path5.join(profileDir,PID_FILE_NAME)}async function writeBrowserPidFile(profileDir,pid){if(!profileDir||!pid)return;const[start,ownerStart]=await Promise.all([processStartTime(pid),ownProcessStartTime()]);mkdirSync(profileDir,{recursive:true});const record={pid,start,profileDir,owner:{pid:process.pid,start:ownerStart}};writeFileSync(pidFilePath(profileDir),`${JSON.stringify(record)}
|
|
1326
|
-
`,{mode:384})}function removeBrowserPidFile(profileDir,pid){if(!profileDir)return;try{const recorded=JSON.parse(readFileSync2(pidFilePath(profileDir),"utf8"));if(readProperty(recorded,"pid")!==pid)return}catch{return}rmSync(pidFilePath(profileDir),{force:true})}async function sameProcessAlive(pid,start){if(typeof pid!=="number"||!Number.isInteger(pid)||pid<=0)return null;if(!isPidAlive(pid))return false;if(start===null||start===undefined)return null;const now=await processStartTime(pid);if(now===null)return null;return now===start}async function reapOrphanedBrowser(profileDir){if(!profileDir)return;let recorded;try{recorded=JSON.parse(readFileSync2(pidFilePath(profileDir),"utf8"))}catch{return}const pid=readProperty(recorded,"pid");const start=readProperty(recorded,"start");const owner=readProperty(recorded,"owner");if(typeof pid!=="number"||!Number.isInteger(pid)||pid<=0){rmSync(pidFilePath(profileDir),{force:true});return}const browserAlive=await sameProcessAlive(pid,start);if(browserAlive===false){rmSync(pidFilePath(profileDir),{force:true});return}if(browserAlive===null||pid===process.pid)return;const ownerAlive=owner===null||owner===undefined?await sameProcessAlive(undefined,undefined):await sameProcessAlive(readProperty(owner,"pid"),readProperty(owner,"start"));if(ownerAlive!==false)return;try{process.kill(pid,"SIGTERM")}catch{}const deadline=Date.now()+TERM_GRACE_MS;while(isPidAlive(pid)&&Date.now()<deadline)await sleep2(REAP_POLL_MS);if(isPidAlive(pid)){try{process.kill(pid,"SIGKILL")}catch{}}rmSync(pidFilePath(profileDir),{force:true})}class NulFrameReader{#parts=[];push(chunk){const frames=[];let start=0;let end;while((end=chunk.indexOf(0,start))!==-1){const tail=chunk.subarray(start,end);let frame=tail;if(this.#parts.length>0){this.#parts.push(tail);frame=Buffer.concat(this.#parts);this.#parts=[]}frames.push(frame.toString("utf8"));start=end+1}if(start<chunk.length)this.#parts.push(chunk.subarray(start));return frames}}class SerialEmitter{#listeners=new Map;on(event,fn){const list=this.#listeners.get(event)??[];list.push(fn);this.#listeners.set(event,list);return()=>{const cur=this.#listeners.get(event)??[];this.#listeners.set(event,cur.filter((f)=>f!==fn))}}async emit(event,data){for(const fn of this.#listeners.get(event)??[])await fn(data)}}var DEFAULT_COMMAND_TIMEOUT_MS2=30000;var DEFAULT_READINESS_TIMEOUT_MS=1e4;var GRACEFUL_CLOSE_TIMEOUT_MS=2000;var STDIO_TAIL_LIMIT=16384;var EXIT_STDERR_DRAIN_MS=1000;class PipeCdpClient{#child;#writeStream;#readStream;#frames=new NulFrameReader;#seq=1;#pending=new Map;#closedSessions=new Set;#sessionTargets=new Map;#launch;#launchId;#launchedAt=0;#receivedBytes=0;#malformedFrameCount=0;#events=new SerialEmitter;#connected=false;#commandTimeoutMs;#readinessTimeoutMs;#browserPath;#browserArgs;#spawnOptions;#stdioTail="";#stderrHead="";#dialogPolicy;transportEvents=new SerialEmitter;logId;constructor({browserPath,browserArgs=[],spawnOptions={},commandTimeoutMs,readinessTimeoutMs,logId,dialogPolicy}){if(!browserPath)throw new TypeError("PipeCdpClient requires browserPath");this.#browserPath=browserPath;this.#browserArgs=browserArgs;this.#spawnOptions=spawnOptions;this.#commandTimeoutMs=commandTimeoutMs??DEFAULT_COMMAND_TIMEOUT_MS2;this.#readinessTimeoutMs=readinessTimeoutMs??DEFAULT_READINESS_TIMEOUT_MS;this.logId=logId??`cdp-pipe-${Date.now()}`;this.#dialogPolicy=normalizeDialogPolicy(dialogPolicy)}get isConnected(){return this.#connected}get isHeadless(){return this.#browserArgs.some((arg)=>/^--headless(?:=|$)/.test(arg))}get childProcess(){return this.#child}get dialogPolicy(){return this.#dialogPolicy}setDialogPolicy(policy){this.#dialogPolicy=normalizeDialogPolicy(policy)}async ensureConnected(){if(this.#connected)return;const stdio=["ignore","pipe","pipe","pipe","pipe"];const profileDir=profileDirFromArgs(this.#browserArgs);await reapOrphanedBrowser(profileDir);const child=spawn3(this.#browserPath,[...this.#browserArgs,"--remote-debugging-pipe"],{detached:browserSpawnDetached,...this.#spawnOptions,stdio});this.#child=child;const spawnFailed=new Promise((resolve)=>child.once("error",resolve));if(child.pid===undefined){const error=await spawnFailed;this.#child=undefined;throw error}const browserPid=child.pid;const launch={};this.#launch=launch;const owned=(listener)=>(...args)=>{if(this.#launch===launch)listener(...args)};this.#launchId=`${this.logId}:${browserPid}`;this.#launchedAt=performance.now();this.#receivedBytes=0;this.#malformedFrameCount=0;this.#frames=new NulFrameReader;this.#sessionTargets.clear();this.#closedSessions.clear();child.once("exit",()=>removeBrowserPidFile(profileDir,browserPid));this.#stdioTail="";this.#stderrHead="";const stderr=child.stderr;for(const stream of[child.stdout,stderr]){if(!stream)continue;stream.setEncoding("utf8");stream.on("data",(chunk)=>{this.#stdioTail=(this.#stdioTail+chunk).slice(-STDIO_TAIL_LIMIT);if(stream===stderr&&this.#stderrHead.length<STDIO_TAIL_LIMIT&&!this.#stderrHead.trimStart().includes(`
|
|
1326
|
+
`,{mode:384})}function removeBrowserPidFile(profileDir,pid){if(!profileDir)return;try{const recorded=JSON.parse(readFileSync2(pidFilePath(profileDir),"utf8"));if(readProperty(recorded,"pid")!==pid)return}catch{return}rmSync(pidFilePath(profileDir),{force:true})}async function sameProcessAlive(pid,start){if(typeof pid!=="number"||!Number.isInteger(pid)||pid<=0)return null;if(!isPidAlive(pid))return false;if(start===null||start===undefined)return null;const now=await processStartTime(pid);if(now===null)return null;return now===start}async function reapOrphanedBrowser(profileDir){if(!profileDir)return;let recorded;try{recorded=JSON.parse(readFileSync2(pidFilePath(profileDir),"utf8"))}catch{return}const pid=readProperty(recorded,"pid");const start=readProperty(recorded,"start");const owner=readProperty(recorded,"owner");if(typeof pid!=="number"||!Number.isInteger(pid)||pid<=0){rmSync(pidFilePath(profileDir),{force:true});return}const browserAlive=await sameProcessAlive(pid,start);if(browserAlive===false){rmSync(pidFilePath(profileDir),{force:true});return}if(browserAlive===null||pid===process.pid)return;const ownerAlive=owner===null||owner===undefined?await sameProcessAlive(undefined,undefined):await sameProcessAlive(readProperty(owner,"pid"),readProperty(owner,"start"));if(ownerAlive!==false)return;try{process.kill(pid,"SIGTERM")}catch{}const deadline=Date.now()+TERM_GRACE_MS;while(isPidAlive(pid)&&Date.now()<deadline)await sleep2(REAP_POLL_MS);if(isPidAlive(pid)){try{process.kill(pid,"SIGKILL")}catch{}}rmSync(pidFilePath(profileDir),{force:true})}class NulFrameReader{#parts=[];push(chunk){const frames=[];let start=0;let end;while((end=chunk.indexOf(0,start))!==-1){const tail=chunk.subarray(start,end);let frame=tail;if(this.#parts.length>0){this.#parts.push(tail);frame=Buffer.concat(this.#parts);this.#parts=[]}frames.push(frame.toString("utf8"));start=end+1}if(start<chunk.length)this.#parts.push(chunk.subarray(start));return frames}}class SerialEmitter{#listeners=new Map;on(event,fn){const list=this.#listeners.get(event)??[];list.push(fn);this.#listeners.set(event,list);return()=>{const cur=this.#listeners.get(event)??[];this.#listeners.set(event,cur.filter((f)=>f!==fn))}}async emit(event,data){for(const fn of this.#listeners.get(event)??[])await fn(data)}}var DEFAULT_COMMAND_TIMEOUT_MS2=30000;var DEFAULT_READINESS_TIMEOUT_MS=1e4;var GRACEFUL_CLOSE_TIMEOUT_MS=2000;var STDIO_TAIL_LIMIT=16384;var EXIT_STDERR_DRAIN_MS=1000;class PipeCdpClient{#child;#writeStream;#readStream;#frames=new NulFrameReader;#seq=1;#pending=new Map;#closedSessions=new Set;#sessionTargets=new Map;#launch;#launchId;#launchedAt=0;#receivedBytes=0;#malformedFrameCount=0;#events=new SerialEmitter;#connected=false;#closedByCaller=false;#commandTimeoutMs;#readinessTimeoutMs;#browserPath;#browserArgs;#spawnOptions;#stdioTail="";#stderrHead="";#dialogPolicy;transportEvents=new SerialEmitter;logId;constructor({browserPath,browserArgs=[],spawnOptions={},commandTimeoutMs,readinessTimeoutMs,logId,dialogPolicy}){if(!browserPath)throw new TypeError("PipeCdpClient requires browserPath");this.#browserPath=browserPath;this.#browserArgs=browserArgs;this.#spawnOptions=spawnOptions;this.#commandTimeoutMs=commandTimeoutMs??DEFAULT_COMMAND_TIMEOUT_MS2;this.#readinessTimeoutMs=readinessTimeoutMs??DEFAULT_READINESS_TIMEOUT_MS;this.logId=logId??`cdp-pipe-${Date.now()}`;this.#dialogPolicy=normalizeDialogPolicy(dialogPolicy)}get isConnected(){return this.#connected}get isHeadless(){return this.#browserArgs.some((arg)=>/^--headless(?:=|$)/.test(arg))}get childProcess(){return this.#child}get dialogPolicy(){return this.#dialogPolicy}setDialogPolicy(policy){this.#dialogPolicy=normalizeDialogPolicy(policy)}async ensureConnected(){this.#closedByCaller=false;if(this.#connected)return;const stdio=["ignore","pipe","pipe","pipe","pipe"];const profileDir=profileDirFromArgs(this.#browserArgs);await reapOrphanedBrowser(profileDir);const child=spawn3(this.#browserPath,[...this.#browserArgs,"--remote-debugging-pipe"],{detached:browserSpawnDetached,...this.#spawnOptions,stdio});this.#child=child;const spawnFailed=new Promise((resolve)=>child.once("error",resolve));if(child.pid===undefined){const error=await spawnFailed;this.#child=undefined;throw error}const browserPid=child.pid;const launch={};this.#launch=launch;const owned=(listener)=>(...args)=>{if(this.#launch===launch)listener(...args)};this.#launchId=`${this.logId}:${browserPid}`;this.#launchedAt=performance.now();this.#receivedBytes=0;this.#malformedFrameCount=0;this.#frames=new NulFrameReader;this.#sessionTargets.clear();this.#closedSessions.clear();child.once("exit",()=>removeBrowserPidFile(profileDir,browserPid));this.#stdioTail="";this.#stderrHead="";const stderr=child.stderr;for(const stream of[child.stdout,stderr]){if(!stream)continue;stream.setEncoding("utf8");stream.on("data",(chunk)=>{this.#stdioTail=(this.#stdioTail+chunk).slice(-STDIO_TAIL_LIMIT);if(stream===stderr&&this.#stderrHead.length<STDIO_TAIL_LIMIT&&!this.#stderrHead.trimStart().includes(`
|
|
1327
1327
|
`)){this.#stderrHead=(this.#stderrHead+chunk).slice(0,STDIO_TAIL_LIMIT)}});stream.on("error",()=>{})}const writeStream=child.stdio[3];const readStream=child.stdio[4];if(!writeStream||!("write"in writeStream))throw new TypeError("CDP pipe write stream (fd 3) is missing");if(!readStream||!("read"in readStream))throw new TypeError("CDP pipe read stream (fd 4) is missing");this.#writeStream=writeStream;this.#readStream=readStream;readStream.on("data",owned((chunk)=>this.#onData(chunk)));for(const event of["end","close"]){readStream.on(event,owned(()=>this.#failCommands(CdpPipeClosedError,`CDP pipe read stream ${event}`)))}for(const stream of[writeStream,readStream]){stream.on("error",owned((error)=>this.#failAll(Error(`CDP pipe error: ${error.code??error.message}`))))}child.on("exit",owned(()=>{this.#connected=false;this.#failAll(Error("CDP pipe browser exited"));this.transportEvents.emit("disconnected").catch(()=>{})}));try{await writeBrowserPidFile(profileDir,browserPid)}catch(error){await this.#quitFailedLaunch();throw error}this.#connected=true;try{await this.#awaitReady();await this.#dispatch("Target.setDiscoverTargets",{discover:true}).catch(()=>{});await this.transportEvents.emit("connected")}catch(error){await this.#quitFailedLaunch();throw error}}async#quitFailedLaunch(){const child=this.#child;this.#child=undefined;this.#connected=false;this.#failAll(Error("CDP pipe launch failed"));if(child===undefined)throw new TypeError("Cannot read properties of undefined (reading 'pid')");await terminateChild(child)}async#awaitReady(){const child=this.#child;if(child===undefined)throw new TypeError("Cannot read properties of undefined (reading 'exitCode')");const deadline=Date.now()+this.#readinessTimeoutMs;const exited=child.exitCode!==null||child.signalCode!==null?Promise.resolve("exited"):new Promise((resolve)=>child.once("exit",()=>resolve("exited")));let lastError;while(Date.now()<deadline){try{const outcome=await Promise.race([this.#dispatch("Browser.getVersion",undefined,undefined,{timeoutMs:1000}),exited]);if(outcome!=="exited")return}catch(error){lastError=error}if(child.exitCode!==null||child.signalCode!==null)throw await this.#exitedBeforeReady(child,deadline);let timer;try{await Promise.race([new Promise((resolve)=>{timer=setTimeout(resolve,100)}),exited])}finally{clearTimeout(timer)}}const reason=lastError?String(readProperty(lastError,"message")??lastError):"no response";const tail=this.#stdioTail.trim();throw Error(`Browser did not become ready over the CDP pipe (${reason})`+(tail?`
|
|
1328
1328
|
Browser stdio tail:
|
|
1329
1329
|
${tail}`:""))}async#exitedBeforeReady(child,deadline){if(child.stderr){let timer;await Promise.race([finished(child.stderr).catch(()=>{}),new Promise((resolve)=>{timer=setTimeout(resolve,Math.max(0,Math.min(EXIT_STDERR_DRAIN_MS,deadline-Date.now())))})]);clearTimeout(timer)}const how=child.signalCode?`signal ${child.signalCode}`:`exit code ${child.exitCode}`;const firstLine=this.#stderrHead.split(`
|
|
@@ -1331,7 +1331,7 @@ ${tail}`:""))}async#exitedBeforeReady(child,deadline){if(child.stderr){let timer
|
|
|
1331
1331
|
`);const repeat=tailLines.findIndex((line)=>line.trim()===firstLine);if(repeat!==-1)tailLines.splice(repeat,1);const tail=tailLines.join(`
|
|
1332
1332
|
`).trim();return Error(`Browser exited before it became ready over the CDP pipe (${how})`+(firstLine?`: ${firstLine}`:"")+(tail?`
|
|
1333
1333
|
Browser stdio tail:
|
|
1334
|
-
${tail}`:""))}async send(method,params,sessionId,opts={}){if(method==="Target.createTarget"&&opts.capability!==targetCreationCapability)throw Error("Target.createTarget is reserved for createAgentTabs");if(String(method).startsWith("OmO.")){throw Error(`Extension commands are unavailable over pipe transport: ${method}`)}await this.ensureConnected();return this.#dispatch(method,params,sessionId,opts)}async#dispatch(method,params,sessionId,opts={}){const id=this.#seq++;const msg={id,method};if(params!==undefined)msg.params=params;if(sessionId)msg.sessionId=sessionId;const entry={method,sessionId,targetId:(params===undefined||params===null?undefined:readProperty(params,"targetId"))??this.#sessionTargets.get(sessionId),sentAt:performance.now(),receivedBytes:this.#receivedBytes};if(this.#closedSessions.has(sessionId)&&method!=="Page.close"){throw this.#commandError(CdpSessionDetachedError,"Page closed",entry)}const readStream=this.#readStream;if(readStream===undefined)throw new TypeError("Cannot read properties of undefined (reading 'readableEnded')");if(readStream.readableEnded||readStream.destroyed){throw this.#commandError(CdpPipeClosedError,"CDP pipe read stream closed",entry)}const{promise,resolve,reject}=Promise.withResolvers();const timeoutMs=opts.timeoutMs??this.#commandTimeoutMs;const timeout=timeoutMs>0?setTimeout(()=>{this.#pending.delete(id);reject(this.#commandError(CdpCommandTimeoutError,"CDP command timeout",entry))},timeoutMs):undefined;this.#pending.set(id,{...entry,resolve,reject,timeout});if(this.#writeStream===undefined)throw new TypeError("Cannot read properties of undefined (reading 'write')");this.#writeStream.write(JSON.stringify(msg)+"\x00");return promise}on(method,fn){return this.#events.on(method,({data})=>fn(data.payload,data.meta))}async discoverTargets(){const{targetInfos}=await this.send("Target.getTargets");return targetInfos.map((t)=>({id:t.targetId,type:t.type,url:t.url??"",title:t.title??"",description:t.description,faviconUrl:t.faviconUrl,parentId:t.openerId}))}closeSession(sessionId){this.#closedSessions.add(sessionId);this.#failCommands(CdpSessionDetachedError,"Page closed",sessionId)}async close(){const child=this.#child;this.#child=undefined;if(child&&child.exitCode===null){const exited=new Promise((resolve)=>child.once("exit",resolve));let quitRequested=false;if(this.#connected){await Promise.race([this
|
|
1334
|
+
${tail}`:""))}async send(method,params,sessionId,opts={}){if(method==="Target.createTarget"&&opts.capability!==targetCreationCapability)throw Error("Target.createTarget is reserved for createAgentTabs");if(String(method).startsWith("OmO.")){throw Error(`Extension commands are unavailable over pipe transport: ${method}`)}if(this.#closedByCaller){throw this.#commandError(CdpPipeClosedError,"CDP pipe client closed",{method,sessionId,targetId:this.#sessionTargets.get(sessionId),sentAt:performance.now(),receivedBytes:this.#receivedBytes})}await this.ensureConnected();return this.#dispatch(method,params,sessionId,opts)}async#dispatch(method,params,sessionId,opts={}){const id=this.#seq++;const msg={id,method};if(params!==undefined)msg.params=params;if(sessionId)msg.sessionId=sessionId;const entry={method,sessionId,targetId:(params===undefined||params===null?undefined:readProperty(params,"targetId"))??this.#sessionTargets.get(sessionId),sentAt:performance.now(),receivedBytes:this.#receivedBytes};if(this.#closedSessions.has(sessionId)&&method!=="Page.close"){throw this.#commandError(CdpSessionDetachedError,"Page closed",entry)}const readStream=this.#readStream;if(readStream===undefined)throw new TypeError("Cannot read properties of undefined (reading 'readableEnded')");if(readStream.readableEnded||readStream.destroyed){throw this.#commandError(CdpPipeClosedError,"CDP pipe read stream closed",entry)}const{promise,resolve,reject}=Promise.withResolvers();const timeoutMs=opts.timeoutMs??this.#commandTimeoutMs;const timeout=timeoutMs>0?setTimeout(()=>{this.#pending.delete(id);reject(this.#commandError(CdpCommandTimeoutError,"CDP command timeout",entry))},timeoutMs):undefined;this.#pending.set(id,{...entry,resolve,reject,timeout});if(this.#writeStream===undefined)throw new TypeError("Cannot read properties of undefined (reading 'write')");this.#writeStream.write(JSON.stringify(msg)+"\x00");return promise}on(method,fn){return this.#events.on(method,({data})=>fn(data.payload,data.meta))}async discoverTargets(){const{targetInfos}=await this.send("Target.getTargets");return targetInfos.map((t)=>({id:t.targetId,type:t.type,url:t.url??"",title:t.title??"",description:t.description,faviconUrl:t.faviconUrl,parentId:t.openerId}))}closeSession(sessionId){this.#closedSessions.add(sessionId);this.#failCommands(CdpSessionDetachedError,"Page closed",sessionId)}async close(){this.#closedByCaller=true;const child=this.#child;this.#child=undefined;if(child&&child.exitCode===null){const exited=new Promise((resolve)=>child.once("exit",resolve));let quitRequested=false;if(this.#connected){await Promise.race([this.#dispatch("Browser.close",undefined,undefined,{timeoutMs:GRACEFUL_CLOSE_TIMEOUT_MS}).then(()=>{quitRequested=true},()=>{}),exited])}this.#connected=false;this.#failAll(Error("CDP pipe client closed"));if(child.exitCode===null){let timer;try{await Promise.race([exited,new Promise((resolve)=>{timer=setTimeout(resolve,GRACEFUL_CLOSE_TIMEOUT_MS)})])}finally{clearTimeout(timer)}}await terminateChild(child,{quitRequested});return}this.#connected=false;this.#failAll(Error("CDP pipe client closed"))}#onData(chunk){this.#receivedBytes+=chunk.length;for(const raw of this.#frames.push(chunk)){if(raw.length===0)continue;let msg;try{msg=JSON.parse(raw)}catch{this.#malformedFrameCount++;continue}this._handleTransportMessage(msg)}}_handleTransportMessage(msg){if(typeof msg.id==="number"){const entry=this.#pending.get(msg.id);if(!entry)return;this.#pending.delete(msg.id);if(entry.timeout)clearTimeout(entry.timeout);if(msg.error){const err=Error(msg.error.message??`CDP command failed: ${entry.method}`);err.code=msg.error.code;err.data=msg.error.data;entry.reject(err)}else{if(entry.method==="Target.attachToTarget"&&msg.result?.sessionId){this.#sessionTargets.set(msg.result.sessionId,entry.targetId)}entry.resolve(msg.result)}return}if(typeof msg.method==="string"){if(msg.method==="Target.attachedToTarget"&&msg.params?.sessionId&&msg.params.targetInfo?.targetId){this.#sessionTargets.set(msg.params.sessionId,msg.params.targetInfo.targetId)}else if(msg.method==="Target.detachedFromTarget"&&msg.params?.sessionId){this.#failCommands(CdpSessionDetachedError,"CDP session detached",msg.params.sessionId);this.#sessionTargets.delete(msg.params.sessionId)}else if(msg.method==="Inspector.targetCrashed"&&msg.sessionId){this.#failCommands(CdpSessionCrashedError,"CDP session crashed",msg.sessionId,"Page.reload")}const meta={sessionId:msg.sessionId};const dialogSessionId=msg.sessionId;if(msg.method==="Page.javascriptDialogOpening"&&dialogSessionId){meta.dialog=new Dialog(msg.params,(action)=>this.send("Page.handleJavaScriptDialog",action,dialogSessionId))}const emitted=this.#events.emit(msg.method,{data:{payload:msg.params,meta}}).catch(()=>{});const{dialog}=meta;return dialog?emitted.then(()=>answerWithPolicy(dialog,this.#dialogPolicy,msg.params)).catch(()=>{}):undefined}}#commandError(ErrorType,reason,entry){const now=performance.now();const receivedBytesSinceSend=this.#receivedBytes-entry.receivedBytes;const details={method:entry.method,launchId:this.#launchId,sessionId:entry.sessionId??null,targetId:entry.targetId??this.#sessionTargets.get(entry.sessionId)??null,elapsedSinceLaunchMs:Math.round(now-this.#launchedAt),commandElapsedMs:Math.round(now-entry.sentAt),receivedReplyBytes:receivedBytesSinceSend>0,receivedBytesSinceSend,malformedFrameCount:this.#malformedFrameCount};const context=Object.entries(details).map(([key,value])=>`${key}=${value}`).join(", ");return new ErrorType(`${reason}: ${entry.method} (${context})`,details)}#failCommands(ErrorType,reason,sessionId,sparedMethod){for(const[id,entry]of this.#pending){if(sessionId!==undefined&&entry.sessionId!==sessionId)continue;if(entry.method===sparedMethod)continue;if(entry.timeout)clearTimeout(entry.timeout);this.#pending.delete(id);entry.reject(this.#commandError(ErrorType,reason,entry))}}#failAll(err){for(const entry of this.#pending.values()){if(entry.timeout)clearTimeout(entry.timeout);entry.reject(err)}this.#pending.clear()}}async function connectPipe({browserPath,browserArgs=[],spawnOptions,storageRoot,commandTimeoutMs,readinessTimeoutMs,logId,dialogPolicy}={}){const client=new PipeCdpClient({browserPath,browserArgs,spawnOptions,commandTimeoutMs,readinessTimeoutMs,logId,dialogPolicy});await client.ensureConnected();const connection=new BrowserConnection(client,{storageRoot});await connection.initialize();connection.browserProcess=client.childProcess;return connection}function errorCode2(error){return error===null||error===undefined?undefined:readProperty(error,"code")}var ACTIVE_PORT_POLL_MS=100;function httpEndpointFromWebSocket(webSocketUrl){const endpoint=new URL(webSocketUrl);endpoint.protocol=endpoint.protocol==="wss:"?"https:":"http:";endpoint.pathname="/";endpoint.search="";endpoint.hash="";return endpoint.toString().replace(/\/$/,"")}function parseActivePort(text){const[portLine,browserPath]=text.trim().split(/\r?\n/);const port=Number(portLine);if(!Number.isInteger(port)||port<1||port>65535)return null;return{endpoint:`http://127.0.0.1:${port}`,browserPath:browserPath?.trim()||null}}function activePortIdentity(info){return{ino:info.ino,mtimeMs:info.mtimeMs,size:info.size}}async function snapshotActivePort(profileDir){if(!profileDir)return null;const activePortPath=path6.join(profileDir,"DevToolsActivePort");try{const identity=activePortIdentity(await stat(activePortPath));return{...identity,text:await readFile4(activePortPath,"utf8")}}catch(error){if(errorCode2(error)==="ENOENT")return null;throw error}}function isSameFile(info,previous){return previous!==null&&info.ino===previous.ino&&info.mtimeMs===previous.mtimeMs&&info.size===previous.size}function assertLaunchedBrowser(child,report,webSocketDebuggerUrl){if(child.exitCode!==null||child.signalCode!==null){throw new Error(`browser exited before its DevTools endpoint ${report.endpoint} could be verified`)}const answered=new URL(webSocketDebuggerUrl).pathname;if(report.browserPath===null||answered!==report.browserPath){throw new Error(`DevTools endpoint ${report.endpoint} answers as ${answered}, not as the launched browser (${report.browserPath??"no browser id reported"})`)}}async function discoverLaunchedEndpoint(child,{profileDir,timeoutMs,previousActivePort=null}={}){const activePortPath=profileDir?path6.join(profileDir,"DevToolsActivePort"):null;return new Promise((resolve,reject)=>{let settled=false;let stderr="";let activePortWatcher;let activePortReading=false;let activePortChangedWhileReading=false;const cleanups=[];const finish=(error,endpoint)=>{if(settled)return;settled=true;for(const cleanup of cleanups.splice(0))cleanup();activePortWatcher?.close();if(error)reject(error);else resolve(endpoint)};const readActivePort=async(portPath)=>{const info=await stat(portPath);if(isSameFile(activePortIdentity(info),previousActivePort))return;const text=await readFile4(portPath,"utf8");if(previousActivePort!==null&&text===previousActivePort.text)return;const report=parseActivePort(text);if(report)finish(null,report)};const tryActivePort=async()=>{if(!activePortPath||settled)return;if(activePortReading){activePortChangedWhileReading=true;return}activePortReading=true;try{do{activePortChangedWhileReading=false;await readActivePort(activePortPath)}while(activePortChangedWhileReading&&!settled)}catch(error){if(errorCode2(error)!=="ENOENT")finish(error)}finally{activePortReading=false}};const onStderr=(chunk)=>{stderr=`${stderr}${chunk}`.slice(-16384);const match=/DevTools listening on (ws:\/\/\S+)/.exec(stderr);const webSocketUrl=match?.[1];if(webSocketUrl!==undefined){finish(null,{endpoint:httpEndpointFromWebSocket(webSocketUrl),browserPath:new URL(webSocketUrl).pathname})}else tryActivePort()};const onError=(error)=>finish(error);const onExit=(code,signal)=>{finish(new Error(`browser exited before exposing DevTools (code ${code}, signal ${signal??"none"})${stderr?`
|
|
1335
1335
|
${stderr}`:""}`))};child.stderr.setEncoding("utf8");child.stderr.on("data",onStderr);child.once("error",onError);child.once("exit",onExit);cleanups.push(()=>child.stderr.off("data",onStderr));cleanups.push(()=>child.off("error",onError));cleanups.push(()=>child.off("exit",onExit));if(activePortPath&&profileDir){try{activePortWatcher=watch(profileDir,(event,filename)=>{if((event==="rename"||event==="change")&&(!filename||filename.toString()===path6.basename(activePortPath))){tryActivePort()}})}catch(error){if(errorCode2(error)!=="ENOENT")finish(error)}tryActivePort();const poll=setInterval(()=>void tryActivePort(),ACTIVE_PORT_POLL_MS);cleanups.push(()=>clearInterval(poll))}const timeout=setTimeout(()=>{finish(new Error(`browser did not expose a DevTools endpoint within ${timeoutMs}ms${stderr?`
|
|
1336
1336
|
${stderr}`:""}`))},timeoutMs);cleanups.push(()=>clearTimeout(timeout))})}var execFileAsync2=promisify2(execFile2);var WINDOWS_COMMAND_TIMEOUT_MS=15000;var ownerOnlyDirectories=new Set;var TRUSTED_TRUSTEES=new Set(["SY","S-1-5-18","BA","S-1-5-32-544","S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464","OW","S-1-3-4","CO","S-1-3-0"]);var DENY_ACE_TYPES=new Set(["D","OD","XD"]);var currentUserSid;function windowsSystemTool(name,env=process.env){return path7.win32.join(env["SystemRoot"]||env["windir"]||"C:\\Windows","System32",name)}async function readCurrentUserSid(run){const{stdout}=await run(windowsSystemTool("whoami.exe"),["/user","/fo","csv","/nh"],{timeout:WINDOWS_COMMAND_TIMEOUT_MS,windowsHide:true});const sid=/"(S-1-[\d-]+)"\s*$/.exec(String(stdout).trim())?.[1];if(!sid)throw new Error(`cannot read the current user's SID from whoami: ${String(stdout).trim()}`);return sid}function cachedCurrentUserSid(){currentUserSid??=readCurrentUserSid(execFileAsync2).catch((error)=>{currentUserSid=undefined;throw error});return currentUserSid}async function readDirectoryDacl(dir,run){const scratch=await mkdtemp(path7.join(tmpdir2(),"omowright-acl-"));try{const saved=path7.join(scratch,"acl");await run(windowsSystemTool("icacls.exe"),[dir,"/save",saved,"/Q"],{timeout:WINDOWS_COMMAND_TIMEOUT_MS,windowsHide:true});const bytes=await readFile5(saved);const text=bytes.length>1&&bytes[1]===0?bytes.toString("utf16le"):bytes.toString("utf8");return/D:[^\r\n]*/.exec(text)?.[0]??""}finally{await rm(scratch,{recursive:true,force:true})}}function parseDacl(dacl){const head=/^D:([A-Z]*)/.exec(dacl);if(!head)return null;const aces=[];let depth=0;let start=0;let i=head[0].length;for(;i<dacl.length;i++){const c=dacl[i];if(c==='"'&&depth>0){i=dacl.indexOf('"',i+1);if(i===-1)return null}else if(c==="("){if(depth++===0)start=i+1}else if(c===")"){if(depth===0)return null;if(--depth===0)aces.push(dacl.slice(start,i).split(";"))}else if(depth===0){break}}if(depth!==0||i<dacl.length&&!dacl.startsWith("S:",i))return null;return{flags:dacl.slice("D:".length,head[0].length),aces}}function inspectDirectoryDacl(text,sid){const dacl=parseDacl(text);if(!dacl)return{parsed:false,ownerOnly:false,foreign:[]};const isUser=(trustee)=>trustee===sid||trustee==="LA"&&sid.endsWith("-500")||trustee==="LG"&&sid.endsWith("-501");const own=dacl.aces.filter((fields)=>isUser(fields[5]));const others=dacl.aces.filter(([type,,,,,trustee])=>!isUser(trustee)&&!TRUSTED_TRUSTEES.has(trustee)&&!DENY_ACE_TYPES.has(type));return{parsed:true,ownerOnly:dacl.flags.includes("P")&&others.length===0&&own.length===1&&own[0]?.[0]==="A"&&own[0]?.[1]==="OICI"&&own[0]?.[2]==="FA",foreign:[...new Set(others.filter(([,flags])=>!String.prototype.includes.call(flags,"ID")).map(([,,,,,trustee])=>trustee))]}}async function directoryIdentity(dir){const{dev,ino,birthtimeNs}=await stat2(dir,{bigint:true});return ino===0n?null:`${dev}:${ino}:${birthtimeNs}`}async function rememberOwnerOnlyDirectory(dir){const identity=await directoryIdentity(dir).catch(()=>null);if(identity)ownerOnlyDirectories.add(identity)}async function restrictToOwner(target,kind,{platform=process.platform,run}={}){if(platform!=="win32"){await chmod(target,kind==="directory"?448:384);return}const command=run??execFileAsync2;const sid=run?await readCurrentUserSid(run):await cachedCurrentUserSid();const dacl=kind==="directory"?inspectDirectoryDacl(await readDirectoryDacl(target,command),sid):null;if(dacl?.ownerOnly){await rememberOwnerOnlyDirectory(target);return}const grant=kind==="directory"?`*${sid}:(OI)(CI)F`:`*${sid}:F`;await command(windowsSystemTool("icacls.exe"),[target,"/inheritance:r","/grant:r",grant,"/Q"],{timeout:WINDOWS_COMMAND_TIMEOUT_MS,windowsHide:true});if(!dacl)return;if(dacl.foreign.length>0){await command(windowsSystemTool("icacls.exe"),[target,"/remove:g",...dacl.foreign.map((trustee)=>`*${trustee}`),"/Q"],{timeout:WINDOWS_COMMAND_TIMEOUT_MS,windowsHide:true})}if(dacl.parsed)await rememberOwnerOnlyDirectory(target)}var RECORD_VERSION=2;var DEFAULT_REGISTRY_ROOT=path8.join(os.homedir(),".local","share","omowright","instances");var DEFAULT_PROBE_TIMEOUT_MS=1000;var DEFAULT_LAUNCH_TIMEOUT_MS=1e4;var DEFAULT_CONNECT_TIMEOUT_MS=1e4;var BROWSER_CLOSE_TIMEOUT_MS=2000;var LOCK_TIMEOUT_MARGIN_MS=5000;var DEFAULT_LOCK_TIMEOUT_MS=resolveLockTimeoutMs({});function errorCode3(error){return error===null||error===undefined?undefined:readProperty(error,"code")}function normalizeName(name){if(typeof name!=="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)){throw new TypeError("instance name must start with a letter or number and contain only letters, numbers, dots, dashes, or underscores")}return name}function registryPaths(registryRoot,name){const root=path8.resolve(registryRoot??DEFAULT_REGISTRY_ROOT);return{root,recordPath:path8.join(root,`${name}.json`),lockPath:path8.join(root,`${name}.flock`)}}async function ensureRegistryRoot(root){await mkdir5(root,{recursive:true,mode:448});await restrictToOwner(root,"directory")}function isRecord(value,expectedName){if(value===null||typeof value!=="object")return false;const pid=readProperty(value,"pid");const endpoint=readProperty(value,"endpoint");const webSocketDebuggerUrl=readProperty(value,"webSocketDebuggerUrl");const profileDir=readProperty(value,"profileDir");const browserPath=readProperty(value,"browserPath");const startedAt=readProperty(value,"startedAt");return readProperty(value,"version")===RECORD_VERSION&&readProperty(value,"name")===expectedName&&typeof pid==="number"&&Number.isInteger(pid)&&pid>0&&typeof endpoint==="string"&&endpoint.length>0&&typeof webSocketDebuggerUrl==="string"&&webSocketDebuggerUrl.length>0&&(typeof profileDir==="string"||profileDir===null)&&typeof browserPath==="string"&&browserPath.length>0&&typeof startedAt==="string"&&!Number.isNaN(Date.parse(startedAt))}async function readRecord(recordPath,expectedName){let text;try{text=await readFile6(recordPath,"utf8")}catch(error){if(errorCode3(error)==="ENOENT")return{exists:false,record:null};throw error}try{const record=JSON.parse(text);return{exists:true,record:isRecord(record,expectedName)?record:null}}catch{return{exists:true,record:null}}}async function writeRecordAtomic(root,recordPath,record){const tempPath=path8.join(root,`.${record.name}.${process.pid}.${randomUUID2()}.tmp`);let handle;try{handle=await open3(tempPath,"wx",384);await handle.writeFile(`${JSON.stringify(record,null,2)}
|
|
1337
1337
|
`,"utf8");await handle.close();handle=null;await restrictToOwner(tempPath,"file");await rename(tempPath,recordPath);await restrictToOwner(recordPath,"file")}catch(error){await handle?.close().catch(()=>{});await unlink3(tempPath).catch(()=>{});throw error}}function isConnectionRefused(error){for(let cause=error;cause;cause=readProperty(cause,"cause")){const code=readProperty(cause,"code");if(code==="ECONNREFUSED"||code==="ENOTFOUND"||code==="ConnectionRefused"){return true}}return false}function isBrowserVersion(value){if(value===null||value===undefined)return false;const webSocketDebuggerUrl=readProperty(value,"webSocketDebuggerUrl");return typeof webSocketDebuggerUrl==="string"&&webSocketDebuggerUrl.length>0}async function probeEndpoint(endpoint,timeoutMs){const versionUrl=new URL("/json/version",endpoint);const response=await fetch(versionUrl,{signal:AbortSignal.timeout(timeoutMs)});if(!response.ok){throw new Error(`CDP discovery request failed (${response.status} ${response.statusText})`)}const version=await response.json();if(!isBrowserVersion(version)){throw new Error("CDP discovery response lacks webSocketDebuggerUrl")}return version}function resolveConnectTimeoutMs(options){return options.connectTimeoutMs??DEFAULT_CONNECT_TIMEOUT_MS}function resolveLockTimeoutMs(options){if(options.lockTimeoutMs!==undefined)return options.lockTimeoutMs;return(options.launchTimeoutMs??DEFAULT_LAUNCH_TIMEOUT_MS)+(options.probeTimeoutMs??resolveConnectTimeoutMs(options))+resolveConnectTimeoutMs(options)+LOCK_TIMEOUT_MARGIN_MS}function nameLockOptions(options){return{timeoutMs:resolveLockTimeoutMs(options)}}async function connectWithin(endpoint,options,timeoutMs){const pending=openConnection(endpoint,options);let timer;try{return await Promise.race([pending,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(`timed out after ${timeoutMs}ms opening a CDP session on ${endpoint}`)),timeoutMs)})])}catch(error){pending.then((connection)=>connection.close().catch(()=>{}),()=>{});throw error}finally{clearTimeout(timer)}}async function removeOwnedRecord(recordPath,name,pid){const loaded=await readRecord(recordPath,name);if(loaded.record?.pid!==pid)return;await unlinkIfPresent(recordPath)}function connectionOptions(options,profileDir){const result={...options.connectionOptions};if(options.storageRoot!==undefined)result.storageRoot=options.storageRoot;else if(result.storageRoot===undefined&&profileDir){result.storageRoot=profileDir}if(options.client!==undefined){result.client={...result.client,...options.client}}if(options.dialogPolicy!==undefined)result.dialogPolicy=options.dialogPolicy;return result}async function askBrowserToQuit(connection,child,disconnect){if(child.exitCode!==null||child.signalCode!==null||!readProperty(connection.cdp,"isConnected")){await disconnect();return false}const exited=new Promise((resolve)=>child.once("exit",resolve));const quitRequested=await Promise.race([connection.cdp.send("Browser.close",undefined,undefined,{timeoutMs:BROWSER_CLOSE_TIMEOUT_MS}).then(()=>true,()=>false),exited.then(()=>true)]);await disconnect();if(child.exitCode===null&&child.signalCode===null){let timer;await Promise.race([exited,new Promise((resolve)=>{timer=setTimeout(resolve,BROWSER_CLOSE_TIMEOUT_MS)})]);clearTimeout(timer)}return quitRequested}async function launchNamed(name,{root,recordPath,lockPath},options){if(typeof options.browserPath!=="string"||options.browserPath.length===0){throw new TypeError(`connectNamed("${name}") requires browserPath when no healthy instance is registered`)}const browserArgs=[...options.browserArgs??[]];const profileDir=options.profileDir?path8.resolve(options.profileDir):profileDirFromArgs(browserArgs);const previousActivePort=await snapshotActivePort(profileDir);const child=spawn4(options.browserPath,[...browserArgs,"--remote-debugging-address=127.0.0.1","--remote-debugging-port=0"],{...process.platform==="win32"?{detached:true}:{},...options.spawnOptions,stdio:["ignore","ignore","pipe"]});let connection;try{const launchTimeoutMs=options.launchTimeoutMs??DEFAULT_LAUNCH_TIMEOUT_MS;const report=await discoverLaunchedEndpoint(child,{profileDir,timeoutMs:launchTimeoutMs,previousActivePort});if(report===undefined)throw new TypeError("launch endpoint discovery settled without a report");const{endpoint}=report;const{webSocketDebuggerUrl}=await probeEndpoint(endpoint,launchTimeoutMs);assertLaunchedBrowser(child,report,webSocketDebuggerUrl);const opened=await connectWithin(endpoint,connectionOptions(options,profileDir),resolveConnectTimeoutMs(options));connection=opened;const record={version:RECORD_VERSION,name,pid:child.pid,endpoint,webSocketDebuggerUrl,profileDir,browserPath:path8.resolve(options.browserPath),startedAt:new Date().toISOString()};await writeRecordAtomic(root,recordPath,record);opened.browserProcess=child;const disconnect=opened.close.bind(opened);opened.close=async()=>{let failure;const quitRequested=await askBrowserToQuit(opened,child,async()=>{try{await disconnect()}catch(error){failure=error}});await terminateChild(child,{quitRequested});try{await withLock(lockPath,nameLockOptions(options),()=>removeOwnedRecord(recordPath,name,child.pid))}catch(error){failure??=error}if(failure)throw failure};return opened}catch(error){await connection?.close().catch(()=>{});await terminateChild(child);throw error}}async function withEngineLock(registryRoot,engineKey,run){const root=path8.resolve(registryRoot??DEFAULT_REGISTRY_ROOT);await ensureRegistryRoot(root);const digest=createHash("sha256").update(path8.resolve(engineKey)).digest("hex").slice(0,16);const lockPath=path8.join(root,`_engine-${digest}.flock`);return withLock(lockPath,{timeoutMs:DEFAULT_LOCK_TIMEOUT_MS},run)}async function connectNamed(name,options={}){const normalizedName=normalizeName(name);const paths=registryPaths(options.registryRoot,normalizedName);await ensureRegistryRoot(paths.root);return withLock(paths.lockPath,nameLockOptions(options),()=>attachOrLaunch(normalizedName,paths,options))}async function attachOrLaunch(normalizedName,paths,options){const loaded=await readRecord(paths.recordPath,normalizedName);if(loaded.record){await restrictToOwner(paths.recordPath,"file");if(isPidAlive(loaded.record.pid)){let version=null;try{version=await probeEndpoint(loaded.record.endpoint,options.probeTimeoutMs??resolveConnectTimeoutMs(options))}catch(error){if(!isConnectionRefused(error)){throw new Error(`unresponsive holder "${normalizedName}" pid ${loaded.record.pid} endpoint ${loaded.record.endpoint}: ${readProperty(error,"message")}`,{cause:error})}}if(version?.webSocketDebuggerUrl===loaded.record.webSocketDebuggerUrl){const{webSocketDebuggerUrl}=loaded.record;const timeoutMs=resolveConnectTimeoutMs(options);try{return await acquireSharedConnection(webSocketDebuggerUrl,connectionOptions(options,loaded.record.profileDir),{open:(shared)=>connectWithin(webSocketDebuggerUrl,shared,timeoutMs),timeoutMs})}catch(error){throw new Error(`unresponsive holder "${normalizedName}" pid ${loaded.record.pid} endpoint ${loaded.record.endpoint}: ${readProperty(error,"message")}`,{cause:error})}}}}if(loaded.exists){await unlink3(paths.recordPath).catch((error)=>{if(errorCode3(error)!=="ENOENT")throw error})}return await launchNamed(normalizedName,paths,options)}async function listInstances(options={}){const root=path8.resolve(options.registryRoot??DEFAULT_REGISTRY_ROOT);await ensureRegistryRoot(root);const entries=await readdir(root,{withFileTypes:true});const records=await Promise.all(entries.filter((entry)=>entry.isFile()&&entry.name.endsWith(".json")).map(async(entry)=>{const expectedName=entry.name.slice(0,-".json".length);const recordPath=path8.join(root,entry.name);const{record}=await readRecord(recordPath,expectedName);if(!record)return null;await restrictToOwner(recordPath,"file");const alive=isPidAlive(record.pid);let responsive=false;if(alive){responsive=await probeEndpoint(record.endpoint,options.probeTimeoutMs??DEFAULT_PROBE_TIMEOUT_MS).then((version)=>version.webSocketDebuggerUrl===record.webSocketDebuggerUrl,()=>false)}return Object.assign(record,{alive,responsive})}));return records.filter((record)=>record!==null).toSorted((left,right)=>left.name.localeCompare(right.name))}var BROWSERSKILL_EXTENSION_IDS=Object.freeze({chrome:"hhcmgoofomhgciiibhipgmgkgnoenaoi",edge:"emacgiaaaiojkkpkddmmdfhmokgmnikg"});var STORE_UPDATE_URLS=Object.freeze({chrome:"https://clients2.google.com/service/update2/crx",edge:"https://edge.microsoft.com/extensionwebstorebase/v1/crx"});var STORE_PAGE_URLS=Object.freeze({chrome:`https://chromewebstore.google.com/detail/${BROWSERSKILL_EXTENSION_IDS.chrome}`,edge:`https://microsoftedge.microsoft.com/addons/detail/browserskill/${BROWSERSKILL_EXTENSION_IDS.edge}`});var NON_CHROMIUM_DEFAULTS=Object.freeze([{id:"safari",label:"Safari",match:["com.apple.safari","safarihtml"]},{id:"firefox",label:"Firefox",match:["org.mozilla.firefox","firefox.desktop","firefoxurl","firefoxhtml"]},{id:"zen",label:"Zen",match:["app.zen-browser.zen","zen.desktop","zenhtml"]},{id:"orion",label:"Orion",match:["com.kagi.kagimacos"]}]);var MAC=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:"Library/Application Support/Google/Chrome",app:"Google Chrome",bundleId:"com.google.Chrome"},{id:"edge",label:"Microsoft Edge",store:"edge",userData:"Library/Application Support/Microsoft Edge",app:"Microsoft Edge",bundleId:"com.microsoft.edgemac"},{id:"brave",label:"Brave",store:"chrome",userData:"Library/Application Support/BraveSoftware/Brave-Browser",app:"Brave Browser",bundleId:"com.brave.Browser"},{id:"chromium",label:"Chromium",store:"chrome",userData:"Library/Application Support/Chromium",app:"Chromium",bundleId:"org.chromium.Chromium"},{id:"arc",label:"Arc",store:"chrome",userData:"Library/Application Support/Arc/User Data",app:"Arc",bundleId:"company.thebrowser.Browser"},{id:"dia",label:"Dia",store:"chrome",userData:"Library/Application Support/Dia/User Data",app:"Dia",bundleId:"company.thebrowser.dia"},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:"Library/Application Support/Vivaldi",app:"Vivaldi",bundleId:"com.vivaldi.Vivaldi"},{id:"opera",label:"Opera",store:"chrome",userData:"Library/Application Support/com.operasoftware.Opera",app:"Opera",bundleId:"com.operasoftware.Opera",externalExtensions:false},{id:"comet",label:"Comet",store:"chrome",userData:"Library/Application Support/Comet",app:"Comet",bundleId:"ai.perplexity.comet"},{id:"aside",label:"Aside",store:"chrome",userData:"Library/Application Support/Aside",app:"Aside",bundleId:"at.studio.AsideBrowser"},{id:"whale",label:"Naver Whale",store:"chrome",userData:"Library/Application Support/Naver/Whale",app:"Naver Whale",bundleId:"com.naver.Whale"}];var LINUX=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:".config/google-chrome",binaries:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/opt/google/chrome/chrome"],externalDir:"/opt/google/chrome/extensions",userExternalDir:false,desktopIds:["google-chrome.desktop","google-chrome-stable.desktop","com.google.Chrome.desktop"],processNames:["chrome","google-chrome"]},{id:"chromium",label:"Chromium",store:"chrome",userData:".config/chromium",binaries:["/usr/bin/chromium","/usr/bin/chromium-browser","/snap/bin/chromium"],externalDir:"/usr/share/chromium/extensions",userExternalDir:true,desktopIds:["chromium.desktop","chromium-browser.desktop","chromium_chromium.desktop","org.chromium.Chromium.desktop"],processNames:["chromium","chromium-browse"]},{id:"edge",label:"Microsoft Edge",store:"edge",userData:".config/microsoft-edge",binaries:["/usr/bin/microsoft-edge","/opt/microsoft/msedge/msedge"],externalDir:"/usr/share/microsoft-edge/extensions",userExternalDir:false,desktopIds:["microsoft-edge.desktop","microsoft-edge-stable.desktop","com.microsoft.Edge.desktop"],processNames:["msedge"]},{id:"brave",label:"Brave",store:"chrome",userData:".config/BraveSoftware/Brave-Browser",binaries:["/usr/bin/brave-browser","/opt/brave.com/brave/brave"],externalDir:"/usr/share/brave/extensions",userExternalDir:false,desktopIds:["brave-browser.desktop","com.brave.Browser.desktop"],processNames:["brave"]},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:".config/vivaldi",binaries:["/usr/bin/vivaldi","/opt/vivaldi/vivaldi"],externalDir:null,userExternalDir:false,externalExtensions:false,desktopIds:["vivaldi-stable.desktop","vivaldi.desktop"],processNames:["vivaldi-bin"]},{id:"opera",label:"Opera",store:"chrome",userData:".config/opera",binaries:["/usr/bin/opera"],externalDir:null,userExternalDir:false,externalExtensions:false,desktopIds:["opera.desktop"],processNames:["opera"]}];var WINDOWS=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:"Google/Chrome/User Data",registryKey:"HKCU\\Software\\Google\\Chrome\\Extensions",binaryRel:"Google/Chrome/Application/chrome.exe",progIds:["chromehtml"],processNames:["chrome.exe"]},{id:"edge",label:"Microsoft Edge",store:"edge",userData:"Microsoft/Edge/User Data",registryKey:"HKCU\\Software\\Microsoft\\Edge\\Extensions",binaryRel:"Microsoft/Edge/Application/msedge.exe",progIds:["msedgehtm"],processNames:["msedge.exe"]},{id:"brave",label:"Brave",store:"chrome",userData:"BraveSoftware/Brave-Browser/User Data",registryKey:"HKCU\\Software\\BraveSoftware\\Brave-Browser\\Extensions",binaryRel:"BraveSoftware/Brave-Browser/Application/brave.exe",progIds:["bravehtml"],processNames:["brave.exe"]},{id:"chromium",label:"Chromium",store:"chrome",userData:"Chromium/User Data",registryKey:"HKCU\\Software\\Chromium\\Extensions",binaryRel:"Chromium/Application/chrome.exe",progIds:["chromiumhtm"],processNames:[]},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:"Vivaldi/User Data",registryKey:null,externalExtensions:false,binaryRel:"Vivaldi/Application/vivaldi.exe",progIds:["vivaldihtm"],processNames:["vivaldi.exe"]},{id:"whale",label:"Naver Whale",store:"chrome",userData:"Naver/Naver Whale/User Data",registryKey:null,externalExtensions:false,binaryRel:"Naver/Naver Whale/Application/whale.exe",progIds:["whalehtml"],processNames:["whale.exe"]}];var BROWSER_IDS=Object.freeze([...new Set([...MAC,...LINUX,...WINDOWS].map((b)=>b.id))]);var pathFor=(platform)=>platform==="win32"?path9.win32:path9.posix;function macRow(b,home,exists){const{join}=path9.posix;const apps=[join("/Applications",`${b.app}.app`),join(home,"Applications",`${b.app}.app`)];const appPath=apps.find((p)=>exists(p))??null;const userDataDir=join(home,b.userData);return{id:b.id,label:b.label,store:b.store,userDataDir,binary:join(appPath??apps[0],"Contents","MacOS",b.app),bundleId:b.bundleId,processNames:apps.map((a)=>join(a,"Contents","MacOS",b.app)),defaultIds:[b.bundleId.toLowerCase()],externalExtensions:b.externalExtensions!==false,installed:appPath!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function linuxRow(b,home,exists){const userDataDir=path9.posix.join(home,b.userData);const binary=b.binaries.find((p)=>exists(p))??null;return{id:b.id,label:b.label,store:b.store,userDataDir,binary,externalDir:b.externalDir,userExternalDir:b.userExternalDir,processNames:b.processNames,defaultIds:b.desktopIds.map((d)=>d.toLowerCase()),externalExtensions:b.externalExtensions!==false,installed:binary!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function windowsRow(b,env,home,exists){const{join}=path9.win32;const localAppData=env["LOCALAPPDATA"]??join(home,"AppData","Local");const programFiles=[localAppData,env["PROGRAMFILES"],env["PROGRAMFILES(X86)"],"C:\\Program Files","C:\\Program Files (x86)"].filter((root)=>Boolean(root));const userDataDir=join(localAppData,b.userData);const binary=programFiles.map((root)=>join(root,b.binaryRel)).find((p)=>exists(p))??null;return{id:b.id,label:b.label,store:b.store,userDataDir,registryKey:b.registryKey,binary,processNames:b.processNames,defaultIds:b.progIds,externalExtensions:b.externalExtensions!==false,installed:binary!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function catalogBrowsers({platform=process.platform,home=homedir(),env=process.env,exists=existsSync}={}){if(platform==="darwin")return MAC.map((b)=>macRow(b,home,exists));if(platform==="linux")return LINUX.map((b)=>linuxRow(b,home,exists));if(platform==="win32")return WINDOWS.map((b)=>windowsRow(b,env,home,exists));return[]}function detectBrowsers(options={}){return catalogBrowsers(options).filter((b)=>b.installed)}var DEFAULT_PORT_CHECK_MS=1000;class RunningBrowserError extends Error{constructor(code,message,candidates=[]){super(message);this.name="RunningBrowserError";this.code=code;this.candidates=candidates}}async function readDevToolsActivePort(userDataDir){const text=await readFile7(path10.join(userDataDir,"DevToolsActivePort"),"utf8").catch(()=>null);if(text===null)return null;const[portLine="",wsPath=""]=text.split(/\r?\n/);const port=Number(portLine.trim());if(!Number.isInteger(port)||port<=0||port>65535)return null;const pathPart=wsPath.trim();return{port,wsPath:pathPart.startsWith("/devtools/browser")?pathPart:null}}function portIsListening(port,timeoutMs){return new Promise((resolve)=>{const socket=connectTcp({host:"127.0.0.1",port});const done=(live)=>{socket.destroy();resolve(live)};socket.setTimeout(timeoutMs,()=>done(false));socket.once("connect",()=>done(true));socket.once("error",()=>done(false))})}function candidateDirs({browser,userDataDirs,catalog}){if(userDataDirs)return userDataDirs.map((dir)=>({id:path10.basename(dir),label:dir,userDataDir:dir}));const rows=catalog().filter((row)=>row.hasProfile);return browser?rows.filter((row)=>row.id===browser):rows}async function findRunningBrowser({browser,userDataDirs,portCheckMs=DEFAULT_PORT_CHECK_MS,catalog=catalogBrowsers}={}){const live=[];for(const candidate of candidateDirs({browser,userDataDirs,catalog})){const active=await readDevToolsActivePort(candidate.userDataDir);if(!active||!active.wsPath)continue;if(!await portIsListening(active.port,portCheckMs))continue;live.push({...candidate,port:active.port,wsUrl:`ws://127.0.0.1:${active.port}${active.wsPath}`})}const[only]=live;if(live.length===1&&only!==undefined)return only;if(live.length===0){throw new RunningBrowserError("not_found","No running browser has remote debugging on. Ask the user to open chrome://inspect/#remote-debugging and allow it, then retry.")}throw new RunningBrowserError("choose_browser",`More than one browser has remote debugging on (${live.map((row)=>row.id).join(", ")}); pass { browser: "<id>" }.`,live)}async function connectRunningBrowser(options={}){const found=await findRunningBrowser(options);const browser=await connect(found.wsUrl,options.connect??{});return{browser,found}}var LEGACY_PROBE_TIMEOUT_MS=1500;var MIN_FINGERPRINT_SEED=1e4;var MAX_FINGERPRINT_SEED=99999;var METADATA_FILE=".omowright-cloak.json";var DEFAULT_PROFILE_DIR=path11.join(os2.homedir(),".local","share","omowright-cloak");function errorField(error,key){return error===null||error===undefined?undefined:readProperty(error,key)}function normalizeFingerprintSeed(value){const seed=typeof value==="string"&&value.trim()!==""?Number(value):value;if(typeof seed!=="number"||!Number.isInteger(seed)||seed<MIN_FINGERPRINT_SEED||seed>MAX_FINGERPRINT_SEED){throw new RangeError(`fingerprint seed must be an integer from ${MIN_FINGERPRINT_SEED} to ${MAX_FINGERPRINT_SEED}`)}return seed}function platformFingerprint(){return process.platform==="darwin"?"macos":"windows"}function identityFlag(value){return/^(--user-data-dir|--fingerprint|--fingerprint-platform)(?:=|$)/.test(value)}function buildCloakBrowserArgs({profileDir,fingerprintSeed,extraArgs=[]}={}){const profile=path11.resolve(profileDir??DEFAULT_PROFILE_DIR);const seed=normalizeFingerprintSeed(fingerprintSeed);const conflicting=extraArgs.filter(identityFlag);if(conflicting.length>0){throw new Error(`extraArgs cannot override fixed profile identity: ${conflicting.join(", ")}`)}return["--no-first-run","--no-default-browser-check","--disable-session-crashed-bubble",`--user-data-dir=${profile}`,`--fingerprint=${seed}`,`--fingerprint-platform=${platformFingerprint()}`,...extraArgs]}async function readMetadata(metadataPath){try{const parsed=JSON.parse(await readFile8(metadataPath,"utf8"));return normalizeFingerprintSeed(readProperty(parsed,"fingerprintSeed"))}catch(error){if(errorField(error,"code")==="ENOENT")return null;if(error instanceof SyntaxError){throw new Error(`invalid CloakBrowser profile metadata: ${metadataPath}`)}throw error}}async function writeMetadata(metadataPath,fingerprintSeed){const handle=await open4(metadataPath,"wx",384);try{await handle.writeFile(`${JSON.stringify({fingerprintSeed},null,2)}
|
|
@@ -1363,7 +1363,7 @@ print(text)
|
|
|
1363
1363
|
a.href = ${JSON.stringify(downloadOptions.url)};
|
|
1364
1364
|
document.body.appendChild(a);
|
|
1365
1365
|
a.click();
|
|
1366
|
-
})()`);const begin=await Promise.race([began,done.then(()=>null)]);if(!begin)throw new Error("No download started for the given URL");await done;const filename=downloadOptions.filename??begin.suggestedFilename;return{id:begin.guid,url:begin.url??downloadOptions.url,filename:path14.join(downloadDir,filename??"download"),state:"complete"}}finally{clearTimeout(timer);offBegin();offProgress();await page.close().catch(()=>{})}},async pause(..._args){throw new UnsupportedOperationError(`chrome.downloads.pause ${EXTENSION_BRIDGE_REQUIRED2}`)},async resume(..._args){throw new UnsupportedOperationError(`chrome.downloads.resume ${EXTENSION_BRIDGE_REQUIRED2}`)},async cancel(..._args){throw new UnsupportedOperationError(`chrome.downloads.cancel ${EXTENSION_BRIDGE_REQUIRED2}`)},async erase(..._args){throw new UnsupportedOperationError(`chrome.downloads.erase ${EXTENSION_BRIDGE_REQUIRED2}`)}};return{tabs,windows,downloads,bookmarks:profile.bookmarks,history:profile.history,topSites:profile.topSites}}var SYSTEM="S-1-5-18";var ADMINISTRATORS="S-1-5-32-544";var TRUSTED_INSTALLER="S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";var OWNER_RIGHTS="S-1-3-4";var CREATOR_OWNER="S-1-3-0";var WRITE_DATA=2;var APPEND_DATA=4;var WRITE_EA=16;var DELETE_CHILD=64;var WRITE_ATTRIBUTES=256;var DELETE=65536;var WRITE_DAC=262144;var WRITE_OWNER=524288;var GENERIC_ALL=268435456;var GENERIC_WRITE=1073741824;var MODIFY=WRITE_DATA|APPEND_DATA|WRITE_EA|WRITE_ATTRIBUTES|DELETE|WRITE_DAC|WRITE_OWNER|GENERIC_ALL|GENERIC_WRITE;var FORBIDDEN={executable:MODIFY,manifest:MODIFY,final:MODIFY|DELETE_CHILD,ancestor:DELETE_CHILD|DELETE|WRITE_DAC|WRITE_OWNER|GENERIC_ALL};var WIN32_REGISTRY_KEYS=Object.freeze({chrome:"HKCU\\Software\\Google\\Chrome\\NativeMessagingHosts",chromium:"HKCU\\Software\\Chromium\\NativeMessagingHosts"});var isWin32RegistryKey=(key)=>typeof key==="string"&&/^HKCU\\Software(\\[^\\/:*?"<>|\r\n]+)*\\NativeMessagingHosts$/i.test(key);function win32PathRisk(item,kind,userSid){const trusted=new Set([userSid,SYSTEM,ADMINISTRATORS,TRUSTED_INSTALLER]);if(item?.inaccessible)return"could not be inspected";if(!item?.exists)return"is missing";if(item.reparse)return"is a symlink, junction or other reparse point";if(kind==="executable"||kind==="manifest"){if(item.directory)return"is not a regular file";if(kind==="executable"&&!/\.(exe|cmd|bat|com)$/i.test(item.path))return"is not a .exe, .cmd, .bat or .com file"}else if(!item.directory)return"is not a directory";if(!trusted.has(item.owner))return`is owned by untrusted ${item.owner}`;trusted.add(OWNER_RIGHTS).add(CREATOR_OWNER);for(const ace of item.aces??[]){if(!readProperty(ace,"allow")||trusted.has(readProperty(ace,"sid")))continue;const mask=!readProperty(ace,"inheritOnly")?FORBIDDEN[kind]:kind==="final"&&readProperty(ace,"objectInherit")?MODIFY:0;if((Number(readProperty(ace,"rights"))&mask)!==0)return`grants ${readProperty(ace,"sid")} write access`}return null}var systemBinary=(...segments)=>{const file=path15.win32.join(process.env["SystemRoot"]||"C:\\Windows","System32",...segments);if(!existsSync3(file))throw new Error(`${file} is missing`);return file};function run(file,args){return new Promise((resolve,reject)=>{execFile3(file,args,{timeout:
|
|
1366
|
+
})()`);const begin=await Promise.race([began,done.then(()=>null)]);if(!begin)throw new Error("No download started for the given URL");await done;const filename=downloadOptions.filename??begin.suggestedFilename;return{id:begin.guid,url:begin.url??downloadOptions.url,filename:path14.join(downloadDir,filename??"download"),state:"complete"}}finally{clearTimeout(timer);offBegin();offProgress();await page.close().catch(()=>{})}},async pause(..._args){throw new UnsupportedOperationError(`chrome.downloads.pause ${EXTENSION_BRIDGE_REQUIRED2}`)},async resume(..._args){throw new UnsupportedOperationError(`chrome.downloads.resume ${EXTENSION_BRIDGE_REQUIRED2}`)},async cancel(..._args){throw new UnsupportedOperationError(`chrome.downloads.cancel ${EXTENSION_BRIDGE_REQUIRED2}`)},async erase(..._args){throw new UnsupportedOperationError(`chrome.downloads.erase ${EXTENSION_BRIDGE_REQUIRED2}`)}};return{tabs,windows,downloads,bookmarks:profile.bookmarks,history:profile.history,topSites:profile.topSites}}var SYSTEM="S-1-5-18";var ADMINISTRATORS="S-1-5-32-544";var TRUSTED_INSTALLER="S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";var OWNER_RIGHTS="S-1-3-4";var CREATOR_OWNER="S-1-3-0";var WRITE_DATA=2;var APPEND_DATA=4;var WRITE_EA=16;var DELETE_CHILD=64;var WRITE_ATTRIBUTES=256;var DELETE=65536;var WRITE_DAC=262144;var WRITE_OWNER=524288;var GENERIC_ALL=268435456;var GENERIC_WRITE=1073741824;var MODIFY=WRITE_DATA|APPEND_DATA|WRITE_EA|WRITE_ATTRIBUTES|DELETE|WRITE_DAC|WRITE_OWNER|GENERIC_ALL|GENERIC_WRITE;var FORBIDDEN={executable:MODIFY,manifest:MODIFY,final:MODIFY|DELETE_CHILD,ancestor:DELETE_CHILD|DELETE|WRITE_DAC|WRITE_OWNER|GENERIC_ALL};var WIN32_REGISTRY_KEYS=Object.freeze({chrome:"HKCU\\Software\\Google\\Chrome\\NativeMessagingHosts",chromium:"HKCU\\Software\\Chromium\\NativeMessagingHosts"});var isWin32RegistryKey=(key)=>typeof key==="string"&&/^HKCU\\Software(\\[^\\/:*?"<>|\r\n]+)*\\NativeMessagingHosts$/i.test(key);function win32PathRisk(item,kind,userSid){const trusted=new Set([userSid,SYSTEM,ADMINISTRATORS,TRUSTED_INSTALLER]);if(item?.inaccessible)return"could not be inspected";if(!item?.exists)return"is missing";if(item.reparse)return"is a symlink, junction or other reparse point";if(kind==="executable"||kind==="manifest"){if(item.directory)return"is not a regular file";if(kind==="executable"&&!/\.(exe|cmd|bat|com)$/i.test(item.path))return"is not a .exe, .cmd, .bat or .com file"}else if(!item.directory)return"is not a directory";if(!trusted.has(item.owner))return`is owned by untrusted ${item.owner}`;trusted.add(OWNER_RIGHTS).add(CREATOR_OWNER);for(const ace of item.aces??[]){if(!readProperty(ace,"allow")||trusted.has(readProperty(ace,"sid")))continue;const mask=!readProperty(ace,"inheritOnly")?FORBIDDEN[kind]:kind==="final"&&readProperty(ace,"objectInherit")?MODIFY:0;if((Number(readProperty(ace,"rights"))&mask)!==0)return`grants ${readProperty(ace,"sid")} write access`}return null}var systemBinary=(...segments)=>{const file=path15.win32.join(process.env["SystemRoot"]||"C:\\Windows","System32",...segments);if(!existsSync3(file))throw new Error(`${file} is missing`);return file};var RUN_TIMEOUT_MS=60000;function run(file,args){return new Promise((resolve,reject)=>{execFile3(file,args,{timeout:RUN_TIMEOUT_MS,windowsHide:true,maxBuffer:4194304,encoding:"utf8"},(error,stdout,stderr)=>{if(error&&(typeof error.code!=="number"||error.killed))reject(error);else resolve({code:error?error.code:0,stdout,stderr})})})}var INSPECT=`$ErrorActionPreference = 'Stop'
|
|
1367
1367
|
$paths = ConvertFrom-Json ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PATHS__')))
|
|
1368
1368
|
$sid = [System.Security.Principal.SecurityIdentifier]
|
|
1369
1369
|
$items = @(foreach ($p in $paths) {
|
|
@@ -1384,15 +1384,15 @@ ConvertTo-Json -Depth 6 -Compress @{ user = [System.Security.Principal.WindowsId
|
|
|
1384
1384
|
`)}}};const handle=(raw)=>{if(!hello){const parsed=checked(ExtensionHelloSchema,raw,"extension hello rejected");if(parsed.extensionId!==extensionId)throw new BridgeProtocolError("extension hello rejected");hello=parsed;hostConnectionId=randomUUID3();effectiveMax=Math.min(maxMessageBytes,parsed.maxMessageBytes);lastEventSeq=0;return write({protocol:PROTOCOL,type:"hello",role:"host",connectionId:hostConnectionId,hostName,hostVersion:"0.1.0",events:EVENT_NAMES2.filter((x)=>parsed.events.includes(x)),commands:COMMAND_NAMES.filter((x)=>parsed.commands.includes(x)),maxMessageBytes:effectiveMax})}const frameType=readProperty(raw,"type");if(frameType==="event")return dispatchEvent(checked(EventSchema,raw,"invalid event"));if(frameType==="response"){const parsed=checked(ResponseSchema,raw,"invalid response");if(parsed.name==="protocolError")throw Object.assign(new BridgeProtocolError(parsed.error?.message??"protocol error"),{code:parsed.error?.code,details:parsed.error?.details});const item=pending.get(parsed.requestId);if(!item||item.name!==parsed.name)throw new BridgeProtocolError("invalid or unknown response");item.settled=true;pending.delete(parsed.requestId);item.cleanup?.();mutationBusy=false;if(parsed.ok)item.resolve(parsed.result);else item.reject(Object.assign(new Error(parsed.error?.message),{code:parsed.error?.code,details:parsed.error?.details}));pumpCommands();return}throw new BridgeProtocolError("unexpected message")};const onData=(chunk)=>{try{buffer=Buffer.concat([buffer,Buffer.from(chunk)]);const out=decodeFrames(buffer,effectiveMax);buffer=out.remainder;for(const raw of out.frames)Promise.resolve(handle(raw)).catch((error)=>{stderr.write?.(`bridge: ${messageOf(error)}
|
|
1385
1385
|
`);disconnect(error)})}catch(error){stderr.write?.(`bridge: ${messageOf(error)}
|
|
1386
1386
|
`);disconnect(error)}};stdin.on("data",onData);stdin.once?.("end",()=>disconnect());stdin.once?.("error",disconnect);return{get isConnected(){return!closed&&!!hello},get capabilities(){return{commands:new Set(hello?.commands??[]),events:new Set(hello?.events??[])}},send:write,request(name,params,{signal,timeoutMs=commandTimeoutMs}={}){if(!hello||!hello.commands.includes(name))return Promise.reject(new BridgeUnavailableError(`unsupported bridge command: ${name}`));let command;try{command=checked(CommandSchema,{protocol:PROTOCOL,type:"command",requestId:randomUUID3(),name,params},"invalid command parameters")}catch(error){return Promise.reject(error)}return new Promise((resolve,reject)=>{if(commandQueue.length+pending.size>=maxPendingWrites){reject(new BridgeProtocolError("BOUNDED_TRANSPORT"));return}const item={requestId:command.requestId,name,command,resolve,reject,timer:null,abortHandler:null,cleanup:()=>{},settled:false};const cleanup=()=>{if(item.timer!==null)clearTimeout(item.timer);if(item.abortHandler){signal?.removeEventListener("abort",item.abortHandler);item.abortHandler=null}};item.cleanup=cleanup;const failIndeterminate=(code,reason=null)=>{if(item.settled)return;item.settled=true;cleanup();if(pending.delete(item.requestId)||commandQueue.includes(item)){const i=commandQueue.indexOf(item);if(i>=0)commandQueue.splice(i,1);item.reject(reason??Object.assign(new Error(`bridge command timed out: ${name}`),{code}))}if(item.started)disconnect(Object.assign(new Error("mutation completion is indeterminate"),{code}))};item.timer=setTimeout(()=>failIndeterminate("TIMEOUT"),timeoutMs);if(signal?.aborted){item.settled=true;cleanup();reject(signal?.reason??Object.assign(new Error(`bridge command aborted: ${name}`),{code:"ABORT_ERR"}));return}item.abortHandler=()=>failIndeterminate("ABORT_ERR",signal?.reason);signal?.addEventListener("abort",item.abortHandler,{once:true});commandQueue.push(item);pumpCommands()})},on(name,listener){if(!EVENT_NAMES2.includes(name))throw new BridgeProtocolError("invalid event name");const set=listeners.get(name)??new Set;set.add(listener);listeners.set(name,set);return()=>{set.delete(listener);if(!set.size)listeners.delete(name)}},emitEvent(name,payload){if(!hello?.events.includes(name))return Promise.reject(new BridgeUnavailableError("unsupported bridge event"));const checkedPayload=payloadSchemas[name].safeParse(payload);if(!checkedPayload.success)return Promise.reject(new BridgeProtocolError("invalid event payload"));sequence+=1;return write({protocol:PROTOCOL,type:"event",connectionId:hostConnectionId,seq:sequence,occurredAt:Date.now(),name,payload:checkedPayload.data})},close(){disconnect("closed");stdin.removeListener?.("data",onData)}}}var NATIVE_HOST_DIRS={darwin:{chrome:["Library","Application Support","Google","Chrome"],chromium:["Library","Application Support","Chromium"]},linux:{chrome:[".config","google-chrome"],chromium:[".config","chromium"]}};function defaultNativeMessagingHostDir(browser="chrome",platform=process.platform){if(platform==="win32"){if(WIN32_REGISTRY_KEYS[browser]===undefined)throw new BridgeProtocolError("custom browser requires nativeMessagingHostDir");return path16.win32.join(process.env["LOCALAPPDATA"]||path16.win32.join(homedir2(),"AppData","Local"),"omowright","NativeMessagingHosts",browser)}const byBrowser=NATIVE_HOST_DIRS[platform];if(!byBrowser)throw new BridgeProtocolError(`no default nativeMessagingHostDir on ${platform}; pass nativeMessagingHostDir`);const segments=byBrowser[browser];if(!segments)throw new BridgeProtocolError("custom browser requires nativeMessagingHostDir");return path16.join(homedir2(),...segments,"NativeMessagingHosts")}async function secureDirectory(dir){const absolute=path16.resolve(dir);const parts=absolute.split(path16.sep).filter(Boolean);let current=path16.parse(absolute).root;let final;while(parts.length){const part=parts.shift();if(part===undefined)break;current=path16.join(current,part);let info=await lstat(current).catch(()=>null);if(!info){await mkdir8(current,{mode:448});info=await lstat(current)}if(info.isSymbolicLink()){if(process.platform!=="darwin"||!["/tmp","/var","/etc"].includes(current)||info.uid!==0)throw new BridgeProtocolError(`nativeMessagingHostDir security rejected at ${current}: symlink is not a root-owned macOS system alias`);let target,resolved;try{target=await readlink(current);resolved=await realpath(current)}catch(error){throw new BridgeProtocolError(`nativeMessagingHostDir security rejected at ${current}: system alias could not be resolved (${String(readProperty(error,"code")??readProperty(error,"message"))})`)}if(!resolved.startsWith("/private/"))throw new BridgeProtocolError(`nativeMessagingHostDir security rejected at ${current}: system alias target is outside /private`);parts.unshift(...target.split(path16.sep).filter(Boolean));current=path16.isAbsolute(target)?path16.parse(target).root:path16.dirname(current);continue}if(!info.isDirectory())throw new BridgeProtocolError(`nativeMessagingHostDir security rejected at ${current}: not a directory`);if(info.uid!==process.getuid?.()&&info.uid!==0)throw new BridgeProtocolError(`nativeMessagingHostDir ownership rejected at ${current}: not owned by the current user or root`);const stickyRootAncestor=parts.length>0&&info.uid===0&&(info.mode&512)!==0;if(!stickyRootAncestor&&(info.mode&18)!==0)throw new BridgeProtocolError(`nativeMessagingHostDir security rejected at ${current}: writable by others`);final=info}if(!final||final.uid!==process.getuid?.()&&final.uid!==0)throw new BridgeProtocolError(`nativeMessagingHostDir ownership rejected at ${current}: not owned by the current user or root`);if((final.mode&63)!==0)await chmod2(absolute,448)}async function secureExecutable(hostPath){const info=await lstat(hostPath).catch(()=>null);if(!info?.isFile()||info.isSymbolicLink()||info.uid!==process.getuid?.()||(info.mode&73)===0||(info.mode&18)!==0)throw new BridgeProtocolError("hostPath must be a securely owned executable file")}async function installNativeMessagingHost({hostName=HOST_NAME,hostPath,extensionId,browser="chrome",nativeMessagingHostDir,force=false,endpointPath,registryKey}={}){const win32=process.platform==="win32";if(endpointPath!==undefined)throw new BridgeProtocolError("endpointPath is not supported");if(hostName!==HOST_NAME||!/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(hostName))throw new BridgeProtocolError("invalid hostName");if(hostPath===undefined||!path16.isAbsolute(hostPath))throw new BridgeProtocolError("hostPath must be absolute");if(!win32)await secureExecutable(hostPath);if(extensionId===undefined||!/^[a-p]{32}$/.test(extensionId))throw new BridgeProtocolError("invalid extensionId");if(!nativeMessagingHostDir&&browser==="cloakbrowser")throw new BridgeProtocolError("CloakBrowser nativeMessagingHostDir must be explicit and verified");if(registryKey!==undefined&&!win32)throw new BridgeProtocolError("registryKey is only used on win32");const dir=nativeMessagingHostDir??defaultNativeMessagingHostDir(browser);const manifest={name:hostName,description:"OmOWright internal CloakBrowser native messaging bridge.",path:hostPath,type:"stdio",allowed_origins:[`chrome-extension://${extensionId}/`]};const writeManifest=async(file)=>{if(!force&&await lstat(file).catch(()=>null))throw new BridgeProtocolError("registration manifest already exists; use force");const temp=`${file}.${process.pid}.${randomUUID3()}.tmp`;const handle=await open5(temp,"wx",384);try{await handle.writeFile(JSON.stringify(manifest,null,2)+`
|
|
1387
|
-
`);await handle.sync()}finally{await handle.close()}await rename2(temp,file);return JSON.parse(await readFile9(file,"utf8"))};if(win32){const key=registryKey??WIN32_REGISTRY_KEYS[browser];if(!isWin32RegistryKey(key))throw new BridgeProtocolError(registryKey===undefined?"custom browser requires registryKey on win32":"registryKey must be HKCU\\Software\\...\\NativeMessagingHosts");try{return await installWin32NativeHost({hostName,hostPath,dir,registryKey:key,force,writeManifest})}catch(error){throw error instanceof BridgeProtocolError?error:new BridgeProtocolError(String(readProperty(error,"message")))}}await secureDirectory(dir);const file=path16.join(dir,`${hostName}.json`);const parsed=await writeManifest(file);await chmod2(file,384);return{path:file,manifest:parsed}}function createBridgeClient(options={}){return createNativeMessagingHost(options)}function createChromeApi2(connection,options={}){const chrome=createChromeApi(connection,options);const bridge=options.bridge;const request=(wire,params)=>bridge?.isConnected&&bridge.capabilities?.commands?.has(wire)?bridge.request(wire,params):Promise.reject(new UnsupportedOperationError(`chrome.${wire} requires the extension bridge in standalone OmOWright`));chrome.bookmarks.create=(details)=>request("bookmarks.create",{details});chrome.bookmarks.move=(id,details={})=>request("bookmarks.move",{details:{...details,id:String(id)}});chrome.bookmarks.remove=(id)=>request("bookmarks.remove",{details:{id:String(id)}});chrome.history.deleteUrl=(details)=>request("history.deleteUrl",{details});chrome.history.deleteRange=(details)=>request("history.deleteRange",{details});chrome.tabGroups={update:(groupId,updateProperties)=>request("tabGroups.update",{details:{groupId,updateProperties}})};chrome.debugger={attach:(target,requiredVersion)=>request("debugger.attach",{details:{tabId:target.tabId??target,requiredVersion}}),detach:(target)=>request("debugger.detach",{details:{tabId:target.tabId??target}})};const eventMap={notifications:["onShown","onClicked","onClosed"],tabGroups:["onCreated","onUpdated","onMoved"],tabs:["onActivated"],windows:["onFocusChanged"]};for(const[namespace,events]of Object.entries(eventMap)){chrome[namespace]??={};for(const event of events){const wire=`${namespace}.${event.slice(2,3).toLowerCase()+event.slice(3)}`;const subscriptions=new Map;chrome[namespace][event]={addListener(listener){if(!bridge?.on)return;const unsubscribe=bridge.on(wire,(payload)=>listener(...namespace==="notifications"&&event==="onClosed"?[payload["notificationId"],payload["byUser"]]:namespace==="notifications"?[payload["notificationId"]]:namespace==="tabGroups"?[payload["group"]]:namespace==="windows"?[payload["windowId"]]:[payload]));subscriptions.set(listener,unsubscribe);return unsubscribe},removeListener(listener){const unsubscribe=subscriptions.get(listener);if(unsubscribe){unsubscribe();subscriptions.delete(listener)}}}}}return chrome}var DEVICE_PRESETS=Object.freeze({"iphone-14":{width:390,height:844,deviceScaleFactor:3,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",platform:"iPhone"},"pixel-7":{width:412,height:915,deviceScaleFactor:2.625,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36",platform:"Linux armv8l"},"ipad-air":{width:820,height:1180,deviceScaleFactor:2,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (iPad; CPU OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",platform:"MacIntel"},"desktop-1440":{width:1440,height:900,deviceScaleFactor:1,mobile:false,hasTouch:false,userAgent:undefined,platform:undefined}});var presetsByName=DEVICE_PRESETS;var originalUAs=new WeakMap;async function emulate(page,presetNameOrObject){let preset;if(presetNameOrObject===null){preset=null}else if(typeof presetNameOrObject==="string"){const named=presetsByName[presetNameOrObject];if(!named){throw new Error(`unknown device preset: ${presetNameOrObject}`)}preset=named}else{preset=presetNameOrObject}const sessionId=await page.resolveSessionId();if(preset===null){await page.cdp.send("Emulation.clearDeviceMetricsOverride",{},sessionId);await page.cdp.send("Emulation.setTouchEmulationEnabled",{enabled:false},sessionId);const originalUA=originalUAs.get(page);if(originalUA){await page.cdp.send("Emulation.setUserAgentOverride",{userAgent:originalUA},sessionId)}}else{if(!originalUAs.has(page)){const ua=await page.evaluate(()=>navigator.userAgent);originalUAs.set(page,ua)}await page.cdp.send("Emulation.setDeviceMetricsOverride",{width:preset.width,height:preset.height,deviceScaleFactor:preset.deviceScaleFactor,mobile:preset.mobile,screenWidth:preset.width,screenHeight:preset.height},sessionId);await page.cdp.send("Emulation.setTouchEmulationEnabled",{enabled:preset.hasTouch,maxTouchPoints:preset.hasTouch?5:1},sessionId);if(preset.userAgent!==undefined){await page.cdp.send("Emulation.setUserAgentOverride",{userAgent:preset.userAgent,platform:preset.platform},sessionId)}}if(page.refreshViewportSize){await page.refreshViewportSize()}return preset}var AUTO_ATTACH={autoAttach:true,waitForDebuggerOnStart:false,flatten:true};var REF_PATTERN2=/^(f\d+)?e\d+$/;function detach(page,sessionId){return page.cdp.send("Target.detachFromTarget",{sessionId}).catch(()=>{})}async function iframeTargets(page){const{targetInfo}=await page.cdp.send("Target.getTargetInfo",{targetId:page.targetId});const browserContextId=targetInfo?.browserContextId;const{targetInfos}=await page.cdp.send("Target.getTargets",{filter:[{type:"iframe"}]});return targetInfos.filter((info)=>info.type==="iframe"&&(!browserContextId||!info.browserContextId||info.browserContextId===browserContextId))}function isAttributed(fm,frameId){const seen=new Set;let frame=fm.frames.get(frameId);while(frame&&!seen.has(frame.frameId)){if(frame.frameId===fm.mainFrameId)return true;seen.add(frame.frameId);frame=frame.parentFrameId?fm.frames.get(frame.parentFrameId):null}return false}async function describeTarget(page,targetId){const{sessionId}=await page.cdp.send("Target.attachToTarget",{targetId,flatten:true});try{await page.cdp.send("Page.enable",undefined,sessionId);const{frameTree}=await page.cdp.send("Page.getFrameTree",undefined,sessionId);return{sessionId,frame:frameTree.frame}}catch(error){await detach(page,sessionId);throw error}}async function adopt(page,sessionId,frame,parentFrameId){await page.cdp.send("DOM.enable",undefined,sessionId);await page.cdp.send("Target.setAutoAttach",AUTO_ATTACH,sessionId).catch(()=>{});page.frameManager.frames.set(frame.id,{frameId:frame.id,parentFrameId,url:frame.url??"",name:frame.name??"",sessionId});const isolatedContextId=await page.frameManager.ensureInjected(frame.id);return{frameId:frame.id,parentFrameId,url:frame.url??"",sessionId,isolatedContextId}}async function reconcileFrames(page){const fm=page.frameManager;const added=[];let pending=(await iframeTargets(page)).filter((info)=>!isAttributed(fm,info.targetId));let progress=true;while(progress&&pending.length>0){progress=false;const retry=[];for(const target of pending){if(isAttributed(fm,target.targetId))continue;const{sessionId,frame}=await describeTarget(page,target.targetId);const parentFrameId=frame.parentId??null;if(!parentFrameId||!isAttributed(fm,parentFrameId)){await detach(page,sessionId);if(parentFrameId)retry.push(target);continue}added.push(await adopt(page,sessionId,frame,parentFrameId));progress=true}pending=retry}return added}function framePrefixes(fm){let counter=1;return fm.collectDescendantFrames(fm.mainFrameId).map(({frameId})=>({frameId,prefix:frameId===fm.mainFrameId?"":`f${counter++}`}))}function collectMissingFrames(page,refs){const seen=new Set(Object.keys(refs??{}).map((ref)=>ref.match(REF_PATTERN2)?.[1]??""));const missing=[];for(const{frameId,prefix}of framePrefixes(page.frameManager)){if(prefix===""||seen.has(prefix))continue;const frame=page.frameManager.getFrame(frameId);if(frame?.isolatedContextId)continue;missing.push({frameId,url:frame?.url??"",injected:false})}return missing}async function snapshotWithFrames(page,opts={}){await reconcileFrames(page);const result=await page.snapshot(opts);const missingFrames=collectMissingFrames(page,result.refs);return missingFrames.length>0?{...result,missingFrames}:result}var package_default={name:"omowright",version:"0.3.1",description:"OmOWright browser automation for standard Chromium CDP endpoints.",keywords:["accessibility-snapshot","ai-agent","browser-automation","bun","cdp","chrome-devtools-protocol","chromium","llm"],homepage:"https://github.com/code-yeongyu/omowright#readme",bugs:{url:"https://github.com/code-yeongyu/omowright/issues"},license:"MIT",repository:{type:"git",url:"git+https://github.com/code-yeongyu/omowright.git"},bin:{"omowright-cloak":"./dist/bin/omowright-cloak.js"},files:["dist/","skills/","presets/","README.md","LICENSE","TOOLS.md"],type:"module",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",default:"./dist/index.js"},"./package.json":"./package.json"},publishConfig:{access:"public",provenance:true},scripts:{test:"bun test","test:node":"bun scripts/node-test.ts","test:cloak-profile":"bun test test/cloak-profile.test.ts test/cloak-profile.integration.test.ts",typecheck:"tsc --noEmit -p tsconfig.json","typecheck:control":"bun scripts/typecheck-control.ts",check:"bun run typecheck:control && bun run typecheck && bun run lint && bun run fmt:check",lint:"oxlint --deny-warnings src bin bridge test scripts","lint:fix":"oxlint --fix src bin bridge test scripts",fmt:"oxfmt --write src bin bridge test scripts","fmt:check":"oxfmt --check src bin bridge test scripts",format:"bun run fmt","format:check":"bun run fmt:check",verify:"bun run check",build:"bun build.ts","build:extension":"bun bridge/build-extension.ts",prepack:"bun run build",preversion:"git diff --quiet HEAD --"},dependencies:{ws:"^8.18.3",zod:"^4.6.6"},devDependencies:{"@types/bun":"1.4.4",acorn:"8.15.0","gpt-tokenizer":"4.1.0",oxfmt:"^0.77.0",oxlint:"^1.92.0",typescript:"^7.0.2","typescript-5":"npm:typescript@5.9.3"},engines:{bun:">=1.4",node:">=22"}};var HTTP_VERSION="HTTP/1.1";var CREATOR=Object.freeze({name:"omowright",version:package_default.version});function headerList(headers){return Object.entries(headers??{}).map(([name,value])=>({name,value:String(value)}))}function headerValue(headers,name){for(const[key,value]of Object.entries(headers??{})){if(key.toLowerCase()===name)return String(value)}return null}function queryString(url){try{return[...new URL(String(url)).searchParams].map(([name,value])=>({name,value}))}catch{return[]}}function elapsed(entry){const started=Number(entry.startedAt);const finished=Number(entry.finishedAt);if(!Number.isFinite(started)||!Number.isFinite(finished))return 0;return Math.max(0,finished-started)}function requestOf(entry){const postData=entry.postData??null;const request={method:entry.method??"GET",url:entry.url??"",httpVersion:HTTP_VERSION,cookies:[],headers:headerList(entry.requestHeaders),queryString:queryString(entry.url),headersSize:-1,bodySize:postData===null?0:Buffer.byteLength(postData)};if(postData!==null){request.postData={mimeType:headerValue(entry.requestHeaders,"content-type")??"",text:postData}}return request}function contentOf(entry){const content={size:Number(entry.encodedDataLength??0),mimeType:entry.mimeType??""};if(typeof entry.body==="string")content.text=entry.body;if(entry.base64Encoded)content.encoding="base64";return content}function responseOf(entry){return{status:entry.failed?0:Number(entry.status??0),statusText:entry.statusText??"",httpVersion:HTTP_VERSION,cookies:[],headers:headerList(entry.responseHeaders),content:contentOf(entry),redirectURL:headerValue(entry.responseHeaders,"location")??"",headersSize:-1,bodySize:Number(entry.encodedDataLength??0)}}function toHar(entries,{creator=CREATOR,pages=[]}={}){const log={version:"1.2",creator,pages,entries:[...entries??[]].map((entry)=>{const time=elapsed(entry);const har={startedDateTime:new Date(Number(entry.startedAt)||0).toISOString(),time,request:requestOf(entry),response:responseOf(entry),cache:{},timings:{send:0,wait:time,receive:0}};if(entry.failed)Object.assign(har,{_errorText:entry.errorText??""});return har})};return{log}}function injectHumanBanner(prompt){if(document.querySelector('[data-omowright-human="1"]'))return true;const host=document.createElement("div");host.setAttribute("data-omowright-human","1");host.style.cssText="position:fixed;top:0;left:0;right:0;z-index:2147483647;display:block;visibility:visible;opacity:1;pointer-events:auto;";const root=host.attachShadow({mode:"open"});const bar=document.createElement("div");bar.setAttribute("style","display:flex;align-items:center;gap:12px;padding:10px 16px;background:#111;color:#fff;font:14px/1.4 system-ui,sans-serif;");const message=document.createElement("span");message.textContent=prompt==null?"":String(prompt);const button=document.createElement("button");button.textContent="Done";button.addEventListener("click",()=>{window.__omowrightHumanDone=true});bar.append(message,button);root.append(bar);(document.documentElement??document.body).appendChild(host);return true}function humanBannerPresent(){return document.querySelector('[data-omowright-human="1"]')!==null}function humanDoneFlag(){return window.__omowrightHumanDone===true}function querySelectorExists(selector){return document.querySelector(selector)!==null}function removeHumanBanner(){document.querySelectorAll('[data-omowright-human="1"]').forEach((node)=>node.remove());try{delete window.__omowrightHumanDone}catch{window.__omowrightHumanDone=undefined}}function sleep3(ms,signal){return new Promise((resolve)=>{if(signal?.aborted){resolve();return}const timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort);resolve()},ms);function onAbort(){clearTimeout(timer);resolve()}signal?.addEventListener("abort",onAbort,{once:true})})}async function ensureBanner(page,prompt){try{if(await page.evaluate(humanBannerPresent))return;await page.evaluate(injectHumanBanner,prompt??"")}catch{}}async function matchesUntil(page,until){if(until==null)return false;if(typeof until==="function")return Boolean(await until(page));if(typeof until==="object"){if(Object.prototype.hasOwnProperty.call(until,"url")){const current=page.url();const expected=until.url;if(expected instanceof RegExp)return expected.test(current);return String(current).includes(String(expected))}if(typeof until.selector==="string"){try{return Boolean(await page.evaluate(querySelectorExists,until.selector))}catch{return false}}}return false}async function isDone(page){try{return await page.evaluate(humanDoneFlag)===true}catch{return false}}async function requestHuman(page,{prompt,until,timeoutMs=300000,pollMs=500,signal}={}){const started=Date.now();const finish=(outcome,reason)=>({outcome,elapsedMs:Date.now()-started,reason});try{await page.bringToFront().catch(()=>{});await ensureBanner(page,prompt);for(;;){if(signal?.aborted)return finish("cancelled","signal");if(await matchesUntil(page,until))return finish("continued","until");if(await isDone(page))return finish("continued","done-button");if(Date.now()-started>=timeoutMs)return finish("timed_out","timed_out");await ensureBanner(page,prompt);const remaining=timeoutMs-(Date.now()-started);if(remaining<=0)return finish("timed_out","timed_out");await sleep3(Math.min(pollMs,remaining),signal)}}finally{await page.evaluate(removeHumanBanner).catch(()=>{})}}async function describeLayers(page,{grid=5}={}){return page.evaluate((gridSize)=>{const width=Math.round(globalThis.visualViewport?.width??globalThis.innerWidth??0);const height=Math.round(globalThis.visualViewport?.height??globalThis.innerHeight??0);const viewport={width,height};const total=gridSize*gridSize;const hits=new Map;function pierceTopmost(x,y){const stack=document.elementsFromPoint(x,y);let el=stack[0]??null;const seen=new Set;while(el?.shadowRoot&&typeof el.shadowRoot.elementsFromPoint==="function"){if(seen.has(el))break;seen.add(el);const inner=el.shadowRoot.elementsFromPoint(x,y)??[];const next=inner.find((node)=>node&&node!==el);if(!next)break;el=next}return el}function parentOf(node){if(!node)return null;if(node.parentElement)return node.parentElement;const root=node.getRootNode?.();return root instanceof ShadowRoot?root.host:null}function promote(el){const minArea=0.5*width*height;let node=el;while(node&&node.nodeType===1){const position=getComputedStyle(node).position;if(position==="fixed"||position==="sticky"||position==="absolute"){const rect=node.getBoundingClientRect();if(rect.width*rect.height>=minArea)return node}node=parentOf(node)}return el}function labelledByText(el){const ids=(el.getAttribute("aria-labelledby")||"").trim();if(!ids)return"";return ids.split(/\s+/).map((id)=>document.getElementById(id)?.textContent?.trim()??"").filter(Boolean).join(" ")}function elementName(el){const ariaLabel=el.getAttribute("aria-label");if(ariaLabel)return ariaLabel;const labelled=labelledByText(el);if(labelled)return labelled;const heading=el.querySelector("h1,h2,h3,h4,h5,h6")?.textContent?.trim();if(heading)return heading;return((el instanceof HTMLElement?el.innerText:undefined)||el.textContent||"").trim().replace(/\s+/g," ").slice(0,80)}function selectorHint(el){if(el.id)return`#${el.id}`;const classes=[...el.classList].join(".");return classes?`${el.tagName.toLowerCase()}.${classes}`:el.tagName.toLowerCase()}function describe(el,coverage){return{tagName:el.tagName,role:el.getAttribute("role")||"",name:elementName(el),coverage,position:getComputedStyle(el).position,selectorHint:selectorHint(el),ariaModal:el.getAttribute("aria-modal")==="true"}}function isMainContent(el){if(el===document.documentElement||el===document.body)return true;if(el.tagName==="MAIN")return true;return(el.getAttribute("role")||"").toLowerCase()==="main"}function isBlocking(el,info){if(info.coverage<0.6)return false;if(getComputedStyle(el).pointerEvents==="none")return false;const role=(info.role||"").toLowerCase();if(role==="dialog"||role==="alertdialog")return true;if(info.ariaModal)return true;if(isMainContent(el))return false;return info.position==="fixed"||info.position==="absolute"}const insetX=width*0.05;const insetY=height*0.05;const spanX=width*0.9;const spanY=height*0.9;for(let row=0;row<gridSize;row++){for(let col=0;col<gridSize;col++){const x=insetX+(col+0.5)*spanX/gridSize;const y=insetY+(row+0.5)*spanY/gridSize;const top=pierceTopmost(x,y);if(!top)continue;const candidate=promote(top);hits.set(candidate,(hits.get(candidate)??0)+1)}}const candidates=[...hits.entries()].map(([el,count])=>{const info=describe(el,total>0?count/total:0);return{el,info}}).toSorted((a,b)=>b.info.coverage-a.info.coverage);const blockingEntry=candidates.find((entry)=>isBlocking(entry.el,entry.info));return{blocking:blockingEntry?blockingEntry.info:null,candidates:candidates.map((entry)=>entry.info),viewport}},grid)}function layersHeader(result){const blocking=result?.blocking;if(!blocking)return"@layers none";const who=blocking.role||blocking.tagName;const pct=Math.round(blocking.coverage*100);return`@layers blocking=${who} "${blocking.name}" coverage=${pct}% hint=${blocking.selectorHint}`}async function snapshotWithLayers(page,snapshotOptions){const snapshot=await page.snapshot(snapshotOptions);if(typeof snapshot!=="object"||snapshot===null||!("tree"in snapshot)||typeof snapshot.tree!=="string"){throw new TypeError("snapshotWithLayers needs the full snapshot (no diff or find options)")}const layers=await describeLayers(page);return{...snapshot,layers,tree:`${layersHeader(layers)}
|
|
1387
|
+
`);await handle.sync()}finally{await handle.close()}await rename2(temp,file);return JSON.parse(await readFile9(file,"utf8"))};if(win32){const key=registryKey??WIN32_REGISTRY_KEYS[browser];if(!isWin32RegistryKey(key))throw new BridgeProtocolError(registryKey===undefined?"custom browser requires registryKey on win32":"registryKey must be HKCU\\Software\\...\\NativeMessagingHosts");try{return await installWin32NativeHost({hostName,hostPath,dir,registryKey:key,force,writeManifest})}catch(error){throw error instanceof BridgeProtocolError?error:new BridgeProtocolError(String(readProperty(error,"message")))}}await secureDirectory(dir);const file=path16.join(dir,`${hostName}.json`);const parsed=await writeManifest(file);await chmod2(file,384);return{path:file,manifest:parsed}}function createBridgeClient(options={}){return createNativeMessagingHost(options)}function createChromeApi2(connection,options={}){const chrome=createChromeApi(connection,options);const bridge=options.bridge;const request=(wire,params)=>bridge?.isConnected&&bridge.capabilities?.commands?.has(wire)?bridge.request(wire,params):Promise.reject(new UnsupportedOperationError(`chrome.${wire} requires the extension bridge in standalone OmOWright`));chrome.bookmarks.create=(details)=>request("bookmarks.create",{details});chrome.bookmarks.move=(id,details={})=>request("bookmarks.move",{details:{...details,id:String(id)}});chrome.bookmarks.remove=(id)=>request("bookmarks.remove",{details:{id:String(id)}});chrome.history.deleteUrl=(details)=>request("history.deleteUrl",{details});chrome.history.deleteRange=(details)=>request("history.deleteRange",{details});chrome.tabGroups={update:(groupId,updateProperties)=>request("tabGroups.update",{details:{groupId,updateProperties}})};chrome.debugger={attach:(target,requiredVersion)=>request("debugger.attach",{details:{tabId:target.tabId??target,requiredVersion}}),detach:(target)=>request("debugger.detach",{details:{tabId:target.tabId??target}})};const eventMap={notifications:["onShown","onClicked","onClosed"],tabGroups:["onCreated","onUpdated","onMoved"],tabs:["onActivated"],windows:["onFocusChanged"]};for(const[namespace,events]of Object.entries(eventMap)){chrome[namespace]??={};for(const event of events){const wire=`${namespace}.${event.slice(2,3).toLowerCase()+event.slice(3)}`;const subscriptions=new Map;chrome[namespace][event]={addListener(listener){if(!bridge?.on)return;const unsubscribe=bridge.on(wire,(payload)=>listener(...namespace==="notifications"&&event==="onClosed"?[payload["notificationId"],payload["byUser"]]:namespace==="notifications"?[payload["notificationId"]]:namespace==="tabGroups"?[payload["group"]]:namespace==="windows"?[payload["windowId"]]:[payload]));subscriptions.set(listener,unsubscribe);return unsubscribe},removeListener(listener){const unsubscribe=subscriptions.get(listener);if(unsubscribe){unsubscribe();subscriptions.delete(listener)}}}}}return chrome}var DEVICE_PRESETS=Object.freeze({"iphone-14":{width:390,height:844,deviceScaleFactor:3,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",platform:"iPhone"},"pixel-7":{width:412,height:915,deviceScaleFactor:2.625,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36",platform:"Linux armv8l"},"ipad-air":{width:820,height:1180,deviceScaleFactor:2,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (iPad; CPU OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",platform:"MacIntel"},"desktop-1440":{width:1440,height:900,deviceScaleFactor:1,mobile:false,hasTouch:false,userAgent:undefined,platform:undefined}});var presetsByName=DEVICE_PRESETS;var originalUAs=new WeakMap;async function emulate(page,presetNameOrObject){let preset;if(presetNameOrObject===null){preset=null}else if(typeof presetNameOrObject==="string"){const named=presetsByName[presetNameOrObject];if(!named){throw new Error(`unknown device preset: ${presetNameOrObject}`)}preset=named}else{preset=presetNameOrObject}const sessionId=await page.resolveSessionId();if(preset===null){await page.cdp.send("Emulation.clearDeviceMetricsOverride",{},sessionId);await page.cdp.send("Emulation.setTouchEmulationEnabled",{enabled:false},sessionId);const originalUA=originalUAs.get(page);if(originalUA){await page.cdp.send("Emulation.setUserAgentOverride",{userAgent:originalUA},sessionId)}}else{if(!originalUAs.has(page)){const ua=await page.evaluate(()=>navigator.userAgent);originalUAs.set(page,ua)}await page.cdp.send("Emulation.setDeviceMetricsOverride",{width:preset.width,height:preset.height,deviceScaleFactor:preset.deviceScaleFactor,mobile:preset.mobile,screenWidth:preset.width,screenHeight:preset.height},sessionId);await page.cdp.send("Emulation.setTouchEmulationEnabled",{enabled:preset.hasTouch,maxTouchPoints:preset.hasTouch?5:1},sessionId);if(preset.userAgent!==undefined){await page.cdp.send("Emulation.setUserAgentOverride",{userAgent:preset.userAgent,platform:preset.platform},sessionId)}}if(page.refreshViewportSize){await page.refreshViewportSize()}return preset}var AUTO_ATTACH={autoAttach:true,waitForDebuggerOnStart:false,flatten:true};var REF_PATTERN2=/^(f\d+)?e\d+$/;function detach(page,sessionId){return page.cdp.send("Target.detachFromTarget",{sessionId}).catch(()=>{})}async function iframeTargets(page){const{targetInfo}=await page.cdp.send("Target.getTargetInfo",{targetId:page.targetId});const browserContextId=targetInfo?.browserContextId;const{targetInfos}=await page.cdp.send("Target.getTargets",{filter:[{type:"iframe"}]});return targetInfos.filter((info)=>info.type==="iframe"&&(!browserContextId||!info.browserContextId||info.browserContextId===browserContextId))}function isAttributed(fm,frameId){const seen=new Set;let frame=fm.frames.get(frameId);while(frame&&!seen.has(frame.frameId)){if(frame.frameId===fm.mainFrameId)return true;seen.add(frame.frameId);frame=frame.parentFrameId?fm.frames.get(frame.parentFrameId):null}return false}async function describeTarget(page,targetId){const{sessionId}=await page.cdp.send("Target.attachToTarget",{targetId,flatten:true});try{await page.cdp.send("Page.enable",undefined,sessionId);const{frameTree}=await page.cdp.send("Page.getFrameTree",undefined,sessionId);return{sessionId,frame:frameTree.frame}}catch(error){await detach(page,sessionId);throw error}}async function adopt(page,sessionId,frame,parentFrameId){await page.cdp.send("DOM.enable",undefined,sessionId);await page.cdp.send("Target.setAutoAttach",AUTO_ATTACH,sessionId).catch(()=>{});page.frameManager.frames.set(frame.id,{frameId:frame.id,parentFrameId,url:frame.url??"",name:frame.name??"",sessionId});const isolatedContextId=await page.frameManager.ensureInjected(frame.id);return{frameId:frame.id,parentFrameId,url:frame.url??"",sessionId,isolatedContextId}}async function reconcileFrames(page){const fm=page.frameManager;const added=[];let pending=(await iframeTargets(page)).filter((info)=>!isAttributed(fm,info.targetId));let progress=true;while(progress&&pending.length>0){progress=false;const retry=[];for(const target of pending){if(isAttributed(fm,target.targetId))continue;const{sessionId,frame}=await describeTarget(page,target.targetId);const parentFrameId=frame.parentId??null;if(!parentFrameId||!isAttributed(fm,parentFrameId)){await detach(page,sessionId);if(parentFrameId)retry.push(target);continue}added.push(await adopt(page,sessionId,frame,parentFrameId));progress=true}pending=retry}return added}function framePrefixes(fm){let counter=1;return fm.collectDescendantFrames(fm.mainFrameId).map(({frameId})=>({frameId,prefix:frameId===fm.mainFrameId?"":`f${counter++}`}))}function collectMissingFrames(page,refs){const seen=new Set(Object.keys(refs??{}).map((ref)=>ref.match(REF_PATTERN2)?.[1]??""));const missing=[];for(const{frameId,prefix}of framePrefixes(page.frameManager)){if(prefix===""||seen.has(prefix))continue;const frame=page.frameManager.getFrame(frameId);if(frame?.isolatedContextId)continue;missing.push({frameId,url:frame?.url??"",injected:false})}return missing}async function snapshotWithFrames(page,opts={}){await reconcileFrames(page);const result=await page.snapshot(opts);const missingFrames=collectMissingFrames(page,result.refs);return missingFrames.length>0?{...result,missingFrames}:result}var package_default={name:"omowright",version:"0.3.2",description:"OmOWright browser automation for standard Chromium CDP endpoints.",keywords:["accessibility-snapshot","ai-agent","browser-automation","bun","cdp","chrome-devtools-protocol","chromium","llm"],homepage:"https://github.com/code-yeongyu/omowright#readme",bugs:{url:"https://github.com/code-yeongyu/omowright/issues"},license:"MIT",repository:{type:"git",url:"git+https://github.com/code-yeongyu/omowright.git"},bin:{"omowright-cloak":"./dist/bin/omowright-cloak.js"},files:["dist/","skills/","presets/","README.md","LICENSE","TOOLS.md"],type:"module",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",default:"./dist/index.js"},"./package.json":"./package.json"},publishConfig:{access:"public",provenance:true},scripts:{test:"bun test --parallel","test:node":"bun scripts/node-test.ts","test:cloak-profile":"bun test test/cloak-profile.test.ts test/cloak-profile.integration.test.ts",typecheck:"bun check --no-script --no-pretty -p tsconfig.json","typecheck:control":"bun scripts/typecheck-control.ts",check:"bun run typecheck:control && bun run typecheck && bun run lint && bun run fmt:check",lint:"oxlint --deny-warnings src bin bridge test scripts && bun scripts/lint-ratchet.ts","lint:ratchet:update":"bun scripts/lint-ratchet.ts --update","lint:fix":"oxlint --fix src bin bridge test scripts",fmt:"bun fmt --no-script --write src bin bridge test scripts","fmt:check":"bun fmt --no-script --check src bin bridge test scripts",format:"bun run fmt","format:check":"bun run fmt:check",verify:"bun run check","check:push":"bun run check && bun run build && git diff --exit-code HEAD --",prepare:"husky",build:"bun build.ts","build:extension":"bun bridge/build-extension.ts",prepack:"bun run build",preversion:"git diff --quiet HEAD --"},dependencies:{ws:"^8.23.0",zod:"^4.6.7"},devDependencies:{"@types/bun":"1.4.5",acorn:"8.19.0","gpt-tokenizer":"4.1.2",husky:"9.1.7","oxc-parser":"0.159.0",oxlint:"^1.94.0","typescript-5":"npm:typescript@5.9.3"},engines:{bun:">=1.4",node:">=22"}};var HTTP_VERSION="HTTP/1.1";var CREATOR=Object.freeze({name:"omowright",version:package_default.version});function headerList(headers){return Object.entries(headers??{}).map(([name,value])=>({name,value:String(value)}))}function headerValue(headers,name){for(const[key,value]of Object.entries(headers??{})){if(key.toLowerCase()===name)return String(value)}return null}function queryString(url){try{return[...new URL(String(url)).searchParams].map(([name,value])=>({name,value}))}catch{return[]}}function elapsed(entry){const started=Number(entry.startedAt);const finished=Number(entry.finishedAt);if(!Number.isFinite(started)||!Number.isFinite(finished))return 0;return Math.max(0,finished-started)}function requestOf(entry){const postData=entry.postData??null;const request={method:entry.method??"GET",url:entry.url??"",httpVersion:HTTP_VERSION,cookies:[],headers:headerList(entry.requestHeaders),queryString:queryString(entry.url),headersSize:-1,bodySize:postData===null?0:Buffer.byteLength(postData)};if(postData!==null){request.postData={mimeType:headerValue(entry.requestHeaders,"content-type")??"",text:postData}}return request}function contentOf(entry){const content={size:Number(entry.encodedDataLength??0),mimeType:entry.mimeType??""};if(typeof entry.body==="string")content.text=entry.body;if(entry.base64Encoded)content.encoding="base64";return content}function responseOf(entry){return{status:entry.failed?0:Number(entry.status??0),statusText:entry.statusText??"",httpVersion:HTTP_VERSION,cookies:[],headers:headerList(entry.responseHeaders),content:contentOf(entry),redirectURL:headerValue(entry.responseHeaders,"location")??"",headersSize:-1,bodySize:Number(entry.encodedDataLength??0)}}function toHar(entries,{creator=CREATOR,pages=[]}={}){const log={version:"1.2",creator,pages,entries:[...entries??[]].map((entry)=>{const time=elapsed(entry);const har={startedDateTime:new Date(Number(entry.startedAt)||0).toISOString(),time,request:requestOf(entry),response:responseOf(entry),cache:{},timings:{send:0,wait:time,receive:0}};if(entry.failed)Object.assign(har,{_errorText:entry.errorText??""});return har})};return{log}}function injectHumanBanner(prompt){if(document.querySelector('[data-omowright-human="1"]'))return true;const host=document.createElement("div");host.setAttribute("data-omowright-human","1");host.style.cssText="position:fixed;top:0;left:0;right:0;z-index:2147483647;display:block;visibility:visible;opacity:1;pointer-events:auto;";const root=host.attachShadow({mode:"open"});const bar=document.createElement("div");bar.setAttribute("style","display:flex;align-items:center;gap:12px;padding:10px 16px;background:#111;color:#fff;font:14px/1.4 system-ui,sans-serif;");const message=document.createElement("span");message.textContent=prompt==null?"":String(prompt);const button=document.createElement("button");button.textContent="Done";button.addEventListener("click",()=>{window.__omowrightHumanDone=true});bar.append(message,button);root.append(bar);(document.documentElement??document.body).appendChild(host);return true}function humanBannerPresent(){return document.querySelector('[data-omowright-human="1"]')!==null}function humanDoneFlag(){return window.__omowrightHumanDone===true}function querySelectorExists(selector){return document.querySelector(selector)!==null}function removeHumanBanner(){document.querySelectorAll('[data-omowright-human="1"]').forEach((node)=>node.remove());try{delete window.__omowrightHumanDone}catch{window.__omowrightHumanDone=undefined}}function sleep3(ms,signal){return new Promise((resolve)=>{if(signal?.aborted){resolve();return}const timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort);resolve()},ms);function onAbort(){clearTimeout(timer);resolve()}signal?.addEventListener("abort",onAbort,{once:true})})}async function ensureBanner(page,prompt){try{if(await page.evaluate(humanBannerPresent))return;await page.evaluate(injectHumanBanner,prompt??"")}catch{}}async function matchesUntil(page,until){if(until==null)return false;if(typeof until==="function")return Boolean(await until(page));if(typeof until==="object"){if(Object.prototype.hasOwnProperty.call(until,"url")){const current=page.url();const expected=until.url;if(expected instanceof RegExp)return expected.test(current);return String(current).includes(String(expected))}if(typeof until.selector==="string"){try{return Boolean(await page.evaluate(querySelectorExists,until.selector))}catch{return false}}}return false}async function isDone(page){try{return await page.evaluate(humanDoneFlag)===true}catch{return false}}async function requestHuman(page,{prompt,until,timeoutMs=300000,pollMs=500,signal}={}){const started=Date.now();const finish=(outcome,reason)=>({outcome,elapsedMs:Date.now()-started,reason});try{await page.bringToFront().catch(()=>{});await ensureBanner(page,prompt);for(;;){if(signal?.aborted)return finish("cancelled","signal");if(await matchesUntil(page,until))return finish("continued","until");if(await isDone(page))return finish("continued","done-button");if(Date.now()-started>=timeoutMs)return finish("timed_out","timed_out");await ensureBanner(page,prompt);const remaining=timeoutMs-(Date.now()-started);if(remaining<=0)return finish("timed_out","timed_out");await sleep3(Math.min(pollMs,remaining),signal)}}finally{await page.evaluate(removeHumanBanner).catch(()=>{})}}async function describeLayers(page,{grid=5}={}){return page.evaluate((gridSize)=>{const width=Math.round(globalThis.visualViewport?.width??globalThis.innerWidth??0);const height=Math.round(globalThis.visualViewport?.height??globalThis.innerHeight??0);const viewport={width,height};const total=gridSize*gridSize;const hits=new Map;function pierceTopmost(x,y){const stack=document.elementsFromPoint(x,y);let el=stack[0]??null;const seen=new Set;while(el?.shadowRoot&&typeof el.shadowRoot.elementsFromPoint==="function"){if(seen.has(el))break;seen.add(el);const inner=el.shadowRoot.elementsFromPoint(x,y)??[];const next=inner.find((node)=>node&&node!==el);if(!next)break;el=next}return el}function parentOf(node){if(!node)return null;if(node.parentElement)return node.parentElement;const root=node.getRootNode?.();return root instanceof ShadowRoot?root.host:null}function promote(el){const minArea=0.5*width*height;let node=el;while(node&&node.nodeType===1){const position=getComputedStyle(node).position;if(position==="fixed"||position==="sticky"||position==="absolute"){const rect=node.getBoundingClientRect();if(rect.width*rect.height>=minArea)return node}node=parentOf(node)}return el}function labelledByText(el){const ids=(el.getAttribute("aria-labelledby")||"").trim();if(!ids)return"";return ids.split(/\s+/).map((id)=>document.getElementById(id)?.textContent?.trim()??"").filter(Boolean).join(" ")}function elementName(el){const ariaLabel=el.getAttribute("aria-label");if(ariaLabel)return ariaLabel;const labelled=labelledByText(el);if(labelled)return labelled;const heading=el.querySelector("h1,h2,h3,h4,h5,h6")?.textContent?.trim();if(heading)return heading;return((el instanceof HTMLElement?el.innerText:undefined)||el.textContent||"").trim().replace(/\s+/g," ").slice(0,80)}function selectorHint(el){if(el.id)return`#${el.id}`;const classes=[...el.classList].join(".");return classes?`${el.tagName.toLowerCase()}.${classes}`:el.tagName.toLowerCase()}function describe(el,coverage){return{tagName:el.tagName,role:el.getAttribute("role")||"",name:elementName(el),coverage,position:getComputedStyle(el).position,selectorHint:selectorHint(el),ariaModal:el.getAttribute("aria-modal")==="true"}}function isMainContent(el){if(el===document.documentElement||el===document.body)return true;if(el.tagName==="MAIN")return true;return(el.getAttribute("role")||"").toLowerCase()==="main"}function isBlocking(el,info){if(info.coverage<0.6)return false;if(getComputedStyle(el).pointerEvents==="none")return false;const role=(info.role||"").toLowerCase();if(role==="dialog"||role==="alertdialog")return true;if(info.ariaModal)return true;if(isMainContent(el))return false;return info.position==="fixed"||info.position==="absolute"}const insetX=width*0.05;const insetY=height*0.05;const spanX=width*0.9;const spanY=height*0.9;for(let row=0;row<gridSize;row++){for(let col=0;col<gridSize;col++){const x=insetX+(col+0.5)*spanX/gridSize;const y=insetY+(row+0.5)*spanY/gridSize;const top=pierceTopmost(x,y);if(!top)continue;const candidate=promote(top);hits.set(candidate,(hits.get(candidate)??0)+1)}}const candidates=[...hits.entries()].map(([el,count])=>{const info=describe(el,total>0?count/total:0);return{el,info}}).toSorted((a,b)=>b.info.coverage-a.info.coverage);const blockingEntry=candidates.find((entry)=>isBlocking(entry.el,entry.info));return{blocking:blockingEntry?blockingEntry.info:null,candidates:candidates.map((entry)=>entry.info),viewport}},grid)}function layersHeader(result){const blocking=result?.blocking;if(!blocking)return"@layers none";const who=blocking.role||blocking.tagName;const pct=Math.round(blocking.coverage*100);return`@layers blocking=${who} "${blocking.name}" coverage=${pct}% hint=${blocking.selectorHint}`}async function snapshotWithLayers(page,snapshotOptions){const snapshot=await page.snapshot(snapshotOptions);if(typeof snapshot!=="object"||snapshot===null||!("tree"in snapshot)||typeof snapshot.tree!=="string"){throw new TypeError("snapshotWithLayers needs the full snapshot (no diff or find options)")}const layers=await describeLayers(page);return{...snapshot,layers,tree:`${layersHeader(layers)}
|
|
1388
1388
|
${snapshot.tree}`}}var DEFAULT_TIMEOUT_MS=30000;var JSON_MIME=/^application\/json\s*(;|$)|\+json\s*(;|$)/i;function matchesText(value,pattern){if(pattern===undefined)return true;if(value===null||value===undefined)return false;if(pattern instanceof RegExp)return pattern.test(String(value));return String(value).includes(String(pattern))}function matchesToken(value,expected){if(expected===undefined)return true;if(value===null||value===undefined)return false;return String(value).toLowerCase()===String(expected).toLowerCase()}function toPredicate(match){if(match===undefined||match===null)return()=>true;if(typeof match==="function")return match;if(typeof match!=="object")throw new TypeError("match must be a predicate function or a descriptor object");return(entry)=>matchesText(entry.url,match.url)&&matchesToken(entry.method,match.method)&&matchesText(entry.mimeType,match.mimeType)&&matchesToken(entry.resourceType,match.resourceType)}function startedAtOf(params){const wallTime=Number(params?.wallTime);return Number.isFinite(wallTime)&&wallTime>0?Math.round(wallTime*1000):Date.now()}function decodeBody(entry){if(typeof entry.body!=="string")return null;return entry.base64Encoded?Buffer.from(entry.body,"base64").toString("utf8"):entry.body}function createNetworkSnoop(page,options={}){if(!page?.cdp||typeof page.resolveSessionId!=="function"){throw new TypeError("createNetworkSnoop requires a page with cdp and resolveSessionId")}const{match,bodies=true,maxEntries=500,maxBodyBytes=5000000}=options;const wanted=toPredicate(match);const inflight=new Map;const buffer=[];const waiters=new Set;const handlers={};let disposed=false;let queue=Promise.resolve();function subscribe(method,handler){handlers[method]=handler}function enqueue(task){queue=queue.then(task).catch((error)=>console.warn("[network-snoop] entry processing failed",error))}async function loadBody(entry,record){if(entry.encodedDataLength>maxBodyBytes){entry.bodySkipped=true;return}try{if(record===undefined)throw new TypeError("Cannot read properties of undefined (reading 'rawBody')");const result=await record.rawBody();entry.body=result?.body??null;entry.base64Encoded=Boolean(result?.base64Encoded)}catch{entry.body=null}}function commit(entry){buffer.push(entry);while(buffer.length>maxEntries)buffer.shift();for(const waiter of[...waiters])if(waiter.test(entry))waiter.resolve(entry)}subscribe("Network.requestWillBeSent",(params)=>{const requestId=params?.requestId;if(!requestId)return;inflight.set(requestId,{requestId,url:params.request?.url??params.documentURL??"",method:params.request?.method??"GET",resourceType:params.type??null,status:null,statusText:null,mimeType:null,requestHeaders:params.request?.headers??{},responseHeaders:null,remoteIPAddress:null,postData:params.request?.postData??null,encodedDataLength:0,body:null,base64Encoded:false,bodySkipped:false,failed:false,errorText:null,startedAt:startedAtOf(params),finishedAt:null})});subscribe("Network.responseReceived",(params)=>{const entry=inflight.get(params?.requestId);if(!entry)return;const response=params.response??{};entry.status=response.status??null;entry.statusText=response.statusText??"";entry.mimeType=response.mimeType??null;entry.responseHeaders=response.headers??{};entry.remoteIPAddress=response.remoteIPAddress??null;if(params.type)entry.resourceType=params.type});subscribe("Network.loadingFinished",(params,record)=>{const entry=inflight.get(params?.requestId);if(!entry)return;inflight.delete(entry.requestId);entry.encodedDataLength=Number(params.encodedDataLength??0);entry.finishedAt=Date.now();enqueue(async()=>{if(!wanted(entry))return;if(bodies)await loadBody(entry,record);commit(entry)})});subscribe("Network.loadingFailed",(params)=>{const entry=inflight.get(params?.requestId);if(!entry)return;inflight.delete(entry.requestId);entry.failed=true;entry.errorText=params.errorText??"";entry.encodedDataLength=Number(readProperty(params,"encodedDataLength")??entry.encodedDataLength);entry.finishedAt=Date.now();enqueue(async()=>{if(wanted(entry))commit(entry)})});function pop(){return buffer.splice(0,buffer.length)}function peek(){return[...buffer]}function popJson(){const values=[];for(const entry of pop()){if(!JSON_MIME.test(String(entry.mimeType??"")))continue;const text=decodeBody(entry);if(text===null)continue;try{values.push(JSON.parse(text))}catch{}}return values}function waitFor(entryMatch,{timeoutMs=DEFAULT_TIMEOUT_MS}={}){if(disposed)return Promise.reject(Error("Network snoop is disposed"));const predicate=toPredicate(entryMatch);return new Promise((resolve,reject)=>{let settled=false;const finish=(callback)=>(value)=>{if(settled)return;settled=true;clearTimeout(timer);waiters.delete(waiter);callback(value)};const waiter={resolve:finish(resolve),reject:finish(reject),test:(entry)=>{try{return Boolean(predicate(entry))}catch(error){waiter.reject(error instanceof Error?error:Error(String(error)));return false}}};const timer=setTimeout(()=>waiter.reject(Error(`Timed out waiting for network response after ${timeoutMs}ms`)),timeoutMs);waiters.add(waiter)})}function summary({max=50}={}){const shown=buffer.slice(0,max);const lines=shown.map((entry)=>[entry.method,entry.status??(entry.failed?"FAILED":"-"),entry.mimeType??"-",`${entry.encodedDataLength}B`,entry.url].join(" "));const hidden=buffer.length-shown.length;if(hidden>0)lines.push(`... +${hidden} more`);return lines.join(`
|
|
1389
1389
|
`)}function dispose(){if(disposed)return;disposed=true;unsubscribe();for(const waiter of[...waiters])waiter.reject(Error("Network snoop disposed"));waiters.clear();inflight.clear()}const unsubscribe=subscribeNetwork(page,handlers);return{pop,peek,popJson,waitFor,summary,dispose}}async function viewportOf(page){return page.viewportSize()??await page.evaluate(()=>({width:innerWidth,height:innerHeight}))}async function scrollOnce(page,mode){if(mode==="end"){await page.evaluate(()=>{const element=document.scrollingElement;if(!element)throw new TypeError("Cannot read properties of null (reading 'scrollHeight')");scrollTo(0,element.scrollHeight)});return}const viewport=await viewportOf(page);await page.mouse.move(Math.floor(viewport.width/2),Math.floor(viewport.height/2));await page.mouse.wheel(0,Math.floor(viewport.height*0.9))}async function*collectWhileScrolling(page,snoop,options={}){const{minItems=Infinity,maxScrolls=10,extract=(json)=>Array.isArray(json)?json:[],scroll="wheel",settleMs=800}=options;if(scroll!=="wheel"&&scroll!=="end")throw new TypeError(`Unknown scroll mode: ${String(scroll)}`);let rounds=0;let total=0;let lastHeight=null;let unchanged=0;let stoppedBecause="maxScrolls";for(;;){for(const json of snoop.popJson()){for(const item of extract(json)){total+=1;yield item}}if(total>=minItems){stoppedBecause="minItems";break}if(rounds>=maxScrolls){stoppedBecause="maxScrolls";break}const height=await page.evaluate(()=>{const element=document.scrollingElement;if(!element)throw new TypeError("Cannot read properties of null (reading 'scrollHeight')");return element.scrollHeight});if(lastHeight!==null&&height===lastHeight){unchanged+=1;if(unchanged>=2){stoppedBecause="noGrowth";break}}else{unchanged=0}lastHeight=height;await scrollOnce(page,scroll);rounds+=1;await new Promise((resolve)=>setTimeout(resolve,settleMs))}return{rounds,total,stoppedBecause}}var SLUG_MAX=48;var SNOOP_MAX_ENTRIES=5000;function slug(name){const value=String(name??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return(value||"step").slice(0,SLUG_MAX)}function messageOf2(error){return error instanceof Error?error.message:String(error)}async function readConsole(page){const api=page.console;let entries;if(typeof api==="function")entries=await api.call(page);else{const logs=api===null||api===undefined?undefined:readProperty(api,"logs");if(logs!==null&&logs!==undefined){if(typeof logs!=="function")throw new TypeError("api.logs is not a function");entries=await logs.call(api)}}return Array.isArray(entries)?entries:[]}function createTrace(page,options={}){if(!page?.cdp||typeof page.resolveSessionId!=="function"){throw new TypeError("createTrace requires a page with cdp and resolveSessionId")}const{dir,screenshots=true,network=true,console:consoleLogs=true,maxBodyBytes=1e6,events}=options;if(typeof dir!=="string"||dir.length===0)throw new TypeError("createTrace requires a dir");const traceDir=dir;const shotDir=path17.join(dir,"screenshots");const ready=mkdir9(shotDir,{recursive:true});const startedAt=Date.now();const records=[];const netEntries=[];const unsubscribers=[];const snoop=network?createNetworkSnoop(page,{bodies:true,maxBodyBytes,maxEntries:SNOOP_MAX_ENTRIES}):null;let seq=0;let consoleSeen=0;let sessionId=null;let stopped=false;let stopping=null;function record(event){const entry={...event,ts:Date.now(),seq:seq++};records.push(entry);return entry}const sessionReady=Promise.resolve(page.resolveSessionId()).then((id)=>{sessionId=id});sessionReady.catch((error)=>record({kind:"warning",scope:"session",message:messageOf2(error)}));unsubscribers.push(page.cdp.on("Page.frameNavigated",(params,meta)=>{if(stopped||params?.frame?.parentId)return;const add=()=>record({kind:"navigation",url:params?.frame?.url??"",frameId:params?.frame?.id??null});if(sessionId===null){sessionReady.then(()=>{if(!stopped&&meta?.sessionId===sessionId)add()}).catch(()=>{});return}if(meta?.sessionId===sessionId)add()}));unsubscribers.push(page.on("dialog",(dialog)=>record({kind:"dialog",type:dialog.type()??null,message:dialog.message()??"",defaultPrompt:dialog.defaultValue(),url:dialog.url??null})));if(events){unsubscribers.push(events.on("downloadStarted",(payload)=>record({kind:"download",phase:"started",...payload})));unsubscribers.push(events.on("downloadFinished",(payload)=>record({kind:"download",phase:"finished",...payload})))}async function capture(stepRecord,phase){const file=path17.join(shotDir,`${stepRecord.seq}-${slug(stepRecord.name)}-${phase}.png`);try{await writeFile3(file,await page.screenshot({type:"png"}));stepRecord.screenshots[phase]=file}catch(error){record({kind:"warning",scope:`screenshot:${phase}`,step:stepRecord.seq,message:messageOf2(error)})}}function drainNetwork(){for(const entry of snoop?.pop()??[]){if(typeof entry.body==="string"&&Buffer.byteLength(entry.body)>maxBodyBytes){entry.body=null;entry.bodySkipped=true}netEntries.push(entry);record({kind:"network",...entry})}}async function drainConsole(){if(!consoleLogs)return;let entries;try{entries=await readConsole(page)}catch{return}if(entries.length<consoleSeen)consoleSeen=0;for(const entry of entries.slice(consoleSeen))record(Object.assign({kind:"console"},entry));consoleSeen=entries.length}async function drain(){drainNetwork();await drainConsole()}async function step(name,fn){if(typeof fn!=="function")throw new TypeError("trace.step requires a function");await ready;const entry=record({kind:"step",name:String(name),startedAt:Date.now(),screenshots:{}});if(screenshots)await capture(entry,"before");try{return await fn()}catch(error){entry.error=messageOf2(error);throw error}finally{entry.endedAt=Date.now();entry.durationMs=entry.endedAt-entry.startedAt;if(screenshots)await capture(entry,"after");await drain()}}function mark(name,data){return record({kind:"mark",name:String(name),data:data??null})}async function finish(){await ready;await drain();stopped=true;for(const off of unsubscribers.splice(0,unsubscribers.length))off();snoop?.dispose();const ordered=records.toSorted((a,b)=>a.seq-b.seq);const summary={steps:ordered.filter((entry)=>entry.kind==="step").length,events:ordered.length,network:netEntries.length,startedAt,endedAt:Date.now(),url:page.url()};await writeFile3(path17.join(traceDir,"trace.jsonl"),ordered.map((entry)=>`${JSON.stringify(entry)}
|
|
1390
1390
|
`).join(""));await writeFile3(path17.join(traceDir,"trace.har"),`${JSON.stringify(toHar(netEntries),null,2)}
|
|
1391
1391
|
`);await writeFile3(path17.join(traceDir,"summary.json"),`${JSON.stringify(summary,null,2)}
|
|
1392
|
-
`);return summary}function stop(){return stopping??=finish()}return{step,mark,stop,get dir(){return dir}}}function isDaemonInfo(value){if(!value||typeof value!=="object"||!("sock_path"in value))return false;return typeof value.sock_path==="string"&&value.sock_path.length>0}function resolveBskHome(env=process.env){const override=env["BSK_HOME"];if(typeof override==="string"&&override.length>0)return override;const home=env["HOME"]&&env["HOME"].length>0?env["HOME"]:
|
|
1392
|
+
`);return summary}function stop(){return stopping??=finish()}return{step,mark,stop,get dir(){return dir}}}var BSK_CLI_VERSION="0.5.0";var RELEASE_TAG=`cli-v${BSK_CLI_VERSION}`;var INSTALL_SH=`https://raw.githubusercontent.com/Tencent/BrowserSkill/${RELEASE_TAG}/install.sh`;var INSTALL_PS1=`https://raw.githubusercontent.com/Tencent/BrowserSkill/${RELEASE_TAG}/install.ps1`;var BSK_PINNED_MANIFEST_URL=`https://github.com/Tencent/BrowserSkill/releases/download/${RELEASE_TAG}/version.json`;var RC_FILES=[".zshrc",".bashrc",".profile"];function windowsPowerShellEnv(env){const key=Object.keys(process.env).find((name)=>name.toUpperCase()==="PSMODULEPATH");if(!key)return env;const value=process.env[key];if(value===undefined)throw new TypeError(`${key} has no value`);const kept=value.split(";").filter((entry)=>entry&&!/[\\/]PowerShell[\\/]/i.test(entry));return{...env,[key]:kept.length>0?kept.join(";"):undefined}}function cliInstallCommand({platform=process.platform,installDir,version=BSK_CLI_VERSION}={}){const env={BSK_INSTALL_DIR:installDir,BSK_VERSION:version};if(platform==="win32"){return{command:windowsSystemTool("WindowsPowerShell\\v1.0\\powershell.exe"),args:["-NoProfile","-ExecutionPolicy","Bypass","-Command",`irm ${INSTALL_PS1} | iex`],env:windowsPowerShellEnv(env)}}return{command:"sh",args:["-c",`curl -fsSL ${INSTALL_SH} | sh`],env}}function runDefault(command,args,env){return new Promise((resolve)=>{const child=spawn6(command,args,{env:{...process.env,...env},stdio:["ignore","pipe","pipe"],windowsHide:true});let stdout="",stderr="";child.stdout.on("data",(c)=>{stdout=(stdout+c).slice(-8192)});child.stderr.on("data",(c)=>{stderr=(stderr+c).slice(-8192)});child.on("error",(error)=>resolve({code:-1,stdout,stderr:error.message}));child.on("exit",(code)=>resolve({code,stdout,stderr}))})}function snapshotRcFiles(home){const snapshot=new Map;for(const name of RC_FILES){const file=path18.join(home,name);snapshot.set(file,existsSync4(file)?readFileSync4(file):null)}return snapshot}function restoreRcFiles(snapshot){const restored=[];for(const[file,before]of snapshot){const after=existsSync4(file)?readFileSync4(file):null;if(before===null&&after===null)continue;if(before!==null&&after!==null&&before.equals(after))continue;if(before===null)rmSync3(file,{force:true});else writeFileSync3(file,before);restored.push(file)}return restored}async function installBskCli({platform=process.platform,home=homedir3(),installDir=path18.join(home,".local","bin"),version,run=runDefault}={}){const spec=cliInstallCommand({platform,installDir,version});const rcBefore=platform==="win32"?new Map:snapshotRcFiles(home);const result=await run(spec.command,spec.args,spec.env);const restoredRcFiles=restoreRcFiles(rcBefore);const bskBin=path18.join(installDir,platform==="win32"?"bsk.exe":"bsk");const installed=result.code===0&&existsSync4(bskBin);return{installed,bskBin:installed?bskBin:null,code:result.code,stdout:result.stdout,stderr:result.stderr,restoredRcFiles}}function cliVersionDefault(bskBin){return new Promise((resolve)=>{const child=spawn6(bskBin,["--version"],{stdio:["ignore","pipe","ignore"],windowsHide:true});let out="";child.stdout.on("data",(c)=>{out+=c});child.on("error",()=>resolve(null));child.on("exit",(code)=>resolve(code===0?out.trim():null))})}function isDaemonInfo(value){if(!value||typeof value!=="object"||!("sock_path"in value))return false;return typeof value.sock_path==="string"&&value.sock_path.length>0}function resolveBskHome(env=process.env){const override=env["BSK_HOME"];if(typeof override==="string"&&override.length>0)return override;const home=env["HOME"]&&env["HOME"].length>0?env["HOME"]:homedir4();return path19.join(home,".bsk")}function daemonInfoPath(home){return path19.join(home,"daemon.json")}function readDaemonInfo(home){let raw;try{raw=readFileSync5(daemonInfoPath(home),"utf8")}catch{return null}let info;try{info=JSON.parse(raw)}catch{return null}if(!isDaemonInfo(info))return null;return info}function findBskBinary(env=process.env){const home=env["HOME"]&&env["HOME"].length>0?env["HOME"]:homedir4();const candidates=[env["BSK_BIN"],path19.join(home,".local","bin",process.platform==="win32"?"bsk.exe":"bsk")].filter((candidate)=>Boolean(candidate));for(const candidate of candidates)if(existsSync5(candidate))return candidate;return"bsk"}var NO_BREAKAWAY=/Job Object/;function windowsDaemonTaskName(home){return`bsk-daemon-${createHash2("sha256").update(path19.resolve(home).toLowerCase()).digest("hex").slice(0,12)}`}var powershellLiteral=(value)=>`'${value.replace(/['\u2018\u2019\u201A\u201B]/g,(quote)=>quote+quote)}'`;function daemonEnv(env,home){return{...env,BSK_HOME:home,BSK_AUTO_UPDATE:env["BSK_AUTO_UPDATE"]??"off",BSK_UPDATE_MANIFEST_URL:env["BSK_UPDATE_MANIFEST_URL"]??BSK_PINNED_MANIFEST_URL}}function windowsDaemonLaunch(env,bskBin){const assignments=["BSK_HOME","BSK_AUTO_UPDATE","BSK_UPDATE_MANIFEST_URL"].map((name)=>`$env:${name} = ${powershellLiteral(env[name]??"")}; `).join("");const script=`${assignments}& ${powershellLiteral(bskBin)} daemon start --foreground; exit $LASTEXITCODE`;return`--headless "${windowsSystemTool("WindowsPowerShell\\v1.0\\powershell.exe")}" -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(script,"utf16le").toString("base64")}`}function startDaemonInWindowsTask({home,env,bskBin,timeoutMs}){const script=["$action = New-ScheduledTaskAction -Execute (Join-Path $env:SystemRoot 'System32\\conhost.exe') -Argument $env:BSK_TASK_ARGUMENT","$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew","Register-ScheduledTask -TaskName $env:BSK_TASK_NAME -Action $action -Settings $settings -Force | Out-Null","Start-ScheduledTask -TaskName $env:BSK_TASK_NAME"].join("; ");return runToExit(windowsSystemTool("WindowsPowerShell\\v1.0\\powershell.exe"),["-NoProfile","-NonInteractive","-Command",script],{env:{...process.env,BSK_TASK_NAME:windowsDaemonTaskName(home),BSK_TASK_ARGUMENT:windowsDaemonLaunch(env,bskBin)},timeoutMs,label:"registering the bsk daemon task"})}function runToExit(command,args,{env,timeoutMs,label}){return new Promise((resolve,reject)=>{const child=spawn7(command,args,{env,stdio:["ignore","pipe","pipe"],windowsHide:true});let output="";const keep=(chunk)=>{output=(output+chunk).slice(-4096)};child.stdout.on("data",keep);child.stderr.on("data",keep);const timer=setTimeout(()=>{child.kill("SIGKILL");reject(new Error(`${label} did not return within ${timeoutMs}ms`))},timeoutMs);child.on("error",(error)=>{clearTimeout(timer);reject(new Error(`could not run ${command}: ${error.message}`))});child.on("exit",(code)=>{clearTimeout(timer);resolve({code,output:output.trim()})})})}async function startDaemonWithCli({home,env=process.env,bskBin=findBskBinary(env),timeoutMs=20000}={}){const daemon=daemonEnv(env,home);const status=await runToExit(bskBin,["status","--json"],{env:daemon,timeoutMs,label:"bsk status"});if(status.code===0)return;if(process.platform==="win32"&&NO_BREAKAWAY.test(status.output)){if(home===undefined)throw new TypeError("startDaemonWithCli needs a home to register the Windows daemon task");const task=await startDaemonInWindowsTask({home,env:daemon,bskBin,timeoutMs});if(task.code===0)return;throw new Error(`${status.output}; registering the bsk daemon task exited with ${task.code}${task.output?`: ${task.output}`:""}`)}throw new Error(`bsk status exited with ${status.code}${status.output?`: ${status.output}`:""}`)}function optionalProperty(value,key){return value===null||value===undefined?undefined:readProperty(value,key)}function listOrEmpty(value,what){if(value===null||value===undefined)return[];if(!Array.isArray(value))throw new TypeError(`${what} is not a list`);const list=value;return list}var DEFAULT_TIMEOUT_MS2=35000;var DISCOVERY_RETRY_MS=250;var DISCOVERY_BUDGET_MS=15000;var TOOL_TIMEOUT_GRACE_MS=5000;var HUMAN_WAIT_METHODS=new Set(["tool.request_help","tool.tab_borrow"]);var HUMAN_WAIT_BACKSTOP_MS=3600000;function ownBudgetMs(params){const budgets=[optionalProperty(params,"timeout_ms"),optionalProperty(params,"confirmation_timeout_ms")].filter((value)=>typeof value==="number");return budgets.length>0?Math.max(...budgets)+TOOL_TIMEOUT_GRACE_MS:undefined}var PROBE_TIMEOUT_MS=2000;function defaultSocketPath(home,env=process.env){if(process.platform!=="win32")return path20.join(home,"run","daemon.sock");return`\\\\.\\pipe\\bsk-daemon-${rustStrHash(env["USERNAME"]??"default",home)}`}function rustStrHash(...values){const bytes=Buffer.concat(values.flatMap((value)=>[Buffer.from(value,"utf8"),Buffer.from([255])]));const mask=(1n<<64n)-1n;const rotl=(x,b)=>(x<<b|x>>64n-b)&mask;let[v0,v1,v2,v3]=[0x736f6d6570736575n,0x646f72616e646f6dn,0x6c7967656e657261n,0x7465646279746573n];const round=()=>{v0=v0+v1&mask;v1=rotl(v1,13n)^v0;v0=rotl(v0,32n);v2=v2+v3&mask;v3=rotl(v3,16n)^v2;v0=v0+v3&mask;v3=rotl(v3,21n)^v0;v2=v2+v1&mask;v1=rotl(v1,17n)^v2;v2=rotl(v2,32n)};const compress=(word)=>{v3^=word;round();v0^=word};const whole=bytes.length-bytes.length%8;for(let i=0;i<whole;i+=8)compress(bytes.readBigUInt64LE(i));let last=BigInt(bytes.length&255)<<56n;for(let i=whole;i<bytes.length;i+=1)last|=BigInt(bytes.readUInt8(i))<<BigInt(8*(i-whole));compress(last);v2^=0xffn;round();round();round();return((v0^v1^v2^v3)&mask).toString(16).padStart(16,"0")}function socketExists(sockPath){if(process.platform!=="win32")return existsSync6(sockPath);try{return readdirSync("\\\\.\\pipe\\").includes(path20.win32.basename(sockPath))}catch{return false}}function probeSocket(sockPath){if(!socketExists(sockPath))return Promise.resolve(false);return new Promise((resolve)=>{const socket=connect2(sockPath);const done=(alive)=>{clearTimeout(timer);socket.destroy();resolve(alive)};const timer=setTimeout(()=>done(false),PROBE_TIMEOUT_MS);socket.on("error",()=>done(false));socket.on("connect",()=>socket.write(JSON.stringify({id:"probe-orphan",method:"system.ping"})+`
|
|
1393
1393
|
`));socket.on("data",()=>done(true))})}class BskRpcError extends Error{constructor(code,message,data){super(message);this.name="BskRpcError";this.code=code;this.data=data}}var noop2=()=>{};function shortId(){return randomBytes(6).toString("hex")}function sleep4(ms){return new Promise((resolve)=>setTimeout(resolve,ms))}var NO_LISTENER=new Set(["ENOENT","ECONNREFUSED"]);function sameRecord(info,stale){return Boolean(stale)&&JSON.stringify(info)===JSON.stringify(stale?.info)}class BskIpcClient{#home;#env;#sockPath;#autoStart;#startDaemon;#timeoutMs;#starting=null;constructor({home,env=process.env,sockPath,autoStart,startDaemon,timeoutMs=DEFAULT_TIMEOUT_MS2,bskBin}={}){this.#home=home??resolveBskHome(env);this.#sockPath=sockPath??null;this.#autoStart=autoStart??env["BSK_AUTO_START"]!=="0";this.#startDaemon=startDaemon??(()=>startDaemonWithCli({home:this.#home,env,bskBin}));this.#timeoutMs=timeoutMs;this.#env=env}get home(){return this.#home}async resolveSocket({isAborted=()=>false,stale}={}){if(this.#sockPath)return this.#sockPath;const found=readDaemonInfo(this.#home);if(found&&!sameRecord(found,stale))return found.sock_path;const orphan=defaultSocketPath(this.#home,this.#env);if(socketExists(orphan)){if(await probeSocket(orphan))return orphan;if(isAborted())throw new BskRpcError("cancelled","cancelled before the daemon was located")}if(!this.#autoStart){if(stale){throw new BskRpcError("no_daemon",`${this.#home}/daemon.json names a BrowserSkill daemon at ${stale.info.sock_path} that is no longer listening (${stale.code}) and automatic start is disabled (BSK_AUTO_START=0); run \`bsk daemon start\` in the environment that owns it`)}throw new BskRpcError("no_daemon",`no BrowserSkill daemon published at ${this.#home}/daemon.json and automatic start is disabled (BSK_AUTO_START=0); run \`bsk daemon start\` in the environment that owns it`)}if(!this.#starting)this.#starting=this.#startDaemon().finally(()=>{this.#starting=null});await this.#starting;const deadline=Date.now()+DISCOVERY_BUDGET_MS;while(Date.now()<deadline&&!isAborted()){const info=readDaemonInfo(this.#home);if(info&&!sameRecord(info,stale))return info.sock_path;await sleep4(DISCOVERY_RETRY_MS)}if(isAborted())throw new BskRpcError("cancelled","cancelled while waiting for the daemon to publish daemon.json");throw new BskRpcError("no_daemon",`daemon start was requested but ${this.#home}/daemon.json never appeared`)}call(method,params,options={}){return this.callWithHandle(method,params,options).promise}callWithHandle(method,params,{idPrefix=method.replace(/[^a-z0-9]+/gi,"-"),timeoutMs}={}){const ownBudget=ownBudgetMs(params);const humanWait=HUMAN_WAIT_METHODS.has(method);const waitMs=humanWait&&ownBudget===undefined&&timeoutMs===undefined?HUMAN_WAIT_BACKSTOP_MS:Math.max(timeoutMs??this.#timeoutMs,ownBudget??0);const rpcId=`${idPrefix}-${shortId()}`;const frame={id:rpcId,method};if(params!==undefined)frame.params=params;let aborted=false;let abortSocket=noop2;const exchange=(sockPath,onNoListener)=>new Promise((resolve,reject)=>{const socket=connect2(sockPath);let buffer="";let settled=false;const finish=(fn,value)=>{if(settled)return;settled=true;clearTimeout(timer);socket.destroy();fn(value)};const timer=setTimeout(()=>{const cancels=method!=="cancel"&&!humanWait;finish(reject,new BskRpcError("timeout",`${method} did not answer within ${waitMs}ms${cancels?"; a cancel was requested at the daemon":""}`));if(cancels)this.cancel(rpcId).catch(()=>{})},waitMs);abortSocket=()=>finish(reject,new BskRpcError("cancelled",`${method} cancelled by caller`));socket.on("error",(error)=>{if(error.code!==undefined&&NO_LISTENER.has(error.code))onNoListener(error.code);finish(reject,new BskRpcError("no_daemon",`IPC socket ${sockPath}: ${error.code??error.message}`))});socket.setEncoding("utf8");socket.on("connect",()=>socket.write(JSON.stringify(frame)+`
|
|
1394
1394
|
`));socket.on("data",(chunk)=>{buffer+=chunk;const idx=buffer.indexOf(`
|
|
1395
|
-
`);if(idx===-1)return;try{finish(resolve,decodeResponse(buffer.slice(0,idx),rpcId,method))}catch(error){finish(reject,error)}});socket.on("close",()=>finish(reject,new BskRpcError("protocol_error",`${method}: daemon closed the connection without a reply`)))});const promise=(async()=>{let stale;for(;;){const sockPath=await this.resolveSocket({isAborted:()=>aborted,stale});if(aborted)throw new BskRpcError("cancelled",`${method} cancelled by caller`);let refused;try{return await exchange(sockPath,(code)=>{refused=code})}catch(error){const info=refused&&!stale&&!this.#sockPath?readDaemonInfo(this.#home):null;if(info?.sock_path!==sockPath)throw error;stale={info,code:refused}}}})();return{rpcId,promise,abort:()=>{aborted=true;abortSocket()}}}async cancel(rpcId){return this.call("cancel",{rpc_id:rpcId},{idPrefix:"cancel",timeoutMs:2000})}}function decodeResponse(line,rpcId,method){let reply;try{reply=JSON.parse(line)}catch{throw new BskRpcError("protocol_error",`${method}: daemon reply is not JSON: ${line.slice(0,120)}`)}const replyId=readProperty(reply,"id");const replyError=readProperty(reply,"error");const undecodableFrame=replyId==="0"&&replyError;if(replyId!==rpcId&&!undecodableFrame){throw new BskRpcError("protocol_error",`${method}: reply id ${replyId} does not match request ${rpcId}`)}if(replyError){const code=readProperty(replyError,"code");const message=readProperty(replyError,"message");throw new BskRpcError(code===undefined?"protocol_error":String(code),message===undefined?"daemon error":String(message),readProperty(replyError,"data"))}return readProperty(reply,"result")}var REF_SHAPE=/^@?e\d+$/;function resolveTarget(target){if(typeof target==="string"){return REF_SHAPE.test(target)?{ref:target}:{selector:target}}if(target&&typeof target==="object"){const spec=target;if(typeof spec.ref==="string")return{ref:spec.ref};if(typeof spec.selector==="string")return{selector:spec.selector};if(typeof spec.captureId==="string"){return{capture_id:spec.captureId,image_x:spec.x,image_y:spec.y}}}throw new TypeError("target must be a ref ('e3' / '@e3'), a CSS selector, or {captureId, x, y}")}function optionalTarget(target){return target===undefined?{}:resolveTarget(target)}function compact(params){const out={};for(const[key,value]of Object.entries(params))if(value!==undefined)out[key]=value;return out}function fromBase64(value,field){if(typeof value!=="string")throw new TypeError(`${field} is not base64 text`);return Buffer.from(value,"base64")}async function captureScreenshot(session,{ref,tabId,fullPage=false,scope,timeoutMs,context,dependsOn}={}){if(!fullPage){const result=await session.tool("screenshot",{ref,tab_id:tabId});return{buffer:fromBase64(readProperty(result,"image_base64"),"image_base64"),width:readProperty(result,"width"),height:readProperty(result,"height"),format:readProperty(result,"format"),captureId:readProperty(result,"capture_id")??null,captureUnavailable:readProperty(result,"capture_unavailable")??null,tabId:readProperty(result,"tab_id"),dialogs:readProperty(result,"dialogs")??[]}}const started=await session.tool("screenshot_full_page",{scope,tab_id:tabId,timeout_ms:timeoutMs,context_id:context,depends_on:dependsOn});const buffer=await readCapture(session,readProperty(started,"capture_id"),readProperty(started,"byte_size"));return{buffer,width:readProperty(started,"width"),height:readProperty(started,"height"),format:readProperty(started,"format"),captureId:readProperty(started,"capture_id"),scope:readProperty(started,"scope")??scope??null,tabId:readProperty(started,"tab_id"),dialogs:readProperty(started,"dialogs")??[]}}async function readCapture(session,captureId,byteSize){const chunks=[];let offset=0;try{for(;;){const chunk=await session.tool("screenshot_read",{capture_id:captureId,offset});const bytes=fromBase64(readProperty(chunk,"data_base64")??"","data_base64");chunks.push(bytes);if(readProperty(chunk,"eof")||bytes.length===0)break;const nextOffset=readProperty(chunk,"next_offset");if(typeof nextOffset!=="number"||nextOffset<=offset)throw new Error(`screenshot_read did not advance past offset ${offset}`);offset=nextOffset}}finally{await session.tool("screenshot_release",{capture_id:captureId}).catch(()=>{})}const buffer=Buffer.concat(chunks);if(typeof byteSize==="number"&&buffer.length!==byteSize){throw new Error(`screenshot capture ${captureId}: expected ${byteSize} bytes, assembled ${buffer.length}`)}return buffer}var SESSION_STOP_TIMEOUT_MS=3600000;function sharedTab({context,dependsOn,...unknown}){const extra=Object.keys(unknown);if(extra.length>0){throw new TypeError(`unknown option ${extra.map((key)=>JSON.stringify(key)).join(", ")}: a shared-tab action takes { context, dependsOn } besides its own options`)}return{context_id:context,depends_on:dependsOn}}class BskSession{#client;#stopped=false;constructor(client,{sessionId,browserInstanceId=null,agentWindowId=null,interaction=null}={}){if(typeof sessionId!=="string"||sessionId.length===0)throw new TypeError("BskSession requires a sessionId");this.#client=client;this.sessionId=sessionId;this.browserInstanceId=browserInstanceId;this.agentWindowId=agentWindowId;this.interaction=interaction}get client(){return this.#client}get stopped(){return this.#stopped}tool(name,params={}){if(this.#stopped)return Promise.reject(new Error(`BrowserSkill session ${this.sessionId} is stopped`));return this.#client.call(`tool.${name}`,compact({session_id:this.sessionId,...params}),{idPrefix:name.replace(/_/g,"-")})}cooperate(action,{tabId,timeoutMs,maxTokens}={}){return this.tool("cooperate",{action,tab_id:tabId,timeout_ms:timeoutMs,max_tokens:maxTokens})}navigate(url,{tabId,waitUntil,timeoutMs,...shared}={}){return this.tool("navigate",{url,tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs,...sharedTab(shared)})}back({tabId,waitUntil,timeoutMs,...shared}={}){return this.tool("navigate_back",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs,...sharedTab(shared)})}forward({tabId,waitUntil,timeoutMs,...shared}={}){return this.tool("navigate_forward",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs,...sharedTab(shared)})}reload({tabId,waitUntil,timeoutMs,hard,...shared}={}){return this.tool("reload",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs,hard,...sharedTab(shared)})}observe({cursor,tabId,maxDepth,maxTokens,debugSurfaces,probeHover,...shared}={}){return this.tool("observe",{cursor,tab_id:tabId,max_depth:maxDepth,max_tokens:maxTokens,debug_surfaces:debugSurfaces,probe_hover:probeHover,...sharedTab(shared)})}snapshot({tabId,maxDepth,maxTokens}={}){return this.tool("snapshot",{tab_id:tabId,max_depth:maxDepth,max_tokens:maxTokens})}getHtml({ref,tabId,maxBytes}={}){return this.tool("get_html",{ref,tab_id:tabId,max_bytes:maxBytes})}screenshot(options){return captureScreenshot(this,options)}click(target,{button,clickCount,modifiers,tabId,timeoutMs,...shared}={}){return this.tool("click",{...resolveTarget(target),button,click_count:clickCount,modifiers,tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}hover(target,{modifiers,settleMs,tabId,timeoutMs,...shared}={}){return this.tool("hover",{...resolveTarget(target),modifiers,settle_ms:settleMs,tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}focus(target,{tabId,timeoutMs,...shared}={}){return this.tool("focus",{...resolveTarget(target),tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}blur(target,{tabId,timeoutMs,...shared}={}){return this.tool("blur",{...resolveTarget(target),tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}fill(target,value,{clearBefore,tabId,timeoutMs,...shared}={}){return this.tool("fill",{...resolveTarget(target),value,clear_before:clearBefore,tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}press(key,{target,modifiers,holdMs,tabId,timeoutMs,...shared}={}){return this.tool("press",{key,...optionalTarget(target),modifiers,hold_ms:holdMs,tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}select(target,values,{tabId,timeoutMs,...shared}={}){return this.tool("select",{...resolveTarget(target),values:Array.isArray(values)?values:[values],tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}scrollTo(target,{tabId,timeoutMs,...shared}={}){return this.tool("scroll_to",{...resolveTarget(target),tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}wheel({deltaX=0,deltaY=0,target,modifiers,tabId,timeoutMs,...shared}={}){return this.tool("wheel",{...optionalTarget(target),delta_x:deltaX,delta_y:deltaY,modifiers,tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}evaluate(expression,{tabId,awaitPromise,returnByValue,timeoutMs,...shared}={}){return this.tool("evaluate",{expression,tab_id:tabId,await_promise:awaitPromise,return_by_value:returnByValue,timeout_ms:timeoutMs,...sharedTab(shared)})}tabList({scope}={}){return this.tool("tab_list",{scope})}tabCreate({url,active,index}={}){return this.tool("tab_create",{url,active,index})}tabClose(tabId,shared={}){return this.tool("tab_close",{tab_id:tabId,...sharedTab(shared)})}tabSelect(tabId){return this.tool("tab_select",{tab_id:tabId})}tabBorrow(tabId,{confirmationTimeoutMs}={}){return this.tool("tab_borrow",{tab_id:tabId,confirmation_timeout_ms:confirmationTimeoutMs})}tabReturn(tabId){return this.tool("tab_return",{tab_id:tabId})}waitForNavigation({tabId,waitUntil,timeoutMs}={}){return this.tool("wait_for_navigation",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs})}requestHelp({prompt,title,targets,completionCriteria,tabId,timeoutMs}={}){return this.tool("request_help",{prompt,title,tab_id:tabId,timeout_ms:timeoutMs,targets:targets?.map((t)=>resolveTarget(t)),completion_criteria:completionCriteria})}console({tabId,since,limit,maxTextChars,includeStack}={}){return this.tool("console",{tab_id:tabId,since,limit,max_text_chars:maxTextChars,include_stack:includeStack})}network({tabId,since,limit,maxTextChars}={}){return this.tool("network",{tab_id:tabId,since,limit,max_text_chars:maxTextChars})}resize(width,height,shared={}){return this.tool("window_resize",{width,height,...sharedTab(shared)})}emulate({tabId,off,overrides,...shared}={}){return this.tool("emulate",{tab_id:tabId,off,overrides,...sharedTab(shared)})}async stop(){if(this.#stopped)return null;this.#stopped=true;return this.#client.call("session.stop",{session_id:this.sessionId},{idPrefix:"session-stop",timeoutMs:SESSION_STOP_TIMEOUT_MS})}}var DEFAULT_WAIT_FOR_BROWSER_MS=15000;var TAB_GROUPING_EXTENSION_VERSIONS=new Set(["0.4.0"]);function isTabGroupingExtension(browser){return TAB_GROUPING_EXTENSION_VERSIONS.has(optionalProperty(browser,"extension_version"))}var TAB_GROUPING_EXTENSION_STEP=`Update the BrowserSkill extension to 0.4.1 or later (chrome://extensions -> Developer mode -> Update, or wait for the store update). Version 0.4.0 puts each task's tabs into a "BrowserSkill" tab group that the browser saves and syncs, so the group stays after the task ends; delete any saved "BrowserSkill" tab groups by hand.`;function outdatedError(browser){return new BskRpcError("extension_outdated",`the BrowserSkill extension in ${readProperty(browser,"browser_name")??"the browser"} [${readProperty(browser,"instance_id")}] is 0.4.0, which leaves a "BrowserSkill" tab group behind in the user's browser after each task. ${TAB_GROUPING_EXTENSION_STEP}`)}function namesBrowser(b,browser){return readProperty(b,"instance_id")===browser||Boolean(readProperty(b,"label")&&readProperty(b,"label")===browser)}function chooseBrowser(browser,browsers){const resolved=resolveBrowser(browser,browsers);if(resolved!==undefined&&resolved!==null){const entry=browsers.find((b)=>namesBrowser(b,resolved));if(entry&&isTabGroupingExtension(entry))throw outdatedError(entry);return resolved}const outdated=browsers.filter(isTabGroupingExtension);if(outdated.length===0)return resolved;const usable=browsers.find((b)=>!isTabGroupingExtension(b));if(!usable)throw outdatedError(outdated[0]);return readProperty(usable,"instance_id")}async function listBrowsers(client,{waitForBrowserMs}={}){const status=await client.call("system.status",compact({wait_for_browser_ms:waitForBrowserMs}),{idPrefix:"status"});return listOrEmpty(readProperty(status,"browsers"),"system.status browsers")}function resolveBrowser(browser,browsers){if(browser===undefined||browser===null)return browser;if(browsers.some((b)=>namesBrowser(b,browser)))return browser;const named=browsers.filter((b)=>readProperty(b,"browser_name")===browser);if(named.length>1){throw new BskRpcError("invalid_params",`browser "${browser}" matches ${named.length} connected browsers (${named.map((b)=>readProperty(b,"instance_id")).join(", ")}); pass the instance id instead`)}return named.length===1?readProperty(named[0],"instance_id"):browser}function describeBrowser(b){const name=optionalProperty(b,"browser_name");const label=optionalProperty(b,"label");const parts=[`${String(label||name||"browser")} [${String(optionalProperty(b,"instance_id"))}]`,[name,optionalProperty(b,"browser_version")].filter(Boolean).join(" ")];const sessions=optionalProperty(b,"session_count");if(typeof sessions==="number")parts.push(`${sessions} session${sessions===1?"":"s"}`);const since=optionalProperty(b,"connected_at_ms");if(typeof since==="number"&&Number.isFinite(since)&&Math.abs(since)<=8640000000000000){parts.push(`online since ${new Date(since).toISOString()}`)}return parts.filter(Boolean).join(", ")}function multipleBrowsersError(error,statusBrowsers){const listed=optionalProperty(error.data,"browsers");const browsers=Array.isArray(listed)?listed:statusBrowsers;const data=error.data;const extra=typeof data==="object"&&data!==null?data:{};return new BskRpcError(error.code,`more than one browser is online; pass browser: "<instance_id or label>" to connectBrowserSkill(). Online: ${browsers.map(describeBrowser).join("; ")}. Tabs are only visible inside a session: ask the user which browser holds the page, or open a session per browser and read tabList({ scope: "user" }) before stopping it.`,{...extra,browsers})}async function connectBrowserSkill({client,home,env,sockPath,autoStart,timeoutMs,bskBin,name,browser,width,height,focused=false,waitForBrowserMs=DEFAULT_WAIT_FOR_BROWSER_MS}={}){const ipc=client??new BskIpcClient({home,env,sockPath,autoStart,timeoutMs,bskBin});const browsers=await listBrowsers(ipc,{waitForBrowserMs});if(browsers.length===0){throw new BskRpcError("no_browser_connected","the BrowserSkill daemon is up but no browser extension is connected; open the browser that has the BrowserSkill extension enabled (bskDoctor() explains the remaining step); never substitute another browser for the user's without telling them")}const browserInstanceId=chooseBrowser(browser,browsers);let started;try{started=await ipc.call("session.start",compact({task_name:name,browser_instance_id:browserInstanceId,width,height,focused}),{idPrefix:"session-start"})}catch(error){if(error instanceof BskRpcError&&error.code==="multiple_browsers_online"){throw multipleBrowsersError(error,browsers)}throw error}return new BskSession(ipc,{sessionId:readProperty(started,"session_id"),browserInstanceId:readProperty(started,"browser_instance_id")??null,agentWindowId:readProperty(started,"agent_window_id")??null,interaction:readProperty(started,"interaction")??null})}var CSS_PATH_FN=String(function cssPath(el){if(!(el instanceof Element))return null;if(el.getRootNode()!==document)return null;const parts=[];let node=el;while(node&&node.nodeType===1&&node!==document.documentElement){let part=node.localName;if(node.id&&/^[A-Za-z_][\w-]*$/.test(node.id)&&document.querySelectorAll("#"+node.id).length===1){parts.unshift("#"+node.id);return parts.join(" > ")}const parent=node.parentElement;if(parent){const same=Array.from(parent.children).filter((c)=>c.localName===part);if(same.length>1)part+=`:nth-of-type(${same.indexOf(node)+1})`}parts.unshift(part);node=parent}parts.unshift("html");return parts.join(" > ")});function buildSnapshotExpression(options={}){return`(function () {
|
|
1395
|
+
`);if(idx===-1)return;try{finish(resolve,decodeResponse(buffer.slice(0,idx),rpcId,method))}catch(error){finish(reject,error)}});socket.on("close",()=>finish(reject,new BskRpcError("protocol_error",`${method}: daemon closed the connection without a reply`)))});const promise=(async()=>{let stale;for(;;){const sockPath=await this.resolveSocket({isAborted:()=>aborted,stale});if(aborted)throw new BskRpcError("cancelled",`${method} cancelled by caller`);let refused;try{return await exchange(sockPath,(code)=>{refused=code})}catch(error){const info=refused&&!stale&&!this.#sockPath?readDaemonInfo(this.#home):null;if(info?.sock_path!==sockPath)throw error;stale={info,code:refused}}}})();return{rpcId,promise,abort:()=>{aborted=true;abortSocket()}}}async cancel(rpcId){return this.call("cancel",{rpc_id:rpcId},{idPrefix:"cancel",timeoutMs:2000})}}function decodeResponse(line,rpcId,method){let reply;try{reply=JSON.parse(line)}catch{throw new BskRpcError("protocol_error",`${method}: daemon reply is not JSON: ${line.slice(0,120)}`)}const replyId=readProperty(reply,"id");const replyError=readProperty(reply,"error");const undecodableFrame=replyId==="0"&&replyError;if(replyId!==rpcId&&!undecodableFrame){throw new BskRpcError("protocol_error",`${method}: reply id ${replyId} does not match request ${rpcId}`)}if(replyError){const code=readProperty(replyError,"code");const message=readProperty(replyError,"message");throw new BskRpcError(code===undefined?"protocol_error":String(code),message===undefined?"daemon error":String(message),readProperty(replyError,"data"))}return readProperty(reply,"result")}var REF_SHAPE=/^@?e\d+$/;function resolveTarget(target){if(typeof target==="string"){return REF_SHAPE.test(target)?{ref:target}:{selector:target}}if(target&&typeof target==="object"){const spec=target;if(typeof spec.ref==="string")return{ref:spec.ref};if(typeof spec.selector==="string")return{selector:spec.selector};if(typeof spec.captureId==="string"){return{capture_id:spec.captureId,image_x:spec.x,image_y:spec.y}}}throw new TypeError("target must be a ref ('e3' / '@e3'), a CSS selector, or {captureId, x, y}")}function optionalTarget(target){return target===undefined?{}:resolveTarget(target)}function compact(params){const out={};for(const[key,value]of Object.entries(params))if(value!==undefined)out[key]=value;return out}function fromBase64(value,field){if(typeof value!=="string")throw new TypeError(`${field} is not base64 text`);return Buffer.from(value,"base64")}async function captureScreenshot(session,{ref,tabId,fullPage=false,scope,timeoutMs,context,dependsOn}={}){if(!fullPage){const result=await session.tool("screenshot",{ref,tab_id:tabId});return{buffer:fromBase64(readProperty(result,"image_base64"),"image_base64"),width:readProperty(result,"width"),height:readProperty(result,"height"),format:readProperty(result,"format"),captureId:readProperty(result,"capture_id")??null,captureUnavailable:readProperty(result,"capture_unavailable")??null,tabId:readProperty(result,"tab_id"),dialogs:readProperty(result,"dialogs")??[]}}const started=await session.tool("screenshot_full_page",{scope,tab_id:tabId,timeout_ms:timeoutMs,context_id:context,depends_on:dependsOn});const buffer=await readCapture(session,readProperty(started,"capture_id"),readProperty(started,"byte_size"));return{buffer,width:readProperty(started,"width"),height:readProperty(started,"height"),format:readProperty(started,"format"),captureId:readProperty(started,"capture_id"),scope:readProperty(started,"scope")??scope??null,tabId:readProperty(started,"tab_id"),dialogs:readProperty(started,"dialogs")??[]}}async function readCapture(session,captureId,byteSize){const chunks=[];let offset=0;try{for(;;){const chunk=await session.tool("screenshot_read",{capture_id:captureId,offset});const bytes=fromBase64(readProperty(chunk,"data_base64")??"","data_base64");chunks.push(bytes);if(readProperty(chunk,"eof")||bytes.length===0)break;const nextOffset=readProperty(chunk,"next_offset");if(typeof nextOffset!=="number"||nextOffset<=offset)throw new Error(`screenshot_read did not advance past offset ${offset}`);offset=nextOffset}}finally{await session.tool("screenshot_release",{capture_id:captureId}).catch(()=>{})}const buffer=Buffer.concat(chunks);if(typeof byteSize==="number"&&buffer.length!==byteSize){throw new Error(`screenshot capture ${captureId}: expected ${byteSize} bytes, assembled ${buffer.length}`)}return buffer}var SESSION_STOP_TIMEOUT_MS=3600000;function sharedTab({context,dependsOn,...unknown}){const extra=Object.keys(unknown);if(extra.length>0){throw new TypeError(`unknown option ${extra.map((key)=>JSON.stringify(key)).join(", ")}: a shared-tab action takes { context, dependsOn } besides its own options`)}return{context_id:context,depends_on:dependsOn}}class BskSession{#client;#stopped=false;constructor(client,{sessionId,browserInstanceId=null,agentWindowId=null,interaction=null}={}){if(typeof sessionId!=="string"||sessionId.length===0)throw new TypeError("BskSession requires a sessionId");this.#client=client;this.sessionId=sessionId;this.browserInstanceId=browserInstanceId;this.agentWindowId=agentWindowId;this.interaction=interaction}get client(){return this.#client}get stopped(){return this.#stopped}tool(name,params={}){if(this.#stopped)return Promise.reject(new Error(`BrowserSkill session ${this.sessionId} is stopped`));return this.#client.call(`tool.${name}`,compact({session_id:this.sessionId,...params}),{idPrefix:name.replace(/_/g,"-")})}cooperate(action,{tabId,timeoutMs,maxTokens}={}){return this.tool("cooperate",{action,tab_id:tabId,timeout_ms:timeoutMs,max_tokens:maxTokens})}navigate(url,{tabId,waitUntil,timeoutMs,...shared}={}){return this.tool("navigate",{url,tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs,...sharedTab(shared)})}back({tabId,waitUntil,timeoutMs,...shared}={}){return this.tool("navigate_back",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs,...sharedTab(shared)})}forward({tabId,waitUntil,timeoutMs,...shared}={}){return this.tool("navigate_forward",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs,...sharedTab(shared)})}reload({tabId,waitUntil,timeoutMs,hard,...shared}={}){return this.tool("reload",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs,hard,...sharedTab(shared)})}observe({cursor,tabId,maxDepth,maxTokens,debugSurfaces,probeHover,...shared}={}){return this.tool("observe",{cursor,tab_id:tabId,max_depth:maxDepth,max_tokens:maxTokens,debug_surfaces:debugSurfaces,probe_hover:probeHover,...sharedTab(shared)})}snapshot({tabId,maxDepth,maxTokens}={}){return this.tool("snapshot",{tab_id:tabId,max_depth:maxDepth,max_tokens:maxTokens})}getHtml({ref,tabId,maxBytes}={}){return this.tool("get_html",{ref,tab_id:tabId,max_bytes:maxBytes})}screenshot(options){return captureScreenshot(this,options)}click(target,{button,clickCount,modifiers,tabId,timeoutMs,...shared}={}){return this.tool("click",{...resolveTarget(target),button,click_count:clickCount,modifiers,tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}hover(target,{modifiers,settleMs,tabId,timeoutMs,...shared}={}){return this.tool("hover",{...resolveTarget(target),modifiers,settle_ms:settleMs,tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}focus(target,{tabId,timeoutMs,...shared}={}){return this.tool("focus",{...resolveTarget(target),tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}blur(target,{tabId,timeoutMs,...shared}={}){return this.tool("blur",{...resolveTarget(target),tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}fill(target,value,{clearBefore,tabId,timeoutMs,...shared}={}){return this.tool("fill",{...resolveTarget(target),value,clear_before:clearBefore,tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}press(key,{target,modifiers,holdMs,tabId,timeoutMs,...shared}={}){return this.tool("press",{key,...optionalTarget(target),modifiers,hold_ms:holdMs,tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}select(target,values,{tabId,timeoutMs,...shared}={}){return this.tool("select",{...resolveTarget(target),values:Array.isArray(values)?values:[values],tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}scrollTo(target,{tabId,timeoutMs,...shared}={}){return this.tool("scroll_to",{...resolveTarget(target),tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}wheel({deltaX=0,deltaY=0,target,modifiers,tabId,timeoutMs,...shared}={}){return this.tool("wheel",{...optionalTarget(target),delta_x:deltaX,delta_y:deltaY,modifiers,tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}evaluate(expression,{tabId,awaitPromise,returnByValue,timeoutMs,...shared}={}){return this.tool("evaluate",{expression,tab_id:tabId,await_promise:awaitPromise,return_by_value:returnByValue,timeout_ms:timeoutMs,...sharedTab(shared)})}tabList({scope}={}){return this.tool("tab_list",{scope})}tabCreate({url,active,index}={}){return this.tool("tab_create",{url,active,index})}tabClose(tabId,shared={}){return this.tool("tab_close",{tab_id:tabId,...sharedTab(shared)})}tabSelect(tabId){return this.tool("tab_select",{tab_id:tabId})}tabBorrow(tabId,{confirmationTimeoutMs}={}){return this.tool("tab_borrow",{tab_id:tabId,confirmation_timeout_ms:confirmationTimeoutMs})}tabReturn(tabId){return this.tool("tab_return",{tab_id:tabId})}waitForNavigation({tabId,waitUntil,timeoutMs}={}){return this.tool("wait_for_navigation",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs})}requestHelp({prompt,title,targets,completionCriteria,tabId,timeoutMs}={}){return this.tool("request_help",{prompt,title,tab_id:tabId,timeout_ms:timeoutMs,targets:targets?.map((t)=>resolveTarget(t)),completion_criteria:completionCriteria})}console({tabId,since,limit,maxTextChars,includeStack}={}){return this.tool("console",{tab_id:tabId,since,limit,max_text_chars:maxTextChars,include_stack:includeStack})}network({tabId,since,limit,maxTextChars}={}){return this.tool("network",{tab_id:tabId,since,limit,max_text_chars:maxTextChars})}resize(width,height,shared={}){return this.tool("window_resize",{width,height,...sharedTab(shared)})}emulate({tabId,off,overrides,...shared}={}){return this.tool("emulate",{tab_id:tabId,off,overrides,...sharedTab(shared)})}async stop(){if(this.#stopped)return null;this.#stopped=true;return this.#client.call("session.stop",{session_id:this.sessionId},{idPrefix:"session-stop",timeoutMs:SESSION_STOP_TIMEOUT_MS})}}var DEFAULT_WAIT_FOR_BROWSER_MS=15000;var TAB_GROUPING_EXTENSION_VERSIONS=new Set(["0.4.0"]);function isTabGroupingExtension(browser){return TAB_GROUPING_EXTENSION_VERSIONS.has(optionalProperty(browser,"extension_version"))}var TAB_GROUPING_EXTENSION_STEP=`Update the BrowserSkill extension to 0.4.1 or later (chrome://extensions -> Developer mode -> Update, or wait for the store update). Version 0.4.0 puts each task's tabs into a "BrowserSkill" tab group that the browser saves and syncs, so the group stays after the task ends; delete any saved "BrowserSkill" tab groups by hand.`;function outdatedError(browser){return new BskRpcError("extension_outdated",`the BrowserSkill extension in ${textField(browser,"browser_name")??"the browser"} [${textField(browser,"instance_id")??"unknown id"}] is 0.4.0, which leaves a "BrowserSkill" tab group behind in the user's browser after each task. ${TAB_GROUPING_EXTENSION_STEP}`)}function namesBrowser(b,browser){return readProperty(b,"instance_id")===browser||Boolean(readProperty(b,"label")&&readProperty(b,"label")===browser)}function chooseBrowser(browser,browsers){const resolved=resolveBrowser(browser,browsers);if(resolved!==undefined&&resolved!==null){const entry=browsers.find((b)=>namesBrowser(b,resolved));if(entry&&isTabGroupingExtension(entry))throw outdatedError(entry);return resolved}const outdated=browsers.filter(isTabGroupingExtension);if(outdated.length===0)return resolved;const usable=browsers.find((b)=>!isTabGroupingExtension(b));if(!usable)throw outdatedError(outdated[0]);return readProperty(usable,"instance_id")}async function listBrowsers(client,{waitForBrowserMs}={}){const status=await client.call("system.status",compact({wait_for_browser_ms:waitForBrowserMs}),{idPrefix:"status"});return listOrEmpty(readProperty(status,"browsers"),"system.status browsers")}function resolveBrowser(browser,browsers){if(browser===undefined||browser===null)return browser;if(browsers.some((b)=>namesBrowser(b,browser)))return browser;const named=browsers.filter((b)=>readProperty(b,"browser_name")===browser);if(named.length>1){throw new BskRpcError("invalid_params",`browser "${browser}" matches ${named.length} connected browsers (${named.map((b)=>textField(b,"instance_id")??"unknown id").join(", ")}); pass the instance id instead`)}return named.length===1?readProperty(named[0],"instance_id"):browser}function textField(b,key){const value=optionalProperty(b,key);if(typeof value==="string")return value;if(typeof value==="number"&&Number.isFinite(value))return String(value);return}function describeBrowser(b){const name=textField(b,"browser_name");const parts=[`${textField(b,"label")||name||"browser"} [${textField(b,"instance_id")??"unknown id"}]`,[name,textField(b,"browser_version")].filter(Boolean).join(" ")];const sessions=optionalProperty(b,"session_count");if(typeof sessions==="number"&&Number.isFinite(sessions))parts.push(`${sessions} session${sessions===1?"":"s"}`);const since=optionalProperty(b,"connected_at_ms");if(typeof since==="number"&&Number.isFinite(since)&&Math.abs(since)<=8640000000000000){parts.push(`online since ${new Date(since).toISOString()}`)}return parts.filter(Boolean).join(", ")}function multipleBrowsersError(error,statusBrowsers){const listed=optionalProperty(error.data,"browsers");const browsers=Array.isArray(listed)?listed:statusBrowsers;const data=error.data;const extra=typeof data==="object"&&data!==null?data:{};return new BskRpcError(error.code,`more than one browser is online; pass browser: "<instance_id or label>" to connectBrowserSkill(). Online: ${browsers.map(describeBrowser).join("; ")}. Tabs are only visible inside a session: ask the user which browser holds the page, or open a session per browser and read tabList({ scope: "user" }) before stopping it.`,{...extra,browsers})}async function connectBrowserSkill({client,home,env,sockPath,autoStart,timeoutMs,bskBin,name,browser,width,height,focused=false,waitForBrowserMs=DEFAULT_WAIT_FOR_BROWSER_MS}={}){const ipc=client??new BskIpcClient({home,env,sockPath,autoStart,timeoutMs,bskBin});const browsers=await listBrowsers(ipc,{waitForBrowserMs});if(browsers.length===0){throw new BskRpcError("no_browser_connected","the BrowserSkill daemon is up but no browser extension is connected; open the browser that has the BrowserSkill extension enabled (bskDoctor() explains the remaining step); never substitute another browser for the user's without telling them")}const browserInstanceId=chooseBrowser(browser,browsers);let started;try{started=await ipc.call("session.start",compact({task_name:name,browser_instance_id:browserInstanceId,width,height,focused}),{idPrefix:"session-start"})}catch(error){if(error instanceof BskRpcError&&error.code==="multiple_browsers_online"){throw multipleBrowsersError(error,browsers)}throw error}return new BskSession(ipc,{sessionId:readProperty(started,"session_id"),browserInstanceId:readProperty(started,"browser_instance_id")??null,agentWindowId:readProperty(started,"agent_window_id")??null,interaction:readProperty(started,"interaction")??null})}var CSS_PATH_FN=String(function cssPath(el){if(!(el instanceof Element))return null;if(el.getRootNode()!==document)return null;const parts=[];let node=el;while(node&&node.nodeType===1&&node!==document.documentElement){let part=node.localName;if(node.id&&/^[A-Za-z_][\w-]*$/.test(node.id)&&document.querySelectorAll("#"+node.id).length===1){parts.unshift("#"+node.id);return parts.join(" > ")}const parent=node.parentElement;if(parent){const same=Array.from(parent.children).filter((c)=>c.localName===part);if(same.length>1)part+=`:nth-of-type(${same.indexOf(node)+1})`}parts.unshift(part);node=parent}parts.unshift("html");return parts.join(" > ")});function buildSnapshotExpression(options={}){return`(function () {
|
|
1396
1396
|
const globalThis = {};
|
|
1397
1397
|
${pageBundle}
|
|
1398
1398
|
const api = globalThis.__omowright;
|
|
@@ -1408,7 +1408,7 @@ ${snapshot.tree}`}}var DEFAULT_TIMEOUT_MS=30000;var JSON_MIME=/^application\/jso
|
|
|
1408
1408
|
`))!==-1){let line=plain(this.#buffer.slice(0,newline)).replace(/\r$/,"");this.#buffer=this.#buffer.slice(newline+1);while(line.startsWith(PROMPT))line=line.slice(PROMPT.length);this.#lines.push(line)}this.#check()}#waitFor(isDone,timeoutMs,timeoutCode){return new Promise((resolve,reject)=>{const timer=setTimeout(()=>{this.#waiter=null;const output=this.#lines.splice(0);reject(new AsideReplError(timeoutCode,`aside repl did not answer within ${timeoutMs} ms`,{output}));this.#terminate()},timeoutMs);this.#waiter={isDone,resolve,reject,timer};this.#check()})}#check(){const waiter=this.#waiter;if(!waiter||!waiter.isDone(plain(this.#buffer),this.#lines))return;this.#waiter=null;clearTimeout(waiter.timer);this.#buffer="";waiter.resolve(this.#lines.splice(0))}#settle(error){const waiter=this.#waiter;if(!waiter)return;this.#waiter=null;clearTimeout(waiter.timer);waiter.reject(error)}}var PROTOCOL_VERSION="2025-06-18";var CLOSE_TIMEOUT_MS2=5000;var KILL_GRACE_MS2=2000;var STDERR_LINES=50;var optional2=(value,key)=>value===null||value===undefined?undefined:readProperty(value,key);var textLines=(part)=>{const text=optional2(part,"text");if(optional2(part,"type")!=="text"||typeof text!=="string"||!text)return[];return text.replace(/\r?\n$/,"").split(/\r?\n/)};class McpTransport{#child;#buffer="";#nextId=1;#pending=new Map;#stderr=[];#closed=false;#exited=false;#terminated=false;#exit;constructor(child){this.#child=child;this.#exit=new Promise((resolve)=>child.once("exit",(code,signal)=>{this.#closed=true;this.#exited=true;const error=new AsideReplError("repl_closed",`aside mcp exited (code ${code}, signal ${signal})`,{output:this.#stderr.splice(0)});for(const{reject,timer}of this.#pending.values()){clearTimeout(timer);reject(error)}this.#pending.clear();resolve()}));child.stdin.on?.("error",()=>{});child.stdout.setEncoding("utf8");child.stdout.on("data",(chunk)=>this.#onData(chunk));child.stderr?.setEncoding("utf8");child.stderr?.on("data",(chunk)=>{this.#stderr.push(...chunk.split(/\r?\n/).filter(Boolean));this.#stderr.splice(0,Math.max(0,this.#stderr.length-STDERR_LINES))})}async ready(timeoutMs){const init=await this.#request("initialize",{protocolVersion:PROTOCOL_VERSION,capabilities:{},clientInfo:{name:"omowright",version:"1"}},timeoutMs,"repl_start_timeout");this.#send({method:"notifications/initialized"});const version=String(optional2(optional2(init,"serverInfo"),"version")??"of unknown version");const listed=await this.#request("tools/list",{},timeoutMs,"repl_start_timeout");const tools=optional2(listed,"tools")??[];if(!Array.isArray(tools)||!tools.some((tool)=>optional2(tool,"name")==="repl")){throw new AsideReplError("repl_unsupported_cli",`Aside CLI ${version} runs a piped \`aside repl\` as one script at EOF and its \`aside mcp\` has no repl tool, so omowright cannot keep a REPL session with it; update the Aside CLI (\`aside --update\`)`)}try{await this.call("void 0",{timeoutMs,timeoutCode:"repl_start_timeout"})}catch(error){if(!(error instanceof AsideReplError)||error.code!=="repl_error")throw error;throw new AsideReplError("repl_start_failed",`aside mcp could not start a REPL session: ${error.message}`,{output:error.output})}return{version}}async call(code,{timeoutMs,timeoutCode="repl_timeout"}){const result=await this.#request("tools/call",{name:"repl",arguments:{title:"omowright",code}},timeoutMs,timeoutCode);const content=optional2(result,"content")??[];const output=Array.isArray(content)?content.flatMap((part)=>textLines(part)):[];if(optional2(result,"isError")){throw new AsideReplError("repl_error",output.join(`
|
|
1409
1409
|
`)||"aside repl reported an error",{output})}return output}async close(){this.#closed=true;if(this.#exited)return;if(!this.#terminated){this.#child.stdin.end();if(await this.#exitsWithin(CLOSE_TIMEOUT_MS2))return;this.#terminate()}if(await this.#exitsWithin(KILL_GRACE_MS2))return;this.#child.kill("SIGKILL");await this.#exit}async#exitsWithin(ms){let timer;const timedOut=new Promise((resolve)=>{timer=setTimeout(()=>resolve(false),ms)});const exited=await Promise.race([this.#exit.then(()=>true),timedOut]);clearTimeout(timer);return exited}#terminate(){this.#terminated=true;this.#child.stdin.end();this.#child.kill()}#send(message){this.#child.stdin.write(`${JSON.stringify({jsonrpc:"2.0",...message})}
|
|
1410
1410
|
`)}#request(method,params,timeoutMs,timeoutCode){if(this.#closed)return Promise.reject(new AsideReplError("repl_closed","aside repl session is closed"));const id=this.#nextId++;return new Promise((resolve,reject)=>{const timer=setTimeout(()=>{this.#pending.delete(id);this.#closed=true;this.#terminate();reject(new AsideReplError(timeoutCode,`aside mcp did not answer ${method} within ${timeoutMs} ms`,{output:this.#stderr.splice(0)}))},timeoutMs);this.#pending.set(id,{resolve,reject,timer,method});this.#send({id,method,params})})}#onData(chunk){this.#buffer+=chunk;let newline;while((newline=this.#buffer.indexOf(`
|
|
1411
|
-
`))!==-1){const line=this.#buffer.slice(0,newline).trim();this.#buffer=this.#buffer.slice(newline+1);let message;try{message=JSON.parse(line)}catch{continue}if(message===null||typeof message!=="object")continue;const id=readProperty(message,"id");const method=readProperty(message,"method");if(method!==undefined){this.#answer(id,method);continue}if(!("result"in message)&&!("error"in message))continue;if(typeof id!=="number")continue;const pending=this.#pending.get(id);if(!pending)continue;this.#pending.delete(id);clearTimeout(pending.timer);const error=readProperty(message,"error");if(error){const reason=optional2(error,"message")??JSON.stringify(error);pending.reject(new AsideReplError("repl_protocol",`aside mcp refused ${pending.method}: ${String(reason)}`))}else pending.resolve(readProperty(message,"result"))}}#answer(id,method){if(id===undefined||id===null||this.#closed)return;if(method==="ping")this.#send({id,result:{}});else this.#send({id,error:{code:-32601,message:`Method not found: ${String(method)}`}})}}
|
|
1411
|
+
`))!==-1){const line=this.#buffer.slice(0,newline).trim();this.#buffer=this.#buffer.slice(newline+1);let message;try{message=JSON.parse(line)}catch{continue}if(message===null||typeof message!=="object")continue;const id=readProperty(message,"id");const method=readProperty(message,"method");if(method!==undefined){this.#answer(id,method);continue}if(!("result"in message)&&!("error"in message))continue;if(typeof id!=="number")continue;const pending=this.#pending.get(id);if(!pending)continue;this.#pending.delete(id);clearTimeout(pending.timer);const error=readProperty(message,"error");if(error){const reason=optional2(error,"message")??JSON.stringify(error);pending.reject(new AsideReplError("repl_protocol",`aside mcp refused ${pending.method}: ${String(reason)}`))}else pending.resolve(readProperty(message,"result"))}}#answer(id,method){if(id===undefined||id===null||this.#closed)return;if(method==="ping")this.#send({id,result:{}});else this.#send({id,error:{code:-32601,message:`Method not found: ${String(method)}`}})}}function findAsideBinary({env=process.env,home=homedir5(),exists=existsSync7}={}){if(env["ASIDE_BIN"])return env["ASIDE_BIN"];const candidates=[path21.join(home,".local","bin",process.platform==="win32"?"aside.exe":"aside")];if(process.platform==="win32"&&env["LOCALAPPDATA"])candidates.push(path21.join(env["LOCALAPPDATA"],"Aside","CLI","current","aside.exe"));for(const dir of(env["PATH"]??"").split(path21.delimiter)){if(dir)candidates.push(path21.join(dir,process.platform==="win32"?"aside.exe":"aside"))}return candidates.find((candidate)=>exists(candidate))??null}var INSTALL_SH2="https://releases.aside.com/install.sh";var APP_STEP="Ask the user to install the Aside browser (aside.com, macOS 15+ or Windows 10 22H2+) and sign in, then re-run asideOnboard().";var loginStep=(bin,account)=>`Ask the user to sign the CLI in: run \`${bin}${account?` --account ${account}`:""} login\` in their terminal and approve the 8-digit code in Aside > Settings > Account > Devices. Then re-run asideOnboard().`;var WINDOWS_CLI_STEP="Ask the user to install the Aside CLI from Aside > Settings > Developers, then re-run asideOnboard().";function asideCliInstallCommand(){return{command:"bash",args:["-c",`curl -fsSL ${INSTALL_SH2} | bash`],env:{}}}async function installAsideCli({home=homedir6(),run=runDefault}={}){const spec=asideCliInstallCommand();const rcBefore=snapshotRcFiles(home);const result=await run(spec.command,spec.args,spec.env);const restoredRcFiles=restoreRcFiles(rcBefore);const asideBin=path222.join(home,".local","bin","aside");const installed=result.code===0&&existsSync8(asideBin);return{installed,asideBin:installed?asideBin:null,code:result.code,stdout:result.stdout,stderr:result.stderr,restoredRcFiles}}function capture(command,args,env){return new Promise((resolve)=>{const child=spawn8(command,args,{env,stdio:["ignore","pipe","pipe"],windowsHide:true});let out="";child.stdout.on("data",(chunk)=>{out+=chunk});child.stderr.on("data",(chunk)=>{out+=chunk});child.on("error",()=>resolve(null));child.on("exit",(code)=>resolve(code===0?out:null))})}function plistString(file,key){try{const text=readFileSync6(file,"utf8");const match=new RegExp(`<key>${key}</key>\\s*<string>([^<]*)</string>`).exec(text);return match?match[1]:null}catch{return null}}function findAsideApp({platform=process.platform,home=homedir6(),exists=existsSync8}={}){if(platform!=="darwin")return{installed:null,path:null,version:null};for(const dir of["/Applications",path222.join(home,"Applications")]){const app=path222.join(dir,"Aside.app");if(!exists(app))continue;const info=path222.join(app,"Contents","Info.plist");return{installed:true,path:app,version:plistString(info,"CFBundleShortVersionString")}}return{installed:false,path:null,version:null}}function parseAccountStatus(output,account){const rows=[];for(const line of output.split(`
|
|
1412
1412
|
`)){const match=/^\s*(\*\s+)?(\S+)\s.*\bsigned (in|out)\b/.exec(line);const id=match?.[2];if(match&&id!==undefined)rows.push({active:Boolean(match[1]),id,signedIn:match[3]==="in"})}const row=account?rows.find((r)=>r.id===account):rows.find((r)=>r.active);return row?{signedIn:row.signedIn,account:row.id}:{signedIn:false,account:account??null}}async function cliReport({asideCommand,env,home,account}){const command=asideCommand??[findAsideBinary({env,home})];const[bin,...lead]=command;if(!bin)return{cli:{installed:false,bin:null,version:null},auth:{signedIn:false,account:null}};const version=await capture(bin,[...lead,"--version"],env);if(version===null)return{cli:{installed:false,bin,version:null},auth:{signedIn:false,account:null}};const status=await capture(bin,[...lead,...account?["--account",account]:[],"account","status"],env);return{cli:{installed:true,bin,version:version.trim()},auth:status===null?{signedIn:false,account:account??null}:parseAccountStatus(status,account)}}function nextStepFor({platform,app,cli,auth}){if(app.installed===false)return APP_STEP;if(!cli.installed)return platform==="win32"?WINDOWS_CLI_STEP:"Install the Aside CLI (asideOnboard() runs the official installer).";if(!auth.signedIn)return loginStep(cli.bin,auth.account);return null}async function asideDoctor({platform=process.platform,home=homedir6(),env=process.env,exists=existsSync8,asideCommand,account}={}){const app=findAsideApp({platform,home,exists});const{cli,auth}=await cliReport({asideCommand,env,home,account});const report={platform,app,cli,auth,ready:app.installed!==false&&cli.installed&&auth.signedIn,nextStep:null};report.nextStep=nextStepFor(report);return report}async function asideOnboard({platform=process.platform,home=homedir6(),env=process.env,exists=existsSync8,asideCommand,account,installOnlyWithApp=false,installCli=installAsideCli}={}){let report=await asideDoctor({platform,home,env,exists,asideCommand,account});let install=null;const appAllows=installOnlyWithApp?report.app.installed===true:report.app.installed!==false;if(!report.cli.installed&&platform!=="win32"&&appAllows){install=await installCli({home});if(install.installed)report=await asideDoctor({platform,home,env,exists,asideCommand:[install.asideBin],account})}return{...report,install}}var isObject2=(value)=>typeof value==="object"&&value!==null;var hasPipes=(child)=>child.stdin!==null&&child.stdout!==null;var DEFAULT_START_TIMEOUT_MS=15000;var DEFAULT_CALL_TIMEOUT_MS=125000;var CLI_PROBE_TIMEOUT_MS=5000;class AsideSession{#transport;#queue=Promise.resolve();#callTimeoutMs;constructor(child,{callTimeoutMs=DEFAULT_CALL_TIMEOUT_MS,protocol="line",account=null}={}){this.#transport=protocol==="mcp"?new McpTransport(child):new LineTransport(child);this.#callTimeoutMs=callTimeoutMs;this.engine="aside";this.account=account;this.sessionDir=null}async ready(timeoutMs=DEFAULT_START_TIMEOUT_MS){const{account,sessionDir}=await this.#transport.ready(timeoutMs);if(account)this.account=account;if(sessionDir)this.sessionDir=sessionDir;return this}async run(code){return(await this.runWithLogs(code)).value}async runWithLogs(code){if(typeof code!=="string"||code.trim()==="")throw new TypeError("run() needs JavaScript source");const tag=`OMOW_RESULT_${randomBytes2(6).toString("hex")}:`;const body=`(async () => {
|
|
1413
1413
|
${code}
|
|
1414
1414
|
})()`;const line=`try { const omowValue = await eval(${JSON.stringify(body)}); const omowJson = JSON.stringify(omowValue ?? null); console.log(${JSON.stringify(tag)} + (omowJson === undefined ? '{"unserializable":true}' : '{"value":' + omowJson + '}')); } catch (omowError) { console.log(${JSON.stringify(tag)} + JSON.stringify({ error: String(omowError?.stack ?? omowError) })); }`;const output=await this.#call(line,tag);const logs=[];let value;let found=false;for(const entry of output){if(entry.startsWith(tag)){let parsed;try{parsed=JSON.parse(entry.slice(tag.length))}catch{parsed={unserializable:true}}const result=isObject2(parsed)?parsed:{};if(result["error"]!==undefined)throw new AsideReplError("repl_error",String(result["error"]),{output:logs});if(result["unserializable"])throw new AsideReplError("repl_unserializable","the code returned a value with no JSON form (a function, symbol or undefined member); return plain data",{output});value=result["value"];found=true}else{logs.push(entry)}}if(!found)throw new AsideReplError("repl_no_result","aside repl finished the call without a result line",{output});return{value,logs}}async open(url){return this.run(`const omowTab = await openTab(${JSON.stringify(String(url))});
|