MCPcopy Create free account
hub / github.com/cloudflare/moltworker / createClient

Function createClient

skills/cloudflare-browser/scripts/cdp-client.js:18–145  ·  view source on GitHub ↗
(options = {})

Source from the content-addressed store, hash-verified

16const WebSocket = require('ws');
17
18function createClient(options = {}) {
19 const CDP_SECRET = options.secret || process.env.CDP_SECRET;
20 if (!CDP_SECRET) {
21 throw new Error('CDP_SECRET environment variable not set');
22 }
23
24 const workerUrl = (options.workerUrl || process.env.WORKER_URL).replace(/^https?:\/\//, '');
25 const wsUrl = `wss://${workerUrl}/cdp?secret=${encodeURIComponent(CDP_SECRET)}`;
26 const timeout = options.timeout || 60000;
27
28 return new Promise((resolve, reject) => {
29 const ws = new WebSocket(wsUrl);
30 let messageId = 1;
31 const pending = new Map();
32 let targetId = null;
33 let targetResolve;
34 const targetReady = new Promise(r => { targetResolve = r; });
35
36 function send(method, params = {}) {
37 return new Promise((res, rej) => {
38 const id = messageId++;
39 const timer = setTimeout(() => {
40 pending.delete(id);
41 rej(new Error(`Timeout: ${method}`));
42 }, timeout);
43 pending.set(id, { resolve: res, reject: rej, timeout: timer });
44 ws.send(JSON.stringify({ id, method, params }));
45 });
46 }
47
48 ws.on('message', (data) => {
49 const msg = JSON.parse(data.toString());
50
51 if (msg.method === 'Target.targetCreated' && msg.params?.targetInfo?.type === 'page') {
52 targetId = msg.params.targetInfo.targetId;
53 targetResolve(targetId);
54 }
55
56 if (msg.id && pending.has(msg.id)) {
57 const { resolve, reject, timeout: timer } = pending.get(msg.id);
58 clearTimeout(timer);
59 pending.delete(msg.id);
60 msg.error ? reject(new Error(msg.error.message)) : resolve(msg.result);
61 }
62 });
63
64 ws.on('error', reject);
65
66 ws.on('open', async () => {
67 try {
68 // Wait for target
69 await Promise.race([
70 targetReady,
71 new Promise((_, rej) => setTimeout(() => rej(new Error('No target created')), 10000))
72 ]);
73
74 // Client API
75 const client = {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected