@rezkam/browser-tools 0.2.1 → 1.0.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,451 @@
1
+ import { spawn, spawnSync } from 'node:child_process';
2
+ import {
3
+ chmodSync,
4
+ closeSync,
5
+ existsSync,
6
+ mkdirSync,
7
+ readFileSync,
8
+ renameSync,
9
+ rmSync,
10
+ statSync,
11
+ writeFileSync,
12
+ } from 'node:fs';
13
+ import { basename, dirname, extname, join, parse, resolve } from 'node:path';
14
+ import {
15
+ OWNER_TOKEN_ENV,
16
+ activePage,
17
+ browserToolsCacheDir,
18
+ connectBrowser,
19
+ ensureCacheDir,
20
+ normalizePort,
21
+ ownerTokenHash,
22
+ sleep,
23
+ } from './browser-control.mjs';
24
+ import { openPrivateFile } from './cdp-common.mjs';
25
+
26
+ export const DEFAULT_GIF_FPS = 10;
27
+ export const DEFAULT_GIF_COLORS = 128;
28
+ export const DEFAULT_GIF_SCALE = 1;
29
+ export const DEFAULT_GIF_PRE_ROLL_MS = 1000;
30
+ export const DEFAULT_GIF_POST_ROLL_MS = 1000;
31
+ export const DEFAULT_GIF_MAX_DURATION_SECONDS = 120;
32
+ export const GIF_START_TIMEOUT_MS = 30000;
33
+ export const GIF_STOP_TIMEOUT_MS = 30000;
34
+
35
+ const GENERIC_GIF_STEMS = new Set([
36
+ 'animation',
37
+ 'browser',
38
+ 'browsercapture',
39
+ 'browsergif',
40
+ 'browserrecording',
41
+ 'capture',
42
+ 'demo',
43
+ 'gif',
44
+ 'output',
45
+ 'page',
46
+ 'recording',
47
+ 'test',
48
+ 'untitled',
49
+ 'website',
50
+ ]);
51
+
52
+ function writePrivateJson(file, value) {
53
+ const temporaryFile = `${file}.${process.pid}.tmp`;
54
+ writeFileSync(temporaryFile, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
55
+ renameSync(temporaryFile, file);
56
+ try {
57
+ chmodSync(file, 0o600);
58
+ } catch {
59
+ // Best effort. Recording state contains paths but never the owner token itself.
60
+ }
61
+ }
62
+
63
+ function readJson(file) {
64
+ try {
65
+ return JSON.parse(readFileSync(file, 'utf-8'));
66
+ } catch (error) {
67
+ if (error?.code === 'ENOENT') return null;
68
+ throw error;
69
+ }
70
+ }
71
+
72
+ function processExists(pid) {
73
+ if (!Number.isInteger(Number(pid)) || Number(pid) < 1) return false;
74
+ try {
75
+ process.kill(Number(pid), 0);
76
+ return true;
77
+ } catch (error) {
78
+ return error?.code === 'EPERM';
79
+ }
80
+ }
81
+
82
+ function normalizedStem(path) {
83
+ return parse(basename(path)).name.toLowerCase().replace(/[^a-z0-9]/g, '');
84
+ }
85
+
86
+ export function normalizeGifOutputPath(output, { cwd = process.cwd() } = {}) {
87
+ if (!output || output === true || !String(output).trim()) {
88
+ throw new Error('Missing --output. Use a meaningful action-specific filename, for example login_process.gif');
89
+ }
90
+
91
+ const path = resolve(cwd, String(output));
92
+ if (extname(path).toLowerCase() !== '.gif') {
93
+ throw new Error(`GIF output must end in .gif: ${output}`);
94
+ }
95
+ if (GENERIC_GIF_STEMS.has(normalizedStem(path))) {
96
+ throw new Error(`GIF output name is too generic: ${basename(path)}. Describe the interaction, for example login_process.gif`);
97
+ }
98
+ return path;
99
+ }
100
+
101
+ export function parseBoundedNumber(value, name, { fallback, min, max, integer = false }) {
102
+ if (value === null || value === undefined) return fallback;
103
+ if (value === true || String(value).trim() === '') throw new Error(`Missing value after ${name}`);
104
+ const number = Number(value);
105
+ if (!Number.isFinite(number) || number < min || number > max || (integer && !Number.isInteger(number))) {
106
+ const kind = integer ? 'an integer' : 'a number';
107
+ throw new Error(`Invalid ${name} value: expected ${kind} from ${min} to ${max}, got "${value}"`);
108
+ }
109
+ return number;
110
+ }
111
+
112
+ export function gifRecordingDirForPort(port) {
113
+ return join(browserToolsCacheDir(), `gif-recording-${normalizePort(port)}`);
114
+ }
115
+
116
+ export function gifRecordingStateFile(port) {
117
+ return join(gifRecordingDirForPort(port), 'state.json');
118
+ }
119
+
120
+ export function gifRecordingStopFile(port) {
121
+ return join(gifRecordingDirForPort(port), 'stop-request.json');
122
+ }
123
+
124
+ export function gifRecordingLogFile(port) {
125
+ return join(gifRecordingDirForPort(port), 'recorder.log');
126
+ }
127
+
128
+ export function readGifRecordingState(port) {
129
+ return readJson(gifRecordingStateFile(port));
130
+ }
131
+
132
+ export function gifRecordingReport(port) {
133
+ const normalizedPort = normalizePort(port);
134
+ const state = readGifRecordingState(normalizedPort);
135
+ if (!state) return { recording: false, port: normalizedPort };
136
+
137
+ const processRunning = processExists(state.pid);
138
+ const terminal = state.status === 'completed' || state.status === 'failed';
139
+ return {
140
+ recording: processRunning && !terminal,
141
+ processRunning,
142
+ port: normalizedPort,
143
+ pid: state.pid ?? null,
144
+ status: state.status ?? 'unknown',
145
+ phase: state.phase ?? null,
146
+ output: state.output ?? null,
147
+ startedAt: state.startedAt ?? null,
148
+ completedAt: state.completedAt ?? null,
149
+ reason: state.reason ?? null,
150
+ error: state.error ?? null,
151
+ };
152
+ }
153
+
154
+ export function claimGifRecording(port) {
155
+ const normalizedPort = normalizePort(port);
156
+ ensureCacheDir();
157
+ const recordingDir = gifRecordingDirForPort(normalizedPort);
158
+
159
+ for (let attempt = 0; attempt < 2; attempt += 1) {
160
+ try {
161
+ mkdirSync(recordingDir, { mode: 0o700 });
162
+ return recordingDir;
163
+ } catch (error) {
164
+ if (error?.code !== 'EEXIST') throw error;
165
+
166
+ const state = readGifRecordingState(normalizedPort);
167
+ if (state && processExists(state.pid) && !['completed', 'failed'].includes(state.status)) {
168
+ throw new Error(`A GIF recording is already active on port ${normalizedPort}: ${state.output}`);
169
+ }
170
+
171
+ let stale = Boolean(state);
172
+ try {
173
+ stale ||= Date.now() - statSync(recordingDir).mtimeMs > GIF_START_TIMEOUT_MS;
174
+ } catch {
175
+ stale = true;
176
+ }
177
+ if (!stale) throw new Error(`A GIF recording is already starting on port ${normalizedPort}`);
178
+ rmSync(recordingDir, { recursive: true, force: true });
179
+ }
180
+ }
181
+
182
+ throw new Error(`Could not claim GIF recording state for port ${normalizedPort}`);
183
+ }
184
+
185
+ export function removeGifRecordingState(port) {
186
+ rmSync(gifRecordingDirForPort(port), { recursive: true, force: true });
187
+ }
188
+
189
+ export function assertFfmpegAvailable() {
190
+ const result = spawnSync('ffmpeg', ['-version'], { encoding: 'utf-8', stdio: 'ignore' });
191
+ if (result.error?.code === 'ENOENT') {
192
+ throw new Error('GIF recording requires ffmpeg. Install it with: brew install ffmpeg');
193
+ }
194
+ if (result.error) throw new Error(`Could not run ffmpeg: ${result.error.message}`);
195
+ if (result.status !== 0) throw new Error(`ffmpeg is not usable: exit status ${result.status}`);
196
+ }
197
+
198
+ export function createFfmpegGifEncoder({
199
+ output,
200
+ fps = DEFAULT_GIF_FPS,
201
+ colors = DEFAULT_GIF_COLORS,
202
+ scale = DEFAULT_GIF_SCALE,
203
+ }) {
204
+ const filters = [];
205
+ if (scale !== 1) filters.push(`scale=iw*${scale}:-1:flags=lanczos`);
206
+ filters.push(`split[s0][s1];[s0]palettegen=stats_mode=diff:max_colors=${colors}[p];[s1][p]paletteuse=dither=bayer`);
207
+
208
+ const child = spawn('ffmpeg', [
209
+ '-loglevel', 'error',
210
+ '-f', 'image2pipe',
211
+ '-framerate', String(fps),
212
+ '-vcodec', 'png',
213
+ '-i', 'pipe:0',
214
+ '-an',
215
+ '-threads', '1',
216
+ '-vf', filters.join(','),
217
+ '-loop', '0',
218
+ '-f', 'gif',
219
+ '-y',
220
+ output,
221
+ ], { stdio: ['pipe', 'ignore', 'pipe'] });
222
+
223
+ let spawnError = null;
224
+ let stderr = '';
225
+ child.once('error', (error) => {
226
+ spawnError = error;
227
+ });
228
+ child.stderr.on('data', (chunk) => {
229
+ stderr += chunk.toString('utf-8');
230
+ });
231
+ const closed = new Promise((resolve) => {
232
+ child.once('close', (code, signal) => resolve({ code, signal }));
233
+ });
234
+
235
+ return {
236
+ async writeFrame(frame) {
237
+ if (spawnError) throw spawnError;
238
+ if (child.exitCode !== null) {
239
+ throw new Error(`ffmpeg exited before GIF recording finished${stderr.trim() ? `: ${stderr.trim()}` : ''}`);
240
+ }
241
+ await new Promise((resolveWrite, rejectWrite) => {
242
+ child.stdin.write(frame, (error) => error ? rejectWrite(error) : resolveWrite());
243
+ });
244
+ },
245
+ async stop() {
246
+ if (!child.stdin.destroyed) child.stdin.end();
247
+ const result = await closed;
248
+ if (spawnError) throw spawnError;
249
+ if (result.code !== 0) {
250
+ const termination = result.signal ? `signal ${result.signal}` : `exit status ${result.code}`;
251
+ throw new Error(`ffmpeg failed to encode GIF (${termination})${stderr.trim() ? `: ${stderr.trim()}` : ''}`);
252
+ }
253
+ chmodSync(output, 0o600);
254
+ },
255
+ };
256
+ }
257
+
258
+ export function assertGifRecordingOwner(state, ownerToken) {
259
+ if (!state?.ownerTokenHash) throw new Error('GIF recording has no owner information');
260
+ if (!ownerToken) {
261
+ throw new Error(`Missing browser owner token. Export ${OWNER_TOKEN_ENV} with the token printed by browser-tools start`);
262
+ }
263
+ if (ownerTokenHash(ownerToken) !== state.ownerTokenHash) {
264
+ throw new Error('GIF recording is owned by another Browser Tools agent');
265
+ }
266
+ }
267
+
268
+ export function requestGifRecordingStop(port, ownerToken) {
269
+ const normalizedPort = normalizePort(port);
270
+ const state = readGifRecordingState(normalizedPort);
271
+ if (!state) throw new Error(`No GIF recording found on port ${normalizedPort}`);
272
+ assertGifRecordingOwner(state, ownerToken);
273
+ writePrivateJson(gifRecordingStopFile(normalizedPort), { requestedAt: new Date().toISOString() });
274
+ return state;
275
+ }
276
+
277
+ export async function waitForGifRecordingState(port, predicate, { timeoutMs = GIF_START_TIMEOUT_MS, intervalMs = 100 } = {}) {
278
+ const deadline = Date.now() + timeoutMs;
279
+ let state = null;
280
+ while (Date.now() < deadline) {
281
+ state = readGifRecordingState(port);
282
+ if (state && predicate(state)) return state;
283
+ await sleep(intervalMs);
284
+ }
285
+ return state;
286
+ }
287
+
288
+ export async function recordGifSession({
289
+ page,
290
+ output,
291
+ fps = DEFAULT_GIF_FPS,
292
+ colors = DEFAULT_GIF_COLORS,
293
+ scale = DEFAULT_GIF_SCALE,
294
+ preRollMs = DEFAULT_GIF_PRE_ROLL_MS,
295
+ postRollMs = DEFAULT_GIF_POST_ROLL_MS,
296
+ maxDurationSeconds = DEFAULT_GIF_MAX_DURATION_SECONDS,
297
+ shouldStop = () => false,
298
+ onPhase = () => {},
299
+ sleepFn = sleep,
300
+ now = () => Date.now(),
301
+ encoderFactory = createFfmpegGifEncoder,
302
+ }) {
303
+ const encoder = encoderFactory({
304
+ output,
305
+ fps,
306
+ colors,
307
+ scale,
308
+ });
309
+ const frameIntervalMs = 1000 / fps;
310
+ let nextFrameAt = now();
311
+ let frameCount = 0;
312
+
313
+ const captureFrame = async () => {
314
+ const waitMs = Math.max(0, nextFrameAt - now());
315
+ if (waitMs > 0) await sleepFn(waitMs);
316
+ const frame = await page.screenshot({
317
+ type: 'png',
318
+ encoding: 'binary',
319
+ captureBeyondViewport: false,
320
+ optimizeForSpeed: true,
321
+ });
322
+ await encoder.writeFrame(frame);
323
+ frameCount += 1;
324
+ nextFrameAt += frameIntervalMs;
325
+ if (nextFrameAt < now()) nextFrameAt = now();
326
+ };
327
+
328
+ const capturePeriod = async (durationMs) => {
329
+ const periodStartedAt = now();
330
+ const requiredFrames = Math.max(1, Math.ceil(durationMs / frameIntervalMs));
331
+ for (let frame = 0; frame < requiredFrames; frame += 1) await captureFrame();
332
+ const remainingMs = periodStartedAt + durationMs - now();
333
+ if (remainingMs > 0) await sleepFn(remainingMs);
334
+ };
335
+
336
+ try {
337
+ await onPhase('pre-roll');
338
+ await capturePeriod(preRollMs);
339
+ await onPhase('recording');
340
+
341
+ const deadline = now() + maxDurationSeconds * 1000;
342
+ while (!shouldStop() && now() < deadline) {
343
+ await captureFrame();
344
+ }
345
+
346
+ const stopRequested = shouldStop();
347
+ const reason = stopRequested ? 'requested' : 'max-duration';
348
+ await onPhase('post-roll', reason);
349
+ await capturePeriod(postRollMs);
350
+ await encoder.stop();
351
+ return { reason, frameCount };
352
+ } catch (error) {
353
+ await encoder.stop().catch(() => {});
354
+ throw error;
355
+ }
356
+ }
357
+
358
+ export async function runGifRecordingWorker({
359
+ port,
360
+ output,
361
+ ownerToken,
362
+ fps = DEFAULT_GIF_FPS,
363
+ colors = DEFAULT_GIF_COLORS,
364
+ scale = DEFAULT_GIF_SCALE,
365
+ preRollMs = DEFAULT_GIF_PRE_ROLL_MS,
366
+ postRollMs = DEFAULT_GIF_POST_ROLL_MS,
367
+ maxDurationSeconds = DEFAULT_GIF_MAX_DURATION_SECONDS,
368
+ }) {
369
+ const normalizedPort = normalizePort(port);
370
+ const stateFile = gifRecordingStateFile(normalizedPort);
371
+ const startedAt = new Date().toISOString();
372
+ const baseState = {
373
+ managedBy: 'browser-tools-gif-recorder',
374
+ pid: process.pid,
375
+ port: normalizedPort,
376
+ output,
377
+ ownerTokenHash: ownerTokenHash(ownerToken),
378
+ status: 'starting',
379
+ phase: 'starting',
380
+ startedAt,
381
+ options: { fps, colors, scale, preRollMs, postRollMs, maxDurationSeconds },
382
+ };
383
+ writePrivateJson(stateFile, baseState);
384
+
385
+ let browser;
386
+ let currentState = baseState;
387
+ const updateState = (changes) => {
388
+ currentState = { ...currentState, ...changes };
389
+ writePrivateJson(stateFile, currentState);
390
+ };
391
+
392
+ try {
393
+ browser = await connectBrowser(normalizedPort, { ownerToken });
394
+ const page = await activePage(browser);
395
+ const result = await recordGifSession({
396
+ page,
397
+ output,
398
+ fps,
399
+ colors,
400
+ scale,
401
+ preRollMs,
402
+ postRollMs,
403
+ maxDurationSeconds,
404
+ shouldStop: () => existsSync(gifRecordingStopFile(normalizedPort)),
405
+ onPhase: (phase, reason = null) => updateState({
406
+ status: phase === 'recording' ? 'recording' : currentState.status,
407
+ phase,
408
+ readyAt: phase === 'recording' ? new Date().toISOString() : currentState.readyAt,
409
+ reason: reason ?? currentState.reason,
410
+ }),
411
+ });
412
+ updateState({
413
+ status: 'completed',
414
+ phase: 'completed',
415
+ reason: result.reason,
416
+ completedAt: new Date().toISOString(),
417
+ });
418
+ } catch (error) {
419
+ updateState({
420
+ status: 'failed',
421
+ phase: 'failed',
422
+ error: error.message,
423
+ completedAt: new Date().toISOString(),
424
+ });
425
+ throw error;
426
+ } finally {
427
+ browser?.disconnect();
428
+ }
429
+ }
430
+
431
+ export function prepareGifOutput(output, { overwrite = false } = {}) {
432
+ mkdirSync(dirname(output), { recursive: true });
433
+ if (existsSync(output) && !overwrite) {
434
+ throw new Error(`GIF output already exists: ${output}. Choose another meaningful name or pass --overwrite`);
435
+ }
436
+ closeSync(openPrivateFile(output, 'w'));
437
+ }
438
+
439
+ export function claimAndPrepareGifOutput(port, output, options = {}, {
440
+ claim = claimGifRecording,
441
+ prepare = prepareGifOutput,
442
+ release = removeGifRecordingState,
443
+ } = {}) {
444
+ claim(port);
445
+ try {
446
+ prepare(output, options);
447
+ } catch (error) {
448
+ release(port);
449
+ throw error;
450
+ }
451
+ }