Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(parsers): detect where the gsap timeline disagrees with timing attributes (#4147)
Miguel Ángel144e8023c661
diff --git a/packages/parsers/src/gsapParserAcorn.ts b/packages/parsers/src/gsapParserAcorn.tsindex f8f4ef962c..9e929947ce 100644--- a/packages/parsers/src/gsapParserAcorn.ts+++ b/packages/parsers/src/gsapParserAcorn.ts@@ -711,6 +711,17 @@ function isGsapTimelineCall(node: any): boolean {interface TimelineDefaults {ease?: string;duration?: number;+ durationUnresolved?: boolean;+}++/** True when the vars argument may carry a duration that static evaluation could not read. */+function hasUnknownDuration(varsNode: any, scope: ScopeBindings): boolean {+ if (!varsNode) return false;+ if (varsNode.type !== "ObjectExpression") return true;+ const props: any[] = varsNode.properties ?? [];+ if (props.some((p) => p.type === "SpreadElement")) return true;+ const prop = props.find((p) => isObjectProperty(p) && propKeyName(p) === "duration");+ return prop !== undefined && typeof resolveNode(prop.value, scope) !== "number";}// How the timeline is referred to in source. `identifier` is the canonical@@ -782,7 +793,10 @@ function extractTimelineDefaults(const key = propKeyName(prop);const val = resolveNode(prop.value, scope);if (key === "ease" && typeof val === "string") result.ease = val;- if (key === "duration" && typeof val === "number") result.duration = val;+ if (key === "duration") {+ if (typeof val === "number") result.duration = val;+ else result.durationUnresolved = true;+ }}return Object.keys(result).length > 0 ? result : undefined;}@@ -1326,6 +1340,8 @@ function tweenCallToAnimation(if (duration === undefined && keyframesData) {duration = computeKeyframesTotalDuration(call.varsArg, scope, source);}+ const durationUnresolved =+ call.method !== "set" && duration === undefined && hasUnknownDuration(call.varsArg, scope);// Relabel object-proxy / empty-target tweens so they don't read as bare// __unresolved__: a dwell/hold spacer or an onUpdate-driven DOM channel (#5/#11).@@ -1385,6 +1401,7 @@ function tweenCallToAnimation(if (keyframesData) anim.keyframes = keyframesData;if (motionPathResult) anim.arcPath = motionPathResult.arcPath;if (hasUnresolvedKeyframes) anim.hasUnresolvedKeyframes = true;+ if (durationUnresolved) anim.durationUnresolved = true;if (selector === "__unresolved__") anim.hasUnresolvedSelector = true;if (provenance) anim.provenance = provenance;return anim;@@ -1601,8 +1618,9 @@ function applyTimelineDefaults(if (!defaults) return;for (const anim of anims) {if (anim.method === "set") continue;- if (anim.duration === undefined && defaults.duration !== undefined) {- anim.duration = defaults.duration;+ if (anim.duration === undefined && !anim.durationUnresolved) {+ if (defaults.duration !== undefined) anim.duration = defaults.duration;+ else if (defaults.durationUnresolved) anim.durationUnresolved = true;}if (anim.ease === undefined && defaults.ease !== undefined) {anim.ease = defaults.ease;@@ -1669,6 +1687,9 @@ function resolveTimelinePositions(): void {let cursor = 0;let prevStart = 0;+ // Once a tween's start or duration is unknown, the timeline end is unknown:+ // every later position that reads the cursor, the previous start or a label is unresolved.+ let cursorKnown = true;const labels = new Map<string, number>();// Interleave addLabel definitions with tweens by source order so labels are// available exactly when later tweens reference them.@@ -1678,6 +1699,7 @@ function resolveTimelinePositions(const defineLabel = (def: AddLabelDef): void => {let value: number;if (typeof def.position === "number") value = def.position;+ else if (!cursorKnown) return;else if (typeof def.position === "string") {value = resolveLabelPosition(def.position, labels, cursor) ?? cursor;} else value = cursor; // no position ⇒ end of timeline@@ -1700,8 +1722,11 @@ function resolveTimelinePositions(}const duration = anim.method === "set" ? 0 : (anim.duration ?? GSAP_DEFAULT_DURATION);- const start = resolveAnimStart(anim, cursor, prevStart, labels);+ const readsCursor = anim.implicitPosition || typeof anim.position !== "number";+ const start =+ cursorKnown || !readsCursor ? resolveAnimStart(anim, cursor, prevStart, labels) : null;+ if (start == null || anim.durationUnresolved) cursorKnown = false;if (start != null) {anim.resolvedStart = Math.max(0, start);prevStart = anim.resolvedStart;diff --git a/packages/parsers/src/gsapSerialize.ts b/packages/parsers/src/gsapSerialize.tsindex cb51b7a2f4..227b188f97 100644--- a/packages/parsers/src/gsapSerialize.ts+++ b/packages/parsers/src/gsapSerialize.ts@@ -57,6 +57,8 @@ export interface GsapAnimation {properties: Record<string, number | string>;fromProperties?: Record<string, number | string>;duration?: number;+ /** A `duration` was authored but is not a static number: unknown, not the 0.5s default. */+ durationUnresolved?: boolean;ease?: string;/** Non-editable GSAP config (stagger, yoyo, repeat, etc.) preserved for round-trips. */extras?: Record<string, unknown>;diff --git a/packages/parsers/src/gsapUnroll.test.ts b/packages/parsers/src/gsapUnroll.test.tsindex 57e2ae2eaa..4dfa1e23f6 100644--- a/packages/parsers/src/gsapUnroll.test.ts+++ b/packages/parsers/src/gsapUnroll.test.ts@@ -59,4 +59,100 @@ describe("unrollComputedTimeline", () => {tl.from("#a", { opacity: 0, duration: 0.5 }, 0.1);`;expect(unrollComputedTimeline(script)).toBe(script);});++ it("leaves a helper call as authored when a tween duration is not a static number", () => {+ const script = `const tl = gsap.timeline();+function fade(sel, at) { tl.to(sel, { opacity: 1, duration: LEN }, at); }+fade("#a", 1);+fade("#b", 2);`;+ expect(unrollComputedTimeline(script)).toBe(script);+ });++ it("still unrolls a sibling statement whose timing is fully known", () => {+ const script = `const tl = gsap.timeline();+function fade(sel, at, len) { tl.to(sel, { opacity: 1, duration: len }, at); }+fade("#a", 1, LEN);+fade("#b", 2, 0.5);`;+ const out = unrollComputedTimeline(script);+ expect(out).toContain('fade("#a", 1, LEN);');+ expect(out).toContain("function fade");+ expect(out).toContain("duration: 0.5");+ });++ it("leaves a nested helper chain declared and callable", () => {+ const script = `const tl = gsap.timeline();+function fade(sel, at) { tl.to(sel, { opacity: 1, duration: 1 }, at); }+function pop(sel, at) { fade(sel, at); }+pop("#a", 1);+fade("#b", 2);`;+ const out = unrollComputedTimeline(script);+ expect(out).toContain("function pop");+ expect(out).toContain("function fade");+ expect(out).toContain('pop("#a", 1);');+ expect(out).not.toContain('tl.to("#a"');+ });++ it("leaves a call site untouched when its helper also runs a nested helper", () => {+ const script = `const tl = gsap.timeline();+function fade(sel, at) { tl.to(sel, { opacity: 1, duration: 1 }, at); }+function pop(sel, at) { fade(sel, at); tl.to(sel, { scale: 2, duration: 1 }, at); }+pop("#a", 1);`;+ expect(unrollComputedTimeline(script)).toBe(script);+ });++ it("leaves an arrow-function helper chain untouched", () => {+ const script = `const tl = gsap.timeline();+const fade = (sel, at) => { tl.to(sel, { opacity: 1, duration: 1 }, at); };+const pop = (sel, at) => { fade(sel, at); };+pop("#a", 1);`;+ expect(unrollComputedTimeline(script)).toBe(script);+ });++ it("keeps a helper that a call the parser did not expand still reaches", () => {+ const script = `const tl = gsap.timeline();+function fade(sel, at) { tl.to(sel, { opacity: 1, duration: 1 }, at); }+(function () { fade("#z", 5); })();+fade("#b", 2);`;+ const out = unrollComputedTimeline(script);+ expect(out).toContain("function fade");+ expect(out).toContain('tl.to("#b"');+ });++ it.each(["$fade", "fade$", "fadé"])(+ "keeps helper %s that an unexpanded call still reaches",+ (name) => {+ const script = `const tl = gsap.timeline();+function ${name}(sel, at) { tl.to(sel, { opacity: 1, duration: 1 }, at); }+(function () { ${name}("#z", 5); })();+${name}("#b", 2);`;+ expect(unrollComputedTimeline(script)).toContain(`function ${name}`);+ },+ );++ it("does not treat a longer name as a reference to a shorter helper", () => {+ const script = `const tl = gsap.timeline();+function fade(sel, at) { tl.to(sel, { opacity: 1, duration: 1 }, at); }+function fadeIn() {}+fade("#b", 2);+fadeIn();`;+ expect(unrollComputedTimeline(script)).not.toContain("function fade(");+ });++ it("leaves a loop with a computed selector as authored", () => {+ const script = `const tl = gsap.timeline();+for (let i = 0; i < 3; i++) { tl.to("#item" + i, { opacity: 1, duration: 1 }, i); }`;+ expect(unrollComputedTimeline(script)).toBe(script);+ });++ it.each([+ ["a $-prefixed name", "$fade(1)"],+ ["a longer name ending in the helper name", "xfade(1)"],+ ["a name that continues with a $", "fade$(1)"],+ ])("does not read %s as a reference to fade", (_case, call) => {+ const script = `const tl = gsap.timeline();+function fade(sel, at) { tl.to(sel, { opacity: 1, duration: 1 }, at); }+fade("#b", 2);+${call};`;+ expect(unrollComputedTimeline(script)).not.toContain("function fade");+ });});diff --git a/packages/parsers/src/gsapUnroll.ts b/packages/parsers/src/gsapUnroll.tsindex 5506e757c2..65b2305a38 100644--- a/packages/parsers/src/gsapUnroll.ts+++ b/packages/parsers/src/gsapUnroll.ts@@ -95,39 +95,101 @@ function enclosingTopLevel(statements: Node[], start: number, end: number): Nodereturn null;}-function isHelperDeclNamed(stmt: Node, names: Set<string>): boolean {- if (stmt.type === "FunctionDeclaration") return names.has(stmt.id?.name);- if (stmt.type === "VariableDeclaration") {- return (stmt.declarations ?? []).some((d: Node) => names.has(d.id?.name));- }- return false;+/** A statement that only declares a function: its tweens run when something calls it, not here. */+function declaresFunction(stmt: Node): boolean {+ if (stmt.type === "FunctionDeclaration") return true;+ return (+ stmt.type === "VariableDeclaration" &&+ (stmt.declarations ?? []).some((d: Node) =>+ ["FunctionExpression", "ArrowFunctionExpression"].includes(d.init?.type),+ )+ );+}++/** Names a top-level function or variable statement declares. */+function declaredNames(stmt: Node): string[] {+ if (stmt.type === "FunctionDeclaration") return stmt.id?.name ? [stmt.id.name] : [];+ if (stmt.type !== "VariableDeclaration") return [];+ return (stmt.declarations ?? []).flatMap((d: Node) => (d.id?.name ? [d.id.name] : []));+}++/** Whole-identifier match; `\b` cannot anchor on `$` or non-ASCII letters, so the boundary is explicit. */+function mentionsIdentifier(text: string, name: string): boolean {+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+ return new RegExp(`(?<![\\p{ID_Continue}$])${escaped}(?![\\p{ID_Continue}$])`, "u").test(text);}/**- * Rewrite `script` so top-level helper calls / loops that build the timeline- * become explicit literal tweens. Returns the original script unchanged when- * there is nothing statically-resolvable to unroll.+ * Helper declarations that nothing left in the script still references. Liveness is read from the+ * remaining source, not inferred from what the parser expanded, so a call it did not expand keeps its helper.*/-export function unrollComputedTimeline(script: string): string {- const parsed = parseGsapScriptAcorn(script);- const computed = parsed.animations.filter((a) => isComputed(a) && a.provenance?.sourceRange);- if (computed.length === 0) return script;+function unreferencedHelperDecls(+ statements: Node[],+ script: string,+ unrolled: Set<Node>,+ helperNames: Set<string>,+) {+ let live = statements.filter((stmt) => !unrolled.has(stmt));+ const dead: Node[] = [];+ for (let changed = true; changed; ) {+ changed = false;+ for (const decl of live) {+ const names = declaredNames(decl);+ if (names.length === 0 || !names.every((n) => helperNames.has(n))) continue;+ const others = live.filter((s) => s !== decl).map((s) => script.slice(s.start, s.end));+ if (names.some((n) => others.some((text) => mentionsIdentifier(text, n)))) continue;+ dead.push(decl);+ live = live.filter((s) => s !== decl);+ changed = true;+ }+ }+ return dead;+}- const statements = topLevelStatements(script);+/** A literal tween cannot encode an unknown start, duration or selector, so those statements stay as authored. */+function dropStatementsWithUnknownTiming(byStatement: Map<Node, GsapAnimation[]>): void {+ for (const [stmt, anims] of byStatement) {+ if (+ anims.some(+ (a) => a.durationUnresolved || a.resolvedStart === undefined || a.hasUnresolvedSelector,+ )+ ) {+ byStatement.delete(stmt);+ }+ }+}- // Group computed animations by the top-level statement that produced them,- // preserving source order within each group.+/**+ * Group computed animations by their top-level statement. Null when a tween originates inside a+ * function declaration: a call site could then mix expandable and unexpandable tweens.+ */+function groupByTopLevelStatement(computed: GsapAnimation[], statements: Node[]) {const byStatement = new Map<Node, GsapAnimation[]>();const helperNames = new Set<string>();for (const anim of computed) {- if (anim.provenance?.fn) helperNames.add(anim.provenance.fn);const [s, e] = anim.provenance!.sourceRange!;const stmt = enclosingTopLevel(statements, s, e);+ if (stmt && declaresFunction(stmt)) return null;if (!stmt) continue; // nested origin — leave it; can't map to a top-level edit+ if (anim.provenance?.fn) helperNames.add(anim.provenance.fn);const list = byStatement.get(stmt) ?? [];list.push(anim);byStatement.set(stmt, list);}+ return { byStatement, helperNames };+}++/** Rewrite top-level helper calls and loops into literal tweens; unchanged when nothing can be unrolled. */+export function unrollComputedTimeline(script: string): string {+ const parsed = parseGsapScriptAcorn(script);+ const computed = parsed.animations.filter((a) => isComputed(a) && a.provenance?.sourceRange);+ if (computed.length === 0) return script;++ const statements = topLevelStatements(script);+ const grouped = groupByTopLevelStatement(computed, statements);+ if (!grouped) return script;+ const { byStatement, helperNames } = grouped;+ dropStatementsWithUnknownTiming(byStatement);if (byStatement.size === 0) return script;const ms = new MagicString(script);@@ -135,9 +197,13 @@ export function unrollComputedTimeline(script: string): string {const literals = anims.map((a) => serializeTweenStatement(parsed.timelineVar, a)).join("\n");ms.overwrite(stmt.start, stmt.end, literals);}- // Drop the now-dead helper declarations.- for (const stmt of statements) {- if (isHelperDeclNamed(stmt, helperNames)) ms.remove(stmt.start, stmt.end);+ for (const decl of unreferencedHelperDecls(+ statements,+ script,+ new Set(byStatement.keys()),+ helperNames,+ )) {+ ms.remove(decl.start, decl.end);}return ms.toString();}diff --git a/packages/parsers/src/index.ts b/packages/parsers/src/index.tsindex 07a9842534..e7f60a6c7a 100644--- a/packages/parsers/src/index.ts+++ b/packages/parsers/src/index.ts@@ -9,6 +9,7 @@ export { queryByAttr } from "./utils/cssSelector.js";export * from "./compositionContract.js";export * from "./canvasScaffoldPatterns.js";export * from "./topLevelElements.js";+export * from "./timingMismatches.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/src/timingMismatches.test.ts b/packages/parsers/src/timingMismatches.test.tsnew file mode 100644index 0000000000..3bcddf6ffd--- /dev/null+++ b/packages/parsers/src/timingMismatches.test.ts@@ -0,0 +1,173 @@+import { describe, expect, it } from "vitest";+import { parseGsapScriptAcorn } from "./gsapParserAcorn.js";+import { timingMismatches } from "./timingMismatches.js";++const comp = (body: string, script: string, rootAttrs = 'data-duration="10"') =>+ `<div data-composition-id="main" ${rootAttrs}>${body}</div><script>const tl = gsap.timeline({paused:true});${script}</script>`;+const clip = (id: string, start: number, dur: number) =>+ `<div id="${id}" data-start="${start}" data-duration="${dur}"></div>`;++describe("timingMismatches", () => {+ it("flags a tween that starts an element outside its data-start window", () => {+ const r = timingMismatches(comp(clip("a", 2, 3), `tl.to("#a",{opacity:1,duration:1},6);`));+ expect(r.findings).toEqual([+ {+ kind: "tween-outside-window",+ selector: "#a",+ elementId: "a",+ dataStart: 2,+ dataEnd: 5,+ tweenStart: 6,+ tweenEnd: 7,+ },+ ]);+ });++ it("accepts a tween inside the window and a set at 0 before the window", () => {+ const r = timingMismatches(+ comp(clip("a", 2, 3), `tl.set("#a",{opacity:0},0);tl.to("#a",{opacity:1,duration:1},2.5);`),+ );+ expect(r).toEqual({ findings: [], unresolved: [] });+ });++ it("flags an animated top-level element with no timing attributes", () => {+ const r = timingMismatches(comp(`<div id="b"></div>`, `tl.to("#b",{x:1,duration:1},0);`));+ expect(r.findings).toEqual([+ { kind: "animated-without-timing", selector: "#b", elementId: "b" },+ ]);+ });++ it("does not flag an untimed element inside a timed clip", () => {+ const html = comp(+ `<div id="a" data-start="0" data-duration="4"><span id="c"></span></div>`,+ `tl.to("#c",{x:1,duration:1},0);`,+ );+ expect(timingMismatches(html).findings).toEqual([]);+ });++ it("flags a timeline that runs past the root data-duration", () => {+ const r = timingMismatches(comp(clip("a", 0, 12), `tl.to("#a",{x:1,duration:2},10);`));+ expect(r.findings).toContainEqual({+ kind: "timeline-exceeds-root-duration",+ rootDuration: 10,+ timelineEnd: 12,+ });+ });++ it("treats a root duration longer than the timeline as benign", () => {+ const r = timingMismatches(comp(clip("a", 0, 4), `tl.to("#a",{x:1,duration:2},0);`));+ expect(r.findings).toEqual([]);+ });++ it("reports a non-literal duration as unresolved and never guesses the next start", () => {+ const r = timingMismatches(+ comp(+ clip("a", 0, 5) + clip("b", 0, 5),+ `tl.to("#a",{x:1,duration:D},0);tl.to("#b",{x:1,duration:1});`,+ ),+ );+ expect(r.findings).toEqual([]);+ expect(r.unresolved).toEqual([+ { selector: "#a", reason: "duration" },+ { selector: "#b", reason: "position" },+ ]);+ });+});++describe("timingMismatches edge cases", () => {+ it("flags a from tween that starts before data-start", () => {+ const r = timingMismatches(comp(clip("a", 2, 3), `tl.from("#a",{opacity:0,duration:1},0);`));+ expect(r.findings).toMatchObject([+ { kind: "tween-outside-window", tweenStart: 0, dataStart: 2 },+ ]);+ });++ it("reports a non-numeric data-start as unresolved, not a finding", () => {+ const html = comp(+ `<div id="a" data-start="other + 1" data-duration="2"></div>`,+ `tl.to("#a",{x:1,duration:1},9);`,+ );+ expect(timingMismatches(html)).toEqual({+ findings: [],+ unresolved: [{ selector: "#a", reason: "start-attribute" }],+ });+ });++ it("reports a staggered tween as unresolved", () => {+ const html = comp(clip("a", 0, 5), `tl.to("#a",{x:1,duration:1,stagger:0.2},9);`);+ expect(timingMismatches(html).unresolved).toEqual([{ selector: "#a", reason: "stagger" }]);+ });++ it("ignores off-timeline global sets and sub-composition hosts", () => {+ const html = comp(+ `<div id="h" data-composition-id="sub" data-start="1" data-duration="2"></div><div id="u"></div>`,+ `gsap.set("#u",{opacity:0});tl.to("#h",{x:1,duration:1},8);`,+ );+ expect(timingMismatches(html).findings).toEqual([]);+ });++ it("reports an untimed animated element once however many tweens target it", () => {+ const html = comp(+ `<div id="b"></div>`,+ `tl.to("#b",{x:1,duration:1},0);tl.to("#b",{y:1,duration:1},1);`,+ );+ expect(timingMismatches(html).findings).toHaveLength(1);+ });+});++describe("parseGsapScriptAcorn unresolved duration", () => {+ const starts = (script: string) =>+ parseGsapScriptAcorn(script).animations.map((a) => a.resolvedStart);++ it("keeps GSAP's 0.5s default for an absent duration", () => {+ expect(starts(`const tl = gsap.timeline();tl.to("#a",{x:1});tl.to("#b",{x:1});`)).toEqual([+ 0, 0.5,+ ]);+ });++ it("leaves every later cursor-relative start unresolved after a non-literal duration", () => {+ expect(+ starts(+ `const tl = gsap.timeline();tl.to("#a",{x:1,duration:D},1);tl.to("#b",{x:1});tl.to("#c",{x:1},4);`,+ ),+ ).toEqual([1, undefined, 4]);+ });++ it("marks the tween itself with durationUnresolved", () => {+ const [a] = parseGsapScriptAcorn(+ `const tl = gsap.timeline();tl.to("#a",{x:1,duration:D});`,+ ).animations;+ expect(a?.durationUnresolved).toBe(true);+ });++ it("marks tweens that inherit a non-literal timeline default duration", () => {+ const [a] = parseGsapScriptAcorn(+ `const tl = gsap.timeline({defaults:{duration:D}});tl.to("#a",{x:1});`,+ ).animations;+ expect(a?.durationUnresolved).toBe(true);+ });+ it.each([+ ["a vars variable", `const v = makeVars(); tl.to("#a", v); tl.to("#b", {x:1});`],+ ["a vars call", `tl.to("#a", makeVars()); tl.to("#b", {x:1});`],+ ["a spread", `tl.to("#a", {x:1, ...opts}); tl.to("#b", {x:1});`],+ ])("treats %s as an unknown duration", (_name, script) => {+ const [, b] = parseGsapScriptAcorn(`const tl = gsap.timeline();${script}`).animations;+ expect(b?.resolvedStart).toBeUndefined();+ });++ it("ignores a duration on a set, which GSAP never reads", () => {+ const [set, next] = parseGsapScriptAcorn(+ `const tl = gsap.timeline();tl.set("#a",{opacity:0,duration:D},0);tl.to("#b",{x:1,duration:1});`,+ ).animations;+ expect(set?.durationUnresolved).toBeUndefined();+ expect(next?.resolvedStart).toBe(0);+ });++ it("does not let a timeline default duration stand in for an authored non-static one", () => {+ const [a] = parseGsapScriptAcorn(+ `const tl = gsap.timeline({defaults:{duration:3}});tl.to("#a",{x:1,duration:D});`,+ ).animations;+ expect(a).toMatchObject({ durationUnresolved: true });+ expect(a?.duration).toBeUndefined();+ });+});diff --git a/packages/parsers/src/timingMismatches.ts b/packages/parsers/src/timingMismatches.tsnew file mode 100644index 0000000000..a4c044fd57--- /dev/null+++ b/packages/parsers/src/timingMismatches.ts@@ -0,0 +1,190 @@+import { parseHTML } from "linkedom";+import { parseGsapScriptAcorn } from "./gsapParserAcorn.js";+import type { GsapAnimation } from "./gsapSerialize.js";+import { isSubCompositionHost, topLevelElements } from "./topLevelElements.js";+import type { StructureNode } from "./topLevelElements.js";++const EPSILON = 0.05;+const NON_RENDERED = new Set(["script", "style", "template", "noscript", "link", "meta"]);++export type TimingFinding =+ | {+ kind: "tween-outside-window";+ selector: string;+ elementId: string | null;+ dataStart: number;+ dataEnd: number | null;+ tweenStart: number;+ tweenEnd: number;+ }+ | { kind: "animated-without-timing"; selector: string; elementId: string | null }+ | { kind: "timeline-exceeds-root-duration"; rootDuration: number; timelineEnd: number };++/** Timing that could not be read statically. Reported, never flagged. */+export interface UnresolvedTiming {+ selector: string;+ reason: "duration" | "position" | "stagger" | "start-attribute";+}++export interface TimingMismatchReport {+ findings: TimingFinding[];+ unresolved: UnresolvedTiming[];+}++interface DomNode extends StructureNode<DomNode> {+ el: Element;+}++const toNode = (el: Element): DomNode => ({+ tag: el.tagName,+ attrs: Object.fromEntries(Array.from(el.attributes, (a) => [a.name, a.value])),+ children: Array.from(el.children, toNode),+ el,+});++const numeric = (value: string | null | undefined): number | null => {+ if (value == null || value.trim() === "") return null;+ const n = Number(value);+ return Number.isFinite(n) ? n : null;+};++function queryAll(root: Element, selector: string): Element[] {+ try {+ return Array.from(root.querySelectorAll(selector));+ } catch {+ return [];+ }+}++type Anim = GsapAnimation;++const unresolvedReason = (anim: Anim): UnresolvedTiming["reason"] | null => {+ if (anim.durationUnresolved) return "duration";+ if (anim.resolvedStart === undefined) return "position";+ return anim.extras?.stagger === undefined ? null : "stagger";+};++interface Layout {+ rowEls: Set<Element>;+ insideRow: Set<Element>;+}++/** Where each element sits: inside a timeline row (timed clip or sub-composition), or loose. */+function rowMembership(root: Element): Layout {+ const rows = topLevelElements(toNode(root));+ const rowEls = new Set(rows.map((r) => r.el));+ const insideRow = new Set<Element>();+ for (const row of rows) {+ insideRow.add(row.el);+ for (const d of Array.from(row.el.querySelectorAll("*"))) insideRow.add(d);+ }+ return { rowEls, insideRow };+}++const attrNumber = (el: Element, name: string): number | null => numeric(el.getAttribute(name));++function windowFinding(+ el: Element,+ selector: string,+ anim: Anim,+ start: number,+ end: number,+): TimingFinding | null {+ const dataStart = attrNumber(el, "data-start");+ const duration = attrNumber(el, "data-duration");+ if (dataStart === null) return null;+ const dataEnd = duration === null ? null : dataStart + duration;+ const beforeStart = anim.method !== "set" && start < dataStart - EPSILON;+ const afterEnd = dataEnd !== null && start > dataEnd + EPSILON;+ if (!beforeStart && !afterEnd) return null;+ const elementId = el.getAttribute("id");+ return {+ kind: "tween-outside-window",+ selector,+ elementId,+ dataStart,+ dataEnd,+ tweenStart: start,+ tweenEnd: end,+ };+}++const tweenEnd = (anim: Anim): number =>+ (anim.resolvedStart as number) + (anim.method === "set" ? 0 : (anim.duration ?? 0.5));++/** Findings and unresolved entries for one resolved tween against one target element. */+function checkTarget(+ el: Element,+ selector: string,+ anim: Anim,+ layout: Layout,+ report: TimingMismatchReport,+) {+ if (!layout.insideRow.has(el)) {+ if (!NON_RENDERED.has(el.tagName.toLowerCase())) {+ report.findings.push({+ kind: "animated-without-timing",+ selector,+ elementId: el.getAttribute("id"),+ });+ }+ return;+ }+ if (!layout.rowEls.has(el) || isSubCompositionHost(toNode(el))) return;+ if (el.hasAttribute("data-start") && attrNumber(el, "data-start") === null) {+ report.unresolved.push({ selector, reason: "start-attribute" });+ return;+ }+ const found = windowFinding(el, selector, anim, anim.resolvedStart as number, tweenEnd(anim));+ if (found) report.findings.push(found);+}++/** Checks one tween against its targets and returns its end, or null when its timing is unresolved. */+function checkTween(+ anim: Anim,+ root: Element,+ layout: Layout,+ seenUntimed: Set<Element>,+ report: TimingMismatchReport,+): number | null {+ const selector = anim.targetSelector;+ const targets = queryAll(root, selector).filter((el) => el !== root);+ const reason = unresolvedReason(anim);+ if (reason) {+ if (targets.length > 0) report.unresolved.push({ selector, reason });+ return null;+ }+ for (const el of targets) {+ const loose = !layout.insideRow.has(el);+ if (loose && seenUntimed.has(el)) continue;+ if (loose) seenUntimed.add(el);+ checkTarget(el, selector, anim, layout, report);+ }+ return tweenEnd(anim);+}++/**+ * Compares the GSAP timeline in a composition file with the timing attributes of its elements.+ * Attributes are authoritative: a tween that places an element outside its window is a finding.+ */+export function timingMismatches(html: string): TimingMismatchReport {+ const report: TimingMismatchReport = { findings: [], unresolved: [] };+ const { document } = parseHTML(html);+ const root = document.querySelector("[data-composition-id]");+ if (!root) return report;++ const layout = rowMembership(root);+ const seenUntimed = new Set<Element>();+ const scripts = Array.from(document.querySelectorAll("script:not([src])"));+ const anims = scripts.flatMap((s) => parseGsapScriptAcorn(s.textContent ?? "").animations);+ const ends = anims+ .filter((anim) => !anim.global && !anim.hasUnresolvedSelector)+ .map((anim) => checkTween(anim, root, layout, seenUntimed, report));+ const timelineEnd = Math.max(0, ...ends.filter((e): e is number => e !== null));++ const rootDuration = attrNumber(root, "data-duration");+ if (rootDuration !== null && timelineEnd > rootDuration + EPSILON) {+ report.findings.push({ kind: "timeline-exceeds-root-duration", rootDuration, timelineEnd });+ }+ return report;+}