-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
cri-client.ts
263 lines (210 loc) · 6.74 KB
/
cri-client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import debugModule from 'debug'
import _ from 'lodash'
const chromeRemoteInterface = require('chrome-remote-interface')
const errors = require('../errors')
const debug = debugModule('cypress:server:browsers:cri-client')
// debug using cypress-verbose:server:browsers:cri-client:send:*
const debugVerboseSend = debugModule('cypress-verbose:server:browsers:cri-client:send:[-->]')
// debug using cypress-verbose:server:browsers:cri-client:recv:*
const debugVerboseReceive = debugModule('cypress-verbose:server:browsers:cri-client:recv:[<--]')
const WEBSOCKET_NOT_OPEN_RE = /^WebSocket is (?:not open|already in CLOSING or CLOSED state)/
/**
* Url returned by the Chrome Remote Interface
*/
type websocketUrl = string
/**
* Enumerations to make programming CDP slightly simpler - provides
* IntelliSense whenever you use named types.
*/
namespace CRI {
export type Command =
'Browser.getVersion' |
'Page.bringToFront' |
'Page.captureScreenshot' |
'Page.navigate' |
'Page.startScreencast' |
'Page.screencastFrameAck' |
'Page.setDownloadBehavior' |
string
export type EventName =
'Page.screencastFrame' |
'Page.downloadWillBegin' |
'Page.downloadProgress' |
string
}
/**
* Wrapper for Chrome Remote Interface client. Only allows "send" method.
* @see https://github.com/cyrus-and/chrome-remote-interface#clientsendmethod-params-callback
*/
interface CRIWrapper {
/**
* Get the `protocolVersion` supported by the browser.
*/
getProtocolVersion (): Promise<Version>
/**
* Rejects if `protocolVersion` is less than the current version.
* @param protocolVersion CDP version string (ex: 1.3)
*/
ensureMinimumProtocolVersion(protocolVersion: string): Promise<void>
/**
* Sends a command to the Chrome remote interface.
* @example client.send('Page.navigate', { url })
*/
send (command: CRI.Command, params?: object): Promise<any>
/**
* Registers callback for particular event.
* @see https://github.com/cyrus-and/chrome-remote-interface#class-cdp
*/
on (eventName: CRI.EventName, cb: Function): void
/**
* Calls underlying remote interface client close
*/
close (): Promise<void>
}
interface Version {
major: number
minor: number
}
const isVersionGte = (a: Version, b: Version) => {
return a.major > b.major || (a.major === b.major && a.minor >= b.minor)
}
const getMajorMinorVersion = (version: string): Version => {
const [major, minor] = version.split('.', 2).map(Number)
return { major, minor }
}
const maybeDebugCdpMessages = (cri) => {
if (debugVerboseReceive.enabled) {
cri._ws.on('message', (data) => {
data = _
.chain(JSON.parse(data))
.tap((data) => {
([
'params.data', // screencast frame data
'result.data', // screenshot data
]).forEach((truncatablePath) => {
const str = _.get(data, truncatablePath)
if (!_.isString(str)) {
return
}
_.set(data, truncatablePath, _.truncate(str, {
length: 100,
omission: `... [truncated string of total bytes: ${str.length}]`,
}))
})
return data
})
.value()
debugVerboseReceive('received CDP message %o', data)
})
}
if (debugVerboseSend.enabled) {
const send = cri._ws.send
cri._ws.send = (data, callback) => {
debugVerboseSend('sending CDP command %o', JSON.parse(data))
return send.call(cri._ws, data, callback)
}
}
}
/**
* Creates a wrapper for Chrome remote interface client
* that only allows to use low-level "send" method
* and not via domain objects and commands.
*
* @example create('ws://localhost:...').send('Page.bringToFront')
*/
export { chromeRemoteInterface }
type DeferredPromise = { resolve: Function, reject: Function }
export const create = async (target: websocketUrl, onAsynchronousError: Function): Promise<CRIWrapper> => {
const subscriptions: {eventName: CRI.EventName, cb: Function}[] = []
let enqueuedCommands: {command: CRI.Command, params: any, p: DeferredPromise }[] = []
let closed = false // has the user called .close on this?
let connected = false // is this currently connected to CDP?
let cri
let client: CRIWrapper
const reconnect = async () => {
debug('disconnected, attempting to reconnect... %o', { closed })
connected = false
if (closed) {
return
}
try {
await connect()
debug('restoring subscriptions + running queued commands... %o', { subscriptions, enqueuedCommands })
subscriptions.forEach((sub) => {
cri.on(sub.eventName, sub.cb)
})
enqueuedCommands.forEach((cmd) => {
cri.send(cmd.command, cmd.params)
.then(cmd.p.resolve, cmd.p.reject)
})
enqueuedCommands = []
} catch (err) {
onAsynchronousError(errors.get('CDP_COULD_NOT_RECONNECT', err))
}
}
const connect = async () => {
cri?.close()
debug('connecting %o', { target })
cri = await chromeRemoteInterface({
target,
local: true,
})
connected = true
maybeDebugCdpMessages(cri)
// @see https://github.com/cyrus-and/chrome-remote-interface/issues/72
cri._notifier.on('disconnect', reconnect)
}
await connect()
const ensureMinimumProtocolVersion = async (protocolVersion: string) => {
const actual = await getProtocolVersion()
const minimum = getMajorMinorVersion(protocolVersion)
if (!isVersionGte(actual, minimum)) {
errors.throw('CDP_VERSION_TOO_OLD', protocolVersion, actual)
}
}
const getProtocolVersion = _.memoize(async () => {
let version
try {
version = await client.send('Browser.getVersion')
} catch (_) {
// could be any version <= 1.2
version = { protocolVersion: '0.0' }
}
return getMajorMinorVersion(version.protocolVersion)
})
client = {
ensureMinimumProtocolVersion,
getProtocolVersion,
async send (command: CRI.Command, params?: object) {
const enqueue = () => {
return new Promise((resolve, reject) => {
enqueuedCommands.push({ command, params, p: { resolve, reject } })
})
}
if (connected) {
try {
return await cri.send(command, params)
} catch (err) {
if (!WEBSOCKET_NOT_OPEN_RE.test(err.message)) {
throw err
}
debug('encountered closed websocket on send %o', { command, params, err })
const p = enqueue()
reconnect()
return p
}
}
return enqueue()
},
on (eventName: CRI.EventName, cb: Function) {
subscriptions.push({ eventName, cb })
debug('registering CDP on event %o', { eventName })
return cri.on(eventName, cb)
},
close () {
closed = true
return cri.close()
},
}
return client
}