Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(engine): audio source-not-found names the file and shares one src resolver with lint (#4172)
Miguel Ángel3f3f3b7f10a6
diff --git a/packages/engine/src/services/audioMixer.test.ts b/packages/engine/src/services/audioMixer.test.tsindex ca328a3add..598ad3030e 100644--- a/packages/engine/src/services/audioMixer.test.ts+++ b/packages/engine/src/services/audioMixer.test.ts@@ -193,6 +193,49 @@ describe("processCompositionAudio", () => {]);});+ it.each([+ {+ src: "assets/music.mp3",+ detail:+ 'Source not found for audio element bed: src="assets/music.mp3" resolved to assets/music.mp3',+ },+ {+ src: "/assets/music.mp3",+ detail: "Source not found for audio element bed: resolved to assets/music.mp3",+ },+ ])("names where a missing local audio file was looked for ($src)", async ({ src, detail }) => {+ const baseDir = mkdtempSync(join(tmpdir(), "hf-audio-missing-"));+ const workDir = mkdtempSync(join(tmpdir(), "hf-audio-work-"));+ tempDirs.push(baseDir, workDir);++ const result = await processCompositionAudio(+ [+ {+ id: "bed",+ src,+ start: 0,+ end: 2,+ mediaStart: 0,+ layer: 0,+ volume: 1,+ type: "audio",+ },+ ],+ baseDir,+ workDir,+ join(baseDir, "out.m4a"),+ 2,+ );++ expect(result.failures).toEqual([+ expect.objectContaining({+ reason: "source_not_found",+ elementId: "bed",+ detail,+ }),+ ]);+ });+it.each([{message: "AbortError: ffprobe operation aborted",diff --git a/packages/engine/src/services/audioMixer.ts b/packages/engine/src/services/audioMixer.tsindex d4cc17aa4c..96e493b01b 100644--- a/packages/engine/src/services/audioMixer.ts+++ b/packages/engine/src/services/audioMixer.ts@@ -6,7 +6,7 @@*/import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, rmSync, writeFileSync } from "fs";-import { join, dirname } from "path";+import { join, dirname, isAbsolute, relative } from "path";import { parseHTML } from "linkedom";import { extractAudioMetadata } from "../utils/ffprobe.js";import { isNotMediaPayload } from "../utils/notMediaPayload.js";@@ -357,6 +357,21 @@ interface ExtractResult {failure?: AudioProcessingFailure;}+// Absolute paths are omitted: boundedDetail redacts them to end-of-line and they name the host.+function missingSourceMessage(+ elementId: string,+ src: string,+ baseDir: string,+ resolvedPath: string,+): string {+ const relativePath = relative(baseDir, resolvedPath).replace(/\\/g, "/");+ const insideProject = !relativePath.startsWith("..") && !isAbsolute(relativePath);+ const authored = /^([\\/]|[A-Za-z]:)/.test(src) ? "" : `src="${src}" `;+ return `Source not found for audio element ${elementId}: ${authored}resolved to ${+ insideProject ? relativePath : "a path outside the project"+ }`;+}+function boundedDetail(message: string, maxLength = 2_000): string {const redacted = message.replace(/\bhttps?:\/\/[^\s"'<>]+/gi, "<redacted-url>")@@ -1164,8 +1179,7 @@ export async function processCompositionAudio(try {let srcPath = element.src;if (!isHttpUrl(srcPath)) {- // Same browser-vs-filesystem path semantics as videos — see- // resolveProjectRelativeSrc in videoFrameExtractor for the full why.+ // Same browser-URL path semantics as videos.srcPath = resolveProjectRelativeSrc(element.src, baseDir, compiledDir);}@@ -1194,7 +1208,7 @@ export async function processCompositionAudio(owner: "user",retryable: false,elementId: element.id,- detail: boundedDetail(`Source not found for audio element ${element.id}`),+ detail: boundedDetail(missingSourceMessage(element.id, element.src, baseDir, srcPath)),});return;}diff --git a/packages/engine/src/services/videoFrameExtractor.test.ts b/packages/engine/src/services/videoFrameExtractor.test.tsindex 5527c88ac5..e60ef97b9d 100644--- a/packages/engine/src/services/videoFrameExtractor.test.ts+++ b/packages/engine/src/services/videoFrameExtractor.test.ts@@ -23,7 +23,6 @@ import {createFrameLookupTable,FrameLookupTable,rebaseVideoToWindow,- resolveProjectRelativeSrc,resolveFrameFormat,codecMayHaveAlpha,decoderForCodec,@@ -680,111 +679,6 @@ describe("resolveFrameFormat", () => {});});-// Regression: a long-standing footgun where `<video src="../assets/foo">`-// inside a sub-composition silently dropped the video from extraction. The-// browser's URL resolver clamps `..` at the served origin's root (so the-// page renders fine in the studio), but `path.join(projectDir, "../assets/foo")`-// normalizes to <parentOfProjectDir>/assets/foo, which doesn't exist —-// extraction skipped, no frame injection, rendered output shows the video's-// first decoded frame for the whole clip duration. The resolver now mirrors-// browser semantics by clamping any traversal that escapes the project root.-describe("resolveProjectRelativeSrc — sub-composition path clamping", () => {- let tmp: string;-- beforeAll(() => {- tmp = mkdtempSync(join(tmpdir(), "hf-resolver-"));- mkdirSync(join(tmp, "project", "assets"), { recursive: true });- writeFileSync(join(tmp, "project", "assets", "foo.mp4"), "");- });- afterAll(() => {- rmSync(tmp, { recursive: true, force: true });- });-- it("returns the literal join when the file exists at projectDir/src", () => {- const projectDir = join(tmp, "project");- expect(resolveProjectRelativeSrc("assets/foo.mp4", projectDir)).toBe(- join(projectDir, "assets/foo.mp4"),- );- });-- it("resolves a browser root-absolute URL from the project root", () => {- const projectDir = join(tmp, "project");- expect(resolveProjectRelativeSrc("/assets/foo.mp4", projectDir)).toBe(- join(projectDir, "assets/foo.mp4"),- );- });-- it("clamps a leading `../` so `../assets/foo.mp4` resolves to assets/foo.mp4", () => {- const projectDir = join(tmp, "project");- expect(resolveProjectRelativeSrc("../assets/foo.mp4", projectDir)).toBe(- join(projectDir, "assets/foo.mp4"),- );- });-- it("clamps multiple leading `../../../` segments", () => {- const projectDir = join(tmp, "project");- expect(resolveProjectRelativeSrc("../../../assets/foo.mp4", projectDir)).toBe(- join(projectDir, "assets/foo.mp4"),- );- });-- it("clamps mid-path traversal that escapes baseDir (not just leading `..`)", () => {- // `assets/../../foo.mp4` collapses past projectDir via path.join — this- // case used to silently escape; the resolver now strips embedded `..`- // segments and re-anchors at the project root.- const projectDir = join(tmp, "project");- expect(resolveProjectRelativeSrc("assets/../../assets/foo.mp4", projectDir)).toBe(- join(projectDir, "assets/foo.mp4"),- );- });-- it("returns the (non-existent) base-dir path on miss so callers get a stable error message", () => {- const projectDir = join(tmp, "project");- expect(resolveProjectRelativeSrc("../assets/missing.mp4", projectDir)).toBe(- join(projectDir, "../assets/missing.mp4"),- );- });-- it("prefers compiled-dir over base-dir when the file exists in both", () => {- const projectDir = join(tmp, "project");- const compiledDir = join(tmp, "compiled");- mkdirSync(join(compiledDir, "assets"), { recursive: true });- writeFileSync(join(compiledDir, "assets", "foo.mp4"), "");- expect(resolveProjectRelativeSrc("assets/foo.mp4", projectDir, compiledDir)).toBe(- join(compiledDir, "assets/foo.mp4"),- );- });-- it("resolves percent-encoded non-Latin filenames across scripts", () => {- const projectDir = join(tmp, "project");- const cases = [- ["arabic", "%D9%87%D9%86%D8%A7-%D9%85%D8%B1%D9%88%D8%A7.mp4"],- ["japanese", "%E6%97%A5%E6%9C%AC%E8%AA%9E.mp4"],- ["cyrillic", "%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82.mp4"],- ["korean", "%ED%95%9C%EA%B8%80.mp4"],- ] as const;-- for (const [, encodedFilename] of cases) {- const filename = decodeURIComponent(encodedFilename);- writeFileSync(join(projectDir, "assets", filename), "");-- expect(resolveProjectRelativeSrc(`assets/${encodedFilename}`, projectDir)).toBe(- join(projectDir, "assets", filename),- );- }- });-- it("falls back to literal filenames when percent sequences are malformed", () => {- const projectDir = join(tmp, "project");- const filename = "100%-discount.mp4";- writeFileSync(join(projectDir, "assets", filename), "");-- expect(resolveProjectRelativeSrc(`assets/${filename}`, projectDir)).toBe(- join(projectDir, "assets", filename),- );- });-});-describe("parseVideoElements", () => {it.each([{diff --git a/packages/engine/src/services/videoFrameExtractor.ts b/packages/engine/src/services/videoFrameExtractor.tsindex 04ece12c52..d456376e5c 100644--- a/packages/engine/src/services/videoFrameExtractor.ts+++ b/packages/engine/src/services/videoFrameExtractor.ts@@ -7,11 +7,11 @@*/import { copyFileSync, existsSync, linkSync, mkdirSync, rmSync } from "fs";-import { isAbsolute, join, posix, resolve, sep } from "path";+import { join } from "path";import { parseHTML } from "linkedom";+import { resolveProjectRelativeSrc } from "@hyperframes/parsers/asset-resolution";import {MEDIA_RENDER_ID_ATTR,- decodeUrlPathVariants,fpsToFfmpegArg,fpsToNumber,MEDIA_DURATION_CLAMP_EPSILON_SECONDS,@@ -63,6 +63,8 @@ import {} from "./extractionCache.js";import { framePathsFromDirectory } from "./extractedFrameIndex.js";+export { resolveProjectRelativeSrc };+export interface VideoElement {id: string;src: string;@@ -1503,71 +1505,6 @@ function sliceSupersetMember(return extractedFramesFromDirectory(work, outputDir, work.videoPath, fps);}-/**- * Resolve a relative `<video src>` to a filesystem path the way the browser- * resolves it as a URL. Browsers clamp `..` segments at the served origin's- * root; `path.join(projectDir, "../assets/foo")` does not. So a sub-comp- * `<video src="../assets/foo">` loads in the page (browser clamps to- * `<projectDir>/assets/foo`) but the filesystem-side resolver lands at- * `<parentOfProjectDir>/assets/foo` — file missing, extraction skipped,- * the rendered output shows the video's first frame for the whole clip.- *- * The clamp covers two escape patterns: leading `..` (`../assets/foo`) AND- * mid-path escapes (`assets/../../foo`) that `path.join` collapses past the- * project root silently. Both fall back to a project-rooted candidate that- * strips traversal from the resolved path.- *- * Returns the first existing candidate, or the base-dir join on miss so- * the caller's `existsSync` check produces a stable error path.- */-export function resolveProjectRelativeSrc(- src: string,- baseDir: string,- compiledDir?: string,-): string {- const qIdx = src.indexOf("?");- const cleanSrc = qIdx >= 0 ? src.slice(0, qIdx) : src;-- // Preserve explicit filesystem paths when they really exist. Otherwise a- // leading slash is a browser origin-root URL (`/assets/foo.mp4`), which the- // file server serves from the project root rather than the host filesystem.- if (isAbsolute(cleanSrc) && existsSync(cleanSrc)) return cleanSrc;-- const candidates: string[] = [];-- const addCandidate = (candidate: string): void => {- if (!candidates.includes(candidate)) candidates.push(candidate);- };-- for (const variant of decodeUrlPathVariants(cleanSrc)) {- const fromCompiled = compiledDir ? join(compiledDir, variant) : null;- const fromBase = join(baseDir, variant);-- // If the joined result escapes the project root (either via leading `..`- // or mid-path traversal that path.join collapsed past baseDir), retry- // with the basename re-anchored at the project root. This mirrors the- // browser URL clamp without relying on a particular `..` shape.- const baseAbs = resolve(baseDir);- const fromBaseAbs = resolve(fromBase);- if (!fromBaseAbs.startsWith(baseAbs + sep) && fromBaseAbs !== baseAbs) {- // Normalize first (`assets/../../assets/foo.mp4` → `../assets/foo.mp4`)- // then strip any remaining leading `..` segments. Stripping `..` from the- // raw input would leave dangling siblings (`assets/../../assets/foo`- // would become `assets/assets/foo` instead of `assets/foo`).- const normalized = posix.normalize(variant.replace(/\\/g, "/"));- const stripped = normalized.replace(/^(\.\.\/)+/, "");- if (stripped && stripped !== variant && !stripped.startsWith("..")) {- if (compiledDir) addCandidate(join(compiledDir, stripped));- addCandidate(join(baseDir, stripped));- }- }-- if (fromCompiled) addCandidate(fromCompiled);- addCandidate(fromBase);- }- return candidates.find(existsSync) ?? join(baseDir, cleanSrc);-}-export async function extractAllVideoFrames(videos: VideoElement[],baseDir: string,diff --git a/packages/lint/src/project.test.ts b/packages/lint/src/project.test.tsindex 7c7159cb1b..bc3f38ccdb 100644--- a/packages/lint/src/project.test.ts+++ b/packages/lint/src/project.test.ts@@ -690,6 +690,21 @@ describe("audio_src_not_found with templating tokens", () => {it("still flags a genuinely missing local audio file", async () => {expect(await hasAudioSrcNotFound(audioProject("audio/missing.mp3"))).toBe(true);});++ it("accepts an existing audio file addressed the way the renderer resolves it", async () => {+ for (const src of [+ "audio/bed.mp3",+ "/audio/bed.mp3",+ "../audio/bed.mp3",+ "audio/bed.mp3?v=2",+ "audio/bed.mp3#t=5",+ ]) {+ const project = audioProject(src);+ mkdirSync(join(project, "audio"), { recursive: true });+ writeFileSync(join(project, "audio", "bed.mp3"), "");+ expect(await hasAudioSrcNotFound(project)).toBe(false);+ }+ });});describe("templating tokens are checked on the raw src, before cleanAssetUrl", () => {diff --git a/packages/lint/src/project.ts b/packages/lint/src/project.tsindex b3d5e8fd36..c7659217c1 100644--- a/packages/lint/src/project.ts+++ b/packages/lint/src/project.ts@@ -14,6 +14,7 @@ import {maskNonScannableRanges,resolveExistingLocalAsset,resolveLocalAssetCandidates,+ resolveProjectRelativeSrc,} from "@hyperframes/parsers/asset-resolution";import {collectLocalVideoCandidates,@@ -362,7 +363,7 @@ function lintAudioSrcNotFound(const rootRelative = compSrcPath? rewriteAssetPath(compSrcPath, src, (path) => existsSync(join(projectDir, path))): src;- if (!resolveLocalAssetCandidates(projectDir, rootRelative).some(existsSync)) {+ if (!existsSync(resolveProjectRelativeSrc(rootRelative, projectDir))) {missingSrcs.push(src);}}diff --git a/packages/parsers/src/assetResolution.test.ts b/packages/parsers/src/assetResolution.test.tsindex 3f99b90746..ead164ad07 100644--- a/packages/parsers/src/assetResolution.test.ts+++ b/packages/parsers/src/assetResolution.test.ts@@ -1,8 +1,12 @@-import { describe, expect, it } from "vitest";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";import {collectSubCompositionSrcs,isUnresolvedAssetPlaceholder,maskNonScannableRanges,+ resolveProjectRelativeSrc,} from "./assetResolution.js";describe("maskNonScannableRanges", () => {@@ -113,3 +117,105 @@ describe("collectSubCompositionSrcs", () => {expect(collectSubCompositionSrcs("<".repeat(1024 * 1024))).toEqual([]);});});++// 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", () => {+ let tmp: string;++ beforeAll(() => {+ tmp = mkdtempSync(join(tmpdir(), "hf-resolver-"));+ mkdirSync(join(tmp, "project", "assets"), { recursive: true });+ writeFileSync(join(tmp, "project", "assets", "foo.mp4"), "");+ });+ afterAll(() => {+ rmSync(tmp, { recursive: true, force: true });+ });++ it("returns the literal join when the file exists at projectDir/src", () => {+ const projectDir = join(tmp, "project");+ expect(resolveProjectRelativeSrc("assets/foo.mp4", projectDir)).toBe(+ join(projectDir, "assets/foo.mp4"),+ );+ });++ it("resolves a browser root-absolute URL from the project root", () => {+ const projectDir = join(tmp, "project");+ expect(resolveProjectRelativeSrc("/assets/foo.mp4", projectDir)).toBe(+ join(projectDir, "assets/foo.mp4"),+ );+ });++ it("clamps a leading `../` so `../assets/foo.mp4` resolves to assets/foo.mp4", () => {+ const projectDir = join(tmp, "project");+ expect(resolveProjectRelativeSrc("../assets/foo.mp4", projectDir)).toBe(+ join(projectDir, "assets/foo.mp4"),+ );+ });++ it("clamps multiple leading `../../../` segments", () => {+ const projectDir = join(tmp, "project");+ expect(resolveProjectRelativeSrc("../../../assets/foo.mp4", projectDir)).toBe(+ join(projectDir, "assets/foo.mp4"),+ );+ });++ it("clamps mid-path traversal that escapes baseDir (not just leading `..`)", () => {+ const projectDir = join(tmp, "project");+ expect(resolveProjectRelativeSrc("assets/../../assets/foo.mp4", projectDir)).toBe(+ join(projectDir, "assets/foo.mp4"),+ );+ });++ it("returns the (non-existent) base-dir path on miss so callers get a stable error message", () => {+ const projectDir = join(tmp, "project");+ expect(resolveProjectRelativeSrc("../assets/missing.mp4", projectDir)).toBe(+ join(projectDir, "../assets/missing.mp4"),+ );+ });++ it("prefers compiled-dir over base-dir when the file exists in both", () => {+ const projectDir = join(tmp, "project");+ const compiledDir = join(tmp, "compiled");+ mkdirSync(join(compiledDir, "assets"), { recursive: true });+ writeFileSync(join(compiledDir, "assets", "foo.mp4"), "");+ expect(resolveProjectRelativeSrc("assets/foo.mp4", projectDir, compiledDir)).toBe(+ join(compiledDir, "assets/foo.mp4"),+ );+ });++ it("resolves percent-encoded non-Latin filenames across scripts", () => {+ const projectDir = join(tmp, "project");+ const cases = [+ "%D9%87%D9%86%D8%A7-%D9%85%D8%B1%D9%88%D8%A7.mp4",+ "%E6%97%A5%E6%9C%AC%E8%AA%9E.mp4",+ "%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82.mp4",+ "%ED%95%9C%EA%B8%80.mp4",+ ];++ for (const encodedFilename of cases) {+ const filename = decodeURIComponent(encodedFilename);+ writeFileSync(join(projectDir, "assets", filename), "");++ expect(resolveProjectRelativeSrc(`assets/${encodedFilename}`, projectDir)).toBe(+ join(projectDir, "assets", filename),+ );+ }+ });++ it("falls back to literal filenames when percent sequences are malformed", () => {+ const projectDir = join(tmp, "project");+ const filename = "100%-discount.mp4";+ writeFileSync(join(projectDir, "assets", filename), "");++ expect(resolveProjectRelativeSrc(`assets/${filename}`, projectDir)).toBe(+ join(projectDir, "assets", filename),+ );+ });++ it("ignores a query string or media fragment when locating the file", () => {+ const projectDir = join(tmp, "project");+ for (const src of ["assets/foo.mp4?v=2", "assets/foo.mp4#t=5", " assets/foo.mp4 "]) {+ expect(resolveProjectRelativeSrc(src, projectDir)).toBe(join(projectDir, "assets/foo.mp4"));+ }+ });+});diff --git a/packages/parsers/src/assetResolution.ts b/packages/parsers/src/assetResolution.tsindex aca5fbeb1e..b14212aa52 100644--- a/packages/parsers/src/assetResolution.ts+++ b/packages/parsers/src/assetResolution.ts@@ -1,5 +1,5 @@import { existsSync } from "node:fs";-import { isAbsolute, posix, relative, resolve } from "node:path";+import { isAbsolute, join, posix, relative, resolve, sep } from "node:path";import { decodeUrlPathVariants } from "./composition.js";/**@@ -158,6 +158,41 @@ export function resolveExistingLocalAsset(return { resolved, rootRelativePath: relative(projectRoot, resolved) };}+// Candidates for a variant whose join escaped the project root, re-anchored at the root.+function reanchoredCandidates(variant: string, baseDir: string, compiledDir?: string): string[] {+ const baseAbs = resolve(baseDir);+ const joinedAbs = resolve(join(baseDir, variant));+ if (joinedAbs === baseAbs || joinedAbs.startsWith(baseAbs + sep)) return [];+ // Normalize before stripping, or `assets/../../assets/foo` becomes `assets/assets/foo`.+ const stripped = posix.normalize(variant.replace(/\\/g, "/")).replace(/^(\.\.\/)+/, "");+ if (!stripped || stripped === variant || stripped.startsWith("..")) return [];+ return compiledDir+ ? [join(compiledDir, stripped), join(baseDir, stripped)]+ : [join(baseDir, stripped)];+}++/** 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,+): string {+ const cleanSrc = cleanAssetUrl(src);++ // A leading slash is an origin-root URL served from the project root, unless the absolute path exists.+ if (isAbsolute(cleanSrc) && existsSync(cleanSrc)) return cleanSrc;++ const candidates = new Set<string>();+ for (const variant of decodeUrlPathVariants(cleanSrc)) {+ for (const candidate of reanchoredCandidates(variant, baseDir, compiledDir)) {+ candidates.add(candidate);+ }+ if (compiledDir) candidates.add(join(compiledDir, variant));+ candidates.add(join(baseDir, variant));+ }+ return [...candidates].find(existsSync) ?? join(baseDir, cleanSrc);+}+function maskRange(src: string, pattern: RegExp): string {return src.replace(pattern, (m) => " ".repeat(m.length));}