cdp-toolkit 3.1.0 → 3.2.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.
@@ -12,7 +12,7 @@
12
12
  * on a fixed interval until the text appears or the timeout elapses.
13
13
  */
14
14
  import { CdpError, withPage } from "../client.ts";
15
- import type { CdpConnection } from "../client.ts";
15
+ import type { PageConnection } from "../client.ts";
16
16
  import type { Target, TargetSelector } from "../types.ts";
17
17
 
18
18
  export interface NavigatePageArgs {
@@ -65,7 +65,7 @@ export async function navigatePage(args: NavigatePageArgs): Promise<NavigatePage
65
65
 
66
66
  return withPage(
67
67
  args.target,
68
- async (conn: CdpConnection): Promise<NavigatePageResult> => {
68
+ async (conn: PageConnection): Promise<NavigatePageResult> => {
69
69
  await conn.send("Page.enable");
70
70
 
71
71
  // Subscribe to the load milestone BEFORE acting so a fast page that loads
@@ -156,7 +156,7 @@ export async function waitForText(args: WaitForArgs): Promise<WaitForResult> {
156
156
 
157
157
  return withPage(
158
158
  args.target,
159
- async (conn: CdpConnection, _target: Target): Promise<WaitForResult> => {
159
+ async (conn: PageConnection, _target: Target): Promise<WaitForResult> => {
160
160
  await conn.send("Runtime.enable");
161
161
  const expr = `(() => { const b = document.body; return !!b && typeof b.innerText === 'string' && b.innerText.includes(${JSON.stringify(args.text)}); })()`;
162
162
 
@@ -11,7 +11,7 @@
11
11
  * CDP connection per target; integration-tested in test/mock-smoke.ts.
12
12
  */
13
13
  import { CdpError, openPage, resolveTarget } from "../client.ts";
14
- import type { CdpConnection } from "../client.ts";
14
+ import type { PageConnection } from "../client.ts";
15
15
  import type { Target, TargetSelector } from "../types.ts";
16
16
 
17
17
  /* ============================================================================
@@ -143,7 +143,7 @@ interface MockRule {
143
143
  }
144
144
 
145
145
  interface MockSession {
146
- conn: CdpConnection;
146
+ conn: PageConnection;
147
147
  target: Target;
148
148
  rules: MockRule[];
149
149
  intercepted: Array<{ url: string; method: string; action: MockAction }>;
@@ -35,7 +35,7 @@
35
35
  * path and the recommended entry point.
36
36
  */
37
37
  import type { Target, TargetSelector } from "../types.ts";
38
- import type { CdpConnection } from "../client.ts";
38
+ import type { PageConnection } from "../client.ts";
39
39
  import { CdpError, openPage } from "../client.ts";
40
40
  import { mkdir, readFile, writeFile, stat, unlink } from "node:fs/promises";
41
41
  import { join } from "node:path";
@@ -75,7 +75,7 @@ interface TraceEvent {
75
75
 
76
76
  /** A traced-page registry entry held in-process between start and stop. */
77
77
  interface LiveTrace {
78
- conn: CdpConnection;
78
+ conn: PageConnection;
79
79
  target: Target;
80
80
  events: TraceEvent[];
81
81
  startedAt: number;
@@ -108,7 +108,7 @@ function stateFilePath(): string {
108
108
  }
109
109
 
110
110
  /** Subscribe to Tracing.dataCollected and buffer every event into `sink`. */
111
- function bufferTraceData(conn: CdpConnection, sink: TraceEvent[]): () => void {
111
+ function bufferTraceData(conn: PageConnection, sink: TraceEvent[]): () => void {
112
112
  return conn.on("Tracing.dataCollected", (params: Record<string, unknown>) => {
113
113
  const value = (params as { value?: TraceEvent[] }).value;
114
114
  if (Array.isArray(value)) sink.push(...value);
@@ -116,7 +116,7 @@ function bufferTraceData(conn: CdpConnection, sink: TraceEvent[]): () => void {
116
116
  }
117
117
 
118
118
  /** Begin a trace on an already-open page connection. */
119
- async function beginTrace(conn: CdpConnection, categories: string[]): Promise<void> {
119
+ async function beginTrace(conn: PageConnection, categories: string[]): Promise<void> {
120
120
  await conn.send("Tracing.start", {
121
121
  traceConfig: { includedCategories: categories },
122
122
  transferMode: "ReportEvents",
@@ -127,7 +127,7 @@ async function beginTrace(conn: CdpConnection, categories: string[]): Promise<vo
127
127
  * End a trace, drain all buffered Tracing.dataCollected, and resolve once
128
128
  * Tracing.tracingComplete fires (or the timeout elapses). Returns the events.
129
129
  */
130
- async function endTrace(conn: CdpConnection, sink: TraceEvent[], timeoutMs = 30_000): Promise<TraceEvent[]> {
130
+ async function endTrace(conn: PageConnection, sink: TraceEvent[], timeoutMs = 30_000): Promise<TraceEvent[]> {
131
131
  const complete = conn.waitFor("Tracing.tracingComplete", undefined, timeoutMs);
132
132
  await conn.send("Tracing.end");
133
133
  await complete;
@@ -66,7 +66,7 @@
66
66
  */
67
67
  import { mkdir, appendFile, writeFile, copyFile } from "node:fs/promises";
68
68
  import { CdpError, listTargets, openPage, resolveTarget } from "../client.ts";
69
- import type { CdpConnection } from "../client.ts";
69
+ import type { PageConnection } from "../client.ts";
70
70
  import { resolveWorkerSelector } from "../cdp/workers.ts";
71
71
  import type { Target, TargetSelector } from "../types.ts";
72
72
  import {
@@ -189,7 +189,7 @@ export interface RecorderHandle {
189
189
  /** The resolved target this recorder is attached to. */
190
190
  target: Target;
191
191
  /** The live connection (exposed so a one-shot caller can drive Page.reload on it). */
192
- conn: CdpConnection;
192
+ conn: PageConnection;
193
193
  /** Count of buffer-write failures observed (0 on a healthy capture). */
194
194
  droppedWrites(): number;
195
195
  }
@@ -286,7 +286,7 @@ export interface CaptureWindow {
286
286
  /** The unique per-capture buffer file (read this for isolated results). */
287
287
  file: string;
288
288
  /** Live connection (open until stop), for Network.getResponseBody etc. */
289
- conn: CdpConnection;
289
+ conn: PageConnection;
290
290
  /** Resolved target identity. */
291
291
  resolved: { id: string; url: string; title: string };
292
292
  /** How the window was driven: "reload" for a page, "listen" for a worker. */
@@ -54,7 +54,7 @@ import { spawn } from "node:child_process";
54
54
  import { mkdir, rm, stat, writeFile } from "node:fs/promises";
55
55
  import { join } from "node:path";
56
56
  import { CdpError, openPage } from "../client.ts";
57
- import type { CdpConnection } from "../client.ts";
57
+ import type { PageConnection } from "../client.ts";
58
58
  import type { Target, TargetSelector } from "../types.ts";
59
59
 
60
60
  const ARTIFACT_DIR = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
@@ -235,6 +235,8 @@ export interface EncoderChoice {
235
235
  codec: "hevc" | "h264";
236
236
  /** -tag:v value, set on HEVC so QuickTime will play the result. */
237
237
  tag?: "hvc1";
238
+ /** Use `-fps_mode vfr` (ffmpeg >=5.1) instead of `-vsync vfr`; set by the probe. */
239
+ fpsMode?: boolean;
238
240
  }
239
241
 
240
242
  /** Preference order: hardware HEVC, hardware H.264, software HEVC, software H.264. */
@@ -278,8 +280,38 @@ export function selectEncoder(encodersOutput: string): EncoderChoice {
278
280
  }
279
281
 
280
282
  /**
281
- * The exact ffmpeg argv. `-vsync vfr` (not `-fps_mode`, which needs ffmpeg
282
- * >=5.1 and would break Ubuntu 22.04's 4.4) passes the concat demuxer's
283
+ * Whether this ffmpeg takes `-fps_mode` (added in 5.1). `-vsync` was deprecated
284
+ * then and later removed, so a new ffmpeg fails with "Unrecognized option 'vsync'",
285
+ * while 4.4 (Ubuntu 22.04) only knows `-vsync`. Parses `ffmpeg -version`;
286
+ * a git snapshot ("ffmpeg version N-1234-g...") is treated as new. Returns
287
+ * `undefined` when the banner has no version it can read, so the caller can
288
+ * look further instead of guessing.
289
+ */
290
+ export function supportsFpsMode(versionOutput: string): boolean | undefined {
291
+ const m = /ffmpeg version n?(\d+)\.(\d+)/.exec(versionOutput);
292
+ if (!m) return /ffmpeg version N-/.test(versionOutput) ? true : undefined;
293
+ const major = Number(m[1]);
294
+ const minor = Number(m[2]);
295
+ return major > 5 || (major === 5 && minor >= 1);
296
+ }
297
+
298
+ /**
299
+ * Pick `-fps_mode` vs `-vsync` from what the probe could read. The version
300
+ * banner decides when it parses; otherwise the option list from `-h full`
301
+ * decides (it names `-fps_mode` only on ffmpeg that has it). When neither could
302
+ * be read, choose `-fps_mode`: it is the current option, while `-vsync` is gone
303
+ * from new ffmpeg, so an unreadable probe must not silently pick the removed one.
304
+ */
305
+ export function chooseFpsMode(versionOutput: string | undefined, helpOutput: string | undefined): boolean {
306
+ const byVersion = versionOutput === undefined ? undefined : supportsFpsMode(versionOutput);
307
+ if (byVersion !== undefined) return byVersion;
308
+ if (helpOutput !== undefined && /-vsync\b|-fps_mode\b/.test(helpOutput)) return /-fps_mode\b/.test(helpOutput);
309
+ return true;
310
+ }
311
+
312
+ /**
313
+ * The exact ffmpeg argv. `-fps_mode vfr` (or `-vsync vfr` on ffmpeg <5.1, see
314
+ * supportsFpsMode) passes the concat demuxer's
283
315
  * per-frame timestamps through instead of resampling them to a constant rate.
284
316
  * `-t` is deliberately NOT used to pin the duration: it trims at the LAST
285
317
  * frame's PTS, which throws away exactly the long final hold the ledger exists
@@ -293,7 +325,7 @@ export function buildFfmpegArgs(manifestPath: string, outPath: string, choice: E
293
325
  "-f", "concat",
294
326
  "-safe", "0",
295
327
  "-i", manifestPath,
296
- "-vsync", "vfr",
328
+ ...(choice.fpsMode ? ["-fps_mode", "vfr"] : ["-vsync", "vfr"]),
297
329
  "-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2",
298
330
  "-c:v", choice.encoder,
299
331
  ...(choice.tag ? ["-tag:v", choice.tag] : []),
@@ -352,7 +384,15 @@ async function probeEncoder(): Promise<EncoderChoice> {
352
384
  throw new CdpError(`${FFMPEG_MISSING} (${(err as Error).message})`);
353
385
  }
354
386
  if (res.code !== 0) throw new CdpError(`${FFMPEG_MISSING} ('-encoders' exited ${res.code}: ${res.stderr.trim().slice(0, 300)})`);
355
- return selectEncoder(`${res.stdout}\n${res.stderr}`);
387
+ const choice = selectEncoder(`${res.stdout}\n${res.stderr}`);
388
+ const output = async (args: string[]): Promise<string | undefined> => {
389
+ const r = await run(FFMPEG_BIN, args).catch(() => undefined);
390
+ return r && r.code === 0 ? `${r.stdout}\n${r.stderr}` : undefined;
391
+ };
392
+ const version = await output(["-version"]);
393
+ const byVersion = version === undefined ? undefined : supportsFpsMode(version);
394
+ const help = byVersion === undefined ? await output(["-hide_banner", "-h", "full"]) : undefined;
395
+ return { ...choice, fpsMode: chooseFpsMode(version, help) };
356
396
  })();
357
397
  // A failed probe must not poison every later call: forget it so a caller who
358
398
  // installs ffmpeg and retries is not told it is still missing.
@@ -367,7 +407,7 @@ async function probeEncoder(): Promise<EncoderChoice> {
367
407
 
368
408
  /** A live screencast held in-process between start and stop, keyed by targetId. */
369
409
  interface LiveRecording {
370
- conn: CdpConnection;
410
+ conn: PageConnection;
371
411
  target: Target;
372
412
  spoolDir: string;
373
413
  ledger: FrameLedgerEntry[];
@@ -8,7 +8,7 @@
8
8
  * `DOM.resolveNode({ backendNodeId: uid })`. There is no server-side ref
9
9
  * table to drift or expire.
10
10
  */
11
- import type { CdpConnection } from "../client.ts";
11
+ import type { PageConnection } from "../client.ts";
12
12
  import { withPage } from "../client.ts";
13
13
  import type { Target, TargetSelector, Uid } from "../types.ts";
14
14
 
@@ -175,7 +175,7 @@ export async function takeSnapshot(args: TakeSnapshotArgs = {}): Promise<TakeSna
175
175
  * Resolve a Uid (backendDOMNodeId) to a live JS object handle. Shared by every
176
176
  * interaction tool in input.ts. Throws if the node no longer exists.
177
177
  */
178
- export async function resolveUid(conn: CdpConnection, uid: Uid): Promise<{ objectId: string }> {
178
+ export async function resolveUid(conn: PageConnection, uid: Uid): Promise<{ objectId: string }> {
179
179
  const { object } = await conn.send<{ object: { objectId?: string } }>("DOM.resolveNode", {
180
180
  backendNodeId: uid,
181
181
  });
package/src/version.ts CHANGED
@@ -6,4 +6,4 @@
6
6
  * ready line; keeping it in its own module means a release bump touches one
7
7
  * line here plus package.json, not a const buried in the server.
8
8
  */
9
- export const VERSION = "3.1.0";
9
+ export const VERSION = "3.2.0";