@open-take/runtime 0.4.4 → 0.5.1

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.
@@ -279,12 +279,34 @@ async function fitViewport(cdp, targetId, vw, vh) {
279
279
  }
280
280
  return inner;
281
281
  }
282
+ function captureCadence(frames) {
283
+ const ordered = [...frames].sort((a, b) => a.offMs - b.offMs);
284
+ const intervals = ordered.slice(1).map((frame, i) => frame.offMs - ordered[i].offMs).sort((a, b) => a - b);
285
+ const rounded = (n) => Math.round(n * 1e3) / 1e3;
286
+ const sources = new Set(frames.map((frame) => frame.timestampSource ?? "arrival"));
287
+ return {
288
+ frameCount: frames.length,
289
+ timestampSource: sources.size > 1 ? "mixed" : sources.has("frame-swap") ? "frame-swap" : "arrival",
290
+ frameOffsetsMs: ordered.map((frame) => rounded(frame.offMs)),
291
+ arrivalOffsetsMs: ordered.map((frame) => rounded(frame.arrivalMs ?? frame.offMs)),
292
+ medianIntervalMs: rounded(intervals[Math.floor(intervals.length / 2)] ?? 0),
293
+ p95IntervalMs: rounded(intervals[Math.max(0, Math.ceil(intervals.length * .95) - 1)] ?? 0),
294
+ maxIntervalMs: rounded(intervals.at(-1) ?? 0),
295
+ maxArrivalDelayMs: rounded(frames.reduce((max, frame) => Math.max(max, (frame.arrivalMs ?? frame.offMs) - frame.offMs), 0)),
296
+ outOfOrderFrames: frames.filter((frame, i) => i > 0 && frame.offMs < frames[i - 1].offMs).length,
297
+ note: "Delivered-frame timing, not unique image content or a smoothness score. Static pages may send no frames; inspect image changes within active action windows. Encoded fps is separate."
298
+ };
299
+ }
282
300
  var Screencast = class {
283
301
  cdp;
284
302
  dir;
285
303
  t0 = 0;
286
304
  n = 0;
305
+ lastArrivalAt = 0;
287
306
  frames = [];
307
+ get idleForMs() {
308
+ return Date.now() - this.lastArrivalAt;
309
+ }
288
310
  constructor(cdp, dir) {
289
311
  this.cdp = cdp;
290
312
  this.dir = dir;
@@ -292,15 +314,22 @@ var Screencast = class {
292
314
  /** Begin capture. `t0` (Date.now) anchors every frame + event onto one clock. */
293
315
  async start(t0, opts) {
294
316
  this.t0 = t0;
317
+ this.lastArrivalAt = t0;
295
318
  this.cdp.on("Page.screencastFrame", (p) => {
296
- const off = Date.now() - this.t0;
319
+ const arrived = Date.now();
320
+ this.lastArrivalAt = arrived;
321
+ const swap = p.metadata?.timestamp;
322
+ const hasSwap = typeof swap === "number" && Number.isFinite(swap);
323
+ const off = Math.max(0, hasSwap ? swap * 1e3 - this.t0 : arrived - this.t0);
297
324
  const file = join(this.dir, `f-${String(this.n++).padStart(5, "0")}.jpg`);
325
+ this.cdp.send("Page.screencastFrameAck", { sessionId: p.sessionId }).catch(() => {});
298
326
  writeFileSync(file, Buffer.from(p.data, "base64"));
299
327
  this.frames.push({
300
328
  file,
301
- offMs: off
329
+ offMs: off,
330
+ arrivalMs: arrived - this.t0,
331
+ timestampSource: hasSwap ? "frame-swap" : "arrival"
302
332
  });
303
- this.cdp.send("Page.screencastFrameAck", { sessionId: p.sessionId }).catch(() => {});
304
333
  });
305
334
  await this.cdp.send("Page.startScreencast", {
306
335
  format: "jpeg",
@@ -314,22 +343,40 @@ var Screencast = class {
314
343
  await this.cdp.send("Page.stopScreencast").catch(() => {});
315
344
  }
316
345
  };
346
+ /** Refresh idle surfaces without interrupting pages already producing frames.
347
+ * Never queue another expensive screenshot behind a slow/in-flight request. */
348
+ async function pumpIdleRaster(cdp, screencast, active, paused) {
349
+ let pending = false;
350
+ while (active()) {
351
+ if (!paused() && !pending && screencast.idleForMs >= 200) {
352
+ pending = true;
353
+ cdp.send("Page.captureScreenshot", {
354
+ format: "jpeg",
355
+ quality: 1
356
+ }).catch(() => {}).finally(() => {
357
+ pending = false;
358
+ });
359
+ }
360
+ await sleep$3(45);
361
+ }
362
+ }
317
363
  async function encodeFrames(frames, endMs, outPath, fps, ffmpegBin) {
318
364
  if (frames.length === 0) throw new Error("open-take(hi-fps): no frames captured");
365
+ frames = [...frames].sort((a, b) => a.offMs - b.offMs);
319
366
  const bin = ffmpegBin ?? await resolveFfmpeg();
320
- const dir = frames[0].file.slice(0, frames[0].file.lastIndexOf("/"));
367
+ const dir = dirname(frames[0].file);
321
368
  const listPath = join(dir, "frames.concat");
322
369
  const lines = [];
323
370
  const bounds = [
324
371
  0,
325
372
  ...frames.slice(1).map((f) => f.offMs),
326
- Math.max(endMs, frames[frames.length - 1].offMs + 33)
373
+ Math.max(endMs, frames[frames.length - 1].offMs + 1e3 / fps)
327
374
  ];
328
375
  for (let i = 0; i < frames.length; i++) {
329
376
  const dur = Math.max(.001, (bounds[i + 1] - bounds[i]) / 1e3);
330
- lines.push(`file '${frames[i].file}'`, `duration ${dur.toFixed(4)}`);
377
+ lines.push(`file '${frames[i].file}'`, "option framerate 1000", `duration ${dur.toFixed(6)}`);
331
378
  }
332
- lines.push(`file '${frames[frames.length - 1].file}'`);
379
+ lines.push(`file '${frames[frames.length - 1].file}'`, "option framerate 1000");
333
380
  writeFileSync(listPath, lines.join("\n"));
334
381
  const isWebm = /\.webm$/i.test(outPath);
335
382
  const codec = isWebm ? [
@@ -388,6 +435,17 @@ async function encodeFrames(frames, endMs, outPath, fps, ffmpegBin) {
388
435
  }
389
436
  /** A throwaway temp dir for the screencast's per-frame JPEGs. */
390
437
  const makeFrameDir = () => mkdtempSync(join(tmpdir(), "open-take-frames-"));
438
+ /** Poll `ready` every few milliseconds until it is true or `timeoutMs` has passed.
439
+ * Resolves true when the condition was met, false on timeout. Used to pace work
440
+ * by something the page did (a painted frame) instead of by a blind timer. */
441
+ async function waitUntil(ready, timeoutMs, stepMs = 4) {
442
+ const deadline = Date.now() + timeoutMs;
443
+ while (!ready()) {
444
+ if (Date.now() >= deadline) return false;
445
+ await new Promise((r) => setTimeout(r, stepMs));
446
+ }
447
+ return true;
448
+ }
391
449
 
392
450
  //#endregion
393
451
  //#region src/capture.ts
@@ -560,7 +618,7 @@ async function ffprobe(path) {
560
618
  }
561
619
  /** Drive `plan` against the live app over CDP, return the ground-truth log. */
562
620
  async function captureTake(plan, opts) {
563
- const { captureTakeCDP: captureTakeCDP$1 } = await import("./cdp-capture-BPfyq-2O.js");
621
+ const { captureTakeCDP: captureTakeCDP$1 } = await import("./cdp-capture-Bm6EPvkE.js");
564
622
  return captureTakeCDP$1(plan, {
565
623
  ...opts,
566
624
  fps: opts.fps ?? 60
@@ -1441,15 +1499,7 @@ async function captureTakeCDP(plan, opts) {
1441
1499
  });
1442
1500
  let pumping = true;
1443
1501
  let pumpPaused = false;
1444
- const pump = (async () => {
1445
- while (pumping) {
1446
- if (!pumpPaused) await Promise.race([cdp.send("Page.captureScreenshot", {
1447
- format: "jpeg",
1448
- quality: 1
1449
- }).catch(() => {}), sleep(150)]);
1450
- await sleep(45);
1451
- }
1452
- })();
1502
+ const pump = opts.rasterRefresh === "off" ? Promise.resolve() : pumpIdleRaster(cdp, screencast, () => pumping, () => pumpPaused);
1453
1503
  await sleep(opts.warmupMs ?? 900);
1454
1504
  const resolvePoint = async (spec) => {
1455
1505
  if (spec.point) return {
@@ -1597,10 +1647,16 @@ async function captureTakeCDP(plan, opts) {
1597
1647
  const chars = [...step.value];
1598
1648
  const cjk = chars.filter((c) => /[\u2E80-\u9FFF\uAC00-\uD7AF\uF900-\uFAFF\uFF66-\uFF9F]/.test(c)).length;
1599
1649
  const auto = Math.min(90, Math.max(28, Math.round(1100 / Math.max(1, chars.length)))) * (cjk * 2 > chars.length ? 1.4 : 1);
1600
- const perChar = Math.round(step.perCharMs ?? auto);
1601
- for (const ch of chars) {
1602
- await cdp.send("Input.insertText", { text: ch });
1603
- await sleep(perChar);
1650
+ if (step.perCharMs === 0) await cdp.send("Input.insertText", { text: step.value });
1651
+ else {
1652
+ const perChar = Math.round(step.perCharMs ?? auto);
1653
+ for (const ch of chars) {
1654
+ const painted = screencast.frames.length, sentAt = Date.now();
1655
+ await cdp.send("Input.insertText", { text: ch });
1656
+ await waitUntil(() => screencast.frames.length > painted, Math.max(perChar, 250));
1657
+ const rest = perChar - (Date.now() - sentAt);
1658
+ if (rest > 0) await sleep(rest);
1659
+ }
1604
1660
  }
1605
1661
  events.push({
1606
1662
  kind: "type",
@@ -2014,6 +2070,10 @@ async function captureTakeCDP(plan, opts) {
2014
2070
  },
2015
2071
  events,
2016
2072
  tEndMs,
2073
+ captureCadence: {
2074
+ ...captureCadence(screencast.frames),
2075
+ rasterRefresh: opts.rasterRefresh ?? "idle"
2076
+ },
2017
2077
  ...skipped.length ? { skipped } : {},
2018
2078
  ...precheck.length ? { precheck } : {},
2019
2079
  ...settleWaits.length ? { settleWaits } : {},
@@ -2075,4 +2135,4 @@ async function navigate(cdp, url) {
2075
2135
 
2076
2136
  //#endregion
2077
2137
  export { PrecheckRefusal, captureTake, captureTakeCDP, ensureChrome, inspectPage, planTargets, precheckPlan, resolveChrome, resolveNavigateUrl };
2078
- //# sourceMappingURL=cdp-capture-Ckt-tZVU.js.map
2138
+ //# sourceMappingURL=cdp-capture-Bl990GzE.js.map