@phil65/demoreel 0.1.0 → 0.3.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.
package/dist/record.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { compose } from "./compose.js";
5
- import { checkFfmpeg, launchChromium } from "./env.js";
5
+ import { checkFfmpeg, DemoreelError, launchChromium } from "./env.js";
6
6
  import { ScreencastRecorder } from "./recorder.js";
7
7
  import { Scene } from "./scene.js";
8
8
  import { serveStatic } from "./server.js";
@@ -10,20 +10,30 @@ import { serveStatic } from "./server.js";
10
10
  export function defineScenario(s) {
11
11
  return s;
12
12
  }
13
- export async function recordScenario(input, opts = {}) {
14
- const scenario = { ...input, ...opts.overrides };
13
+ /** Resolves a Playwright storageState file path and throws a clear DemoreelError if missing. */
14
+ export function resolveStorageState(statePath, baseDir = process.cwd()) {
15
+ if (!statePath)
16
+ return undefined;
17
+ const resolved = path.resolve(baseDir, statePath);
18
+ if (!fs.existsSync(resolved)) {
19
+ throw new DemoreelError(`storageState file not found: ${resolved}`, `demoreel login <url> --state ${statePath}`);
20
+ }
21
+ return resolved;
22
+ }
23
+ function mergeScenario(input, overrides) {
24
+ const scenario = { ...input, ...overrides };
15
25
  if (!scenario.name || typeof scenario.run !== "function") {
16
26
  throw new Error("a scenario needs a `name` and an async `run(scene, ctx)` (use defineScenario)");
17
27
  }
18
- checkFfmpeg();
19
- const outDir = path.resolve(opts.outDir ?? path.join("out", scenario.name));
20
- const timings = {};
21
- const t0 = Date.now();
22
- fs.mkdirSync(outDir, { recursive: true });
23
- const viewport = scenario.viewport ?? { width: 1920, height: 1080 };
24
- const framesDir = path.join(outDir, ".frames");
25
- fs.rmSync(framesDir, { recursive: true, force: true });
28
+ return scenario;
29
+ }
30
+ /** Shared Chromium context + static server setup for both recording and dry runs. */
31
+ async function openScenarioSession(input, opts) {
32
+ const scenario = mergeScenario(input, opts.overrides);
26
33
  const baseDir = opts.scenarioFile ? path.dirname(path.resolve(opts.scenarioFile)) : process.cwd();
34
+ const storageState = opts.storageState
35
+ ? resolveStorageState(opts.storageState, process.cwd())
36
+ : resolveStorageState(scenario.storageState, baseDir);
27
37
  let server = null;
28
38
  if (scenario.serve) {
29
39
  const dir = path.resolve(baseDir, scenario.serve);
@@ -31,11 +41,16 @@ export async function recordScenario(input, opts = {}) {
31
41
  throw new Error(`scenario.serve: ${dir} does not exist`);
32
42
  server = await serveStatic(dir);
33
43
  }
34
- const browser = await launchChromium({ headless: !opts.headed });
35
- let recorder = null;
36
- let scene = null;
44
+ const viewport = scenario.viewport ?? { width: 1920, height: 1080 };
45
+ let browser = null;
37
46
  try {
38
- const context = await browser.newContext({ viewport, deviceScaleFactor: 1, colorScheme: scenario.colorScheme ?? "light" });
47
+ browser = await launchChromium({ headless: !opts.headed });
48
+ const context = await browser.newContext({
49
+ viewport,
50
+ deviceScaleFactor: 1,
51
+ colorScheme: scenario.colorScheme ?? "light",
52
+ ...(storageState ? { storageState } : {}),
53
+ });
39
54
  if (scenario.cssZoom && scenario.cssZoom !== 1) {
40
55
  await context.addInitScript((z) => {
41
56
  const apply = () => document.documentElement?.style.setProperty("zoom", String(z), "important");
@@ -45,32 +60,57 @@ export async function recordScenario(input, opts = {}) {
45
60
  }, scenario.cssZoom);
46
61
  }
47
62
  const page = await context.newPage();
48
- scene = new Scene(page, viewport, async () => {
49
- recorder = new ScreencastRecorder(page, framesDir, { maxWidth: viewport.width, maxHeight: viewport.height });
63
+ const close = async () => {
64
+ await browser?.close().catch(() => { });
65
+ await server?.close();
66
+ };
67
+ return { scenario, viewport, browser, context, page, baseUrl: server?.url ?? "", close };
68
+ }
69
+ catch (e) {
70
+ await browser?.close().catch(() => { });
71
+ await server?.close();
72
+ throw e;
73
+ }
74
+ }
75
+ export async function recordScenario(input, opts = {}) {
76
+ const scenario = mergeScenario(input, opts.overrides);
77
+ checkFfmpeg();
78
+ const outDir = path.resolve(opts.outDir ?? path.join("out", scenario.name));
79
+ const timings = {};
80
+ const t0 = Date.now();
81
+ const session = await openScenarioSession(input, opts);
82
+ const framesDir = path.join(outDir, ".frames");
83
+ fs.mkdirSync(outDir, { recursive: true });
84
+ fs.rmSync(framesDir, { recursive: true, force: true });
85
+ let recorder = null;
86
+ let scene = null;
87
+ try {
88
+ scene = new Scene(session.page, session.viewport, async () => {
89
+ recorder = new ScreencastRecorder(session.page, framesDir, {
90
+ maxWidth: session.viewport.width,
91
+ maxHeight: session.viewport.height,
92
+ });
50
93
  await recorder.start();
51
94
  return recorder;
52
- }, { seed: scenario.seed, pacing: scenario.pacing });
95
+ }, { seed: session.scenario.seed, pacing: session.scenario.pacing });
53
96
  const tRun = Date.now();
54
- await scenario.run(scene, { baseUrl: server?.url ?? "" });
97
+ await session.scenario.run(scene, { baseUrl: session.baseUrl });
55
98
  // Hold the last frame so the final zoom-out and captions finish.
56
99
  const lastCaptionEnd = Math.max(0, ...scene.captions.map((c) => c.endMs));
57
100
  await scene.pause(Math.max(900, lastCaptionEnd - scene.now() + 300));
58
101
  timings.scenarioMs = Date.now() - tRun;
59
102
  }
60
103
  catch (e) {
61
- await browser.close().catch(() => { });
62
- await server?.close();
104
+ await session.close();
63
105
  throw e;
64
106
  }
65
107
  const rec = recorder;
66
108
  if (!rec || !scene) {
67
- await browser.close().catch(() => { });
68
- await server?.close();
109
+ await session.close();
69
110
  throw new Error("scenario never started recording (call scene.goto first)");
70
111
  }
71
112
  const { durationMs, frameCount } = await rec.stop();
72
- await browser.close();
73
- await server?.close();
113
+ await session.close();
74
114
  const videoPath = path.join(outDir, "recording.mp4");
75
115
  const tEnc = Date.now();
76
116
  await rec.encode(videoPath, 30);
@@ -79,27 +119,27 @@ export async function recordScenario(input, opts = {}) {
79
119
  fs.rmSync(framesDir, { recursive: true, force: true });
80
120
  timings.recordTotalMs = Date.now() - t0;
81
121
  const composed = compose({
82
- name: scenario.name,
122
+ name: session.scenario.name,
83
123
  outDir,
84
124
  videoPath,
85
125
  durationMs,
86
126
  frameCount,
87
- viewport,
127
+ viewport: session.viewport,
88
128
  frameSize: rec.frameSize,
89
129
  actions: scene.actions,
90
130
  captions: scene.captions,
91
131
  samples: scene.samples,
92
132
  frameTimes,
93
133
  timings,
94
- zoom: scenario.zoom,
95
- look: scenario.look,
96
- trimIdle: scenario.trimIdle,
134
+ zoom: session.scenario.zoom,
135
+ look: session.scenario.look,
136
+ trimIdle: session.scenario.trimIdle,
97
137
  });
98
138
  const result = {
99
139
  videoPath,
100
140
  durationMs,
101
141
  frameSize: rec.frameSize,
102
- viewport,
142
+ viewport: session.viewport,
103
143
  samples: scene.samples,
104
144
  actions: scene.actions,
105
145
  captions: scene.captions,
@@ -109,3 +149,41 @@ export async function recordScenario(input, opts = {}) {
109
149
  };
110
150
  return { ...composed, result, outDir, zoomRegions: composed.timeline.zoomRegions };
111
151
  }
152
+ /**
153
+ * Runs a scenario quickly in fast mode (no ffmpeg, no CDP screencast, no output files).
154
+ * Invokes `atEnd(page)` on both success and failure before closing the browser and static server.
155
+ */
156
+ export async function dryRunScenario(input, opts = {}) {
157
+ const t0 = performance.now();
158
+ const session = await openScenarioSession(input, opts);
159
+ try {
160
+ const startClock = async () => {
161
+ const origin = performance.now();
162
+ return { now: () => performance.now() - origin };
163
+ };
164
+ const scene = new Scene(session.page, session.viewport, startClock, {
165
+ seed: session.scenario.seed,
166
+ pacing: session.scenario.pacing,
167
+ fast: true,
168
+ });
169
+ try {
170
+ await session.scenario.run(scene, { baseUrl: session.baseUrl });
171
+ const durationMs = Math.round(performance.now() - t0);
172
+ await opts.atEnd?.(session.page);
173
+ return { ok: true, actions: scene.actions, durationMs };
174
+ }
175
+ catch (e) {
176
+ const durationMs = Math.round(performance.now() - t0);
177
+ const error = {
178
+ message: e instanceof Error ? e.message : String(e),
179
+ actionIndex: scene.actions.length,
180
+ };
181
+ await opts.onFailure?.(error, session.page);
182
+ await opts.atEnd?.(session.page);
183
+ return { ok: false, actions: scene.actions, durationMs, error };
184
+ }
185
+ }
186
+ finally {
187
+ await session.close();
188
+ }
189
+ }
@@ -7,6 +7,7 @@ export interface ScreencastOptions {
7
7
  export declare class ScreencastRecorder {
8
8
  private session;
9
9
  private frames;
10
+ private lastFrameData;
10
11
  private pending;
11
12
  private stopTs;
12
13
  private firstFrame;
package/dist/recorder.js CHANGED
@@ -13,6 +13,7 @@ import { ffmpegBin } from "./env.js";
13
13
  export class ScreencastRecorder {
14
14
  session = null;
15
15
  frames = [];
16
+ lastFrameData = null;
16
17
  pending = [];
17
18
  stopTs = 0;
18
19
  firstFrame;
@@ -39,6 +40,13 @@ export class ScreencastRecorder {
39
40
  this.session = session;
40
41
  session.on("Page.screencastFrame", (ev) => {
41
42
  const index = this.frames.length;
43
+ // Skip byte-identical repaints (e.g. idle WebGL/Three.js requestAnimationFrame loops)
44
+ // so encode() holds the previous frame and frameTimes reflects real visual changes.
45
+ if (index > 0 && ev.data === this.lastFrameData) {
46
+ session.send("Page.screencastFrameAck", { sessionId: ev.sessionId }).catch(() => { });
47
+ return;
48
+ }
49
+ this.lastFrameData = ev.data;
42
50
  const file = path.join(this.dir, `f${String(index).padStart(6, "0")}.jpg`);
43
51
  const ts = (ev.metadata.timestamp ?? Date.now() / 1000) * 1000;
44
52
  this.frames.push({ file, ts });
package/dist/scene.d.ts CHANGED
@@ -5,10 +5,45 @@
5
5
  */
6
6
  import type { Locator, Page } from "playwright";
7
7
  import { type Point } from "./motion.ts";
8
- import type { ScreencastRecorder } from "./recorder.ts";
9
8
  import type { ActionRecord, Caption, CursorSample, Depth, Viewport, ZoomHint } from "./types.ts";
10
- /** A CSS/Playwright selector string or a Playwright Locator. */
11
- export type Target = string | Locator;
9
+ /** Minimal recording clock (satisfied by ScreencastRecorder and dry-run clocks). */
10
+ export interface SceneClock {
11
+ now(): number;
12
+ }
13
+ /** Accessibility-first target spec mapped to Playwright's `getBy*` / `locator` methods. */
14
+ export type TargetSpec = {
15
+ role: Parameters<Page["getByRole"]>[0];
16
+ name?: string | RegExp;
17
+ exact?: boolean;
18
+ nth?: number;
19
+ } | {
20
+ label: string | RegExp;
21
+ exact?: boolean;
22
+ nth?: number;
23
+ } | {
24
+ placeholder: string | RegExp;
25
+ exact?: boolean;
26
+ nth?: number;
27
+ } | {
28
+ text: string | RegExp;
29
+ exact?: boolean;
30
+ nth?: number;
31
+ } | {
32
+ testId: string | RegExp;
33
+ nth?: number;
34
+ } | {
35
+ css: string;
36
+ nth?: number;
37
+ };
38
+ /** A CSS/Playwright selector string, a Playwright Locator, or a structured TargetSpec. */
39
+ export type Target = string | Locator | TargetSpec;
40
+ /**
41
+ * Resolves a Target to a Playwright Locator filtered to visible matches.
42
+ * Uses `.nth(nth)` when `nth` is specified on a TargetSpec, otherwise `.first()`.
43
+ */
44
+ export declare function resolveTarget(page: Page, target: Target): Locator;
45
+ /** Readable default label for a Target, used in timeline.json, marks.json and error messages. */
46
+ export declare function describeTarget(target: Target): string;
12
47
  /** Attribute that marks a zoom anchor: actions inside it zoom onto the anchor's box. */
13
48
  export declare const ZOOM_ATTRIBUTE = "data-demoreel-zoom";
14
49
  export interface PacingOptions {
@@ -29,7 +64,7 @@ export declare const DEFAULT_PACING: PacingOptions;
29
64
  export interface ActionOptions {
30
65
  /** Zoom onto the target (click/type default true, hover default false). */
31
66
  zoom?: boolean | ZoomHint;
32
- /** Shown in timeline.json / marks.json (default: the selector). */
67
+ /** Shown in timeline.json / marks.json (default: derived from the target). */
33
68
  label?: string;
34
69
  /** Wait for a navigation started by this click. */
35
70
  navigates?: boolean;
@@ -72,13 +107,15 @@ export declare class Scene {
72
107
  private rand;
73
108
  private recorder;
74
109
  private startRecording;
110
+ private fast;
75
111
  pacing: PacingOptions;
76
112
  /** The underlying Playwright page, for anything the Scene API does not cover. */
77
113
  readonly page: Page;
78
114
  readonly viewport: Viewport;
79
- constructor(page: Page, viewport: Viewport, startRecording: () => Promise<ScreencastRecorder>, opts?: {
115
+ constructor(page: Page, viewport: Viewport, startRecording: () => Promise<SceneClock>, opts?: {
80
116
  seed?: number;
81
117
  pacing?: Partial<PacingOptions>;
118
+ fast?: boolean;
82
119
  });
83
120
  private ensureRecording;
84
121
  /** Current time on the recording clock (ms since the first frame; 0 before recording). */
@@ -100,6 +137,25 @@ export declare class Scene {
100
137
  waitUntil?: "load" | "domcontentloaded" | "networkidle";
101
138
  }): Promise<void>;
102
139
  click(target: Target, opts?: ActionOptions): Promise<void>;
140
+ /**
141
+ * Moves to a `<select>` element and picks an option via Playwright's `selectOption`.
142
+ */
143
+ select(target: Target, value: string | {
144
+ value?: string;
145
+ label?: string;
146
+ index?: number;
147
+ }, opts?: ActionOptions): Promise<void>;
148
+ /**
149
+ * Drags from a target or viewport point to another target, point, or relative offset `{ dx, dy }`.
150
+ * Records continuous cursor telemetry so OpenScreen renders the cursor tracking the drag
151
+ * (useful for 3D canvases, sliders, and drag-and-drop).
152
+ */
153
+ drag(from: Target | Point, to: Target | Point | {
154
+ dx: number;
155
+ dy: number;
156
+ }, opts?: ActionOptions & {
157
+ duration?: number;
158
+ }): Promise<void>;
103
159
  type(target: Target, text: string, opts?: ActionOptions & {
104
160
  clear?: boolean;
105
161
  }): Promise<void>;