@midscene/web 1.17.8-beta-20261110095715.0 → 1.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/es/bridge-mode/io-client.mjs +1 -1
- package/dist/es/bridge-mode/io-server.mjs +2 -2
- package/dist/es/bridge-mode/io-server.mjs.map +1 -1
- package/dist/es/bridge-mode/page-browser-side.mjs +1 -1
- package/dist/es/bridge-mode/page-browser-side.mjs.map +1 -1
- package/dist/es/cli.mjs +1 -1
- package/dist/es/common/test-runner/cookies.mjs +16 -8
- package/dist/es/common/test-runner/cookies.mjs.map +1 -1
- package/dist/es/common/test-runner/nodes.mjs +4 -2
- package/dist/es/common/test-runner/nodes.mjs.map +1 -1
- package/dist/es/platform.mjs +4 -1
- package/dist/es/platform.mjs.map +1 -1
- package/dist/lib/bridge-mode/io-client.js +1 -1
- package/dist/lib/bridge-mode/io-server.js +2 -2
- package/dist/lib/bridge-mode/io-server.js.map +1 -1
- package/dist/lib/bridge-mode/page-browser-side.js +1 -1
- package/dist/lib/bridge-mode/page-browser-side.js.map +1 -1
- package/dist/lib/cli.js +1 -1
- package/dist/lib/common/test-runner/cookies.js +16 -8
- package/dist/lib/common/test-runner/cookies.js.map +1 -1
- package/dist/lib/common/test-runner/nodes.js +4 -2
- package/dist/lib/common/test-runner/nodes.js.map +1 -1
- package/dist/lib/platform.js +4 -1
- package/dist/lib/platform.js.map +1 -1
- package/dist/types/common/test-runner/cookies.d.ts.map +1 -1
- package/dist/types/platform.d.ts.map +1 -1
- package/package.json +4 -4
|
@@ -101,7 +101,7 @@ class BridgeServer {
|
|
|
101
101
|
logMsg('one client connected');
|
|
102
102
|
this.socket = socket;
|
|
103
103
|
const clientVersion = socket.handshake.query.version;
|
|
104
|
-
logMsg(`Bridge connected, cli-side version v1.
|
|
104
|
+
logMsg(`Bridge connected, cli-side version v1.18.0, browser-side version v${clientVersion}`);
|
|
105
105
|
socket.on(BridgeEvent.CallResponse, (params)=>{
|
|
106
106
|
const id = params.id;
|
|
107
107
|
const response = params.response;
|
|
@@ -125,7 +125,7 @@ class BridgeServer {
|
|
|
125
125
|
setTimeout(()=>{
|
|
126
126
|
this.onConnect?.();
|
|
127
127
|
const payload = {
|
|
128
|
-
version: "1.
|
|
128
|
+
version: "1.18.0"
|
|
129
129
|
};
|
|
130
130
|
socket.emit(BridgeEvent.Connected, payload);
|
|
131
131
|
Promise.resolve().then(()=>{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bridge-mode/io-server.mjs","sources":["../../../src/bridge-mode/io-server.ts"],"sourcesContent":["import {\n type IncomingMessage,\n type ServerResponse,\n createServer,\n} from 'node:http';\nimport { sleep } from '@midscene/core/utils';\nimport { getDebug } from '@midscene/shared/logger';\nimport { logMsg } from '@midscene/shared/utils';\nimport { Server, type Socket as ServerSocket } from 'socket.io';\nimport { io as ClientIO } from 'socket.io-client';\n\nimport {\n type BridgeCall,\n type BridgeCallResponse,\n BridgeCallTimeout,\n type BridgeConnectedEventPayload,\n BridgeErrorCodeNoClientConnected,\n BridgeEvent,\n BridgeSignalKill,\n DefaultBridgeServerHost,\n DefaultBridgeServerPort,\n} from './common';\n\nconst debug = getDebug('web:bridge:io-server');\n\ndeclare const __VERSION__: string;\n\n/**\n * Returns true if the given Origin header value is allowed to connect\n * to the bridge server. Trusted origins are:\n * - No Origin header (local Node.js processes like killRunningServer)\n * - chrome-extension:// origins (the Midscene Chrome extension)\n *\n * Browser pages (https://evil.com, etc.) are rejected to prevent\n * Cross-Site WebSocket Hijacking (CSWSH) attacks.\n */\nfunction isTrustedOrigin(origin: string | undefined): boolean {\n if (!origin) return true;\n if (origin.startsWith('chrome-extension://')) return true;\n return false;\n}\n\nexport const killRunningServer = async (\n port?: number,\n host = DefaultBridgeServerHost,\n) => {\n try {\n const client = ClientIO(`ws://${host}:${port || DefaultBridgeServerPort}`, {\n query: {\n [BridgeSignalKill]: 1,\n },\n });\n await sleep(300);\n await client.close();\n } catch (e) {\n debug('failed to kill port: %O', e);\n }\n};\n\n// ws server, this is where the request is sent\nexport class BridgeServer {\n private callId = 0;\n private io: Server | null = null;\n private socket: ServerSocket | null = null;\n private listeningTimeoutId: NodeJS.Timeout | null = null;\n private listeningTimerFlag = false;\n private connectionTipTimer: NodeJS.Timeout | null = null;\n public calls: Record<string, BridgeCall> = {};\n\n private connectionLost = false;\n private connectionLostReason = '';\n\n constructor(\n public host: string,\n public port: number,\n public onConnect?: () => void,\n public onDisconnect?: (reason: string) => void,\n public closeConflictServer?: boolean,\n ) {}\n\n async listen(\n opts: {\n timeout?: number | false;\n } = {},\n ): Promise<void> {\n const { timeout = 30000 } = opts;\n\n if (this.closeConflictServer) {\n await killRunningServer(this.port, this.host);\n }\n\n return new Promise((resolve, reject) => {\n if (this.listeningTimerFlag) {\n return reject(new Error('already listening'));\n }\n this.listeningTimerFlag = true;\n\n this.listeningTimeoutId = timeout\n ? setTimeout(() => {\n reject(\n new Error(\n `no extension connected after ${timeout}ms (${BridgeErrorCodeNoClientConnected})`,\n ),\n );\n }, timeout)\n : null;\n\n this.connectionTipTimer =\n !timeout || timeout > 3000\n ? setTimeout(() => {\n logMsg('waiting for bridge to connect...');\n }, 2000)\n : null;\n\n // Create HTTP server — no /bridge-auth endpoint needed since we use\n // pure Origin checking in the Socket.IO middleware below.\n const httpServer = createServer(\n (_req: IncomingMessage, res: ServerResponse) => {\n res.writeHead(404);\n res.end();\n },\n );\n\n // Set up HTTP server event listeners FIRST\n httpServer.once('listening', () => {\n resolve();\n });\n\n httpServer.once('error', (err: Error) => {\n reject(new Error(`Bridge Listening Error: ${err.message}`));\n });\n\n // Always honor the configured interface, including the loopback default.\n httpServer.listen(this.port, this.host);\n\n // Now create Socket.IO Server attached to the already-listening HTTP server\n this.io = new Server(httpServer, {\n maxHttpBufferSize: 100 * 1024 * 1024, // 100MB\n // Increase pingTimeout to tolerate Chrome MV3 Service Worker suspension.\n // The SW keepalive alarm fires every ~24s; default pingTimeout (20s) may\n // be too short if the SW is suspended between alarm pings.\n pingTimeout: 60000,\n });\n\n this.io.use((socket, next) => {\n // Reject connections from untrusted browser origins to prevent\n // Cross-Site WebSocket Hijacking (CSWSH) and unauthorized kill signals.\n // The browser automatically sets the Origin header on WebSocket\n // handshakes, and JavaScript cannot override it.\n const origin = socket.handshake.headers.origin;\n if (!isTrustedOrigin(origin)) {\n debug('connection rejected: untrusted origin=%s', origin);\n return next(new Error('origin not allowed'));\n }\n\n // Allow new connections to replace old ones (reconnection after\n // extension Stop→Start). If the old socket is already disconnected\n // or unresponsive, accept the new connection immediately.\n if (\n socket.handshake.url.includes(BridgeSignalKill) === false &&\n this.socket?.connected\n ) {\n return next(new Error('server already connected by another client'));\n }\n next();\n });\n\n this.io.on('connection', (socket) => {\n // check the connection url\n const url = socket.handshake.url;\n if (url.includes(BridgeSignalKill)) {\n console.warn('kill signal received, closing bridge server');\n return this.close();\n }\n\n this.connectionLost = false;\n this.connectionLostReason = '';\n this.listeningTimeoutId && clearTimeout(this.listeningTimeoutId);\n this.listeningTimeoutId = null;\n this.connectionTipTimer && clearTimeout(this.connectionTipTimer);\n this.connectionTipTimer = null;\n if (this.socket?.connected) {\n socket.emit(BridgeEvent.Refused);\n socket.disconnect();\n logMsg(\n 'refused new connection: server already connected by another client',\n );\n return;\n }\n\n // Clean up stale old socket if it exists but is no longer connected\n if (this.socket) {\n try {\n this.socket.disconnect();\n } catch (e) {\n logMsg(`failed to disconnect stale socket: ${e}`);\n }\n this.socket = null;\n }\n\n try {\n logMsg('one client connected');\n this.socket = socket;\n\n const clientVersion = socket.handshake.query.version;\n logMsg(\n `Bridge connected, cli-side version v${__VERSION__}, browser-side version v${clientVersion}`,\n );\n\n socket.on(BridgeEvent.CallResponse, (params: BridgeCallResponse) => {\n const id = params.id;\n const response = params.response;\n const error = params.error;\n\n this.triggerCallResponseCallback(id, error, response);\n });\n\n socket.on('disconnect', (reason: string) => {\n this.connectionLost = true;\n this.connectionLostReason = reason;\n this.socket = null;\n\n // flush all pending calls as error and clean up completed calls\n for (const id in this.calls) {\n const call = this.calls[id];\n\n if (!call.responseTime) {\n const errorMessage = this.connectionLostErrorMsg();\n this.triggerCallResponseCallback(\n id,\n new Error(errorMessage),\n null,\n );\n }\n }\n\n // Clean up completed calls to prevent memory leaks in long-running sessions\n for (const id in this.calls) {\n if (this.calls[id].responseTime) {\n delete this.calls[id];\n }\n }\n\n this.onDisconnect?.(reason);\n });\n\n setTimeout(() => {\n this.onConnect?.();\n\n const payload = {\n version: __VERSION__,\n } as BridgeConnectedEventPayload;\n socket.emit(BridgeEvent.Connected, payload);\n Promise.resolve().then(() => {\n for (const id in this.calls) {\n if (this.calls[id].callTime === 0) {\n this.emitCall(id);\n }\n }\n });\n }, 0);\n } catch (e) {\n logMsg(`failed to handle connection event: ${e}`);\n }\n });\n\n this.io.on('close', () => {\n this.close();\n });\n });\n }\n\n private connectionLostErrorMsg = () => {\n return `Connection lost, reason: ${this.connectionLostReason}`;\n };\n\n private async triggerCallResponseCallback(\n id: string | number,\n error: Error | string | null,\n response: any,\n ) {\n const call = this.calls[id];\n if (!call) {\n throw new Error(`call ${id} not found`);\n }\n // Ensure error is always an Error object (bridge client may send strings)\n if (error) {\n call.error =\n error instanceof Error\n ? error\n : new Error(typeof error === 'string' ? error : String(error));\n } else {\n call.error = undefined;\n }\n call.response = response;\n call.responseTime = Date.now();\n\n call.callback(call.error, response);\n }\n\n private async emitCall(id: string) {\n const call = this.calls[id];\n if (!call) {\n throw new Error(`call ${id} not found`);\n }\n\n if (this.connectionLost) {\n const message = `Connection lost, reason: ${this.connectionLostReason}`;\n call.callback(new Error(message), null);\n return;\n }\n\n if (this.socket) {\n this.socket.emit(BridgeEvent.Call, {\n id,\n method: call.method,\n args: call.args,\n });\n call.callTime = Date.now();\n }\n }\n\n async call<T = any>(\n method: string,\n args: any[],\n timeout = BridgeCallTimeout,\n ): Promise<T> {\n const id = `${this.callId++}`;\n\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n logMsg(`bridge call timeout, id=${id}, method=${method}, args=`, args);\n this.calls[id].error = new Error(\n `Bridge call timeout after ${timeout}ms: ${method}`,\n );\n reject(this.calls[id].error);\n }, timeout);\n\n this.calls[id] = {\n method,\n args,\n response: null,\n callTime: 0,\n responseTime: 0,\n callback: (error: Error | undefined, response: any) => {\n clearTimeout(timeoutId);\n if (error) {\n reject(error);\n } else {\n resolve(response);\n }\n },\n };\n\n this.emitCall(id);\n });\n }\n\n // do NOT restart after close\n async close() {\n this.listeningTimeoutId && clearTimeout(this.listeningTimeoutId);\n this.connectionTipTimer && clearTimeout(this.connectionTipTimer);\n const closeProcess = this.io?.close();\n this.io = null;\n\n return closeProcess;\n }\n}\n"],"names":["debug","getDebug","isTrustedOrigin","origin","killRunningServer","port","host","DefaultBridgeServerHost","client","ClientIO","DefaultBridgeServerPort","BridgeSignalKill","sleep","e","BridgeServer","opts","timeout","Promise","resolve","reject","Error","setTimeout","BridgeErrorCodeNoClientConnected","logMsg","httpServer","createServer","_req","res","err","Server","socket","next","url","console","clearTimeout","BridgeEvent","clientVersion","params","id","response","error","reason","call","errorMessage","payload","__VERSION__","String","undefined","Date","message","method","args","BridgeCallTimeout","timeoutId","closeProcess","onConnect","onDisconnect","closeConflictServer"],"mappings":";;;;;;;;;;;;;;;;;AAuBA,MAAMA,QAAQC,SAAS;AAavB,SAASC,gBAAgBC,MAA0B;IACjD,IAAI,CAACA,QAAQ,OAAO;IACpB,IAAIA,OAAO,UAAU,CAAC,wBAAwB,OAAO;IACrD,OAAO;AACT;AAEO,MAAMC,oBAAoB,OAC/BC,MACAC,OAAOC,uBAAuB;IAE9B,IAAI;QACF,MAAMC,SAASC,GAAS,CAAC,KAAK,EAAEH,KAAK,CAAC,EAAED,QAAQK,yBAAyB,EAAE;YACzE,OAAO;gBACL,CAACC,iBAAiB,EAAE;YACtB;QACF;QACA,MAAMC,MAAM;QACZ,MAAMJ,OAAO,KAAK;IACpB,EAAE,OAAOK,GAAG;QAC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,sBAAsB,GAAG,IACxB,CAAC,yBAAyB,EAAE,IAAI,CAAC,oBAAoB,EAAE;IAnM7D;AAiSL"}
|
|
1
|
+
{"version":3,"file":"bridge-mode/io-server.mjs","sources":["../../../src/bridge-mode/io-server.ts"],"sourcesContent":["import {\n type IncomingMessage,\n type ServerResponse,\n createServer,\n} from 'node:http';\nimport { sleep } from '@midscene/core/utils';\nimport { getDebug } from '@midscene/shared/logger';\nimport { logMsg } from '@midscene/shared/utils';\nimport { Server, type Socket as ServerSocket } from 'socket.io';\nimport { io as ClientIO } from 'socket.io-client';\n\nimport {\n type BridgeCall,\n type BridgeCallResponse,\n BridgeCallTimeout,\n type BridgeConnectedEventPayload,\n BridgeErrorCodeNoClientConnected,\n BridgeEvent,\n BridgeSignalKill,\n DefaultBridgeServerHost,\n DefaultBridgeServerPort,\n} from './common';\n\nconst debug = getDebug('web:bridge:io-server');\n\ndeclare const __VERSION__: string;\n\n/**\n * Returns true if the given Origin header value is allowed to connect\n * to the bridge server. Trusted origins are:\n * - No Origin header (local Node.js processes like killRunningServer)\n * - chrome-extension:// origins (the Midscene Chrome extension)\n *\n * Browser pages (https://evil.com, etc.) are rejected to prevent\n * Cross-Site WebSocket Hijacking (CSWSH) attacks.\n */\nfunction isTrustedOrigin(origin: string | undefined): boolean {\n if (!origin) return true;\n if (origin.startsWith('chrome-extension://')) return true;\n return false;\n}\n\nexport const killRunningServer = async (\n port?: number,\n host = DefaultBridgeServerHost,\n) => {\n try {\n const client = ClientIO(`ws://${host}:${port || DefaultBridgeServerPort}`, {\n query: {\n [BridgeSignalKill]: 1,\n },\n });\n await sleep(300);\n await client.close();\n } catch (e) {\n debug('failed to kill port: %O', e);\n }\n};\n\n// ws server, this is where the request is sent\nexport class BridgeServer {\n private callId = 0;\n private io: Server | null = null;\n private socket: ServerSocket | null = null;\n private listeningTimeoutId: NodeJS.Timeout | null = null;\n private listeningTimerFlag = false;\n private connectionTipTimer: NodeJS.Timeout | null = null;\n public calls: Record<string, BridgeCall> = {};\n\n private connectionLost = false;\n private connectionLostReason = '';\n\n constructor(\n public host: string,\n public port: number,\n public onConnect?: () => void,\n public onDisconnect?: (reason: string) => void,\n public closeConflictServer?: boolean,\n ) {}\n\n async listen(\n opts: {\n timeout?: number | false;\n } = {},\n ): Promise<void> {\n const { timeout = 30000 } = opts;\n\n if (this.closeConflictServer) {\n await killRunningServer(this.port, this.host);\n }\n\n return new Promise((resolve, reject) => {\n if (this.listeningTimerFlag) {\n return reject(new Error('already listening'));\n }\n this.listeningTimerFlag = true;\n\n this.listeningTimeoutId = timeout\n ? setTimeout(() => {\n reject(\n new Error(\n `no extension connected after ${timeout}ms (${BridgeErrorCodeNoClientConnected})`,\n ),\n );\n }, timeout)\n : null;\n\n this.connectionTipTimer =\n !timeout || timeout > 3000\n ? setTimeout(() => {\n logMsg('waiting for bridge to connect...');\n }, 2000)\n : null;\n\n // Create HTTP server — no /bridge-auth endpoint needed since we use\n // pure Origin checking in the Socket.IO middleware below.\n const httpServer = createServer(\n (_req: IncomingMessage, res: ServerResponse) => {\n res.writeHead(404);\n res.end();\n },\n );\n\n // Set up HTTP server event listeners FIRST\n httpServer.once('listening', () => {\n resolve();\n });\n\n httpServer.once('error', (err: Error) => {\n reject(new Error(`Bridge Listening Error: ${err.message}`));\n });\n\n // Always honor the configured interface, including the loopback default.\n httpServer.listen(this.port, this.host);\n\n // Now create Socket.IO Server attached to the already-listening HTTP server\n this.io = new Server(httpServer, {\n maxHttpBufferSize: 100 * 1024 * 1024, // 100MB\n // Increase pingTimeout to tolerate Chrome MV3 Service Worker suspension.\n // The SW keepalive alarm fires every ~24s; default pingTimeout (20s) may\n // be too short if the SW is suspended between alarm pings.\n pingTimeout: 60000,\n });\n\n this.io.use((socket, next) => {\n // Reject connections from untrusted browser origins to prevent\n // Cross-Site WebSocket Hijacking (CSWSH) and unauthorized kill signals.\n // The browser automatically sets the Origin header on WebSocket\n // handshakes, and JavaScript cannot override it.\n const origin = socket.handshake.headers.origin;\n if (!isTrustedOrigin(origin)) {\n debug('connection rejected: untrusted origin=%s', origin);\n return next(new Error('origin not allowed'));\n }\n\n // Allow new connections to replace old ones (reconnection after\n // extension Stop→Start). If the old socket is already disconnected\n // or unresponsive, accept the new connection immediately.\n if (\n socket.handshake.url.includes(BridgeSignalKill) === false &&\n this.socket?.connected\n ) {\n return next(new Error('server already connected by another client'));\n }\n next();\n });\n\n this.io.on('connection', (socket) => {\n // check the connection url\n const url = socket.handshake.url;\n if (url.includes(BridgeSignalKill)) {\n console.warn('kill signal received, closing bridge server');\n return this.close();\n }\n\n this.connectionLost = false;\n this.connectionLostReason = '';\n this.listeningTimeoutId && clearTimeout(this.listeningTimeoutId);\n this.listeningTimeoutId = null;\n this.connectionTipTimer && clearTimeout(this.connectionTipTimer);\n this.connectionTipTimer = null;\n if (this.socket?.connected) {\n socket.emit(BridgeEvent.Refused);\n socket.disconnect();\n logMsg(\n 'refused new connection: server already connected by another client',\n );\n return;\n }\n\n // Clean up stale old socket if it exists but is no longer connected\n if (this.socket) {\n try {\n this.socket.disconnect();\n } catch (e) {\n logMsg(`failed to disconnect stale socket: ${e}`);\n }\n this.socket = null;\n }\n\n try {\n logMsg('one client connected');\n this.socket = socket;\n\n const clientVersion = socket.handshake.query.version;\n logMsg(\n `Bridge connected, cli-side version v${__VERSION__}, browser-side version v${clientVersion}`,\n );\n\n socket.on(BridgeEvent.CallResponse, (params: BridgeCallResponse) => {\n const id = params.id;\n const response = params.response;\n const error = params.error;\n\n this.triggerCallResponseCallback(id, error, response);\n });\n\n socket.on('disconnect', (reason: string) => {\n this.connectionLost = true;\n this.connectionLostReason = reason;\n this.socket = null;\n\n // flush all pending calls as error and clean up completed calls\n for (const id in this.calls) {\n const call = this.calls[id];\n\n if (!call.responseTime) {\n const errorMessage = this.connectionLostErrorMsg();\n this.triggerCallResponseCallback(\n id,\n new Error(errorMessage),\n null,\n );\n }\n }\n\n // Clean up completed calls to prevent memory leaks in long-running sessions\n for (const id in this.calls) {\n if (this.calls[id].responseTime) {\n delete this.calls[id];\n }\n }\n\n this.onDisconnect?.(reason);\n });\n\n setTimeout(() => {\n this.onConnect?.();\n\n const payload = {\n version: __VERSION__,\n } as BridgeConnectedEventPayload;\n socket.emit(BridgeEvent.Connected, payload);\n Promise.resolve().then(() => {\n for (const id in this.calls) {\n if (this.calls[id].callTime === 0) {\n this.emitCall(id);\n }\n }\n });\n }, 0);\n } catch (e) {\n logMsg(`failed to handle connection event: ${e}`);\n }\n });\n\n this.io.on('close', () => {\n this.close();\n });\n });\n }\n\n private connectionLostErrorMsg = () => {\n return `Connection lost, reason: ${this.connectionLostReason}`;\n };\n\n private async triggerCallResponseCallback(\n id: string | number,\n error: Error | string | null,\n response: any,\n ) {\n const call = this.calls[id];\n if (!call) {\n throw new Error(`call ${id} not found`);\n }\n // Ensure error is always an Error object (bridge client may send strings)\n if (error) {\n call.error =\n error instanceof Error\n ? error\n : new Error(typeof error === 'string' ? error : String(error));\n } else {\n call.error = undefined;\n }\n call.response = response;\n call.responseTime = Date.now();\n\n call.callback(call.error, response);\n }\n\n private async emitCall(id: string) {\n const call = this.calls[id];\n if (!call) {\n throw new Error(`call ${id} not found`);\n }\n\n if (this.connectionLost) {\n const message = `Connection lost, reason: ${this.connectionLostReason}`;\n call.callback(new Error(message), null);\n return;\n }\n\n if (this.socket) {\n this.socket.emit(BridgeEvent.Call, {\n id,\n method: call.method,\n args: call.args,\n });\n call.callTime = Date.now();\n }\n }\n\n async call<T = any>(\n method: string,\n args: any[],\n timeout = BridgeCallTimeout,\n ): Promise<T> {\n const id = `${this.callId++}`;\n\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n logMsg(`bridge call timeout, id=${id}, method=${method}, args=`, args);\n this.calls[id].error = new Error(\n `Bridge call timeout after ${timeout}ms: ${method}`,\n );\n reject(this.calls[id].error);\n }, timeout);\n\n this.calls[id] = {\n method,\n args,\n response: null,\n callTime: 0,\n responseTime: 0,\n callback: (error: Error | undefined, response: any) => {\n clearTimeout(timeoutId);\n if (error) {\n reject(error);\n } else {\n resolve(response);\n }\n },\n };\n\n this.emitCall(id);\n });\n }\n\n // do NOT restart after close\n async close() {\n this.listeningTimeoutId && clearTimeout(this.listeningTimeoutId);\n this.connectionTipTimer && clearTimeout(this.connectionTipTimer);\n const closeProcess = this.io?.close();\n this.io = null;\n\n return closeProcess;\n }\n}\n"],"names":["debug","getDebug","isTrustedOrigin","origin","killRunningServer","port","host","DefaultBridgeServerHost","client","ClientIO","DefaultBridgeServerPort","BridgeSignalKill","sleep","e","BridgeServer","opts","timeout","Promise","resolve","reject","Error","setTimeout","BridgeErrorCodeNoClientConnected","logMsg","httpServer","createServer","_req","res","err","Server","socket","next","url","console","clearTimeout","BridgeEvent","clientVersion","params","id","response","error","reason","call","errorMessage","payload","__VERSION__","String","undefined","Date","message","method","args","BridgeCallTimeout","timeoutId","closeProcess","onConnect","onDisconnect","closeConflictServer"],"mappings":";;;;;;;;;;;;;;;;;AAuBA,MAAMA,QAAQC,SAAS;AAavB,SAASC,gBAAgBC,MAA0B;IACjD,IAAI,CAACA,QAAQ,OAAO;IACpB,IAAIA,OAAO,UAAU,CAAC,wBAAwB,OAAO;IACrD,OAAO;AACT;AAEO,MAAMC,oBAAoB,OAC/BC,MACAC,OAAOC,uBAAuB;IAE9B,IAAI;QACF,MAAMC,SAASC,GAAS,CAAC,KAAK,EAAEH,KAAK,CAAC,EAAED,QAAQK,yBAAyB,EAAE;YACzE,OAAO;gBACL,CAACC,iBAAiB,EAAE;YACtB;QACF;QACA,MAAMC,MAAM;QACZ,MAAMJ,OAAO,KAAK;IACpB,EAAE,OAAOK,GAAG;QACVb,MAAM,2BAA2Ba;IACnC;AACF;AAGO,MAAMC;IAoBX,MAAM,OACJC,OAEI,CAAC,CAAC,EACS;QACf,MAAM,EAAEC,UAAU,KAAK,EAAE,GAAGD;QAE5B,IAAI,IAAI,CAAC,mBAAmB,EAC1B,MAAMX,kBAAkB,IAAI,CAAC,IAAI,EAAE,IAAI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gBACAC;gBACA,UAAU;gBACV,UAAU;gBACV,cAAc;gBACd,UAAU,CAACX,OAA0BD;oBACnCL,aAAamB;oBACb,IAAIb,OACFrB,OAAOqB;yBAEPtB,QAAQqB;gBAEZ;YACF;YAEA,IAAI,CAAC,QAAQ,CAACD;QAChB;IACF;IAGA,MAAM,QAAQ;QACZ,IAAI,CAAC,kBAAkB,IAAIJ,aAAa,IAAI,CAAC,kBAAkB;QAC/D,IAAI,CAAC,kBAAkB,IAAIA,aAAa,IAAI,CAAC,kBAAkB;QAC/D,MAAMoB,eAAe,IAAI,CAAC,EAAE,EAAE;QAC9B,IAAI,CAAC,EAAE,GAAG;QAEV,OAAOA;IACT;IAtSA,YACShD,IAAY,EACZD,IAAY,EACZkD,SAAsB,EACtBC,YAAuC,EACvCC,mBAA6B,CACpC;;;;;;QAjBF,uBAAQ,UAAR;QACA,uBAAQ,MAAR;QACA,uBAAQ,UAAR;QACA,uBAAQ,sBAAR;QACA,uBAAQ,sBAAR;QACA,uBAAQ,sBAAR;QACA,uBAAO,SAAP;QAEA,uBAAQ,kBAAR;QACA,uBAAQ,wBAAR;QA0MA,uBAAQ,0BAAR;aAvMSnD,IAAI,GAAJA;aACAD,IAAI,GAAJA;aACAkD,SAAS,GAATA;aACAC,YAAY,GAAZA;aACAC,mBAAmB,GAAnBA;aAhBD,MAAM,GAAG;aACT,EAAE,GAAkB;aACpB,MAAM,GAAwB;aAC9B,kBAAkB,GAA0B;aAC5C,kBAAkB,GAAG;aACrB,kBAAkB,GAA0B;aAC7C,KAAK,GAA+B,CAAC;aAEpC,cAAc,GAAG;aACjB,oBAAoB,GAAG;aA0MvB,sBAAsB,GAAG,IACxB,CAAC,yBAAyB,EAAE,IAAI,CAAC,oBAAoB,EAAE;IAnM7D;AAiSL"}
|
|
@@ -100,7 +100,7 @@ class ExtensionBridgePageBrowserSide extends page {
|
|
|
100
100
|
throw new Error('Connection denied by user');
|
|
101
101
|
}
|
|
102
102
|
}
|
|
103
|
-
this.onLogMessage(`Bridge connected, cli-side version v${this.bridgeClient.serverVersion}, browser-side version v1.
|
|
103
|
+
this.onLogMessage(`Bridge connected, cli-side version v${this.bridgeClient.serverVersion}, browser-side version v1.18.0`, 'log');
|
|
104
104
|
}
|
|
105
105
|
async connect() {
|
|
106
106
|
return await this.setupBridgeClient();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bridge-mode/page-browser-side.mjs","sources":["../../../src/bridge-mode/page-browser-side.ts"],"sourcesContent":["import { assert } from '@midscene/shared/utils';\nimport ChromeExtensionProxyPage from '../chrome-extension/page';\nimport type {\n ChromePageDestroyOptions,\n KeyboardAction,\n MouseAction,\n} from '../web-page';\nimport {\n type BridgeConnectTabOptions,\n BridgeEvent,\n DefaultBridgeServerHost,\n DefaultBridgeServerPort,\n KeyboardEvent,\n MouseEvent,\n} from './common';\nimport { BridgeClient } from './io-client';\n\ndeclare const __VERSION__: string;\n\nconst NEW_TAB_LOAD_TIMEOUT_MS = 30_000;\n\nfunction isBlankUrl(url: string | undefined): boolean {\n if (!url) return true;\n return url === 'about:blank' || url.startsWith('chrome://newtab');\n}\n\n// Wait until the freshly created tab has navigated away from about:blank\n// and reached `status === 'complete'`. Resolves on timeout instead of\n// throwing so callers degrade to the existing lazy-attach behavior.\nfunction waitForTabNavigationComplete(\n tabId: number,\n targetUrl: string,\n timeoutMs = NEW_TAB_LOAD_TIMEOUT_MS,\n): Promise<void> {\n return new Promise((resolve) => {\n let settled = false;\n const finish = () => {\n if (settled) return;\n settled = true;\n try {\n chrome.tabs.onUpdated.removeListener(onUpdated);\n } catch {}\n clearTimeout(timer);\n resolve();\n };\n\n const isReady = (tab: chrome.tabs.Tab | undefined): boolean => {\n if (!tab) return false;\n if (tab.status !== 'complete') return false;\n const currentUrl = tab.url || tab.pendingUrl || '';\n // Skip the initial about:blank \"complete\" that fires before\n // the target URL navigation kicks in.\n if (isBlankUrl(currentUrl) && !isBlankUrl(targetUrl)) return false;\n return true;\n };\n\n const onUpdated = (\n id: number,\n _info: chrome.tabs.TabChangeInfo,\n tab: chrome.tabs.Tab,\n ) => {\n if (id !== tabId) return;\n if (isReady(tab)) finish();\n };\n\n chrome.tabs.onUpdated.addListener(onUpdated);\n const timer = setTimeout(finish, timeoutMs);\n\n // Handle the race where the tab already finished loading before\n // we registered the listener.\n chrome.tabs\n .get(tabId)\n .then((tab) => {\n if (isReady(tab)) finish();\n })\n .catch(() => {});\n });\n}\n\nexport class ExtensionBridgePageBrowserSide extends ChromeExtensionProxyPage {\n public bridgeClient: BridgeClient | null = null;\n\n private destroyOptions?: ChromePageDestroyOptions;\n\n private newlyCreatedTabIds: number[] = [];\n\n // Connection confirmation state\n private confirmationPromise: Promise<boolean> | null = null;\n\n constructor(\n public serverEndpoint?: string,\n public onDisconnect: () => void = () => {},\n public onLogMessage: (\n message: string,\n type: 'log' | 'status',\n ) => void = () => {},\n forceSameTabNavigation = true,\n public onConnectionRequest?: () => Promise<boolean>,\n ) {\n super(forceSameTabNavigation);\n }\n\n private async setupBridgeClient() {\n const endpoint =\n this.serverEndpoint ||\n `ws://${DefaultBridgeServerHost}:${DefaultBridgeServerPort}`;\n\n // Create confirmation gate BEFORE establishing connection,\n // so that any calls received immediately after connection are blocked\n // until user confirms. This prevents a race condition where server-side\n // queued calls bypass the confirmation dialog.\n let resolveConfirmationGate: (allowed: boolean) => void = () => {};\n if (this.onConnectionRequest) {\n this.confirmationPromise = new Promise<boolean>((resolve) => {\n resolveConfirmationGate = resolve;\n });\n }\n\n this.bridgeClient = new BridgeClient(\n endpoint,\n async (method, args: any[]) => {\n // Wait for user confirmation before processing any commands\n if (this.confirmationPromise) {\n const allowed = await this.confirmationPromise;\n if (!allowed) {\n throw new Error('Connection denied by user');\n }\n }\n\n this.onLogMessage(`bridge call from cli side: ${method}`, 'log');\n if (method === BridgeEvent.ConnectNewTabWithUrl) {\n return this.connectNewTabWithUrl.apply(\n this,\n args as unknown as [string],\n );\n }\n\n if (method === BridgeEvent.GetBrowserTabList) {\n return this.getBrowserTabList.apply(this, args as any);\n }\n\n if (method === BridgeEvent.SetActiveTabId) {\n return this.setActiveTabId.apply(this, args as any);\n }\n\n if (method === BridgeEvent.ConnectCurrentTab) {\n return this.connectCurrentTab.apply(this, args as any);\n }\n\n if (method === BridgeEvent.UpdateAgentStatus) {\n return this.onLogMessage(args[0] as string, 'status');\n }\n\n const tabId = await this.getActiveTabId();\n if (!tabId || tabId === 0) {\n throw new Error('no tab is connected');\n }\n\n // this.onLogMessage(`calling method: ${method}`);\n\n if (method.startsWith(MouseEvent.PREFIX)) {\n const actionName = method.split('.')[1] as keyof MouseAction;\n if (actionName === 'drag') {\n return this.mouse[actionName].apply(this.mouse, args as any);\n }\n return this.mouse[actionName].apply(this.mouse, args as any);\n }\n\n if (method.startsWith(KeyboardEvent.PREFIX)) {\n const actionName = method.split('.')[1] as keyof KeyboardAction;\n if (actionName === 'press') {\n return this.keyboard[actionName].apply(this.keyboard, args as any);\n }\n return this.keyboard[actionName].apply(this.keyboard, args as any);\n }\n\n // Generic method lookup. Methods like `setWaterFlowAnimationEnabled`\n // and `getWaterFlowAnimationEnabled` are inherited from\n // ChromeExtensionProxyPage and found via `this[method]`.\n if (!this[method as keyof ChromeExtensionProxyPage]) {\n this.onLogMessage(`method not found: ${method}`, 'log');\n return undefined;\n }\n\n try {\n // @ts-expect-error\n const result = await this[method as keyof ChromeExtensionProxyPage](\n ...args,\n );\n return result;\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : 'Unknown error';\n this.onLogMessage(\n `Error calling method: ${method}, ${errorMessage}`,\n 'log',\n );\n throw new Error(errorMessage, { cause: e });\n }\n },\n // on disconnect\n () => {\n return this.destroy();\n },\n );\n await this.bridgeClient.connect();\n\n // Show confirmation dialog after connection is established\n if (this.onConnectionRequest) {\n this.onLogMessage('Waiting for user confirmation...', 'log');\n const allowed = await this.onConnectionRequest();\n resolveConfirmationGate(allowed);\n this.confirmationPromise = null;\n\n if (!allowed) {\n this.onLogMessage('Connection denied by user', 'log');\n this.bridgeClient.disconnect();\n this.bridgeClient = null;\n throw new Error('Connection denied by user');\n }\n }\n\n this.onLogMessage(\n `Bridge connected, cli-side version v${this.bridgeClient.serverVersion}, browser-side version v${__VERSION__}`,\n 'log',\n );\n }\n\n public async connect() {\n return await this.setupBridgeClient();\n }\n\n public async connectNewTabWithUrl(\n url: string,\n options: BridgeConnectTabOptions = {\n forceSameTabNavigation: true,\n },\n ) {\n // Set the water-flow animation flag BEFORE any debugger commands are\n // sent (which trigger enableWaterFlowAnimation via sendCommandToDebugger).\n // Otherwise the animation gets injected during the connection flow\n // before the CLI side's setWaterFlowAnimationEnabled(false) arrives.\n if (options.enableWaterFlowAnimation !== undefined) {\n this.waterFlowAnimationEnabled = options.enableWaterFlowAnimation;\n }\n\n // Preserve the historical default: activate the new tab unless the caller opts into background mode.\n const activate = options.activateTab ?? true;\n const tab = await chrome.tabs.create({ url, active: activate });\n const tabId = tab.id;\n assert(tabId, 'failed to get tabId after creating a new tab');\n\n // new tab\n this.onLogMessage(`Creating new tab: ${url}`, 'log');\n this.newlyCreatedTabIds.push(tabId);\n\n this.forceSameTabNavigation = options?.forceSameTabNavigation ?? true;\n\n // chrome.tabs.create returns immediately with an about:blank target,\n // then navigates to `url`. If we attach the debugger during that\n // cross-origin transition Site Isolation will detach it again, leaving\n // the first CDP command to fail with \"Debugger is not attached to the\n // tab\". Wait for navigation to settle so the lazy attach lands on a\n // stable target.\n await waitForTabNavigationComplete(tabId, url);\n\n await this.setActiveTabId(tabId, { activate });\n }\n\n public async connectCurrentTab(\n options: BridgeConnectTabOptions = {\n forceSameTabNavigation: true,\n },\n ) {\n // Set the water-flow animation flag BEFORE any debugger commands are\n // sent (which trigger enableWaterFlowAnimation via sendCommandToDebugger).\n if (options.enableWaterFlowAnimation !== undefined) {\n this.waterFlowAnimationEnabled = options.enableWaterFlowAnimation;\n }\n\n const tabs =\n options?.tabId !== undefined\n ? [await chrome.tabs.get(options.tabId)]\n : await chrome.tabs.query({ active: true, currentWindow: true });\n const tabId = tabs[0]?.id;\n assert(tabId, 'failed to get tabId');\n\n this.onLogMessage(`Connected to current tab: ${tabs[0]?.url}`, 'log');\n\n this.forceSameTabNavigation = options?.forceSameTabNavigation ?? true;\n\n await this.setActiveTabId(tabId);\n }\n\n public async setDestroyOptions(options: ChromePageDestroyOptions) {\n this.destroyOptions = options;\n }\n\n async destroy() {\n if (this.destroyOptions?.closeTab && this.newlyCreatedTabIds.length > 0) {\n this.onLogMessage('Closing all newly created tabs by bridge...', 'log');\n for (const tabId of this.newlyCreatedTabIds) {\n await chrome.tabs.remove(tabId);\n }\n this.newlyCreatedTabIds = [];\n }\n\n await super.destroy();\n\n if (this.bridgeClient) {\n this.bridgeClient.disconnect();\n this.bridgeClient = null;\n this.onDisconnect();\n }\n }\n}\n"],"names":["NEW_TAB_LOAD_TIMEOUT_MS","isBlankUrl","url","waitForTabNavigationComplete","tabId","targetUrl","timeoutMs","Promise","resolve","settled","finish","chrome","onUpdated","clearTimeout","timer","isReady","tab","currentUrl","id","_info","setTimeout","ExtensionBridgePageBrowserSide","ChromeExtensionProxyPage","endpoint","DefaultBridgeServerHost","DefaultBridgeServerPort","resolveConfirmationGate","BridgeClient","method","args","allowed","Error","BridgeEvent","MouseEvent","actionName","KeyboardEvent","result","e","errorMessage","options","undefined","activate","assert","tabs","serverEndpoint","onDisconnect","onLogMessage","forceSameTabNavigation","onConnectionRequest"],"mappings":";;;;;;;;;;;;;;AAmBA,MAAMA,0BAA0B;AAEhC,SAASC,WAAWC,GAAuB;IACzC,IAAI,CAACA,KAAK,OAAO;IACjB,OAAOA,AAAQ,kBAARA,OAAyBA,IAAI,UAAU,CAAC;AACjD;AAKA,SAASC,6BACPC,KAAa,EACbC,SAAiB,EACjBC,YAAYN,uBAAuB;IAEnC,OAAO,IAAIO,QAAQ,CAACC;QAClB,IAAIC,UAAU;QACd,MAAMC,SAAS;YACb,IAAID,SAAS;YACbA,UAAU;YACV,IAAI;gBACFE,OAAO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CAAC,EACnCC,eAGK,KAAO,CAAC,EACpBC,yBAAyB,IAAI,EACtBC,mBAA4C,CACnD;QACA,KAAK,CAACD,yBAAAA,iBAAAA,IAAAA,EAAAA,kBAAAA,KAAAA,IAAAA,iBAAAA,IAAAA,EAAAA,gBAAAA,KAAAA,IAAAA,iBAAAA,IAAAA,EAAAA,gBAAAA,KAAAA,IAAAA,iBAAAA,IAAAA,EAAAA,uBAAAA,KAAAA,IAnBR,uBAAO,gBAAP,SAEA,uBAAQ,kBAAR,SAEA,uBAAQ,sBAAR,SAGA,uBAAQ,uBAAR,cAGSH,cAAc,GAAdA,gBAAAA,IAAAA,CACAC,YAAY,GAAZA,cAAAA,IAAAA,CACAC,YAAY,GAAZA,cAAAA,IAAAA,CAKAE,mBAAmB,GAAnBA,qBAAAA,IAAAA,CAjBF,YAAY,GAAwB,WAInC,kBAAkB,GAAa,EAAE,OAGjC,mBAAmB,GAA4B;IAavD;AAsNF"}
|
|
1
|
+
{"version":3,"file":"bridge-mode/page-browser-side.mjs","sources":["../../../src/bridge-mode/page-browser-side.ts"],"sourcesContent":["import { assert } from '@midscene/shared/utils';\nimport ChromeExtensionProxyPage from '../chrome-extension/page';\nimport type {\n ChromePageDestroyOptions,\n KeyboardAction,\n MouseAction,\n} from '../web-page';\nimport {\n type BridgeConnectTabOptions,\n BridgeEvent,\n DefaultBridgeServerHost,\n DefaultBridgeServerPort,\n KeyboardEvent,\n MouseEvent,\n} from './common';\nimport { BridgeClient } from './io-client';\n\ndeclare const __VERSION__: string;\n\nconst NEW_TAB_LOAD_TIMEOUT_MS = 30_000;\n\nfunction isBlankUrl(url: string | undefined): boolean {\n if (!url) return true;\n return url === 'about:blank' || url.startsWith('chrome://newtab');\n}\n\n// Wait until the freshly created tab has navigated away from about:blank\n// and reached `status === 'complete'`. Resolves on timeout instead of\n// throwing so callers degrade to the existing lazy-attach behavior.\nfunction waitForTabNavigationComplete(\n tabId: number,\n targetUrl: string,\n timeoutMs = NEW_TAB_LOAD_TIMEOUT_MS,\n): Promise<void> {\n return new Promise((resolve) => {\n let settled = false;\n const finish = () => {\n if (settled) return;\n settled = true;\n try {\n chrome.tabs.onUpdated.removeListener(onUpdated);\n } catch {}\n clearTimeout(timer);\n resolve();\n };\n\n const isReady = (tab: chrome.tabs.Tab | undefined): boolean => {\n if (!tab) return false;\n if (tab.status !== 'complete') return false;\n const currentUrl = tab.url || tab.pendingUrl || '';\n // Skip the initial about:blank \"complete\" that fires before\n // the target URL navigation kicks in.\n if (isBlankUrl(currentUrl) && !isBlankUrl(targetUrl)) return false;\n return true;\n };\n\n const onUpdated = (\n id: number,\n _info: chrome.tabs.TabChangeInfo,\n tab: chrome.tabs.Tab,\n ) => {\n if (id !== tabId) return;\n if (isReady(tab)) finish();\n };\n\n chrome.tabs.onUpdated.addListener(onUpdated);\n const timer = setTimeout(finish, timeoutMs);\n\n // Handle the race where the tab already finished loading before\n // we registered the listener.\n chrome.tabs\n .get(tabId)\n .then((tab) => {\n if (isReady(tab)) finish();\n })\n .catch(() => {});\n });\n}\n\nexport class ExtensionBridgePageBrowserSide extends ChromeExtensionProxyPage {\n public bridgeClient: BridgeClient | null = null;\n\n private destroyOptions?: ChromePageDestroyOptions;\n\n private newlyCreatedTabIds: number[] = [];\n\n // Connection confirmation state\n private confirmationPromise: Promise<boolean> | null = null;\n\n constructor(\n public serverEndpoint?: string,\n public onDisconnect: () => void = () => {},\n public onLogMessage: (\n message: string,\n type: 'log' | 'status',\n ) => void = () => {},\n forceSameTabNavigation = true,\n public onConnectionRequest?: () => Promise<boolean>,\n ) {\n super(forceSameTabNavigation);\n }\n\n private async setupBridgeClient() {\n const endpoint =\n this.serverEndpoint ||\n `ws://${DefaultBridgeServerHost}:${DefaultBridgeServerPort}`;\n\n // Create confirmation gate BEFORE establishing connection,\n // so that any calls received immediately after connection are blocked\n // until user confirms. This prevents a race condition where server-side\n // queued calls bypass the confirmation dialog.\n let resolveConfirmationGate: (allowed: boolean) => void = () => {};\n if (this.onConnectionRequest) {\n this.confirmationPromise = new Promise<boolean>((resolve) => {\n resolveConfirmationGate = resolve;\n });\n }\n\n this.bridgeClient = new BridgeClient(\n endpoint,\n async (method, args: any[]) => {\n // Wait for user confirmation before processing any commands\n if (this.confirmationPromise) {\n const allowed = await this.confirmationPromise;\n if (!allowed) {\n throw new Error('Connection denied by user');\n }\n }\n\n this.onLogMessage(`bridge call from cli side: ${method}`, 'log');\n if (method === BridgeEvent.ConnectNewTabWithUrl) {\n return this.connectNewTabWithUrl.apply(\n this,\n args as unknown as [string],\n );\n }\n\n if (method === BridgeEvent.GetBrowserTabList) {\n return this.getBrowserTabList.apply(this, args as any);\n }\n\n if (method === BridgeEvent.SetActiveTabId) {\n return this.setActiveTabId.apply(this, args as any);\n }\n\n if (method === BridgeEvent.ConnectCurrentTab) {\n return this.connectCurrentTab.apply(this, args as any);\n }\n\n if (method === BridgeEvent.UpdateAgentStatus) {\n return this.onLogMessage(args[0] as string, 'status');\n }\n\n const tabId = await this.getActiveTabId();\n if (!tabId || tabId === 0) {\n throw new Error('no tab is connected');\n }\n\n // this.onLogMessage(`calling method: ${method}`);\n\n if (method.startsWith(MouseEvent.PREFIX)) {\n const actionName = method.split('.')[1] as keyof MouseAction;\n if (actionName === 'drag') {\n return this.mouse[actionName].apply(this.mouse, args as any);\n }\n return this.mouse[actionName].apply(this.mouse, args as any);\n }\n\n if (method.startsWith(KeyboardEvent.PREFIX)) {\n const actionName = method.split('.')[1] as keyof KeyboardAction;\n if (actionName === 'press') {\n return this.keyboard[actionName].apply(this.keyboard, args as any);\n }\n return this.keyboard[actionName].apply(this.keyboard, args as any);\n }\n\n // Generic method lookup. Methods like `setWaterFlowAnimationEnabled`\n // and `getWaterFlowAnimationEnabled` are inherited from\n // ChromeExtensionProxyPage and found via `this[method]`.\n if (!this[method as keyof ChromeExtensionProxyPage]) {\n this.onLogMessage(`method not found: ${method}`, 'log');\n return undefined;\n }\n\n try {\n // @ts-expect-error\n const result = await this[method as keyof ChromeExtensionProxyPage](\n ...args,\n );\n return result;\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : 'Unknown error';\n this.onLogMessage(\n `Error calling method: ${method}, ${errorMessage}`,\n 'log',\n );\n throw new Error(errorMessage, { cause: e });\n }\n },\n // on disconnect\n () => {\n return this.destroy();\n },\n );\n await this.bridgeClient.connect();\n\n // Show confirmation dialog after connection is established\n if (this.onConnectionRequest) {\n this.onLogMessage('Waiting for user confirmation...', 'log');\n const allowed = await this.onConnectionRequest();\n resolveConfirmationGate(allowed);\n this.confirmationPromise = null;\n\n if (!allowed) {\n this.onLogMessage('Connection denied by user', 'log');\n this.bridgeClient.disconnect();\n this.bridgeClient = null;\n throw new Error('Connection denied by user');\n }\n }\n\n this.onLogMessage(\n `Bridge connected, cli-side version v${this.bridgeClient.serverVersion}, browser-side version v${__VERSION__}`,\n 'log',\n );\n }\n\n public async connect() {\n return await this.setupBridgeClient();\n }\n\n public async connectNewTabWithUrl(\n url: string,\n options: BridgeConnectTabOptions = {\n forceSameTabNavigation: true,\n },\n ) {\n // Set the water-flow animation flag BEFORE any debugger commands are\n // sent (which trigger enableWaterFlowAnimation via sendCommandToDebugger).\n // Otherwise the animation gets injected during the connection flow\n // before the CLI side's setWaterFlowAnimationEnabled(false) arrives.\n if (options.enableWaterFlowAnimation !== undefined) {\n this.waterFlowAnimationEnabled = options.enableWaterFlowAnimation;\n }\n\n // Preserve the historical default: activate the new tab unless the caller opts into background mode.\n const activate = options.activateTab ?? true;\n const tab = await chrome.tabs.create({ url, active: activate });\n const tabId = tab.id;\n assert(tabId, 'failed to get tabId after creating a new tab');\n\n // new tab\n this.onLogMessage(`Creating new tab: ${url}`, 'log');\n this.newlyCreatedTabIds.push(tabId);\n\n this.forceSameTabNavigation = options?.forceSameTabNavigation ?? true;\n\n // chrome.tabs.create returns immediately with an about:blank target,\n // then navigates to `url`. If we attach the debugger during that\n // cross-origin transition Site Isolation will detach it again, leaving\n // the first CDP command to fail with \"Debugger is not attached to the\n // tab\". Wait for navigation to settle so the lazy attach lands on a\n // stable target.\n await waitForTabNavigationComplete(tabId, url);\n\n await this.setActiveTabId(tabId, { activate });\n }\n\n public async connectCurrentTab(\n options: BridgeConnectTabOptions = {\n forceSameTabNavigation: true,\n },\n ) {\n // Set the water-flow animation flag BEFORE any debugger commands are\n // sent (which trigger enableWaterFlowAnimation via sendCommandToDebugger).\n if (options.enableWaterFlowAnimation !== undefined) {\n this.waterFlowAnimationEnabled = options.enableWaterFlowAnimation;\n }\n\n const tabs =\n options?.tabId !== undefined\n ? [await chrome.tabs.get(options.tabId)]\n : await chrome.tabs.query({ active: true, currentWindow: true });\n const tabId = tabs[0]?.id;\n assert(tabId, 'failed to get tabId');\n\n this.onLogMessage(`Connected to current tab: ${tabs[0]?.url}`, 'log');\n\n this.forceSameTabNavigation = options?.forceSameTabNavigation ?? true;\n\n await this.setActiveTabId(tabId);\n }\n\n public async setDestroyOptions(options: ChromePageDestroyOptions) {\n this.destroyOptions = options;\n }\n\n async destroy() {\n if (this.destroyOptions?.closeTab && this.newlyCreatedTabIds.length > 0) {\n this.onLogMessage('Closing all newly created tabs by bridge...', 'log');\n for (const tabId of this.newlyCreatedTabIds) {\n await chrome.tabs.remove(tabId);\n }\n this.newlyCreatedTabIds = [];\n }\n\n await super.destroy();\n\n if (this.bridgeClient) {\n this.bridgeClient.disconnect();\n this.bridgeClient = null;\n this.onDisconnect();\n }\n }\n}\n"],"names":["NEW_TAB_LOAD_TIMEOUT_MS","isBlankUrl","url","waitForTabNavigationComplete","tabId","targetUrl","timeoutMs","Promise","resolve","settled","finish","chrome","onUpdated","clearTimeout","timer","isReady","tab","currentUrl","id","_info","setTimeout","ExtensionBridgePageBrowserSide","ChromeExtensionProxyPage","endpoint","DefaultBridgeServerHost","DefaultBridgeServerPort","resolveConfirmationGate","BridgeClient","method","args","allowed","Error","BridgeEvent","MouseEvent","actionName","KeyboardEvent","result","e","errorMessage","options","undefined","activate","assert","tabs","serverEndpoint","onDisconnect","onLogMessage","force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,CAAC,YAAY,CAAC,+CAA+C;YACjE,KAAK,MAAMnC,SAAS,IAAI,CAAC,kBAAkB,CACzC,MAAMO,OAAO,IAAI,CAAC,MAAM,CAACP;YAE3B,IAAI,CAAC,kBAAkB,GAAG,EAAE;QAC9B;QAEA,MAAM,KAAK,CAAC;QAEZ,IAAI,IAAI,CAAC,YAAY,EAAE;YACrB,IAAI,CAAC,YAAY,CAAC,UAAU;YAC5B,IAAI,CAAC,YAAY,GAAG;YACpB,IAAI,CAAC,YAAY;QACnB;IACF;IAhOA,YACSwC,cAAuB,EACvBC,eAA2B,KAAO,CAAC,EACnCC,eAGK,KAAO,CAAC,EACpBC,yBAAyB,IAAI,EACtBC,mBAA4C,CACnD;QACA,KAAK,CAACD,yBAAAA,iBAAAA,IAAAA,EAAAA,kBAAAA,KAAAA,IAAAA,iBAAAA,IAAAA,EAAAA,gBAAAA,KAAAA,IAAAA,iBAAAA,IAAAA,EAAAA,gBAAAA,KAAAA,IAAAA,iBAAAA,IAAAA,EAAAA,uBAAAA,KAAAA,IAnBR,uBAAO,gBAAP,SAEA,uBAAQ,kBAAR,SAEA,uBAAQ,sBAAR,SAGA,uBAAQ,uBAAR,cAGSH,cAAc,GAAdA,gBAAAA,IAAAA,CACAC,YAAY,GAAZA,cAAAA,IAAAA,CACAC,YAAY,GAAZA,cAAAA,IAAAA,CAKAE,mBAAmB,GAAnBA,qBAAAA,IAAAA,CAjBF,YAAY,GAAwB,WAInC,kBAAkB,GAAa,EAAE,OAGjC,mBAAmB,GAA4B;IAavD;AAsNF"}
|
package/dist/es/cli.mjs
CHANGED
|
@@ -18,7 +18,7 @@ Promise.resolve().then(()=>{
|
|
|
18
18
|
return runToolsCLI(tools, 'midscene-web', {
|
|
19
19
|
stripPrefix: 'web_',
|
|
20
20
|
argv: parsedOptions.argv,
|
|
21
|
-
version: "1.
|
|
21
|
+
version: "1.18.0",
|
|
22
22
|
extraCommands: createReportCliCommands()
|
|
23
23
|
});
|
|
24
24
|
}).catch((e)=>{
|
|
@@ -53,8 +53,10 @@ const parseCookieHeader = (raw, url)=>{
|
|
|
53
53
|
const parseCookieJson = (raw)=>{
|
|
54
54
|
try {
|
|
55
55
|
return JSON.parse(raw);
|
|
56
|
-
} catch
|
|
57
|
-
throw new TypeError('setCookies source must contain valid JSON or a Cookie header.'
|
|
56
|
+
} catch (cause) {
|
|
57
|
+
throw new TypeError('setCookies source must contain valid JSON or a Cookie header.', {
|
|
58
|
+
cause
|
|
59
|
+
});
|
|
58
60
|
}
|
|
59
61
|
};
|
|
60
62
|
const normalizeCookie = (candidate, defaultUrl, index)=>{
|
|
@@ -90,8 +92,10 @@ const resolveCookieInput = async (input, ctx, options)=>{
|
|
|
90
92
|
let env;
|
|
91
93
|
try {
|
|
92
94
|
env = await options.getEnv?.(ctx) ?? process.env;
|
|
93
|
-
} catch
|
|
94
|
-
throw new Error(`Failed to resolve cookie environment ${reference.name}
|
|
95
|
+
} catch (cause) {
|
|
96
|
+
throw new Error(`Failed to resolve cookie environment ${reference.name}.`, {
|
|
97
|
+
cause
|
|
98
|
+
});
|
|
95
99
|
}
|
|
96
100
|
const raw = env[reference.name];
|
|
97
101
|
if (!raw?.trim()) throw new Error(`Environment variable ${reference.name} is missing or blank.`);
|
|
@@ -107,8 +111,10 @@ const resolveCookieInput = async (input, ctx, options)=>{
|
|
|
107
111
|
context: ctx.context,
|
|
108
112
|
signal: ctx.signal
|
|
109
113
|
});
|
|
110
|
-
} catch
|
|
111
|
-
throw new Error(`Failed to resolve cookie profile ${reference.name}
|
|
114
|
+
} catch (cause) {
|
|
115
|
+
throw new Error(`Failed to resolve cookie profile ${reference.name}.`, {
|
|
116
|
+
cause
|
|
117
|
+
});
|
|
112
118
|
}
|
|
113
119
|
break;
|
|
114
120
|
case 'storage-state':
|
|
@@ -117,8 +123,10 @@ const resolveCookieInput = async (input, ctx, options)=>{
|
|
|
117
123
|
try {
|
|
118
124
|
const path = options.resolveStorageStatePath ? await options.resolveStorageStatePath(reference.name, ctx) : resolve(process.cwd(), reference.name);
|
|
119
125
|
contents = await readFile(path, 'utf8');
|
|
120
|
-
} catch
|
|
121
|
-
throw new Error(`Failed to read cookie storage state ${reference.name}
|
|
126
|
+
} catch (cause) {
|
|
127
|
+
throw new Error(`Failed to read cookie storage state ${reference.name}.`, {
|
|
128
|
+
cause
|
|
129
|
+
});
|
|
122
130
|
}
|
|
123
131
|
source = parseCookieJson(contents);
|
|
124
132
|
break;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"common/test-runner/cookies.mjs","sources":["../../../../src/common/test-runner/cookies.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { z } from 'zod/v4';\nimport { resolveWebUrl } from './utils';\n\ntype Awaitable<T> = T | Promise<T>;\n\nexport type CookieSourceReference =\n | { kind: 'env'; name: string }\n | { kind: 'profile'; name: string }\n | { kind: 'storage-state'; name: string };\n\nexport interface WebNodeContext<TContext> {\n input: unknown;\n context: TContext;\n signal: AbortSignal;\n}\n\nexport interface CookieProfileContext<TContext> {\n profile: string;\n context: TContext;\n signal: AbortSignal;\n}\n\nexport interface WebCookieSourceOptions<TAgent> {\n getEnv?(\n ctx: WebNodeContext<TAgent>,\n ): Awaitable<Readonly<Record<string, string | undefined>>>;\n getCookieProfile?(input: CookieProfileContext<TAgent>): Awaitable<unknown>;\n resolveStorageStatePath?(\n path: string,\n ctx: WebNodeContext<TAgent>,\n ): Awaitable<string>;\n}\n\nexport interface PortableWebCookie extends Record<string, unknown> {\n name: string;\n value: string;\n url?: string;\n domain?: string;\n path?: string;\n}\n\nexport const setCookiesInputSchema = z\n .strictObject({\n cookiesEnv: z\n .string()\n .regex(/^[A-Za-z_][A-Za-z0-9_]*$/)\n .optional()\n .describe(\n 'The environment variable containing a Cookie header, cookie array JSON, or browser storage-state JSON.',\n ),\n profile: z\n .string()\n .regex(/\\S/)\n .optional()\n .describe('A cookie profile resolved by getCookieProfile().'),\n storageStatePath: z\n .string()\n .regex(/\\S/)\n .optional()\n .describe('A path to a browser storage-state JSON file.'),\n url: z\n .string()\n .url()\n .optional()\n .describe(\n 'The HTTP(S) URL used to scope Cookie-header values or cookies without domain/path.',\n ),\n })\n .superRefine((input, ctx) => {\n const sourceCount = [\n input.cookiesEnv,\n input.profile,\n input.storageStatePath,\n ].filter((value) => value !== undefined).length;\n if (sourceCount !== 1) {\n ctx.addIssue({\n code: 'custom',\n message:\n 'exactly one of cookiesEnv, profile, and storageStatePath is required',\n });\n }\n });\n\nexport type SetCookiesNodeInput = z.infer<typeof setCookiesInputSchema>;\n\nexport interface SetCookiesNodeResult {\n source: CookieSourceReference['kind'];\n sourceName: string;\n count: number;\n}\n\nconst toCookieSourceReference = (\n input: SetCookiesNodeInput,\n): CookieSourceReference => {\n if (input.cookiesEnv !== undefined) {\n return { kind: 'env', name: input.cookiesEnv };\n }\n if (input.profile !== undefined) {\n return { kind: 'profile', name: input.profile };\n }\n if (input.storageStatePath !== undefined) {\n return { kind: 'storage-state', name: input.storageStatePath };\n }\n throw new TypeError('setCookies requires one cookie source.');\n};\n\nconst parseCookieHeader = (raw: string, url: string | undefined) => {\n if (url === undefined) {\n throw new TypeError(\n 'setCookies.url is required when cookiesEnv contains a Cookie header.',\n );\n }\n const segments = raw\n .split(';')\n .map((segment) => segment.trim())\n .filter(Boolean);\n if (segments.length === 0) {\n throw new TypeError('setCookies Cookie header contains no cookies.');\n }\n return segments.map((segment) => {\n const separator = segment.indexOf('=');\n if (separator <= 0) {\n throw new TypeError(\n 'setCookies Cookie header contains an invalid name/value pair.',\n );\n }\n const name = segment.slice(0, separator).trim();\n const value = segment.slice(separator + 1).trim();\n if (!name) {\n throw new TypeError('setCookies Cookie header contains an empty name.');\n }\n return { name, value, url } satisfies PortableWebCookie;\n });\n};\n\nconst parseCookieJson = (raw: string): unknown => {\n try {\n return JSON.parse(raw);\n } catch {\n throw new TypeError(\n 'setCookies source must contain valid JSON or a Cookie header.',\n );\n }\n};\n\nconst normalizeCookie = (\n candidate: unknown,\n defaultUrl: string | undefined,\n index: number,\n): PortableWebCookie => {\n if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {\n throw new TypeError(\n `setCookies cookie at index ${index} must be an object.`,\n );\n }\n const cookie = candidate as Record<string, unknown>;\n if (typeof cookie.name !== 'string' || !cookie.name.trim()) {\n throw new TypeError(\n `setCookies cookie at index ${index} requires a non-blank name.`,\n );\n }\n if (typeof cookie.value !== 'string') {\n throw new TypeError(\n `setCookies cookie at index ${index} requires a string value.`,\n );\n }\n\n const normalized = { ...cookie } as PortableWebCookie;\n const hasUrl = typeof cookie.url === 'string' && cookie.url.length > 0;\n const hasDomain =\n typeof cookie.domain === 'string' && cookie.domain.length > 0;\n if (!hasUrl && !hasDomain) {\n if (defaultUrl === undefined) {\n throw new TypeError(\n `setCookies cookie at index ${index} requires url or domain, or setCookies.url must be provided.`,\n );\n }\n normalized.url = defaultUrl;\n }\n if (hasDomain && typeof cookie.path !== 'string') normalized.path = '/';\n return normalized;\n};\n\nconst normalizeCookies = (\n source: unknown,\n defaultUrl: string | undefined,\n): PortableWebCookie[] => {\n const candidates = Array.isArray(source)\n ? source\n : source &&\n typeof source === 'object' &&\n Array.isArray((source as { cookies?: unknown }).cookies)\n ? (source as { cookies: unknown[] }).cookies\n : undefined;\n if (!candidates) {\n throw new TypeError(\n 'setCookies JSON must be a cookie array or an object with a cookies array.',\n );\n }\n if (candidates.length === 0) {\n throw new TypeError('setCookies source contains no cookies.');\n }\n return candidates.map((cookie, index) =>\n normalizeCookie(cookie, defaultUrl, index),\n );\n};\n\nexport const resolveCookieInput = async <TAgent>(\n input: SetCookiesNodeInput,\n ctx: WebNodeContext<TAgent>,\n options: WebCookieSourceOptions<TAgent>,\n): Promise<{\n cookies: PortableWebCookie[];\n result: SetCookiesNodeResult;\n}> => {\n const defaultUrl =\n input.url === undefined\n ? undefined\n : resolveWebUrl(input.url, undefined, 'setCookies.url');\n const reference = toCookieSourceReference(input);\n let source: unknown;\n switch (reference.kind) {\n case 'env': {\n let env: Readonly<Record<string, string | undefined>>;\n try {\n env = (await options.getEnv?.(ctx)) ?? process.env;\n } catch {\n throw new Error(\n `Failed to resolve cookie environment ${reference.name}; the original error was redacted because it may contain cookie values.`,\n );\n }\n const raw = env[reference.name];\n if (!raw?.trim()) {\n throw new Error(\n `Environment variable ${reference.name} is missing or blank.`,\n );\n }\n const trimmed = raw.trim();\n source = /^[\\[{]/.test(trimmed)\n ? parseCookieJson(trimmed)\n : parseCookieHeader(trimmed, defaultUrl);\n break;\n }\n case 'profile': {\n if (!options.getCookieProfile) {\n throw new Error(\n 'setCookies.profile requires a configured getCookieProfile callback.',\n );\n }\n try {\n source = await options.getCookieProfile({\n profile: reference.name,\n context: ctx.context,\n signal: ctx.signal,\n });\n } catch {\n throw new Error(\n `Failed to resolve cookie profile ${reference.name}; the original error was redacted because it may contain cookie values.`,\n );\n }\n break;\n }\n case 'storage-state': {\n let contents: string;\n try {\n const path = options.resolveStorageStatePath\n ? await options.resolveStorageStatePath(reference.name, ctx)\n : resolve(process.cwd(), reference.name);\n contents = await readFile(path, 'utf8');\n } catch {\n throw new Error(\n `Failed to read cookie storage state ${reference.name}; the original error was redacted because it may contain cookie values.`,\n );\n }\n source = parseCookieJson(contents);\n break;\n }\n }\n const cookies = normalizeCookies(source, defaultUrl);\n return {\n cookies,\n result: {\n source: reference.kind,\n sourceName: reference.name,\n count: cookies.length,\n },\n };\n};\n"],"names":["setCookiesInputSchema","z","input","ctx","sourceCount","value","undefined","toCookieSourceReference","TypeError","parseCookieHeader","raw","url","segments","segment","Boolean","separator","name","parseCookieJson","JSON","normalizeCookie","candidate","defaultUrl","index","Array","cookie","normalized","hasUrl","hasDomain","normalizeCookies","source","candidates","resolveCookieInput","options","resolveWebUrl","reference","env","process","Error","trimmed","contents","path","resolve","readFile","cookies"],"mappings":";;;;AA2CO,MAAMA,wBAAwBC,EAAAA,YACtB,CAAC;IACZ,YAAYA,EAAAA,MACH,GACN,KAAK,CA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MACR;YAGJ,IAAI;gBACFR,SAAS,MAAMG,QAAQ,gBAAgB,CAAC;oBACtC,SAASE,UAAU,IAAI;oBACvB,SAAS/B,IAAI,OAAO;oBACpB,QAAQA,IAAI,MAAM;gBACpB;YACF,EAAE,OAAM;gBACN,MAAM,IAAIkC,MACR,CAAC,iCAAiC,EAAEH,UAAU,IAAI,CAAC,uEAAuE,CAAC;YAE/H;YACA;QAEF,KAAK;YAAiB;gBACpB,IAAIK;gBACJ,IAAI;oBACF,MAAMC,OAAOR,QAAQ,uBAAuB,GACxC,MAAMA,QAAQ,uBAAuB,CAACE,UAAU,IAAI,EAAE/B,OACtDsC,QAAQL,QAAQ,GAAG,IAAIF,UAAU,IAAI;oBACzCK,WAAW,MAAMG,SAASF,MAAM;gBAClC,EAAE,OAAM;oBACN,MAAM,IAAIH,MACR,CAAC,oCAAoC,EAAEH,UAAU,IAAI,CAAC,uEAAuE,CAAC;gBAElI;gBACAL,SAASZ,gBAAgBsB;gBACzB;YACF;IACF;IACA,MAAMI,UAAUf,iBAAiBC,QAAQR;IACzC,OAAO;QACLsB;QACA,QAAQ;YACN,QAAQT,UAAU,IAAI;YACtB,YAAYA,UAAU,IAAI;YAC1B,OAAOS,QAAQ,MAAM;QACvB;IACF;AACF"}
|
|
1
|
+
{"version":3,"file":"common/test-runner/cookies.mjs","sources":["../../../../src/common/test-runner/cookies.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { z } from 'zod/v4';\nimport { resolveWebUrl } from './utils';\n\ntype Awaitable<T> = T | Promise<T>;\n\nexport type CookieSourceReference =\n | { kind: 'env'; name: string }\n | { kind: 'profile'; name: string }\n | { kind: 'storage-state'; name: string };\n\nexport interface WebNodeContext<TContext> {\n input: unknown;\n context: TContext;\n signal: AbortSignal;\n}\n\nexport interface CookieProfileContext<TContext> {\n profile: string;\n context: TContext;\n signal: AbortSignal;\n}\n\nexport interface WebCookieSourceOptions<TAgent> {\n getEnv?(\n ctx: WebNodeContext<TAgent>,\n ): Awaitable<Readonly<Record<string, string | undefined>>>;\n getCookieProfile?(input: CookieProfileContext<TAgent>): Awaitable<unknown>;\n resolveStorageStatePath?(\n path: string,\n ctx: WebNodeContext<TAgent>,\n ): Awaitable<string>;\n}\n\nexport interface PortableWebCookie extends Record<string, unknown> {\n name: string;\n value: string;\n url?: string;\n domain?: string;\n path?: string;\n}\n\nexport const setCookiesInputSchema = z\n .strictObject({\n cookiesEnv: z\n .string()\n .regex(/^[A-Za-z_][A-Za-z0-9_]*$/)\n .optional()\n .describe(\n 'The environment variable containing a Cookie header, cookie array JSON, or browser storage-state JSON.',\n ),\n profile: z\n .string()\n .regex(/\\S/)\n .optional()\n .describe('A cookie profile resolved by getCookieProfile().'),\n storageStatePath: z\n .string()\n .regex(/\\S/)\n .optional()\n .describe('A path to a browser storage-state JSON file.'),\n url: z\n .string()\n .url()\n .optional()\n .describe(\n 'The HTTP(S) URL used to scope Cookie-header values or cookies without domain/path.',\n ),\n })\n .superRefine((input, ctx) => {\n const sourceCount = [\n input.cookiesEnv,\n input.profile,\n input.storageStatePath,\n ].filter((value) => value !== undefined).length;\n if (sourceCount !== 1) {\n ctx.addIssue({\n code: 'custom',\n message:\n 'exactly one of cookiesEnv, profile, and storageStatePath is required',\n });\n }\n });\n\nexport type SetCookiesNodeInput = z.infer<typeof setCookiesInputSchema>;\n\nexport interface SetCookiesNodeResult {\n source: CookieSourceReference['kind'];\n sourceName: string;\n count: number;\n}\n\nconst toCookieSourceReference = (\n input: SetCookiesNodeInput,\n): CookieSourceReference => {\n if (input.cookiesEnv !== undefined) {\n return { kind: 'env', name: input.cookiesEnv };\n }\n if (input.profile !== undefined) {\n return { kind: 'profile', name: input.profile };\n }\n if (input.storageStatePath !== undefined) {\n return { kind: 'storage-state', name: input.storageStatePath };\n }\n throw new TypeError('setCookies requires one cookie source.');\n};\n\nconst parseCookieHeader = (raw: string, url: string | undefined) => {\n if (url === undefined) {\n throw new TypeError(\n 'setCookies.url is required when cookiesEnv contains a Cookie header.',\n );\n }\n const segments = raw\n .split(';')\n .map((segment) => segment.trim())\n .filter(Boolean);\n if (segments.length === 0) {\n throw new TypeError('setCookies Cookie header contains no cookies.');\n }\n return segments.map((segment) => {\n const separator = segment.indexOf('=');\n if (separator <= 0) {\n throw new TypeError(\n 'setCookies Cookie header contains an invalid name/value pair.',\n );\n }\n const name = segment.slice(0, separator).trim();\n const value = segment.slice(separator + 1).trim();\n if (!name) {\n throw new TypeError('setCookies Cookie header contains an empty name.');\n }\n return { name, value, url } satisfies PortableWebCookie;\n });\n};\n\nconst parseCookieJson = (raw: string): unknown => {\n try {\n return JSON.parse(raw);\n } catch (cause) {\n throw new TypeError(\n 'setCookies source must contain valid JSON or a Cookie header.',\n { cause },\n );\n }\n};\n\nconst normalizeCookie = (\n candidate: unknown,\n defaultUrl: string | undefined,\n index: number,\n): PortableWebCookie => {\n if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {\n throw new TypeError(\n `setCookies cookie at index ${index} must be an object.`,\n );\n }\n const cookie = candidate as Record<string, unknown>;\n if (typeof cookie.name !== 'string' || !cookie.name.trim()) {\n throw new TypeError(\n `setCookies cookie at index ${index} requires a non-blank name.`,\n );\n }\n if (typeof cookie.value !== 'string') {\n throw new TypeError(\n `setCookies cookie at index ${index} requires a string value.`,\n );\n }\n\n const normalized = { ...cookie } as PortableWebCookie;\n const hasUrl = typeof cookie.url === 'string' && cookie.url.length > 0;\n const hasDomain =\n typeof cookie.domain === 'string' && cookie.domain.length > 0;\n if (!hasUrl && !hasDomain) {\n if (defaultUrl === undefined) {\n throw new TypeError(\n `setCookies cookie at index ${index} requires url or domain, or setCookies.url must be provided.`,\n );\n }\n normalized.url = defaultUrl;\n }\n if (hasDomain && typeof cookie.path !== 'string') normalized.path = '/';\n return normalized;\n};\n\nconst normalizeCookies = (\n source: unknown,\n defaultUrl: string | undefined,\n): PortableWebCookie[] => {\n const candidates = Array.isArray(source)\n ? source\n : source &&\n typeof source === 'object' &&\n Array.isArray((source as { cookies?: unknown }).cookies)\n ? (source as { cookies: unknown[] }).cookies\n : undefined;\n if (!candidates) {\n throw new TypeError(\n 'setCookies JSON must be a cookie array or an object with a cookies array.',\n );\n }\n if (candidates.length === 0) {\n throw new TypeError('setCookies source contains no cookies.');\n }\n return candidates.map((cookie, index) =>\n normalizeCookie(cookie, defaultUrl, index),\n );\n};\n\nexport const resolveCookieInput = async <TAgent>(\n input: SetCookiesNodeInput,\n ctx: WebNodeContext<TAgent>,\n options: WebCookieSourceOptions<TAgent>,\n): Promise<{\n cookies: PortableWebCookie[];\n result: SetCookiesNodeResult;\n}> => {\n const defaultUrl =\n input.url === undefined\n ? undefined\n : resolveWebUrl(input.url, undefined, 'setCookies.url');\n const reference = toCookieSourceReference(input);\n let source: unknown;\n switch (reference.kind) {\n case 'env': {\n let env: Readonly<Record<string, string | undefined>>;\n try {\n env = (await options.getEnv?.(ctx)) ?? process.env;\n } catch (cause) {\n throw new Error(\n `Failed to resolve cookie environment ${reference.name}.`,\n { cause },\n );\n }\n const raw = env[reference.name];\n if (!raw?.trim()) {\n throw new Error(\n `Environment variable ${reference.name} is missing or blank.`,\n );\n }\n const trimmed = raw.trim();\n source = /^[\\[{]/.test(trimmed)\n ? parseCookieJson(trimmed)\n : parseCookieHeader(trimmed, defaultUrl);\n break;\n }\n case 'profile': {\n if (!options.getCookieProfile) {\n throw new Error(\n 'setCookies.profile requires a configured getCookieProfile callback.',\n );\n }\n try {\n source = await options.getCookieProfile({\n profile: reference.name,\n context: ctx.context,\n signal: ctx.signal,\n });\n } catch (cause) {\n throw new Error(`Failed to resolve cookie profile ${reference.name}.`, {\n cause,\n });\n }\n break;\n }\n case 'storage-state': {\n let contents: string;\n try {\n const path = options.resolveStorageStatePath\n ? await options.resolveStorageStatePath(reference.name, ctx)\n : resolve(process.cwd(), reference.name);\n contents = await readFile(path, 'utf8');\n } catch (cause) {\n throw new Error(\n `Failed to read cookie storage state ${reference.name}.`,\n { cause },\n );\n }\n source = parseCookieJson(contents);\n break;\n }\n }\n const cookies = normalizeCookies(source, defaultUrl);\n return {\n cookies,\n result: {\n source: reference.kind,\n sourceName: reference.name,\n count: cookies.length,\n },\n };\n};\n"],"names":["setCookiesInputSchema","z","input","ctx","sourceCount","value","undefined","toCookieSourceReference","TypeError","parseCookieHeader","raw","url","segments","segment","Boolean","separator","name","parseCookieJson","JSON","cause","normalizeCookie","candidate","defaultUrl","index","Array","cookie","normalized","hasUrl","hasDomain","normalizeCookies","source","candidates","resolveCookieInput","options","resolveWebUrl","reference","env","process","Error","trimmed","contents","path","resolve","readFile","cookies"],"mappings":";;;;AA2CO,MAAMA,wBAAwBC,EAAAA,YACtB,CAAC;IACZ,YAAYA,EAAAA,MACH,GACN,KAAK,CAAC,4BACN,QAAQ,GACR,QAAQ,CACP;IAEJ,SAASA,EAAAA,MACA,GACN,KAAK,CAAC,MACN,QAAQ,GACR,QAAQ,CAAC;IACZ,kBAAkBA,EAAAA,MACT,GACN,KAAK,CAAC,MACN,QAAQ,GACR,QAAQ,CAAC;IACZ,KAAKA,EAAAA,MACI,GACN,GAAG,GACH,QAAQ,GACR,QAAQ,CACP;AAEN,GACC,WAAW,CAAC,CAACC,OAAOC;IACnB,MAAMC,cAAc;QAClBF,MAAM,UAAU;QAChBA,MAAM,OAAO;QACbA,MAAM,gBAAgB;KACvB,CAAC,MAAM,CAAC,CAACG,QAAUA,AAAUC,WAAVD,OAAqB,MAAM;IAC/C,IAAID,AAAgB,MAAhBA,aACFD,IAAI,QAAQ,CAAC;QACX,MAAM;QACN,SACE;IACJ;AAEJ;AAUF,MAAMI,0BAA0B,CAC9BL;IAEA,IAAIA,AAAqBI,WAArBJ,MAAM,UAAU,EAClB,OAAO;QAAE,MAAM;QAAO,MAAMA,MAAM,UAAU;IAAC;IAE/C,IAAIA,AAAkBI,WAAlBJ,MAAM,OAAO,EACf,OAAO;QAAE,MAAM;QAAW,MAAMA,MAAM,OAAO;IAAC;IAEhD,IAAIA,AAA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BC,QAAQR;IACzC,OAAO;QACLsB;QACA,QAAQ;YACN,QAAQT,UAAU,IAAI;YACtB,YAAYA,UAAU,IAAI;YAC1B,OAAOS,QAAQ,MAAM;QACvB;IACF;AACF"}
|
|
@@ -78,8 +78,10 @@ const createWebTestRunnerNodeDefinitions = (adapter)=>{
|
|
|
78
78
|
throwIfAborted(executionContext.signal, 'setCookies');
|
|
79
79
|
try {
|
|
80
80
|
await driver.setCookies(cookies);
|
|
81
|
-
} catch
|
|
82
|
-
throw new Error(`Failed to set ${cookies.length} browser cookie(s)
|
|
81
|
+
} catch (cause) {
|
|
82
|
+
throw new Error(`Failed to set ${cookies.length} browser cookie(s).`, {
|
|
83
|
+
cause
|
|
84
|
+
});
|
|
83
85
|
}
|
|
84
86
|
return {
|
|
85
87
|
summary: `Set ${result.count} browser cookie(s) from ${result.source} ${result.sourceName}`,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"common/test-runner/nodes.mjs","sources":["../../../../src/common/test-runner/nodes.ts"],"sourcesContent":["import type { AgentTestRunnerNodeDefinition } from '@midscene/core/agent';\nimport { z } from 'zod/v4';\nimport {\n type SetCookiesNodeResult,\n resolveCookieInput,\n setCookiesInputSchema,\n} from './cookies';\nimport type {\n WebCookieFilters,\n WebTestDriverAdapter,\n WebTestRunnerOptions,\n WebViewportSize,\n} from './driver';\nimport { resolveWebUrl, throwIfAborted } from './utils';\n\nconst DEFAULT_NAVIGATION_TIMEOUT_MS = 60_000;\nconst DEFAULT_WAIT_UNTIL = 'domcontentloaded' as const;\n\nexport const gotoUrlInputSchema = z.strictObject({\n url: z\n .string()\n .min(1)\n .describe(\n 'An absolute HTTP(S) URL or a path relative to testRunner.baseURL or the current page URL.',\n ),\n waitUntil: z\n .enum([\n 'commit',\n 'domcontentloaded',\n 'load',\n 'networkidle',\n 'networkidle0',\n 'networkidle2',\n ])\n .default(DEFAULT_WAIT_UNTIL)\n .describe(\n 'The navigation lifecycle event. domcontentloaded, load, and networkidle are portable across browser drivers.',\n ),\n timeoutMs: z\n .number()\n .positive()\n .max(10 * 60_000)\n .default(DEFAULT_NAVIGATION_TIMEOUT_MS)\n .describe('The navigation timeout in milliseconds.'),\n});\n\nexport type GotoUrlNodeInput = z.infer<typeof gotoUrlInputSchema>;\n\nexport interface GotoUrlNodeResult {\n url: string;\n status: number | null;\n title: string;\n}\n\nexport const clearCookiesInputSchema = z.strictObject({\n name: z.string().regex(/\\S/).optional().describe('Cookie name to clear.'),\n domain: z.string().regex(/\\S/).optional().describe('Cookie domain to clear.'),\n path: z.string().regex(/\\S/).optional().describe('Cookie path to clear.'),\n});\n\nexport type ClearCookiesNodeInput = z.infer<typeof clearCookiesInputSchema>;\n\nexport const setViewportSizeInputSchema = z.strictObject({\n width: z.number().int().positive().describe('Viewport width in CSS pixels.'),\n height: z\n .number()\n .int()\n .positive()\n .describe('Viewport height in CSS pixels.'),\n});\n\nexport type SetViewportSizeNodeInput = z.infer<\n typeof setViewportSizeInputSchema\n>;\n\nconst resolveNavigationUrl = (\n target: string,\n currentUrl: string,\n configuredBase: string | undefined,\n): string => {\n const trimmed = target.trim();\n if (!trimmed) throw new TypeError('gotoUrl.url must not be blank.');\n if (/^[a-z][a-z\\d+.-]*:/i.test(trimmed)) {\n return resolveWebUrl(trimmed, undefined, 'gotoUrl.url');\n }\n if (configuredBase !== undefined) {\n return resolveWebUrl(trimmed, configuredBase, 'gotoUrl.url');\n }\n if (!/^https?:\\/\\//i.test(currentUrl)) {\n throw new TypeError(\n `gotoUrl.url cannot resolve a relative URL from ${JSON.stringify(currentUrl)}. Use an absolute HTTP(S) URL for the first navigation or configure testRunner.baseURL.`,\n );\n }\n return resolveWebUrl(trimmed, currentUrl, 'gotoUrl.url');\n};\n\n/** Create the browser-neutral built-in Web Nodes for one browser adapter. */\nexport const createWebTestRunnerNodeDefinitions = <\n TAgent,\n TOptions extends WebTestRunnerOptions<TAgent>,\n>(\n adapter: WebTestDriverAdapter<TAgent, TOptions>,\n): readonly AgentTestRunnerNodeDefinition[] => {\n const gotoUrlNode: AgentTestRunnerNodeDefinition<\n z.output<typeof gotoUrlInputSchema>,\n GotoUrlNodeResult\n > = {\n name: 'gotoUrl',\n title: 'Open a Web URL',\n description:\n 'Navigate the current browser Page to an absolute HTTP(S) URL or a path relative to testRunner.baseURL or the current page URL.',\n stringInputKey: 'url',\n inputSchema: gotoUrlInputSchema,\n async execute(agent, input, executionContext) {\n const runtimeAgent = adapter.requireAgent(agent);\n const driver = adapter.createDriver(runtimeAgent);\n throwIfAborted(executionContext.signal, 'gotoUrl');\n const url = resolveNavigationUrl(\n input.url,\n driver.currentUrl(),\n adapter.getOptions(runtimeAgent)?.baseURL ?? driver.baseUrl(),\n );\n const response = await driver.goto(url, {\n waitUntil: input.waitUntil,\n timeoutMs: input.timeoutMs,\n });\n throwIfAborted(executionContext.signal, 'gotoUrl');\n const result = {\n url: driver.currentUrl(),\n status: response.status,\n title: await driver.title(),\n };\n return { summary: `Navigated to ${result.url}`, data: result };\n },\n };\n\n const setCookiesNode: AgentTestRunnerNodeDefinition<\n z.output<typeof setCookiesInputSchema>,\n SetCookiesNodeResult\n > = {\n name: 'setCookies',\n title: 'Set browser cookies',\n description:\n 'Load cookies from an environment variable, configured profile, or browser storage-state file without persisting cookie values in workflow input or output.',\n stringInputKey: false,\n inputSchema: setCookiesInputSchema,\n async execute(agent, input, executionContext) {\n const runtimeAgent = adapter.requireAgent(agent);\n const driver = adapter.createDriver(runtimeAgent);\n throwIfAborted(executionContext.signal, 'setCookies');\n const { cookies, result } = await resolveCookieInput(\n input,\n { ...executionContext, input, context: runtimeAgent },\n adapter.getOptions(runtimeAgent) ?? {},\n );\n throwIfAborted(executionContext.signal, 'setCookies');\n try {\n await driver.setCookies(cookies);\n } catch {\n throw new Error(\n `Failed to set ${cookies.length} browser cookie(s); the browser error was redacted because it may contain cookie values.`,\n );\n }\n return {\n summary: `Set ${result.count} browser cookie(s) from ${result.source} ${result.sourceName}`,\n data: result,\n };\n },\n };\n\n const clearCookiesNode: AgentTestRunnerNodeDefinition<\n z.output<typeof clearCookiesInputSchema>,\n { filters: WebCookieFilters }\n > = {\n name: 'clearCookies',\n title: 'Clear browser cookies',\n description:\n 'Clear all cookies from the current browser context, or only cookies matching name, domain, or path.',\n stringInputKey: false,\n inputSchema: clearCookiesInputSchema,\n async execute(agent, input, executionContext) {\n const runtimeAgent = adapter.requireAgent(agent);\n const driver = adapter.createDriver(runtimeAgent);\n throwIfAborted(executionContext.signal, 'clearCookies');\n const filters: WebCookieFilters = { ...input };\n await driver.clearCookies(filters);\n const filterNames = Object.keys(filters);\n return {\n summary:\n filterNames.length === 0\n ? 'Cleared all browser cookies'\n : `Cleared browser cookies matching ${filterNames.join(', ')}`,\n data: { filters },\n };\n },\n };\n\n const setViewportSizeNode: AgentTestRunnerNodeDefinition<\n z.output<typeof setViewportSizeInputSchema>,\n WebViewportSize\n > = {\n name: 'setViewportSize',\n title: 'Set the browser viewport size',\n description:\n 'Set the current browser Page viewport size in CSS pixels and return the effective size.',\n stringInputKey: false,\n inputSchema: setViewportSizeInputSchema,\n async execute(agent, input, executionContext) {\n const runtimeAgent = adapter.requireAgent(agent);\n const driver = adapter.createDriver(runtimeAgent);\n throwIfAborted(executionContext.signal, 'setViewportSize');\n const viewport = await driver.setViewportSize(input);\n return {\n summary: `Set viewport to ${viewport.width}x${viewport.height}`,\n data: viewport,\n };\n },\n };\n\n return [gotoUrlNode, setCookiesNode, clearCookiesNode, setViewportSizeNode];\n};\n\nexport { setCookiesInputSchema };\nexport type { SetCookiesNodeInput, SetCookiesNodeResult } from './cookies';\n"],"names":["DEFAULT_NAVIGATION_TIMEOUT_MS","DEFAULT_WAIT_UNTIL","gotoUrlInputSchema","z","clearCookiesInputSchema","setViewportSizeInputSchema","resolveNavigationUrl","target","currentUrl","configuredBase","trimmed","TypeError","resolveWebUrl","undefined","JSON","createWebTestRunnerNodeDefinitions","adapter","gotoUrlNode","agent","input","executionContext","runtimeAgent","driver","throwIfAborted","url","response","result","setCookiesNode","setCookiesInputSchema","cookies","resolveCookieInput","Error","clearCookiesNode","filters","filterNames","Object","setViewportSizeNode","viewport"],"mappings":";;;AAeA,MAAMA,gCAAgC;AACtC,MAAMC,qBAAqB;AAEpB,MAAMC,qBAAqBC,EAAE,YAAY,CAAC;IAC/C,KAAKA,EAAAA,MACI,GACN,GAAG,CAAC,GACJ,QAAQ,CACP;IAEJ,WAAWA,CAAC,CAADA,OACJ,CAAC;QACJ;QACA;QACA;QACA;QACA;QACA;KACD,EACA,OAAO,CAACF,oBACR,QAAQ,CACP;IAEJ,WAAWE,EAAAA,MACF,GACN,QAAQ,GACR,GAAG,CAAC,QACJ,OAAO,CAACH,+BACR,QAAQ,CAAC;AACd;AAUO,MAAMI,0BAA0BD,EAAE,YAAY,CAAC;IACpD,MAAMA,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,QAAQ,GAAG,QAAQ,CAAC;IACjD,QAAQA,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,QAAQ,GAAG,QAAQ,CAAC;IACnD,MAAMA,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,QAAQ,GAAG,QAAQ,CAAC;AACnD;AAIO,MAAME,6BAA6BF,EAAE,YAAY,CAAC;IACvD,OAAOA,EAAE,MAAM,GAAG,GAAG,GAAG,QAAQ,GAAG,QAAQ,CAAC;IAC5C,QAAQA,EAAAA,MACC,GACN,GAAG,GACH,QAAQ,GACR,QAAQ,CAAC;AACd;AAMA,MAAMG,uBAAuB,CAC3BC,QACAC,YACAC;IAEA,MAAMC,UAAUH,OAAO,IAAI;IAC3B,IAAI,CAACG,SAAS,MAAM,IAAIC,UAAU;IAClC,IAAI,sBAAsB,IAAI,CAACD,UAC7B,OAAOE,cAAcF,SAASG,QAAW;IAE3C,IAAIJ,AAAmBI,WAAnBJ,gBACF,OAAOG,cAAcF,SAASD,gBAAgB;IAEhD,IAAI,CAAC,gBAAgB,IAAI,CAACD,aACxB,MAAM,IAAIG,UACR,CAAC,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EAAEA,SAAS,MAAM,EAAE;gBAC/D,MAAMA;YACR;QACF;IACF;IAEA,OAAO;QAACpB;QAAaU;QAAgBK;QAAkBI;KAAoB;AAC7E"}
|
|
1
|
+
{"version":3,"file":"common/test-runner/nodes.mjs","sources":["../../../../src/common/test-runner/nodes.ts"],"sourcesContent":["import type { AgentTestRunnerNodeDefinition } from '@midscene/core/agent';\nimport { z } from 'zod/v4';\nimport {\n type SetCookiesNodeResult,\n resolveCookieInput,\n setCookiesInputSchema,\n} from './cookies';\nimport type {\n WebCookieFilters,\n WebTestDriverAdapter,\n WebTestRunnerOptions,\n WebViewportSize,\n} from './driver';\nimport { resolveWebUrl, throwIfAborted } from './utils';\n\nconst DEFAULT_NAVIGATION_TIMEOUT_MS = 60_000;\nconst DEFAULT_WAIT_UNTIL = 'domcontentloaded' as const;\n\nexport const gotoUrlInputSchema = z.strictObject({\n url: z\n .string()\n .min(1)\n .describe(\n 'An absolute HTTP(S) URL or a path relative to testRunner.baseURL or the current page URL.',\n ),\n waitUntil: z\n .enum([\n 'commit',\n 'domcontentloaded',\n 'load',\n 'networkidle',\n 'networkidle0',\n 'networkidle2',\n ])\n .default(DEFAULT_WAIT_UNTIL)\n .describe(\n 'The navigation lifecycle event. domcontentloaded, load, and networkidle are portable across browser drivers.',\n ),\n timeoutMs: z\n .number()\n .positive()\n .max(10 * 60_000)\n .default(DEFAULT_NAVIGATION_TIMEOUT_MS)\n .describe('The navigation timeout in milliseconds.'),\n});\n\nexport type GotoUrlNodeInput = z.infer<typeof gotoUrlInputSchema>;\n\nexport interface GotoUrlNodeResult {\n url: string;\n status: number | null;\n title: string;\n}\n\nexport const clearCookiesInputSchema = z.strictObject({\n name: z.string().regex(/\\S/).optional().describe('Cookie name to clear.'),\n domain: z.string().regex(/\\S/).optional().describe('Cookie domain to clear.'),\n path: z.string().regex(/\\S/).optional().describe('Cookie path to clear.'),\n});\n\nexport type ClearCookiesNodeInput = z.infer<typeof clearCookiesInputSchema>;\n\nexport const setViewportSizeInputSchema = z.strictObject({\n width: z.number().int().positive().describe('Viewport width in CSS pixels.'),\n height: z\n .number()\n .int()\n .positive()\n .describe('Viewport height in CSS pixels.'),\n});\n\nexport type SetViewportSizeNodeInput = z.infer<\n typeof setViewportSizeInputSchema\n>;\n\nconst resolveNavigationUrl = (\n target: string,\n currentUrl: string,\n configuredBase: string | undefined,\n): string => {\n const trimmed = target.trim();\n if (!trimmed) throw new TypeError('gotoUrl.url must not be blank.');\n if (/^[a-z][a-z\\d+.-]*:/i.test(trimmed)) {\n return resolveWebUrl(trimmed, undefined, 'gotoUrl.url');\n }\n if (configuredBase !== undefined) {\n return resolveWebUrl(trimmed, configuredBase, 'gotoUrl.url');\n }\n if (!/^https?:\\/\\//i.test(currentUrl)) {\n throw new TypeError(\n `gotoUrl.url cannot resolve a relative URL from ${JSON.stringify(currentUrl)}. Use an absolute HTTP(S) URL for the first navigation or configure testRunner.baseURL.`,\n );\n }\n return resolveWebUrl(trimmed, currentUrl, 'gotoUrl.url');\n};\n\n/** Create the browser-neutral built-in Web Nodes for one browser adapter. */\nexport const createWebTestRunnerNodeDefinitions = <\n TAgent,\n TOptions extends WebTestRunnerOptions<TAgent>,\n>(\n adapter: WebTestDriverAdapter<TAgent, TOptions>,\n): readonly AgentTestRunnerNodeDefinition[] => {\n const gotoUrlNode: AgentTestRunnerNodeDefinition<\n z.output<typeof gotoUrlInputSchema>,\n GotoUrlNodeResult\n > = {\n name: 'gotoUrl',\n title: 'Open a Web URL',\n description:\n 'Navigate the current browser Page to an absolute HTTP(S) URL or a path relative to testRunner.baseURL or the current page URL.',\n stringInputKey: 'url',\n inputSchema: gotoUrlInputSchema,\n async execute(agent, input, executionContext) {\n const runtimeAgent = adapter.requireAgent(agent);\n const driver = adapter.createDriver(runtimeAgent);\n throwIfAborted(executionContext.signal, 'gotoUrl');\n const url = resolveNavigationUrl(\n input.url,\n driver.currentUrl(),\n adapter.getOptions(runtimeAgent)?.baseURL ?? driver.baseUrl(),\n );\n const response = await driver.goto(url, {\n waitUntil: input.waitUntil,\n timeoutMs: input.timeoutMs,\n });\n throwIfAborted(executionContext.signal, 'gotoUrl');\n const result = {\n url: driver.currentUrl(),\n status: response.status,\n title: await driver.title(),\n };\n return { summary: `Navigated to ${result.url}`, data: result };\n },\n };\n\n const setCookiesNode: AgentTestRunnerNodeDefinition<\n z.output<typeof setCookiesInputSchema>,\n SetCookiesNodeResult\n > = {\n name: 'setCookies',\n title: 'Set browser cookies',\n description:\n 'Load cookies from an environment variable, configured profile, or browser storage-state file without persisting cookie values in workflow input or output.',\n stringInputKey: false,\n inputSchema: setCookiesInputSchema,\n async execute(agent, input, executionContext) {\n const runtimeAgent = adapter.requireAgent(agent);\n const driver = adapter.createDriver(runtimeAgent);\n throwIfAborted(executionContext.signal, 'setCookies');\n const { cookies, result } = await resolveCookieInput(\n input,\n { ...executionContext, input, context: runtimeAgent },\n adapter.getOptions(runtimeAgent) ?? {},\n );\n throwIfAborted(executionContext.signal, 'setCookies');\n try {\n await driver.setCookies(cookies);\n } catch (cause) {\n throw new Error(`Failed to set ${cookies.length} browser cookie(s).`, {\n cause,\n });\n }\n return {\n summary: `Set ${result.count} browser cookie(s) from ${result.source} ${result.sourceName}`,\n data: result,\n };\n },\n };\n\n const clearCookiesNode: AgentTestRunnerNodeDefinition<\n z.output<typeof clearCookiesInputSchema>,\n { filters: WebCookieFilters }\n > = {\n name: 'clearCookies',\n title: 'Clear browser cookies',\n description:\n 'Clear all cookies from the current browser context, or only cookies matching name, domain, or path.',\n stringInputKey: false,\n inputSchema: clearCookiesInputSchema,\n async execute(agent, input, executionContext) {\n const runtimeAgent = adapter.requireAgent(agent);\n const driver = adapter.createDriver(runtimeAgent);\n throwIfAborted(executionContext.signal, 'clearCookies');\n const filters: WebCookieFilters = { ...input };\n await driver.clearCookies(filters);\n const filterNames = Object.keys(filters);\n return {\n summary:\n filterNames.length === 0\n ? 'Cleared all browser cookies'\n : `Cleared browser cookies matching ${filterNames.join(', ')}`,\n data: { filters },\n };\n },\n };\n\n const setViewportSizeNode: AgentTestRunnerNodeDefinition<\n z.output<typeof setViewportSizeInputSchema>,\n WebViewportSize\n > = {\n name: 'setViewportSize',\n title: 'Set the browser viewport size',\n description:\n 'Set the current browser Page viewport size in CSS pixels and return the effective size.',\n stringInputKey: false,\n inputSchema: setViewportSizeInputSchema,\n async execute(agent, input, executionContext) {\n const runtimeAgent = adapter.requireAgent(agent);\n const driver = adapter.createDriver(runtimeAgent);\n throwIfAborted(executionContext.signal, 'setViewportSize');\n const viewport = await driver.setViewportSize(input);\n return {\n summary: `Set viewport to ${viewport.width}x${viewport.height}`,\n data: viewport,\n };\n },\n };\n\n return [gotoUrlNode, setCookiesNode, clearCookiesNode, setViewportSizeNode];\n};\n\nexport { setCookiesInputSchema };\nexport type { SetCookiesNodeInput, SetCookiesNodeResult } from './cookies';\n"],"names":["DEFAULT_NAVIGATION_TIMEOUT_MS","DEFAULT_WAIT_UNTIL","gotoUrlInputSchema","z","clearCookiesInputSchema","setViewportSizeInputSchema","resolveNavigationUrl","target","currentUrl","configuredBase","trimmed","TypeError","resolveWebUrl","undefined","JSON","createWebTestRunnerNodeDefinitions","adapter","gotoUrlNode","agent","input","executionContext","runtimeAgent","driver","throwIfAborted","url","response","result","setCookiesNode","setCookiesInputSchema","cookies","resolveCookieInput","cause","Error","clearCookiesNode","filters","filterNames","Object","setViewportSizeNode","viewport"],"mappings":";;;AAeA,MAAMA,gCAAgC;AACtC,MAAMC,qBAAqB;AAEpB,MAAMC,qBAAqBC,EAAE,YAAY,CAAC;IAC/C,KAAKA,EAAAA,MACI,GACN,GAAG,CAAC,GACJ,QAAQ,CACP;IAEJ,WAAWA,CAAC,CAADA,OACJ,CAAC;QACJ;QACA;QACA;QACA;QACA;QACA;KACD,EACA,OAAO,CAACF,oBACR,QAAQ,CACP;IAEJ,WAAWE,EAAAA,MACF,GACN,QAAQ,GACR,GAAG,CAAC,QACJ,OAAO,CAACH,+BACR,QAAQ,CAAC;AACd;A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ACb,MAAM,SAAQc,KAAK,EAAEC,KAAK,EAAEC,gBAAgB;YAC1C,MAAMC,eAAeL,QAAQ,YAAY,CAACE;YAC1C,MAAMI,SAASN,QAAQ,YAAY,CAACK;YACpCE,eAAeH,iBAAiB,MAAM,EAAE;YACxC,MAAMc,UAA4B;gBAAE,GAAGf,KAAK;YAAC;YAC7C,MAAMG,OAAO,YAAY,CAACY;YAC1B,MAAMC,cAAcC,OAAO,IAAI,CAACF;YAChC,OAAO;gBACL,SACEC,AAAuB,MAAvBA,YAAY,MAAM,GACd,gCACA,CAAC,iCAAiC,EAAEA,YAAY,IAAI,CAAC,OAAO;gBAClE,MAAM;oBAAED;gBAAQ;YAClB;QACF;IACF;IAEA,MAAMG,sBAGF;QACF,MAAM;QACN,OAAO;QACP,aACE;QACF,gBAAgB;QAChB,aAAahC;QACb,MAAM,SAAQa,KAAK,EAAEC,KAAK,EAAEC,gBAAgB;YAC1C,MAAMC,eAAeL,QAAQ,YAAY,CAACE;YAC1C,MAAMI,SAASN,QAAQ,YAAY,CAACK;YACpCE,eAAeH,iBAAiB,MAAM,EAAE;YACxC,MAAMkB,WAAW,MAAMhB,OAAO,eAAe,CAACH;YAC9C,OAAO;gBACL,SAAS,CAAC,gBAAgB,EAAEmB,SAAS,KAAK,CAAC,CAAC,EAAEA,SAAS,MAAM,EAAE;gBAC/D,MAAMA;YACR;QACF;IACF;IAEA,OAAO;QAACrB;QAAaU;QAAgBM;QAAkBI;KAAoB;AAC7E"}
|
package/dist/es/platform.mjs
CHANGED
|
@@ -24,7 +24,10 @@ const webPlaygroundPlatform = definePlaygroundPlatform({
|
|
|
24
24
|
title: options?.title || 'Midscene Web Playground',
|
|
25
25
|
agent: agent || (agentFactory ? void 0 : createDefaultWebAgent()),
|
|
26
26
|
agentFactory,
|
|
27
|
-
launchOptions:
|
|
27
|
+
launchOptions: {
|
|
28
|
+
enableCors: true,
|
|
29
|
+
...options?.launchOptions
|
|
30
|
+
},
|
|
28
31
|
preview: options?.preview || createMjpegPreviewDescriptor({
|
|
29
32
|
title: 'Web page preview'
|
|
30
33
|
}),
|
package/dist/es/platform.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"platform.mjs","sources":["../../src/platform.ts"],"sourcesContent":["import { ScreenshotItem } from '@midscene/core';\nimport type { Agent } from '@midscene/core/agent';\nimport {\n type AgentFactory,\n type LaunchPlaygroundOptions,\n type PlaygroundPreviewDescriptor,\n createMjpegPreviewDescriptor,\n definePlaygroundPlatform,\n} from '@midscene/playground';\nimport { StaticPage, StaticPageAgent } from './static';\n\nexport interface WebPlatformOptions {\n agent?: Agent;\n agentFactory?: AgentFactory;\n title?: string;\n preview?: PlaygroundPreviewDescriptor;\n launchOptions?: LaunchPlaygroundOptions;\n}\n\nfunction createDefaultWebAgent(): StaticPageAgent {\n const page = new StaticPage({\n shotSize: { width: 800, height: 600 },\n screenshot: ScreenshotItem.create('', Date.now()),\n shrunkShotToLogicalRatio: 1,\n });\n\n return new StaticPageAgent(page);\n}\n\nexport const webPlaygroundPlatform = definePlaygroundPlatform<\n WebPlatformOptions | undefined\n>({\n id: 'web',\n title: 'Midscene Web Playground',\n description: 'Web playground platform descriptor',\n async prepare(options) {\n const agent = options?.agent;\n const agentFactory =\n options?.agentFactory ||\n (!options?.agent && !options?.agentFactory\n ? () => createDefaultWebAgent()\n : undefined);\n\n return {\n platformId: 'web',\n title: options?.title || 'Midscene Web Playground',\n agent: agent || (!agentFactory ? createDefaultWebAgent() : undefined),\n agentFactory,\n launchOptions: options?.launchOptions,\n preview:\n options?.preview ||\n createMjpegPreviewDescriptor({\n title: 'Web page preview',\n }),\n metadata: {\n interfaceType: agent?.interface?.interfaceType || 'web',\n },\n };\n },\n});\n"],"names":["createDefaultWebAgent","page","StaticPage","ScreenshotItem","Date","StaticPageAgent","webPlaygroundPlatform","definePlaygroundPlatform","options","agent","agentFactory","undefined","createMjpegPreviewDescriptor"],"mappings":";;;AAmBA,SAASA;IACP,MAAMC,OAAO,IAAIC,WAAW;QAC1B,UAAU;YAAE,OAAO;YAAK,QAAQ;QAAI;QACpC,YAAYC,eAAe,MAAM,CAAC,IAAIC,KAAK,GAAG;QAC9C,0BAA0B;IAC5B;IAEA,OAAO,IAAIC,gBAAgBJ;AAC7B;AAEO,MAAMK,wBAAwBC,yBAEnC;IACA,IAAI;IACJ,OAAO;IACP,aAAa;IACb,MAAM,SAAQC,OAAO;QACnB,MAAMC,QAAQD,SAAS;QACvB,MAAME,eACJF,SAAS,gBACR,CAACA,SAAS,SAAUA,SAAS,eAE1BG,SADA,IAAMX,uBACE;QAEd,OAAO;YACL,YAAY;YACZ,OAAOQ,SAAS,SAAS;YACzB,OAAOC,SAAU,CAACC,eAAyCC,SAA1BX,uBAAkC;YACnEU;YACA,
|
|
1
|
+
{"version":3,"file":"platform.mjs","sources":["../../src/platform.ts"],"sourcesContent":["import { ScreenshotItem } from '@midscene/core';\nimport type { Agent } from '@midscene/core/agent';\nimport {\n type AgentFactory,\n type LaunchPlaygroundOptions,\n type PlaygroundPreviewDescriptor,\n createMjpegPreviewDescriptor,\n definePlaygroundPlatform,\n} from '@midscene/playground';\nimport { StaticPage, StaticPageAgent } from './static';\n\nexport interface WebPlatformOptions {\n agent?: Agent;\n agentFactory?: AgentFactory;\n title?: string;\n preview?: PlaygroundPreviewDescriptor;\n launchOptions?: LaunchPlaygroundOptions;\n}\n\nfunction createDefaultWebAgent(): StaticPageAgent {\n const page = new StaticPage({\n shotSize: { width: 800, height: 600 },\n screenshot: ScreenshotItem.create('', Date.now()),\n shrunkShotToLogicalRatio: 1,\n });\n\n return new StaticPageAgent(page);\n}\n\nexport const webPlaygroundPlatform = definePlaygroundPlatform<\n WebPlatformOptions | undefined\n>({\n id: 'web',\n title: 'Midscene Web Playground',\n description: 'Web playground platform descriptor',\n async prepare(options) {\n const agent = options?.agent;\n const agentFactory =\n options?.agentFactory ||\n (!options?.agent && !options?.agentFactory\n ? () => createDefaultWebAgent()\n : undefined);\n\n return {\n platformId: 'web',\n title: options?.title || 'Midscene Web Playground',\n agent: agent || (!agentFactory ? createDefaultWebAgent() : undefined),\n agentFactory,\n launchOptions: {\n enableCors: true,\n ...options?.launchOptions,\n },\n preview:\n options?.preview ||\n createMjpegPreviewDescriptor({\n title: 'Web page preview',\n }),\n metadata: {\n interfaceType: agent?.interface?.interfaceType || 'web',\n },\n };\n },\n});\n"],"names":["createDefaultWebAgent","page","StaticPage","ScreenshotItem","Date","StaticPageAgent","webPlaygroundPlatform","definePlaygroundPlatform","options","agent","agentFactory","undefined","createMjpegPreviewDescriptor"],"mappings":";;;AAmBA,SAASA;IACP,MAAMC,OAAO,IAAIC,WAAW;QAC1B,UAAU;YAAE,OAAO;YAAK,QAAQ;QAAI;QACpC,YAAYC,eAAe,MAAM,CAAC,IAAIC,KAAK,GAAG;QAC9C,0BAA0B;IAC5B;IAEA,OAAO,IAAIC,gBAAgBJ;AAC7B;AAEO,MAAMK,wBAAwBC,yBAEnC;IACA,IAAI;IACJ,OAAO;IACP,aAAa;IACb,MAAM,SAAQC,OAAO;QACnB,MAAMC,QAAQD,SAAS;QACvB,MAAME,eACJF,SAAS,gBACR,CAACA,SAAS,SAAUA,SAAS,eAE1BG,SADA,IAAMX,uBACE;QAEd,OAAO;YACL,YAAY;YACZ,OAAOQ,SAAS,SAAS;YACzB,OAAOC,SAAU,CAACC,eAAyCC,SAA1BX,uBAAkC;YACnEU;YACA,eAAe;gBACb,YAAY;gBACZ,GAAGF,SAAS,aAAa;YAC3B;YACA,SACEA,SAAS,WACTI,6BAA6B;gBAC3B,OAAO;YACT;YACF,UAAU;gBACR,eAAeH,OAAO,WAAW,iBAAiB;YACpD;QACF;IACF;AACF"}
|
|
@@ -130,7 +130,7 @@ class BridgeServer {
|
|
|
130
130
|
(0, shared_utils_namespaceObject.logMsg)('one client connected');
|
|
131
131
|
this.socket = socket;
|
|
132
132
|
const clientVersion = socket.handshake.query.version;
|
|
133
|
-
(0, shared_utils_namespaceObject.logMsg)(`Bridge connected, cli-side version v1.
|
|
133
|
+
(0, shared_utils_namespaceObject.logMsg)(`Bridge connected, cli-side version v1.18.0, browser-side version v${clientVersion}`);
|
|
134
134
|
socket.on(external_common_js_namespaceObject.BridgeEvent.CallResponse, (params)=>{
|
|
135
135
|
const id = params.id;
|
|
136
136
|
const response = params.response;
|
|
@@ -154,7 +154,7 @@ class BridgeServer {
|
|
|
154
154
|
setTimeout(()=>{
|
|
155
155
|
this.onConnect?.();
|
|
156
156
|
const payload = {
|
|
157
|
-
version: "1.
|
|
157
|
+
version: "1.18.0"
|
|
158
158
|
};
|
|
159
159
|
socket.emit(external_common_js_namespaceObject.BridgeEvent.Connected, payload);
|
|
160
160
|
Promise.resolve().then(()=>{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bridge-mode/io-server.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../src/bridge-mode/io-server.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import {\n type IncomingMessage,\n type ServerResponse,\n createServer,\n} from 'node:http';\nimport { sleep } from '@midscene/core/utils';\nimport { getDebug } from '@midscene/shared/logger';\nimport { logMsg } from '@midscene/shared/utils';\nimport { Server, type Socket as ServerSocket } from 'socket.io';\nimport { io as ClientIO } from 'socket.io-client';\n\nimport {\n type BridgeCall,\n type BridgeCallResponse,\n BridgeCallTimeout,\n type BridgeConnectedEventPayload,\n BridgeErrorCodeNoClientConnected,\n BridgeEvent,\n BridgeSignalKill,\n DefaultBridgeServerHost,\n DefaultBridgeServerPort,\n} from './common';\n\nconst debug = getDebug('web:bridge:io-server');\n\ndeclare const __VERSION__: string;\n\n/**\n * Returns true if the given Origin header value is allowed to connect\n * to the bridge server. Trusted origins are:\n * - No Origin header (local Node.js processes like killRunningServer)\n * - chrome-extension:// origins (the Midscene Chrome extension)\n *\n * Browser pages (https://evil.com, etc.) are rejected to prevent\n * Cross-Site WebSocket Hijacking (CSWSH) attacks.\n */\nfunction isTrustedOrigin(origin: string | undefined): boolean {\n if (!origin) return true;\n if (origin.startsWith('chrome-extension://')) return true;\n return false;\n}\n\nexport const killRunningServer = async (\n port?: number,\n host = DefaultBridgeServerHost,\n) => {\n try {\n const client = ClientIO(`ws://${host}:${port || DefaultBridgeServerPort}`, {\n query: {\n [BridgeSignalKill]: 1,\n },\n });\n await sleep(300);\n await client.close();\n } catch (e) {\n debug('failed to kill port: %O', e);\n }\n};\n\n// ws server, this is where the request is sent\nexport class BridgeServer {\n private callId = 0;\n private io: Server | null = null;\n private socket: ServerSocket | null = null;\n private listeningTimeoutId: NodeJS.Timeout | null = null;\n private listeningTimerFlag = false;\n private connectionTipTimer: NodeJS.Timeout | null = null;\n public calls: Record<string, BridgeCall> = {};\n\n private connectionLost = false;\n private connectionLostReason = '';\n\n constructor(\n public host: string,\n public port: number,\n public onConnect?: () => void,\n public onDisconnect?: (reason: string) => void,\n public closeConflictServer?: boolean,\n ) {}\n\n async listen(\n opts: {\n timeout?: number | false;\n } = {},\n ): Promise<void> {\n const { timeout = 30000 } = opts;\n\n if (this.closeConflictServer) {\n await killRunningServer(this.port, this.host);\n }\n\n return new Promise((resolve, reject) => {\n if (this.listeningTimerFlag) {\n return reject(new Error('already listening'));\n }\n this.listeningTimerFlag = true;\n\n this.listeningTimeoutId = timeout\n ? setTimeout(() => {\n reject(\n new Error(\n `no extension connected after ${timeout}ms (${BridgeErrorCodeNoClientConnected})`,\n ),\n );\n }, timeout)\n : null;\n\n this.connectionTipTimer =\n !timeout || timeout > 3000\n ? setTimeout(() => {\n logMsg('waiting for bridge to connect...');\n }, 2000)\n : null;\n\n // Create HTTP server — no /bridge-auth endpoint needed since we use\n // pure Origin checking in the Socket.IO middleware below.\n const httpServer = createServer(\n (_req: IncomingMessage, res: ServerResponse) => {\n res.writeHead(404);\n res.end();\n },\n );\n\n // Set up HTTP server event listeners FIRST\n httpServer.once('listening', () => {\n resolve();\n });\n\n httpServer.once('error', (err: Error) => {\n reject(new Error(`Bridge Listening Error: ${err.message}`));\n });\n\n // Always honor the configured interface, including the loopback default.\n httpServer.listen(this.port, this.host);\n\n // Now create Socket.IO Server attached to the already-listening HTTP server\n this.io = new Server(httpServer, {\n maxHttpBufferSize: 100 * 1024 * 1024, // 100MB\n // Increase pingTimeout to tolerate Chrome MV3 Service Worker suspension.\n // The SW keepalive alarm fires every ~24s; default pingTimeout (20s) may\n // be too short if the SW is suspended between alarm pings.\n pingTimeout: 60000,\n });\n\n this.io.use((socket, next) => {\n // Reject connections from untrusted browser origins to prevent\n // Cross-Site WebSocket Hijacking (CSWSH) and unauthorized kill signals.\n // The browser automatically sets the Origin header on WebSocket\n // handshakes, and JavaScript cannot override it.\n const origin = socket.handshake.headers.origin;\n if (!isTrustedOrigin(origin)) {\n debug('connection rejected: untrusted origin=%s', origin);\n return next(new Error('origin not allowed'));\n }\n\n // Allow new connections to replace old ones (reconnection after\n // extension Stop→Start). If the old socket is already disconnected\n // or unresponsive, accept the new connection immediately.\n if (\n socket.handshake.url.includes(BridgeSignalKill) === false &&\n this.socket?.connected\n ) {\n return next(new Error('server already connected by another client'));\n }\n next();\n });\n\n this.io.on('connection', (socket) => {\n // check the connection url\n const url = socket.handshake.url;\n if (url.includes(BridgeSignalKill)) {\n console.warn('kill signal received, closing bridge server');\n return this.close();\n }\n\n this.connectionLost = false;\n this.connectionLostReason = '';\n this.listeningTimeoutId && clearTimeout(this.listeningTimeoutId);\n this.listeningTimeoutId = null;\n this.connectionTipTimer && clearTimeout(this.connectionTipTimer);\n this.connectionTipTimer = null;\n if (this.socket?.connected) {\n socket.emit(BridgeEvent.Refused);\n socket.disconnect();\n logMsg(\n 'refused new connection: server already connected by another client',\n );\n return;\n }\n\n // Clean up stale old socket if it exists but is no longer connected\n if (this.socket) {\n try {\n this.socket.disconnect();\n } catch (e) {\n logMsg(`failed to disconnect stale socket: ${e}`);\n }\n this.socket = null;\n }\n\n try {\n logMsg('one client connected');\n this.socket = socket;\n\n const clientVersion = socket.handshake.query.version;\n logMsg(\n `Bridge connected, cli-side version v${__VERSION__}, browser-side version v${clientVersion}`,\n );\n\n socket.on(BridgeEvent.CallResponse, (params: BridgeCallResponse) => {\n const id = params.id;\n const response = params.response;\n const error = params.error;\n\n this.triggerCallResponseCallback(id, error, response);\n });\n\n socket.on('disconnect', (reason: string) => {\n this.connectionLost = true;\n this.connectionLostReason = reason;\n this.socket = null;\n\n // flush all pending calls as error and clean up completed calls\n for (const id in this.calls) {\n const call = this.calls[id];\n\n if (!call.responseTime) {\n const errorMessage = this.connectionLostErrorMsg();\n this.triggerCallResponseCallback(\n id,\n new Error(errorMessage),\n null,\n );\n }\n }\n\n // Clean up completed calls to prevent memory leaks in long-running sessions\n for (const id in this.calls) {\n if (this.calls[id].responseTime) {\n delete this.calls[id];\n }\n }\n\n this.onDisconnect?.(reason);\n });\n\n setTimeout(() => {\n this.onConnect?.();\n\n const payload = {\n version: __VERSION__,\n } as BridgeConnectedEventPayload;\n socket.emit(BridgeEvent.Connected, payload);\n Promise.resolve().then(() => {\n for (const id in this.calls) {\n if (this.calls[id].callTime === 0) {\n this.emitCall(id);\n }\n }\n });\n }, 0);\n } catch (e) {\n logMsg(`failed to handle connection event: ${e}`);\n }\n });\n\n this.io.on('close', () => {\n this.close();\n });\n });\n }\n\n private connectionLostErrorMsg = () => {\n return `Connection lost, reason: ${this.connectionLostReason}`;\n };\n\n private async triggerCallResponseCallback(\n id: string | number,\n error: Error | string | null,\n response: any,\n ) {\n const call = this.calls[id];\n if (!call) {\n throw new Error(`call ${id} not found`);\n }\n // Ensure error is always an Error object (bridge client may send strings)\n if (error) {\n call.error =\n error instanceof Error\n ? error\n : new Error(typeof error === 'string' ? error : String(error));\n } else {\n call.error = undefined;\n }\n call.response = response;\n call.responseTime = Date.now();\n\n call.callback(call.error, response);\n }\n\n private async emitCall(id: string) {\n const call = this.calls[id];\n if (!call) {\n throw new Error(`call ${id} not found`);\n }\n\n if (this.connectionLost) {\n const message = `Connection lost, reason: ${this.connectionLostReason}`;\n call.callback(new Error(message), null);\n return;\n }\n\n if (this.socket) {\n this.socket.emit(BridgeEvent.Call, {\n id,\n method: call.method,\n args: call.args,\n });\n call.callTime = Date.now();\n }\n }\n\n async call<T = any>(\n method: string,\n args: any[],\n timeout = BridgeCallTimeout,\n ): Promise<T> {\n const id = `${this.callId++}`;\n\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n logMsg(`bridge call timeout, id=${id}, method=${method}, args=`, args);\n this.calls[id].error = new Error(\n `Bridge call timeout after ${timeout}ms: ${method}`,\n );\n reject(this.calls[id].error);\n }, timeout);\n\n this.calls[id] = {\n method,\n args,\n response: null,\n callTime: 0,\n responseTime: 0,\n callback: (error: Error | undefined, response: any) => {\n clearTimeout(timeoutId);\n if (error) {\n reject(error);\n } else {\n resolve(response);\n }\n },\n };\n\n this.emitCall(id);\n });\n }\n\n // do NOT restart after close\n async close() {\n this.listeningTimeoutId && clearTimeout(this.listeningTimeoutId);\n this.connectionTipTimer && clearTimeout(this.connectionTipTimer);\n const closeProcess = this.io?.close();\n this.io = null;\n\n return closeProcess;\n }\n}\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","debug","getDebug","isTrustedOrigin","origin","killRunningServer","port","host","DefaultBridgeServerHost","client","ClientIO","DefaultBridgeServerPort","BridgeSignalKill","sleep","e","BridgeServer","opts","timeout","Promise","resolve","reject","Error","setTimeout","BridgeErrorCodeNoClientConnected","logMsg","httpServer","createServer","_req","res","err","Server","socket","next","url","console","clearTimeout","BridgeEvent","clientVersion","params","id","response","error","reason","call","errorMessage","payload","__VERSION__","String","undefined","Date","message","method","args","BridgeCallTimeout","timeoutId","closeProcess","onConnect","onDisconnect","closeConflictServer"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,MAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,UAAS,cAAc;YAAE,OAAO;QAAK;IAC5D;;;;;;;;;;;;;;;;;;;;;;;;;ACiBA,MAAMI,QAAQC,AAAAA,IAAAA,uBAAAA,QAAAA,AAAAA,EAAS;AAavB,SAASC,gBAAgBC,MAA0B;IACjD,IAAI,CAACA,QAAQ,OAAO;IACpB,IAAIA,OAAO,UAAU,CAAC,wBAAwB,OAAO;IACrD,OAAO;AACT;AAEO,MAAMC,oBAAoB,OAC/BC,MACAC,OAAOC,mCAAAA,uBAAuB;IAE9B,IAAI;QACF,MAAMC,SAASC,AAAAA,IAAAA,0CAAAA,EAAAA,AAAAA,EAAS,CAAC,KAAK,EAAEH,KAAK,CAAC,EAAED,QAAQK,mCAAAA,uBAAuBA,EAAE,EAAE;YACzE,OAAO;gBACL,CAACC,mCAAAA,gBAAgBA,CAAC,EAAE;YACtB;QACF;QACA,MAAM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,UAAR;QACA,uBAAQ,MAAR;QACA,uBAAQ,UAAR;QACA,uBAAQ,sBAAR;QACA,uBAAQ,sBAAR;QACA,uBAAQ,sBAAR;QACA,uBAAO,SAAP;QAEA,uBAAQ,kBAAR;QACA,uBAAQ,wBAAR;QA0MA,uBAAQ,0BAAR;aAvMSnD,IAAI,GAAJA;aACAD,IAAI,GAAJA;aACAkD,SAAS,GAATA;aACAC,YAAY,GAAZA;aACAC,mBAAmB,GAAnBA;aAhBD,MAAM,GAAG;aACT,EAAE,GAAkB;aACpB,MAAM,GAAwB;aAC9B,kBAAkB,GAA0B;aAC5C,kBAAkB,GAAG;aACrB,kBAAkB,GAA0B;aAC7C,KAAK,GAA+B,CAAC;aAEpC,cAAc,GAAG;aACjB,oBAAoB,GAAG;aA0MvB,sBAAsB,GAAG,IACxB,CAAC,yBAAyB,EAAE,IAAI,CAAC,oBAAoB,EAAE;IAnM7D;AAiSL"}
|
|
1
|
+
{"version":3,"file":"bridge-mode/io-server.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../src/bridge-mode/io-server.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import {\n type IncomingMessage,\n type ServerResponse,\n createServer,\n} from 'node:http';\nimport { sleep } from '@midscene/core/utils';\nimport { getDebug } from '@midscene/shared/logger';\nimport { logMsg } from '@midscene/shared/utils';\nimport { Server, type Socket as ServerSocket } from 'socket.io';\nimport { io as ClientIO } from 'socket.io-client';\n\nimport {\n type BridgeCall,\n type BridgeCallResponse,\n BridgeCallTimeout,\n type BridgeConnectedEventPayload,\n BridgeErrorCodeNoClientConnected,\n BridgeEvent,\n BridgeSignalKill,\n DefaultBridgeServerHost,\n DefaultBridgeServerPort,\n} from './common';\n\nconst debug = getDebug('web:bridge:io-server');\n\ndeclare const __VERSION__: string;\n\n/**\n * Returns true if the given Origin header value is allowed to connect\n * to the bridge server. Trusted origins are:\n * - No Origin header (local Node.js processes like killRunningServer)\n * - chrome-extension:// origins (the Midscene Chrome extension)\n *\n * Browser pages (https://evil.com, etc.) are rejected to prevent\n * Cross-Site WebSocket Hijacking (CSWSH) attacks.\n */\nfunction isTrustedOrigin(origin: string | undefined): boolean {\n if (!origin) return true;\n if (origin.startsWith('chrome-extension://')) return true;\n return false;\n}\n\nexport const killRunningServer = async (\n port?: number,\n host = DefaultBridgeServerHost,\n) => {\n try {\n const client = ClientIO(`ws://${host}:${port || DefaultBridgeServerPort}`, {\n query: {\n [BridgeSignalKill]: 1,\n },\n });\n await sleep(300);\n await client.close();\n } catch (e) {\n debug('failed to kill port: %O', e);\n }\n};\n\n// ws server, this is where the request is sent\nexport class BridgeServer {\n private callId = 0;\n private io: Server | null = null;\n private socket: ServerSocket | null = null;\n private listeningTimeoutId: NodeJS.Timeout | null = null;\n private listeningTimerFlag = false;\n private connectionTipTimer: NodeJS.Timeout | null = null;\n public calls: Record<string, BridgeCall> = {};\n\n private connectionLost = false;\n private connectionLostReason = '';\n\n constructor(\n public host: string,\n public port: number,\n public onConnect?: () => void,\n public onDisconnect?: (reason: string) => void,\n public closeConflictServer?: boolean,\n ) {}\n\n async listen(\n opts: {\n timeout?: number | false;\n } = {},\n ): Promise<void> {\n const { timeout = 30000 } = opts;\n\n if (this.closeConflictServer) {\n await killRunningServer(this.port, this.host);\n }\n\n return new Promise((resolve, reject) => {\n if (this.listeningTimerFlag) {\n return reject(new Error('already listening'));\n }\n this.listeningTimerFlag = true;\n\n this.listeningTimeoutId = timeout\n ? setTimeout(() => {\n reject(\n new Error(\n `no extension connected after ${timeout}ms (${BridgeErrorCodeNoClientConnected})`,\n ),\n );\n }, timeout)\n : null;\n\n this.connectionTipTimer =\n !timeout || timeout > 3000\n ? setTimeout(() => {\n logMsg('waiting for bridge to connect...');\n }, 2000)\n : null;\n\n // Create HTTP server — no /bridge-auth endpoint needed since we use\n // pure Origin checking in the Socket.IO middleware below.\n const httpServer = createServer(\n (_req: IncomingMessage, res: ServerResponse) => {\n res.writeHead(404);\n res.end();\n },\n );\n\n // Set up HTTP server event listeners FIRST\n httpServer.once('listening', () => {\n resolve();\n });\n\n httpServer.once('error', (err: Error) => {\n reject(new Error(`Bridge Listening Error: ${err.message}`));\n });\n\n // Always honor the configured interface, including the loopback default.\n httpServer.listen(this.port, this.host);\n\n // Now create Socket.IO Server attached to the already-listening HTTP server\n this.io = new Server(httpServer, {\n maxHttpBufferSize: 100 * 1024 * 1024, // 100MB\n // Increase pingTimeout to tolerate Chrome MV3 Service Worker suspension.\n // The SW keepalive alarm fires every ~24s; default pingTimeout (20s) may\n // be too short if the SW is suspended between alarm pings.\n pingTimeout: 60000,\n });\n\n this.io.use((socket, next) => {\n // Reject connections from untrusted browser origins to prevent\n // Cross-Site WebSocket Hijacking (CSWSH) and unauthorized kill signals.\n // The browser automatically sets the Origin header on WebSocket\n // handshakes, and JavaScript cannot override it.\n const origin = socket.handshake.headers.origin;\n if (!isTrustedOrigin(origin)) {\n debug('connection rejected: untrusted origin=%s', origin);\n return next(new Error('origin not allowed'));\n }\n\n // Allow new connections to replace old ones (reconnection after\n // extension Stop→Start). If the old socket is already disconnected\n // or unresponsive, accept the new connection immediately.\n if (\n socket.handshake.url.includes(BridgeSignalKill) === false &&\n this.socket?.connected\n ) {\n return next(new Error('server already connected by another client'));\n }\n next();\n });\n\n this.io.on('connection', (socket) => {\n // check the connection url\n const url = socket.handshake.url;\n if (url.includes(BridgeSignalKill)) {\n console.warn('kill signal received, closing bridge server');\n return this.close();\n }\n\n this.connectionLost = false;\n this.connectionLostReason = '';\n this.listeningTimeoutId && clearTimeout(this.listeningTimeoutId);\n this.listeningTimeoutId = null;\n this.connectionTipTimer && clearTimeout(this.connectionTipTimer);\n this.connectionTipTimer = null;\n if (this.socket?.connected) {\n socket.emit(BridgeEvent.Refused);\n socket.disconnect();\n logMsg(\n 'refused new connection: server already connected by another client',\n );\n return;\n }\n\n // Clean up stale old socket if it exists but is no longer connected\n if (this.socket) {\n try {\n this.socket.disconnect();\n } catch (e) {\n logMsg(`failed to disconnect stale socket: ${e}`);\n }\n this.socket = null;\n }\n\n try {\n logMsg('one client connected');\n this.socket = socket;\n\n const clientVersion = socket.handshake.query.version;\n logMsg(\n `Bridge connected, cli-side version v${__VERSION__}, browser-side version v${clientVersion}`,\n );\n\n socket.on(BridgeEvent.CallResponse, (params: BridgeCallResponse) => {\n const id = params.id;\n const response = params.response;\n const error = params.error;\n\n this.triggerCallResponseCallback(id, error, response);\n });\n\n socket.on('disconnect', (reason: string) => {\n this.connectionLost = true;\n this.connectionLostReason = reason;\n this.socket = null;\n\n // flush all pending calls as error and clean up completed calls\n for (const id in this.calls) {\n const call = this.calls[id];\n\n if (!call.responseTime) {\n const errorMessage = this.connectionLostErrorMsg();\n this.triggerCallResponseCallback(\n id,\n new Error(errorMessage),\n null,\n );\n }\n }\n\n // Clean up completed calls to prevent memory leaks in long-running sessions\n for (const id in this.calls) {\n if (this.calls[id].responseTime) {\n delete this.calls[id];\n }\n }\n\n this.onDisconnect?.(reason);\n });\n\n setTimeout(() => {\n this.onConnect?.();\n\n const payload = {\n version: __VERSION__,\n } as BridgeConnectedEventPayload;\n socket.emit(BridgeEvent.Connected, payload);\n Promise.resolve().then(() => {\n for (const id in this.calls) {\n if (this.calls[id].callTime === 0) {\n this.emitCall(id);\n }\n }\n });\n }, 0);\n } catch (e) {\n logMsg(`failed to handle connection event: ${e}`);\n }\n });\n\n this.io.on('close', () => {\n this.close();\n });\n });\n }\n\n private connectionLostErrorMsg = () => {\n return `Connection lost, reason: ${this.connectionLostReason}`;\n };\n\n private async triggerCallResponseCallback(\n id: string | number,\n error: Error | string | null,\n response: any,\n ) {\n const call = this.calls[id];\n if (!call) {\n throw new Error(`call ${id} not found`);\n }\n // Ensure error is always an Error object (bridge client may send strings)\n if (error) {\n call.error =\n error instanceof Error\n ? error\n : new Error(typeof error === 'string' ? error : String(error));\n } else {\n call.error = undefined;\n }\n call.response = response;\n call.responseTime = Date.now();\n\n call.callback(call.error, response);\n }\n\n private async emitCall(id: string) {\n const call = this.calls[id];\n if (!call) {\n throw new Error(`call ${id} not found`);\n }\n\n if (this.connectionLost) {\n const message = `Connection lost, reason: ${this.connectionLostReason}`;\n call.callback(new Error(message), null);\n return;\n }\n\n if (this.socket) {\n this.socket.emit(BridgeEvent.Call, {\n id,\n method: call.method,\n args: call.args,\n });\n call.callTime = Date.now();\n }\n }\n\n async call<T = any>(\n method: string,\n args: any[],\n timeout = BridgeCallTimeout,\n ): Promise<T> {\n const id = `${this.callId++}`;\n\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n logMsg(`bridge call timeout, id=${id}, method=${method}, args=`, args);\n this.calls[id].error = new Error(\n `Bridge call timeout after ${timeout}ms: ${method}`,\n );\n reject(this.calls[id].error);\n }, timeout);\n\n this.calls[id] = {\n method,\n args,\n response: null,\n callTime: 0,\n responseTime: 0,\n callback: (error: Error | undefined, response: any) => {\n clearTimeout(timeoutId);\n if (error) {\n reject(error);\n } else {\n resolve(response);\n }\n },\n };\n\n this.emitCall(id);\n });\n }\n\n // do NOT restart after close\n async close() {\n this.listeningTimeoutId && clearTimeout(this.listeningTimeoutId);\n this.connectionTipTimer && clearTimeout(this.connectionTipTimer);\n const closeProcess = this.io?.close();\n this.io = null;\n\n return closeProcess;\n }\n}\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","debug","getDebug","isTrustedOrigin","origin","killRunningServer","port","host","DefaultBridgeServerHost","client","ClientIO","DefaultBridgeServerPort","BridgeSignalKill","sleep","e","BridgeServer","opts","timeout","Promise","resolve","reject","Error","setTimeout","BridgeErrorCodeNoClientConnected","logMsg","httpServer","createServer","_req","res","err","Server","socket","next","url","console","clearTimeout","BridgeEvent","clientVersion","params","id","response","error","reason","call","errorMessage","payload","__VERSION__","String","undefined","Date","message","method","args","BridgeCallTimeout","timeoutId","closeProcess","onConnect","onDisconnect","closeConflictServer"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,MAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,UAAS,cAAc;YAAE,OAAO;QAAK;IAC5D;;;;;;;;;;;;;;;;;;;;;;;;;ACiBA,MAAMI,QAAQC,AAAAA,IAAAA,uBAAAA,QAAAA,AAAAA,EAAS;AAavB,SAASC,gBAAgBC,MAA0B;IACjD,IAAI,CAACA,QAAQ,OAAO;IACpB,IAAIA,OAAO,UAAU,CAAC,wBAAwB,OAAO;IACrD,OAAO;AACT;AAEO,MAAMC,oBAAoB,OAC/BC,MACAC,OAAOC,mCAAAA,uBAAuB;IAE9B,IAAI;QACF,MAAMC,SAASC,AAAAA,IAAAA,0CAAAA,EAAAA,AAAAA,EAAS,CAAC,KAAK,EAAEH,KAAK,CAAC,EAAED,QAAQK,m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T;IAtSA,YACShD,IAAY,EACZD,IAAY,EACZkD,SAAsB,EACtBC,YAAuC,EACvCC,mBAA6B,CACpC;;;;;;QAjBF,uBAAQ,UAAR;QACA,uBAAQ,MAAR;QACA,uBAAQ,UAAR;QACA,uBAAQ,sBAAR;QACA,uBAAQ,sBAAR;QACA,uBAAQ,sBAAR;QACA,uBAAO,SAAP;QAEA,uBAAQ,kBAAR;QACA,uBAAQ,wBAAR;QA0MA,uBAAQ,0BAAR;aAvMSnD,IAAI,GAAJA;aACAD,IAAI,GAAJA;aACAkD,SAAS,GAATA;aACAC,YAAY,GAAZA;aACAC,mBAAmB,GAAnBA;aAhBD,MAAM,GAAG;aACT,EAAE,GAAkB;aACpB,MAAM,GAAwB;aAC9B,kBAAkB,GAA0B;aAC5C,kBAAkB,GAAG;aACrB,kBAAkB,GAA0B;aAC7C,KAAK,GAA+B,CAAC;aAEpC,cAAc,GAAG;aACjB,oBAAoB,GAAG;aA0MvB,sBAAsB,GAAG,IACxB,CAAC,yBAAyB,EAAE,IAAI,CAAC,oBAAoB,EAAE;IAnM7D;AAiSL"}
|
|
@@ -138,7 +138,7 @@ class ExtensionBridgePageBrowserSide extends page_js_default() {
|
|
|
138
138
|
throw new Error('Connection denied by user');
|
|
139
139
|
}
|
|
140
140
|
}
|
|
141
|
-
this.onLogMessage(`Bridge connected, cli-side version v${this.bridgeClient.serverVersion}, browser-side version v1.
|
|
141
|
+
this.onLogMessage(`Bridge connected, cli-side version v${this.bridgeClient.serverVersion}, browser-side version v1.18.0`, 'log');
|
|
142
142
|
}
|
|
143
143
|
async connect() {
|
|
144
144
|
return await this.setupBridgeClient();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bridge-mode/page-browser-side.js","sources":["webpack/runtime/compat_get_default_export","webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../src/bridge-mode/page-browser-side.ts"],"sourcesContent":["// getDefaultExport function for compatibility with non-ESM modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};\n","__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { assert } from '@midscene/shared/utils';\nimport ChromeExtensionProxyPage from '../chrome-extension/page';\nimport type {\n ChromePageDestroyOptions,\n KeyboardAction,\n MouseAction,\n} from '../web-page';\nimport {\n type BridgeConnectTabOptions,\n BridgeEvent,\n DefaultBridgeServerHost,\n DefaultBridgeServerPort,\n KeyboardEvent,\n MouseEvent,\n} from './common';\nimport { BridgeClient } from './io-client';\n\ndeclare const __VERSION__: string;\n\nconst NEW_TAB_LOAD_TIMEOUT_MS = 30_000;\n\nfunction isBlankUrl(url: string | undefined): boolean {\n if (!url) return true;\n return url === 'about:blank' || url.startsWith('chrome://newtab');\n}\n\n// Wait until the freshly created tab has navigated away from about:blank\n// and reached `status === 'complete'`. Resolves on timeout instead of\n// throwing so callers degrade to the existing lazy-attach behavior.\nfunction waitForTabNavigationComplete(\n tabId: number,\n targetUrl: string,\n timeoutMs = NEW_TAB_LOAD_TIMEOUT_MS,\n): Promise<void> {\n return new Promise((resolve) => {\n let settled = false;\n const finish = () => {\n if (settled) return;\n settled = true;\n try {\n chrome.tabs.onUpdated.removeListener(onUpdated);\n } catch {}\n clearTimeout(timer);\n resolve();\n };\n\n const isReady = (tab: chrome.tabs.Tab | undefined): boolean => {\n if (!tab) return false;\n if (tab.status !== 'complete') return false;\n const currentUrl = tab.url || tab.pendingUrl || '';\n // Skip the initial about:blank \"complete\" that fires before\n // the target URL navigation kicks in.\n if (isBlankUrl(currentUrl) && !isBlankUrl(targetUrl)) return false;\n return true;\n };\n\n const onUpdated = (\n id: number,\n _info: chrome.tabs.TabChangeInfo,\n tab: chrome.tabs.Tab,\n ) => {\n if (id !== tabId) return;\n if (isReady(tab)) finish();\n };\n\n chrome.tabs.onUpdated.addListener(onUpdated);\n const timer = setTimeout(finish, timeoutMs);\n\n // Handle the race where the tab already finished loading before\n // we registered the listener.\n chrome.tabs\n .get(tabId)\n .then((tab) => {\n if (isReady(tab)) finish();\n })\n .catch(() => {});\n });\n}\n\nexport class ExtensionBridgePageBrowserSide extends ChromeExtensionProxyPage {\n public bridgeClient: BridgeClient | null = null;\n\n private destroyOptions?: ChromePageDestroyOptions;\n\n private newlyCreatedTabIds: number[] = [];\n\n // Connection confirmation state\n private confirmationPromise: Promise<boolean> | null = null;\n\n constructor(\n public serverEndpoint?: string,\n public onDisconnect: () => void = () => {},\n public onLogMessage: (\n message: string,\n type: 'log' | 'status',\n ) => void = () => {},\n forceSameTabNavigation = true,\n public onConnectionRequest?: () => Promise<boolean>,\n ) {\n super(forceSameTabNavigation);\n }\n\n private async setupBridgeClient() {\n const endpoint =\n this.serverEndpoint ||\n `ws://${DefaultBridgeServerHost}:${DefaultBridgeServerPort}`;\n\n // Create confirmation gate BEFORE establishing connection,\n // so that any calls received immediately after connection are blocked\n // until user confirms. This prevents a race condition where server-side\n // queued calls bypass the confirmation dialog.\n let resolveConfirmationGate: (allowed: boolean) => void = () => {};\n if (this.onConnectionRequest) {\n this.confirmationPromise = new Promise<boolean>((resolve) => {\n resolveConfirmationGate = resolve;\n });\n }\n\n this.bridgeClient = new BridgeClient(\n endpoint,\n async (method, args: any[]) => {\n // Wait for user confirmation before processing any commands\n if (this.confirmationPromise) {\n const allowed = await this.confirmationPromise;\n if (!allowed) {\n throw new Error('Connection denied by user');\n }\n }\n\n this.onLogMessage(`bridge call from cli side: ${method}`, 'log');\n if (method === BridgeEvent.ConnectNewTabWithUrl) {\n return this.connectNewTabWithUrl.apply(\n this,\n args as unknown as [string],\n );\n }\n\n if (method === BridgeEvent.GetBrowserTabList) {\n return this.getBrowserTabList.apply(this, args as any);\n }\n\n if (method === BridgeEvent.SetActiveTabId) {\n return this.setActiveTabId.apply(this, args as any);\n }\n\n if (method === BridgeEvent.ConnectCurrentTab) {\n return this.connectCurrentTab.apply(this, args as any);\n }\n\n if (method === BridgeEvent.UpdateAgentStatus) {\n return this.onLogMessage(args[0] as string, 'status');\n }\n\n const tabId = await this.getActiveTabId();\n if (!tabId || tabId === 0) {\n throw new Error('no tab is connected');\n }\n\n // this.onLogMessage(`calling method: ${method}`);\n\n if (method.startsWith(MouseEvent.PREFIX)) {\n const actionName = method.split('.')[1] as keyof MouseAction;\n if (actionName === 'drag') {\n return this.mouse[actionName].apply(this.mouse, args as any);\n }\n return this.mouse[actionName].apply(this.mouse, args as any);\n }\n\n if (method.startsWith(KeyboardEvent.PREFIX)) {\n const actionName = method.split('.')[1] as keyof KeyboardAction;\n if (actionName === 'press') {\n return this.keyboard[actionName].apply(this.keyboard, args as any);\n }\n return this.keyboard[actionName].apply(this.keyboard, args as any);\n }\n\n // Generic method lookup. Methods like `setWaterFlowAnimationEnabled`\n // and `getWaterFlowAnimationEnabled` are inherited from\n // ChromeExtensionProxyPage and found via `this[method]`.\n if (!this[method as keyof ChromeExtensionProxyPage]) {\n this.onLogMessage(`method not found: ${method}`, 'log');\n return undefined;\n }\n\n try {\n // @ts-expect-error\n const result = await this[method as keyof ChromeExtensionProxyPage](\n ...args,\n );\n return result;\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : 'Unknown error';\n this.onLogMessage(\n `Error calling method: ${method}, ${errorMessage}`,\n 'log',\n );\n throw new Error(errorMessage, { cause: e });\n }\n },\n // on disconnect\n () => {\n return this.destroy();\n },\n );\n await this.bridgeClient.connect();\n\n // Show confirmation dialog after connection is established\n if (this.onConnectionRequest) {\n this.onLogMessage('Waiting for user confirmation...', 'log');\n const allowed = await this.onConnectionRequest();\n resolveConfirmationGate(allowed);\n this.confirmationPromise = null;\n\n if (!allowed) {\n this.onLogMessage('Connection denied by user', 'log');\n this.bridgeClient.disconnect();\n this.bridgeClient = null;\n throw new Error('Connection denied by user');\n }\n }\n\n this.onLogMessage(\n `Bridge connected, cli-side version v${this.bridgeClient.serverVersion}, browser-side version v${__VERSION__}`,\n 'log',\n );\n }\n\n public async connect() {\n return await this.setupBridgeClient();\n }\n\n public async connectNewTabWithUrl(\n url: string,\n options: BridgeConnectTabOptions = {\n forceSameTabNavigation: true,\n },\n ) {\n // Set the water-flow animation flag BEFORE any debugger commands are\n // sent (which trigger enableWaterFlowAnimation via sendCommandToDebugger).\n // Otherwise the animation gets injected during the connection flow\n // before the CLI side's setWaterFlowAnimationEnabled(false) arrives.\n if (options.enableWaterFlowAnimation !== undefined) {\n this.waterFlowAnimationEnabled = options.enableWaterFlowAnimation;\n }\n\n // Preserve the historical default: activate the new tab unless the caller opts into background mode.\n const activate = options.activateTab ?? true;\n const tab = await chrome.tabs.create({ url, active: activate });\n const tabId = tab.id;\n assert(tabId, 'failed to get tabId after creating a new tab');\n\n // new tab\n this.onLogMessage(`Creating new tab: ${url}`, 'log');\n this.newlyCreatedTabIds.push(tabId);\n\n this.forceSameTabNavigation = options?.forceSameTabNavigation ?? true;\n\n // chrome.tabs.create returns immediately with an about:blank target,\n // then navigates to `url`. If we attach the debugger during that\n // cross-origin transition Site Isolation will detach it again, leaving\n // the first CDP command to fail with \"Debugger is not attached to the\n // tab\". Wait for navigation to settle so the lazy attach lands on a\n // stable target.\n await waitForTabNavigationComplete(tabId, url);\n\n await this.setActiveTabId(tabId, { activate });\n }\n\n public async connectCurrentTab(\n options: BridgeConnectTabOptions = {\n forceSameTabNavigation: true,\n },\n ) {\n // Set the water-flow animation flag BEFORE any debugger commands are\n // sent (which trigger enableWaterFlowAnimation via sendCommandToDebugger).\n if (options.enableWaterFlowAnimation !== undefined) {\n this.waterFlowAnimationEnabled = options.enableWaterFlowAnimation;\n }\n\n const tabs =\n options?.tabId !== undefined\n ? [await chrome.tabs.get(options.tabId)]\n : await chrome.tabs.query({ active: true, currentWindow: true });\n const tabId = tabs[0]?.id;\n assert(tabId, 'failed to get tabId');\n\n this.onLogMessage(`Connected to current tab: ${tabs[0]?.url}`, 'log');\n\n this.forceSameTabNavigation = options?.forceSameTabNavigation ?? true;\n\n await this.setActiveTabId(tabId);\n }\n\n public async setDestroyOptions(options: ChromePageDestroyOptions) {\n this.destroyOptions = options;\n }\n\n async destroy() {\n if (this.destroyOptions?.closeTab && this.newlyCreatedTabIds.length > 0) {\n this.onLogMessage('Closing all newly created tabs by bridge...', 'log');\n for (const tabId of this.newlyCreatedTabIds) {\n await chrome.tabs.remove(tabId);\n }\n this.newlyCreatedTabIds = [];\n }\n\n await super.destroy();\n\n if (this.bridgeClient) {\n this.bridgeClient.disconnect();\n this.bridgeClient = null;\n this.onDisconnect();\n }\n }\n}\n"],"names":["__webpack_require__","module","getter","definition","key","Object","obj","prop","Symbol","NEW_TAB_LOAD_TIMEOUT_MS","isBlankUrl","url","waitForTabNavigationComplete","tabId","targetUrl","timeoutMs","Promise","resolve","settled","finish","chrome","onUpdated","clearTimeout","timer","isReady","tab","currentUrl","id","_info","setTimeout","ExtensionBridgePageBrowserSide","ChromeExtensionProxyPage","endpoint","DefaultBridgeServerHost","DefaultBridgeServerPort","resolveConfirmationGate","BridgeClient","method","args","allowed","Error","BridgeEvent","MouseEvent","actionName","KeyboardEvent","result","e","errorMessage","options","undefined","activate","assert","tabs","serverEndpoint","onDisconnect","onLogMessage","forceSameTabNavigation","onConnectionRequest"],"mappings":";;;IACAA,oBAAoB,CAAC,GAAG,CAACC;QACxB,IAAIC,SAASD,UAAUA,OAAO,UAAU,GACvC,IAAOA,MAAM,CAAC,UAAU,GACxB,IAAOA;QACRD,oBAAoB,CAAC,CAACE,QAA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,IAAI,EACtBC,mBAA4C,CACnD;QACA,KAAK,CAACD,yBAAAA,iBAAAA,IAAAA,EAAAA,kBAAAA,KAAAA,IAAAA,iBAAAA,IAAAA,EAAAA,gBAAAA,KAAAA,IAAAA,iBAAAA,IAAAA,EAAAA,gBAAAA,KAAAA,IAAAA,iBAAAA,IAAAA,EAAAA,uBAAAA,KAAAA,IAnBR,uBAAO,gBAAP,SAEA,uBAAQ,kBAAR,SAEA,uBAAQ,sBAAR,SAGA,uBAAQ,uBAAR,cAGSH,cAAc,GAAdA,gBAAAA,IAAAA,CACAC,YAAY,GAAZA,cAAAA,IAAAA,CACAC,YAAY,GAAZA,cAAAA,IAAAA,CAKAE,mBAAmB,GAAnBA,qBAAAA,IAAAA,CAjBF,YAAY,GAAwB,WAInC,kBAAkB,GAAa,EAAE,OAGjC,mBAAmB,GAA4B;IAavD;AAsNF"}
|
|
1
|
+
{"version":3,"file":"bridge-mode/page-browser-side.js","sources":["webpack/runtime/compat_get_default_export","webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../src/bridge-mode/page-browser-side.ts"],"sourcesContent":["// getDefaultExport function for compatibility with non-ESM modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};\n","__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { assert } from '@midscene/shared/utils';\nimport ChromeExtensionProxyPage from '../chrome-extension/page';\nimport type {\n ChromePageDestroyOptions,\n KeyboardAction,\n MouseAction,\n} from '../web-page';\nimport {\n type BridgeConnectTabOptions,\n BridgeEvent,\n DefaultBridgeServerHost,\n DefaultBridgeServerPort,\n KeyboardEvent,\n MouseEvent,\n} from './common';\nimport { BridgeClient } from './io-client';\n\ndeclare const __VERSION__: string;\n\nconst NEW_TAB_LOAD_TIMEOUT_MS = 30_000;\n\nfunction isBlankUrl(url: string | undefined): boolean {\n if (!url) return true;\n return url === 'about:blank' || url.startsWith('chrome://newtab');\n}\n\n// Wait until the freshly created tab has navigated away from about:blank\n// and reached `status === 'complete'`. Resolves on timeout instead of\n// throwing so callers degrade to the existing lazy-attach behavior.\nfunction waitForTabNavigationComplete(\n tabId: number,\n targetUrl: string,\n timeoutMs = NEW_TAB_LOAD_TIMEOUT_MS,\n): Promise<void> {\n return new Promise((resolve) => {\n let settled = false;\n const finish = () => {\n if (settled) return;\n settled = true;\n try {\n chrome.tabs.onUpdated.removeListener(onUpdated);\n } catch {}\n clearTimeout(timer);\n resolve();\n };\n\n const isReady = (tab: chrome.tabs.Tab | undefined): boolean => {\n if (!tab) return false;\n if (tab.status !== 'complete') return false;\n const currentUrl = tab.url || tab.pendingUrl || '';\n // Skip the initial about:blank \"complete\" that fires before\n // the target URL navigation kicks in.\n if (isBlankUrl(currentUrl) && !isBlankUrl(targetUrl)) return false;\n return true;\n };\n\n const onUpdated = (\n id: number,\n _info: chrome.tabs.TabChangeInfo,\n tab: chrome.tabs.Tab,\n ) => {\n if (id !== tabId) return;\n if (isReady(tab)) finish();\n };\n\n chrome.tabs.onUpdated.addListener(onUpdated);\n const timer = setTimeout(finish, timeoutMs);\n\n // Handle the race where the tab already finished loading before\n // we registered the listener.\n chrome.tabs\n .get(tabId)\n .then((tab) => {\n if (isReady(tab)) finish();\n })\n .catch(() => {});\n });\n}\n\nexport class ExtensionBridgePageBrowserSide extends ChromeExtensionProxyPage {\n public bridgeClient: BridgeClient | null = null;\n\n private destroyOptions?: ChromePageDestroyOptions;\n\n private newlyCreatedTabIds: number[] = [];\n\n // Connection confirmation state\n private confirmationPromise: Promise<boolean> | null = null;\n\n constructor(\n public serverEndpoint?: string,\n public onDisconnect: () => void = () => {},\n public onLogMessage: (\n message: string,\n type: 'log' | 'status',\n ) => void = () => {},\n forceSameTabNavigation = true,\n public onConnectionRequest?: () => Promise<boolean>,\n ) {\n super(forceSameTabNavigation);\n }\n\n private async setupBridgeClient() {\n const endpoint =\n this.serverEndpoint ||\n `ws://${DefaultBridgeServerHost}:${DefaultBridgeServerPort}`;\n\n // Create confirmation gate BEFORE establishing connection,\n // so that any calls received immediately after connection are blocked\n // until user confirms. This prevents a race condition where server-side\n // queued calls bypass the confirmation dialog.\n let resolveConfirmationGate: (allowed: boolean) => void = () => {};\n if (this.onConnectionRequest) {\n this.confirmationPromise = new Promise<boolean>((resolve) => {\n resolveConfirmationGate = resolve;\n });\n }\n\n this.bridgeClient = new BridgeClient(\n endpoint,\n async (method, args: any[]) => {\n // Wait for user confirmation before processing any commands\n if (this.confirmationPromise) {\n const allowed = await this.confirmationPromise;\n if (!allowed) {\n throw new Error('Connection denied by user');\n }\n }\n\n this.onLogMessage(`bridge call from cli side: ${method}`, 'log');\n if (method === BridgeEvent.ConnectNewTabWithUrl) {\n return this.connectNewTabWithUrl.apply(\n this,\n args as unknown as [string],\n );\n }\n\n if (method === BridgeEvent.GetBrowserTabList) {\n return this.getBrowserTabList.apply(this, args as any);\n }\n\n if (method === BridgeEvent.SetActiveTabId) {\n return this.setActiveTabId.apply(this, args as any);\n }\n\n if (method === BridgeEvent.ConnectCurrentTab) {\n return this.connectCurrentTab.apply(this, args as any);\n }\n\n if (method === BridgeEvent.UpdateAgentStatus) {\n return this.onLogMessage(args[0] as string, 'status');\n }\n\n const tabId = await this.getActiveTabId();\n if (!tabId || tabId === 0) {\n throw new Error('no tab is connected');\n }\n\n // this.onLogMessage(`calling method: ${method}`);\n\n if (method.startsWith(MouseEvent.PREFIX)) {\n const actionName = method.split('.')[1] as keyof MouseAction;\n if (actionName === 'drag') {\n return this.mouse[actionName].apply(this.mouse, args as any);\n }\n return this.mouse[actionName].apply(this.mouse, args as any);\n }\n\n if (method.startsWith(KeyboardEvent.PREFIX)) {\n const actionName = method.split('.')[1] as keyof KeyboardAction;\n if (actionName === 'press') {\n return this.keyboard[actionName].apply(this.keyboard, args as any);\n }\n return this.keyboard[actionName].apply(this.keyboard, args as any);\n }\n\n // Generic method lookup. Methods like `setWaterFlowAnimationEnabled`\n // and `getWaterFlowAnimationEnabled` are inherited from\n // ChromeExtensionProxyPage and found via `this[method]`.\n if (!this[method as keyof ChromeExtensionProxyPage]) {\n this.onLogMessage(`method not found: ${method}`, 'log');\n return undefined;\n }\n\n try {\n // @ts-expect-error\n const result = await this[method as keyof ChromeExtensionProxyPage](\n ...args,\n );\n return result;\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : 'Unknown error';\n this.onLogMessage(\n `Error calling method: ${method}, ${errorMessage}`,\n 'log',\n );\n throw new Error(errorMessage, { cause: e });\n }\n },\n // on disconnect\n () => {\n return this.destroy();\n },\n );\n await this.bridgeClient.connect();\n\n // Show confirmation dialog after connection is established\n if (this.onConnectionRequest) {\n this.onLogMessage('Waiting for user confirmation...', 'log');\n const allowed = await this.onConnectionRequest();\n resolveConfirmationGate(allowed);\n this.confirmationPromise = null;\n\n if (!allowed) {\n this.onLogMessage('Connection denied by user', 'log');\n this.bridgeClient.disconnect();\n this.bridgeClient = null;\n throw new Error('Connection denied by user');\n }\n }\n\n this.onLogMessage(\n `Bridge connected, cli-side version v${this.bridgeClient.serverVersion}, browser-side version v${__VERSION__}`,\n 'log',\n );\n }\n\n public async connect() {\n return await this.setupBridgeClient();\n }\n\n public async connectNewTabWithUrl(\n url: string,\n options: BridgeConnectTabOptions = {\n forceSameTabNavigation: true,\n },\n ) {\n // Set the water-flow animation flag BEFORE any debugger commands are\n // sent (which trigger enableWaterFlowAnimation via sendCommandToDebugger).\n // Otherwise the animation gets injected during the connection flow\n // before the CLI side's setWaterFlowAnimationEnabled(false) arrives.\n if (options.enableWaterFlowAnimation !== undefined) {\n this.waterFlowAnimationEnabled = options.enableWaterFlowAnimation;\n }\n\n // Preserve the historical default: activate the new tab unless the caller opts into background mode.\n const activate = options.activateTab ?? true;\n const tab = await chrome.tabs.create({ url, active: activate });\n const tabId = tab.id;\n assert(tabId, 'failed to get tabId after creating a new tab');\n\n // new tab\n this.onLogMessage(`Creating new tab: ${url}`, 'log');\n this.newlyCreatedTabIds.push(tabId);\n\n this.forceSameTabNavigation = options?.forceSameTabNavigation ?? true;\n\n // chrome.tabs.create returns immediately with an about:blank target,\n // then navigates to `url`. If we attach the debugger during that\n // cross-origin transition Site Isolation will detach it again, leaving\n // the first CDP command to fail with \"Debugger is not attached to the\n // tab\". Wait for navigation to settle so the lazy attach lands on a\n // stable target.\n await waitForTabNavigationComplete(tabId, url);\n\n await this.setActiveTabId(tabId, { activate });\n }\n\n public async connectCurrentTab(\n options: BridgeConnectTabOptions = {\n forceSameTabNavigation: true,\n },\n ) {\n // Set the water-flow animation flag BEFORE any debugger commands are\n // sent (which trigger enableWaterFlowAnimation via sendCommandToDebugger).\n if (options.enableWaterFlowAnimation !== undefined) {\n this.waterFlowAnimationEnabled = options.enableWaterFlowAnimation;\n }\n\n const tabs =\n options?.tabId !== undefined\n ? [await chrome.tabs.get(options.tabId)]\n : await chrome.tabs.query({ active: true, currentWindow: true });\n const tabId = tabs[0]?.id;\n assert(tabId, 'failed to get tabId');\n\n this.onLogMessage(`Connected to current tab: ${tabs[0]?.url}`, 'log');\n\n this.forceSameTabNavigation = options?.forceSameTabNavigation ?? true;\n\n await this.setActiveTabId(tabId);\n }\n\n public async setDestroyOptions(options: ChromePageDestroyOptions) {\n this.destroyOptions = options;\n }\n\n async destroy() {\n if (this.destroyOptions?.closeTab && this.newlyCreatedTabIds.length > 0) {\n this.onLogMessage('Closing all newly created tabs by bridge...', 'log');\n for (const tabId of this.newlyCreatedTabIds) {\n await chrome.tabs.remove(tabId);\n }\n this.newlyCreatedTabIds = [];\n }\n\n await super.destroy();\n\n if (this.bridgeClient) {\n this.bridgeClient.disconnect();\n this.bridgeClient = null;\n this.onDisconnect();\n }\n }\n}\n"],"names":["__webpack_require__","module","getter","definition","key","Object","obj","prop","Symbol","NEW_TAB_LOAD_TIMEOUT_MS","isBlankUrl","url","waitForTabNavigationComplete","tabId","targetUrl","timeoutMs","Promise","resolve","settled","finish","chrome","onUpdated","clearTimeout","timer","isReady","tab","currentUrl","id","_info","setTimeout","ExtensionBridgePageBrowserSide","ChromeExtensionProxyPage","endpoint","DefaultBridgeServerHost","DefaultBridgeServerPort","resolveConfirmationGate","BridgeClient","method","args","allowed","Error","BridgeEvent","MouseEvent","actionName","KeyboardEvent","result","e","errorMessage","options","undefined","activate","assert","tabs","serverEndpoint","onDisconnect","onLogMessage","forceSameTabNavigation","onConnectionRequest"],"mappings":";;;IACAA,oBAAoB,CAAC,GAAG,CAACC;QACxB,IAAIC,SAASD,UAAUA,OAAO,UAAU,GACvC,IAAOA,MAAM,CAAC,UAAU,GACxB,IAAOA;QACRD,oBAAoB,CAAC,CAACE,QAAQ;YAAE,GAAGA;QAAO;QAC1C,OAAOA;IACR;;;ICPAF,oBAAoB,CAAC,GAAG,CAAC,UAASG;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGH,oBAAoB,CAAC,CAACG,YAAYC,QAAQ,CAACJ,oBAAoB,CAAC,CAAC,UAASI,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAJ,oBAAoB,CAAC,GAAG,CAACM,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFP,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,MAAlB,OAAOQ,UAA0BA,OAAO,WAAW,EACrDH,OAAO,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kB,GAAa,EAAE,OAGjC,mBAAmB,GAA4B;IAavD;AAsNF"}
|
package/dist/lib/cli.js
CHANGED
|
@@ -42,7 +42,7 @@ Promise.resolve().then(()=>{
|
|
|
42
42
|
return (0, cli_namespaceObject.runToolsCLI)(tools, 'midscene-web', {
|
|
43
43
|
stripPrefix: 'web_',
|
|
44
44
|
argv: parsedOptions.argv,
|
|
45
|
-
version: "1.
|
|
45
|
+
version: "1.18.0",
|
|
46
46
|
extraCommands: (0, core_namespaceObject.createReportCliCommands)()
|
|
47
47
|
});
|
|
48
48
|
}).catch((e)=>{
|
|
@@ -82,8 +82,10 @@ const parseCookieHeader = (raw, url)=>{
|
|
|
82
82
|
const parseCookieJson = (raw)=>{
|
|
83
83
|
try {
|
|
84
84
|
return JSON.parse(raw);
|
|
85
|
-
} catch
|
|
86
|
-
throw new TypeError('setCookies source must contain valid JSON or a Cookie header.'
|
|
85
|
+
} catch (cause) {
|
|
86
|
+
throw new TypeError('setCookies source must contain valid JSON or a Cookie header.', {
|
|
87
|
+
cause
|
|
88
|
+
});
|
|
87
89
|
}
|
|
88
90
|
};
|
|
89
91
|
const normalizeCookie = (candidate, defaultUrl, index)=>{
|
|
@@ -119,8 +121,10 @@ const resolveCookieInput = async (input, ctx, options)=>{
|
|
|
119
121
|
let env;
|
|
120
122
|
try {
|
|
121
123
|
env = await options.getEnv?.(ctx) ?? process.env;
|
|
122
|
-
} catch
|
|
123
|
-
throw new Error(`Failed to resolve cookie environment ${reference.name}
|
|
124
|
+
} catch (cause) {
|
|
125
|
+
throw new Error(`Failed to resolve cookie environment ${reference.name}.`, {
|
|
126
|
+
cause
|
|
127
|
+
});
|
|
124
128
|
}
|
|
125
129
|
const raw = env[reference.name];
|
|
126
130
|
if (!raw?.trim()) throw new Error(`Environment variable ${reference.name} is missing or blank.`);
|
|
@@ -136,8 +140,10 @@ const resolveCookieInput = async (input, ctx, options)=>{
|
|
|
136
140
|
context: ctx.context,
|
|
137
141
|
signal: ctx.signal
|
|
138
142
|
});
|
|
139
|
-
} catch
|
|
140
|
-
throw new Error(`Failed to resolve cookie profile ${reference.name}
|
|
143
|
+
} catch (cause) {
|
|
144
|
+
throw new Error(`Failed to resolve cookie profile ${reference.name}.`, {
|
|
145
|
+
cause
|
|
146
|
+
});
|
|
141
147
|
}
|
|
142
148
|
break;
|
|
143
149
|
case 'storage-state':
|
|
@@ -146,8 +152,10 @@ const resolveCookieInput = async (input, ctx, options)=>{
|
|
|
146
152
|
try {
|
|
147
153
|
const path = options.resolveStorageStatePath ? await options.resolveStorageStatePath(reference.name, ctx) : (0, external_node_path_namespaceObject.resolve)(process.cwd(), reference.name);
|
|
148
154
|
contents = await (0, promises_namespaceObject.readFile)(path, 'utf8');
|
|
149
|
-
} catch
|
|
150
|
-
throw new Error(`Failed to read cookie storage state ${reference.name}
|
|
155
|
+
} catch (cause) {
|
|
156
|
+
throw new Error(`Failed to read cookie storage state ${reference.name}.`, {
|
|
157
|
+
cause
|
|
158
|
+
});
|
|
151
159
|
}
|
|
152
160
|
source = parseCookieJson(contents);
|
|
153
161
|
break;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"common/test-runner/cookies.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../src/common/test-runner/cookies.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { readFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { z } from 'zod/v4';\nimport { resolveWebUrl } from './utils';\n\ntype Awaitable<T> = T | Promise<T>;\n\nexport type CookieSourceReference =\n | { kind: 'env'; name: string }\n | { kind: 'profile'; name: string }\n | { kind: 'storage-state'; name: string };\n\nexport interface WebNodeContext<TContext> {\n input: unknown;\n context: TContext;\n signal: AbortSignal;\n}\n\nexport interface CookieProfileContext<TContext> {\n profile: string;\n context: TContext;\n signal: AbortSignal;\n}\n\nexport interface WebCookieSourceOptions<TAgent> {\n getEnv?(\n ctx: WebNodeContext<TAgent>,\n ): Awaitable<Readonly<Record<string, string | undefined>>>;\n getCookieProfile?(input: CookieProfileContext<TAgent>): Awaitable<unknown>;\n resolveStorageStatePath?(\n path: string,\n ctx: WebNodeContext<TAgent>,\n ): Awaitable<string>;\n}\n\nexport interface PortableWebCookie extends Record<string, unknown> {\n name: string;\n value: string;\n url?: string;\n domain?: string;\n path?: string;\n}\n\nexport const setCookiesInputSchema = z\n .strictObject({\n cookiesEnv: z\n .string()\n .regex(/^[A-Za-z_][A-Za-z0-9_]*$/)\n .optional()\n .describe(\n 'The environment variable containing a Cookie header, cookie array JSON, or browser storage-state JSON.',\n ),\n profile: z\n .string()\n .regex(/\\S/)\n .optional()\n .describe('A cookie profile resolved by getCookieProfile().'),\n storageStatePath: z\n .string()\n .regex(/\\S/)\n .optional()\n .describe('A path to a browser storage-state JSON file.'),\n url: z\n .string()\n .url()\n .optional()\n .describe(\n 'The HTTP(S) URL used to scope Cookie-header values or cookies without domain/path.',\n ),\n })\n .superRefine((input, ctx) => {\n const sourceCount = [\n input.cookiesEnv,\n input.profile,\n input.storageStatePath,\n ].filter((value) => value !== undefined).length;\n if (sourceCount !== 1) {\n ctx.addIssue({\n code: 'custom',\n message:\n 'exactly one of cookiesEnv, profile, and storageStatePath is required',\n });\n }\n });\n\nexport type SetCookiesNodeInput = z.infer<typeof setCookiesInputSchema>;\n\nexport interface SetCookiesNodeResult {\n source: CookieSourceReference['kind'];\n sourceName: string;\n count: number;\n}\n\nconst toCookieSourceReference = (\n input: SetCookiesNodeInput,\n): CookieSourceReference => {\n if (input.cookiesEnv !== undefined) {\n return { kind: 'env', name: input.cookiesEnv };\n }\n if (input.profile !== undefined) {\n return { kind: 'profile', name: input.profile };\n }\n if (input.storageStatePath !== undefined) {\n return { kind: 'storage-state', name: input.storageStatePath };\n }\n throw new TypeError('setCookies requires one cookie source.');\n};\n\nconst parseCookieHeader = (raw: string, url: string | undefined) => {\n if (url === undefined) {\n throw new TypeError(\n 'setCookies.url is required when cookiesEnv contains a Cookie header.',\n );\n }\n const segments = raw\n .split(';')\n .map((segment) => segment.trim())\n .filter(Boolean);\n if (segments.length === 0) {\n throw new TypeError('setCookies Cookie header contains no cookies.');\n }\n return segments.map((segment) => {\n const separator = segment.indexOf('=');\n if (separator <= 0) {\n throw new TypeError(\n 'setCookies Cookie header contains an invalid name/value pair.',\n );\n }\n const name = segment.slice(0, separator).trim();\n const value = segment.slice(separator + 1).trim();\n if (!name) {\n throw new TypeError('setCookies Cookie header contains an empty name.');\n }\n return { name, value, url } satisfies PortableWebCookie;\n });\n};\n\nconst parseCookieJson = (raw: string): unknown => {\n try {\n return JSON.parse(raw);\n } catch {\n throw new TypeError(\n 'setCookies source must contain valid JSON or a Cookie header.',\n );\n }\n};\n\nconst normalizeCookie = (\n candidate: unknown,\n defaultUrl: string | undefined,\n index: number,\n): PortableWebCookie => {\n if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {\n throw new TypeError(\n `setCookies cookie at index ${index} must be an object.`,\n );\n }\n const cookie = candidate as Record<string, unknown>;\n if (typeof cookie.name !== 'string' || !cookie.name.trim()) {\n throw new TypeError(\n `setCookies cookie at index ${index} requires a non-blank name.`,\n );\n }\n if (typeof cookie.value !== 'string') {\n throw new TypeError(\n `setCookies cookie at index ${index} requires a string value.`,\n );\n }\n\n const normalized = { ...cookie } as PortableWebCookie;\n const hasUrl = typeof cookie.url === 'string' && cookie.url.length > 0;\n const hasDomain =\n typeof cookie.domain === 'string' && cookie.domain.length > 0;\n if (!hasUrl && !hasDomain) {\n if (defaultUrl === undefined) {\n throw new TypeError(\n `setCookies cookie at index ${index} requires url or domain, or setCookies.url must be provided.`,\n );\n }\n normalized.url = defaultUrl;\n }\n if (hasDomain && typeof cookie.path !== 'string') normalized.path = '/';\n return normalized;\n};\n\nconst normalizeCookies = (\n source: unknown,\n defaultUrl: string | undefined,\n): PortableWebCookie[] => {\n const candidates = Array.isArray(source)\n ? source\n : source &&\n typeof source === 'object' &&\n Array.isArray((source as { cookies?: unknown }).cookies)\n ? (source as { cookies: unknown[] }).cookies\n : undefined;\n if (!candidates) {\n throw new TypeError(\n 'setCookies JSON must be a cookie array or an object with a cookies array.',\n );\n }\n if (candidates.length === 0) {\n throw new TypeError('setCookies source contains no cookies.');\n }\n return candidates.map((cookie, index) =>\n normalizeCookie(cookie, defaultUrl, index),\n );\n};\n\nexport const resolveCookieInput = async <TAgent>(\n input: SetCookiesNodeInput,\n ctx: WebNodeContext<TAgent>,\n options: WebCookieSourceOptions<TAgent>,\n): Promise<{\n cookies: PortableWebCookie[];\n result: SetCookiesNodeResult;\n}> => {\n const defaultUrl =\n input.url === undefined\n ? undefined\n : resolveWebUrl(input.url, undefined, 'setCookies.url');\n const reference = toCookieSourceReference(input);\n let source: unknown;\n switch (reference.kind) {\n case 'env': {\n let env: Readonly<Record<string, string | undefined>>;\n try {\n env = (await options.getEnv?.(ctx)) ?? process.env;\n } catch {\n throw new Error(\n `Failed to resolve cookie environment ${reference.name}; the original error was redacted because it may contain cookie values.`,\n );\n }\n const raw = env[reference.name];\n if (!raw?.trim()) {\n throw new Error(\n `Environment variable ${reference.name} is missing or blank.`,\n );\n }\n const trimmed = raw.trim();\n source = /^[\\[{]/.test(trimmed)\n ? parseCookieJson(trimmed)\n : parseCookieHeader(trimmed, defaultUrl);\n break;\n }\n case 'profile': {\n if (!options.getCookieProfile) {\n throw new Error(\n 'setCookies.profile requires a configured getCookieProfile callback.',\n );\n }\n try {\n source = await options.getCookieProfile({\n profile: reference.name,\n context: ctx.context,\n signal: ctx.signal,\n });\n } catch {\n throw new Error(\n `Failed to resolve cookie profile ${reference.name}; the original error was redacted because it may contain cookie values.`,\n );\n }\n break;\n }\n case 'storage-state': {\n let contents: string;\n try {\n const path = options.resolveStorageStatePath\n ? await options.resolveStorageStatePath(reference.name, ctx)\n : resolve(process.cwd(), reference.name);\n contents = await readFile(path, 'utf8');\n } catch {\n throw new Error(\n `Failed to read cookie storage state ${reference.name}; the original error was redacted because it may contain cookie values.`,\n );\n }\n source = parseCookieJson(contents);\n break;\n }\n }\n const cookies = normalizeCookies(source, defaultUrl);\n return {\n cookies,\n result: {\n source: reference.kind,\n sourceName: reference.name,\n count: cookies.length,\n },\n };\n};\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","setCookiesInputSchema","z","input","ctx","sourceCount","value","undefined","toCookieSourceReference","TypeError","parseCookieHeader","raw","url","segments","segment","Boolean","separator","name","parseCookieJson","JSON","normalizeCookie","candidate","defaultUrl","index","Array","cookie","normalized","hasUrl","hasDomain","normalizeCookies","source","candidates","resolveCookieInput","options","resolveWebUrl","reference","env","process","Error","trimmed","contents","path","resolve","readFile","cookies"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,MAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,O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,CAACxB,KAAK,QACR,MAAM,IAAI2B,MACR,CAAC,qBAAqB,EAAEH,UAAU,IAAI,CAAC,qBAAqB,CAAC;gBAGjE,MAAMI,UAAU5B,IAAI,IAAI;gBACxBmB,SAAS,SAAS,IAAI,CAACS,WACnBrB,gBAAgBqB,WAChB7B,kBAAkB6B,SAASjB;gBAC/B;YACF;QACA,KAAK;YACH,IAAI,CAACW,QAAQ,gBAAgB,EAC3B,MAAM,IAAIK,MACR;YAGJ,IAAI;gBACFR,SAAS,MAAMG,QAAQ,gBAAgB,CAAC;oBACtC,SAASE,UAAU,IAAI;oBACvB,SAAS/B,IAAI,OAAO;oBACpB,QAAQA,IAAI,MAAM;gBACpB;YACF,EAAE,OAAM;gBACN,MAAM,IAAIkC,MACR,CAAC,iCAAiC,EAAEH,UAAU,IAAI,CAAC,uEAAuE,CAAC;YAE/H;YACA;QAEF,KAAK;YAAiB;gBACpB,IAAIK;gBACJ,IAAI;oBACF,MAAMC,OAAOR,QAAQ,uBAAuB,GACxC,MAAMA,QAAQ,uBAAuB,CAACE,UAAU,IAAI,EAAE/B,OACtDsC,AAAAA,IAAAA,mCAAAA,OAAAA,AAAAA,EAAQL,QAAQ,GAAG,IAAIF,UAAU,IAAI;oBACzCK,WAAW,MAAMG,AAAAA,IAAAA,yBAAAA,QAAAA,AAAAA,EAASF,MAAM;gBAClC,EAAE,OAAM;oBACN,MAAM,IAAIH,MACR,CAAC,oCAAoC,EAAEH,UAAU,IAAI,CAAC,uEAAuE,CAAC;gBAElI;gBACAL,SAASZ,gBAAgBsB;gBACzB;YACF;IACF;IACA,MAAMI,UAAUf,iBAAiBC,QAAQR;IACzC,OAAO;QACLsB;QACA,QAAQ;YACN,QAAQT,UAAU,IAAI;YACtB,YAAYA,UAAU,IAAI;YAC1B,OAAOS,QAAQ,MAAM;QACvB;IACF;AACF"}
|
|
1
|
+
{"version":3,"file":"common/test-runner/cookies.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../src/common/test-runner/cookies.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { readFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { z } from 'zod/v4';\nimport { resolveWebUrl } from './utils';\n\ntype Awaitable<T> = T | Promise<T>;\n\nexport type CookieSourceReference =\n | { kind: 'env'; name: string }\n | { kind: 'profile'; name: string }\n | { kind: 'storage-state'; name: string };\n\nexport interface WebNodeContext<TContext> {\n input: unknown;\n context: TContext;\n signal: AbortSignal;\n}\n\nexport interface CookieProfileContext<TContext> {\n profile: string;\n context: TContext;\n signal: AbortSignal;\n}\n\nexport interface WebCookieSourceOptions<TAgent> {\n getEnv?(\n ctx: WebNodeContext<TAgent>,\n ): Awaitable<Readonly<Record<string, string | undefined>>>;\n getCookieProfile?(input: CookieProfileContext<TAgent>): Awaitable<unknown>;\n resolveStorageStatePath?(\n path: string,\n ctx: WebNodeContext<TAgent>,\n ): Awaitable<string>;\n}\n\nexport interface PortableWebCookie extends Record<string, unknown> {\n name: string;\n value: string;\n url?: string;\n domain?: string;\n path?: string;\n}\n\nexport const setCookiesInputSchema = z\n .strictObject({\n cookiesEnv: z\n .string()\n .regex(/^[A-Za-z_][A-Za-z0-9_]*$/)\n .optional()\n .describe(\n 'The environment variable containing a Cookie header, cookie array JSON, or browser storage-state JSON.',\n ),\n profile: z\n .string()\n .regex(/\\S/)\n .optional()\n .describe('A cookie profile resolved by getCookieProfile().'),\n storageStatePath: z\n .string()\n .regex(/\\S/)\n .optional()\n .describe('A path to a browser storage-state JSON file.'),\n url: z\n .string()\n .url()\n .optional()\n .describe(\n 'The HTTP(S) URL used to scope Cookie-header values or cookies without domain/path.',\n ),\n })\n .superRefine((input, ctx) => {\n const sourceCount = [\n input.cookiesEnv,\n input.profile,\n input.storageStatePath,\n ].filter((value) => value !== undefined).length;\n if (sourceCount !== 1) {\n ctx.addIssue({\n code: 'custom',\n message:\n 'exactly one of cookiesEnv, profile, and storageStatePath is required',\n });\n }\n });\n\nexport type SetCookiesNodeInput = z.infer<typeof setCookiesInputSchema>;\n\nexport interface SetCookiesNodeResult {\n source: CookieSourceReference['kind'];\n sourceName: string;\n count: number;\n}\n\nconst toCookieSourceReference = (\n input: SetCookiesNodeInput,\n): CookieSourceReference => {\n if (input.cookiesEnv !== undefined) {\n return { kind: 'env', name: input.cookiesEnv };\n }\n if (input.profile !== undefined) {\n return { kind: 'profile', name: input.profile };\n }\n if (input.storageStatePath !== undefined) {\n return { kind: 'storage-state', name: input.storageStatePath };\n }\n throw new TypeError('setCookies requires one cookie source.');\n};\n\nconst parseCookieHeader = (raw: string, url: string | undefined) => {\n if (url === undefined) {\n throw new TypeError(\n 'setCookies.url is required when cookiesEnv contains a Cookie header.',\n );\n }\n const segments = raw\n .split(';')\n .map((segment) => segment.trim())\n .filter(Boolean);\n if (segments.length === 0) {\n throw new TypeError('setCookies Cookie header contains no cookies.');\n }\n return segments.map((segment) => {\n const separator = segment.indexOf('=');\n if (separator <= 0) {\n throw new TypeError(\n 'setCookies Cookie header contains an invalid name/value pair.',\n );\n }\n const name = segment.slice(0, separator).trim();\n const value = segment.slice(separator + 1).trim();\n if (!name) {\n throw new TypeError('setCookies Cookie header contains an empty name.');\n }\n return { name, value, url } satisfies PortableWebCookie;\n });\n};\n\nconst parseCookieJson = (raw: string): unknown => {\n try {\n return JSON.parse(raw);\n } catch (cause) {\n throw new TypeError(\n 'setCookies source must contain valid JSON or a Cookie header.',\n { cause },\n );\n }\n};\n\nconst normalizeCookie = (\n candidate: unknown,\n defaultUrl: string | undefined,\n index: number,\n): PortableWebCookie => {\n if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {\n throw new TypeError(\n `setCookies cookie at index ${index} must be an object.`,\n );\n }\n const cookie = candidate as Record<string, unknown>;\n if (typeof cookie.name !== 'string' || !cookie.name.trim()) {\n throw new TypeError(\n `setCookies cookie at index ${index} requires a non-blank name.`,\n );\n }\n if (typeof cookie.value !== 'string') {\n throw new TypeError(\n `setCookies cookie at index ${index} requires a string value.`,\n );\n }\n\n const normalized = { ...cookie } as PortableWebCookie;\n const hasUrl = typeof cookie.url === 'string' && cookie.url.length > 0;\n const hasDomain =\n typeof cookie.domain === 'string' && cookie.domain.length > 0;\n if (!hasUrl && !hasDomain) {\n if (defaultUrl === undefined) {\n throw new TypeError(\n `setCookies cookie at index ${index} requires url or domain, or setCookies.url must be provided.`,\n );\n }\n normalized.url = defaultUrl;\n }\n if (hasDomain && typeof cookie.path !== 'string') normalized.path = '/';\n return normalized;\n};\n\nconst normalizeCookies = (\n source: unknown,\n defaultUrl: string | undefined,\n): PortableWebCookie[] => {\n const candidates = Array.isArray(source)\n ? source\n : source &&\n typeof source === 'object' &&\n Array.isArray((source as { cookies?: unknown }).cookies)\n ? (source as { cookies: unknown[] }).cookies\n : undefined;\n if (!candidates) {\n throw new TypeError(\n 'setCookies JSON must be a cookie array or an object with a cookies array.',\n );\n }\n if (candidates.length === 0) {\n throw new TypeError('setCookies source contains no cookies.');\n }\n return candidates.map((cookie, index) =>\n normalizeCookie(cookie, defaultUrl, index),\n );\n};\n\nexport const resolveCookieInput = async <TAgent>(\n input: SetCookiesNodeInput,\n ctx: WebNodeContext<TAgent>,\n options: WebCookieSourceOptions<TAgent>,\n): Promise<{\n cookies: PortableWebCookie[];\n result: SetCookiesNodeResult;\n}> => {\n const defaultUrl =\n input.url === undefined\n ? undefined\n : resolveWebUrl(input.url, undefined, 'setCookies.url');\n const reference = toCookieSourceReference(input);\n let source: unknown;\n switch (reference.kind) {\n case 'env': {\n let env: Readonly<Record<string, string | undefined>>;\n try {\n env = (await options.getEnv?.(ctx)) ?? process.env;\n } catch (cause) {\n throw new Error(\n `Failed to resolve cookie environment ${reference.name}.`,\n { cause },\n );\n }\n const raw = env[reference.name];\n if (!raw?.trim()) {\n throw new Error(\n `Environment variable ${reference.name} is missing or blank.`,\n );\n }\n const trimmed = raw.trim();\n source = /^[\\[{]/.test(trimmed)\n ? parseCookieJson(trimmed)\n : parseCookieHeader(trimmed, defaultUrl);\n break;\n }\n case 'profile': {\n if (!options.getCookieProfile) {\n throw new Error(\n 'setCookies.profile requires a configured getCookieProfile callback.',\n );\n }\n try {\n source = await options.getCookieProfile({\n profile: reference.name,\n context: ctx.context,\n signal: ctx.signal,\n });\n } catch (cause) {\n throw new Error(`Failed to resolve cookie profile ${reference.name}.`, {\n cause,\n });\n }\n break;\n }\n case 'storage-state': {\n let contents: string;\n try {\n const path = options.resolveStorageStatePath\n ? await options.resolveStorageStatePath(reference.name, ctx)\n : resolve(process.cwd(), reference.name);\n contents = await readFile(path, 'utf8');\n } catch (cause) {\n throw new Error(\n `Failed to read cookie storage state ${reference.name}.`,\n { cause },\n );\n }\n source = parseCookieJson(contents);\n break;\n }\n }\n const cookies = normalizeCookies(source, defaultUrl);\n return {\n cookies,\n result: {\n source: reference.kind,\n sourceName: reference.name,\n count: cookies.length,\n },\n };\n};\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","setCookiesInputSchema","z","input","ctx","sourceCount","value","undefined","toCookieSourceReference","TypeError","parseCookieHeader","raw","url","segments","segment","Boolean","separator","name","parseCookieJson","JSON","cause","normalizeCookie","candidate","defaultUrl","index","Array","cookie","normalized","hasUrl","hasDomain","normalizeCookies","source","candidates","resolveCookieInput","options","resolveWebUrl","reference","env","process","Error","trimmed","contents","path","resolve","readFile","cookies"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC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OAAAA,AAAAA,EAAQL,QAAQ,GAAG,IAAIF,UAAU,IAAI;oBACzCK,WAAW,MAAMG,AAAAA,IAAAA,yBAAAA,QAAAA,AAAAA,EAASF,MAAM;gBAClC,EAAE,OAAOtB,OAAO;oBACd,MAAM,IAAImB,MACR,CAAC,oCAAoC,EAAEH,UAAU,IAAI,CAAC,CAAC,CAAC,EACxD;wBAAEhB;oBAAM;gBAEZ;gBACAW,SAASb,gBAAgBuB;gBACzB;YACF;IACF;IACA,MAAMI,UAAUf,iBAAiBC,QAAQR;IACzC,OAAO;QACLsB;QACA,QAAQ;YACN,QAAQT,UAAU,IAAI;YACtB,YAAYA,UAAU,IAAI;YAC1B,OAAOS,QAAQ,MAAM;QACvB;IACF;AACF"}
|
|
@@ -110,8 +110,10 @@ const createWebTestRunnerNodeDefinitions = (adapter)=>{
|
|
|
110
110
|
(0, external_utils_js_namespaceObject.throwIfAborted)(executionContext.signal, 'setCookies');
|
|
111
111
|
try {
|
|
112
112
|
await driver.setCookies(cookies);
|
|
113
|
-
} catch
|
|
114
|
-
throw new Error(`Failed to set ${cookies.length} browser cookie(s)
|
|
113
|
+
} catch (cause) {
|
|
114
|
+
throw new Error(`Failed to set ${cookies.length} browser cookie(s).`, {
|
|
115
|
+
cause
|
|
116
|
+
});
|
|
115
117
|
}
|
|
116
118
|
return {
|
|
117
119
|
summary: `Set ${result.count} browser cookie(s) from ${result.source} ${result.sourceName}`,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"common/test-runner/nodes.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../src/common/test-runner/nodes.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import type { AgentTestRunnerNodeDefinition } from '@midscene/core/agent';\nimport { z } from 'zod/v4';\nimport {\n type SetCookiesNodeResult,\n resolveCookieInput,\n setCookiesInputSchema,\n} from './cookies';\nimport type {\n WebCookieFilters,\n WebTestDriverAdapter,\n WebTestRunnerOptions,\n WebViewportSize,\n} from './driver';\nimport { resolveWebUrl, throwIfAborted } from './utils';\n\nconst DEFAULT_NAVIGATION_TIMEOUT_MS = 60_000;\nconst DEFAULT_WAIT_UNTIL = 'domcontentloaded' as const;\n\nexport const gotoUrlInputSchema = z.strictObject({\n url: z\n .string()\n .min(1)\n .describe(\n 'An absolute HTTP(S) URL or a path relative to testRunner.baseURL or the current page URL.',\n ),\n waitUntil: z\n .enum([\n 'commit',\n 'domcontentloaded',\n 'load',\n 'networkidle',\n 'networkidle0',\n 'networkidle2',\n ])\n .default(DEFAULT_WAIT_UNTIL)\n .describe(\n 'The navigation lifecycle event. domcontentloaded, load, and networkidle are portable across browser drivers.',\n ),\n timeoutMs: z\n .number()\n .positive()\n .max(10 * 60_000)\n .default(DEFAULT_NAVIGATION_TIMEOUT_MS)\n .describe('The navigation timeout in milliseconds.'),\n});\n\nexport type GotoUrlNodeInput = z.infer<typeof gotoUrlInputSchema>;\n\nexport interface GotoUrlNodeResult {\n url: string;\n status: number | null;\n title: string;\n}\n\nexport const clearCookiesInputSchema = z.strictObject({\n name: z.string().regex(/\\S/).optional().describe('Cookie name to clear.'),\n domain: z.string().regex(/\\S/).optional().describe('Cookie domain to clear.'),\n path: z.string().regex(/\\S/).optional().describe('Cookie path to clear.'),\n});\n\nexport type ClearCookiesNodeInput = z.infer<typeof clearCookiesInputSchema>;\n\nexport const setViewportSizeInputSchema = z.strictObject({\n width: z.number().int().positive().describe('Viewport width in CSS pixels.'),\n height: z\n .number()\n .int()\n .positive()\n .describe('Viewport height in CSS pixels.'),\n});\n\nexport type SetViewportSizeNodeInput = z.infer<\n typeof setViewportSizeInputSchema\n>;\n\nconst resolveNavigationUrl = (\n target: string,\n currentUrl: string,\n configuredBase: string | undefined,\n): string => {\n const trimmed = target.trim();\n if (!trimmed) throw new TypeError('gotoUrl.url must not be blank.');\n if (/^[a-z][a-z\\d+.-]*:/i.test(trimmed)) {\n return resolveWebUrl(trimmed, undefined, 'gotoUrl.url');\n }\n if (configuredBase !== undefined) {\n return resolveWebUrl(trimmed, configuredBase, 'gotoUrl.url');\n }\n if (!/^https?:\\/\\//i.test(currentUrl)) {\n throw new TypeError(\n `gotoUrl.url cannot resolve a relative URL from ${JSON.stringify(currentUrl)}. Use an absolute HTTP(S) URL for the first navigation or configure testRunner.baseURL.`,\n );\n }\n return resolveWebUrl(trimmed, currentUrl, 'gotoUrl.url');\n};\n\n/** Create the browser-neutral built-in Web Nodes for one browser adapter. */\nexport const createWebTestRunnerNodeDefinitions = <\n TAgent,\n TOptions extends WebTestRunnerOptions<TAgent>,\n>(\n adapter: WebTestDriverAdapter<TAgent, TOptions>,\n): readonly AgentTestRunnerNodeDefinition[] => {\n const gotoUrlNode: AgentTestRunnerNodeDefinition<\n z.output<typeof gotoUrlInputSchema>,\n GotoUrlNodeResult\n > = {\n name: 'gotoUrl',\n title: 'Open a Web URL',\n description:\n 'Navigate the current browser Page to an absolute HTTP(S) URL or a path relative to testRunner.baseURL or the current page URL.',\n stringInputKey: 'url',\n inputSchema: gotoUrlInputSchema,\n async execute(agent, input, executionContext) {\n const runtimeAgent = adapter.requireAgent(agent);\n const driver = adapter.createDriver(runtimeAgent);\n throwIfAborted(executionContext.signal, 'gotoUrl');\n const url = resolveNavigationUrl(\n input.url,\n driver.currentUrl(),\n adapter.getOptions(runtimeAgent)?.baseURL ?? driver.baseUrl(),\n );\n const response = await driver.goto(url, {\n waitUntil: input.waitUntil,\n timeoutMs: input.timeoutMs,\n });\n throwIfAborted(executionContext.signal, 'gotoUrl');\n const result = {\n url: driver.currentUrl(),\n status: response.status,\n title: await driver.title(),\n };\n return { summary: `Navigated to ${result.url}`, data: result };\n },\n };\n\n const setCookiesNode: AgentTestRunnerNodeDefinition<\n z.output<typeof setCookiesInputSchema>,\n SetCookiesNodeResult\n > = {\n name: 'setCookies',\n title: 'Set browser cookies',\n description:\n 'Load cookies from an environment variable, configured profile, or browser storage-state file without persisting cookie values in workflow input or output.',\n stringInputKey: false,\n inputSchema: setCookiesInputSchema,\n async execute(agent, input, executionContext) {\n const runtimeAgent = adapter.requireAgent(agent);\n const driver = adapter.createDriver(runtimeAgent);\n throwIfAborted(executionContext.signal, 'setCookies');\n const { cookies, result } = await resolveCookieInput(\n input,\n { ...executionContext, input, context: runtimeAgent },\n adapter.getOptions(runtimeAgent) ?? {},\n );\n throwIfAborted(executionContext.signal, 'setCookies');\n try {\n await driver.setCookies(cookies);\n } catch {\n throw new Error(\n `Failed to set ${cookies.length} browser cookie(s); the browser error was redacted because it may contain cookie values.`,\n );\n }\n return {\n summary: `Set ${result.count} browser cookie(s) from ${result.source} ${result.sourceName}`,\n data: result,\n };\n },\n };\n\n const clearCookiesNode: AgentTestRunnerNodeDefinition<\n z.output<typeof clearCookiesInputSchema>,\n { filters: WebCookieFilters }\n > = {\n name: 'clearCookies',\n title: 'Clear browser cookies',\n description:\n 'Clear all cookies from the current browser context, or only cookies matching name, domain, or path.',\n stringInputKey: false,\n inputSchema: clearCookiesInputSchema,\n async execute(agent, input, executionContext) {\n const runtimeAgent = adapter.requireAgent(agent);\n const driver = adapter.createDriver(runtimeAgent);\n throwIfAborted(executionContext.signal, 'clearCookies');\n const filters: WebCookieFilters = { ...input };\n await driver.clearCookies(filters);\n const filterNames = Object.keys(filters);\n return {\n summary:\n filterNames.length === 0\n ? 'Cleared all browser cookies'\n : `Cleared browser cookies matching ${filterNames.join(', ')}`,\n data: { filters },\n };\n },\n };\n\n const setViewportSizeNode: AgentTestRunnerNodeDefinition<\n z.output<typeof setViewportSizeInputSchema>,\n WebViewportSize\n > = {\n name: 'setViewportSize',\n title: 'Set the browser viewport size',\n description:\n 'Set the current browser Page viewport size in CSS pixels and return the effective size.',\n stringInputKey: false,\n inputSchema: setViewportSizeInputSchema,\n async execute(agent, input, executionContext) {\n const runtimeAgent = adapter.requireAgent(agent);\n const driver = adapter.createDriver(runtimeAgent);\n throwIfAborted(executionContext.signal, 'setViewportSize');\n const viewport = await driver.setViewportSize(input);\n return {\n summary: `Set viewport to ${viewport.width}x${viewport.height}`,\n data: viewport,\n };\n },\n };\n\n return [gotoUrlNode, setCookiesNode, clearCookiesNode, setViewportSizeNode];\n};\n\nexport { setCookiesInputSchema };\nexport type { SetCookiesNodeInput, SetCookiesNodeResult } from './cookies';\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","DEFAULT_NAVIGATION_TIMEOUT_MS","DEFAULT_WAIT_UNTIL","gotoUrlInputSchema","z","clearCookiesInputSchema","setViewportSizeInputSchema","resolveNavigationUrl","target","currentUrl","configuredBase","trimmed","TypeError","resolveWebUrl","undefined","JSON","createWebTestRunnerNodeDefinitions","adapter","gotoUrlNode","agent","input","executionContext","runtimeAgent","driver","throwIfAborted","url","response","result","setCookiesNode","setCookiesInputSchema","cookies","resolveCookieInput","Error","clearCookiesNode","filters","filterNames","setViewportSizeNode","viewport"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBA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AA4B;gBAAE,GAAGd,KAAK;YAAC;YAC7C,MAAMG,OAAO,YAAY,CAACW;YAC1B,MAAMC,cAActC,OAAO,IAAI,CAACqC;YAChC,OAAO;gBACL,SACEC,AAAuB,MAAvBA,YAAY,MAAM,GACd,gCACA,CAAC,iCAAiC,EAAEA,YAAY,IAAI,CAAC,OAAO;gBAClE,MAAM;oBAAED;gBAAQ;YAClB;QACF;IACF;IAEA,MAAME,sBAGF;QACF,MAAM;QACN,OAAO;QACP,aACE;QACF,gBAAgB;QAChB,aAAa9B;QACb,MAAM,SAAQa,KAAK,EAAEC,KAAK,EAAEC,gBAAgB;YAC1C,MAAMC,eAAeL,QAAQ,YAAY,CAACE;YAC1C,MAAMI,SAASN,QAAQ,YAAY,CAACK;YACpCE,IAAAA,kCAAAA,cAAAA,AAAAA,EAAeH,iBAAiB,MAAM,EAAE;YACxC,MAAMgB,WAAW,MAAMd,OAAO,eAAe,CAACH;YAC9C,OAAO;gBACL,SAAS,CAAC,gBAAgB,EAAEiB,SAAS,KAAK,CAAC,CAAC,EAAEA,SAAS,MAAM,EAAE;gBAC/D,MAAMA;YACR;QACF;IACF;IAEA,OAAO;QAACnB;QAAaU;QAAgBK;QAAkBG;KAAoB;AAC7E"}
|
|
1
|
+
{"version":3,"file":"common/test-runner/nodes.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../src/common/test-runner/nodes.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import type { AgentTestRunnerNodeDefinition } from '@midscene/core/agent';\nimport { z } from 'zod/v4';\nimport {\n type SetCookiesNodeResult,\n resolveCookieInput,\n setCookiesInputSchema,\n} from './cookies';\nimport type {\n WebCookieFilters,\n WebTestDriverAdapter,\n WebTestRunnerOptions,\n WebViewportSize,\n} from './driver';\nimport { resolveWebUrl, throwIfAborted } from './utils';\n\nconst DEFAULT_NAVIGATION_TIMEOUT_MS = 60_000;\nconst DEFAULT_WAIT_UNTIL = 'domcontentloaded' as const;\n\nexport const gotoUrlInputSchema = z.strictObject({\n url: z\n .string()\n .min(1)\n .describe(\n 'An absolute HTTP(S) URL or a path relative to testRunner.baseURL or the current page URL.',\n ),\n waitUntil: z\n .enum([\n 'commit',\n 'domcontentloaded',\n 'load',\n 'networkidle',\n 'networkidle0',\n 'networkidle2',\n ])\n .default(DEFAULT_WAIT_UNTIL)\n .describe(\n 'The navigation lifecycle event. domcontentloaded, load, and networkidle are portable across browser drivers.',\n ),\n timeoutMs: z\n .number()\n .positive()\n .max(10 * 60_000)\n .default(DEFAULT_NAVIGATION_TIMEOUT_MS)\n .describe('The navigation timeout in milliseconds.'),\n});\n\nexport type GotoUrlNodeInput = z.infer<typeof gotoUrlInputSchema>;\n\nexport interface GotoUrlNodeResult {\n url: string;\n status: number | null;\n title: string;\n}\n\nexport const clearCookiesInputSchema = z.strictObject({\n name: z.string().regex(/\\S/).optional().describe('Cookie name to clear.'),\n domain: z.string().regex(/\\S/).optional().describe('Cookie domain to clear.'),\n path: z.string().regex(/\\S/).optional().describe('Cookie path to clear.'),\n});\n\nexport type ClearCookiesNodeInput = z.infer<typeof clearCookiesInputSchema>;\n\nexport const setViewportSizeInputSchema = z.strictObject({\n width: z.number().int().positive().describe('Viewport width in CSS pixels.'),\n height: z\n .number()\n .int()\n .positive()\n .describe('Viewport height in CSS pixels.'),\n});\n\nexport type SetViewportSizeNodeInput = z.infer<\n typeof setViewportSizeInputSchema\n>;\n\nconst resolveNavigationUrl = (\n target: string,\n currentUrl: string,\n configuredBase: string | undefined,\n): string => {\n const trimmed = target.trim();\n if (!trimmed) throw new TypeError('gotoUrl.url must not be blank.');\n if (/^[a-z][a-z\\d+.-]*:/i.test(trimmed)) {\n return resolveWebUrl(trimmed, undefined, 'gotoUrl.url');\n }\n if (configuredBase !== undefined) {\n return resolveWebUrl(trimmed, configuredBase, 'gotoUrl.url');\n }\n if (!/^https?:\\/\\//i.test(currentUrl)) {\n throw new TypeError(\n `gotoUrl.url cannot resolve a relative URL from ${JSON.stringify(currentUrl)}. Use an absolute HTTP(S) URL for the first navigation or configure testRunner.baseURL.`,\n );\n }\n return resolveWebUrl(trimmed, currentUrl, 'gotoUrl.url');\n};\n\n/** Create the browser-neutral built-in Web Nodes for one browser adapter. */\nexport const createWebTestRunnerNodeDefinitions = <\n TAgent,\n TOptions extends WebTestRunnerOptions<TAgent>,\n>(\n adapter: WebTestDriverAdapter<TAgent, TOptions>,\n): readonly AgentTestRunnerNodeDefinition[] => {\n const gotoUrlNode: AgentTestRunnerNodeDefinition<\n z.output<typeof gotoUrlInputSchema>,\n GotoUrlNodeResult\n > = {\n name: 'gotoUrl',\n title: 'Open a Web URL',\n description:\n 'Navigate the current browser Page to an absolute HTTP(S) URL or a path relative to testRunner.baseURL or the current page URL.',\n stringInputKey: 'url',\n inputSchema: gotoUrlInputSchema,\n async execute(agent, input, executionContext) {\n const runtimeAgent = adapter.requireAgent(agent);\n const driver = adapter.createDriver(runtimeAgent);\n throwIfAborted(executionContext.signal, 'gotoUrl');\n const url = resolveNavigationUrl(\n input.url,\n driver.currentUrl(),\n adapter.getOptions(runtimeAgent)?.baseURL ?? driver.baseUrl(),\n );\n const response = await driver.goto(url, {\n waitUntil: input.waitUntil,\n timeoutMs: input.timeoutMs,\n });\n throwIfAborted(executionContext.signal, 'gotoUrl');\n const result = {\n url: driver.currentUrl(),\n status: response.status,\n title: await driver.title(),\n };\n return { summary: `Navigated to ${result.url}`, data: result };\n },\n };\n\n const setCookiesNode: AgentTestRunnerNodeDefinition<\n z.output<typeof setCookiesInputSchema>,\n SetCookiesNodeResult\n > = {\n name: 'setCookies',\n title: 'Set browser cookies',\n description:\n 'Load cookies from an environment variable, configured profile, or browser storage-state file without persisting cookie values in workflow input or output.',\n stringInputKey: false,\n inputSchema: setCookiesInputSchema,\n async execute(agent, input, executionContext) {\n const runtimeAgent = adapter.requireAgent(agent);\n const driver = adapter.createDriver(runtimeAgent);\n throwIfAborted(executionContext.signal, 'setCookies');\n const { cookies, result } = await resolveCookieInput(\n input,\n { ...executionContext, input, context: runtimeAgent },\n adapter.getOptions(runtimeAgent) ?? {},\n );\n throwIfAborted(executionContext.signal, 'setCookies');\n try {\n await driver.setCookies(cookies);\n } catch (cause) {\n throw new Error(`Failed to set ${cookies.length} browser cookie(s).`, {\n cause,\n });\n }\n return {\n summary: `Set ${result.count} browser cookie(s) from ${result.source} ${result.sourceName}`,\n data: result,\n };\n },\n };\n\n const clearCookiesNode: AgentTestRunnerNodeDefinition<\n z.output<typeof clearCookiesInputSchema>,\n { filters: WebCookieFilters }\n > = {\n name: 'clearCookies',\n title: 'Clear browser cookies',\n description:\n 'Clear all cookies from the current browser context, or only cookies matching name, domain, or path.',\n stringInputKey: false,\n inputSchema: clearCookiesInputSchema,\n async execute(agent, input, executionContext) {\n const runtimeAgent = adapter.requireAgent(agent);\n const driver = adapter.createDriver(runtimeAgent);\n throwIfAborted(executionContext.signal, 'clearCookies');\n const filters: WebCookieFilters = { ...input };\n await driver.clearCookies(filters);\n const filterNames = Object.keys(filters);\n return {\n summary:\n filterNames.length === 0\n ? 'Cleared all browser cookies'\n : `Cleared browser cookies matching ${filterNames.join(', ')}`,\n data: { filters },\n };\n },\n };\n\n const setViewportSizeNode: AgentTestRunnerNodeDefinition<\n z.output<typeof setViewportSizeInputSchema>,\n WebViewportSize\n > = {\n name: 'setViewportSize',\n title: 'Set the browser viewport size',\n description:\n 'Set the current browser Page viewport size in CSS pixels and return the effective size.',\n stringInputKey: false,\n inputSchema: setViewportSizeInputSchema,\n async execute(agent, input, executionContext) {\n const runtimeAgent = adapter.requireAgent(agent);\n const driver = adapter.createDriver(runtimeAgent);\n throwIfAborted(executionContext.signal, 'setViewportSize');\n const viewport = await driver.setViewportSize(input);\n return {\n summary: `Set viewport to ${viewport.width}x${viewport.height}`,\n data: viewport,\n };\n },\n };\n\n return [gotoUrlNode, setCookiesNode, clearCookiesNode, setViewportSizeNode];\n};\n\nexport { setCookiesInputSchema };\nexport type { SetCookiesNodeInput, SetCookiesNodeResult } from './cookies';\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","DEFAULT_NAVIGATION_TIMEOUT_MS","DEFAULT_WAIT_UNTIL","gotoUrlInputSchema","z","clearCookiesInputSchema","setViewportSizeInputSchema","resolveNavigationUrl","target","currentUrl","configuredBase","trimmed","TypeError","resolveWebUrl","undefined","JSON","createWebTestRunnerNodeDefinitions","adapter","gotoUrlNode","agent","input","executionContext","runtimeAgent","driver","throwIfAborted","url","response","result","setCookiesNode","setCookiesInputSchema","cookies","resolveCookieInput","cause","Error","clearCookiesNode","filters","filterNames","setViewportSizeNode","viewport"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,MAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEt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L,SACEC,AAAuB,MAAvBA,YAAY,MAAM,GACd,gCACA,CAAC,iCAAiC,EAAEA,YAAY,IAAI,CAAC,OAAO;gBAClE,MAAM;oBAAED;gBAAQ;YAClB;QACF;IACF;IAEA,MAAME,sBAGF;QACF,MAAM;QACN,OAAO;QACP,aACE;QACF,gBAAgB;QAChB,aAAa/B;QACb,MAAM,SAAQa,KAAK,EAAEC,KAAK,EAAEC,gBAAgB;YAC1C,MAAMC,eAAeL,QAAQ,YAAY,CAACE;YAC1C,MAAMI,SAASN,QAAQ,YAAY,CAACK;YACpCE,IAAAA,kCAAAA,cAAAA,AAAAA,EAAeH,iBAAiB,MAAM,EAAE;YACxC,MAAMiB,WAAW,MAAMf,OAAO,eAAe,CAACH;YAC9C,OAAO;gBACL,SAAS,CAAC,gBAAgB,EAAEkB,SAAS,KAAK,CAAC,CAAC,EAAEA,SAAS,MAAM,EAAE;gBAC/D,MAAMA;YACR;QACF;IACF;IAEA,OAAO;QAACpB;QAAaU;QAAgBM;QAAkBG;KAAoB;AAC7E"}
|
package/dist/lib/platform.js
CHANGED
|
@@ -52,7 +52,10 @@ const webPlaygroundPlatform = (0, playground_namespaceObject.definePlaygroundPla
|
|
|
52
52
|
title: options?.title || 'Midscene Web Playground',
|
|
53
53
|
agent: agent || (agentFactory ? void 0 : createDefaultWebAgent()),
|
|
54
54
|
agentFactory,
|
|
55
|
-
launchOptions:
|
|
55
|
+
launchOptions: {
|
|
56
|
+
enableCors: true,
|
|
57
|
+
...options?.launchOptions
|
|
58
|
+
},
|
|
56
59
|
preview: options?.preview || (0, playground_namespaceObject.createMjpegPreviewDescriptor)({
|
|
57
60
|
title: 'Web page preview'
|
|
58
61
|
}),
|
package/dist/lib/platform.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"platform.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../src/platform.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { ScreenshotItem } from '@midscene/core';\nimport type { Agent } from '@midscene/core/agent';\nimport {\n type AgentFactory,\n type LaunchPlaygroundOptions,\n type PlaygroundPreviewDescriptor,\n createMjpegPreviewDescriptor,\n definePlaygroundPlatform,\n} from '@midscene/playground';\nimport { StaticPage, StaticPageAgent } from './static';\n\nexport interface WebPlatformOptions {\n agent?: Agent;\n agentFactory?: AgentFactory;\n title?: string;\n preview?: PlaygroundPreviewDescriptor;\n launchOptions?: LaunchPlaygroundOptions;\n}\n\nfunction createDefaultWebAgent(): StaticPageAgent {\n const page = new StaticPage({\n shotSize: { width: 800, height: 600 },\n screenshot: ScreenshotItem.create('', Date.now()),\n shrunkShotToLogicalRatio: 1,\n });\n\n return new StaticPageAgent(page);\n}\n\nexport const webPlaygroundPlatform = definePlaygroundPlatform<\n WebPlatformOptions | undefined\n>({\n id: 'web',\n title: 'Midscene Web Playground',\n description: 'Web playground platform descriptor',\n async prepare(options) {\n const agent = options?.agent;\n const agentFactory =\n options?.agentFactory ||\n (!options?.agent && !options?.agentFactory\n ? () => createDefaultWebAgent()\n : undefined);\n\n return {\n platformId: 'web',\n title: options?.title || 'Midscene Web Playground',\n agent: agent || (!agentFactory ? createDefaultWebAgent() : undefined),\n agentFactory,\n launchOptions: options?.launchOptions,\n preview:\n options?.preview ||\n createMjpegPreviewDescriptor({\n title: 'Web page preview',\n }),\n metadata: {\n interfaceType: agent?.interface?.interfaceType || 'web',\n },\n };\n },\n});\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","createDefaultWebAgent","page","StaticPage","ScreenshotItem","Date","StaticPageAgent","webPlaygroundPlatform","definePlaygroundPlatform","options","agent","agentFactory","undefined","createMjpegPreviewDescriptor"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,MAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,UAAS,cAAc;YAAE,OAAO;QAAK;IAC5D;;;;;;;;;;ACaA,SAASI;IACP,MAAMC,OAAO,IAAIC,yBAAAA,UAAUA,CAAC;QAC1B,UAAU;YAAE,OAAO;YAAK,QAAQ;QAAI;QACpC,YAAYC,qBAAAA,cAAAA,CAAAA,MAAqB,CAAC,IAAIC,KAAK,GAAG;QAC9C,0BAA0B;IAC5B;IAEA,OAAO,IAAIC,yBAAAA,eAAeA,CAACJ;AAC7B;AAEO,MAAMK,wBAAwBC,AAAAA,IAAAA,2BAAAA,wBAAAA,AAAAA,EAEnC;IACA,IAAI;IACJ,OAAO;IACP,aAAa;IACb,MAAM,SAAQC,OAAO;QACnB,MAAMC,QAAQD,SAAS;QACvB,MAAME,eACJF,SAAS,gBACR,CAACA,SAAS,SAAUA,SAAS,eAE1BG,SADA,IAAMX,uBACE;QAEd,OAAO;YACL,YAAY;YACZ,OAAOQ,SAAS,SAAS;YACzB,OAAOC,SAAU,CAACC,eAAyCC,SAA1BX,uBAAkC;YACnEU;YACA,
|
|
1
|
+
{"version":3,"file":"platform.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../src/platform.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { ScreenshotItem } from '@midscene/core';\nimport type { Agent } from '@midscene/core/agent';\nimport {\n type AgentFactory,\n type LaunchPlaygroundOptions,\n type PlaygroundPreviewDescriptor,\n createMjpegPreviewDescriptor,\n definePlaygroundPlatform,\n} from '@midscene/playground';\nimport { StaticPage, StaticPageAgent } from './static';\n\nexport interface WebPlatformOptions {\n agent?: Agent;\n agentFactory?: AgentFactory;\n title?: string;\n preview?: PlaygroundPreviewDescriptor;\n launchOptions?: LaunchPlaygroundOptions;\n}\n\nfunction createDefaultWebAgent(): StaticPageAgent {\n const page = new StaticPage({\n shotSize: { width: 800, height: 600 },\n screenshot: ScreenshotItem.create('', Date.now()),\n shrunkShotToLogicalRatio: 1,\n });\n\n return new StaticPageAgent(page);\n}\n\nexport const webPlaygroundPlatform = definePlaygroundPlatform<\n WebPlatformOptions | undefined\n>({\n id: 'web',\n title: 'Midscene Web Playground',\n description: 'Web playground platform descriptor',\n async prepare(options) {\n const agent = options?.agent;\n const agentFactory =\n options?.agentFactory ||\n (!options?.agent && !options?.agentFactory\n ? () => createDefaultWebAgent()\n : undefined);\n\n return {\n platformId: 'web',\n title: options?.title || 'Midscene Web Playground',\n agent: agent || (!agentFactory ? createDefaultWebAgent() : undefined),\n agentFactory,\n launchOptions: {\n enableCors: true,\n ...options?.launchOptions,\n },\n preview:\n options?.preview ||\n createMjpegPreviewDescriptor({\n title: 'Web page preview',\n }),\n metadata: {\n interfaceType: agent?.interface?.interfaceType || 'web',\n },\n };\n },\n});\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","createDefaultWebAgent","page","StaticPage","ScreenshotItem","Date","StaticPageAgent","webPlaygroundPlatform","definePlaygroundPlatform","options","agent","agentFactory","undefined","createMjpegPreviewDescriptor"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,MAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,UAAS,cAAc;YAAE,OAAO;QAAK;IAC5D;;;;;;;;;;ACaA,SAASI;IACP,MAAMC,OAAO,IAAIC,yBAAAA,UAAUA,CAAC;QAC1B,UAAU;YAAE,OAAO;YAAK,QAAQ;QAAI;QACpC,YAAYC,qBAAAA,cAAAA,CAAAA,MAAqB,CAAC,IAAIC,KAAK,GAAG;QAC9C,0BAA0B;IAC5B;IAEA,OAAO,IAAIC,yBAAAA,eAAeA,CAACJ;AAC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;;;;kBAwC9B,CAAC;AAEL,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAExE,MAAM,WAAW,oBAAoB;IACnC,MAAM,EAAE,qBAAqB,CAAC,MAAM,CAAC,CAAC;IACtC,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;CACf;AAuHD,eAAO,MAAM,kBAAkB,GAAU,MAAM,EAC7C,OAAO,mBAAmB,EAC1B,KAAK,cAAc,CAAC,MAAM,CAAC,EAC3B,SAAS,sBAAsB,CAAC,MAAM,CAAC,KACtC,OAAO,CAAC;IACT,OAAO,EAAE,iBAAiB,EAAE,CAAC;IAC7B,MAAM,EAAE,oBAAoB,CAAC;CAC9B,CA2EA,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"platform.d.ts","sourceRoot":"","sources":["../../src/platform.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EACL,KAAK,YAAY,EACjB,KAAK,uBAAuB,EAC5B,KAAK,2BAA2B,EAGjC,MAAM,sBAAsB,CAAC;AAG9B,MAAM,WAAW,kBAAkB;IACjC,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,2BAA2B,CAAC;IACtC,aAAa,CAAC,EAAE,uBAAuB,CAAC;CACzC;AAYD,eAAO,MAAM,qBAAqB,
|
|
1
|
+
{"version":3,"file":"platform.d.ts","sourceRoot":"","sources":["../../src/platform.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EACL,KAAK,YAAY,EACjB,KAAK,uBAAuB,EAC5B,KAAK,2BAA2B,EAGjC,MAAM,sBAAsB,CAAC;AAG9B,MAAM,WAAW,kBAAkB;IACjC,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,2BAA2B,CAAC;IACtC,aAAa,CAAC,EAAE,uBAAuB,CAAC;CACzC;AAYD,eAAO,MAAM,qBAAqB,6FAiChC,CAAC"}
|
package/package.json
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"Browser use",
|
|
9
9
|
"Android use"
|
|
10
10
|
],
|
|
11
|
-
"version": "1.
|
|
11
|
+
"version": "1.18.0",
|
|
12
12
|
"repository": "https://github.com/web-infra-dev/midscene",
|
|
13
13
|
"homepage": "https://midscenejs.com/",
|
|
14
14
|
"main": "./dist/lib/index.js",
|
|
@@ -102,9 +102,9 @@
|
|
|
102
102
|
"socket.io-client": "4.8.4",
|
|
103
103
|
"ws": "^8.22.1",
|
|
104
104
|
"zod": "^3.25.1",
|
|
105
|
-
"@midscene/core": "1.
|
|
106
|
-
"@midscene/shared": "1.
|
|
107
|
-
"@midscene/playground": "1.
|
|
105
|
+
"@midscene/core": "1.18.0",
|
|
106
|
+
"@midscene/shared": "1.18.0",
|
|
107
|
+
"@midscene/playground": "1.18.0"
|
|
108
108
|
},
|
|
109
109
|
"devDependencies": {
|
|
110
110
|
"@playwright/test": "^1.45.0",
|