@skilldeck/studio 0.0.0-stage → 0.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,310 @@
1
+ // studio / lib/cdp.mjs
2
+ //
3
+ // A minimal Chrome DevTools Protocol client with no dependencies: find a local
4
+ // Chrome, launch it headless with --remote-debugging-port=0, read the browser
5
+ // WebSocket URL from stderr or DevToolsActivePort, and talk CDP over Node 22's
6
+ // global WebSocket using flattened target sessions.
7
+ //
8
+ // Nothing here touches the network beyond 127.0.0.1.
9
+
10
+ import { spawn, spawnSync } from 'node:child_process'
11
+ import fs from 'node:fs'
12
+ import os from 'node:os'
13
+ import path from 'node:path'
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // Finding Chrome
17
+ // ---------------------------------------------------------------------------
18
+
19
+ const MAC_APPS = [
20
+ 'Google Chrome.app/Contents/MacOS/Google Chrome',
21
+ 'Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',
22
+ 'Chromium.app/Contents/MacOS/Chromium',
23
+ 'Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
24
+ 'Brave Browser.app/Contents/MacOS/Brave Browser',
25
+ ]
26
+ const LINUX_BINS = ['google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser', 'microsoft-edge', 'microsoft-edge-stable', 'brave-browser']
27
+ const WIN_REL = [
28
+ ['Google', 'Chrome', 'Application', 'chrome.exe'],
29
+ ['Chromium', 'Application', 'chrome.exe'],
30
+ ['Microsoft', 'Edge', 'Application', 'msedge.exe'],
31
+ ['BraveSoftware', 'Brave-Browser', 'Application', 'brave.exe'],
32
+ ]
33
+
34
+ /** Ordered list of places a Chromium browser may live on this platform. */
35
+ export function chromeCandidates(platform = process.platform, env = process.env, home = os.homedir()) {
36
+ if (platform === 'darwin') {
37
+ return [...MAC_APPS.map((a) => path.posix.join('/Applications', a)), ...MAC_APPS.map((a) => path.posix.join(home, 'Applications', a))]
38
+ }
39
+ if (platform === 'win32') {
40
+ const roots = [env.PROGRAMFILES, env['PROGRAMFILES(X86)'], env.LOCALAPPDATA].filter(Boolean)
41
+ return roots.flatMap((r) => WIN_REL.map((rel) => path.win32.join(r, ...rel)))
42
+ }
43
+ const dirs = (env.PATH ?? '').split(':').filter(Boolean)
44
+ const onPath = LINUX_BINS.flatMap((b) => dirs.map((d) => path.posix.join(d, b)))
45
+ const fixed = ['/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/snap/bin/chromium', '/opt/google/chrome/chrome']
46
+ return [...new Set([...onPath, ...fixed])]
47
+ }
48
+
49
+ /**
50
+ * Locate a Chromium browser. CHROME_PATH wins when set.
51
+ * Returns { path, source } or { path: null, error, tried }.
52
+ */
53
+ export function findChrome({ env = process.env, platform = process.platform, exists = fs.existsSync, home = os.homedir() } = {}) {
54
+ if (env.CHROME_PATH) {
55
+ return exists(env.CHROME_PATH)
56
+ ? { path: env.CHROME_PATH, source: 'CHROME_PATH' }
57
+ : { path: null, error: `CHROME_PATH is set to ${env.CHROME_PATH}, which does not exist`, tried: [env.CHROME_PATH] }
58
+ }
59
+ const tried = chromeCandidates(platform, env, home)
60
+ const hit = tried.find((p) => exists(p))
61
+ if (hit) return { path: hit, source: 'search' }
62
+ return { path: null, error: 'no Chrome, Chromium, Edge or Brave found; install one or set CHROME_PATH', tried }
63
+ }
64
+
65
+ /** Best-effort browser version string (Windows builds do not print one). */
66
+ export function chromeVersion(chromePath) {
67
+ try {
68
+ const r = spawnSync(chromePath, ['--version'], { encoding: 'utf8', timeout: 15000 })
69
+ return (r.stdout || '').trim() || null
70
+ } catch {
71
+ return null
72
+ }
73
+ }
74
+
75
+ // ---------------------------------------------------------------------------
76
+ // Launching
77
+ // ---------------------------------------------------------------------------
78
+
79
+ /** Flags for a quiet, deterministic, isolated headless browser. */
80
+ export function chromeArgs({ userDataDir, headless = true, extra = [] } = {}) {
81
+ return [
82
+ headless ? '--headless=new' : null,
83
+ '--remote-debugging-port=0',
84
+ '--remote-debugging-address=127.0.0.1',
85
+ userDataDir ? `--user-data-dir=${userDataDir}` : null,
86
+ '--no-first-run',
87
+ '--no-default-browser-check',
88
+ '--disable-extensions',
89
+ '--disable-background-networking',
90
+ '--disable-background-timer-throttling',
91
+ '--disable-backgrounding-occluded-windows',
92
+ '--disable-renderer-backgrounding',
93
+ '--disable-component-update',
94
+ '--disable-default-apps',
95
+ '--disable-sync',
96
+ '--metrics-recording-only',
97
+ '--password-store=basic',
98
+ '--use-mock-keychain',
99
+ '--hide-scrollbars',
100
+ '--mute-audio',
101
+ '--force-color-profile=srgb',
102
+ '--font-render-hinting=none',
103
+ '--allow-file-access-from-files',
104
+ ...extra,
105
+ 'about:blank',
106
+ ].filter(Boolean)
107
+ }
108
+
109
+ /** Pull the browser WebSocket URL out of Chrome's stderr. */
110
+ export function parseDevToolsUrl(text) {
111
+ const m = /DevTools listening on (ws:\/\/\S+)/.exec(String(text))
112
+ return m ? m[1] : null
113
+ }
114
+
115
+ /** DevToolsActivePort holds "<port>\n<browser path>". */
116
+ export function parseActivePort(text, host = '127.0.0.1') {
117
+ const [port, p] = String(text).trim().split(/\r?\n/)
118
+ if (!/^\d+$/.test(port ?? '') || !p) return null
119
+ return `ws://${host}:${port}${p}`
120
+ }
121
+
122
+ /**
123
+ * Launch a headless browser with a throwaway profile.
124
+ * Returns { wsUrl, proc, userDataDir, close() }.
125
+ */
126
+ export async function launchChrome({ chromePath, headless = true, extraArgs = [], timeoutMs = 30000 } = {}) {
127
+ if (!chromePath) {
128
+ const found = findChrome()
129
+ if (!found.path) throw Object.assign(new Error(found.error), { code: 'ENOCHROME' })
130
+ chromePath = found.path
131
+ }
132
+ const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'studio-chrome-'))
133
+ const proc = spawn(chromePath, chromeArgs({ userDataDir, headless, extra: extraArgs }), { stdio: ['ignore', 'ignore', 'pipe'] })
134
+ let stderr = ''
135
+ const wsUrl = await new Promise((resolve, reject) => {
136
+ const portFile = path.join(userDataDir, 'DevToolsActivePort')
137
+ const done = (err, url) => {
138
+ clearInterval(poll)
139
+ clearTimeout(timer)
140
+ proc.stderr.off('data', onData)
141
+ proc.off('exit', onExit)
142
+ err ? reject(err) : resolve(url)
143
+ }
144
+ const onData = (d) => {
145
+ stderr += d
146
+ const url = parseDevToolsUrl(stderr)
147
+ if (url) done(null, url)
148
+ }
149
+ const onExit = (code) => done(new Error(`Chrome exited (code ${code}) before DevTools was ready\n${stderr.slice(-2000)}`))
150
+ const poll = setInterval(() => {
151
+ try {
152
+ const url = parseActivePort(fs.readFileSync(portFile, 'utf8'))
153
+ if (url) done(null, url)
154
+ } catch {}
155
+ }, 100)
156
+ const timer = setTimeout(() => done(new Error(`Chrome did not expose DevTools within ${timeoutMs}ms\n${stderr.slice(-2000)}`)), timeoutMs)
157
+ proc.stderr.on('data', onData)
158
+ proc.on('exit', onExit)
159
+ proc.on('error', (e) => done(e))
160
+ })
161
+ proc.stderr.resume()
162
+ let closed = false
163
+ const close = async () => {
164
+ if (closed) return
165
+ closed = true
166
+ if (proc.exitCode === null) {
167
+ const exited = new Promise((res) => proc.once('exit', res))
168
+ proc.kill('SIGTERM')
169
+ const t = setTimeout(() => proc.kill('SIGKILL'), 3000)
170
+ await exited
171
+ clearTimeout(t)
172
+ }
173
+ for (let i = 0; i < 5; i++) {
174
+ try {
175
+ fs.rmSync(userDataDir, { recursive: true, force: true })
176
+ break
177
+ } catch {
178
+ await new Promise((r) => setTimeout(r, 200))
179
+ }
180
+ }
181
+ }
182
+ return { wsUrl, proc, userDataDir, close }
183
+ }
184
+
185
+ // ---------------------------------------------------------------------------
186
+ // The protocol client
187
+ // ---------------------------------------------------------------------------
188
+
189
+ export class CDP {
190
+ constructor(ws) {
191
+ this.ws = ws
192
+ this.nextId = 1
193
+ this.pending = new Map()
194
+ this.listeners = new Set()
195
+ ws.addEventListener('message', (e) => this.#onMessage(e.data))
196
+ ws.addEventListener('close', () => {
197
+ for (const p of this.pending.values()) p.reject(new Error('CDP connection closed'))
198
+ this.pending.clear()
199
+ })
200
+ }
201
+
202
+ static async connect(wsUrl, { timeoutMs = 15000 } = {}) {
203
+ if (typeof WebSocket !== 'function') throw Object.assign(new Error('global WebSocket is missing: Node 22 or newer is required'), { code: 'ENODE' })
204
+ const ws = new WebSocket(wsUrl)
205
+ await new Promise((resolve, reject) => {
206
+ const t = setTimeout(() => reject(new Error(`could not connect to ${wsUrl}`)), timeoutMs)
207
+ ws.addEventListener('open', () => (clearTimeout(t), resolve()), { once: true })
208
+ ws.addEventListener('error', () => (clearTimeout(t), reject(new Error(`could not connect to ${wsUrl}`))), { once: true })
209
+ })
210
+ return new CDP(ws)
211
+ }
212
+
213
+ #onMessage(data) {
214
+ const msg = JSON.parse(typeof data === 'string' ? data : Buffer.from(data).toString('utf8'))
215
+ if (msg.id !== undefined) {
216
+ const p = this.pending.get(msg.id)
217
+ if (!p) return
218
+ this.pending.delete(msg.id)
219
+ if (msg.error) p.reject(new Error(`${p.method}: ${msg.error.message}${msg.error.data ? ` (${msg.error.data})` : ''}`))
220
+ else p.resolve(msg.result ?? {})
221
+ return
222
+ }
223
+ for (const l of this.listeners) if (l.method === msg.method && (l.sessionId === undefined || l.sessionId === msg.sessionId)) l.fn(msg.params ?? {})
224
+ }
225
+
226
+ /** Send a command; `sessionId` targets an attached page. */
227
+ send(method, params = {}, sessionId) {
228
+ const id = this.nextId++
229
+ const payload = { id, method, params }
230
+ if (sessionId) payload.sessionId = sessionId
231
+ return new Promise((resolve, reject) => {
232
+ this.pending.set(id, { resolve, reject, method })
233
+ this.ws.send(JSON.stringify(payload))
234
+ })
235
+ }
236
+
237
+ /** Subscribe to an event; returns an unsubscribe function. */
238
+ on(method, fn, sessionId) {
239
+ const l = { method, fn, sessionId }
240
+ this.listeners.add(l)
241
+ return () => this.listeners.delete(l)
242
+ }
243
+
244
+ /** Resolve with the next matching event, or reject after `timeoutMs`. */
245
+ once(method, { sessionId, timeoutMs = 30000, predicate = () => true } = {}) {
246
+ return new Promise((resolve, reject) => {
247
+ const t = setTimeout(() => (off(), reject(new Error(`timed out waiting for ${method}`))), timeoutMs)
248
+ const off = this.on(
249
+ method,
250
+ (p) => {
251
+ if (!predicate(p)) return
252
+ clearTimeout(t)
253
+ off()
254
+ resolve(p)
255
+ },
256
+ sessionId,
257
+ )
258
+ })
259
+ }
260
+
261
+ close() {
262
+ try {
263
+ this.ws.close()
264
+ } catch {}
265
+ }
266
+ }
267
+
268
+ /** Create a new tab and attach to it with a flattened session. */
269
+ export async function openPage(cdp) {
270
+ const { targetId } = await cdp.send('Target.createTarget', { url: 'about:blank' })
271
+ const { sessionId } = await cdp.send('Target.attachToTarget', { targetId, flatten: true })
272
+ return {
273
+ targetId,
274
+ sessionId,
275
+ send: (method, params) => cdp.send(method, params, sessionId),
276
+ on: (method, fn) => cdp.on(method, fn, sessionId),
277
+ once: (method, opts = {}) => cdp.once(method, { ...opts, sessionId }),
278
+ /** Evaluate an expression, awaiting promises, and return its JSON value. */
279
+ async evaluate(expression, { timeoutMs = 60000 } = {}) {
280
+ let timer
281
+ const r = await Promise.race([
282
+ cdp.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, sessionId),
283
+ new Promise((_, rej) => (timer = setTimeout(() => rej(new Error(`evaluation timed out after ${timeoutMs}ms`)), timeoutMs))),
284
+ ]).finally(() => clearTimeout(timer))
285
+ if (r.exceptionDetails) {
286
+ const d = r.exceptionDetails
287
+ throw new Error(d.exception?.description ?? d.exception?.value ?? d.text ?? 'evaluation failed')
288
+ }
289
+ return r.result?.value
290
+ },
291
+ }
292
+ }
293
+
294
+ /** Launch, connect, run `fn({ cdp, browser })`, and always tear the browser down. */
295
+ export async function withChrome(fn, opts = {}) {
296
+ const browser = await launchChrome(opts)
297
+ let cdp
298
+ try {
299
+ cdp = await CDP.connect(browser.wsUrl)
300
+ return await fn({ cdp, browser })
301
+ } finally {
302
+ if (cdp) {
303
+ let t
304
+ await Promise.race([cdp.send('Browser.close').catch(() => {}), new Promise((r) => (t = setTimeout(r, 2000)))])
305
+ clearTimeout(t)
306
+ cdp.close()
307
+ }
308
+ await browser.close()
309
+ }
310
+ }