Merge remote-tracking branch 'origin/main' into fix/rename-nested-folder-references

This commit is contained in:
Miguel Ángel
2026-11-25 07:30:30 +00:00
188 changed files with 3454 additions and 567 deletions
+25
View File
@@ -91,6 +91,27 @@
]
}
},
{
"files": ["packages/*/src/**/*.ts"],
"excludeFiles": [
"**/*.test.ts",
"packages/parsers/src/linkedom.ts",
"packages/cli/src/**/*.ts"
],
"rules": {
"no-restricted-imports": [
"error",
{
"paths": [
{
"name": "linkedom",
"message": "Import from @hyperframes/parsers/linkedom: it writes <title> and <textarea> text so it can't close its element."
}
]
}
]
}
},
{
"files": ["packages/cli/src/**/*.ts"],
"excludeFiles": [
@@ -111,6 +132,10 @@
{
"name": "@clack/prompts",
"message": "Import prompts and spinners from packages/cli/src/ui/prompts.ts: it refuses to prompt when nobody can answer."
},
{
"name": "linkedom",
"message": "Import from @hyperframes/parsers/linkedom: it writes <title> and <textarea> text so it can't close its element."
}
]
}
+3 -3
View File
@@ -339,7 +339,7 @@
"devDependencies": {
"@types/node": "^25.0.10",
"typescript": "^5.0.0",
"vite": "^6.4.5",
"vite": "^6.4.6",
"vitest": "^4.1.12",
},
},
@@ -411,7 +411,7 @@
"tailwindcss": "^4.3.3",
"tsup": "^8.0.0",
"typescript": "^5.0.0",
"vite": "^6.4.5",
"vite": "^6.4.6",
"vitest": "^4.1.12",
"zustand": "^5.0.0",
},
@@ -2188,7 +2188,7 @@
"uuid": ["uuid@8.3.2", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="],
"vite": ["vite@6.4.5", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", "picomatch": "^4.0.2", "postcss": "^8.5.3", "rollup": "^4.34.9", "tinyglobby": "^0.2.13" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "jiti": ">=1.21.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-4enwjFfi4IwtEh0w+jPzpLVOFQiPHmmzPxcHXQOyEur47o6u0jE573DmGpjA+7irXoMLYRZD5ZaFUEneS3abPg=="],
"vite": ["vite@6.4.6", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", "picomatch": "^4.0.2", "postcss": "^8.5.3", "rollup": "^4.34.9", "tinyglobby": "^0.2.13" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "jiti": ">=1.21.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-RtsraAwEG68idOA6iUOoIpOlcSKROnf815aIq9qHTSrDNpLoBrBa12suyfcEd8qn0xwOVQI1Yhm1GbmTjF600A=="],
"vitest": ["vitest@4.1.12", "", { "dependencies": { "@vitest/expect": "4.1.12", "@vitest/mocker": "4.1.12", "@vitest/pretty-format": "4.1.12", "@vitest/runner": "4.1.12", "@vitest/snapshot": "4.1.12", "@vitest/spy": "4.1.12", "@vitest/utils": "4.1.12", "es-module-lexer": "^2.0.0", "expect-type": "^1.3.0", "magic-string": "^0.30.21", "obug": "^2.1.1", "pathe": "^2.0.3", "picomatch": "^4.0.3", "std-env": "^4.0.0-rc.1", "tinybench": "^2.9.0", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tinyrainbow": "^3.1.0", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "4.1.12", "@vitest/browser-preview": "4.1.12", "@vitest/browser-webdriverio": "^4.1.11", "@vitest/coverage-istanbul": "4.1.12", "@vitest/coverage-v8": "4.1.12", "@vitest/ui": "4.1.12", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/coverage-istanbul", "@vitest/coverage-v8", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "./vitest.mjs" } }, "sha512-5eWdz2yb3ajxWF3C8C4TjkXl7FGm3n2E/VlazALrQHzK7nYMSGFnCZto0bbPNl77AwkOZVLk0YnBAejUu0NiWA=="],
+2 -1
View File
@@ -31,7 +31,8 @@ through `hyperframes share --manage`.
Source uses the same portable project policy as Desktop: authored HTML, scripts,
styles, assets, and supported Studio edit metadata. Known credential filenames
(such as `.env`, `.npmrc`, and `*.pem`), dependency directories, chat
history, local sharing state, and recorded render outputs stay out.
history, local sharing state, and recorded render outputs stay out. Files ending in `.key` stay local,
including Keynote decks.
These are filename rules, not a secret scanner. `.gitignore` does not control
source capture. Other regular files can be included even if Git ignores them. For example,
+2 -2
View File
@@ -1,6 +1,6 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { findFfBinary, mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
import { findFfBinary, mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
import { assertLiteralMediaInput } from "@hyperframes/parsers/literal-media-input";
import {
decodableAudioStream,
@@ -26,7 +26,7 @@ function requiredBinary(name: "ffmpeg" | "ffprobe"): string {
}
function literalInputArgs(binary: string, file: string, inputArgs: readonly string[]) {
if (inputArgs.length === 0) return mediaInputFormatArgs(binary, file);
if (inputArgs.length === 0) return mediaInputArgs(binary, file);
assertLiteralMediaInput(file);
return inputArgs;
}
+2 -2
View File
@@ -11,7 +11,7 @@ import {
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { findFfBinary, mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
import { findFfBinary, mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
import { setTimeout as sleep } from "node:timers/promises";
import { downloadToFile } from "../../cloud/download.js";
@@ -174,7 +174,7 @@ async function encoded(path: string, dir: string, signal: AbortSignal): Promise<
await runFile(
ffmpeg,
[
...["-v", "error", "-y", ...mediaInputFormatArgs(ffmpeg, path), "-i", path],
...["-v", "error", "-y", ...mediaInputArgs(ffmpeg, path), "-i", path],
...["-map", `0:a:${audio.audioStream}`],
...["-vn", "-ac", "2", "-ar", "44100", "-b:a", "192k", out],
],
@@ -17,7 +17,7 @@ import { spawn } from "node:child_process";
import { randomUUID } from "node:crypto";
import { renameSync, rmSync } from "node:fs";
import { basename, dirname, extname, join } from "node:path";
import { mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
import { mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
import { findFFmpeg, findFFprobe, getFFmpegInstallHint } from "../browser/ffmpeg.js";
import { runCancellableProcess } from "../utils/cancellableProcess.js";
import { readFrames } from "./frameReader.js";
@@ -132,7 +132,7 @@ async function decoderTransposesDimensions(inputPath: string): Promise<boolean>
"-show_streams",
"-print_format",
"json",
...mediaInputFormatArgs(ffprobePath, inputPath),
...mediaInputArgs(ffprobePath, inputPath),
"--",
inputPath,
],
@@ -438,7 +438,7 @@ async function runPipeline(
const decoder = spawnFfmpeg(
ffmpegPath,
[
...["-loglevel", "error", ...mediaInputFormatArgs(ffmpegPath, inputPath), "-i", inputPath],
...["-loglevel", "error", ...mediaInputArgs(ffmpegPath, inputPath), "-i", inputPath],
...["-f", "rawvideo", "-pix_fmt", "rgb24", "-an", "-"],
],
"ffmpeg decoder",
@@ -1,4 +1,4 @@
import { DOMParser } from "linkedom";
import { DOMParser } from "@hyperframes/parsers/linkedom";
import { parse, walk } from "css-tree";
import { loadSharp } from "../utils/optionalPackages.js";
@@ -1,4 +1,4 @@
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
const FRAMEWORK_SRC_PATTERNS = [
/_next\/static\/chunks\/(main|framework|webpack|pages\/)/,
+1 -1
View File
@@ -14,7 +14,7 @@
* resize for raster. They answer "does this drawing carry its own backdrop", nothing more.
*/
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import { loadSharp } from "../utils/optionalPackages.js";
/** What a downloaded icon is, as a drawing. `unknown` when the format cannot be inspected. */
@@ -1,4 +1,12 @@
import { mkdirSync, mkdtempSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import {
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest";
@@ -72,7 +80,10 @@ describe("runPostExtraction", () => {
},
);
async function runWithFonts(read: () => unknown): Promise<void> {
async function runWithFonts(
read: () => unknown,
bodyHtml?: string,
): Promise<{ outputDir: string }> {
const root = mkdtempSync(join(tmpdir(), "hyperframes-post-extraction-"));
onTestFinished(() => rmSync(root, { recursive: true, force: true }));
const outputDir = join(root, "capture");
@@ -80,6 +91,7 @@ describe("runPostExtraction", () => {
mkdirSync(join(outputDir, dir), { recursive: true });
}
const state = createPartialCaptureState({ url: "https://example.com", outputDir });
if (bodyHtml !== undefined) state.extracted.bodyHtml = bodyHtml;
fonts.read = read;
await runPostExtraction({
state,
@@ -102,8 +114,23 @@ describe("runPostExtraction", () => {
fontDrops: noDrops(),
canWrite: () => true,
});
return { outputDir };
}
// fails without the fix: a captured site that carries the composition marker was saved with it, so Studio listed
// extracted/page.html as a composition and ran its scripts on its own origin
it("saves the captured page without the composition marker", async () => {
vi.spyOn(console, "error").mockImplementation(() => {});
const { outputDir } = await runWithFonts(
() => ({ files: [], families: [], unidentified: [] }),
`<div data-composition-id="x"><script>fetch("/api/projects")</script></div><i DATA-COMPOSITION-ID = 'y'></i>`,
);
const saved = readFileSync(join(outputDir, "extracted", "page.html"), "utf-8");
expect(saved).toContain(`<script>fetch("/api/projects")</script>`);
expect(saved).not.toMatch(/data-composition-id/i);
});
const printed = (spy: { mock: { calls: unknown[][] } }): string =>
spy.mock.calls.map((call) => call.map(String).join(" ")).join("\n");
@@ -87,6 +87,9 @@ export interface PostExtractionResult {
animationCatalog: CaptureResult["animationCatalog"];
}
const withoutCompositionMarker = (capturedHtml: string): string =>
capturedHtml.replace(/data-composition-id/gi, "data-captured-composition-id");
export async function runPostExtraction(input: PostExtractionInput): Promise<PostExtractionResult> {
let {
state,
@@ -289,7 +292,9 @@ export async function runPostExtraction(input: PostExtractionInput): Promise<Pos
// Persist a self-contained page recreation under extracted/, with images already inlined.
try {
const pageHtml = `<!doctype html>\n<html ${extracted.htmlAttrs || ""}>\n<head>\n${extracted.headHtml}\n</head>\n<body>\n${extracted.bodyHtml}\n</body>\n</html>\n`;
const pageHtml = withoutCompositionMarker(
`<!doctype html>\n<html ${extracted.htmlAttrs || ""}>\n<head>\n${extracted.headHtml}\n</head>\n<body>\n${extracted.bodyHtml}\n</body>\n</html>\n`,
);
state.pageHtml = pageHtml;
if (canWrite())
writeCaptureFileSync(join(outputDir, "extracted", "page.html"), pageHtml, "utf-8");
+1 -1
View File
@@ -21,7 +21,7 @@ import {
import { tmpdir } from "node:os";
import { basename, dirname, extname, join, posix, relative, resolve } from "node:path";
import { promisify } from "node:util";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import { parseAnimatedGifMetadata } from "@hyperframes/core";
import { rewriteAssetPath } from "@hyperframes/parsers/asset-paths";
import { templateContent } from "@hyperframes/parsers/sub-composition-validity";
+1 -1
View File
@@ -1,5 +1,5 @@
import { basename } from "node:path";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import {
readAuthoredDurationSeconds,
readMediaOffsetSeconds,
+1 -1
View File
@@ -13,7 +13,7 @@ export const examples: Example[] = [
];
import { existsSync, readFileSync } from "node:fs";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import { firstTemplateContent } from "@hyperframes/parsers/sub-composition-validity";
import { join, resolve, relative, sep } from "node:path";
import {
+2 -2
View File
@@ -23,7 +23,7 @@ import {
import { gsapCdnDist } from "@hyperframes/core/gsap-cdn";
import { defineCommand } from "../utils/defineCommand.js";
import type { Example } from "./_examples.js";
import { mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
import { mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
import { openSettledCompositionPage, runFfmpegOnce } from "../capture/captureCompositionFrame.js";
import { findFFmpeg } from "../browser/ffmpeg.js";
import { c } from "../ui/colors.js";
@@ -519,7 +519,7 @@ async function extractVideoFrameToBuffer(videoPath: string): Promise<Buffer | nu
"error",
"-ss",
"0",
...mediaInputFormatArgs(ffmpegPath, videoPath),
...mediaInputArgs(ffmpegPath, videoPath),
"-i",
videoPath,
"-frames:v",
+3 -3
View File
@@ -51,7 +51,7 @@ import { trackInitTemplate } from "../telemetry/events.js";
import { DEFAULT_MODEL, hasFFmpeg } from "../whisper/manager.js";
import { TRANSCRIPT_FILE } from "../whisper/transcriptFile.js";
import { initialModelForLanguage } from "../whisper/transcribe.js";
import { mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
import { mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
import { findFFmpeg, findFFprobe, getFFmpegInstallHint } from "../browser/ffmpeg.js";
import { VERSION } from "../version.js";
import {
@@ -135,7 +135,7 @@ function probeVideo(filePath: string): VideoMeta | undefined {
[
"-v",
"quiet",
...mediaInputFormatArgs(ffprobePath, filePath),
...mediaInputArgs(ffprobePath, filePath),
"-print_format",
"json",
"-show_format",
@@ -244,7 +244,7 @@ export function transcodeToMp4(inputPath: string, outputPath: string): Promise<b
const child = spawn(
ffmpegPath,
[
...mediaInputFormatArgs(ffmpegPath, inputPath),
...mediaInputArgs(ffmpegPath, inputPath),
"-i",
inputPath,
"-c:v",
+1 -1
View File
@@ -29,7 +29,7 @@ import {
import { ensureHfIds } from "@hyperframes/parsers/hf-ids";
import { defineCommand } from "../utils/defineCommand.js";
import { lintHyperframeHtml } from "@hyperframes/lint";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import type { Example } from "./_examples.js";
import { c } from "../ui/colors.js";
import { CliUsageError, failCommand, failUsage } from "../utils/commandResult.js";
+7 -11
View File
@@ -10,7 +10,7 @@ import {
isHdrColorSpace,
sdrCanvasColourFilters,
} from "@hyperframes/engine";
import { mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
import { mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
import { projectFolder } from "../utils/projectRecords.js";
import { screenshotOnceMore } from "../utils/screenshotOnceMore.js";
import { parseTimeoutMs } from "../utils/timeoutArg.js";
@@ -91,7 +91,7 @@ import {
type RateSpec,
terminalText,
} from "@hyperframes/core";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import { resolveProject } from "../utils/project.js";
import {
definitiveEntryMismatchComposition,
@@ -499,11 +499,7 @@ export async function probeContainingSourceFrameSeek(
const { stdout } = await runCancellableProcess(
ffprobe,
[
...[
"-v",
"error",
...mediaInputFormatArgs(ffprobe, videoPath, WALKED_BY_PROJECT_VIDEO_FILE),
],
...["-v", "error", ...mediaInputArgs(ffprobe, videoPath, WALKED_BY_PROJECT_VIDEO_FILE)],
...["-select_streams", "v:0", "-read_intervals", readIntervals],
...["-show_entries", entries, "-of", "json", "--", videoPath],
],
@@ -633,7 +629,7 @@ async function probeSeekLanding(
"error",
"-copyts",
"-noaccurate_seek",
...mediaInputFormatArgs(ffmpeg, videoPath, WALKED_BY_PROJECT_VIDEO_FILE),
...mediaInputArgs(ffmpeg, videoPath, WALKED_BY_PROJECT_VIDEO_FILE),
],
...["-ss", String(seek), "-i", videoPath],
...["-map", "0:v:0", "-c", "copy", "-frames:v", "1", "-f", "framecrc", "-"],
@@ -695,7 +691,7 @@ async function frameColour(
const read = (args: string[]) =>
runFfmpegOnce(
ffmpegPath,
[...mediaInputFormatArgs(ffmpegPath, videoPath, WALKED_BY_PROJECT_VIDEO_FILE), ...args],
[...mediaInputArgs(ffmpegPath, videoPath, WALKED_BY_PROJECT_VIDEO_FILE), ...args],
FFMPEG_EXTRACT_TIMEOUT_MS,
);
const probe = await read(firstFrameColourArgs(videoPath));
@@ -750,7 +746,7 @@ export async function extractVideoFrameToBuffer(
if (useVp9AlphaDecoder) args.push("-c:v", "libvpx-vp9");
if (seek.seek !== undefined) args.push("-ss", String(seek.seek));
args.push(
...mediaInputFormatArgs(ffmpegPath, videoPath, WALKED_BY_PROJECT_VIDEO_FILE),
...mediaInputArgs(ffmpegPath, videoPath, WALKED_BY_PROJECT_VIDEO_FILE),
"-i",
videoPath,
"-map",
@@ -817,7 +813,7 @@ export async function decodeFramesInOnePass(
const args = ["-hide_banner", "-loglevel", "error"];
if (useVp9AlphaDecoder) args.push("-c:v", "libvpx-vp9");
args.push(
...mediaInputFormatArgs(ffmpegPath, videoPath, WALKED_BY_PROJECT_VIDEO_FILE),
...mediaInputArgs(ffmpegPath, videoPath, WALKED_BY_PROJECT_VIDEO_FILE),
"-ss",
String(start),
"-i",
@@ -1,10 +1,10 @@
import { existsSync } from "node:fs";
import { isAbsolute, relative, resolve } from "node:path";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import { MEDIA_RENDER_ID_ATTR, naturalVideoSize, streamRotation } from "@hyperframes/core";
import { isPrivateFileUnder, isStudioPrivatePath } from "@hyperframes/core/safe-path";
import { isNotMediaPayload, type CaptureVideoMetadataHint } from "@hyperframes/engine";
import { mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
import { mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
import { findFFprobe } from "../browser/ffmpeg.js";
import { runCancellableProcess } from "../utils/cancellableProcess.js";
@@ -108,7 +108,7 @@ export function probeHeldVideo(
[
"-v",
"error",
...mediaInputFormatArgs(ffprobe, path, { playlists: true }),
...mediaInputArgs(ffprobe, path, { playlists: true }),
"-select_streams",
"v:0",
"-show_entries",
+1 -1
View File
@@ -1,4 +1,4 @@
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import { topLevelElements, trackKindOf } from "@hyperframes/parsers";
import { toDomNode } from "../timeline/domStructure.js";
import {
@@ -1,4 +1,4 @@
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import { createRuntimeStartTimeResolver } from "@hyperframes/core";
import { CliUsageError } from "../utils/commandResult.js";
export type SnapshotRange = [number, number];
+2 -2
View File
@@ -1,7 +1,7 @@
// How big the face is and where, ported from hf-media's face_size: OpenCV's frontal and profile Haar cascades on
// evenly spaced frames, graded by face height over frame height. A regenerated presenter keeps the likeness from
// FACE_HOLDS up; below FACE_FLOOR a video model cannot carry one at all (the harness's face-size eval, 2026-10-08).
import { mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
import { mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
import {
GUARDED_RUN_MS,
ffmpegBin,
@@ -56,7 +56,7 @@ export function minWindow(h: number, share: number): number {
}
function decode(info: VideoInfo, args: string[]): Buffer {
const formats = mediaInputFormatArgs(ffmpegBin(), info.path, { playlists: info.guarded });
const formats = mediaInputArgs(ffmpegBin(), info.path, { playlists: info.guarded });
if (!info.guarded) return runFfmpeg([...formats, ...args]);
try {
return runFfmpeg([...formats, ...args], undefined, undefined, GUARDED_RUN_MS);
+4 -4
View File
@@ -5,7 +5,7 @@ import { closeSync, existsSync, mkdirSync, openSync, readSync, rmSync } from "no
import { basename, dirname, join, resolve } from "node:path";
import { createStagingDir } from "@hyperframes/core/atomic-file";
import { renameWithRetry } from "@hyperframes/core/rename-retry";
import { mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
import { mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
import { assertLiteralMediaOutput } from "@hyperframes/parsers/literal-media-input";
import { findFFmpeg, findFFprobe, getFFmpegInstallHint } from "../browser/ffmpeg.js";
import { recordFolder } from "../utils/projectRecords.js";
@@ -68,7 +68,7 @@ export function runFfmpeg(args: string[], input?: Buffer, cwd?: string, timeout?
}
export function ffmpegInput(path: string, { playlists = false } = {}): string[] {
return [...mediaInputFormatArgs(ffmpegBin(), path, { playlists }), "-i", path];
return [...mediaInputArgs(ffmpegBin(), path, { playlists }), "-i", path];
}
export function ffmpegToFile(args: string[], out: string, input?: Buffer): string {
@@ -140,7 +140,7 @@ export function probeSeconds(path: string): number {
[
"-v",
"error",
...mediaInputFormatArgs(bin, path),
...mediaInputArgs(bin, path),
"-show_entries",
"format=duration",
"-of",
@@ -219,7 +219,7 @@ function startsWithMp4Header(path: string): boolean {
export function probeVideo(path: string, { guarded = false } = {}): VideoInfo {
if (!existsSync(path)) throw new Fix(`no file at ${path}`, missingFileFix(path));
const bin = ffprobeBin();
const formats = mediaInputFormatArgs(bin, path, { playlists: guarded });
const formats = mediaInputArgs(bin, path, { playlists: guarded });
let json: { streams?: ProbeStream[]; format?: { duration?: string } };
try {
json = JSON.parse(
@@ -0,0 +1,86 @@
import { randomBytes } from "node:crypto";
import { lstatSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
// Writes into a folder someone else may have filled: a link already at a name is replaced or refused, never followed.
/** Folder `rel` under `base`, made if missing; throws when any folder on the way is a link. */
export function ownFolder(base, rel) {
let dir = base;
// Each folder is looked at before it is made, so nothing is ever made through a link.
for (const part of rel.split(/[\\/]/).filter(Boolean)) {
dir = join(dir, part);
if (lstatSync(dir, { throwIfNoEntry: false })?.isSymbolicLink()) {
throw new Error(
`${dir} is a link; media is written only into real folders, so nothing was written there`,
);
}
mkdirSync(dir, { recursive: true });
}
return dir;
}
/** A new temp file beside `path` holding `content`, with a random name, created exclusively. */
export function writeTempBeside(path, content) {
// Same shape as core atomicTempPath, which Studio's project history skips.
const temp = `${path}.hf${randomBytes(3).toString("hex")}.tmp`;
try {
writeFileSync(temp, content, { flag: "wx" });
} catch (error) {
// EEXIST: the random name belongs to another writer, so it is left alone. A failed cleanup must not hide `error`.
if (error?.code !== "EEXIST") {
try {
rmSync(temp, { force: true });
} catch {}
}
throw error;
}
return temp;
}
/** Writes `content` to a temp file beside `path`, then renames it over: a link at `path` is replaced, not followed. */
export function replaceFile(path, content) {
publish(writeTempBeside(path, content), path);
}
/** As replaceFile, with `write(temp)` filling the temp file (an ffmpeg run, say); a throw leaves `path` as it was. */
export function replaceFileWith(path, write) {
const temp = writeTempBeside(path, "");
try {
write(temp);
} catch (error) {
rmSync(temp, { force: true });
throw error;
}
publish(temp, path);
}
function publish(temp, path) {
try {
renameRidingWindowsHolds(temp, path);
} catch (error) {
rmSync(temp, { force: true });
throw error;
}
}
// Windows refuses a rename for a moment while antivirus or a just-exited process still holds the file.
const WINDOWS_HOLD = new Set(["EPERM", "EACCES", "EBUSY"]);
const HOLD_BACKOFF_MS = [10, 20, 40, 80, 160, 320, 640];
function renameRidingWindowsHolds(from, to) {
for (let attempt = 0; ; attempt++) {
try {
return renameSync(from, to);
} catch (error) {
const held = process.platform === "win32" && WINDOWS_HOLD.has(error?.code);
if (!held || attempt >= HOLD_BACKOFF_MS.length) throw error;
sleepMs(HOLD_BACKOFF_MS[attempt]);
}
}
}
/** Sync sleep (no busy-spin). */
export function sleepMs(ms) {
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
}
@@ -1,15 +1,14 @@
// The standalone twin of assertLiteralMediaInput in packages/parsers/src/literalMediaInput.ts, for inputs and outputs; a test keeps them equal.
const PATTERN_IMAGE2_EXPANDS = /%\d*[d%*?[\]{}]/;
const WILDCARD_MAKES_ANY_PERCENT_A_PATTERN = /[*?[{]/;
const URL_SCHEME = /^[a-z][a-z0-9+.-]+:/i;
const FORWARDED = /^https?:/i;
/** ffmpeg's image2 reader or writer would use other files, folders included, than the one named. */
export function assertLiteralMediaPath(input) {
const local = !URL_SCHEME.test(input) || /^file:/i.test(input);
const pattern =
PATTERN_IMAGE2_EXPANDS.test(input) ||
(input.includes("%") && WILDCARD_MAKES_ANY_PERCENT_A_PATTERN.test(input));
if (!local || !pattern) return;
if (FORWARDED.test(input) || !pattern) return;
throw new Error(
`[FFmpeg] refused media path "${input.split(/[\\/]/).pop()}": a "%" followed by "d", another "%" or a wildcard, ` +
'with or without digits between, or a "%" and a wildcard (*, ?, [ or {) anywhere in the path, would make ffmpeg ' +
+3 -67
View File
@@ -8,13 +8,15 @@ import {
writeFileSync,
writeSync,
rmSync,
renameSync,
lstatSync,
realpathSync,
constants,
} from "node:fs";
import { randomBytes } from "node:crypto";
import { basename, join } from "node:path";
import { ownFolder, replaceFile, sleepMs, writeTempBeside } from "./link-safe-write.mjs";
export { ownFolder, replaceFile, writeTempBeside };
const MANIFEST_FILE = "manifest.jsonl";
const INDEX_FILE = "index.md";
@@ -93,22 +95,6 @@ export function ownTypeDir(projectDir, type) {
return ownFolder(ownMediaDir(projectDir), typeSubdir(type));
}
/** Folder `rel` under `base`, made if missing; throws when any folder on the way is a link. */
export function ownFolder(base, rel) {
let dir = base;
// Each folder is looked at before it is made, so nothing is ever made through a link.
for (const part of rel.split(/[\\/]/).filter(Boolean)) {
dir = join(dir, part);
if (lstatSync(dir, { throwIfNoEntry: false })?.isSymbolicLink()) {
throw new Error(
`${dir} is a link; media is written only into real folders, so nothing was written there`,
);
}
mkdirSync(dir, { recursive: true });
}
return dir;
}
/** Throws when `path` is a link. */
export function refuseLink(path) {
if (lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink()) {
@@ -116,51 +102,6 @@ export function refuseLink(path) {
}
}
/** A new temp file beside `path` holding `content`, with a random name, created exclusively. */
export function writeTempBeside(path, content) {
// Same shape as core atomicTempPath, which Studio's project history skips.
const temp = `${path}.hf${randomBytes(3).toString("hex")}.tmp`;
try {
writeFileSync(temp, content, { flag: "wx" });
} catch (error) {
// EEXIST: the random name belongs to another writer, so it is left alone. A failed cleanup must not hide `error`.
if (error?.code !== "EEXIST") {
try {
rmSync(temp, { force: true });
} catch {}
}
throw error;
}
return temp;
}
/** Writes `content` to a temp file beside `path`, then renames it over: a link at `path` is replaced, not followed. */
export function replaceFile(path, content) {
const temp = writeTempBeside(path, content);
try {
renameRidingWindowsHolds(temp, path);
} catch (error) {
rmSync(temp, { force: true });
throw error;
}
}
// Windows refuses a rename for a moment while antivirus or a just-exited process still holds the file.
const WINDOWS_HOLD = new Set(["EPERM", "EACCES", "EBUSY"]);
const HOLD_BACKOFF_MS = [10, 20, 40, 80, 160, 320, 640];
function renameRidingWindowsHolds(from, to) {
for (let attempt = 0; ; attempt++) {
try {
return renameSync(from, to);
} catch (error) {
const held = process.platform === "win32" && WINDOWS_HOLD.has(error?.code);
if (!held || attempt >= HOLD_BACKOFF_MS.length) throw error;
sleepMs(HOLD_BACKOFF_MS[attempt]);
}
}
}
export function appendRecord(projectDir, record) {
ownTypeDir(projectDir, record.type);
@@ -257,11 +198,6 @@ export function nextId(projectDir, type) {
return `${prefix}_${String(max + 1).padStart(3, "0")}`;
}
// Sync sleep (no busy-spin) for the allocation lock retry.
function sleepMs(ms) {
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
}
// Coarse per-project lock so concurrent resolves don't race on id allocation.
// ponytail: one lock file with a 15s stale-steal (a crashed holder can't wedge
// the project); fine for agent-scale concurrency — revisit if throughput needs
File diff suppressed because one or more lines are too long
@@ -125,7 +125,10 @@ describe("a project page opened by direct navigation", () => {
it("is answered sandboxed by this server", async () => {
const project = path.join(root, "project");
fs.writeFileSync(path.join(project, "index.html"), '<div data-composition-id="main"></div>');
fs.writeFileSync(path.join(project, "page.html"), "<script>document.title = 1</script>");
fs.writeFileSync(
path.join(project, "page.html"),
'<div data-composition-id="page"></div><script>document.title = 1</script>',
);
const id = encodeURIComponent(path.basename(project));
for (const file of ["page.html", "comp/page.html"]) {
const response = await server.app.request(`/api/projects/${id}/preview/${file}`, {
@@ -22,6 +22,7 @@ import {
fileContentVersion,
HistoryBusyError,
HistoryClosedError,
RANGE_NOT_RENDERED,
} from "@hyperframes/studio-server";
import { thumbnailSeekReadyInBrowser } from "@hyperframes/studio-server/screenshot-clip";
import { loadHyperframeRuntimeSource } from "@hyperframes/core";
@@ -586,6 +587,22 @@ describe("createStudioServer shutdown", () => {
await shutdownPromise;
});
it("fails a job that asks for a part of the film instead of rendering it whole", async () => {
let executed = false;
producerState.executeRenderJob = async () => {
executed = true;
};
server = createStudioServer({ projectDir: tmpProject() });
const job = server.adapter.startRender({
...startRenderOpts("job-range", join(tmpdir(), "part.mp4")),
range: { startSeconds: 2, endSeconds: 4 },
});
expect(job.status).toBe("failed");
expect(job.error).toBe(RANGE_NOT_RENDERED);
expect(executed).toBe(false);
});
const thumbnailOpts = () => ({
project: { id: "demo", dir: tmpProject(), title: "demo" },
compPath: "index.html",
+10
View File
@@ -91,6 +91,7 @@ import {
carriesOAuthReturn,
inertRefusal,
refuseOAuthReturn,
RANGE_NOT_RENDERED,
} from "@hyperframes/studio-server";
import { encoderJobOptions } from "@hyperframes/studio-server/encoder-options";
import { isLinkFreeWithinProject } from "@hyperframes/studio-server/safe-path";
@@ -697,6 +698,15 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
error: "Studio server is shutting down",
};
}
if (opts.range) {
return {
id: opts.jobId,
status: "failed",
progress: 0,
outputPath: opts.outputPath,
error: RANGE_NOT_RENDERED,
};
}
// The render POST is a request boundary like any other. Without this an
// already-open Studio tab keeps rendering under the posture cached when
// the server booted.
+3 -3
View File
@@ -1,5 +1,5 @@
import { existsSync } from "node:fs";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import { normalizeRateSpec, sourceTimeAt } from "@hyperframes/core";
import { silence } from "@hyperframes/core/audio-analysis";
import {
@@ -9,7 +9,7 @@ import {
type AudioElement,
type AudioMetadata,
} from "@hyperframes/engine";
import { findFfBinary, mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
import { findFfBinary, mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
import { decodeAudio } from "../audio/analysis/decode.js";
import { createProbeGate } from "../timeline/describeProject.js";
import { findingAtRoot } from "./checkFindings.js";
@@ -73,7 +73,7 @@ async function silentPart(
{
mono: true,
sampleRate: SILENCE_SAMPLE_RATE,
inputArgs: mediaInputFormatArgs(findFfBinary("ffmpeg") ?? "ffmpeg", path, {
inputArgs: mediaInputArgs(findFfBinary("ffmpeg") ?? "ffmpeg", path, {
playlists: true,
}),
},
+1 -1
View File
@@ -1,4 +1,4 @@
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
/**
* A privacy-preserving structural anatomy of a HyperFrames composition. The
+1 -1
View File
@@ -2,7 +2,7 @@ import { terminalText } from "@hyperframes/core/terminal-text";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { DISTRIBUTED_FPS, type DistributedFps, isDistributedFps } from "@hyperframes/core";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import { c } from "../ui/colors.js";
function getHtmlAttribute(element: Element, name: string): string | null {
@@ -1,5 +1,5 @@
import { quantizePreviewProxyBox, type PreviewProxyBox } from "@hyperframes/core";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
const DEFAULT_VIEWPORT = { width: 1920, height: 1080 } as const;
const MAX_VIEWPORT_DIMENSION = 4096;
+1 -1
View File
@@ -1,4 +1,4 @@
import { DOMParser } from "linkedom";
import { DOMParser } from "@hyperframes/parsers/linkedom";
/**
* Polyfill DOMParser on globalThis so @hyperframes/core's parseHtml works in Node.js.
+1 -1
View File
@@ -1,7 +1,7 @@
import { closeSync, openSync, readSync, realpathSync, statSync } from "node:fs";
import { dirname, isAbsolute, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import { isNonRelativeUrl } from "@hyperframes/core";
import { resolveCompositionSrc } from "@hyperframes/parsers/asset-resolution";
import { HF_COLOR_GRADING_ATTR } from "@hyperframes/core/color-grading";
+1 -1
View File
@@ -1,4 +1,4 @@
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
const number = (value: string | null | undefined): number | undefined => {
const parsed = Number(value);
+1 -1
View File
@@ -11,7 +11,7 @@ import {
type Stats,
statSync,
} from "node:fs";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import AdmZip from "adm-zip";
import type { Ignore } from "ignore";
import { projectIgnore } from "@hyperframes/lint";
+1 -1
View File
@@ -28,7 +28,7 @@
import { existsSync } from "node:fs";
import { readFile } from "node:fs/promises";
import { basename, dirname, resolve } from "node:path";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import { rewriteAssetPath } from "@hyperframes/parsers/asset-paths";
import {
cleanAssetUrl,
+3 -3
View File
@@ -1,5 +1,5 @@
import { execFileSync } from "node:child_process";
import { mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
import { mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
import { findFFmpeg, findFFprobe } from "../browser/ffmpeg.js";
import { c } from "../ui/colors.js";
@@ -87,7 +87,7 @@ function probeWebmAlpha(filePath: string): WebmAlphaProbe {
"stream=codec_name:stream_tags=alpha_mode",
"-of",
"json",
...mediaInputFormatArgs(ffprobePath, filePath),
...mediaInputArgs(ffprobePath, filePath),
"--",
filePath,
],
@@ -149,7 +149,7 @@ export function sampledAlphaIsFullyOpaque(filePath: string): boolean | undefined
"error",
"-c:v",
"libvpx-vp9",
...mediaInputFormatArgs(ffmpegPath, filePath),
...mediaInputArgs(ffmpegPath, filePath),
"-i",
filePath,
"-frames:v",
+1 -1
View File
@@ -3,7 +3,7 @@ import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
import { readJsonFileText } from "../utils/jsonFlag.js";
import { extname, join } from "node:path";
import { parseExpressionAt, tokenizer } from "acorn";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
export interface Word {
/** Stable identifier for referencing this word in overrides and compositions.
+5 -5
View File
@@ -36,7 +36,7 @@ import { parseWhisperJson, type Word } from "./normalize.js";
import { emitWords } from "./progress.js";
import { probeAudio } from "../audio/analysis/decode.js";
import { decodableAudioStream } from "@hyperframes/parsers/media-streams";
import { mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
import { mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
export { initialModelForLanguage };
@@ -185,7 +185,7 @@ export function getMediaDurationSeconds(filePath: string): number | null {
"format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
...mediaInputFormatArgs(ffprobePath, filePath),
...mediaInputArgs(ffprobePath, filePath),
"--",
filePath,
]);
@@ -381,7 +381,7 @@ async function extractAudio(videoPath: string, signal?: AbortSignal): Promise<st
await runFfmpeg(
ffmpegPath,
[
...mediaInputFormatArgs(ffmpegPath, videoPath),
...mediaInputArgs(ffmpegPath, videoPath),
"-i",
videoPath,
"-map",
@@ -428,7 +428,7 @@ function isWav16kMono(filePath: string): boolean {
"-print_format",
"json",
"-show_streams",
...mediaInputFormatArgs(ffprobePath, filePath),
...mediaInputArgs(ffprobePath, filePath),
"--",
filePath,
]);
@@ -458,7 +458,7 @@ async function prepareAudio(audioPath: string, signal?: AbortSignal): Promise<st
await runFfmpeg(
ffmpegPath,
[
...mediaInputFormatArgs(ffmpegPath, audioPath),
...mediaInputArgs(ffmpegPath, audioPath),
"-i",
audioPath,
"-ar",
+4
View File
@@ -646,6 +646,10 @@ const PRESETS_BY_ID = new Map<string, HfColorGradingPreset>(
const VARIABLE_REF_RE = /^\$(?:\{([A-Za-z0-9_.:-]+)\}|([A-Za-z0-9_.:-]+))$/;
export function isHfColorGradingVariableRef(value: unknown): boolean {
return typeof value === "string" && VARIABLE_REF_RE.test(value.trim());
}
const ADJUST_LIMITS: Record<HfColorGradingAdjustKey, { min: number; max: number }> = {
exposure: { min: -2, max: 2 },
contrast: { min: -1, max: 1 },
@@ -0,0 +1,51 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { bundleToSingleHtml } from "./htmlBundler";
const READ_UNLIKE_BROWSER = /can't be read the way a browser reads them/;
const ICON = "<svg><title><!-- </title><img src=x onerror=f()> --></title></svg>";
const root = (body: string) =>
`<!DOCTYPE html><html><head></head><body><div data-composition-id="main" data-width="320" data-height="180">${body}</div></body></html>`;
async function bundle(files: Record<string, string>): Promise<string> {
const dir = mkdtempSync(join(tmpdir(), "hf-foreign-text-"));
try {
for (const [path, html] of Object.entries(files)) {
mkdirSync(join(dir, path, ".."), { recursive: true });
writeFileSync(join(dir, path), html);
}
return await bundleToSingleHtml(dir);
} finally {
rmSync(dir, { recursive: true, force: true });
}
}
// fails without the fix: the preview and render bundle served the title's hidden img as a live element.
describe("bundleToSingleHtml with markup hidden in an svg title", () => {
it("refuses it in the root composition", async () => {
await expect(bundle({ "index.html": root(`<div class="clip">${ICON}</div>`) })).rejects.toThrow(
READ_UNLIKE_BROWSER,
);
});
it("refuses it in a sub-composition", async () => {
const sub = `<template><div data-composition-id="sub" data-width="320" data-height="180">${ICON}</div></template>`;
const host =
'<div data-composition-id="sub" data-composition-src="compositions/sub.html" data-start="0" data-duration="1"></div>';
await expect(
bundle({ "index.html": root(host), "compositions/sub.html": sub }),
).rejects.toThrow(READ_UNLIKE_BROWSER);
});
it("still bundles an svg whose title is plain text", async () => {
const html = await bundle({
"index.html": root(
'<svg viewBox="0 0 4 4"><title>Icon 1 &lt; 2</title><circle r="2"></circle></svg>',
),
});
expect(html).toContain("<title>Icon 1 &lt; 2</title>");
});
});
+1 -1
View File
@@ -1,6 +1,6 @@
import { acceleratedCanvasTrackerSource } from "../pageMotionBlur.js";
import { findSceneTemplate, templateContent } from "@hyperframes/parsers/sub-composition-validity";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import {
escapeInlineScriptSource,
indexOfLower,
@@ -1,4 +1,4 @@
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
export interface HtmlParityComposition {
id: string;
@@ -1,4 +1,4 @@
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import { HF_AUDIO_FX_ATTR } from "../audioFx";
import { locateSceneRoot } from "./htmlDocument";
+1 -1
View File
@@ -2,7 +2,7 @@
* (linkedom): unknown elements and attributes are dropped by default rather than pattern-matched
* as dangerous, so a new SVG feature can't reopen a class of bug the way regex denylisting did.
*/
import { DOMParser } from "linkedom";
import { DOMParser } from "@hyperframes/parsers/linkedom";
import {
SVG_ATTRIBUTES as SAFE_ATTRIBUTES,
SVG_ELEMENTS as SAFE_ELEMENTS,
+1 -1
View File
@@ -1,4 +1,4 @@
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
export type PageDocument = ReturnType<typeof parseHTML>["document"];
+1 -1
View File
@@ -1,4 +1,4 @@
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import { sanitizeRichTextChildren } from "../utils/richTextSanitize";
function escape(value: string): string {
+3 -3
View File
@@ -1,6 +1,6 @@
import { execFileSync } from "node:child_process";
import { basename, extname } from "node:path";
import { mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
import { mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
const IMAGE_EXTENSIONS = new Set([
".jpg",
@@ -116,7 +116,7 @@ function probeMedia(mediaPath: string, ffprobePath: string): GradeMediaProbe {
[
"-v",
"error",
...mediaInputFormatArgs(ffprobePath, mediaPath),
...mediaInputArgs(ffprobePath, mediaPath),
"-select_streams",
"v:0",
"-show_entries",
@@ -322,7 +322,7 @@ function readSignalStats(
"-nostdin",
"-v",
"error",
...mediaInputFormatArgs(ffmpegPath, mediaPath),
...mediaInputArgs(ffmpegPath, mediaPath),
...keyframeSeek,
"-i",
mediaPath,
@@ -1,4 +1,6 @@
import { gsap as realGsap } from "gsap";
import { afterEach, describe, expect, it, vi } from "vitest";
import { drawDrafts } from "../editingDraft";
import { handleFor } from "../editingHandles";
import { gsapSet, parseGsapSet } from "./gsapSet";
@@ -45,4 +47,22 @@ describe("gsap-set", () => {
expect(parseGsapSet({ handle: "#box", props: { x: 1 } })).toBeNull();
expect(parseGsapSet({ handle, props: { x: 1 }, extra: true })).toBeNull();
});
// fails without the fix: the draft's end put the layer's CSS translate back under the x/y committed from it, so a
// sealed resize handed to GSAP drew 50 px off (translate 40px 30px) where an open preview leaves translate none.
it.each(["keep-size", "restore"] as const)(
"leaves the CSS translate GSAP's committed x/y now carry cleared when the draft ends (%s)",
(end) => {
Object.assign(window, { gsap: realGsap });
const el = box();
el.style.translate = "40px 30px";
const handle = handleFor(el);
drawDrafts([{ handle, translate: { x: -10, y: -4, route: "gsap" }, size: null }]);
gsapSet({ handle, props: { x: -10.073, y: -3.715 } });
drawDrafts([{ handle, end }]);
expect(el.style.translate).toBe("none");
},
);
});
@@ -170,7 +170,7 @@ describe("patch-tweens ending a gesture's draft", () => {
expect(reply).toEqual({ patched: true });
expect(set).toHaveBeenCalledExactlyOnceWith(element, { x: 130, y: 80 });
expect(element.style.translate).toBe("");
expect(element.style.translate).toBe("none");
});
it("leaves a live draft alone when the patch ends none", () => {
+61 -5
View File
@@ -6,6 +6,7 @@ import { handleFor } from "./editingHandles";
afterEach(() => {
document.body.innerHTML = "";
document.head.innerHTML = "";
delete (window as { gsap?: unknown }).gsap;
});
@@ -182,10 +183,20 @@ describe("moves through GSAP", () => {
function gsapHeld() {
const { element, handle } = card("translate: 4px 2px; width: 50px");
const position = { x: 40, y: 30 };
(window as { gsap?: unknown }).gsap = {
getProperty: (_: Element, axis: "x" | "y") => position[axis],
// Like real GSAP, the first read folds the CSS translate into x/y and leaves translate none.
const gsap = {
getProperty: (target: HTMLElement, axis: "x" | "y") => {
if (target.style.translate !== "none") {
const [x = 0, y = 0] = shown(target);
Object.assign(position, { x: position.x + x, y: position.y + y });
target.style.setProperty("translate", "none");
}
return position[axis];
},
set: (_: Element, props: Partial<typeof position>) => Object.assign(position, props),
};
(window as { gsap?: unknown }).gsap = gsap;
gsap.getProperty(element, "x"); // the press reads GSAP's x/y before any draft draws
const move = (x: number, y: number) =>
drawDrafts([{ handle, translate: { x, y, route: "gsap" }, size: null }]);
return { element, handle, position, move };
@@ -202,14 +213,59 @@ describe("moves through GSAP", () => {
const { element, handle, position, move } = gsapHeld();
move(30, 36);
drawDrafts([{ handle, end: "restore" }]);
expect([position, element.style.translate]).toEqual([{ x: 40, y: 30 }, "4px 2px"]);
expect([position, element.style.translate]).toEqual([{ x: 44, y: 32 }, "none"]);
});
it("leaves GSAP where the drag drew it when the draft ends keeping its size", () => {
const { element, handle, position, move } = gsapHeld();
move(30, 36);
drawDrafts([{ handle, end: "keep-size" }]);
expect([position, element.style.translate]).toEqual([{ x: 30, y: 36 }, "4px 2px"]);
expect([position, element.style.translate]).toEqual([{ x: 30, y: 36 }, "none"]);
});
// fails without the fix: a sealed resize saved as GSAP x/y over a stylesheet translate drew 50 px off after the
// drop, because the end put back the press's empty inline translate over the none GSAP's soft reload had set.
it("keeps the translate GSAP folded off when a soft reload set it before the end", () => {
document.head.innerHTML = "<style>#card { translate: 40px 30px }</style>";
const { element, handle } = card("width: 50px");
(window as { gsap?: unknown }).gsap = { getProperty: () => 0, set: () => {} };
drawDrafts([{ handle, translate: { x: -50, y: -33 }, size: { width: 80, height: 40 } }]);
element.style.setProperty("translate", "none");
drawDrafts([{ handle, end: "keep-size" }]);
expect([getComputedStyle(element).translate, element.style.width]).toEqual(["none", "80px"]);
});
it("puts back a CSS-placed layer's translate when GSAP is loaded but never moved it", () => {
document.head.innerHTML = "<style>#card { translate: 40px 30px }</style>";
const { element, handle } = card("width: 50px");
(window as { gsap?: unknown }).gsap = { getProperty: () => 0, set: () => {} };
drawDrafts([{ handle, translate: { x: -50, y: -33 }, size: { width: 80, height: 40 } }]);
drawDrafts([{ handle, end: "keep-size" }]);
expect([getComputedStyle(element).translate, element.style.width]).toEqual([
"40px 30px",
"80px",
]);
});
it("keeps translate none after a GSAP-route draft when GSAP folded a stylesheet translate", () => {
document.head.innerHTML = "<style>#card { translate: 40px 30px }</style>";
const { element, handle } = card("width: 50px");
const fold = (target: HTMLElement) => target.style.setProperty("translate", "none");
(window as { gsap?: unknown }).gsap = {
getProperty: (t: HTMLElement) => (fold(t), 0),
set: () => {},
};
drawDrafts([
{ handle, translate: { x: 10, y: 0, route: "gsap" }, size: { width: 80, height: 40 } },
]);
drawDrafts([{ handle, end: "keep-size" }]);
expect(getComputedStyle(element).translate).toBe("none");
});
// fails without the fix: restore compared GSAP's x/y with the drawn one, so a later set to that same value, or one
@@ -234,7 +290,7 @@ describe("moves through GSAP", () => {
move(30, 36);
gsapSet({ handle, props: { x: 25 } });
drawDrafts([{ handle, end: "restore" }]);
expect(position).toEqual({ x: 25, y: 30 });
expect(position).toEqual({ x: 25, y: 32 });
});
// fails without the fix: the hold dropped only when the whole batch landed, so a restore after a batch with a missed
+29 -8
View File
@@ -30,6 +30,7 @@ interface Before {
/** GSAP's rotation before the first GSAP turn drawn, to put back on "restore". */
gsapRotation?: number;
gsapPosition?: { x: number; y: number };
drawnTranslate?: string;
drewTransform?: boolean;
propsSet?: string[];
putMarkBack?: () => void;
@@ -134,23 +135,31 @@ export function movedTranslate(
type DraftTranslate = NonNullable<Extract<EditingDraft, { translate: unknown }>["translate"]>;
function writeDrawnTranslate(element: Styled, saved: Before, value: string): void {
element.style.setProperty("translate", value);
saved.drawnTranslate = element.style.getPropertyValue("translate");
}
function drawTranslate(element: Styled, offset: DraftTranslate): void {
const saved = beforeOf(element);
if (offset.route !== "gsap")
return void element.style.setProperty("translate", movedTranslate(saved.translate, offset));
return writeDrawnTranslate(element, saved, movedTranslate(saved.translate, offset));
const gsap = frameGsap();
const read = (axis: string) => Number(gsap?.getProperty?.(element, axis)) || 0;
saved.gsapPosition ??= { x: read("x"), y: read("y") };
element.style.setProperty("translate", "none");
writeDrawnTranslate(element, saved, "none");
gsap?.set?.(element, { x: offset.x, y: offset.y });
}
export function rebaseDrawnPosition(element: Element, props: Record<string, unknown>): void {
const position = before.get(element)?.gsapPosition;
for (const axis of ["x", "y"] as const) {
const value = props[axis];
if (position && typeof value === "number" && Number.isFinite(value)) position[axis] = value;
}
const saved = before.get(element);
const moved = (["x", "y"] as const).filter((axis) => Number.isFinite(props[axis]));
if (!moved.length || !isStylableElement(element)) return;
if (!saved) element.style.setProperty("translate", "none");
for (const entry of saved?.inline ?? [])
if (entry[0] === "translate") [entry[1], entry[2]] = ["none", ""];
for (const axis of moved)
if (saved?.gsapPosition) saved.gsapPosition[axis] = props[axis] as number;
}
function restoreGsapPosition(element: Styled): void {
@@ -227,6 +236,18 @@ function clearProps(element: Styled, saved: Before): void {
putLiveDraftsBack();
}
function settleTranslateUnderGsap(element: Styled): void {
restore(element, ["translate"]);
const under = getComputedStyle(element).getPropertyValue("translate");
if (under && under !== "none") element.style.setProperty("translate", "none");
}
function dropDrawnTranslate(element: Styled, saved: Before): void {
if (saved.gsapPosition !== undefined) return settleTranslateUnderGsap(element);
if (element.style.getPropertyValue("translate") === saved.drawnTranslate)
restore(element, ["translate"]);
}
function end(element: Styled, ending: EditingDraftEnd): boolean {
const saved = before.get(element);
if (!saved || ("draft" in ending && ending.draft !== saved.draft)) return false;
@@ -237,7 +258,7 @@ function end(element: Styled, ending: EditingDraftEnd): boolean {
restoreGsapPosition(element);
restoreGsapRotation(element);
}
if (ending.end === "keep-size") restore(element, ["translate"]);
if (ending.end === "keep-size") dropDrawnTranslate(element, saved);
before.delete(element);
return ending.end === "restore";
}
@@ -159,13 +159,15 @@ describe("gesture start", () => {
expect(card.getAttribute("style")).toBe("translate: 10px 20px;");
});
it("leaves GSAP out of an element it does not move, without asking it for x", () => {
// fails without the fix: a sealed resize handed to GSAP started a layer GSAP does not move at x/y 0, 0.
it("reads GSAP's x/y for an element it does not move, without GSAP taking it over", () => {
const card = turnedCard("");
const getProperty = gsapWith([tween(document.body, { x: 10 }, 1)]);
gsapWith([tween(document.body, { x: 10 }, 1)], { x: 40, y: 30 });
const [start] = gestureStart([handleFor(card)]).elements;
expect(start!.gsap).toBeNull();
expect(getProperty).not.toHaveBeenCalled();
expect(start!.gsapAt).toEqual({ x: 40, y: 30 });
expect(card.getAttribute("style")).toBe("");
expect("_gsap" in card).toBe(false);
});
it.each<[string, (card: HTMLElement) => Tween, boolean]>([
@@ -29,8 +29,9 @@ export interface EditingGestureStart extends EditingElementGeometry {
move: { a: number; b: number; c: number; d: number } | null;
/** Frame px its centre moves per px of drawn width, `a, b`, and height, `c, d`; null when it has no box. */
grow: { a: number; b: number; c: number; d: number } | null;
/** Set when GSAP owns its position: its x/y now, and whether a tween with a duration moves it. */
/** Set when GSAP owns its position: x/y, whether a tween moves it. `gsapAt`: read when null; 0, 0 with no GSAP. */
gsap: { x: number; y: number; moving: boolean; drawsTranslate: true } | null;
gsapAt: { x: number; y: number };
/** GSAP's rotation now when it owns the element's turn; null when it turns by its own CSS `rotate`. */
gsapRotation: number | null;
cssRotation: CssRotationStart | null;
@@ -263,6 +264,10 @@ export function gestureStart(handles: readonly EditingElementHandle[]): {
move: measureMoveResponse(element),
grow: measureGrowResponse(element, geometry.layout),
gsap: gsapPosition(element),
gsapAt: withoutGsapTakeover(element, () => ({
x: readGsap(element, "x"),
y: readGsap(element, "y"),
})),
gsapRotation: rotation,
cssRotation: rotation === null ? readCssRotationStart(element as HTMLElement) : null,
planar: planarOf(element),
+33
View File
@@ -3747,6 +3747,39 @@ describe("initSandboxRuntimeModular", () => {
expect(seekCalls).toEqual([{ time: 2, suppressEvents: false }]);
});
// A sealed frame gets each seek as its own message, so Studio re-renders it with one seek to the time it shows.
const rootSeeking = (children?: unknown[]) => {
document.body.innerHTML = `<div data-composition-id="main" data-root="true" data-start="0" data-duration="10" data-width="1920" data-height="1080"></div>`;
const seekCalls: Array<{ time: number; suppressEvents?: boolean }> = [];
const rootTimeline = createMockTimeline(10);
const originalTotalTime = rootTimeline.totalTime;
rootTimeline.totalTime = (time: number, suppressEvents?: boolean) => {
if (time !== undefined) seekCalls.push({ time, suppressEvents });
return originalTotalTime?.(time, suppressEvents);
};
if (children) Object.assign(rootTimeline, { getChildren: () => children });
window.__timelines = { main: rootTimeline };
initSandboxRuntimeModular();
window.__player?.seek(2);
seekCalls.length = 0;
window.__player?.seek(2);
return seekCalls;
};
it("redraws the root timeline on a seek to the time it already shows", () => {
expect(rootSeeking()).toEqual([
{ time: 2, suppressEvents: false },
{ time: 1.999, suppressEvents: true },
{ time: 2, suppressEvents: true },
]);
});
it("does not redraw a root timeline holding a zero-duration callback on a seek to its own time", () => {
const callback = { vars: { onComplete: () => {} }, duration: () => 0, totalDuration: () => 0 };
// Known limit: a redraw would fire the callback again, so only the seek itself lands.
expect(rootSeeking([callback])).toEqual([{ time: 2, suppressEvents: false }]);
});
it("keeps a later root tween's value over a nested scene the root already drew", () => {
document.body.innerHTML = `<div data-composition-id="main" data-root="true" data-start="0" data-duration="2" data-width="1920" data-height="1080"><div data-composition-id="child" data-start="0" data-duration="2"><div id="box"></div></div></div>`;
const box = document.getElementById("box")!;
+1 -1
View File
@@ -5,7 +5,7 @@ import { closeSync, existsSync, mkdirSync, openSync, rmSync, writeFileSync } fro
import { renameWithRetry } from "@hyperframes/core/rename-retry";
import { removeScratch } from "@hyperframes/core/remove-scratch";
import { join, dirname, isAbsolute, relative } from "path";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import {
extractAudioMetadata,
ffmpegSeekSeconds,
@@ -165,13 +165,16 @@ describe("classifyPageError", () => {
});
// initializeSession registers its listeners before the incomplete fake session makes it throw.
async function listenedSession(memo: SubTimelineWaitMemo = {}) {
async function listenedSession(
memo: SubTimelineWaitMemo = {},
send: (method: string) => Promise<unknown> = async () => ({}),
) {
const runtimeListeners = new Map<string, (event: unknown) => void>();
const pageListeners = new Map<string, (event: unknown) => void>();
const listen =
(listeners: typeof pageListeners) => (event: string, listener: (event: unknown) => void) =>
listeners.set(event, listener);
const client = { on: listen(runtimeListeners), send: async () => ({}) };
const client = { on: listen(runtimeListeners), send };
const page = { on: listen(pageListeners), createCDPSession: async () => client };
const session = {
page,
@@ -273,6 +276,38 @@ describe("classifyPageError", () => {
}
});
// fails without the fix: every throw turned the debugger on and downloaded the whole script again
it("looks up a throw site once per distinct error, for a few errors in all, however often the page throws", async () => {
const sent: string[] = [];
const scriptSource = `${"// filler\n".repeat(1_000_000)}document.getElementById("hero").textContent = 1;`;
const { session, runtimeListeners } = await listenedSession({}, async (method) => {
sent.push(method);
return method === "Debugger.getScriptSource" ? { scriptSource } : {};
});
const frame = { url: named, scriptId: "7", lineNumber: 1_000_000, columnNumber: 9 };
const throwAt = (message: string) =>
runtimeListeners.get("Runtime.exceptionThrown")?.({
exceptionDetails: {
...thrown(`TypeError: ${message}`, named, []),
stackTrace: { callFrames: [frame as Protocol.Runtime.CallFrame] },
},
});
for (let n = 0; n < 1_000; n++) throwAt("hero is null");
for (let n = 0; n < 1_000; n++) throwAt(`step ${n} is null`);
expect(sent.filter((method) => method === "Debugger.enable")).toHaveLength(10);
await vi.waitFor(() =>
expect(sent.filter((method) => method === "Debugger.disable")).toHaveLength(10),
);
expect(sent.filter((method) => method === "Debugger.getScriptSource")).toHaveLength(10);
const hero = session.pageErrors.filter((error) => error.includes("hero is null"));
expect(hero).toEqual([
`runtime-error:TypeError: hero is null [thrown at: ${named}:1000001:10, getElementById("hero")]`,
]);
expect(session.pageErrors.filter((error) => error.includes("[thrown at:"))).toHaveLength(10);
expect(session.pageErrors).toHaveLength(50);
});
it("classifies a script by its whole URL before keeping a cut copy", async () => {
const { session, pageListeners } = await listenedSession();
const url = `https://${"a".repeat(2_100)}.example.com/x.js`;
+8 -2
View File
@@ -241,6 +241,7 @@ export interface CaptureSession {
scriptLoadCauses?: ScriptLoadCause[];
/** Uncaught page errors; a timed-out timeline wait with any of these becomes a script failure. */
pageErrors: string[];
throwSiteLookups?: Set<string>;
/** True once this session honoured `options.strictVariables`: the check ran and passed. */
strictVariablesChecked?: boolean;
/** The first VFX chain error; its frames would lack the effect, so it stops the render. */
@@ -596,6 +597,7 @@ const CAPTURE_SESSION_CLOSE_TIMEOUT_MS = 5_000;
const PAGE_TEXT_MAX_CHARS = 2_000;
const PAGE_LIST_MAX = 50;
const THROW_SITE_LOOKUP_MAX = 10;
const CUT_NOTE_MAX_CHARS = 40;
@@ -3229,10 +3231,14 @@ export async function initializeSession(session: CaptureSession): Promise<void>
const runtimeClient = await getCdpSession(page);
runtimeClient.on("Runtime.exceptionThrown", ({ exceptionDetails }) => {
const error = classifyPageError(exceptionDetails, projectScripts);
recordPageError(session, error);
if (!error) return;
// Recorded first so fail-fast sees it; the throw site is appended once the source is fetched.
const kept = boundedPageText(error);
const lookedUp = (session.throwSiteLookups ??= new Set());
if (lookedUp.has(kept)) return;
// Recorded first so fail-fast sees it; the throw site is appended once the source is fetched.
recordPageError(session, error);
if (lookedUp.size >= THROW_SITE_LOOKUP_MAX || !session.pageErrors.includes(kept)) return;
lookedUp.add(kept);
void describeThrowSite(runtimeClient, exceptionDetails, projectScripts).then((site) => {
const i = session.pageErrors.indexOf(kept);
if (!site || i < 0) return;
@@ -15,11 +15,15 @@ import {
const BYTES_PER_MIB = 1024 * 1024;
const CGROUP_V2_MEMORY_MAX_PATH = "/sys/fs/cgroup/memory.max";
const CGROUP_V1_MEMORY_LIMIT_PATH = "/sys/fs/cgroup/memory/memory.limit_in_bytes";
const CGROUP_V2_CONTROLLERS_PATH = "/sys/fs/cgroup/cgroup.controllers";
const CGROUP_V1_CPU_QUOTA_PATH = "/sys/fs/cgroup/cpu/cpu.cfs_quota_us";
const CGROUP_V1_CPU_PERIOD_PATH = "/sys/fs/cgroup/cpu/cpu.cfs_period_us";
type SystemMemoryModule = typeof import("./systemMemory.js");
type MockSystemMemoryOptions = {
availableParallelism?: number;
cgroupVersion?: 1 | 2;
hostCpus?: number;
files?: Record<string, string>;
hostTotalMb?: number;
@@ -46,14 +50,20 @@ async function withSystemMemoryMocks(
): Promise<void> {
const {
availableParallelism = 32,
cgroupVersion = 2,
hostCpus = 32,
files = {},
files: layoutFiles = {},
hostTotalMb = 32768,
platform = "linux",
readErrors = {},
onRead,
throwOnFileRead = false,
} = options;
// The same object, so a test can change a file between probes.
const files =
cgroupVersion === 2
? Object.assign(layoutFiles, { [CGROUP_V2_CONTROLLERS_PATH]: "cpu memory" })
: layoutFiles;
const restorePlatform = stubPlatform(platform);
vi.resetModules();
@@ -198,6 +208,58 @@ describe("getCgroupCpuLimit", () => {
expect(getCgroupCpuLimit()).toBeNull(),
);
});
it("reads the quota over its period on a cgroup v1 host", async () => {
await withSystemMemoryMocks(
{
cgroupVersion: 1,
files: { [CGROUP_V1_CPU_QUOTA_PATH]: "200000", [CGROUP_V1_CPU_PERIOD_PATH]: "100000" },
},
({ getCgroupCpuLimit }) => expect(getCgroupCpuLimit()).toBe(2),
);
});
});
describe("a cgroup v2 host with no limit at its root", () => {
// On v2, /sys/fs/cgroup/cpu and /sys/fs/cgroup/memory are child cgroups, not v1 controllers.
const unreadable = Object.assign(new Error("permission denied"), { code: "EACCES" });
it("never reads v1 paths, so finds no limit and warns about nothing", async () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const readCalls: string[] = [];
await withSystemMemoryMocks(
{
readErrors: {
[CGROUP_V1_CPU_QUOTA_PATH]: unreadable,
[CGROUP_V1_CPU_PERIOD_PATH]: unreadable,
[CGROUP_V1_MEMORY_LIMIT_PATH]: unreadable,
},
onRead: (path) => readCalls.push(path),
},
({ getCgroupCpuLimit, getCgroupMemoryLimitMb }) => {
expect(getCgroupCpuLimit()).toBeNull();
expect(getCgroupMemoryLimitMb()).toBeNull();
expect(readCalls).not.toContain(CGROUP_V1_CPU_QUOTA_PATH);
expect(readCalls).not.toContain(CGROUP_V1_MEMORY_LIMIT_PATH);
expect(warn).not.toHaveBeenCalled();
},
);
});
it("names the CPU file it could not read, not a memory limit", async () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
await withSystemMemoryMocks(
{ readErrors: { "/sys/fs/cgroup/cpu.max": unreadable } },
({ getCgroupCpuLimit }) => {
expect(getCgroupCpuLimit()).toBeNull();
expect(warn).toHaveBeenCalledTimes(1);
expect(warn.mock.calls[0]?.[0]).toContain(
"[SystemMemory] Unable to read /sys/fs/cgroup/cpu.max (EACCES",
);
expect(warn.mock.calls[0]?.[0]).not.toContain("memory");
},
);
});
});
describe("usableCpuCount under a CPU quota", () => {
@@ -305,13 +367,18 @@ describe("getSystemTotalMb", () => {
({ _resetCgroupLimitCacheForTests, getSystemTotalMb }) => {
expect(getSystemTotalMb()).toBe(4096);
expect(getSystemTotalMb()).toBe(4096);
expect(readCalls).toEqual([CGROUP_V2_MEMORY_MAX_PATH]);
expect(readCalls).toEqual([CGROUP_V2_CONTROLLERS_PATH, CGROUP_V2_MEMORY_MAX_PATH]);
files[CGROUP_V2_MEMORY_MAX_PATH] = `${2048 * BYTES_PER_MIB}`;
_resetCgroupLimitCacheForTests();
expect(getSystemTotalMb()).toBe(2048);
expect(readCalls).toEqual([CGROUP_V2_MEMORY_MAX_PATH, CGROUP_V2_MEMORY_MAX_PATH]);
expect(readCalls).toEqual([
CGROUP_V2_CONTROLLERS_PATH,
CGROUP_V2_MEMORY_MAX_PATH,
CGROUP_V2_CONTROLLERS_PATH,
CGROUP_V2_MEMORY_MAX_PATH,
]);
},
);
});
@@ -333,6 +400,7 @@ describe("getSystemTotalMb", () => {
it("honors cgroup v1 numeric limits when cgroup v2 is absent", async () => {
await withSystemMemoryMocks(
{
cgroupVersion: 1,
files: {
[CGROUP_V1_MEMORY_LIMIT_PATH]: `${6144 * BYTES_PER_MIB}`,
},
@@ -347,6 +415,7 @@ describe("getSystemTotalMb", () => {
it("uses the host total when cgroup v1 reports a no-limit sentinel", async () => {
await withSystemMemoryMocks(
{
cgroupVersion: 1,
files: {
[CGROUP_V1_MEMORY_LIMIT_PATH]: "9223372036854771712",
},
@@ -381,7 +450,7 @@ describe("getSystemTotalMb", () => {
expect(isLowMemorySystem()).toBe(false);
expect(warn).toHaveBeenCalledTimes(1);
expect(warn.mock.calls[0]?.[0]).toContain(
"[SystemMemory] Unable to read cgroup memory limit",
`[SystemMemory] Unable to read ${CGROUP_V2_MEMORY_MAX_PATH} (`,
);
expect(warn.mock.calls[0]?.[0]).toContain("EACCES");
},
@@ -440,6 +509,7 @@ describe("getSystemTotalMb", () => {
async (content) => {
await withSystemMemoryMocks(
{
cgroupVersion: 1,
files: {
[CGROUP_V1_MEMORY_LIMIT_PATH]: content,
},
+17 -15
View File
@@ -22,6 +22,7 @@ const BYTES_PER_MIB_BIGINT = BigInt(BYTES_PER_MIB);
// slice (e.g. /sys/fs/cgroup/user.slice/.../memory.max) that these root paths
// don't see, and that's acceptable — bare hosts are covered by total-RAM
// detection, and chasing nested slices adds fragility for no container gain.
const CGROUP_V2_CONTROLLERS_PATH = "/sys/fs/cgroup/cgroup.controllers";
const CGROUP_V2_MEMORY_MAX_PATH = "/sys/fs/cgroup/memory.max";
const CGROUP_V1_MEMORY_LIMIT_PATH = "/sys/fs/cgroup/memory/memory.limit_in_bytes";
// Kernel no-limit sentinel is page-rounded 2^63-1 (~9223372036854771712); >= 2^60 is implausible as a real limit.
@@ -111,15 +112,13 @@ export function _resetCgroupLimitCacheForTests(): void {
export function getCgroupCpuLimit(): number | null {
if (_cachedCgroupCpus !== undefined) return _cachedCgroupCpus;
if (process.platform !== "linux") return (_cachedCgroupCpus = null);
const v2 = readCgroupFile(CGROUP_V2_CPU_MAX_PATH);
_cachedCgroupCpus =
v2 !== null
? parseCgroupCpus(v2, null, null)
: parseCgroupCpus(
null,
readCgroupFile(CGROUP_V1_CPU_QUOTA_PATH),
readCgroupFile(CGROUP_V1_CPU_PERIOD_PATH),
);
_cachedCgroupCpus = isCgroupV2()
? parseCgroupCpus(readCgroupFile(CGROUP_V2_CPU_MAX_PATH), null, null)
: parseCgroupCpus(
null,
readCgroupFile(CGROUP_V1_CPU_QUOTA_PATH),
readCgroupFile(CGROUP_V1_CPU_PERIOD_PATH),
);
return _cachedCgroupCpus;
}
@@ -135,10 +134,9 @@ export function getCgroupMemoryLimitMb(): number | null {
return null;
}
const v2Content = readCgroupFile(CGROUP_V2_MEMORY_MAX_PATH);
const v1Content = v2Content === null ? readCgroupFile(CGROUP_V1_MEMORY_LIMIT_PATH) : null;
_cachedCgroupLimitMb = parseCgroupLimitMb(v2Content, v1Content);
_cachedCgroupLimitMb = isCgroupV2()
? parseCgroupLimitMb(readCgroupFile(CGROUP_V2_MEMORY_MAX_PATH), null)
: parseCgroupLimitMb(null, readCgroupFile(CGROUP_V1_MEMORY_LIMIT_PATH));
if (_cachedCgroupLimitMb !== null) {
// stderr, not stdout: this is a diagnostic notice, and commands like `check --json`
// write their machine-readable payload to stdout. A banner on stdout corrupts that
@@ -151,6 +149,10 @@ export function getCgroupMemoryLimitMb(): number | null {
return _cachedCgroupLimitMb;
}
function isCgroupV2(): boolean {
return readCgroupFile(CGROUP_V2_CONTROLLERS_PATH) !== null;
}
function readCgroupFile(path: string): string | null {
try {
return readFileSync(path, "utf8");
@@ -181,8 +183,8 @@ function warnCgroupReadFailure(path: string, error: unknown): void {
if (_warnedCgroupReadFailure) return;
_warnedCgroupReadFailure = true;
console.warn(
`[SystemMemory] Unable to read cgroup memory limit at ${path} ` +
`(${formatCgroupReadError(error)}); falling back to host RAM.`,
`[SystemMemory] Unable to read ${path} ` +
`(${formatCgroupReadError(error)}); using the host's values instead.`,
);
}
@@ -12,7 +12,7 @@ import { copyFileSync, existsSync, linkSync, mkdirSync, mkdtempSync, rmSync, sta
import { basename, isAbsolute, join, normalize, relative, win32 } from "path";
import { tmpdir } from "os";
import { createConcurrencyLimit } from "../utils/concurrencyLimit.js";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import { HF_COLOR_GRADING_ATTR } from "@hyperframes/core";
import { isPathInside } from "@hyperframes/parsers/asset-paths";
import { resolveProjectRelativeSrc } from "@hyperframes/parsers/asset-resolution";
+2 -2
View File
@@ -3,7 +3,7 @@ import { redactUrlQueryStrings } from "@hyperframes/core";
import {
SELF_CONTAINED_FORMATS,
assertLiteralMediaInput,
mediaInputFormatArgs,
mediaInputArgs,
} from "@hyperframes/parsers/ff-binaries";
import { resolveRestrictPageNetwork } from "../config.js";
import { getFfmpegBinary, getFfprobeBinary } from "./ffmpegBinaries.js";
@@ -68,7 +68,7 @@ export function urlInputArgs(
): string[] {
assertLiteralMediaInput(input);
const mediaFormats = () =>
mediaInputFormatArgs(tool === "ffprobe" ? getFfprobeBinary() : getFfmpegBinary(), input, {
mediaInputArgs(tool === "ffprobe" ? getFfprobeBinary() : getFfmpegBinary(), input, {
playlists: true,
});
const restricted = resolveRestrictPageNetwork();
+4 -4
View File
@@ -4,7 +4,7 @@ import { join } from "node:path";
import { rewriteAssetPath } from "@hyperframes/parsers/asset-paths";
import { parseNumeric } from "@hyperframes/parsers/composition-contract";
import { templateContent } from "@hyperframes/parsers/sub-composition-validity";
import { findFfBinary, mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
import { findFfBinary, mediaInputArgs } from "@hyperframes/parsers/ff-binaries";
import {
cleanAssetUrl,
isRemoteOrInlineUrl,
@@ -12,7 +12,7 @@ import {
maskNonScannableRanges,
resolveExistingLocalAsset,
} from "@hyperframes/parsers/asset-resolution";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import type { HyperframeLintFinding } from "./types.js";
import { mediaSrcOf, mediaSrcTagRe } from "./utils";
@@ -89,7 +89,7 @@ async function probeIsHevc(ffprobePath: string, filePath: string): Promise<boole
const stdout = await execFileAsync(ffprobePath, [
"-v",
"error",
...mediaInputFormatArgs(ffprobePath, filePath),
...mediaInputArgs(ffprobePath, filePath),
"-select_streams",
"v:0",
"-show_entries",
@@ -247,7 +247,7 @@ async function probePlayableVideoDuration(
await execFileAsync(ffprobePath, [
"-v",
"error",
...mediaInputFormatArgs(ffprobePath, filePath),
...mediaInputArgs(ffprobePath, filePath),
"-select_streams",
"v:0",
"-show_entries",
@@ -8,7 +8,7 @@ vi.mock("node:child_process", () => {
});
vi.mock("@hyperframes/parsers/ff-binaries", () => ({
findFfBinary: () => "/fake/bin/ffprobe",
mediaInputFormatArgs: () => [],
mediaInputArgs: () => [],
}));
import { lintHevcPreviewCodec } from "./hevcPreviewLint.js";
+1 -1
View File
@@ -28,7 +28,7 @@ import {
checkSubCompositionUsability,
templateContent,
} from "@hyperframes/parsers/sub-composition-validity";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import postcss from "postcss";
import {
cleanAssetUrl,
+1 -1
View File
@@ -1,7 +1,7 @@
import { emptyStyleBlocks, hasScriptWithSrc, replaceBlockComments } from "../linearScans";
import type { LintContext, HyperframeLintFinding, ExtractedBlock, OpenTag } from "../context";
import selectorParser from "postcss-selector-parser";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import {
findHtmlTag,
extractTimelineRegistryKeys,
+1 -1
View File
@@ -17,7 +17,7 @@ import {
validateColorGradingContract,
} from "@hyperframes/parsers/color-grading-contract";
import { extractMediaSrcMutations } from "@hyperframes/parsers/composition";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import { findLinkedClipFindings } from "./linkedClips";
import { findUnreadableAudioAttributeFindings } from "./audioAttributes";
+6
View File
@@ -50,6 +50,12 @@
"types": "./dist/hfIds.d.ts",
"environments": ["browser", "bun", "node"]
},
"./linkedom": {
"source": "./src/linkedom.ts",
"runtime": "./dist/linkedom.js",
"types": "./dist/linkedom.d.ts",
"environments": ["browser", "bun", "node"]
},
"./gsap-parser-recast": {
"source": "./src/gsapParser.ts",
"runtime": "./dist/gsapParser.js",
+10
View File
@@ -58,6 +58,12 @@
"import": "./src/hfIds.ts",
"types": "./src/hfIds.ts"
},
"./linkedom": {
"bun": "./src/linkedom.ts",
"node": "./dist/linkedom.js",
"import": "./src/linkedom.ts",
"types": "./src/linkedom.ts"
},
"./gsap-parser-recast": {
"bun": "./src/gsapParser.ts",
"node": "./dist/gsapParser.js",
@@ -223,6 +229,10 @@
"import": "./dist/hfIds.js",
"types": "./dist/hfIds.d.ts"
},
"./linkedom": {
"import": "./dist/linkedom.js",
"types": "./dist/linkedom.d.ts"
},
"./gsap-parser-recast": {
"import": "./dist/gsapParser.js",
"types": "./dist/gsapParser.d.ts"
+16 -1
View File
@@ -2,7 +2,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { execFileSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, posix, win32 } from "node:path";
import { isAbsolute, join, posix, resolve, win32 } from "node:path";
import { pathToFileURL } from "node:url";
import {
collectSubCompositionSrcs,
@@ -143,6 +143,21 @@ describe("collectSubCompositionSrcs", () => {
// The browser clamps `..` at the origin root; path.join does not. One resolver must serve lint and render.
describe("resolveProjectRelativeSrc — the one src resolver for lint and render", () => {
// fails without the fix: with "." as the base the join stayed relative, so a src such as concat:a.wav|b.wav led
// the path ffmpeg was handed, and ffmpeg read it as its concat protocol instead of a project file.
it("returns an absolute path whatever base the caller passed", () => {
for (const base of [".", "./", ""])
for (const src of [
"concat:a.wav|b.wav",
"subfile,,start,0,end,1,,:clip.mp4",
"assets/clip.mp4",
]) {
const path = resolveProjectRelativeSrc(src, base, base && `${base}/compiled`);
expect(isAbsolute(path)).toBe(true);
expect(path.startsWith(resolve(base))).toBe(true);
}
});
let tmp: string;
beforeAll(() => {
+4 -2
View File
@@ -230,9 +230,11 @@ function gitBashFile(src: string): string | undefined {
/** Resolves a media `src` like a browser URL (`..` clamps at the project root); a miss returns the base-dir join. */
export function resolveProjectRelativeSrc(
src: string,
baseDir: string,
compiledDir?: string,
relativeOrAbsoluteBase: string,
relativeOrAbsoluteCompiled?: string,
): string {
const baseDir = resolve(relativeOrAbsoluteBase);
const compiledDir = relativeOrAbsoluteCompiled && resolve(relativeOrAbsoluteCompiled);
const cleanSrc = fileUrlAsPath(cleanAssetUrl(src));
// A leading slash is an origin-root URL served from the project root, unless the absolute path exists.
+14 -9
View File
@@ -525,7 +525,7 @@ describe("mediaInputFormatArgs", () => {
vi.resetModules();
vi.doUnmock("node:fs");
vi.doUnmock("node:child_process");
const { findFfBinary, mediaInputFormatArgs } = await importFresh();
const { findFfBinary, mediaInputArgs } = await importFresh();
const ffmpeg = findFfBinary("ffmpeg");
if (!ffmpeg) return;
const dir = mkdtempSync(join(tmpdir(), "hf-text-art-"));
@@ -533,7 +533,7 @@ describe("mediaInputFormatArgs", () => {
const note = join(dir, "note.asc");
writeFileSync(note, "API_KEY=not-a-video\nsecond line\n");
const frame = join(dir, "frame.png");
const args = ["-v", "error", "-y", ...mediaInputFormatArgs(ffmpeg, note), "-i", note];
const args = ["-v", "error", "-y", ...mediaInputArgs(ffmpeg, note), "-i", note];
spawnSync(ffmpeg, [...args, "-frames:v", "1", frame]);
expect(existsSync(frame)).toBe(false);
});
@@ -547,7 +547,7 @@ describe("mediaInputFormatArgs", () => {
vi.resetModules();
vi.doUnmock("node:fs");
vi.doUnmock("node:child_process");
const { findFfBinary, mediaInputFormatArgs } = await importFresh();
const { findFfBinary, mediaInputArgs } = await importFresh();
const ffmpeg = findFfBinary("ffmpeg");
if (!ffmpeg) return;
const dir = realpathSync(mkdtempSync(join(tmpdir(), "hf-playlist-input-")));
@@ -576,7 +576,7 @@ describe("mediaInputFormatArgs", () => {
writeFileSync(input, "ffconcat version 1.0\nfile inner.m3u8\n");
}
const out = join(dir, "out.wav");
spawnSync(ffmpeg, ["-v", "error", ...mediaInputFormatArgs(ffmpeg, input), "-i", input, out]);
spawnSync(ffmpeg, ["-v", "error", ...mediaInputArgs(ffmpeg, input), "-i", input, out]);
expect(existsSync(out)).toBe(false);
});
@@ -586,14 +586,21 @@ describe("mediaInputFormatArgs", () => {
["concat:/project/a.mp4|/project/b.mp4", true],
["https://cdn.example/clip.mp4", false],
])("reads %s as a local file only: %s", async (input, local) => {
const { _setDemuxerListingForTests, mediaInputFormatArgs } = await importFresh();
const { _setDemuxerListingForTests, mediaInputArgs } = await importFresh();
_setDemuxerListingForTests(" D mov,mp4,m4a QuickTime / MOV");
const args = mediaInputFormatArgs("/ffmpeg", input);
const args = mediaInputArgs("/ffmpeg", input);
expect(args.slice(0, 2)).toEqual(
local ? ["-protocol_whitelist", "file"] : ["-format_whitelist", "mov,mp4,m4a"],
);
});
it("is the one -format_whitelist pair a caller reads by position, for a local file too", async () => {
const { _setDemuxerListingForTests, mediaInputFormatArgs } = await importFresh();
_setDemuxerListingForTests(" D mov,mp4,m4a QuickTime / MOV");
const [flag, formats, ...rest] = mediaInputFormatArgs("/ffmpeg", "/project/clip.mp4");
expect([flag, formats, rest]).toEqual(["-format_whitelist", "mov,mp4,m4a", []]);
});
it("reads playlists only for a caller that walked the file", async () => {
const { _setDemuxerListingForTests, mediaInputFormatArgs } = await importFresh();
_setDemuxerListingForTests(
@@ -622,13 +629,11 @@ describe("mediaInputFormatArgs", () => {
`#!/bin/sh\nif [ -e "${dir}/ran" ]; then echo ' D wav WAV'; else touch "${dir}/ran"; exit 1; fi\n`,
);
chmodSync(binary, 0o755);
const local = ["-protocol_whitelist", "file"];
expect(mediaInputFormatArgs(binary, "a.wav")).toEqual([
...local,
"-format_whitelist",
SELF_CONTAINED_FORMATS,
]);
expect(mediaInputFormatArgs(binary, "a.wav")).toEqual([...local, "-format_whitelist", "wav"]);
expect(mediaInputFormatArgs(binary, "a.wav")).toEqual(["-format_whitelist", "wav"]);
});
it("falls back to a list the installed ffprobe reads CAF, W64, WavPack, AU and AC3 with", async () => {
+12 -4
View File
@@ -347,14 +347,13 @@ export { assertLiteralMediaInput };
const PLAYLIST_DEMUXERS = new Set(["hls", "applehttp", "concat"]);
/** Every demuxer `listingBinary` reports that opens nothing by itself and is not text art, for reading `input`; one that cannot be asked gets the self-contained list, and is asked again. Playlists only with `playlists: true`; anything but an http(s) URL reads as a local file. */
/** The `-format_whitelist` pair for `input` (no playlists unless `playlists: true`); callers read it by position. */
export function mediaInputFormatArgs(
listingBinary: string,
input: string,
{ playlists = false }: { playlists?: boolean } = {},
): string[] {
assertLiteralMediaInput(input);
const local = /^https?:\/\//i.test(input) ? [] : ["-protocol_whitelist", "file"];
const allowed = (formats: string) =>
playlists
? formats
@@ -377,10 +376,19 @@ export function mediaInputFormatArgs(
} catch {
formats = undefined;
}
if (formats === undefined) return [...local, "-format_whitelist", SELF_CONTAINED_FORMATS];
if (formats === undefined) return ["-format_whitelist", SELF_CONTAINED_FORMATS];
demuxerLists.set(listingBinary, formats);
}
return [...local, "-format_whitelist", allowed(formats)];
return ["-format_whitelist", allowed(formats)];
}
export function mediaInputArgs(
listingBinary: string,
input: string,
options: { playlists?: boolean } = {},
): string[] {
const local = /^https?:\/\//i.test(input) ? [] : ["-protocol_whitelist", "file"];
return [...local, ...mediaInputFormatArgs(listingBinary, input, options)];
}
const OUT_TIME = /^out_time_(?:us|ms)=(\d+)$/;
+1 -1
View File
@@ -8,7 +8,7 @@
* Hash is CONTENT ONLY (tag + sorted attrs + own text) — no sibling position,
* so inserting a non-identical sibling never shifts another element's id.
*/
import { parseHTML } from "linkedom";
import { parseHTML } from "./linkedom.js";
import { EXCLUDED_TAGS, assignHfIds, getChildElements } from "./hfIdAssignment.js";
export {
EXCLUDED_TAGS,
+98
View File
@@ -0,0 +1,98 @@
import { describe, expect, it, vi } from "vitest";
import { HTMLElement as LinkedomElement, HTMLTitleElement } from "linkedom";
import { parseHTML } from "./linkedom.js";
const BREAKOUT = "<script>window.pwned=1</script>";
const countScripts = (html: string) => parseHTML(html).document.querySelectorAll("script").length;
describe("@hyperframes/parsers/linkedom", () => {
it("a parse and save keeps an escaped <title> escaped", () => {
const src =
"<!DOCTYPE html><html><head><title>a &lt;/title&gt;&lt;script&gt;t()&lt;/script&gt; &amp; b</title></head><body><p>hi</p></body></html>";
const { document } = parseHTML(src);
document.querySelector("p")!.textContent = "edited elsewhere";
const out = document.toString();
expect(countScripts(out)).toBe(0);
expect(out).toContain(
"<title>a &lt;/title&gt;&lt;script&gt;t()&lt;/script&gt; &amp; b</title>",
);
});
it.each(["textarea", "TEXTAREA", "TextArea"])(
"text set on a <textarea> can't close it (%s)",
(tag) => {
const { document } = parseHTML(
"<!DOCTYPE html><html><body><div><textarea>old</textarea></div></body></html>",
);
document.querySelector("textarea")!.textContent = `</${tag}>${BREAKOUT}`;
const out = document.toString();
expect(countScripts(out)).toBe(0);
expect(parseHTML(out).document.querySelectorAll("textarea").length).toBe(1);
},
);
it("text set on a <title> can't close it", () => {
const { document } = parseHTML(
"<!DOCTYPE html><html><head><title>t</title></head><body></body></html>",
);
document.querySelector("title")!.textContent = `</title>${BREAKOUT}`;
expect(countScripts(document.toString())).toBe(0);
});
it.each(["textarea", "title"])("a '><' in a <%s> attribute keeps the text out of it", (tag) => {
const { document } = parseHTML(
`<!DOCTYPE html><html><body><${tag} data-x="a><b">old</${tag}></body></html>`,
);
document.querySelector(tag)!.textContent = "new";
const saved = parseHTML(document.toString()).document.querySelector(tag)!;
expect(saved.getAttribute("data-x")).toBe("a><b");
expect(saved.textContent).toBe("new");
});
it("a <textarea>'s source bytes round-trip unchanged", () => {
const body = "<textarea>x &lt;y&gt; &amp; z</textarea><textarea>raw <b>tag</b></textarea>";
const src = `<!DOCTYPE html><html><head></head><body>${body}</body></html>`;
expect(parseHTML(src).document.toString()).toContain(body);
});
it("<script> and <style> text stays raw", () => {
const body = "<script>if (a < b && c > d) go();</script><style>a > b { content: '&'; }</style>";
const src = `<!DOCTYPE html><html><head></head><body>${body}</body></html>`;
expect(parseHTML(src).document.toString()).toContain(body);
});
// When either fails, linkedom changed how it reads or writes these tags: re-check, or drop, the override.
it("linkedom still decodes <title> and keeps <textarea> text as written", () => {
const { document } = parseHTML("<title>a &lt;b&gt;</title><textarea>c &lt;d&gt;</textarea>");
expect(document.querySelector("title")!.textContent).toBe("a <b>");
expect(document.querySelector("textarea")!.textContent).toBe("c &lt;d&gt;");
});
// A plain re-export lets a bundler link straight to linkedom and drop this module under "sideEffects": false.
it("parseHTML and DOMParser are this module's own functions, not linkedom's", async () => {
const linkedom = await import("linkedom");
const own = await import("./linkedom.js");
expect(own.parseHTML).not.toBe(linkedom.parseHTML);
expect(own.DOMParser).not.toBe(linkedom.DOMParser);
});
it("a fresh process escapes on save once a DOMParser is made", async () => {
vi.resetModules();
const linkedom = await import("linkedom");
const { DOMParser } = await import("./linkedom.js");
new DOMParser();
const { document } = linkedom.parseHTML(
"<!DOCTYPE html><html><body><textarea>x</textarea></body></html>",
);
document.querySelector("textarea")!.textContent = `</textarea>${BREAKOUT}`;
expect(countScripts(document.toString())).toBe(0);
});
it("linkedom's own text-element writer is the one the override replaces", () => {
const own = Object.getPrototypeOf(HTMLTitleElement.prototype).toString;
expect(own).not.toBe(LinkedomElement.prototype.toString);
expect(String(own).replace(/\s+/g, " ")).toBe(
"toString() { const outerHTML = toString.call(this.cloneNode()); return outerHTML.replace('><', () => `>${this.textContent}<`); }",
);
});
});
+112
View File
@@ -0,0 +1,112 @@
// The one linkedom entry point: linkedom wrote <title>/<textarea> text raw, so "</title>" closed it on save.
import {
DOMParser as LinkedomDOMParser,
HTMLElement,
HTMLTextAreaElement,
HTMLTitleElement,
parseHTML as linkedomParseHTML,
} from "linkedom";
// Parse decodes <title> text but keeps <textarea> text as written: each escapes only what keeps bytes intact.
const escapeDecodedTitleText = (text: string) =>
text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
const neutraliseTextareaEndTag = (text: string) => text.replace(/<(\/textarea)/gi, "&lt;$1");
const writeEmptyElement = HTMLElement.prototype.toString;
let installed = false;
// Runs from the parsers below, not at import: "sideEffects": false lets a bundler drop an import-time patch.
function escapeTextOnWrite(): void {
if (installed) return;
installed = true;
for (const [Element, escape] of [
[HTMLTitleElement, escapeDecodedTitleText],
[HTMLTextAreaElement, neutraliseTextareaEndTag],
] as const) {
Object.defineProperty(Element.prototype, "toString", {
configurable: true,
writable: true,
value(this: InstanceType<typeof Element>) {
const empty = writeEmptyElement.call(this.cloneNode());
const close = empty.lastIndexOf("</");
return empty.slice(0, close) + escape(this.textContent ?? "") + empty.slice(close);
},
});
}
}
// linkedom reads these as plain text even inside svg or math, where a browser reads their markup.
const READ_AS_TEXT = new Set(["title", "style", "script", "textarea", "xmp"]);
const FOREIGN = new Set(["svg", "math"]);
const BACK_TO_HTML = new Set(["foreignobject", "desc"]);
const TAG_OR_COMMENT = /<[A-Za-z!/?]/;
const CDATA = /<!\[CDATA\[[\s\S]*?\]\]>/g;
export class HtmlReadUnlikeBrowserError extends Error {
constructor() {
super(
"This HTML has tags or comments inside an SVG or MathML title, style, script, textarea or xmp element, which can't be read the way a browser reads them.",
);
this.name = "HtmlReadUnlikeBrowserError";
}
}
function insideForeign(element: Element): boolean {
for (let up = element.parentElement; up; up = up.parentElement) {
const name = up.localName.toLowerCase();
if (BACK_TO_HTML.has(name)) return false;
if (FOREIGN.has(name)) return true;
}
return false;
}
function readAsTextUnlikeBrowser(element: Element): boolean {
return (
READ_AS_TEXT.has(element.localName.toLowerCase()) &&
insideForeign(element) &&
TAG_OR_COMMENT.test((element.textContent ?? "").replace(CDATA, ""))
);
}
function nextInDocumentOrder(element: Element): Element | null {
if (element.firstElementChild) return element.firstElementChild;
for (let at: Element | null = element; at; at = at.parentElement)
if (at.nextElementSibling) return at.nextElementSibling;
return null;
}
// One pass in document order: linkedom keeps the tree as a list, so asking each element for its children is quadratic.
// A parsed template's children are in that list; its `content` is a deep copy linkedom makes and keeps on first read.
function readsUnlikeBrowser(root: ParentNode): boolean {
for (let element = root.firstElementChild; element; element = nextInDocumentOrder(element))
if (readAsTextUnlikeBrowser(element)) return true;
return false;
}
// Typed with the DOM's own types: published declarations that name linkedom's fail a strict consumer.
/** linkedom's `parseHTML`, refusing HTML that a browser would read as a different tree. */
export function parseHTML(html: string, globals?: unknown): Window & typeof globalThis {
escapeTextOnWrite();
const parsed = linkedomParseHTML(html, globals) as Window & typeof globalThis;
if (readsUnlikeBrowser(parsed.document)) throw new HtmlReadUnlikeBrowserError();
return parsed;
}
/** linkedom's `DOMParser`, with the same refusal for `text/html`. */
export const DOMParser = class extends LinkedomDOMParser {
constructor() {
super();
escapeTextOnWrite();
}
override parseFromString<Mime extends Parameters<LinkedomDOMParser["parseFromString"]>[1]>(
markup: string,
mimeType: Mime,
globals?: unknown,
) {
const parsed = super.parseFromString(markup, mimeType, globals);
if (mimeType === "text/html" && readsUnlikeBrowser(parsed as unknown as Document))
throw new HtmlReadUnlikeBrowserError();
return parsed;
}
} as unknown as { new (): globalThis.DOMParser };
@@ -0,0 +1,54 @@
import { describe, expect, it } from "vitest";
import { DOMParser, parseHTML } from "./linkedom.js";
const READ_UNLIKE_BROWSER = /can't be read the way a browser reads them/;
const HIDDEN = "<svg><title><!-- </title><img src=x onerror=f()> --></title></svg>";
const page = (body: string) => `<!DOCTYPE html><html><head></head><body>${body}</body></html>`;
// fails without the fix: linkedom ended the title inside its comment, so a browser's inert comment became a live img.
describe("parseHTML", () => {
it.each([
HIDDEN,
"<svg><style><!-- </style><img src=x onerror=f()> --></style></svg>",
"<math><title><!-- </title><img src=x onerror=f()> --></title></math>",
"<svg><style><![CDATA[ a{} ]]><!-- </style><img src=x onerror=f()> --></style></svg>",
`<template><div>${HIDDEN}</div></template>`,
])("refuses %s, which a browser reads differently", (body) => {
expect(() => parseHTML(page(body))).toThrow(READ_UNLIKE_BROWSER);
expect(() => new DOMParser().parseFromString(page(body), "text/html")).toThrow(
READ_UNLIKE_BROWSER,
);
});
it.each([
'<svg viewBox="0 0 4 4"><title>Icon 1 &lt; 2 &amp; 3</title><circle r="2"></circle></svg>',
"<title>Page</title><style>a > b { color: red }</style>",
"<p><!-- </title><img> --></p>",
'<head><meta name="description" content="x"></head>',
"<template></template>",
"<svg><foreignObject><title>a <b> c</title></foreignObject></svg>",
'<svg><style><![CDATA[ a::after { content: "<b>" } ]]></style></svg>',
])("reads %s as linkedom does", (body) => {
const { document } = parseHTML(page(body));
expect(document.querySelectorAll("img")).toHaveLength(0);
});
// fails without the fix: the check read each template's content, so linkedom copied every mounted scene and kept
// the copy, and a later edit to the template never reached its content.
it("leaves a template's content to be made from its children when it is first read", () => {
const { document } = parseHTML(page("<template><p>before</p></template>"));
const template = document.querySelector("template") as HTMLTemplateElement;
template.querySelector("p")!.textContent = "after";
expect(template.content.firstChild?.textContent).toBe("after");
});
it("reads a page that is only a comment", () => {
expect(() => parseHTML("<!-- <template><div></div></template> -->")).not.toThrow();
});
it("leaves svg read as XML to linkedom", () => {
const doc = new DOMParser().parseFromString(HIDDEN, "image/svg+xml");
expect(doc.querySelectorAll("img")).toHaveLength(0);
});
});
@@ -0,0 +1,22 @@
import { describe, expect, it } from "vitest";
import { assertLiteralMediaInput, assertLiteralMediaOutput } from "./literalMediaInput.js";
describe("assertLiteralMediaInput", () => {
// fails without the fix: every scheme but file: skipped the check, as if another check had vetted it.
it("checks a scheme-led name as a local one; only http and https are left to the caller", () => {
for (const path of [
"concat:/a/b%d.png",
"subfile,,start,0,end,0,,:/a/b%d.png",
"data:/a%d.png",
]) {
expect(() => assertLiteralMediaInput(path)).toThrow(/pattern of other files/);
expect(() => assertLiteralMediaOutput(path)).toThrow(/pattern of other files/);
}
for (const path of [
"https://cdn.example/a%2d.png",
"HTTP://cdn.example/a%2d.png",
"/a/clip.mp4",
])
expect(() => assertLiteralMediaInput(path)).not.toThrow();
});
});
+2 -3
View File
@@ -1,13 +1,12 @@
const PATTERN_IMAGE2_EXPANDS = /%\d*[d%*?[\]{}]/;
const WILDCARD_MAKES_ANY_PERCENT_A_PATTERN = /[*?[{]/;
const URL_SCHEME = /^[a-z][a-z0-9+.-]+:/i;
const FORWARDED = /^https?:/i;
function refusePattern(path: string, use: "read" | "write"): void {
const local = !URL_SCHEME.test(path) || /^file:/i.test(path);
const pattern =
PATTERN_IMAGE2_EXPANDS.test(path) ||
(path.includes("%") && WILDCARD_MAKES_ANY_PERCENT_A_PATTERN.test(path));
if (!local || !pattern) return;
if (FORWARDED.test(path) || !pattern) return;
throw new Error(
`[FFmpeg] refused media path "${path.split(/[\\/]/).pop()}": a "%" followed by "d", another "%" or a wildcard, ` +
`with or without digits between, or a "%" and a wildcard (*, ?, [ or {) anywhere in the path, would make ffmpeg ` +
+29 -38
View File
@@ -32,26 +32,10 @@ function withoutTrailingDotsOrSpaces(segment: string): string {
return segment.slice(0, end);
}
// Git metadata and env files hold commands other tools run and secrets: nothing serves or inlines them.
export function isVcsOrSecretPath(relPath: string): boolean {
return projectPathSegments(relPath).some(
(segment) => segment === ".git" || segment.startsWith(".env"),
);
}
// `.hyperframes/` holds the desktop app's and the CLI's own records (a hand-off, chat history, read marks): no file
// server serves any of it, the folder itself included, but Studio's own files and the assets compositions load. Studio
// reads and writes those only in the project's own `.hyperframes/`, so one in a subfolder holds records only.
const STUDIO_FILES = new Set([
".hyperframes/studio-motion.json",
".hyperframes/studio-manual-edits.json",
]);
const STUDIO_FOLDERS = [".hyperframes/prepared-assets", ".hyperframes/requests"];
const UNCONVERTED_PREVIEW_DOWNLOADS = ".hyperframes/prepared-assets/downloads";
// Credentials and coding-tool state that projects often sit next to: registry tokens, MCP and agent settings, cloud and
// SSH keys. No composition loads one, so no file server serves one and no upload ships one.
const CREDENTIAL_FILES = new Set([
// Shared with the editable-source contract. Each expression matches whole normalized paths.
const anyDepth = String.raw`(?:[^/]*/)*`;
const vcsOrEnv = String.raw`(?:\.git|\.env[^/]*)(?:/.*)?`;
const credentialNames = [
".npmrc",
".yarnrc",
".yarnrc.yml",
@@ -67,8 +51,8 @@ const CREDENTIAL_FILES = new Set([
"serviceaccountkey.json",
"service-account.json",
"service_account.json",
]);
const CREDENTIAL_FOLDERS = new Set([
];
const toolFolders = [
".ssh",
".aws",
".gnupg",
@@ -82,26 +66,33 @@ const CREDENTIAL_FOLDERS = new Set([
".gemini",
".vscode",
".idea",
];
const alternatives = (names: string[]) =>
names.map((name) => name.replaceAll(".", "\\.")).join("|");
const keyOrStore = String.raw`id_(?:rsa|dsa|ecdsa|ed25519)[^/]*|[^/]*\.(?:pem|key|p12|pfx|p8|ppk|jks|keystore|kdbx|tfstate(?:\.backup)?|tfvars(?:\.json)?)`;
const folders = String.raw`(?:${alternatives(toolFolders)}|\.config/(?:gcloud|gh))(?:/.*)?`;
const credentials = [alternatives(credentialNames), keyOrStore, folders].join("|");
export const portablePrivatePattern = `${anyDepth}(?:${vcsOrEnv}|${credentials})`;
const vcsOrSecret = new RegExp(`^${anyDepth}(?:${vcsOrEnv})$`, "su");
const credentialOrToolState = new RegExp(`^${anyDepth}(?:${credentials})$`, "su");
// Git metadata and env files hold commands other tools run and secrets: nothing serves or inlines them.
export function isVcsOrSecretPath(relPath: string): boolean {
return vcsOrSecret.test(projectPathSegments(relPath).join("/"));
}
// Only known project files in the root .hyperframes directory can be served as assets.
const STUDIO_FILES = new Set([
".hyperframes/studio-motion.json",
".hyperframes/studio-manual-edits.json",
]);
const CREDENTIAL_CONFIG_FOLDERS = new Set(["gcloud", "gh"]);
const KEY_FILE =
/^(?:id_(?:rsa|dsa|ecdsa|ed25519).*|.*\.(?:pem|key|p12|pfx|p8|ppk|jks|keystore|kdbx))$/;
const SECRET_STORE_FILE = /\.(?:tfstate(?:\.backup)?|tfvars(?:\.json)?)$/;
const STUDIO_FOLDERS = [".hyperframes/prepared-assets", ".hyperframes/requests"];
const UNCONVERTED_PREVIEW_DOWNLOADS = ".hyperframes/prepared-assets/downloads";
/** Credential files and tool or agent state, for a project-relative path in any spelling Windows opens. */
export function isCredentialOrToolStatePath(relPath: string): boolean {
const segments = projectPathSegments(relPath);
const name = segments.at(-1) ?? "";
return (
CREDENTIAL_FILES.has(name) ||
KEY_FILE.test(name) ||
SECRET_STORE_FILE.test(name) ||
segments.some(
(segment, at) =>
CREDENTIAL_FOLDERS.has(segment) ||
(segment === ".config" && CREDENTIAL_CONFIG_FOLDERS.has(segments[at + 1] ?? "")),
)
);
return credentialOrToolState.test(projectPathSegments(relPath).join("/"));
}
/** Files no composition loads, in any spelling Windows opens: git, env, credentials, tool state, app records. */
+1 -1
View File
@@ -1,4 +1,4 @@
import { parseHTML } from "linkedom";
import { parseHTML } from "./linkedom.js";
import { parseGsapScriptAcorn } from "./gsapParserAcorn.js";
import type { GsapAnimation } from "./gsapSerialize.js";
import { TIMING_TOLERANCE_SECONDS } from "./compositionDuration.js";
+1
View File
@@ -9,6 +9,7 @@ export default defineConfig({
gsapConstants: "src/gsapConstants.ts",
springEase: "src/springEase.ts",
hfIds: "src/hfIds.ts",
linkedom: "src/linkedom.ts",
gsapParser: "src/gsapParser.ts",
slideshow: "src/slideshow/index.ts",
assets: "src/assets.ts",
@@ -2,7 +2,7 @@
import { createHash, randomUUID } from "node:crypto";
import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, statSync } from "node:fs";
import { dirname, isAbsolute, join, resolve } from "node:path";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import { parseAnimatedGifMetadata, type AnimatedGifMetadata } from "@hyperframes/core";
import {
DEFAULT_VP9_CPU_USED,
@@ -5,7 +5,7 @@
* Compares compiled HTML against golden files using semantic attribute matching.
*/
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
export interface CompiledElement {
id: string;
@@ -13,7 +13,7 @@ import {
writeFileSync,
} from "node:fs";
import { dirname, join, resolve } from "node:path";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import { renameWithRetry, runFfmpeg, runFfprobe, urlInputArgs } from "@hyperframes/engine";
import { readHeifPrimaryRotation } from "./heifRotation.js";
import { withMediaProbeSlot } from "../utils/mediaProbeConcurrency.js";
@@ -27,7 +27,7 @@ import {
import { createHash } from "node:crypto";
import { createReadStream, existsSync, mkdirSync, readFileSync, statSync } from "fs";
import { join, dirname, resolve, basename, relative, sep } from "path";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import { bundledGsapStandIn, bundledScript } from "./bundledScripts.js";
import {
inlineScriptBlocks,
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { resolveFrameWindow } from "./frameWindow.js";
import { assertRangeSupported, resolveFrameWindow } from "./frameWindow.js";
const fps30 = { num: 30, den: 1 };
const ntsc = { num: 30000, den: 1001 };
@@ -42,3 +42,21 @@ describe("resolveFrameWindow", () => {
);
});
});
describe("assertRangeSupported", () => {
const window = { startFrame: 75, endFrame: 120 };
it("lets the disk and layered routes capture a window", () => {
expect(() => assertRangeSupported(window, "sdr_disk")).not.toThrow();
expect(() => assertRangeSupported(window, "hdr_layered")).not.toThrow();
});
it("refuses a window on the streaming routes, which render whole films", () => {
expect(() => assertRangeSupported(window, "sdr_streaming")).toThrow(
/renders the whole film only/,
);
expect(() => assertRangeSupported(window, "sdr_segmented")).toThrow(
/renders the whole film only/,
);
});
});
@@ -30,12 +30,16 @@ export function resolveFrameWindow(range: RenderRange, fps: Fps, filmFrames: num
return { startFrame, endFrame };
}
/** Only the disk route captures a frame window; HDR content and shader transitions render whole films for now. */
export function windowStartFrame(frameWindow: FrameWindow | undefined): number {
return frameWindow?.startFrame ?? 0;
}
/** The disk and layered routes capture a frame window; the streaming routes render whole films. */
export function assertRangeSupported(
frameWindow: FrameWindow | undefined,
route: CapturePlan["kind"],
): void {
if (!frameWindow || route === "sdr_disk") return;
if (!frameWindow || route === "sdr_disk" || route === "hdr_layered") return;
throw new Error(
`This composition renders on the "${route}" capture route, which renders the whole film only; ` +
"render it without a start or end.",
@@ -171,6 +171,11 @@ describe("partitionTransitionFrames", () => {
expect(set.has(3)).toBe(false);
});
it("keeps a window's film frames, from its first frame", () => {
const set = partitionTransitionFrames([{ startFrame: 95, endFrame: 105 }], 10, 100);
expect([...set].sort((a, b) => a - b)).toEqual([100, 101, 102, 103, 104, 105]);
});
it("returns empty set for non-positive totalFrames", () => {
expect(partitionTransitionFrames([{ startFrame: 0, endFrame: 5 }], 0).size).toBe(0);
expect(partitionTransitionFrames([{ startFrame: 0, endFrame: 5 }], -1).size).toBe(0);
@@ -9,6 +9,7 @@
* centralized here.
*/
import type { Fps } from "@hyperframes/core";
import {
type BeforeCaptureHook,
type CaptureSession,
@@ -89,12 +90,13 @@ export function distributeLayeredHybridFrameRanges(
export function partitionTransitionFrames(
transitionRanges: ReadonlyArray<Pick<TransitionRange, "startFrame" | "endFrame">>,
totalFrames: number,
firstFrame = 0,
): Set<number> {
const frames = new Set<number>();
if (totalFrames <= 0) return frames;
for (const range of transitionRanges) {
const start = Math.max(0, range.startFrame);
const end = Math.min(totalFrames - 1, range.endFrame);
const start = Math.max(firstFrame, range.startFrame);
const end = Math.min(firstFrame + totalFrames - 1, range.endFrame);
for (let i = start; i <= end; i++) frames.add(i);
}
return frames;
@@ -416,3 +418,25 @@ export function cleanupEndedHdrVideos(args: {
}
}
}
export function transitionAtFrame(
transitionRanges: TransitionRange[],
frame: number,
): TransitionRange | undefined {
return transitionRanges.find((t) => frame >= t.startFrame && frame <= t.endFrame);
}
export function cleanupHdrVideosEndedBefore(
firstFrame: number,
fps: Fps,
transitionRanges: TransitionRange[],
state: Omit<Parameters<typeof cleanupEndedHdrVideos>[0], "time" | "activeTransition">,
): void {
for (let frame = 0; frame < firstFrame; frame++) {
cleanupEndedHdrVideos({
...state,
time: (frame * fps.den) / fps.num,
activeTransition: transitionAtFrame(transitionRanges, frame),
});
}
}
@@ -1,6 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ShaderBlendRequest } from "../../shaderTransitionWorkerPool.js";
import { type HybridLoopInput, runHybridLayeredFrameLoop } from "./captureHdrHybridLoop.js";
import {
captureTransitionFrameOnWorker,
seekInjectAndQueryStacking,
} from "./captureHdrFrameShared.js";
vi.mock("@hyperframes/engine", async (importOriginal) => ({
...(await importOriginal<typeof import("@hyperframes/engine")>()),
@@ -47,11 +51,18 @@ vi.mock("../../shaderTransitionWorkerPool.js", () => ({
function loopInput(overrides: {
writeFrame?: (frame: number) => boolean;
assertNotAborted?: () => void;
firstFrame?: number;
}): HybridLoopInput {
const first = overrides.firstFrame ?? 0;
const log = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };
let frame = 0;
const input = {
job: { config: { fps: { num: 30, den: 1 } }, totalFrames: 16, framesRendered: 0 },
job: {
config: { fps: { num: 30, den: 1 } },
totalFrames: 16,
framesRendered: 0,
...(first && { frameWindow: { startFrame: first, endFrame: first + 16 } }),
},
cfg: {},
log,
framesDir: "/tmp/unused",
@@ -78,8 +89,8 @@ function loopInput(overrides: {
ease: "",
fromScene: "a",
toScene: "b",
startFrame: 2,
endFrame: 13,
startFrame: first + 2,
endFrame: first + 13,
},
],
sceneElements: { a: ["a"], b: ["b"] },
@@ -117,6 +128,25 @@ describe("runHybridLayeredFrameLoop failures with 2 workers", () => {
expect(escaped).toEqual([]);
});
it("seeks film frames and finds the film's transition inside a window", async () => {
vi.mocked(seekInjectAndQueryStacking).mockClear();
vi.mocked(captureTransitionFrameOnWorker).mockClear();
const input = loopInput({ firstFrame: 100 });
await runHybridLayeredFrameLoop(input);
expect(input.job.framesRendered).toBe(16);
const transitions = vi
.mocked(captureTransitionFrameOnWorker)
.mock.calls.map(([args]) => args as { frameIdx: number; time: number });
const normalTimes = vi.mocked(seekInjectAndQueryStacking).mock.calls.map((call) => call[1]);
const seekedFrames = [...normalTimes, ...transitions.map((t) => t.time)]
.map((time) => Math.round(Number(time) * 30))
.sort((a, b) => a - b);
expect(seekedFrames).toEqual(Array.from({ length: 16 }, (_, k) => 100 + k));
expect(transitions.map((t) => t.frameIdx).sort((a, b) => a - b)).toEqual(
Array.from({ length: 12 }, (_, k) => 102 + k),
);
});
let aborts = 0;
it.each([
{
@@ -54,8 +54,10 @@ import {
ensureFrameWritten,
partitionTransitionFrames,
seekInjectAndQueryStacking,
transitionAtFrame,
} from "./captureHdrFrameShared.js";
import { reportFrameProgress } from "../shared.js";
import { windowStartFrame } from "../frameWindow.js";
export interface HybridLoopInput {
job: RenderJob;
@@ -112,7 +114,8 @@ export async function runHybridLayeredFrameLoop(input: HybridLoopInput): Promise
assertNotAborted,
onProgress,
} = input;
const transitionFramesSet = partitionTransitionFrames(transitionRanges, totalFrames);
const firstFrame = windowStartFrame(job.frameWindow);
const transitionFramesSet = partitionTransitionFrames(transitionRanges, totalFrames, firstFrame);
const hasTransitions = transitionRanges.length > 0;
const bufSize = width * height * 6;
@@ -228,9 +231,10 @@ export async function runHybridLayeredFrameLoop(input: HybridLoopInput): Promise
for (let i = range.start; i < range.end; i++) {
throwIfFailed();
assertNotAborted();
const time = (i * job.config.fps.den) / job.config.fps.num;
const activeTransition = transitionFramesSet.has(i)
? transitionRanges.find((t) => i >= t.startFrame && i <= t.endFrame)
const frame = firstFrame + i;
const time = (frame * job.config.fps.den) / job.config.fps.num;
const activeTransition = transitionFramesSet.has(frame)
? transitionAtFrame(transitionRanges, frame)
: undefined;
if (activeTransition && ring) {
// Pick the next ring slot. If it's still in flight from an earlier
@@ -247,7 +251,7 @@ export async function runHybridLayeredFrameLoop(input: HybridLoopInput): Promise
// because the per-worker browser session is single-threaded.
await captureTransitionFrameOnWorker({
session,
frameIdx: i,
frameIdx: frame,
time,
transition: activeTransition,
buffers,
@@ -265,7 +269,7 @@ export async function runHybridLayeredFrameLoop(input: HybridLoopInput): Promise
const progress =
activeTransition.endFrame === activeTransition.startFrame
? 1
: (i - activeTransition.startFrame) /
: (frame - activeTransition.startFrame) /
(activeTransition.endFrame - activeTransition.startFrame);
// BLEND + ENCODE without awaiting. The promise drains back into
// `ringInFlight[slot]`; the next iteration that picks `slot`
@@ -327,7 +331,7 @@ export async function runHybridLayeredFrameLoop(input: HybridLoopInput): Promise
// Rebind ctx to this worker's session for per-layer captures
const wctx: HdrCompositeContext = { ...hdrCompositeCtx, domSession: session };
await timeHdrPhaseAsync(hdrPerf, "normalCompositeMs", () =>
compositeHdrFrame(wctx, canvas, time, stackingInfo, undefined, i),
compositeHdrFrame(wctx, canvas, time, stackingInfo, undefined, frame),
);
if (debugDumpEnabled && debugDumpDir && i % 30 === 0) {
writeFileExclusiveSync(
@@ -0,0 +1,91 @@
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, it, vi } from "vitest";
import { compositeHdrFrame } from "../../hdrCompositor.js";
import { captureSceneIntoBuffer, seekInjectAndQueryStacking } from "./captureHdrFrameShared.js";
import {
type SequentialLoopInput,
runSequentialLayeredFrameLoop,
} from "./captureHdrSequentialLoop.js";
vi.mock("./captureHdrFrameShared.js", async (importOriginal) => ({
...(await importOriginal<typeof import("./captureHdrFrameShared.js")>()),
captureSceneIntoBuffer: vi.fn(async () => {}),
seekInjectAndQueryStacking: vi.fn(async () => []),
}));
vi.mock("../../hdrCompositor.js", async (importOriginal) => ({
...(await importOriginal<typeof import("../../hdrCompositor.js")>()),
compositeHdrFrame: vi.fn(async () => {}),
}));
function windowInput(written: number[]): SequentialLoopInput {
return {
job: {
config: { fps: { num: 30, den: 1 } },
totalFrames: 10,
framesRendered: 0,
frameWindow: { startFrame: 100, endFrame: 110 },
},
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
width: 1,
height: 1,
totalFrames: 10,
nativeHdrIds: new Set<string>(),
nativeHdrImageIds: new Set<string>(),
hdrCompositeCtx: {},
hdrPerf: undefined,
hdrEncoder: { writeFrame: async () => written.push(written.length) > 0 },
domSession: { page: {} },
transitionRanges: [
{ time: 0, duration: 0, shader: "crossfade", ease: "", fromScene: "a", toScene: "b" },
].map((t) => ({ ...t, startFrame: 104, endFrame: 106 })),
sceneElements: { a: ["a"], b: ["b"] },
compositeTransfer: "srgb",
hdrTargetTransfer: undefined,
hdrVideoEndTimes: new Map(),
cleanedUpVideos: new Set(),
hdrVideoFrameSources: new Map(),
debugDumpEnabled: false,
debugDumpDir: null,
assertNotAborted: () => {},
// The loop only touches the fields above.
} as unknown as SequentialLoopInput;
}
it("seeks film frames and finds the film's transition inside a window", async () => {
const written: number[] = [];
await runSequentialLayeredFrameLoop(windowInput(written));
const seeked = vi
.mocked(seekInjectAndQueryStacking)
.mock.calls.map((call) => Math.round(Number(call[1]) * 30));
expect(seeked).toEqual(Array.from({ length: 10 }, (_, k) => 100 + k));
// Two scenes per transition frame, film frames 104-106.
const transitionFrames = vi
.mocked(captureSceneIntoBuffer)
.mock.calls.map(([args]) => args.frameIdx);
expect(transitionFrames).toEqual([104, 104, 105, 105, 106, 106]);
expect(written).toHaveLength(10);
});
it("starts a window without the HDR videos a whole render has already passed the end of", async () => {
const input = windowInput([]);
const close = vi.fn();
input.hdrVideoEndTimes.set("ended", 1);
input.hdrVideoEndTimes.set("playing", 5);
// Ends between frames 99 and 100: a whole render still draws it at frame 100, then frees it.
input.hdrVideoEndTimes.set("endsAtFirstFrame", 3.31);
for (const id of ["ended", "playing", "endsAtFirstFrame"]) {
const dir = mkdtempSync(join(tmpdir(), `hf-hdr-${id}-`));
input.hdrVideoFrameSources.set(id, { dir, windows: { close } } as never);
}
let shownAtFirstFrame: string[] = [];
vi.mocked(compositeHdrFrame).mockImplementationOnce(async () => {
shownAtFirstFrame = [...input.hdrVideoFrameSources.keys()];
});
await runSequentialLayeredFrameLoop(input);
expect(shownAtFirstFrame).toEqual(["playing", "endsAtFirstFrame"]);
});
@@ -36,11 +36,14 @@ import { writeFileExclusiveSync } from "../shared.js";
import {
captureSceneIntoBuffer,
cleanupEndedHdrVideos,
cleanupHdrVideosEndedBefore,
transitionAtFrame,
ensureFrameWritten,
type LayeredTransitionBuffers,
seekInjectAndQueryStacking,
} from "./captureHdrFrameShared.js";
import { reportFrameProgress } from "../shared.js";
import { windowStartFrame } from "../frameWindow.js";
export interface SequentialLoopInput {
job: RenderJob;
@@ -104,9 +107,18 @@ export async function runSequentialLayeredFrameLoop(input: SequentialLoopInput):
: null;
const normalCanvas = Buffer.alloc(bufSize);
const firstFrame = windowStartFrame(job.frameWindow);
cleanupHdrVideosEndedBefore(firstFrame, job.config.fps, transitionRanges, {
hdrVideoEndTimes,
cleanedUpVideos,
hdrVideoFrameSources,
sceneElements,
log,
});
for (let i = 0; i < totalFrames; i++) {
assertNotAborted();
const time = (i * job.config.fps.den) / job.config.fps.num;
const frame = firstFrame + i;
const time = (frame * job.config.fps.den) / job.config.fps.num;
if (hdrPerf) hdrPerf.frames += 1;
const stackingInfo = await seekInjectAndQueryStacking(
@@ -119,12 +131,12 @@ export async function runSequentialLayeredFrameLoop(input: SequentialLoopInput):
"frameInjectMs",
"stackingQueryMs",
);
const activeTransition = transitionRanges.find((t) => i >= t.startFrame && i <= t.endFrame);
const activeTransition = transitionAtFrame(transitionRanges, frame);
if (i % 30 === 0 && (log.isLevelEnabled?.("debug") ?? true)) {
const hdrEl = stackingInfo.find((e) => e.isHdr);
log.debug("[Render] HDR layer composite frame", {
frame: i,
frame,
time: time.toFixed(2),
hdrElement: hdrEl ? { z: hdrEl.zIndex, visible: hdrEl.visible, width: hdrEl.width } : null,
stackingCount: stackingInfo.length,
@@ -138,7 +150,7 @@ export async function runSequentialLayeredFrameLoop(input: SequentialLoopInput):
const progress =
activeTransition.endFrame === activeTransition.startFrame
? 1
: (i - activeTransition.startFrame) /
: (frame - activeTransition.startFrame) /
(activeTransition.endFrame - activeTransition.startFrame);
const sceneAIds = new Set(sceneElements[activeTransition.fromScene] ?? []);
const sceneBIds = new Set(sceneElements[activeTransition.toScene] ?? []);
@@ -169,7 +181,7 @@ export async function runSequentialLayeredFrameLoop(input: SequentialLoopInput):
hdrTargetTransfer,
hdrPerf,
log,
frameIdx: i,
frameIdx: frame,
});
}
@@ -196,7 +208,7 @@ export async function runSequentialLayeredFrameLoop(input: SequentialLoopInput):
if (hdrPerf) hdrPerf.normalFrames += 1;
timeHdrPhase(hdrPerf, "canvasClearMs", () => normalCanvas.fill(0));
await timeHdrPhaseAsync(hdrPerf, "normalCompositeMs", () =>
compositeHdrFrame(hdrCompositeCtx, normalCanvas, time, stackingInfo, undefined, i),
compositeHdrFrame(hdrCompositeCtx, normalCanvas, time, stackingInfo, undefined, frame),
);
if (debugDumpEnabled && debugDumpDir && i % 30 === 0) {
writeFileExclusiveSync(
@@ -80,6 +80,7 @@ import { wrapCaptureStageError } from "../captureStageError.js";
import { encoderFailureError } from "../encoderInterruption.js";
import type { HdrLayeredCapturePlan } from "../capturePlan.js";
import type { DeliveryEncoderOptions } from "../deliveryEncoder.js";
import { windowStartFrame } from "../frameWindow.js";
export interface CaptureHdrStageInput {
job: RenderJob;
@@ -369,7 +370,11 @@ export async function runCaptureHdrStage(
// ── Dispatch to sequential or hybrid frame loop ────────────────────
const effectiveWorkerCount = Math.max(1, workerCount);
const transitionFrameCount = partitionTransitionFrames(transitionRanges, totalFrames).size;
const transitionFrameCount = partitionTransitionFrames(
transitionRanges,
totalFrames,
windowStartFrame(job.frameWindow),
).size;
const useHybrid = shouldUseHybridLayeredPath({
hasHdrContent,
transitionFramesCount: transitionFrameCount,
@@ -29,7 +29,7 @@
import { createHash } from "node:crypto";
import { basename, join } from "node:path";
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import {
type CaptureOptions,
type CaptureSession,
@@ -44,7 +44,7 @@
* that legitimately happens on a 29.97 fps timeline).
*/
import { parseHTML } from "linkedom";
import { parseHTML } from "@hyperframes/parsers/linkedom";
import {
fpsToNumber,
normalizeRateSpec,
@@ -87,7 +87,6 @@ export interface VideoFrameCoverageErrorDetails {
export class VideoFrameCoverageError extends Error {
// Read structurally by isVideoFrameCoverageError and cross-module callers.
// fallow-ignore-next-line unused-class-member
readonly hyperframesVideoFrameCoverageError = true as const;
readonly threshold: number;
readonly worst: VideoFrameCoverageReport;

Some files were not shown because too many files have changed in this diff Show More