Skip to content

armgit / hypit

Public Imported from GitHub
0

Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.

feat(capture): add browser screenshots and recording tools

kashorin76147c1d6cb6
diff --git a/package.json b/package.json
index af0ebde0..34cd12f2 100644
--- a/package.json
+++ b/package.json
@@ -5,6 +5,10 @@
"license": "SEE LICENSE IN LICENSE",
"type": "module",
"exports": {
+ "./browser-capture": {
+ "types": "./dist/public/browser-capture.d.ts",
+ "import": "./packages/browser-capture/src/index.ts"
+ },
"./artifact": {
"types": "./dist/public/artifact.d.ts",
"import": "./packages/artifact/src/index.ts"
@@ -141,6 +145,7 @@
"node": ">=22.12.0"
},
"devDependencies": {
+ "@hypit/browser-capture": "workspace:*",
"@hypit/artifact": "workspace:*",
"@hypit/audio-track": "workspace:*",
"@hypit/audio-track-studio": "workspace:*",
@@ -233,6 +238,9 @@
"vitepress": "^1.6.4"
},
"dependencies": {
+ "@puppeteer/browsers": "3.2.2",
+ "puppeteer-core": "25.10.0",
+ "sharp": "0.35.3",
"cmu-pronouncing-dictionary": "3.0.0",
"tsx": "4.21.0",
"typescript": "5.9.3",
diff --git a/packages/browser-capture/README.md b/packages/browser-capture/README.md
new file mode 100644
index 00000000..36aa43c9
--- /dev/null
+++ b/packages/browser-capture/README.md
@@ -0,0 +1,82 @@
+# `@hypit/browser-capture`
+
+Browser material capture for websites and authored HTML. The package owns browser lifecycle and file
+capture; the task owns navigation, page state and the material worth showing. It imports Puppeteer Core,
+the upstream browser installer and Sharp directly and has no dependency on Hypit Core, Runtime,
+Providers or graph types.
+
+The Distribution supplies `hypit capture screenshot` and `hypit capture run`. See `hypit capture --help`
+for command options. Puppeteer Core is a pinned Distribution dependency, so a plain video project
+needs no browser-library installation or private `node_modules` import path.
+`hypit capture install-browser` explicitly prepares the package's tested Chrome for Testing revision
+in the browser cache (`PUPPETEER_CACHE_DIR`, or `~/.cache/puppeteer`).
+`captureBrowserExecutablePath()` reports that path.
+The package pins Chrome 153.0.8010.12 for the native recording API; `installCaptureBrowser()` uses
+the upstream installer. Existing compatible browsers remain selectable through launch options.
+
+## Library
+
+`withCapture(options, task, onOutput?)` opens a browser, calls the async task, finishes open recordings
+and closes the browser. It returns every completed `CaptureOutput`; `onOutput` receives each saved
+file as it finishes. A task failure closes the browser while preserving earlier completed files.
+
+`CaptureOptions` accepts:
+
+- `launch`: ordinary Puppeteer `LaunchOptions`. The default viewport is 1280 × 720 at device scale 1;
+ `defaultViewport` replaces it. `channel` selects an installed Chrome channel, `executablePath`
+ selects a specific executable, and the default uses this package's tested Chrome for Testing.
+ `PUPPETEER_CACHE_DIR` selects the cache directory.
+- `timeoutMs`: operation and navigation timeout for the initial page. Omission keeps Puppeteer's
+ default; `0` disables that timeout. Scripts can configure other pages themselves.
+- `ffprobePath`: metadata reader for finished recordings; defaults to `ffprobe` on `PATH`.
+
+The task receives the ordinary Puppeteer `browser` and `page`, plus:
+
+```ts
+await screenshot({ path: "assets/screen.png", fullPage: true });
+await screenshot({ path: "assets/card.png", selector: "#card", omitBackground: true });
+const recording = await record({ path: "assets/demo.mp4", fps: 30 });
+// Perform this task's page interactions.
+const video = await recording.stop();
+```
+
+`screenshot` accepts Puppeteer's `ScreenshotOptions` with required `path`, no `encoding`, and optional
+`selector`. Selectors use Puppeteer syntax and wait for a visible element. Element, rectangular clip
+and full-page capture are separate choices. Dimensions come from the saved bytes, including device
+scale. PNG, JPEG and WebP follow Puppeteer's screenshot support.
+
+`record` accepts Puppeteer's native `RecordOptions` with required `path`, excluding `overwrite`.
+It uses `Page.record` on Chrome 153 or later. Chrome produces MP4; use an `.mp4` destination.
+`audio: true` includes page audio; the default is picture only. `fps` / `frameRate` specify the maximum
+capture rate, and `maxWidth` / `maxHeight` constrain output dimensions. These options pass through
+to Puppeteer. The helper defaults those upper bounds to the viewport's device-pixel dimensions.
+Chrome determines the recorded dimensions; device scale can enlarge a screenshot without enlarging
+the recording. Use the returned `width` and `height` for placement. No FFmpeg encoder is involved;
+`ffprobe` reads the completed file's actual dimensions,
+duration, frame rate and audio presence. `stop()` is idempotent and waits for the file to finish.
+
+Both functions accept an optional second `Page` argument for scripts using several pages. Returning
+finishes recordings started through `record`. Ordinary Puppeteer methods remain available; files
+written directly by a script are outside the helper's output list and overwrite behavior.
+
+Outputs include absolute `path`, `kind`, `url`, `width`, `height`, `format`, plus `duration`, `frameRate`
+and `hasAudio` for video when available. Helpers refuse overwrites; a failed capture removes only its
+own incomplete output. The CLI prints completed paths as work progresses; `--json` returns the
+complete output list as `hypit.capture@1`.
+
+## Project scripts
+
+A `.mjs` file exports a default async function receiving the session plus `args` and `log`.
+`hypit capture run task.mjs -- <arguments>` forwards arguments after `--` unchanged. `log` writes
+progress separately from JSON output. Optional `export const options` supplies `CaptureOptions`;
+explicit CLI browser options override it. Relative output paths follow the working directory, while
+`import.meta.url` can locate inputs beside the script. These are ordinary Node.js scripts with the
+caller's permissions.
+
+Waiting for lazy content, choosing a device profile, authentication and interacting with banners
+belong in those scripts through normal Puppeteer APIs. A simple screenshot waits for page load;
+`--wait-for` and `--wait-ms` add an authored readiness condition. The package does not interpret
+websites or silently rewrite page content.
+
+For a library import in an installed Distribution, use `hypit/browser-capture`. The workspace package
+also exports the same API as `@hypit/browser-capture`.
diff --git a/packages/browser-capture/package.json b/packages/browser-capture/package.json
new file mode 100644
index 00000000..bbdee50c
--- /dev/null
+++ b/packages/browser-capture/package.json
@@ -0,0 +1,15 @@
+{
+ "name": "@hypit/browser-capture",
+ "version": "0.0.0-dev",
+ "license": "SEE LICENSE IN LICENSE",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "dependencies": {
+ "@puppeteer/browsers": "3.2.2",
+ "puppeteer-core": "25.10.0",
+ "sharp": "0.35.3"
+ }
+}
diff --git a/packages/browser-capture/src/browser.ts b/packages/browser-capture/src/browser.ts
new file mode 100644
index 00000000..ead0a1ac
--- /dev/null
+++ b/packages/browser-capture/src/browser.ts
@@ -0,0 +1,19 @@
+import { homedir } from "node:os";
+import { join } from "node:path";
+import { Browser, computeExecutablePath, install } from "@puppeteer/browsers";
+
+// Page.record uses Chrome's native recording protocol, introduced in Chrome 153.
+// This package owns its tested browser revision independently of other renderers.
+const chromeVersion = "153.0.8010.12";
+
+const cacheDirectory = () => process.env.PUPPETEER_CACHE_DIR ?? join(homedir(), ".cache", "puppeteer");
+
+export async function captureBrowserExecutablePath(): Promise<string> {
+ return computeExecutablePath({ browser: Browser.CHROME, buildId: chromeVersion, cacheDir: cacheDirectory() });
+}
+
+/** Explicit setup, using Puppeteer's cache configuration and upstream browser installer. */
+export async function installCaptureBrowser(): Promise<string> {
+ const installed = await install({ browser: Browser.CHROME, buildId: chromeVersion, cacheDir: cacheDirectory() });
+ return installed.executablePath;
+}
diff --git a/packages/browser-capture/src/index.ts b/packages/browser-capture/src/index.ts
new file mode 100644
index 00000000..a256ae5a
--- /dev/null
+++ b/packages/browser-capture/src/index.ts
@@ -0,0 +1,198 @@
+import { execFile } from "node:child_process";
+import { mkdir, open, rm } from "node:fs/promises";
+import { dirname, resolve } from "node:path";
+import { Writable } from "node:stream";
+import { promisify } from "node:util";
+import { existsSync } from "node:fs";
+import puppeteer from "puppeteer-core";
+import type { Browser, LaunchOptions, Page, RecordOptions, ScreenshotOptions } from "puppeteer-core";
+import sharp from "sharp";
+import { captureBrowserExecutablePath } from "./browser.js";
+export { captureBrowserExecutablePath, installCaptureBrowser } from "./browser.js";
+
+export type CaptureOptions = {
+ /** Ordinary Puppeteer launch options, including channel, executablePath and defaultViewport. */
+ readonly launch?: LaunchOptions;
+ /** Page operation and navigation timeout; Puppeteer's default applies when omitted. */
+ readonly timeoutMs?: number;
+ /** Used to read the actual dimensions and duration after a recording finishes. */
+ readonly ffprobePath?: string;
+};
+
+export type CaptureOutput = {
+ readonly kind: "image" | "video";
+ readonly path: string;
+ readonly url: string;
+ readonly width: number;
+ readonly height: number;
+ readonly format: string;
+ readonly duration?: number;
+ readonly frameRate?: number;
+ readonly hasAudio?: boolean;
+};
+
+export type ScreenshotCaptureOptions = Omit<ScreenshotOptions, "path" | "encoding"> & {
+ readonly path: string;
+ readonly selector?: string;
+};
+
+export type RecordingCaptureOptions = Omit<RecordOptions, "path" | "overwrite"> & {
+ readonly path: string;
+};
+
+export type CaptureRecording = { stop(): Promise<CaptureOutput> };
+
+export type CaptureSession = {
+ readonly browser: Browser;
+ readonly page: Page;
+ /** Capture the default page, or a page created by the script in this browser. */
+ screenshot(options: ScreenshotCaptureOptions, page?: Page): Promise<CaptureOutput>;
+ /** Record page changes through Chrome's native recorder; audio is opt-in. */
+ record(options: RecordingCaptureOptions, page?: Page): Promise<CaptureRecording>;
+};
+
+export type CaptureScriptContext = CaptureSession & {
+ readonly args: readonly string[];
+ log(message: string): void;
+};
+
+export type CaptureScript = (context: CaptureScriptContext) => Promise<void>;
+
+async function reserve(path: string) {
+ await mkdir(dirname(path), { recursive: true });
+ try { return await open(path, "wx"); }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") {
+ throw new Error(`Destination ${path} already exists`, { cause: error });
+ }
+ throw error;
+ }
+}
+
+const exec = promisify(execFile);
+async function recordingInfo(path: string, ffprobe: string): Promise<Omit<CaptureOutput, "kind" | "path" | "url">> {
+ const { stdout } = await exec(ffprobe, ["-v", "error", "-show_entries",
+ "format=format_name,duration:stream=codec_type,width,height,avg_frame_rate", "-of", "json", path]);
+ const data = JSON.parse(stdout) as {
+ format?: { format_name?: string; duration?: string };
+ streams?: { codec_type?: string; width?: number; height?: number; avg_frame_rate?: string }[];
+ };
+ const video = data.streams?.find((stream) => stream.codec_type === "video");
+ const [num, den = "1"] = (video?.avg_frame_rate ?? "0").split("/");
+ const rate = Number(num) / Number(den);
+ const duration = Number(data.format?.duration);
+ if (!video?.width || !video.height || !Number.isFinite(duration) || duration <= 0) {
+ throw new Error(`Recording ${path} has no readable video duration or dimensions`);
+ }
+ return { width: video.width, height: video.height, duration,
+ format: data.format?.format_name ?? "unknown", hasAudio: data.streams?.some((s) => s.codec_type === "audio") ?? false,
+ ...(Number.isFinite(rate) && rate > 0 ? { frameRate: rate } : {}) };
+}
+
+/**
+ * One browser for an authored capture task. The callback uses ordinary Puppeteer objects;
+ * no website interpretation, Runtime, Build, or Source graph participates here.
+ */
+export async function withCapture(
+ options: CaptureOptions,
+ task: (session: CaptureSession) => Promise<void>,
+ onOutput?: (output: CaptureOutput) => void,
+): Promise<readonly CaptureOutput[]> {
+ const launch = { ...options.launch };
+ if (!launch.channel && !launch.executablePath) {
+ launch.executablePath = await captureBrowserExecutablePath();
+ if (!existsSync(launch.executablePath)) throw new Error(
+ `Capture browser is not installed at ${launch.executablePath}. Run hypit capture install-browser, or select an installed compatible browser.`);
+ }
+ const browser = await puppeteer.launch({
+ defaultViewport: { width: 1280, height: 720, deviceScaleFactor: 1 },
+ ...launch,
+ });
+ const outputs: CaptureOutput[] = [];
+ const recordings = new Set<CaptureRecording>();
+ const publish = (output: CaptureOutput): CaptureOutput => {
+ outputs.push(output);
+ onOutput?.(output);
+ return output;
+ };
+ try {
+ const page = await browser.newPage();
+ if (options.timeoutMs !== undefined) {
+ page.setDefaultTimeout(options.timeoutMs);
+ page.setDefaultNavigationTimeout(options.timeoutMs);
+ }
+ await task({
+ browser, page,
+ async screenshot(input, target = page) {
+ const { path: destination, selector, ...screenshotOptions } = input;
+ if (selector !== undefined && (input.fullPage || input.clip !== undefined)) {
+ throw new Error("Choose a selector, a clip, or the full page for a screenshot");
+ }
+ const path = resolve(destination);
+ const handle = await reserve(path);
+ await handle.close();
+ try {
+ if (selector === undefined) {
+ await target.screenshot({ ...screenshotOptions, path });
+ } else {
+ const element = await target.waitForSelector(selector, { visible: true });
+ if (element === null) throw new Error(`No visible element matches ${selector}`);
+ try { await element.screenshot({ ...screenshotOptions, path }); }
+ finally { await element.dispose(); }
+ }
+ const info = await sharp(path).metadata();
+ return publish({ kind: "image", path, url: target.url(), width: info.width, height: info.height,
+ format: info.format });
+ } catch (error) {
+ await rm(path, { force: true });
+ throw error;
+ }
+ },
+ async record(input, target = page) {
+ const { path: destination, ...recordOptions } = input;
+ const path = resolve(destination);
+ await exec(options.ffprobePath ?? "ffprobe", ["-version"]);
+ const pixels = await target.evaluate(() => ({
+ maxWidth: Math.round(window.innerWidth * window.devicePixelRatio),
+ maxHeight: Math.round(window.innerHeight * window.devicePixelRatio),
+ }));
+ const file = await reserve(path);
+ let native: Awaited<ReturnType<Page["record"]>>;
+ try { native = await target.record({ ...pixels, ...recordOptions }); }
+ catch (error) {
+ await file.close(); await rm(path, { force: true });
+ throw new Error(`Could not start native recording in ${await browser.version()}. `
+ + `Page recording requires Chrome 153 or later: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
+ }
+ const url = target.url();
+ // Own the output stream so stop() also waits for the file to finish writing.
+ const written = native.pipeTo(Writable.toWeb(file.createWriteStream()));
+ void written.catch(() => {});
+ let stopped: Promise<CaptureOutput> | undefined;
+ const recording: CaptureRecording = {
+ stop() {
+ stopped ??= (async () => {
+ try {
+ await native.stop();
+ await written;
+ return publish({ kind: "video", path, url,
+ ...await recordingInfo(path, options.ffprobePath ?? "ffprobe") });
+ } catch (error) {
+ await rm(path, { force: true });
+ throw error;
+ } finally { recordings.delete(recording); }
+ })();
+ return stopped;
+ },
+ };
+ recordings.add(recording);
+ return recording;
+ },
+ });
+ await Promise.all([...recordings].map((recording) => recording.stop()));
+ return outputs;
+ } finally {
+ try { await Promise.allSettled([...recordings].map((recording) => recording.stop())); }
+ finally { await browser.close(); }
+ }
+}
diff --git a/packages/browser-capture/test/capture.test.ts b/packages/browser-capture/test/capture.test.ts
new file mode 100644
index 00000000..191c3259
--- /dev/null
+++ b/packages/browser-capture/test/capture.test.ts
@@ -0,0 +1,103 @@
+import assert from "node:assert/strict";
+import { existsSync } from "node:fs";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { pathToFileURL } from "node:url";
+import test from "node:test";
+import { spawnSync } from "node:child_process";
+import puppeteer from "puppeteer-core";
+import sharp from "sharp";
+import { withCapture, captureBrowserExecutablePath } from "../src/index.js";
+import type { CaptureOutput } from "../src/index.js";
+
+const executablePath = process.env.HYPIT_CAPTURE_TEST_BROWSER ?? await captureBrowserExecutablePath();
+const browserReady = existsSync(executablePath);
+const codecsReady = ["ffprobe"].every((name) => spawnSync(name, ["-version"], { stdio: "ignore" }).status === 0);
+
+test("capture saves actual page pixels, transparent elements and rectangles at the chosen scale", {
+ skip: !browserReady && "Chrome is not installed", timeout: 30_000,
+}, async () => {
+ const work = await mkdtemp(join(tmpdir(), "hypit-capture-images-"));
+ let launched: Awaited<ReturnType<typeof puppeteer.launch>> | undefined;
+ try {
+ const source = join(work, "page.html");
+ await writeFile(source, `<style>body{margin:0;height:900px;background:transparent}
+ #card{position:absolute;top:40px;left:30px;width:160px;height:100px;background:#ff0000;border-radius:20px}
+ </style><button id="card" onclick="this.style.background='#0000ff'">Compare</button>`);
+ const outputs = await withCapture({ launch: { executablePath,
+ defaultViewport: { width: 320, height: 240, deviceScaleFactor: 2 } } }, async (capture) => {
+ launched = capture.browser;
+ await capture.page.goto(pathToFileURL(source).href);
+ await capture.screenshot({ path: join(work, "viewport.png"), omitBackground: true });
+ await capture.screenshot({ path: join(work, "full.png"), fullPage: true });
+ await capture.screenshot({ path: join(work, "element.png"), selector: "#card", omitBackground: true });
+ await capture.page.click("#card");
+ await capture.screenshot({ path: join(work, "region.png"), clip: { x: 60, y: 70, width: 10, height: 10 } });
+ await assert.rejects(capture.screenshot({ path: join(work, "full.png") }), /already exists/);
+ });
+ assert.equal(launched?.connected, false, "the owned browser closes after the task");
+ assert.deepEqual(outputs.map(({ width, height }) => [width, height]), [[640, 480], [640, 1800], [320, 200], [20, 20]]);
+ const pixels = await sharp(join(work, "region.png")).removeAlpha().raw().toBuffer();
+ assert.deepEqual([...pixels.subarray(0, 3)], [0, 0, 255], "script interaction changes the captured state");
+ const transparent = await sharp(join(work, "viewport.png")).ensureAlpha().raw().toBuffer();
+ assert.equal(transparent[3], 0);
+ assert.equal(outputs[0]?.url, pathToFileURL(source).href);
+ assert.ok((await readFile(join(work, "full.png"))).byteLength > 0);
+ } finally { await rm(work, { recursive: true, force: true }); }
+});
+
+test("recording finalizes its file and reports actual dimensions and time", {
+ skip: (!browserReady || !codecsReady) && "Chrome and ffprobe are required", timeout: 30_000,
+}, async () => {
+ const work = await mkdtemp(join(tmpdir(), "hypit-capture-record-"));
+ try {
+ const published: CaptureOutput[] = [];
+ const outputs = await withCapture({ launch: { executablePath,
+ defaultViewport: { width: 960, height: 600, deviceScaleFactor: 1 } } }, async (capture) => {
+ await capture.page.setContent(`<style>body{background:#123456}div{width:50px;height:50px;background:coral;
+ animation:move .4s infinite alternate linear}@keyframes move{to{transform:translateX(120px)}}</style><div></div>`);
+ const recording = await capture.record({ path: join(work, "motion.mp4"), fps: 20 });
+ await new Promise((done) => setTimeout(done, 650));
+ const result = await recording.stop();
+ assert.equal(await recording.stop(), result, "stop is idempotent and publishes once");
+ assert.equal(result.width, 960);
+ assert.equal(result.height, 600);
+ assert.ok(result.duration! > 0.3 && result.duration! < 3, String(result.duration));
+ assert.equal(result.hasAudio, false);
+ assert.ok(result.frameRate! > 0);
+ await capture.record({ path: join(work, "auto-stop.mp4"), fps: 20 });
+ await new Promise((done) => setTimeout(done, 350));
+ // Finish the moving recording, then verify a settled screen also records its held state.
+ }, (output) => published.push(output));
+ const still = await withCapture({ launch: { executablePath,
+ defaultViewport: { width: 320, height: 240 } } }, async (capture) => {
+ await capture.page.setContent("<p>A settled product screen</p>");
+ await new Promise((done) => setTimeout(done, 150));
+ await capture.record({ path: join(work, "still.mp4"), fps: 20 });
+ await new Promise((done) => setTimeout(done, 350));
+ }, (output) => published.push(output));
+ assert.equal(outputs.length, 2, "returning from the task finishes its open recording");
+ assert.equal(still.length, 1);
+ assert.deepEqual(published, [...outputs, ...still]);
+ for (const output of outputs) assert.ok((await readFile(output.path)).byteLength > 100);
+ } finally { await rm(work, { recursive: true, force: true }); }
+});
+
+test("a failed script closes the browser and preserves earlier completed captures", {
+ skip: !browserReady && "Chrome is not installed", timeout: 30_000,
+}, async () => {
+ const work = await mkdtemp(join(tmpdir(), "hypit-capture-failure-"));
+ let launched: Awaited<ReturnType<typeof puppeteer.launch>> | undefined;
+ try {
+ await assert.rejects(withCapture({ launch: { executablePath }, timeoutMs: 100 }, async (capture) => {
+ launched = capture.browser;
+ await capture.page.setContent("<p>Available</p>");
+ await capture.screenshot({ path: join(work, "saved.png") });
+ await capture.screenshot({ path: join(work, "missing.png"), selector: "#missing" });
+ }), /Waiting for selector/);
+ assert.equal(launched?.connected, false);
+ assert.ok(existsSync(join(work, "saved.png")));
+ assert.equal(existsSync(join(work, "missing.png")), false);
+ } finally { await rm(work, { recursive: true, force: true }); }
+});
diff --git a/packages/video-cli/README.md b/packages/video-cli/README.md
index fbd3de51..10087836 100644
--- a/packages/video-cli/README.md
+++ b/packages/video-cli/README.md
@@ -107,6 +107,14 @@ children and example, or the value shapes a drawing Producer must emit.
Install the `hypit` Distribution globally once. It resolves its own TypeScript loader and CLI, so it
neither invokes npm per command nor requires a project to contain Hypit's `package.json`.
+`hypit capture screenshot <url-or-file> --to <image>` saves browser material, and
+`hypit capture run <script.mjs> [-- arguments]` runs ordinary project interactions with a prepared
+Puppeteer page and screenshot/recording helpers. `hypit capture --help` lists viewport, region,
+readiness and browser options. `hypit capture install-browser` prepares the package's tested browser
+revision; an already installed compatible browser can be selected explicitly. The independently maintained `@hypit/browser-capture` package owns
+browser lifecycle and capture; Video CLI owns command presentation. This preparation tool outputs
+ordinary project files and opens no Runtime Profile or Build. The package README owns the script API.
+
`--workspace` is only the Source Workspace containment boundary. `--asset-root` may additionally admit
explicit asset bytes without widening Source imports. `--package-root` is only the Host
override used to resolve installed packages. By default, a project with
diff --git a/packages/video-cli/package.json b/packages/video-cli/package.json
index cde55822..c6cd085d 100644
--- a/packages/video-cli/package.json
+++ b/packages/video-cli/package.json
@@ -9,6 +9,7 @@
"./cli": "./src/cli.ts"
},
"dependencies": {
+ "@hypit/browser-capture": "workspace:*",
"@hypit/cli": "workspace:*",
"@hypit/compiler-markup-node": "workspace:*",
"@hypit/composition": "workspace:*",
diff --git a/packages/video-cli/src/capture.ts b/packages/video-cli/src/capture.ts
new file mode 100644
index 00000000..39a94e3e
--- /dev/null
+++ b/packages/video-cli/src/capture.ts
@@ -0,0 +1,174 @@
+import { stat } from "node:fs/promises";
+import { resolve } from "node:path";
+import { pathToFileURL } from "node:url";
+import { parseArgs } from "node:util";
+import type { CliIo } from "@hypit/cli";
+import type { CaptureOptions, CaptureOutput, CaptureScript } from "@hypit/browser-capture";
+
+export function writeCaptureHelp(io: CliIo): void {
+ io.write(`Browser capture — save website or local HTML material to project files.
+
+ hypit capture screenshot <url-or-file> --to <image> [options]
+ hypit capture run <script.mjs> [browser options] [-- script arguments]
+ hypit capture install-browser
+
+Screenshot options:
+ --full-page Capture the full document
+ --selector <selector> Capture one visible element (Puppeteer selector syntax)
+ --clip <x,y,width,height> Capture a rectangle in CSS pixels
+ --transparent Preserve a transparent page background
+ --wait-for <selector> Wait for a visible element before capture
+ --wait-ms <milliseconds> Additional explicitly chosen delay
+
+Browser options:
+ --viewport <width>x<height> CSS viewport size (default: 1280x720)
+ --scale <number> Device pixel ratio (default: 1)
+ --channel <name> Installed Chrome channel, e.g. chrome
+ --browser <path> Explicit browser executable instead of a channel
+ --headed Show the browser
+ --timeout-ms <milliseconds> Page operation and navigation timeout
+ --json Print all saved files with their actual dimensions
+
+The browser defaults to this package's tested Chrome for Testing revision. Prepare
+it once with install-browser, or select a compatible installed browser. Native page
+recording requires Chrome 153+ and ffprobe on PATH. A script exports default async ({ page, browser, screenshot,
+record, args, log }) => { ... }; optional export const options configures Puppeteer
+launch options and ffprobePath. Use page.goto/click/type/evaluate normally, then
+screenshot({ path: 'assets/page.png' }) or record({ path: 'assets/demo.mp4' }).
+Await recorder.stop() to finish a recording; returning finishes open recordings.
+Native recording produces MP4; audio is included when record({ audio: true, ... }).
+
+Outputs refuse to overwrite existing files. Paths are relative to the working
+directory. Scripts are ordinary project code executed with Node.js permissions.
+`);
+}
+
+function numeric(raw: string | undefined, label: string, zero = false): number | undefined {
+ if (raw === undefined) return undefined;
+ const value = Number(raw);
+ if (!Number.isFinite(value) || (zero ? value < 0 : value <= 0)) {
+ throw new Error(`${label} must be ${zero ? "non-negative" : "positive"}`);
+ }
+ return value;
+}
+
+async function sourceUrl(source: string, cwd: string): Promise<string> {
+ if (/^https?:\/\//i.test(source) || source.startsWith("file:")) return new URL(source).href;
+ const path = resolve(cwd, source);
+ if (!(await stat(path)).isFile()) throw new Error(`Not a file: ${path}`);
+ return pathToFileURL(path).href;
+}
+
+export async function runCaptureCli(argv: readonly string[], io: CliIo, cwd = process.cwd()): Promise<void> {
+ const command = argv[1];
+ if (command === undefined || command === "--help") { writeCaptureHelp(io); return; }
+ if (command !== "screenshot" && command !== "run" && command !== "install-browser") throw new Error(`Unknown capture command ${command}`);
+ const separator = argv.indexOf("--");
+ const args = separator < 0 ? [] : argv.slice(separator + 1);
+ if (command === "screenshot" && args.length > 0) throw new Error("Script arguments belong to capture run");
+ const parsed = parseArgs({
+ args: (separator < 0 ? argv : argv.slice(0, separator)).slice(2), allowPositionals: true,
+ options: {
+ viewport: { type: "string" }, scale: { type: "string" }, channel: { type: "string" },
+ browser: { type: "string" }, headed: { type: "boolean" }, "timeout-ms": { type: "string" },
+ json: { type: "boolean" }, debug: { type: "boolean" }, verbose: { type: "boolean" },
+ "no-color": { type: "boolean" }, color: { type: "string" }, help: { type: "boolean" },
+ to: { type: "string" }, "full-page": { type: "boolean" },
+ selector: { type: "string" }, clip: { type: "string" },
+ transparent: { type: "boolean" }, "wait-for": { type: "string" },
+ "wait-ms": { type: "string" },
+ },
+ });
+ const values = parsed.values;
+ if (values.help) { writeCaptureHelp(io); return; }
+ if (command === "install-browser") {
+ if (parsed.positionals.length > 0 || args.length > 0) throw new Error("install-browser takes no positional arguments");
+ for (const name of Object.keys(values)) {
+ if (!["json", "debug", "verbose", "color", "no-color"].includes(name)) throw new Error(`install-browser does not use --${name}`);
+ }
+ io.writeProgress?.("Preparing the capture browser…\n");
+ const { installCaptureBrowser } = await import("@hypit/browser-capture");
+ const path = await installCaptureBrowser();
+ io.write(values.json ? `${JSON.stringify({ format: "hypit.capture-browser@1", path })}\n` : `Capture browser ready: ${path}\n`);
+ return;
+ }
+ const source = parsed.positionals[0];
+ if (source === undefined || parsed.positionals.length !== 1) {
+ throw new Error(`capture ${command} needs exactly one ${command === "run" ? "script" : "URL or local file"}`);
+ }
+ if (values.browser && values.channel) throw new Error("Choose --browser or --channel");
+ let options: CaptureOptions = {};
+ let script: CaptureScript;
+ if (command === "run") {
+ for (const name of ["to", "full-page", "selector", "clip", "transparent", "wait-for", "wait-ms"] as const) {
+ if (values[name] !== undefined) throw new Error(`--${name} belongs to capture screenshot; use the script for capture run`);
+ }
+ const loaded = await import(pathToFileURL(resolve(cwd, source)).href) as {
+ options?: CaptureOptions; default?: CaptureScript;
+ };
+ if (typeof loaded.default !== "function") throw new Error("Capture script must export a default async function");
+ options = loaded.options ?? {};
+ script = loaded.default;
+ } else {
+ if (!values.to) throw new Error("capture screenshot requires --to <image>");
+ const modes = [values["full-page"], values.selector, values.clip].filter(Boolean);
+ if (modes.length > 1) throw new Error("Choose --full-page, --selector or --clip");
+ let clip: { x: number; y: number; width: number; height: number } | undefined;
+ if (values.clip) {
+ const [x, y, width, height, extra] = values.clip.split(",").map(Number);
+ if (extra !== undefined || [x, y, width, height].some((n) => n === undefined || !Number.isFinite(n))
+ || x! < 0 || y! < 0 || width! <= 0 || height! <= 0) {
+ throw new Error("--clip needs x,y,width,height with non-negative coordinates and positive dimensions");
+ }
+ clip = { x: x!, y: y!, width: width!, height: height! };
+ }
+ const url = await sourceUrl(source, cwd);
+ const path = resolve(cwd, values.to);
+ const waitMs = numeric(values["wait-ms"], "--wait-ms", true);
+ script = async ({ page, screenshot }) => {
+ const response = await page.goto(url, { waitUntil: "load" });
+ if (response && !response.ok()) throw new Error(`Page returned HTTP ${response.status()}: ${page.url()}`);
+ if (values["wait-for"]) await page.waitForSelector(values["wait-for"], { visible: true });
+ if (waitMs) await new Promise((done) => setTimeout(done, waitMs));
+ await screenshot({ path,
+ ...(values["full-page"] ? { fullPage: true } : {}),
+ ...(values.selector ? { selector: values.selector } : {}),
+ ...(clip ? { clip } : {}),
+ ...(values.transparent ? { omitBackground: true } : {}),
+ });
+ };
+ }
+ const launch = { ...options.launch };
+ if (values.browser) { launch.executablePath = resolve(cwd, values.browser); delete launch.channel; }
+ if (values.channel) {
+ if (!["chrome", "chrome-beta", "chrome-canary", "chrome-dev"].includes(values.channel)) {
+ throw new Error("--channel must name a Puppeteer Chrome channel: chrome, chrome-beta, chrome-canary or chrome-dev");
+ }
+ launch.channel = values.channel as NonNullable<typeof launch.channel>;
+ delete launch.executablePath;
+ }
+ if (values.headed) launch.headless = false;
+ if (values.viewport || values.scale) {
+ const viewport = { width: 1280, height: 720, deviceScaleFactor: 1, ...launch.defaultViewport };
+ if (values.viewport) {
+ const match = /^(\d+)x(\d+)$/.exec(values.viewport);
+ if (!match || Number(match[1]) < 1 || Number(match[2]) < 1) throw new Error("--viewport needs positive WIDTHxHEIGHT");
+ viewport.width = Number(match[1]); viewport.height = Number(match[2]);
+ }
+ viewport.deviceScaleFactor = numeric(values.scale, "--scale") ?? viewport.deviceScaleFactor;
+ launch.defaultViewport = viewport;
+ }
+ const timeoutMs = numeric(values["timeout-ms"], "--timeout-ms", true) ?? options.timeoutMs;
+ const progress = (text: string) => {
+ if (io.writeProgress) io.writeProgress(`${text}\n`);
+ else if (!values.json) io.write(`${text}\n`);
+ };
+ const show = (output: CaptureOutput) => progress(`Saved ${output.path} (${output.width}×${output.height}${
+ output.duration === undefined ? "" : `, ${output.duration.toFixed(2)}s`})`);
+ // Loading the browser library is specific to capture; ordinary Hypit commands do not load it.
+ const { withCapture } = await import("@hypit/browser-capture");
+ const outputs = await withCapture({ ...options, launch, ...(timeoutMs === undefined ? {} : { timeoutMs }) },
+ async (session) => await script({ ...session, args, log: progress }), show);
+ if (values.json) io.write(`${JSON.stringify({ format: "hypit.capture@1", outputs }, null, 2)}\n`);
+ else io.write(`Capture complete: ${outputs.length} file${outputs.length === 1 ? "" : "s"}.\n`);
+}
diff --git a/packages/video-cli/src/cli.ts b/packages/video-cli/src/cli.ts
index e136185e..fe9f8ade 100644
--- a/packages/video-cli/src/cli.ts
+++ b/packages/video-cli/src/cli.ts
@@ -4,6 +4,7 @@ import type { CliIo } from "@hypit/cli";
import { creationCommands, isCreationCommand, writeCreationHelp } from "./creation.js";
import { isMediaCommand, mediaCommands, writeMediaHelp } from "./media.js";
import { writeVocabularyHelp } from "./vocabulary.js";
+import { writeCaptureHelp } from "./capture.js";
const argv = process.argv.slice(2);
const json = argv.includes("--json");
@@ -61,7 +62,8 @@ const io: CliIo = {
};
async function main(): Promise<void> {
- if (argv.length === 0 || argv[0] === "help" || argv.includes("--help")) {
+ const commandArgs = argv[0] === "capture" && argv.includes("--") ? argv.slice(0, argv.indexOf("--")) : argv;
+ if (argv.length === 0 || argv[0] === "help" || commandArgs.includes("--help")) {
const topic = argv[0] === "help" ? argv[1] : argv.includes("--help") ? argv[0] : undefined;
if (isCreationCommand(topic)) {
writeCreationHelp(io, topic);
@@ -76,11 +78,15 @@ async function main(): Promise<void> {
writeVocabularyHelp(io);
return;
}
+ if (topic === "capture") {
+ writeCaptureHelp(io);
+ return;
+ }
writeCliHelp(io, topic);
if (topic === undefined) {
io.write(`\nCreation tools (one request through the selected Runtime Profile, no Build)\n${
creationCommands.map((item) => ` ${item}`).join("\n")}\n hypit help <tool> for each\n`
- + `\nPreparation (local, no request, no state)\n media ${mediaCommands.join(" | ")}\n vocabulary\n hypit help media, hypit help vocabulary\n`);
+ + `\nPreparation (local tools and project files)\n media ${mediaCommands.join(" | ")}\n capture screenshot | run | install-browser\n vocabulary\n hypit help media, hypit help capture, hypit help vocabulary\n`);
}
return;
}
diff --git a/packages/video-cli/src/index.ts b/packages/video-cli/src/index.ts
index 8c942369..041f9cb6 100644
--- a/packages/video-cli/src/index.ts
+++ b/packages/video-cli/src/index.ts
@@ -11,6 +11,7 @@ import { isCreationCommand, runCreationCli } from "./creation.js";
import { videoCliDistribution } from "./distribution.js";
import { runMediaCli } from "./media.js";
import { runVocabularyCli } from "./vocabulary.js";
+import { runCaptureCli } from "./capture.js";
export {
createVideoCompiler,
@@ -23,6 +24,7 @@ export { creationCommands, isCreationCommand, runCreationCli, writeCreationHelp
export type { CreationCommand, CreationEnvironment, CreationHost } from "./creation.js";
export { isMediaCommand, mediaCommands, runMediaCli, writeMediaHelp } from "./media.js";
export type { MediaCommand, MediaProbe } from "./media.js";
+export { runCaptureCli, writeCaptureHelp } from "./capture.js";
export { listPackages, listSurfaces, runVocabularyCli, visualSchema, writeVocabularyHelp } from "./vocabulary.js";
export type { PackageListing, SurfaceListing } from "./vocabulary.js";
/** The project's selected Runtime Profile, read the way `hypit` reads it, for tools that run beside the CLI. */
@@ -39,6 +41,7 @@ export function runVideoCli(
installExternalPackageResolution([hypitHostPackageRoot()]);
if (isCreationCommand(argv[0])) return runCreationCli(argv, io);
if (argv[0] === "media") return runMediaCli(argv, io);
+ if (argv[0] === "capture") return runCaptureCli(argv, io);
if (argv[0] === "vocabulary") return runVocabularyCli(argv, io);
return runCli(argv, io, {
...videoCliDistribution,
diff --git a/packages/video-cli/test/capture.test.ts b/packages/video-cli/test/capture.test.ts
new file mode 100644
index 00000000..8b5b0cf7
--- /dev/null
+++ b/packages/video-cli/test/capture.test.ts
@@ -0,0 +1,53 @@
+import assert from "node:assert/strict";
+import { execFile } from "node:child_process";
+import { existsSync } from "node:fs";
+import { mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import test from "node:test";
+import { promisify } from "node:util";
+import { captureBrowserExecutablePath } from "@hypit/browser-capture";
+import { runCaptureCli } from "../src/capture.js";
+import type { CliIo } from "@hypit/cli";
+
+const executablePath = process.env.HYPIT_CAPTURE_TEST_BROWSER ?? await captureBrowserExecutablePath();
+const exec = promisify(execFile);
+const launcher = resolve("bin/hypit.mjs");
+
+test("capture rejects incomplete or contradictory requests before browser work", async () => {
+ const io: CliIo = { write: () => {}, setExitCode: () => {} };
+ await assert.rejects(runCaptureCli(["capture", "screenshot", "https://example.com"], io), /requires --to/);
+ await assert.rejects(runCaptureCli(["capture", "screenshot", "https://example.com", "--to", "x.png",
+ "--full-page", "--selector", "main"], io), /Choose --full-page/);
+ await assert.rejects(runCaptureCli(["capture", "screenshot", "https://example.com", "--to", "x.png",
+ "--clip", "1,2,3"], io), /--clip needs/);
+ await assert.rejects(runCaptureCli(["capture", "run", "x.mjs", "--to", "x.png"], io), /belongs to capture screenshot/);
+});
+
+test("the shipped launcher captures from a plain project and passes script arguments without project dependencies", {
+ skip: !existsSync(executablePath) && "Chrome is not installed", timeout: 30_000,
+}, async () => {
+ const work = await mkdtemp(join(tmpdir(), "hypit-capture-cli-"));
+ try {
+ await writeFile(join(work, "page.html"), "<style>body{margin:0;height:1000px}</style><p>Product evidence</p>");
+ const common = ["--browser", executablePath, "--json"];
+ const first = await exec(process.execPath, [launcher, "capture", "screenshot", "page.html",
+ "--to", "assets/page.png", "--full-page", "--viewport", "400x300", ...common], { cwd: work });
+ const view = JSON.parse(first.stdout);
+ assert.equal(view.outputs[0].width, 400);
+ assert.equal(view.outputs[0].height, 1000);
+ assert.equal(view.outputs[0].path, join(await realpath(work), "assets/page.png"));
+ await writeFile(join(work, "task.mjs"), `export const options = { launch: { defaultViewport: { width: 240, height: 160 } } };
+ export default async ({page, screenshot, args, log}) => {
+ if(args[0] !== '--help') throw new Error('script arguments were not forwarded');
+ await page.setContent('<p>Authored HTML</p>');
+ log('Capturing the authored card');
+ await screenshot({path: 'assets/card.png'});
+ };`);
+ const second = await exec(process.execPath, [launcher, "capture", "run", "task.mjs", ...common,
+ "--", "--help"], { cwd: work });
+ assert.equal(JSON.parse(second.stdout).outputs[0].width, 240);
+ assert.match(second.stderr, /Capturing the authored card/);
+ assert.equal(existsSync(join(work, "node_modules")), false);
+ } finally { await rm(work, { recursive: true, force: true }); }
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 0102abea..8028c36f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -8,9 +8,18 @@ importers:
.:
dependencies:
+ '@puppeteer/browsers':
+ specifier: 3.2.2
+ version: 3.2.2
cmu-pronouncing-dictionary:
specifier: 3.0.0
version: 3.0.0
+ puppeteer-core:
+ specifier: 25.10.0
+ version: 25.10.0
+ sharp:
+ specifier: 0.35.3
+ version: 0.35.3(@types/[email protected])
tsx:
specifier: 4.21.0
version: 4.21.0
@@ -36,6 +45,9 @@ importers:
'@hypit/background-removal':
specifier: workspace:*
version: link:packages/background-removal
+ '@hypit/browser-capture':
+ specifier: workspace:*
+ version: link:packages/browser-capture
'@hypit/build-result':
specifier: workspace:*
version: link:packages/build-result
@@ -416,6 +428,18 @@ importers:
specifier: workspace:*
version: link:../protocol
+ packages/browser-capture:
+ dependencies:
+ '@puppeteer/browsers':
+ specifier: 3.2.2
+ version: 3.2.2
+ puppeteer-core:
+ specifier: 25.10.0
+ version: 25.10.0
+ sharp:
+ specifier: 0.35.3
+ version: 0.35.3(@types/[email protected])
+
packages/build-result:
dependencies:
'@hypit/protocol':
@@ -3221,6 +3245,9 @@ importers:
packages/video-cli:
dependencies:
+ '@hypit/browser-capture':
+ specifier: workspace:*
+ version: link:../browser-capture
'@hypit/cli':
specifier: workspace:*
version: link:../cli
@@ -4666,6 +4693,19 @@ packages:
yauzl:
optional: true
+ '@puppeteer/[email protected]':
+ resolution: {integrity: sha512-q2BU4YfO9h/Wt7IcWPcggpOOqLk2Tbs1hDwolvKZrweRjy751OJBKMN9zO5bfD0pzU7X/tvKw/exQds4pM/LOg==}
+ engines: {node: '>=22.12.0'}
+ hasBin: true
+ peerDependencies:
+ proxy-agent: '>=8.0.1'
+ yauzl: ^2.10.0 || ^3.4.0
+ peerDependenciesMeta:
+ proxy-agent:
+ optional: true
+ yauzl:
+ optional: true
+
'@rolldown/[email protected]':
resolution: {integrity: sha512-EypzgnYCwyVY4NDHKzGmNJT5b+XaQEBniHxsMdeIQLB/tcCzZnhqrzHpZFbX9iaxx+5RiB8caATBtfvZP7zVxQ==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -5327,6 +5367,9 @@ packages:
resolution: {integrity: sha512-pGVkY3T/qXxAp2nFPodwYqOevk6ncNMSmvL8QfRCx5ZWGd6Vor7AFNmyaA8Zs6uJyP1QAfjuLandCgvSix1BNA==}
+ resolution: {integrity: sha512-gCcO42XCHKEs7Ag0S7aGYsnJ7hlgrO3qderYqeiY0Eqk+0GFfuvT13IA0hHreJTa2KCdDVyGMeOhdMNmrrTjVg==}
+
resolution: {integrity: sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==}
@@ -5736,6 +5779,10 @@ packages:
resolution: {integrity: sha512-t9VmxaqrmANnEOBhpSDI6HD192Ge48k8vmWqQQL7hSFEqHEYwZbbsu49+aKLWZeRvFs3j1pMhXOqqF4kPlvjkQ==}
engines: {node: '>=18.0.0'}
+ resolution: {integrity: sha512-snEhs+6G5Tjd4I7tLCDOaoln2RgE0bD19RzEKgvgK2hZ5VKy3MpLhLTZ2fWpXSTg4K2cyPwp+VHATFJhxfnOeA==}
+ engines: {node: '>=18.0.0'}
+
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
@@ -5842,6 +5889,10 @@ packages:
resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==}
+ resolution: {integrity: sha512-Hy5eMQshOEMil4JUUx03h5pw1HYkYCso1RG/gcpPlFSd4cYPOcopxcXEAxpLPOkOPJb9LIJtwxuj66bSdvknFg==}
+ engines: {node: '>=22.12.0'}
+
resolution: {integrity: sha512-XPNT0dQJtphqQ4I29zxlG4IIPbg1iEHAQKWuQgtMJGXjACV77pZSmJvDi51IIIfd+DTKICcopJwUx4upVQ4XbA==}
engines: {node: '>=22.12.0'}
@@ -6175,6 +6226,9 @@ packages:
resolution: {integrity: sha512-VSV+fzfChirL3e7jay2yUC7B4HQCGtEWEg/MSSQbK+qWbqeGlRLlXTzPpYr3XGUvbpDHumWZBJxgesg4N7dbtA==}
+ resolution: {integrity: sha512-uuN0goWfxP22B7J/uAgBpOYNPttC+XVseYE+rSY5+rQ+YBeVz/VORw8WbmLVcqW78zNg5A4qnjNXYUWR3il2ig==}
+
resolution: {integrity: sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==}
engines: {node: '>=18'}
@@ -6194,6 +6248,18 @@ packages:
utf-8-validate:
optional: true
+ resolution: {integrity: sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==}
+ engines: {node: '>=10.0.0'}
+ peerDependencies:
+ bufferutil: ^4.0.1
+ utf-8-validate: '>=5.0.2'
+ peerDependenciesMeta:
+ bufferutil:
+ optional: true
+ utf-8-validate:
+ optional: true
+
resolution: {integrity: sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw==}
engines: {node: '>=18'}
@@ -7433,6 +7499,11 @@ snapshots:
modern-tar: 0.7.7
yargs: 18.1.0
+ '@puppeteer/[email protected]':
+ dependencies:
+ modern-tar: 0.8.5
+ yargs: 18.1.0
+
'@rolldown/[email protected]':
optional: true
@@ -7897,6 +7968,12 @@ snapshots:
mitt: 3.0.1
zod: 3.25.76
+ dependencies:
+ devtools-protocol: 0.0.1666840
+ mitt: 3.0.1
+ zod: 3.25.76
+
@@ -7980,6 +8057,8 @@ snapshots:
+
@@ -8492,6 +8571,8 @@ snapshots:
+
@@ -8600,6 +8681,20 @@ snapshots:
end-of-stream: 1.4.5
once: 1.4.0
+ dependencies:
+ '@puppeteer/browsers': 3.2.2
+ chromium-bidi: 17.0.2([email protected])
+ devtools-protocol: 0.0.1666840
+ typed-query-selector: 2.12.2
+ webdriver-bidi-protocol: 0.4.3
+ ws: 8.21.3
+ transitivePeerDependencies:
+ - bufferutil
+ - proxy-agent
+ - utf-8-validate
+ - yauzl
+
dependencies:
'@puppeteer/browsers': 3.1.0
@@ -9051,6 +9146,8 @@ snapshots:
+
dependencies:
ansi-styles: 6.2.3
@@ -9061,6 +9158,8 @@ snapshots:
+
dependencies:
is-wsl: 3.1.1
diff --git a/skills/hypit/references/environment/local-tools.md b/skills/hypit/references/environment/local-tools.md
index b21a060d..0ba82a2c 100644
--- a/skills/hypit/references/environment/local-tools.md
+++ b/skills/hypit/references/environment/local-tools.md
@@ -104,7 +104,7 @@ answers its health probe; `hypit doctor` then checks the selected Endpoint as pa
If local installation is incompatible with the machine, blocked by the network, or making no useful
progress within the user's available time, report the exact evidence and offer another Provider for
-the same capability. Repeated installation attempts are not a substitute for a working ear.
+the same capability. Continue independent reference or production work while that choice is resolved.
## Repair from the narrowest evidence
diff --git a/skills/hypit/references/production/browser-capture.md b/skills/hypit/references/production/browser-capture.md
new file mode 100644
index 00000000..2c9faa41
--- /dev/null
+++ b/skills/hypit/references/production/browser-capture.md
@@ -0,0 +1,104 @@
+# Capturing websites and authored HTML
+
+Read this when a real interface, product page or locally authored graphic should become picture
+material in the video. `hypit capture` supplies browser capture from the installed Distribution;
+the project's scripts describe the actual page interactions.
+
+Choose the material from its role. A screenshot preserves wording and a visible state. A long page
+can become a controlled scroll through Media Track's Sampling. A recording preserves interaction
+and changing page content when those changes are part of the demonstration. A local HTML file can
+produce a static card or graphic. [Graphic composition](../playbooks/craft/graphic-compositions.md)
+explains when editable component state is useful, and
+[compositing](../playbooks/craft/compositing.md) explains the screen's place in the frame.
+
+## Save a page or region
+
+```bash
+hypit capture screenshot https://example.com/product \
+ --viewport 540x960 --scale 2 --full-page --to assets/product-page.png
+
+hypit capture screenshot https://example.com/product \
+ --selector '#comparison' --to assets/comparison.png
+
+hypit capture screenshot ./assets/card.html \
+ --viewport 1080x300 --transparent --to assets/card.png
+```
+
+Use `--clip x,y,width,height` for a rectangular region in CSS pixels. A selector, clip or full-page
+capture chooses a different extent; the default captures the viewport. Viewport and device scale
+are separate: 540 × 960 at scale 2 produces a 1080 × 1920 viewport image. They are task choices;
+Puppeteer's device emulation is available in a script when mobile behavior or a user agent matters.
+
+The command waits for page load. `--wait-for <selector>` waits for a visible element, and `--wait-ms`
+adds a chosen delay. If content loads through scrolling or interaction, express that in a script.
+Watch the saved image to see whether it contains the intended evidence and is readable in its
+destination Frame.
+
+## Use ordinary page interactions
+
+For several captures, lazy loading, an authenticated page or a demonstration, put the actual
+interactions in a project `.mjs` file. This script needs no Puppeteer import:
+
+```js
+// scripts/capture-product.mjs
+export const options = {
+ launch: { defaultViewport: { width: 1280, height: 720, deviceScaleFactor: 1 } },
+};
+
+export default async ({ page, screenshot, record, args, log }) => {
+ const [url, destination] = args;
+ await page.goto(url);
+ await page.waitForSelector('#comparison', { visible: true });
+ await screenshot({ path: 'assets/comparison.png', selector: '#comparison' });
+
+ log('Recording the product interaction');
+ const recording = await record({ path: destination, fps: 30 });
+ await page.click('#show-example');
+ await page.waitForSelector('#example-result', { visible: true });
+ await recording.stop();
+};
+```
+
+```bash
+hypit capture run scripts/capture-product.mjs -- \
+ https://example.com/product assets/product-demo.mp4
+```
+
+The selectors above describe an example page; choose the real controls and meaningful start and end
+states of the page being captured. Use normal Puppeteer navigation, locators, input and evaluation
+to express the task. `browser` is also available for opening more pages; pass one as the second
+argument to `screenshot` or `record` to capture it. Returning finishes open recordings and closes
+the browser. Completed captures survive a later script failure.
+
+For local inputs beside the script, `new URL('../assets/card.html', import.meta.url).href` locates
+the file. Relative output paths follow the directory where the command runs. `args` contains the
+arguments after `--`; use `log` for progress. `--json` reports every completed helper output with its
+path and actual dimensions, plus recorded duration and frame rate. Output paths must be new.
+
+## Browser and recording choices
+
+Prepare the package's tested browser once with `hypit capture install-browser`. It uses Puppeteer's
+browser cache and leaves existing browsers in place. `--channel chrome` selects an installed Chrome; `--browser <executable>` selects another explicit compatible path. `--headed` opens a visible
+window. The script's `options.launch` accepts ordinary Puppeteer launch options, including a chosen
+`userDataDir` when a dedicated persistent browser profile is useful. CLI browser options override
+the script's choices. `--timeout-ms` sets page operation and navigation timeouts.
+
+Native page recordings require Chrome 153 or later, supplied by `install-browser`. They produce MP4;
+use an `.mp4` destination. `record({ path, audio: true })` includes page audio when the demonstration
+needs it; the default captures picture only. The browser performs encoding. `ffprobe` on `PATH`
+reads the saved file's actual dimensions and duration; `options.ffprobePath` can select another
+executable. `record` accepts Puppeteer's `RecordOptions`, including `fps` / `frameRate` as a maximum
+capture rate and `maxWidth` / `maxHeight` for output dimensions. Music, narration and effects added
+in the edit remain ordinary authored audio layers. The helper sets maximum dimensions from the
+viewport's device-pixel dimensions; Chrome determines the recorded size. Device scale can enlarge
+a screenshot without enlarging the recording. Use the saved video's reported dimensions when
+placing it in the composition.
+
+## Place the captured material
+
+Keep captures in project assets and record the source page and its purpose in the project notes.
+An image enters through `media:Image`; a recording enters through `media:Video` and the ordinary
+[normalization path](media.md). Place them with
+[Media Track](tracks.md#coverage-has-a-window-and-a-separate-playback-choice) and the Script's
+Selections or Moments as appropriate. Their visibility, crop, scroll and transitions belong to the
+composition, so those changes can reuse the captured file.