Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(core): a composition with no authored length takes it from its clips (#4174)
Miguel Ángelfa44d7621d3a
diff --git a/packages/core/src/runtime/init.test.ts b/packages/core/src/runtime/init.test.tsindex 52a607f784..bc50d005ba 100644--- a/packages/core/src/runtime/init.test.ts+++ b/packages/core/src/runtime/init.test.ts@@ -3122,6 +3122,126 @@ describe("initSandboxRuntimeModular", () => {delete (window as Window & { __hfLottie?: unknown[] }).__hfLottie;});+ describe("a root with no data-duration and no timeline takes its length from its clips", () => {+ const mountRoot = (children: string) => {+ document.body.innerHTML = `<div data-composition-id="main" data-root="true" data-start="0" data-width="1920" data-height="1080">${children}</div>`;+ window.__timelines = {};+ initSandboxRuntimeModular();+ };++ it("counts a timed image at the dropped-image default and reports the derived source", () => {+ mountRoot('<img id="a" data-start="2" src="a.png" />');+ expect(window.__player?.getDuration()).toBe(5);+ expect(window.__hf?.durationSource).toEqual({+ source: "derived",+ seconds: 5,+ pendingClips: 0,+ });+ });++ it("counts a plain clip with data-start and data-duration", () => {+ mountRoot('<div class="clip" data-start="1" data-duration="4"></div>');+ expect(window.__player?.getDuration()).toBe(5);+ });++ it("stays at zero while a video's length is pending, so a renderer never locks in a short one", () => {+ mountRoot(+ '<div class="clip" data-start="0" data-duration="2"></div><video data-start="0"></video>',+ );+ expect(window.__player?.getDuration()).toBe(0);+ expect(window.__hf?.durationSource).toEqual({+ source: "unresolved",+ seconds: null,+ pendingClips: 1,+ });+ });++ it("stays at zero while a sub-composition's own length is not known yet", () => {+ mountRoot(+ '<div class="clip" data-start="0" data-duration="2"></div><div data-composition-id="sub" data-start="0"></div>',+ );+ expect(window.__player?.getDuration()).toBe(0);+ expect(window.__hf?.durationSource?.pendingClips).toBe(1);+ });++ it("stays at zero while a loaded Lottie has registered no animation, instead of locking in the clip's length", () => {+ const lottieWindow = window as Window & { lottie?: unknown };+ lottieWindow.lottie = { getRegisteredAnimations: () => [] };+ try {+ mountRoot('<div class="clip" data-start="0" data-duration="2"></div>');+ expect(window.__player?.getDuration()).toBe(0);+ expect(window.__hf?.durationSource).toEqual({+ source: "unresolved",+ seconds: null,+ pendingClips: 1,+ });+ } finally {+ delete lottieWindow.lottie;+ }+ });++ it("treats a declared data-lottie-src or a loaded DotLottie as a pending clip too", () => {+ mountRoot(+ '<div class="clip" data-start="0" data-duration="2"></div><div data-lottie-src="a.json"></div>',+ );+ expect(window.__player?.getDuration()).toBe(0);+ const dotLottieWindow = window as Window & { DotLottie?: unknown };+ dotLottieWindow.DotLottie = class {};+ try {+ mountRoot('<div class="clip" data-start="0" data-duration="2"></div>');+ expect(window.__hf?.durationSource?.pendingClips).toBe(1);+ } finally {+ delete dotLottieWindow.DotLottie;+ }+ });++ it("uses the Lottie's own length once it is registered, not the clips' length", () => {+ const lottieWindow = window as Window & { lottie?: unknown; __hfLottie?: unknown[] };+ lottieWindow.lottie = { getRegisteredAnimations: () => [] };+ lottieWindow.__hfLottie = [+ { play: () => {}, pause: () => {}, totalFrames: 150, frameRate: 30 },+ ];+ try {+ mountRoot('<div class="clip" data-start="0" data-duration="2"></div>');+ expect(window.__player?.getDuration()).toBe(5);+ expect(window.__hf?.durationSource).toBeUndefined();+ } finally {+ delete lottieWindow.lottie;+ delete lottieWindow.__hfLottie;+ }+ });++ it("posts the derived-length diagnostic only for a derived length", () => {+ const spy = vi.spyOn(window, "postMessage");+ const codes = () =>+ spy.mock.calls+ .map(([message]) => (message as { code?: string } | undefined)?.code)+ .filter((code) => code === "composition_duration_derived");+ mountRoot("<p>static</p>");+ expect(codes()).toHaveLength(0);+ mountRoot('<div class="clip" data-start="0" data-duration="2"></div>');+ expect(codes()).toHaveLength(1);+ });++ it("reports no derived source when a timeline supplies the length", () => {+ mountRoot('<div class="clip" data-start="0" data-duration="2"></div>');+ expect(window.__hf?.durationSource?.source).toBe("derived");+ document.body.innerHTML = "";+ window.__timelines = {};+ document.body.innerHTML =+ '<div data-composition-id="main" data-root="true" data-start="0" data-duration="8"></div>';+ initSandboxRuntimeModular();+ expect(window.__player?.getDuration()).toBe(8);+ expect(window.__hf?.durationSource).toBeUndefined();+ });++ it("stays at zero, reported unresolved, when there is no timed content", () => {+ mountRoot("<p>static</p>");+ expect(window.__player?.getDuration()).toBe(0);+ expect(window.__hf?.durationSource?.source).toBe("unresolved");+ });+ });+it("regression: a GSAP timeline's duration is unaffected by adapter duration inference", () => {// A GSAP composition can legitimately have an incidental, short CSS// animation running alongside the timeline (e.g. a decorative shimmer).diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.tsindex fe24b7ea08..7dc7173e36 100644--- a/packages/core/src/runtime/init.ts+++ b/packages/core/src/runtime/init.ts@@ -37,6 +37,7 @@ import { createPickerModule } from "./picker";import { createRuntimePlayer, type RuntimePlayerTransport } from "./player";import { createRuntimeState } from "./state";import { collectRuntimeTimelinePayload } from "./timeline";+import { resolveCompositionDuration } from "@hyperframes/parsers/composition-duration";import { createRuntimeStartTimeResolver } from "./startResolver";import { createClipTree } from "./clipTree";import { loadExternalCompositions, loadInlineTemplateCompositions } from "./compositionLoader";@@ -920,15 +921,19 @@ export function initSandboxRuntimeModular(): void {// this every tick, and it should not pay for a resolver it never uses.if (mediaNodes.length === 0) return null;return withTimingResolver(() => {- let maxWindowEndSeconds = 0;+ const clipEnds: number[] = [];for (const node of mediaNodes) {const start = resolveAbsoluteMediaStartSeconds(node);if (!Number.isFinite(start)) continue;const duration = resolveMediaElementDurationSeconds(node);if (duration == null || duration <= MIN_VALID_TIMELINE_DURATION_SECONDS) continue;- maxWindowEndSeconds = Math.max(maxWindowEndSeconds, Math.max(0, start) + duration);+ clipEnds.push(Math.max(0, start) + duration);}- return maxWindowEndSeconds > MIN_VALID_TIMELINE_DURATION_SECONDS ? maxWindowEndSeconds : null;+ const { seconds } = resolveCompositionDuration({+ authoredDurationSeconds: null,+ clipEndsSeconds: clipEnds,+ });+ return seconds !== null && seconds > MIN_VALID_TIMELINE_DURATION_SECONDS ? seconds : null;});};@@ -940,16 +945,13 @@ export function initSandboxRuntimeModular(): void {timelineRegistry: timelines,includeAuthoredTimingAttrs: true,});- let maxWindowEndSeconds = 0;// The root's own data-duration is the authored source of truth for// composition length. Without it in the floor, a GSAP timeline that ends// even slightly short of the declared duration shrinks the playable// window — and duration-gated consumers (e.g. the studio's adapter// selection) silently reject the runtime player, losing audio playback.const rootDeclaredSeconds = parseStrictFiniteTimingNumber(rootEl.getAttribute("data-duration"));- if (rootDeclaredSeconds != null && rootDeclaredSeconds > 0) {- maxWindowEndSeconds = rootDeclaredSeconds;- }+ const subCompositionEnds: number[] = [];const compositionNodes = Array.from(rootEl.querySelectorAll("[data-composition-id][data-start]"),);@@ -960,9 +962,98 @@ export function initSandboxRuntimeModular(): void {const start = startResolver.resolveStartForElement(node, 0);const duration = startResolver.resolveDurationForElement(node);if (!Number.isFinite(start) || duration == null || duration <= 0) continue;- maxWindowEndSeconds = Math.max(maxWindowEndSeconds, Math.max(0, start) + duration);+ subCompositionEnds.push(Math.max(0, start) + duration);}- return maxWindowEndSeconds > MIN_VALID_TIMELINE_DURATION_SECONDS ? maxWindowEndSeconds : null;+ // A floor, not a resolution: the declared duration and every sub-composition end all hold,+ // so the latest of them is the floor.+ const { seconds: floorSeconds } = resolveCompositionDuration({+ authoredDurationSeconds: null,+ clipEndsSeconds: [rootDeclaredSeconds, ...subCompositionEnds],+ });+ return floorSeconds !== null && floorSeconds > MIN_VALID_TIMELINE_DURATION_SECONDS+ ? floorSeconds+ : null;+ };++ /** The last-resort length: the latest end among the root's timed clips, used only when no+ * timeline, floor or caller-supplied length exists. Pending media is counted, not guessed. */+ // A sub-composition's length comes from its own timeline, which may not be registered yet.+ const isCompositionHost = (node: Element): boolean =>+ node.hasAttribute("data-composition-id") || node.hasAttribute("data-composition-src");+ // Lottie registers its animations from author scripts, often after the runtime is ready, and+ // nothing in the DOM says when. A loaded Lottie library or a declared source means a length+ // that has not been registered yet, so it counts as a pending clip like media does.+ const hasUnregisteredLottie = (rootEl: Element): boolean => {+ const lottieWindow = window as Window & { lottie?: unknown; DotLottie?: unknown };+ return Boolean(+ lottieWindow.lottie || lottieWindow.DotLottie || rootEl.querySelector("[data-lottie-src]"),+ );+ };+ const resolveContentDerivedDuration = () => {+ const rootEl = resolveRootCompositionElement();+ if (!rootEl)+ return resolveCompositionDuration({ authoredDurationSeconds: null, clipEndsSeconds: [] });+ const startResolver = createRuntimeStartTimeResolver({+ timelineRegistry: (window.__timelines ?? {}) as Record<+ string,+ RuntimeTimelineLike | undefined+ >,+ includeAuthoredTimingAttrs: true,+ });+ const clipEnds: Array<number | null> = [];+ for (const node of Array.from(rootEl.querySelectorAll("[data-start]"))) {+ if (!isElementNode(node)) continue;+ const start = startResolver.resolveStartForElement(node, 0);+ if (!Number.isFinite(start)) continue;+ const duration = startResolver.resolveDurationForElement(node);+ if (duration != null) clipEnds.push(Math.max(0, start) + duration);+ else if (isMediaElement(node) || isCompositionHost(node)) clipEnds.push(null);+ }+ if (hasUnregisteredLottie(rootEl)) clipEnds.push(null);+ const result = resolveCompositionDuration({+ authoredDurationSeconds: null,+ clipEndsSeconds: clipEnds,+ });+ // A length that a pending clip can still extend is not final, and a renderer that reads the+ // duration once would lock the short one in: stay at zero until every clip's length is known.+ return result.pendingClips > 0+ ? {+ ...result,+ seconds: null,+ source: "unresolved" as const,+ reason: "a clip's length is pending",+ }+ : result;+ };++ let contentDerivedCache: {+ revision: number;+ result: ReturnType<typeof resolveContentDerivedDuration>;+ } | null = null;+ /** Cached per timing revision like the floors; the render path never reads a cache. */+ const readContentDerivedDuration = () => {+ if (renderCaptureSeekStarted) return resolveContentDerivedDuration();+ const revision = readCompositionTimingRevision();+ if (contentDerivedCache?.revision !== revision) {+ contentDerivedCache = { revision, result: resolveContentDerivedDuration() };+ }+ return contentDerivedCache.result;+ };++ /** Carries how a length that no timeline supplied was found, for render telemetry. */+ const publishDerivedDuration = (result: ReturnType<typeof resolveCompositionDuration>) => {+ window.__hf = window.__hf || {};+ window.__hf.durationSource = {+ source: result.source,+ seconds: result.seconds,+ pendingClips: result.pendingClips,+ };+ if (result.source !== "derived") return;+ postRuntimeDiagnosticOnce(+ "composition_duration_derived",+ { source: result.source, seconds: result.seconds, pendingClips: result.pendingClips },+ `composition_duration_derived:${result.seconds}`,+ );};const resolveMediaDurationFloorSeconds = (): number | null => {@@ -1217,14 +1308,21 @@ export function initSandboxRuntimeModular(): void {const fallbackDuration =Number.isFinite(fallback) && fallback > MIN_VALID_TIMELINE_DURATION_SECONDS ? fallback : 0;let safeDuration = 0;+ let derivedDuration: ReturnType<typeof resolveContentDerivedDuration> | null = null;// Timeline is the source of truth for authored composition duration.if (isUsableTimelineDuration(timelineDuration)) {safeDuration = Math.max(timelineDuration, durationFloor, fallbackDuration);} else if (isUsableTimelineDuration(durationFloor)) {safeDuration = Math.max(durationFloor, fallbackDuration);- } else {+ } else if (fallbackDuration > 0) {safeDuration = fallbackDuration;+ } else {+ derivedDuration = readContentDerivedDuration();+ safeDuration = derivedDuration.seconds ?? 0;}+ // The published source describes only a length that was derived; any other source clears it.+ if (derivedDuration) publishDerivedDuration(derivedDuration);+ else if (window.__hf?.durationSource) delete window.__hf.durationSource;return safeDuration > 0 ? Math.max(0, safeDuration) : 0;};diff --git a/packages/core/src/runtime/window.d.ts b/packages/core/src/runtime/window.d.tsindex 3de25e17fc..61ed1662b8 100644--- a/packages/core/src/runtime/window.d.ts+++ b/packages/core/src/runtime/window.d.ts@@ -46,6 +46,12 @@ declare global {onSwallowed?: (label: string, err: unknown) => void;seek?: (timeSeconds: number, options?: RuntimeSeekOptions) => void;duration?: number;+ /** How a length that no timeline supplied was found: the render telemetry reads this. */+ durationSource?: {+ source: "authored" | "derived" | "unresolved";+ seconds: number | null;+ pendingClips: number;+ };/** Borrow an element's playback while the transport clock is paused, so the* runtime's paused-side enforcement leaves it alone. Always release. */leasePausedMedia?: (el: HTMLMediaElement) => void;diff --git a/packages/lint/src/rules/composition.test.ts b/packages/lint/src/rules/composition.test.tsindex 91452e58ac..719d8061e1 100644--- a/packages/lint/src/rules/composition.test.ts+++ b/packages/lint/src/rules/composition.test.ts@@ -1639,6 +1639,55 @@ describe("composition rules", () => {expect(finding?.severity).toBe("error");});+ it("warns, and says where to author the length, when timed clips give the root a length", async () => {+ const html = `<html><body>+ <div data-composition-id="main" data-start="0" data-width="1920" data-height="1080">+ <img src="a.png" data-start="2" />+ <div class="clip" data-start="0" data-duration="6"></div>+ </div>+ </body></html>`;+ const result = await lintHyperframeHtml(html);+ expect(find(result.findings)).toBeUndefined();+ const derived = result.findings.find((f) => f.code === "root_composition_duration_derived");+ expect(derived?.severity).toBe("warning");+ expect(derived?.message).toContain("at least 6s");+ expect(derived?.fixHint).toContain("data-duration");+ });++ it("counts a clip with a reference start or a video with no length as known only at runtime", async () => {+ const html = `<html><body>+ <div data-composition-id="main" data-start="0" data-width="1920" data-height="1080">+ <img src="a.png" data-start="0" />+ <video src="v.mp4" data-start="0"></video>+ <div class="clip" data-start="a+1" data-duration="2"></div>+ </div>+ </body></html>`;+ const result = await lintHyperframeHtml(html);+ const derived = result.findings.find((f) => f.code === "root_composition_duration_derived");+ expect(derived?.message).toContain("at least 3s");+ expect(derived?.message).toContain("2 clip(s) whose length is only known at runtime");+ });++ it("does not count a clip whose data-end is before its start", async () => {+ const html = `<html><body>+ <div data-composition-id="main" data-start="0" data-width="1920" data-height="1080">+ <div class="clip" data-start="5" data-end="3"></div>+ </div>+ </body></html>`;+ const result = await lintHyperframeHtml(html);+ expect(find(result.findings)?.severity).toBe("error");+ });++ it("still errors when the only clips have no length to derive from", async () => {+ const html = `<html><body>+ <div data-composition-id="main" data-start="0" data-width="1920" data-height="1080">+ <div class="clip" data-start="0"></div>+ </div>+ </body></html>`;+ const result = await lintHyperframeHtml(html);+ expect(find(result.findings)?.severity).toBe("error");+ });+it("does not error when data-duration is declared on the root", async () => {const html = `<html><body><div data-composition-id="main" data-start="0" data-duration="6" data-width="1920" data-height="1080">diff --git a/packages/lint/src/rules/composition.ts b/packages/lint/src/rules/composition.tsindex 59df0415f6..4fedabd3c9 100644--- a/packages/lint/src/rules/composition.ts+++ b/packages/lint/src/rules/composition.ts@@ -12,6 +12,12 @@ import {} from "../utils";import { COMPOSITION_VARIABLE_TYPES, isSafeMediaUrl } from "@hyperframes/parsers/composition";import { COMPOSITION_ATTRIBUTES, readClipTiming } from "@hyperframes/parsers/composition-contract";+import { resolveCompositionDuration } from "@hyperframes/parsers/composition-duration";+import {+ readAuthoredDurationSeconds,+ resolveMediaDuration,+ type MediaTag,+} from "@hyperframes/parsers/media-duration";// Agent guidance thresholds: warning-only nudges for files/tracks that become hard// to inspect and revise reliably in a single composition.@@ -1050,6 +1056,25 @@ export const compositionRules: Array<(ctx: LintContext) => HyperframeLintFindingconst hasAnyNonGsapSignal = usesLottie || usesThree || usesWaapi || hasCssAnimationName;if (!hasAnyNonGsapSignal) {+ const derived = deriveDurationFromClips(tags, rootTag);+ if (derived.source === "derived") {+ return [+ {+ code: "root_composition_duration_derived",+ severity: "warning",+ message:+ "Root composition has no data-duration and no GSAP timeline, so its length is taken from " ++ `its clips: at least ${derived.seconds}s` ++ (derived.pendingClips > 0+ ? `, and ${derived.pendingClips} clip(s) whose length is only known at runtime`+ : "") ++ ".",+ fixHint:+ 'Add data-duration="<seconds>" to the root element to set the length yourself.',+ snippet: truncateSnippet(rootTag.raw),+ },+ ];+ }// No GSAP timeline, no data-duration, and nothing for any adapter to// discover — the composition has no source of truth for duration at// all. This is the exact shape of the 27K "zero duration" render@@ -1205,3 +1230,37 @@ export const compositionRules: Array<(ctx: LintContext) => HyperframeLintFinding];},];++const CLIP_MEDIA_TAGS = new Set<string>(["img", "video", "audio"]);++/** The root's length from its timed clips, through the shared resolvers. A video or audio with no+ * authored length is pending here (only the file knows it), so it is counted, not guessed. */+function deriveDurationFromClips(tags: OpenTag[], rootTag: OpenTag) {+ const clipEnds: Array<number | null> = [];+ for (const tag of tags) {+ if (tag === rootTag) continue;+ const startRaw = readAttr(tag.raw, "data-start");+ if (startRaw === null) continue;+ const start = Number(startRaw);+ // A reference start ("intro+2") is resolved by the runtime; here it is a clip of unknown end.+ if (!Number.isFinite(start)) {+ clipEnds.push(null);+ continue;+ }+ const getAttr = (name: string) => readAttr(tag.raw, name);+ const authored = readAuthoredDurationSeconds(getAttr, start);+ if (CLIP_MEDIA_TAGS.has(tag.name)) {+ const { seconds } = resolveMediaDuration({+ tag: tag.name as MediaTag,+ authoredDurationSeconds: authored,+ sourceDurationSeconds: null,+ mediaStartSeconds: 0,+ playbackRate: 1,+ });+ clipEnds.push(seconds === null ? null : start + seconds);+ } else if (authored !== null && authored > 0) {+ clipEnds.push(start + authored);+ }+ }+ return resolveCompositionDuration({ authoredDurationSeconds: null, clipEndsSeconds: clipEnds });+}diff --git a/packages/parsers/package-subpaths.json b/packages/parsers/package-subpaths.jsonindex 0ccb3cdf24..122a255878 100644--- a/packages/parsers/package-subpaths.json+++ b/packages/parsers/package-subpaths.json@@ -121,6 +121,12 @@"runtime": "./dist/assetResolution.js","types": "./dist/assetResolution.d.ts","environments": ["bun", "node"]+ },+ "./composition-duration": {+ "source": "./src/compositionDuration.ts",+ "runtime": "./dist/compositionDuration.js",+ "types": "./dist/compositionDuration.d.ts",+ "environments": ["browser", "bun", "node"]}}}diff --git a/packages/parsers/package.json b/packages/parsers/package.jsonindex 5db7df41d1..c721768521 100644--- a/packages/parsers/package.json+++ b/packages/parsers/package.json@@ -129,6 +129,12 @@"node": "./dist/assetResolution.js","import": "./src/assetResolution.ts","types": "./src/assetResolution.ts"+ },+ "./composition-duration": {+ "bun": "./src/compositionDuration.ts",+ "node": "./dist/compositionDuration.js",+ "import": "./src/compositionDuration.ts",+ "types": "./src/compositionDuration.ts"}},"publishConfig": {@@ -210,6 +216,10 @@"./asset-resolution": {"import": "./dist/assetResolution.js","types": "./dist/assetResolution.d.ts"+ },+ "./composition-duration": {+ "import": "./dist/compositionDuration.js",+ "types": "./dist/compositionDuration.d.ts"}},"main": "./dist/index.js",diff --git a/packages/parsers/src/compositionDuration.test.ts b/packages/parsers/src/compositionDuration.test.tsnew file mode 100644index 0000000000..eaac87b96a--- /dev/null+++ b/packages/parsers/src/compositionDuration.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from "vitest";+import { resolveCompositionDuration } from "./compositionDuration.js";++describe("resolveCompositionDuration", () => {+ it("an authored duration wins over any clip end", () => {+ expect(+ resolveCompositionDuration({ authoredDurationSeconds: 6, clipEndsSeconds: [3, 9] }),+ ).toEqual({ seconds: 6, source: "authored", pendingClips: 0 });+ });++ it("derives the latest clip end when nothing is authored", () => {+ expect(+ resolveCompositionDuration({ authoredDurationSeconds: null, clipEndsSeconds: [2, 7.5, 4] }),+ ).toEqual({ seconds: 7.5, source: "derived", pendingClips: 0 });+ });++ it("counts a pending clip instead of guessing its end", () => {+ expect(+ resolveCompositionDuration({ authoredDurationSeconds: null, clipEndsSeconds: [4, null] }),+ ).toEqual({ seconds: 4, source: "derived", pendingClips: 1 });+ });++ it("is unresolved with a reason when there is nothing to derive from", () => {+ expect(+ resolveCompositionDuration({ authoredDurationSeconds: null, clipEndsSeconds: [] }),+ ).toEqual({+ seconds: null,+ source: "unresolved",+ pendingClips: 0,+ reason: "no authored duration and no clip with a length",+ });+ expect(+ resolveCompositionDuration({ authoredDurationSeconds: null, clipEndsSeconds: [null] }).reason,+ ).toBe("every clip's length is still pending");+ });++ it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])(+ "does not treat %s as an authored duration or a clip end",+ (bad) => {+ expect(+ resolveCompositionDuration({ authoredDurationSeconds: bad, clipEndsSeconds: [bad] }).source,+ ).toBe("unresolved");+ },+ );+});diff --git a/packages/parsers/src/compositionDuration.ts b/packages/parsers/src/compositionDuration.tsnew file mode 100644index 0000000000..9bdda9bc0c--- /dev/null+++ b/packages/parsers/src/compositionDuration.ts@@ -0,0 +1,44 @@+/** How long a composition is when nothing runs it: its authored `data-duration`, else the latest+ * end among its clips. A clip whose length is not known yet is counted, never guessed. */++export type CompositionDurationSource = "authored" | "derived" | "unresolved";++export interface CompositionDurationResult {+ seconds: number | null;+ source: CompositionDurationSource;+ /** Clips whose end is not known yet; a `derived` length is a lower bound while this is above 0. */+ pendingClips: number;+ /** Set only when source is "unresolved". */+ reason?: string;+}++export interface ResolveCompositionDurationInput {+ authoredDurationSeconds: number | null;+ /** Each clip's end on the composition timeline, or null while its length is pending. */+ clipEndsSeconds: readonly (number | null)[];+}++const isPositiveFinite = (value: number | null): value is number =>+ value !== null && Number.isFinite(value) && value > 0;++export function resolveCompositionDuration(+ input: ResolveCompositionDurationInput,+): CompositionDurationResult {+ const pendingClips = input.clipEndsSeconds.filter((end) => end === null).length;+ if (isPositiveFinite(input.authoredDurationSeconds)) {+ return { seconds: input.authoredDurationSeconds, source: "authored", pendingClips };+ }+ const known = input.clipEndsSeconds.filter(isPositiveFinite);+ if (known.length > 0) {+ return { seconds: Math.max(...known), source: "derived", pendingClips };+ }+ return {+ seconds: null,+ source: "unresolved",+ pendingClips,+ reason:+ pendingClips > 0+ ? "every clip's length is still pending"+ : "no authored duration and no clip with a length",+ };+}diff --git a/packages/parsers/src/index.ts b/packages/parsers/src/index.tsindex 2b548aed3f..783d8820ed 100644--- a/packages/parsers/src/index.ts+++ b/packages/parsers/src/index.ts@@ -11,6 +11,7 @@ export * from "./canvasScaffoldPatterns.js";export * from "./topLevelElements.js";export * from "./timingMismatches.js";export * from "./mediaDuration.js";+export * from "./compositionDuration.js";// Pure, browser-safe composition primitives shared by the linter (so it can// consume them without depending on @hyperframes/core). The Node-only assetdiff --git a/packages/parsers/tsup.config.ts b/packages/parsers/tsup.config.tsindex 90ce049021..dff60190b5 100644--- a/packages/parsers/tsup.config.ts+++ b/packages/parsers/tsup.config.ts@@ -14,6 +14,7 @@ export default defineConfig({assets: "src/assets.ts",composition: "src/composition.ts",compositionContract: "src/compositionContract.ts",+ compositionDuration: "src/compositionDuration.ts",mediaDuration: "src/mediaDuration.ts",mediaDurationFixtures: "src/mediaDurationFixtures.ts",topLevelElements: "src/topLevelElements.ts",diff --git a/skills-manifest.json b/skills-manifest.jsonindex f6a61ea697..c305a0fdbb 100644--- a/skills-manifest.json+++ b/skills-manifest.json@@ -34,7 +34,7 @@"files": 11},"hyperframes-core": {- "hash": "99a07539f407ca0d",+ "hash": "77ce4deba31148a2","files": 11},"hyperframes-creative": {diff --git a/skills/hyperframes-core/references/data-attributes.md b/skills/hyperframes-core/references/data-attributes.mdindex c3dac793df..4f410a8656 100644--- a/skills/hyperframes-core/references/data-attributes.md+++ b/skills/hyperframes-core/references/data-attributes.md@@ -14,7 +14,7 @@ Every renderable composition needs one root element:| `data-fps` | No | Optional frame rate hint. CLI render flags can override output fps. || `data-composition-variables` | No | JSON array of variable declarations (on `<html>`). See `variables-and-media.md`. |-\*`data-duration` is optional whenever the runtime can auto-infer duration: a registered GSAP timeline, a finite CSS animation, a finite WAAPI `element.animate()`, or a registered Lottie animation. It is **required** for Three.js (no auto-inference), for infinite/unbounded CSS or WAAPI animations, and for any composition with no GSAP timeline and no animation signal at all. `npx hyperframes lint` enforces this (`root_composition_missing_duration_source`). Per-runtime inference lives in `hyperframes-animation/adapters/`.+\*`data-duration` is optional whenever the runtime can auto-infer duration: a registered GSAP timeline, a finite CSS animation, a finite WAAPI `element.animate()`, a registered Lottie animation, or timed clips (the root then ends at its latest clip end, and lint only warns `root_composition_duration_derived`). It is **required** for Three.js (no auto-inference), for infinite/unbounded CSS or WAAPI animations, and for any composition with no GSAP timeline, no animation signal and no timed clip with a length. `npx hyperframes lint` enforces this (`root_composition_missing_duration_source`). Per-runtime inference lives in `hyperframes-animation/adapters/`.The root should be `position: relative`, have explicit pixel dimensions, and hide overflow unless intentionally composing outside the frame.