@rezkam/browser-tools 1.0.3 → 1.1.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.
@@ -0,0 +1,96 @@
1
+ import { accessSync, constants, readFileSync, realpathSync, statSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { basename, isAbsolute, join } from 'node:path';
4
+
5
+ const MAC_CHROME = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
6
+ const LINUX_NAMES = [
7
+ 'google-chrome', 'google-chrome-stable', 'google-chrome-beta',
8
+ 'google-chrome-unstable', 'chromium', 'chromium-browser',
9
+ ];
10
+ const LINUX_LOCATIONS = ['/usr/bin', '/usr/local/bin', '/opt/bin']
11
+ .flatMap((directory) => LINUX_NAMES.map((name) => join(directory, name))).concat([
12
+ // Use the supported snap launcher, never its internal binary.
13
+ '/snap/bin/chromium',
14
+ '/opt/google/chrome/chrome', '/opt/google/chrome-beta/chrome',
15
+ '/opt/google/chrome-unstable/chrome',
16
+ '/usr/lib/chromium/chromium', '/usr/lib64/chromium-browser/chromium-browser',
17
+ '/usr/lib/chromium-browser/chromium-browser', '/usr/lib64/chromium/chromium',
18
+ ]);
19
+
20
+ function executable(file) {
21
+ try {
22
+ accessSync(file, constants.X_OK);
23
+ return statSync(file).isFile();
24
+ } catch { return false; }
25
+ }
26
+
27
+ /** Read-only discovery: executable Linux launcher or null if absent.
28
+ * macOS preserves its historical default even when not installed.
29
+ * Explicit configuration/env overrides belong to the caller.
30
+ */
31
+ export function discoverChromeBinary({ platform = process.platform, env = process.env, home = homedir() } = {}) {
32
+ if (platform === 'darwin') return MAC_CHROME;
33
+ if (platform !== 'linux') return null;
34
+ void home; // Do not infer installations from arbitrary downloads/caches.
35
+ const directories = (env.PATH || '').split(':').filter(Boolean);
36
+ for (const name of LINUX_NAMES) {
37
+ for (const directory of directories) {
38
+ const candidate = join(directory, name);
39
+ if (executable(candidate)) return candidate;
40
+ }
41
+ }
42
+ return LINUX_LOCATIONS.find(executable) || null;
43
+ }
44
+
45
+ function directoryExists(directory) {
46
+ try { return statSync(directory).isDirectory(); } catch { return false; }
47
+ }
48
+
49
+ function snapChromium(binary, env = process.env) {
50
+ if (!binary.includes('/')) {
51
+ binary = (env.PATH || '').split(':').filter(Boolean).map(dir => join(dir, binary)).find(executable) || binary;
52
+ }
53
+ if (binary === '/snap/bin/chromium' || binary.includes('/snap/chromium/')) return true;
54
+ try {
55
+ const target = realpathSync(binary);
56
+ if (target === '/usr/bin/snap' || target.includes('/snap/chromium/')) return true;
57
+ // Ubuntu's chromium-browser compatibility launcher delegates to snap.
58
+ if (statSync(binary).size < 64 * 1024) {
59
+ return /(?:\/snap\/bin\/chromium|\bsnap\s+run\s+chromium\b)/.test(readFileSync(binary, 'utf8'));
60
+ }
61
+ } catch { /* Missing or unreadable launchers retain predictable defaults. */ }
62
+ return false;
63
+ }
64
+
65
+ /** User-data root for the selected browser family/channel; never creates it.
66
+ * Never substitutes another browser family's existing profile.
67
+ */
68
+ export function discoverChromeSourceDir({ chromeBin, platform = process.platform, env = process.env, home = homedir() } = {}) {
69
+ if (platform === 'darwin') return join(home, 'Library', 'Application Support', 'Google', 'Chrome');
70
+ if (platform !== 'linux') return null;
71
+ const binary = chromeBin || discoverChromeBinary({ platform, env, home }) || 'google-chrome';
72
+ const name = basename(binary).toLowerCase();
73
+ const configRoot = env.XDG_CONFIG_HOME && isAbsolute(env.XDG_CONFIG_HOME)
74
+ ? env.XDG_CONFIG_HOME : join(home, '.config');
75
+ if (name.includes('chromium') || binary.includes('/snap/chromium/')) {
76
+ const native = join(configRoot, 'chromium');
77
+ const snap = join(home, 'snap', 'chromium', 'common', 'chromium');
78
+ if (snapChromium(binary, env)) return snap;
79
+ // Distro launchers can delegate to snap; stay within the Chromium family.
80
+ return !directoryExists(native) && directoryExists(snap) ? snap : native;
81
+ }
82
+ const channel = /(?:google-chrome|chrome)[-/]beta(?:[/]|$)/.test(binary) ? '-beta'
83
+ : /(?:google-chrome|chrome)[-/](?:unstable|dev)(?:[/]|$)/.test(binary) ? '-unstable' : '';
84
+ return join(configRoot, 'google-chrome' + channel);
85
+ }
86
+
87
+ /** User-agent platform component, not a full User-Agent string. */
88
+ export function chromePlatformToken({ platform = process.platform, arch = process.arch } = {}) {
89
+ if (platform === 'darwin') return 'Macintosh; Intel Mac OS X 10_15_7';
90
+ if (platform === 'win32') return 'Windows NT 10.0; Win64; x64';
91
+ if (platform === 'linux') {
92
+ const machine = { x64: 'x86_64', arm64: 'aarch64', ia32: 'i686', arm: 'armv7l' }[arch] || arch;
93
+ return 'X11; Linux ' + machine;
94
+ }
95
+ return 'X11; ' + platform + ' ' + arch;
96
+ }
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Serves tabs of one shared Chrome to every client that leases one (see tab-broker.mjs).
4
+ *
5
+ * Usage: serve.mjs [--max-tabs <n>] [--tab-seconds <n>] [--headless] [--proxy-server <url>]
6
+ * [--chrome-arg <arg>]... [--port <n>] [--until-stdin-closes]
7
+ *
8
+ * Prints {"url": ...} on stdout once it listens, and one JSON log line per event on stderr.
9
+ */
10
+
11
+ import { browserToolsChromeBin, hasFlag, parsePositiveIntegerOption, requiredOptionValue } from './browser-control.mjs';
12
+ import { DEFAULT_MAX_TABS, DEFAULT_TAB_SECONDS, serveTabs } from './tab-broker.mjs';
13
+
14
+ const args = process.argv.slice(2);
15
+ const chromeArgs = args.flatMap((arg, index) => (args[index - 1] === '--chrome-arg' ? [arg] : []));
16
+
17
+ const served = await serveTabs({
18
+ chromeBin: browserToolsChromeBin(),
19
+ chromeArgs,
20
+ headless: hasFlag(args, '--headless'),
21
+ proxyServer: requiredOptionValue(args, '--proxy-server'),
22
+ maxTabs: parsePositiveIntegerOption(args, '--max-tabs', DEFAULT_MAX_TABS),
23
+ tabSeconds: parsePositiveIntegerOption(args, '--tab-seconds', DEFAULT_TAB_SECONDS),
24
+ port: parsePositiveIntegerOption(args, '--port', 0),
25
+ });
26
+ process.stdout.write(`${JSON.stringify({ url: served.url })}\n`);
27
+
28
+ let stopping = false;
29
+ async function stop() {
30
+ if (stopping) return;
31
+ stopping = true;
32
+ await served.close();
33
+ process.exit(0);
34
+ }
35
+ process.on('SIGTERM', stop);
36
+ process.on('SIGINT', stop);
37
+ // A parent that holds our stdin and dies, even by SIGKILL, closes it, so the browser goes with it.
38
+ if (hasFlag(args, '--until-stdin-closes')) {
39
+ process.stdin.on('end', stop);
40
+ process.stdin.on('close', stop);
41
+ process.stdin.resume();
42
+ }
package/scripts/stop.mjs CHANGED
@@ -8,8 +8,8 @@
8
8
  * scripts/stop.mjs --port 9223
9
9
  * scripts/stop.mjs --clean
10
10
  * scripts/stop.mjs --dry-run
11
- * scripts/stop.mjs --prune (reap orphans, then remove all cached clones not in use)
12
- * scripts/stop.mjs --reap (kill managed browsers no lifecycle file tracks)
11
+ * scripts/stop.mjs --prune (reap leftovers, then remove all cached clones not in use)
12
+ * scripts/stop.mjs --reap (kill reclaimable managed browsers)
13
13
  * scripts/stop.mjs --reap --dry-run (list them without killing anything)
14
14
  * scripts/stop.mjs --status (show how many managed browsers are running)
15
15
  * scripts/stop.mjs --owner-token "$BROWSER_TOOLS_OWNER_TOKEN"
@@ -35,7 +35,7 @@ const ownerToken = parseOwnerToken(args);
35
35
 
36
36
  function reportReaped(reaped, wasDryRun) {
37
37
  if (!reaped.length) {
38
- console.log('No untracked managed browsers found.');
38
+ console.log('No reclaimable managed browsers found.');
39
39
  return;
40
40
  }
41
41
  for (const entry of reaped) {
@@ -0,0 +1,351 @@
1
+ /**
2
+ * One Chrome shared by every client on the machine, handing out at most `maxTabs` tabs at a time.
3
+ *
4
+ * A client leases a tab with an HTTP request that the broker answers with one JSON line once a tab is
5
+ * free and then holds open. The tab lives in a browser context of its own, so tabs share no cookies or
6
+ * storage, and the context is disposed when the client closes the connection (or exits), or when the
7
+ * tab has been held for `tabSeconds`.
8
+ */
9
+
10
+ import { spawn } from 'node:child_process';
11
+ import { randomUUID } from 'node:crypto';
12
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs';
13
+ import { createServer, get as httpGet } from 'node:http';
14
+ import { tmpdir } from 'node:os';
15
+ import { join } from 'node:path';
16
+ import { connectOwnBrowser } from './browser-control.mjs';
17
+
18
+ export const DEFAULT_MAX_TABS = 4;
19
+ export const DEFAULT_TAB_SECONDS = 120;
20
+ export const DEFAULT_SAMPLE_SECONDS = 15;
21
+ const CHROME_START_TIMEOUT_MS = 30_000;
22
+ const CHROME_STOP_TIMEOUT_MS = 5_000;
23
+
24
+ // Everything a fresh profile would start in the background is off: tabs are the only work.
25
+ export const LEAN_CHROME_ARGS = [
26
+ '--no-first-run',
27
+ '--no-default-browser-check',
28
+ '--no-startup-window',
29
+ '--disable-sync',
30
+ '--disable-extensions',
31
+ '--disable-component-extensions-with-background-pages',
32
+ '--disable-component-update',
33
+ '--disable-default-apps',
34
+ '--disable-background-networking',
35
+ '--disable-domain-reliability',
36
+ '--disable-client-side-phishing-detection',
37
+ '--disable-breakpad',
38
+ '--disable-crash-reporter',
39
+ '--no-service-autorun',
40
+ '--password-store=basic',
41
+ '--mute-audio',
42
+ '--disable-blink-features=AutomationControlled',
43
+ // A closed tab's renderer would otherwise stay alive for the back-forward cache, and a spare
44
+ // renderer is kept warm for the next navigation.
45
+ '--disable-features=BackForwardCache,SpareRendererForSitePerProcess,Translate,MediaRouter,OptimizationHints,InterestFeedContentSuggestions,AutofillServerCommunication',
46
+ ];
47
+
48
+ function defaultLog(line) {
49
+ process.stderr.write(`${JSON.stringify(line)}\n`);
50
+ }
51
+
52
+ export async function serveTabs({
53
+ chromeBin,
54
+ chromeArgs = [],
55
+ headless = false,
56
+ proxyServer = null,
57
+ maxTabs = DEFAULT_MAX_TABS,
58
+ tabSeconds = DEFAULT_TAB_SECONDS,
59
+ sampleSeconds = DEFAULT_SAMPLE_SECONDS,
60
+ host = '127.0.0.1',
61
+ port = 0,
62
+ log = defaultLog,
63
+ }) {
64
+ if (!chromeBin) throw new Error('chromeBin is required');
65
+ if (!Number.isInteger(maxTabs) || maxTabs < 1) throw new Error('maxTabs must be a positive integer');
66
+ if (!(tabSeconds > 0)) throw new Error('tabSeconds must be positive');
67
+
68
+ const waiting = [];
69
+ const held = new Set();
70
+ let chrome = null;
71
+ let starting = null;
72
+ let closed = false;
73
+
74
+ async function launchChrome() {
75
+ const profile = mkdtempSync(join(tmpdir(), 'browser-tools-tabs-'));
76
+ const args = [...LEAN_CHROME_ARGS, `--user-data-dir=${profile}`, '--remote-debugging-address=127.0.0.1', '--remote-debugging-port=0'];
77
+ if (headless) args.push('--headless=new');
78
+ if (proxyServer) {
79
+ // Chrome sends loopback addresses around a proxy unless told otherwise, and WebRTC around it
80
+ // over UDP, either of which would let a page reach what the proxy refuses.
81
+ args.push(`--proxy-server=${proxyServer}`, '--proxy-bypass-list=<-loopback>', '--webrtc-ip-handling-policy=disable_non_proxied_udp');
82
+ }
83
+ args.push(...chromeArgs);
84
+ const child = spawn(chromeBin, args, { stdio: ['ignore', 'ignore', 'pipe'] });
85
+ let stderr = '';
86
+ child.stderr.on('data', (chunk) => {
87
+ stderr = (stderr + chunk).slice(-2000);
88
+ });
89
+ const exited = new Promise((resolve) => child.once('exit', (code, signal) => resolve({ code, signal })));
90
+ const portFile = join(profile, 'DevToolsActivePort');
91
+ const deadline = Date.now() + CHROME_START_TIMEOUT_MS;
92
+ let exit = null;
93
+ exited.then((value) => {
94
+ exit = value;
95
+ });
96
+ while (!existsSync(portFile) || readFileSync(portFile, 'utf8').split('\n').length < 2) {
97
+ if (exit) throw new Error(`Chrome exited while starting (${exit.signal ?? exit.code}): ${stderr.trim().slice(-500)}`);
98
+ if (Date.now() > deadline) {
99
+ child.kill('SIGKILL');
100
+ throw new Error(`Chrome did not start within ${CHROME_START_TIMEOUT_MS}ms`);
101
+ }
102
+ await new Promise((resolve) => setTimeout(resolve, 50));
103
+ }
104
+ const [cdpPort, path] = readFileSync(portFile, 'utf8').split('\n');
105
+ const cdpUrl = `ws://127.0.0.1:${cdpPort}${path}`;
106
+ const browser = await connectOwnBrowser(cdpUrl, { targetFilter: () => false });
107
+ const session = await browser.target().createCDPSession();
108
+ const started = { child, browser, session, cdpUrl, cdpPort: Number(cdpPort), profile, exited };
109
+ exited.then(({ code, signal }) => {
110
+ if (chrome === started) chrome = null;
111
+ rmSync(profile, { recursive: true, force: true });
112
+ if (!closed) log({ event: 'browser_exit', code, signal });
113
+ });
114
+ log({ event: 'browser_start', pid: child.pid });
115
+ return started;
116
+ }
117
+
118
+ async function ensureChrome() {
119
+ if (chrome && chrome.browser.connected && chrome.child.exitCode === null && chrome.child.signalCode === null) return chrome;
120
+ chrome = null;
121
+ starting ??= launchChrome().finally(() => {
122
+ starting = null;
123
+ });
124
+ chrome = await starting;
125
+ return chrome;
126
+ }
127
+
128
+ function pump() {
129
+ while (!closed && held.size < maxTabs && waiting.length > 0) {
130
+ const lease = waiting.shift();
131
+ held.add(lease);
132
+ void grant(lease);
133
+ }
134
+ }
135
+
136
+ function write(lease, line) {
137
+ if (!lease.response.writableEnded && !lease.response.destroyed) lease.response.write(`${JSON.stringify(line)}\n`);
138
+ }
139
+
140
+ function end(lease, ended) {
141
+ if (lease.ended) return;
142
+ lease.ended = ended;
143
+ clearTimeout(lease.timer);
144
+ held.delete(lease);
145
+ if (lease.context && lease.chrome) {
146
+ lease.chrome.session.send('Target.disposeBrowserContext', { browserContextId: lease.context }).catch(() => {});
147
+ }
148
+ log({
149
+ event: 'tab_lease',
150
+ client: lease.client,
151
+ waited_ms: (lease.granted ?? Date.now()) - lease.asked,
152
+ held_ms: lease.granted ? Date.now() - lease.granted : 0,
153
+ ended,
154
+ tabs: held.size,
155
+ waiting: waiting.length,
156
+ });
157
+ if (ended !== 'released') {
158
+ write(lease, ended === 'error' ? { error: lease.error } : { ended });
159
+ lease.response.end();
160
+ }
161
+ pump();
162
+ }
163
+
164
+ async function grant(lease) {
165
+ try {
166
+ const running = await ensureChrome();
167
+ lease.chrome = running;
168
+ const { browserContextId } = await running.session.send('Target.createBrowserContext', {
169
+ disposeOnDetach: false,
170
+ ...(proxyServer ? { proxyServer, proxyBypassList: '<-loopback>' } : {}),
171
+ });
172
+ lease.context = browserContextId;
173
+ await running.session.send('Browser.setDownloadBehavior', { behavior: 'deny', browserContextId });
174
+ // The tab opens on an address of its own, which is how a client finds it among the browser's targets.
175
+ const tabUrl = `about:blank#${randomUUID()}`;
176
+ const { targetId } = await running.session.send('Target.createTarget', { url: tabUrl, browserContextId });
177
+ if (lease.gone) return end(lease, 'released');
178
+ lease.granted = Date.now();
179
+ lease.timer = setTimeout(() => end(lease, 'expired'), tabSeconds * 1000);
180
+ write(lease, { cdp_url: running.cdpUrl, target_id: targetId, tab_url: tabUrl, deadline: lease.granted + tabSeconds * 1000 });
181
+ } catch (error) {
182
+ lease.error = error instanceof Error ? error.message : String(error);
183
+ end(lease, 'error');
184
+ }
185
+ }
186
+
187
+ const server = createServer((request, response) => {
188
+ const url = new URL(request.url, 'http://broker');
189
+ if (request.method !== 'GET' || url.pathname !== '/lease') {
190
+ response.writeHead(404).end();
191
+ return;
192
+ }
193
+ if (closed) {
194
+ response.writeHead(503).end();
195
+ return;
196
+ }
197
+ const lease = { client: url.searchParams.get('client') || 'unnamed', asked: Date.now(), response, gone: false };
198
+ response.writeHead(200, { 'content-type': 'application/x-ndjson', 'cache-control': 'no-store' });
199
+ response.flushHeaders();
200
+ response.on('close', () => {
201
+ lease.gone = true;
202
+ const queued = waiting.indexOf(lease);
203
+ if (queued >= 0) waiting.splice(queued, 1);
204
+ else if (lease.granted) end(lease, 'released');
205
+ });
206
+ waiting.push(lease);
207
+ pump();
208
+ });
209
+ server.requestTimeout = 0;
210
+ await new Promise((resolve, reject) => {
211
+ server.once('error', reject);
212
+ server.listen(port, host, resolve);
213
+ });
214
+
215
+ const sampler =
216
+ process.platform === 'linux'
217
+ ? setInterval(() => {
218
+ if (!chrome) return;
219
+ const sample = chromeMemory(chrome.child.pid);
220
+ if (sample) log({ event: 'browser_memory', ...sample, tabs: held.size, waiting: waiting.length });
221
+ }, sampleSeconds * 1000)
222
+ : null;
223
+ sampler?.unref();
224
+
225
+ const address = server.address();
226
+ return {
227
+ url: `http://${host}:${address.port}`,
228
+ get cdpPort() {
229
+ return chrome?.cdpPort ?? null;
230
+ },
231
+ async close() {
232
+ closed = true;
233
+ if (sampler) clearInterval(sampler);
234
+ for (const lease of [...held]) end(lease, 'closed');
235
+ for (const lease of waiting.splice(0)) lease.response.writeHead?.(503) && lease.response.end();
236
+ server.closeAllConnections();
237
+ await new Promise((resolve) => server.close(resolve));
238
+ const running = chrome ?? (await starting?.catch(() => null));
239
+ if (!running) return;
240
+ await running.session.send('Browser.close').catch(() => {});
241
+ running.browser.disconnect().catch?.(() => {});
242
+ const stopped = await Promise.race([
243
+ running.exited.then(() => true),
244
+ new Promise((resolve) => setTimeout(() => resolve(false), CHROME_STOP_TIMEOUT_MS)),
245
+ ]);
246
+ if (!stopped) {
247
+ running.child.kill('SIGKILL');
248
+ await running.exited;
249
+ }
250
+ },
251
+ };
252
+ }
253
+
254
+ const PROCESS_TYPES = { renderer: 'renderer', 'gpu-process': 'gpu', utility: 'utility', zygote: 'zygote' };
255
+
256
+ /** Proportional set size of Chrome's process tree, by process type, from /proc. */
257
+ export function chromeMemory(rootPid) {
258
+ const children = new Map();
259
+ for (const name of readdirSync('/proc')) {
260
+ if (!/^\d+$/.test(name)) continue;
261
+ try {
262
+ const stat = readFileSync(`/proc/${name}/stat`, 'utf8');
263
+ const ppid = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]);
264
+ if (!children.has(ppid)) children.set(ppid, []);
265
+ children.get(ppid).push(Number(name));
266
+ } catch {
267
+ // The process exited while the table was read.
268
+ }
269
+ }
270
+ const pss = { browser: 0, renderer: 0, gpu: 0, utility: 0, zygote: 0, other: 0 };
271
+ let processes = 0;
272
+ let renderers = 0;
273
+ const pending = [rootPid];
274
+ while (pending.length > 0) {
275
+ const pid = pending.pop();
276
+ pending.push(...(children.get(pid) ?? []));
277
+ try {
278
+ const rollup = readFileSync(`/proc/${pid}/smaps_rollup`, 'utf8');
279
+ const kib = Number(/^Pss:\s+(\d+)/m.exec(rollup)?.[1] ?? 0);
280
+ const type = /--type=([\w-]+)/.exec(readFileSync(`/proc/${pid}/cmdline`, 'utf8').replaceAll('\0', ' '))?.[1];
281
+ const key = pid === rootPid ? 'browser' : (PROCESS_TYPES[type] ?? 'other');
282
+ pss[key] += kib;
283
+ processes += 1;
284
+ if (key === 'renderer') renderers += 1;
285
+ } catch {
286
+ // The process exited while it was read.
287
+ }
288
+ }
289
+ if (processes === 0) return null;
290
+ const mib = (kib) => Math.round(kib / 1024);
291
+ return {
292
+ total_mib: mib(Object.values(pss).reduce((sum, kib) => sum + kib, 0)),
293
+ pss_mib: Object.fromEntries(Object.entries(pss).map(([key, kib]) => [key, mib(kib)])),
294
+ processes,
295
+ renderers,
296
+ };
297
+ }
298
+
299
+ /**
300
+ * Waits for a tab from the broker at `brokerUrl`. The tab is the client's until `release()` is called
301
+ * or the process exits; `ended` settles with 'expired' if the broker took the tab back first.
302
+ * The tab is the page at `tabUrl` in the browser at `cdpUrl`.
303
+ */
304
+ export function leaseTab(brokerUrl, { client = 'unnamed' } = {}) {
305
+ return new Promise((resolve, reject) => {
306
+ let granted = null;
307
+ let finish;
308
+ const ended = new Promise((resolveEnded) => {
309
+ finish = resolveEnded;
310
+ });
311
+ const request = httpGet(`${brokerUrl}/lease?client=${encodeURIComponent(client)}`, { agent: false }, (response) => {
312
+ if (response.statusCode !== 200) {
313
+ response.resume();
314
+ reject(new Error(`the tab broker refused the lease with HTTP ${response.statusCode}`));
315
+ return;
316
+ }
317
+ response.setEncoding('utf8');
318
+ let buffer = '';
319
+ response.on('data', (chunk) => {
320
+ buffer += chunk;
321
+ for (let index = buffer.indexOf('\n'); index >= 0; index = buffer.indexOf('\n')) {
322
+ const line = JSON.parse(buffer.slice(0, index));
323
+ buffer = buffer.slice(index + 1);
324
+ if (line.error) {
325
+ reject(new Error(`the tab broker could not open a tab: ${line.error}`));
326
+ } else if (!granted) {
327
+ granted = {
328
+ cdpUrl: line.cdp_url,
329
+ targetId: line.target_id,
330
+ tabUrl: line.tab_url,
331
+ deadline: line.deadline,
332
+ ended,
333
+ release: () => request.destroy(),
334
+ };
335
+ resolve(granted);
336
+ } else if (line.ended) {
337
+ finish(line.ended);
338
+ }
339
+ }
340
+ });
341
+ response.on('close', () => {
342
+ if (!granted) reject(new Error('the tab broker closed the lease before granting a tab'));
343
+ finish('released');
344
+ });
345
+ });
346
+ request.on('error', (error) => {
347
+ if (!granted) reject(error);
348
+ finish('released');
349
+ });
350
+ });
351
+ }