hyperframes 0.6.57 → 0.6.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -50,7 +50,7 @@ var VERSION;
50
50
  var init_version = __esm({
51
51
  "src/version.ts"() {
52
52
  "use strict";
53
- VERSION = true ? "0.6.57" : "0.0.0-dev";
53
+ VERSION = true ? "0.6.59" : "0.0.0-dev";
54
54
  }
55
55
  });
56
56
 
@@ -58652,6 +58652,16 @@ function registerFileRoutes(api, adapter2) {
58652
58652
  });
58653
58653
  break;
58654
58654
  }
58655
+ case "update-from-property": {
58656
+ const parsed = parseGsapScript2(block.scriptText);
58657
+ const anim = parsed.animations.find((a) => a.id === body.animationId);
58658
+ if (!anim) return c3.json({ error: "animation not found" }, 404);
58659
+ if (anim.method !== "fromTo") return c3.json({ error: "animation is not a fromTo" }, 400);
58660
+ newScript = updateAnimationInScript2(block.scriptText, body.animationId, {
58661
+ fromProperties: { ...anim.fromProperties ?? {}, [body.property]: body.value }
58662
+ });
58663
+ break;
58664
+ }
58655
58665
  case "update-meta": {
58656
58666
  newScript = updateAnimationInScript2(block.scriptText, body.animationId, body.updates);
58657
58667
  break;
@@ -58663,7 +58673,8 @@ function registerFileRoutes(api, adapter2) {
58663
58673
  position: body.position,
58664
58674
  duration: body.duration,
58665
58675
  ease: body.ease,
58666
- properties: body.properties
58676
+ properties: body.properties,
58677
+ fromProperties: body.fromProperties
58667
58678
  });
58668
58679
  newScript = result.script;
58669
58680
  break;
@@ -58681,6 +58692,16 @@ function registerFileRoutes(api, adapter2) {
58681
58692
  });
58682
58693
  break;
58683
58694
  }
58695
+ case "add-from-property": {
58696
+ const parsed = parseGsapScript2(block.scriptText);
58697
+ const anim = parsed.animations.find((a) => a.id === body.animationId);
58698
+ if (!anim) return c3.json({ error: "animation not found" }, 404);
58699
+ if (anim.method !== "fromTo") return c3.json({ error: "animation is not a fromTo" }, 400);
58700
+ newScript = updateAnimationInScript2(block.scriptText, body.animationId, {
58701
+ fromProperties: { ...anim.fromProperties ?? {}, [body.property]: body.defaultValue }
58702
+ });
58703
+ break;
58704
+ }
58684
58705
  case "remove-property": {
58685
58706
  const parsed = parseGsapScript2(block.scriptText);
58686
58707
  const anim = parsed.animations.find((a) => a.id === body.animationId);
@@ -58692,6 +58713,18 @@ function registerFileRoutes(api, adapter2) {
58692
58713
  });
58693
58714
  break;
58694
58715
  }
58716
+ case "remove-from-property": {
58717
+ const parsed = parseGsapScript2(block.scriptText);
58718
+ const anim = parsed.animations.find((a) => a.id === body.animationId);
58719
+ if (!anim) return c3.json({ error: "animation not found" }, 404);
58720
+ if (anim.method !== "fromTo") return c3.json({ error: "animation is not a fromTo" }, 400);
58721
+ const filtered = { ...anim.fromProperties ?? {} };
58722
+ delete filtered[body.property];
58723
+ newScript = updateAnimationInScript2(block.scriptText, body.animationId, {
58724
+ fromProperties: filtered
58725
+ });
58726
+ break;
58727
+ }
58695
58728
  default:
58696
58729
  return c3.json({ error: `unknown mutation type: ${body.type}` }, 400);
58697
58730
  }
@@ -69522,6 +69555,7 @@ __export(deterministicFonts_exports, {
69522
69555
  iterateFontFamilyDeclarations: () => iterateFontFamilyDeclarations,
69523
69556
  parseFontFamilyValue: () => parseFontFamilyValue
69524
69557
  });
69558
+ import { createHash as createHash6 } from "crypto";
69525
69559
  import { existsSync as existsSync31, mkdirSync as mkdirSync18, readFileSync as readFileSync24, writeFileSync as writeFileSync15 } from "fs";
69526
69560
  import { homedir as homedir8, tmpdir as tmpdir3 } from "os";
69527
69561
  import { join as join33 } from "path";
@@ -69576,7 +69610,7 @@ function extractRequestedFontFamilies(html) {
69576
69610
  }
69577
69611
  return requested;
69578
69612
  }
69579
- function buildFontFaceRule(familyName, src, weight, style) {
69613
+ function buildFontFaceRule(familyName, src, weight, style, unicodeRange) {
69580
69614
  return [
69581
69615
  "@font-face {",
69582
69616
  ` font-family: "${familyName}";`,
@@ -69584,6 +69618,9 @@ function buildFontFaceRule(familyName, src, weight, style) {
69584
69618
  ` font-style: ${style};`,
69585
69619
  ` font-weight: ${weight};`,
69586
69620
  " font-display: block;",
69621
+ // Preserve the subset's unicode-range so the browser selects the right
69622
+ // per-codepoint subset (matching Google Fonts' own CSS semantics).
69623
+ ...unicodeRange ? [` unicode-range: ${unicodeRange};`] : [],
69587
69624
  "}"
69588
69625
  ].join("\n");
69589
69626
  }
@@ -69604,18 +69641,31 @@ async function buildFontFaceCss(requestedFamilies, options) {
69604
69641
  }
69605
69642
  const googleFaces2 = await fetchGoogleFont(originalCaseFamily, options);
69606
69643
  for (const face of googleFaces2) {
69607
- const key2 = `${face.weight}:${face.style}`;
69608
- if (!coveredWeights.has(key2)) {
69609
- rules.push(buildFontFaceRule(originalCaseFamily, face.dataUri, face.weight, face.style));
69610
- coveredWeights.add(key2);
69611
- }
69644
+ if (coveredWeights.has(`${face.weight}:${face.style}`)) continue;
69645
+ rules.push(
69646
+ buildFontFaceRule(
69647
+ originalCaseFamily,
69648
+ face.dataUri,
69649
+ face.weight,
69650
+ face.style,
69651
+ face.unicodeRange
69652
+ )
69653
+ );
69612
69654
  }
69613
69655
  continue;
69614
69656
  }
69615
69657
  const googleFaces = await fetchGoogleFont(originalCaseFamily, options);
69616
69658
  if (googleFaces.length > 0) {
69617
69659
  for (const face of googleFaces) {
69618
- rules.push(buildFontFaceRule(originalCaseFamily, face.dataUri, face.weight, face.style));
69660
+ rules.push(
69661
+ buildFontFaceRule(
69662
+ originalCaseFamily,
69663
+ face.dataUri,
69664
+ face.weight,
69665
+ face.style,
69666
+ face.unicodeRange
69667
+ )
69668
+ );
69619
69669
  }
69620
69670
  continue;
69621
69671
  }
@@ -69656,14 +69706,43 @@ function fontCacheDir(slug) {
69656
69706
  }
69657
69707
  return dir;
69658
69708
  }
69659
- function cachedWoff2Path(slug, weight, style) {
69660
- return join33(fontCacheDir(slug), `${weight}-${style}.woff2`);
69709
+ function subsetToken(woff2Url) {
69710
+ return createHash6("sha1").update(woff2Url).digest("hex").slice(0, 12);
69711
+ }
69712
+ function cachedWoff2Path(slug, weight, style, subset) {
69713
+ return join33(fontCacheDir(slug), `${weight}-${style}-${subset}.woff2`);
69661
69714
  }
69662
69715
  function fontFetchError(familyName, url, what, cause) {
69663
69716
  const reason = "status" in cause ? `returned HTTP ${cause.status}` : `failed: ${cause.error.message}`;
69664
69717
  const message = `[deterministicFonts] ${what} fetch for ${JSON.stringify(familyName)} ${reason}. Distributed renders require deterministic fonts; system-font fallback would produce non-byte-identical output.`;
69665
69718
  return new FontFetchError(familyName, url, message, "error" in cause ? cause.error : void 0);
69666
69719
  }
69720
+ async function ensureWoff2DataUri(cachePath2, woff2Url, familyName, weight, style, options) {
69721
+ try {
69722
+ return `data:font/woff2;base64,${readFileSync24(cachePath2).toString("base64")}`;
69723
+ } catch {
69724
+ }
69725
+ const woff2What = `Google Fonts woff2 (${weight}/${style})`;
69726
+ try {
69727
+ const fontRes = await options.fetchImpl(woff2Url);
69728
+ if (!fontRes.ok) {
69729
+ if (fontRes.status >= 500 && options.failClosedFontFetch) {
69730
+ throw fontFetchError(familyName, woff2Url, woff2What, { status: fontRes.status });
69731
+ }
69732
+ return null;
69733
+ }
69734
+ writeFileSync15(cachePath2, Buffer.from(await fontRes.arrayBuffer()), { flag: "wx", mode: 420 });
69735
+ } catch (err) {
69736
+ if (err instanceof FontFetchError) throw err;
69737
+ if (err.code === "EEXIST") {
69738
+ } else if (options.failClosedFontFetch) {
69739
+ throw fontFetchError(familyName, woff2Url, woff2What, { error: err });
69740
+ } else {
69741
+ return null;
69742
+ }
69743
+ }
69744
+ return `data:font/woff2;base64,${readFileSync24(cachePath2).toString("base64")}`;
69745
+ }
69667
69746
  async function fetchGoogleFont(familyName, options) {
69668
69747
  const slug = fontSlug(familyName);
69669
69748
  const encodedFamily = encodeURIComponent(familyName);
@@ -69687,37 +69766,24 @@ async function fetchGoogleFont(familyName, options) {
69687
69766
  }
69688
69767
  return [];
69689
69768
  }
69690
- const faceRegex = /@font-face\s*\{[^}]*font-style:\s*(normal|italic)[^}]*font-weight:\s*(\d+)[^}]*src:\s*url\(([^)]+)\)\s*format\(['"]woff2['"]\)[^}]*\}/gi;
69769
+ const faceRegex = /@font-face\s*\{[^}]*font-style:\s*(normal|italic)[^}]*font-weight:\s*(\d+)[^}]*src:\s*url\(([^)]+)\)\s*format\(['"]woff2['"]\)(?:[^}]*?unicode-range:\s*([^;}]+))?[^}]*\}/gi;
69691
69770
  const faces = [];
69692
69771
  for (const match of cssText.matchAll(faceRegex)) {
69693
69772
  const style = match[1] || "normal";
69694
69773
  const weight = match[2] || "400";
69695
69774
  const woff2Url = match[3] || "";
69775
+ const unicodeRange = match[4]?.trim() || void 0;
69696
69776
  if (!woff2Url) continue;
69697
- const cachePath2 = cachedWoff2Path(slug, weight, style);
69698
- if (!existsSync31(cachePath2)) {
69699
- const woff2What = `Google Fonts woff2 (${weight}/${style})`;
69700
- try {
69701
- const fontRes = await options.fetchImpl(woff2Url);
69702
- if (!fontRes.ok) {
69703
- if (fontRes.status >= 500 && options.failClosedFontFetch) {
69704
- throw fontFetchError(familyName, woff2Url, woff2What, { status: fontRes.status });
69705
- }
69706
- continue;
69707
- }
69708
- const buffer = Buffer.from(await fontRes.arrayBuffer());
69709
- writeFileSync15(cachePath2, buffer);
69710
- } catch (err) {
69711
- if (err instanceof FontFetchError) throw err;
69712
- if (options.failClosedFontFetch) {
69713
- throw fontFetchError(familyName, woff2Url, woff2What, { error: err });
69714
- }
69715
- continue;
69716
- }
69717
- }
69718
- const fontBytes = readFileSync24(cachePath2);
69719
- const dataUri = `data:font/woff2;base64,${fontBytes.toString("base64")}`;
69720
- faces.push({ weight, style, dataUri });
69777
+ const cachePath2 = cachedWoff2Path(slug, weight, style, subsetToken(woff2Url));
69778
+ const dataUri = await ensureWoff2DataUri(
69779
+ cachePath2,
69780
+ woff2Url,
69781
+ familyName,
69782
+ weight,
69783
+ style,
69784
+ options
69785
+ );
69786
+ if (dataUri) faces.push({ weight, style, dataUri, unicodeRange });
69721
69787
  }
69722
69788
  if (faces.length > 0) {
69723
69789
  console.log(
@@ -69914,7 +69980,7 @@ var init_deterministicFonts = __esm({
69914
69980
  });
69915
69981
 
69916
69982
  // ../producer/src/services/hyperframeRuntimeLoader.ts
69917
- import { createHash as createHash6 } from "crypto";
69983
+ import { createHash as createHash7 } from "crypto";
69918
69984
  import { existsSync as existsSync32, readFileSync as readFileSync25 } from "fs";
69919
69985
  import { dirname as dirname11, resolve as resolve16 } from "path";
69920
69986
  import { fileURLToPath as fileURLToPath2 } from "url";
@@ -69957,7 +70023,7 @@ function resolveVerifiedHyperframeRuntime() {
69957
70023
  throw new Error(`[HyperframeRuntimeLoader] Missing runtime artifact at ${runtimePath}.`);
69958
70024
  }
69959
70025
  const runtimeSource = readFileSync25(runtimePath, "utf8");
69960
- const runtimeSha = createHash6("sha256").update(runtimeSource, "utf8").digest("hex");
70026
+ const runtimeSha = createHash7("sha256").update(runtimeSource, "utf8").digest("hex");
69961
70027
  if (runtimeSha !== manifest.sha256) {
69962
70028
  throw new Error(
69963
70029
  `[HyperframeRuntimeLoader] Runtime checksum mismatch. expected=${manifest.sha256} actual=${runtimeSha}`
@@ -76475,9 +76541,9 @@ var init_parityContract2 = __esm({
76475
76541
  });
76476
76542
 
76477
76543
  // ../producer/src/services/render/stages/planHash.ts
76478
- import { createHash as createHash7 } from "crypto";
76544
+ import { createHash as createHash8 } from "crypto";
76479
76545
  function computePlanHash(input2) {
76480
- const hash2 = createHash7("sha256");
76546
+ const hash2 = createHash8("sha256");
76481
76547
  hash2.update(PLAN_HASH_SCHEMA_PREFIX, "utf8");
76482
76548
  hash2.update(input2.compositionHtml);
76483
76549
  hash2.update(FIELD_DELIMITER);
@@ -76524,7 +76590,7 @@ function canonicalJsonStringify(value) {
76524
76590
  throw new TypeError(`canonicalJsonStringify: unsupported value type ${typeof value}`);
76525
76591
  }
76526
76592
  function sha256Hex(bytes) {
76527
- const h3 = createHash7("sha256");
76593
+ const h3 = createHash8("sha256");
76528
76594
  h3.update(bytes);
76529
76595
  return h3.digest("hex");
76530
76596
  }
@@ -106767,7 +106833,7 @@ var require_websocket = __commonJS({
106767
106833
  var http4 = __require("http");
106768
106834
  var net2 = __require("net");
106769
106835
  var tls = __require("tls");
106770
- var { randomBytes: randomBytes4, createHash: createHash9 } = __require("crypto");
106836
+ var { randomBytes: randomBytes4, createHash: createHash10 } = __require("crypto");
106771
106837
  var { Duplex, Readable: Readable3 } = __require("stream");
106772
106838
  var { URL: URL2 } = __require("url");
106773
106839
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -107427,7 +107493,7 @@ var require_websocket = __commonJS({
107427
107493
  abortHandshake(websocket, socket, "Invalid Upgrade header");
107428
107494
  return;
107429
107495
  }
107430
- const digest = createHash9("sha1").update(key2 + GUID).digest("base64");
107496
+ const digest = createHash10("sha1").update(key2 + GUID).digest("base64");
107431
107497
  if (res.headers["sec-websocket-accept"] !== digest) {
107432
107498
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
107433
107499
  return;
@@ -107794,7 +107860,7 @@ var require_websocket_server = __commonJS({
107794
107860
  var EventEmitter = __require("events");
107795
107861
  var http4 = __require("http");
107796
107862
  var { Duplex } = __require("stream");
107797
- var { createHash: createHash9 } = __require("crypto");
107863
+ var { createHash: createHash10 } = __require("crypto");
107798
107864
  var extension2 = require_extension();
107799
107865
  var PerMessageDeflate2 = require_permessage_deflate();
107800
107866
  var subprotocol2 = require_subprotocol();
@@ -108095,7 +108161,7 @@ var require_websocket_server = __commonJS({
108095
108161
  );
108096
108162
  }
108097
108163
  if (this._state > RUNNING) return abortHandshake(socket, 503);
108098
- const digest = createHash9("sha1").update(key2 + GUID).digest("base64");
108164
+ const digest = createHash10("sha1").update(key2 + GUID).digest("base64");
108099
108165
  const headers = [
108100
108166
  "HTTP/1.1 101 Switching Protocols",
108101
108167
  "Upgrade: websocket",
@@ -132252,10 +132318,10 @@ var init_client3 = __esm({
132252
132318
  });
132253
132319
 
132254
132320
  // src/auth/pkce.ts
132255
- import { createHash as createHash8, randomBytes as randomBytes3 } from "crypto";
132321
+ import { createHash as createHash9, randomBytes as randomBytes3 } from "crypto";
132256
132322
  function generatePkcePair() {
132257
132323
  const verifier = base64UrlEncode(randomBytes3(VERIFIER_BYTES));
132258
- const challenge = base64UrlEncode(createHash8("sha256").update(verifier).digest());
132324
+ const challenge = base64UrlEncode(createHash9("sha256").update(verifier).digest());
132259
132325
  return { verifier, challenge, method: "S256" };
132260
132326
  }
132261
132327
  function generateState() {
@@ -133054,7 +133120,6 @@ var init_errors2 = __esm({
133054
133120
  init_format();
133055
133121
  init_client2();
133056
133122
  ERROR_CODE_HINTS = {
133057
- hyperframes_project_invalid: "The uploaded zip didn't validate. Confirm it contains index.html at the root (or matches --composition), and that all referenced assets are present.",
133058
133123
  hyperframes_project_too_large: "The zip exceeded the 32 MB limit. Trim large media (or pre-host them and reference by URL), then try again.",
133059
133124
  hyperframes_render_not_found: "The render_id no longer exists \u2014 either soft-deleted or never created.",
133060
133125
  invalid_parameter: "Check the listed parameter against `hyperframes cloud render --help` for the accepted values.",
@@ -1,4 +1,4 @@
1
- var de=Object.defineProperty;var le=(n,e,t)=>e in n?de(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var c=(n,e,t)=>le(n,typeof e!="symbol"?e+"":e,t);function he(n){return n.hasRuntime||n.runtimeInjected?!1:!!(n.hasNestedCompositions||n.hasTimelines&&n.attempts>=5)}function D(n){return typeof n=="object"&&n!==null}function ce(n){return D(n)&&typeof n.getDuration=="function"}function ue(n){return D(n)&&typeof n.duration=="function"&&typeof n.time=="function"&&typeof n.seek=="function"&&typeof n.play=="function"&&typeof n.pause=="function"}const pe="https://cdn.jsdelivr.net/npm/@hyperframes/core/dist/hyperframe.runtime.iife.js";function K(n){if(n===null)return null;const e=Number.parseInt(n,10);return Number.isFinite(e)&&e>0?e:null}function me(n){const e=(n==null?void 0:n.querySelector("[data-composition-id][data-width][data-height]"))??(n==null?void 0:n.querySelector("[data-width][data-height]"));if(!e)return null;const t=K(e.getAttribute("data-width")),i=K(e.getAttribute("data-height"));return t!==null&&i!==null?{width:t,height:i}:null}class fe{constructor(e,t){c(this,"_interval",null);c(this,"_runtimeInjected",!1);this._iframe=e,this._callbacks=t}get runtimeInjected(){return this._runtimeInjected}start(){this.stop(),this._runtimeInjected=!1;let e=0;this._interval=setInterval(()=>{var t;e++;try{const i=this._iframe.contentWindow;if(!i)return;const r=!!(i.__hf||i.__player),s=!!(i.__timelines&&Object.keys(i.__timelines).length>0),a=!!((t=this._iframe.contentDocument)!=null&&t.querySelector("[data-composition-src]"));if(he({hasRuntime:r,hasTimelines:s,hasNestedCompositions:a,runtimeInjected:this._runtimeInjected,attempts:e})){this._injectRuntime();return}if(this._runtimeInjected&&!r)return;const d=this._resolvePlaybackDurationAdapter(i);if(d&&d.getDuration()>0){this.stop();const u=me(this._iframe.contentDocument);this._callbacks.onReady({duration:d.getDuration(),adapter:d,compositionSize:u});return}}catch{}e>=40&&(this.stop(),this._callbacks.onError("Composition timeline not found after 8s"))},200)}stop(){this._interval!==null&&(clearInterval(this._interval),this._interval=null)}resolveDirectTimelineAdapter(){try{const e=this._iframe.contentWindow;return e?this._resolveDirectTimelineAdapterFromWindow(e):null}catch{return null}}resolveDirectTimelineAdapterFromWindow(e){return this._resolveDirectTimelineAdapterFromWindow(e)}hasRuntimeBridge(e){return Reflect.get(e,"__hf")!==void 0||D(Reflect.get(e,"__player"))}_injectRuntime(){var e,t;this._runtimeInjected=!0;try{const i=this._iframe.contentDocument;if(!i)return;const r=i.createElement("script");r.src=pe,(i.head||i.documentElement).appendChild(r),(t=(e=this._callbacks).onRuntimeInjected)==null||t.call(e)}catch{}}_resolveDirectTimelineAdapterFromWindow(e){var d,u;if(this.hasRuntimeBridge(e))return null;const t=Reflect.get(e,"__timelines");if(!D(t))return null;const i=Object.keys(t);if(i.length===0)return null;const r=(u=(d=this._iframe.contentDocument)==null?void 0:d.querySelector("[data-composition-id]"))==null?void 0:u.getAttribute("data-composition-id"),s=r&&r in t?r:i[i.length-1],a=t[s];return ue(a)?a:null}_resolvePlaybackDurationAdapter(e){const t=Reflect.get(e,"__player");if(ce(t))return{kind:"runtime",getDuration:()=>t.getDuration()};const i=this._resolveDirectTimelineAdapterFromWindow(e);return i?{kind:"direct-timeline",timeline:i,getDuration:()=>i.duration()}:null}}const ge=`
1
+ var le=Object.defineProperty;var he=(n,e,t)=>e in n?le(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var c=(n,e,t)=>he(n,typeof e!="symbol"?e+"":e,t);function ce(n){return n.hasRuntime||n.runtimeInjected?!1:!!(n.hasNestedCompositions||n.hasTimelines&&n.attempts>=5)}function D(n){return typeof n=="object"&&n!==null}function ue(n){return D(n)&&typeof n.getDuration=="function"}function pe(n){return D(n)&&typeof n.duration=="function"&&typeof n.time=="function"&&typeof n.seek=="function"&&typeof n.play=="function"&&typeof n.pause=="function"}const me="https://cdn.jsdelivr.net/npm/@hyperframes/core/dist/hyperframe.runtime.iife.js";function ee(n){if(n===null)return null;const e=Number.parseInt(n,10);return Number.isFinite(e)&&e>0?e:null}function fe(n){const e=(n==null?void 0:n.querySelector("[data-composition-id][data-width][data-height]"))??(n==null?void 0:n.querySelector("[data-width][data-height]"));if(!e)return null;const t=ee(e.getAttribute("data-width")),i=ee(e.getAttribute("data-height"));return t!==null&&i!==null?{width:t,height:i}:null}class _e{constructor(e,t){c(this,"_interval",null);c(this,"_runtimeInjected",!1);this._iframe=e,this._callbacks=t}get runtimeInjected(){return this._runtimeInjected}start(){this.stop(),this._runtimeInjected=!1;let e=0;this._interval=setInterval(()=>{var t;e++;try{const i=this._iframe.contentWindow;if(!i)return;const r=!!(i.__hf||i.__player),s=!!(i.__timelines&&Object.keys(i.__timelines).length>0),a=!!((t=this._iframe.contentDocument)!=null&&t.querySelector("[data-composition-src]"));if(ce({hasRuntime:r,hasTimelines:s,hasNestedCompositions:a,runtimeInjected:this._runtimeInjected,attempts:e})){this._injectRuntime();return}if(this._runtimeInjected&&!r)return;const d=this._resolvePlaybackDurationAdapter(i);if(d&&d.getDuration()>0){this.stop();const u=fe(this._iframe.contentDocument);this._callbacks.onReady({duration:d.getDuration(),adapter:d,compositionSize:u});return}}catch{}e>=40&&(this.stop(),this._callbacks.onError("Composition timeline not found after 8s"))},200)}stop(){this._interval!==null&&(clearInterval(this._interval),this._interval=null)}resolveDirectTimelineAdapter(){try{const e=this._iframe.contentWindow;return e?this._resolveDirectTimelineAdapterFromWindow(e):null}catch{return null}}resolveDirectTimelineAdapterFromWindow(e){return this._resolveDirectTimelineAdapterFromWindow(e)}hasRuntimeBridge(e){return Reflect.get(e,"__hf")!==void 0||D(Reflect.get(e,"__player"))}_injectRuntime(){var e,t;this._runtimeInjected=!0;try{const i=this._iframe.contentDocument;if(!i)return;const r=i.createElement("script");r.src=me,(i.head||i.documentElement).appendChild(r),(t=(e=this._callbacks).onRuntimeInjected)==null||t.call(e)}catch{}}_resolveDirectTimelineAdapterFromWindow(e){var d,u;if(this.hasRuntimeBridge(e))return null;const t=Reflect.get(e,"__timelines");if(!D(t))return null;const i=Object.keys(t);if(i.length===0)return null;const r=(u=(d=this._iframe.contentDocument)==null?void 0:d.querySelector("[data-composition-id]"))==null?void 0:u.getAttribute("data-composition-id"),s=r&&r in t?r:i[i.length-1],a=t[s];return pe(a)?a:null}_resolvePlaybackDurationAdapter(e){const t=Reflect.get(e,"__player");if(ue(t))return{kind:"runtime",getDuration:()=>t.getDuration()};const i=this._resolveDirectTimelineAdapterFromWindow(e);return i?{kind:"direct-timeline",timeline:i,getDuration:()=>i.duration()}:null}}const ge=`
2
2
  :host {
3
3
  display: block;
4
4
  position: relative;
@@ -415,4 +415,4 @@ var de=Object.defineProperty;var le=(n,e,t)=>e in n?de(n,e,{enumerable:!0,config
415
415
  background: var(--hfp-accent, #fff);
416
416
  pointer-events: none;
417
417
  }
418
- `,ee='<svg width="24" height="24" viewBox="0 0 18 18" fill="currentColor"><polygon points="4,2 16,9 4,16"/></svg>',_e='<svg width="24" height="24" viewBox="0 0 18 18" fill="currentColor"><rect x="3" y="2" width="4" height="14"/><rect x="11" y="2" width="4" height="14"/></svg>',te='<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M3 9v6h4l5 5V4L7 9H3z"/><path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"/><path d="M14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"/></svg>',ie='<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M3 9v6h4l5 5V4L7 9H3z"/><path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"/></svg>',be='<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M3 9v6h4l5 5V4L7 9H3z"/><path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z" opacity="0.3"/><line x1="18" y1="7" x2="14" y2="17" stroke="currentColor" stroke-width="2"/></svg>',ve=[.25,.5,1,1.5,2,4];function N(n){return Number.isInteger(n)?`${n}x`:`${n}x`}function re(n){if(!Number.isFinite(n)||n<0)return"0:00";const e=Math.floor(n),t=Math.floor(e/60),i=e%60;return`${t}:${i.toString().padStart(2,"0")}`}function ye(n,e,t={}){const i=t.speedPresets??ve,r=document.createElement("div");r.className="hfp-controls",r.addEventListener("click",o=>{o.stopPropagation()});const s=document.createElement("button");s.className="hfp-play-btn",s.type="button",s.innerHTML=ee,s.setAttribute("aria-label","Play");const a=document.createElement("div");a.className="hfp-scrubber";const d=document.createElement("div");d.className="hfp-progress",d.style.width="0%",a.appendChild(d);const u=document.createElement("span");u.className="hfp-time",u.textContent="0:00 / 0:00";const m=document.createElement("div");m.className="hfp-speed-wrap";const p=document.createElement("button");p.className="hfp-speed-btn",p.type="button",p.textContent="1x",p.setAttribute("aria-label","Playback speed");const h=document.createElement("div");h.className="hfp-speed-menu",h.setAttribute("role","menu");for(const o of i){const l=document.createElement("button");l.className="hfp-speed-option",l.type="button",l.setAttribute("role","menuitem"),l.dataset.speed=String(o),l.textContent=N(o),o===1&&l.classList.add("hfp-active"),h.appendChild(l)}m.appendChild(h),m.appendChild(p);const b=document.createElement("div");b.className="hfp-volume-wrap";const f=document.createElement("button");f.className="hfp-mute-btn",f.type="button",f.innerHTML=te,f.setAttribute("aria-label","Mute");const _=document.createElement("div");_.className="hfp-volume-slider-wrap";const g=document.createElement("div");g.className="hfp-volume-slider",g.setAttribute("role","slider"),g.setAttribute("aria-label","Volume"),g.setAttribute("aria-valuemin","0"),g.setAttribute("aria-valuemax","100"),g.setAttribute("aria-valuenow","100"),g.tabIndex=0;const y=document.createElement("div");y.className="hfp-volume-fill",y.style.width="100%",g.appendChild(y),_.appendChild(g),b.appendChild(_),b.appendChild(f),r.appendChild(s),r.appendChild(a),r.appendChild(u),r.appendChild(b),r.appendChild(m),n.appendChild(r);let M=!1,E=!1,w=1,x=null;i.indexOf(1);const L=(o,l)=>o?be:l===0||l<.5?ie:te;s.addEventListener("click",o=>{o.stopPropagation(),M?e.onPause():e.onPlay()}),f.addEventListener("click",o=>{o.stopPropagation(),e.onMuteToggle()});let T=!1;const P=o=>{const l=g.getBoundingClientRect(),v=Math.max(0,Math.min(1,(o-l.left)/l.width));w=v,y.style.width=`${v*100}%`,g.setAttribute("aria-valuenow",String(Math.round(v*100))),E&&v>0&&e.onMuteToggle(),f.innerHTML=L(E,v),e.onVolumeChange(v)};g.addEventListener("mousedown",o=>{o.stopPropagation(),T=!0,P(o.clientX)});const H=o=>{T&&P(o.clientX)},$=()=>{T=!1};document.addEventListener("mousemove",H),document.addEventListener("mouseup",$),g.addEventListener("touchstart",o=>{T=!0;const l=o.touches[0];l&&P(l.clientX)},{passive:!0});const z=o=>{if(T){const l=o.touches[0];l&&P(l.clientX)}},j=()=>{T=!1};document.addEventListener("touchmove",z,{passive:!0}),document.addEventListener("touchend",j);const q=.05;g.addEventListener("keydown",o=>{let l=w;if(o.key==="ArrowRight"||o.key==="ArrowUp")l=Math.min(1,w+q);else if(o.key==="ArrowLeft"||o.key==="ArrowDown")l=Math.max(0,w-q);else return;o.preventDefault(),o.stopPropagation(),w=l,y.style.width=`${l*100}%`,g.setAttribute("aria-valuenow",String(Math.round(l*100))),E&&l>0&&e.onMuteToggle(),f.innerHTML=L(E,l),e.onVolumeChange(l)});const W=o=>{for(const l of h.querySelectorAll(".hfp-speed-option"))l.classList.toggle("hfp-active",l.dataset.speed===String(o))};p.addEventListener("click",o=>{o.stopPropagation();const l=h.classList.toggle("hfp-open");p.setAttribute("aria-expanded",String(l))}),h.addEventListener("click",o=>{o.stopPropagation();const l=o.target.closest(".hfp-speed-option");if(!l)return;const v=parseFloat(l.dataset.speed);i.indexOf(v),p.textContent=N(v),W(v),h.classList.remove("hfp-open"),p.setAttribute("aria-expanded","false"),e.onSpeedChange(v)});const B=()=>{h.classList.remove("hfp-open"),p.setAttribute("aria-expanded","false")};document.addEventListener("click",B);const R=o=>{const l=a.getBoundingClientRect(),v=Math.max(0,Math.min(1,(o-l.left)/l.width));e.onSeek(v)};let A=!1;a.addEventListener("mousedown",o=>{o.stopPropagation(),A=!0,R(o.clientX)});const X=o=>{A&&R(o.clientX)},G=()=>{A=!1};document.addEventListener("mousemove",X),document.addEventListener("mouseup",G),a.addEventListener("touchstart",o=>{A=!0;const l=o.touches[0];l&&R(l.clientX)},{passive:!0});const Y=o=>{if(A){const l=o.touches[0];l&&R(l.clientX)}},Q=()=>{A=!1};document.addEventListener("touchmove",Y,{passive:!0}),document.addEventListener("touchend",Q);const J=()=>{x&&clearTimeout(x),x=setTimeout(()=>{M&&r.classList.add("hfp-hidden")},3e3)},Z=n instanceof ShadowRoot?n.host:n;return Z.addEventListener("mousemove",()=>{r.classList.remove("hfp-hidden"),J()}),Z.addEventListener("mouseleave",()=>{M&&r.classList.add("hfp-hidden")}),{updateTime(o,l){const v=l>0?Math.min(o,l):o,ae=l>0?v/l*100:0;d.style.width=`${ae}%`,u.textContent=`${re(v)} / ${re(l)}`},updatePlaying(o){M=o,s.innerHTML=o?_e:ee,s.setAttribute("aria-label",o?"Pause":"Play"),o?J():r.classList.remove("hfp-hidden")},updateSpeed(o){i.indexOf(o),p.textContent=N(o),W(o)},updateMuted(o){E=o,f.innerHTML=L(o,w),f.setAttribute("aria-label",o?"Unmute":"Mute")},updateVolume(o){w=o,y.style.width=`${o*100}%`,g.setAttribute("aria-valuenow",String(Math.round(o*100))),f.innerHTML=L(E,o)},show(){r.style.display=""},hide(){r.style.display="none"},destroy(){document.removeEventListener("mousemove",X),document.removeEventListener("mouseup",G),document.removeEventListener("touchmove",Y),document.removeEventListener("touchend",Q),document.removeEventListener("mousemove",H),document.removeEventListener("mouseup",$),document.removeEventListener("touchmove",z),document.removeEventListener("touchend",j),document.removeEventListener("click",B),x&&clearTimeout(x)}}}function we(n,e,t,i,r){const s=i?i.split(",").map(Number).filter(u=>!isNaN(u)&&u>0):void 0,d=ye(n,r,s?{speedPresets:s}:{});return d.updateMuted(e),d.updateVolume(t),d}function ne(n,e,t){return e?(t||(t=document.createElement("img"),t.className="hfp-poster",n.appendChild(t)),t.src=e,t):(t==null||t.remove(),null)}function Ee(n){return n.composedPath().some(e=>e instanceof HTMLElement&&e.classList.contains("hfp-controls"))}let I=null;function Te(n,e){if(typeof CSSStyleSheet<"u")try{I||(I=new CSSStyleSheet,I.replaceSync(e)),n.adoptedStyleSheets=[I];return}catch{}const t=document.createElement("style");t.textContent=e,n.appendChild(t)}function Ae(){const n=document.createElement("div");n.className="hfp-container";const e=document.createElement("iframe");return e.className="hfp-iframe",e.sandbox.add("allow-scripts","allow-same-origin"),e.allow="autoplay; fullscreen",e.referrerPolicy="no-referrer",e.title="HyperFrames Composition",n.appendChild(e),{container:n,iframe:e}}function Ce(n,e,t,i){const r=n.offsetWidth,s=n.offsetHeight;if(r===0||s===0)return;const a=Math.min(r/t,s/i);e.style.width=`${t}px`,e.style.height=`${i}px`,e.style.transform=`translate(-50%, -50%) scale(${a})`}const xe=100;class ke{constructor(e){c(this,"_raf",null);c(this,"_lastUpdateMs",0);this._callbacks=e}start(e,t,i,r){this.stop();const s=()=>{if(r()){this._raf=null;return}let a;try{a=e.time()}catch{this._raf=null;return}const d=i();d>0&&(a=Math.min(a,d));const u=d>0&&a>=d,m=performance.now();if((m-this._lastUpdateMs>xe||u)&&(this._lastUpdateMs=m,this._callbacks.onTimeUpdate(a,d)),u){if(this._callbacks.getLoop()){this._callbacks.restart();return}try{e.pause()}catch{}this._callbacks.onPaused(),this._raf=null;return}this._raf=requestAnimationFrame(s)};this._raf=requestAnimationFrame(s)}stop(){this._raf!==null&&(cancelAnimationFrame(this._raf),this._raf=null)}get isRunning(){return this._raf!==null}}function Se(n){const e=Array.from(n.querySelectorAll("[data-composition-id]"));if(e.length===0)return n.body?[n.body]:[];const t=[];for(const i of e)Le(i)||t.push(i);return Me(n),t}function Me(n){const e=n.body;if(!e||typeof console>"u"||typeof console.warn!="function")return;const t=e.querySelectorAll("audio[data-start], video[data-start]");if(t.length===0)return;const i=[];for(const r of t)r.closest("[data-composition-id]")||i.push(r);i.length!==0&&console.warn(`[hyperframes-player] selectMediaObserverTargets: composition hosts are present, but ${i.length} body-level timed media element(s) sit outside every [data-composition-id] subtree and will not be observed. Move them inside a composition host or the parent-frame proxy will never adopt them.`,i)}function Le(n){let e=n.parentElement;for(;e;){if(e.hasAttribute("data-composition-id"))return!0;e=e.parentElement}return!1}const Pe=.05,Re=2;class Ie{constructor(e){c(this,"_entries",[]);c(this,"_mediaObserver");c(this,"_playbackErrorPosted",!1);c(this,"_audioOwner","runtime");c(this,"_dispatchEvent");c(this,"_getMuted");c(this,"_getVolume");c(this,"_getPlaybackRate");c(this,"_getCurrentTime");c(this,"_isPaused");this._dispatchEvent=e.dispatchEvent,this._getMuted=e.getMuted,this._getVolume=e.getVolume,this._getPlaybackRate=e.getPlaybackRate,this._getCurrentTime=e.getCurrentTime,this._isPaused=e.isPaused}get audioOwner(){return this._audioOwner}get entries(){return this._entries}get playbackErrorPosted(){return this._playbackErrorPosted}resetForIframeLoad(){this._playbackErrorPosted=!1;const e=this._audioOwner==="parent";this._audioOwner="runtime",this.pauseAll(),this.teardownObserver(),e&&this._dispatchEvent(new CustomEvent("audioownershipchange",{detail:{owner:"runtime",reason:"iframe-reload"}}))}destroy(){this.teardownObserver();for(const e of this._entries)e.el.pause(),e.el.src="";this._entries=[]}updateMuted(e){for(const t of this._entries)t.el.muted=e}updateVolume(e){for(const t of this._entries)t.el.volume=e}updatePlaybackRate(e){for(const t of this._entries)t.el.playbackRate=e}playAll(){for(const e of this._entries)e.el.src&&e.el.play().catch(t=>this._reportPlaybackError(t))}pauseAll(){for(const e of this._entries)e.el.pause()}seekAll(e){for(const t of this._entries){const i=e-t.start;i>=0&&i<t.duration&&(t.el.currentTime=i)}}mirrorTime(e,t){const i=(t==null?void 0:t.force)===!0;for(const r of this._entries){const s=e-r.start;if(s<0||s>=r.duration){r.driftSamples=0;continue}Math.abs(r.el.currentTime-s)>Pe?(r.driftSamples+=1,(i||r.driftSamples>=Re)&&(r.el.currentTime=s,r.driftSamples=0)):r.driftSamples=0}}promoteToParentProxy(e,t){if(this._audioOwner==="parent")return;if(this._audioOwner="parent",e)for(const r of e.querySelectorAll("video, audio"))r.muted=!0;const i=this._getCurrentTime();t?t(i,{force:!0}):this.mirrorTime(i,{force:!0}),this._isPaused()||this.playAll(),this._dispatchEvent(new CustomEvent("audioownershipchange",{detail:{owner:"parent",reason:"autoplay-blocked"}}))}setupFromIframe(e){const t=e.querySelectorAll("audio[data-start], video[data-start]");for(const i of t)this._adoptIframeMedia(i);this._observeDynamicMedia(e)}setupFromUrl(e){this._createEntry(e,"audio",0,1/0)}teardownObserver(){var e;(e=this._mediaObserver)==null||e.disconnect(),this._mediaObserver=void 0}_reportPlaybackError(e){this._playbackErrorPosted||(this._playbackErrorPosted=!0,this._dispatchEvent(new CustomEvent("playbackerror",{detail:{source:"parent-proxy",error:e}})))}_createEntry(e,t,i,r){if(this._entries.some(u=>u.el.src===e))return null;const s=t==="video"?document.createElement("video"):new Audio;s.preload="auto",s.src=e,s.load(),s.muted=this._getMuted(),s.volume=this._getVolume();const a=this._getPlaybackRate();a!==1&&(s.playbackRate=a);const d={el:s,start:i,duration:r,driftSamples:0};return this._entries.push(d),d}_adoptIframeMedia(e){var u;if(e.preload==="metadata"||e.preload==="none")return;const t=e.getAttribute("src")||((u=e.querySelector("source"))==null?void 0:u.getAttribute("src"));if(!t)return;const i=new URL(t,e.ownerDocument.baseURI).href,r=parseFloat(e.getAttribute("data-start")||"0"),s=parseFloat(e.getAttribute("data-duration")||"Infinity"),a=e.tagName==="VIDEO"?"video":"audio",d=this._createEntry(i,a,r,s);d&&this._audioOwner==="parent"&&(this.mirrorTime(this._getCurrentTime(),{force:!0}),!this._isPaused()&&d.el.src&&d.el.play().catch(m=>this._reportPlaybackError(m)))}_detachIframeMedia(e){var a;const t=e.getAttribute("src")||((a=e.querySelector("source"))==null?void 0:a.getAttribute("src"));if(!t)return;const i=new URL(t,e.ownerDocument.baseURI).href,r=this._entries.findIndex(d=>d.el.src===i);if(r===-1)return;const s=this._entries[r];s.el.pause(),s.el.src="",this._entries.splice(r,1)}_observeDynamicMedia(e){if(this.teardownObserver(),typeof MutationObserver>"u"||!e.body)return;const t=new MutationObserver(s=>{var a,d,u,m;for(const p of s){if(p.type==="attributes"&&p.attributeName==="preload"){const h=p.target;h instanceof HTMLMediaElement&&h.matches("audio[data-start], video[data-start]")&&h.preload==="auto"&&this._adoptIframeMedia(h);continue}for(const h of p.addedNodes){if(!(h instanceof Element))continue;const b=[];(a=h.matches)!=null&&a.call(h,"audio[data-start], video[data-start]")&&b.push(h);const f=(d=h.querySelectorAll)==null?void 0:d.call(h,"audio[data-start], video[data-start]");if(f)for(const _ of f)b.push(_);for(const _ of b)this._adoptIframeMedia(_)}for(const h of p.removedNodes){if(!(h instanceof Element))continue;const b=[];(u=h.matches)!=null&&u.call(h,"audio[data-start], video[data-start]")&&b.push(h);const f=(m=h.querySelectorAll)==null?void 0:m.call(h,"audio[data-start], video[data-start]");if(f)for(const _ of f)b.push(_);for(const _ of b)this._detachIframeMedia(_)}}}),i={childList:!0,subtree:!0,attributes:!0,attributeFilter:["preload"]},r=Se(e);for(const s of r)t.observe(s,i);this._mediaObserver=t}}const Oe=100;function De(n,e,t,i){const r=(n.frame??0)/e,s=t.duration>0?Math.min(r,t.duration):r,a=!t.paused,d=!n.isPlaying,u=t.duration>0&&s>=t.duration&&(a||n.isPlaying);if(u&&i.getLoop())return i.media.audioOwner==="parent"&&i.media.pauseAll(),i.seek(0),i.play(),{...t,currentTime:s,paused:!1};const m={...t,currentTime:s,paused:d};i.media.audioOwner==="parent"&&(a&&d?i.media.pauseAll():!a&&!d&&i.media.playAll(),i.media.mirrorTime(s));const p=performance.now(),h=d!==t.paused;return(p-t.lastUpdateMs>Oe||h)&&(m.lastUpdateMs=p,i.updateControlsTime(s,t.duration),i.updateControlsPlaying(!d),i.dispatchEvent(new CustomEvent("timeupdate",{detail:{currentTime:s}}))),u&&(i.media.audioOwner==="parent"&&i.media.pauseAll(),m.paused=!0,i.updateControlsPlaying(!1),i.dispatchEvent(new Event("ended"))),m}const se=30;function Ne(n,e,t){if(n.source!==e)return;const i=n.data;if(!(!i||i.source!=="hf-preview")){if(i.type==="shader-transition-state"){const r=i.state&&typeof i.state=="object"?i.state:{};t.shaderLoader.update(r,t.getShaderLoadingMode()),t.dispatchEvent(new CustomEvent("shadertransitionstate",{detail:{compositionId:i.compositionId,state:r}}));return}if(i.type==="state"){t.setPlaybackState(De({frame:i.frame??0,isPlaying:!!i.isPlaying},se,t.getPlaybackState(),t));return}if(i.type==="media-autoplay-blocked"){let r=null;try{r=t.getIframeDoc()}catch{}t.media.promoteToParentProxy(r,(s,a)=>t.media.mirrorTime(s,a)),t.sendControl("set-media-output-muted",{muted:!0});return}if(i.type==="timeline"&&i.durationInFrames>0){if(Number.isFinite(i.durationInFrames)){const r=t.getPlaybackState(),s=i.durationInFrames/se;t.setPlaybackState({...r,duration:s}),t.updateControlsTime(r.currentTime,s)}return}i.type==="stage-size"&&i.width>0&&i.height>0&&t.setCompositionSize(i.width,i.height)}}const C="shader-capture-scale",k="shader-loading",Fe="__hf_shader_capture_scale",Ue="__hf_shader_loading",O=["Preparing scene transitions","Sampling outgoing scene motion","Sampling incoming scene motion","Caching transition frames","Finalizing transition preview"];function V(n){if(n===null)return null;const e=Number(n);return!Number.isFinite(e)||e<=0?null:String(Math.min(1,Math.max(.25,e)))}function Ve(n){if(n===null||n.trim()==="")return"composition";const e=n.trim().toLowerCase();return e==="none"||e==="false"||e==="0"||e==="off"?"none":e==="player"||e==="true"||e==="1"||e==="on"?"player":"composition"}function oe(n,e,t){t===null?n.delete(e):n.set(e,t)}function He(n,e,t){const i=n.indexOf("#"),r=i>=0?n.slice(0,i):n,s=i>=0?n.slice(i):"",a=r.indexOf("?"),d=a>=0?r.slice(0,a):r,u=a>=0?r.slice(a+1):"",m=new URLSearchParams(u);oe(m,Fe,e),oe(m,Ue,t==="composition"?null:t);const p=m.toString();return`${d}${p?`?${p}`:""}${s}`}function $e(n,e,t){if(e===null&&t==="composition")return n;const i=[];e!==null&&i.push(`window.__HF_SHADER_CAPTURE_SCALE=${JSON.stringify(e)};`),t!=="composition"&&i.push(`window.__HF_SHADER_LOADING=${JSON.stringify(t)};`);const r=`<script data-hyperframes-player-shader-options>${i.join("")}<\/script>`;return/<head\b[^>]*>/i.test(n)?n.replace(/<head\b[^>]*>/i,s=>`${s}${r}`):/<html\b[^>]*>/i.test(n)?n.replace(/<html\b[^>]*>/i,s=>`${s}${r}`):`${r}${n}`}function S(n){return Ve(n.getAttribute(k))}function ze(n){return Number(V(n.getAttribute(C))??"1")}function F(n,e){return He(e,V(n.getAttribute(C)),S(n))}function U(n,e){return $e(e,V(n.getAttribute(C)),S(n))}function je(){const n=document.createElement("div");n.className="hfp-shader-loader",n.setAttribute("role","status"),n.setAttribute("aria-live","polite"),n.setAttribute("aria-label","Preparing scene transitions"),n.setAttribute("data-hyperframes-ignore",""),n.draggable=!1;const e=f=>{f.preventDefault(),f.stopPropagation()};for(const f of["selectstart","dragstart","pointerdown","mousedown","click","dblclick","contextmenu","touchstart"])n.addEventListener(f,e,{capture:!0});const t=document.createElement("div");t.className="hfp-shader-loader-panel",t.draggable=!1;const i=document.createElement("div");i.className="hfp-shader-loader-mark",i.draggable=!1,i.innerHTML=['<svg width="78" height="78" viewBox="0 0 100 100" fill="none" aria-hidden="true" draggable="false">','<path d="M10.1851 57.8021L33.1145 73.8313C36.2202 75.9978 41.5173 73.5433 42.4816 69.4984L51.7611 30.4271C52.7253 26.3822 48.5802 23.9277 44.4602 26.0942L13.917 42.1235C6.96677 45.7676 4.97564 54.1579 10.1851 57.8021Z" fill="url(#hfp-shader-loader-grad-left)"/>','<path d="M87.5129 57.5141L56.9696 73.5433C52.8371 75.7098 48.7046 73.2553 49.6688 69.2104L58.9483 30.1391C59.9125 26.0942 65.2097 23.6397 68.3154 25.8062L91.2447 41.8354C96.4668 45.4796 94.4631 53.8699 87.5129 57.5141Z" fill="url(#hfp-shader-loader-grad-right)"/>',"<defs>",'<linearGradient id="hfp-shader-loader-grad-left" x1="48.5676" y1="25" x2="44.7804" y2="71.9384" gradientUnits="userSpaceOnUse">','<stop stop-color="#06E3FA"/>','<stop offset="1" stop-color="#4FDB5E"/>',"</linearGradient>",'<linearGradient id="hfp-shader-loader-grad-right" x1="54.8282" y1="73.8392" x2="72.0989" y2="32.8932" gradientUnits="userSpaceOnUse">','<stop stop-color="#06E3FA"/>','<stop offset="1" stop-color="#4FDB5E"/>',"</linearGradient>","</defs>","</svg>"].join("");const r=document.createElement("div");r.className="hfp-shader-loader-title";const s=document.createElement("span");s.className="hfp-shader-loader-title-text",s.textContent=O[0],r.appendChild(s);const a=document.createElement("div");a.className="hfp-shader-loader-detail",a.textContent="Rendering animated scene samples for shader transitions.";const d=document.createElement("div");d.className="hfp-shader-loader-track",d.setAttribute("aria-hidden","true");const u=document.createElement("div");u.className="hfp-shader-loader-fill",d.appendChild(u);const m=document.createElement("div");m.className="hfp-shader-loader-progress";const p=f=>{const _=document.createElement("div");_.className="hfp-shader-loader-row";const g=document.createElement("span");g.className="hfp-shader-loader-label",g.textContent=f;const y=document.createElement("span");return y.className="hfp-shader-loader-value",_.appendChild(g),_.appendChild(y),m.appendChild(_),{row:_,label:g,value:y}},h=p("transition"),b=p("transition frame");return t.appendChild(i),t.appendChild(r),t.appendChild(a),t.appendChild(d),t.appendChild(m),n.appendChild(t),{root:n,fill:u,title:s,detail:a,transitionValue:h.value,frameLabel:b.label,frameValue:b.value,frameRow:b.row}}const qe=420;class We{constructor(e){c(this,"_el");c(this,"_hideTimeout",null);this._el=e}show(){this._hideTimeout&&(clearTimeout(this._hideTimeout),this._hideTimeout=null),this._el.root.classList.remove("hfp-hiding"),this._el.root.classList.add("hfp-visible")}hide(){if(this._el.root.classList.contains("hfp-hiding")){this._hideTimeout||this._scheduleCleanup();return}this._el.root.classList.contains("hfp-visible")&&(this._el.root.classList.add("hfp-hiding"),this._el.root.classList.remove("hfp-visible"),this._scheduleCleanup())}reset(){this._hideTimeout&&(clearTimeout(this._hideTimeout),this._hideTimeout=null),this._el.root.classList.remove("hfp-visible","hfp-hiding"),this._el.fill.style.transform="scaleX(0)",this._el.transitionValue.textContent="",this._el.frameValue.textContent="",this._el.frameRow.style.visibility="hidden"}update(e,t){if(t!=="player"){this.reset();return}if(e.ready||!e.loading){this.hide();return}const i=typeof e.progress=="number"&&Number.isFinite(e.progress)?e.progress:0,r=typeof e.total=="number"&&Number.isFinite(e.total)?e.total:0,s=r>0?Math.min(1,Math.max(0,i/r)):0,a=Math.min(O.length-1,Math.floor(s*O.length));this._el.title.textContent=O[a]||"Preparing scene transitions",this._el.detail.textContent=e.phase==="cached"?"Loading cached transition frames before playback.":e.phase==="finalizing"?"Uploading transition textures for smooth playback.":"Rendering animated scene samples for shader transitions.",this._el.fill.style.transform=`scaleX(${s})`,this._el.transitionValue.textContent=e.currentTransition!==void 0&&e.transitionTotal!==void 0?`${e.currentTransition}/${e.transitionTotal}`:r>0?`${i}/${r}`:"";const d=e.transitionFrame!==void 0&&e.transitionFrames!==void 0?`${e.transitionFrame}/${e.transitionFrames}`:"";this._el.frameLabel.textContent=e.phase==="cached"?"cached transition frames":e.phase==="finalizing"?"finalizing transition frames":"rendering transition frames",this._el.frameValue.textContent=d,this._el.frameRow.style.visibility=d?"visible":"hidden",this._el.root.setAttribute("aria-valuenow",String(Math.round(s*100))),this.show()}get hideTimeout(){return this._hideTimeout}destroy(){this._hideTimeout&&(clearTimeout(this._hideTimeout),this._hideTimeout=null)}_scheduleCleanup(){this._hideTimeout&&clearTimeout(this._hideTimeout),this._hideTimeout=setTimeout(()=>{this._el.root.classList.remove("hfp-hiding"),this._hideTimeout=null},qe)}}class Be extends HTMLElement{constructor(){super();c(this,"shadow");c(this,"container");c(this,"iframe");c(this,"posterEl",null);c(this,"controlsApi",null);c(this,"resizeObserver");c(this,"shaderLoader");c(this,"probe");c(this,"_ready",!1);c(this,"_currentTime",0);c(this,"_duration",0);c(this,"_paused",!0);c(this,"_lastUpdateMs",0);c(this,"_volume",1);c(this,"_compositionWidth",1920);c(this,"_compositionHeight",1080);c(this,"_directTimelineAdapter",null);c(this,"_directTimelineClock");c(this,"_parentTickRaf",null);c(this,"_media");this.shadow=this.attachShadow({mode:"open"}),Te(this.shadow,ge),{container:this.container,iframe:this.iframe}=Ae(),this.shadow.appendChild(this.container);const t=je();this.shadow.appendChild(t.root),this.shaderLoader=new We(t),this._media=new Ie({dispatchEvent:i=>this.dispatchEvent(i),getMuted:()=>this.muted,getVolume:()=>this._volume,getPlaybackRate:()=>this.playbackRate,getCurrentTime:()=>this._currentTime,isPaused:()=>this._paused}),this._directTimelineClock=new ke({onTimeUpdate:(i,r)=>{var s;this._currentTime=i,(s=this.controlsApi)==null||s.updateTime(i,r),this.dispatchEvent(new CustomEvent("timeupdate",{detail:{currentTime:i}}))},getLoop:()=>this.loop,restart:()=>{this.seek(0),this.play()},onPaused:()=>{var i;this._media.audioOwner==="parent"&&this._media.pauseAll(),this._paused=!0,(i=this.controlsApi)==null||i.updatePlaying(!1),this.dispatchEvent(new Event("ended"))},onEnded:()=>this.loop}),this.probe=new fe(this.iframe,{onReady:i=>this._onProbeReady(i),onError:i=>this.dispatchEvent(new CustomEvent("error",{detail:{message:i}}))}),this.addEventListener("click",i=>{Ee(i)||(this._paused?this.play():this.pause())}),this.resizeObserver=new ResizeObserver(()=>this._rescale()),this._onMessage=this._onMessage.bind(this),this._onIframeLoad=this._onIframeLoad.bind(this)}static get observedAttributes(){return["src","srcdoc","width","height","controls","muted","volume","poster","playback-rate","audio-src",C,k]}connectedCallback(){this.resizeObserver.observe(this),window.addEventListener("message",this._onMessage),this.iframe.addEventListener("load",this._onIframeLoad),this.hasAttribute("controls")&&this._setupControls(),this.hasAttribute("poster")&&(this.posterEl=ne(this.shadow,this.getAttribute("poster"),this.posterEl)),this.hasAttribute("audio-src")&&this._media.setupFromUrl(this.getAttribute("audio-src")),this.hasAttribute("srcdoc")&&(this.iframe.srcdoc=U(this,this.getAttribute("srcdoc"))),this.hasAttribute("src")&&(this.iframe.src=F(this,this.getAttribute("src")))}disconnectedCallback(){var t;this.resizeObserver.disconnect(),window.removeEventListener("message",this._onMessage),this.iframe.removeEventListener("load",this._onIframeLoad),this.probe.stop(),this._directTimelineClock.stop(),this._stopParentTickClock(),this._directTimelineAdapter=null,this.shaderLoader.destroy(),this._media.destroy(),(t=this.controlsApi)==null||t.destroy()}attributeChangedCallback(t,i,r){var s,a,d,u,m,p;switch(t){case"src":r&&(this._ready=!1,this.iframe.src=F(this,r));break;case"srcdoc":this._ready=!1,r!==null?this.iframe.srcdoc=U(this,r):this.iframe.removeAttribute("srcdoc");break;case"width":this._compositionWidth=parseInt(r||"1920",10),this._rescale();break;case"height":this._compositionHeight=parseInt(r||"1080",10),this._rescale();break;case"controls":r!==null?this._setupControls():((s=this.controlsApi)==null||s.destroy(),this.controlsApi=null);break;case"poster":this.posterEl=ne(this.shadow,r,this.posterEl);break;case"playback-rate":{const h=parseFloat(r||"1");this._media.updatePlaybackRate(h),this._sendControl("set-playback-rate",{playbackRate:h}),(d=(a=this._directTimelineAdapter)==null?void 0:a.timeScale)==null||d.call(a,h),(u=this.controlsApi)==null||u.updateSpeed(h),this.dispatchEvent(new Event("ratechange"));break}case"muted":this._media.updateMuted(r!==null),this._sendControl("set-muted",{muted:r!==null}),(m=this.controlsApi)==null||m.updateMuted(r!==null),this.dispatchEvent(new Event("volumechange"));break;case"volume":{const h=Math.max(0,Math.min(1,parseFloat(r||"1")));this._volume=h,this._media.updateVolume(h),this._sendControl("set-volume",{volume:h}),(p=this.controlsApi)==null||p.updateVolume(h),this.dispatchEvent(new Event("volumechange"));break}case"audio-src":r&&this._media.setupFromUrl(r);break;case C:case k:this._reloadShaderOptions();break}}get iframeElement(){return this.iframe}play(){var i,r;(i=this.posterEl)==null||i.remove(),this.posterEl=null,this._duration>0&&this._currentTime>=this._duration&&this.seek(0),this._paused=!1;const t=this._tryDirectTimelinePlay();t||(this._sendControl("play"),this._ready&&!this._directTimelineAdapter&&this._startParentTickClock()),this._media.audioOwner==="parent"&&this._media.playAll(),(r=this.controlsApi)==null||r.updatePlaying(!0),this.dispatchEvent(new Event("play")),t&&this._directTimelineAdapter&&this._directTimelineClock.start(this._directTimelineAdapter,()=>this._currentTime,()=>this._duration,()=>this._paused)}pause(){var t;this._tryDirectTimelinePause()||this._sendControl("pause"),this._directTimelineClock.stop(),this._stopParentTickClock(),this._media.audioOwner==="parent"&&this._media.pauseAll(),this._paused=!0,(t=this.controlsApi)==null||t.updatePlaying(!1),this.dispatchEvent(new Event("pause"))}seek(t){var i,r;!this._trySyncSeek(t)&&!this._tryDirectTimelineSeek(t)&&this._sendControl("seek",{frame:Math.round(t*30)}),this._directTimelineClock.stop(),this._stopParentTickClock(),this._currentTime=t,this._media.audioOwner==="parent"&&(this._media.pauseAll(),this._media.seekAll(t)),this._paused=!0,(i=this.controlsApi)==null||i.updatePlaying(!1),(r=this.controlsApi)==null||r.updateTime(this._currentTime,this._duration)}get currentTime(){return this._currentTime}set currentTime(t){this.seek(t)}get duration(){return this._duration}get paused(){return this._paused}get ready(){return this._ready}get playbackRate(){return parseFloat(this.getAttribute("playback-rate")||"1")}set playbackRate(t){this.setAttribute("playback-rate",String(t))}get shaderCaptureScale(){return ze(this)}set shaderCaptureScale(t){this.setAttribute(C,String(t))}get shaderLoading(){return S(this)}set shaderLoading(t){t==="composition"?this.removeAttribute(k):this.setAttribute(k,t)}get muted(){return this.hasAttribute("muted")}set muted(t){t?this.setAttribute("muted",""):this.removeAttribute("muted")}get volume(){return this._volume}set volume(t){this.setAttribute("volume",String(Math.max(0,Math.min(1,t))))}get loop(){return this.hasAttribute("loop")}set loop(t){t?this.setAttribute("loop",""):this.removeAttribute("loop")}_sendControl(t,i={}){var r;try{(r=this.iframe.contentWindow)==null||r.postMessage({source:"hf-parent",type:"control",action:t,...i},"*")}catch{}}_reloadShaderOptions(){if(S(this)!=="player"&&this.shaderLoader.reset(),this.hasAttribute("srcdoc")){this.iframe.srcdoc=U(this,this.getAttribute("srcdoc")||"");return}this.hasAttribute("src")&&(this.iframe.src=F(this,this.getAttribute("src")||""))}_trySyncSeek(t){try{const i=this.iframe.contentWindow,r=i==null?void 0:i.__player;return typeof(r==null?void 0:r.seek)!="function"?!1:(r.seek.call(r,t),!0)}catch{return!1}}_withDirectTimeline(t){const i=this._directTimelineAdapter||this.probe.resolveDirectTimelineAdapter();if(!i)return!1;try{return t(i),this._directTimelineAdapter=i,!0}catch{return!1}}_tryDirectTimelineSeek(t){return this._withDirectTimeline(i=>{i.seek(t),i.pause()})}_tryDirectTimelinePlay(){return this._withDirectTimeline(t=>void t.play())}_tryDirectTimelinePause(){return this._withDirectTimeline(t=>void t.pause())}_startParentTickClock(){this._stopParentTickClock();const t=()=>{if(this._paused){this._parentTickRaf=null;return}this._sendControl("tick"),this._parentTickRaf=requestAnimationFrame(t)};this._parentTickRaf=requestAnimationFrame(t)}_stopParentTickClock(){this._parentTickRaf!==null&&(cancelAnimationFrame(this._parentTickRaf),this._parentTickRaf=null)}_onMessage(t){Ne(t,this.iframe.contentWindow,{getPlaybackState:()=>({currentTime:this._currentTime,duration:this._duration,paused:this._paused,lastUpdateMs:this._lastUpdateMs}),setPlaybackState:({currentTime:i,duration:r,paused:s,lastUpdateMs:a})=>{this._currentTime=i,this._duration=r,this._paused=s,this._lastUpdateMs=a},getShaderLoadingMode:()=>S(this),shaderLoader:this.shaderLoader,setCompositionSize:(i,r)=>{this._compositionWidth=i,this._compositionHeight=r,this._rescale()},sendControl:(i,r)=>this._sendControl(i,r),getIframeDoc:()=>this.iframe.contentDocument,updateControlsTime:(i,r)=>{var s;return(s=this.controlsApi)==null?void 0:s.updateTime(i,r)},updateControlsPlaying:i=>{var r;return(r=this.controlsApi)==null?void 0:r.updatePlaying(i)},dispatchEvent:i=>this.dispatchEvent(i),seek:i=>this.seek(i),play:()=>this.play(),getLoop:()=>this.loop,media:this._media})}_onProbeReady({duration:t,adapter:i,compositionSize:r}){var s;this._duration=t,this._directTimelineAdapter=i.kind==="direct-timeline"?i.timeline:null,this._ready=!0,(s=this.controlsApi)==null||s.updateTime(0,t),this.dispatchEvent(new CustomEvent("ready",{detail:{duration:t}})),r&&(this._compositionWidth=r.width,this._compositionHeight=r.height,this._rescale());try{const a=this.iframe.contentDocument;a&&this._media.setupFromIframe(a)}catch{}this.hasAttribute("autoplay")&&this.play()}_rescale(){Ce(this,this.iframe,this._compositionWidth,this._compositionHeight)}_onIframeLoad(){this._directTimelineAdapter=null,this._directTimelineClock.stop(),this._stopParentTickClock(),this.shaderLoader.reset(),this._media.resetForIframeLoad(),this.probe.start()}_setupControls(){this.controlsApi||(this.controlsApi=we(this.shadow,this.muted,this._volume,this.getAttribute("speed-presets"),{onPlay:()=>this.play(),onPause:()=>this.pause(),onSeek:t=>this.seek(t*this._duration),onSpeedChange:t=>void(this.playbackRate=t),onMuteToggle:()=>void(this.muted=!this.muted),onVolumeChange:t=>void(this.volume=t)}))}get _audioOwner(){return this._media.audioOwner}get _parentMedia(){return this._media.entries}_mirrorParentMediaTime(t,i){this._media.mirrorTime(t,i)}_promoteToParentProxy(){let t=null;try{t=this.iframe.contentDocument}catch{}this._media.promoteToParentProxy(t,(i,r)=>this._mirrorParentMediaTime(i,r)),this._sendControl("set-media-output-muted",{muted:!0})}_observeDynamicMedia(t){this._media.setupFromIframe(t)}}customElements.get("hyperframes-player")||customElements.define("hyperframes-player",Be);export{Be as HyperframesPlayer,ve as SPEED_PRESETS,N as formatSpeed,re as formatTime};
418
+ `,te='<svg width="24" height="24" viewBox="0 0 18 18" fill="currentColor"><polygon points="4,2 16,9 4,16"/></svg>',be='<svg width="24" height="24" viewBox="0 0 18 18" fill="currentColor"><rect x="3" y="2" width="4" height="14"/><rect x="11" y="2" width="4" height="14"/></svg>',ie='<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M3 9v6h4l5 5V4L7 9H3z"/><path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"/><path d="M14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"/></svg>',re='<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M3 9v6h4l5 5V4L7 9H3z"/><path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"/></svg>',ve='<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M3 9v6h4l5 5V4L7 9H3z"/><path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z" opacity="0.3"/><line x1="18" y1="7" x2="14" y2="17" stroke="currentColor" stroke-width="2"/></svg>',ye=[.25,.5,1,1.5,2,4];function N(n){return Number.isInteger(n)?`${n}x`:`${n}x`}function ne(n){if(!Number.isFinite(n)||n<0)return"0:00";const e=Math.floor(n),t=Math.floor(e/60),i=e%60;return`${t}:${i.toString().padStart(2,"0")}`}function we(n,e,t={}){const i=t.speedPresets??ye,r=document.createElement("div");r.className="hfp-controls",r.addEventListener("click",o=>{o.stopPropagation()});const s=document.createElement("button");s.className="hfp-play-btn",s.type="button",s.innerHTML=te,s.setAttribute("aria-label","Play");const a=document.createElement("div");a.className="hfp-scrubber";const d=document.createElement("div");d.className="hfp-progress",d.style.width="0%",a.appendChild(d);const u=document.createElement("span");u.className="hfp-time",u.textContent="0:00 / 0:00";const m=document.createElement("div");m.className="hfp-speed-wrap";const p=document.createElement("button");p.className="hfp-speed-btn",p.type="button",p.textContent="1x",p.setAttribute("aria-label","Playback speed");const h=document.createElement("div");h.className="hfp-speed-menu",h.setAttribute("role","menu");for(const o of i){const l=document.createElement("button");l.className="hfp-speed-option",l.type="button",l.setAttribute("role","menuitem"),l.dataset.speed=String(o),l.textContent=N(o),o===1&&l.classList.add("hfp-active"),h.appendChild(l)}m.appendChild(h),m.appendChild(p);const b=document.createElement("div");b.className="hfp-volume-wrap";const f=document.createElement("button");f.className="hfp-mute-btn",f.type="button",f.innerHTML=ie,f.setAttribute("aria-label","Mute");const g=document.createElement("div");g.className="hfp-volume-slider-wrap";const _=document.createElement("div");_.className="hfp-volume-slider",_.setAttribute("role","slider"),_.setAttribute("aria-label","Volume"),_.setAttribute("aria-valuemin","0"),_.setAttribute("aria-valuemax","100"),_.setAttribute("aria-valuenow","100"),_.tabIndex=0;const y=document.createElement("div");y.className="hfp-volume-fill",y.style.width="100%",_.appendChild(y),g.appendChild(_),b.appendChild(g),b.appendChild(f),r.appendChild(s),r.appendChild(a),r.appendChild(u),r.appendChild(b),r.appendChild(m),n.appendChild(r);let M=!1,A=!1,w=1,x=null;i.indexOf(1);const L=(o,l)=>o?ve:l===0||l<.5?re:ie;s.addEventListener("click",o=>{o.stopPropagation(),M?e.onPause():e.onPlay()}),f.addEventListener("click",o=>{o.stopPropagation(),e.onMuteToggle()});let E=!1;const P=o=>{const l=_.getBoundingClientRect(),v=Math.max(0,Math.min(1,(o-l.left)/l.width));w=v,y.style.width=`${v*100}%`,_.setAttribute("aria-valuenow",String(Math.round(v*100))),A&&v>0&&e.onMuteToggle(),f.innerHTML=L(A,v),e.onVolumeChange(v)};_.addEventListener("mousedown",o=>{o.stopPropagation(),E=!0,P(o.clientX)});const $=o=>{E&&P(o.clientX)},z=()=>{E=!1};document.addEventListener("mousemove",$),document.addEventListener("mouseup",z),_.addEventListener("touchstart",o=>{E=!0;const l=o.touches[0];l&&P(l.clientX)},{passive:!0});const j=o=>{if(E){const l=o.touches[0];l&&P(l.clientX)}},q=()=>{E=!1};document.addEventListener("touchmove",j,{passive:!0}),document.addEventListener("touchend",q);const B=.05;_.addEventListener("keydown",o=>{let l=w;if(o.key==="ArrowRight"||o.key==="ArrowUp")l=Math.min(1,w+B);else if(o.key==="ArrowLeft"||o.key==="ArrowDown")l=Math.max(0,w-B);else return;o.preventDefault(),o.stopPropagation(),w=l,y.style.width=`${l*100}%`,_.setAttribute("aria-valuenow",String(Math.round(l*100))),A&&l>0&&e.onMuteToggle(),f.innerHTML=L(A,l),e.onVolumeChange(l)});const W=o=>{for(const l of h.querySelectorAll(".hfp-speed-option"))l.classList.toggle("hfp-active",l.dataset.speed===String(o))};p.addEventListener("click",o=>{o.stopPropagation();const l=h.classList.toggle("hfp-open");p.setAttribute("aria-expanded",String(l))}),h.addEventListener("click",o=>{o.stopPropagation();const l=o.target.closest(".hfp-speed-option");if(!l)return;const v=parseFloat(l.dataset.speed);i.indexOf(v),p.textContent=N(v),W(v),h.classList.remove("hfp-open"),p.setAttribute("aria-expanded","false"),e.onSpeedChange(v)});const X=()=>{h.classList.remove("hfp-open"),p.setAttribute("aria-expanded","false")};document.addEventListener("click",X);const R=o=>{const l=a.getBoundingClientRect(),v=Math.max(0,Math.min(1,(o-l.left)/l.width));e.onSeek(v)};let T=!1;a.addEventListener("mousedown",o=>{o.stopPropagation(),T=!0,R(o.clientX)});const G=o=>{T&&R(o.clientX)},Y=()=>{T=!1};document.addEventListener("mousemove",G),document.addEventListener("mouseup",Y),a.addEventListener("touchstart",o=>{T=!0;const l=o.touches[0];l&&R(l.clientX)},{passive:!0});const Q=o=>{if(T){const l=o.touches[0];l&&R(l.clientX)}},J=()=>{T=!1};document.addEventListener("touchmove",Q,{passive:!0}),document.addEventListener("touchend",J);const K=()=>{x&&clearTimeout(x),x=setTimeout(()=>{M&&r.classList.add("hfp-hidden")},3e3)},Z=n instanceof ShadowRoot?n.host:n;return Z.addEventListener("mousemove",()=>{r.classList.remove("hfp-hidden"),K()}),Z.addEventListener("mouseleave",()=>{M&&r.classList.add("hfp-hidden")}),{updateTime(o,l){const v=l>0?Math.min(o,l):o,de=l>0?v/l*100:0;d.style.width=`${de}%`,u.textContent=`${ne(v)} / ${ne(l)}`},updatePlaying(o){M=o,s.innerHTML=o?be:te,s.setAttribute("aria-label",o?"Pause":"Play"),o?K():r.classList.remove("hfp-hidden")},updateSpeed(o){i.indexOf(o),p.textContent=N(o),W(o)},updateMuted(o){A=o,f.innerHTML=L(o,w),f.setAttribute("aria-label",o?"Unmute":"Mute")},updateVolume(o){w=o,y.style.width=`${o*100}%`,_.setAttribute("aria-valuenow",String(Math.round(o*100))),f.innerHTML=L(A,o)},show(){r.style.display=""},hide(){r.style.display="none"},destroy(){document.removeEventListener("mousemove",G),document.removeEventListener("mouseup",Y),document.removeEventListener("touchmove",Q),document.removeEventListener("touchend",J),document.removeEventListener("mousemove",$),document.removeEventListener("mouseup",z),document.removeEventListener("touchmove",j),document.removeEventListener("touchend",q),document.removeEventListener("click",X),x&&clearTimeout(x)}}}function Ae(n,e,t,i,r){const s=i?i.split(",").map(Number).filter(u=>!isNaN(u)&&u>0):void 0,d=we(n,r,s?{speedPresets:s}:{});return d.updateMuted(e),d.updateVolume(t),d}function se(n,e,t){return e?(t||(t=document.createElement("img"),t.className="hfp-poster",n.appendChild(t)),t.src=e,t):(t==null||t.remove(),null)}function Ee(n){return n.composedPath().some(e=>e instanceof HTMLElement&&e.classList.contains("hfp-controls"))}let I=null;function Te(n,e){if(typeof CSSStyleSheet<"u")try{I||(I=new CSSStyleSheet,I.replaceSync(e)),n.adoptedStyleSheets=[I];return}catch{}const t=document.createElement("style");t.textContent=e,n.appendChild(t)}function Ce(){const n=document.createElement("div");n.className="hfp-container";const e=document.createElement("iframe");return e.className="hfp-iframe",e.sandbox.add("allow-scripts","allow-same-origin"),e.allow="autoplay; fullscreen",e.referrerPolicy="no-referrer",e.title="HyperFrames Composition",n.appendChild(e),{container:n,iframe:e}}function xe(n,e,t,i){const r=n.offsetWidth,s=n.offsetHeight;if(r===0||s===0)return;const a=Math.min(r/t,s/i);e.style.width=`${t}px`,e.style.height=`${i}px`,e.style.transform=`translate(-50%, -50%) scale(${a})`}const ke=100;class Se{constructor(e){c(this,"_raf",null);c(this,"_lastUpdateMs",0);this._callbacks=e}start(e,t,i,r){this.stop();const s=()=>{if(r()){this._raf=null;return}let a;try{a=e.time()}catch{this._raf=null;return}const d=i();d>0&&(a=Math.min(a,d));const u=d>0&&a>=d,m=performance.now();if((m-this._lastUpdateMs>ke||u)&&(this._lastUpdateMs=m,this._callbacks.onTimeUpdate(a,d)),u){if(this._callbacks.getLoop()){this._callbacks.restart();return}try{e.pause()}catch{}this._callbacks.onPaused(),this._raf=null;return}this._raf=requestAnimationFrame(s)};this._raf=requestAnimationFrame(s)}stop(){this._raf!==null&&(cancelAnimationFrame(this._raf),this._raf=null)}get isRunning(){return this._raf!==null}}function Me(n){const e=Array.from(n.querySelectorAll("[data-composition-id]"));if(e.length===0)return n.body?[n.body]:[];const t=[];for(const i of e)Pe(i)||t.push(i);return Le(n),t}function Le(n){const e=n.body;if(!e||typeof console>"u"||typeof console.warn!="function")return;const t=e.querySelectorAll("audio[data-start], video[data-start]");if(t.length===0)return;const i=[];for(const r of t)r.closest("[data-composition-id]")||i.push(r);i.length!==0&&console.warn(`[hyperframes-player] selectMediaObserverTargets: composition hosts are present, but ${i.length} body-level timed media element(s) sit outside every [data-composition-id] subtree and will not be observed. Move them inside a composition host or the parent-frame proxy will never adopt them.`,i)}function Pe(n){let e=n.parentElement;for(;e;){if(e.hasAttribute("data-composition-id"))return!0;e=e.parentElement}return!1}const Re=.05,Ie=2;class Oe{constructor(e){c(this,"_entries",[]);c(this,"_mediaObserver");c(this,"_playbackErrorPosted",!1);c(this,"_audioOwner","runtime");c(this,"_dispatchEvent");c(this,"_getMuted");c(this,"_getVolume");c(this,"_getPlaybackRate");c(this,"_getCurrentTime");c(this,"_isPaused");this._dispatchEvent=e.dispatchEvent,this._getMuted=e.getMuted,this._getVolume=e.getVolume,this._getPlaybackRate=e.getPlaybackRate,this._getCurrentTime=e.getCurrentTime,this._isPaused=e.isPaused}get audioOwner(){return this._audioOwner}get entries(){return this._entries}get playbackErrorPosted(){return this._playbackErrorPosted}resetForIframeLoad(){this._playbackErrorPosted=!1;const e=this._audioOwner==="parent";this._audioOwner="runtime",this.pauseAll(),this.teardownObserver(),e&&this._dispatchEvent(new CustomEvent("audioownershipchange",{detail:{owner:"runtime",reason:"iframe-reload"}}))}destroy(){this.teardownObserver();for(const e of this._entries)e.el.pause(),e.el.src="";this._entries=[]}updateMuted(e){for(const t of this._entries)t.el.muted=e}updateVolume(e){for(const t of this._entries)t.el.volume=e}updatePlaybackRate(e){for(const t of this._entries)t.el.playbackRate=e}playAll(){for(const e of this._entries)e.el.src&&e.el.play().catch(t=>this._reportPlaybackError(t))}pauseAll(){for(const e of this._entries)e.el.pause()}seekAll(e){for(const t of this._entries){const i=e-t.start;i>=0&&i<t.duration&&(t.el.currentTime=i)}}mirrorTime(e,t){const i=(t==null?void 0:t.force)===!0;for(const r of this._entries){const s=e-r.start;if(s<0||s>=r.duration){r.driftSamples=0;continue}Math.abs(r.el.currentTime-s)>Re?(r.driftSamples+=1,(i||r.driftSamples>=Ie)&&(r.el.currentTime=s,r.driftSamples=0)):r.driftSamples=0}}promoteToParentProxy(e,t){if(this._audioOwner==="parent")return;if(this._audioOwner="parent",e)for(const r of e.querySelectorAll("video, audio"))r.muted=!0;const i=this._getCurrentTime();t?t(i,{force:!0}):this.mirrorTime(i,{force:!0}),this._isPaused()||this.playAll(),this._dispatchEvent(new CustomEvent("audioownershipchange",{detail:{owner:"parent",reason:"autoplay-blocked"}}))}setupFromIframe(e){const t=e.querySelectorAll("audio[data-start], video[data-start]");for(const i of t)this._adoptIframeMedia(i);this._observeDynamicMedia(e)}setupFromUrl(e){this._createEntry(e,"audio",0,1/0)}teardownObserver(){var e;(e=this._mediaObserver)==null||e.disconnect(),this._mediaObserver=void 0}_reportPlaybackError(e){this._playbackErrorPosted||(this._playbackErrorPosted=!0,this._dispatchEvent(new CustomEvent("playbackerror",{detail:{source:"parent-proxy",error:e}})))}_createEntry(e,t,i,r){if(this._entries.some(u=>u.el.src===e))return null;const s=t==="video"?document.createElement("video"):new Audio;s.preload="auto",s.src=e,s.load(),s.muted=this._getMuted(),s.volume=this._getVolume();const a=this._getPlaybackRate();a!==1&&(s.playbackRate=a);const d={el:s,start:i,duration:r,driftSamples:0};return this._entries.push(d),d}_adoptIframeMedia(e){var u;if(e.preload==="metadata"||e.preload==="none")return;const t=e.getAttribute("src")||((u=e.querySelector("source"))==null?void 0:u.getAttribute("src"));if(!t)return;const i=new URL(t,e.ownerDocument.baseURI).href,r=parseFloat(e.getAttribute("data-start")||"0"),s=parseFloat(e.getAttribute("data-duration")||"Infinity"),a=e.tagName==="VIDEO"?"video":"audio",d=this._createEntry(i,a,r,s);d&&this._audioOwner==="parent"&&(this.mirrorTime(this._getCurrentTime(),{force:!0}),!this._isPaused()&&d.el.src&&d.el.play().catch(m=>this._reportPlaybackError(m)))}_detachIframeMedia(e){var a;const t=e.getAttribute("src")||((a=e.querySelector("source"))==null?void 0:a.getAttribute("src"));if(!t)return;const i=new URL(t,e.ownerDocument.baseURI).href,r=this._entries.findIndex(d=>d.el.src===i);if(r===-1)return;const s=this._entries[r];s.el.pause(),s.el.src="",this._entries.splice(r,1)}_observeDynamicMedia(e){if(this.teardownObserver(),typeof MutationObserver>"u"||!e.body)return;const t=new MutationObserver(s=>{var a,d,u,m;for(const p of s){if(p.type==="attributes"&&p.attributeName==="preload"){const h=p.target;h instanceof HTMLMediaElement&&h.matches("audio[data-start], video[data-start]")&&h.preload==="auto"&&this._adoptIframeMedia(h);continue}for(const h of p.addedNodes){if(!(h instanceof Element))continue;const b=[];(a=h.matches)!=null&&a.call(h,"audio[data-start], video[data-start]")&&b.push(h);const f=(d=h.querySelectorAll)==null?void 0:d.call(h,"audio[data-start], video[data-start]");if(f)for(const g of f)b.push(g);for(const g of b)this._adoptIframeMedia(g)}for(const h of p.removedNodes){if(!(h instanceof Element))continue;const b=[];(u=h.matches)!=null&&u.call(h,"audio[data-start], video[data-start]")&&b.push(h);const f=(m=h.querySelectorAll)==null?void 0:m.call(h,"audio[data-start], video[data-start]");if(f)for(const g of f)b.push(g);for(const g of b)this._detachIframeMedia(g)}}}),i={childList:!0,subtree:!0,attributes:!0,attributeFilter:["preload"]},r=Me(e);for(const s of r)t.observe(s,i);this._mediaObserver=t}}const De=100;function Ne(n,e,t,i){const r=(n.frame??0)/e,s=t.duration>0?Math.min(r,t.duration):r,a=!t.paused,d=!n.isPlaying,u=t.duration>0&&s>=t.duration&&(a||n.isPlaying);if(u&&i.getLoop())return i.media.audioOwner==="parent"&&i.media.pauseAll(),i.seek(0),i.play(),{...t,currentTime:s,paused:!1};const m={...t,currentTime:s,paused:d};i.media.audioOwner==="parent"&&(a&&d?i.media.pauseAll():!a&&!d&&i.media.playAll(),i.media.mirrorTime(s));const p=performance.now(),h=d!==t.paused;return(p-t.lastUpdateMs>De||h)&&(m.lastUpdateMs=p,i.updateControlsTime(s,t.duration),i.updateControlsPlaying(!d),i.dispatchEvent(new CustomEvent("timeupdate",{detail:{currentTime:s}}))),u&&(i.media.audioOwner==="parent"&&i.media.pauseAll(),m.paused=!0,i.updateControlsPlaying(!1),i.dispatchEvent(new Event("ended"))),m}const oe=30;function Fe(n,e,t){if(n.source!==e)return;const i=n.data;if(!(!i||i.source!=="hf-preview")){if(i.type==="shader-transition-state"){const r=i.state&&typeof i.state=="object"?i.state:{};t.shaderLoader.update(r,t.getShaderLoadingMode()),t.dispatchEvent(new CustomEvent("shadertransitionstate",{detail:{compositionId:i.compositionId,state:r}}));return}if(i.type==="state"){t.setPlaybackState(Ne({frame:i.frame??0,isPlaying:!!i.isPlaying},oe,t.getPlaybackState(),t));return}if(i.type==="media-autoplay-blocked"){let r=null;try{r=t.getIframeDoc()}catch{}t.media.promoteToParentProxy(r,(s,a)=>t.media.mirrorTime(s,a)),t.sendControl("set-media-output-muted",{muted:!0});return}if(i.type==="timeline"&&i.durationInFrames>0){if(Number.isFinite(i.durationInFrames)){const r=t.getPlaybackState(),s=i.durationInFrames/oe;t.setPlaybackState({...r,duration:s}),t.updateControlsTime(r.currentTime,s)}return}i.type==="stage-size"&&i.width>0&&i.height>0&&t.setCompositionSize(i.width,i.height)}}const C="shader-capture-scale",k="shader-loading",Ue="__hf_shader_capture_scale",Ve="__hf_shader_loading",O=["Preparing scene transitions","Sampling outgoing scene motion","Sampling incoming scene motion","Caching transition frames","Finalizing transition preview"];function H(n){if(n===null)return null;const e=Number(n);return!Number.isFinite(e)||e<=0?null:String(Math.min(1,Math.max(.25,e)))}function He(n){if(n===null||n.trim()==="")return"composition";const e=n.trim().toLowerCase();return e==="none"||e==="false"||e==="0"||e==="off"?"none":e==="player"||e==="true"||e==="1"||e==="on"?"player":"composition"}function ae(n,e,t){t===null?n.delete(e):n.set(e,t)}function $e(n,e,t){const i=n.indexOf("#"),r=i>=0?n.slice(0,i):n,s=i>=0?n.slice(i):"",a=r.indexOf("?"),d=a>=0?r.slice(0,a):r,u=a>=0?r.slice(a+1):"",m=new URLSearchParams(u);ae(m,Ue,e),ae(m,Ve,t==="composition"?null:t);const p=m.toString();return`${d}${p?`?${p}`:""}${s}`}function ze(n,e,t){if(e===null&&t==="composition")return n;const i=[];e!==null&&i.push(`window.__HF_SHADER_CAPTURE_SCALE=${JSON.stringify(e)};`),t!=="composition"&&i.push(`window.__HF_SHADER_LOADING=${JSON.stringify(t)};`);const r=`<script data-hyperframes-player-shader-options>${i.join("")}<\/script>`;return/<head\b[^>]*>/i.test(n)?n.replace(/<head\b[^>]*>/i,s=>`${s}${r}`):/<html\b[^>]*>/i.test(n)?n.replace(/<html\b[^>]*>/i,s=>`${s}${r}`):`${r}${n}`}function S(n){return He(n.getAttribute(k))}function je(n){return Number(H(n.getAttribute(C))??"1")}function F(n,e){return $e(e,H(n.getAttribute(C)),S(n))}function U(n,e){return ze(e,H(n.getAttribute(C)),S(n))}function qe(){const n=document.createElement("div");n.className="hfp-shader-loader",n.setAttribute("role","status"),n.setAttribute("aria-live","polite"),n.setAttribute("aria-label","Preparing scene transitions"),n.setAttribute("data-hyperframes-ignore",""),n.draggable=!1;const e=f=>{f.preventDefault(),f.stopPropagation()};for(const f of["selectstart","dragstart","pointerdown","mousedown","click","dblclick","contextmenu","touchstart"])n.addEventListener(f,e,{capture:!0});const t=document.createElement("div");t.className="hfp-shader-loader-panel",t.draggable=!1;const i=document.createElement("div");i.className="hfp-shader-loader-mark",i.draggable=!1,i.innerHTML=['<svg width="78" height="78" viewBox="0 0 100 100" fill="none" aria-hidden="true" draggable="false">','<path d="M10.1851 57.8021L33.1145 73.8313C36.2202 75.9978 41.5173 73.5433 42.4816 69.4984L51.7611 30.4271C52.7253 26.3822 48.5802 23.9277 44.4602 26.0942L13.917 42.1235C6.96677 45.7676 4.97564 54.1579 10.1851 57.8021Z" fill="url(#hfp-shader-loader-grad-left)"/>','<path d="M87.5129 57.5141L56.9696 73.5433C52.8371 75.7098 48.7046 73.2553 49.6688 69.2104L58.9483 30.1391C59.9125 26.0942 65.2097 23.6397 68.3154 25.8062L91.2447 41.8354C96.4668 45.4796 94.4631 53.8699 87.5129 57.5141Z" fill="url(#hfp-shader-loader-grad-right)"/>',"<defs>",'<linearGradient id="hfp-shader-loader-grad-left" x1="48.5676" y1="25" x2="44.7804" y2="71.9384" gradientUnits="userSpaceOnUse">','<stop stop-color="#06E3FA"/>','<stop offset="1" stop-color="#4FDB5E"/>',"</linearGradient>",'<linearGradient id="hfp-shader-loader-grad-right" x1="54.8282" y1="73.8392" x2="72.0989" y2="32.8932" gradientUnits="userSpaceOnUse">','<stop stop-color="#06E3FA"/>','<stop offset="1" stop-color="#4FDB5E"/>',"</linearGradient>","</defs>","</svg>"].join("");const r=document.createElement("div");r.className="hfp-shader-loader-title";const s=document.createElement("span");s.className="hfp-shader-loader-title-text",s.textContent=O[0],r.appendChild(s);const a=document.createElement("div");a.className="hfp-shader-loader-detail",a.textContent="Rendering animated scene samples for shader transitions.";const d=document.createElement("div");d.className="hfp-shader-loader-track",d.setAttribute("aria-hidden","true");const u=document.createElement("div");u.className="hfp-shader-loader-fill",d.appendChild(u);const m=document.createElement("div");m.className="hfp-shader-loader-progress";const p=f=>{const g=document.createElement("div");g.className="hfp-shader-loader-row";const _=document.createElement("span");_.className="hfp-shader-loader-label",_.textContent=f;const y=document.createElement("span");return y.className="hfp-shader-loader-value",g.appendChild(_),g.appendChild(y),m.appendChild(g),{row:g,label:_,value:y}},h=p("transition"),b=p("transition frame");return t.appendChild(i),t.appendChild(r),t.appendChild(a),t.appendChild(d),t.appendChild(m),n.appendChild(t),{root:n,fill:u,title:s,detail:a,transitionValue:h.value,frameLabel:b.label,frameValue:b.value,frameRow:b.row}}const Be=420;class We{constructor(e){c(this,"_el");c(this,"_hideTimeout",null);this._el=e}show(){this._hideTimeout&&(clearTimeout(this._hideTimeout),this._hideTimeout=null),this._el.root.classList.remove("hfp-hiding"),this._el.root.classList.add("hfp-visible")}hide(){if(this._el.root.classList.contains("hfp-hiding")){this._hideTimeout||this._scheduleCleanup();return}this._el.root.classList.contains("hfp-visible")&&(this._el.root.classList.add("hfp-hiding"),this._el.root.classList.remove("hfp-visible"),this._scheduleCleanup())}reset(){this._hideTimeout&&(clearTimeout(this._hideTimeout),this._hideTimeout=null),this._el.root.classList.remove("hfp-visible","hfp-hiding"),this._el.fill.style.transform="scaleX(0)",this._el.transitionValue.textContent="",this._el.frameValue.textContent="",this._el.frameRow.style.visibility="hidden"}update(e,t){if(t!=="player"){this.reset();return}if(e.ready||!e.loading){this.hide();return}const i=typeof e.progress=="number"&&Number.isFinite(e.progress)?e.progress:0,r=typeof e.total=="number"&&Number.isFinite(e.total)?e.total:0,s=r>0?Math.min(1,Math.max(0,i/r)):0,a=Math.min(O.length-1,Math.floor(s*O.length));this._el.title.textContent=O[a]||"Preparing scene transitions",this._el.detail.textContent=e.phase==="cached"?"Loading cached transition frames before playback.":e.phase==="finalizing"?"Uploading transition textures for smooth playback.":"Rendering animated scene samples for shader transitions.",this._el.fill.style.transform=`scaleX(${s})`,this._el.transitionValue.textContent=e.currentTransition!==void 0&&e.transitionTotal!==void 0?`${e.currentTransition}/${e.transitionTotal}`:r>0?`${i}/${r}`:"";const d=e.transitionFrame!==void 0&&e.transitionFrames!==void 0?`${e.transitionFrame}/${e.transitionFrames}`:"";this._el.frameLabel.textContent=e.phase==="cached"?"cached transition frames":e.phase==="finalizing"?"finalizing transition frames":"rendering transition frames",this._el.frameValue.textContent=d,this._el.frameRow.style.visibility=d?"visible":"hidden",this._el.root.setAttribute("aria-valuenow",String(Math.round(s*100))),this.show()}get hideTimeout(){return this._hideTimeout}destroy(){this._hideTimeout&&(clearTimeout(this._hideTimeout),this._hideTimeout=null)}_scheduleCleanup(){this._hideTimeout&&clearTimeout(this._hideTimeout),this._hideTimeout=setTimeout(()=>{this._el.root.classList.remove("hfp-hiding"),this._hideTimeout=null},Be)}}const Xe=.1,Ge=5;function V(n){return!Number.isFinite(n)||n<=0?1:Math.max(Xe,Math.min(Ge,n))}class Ye extends HTMLElement{constructor(){super();c(this,"shadow");c(this,"container");c(this,"iframe");c(this,"posterEl",null);c(this,"controlsApi",null);c(this,"resizeObserver");c(this,"shaderLoader");c(this,"probe");c(this,"_ready",!1);c(this,"_currentTime",0);c(this,"_duration",0);c(this,"_paused",!0);c(this,"_lastUpdateMs",0);c(this,"_volume",1);c(this,"_compositionWidth",1920);c(this,"_compositionHeight",1080);c(this,"_directTimelineAdapter",null);c(this,"_directTimelineClock");c(this,"_parentTickRaf",null);c(this,"_media");this.shadow=this.attachShadow({mode:"open"}),Te(this.shadow,ge),{container:this.container,iframe:this.iframe}=Ce(),this.shadow.appendChild(this.container);const t=qe();this.shadow.appendChild(t.root),this.shaderLoader=new We(t),this._media=new Oe({dispatchEvent:i=>this.dispatchEvent(i),getMuted:()=>this.muted,getVolume:()=>this._volume,getPlaybackRate:()=>this.playbackRate,getCurrentTime:()=>this._currentTime,isPaused:()=>this._paused}),this._directTimelineClock=new Se({onTimeUpdate:(i,r)=>{var s;this._currentTime=i,(s=this.controlsApi)==null||s.updateTime(i,r),this.dispatchEvent(new CustomEvent("timeupdate",{detail:{currentTime:i}}))},getLoop:()=>this.loop,restart:()=>{this.seek(0),this.play()},onPaused:()=>{var i;this._media.audioOwner==="parent"&&this._media.pauseAll(),this._paused=!0,(i=this.controlsApi)==null||i.updatePlaying(!1),this.dispatchEvent(new Event("ended"))},onEnded:()=>this.loop}),this.probe=new _e(this.iframe,{onReady:i=>this._onProbeReady(i),onError:i=>this.dispatchEvent(new CustomEvent("error",{detail:{message:i}}))}),this.addEventListener("click",i=>{Ee(i)||(this._paused?this.play():this.pause())}),this.resizeObserver=new ResizeObserver(()=>this._rescale()),this._onMessage=this._onMessage.bind(this),this._onIframeLoad=this._onIframeLoad.bind(this)}static get observedAttributes(){return["src","srcdoc","width","height","controls","muted","volume","poster","playback-rate","audio-src",C,k]}connectedCallback(){this.resizeObserver.observe(this),window.addEventListener("message",this._onMessage),this.iframe.addEventListener("load",this._onIframeLoad),this.hasAttribute("controls")&&this._setupControls(),this.hasAttribute("poster")&&(this.posterEl=se(this.shadow,this.getAttribute("poster"),this.posterEl)),this.hasAttribute("audio-src")&&this._media.setupFromUrl(this.getAttribute("audio-src")),this.hasAttribute("srcdoc")&&(this.iframe.srcdoc=U(this,this.getAttribute("srcdoc"))),this.hasAttribute("src")&&(this.iframe.src=F(this,this.getAttribute("src")))}disconnectedCallback(){var t;this.resizeObserver.disconnect(),window.removeEventListener("message",this._onMessage),this.iframe.removeEventListener("load",this._onIframeLoad),this.probe.stop(),this._directTimelineClock.stop(),this._stopParentTickClock(),this._directTimelineAdapter=null,this.shaderLoader.destroy(),this._media.destroy(),(t=this.controlsApi)==null||t.destroy()}attributeChangedCallback(t,i,r){var s,a,d,u,m,p;switch(t){case"src":r&&(this._ready=!1,this.iframe.src=F(this,r));break;case"srcdoc":this._ready=!1,r!==null?this.iframe.srcdoc=U(this,r):this.iframe.removeAttribute("srcdoc");break;case"width":this._compositionWidth=parseInt(r||"1920",10),this._rescale();break;case"height":this._compositionHeight=parseInt(r||"1080",10),this._rescale();break;case"controls":r!==null?this._setupControls():((s=this.controlsApi)==null||s.destroy(),this.controlsApi=null);break;case"poster":this.posterEl=se(this.shadow,r,this.posterEl);break;case"playback-rate":{const h=V(parseFloat(r||"1"));this._media.updatePlaybackRate(h),this._sendControl("set-playback-rate",{playbackRate:h}),(d=(a=this._directTimelineAdapter)==null?void 0:a.timeScale)==null||d.call(a,h),(u=this.controlsApi)==null||u.updateSpeed(h),this.dispatchEvent(new Event("ratechange"));break}case"muted":this._media.updateMuted(r!==null),this._sendControl("set-muted",{muted:r!==null}),(m=this.controlsApi)==null||m.updateMuted(r!==null),this.dispatchEvent(new Event("volumechange"));break;case"volume":{const h=Math.max(0,Math.min(1,parseFloat(r||"1")));this._volume=h,this._media.updateVolume(h),this._sendControl("set-volume",{volume:h}),(p=this.controlsApi)==null||p.updateVolume(h),this.dispatchEvent(new Event("volumechange"));break}case"audio-src":r&&this._media.setupFromUrl(r);break;case C:case k:this._reloadShaderOptions();break}}get iframeElement(){return this.iframe}play(){var i,r;(i=this.posterEl)==null||i.remove(),this.posterEl=null,this._duration>0&&this._currentTime>=this._duration&&this.seek(0),this._paused=!1;const t=this._tryDirectTimelinePlay();t||(this._sendControl("play"),this._ready&&!this._directTimelineAdapter&&this._startParentTickClock()),this._media.audioOwner==="parent"&&this._media.playAll(),(r=this.controlsApi)==null||r.updatePlaying(!0),this.dispatchEvent(new Event("play")),t&&this._directTimelineAdapter&&this._directTimelineClock.start(this._directTimelineAdapter,()=>this._currentTime,()=>this._duration,()=>this._paused)}pause(){var t;this._tryDirectTimelinePause()||this._sendControl("pause"),this._directTimelineClock.stop(),this._stopParentTickClock(),this._media.audioOwner==="parent"&&this._media.pauseAll(),this._paused=!0,(t=this.controlsApi)==null||t.updatePlaying(!1),this.dispatchEvent(new Event("pause"))}seek(t){var i,r;!this._trySyncSeek(t)&&!this._tryDirectTimelineSeek(t)&&this._sendControl("seek",{frame:Math.round(t*30)}),this._directTimelineClock.stop(),this._stopParentTickClock(),this._currentTime=t,this._media.audioOwner==="parent"&&(this._media.pauseAll(),this._media.seekAll(t)),this._paused=!0,(i=this.controlsApi)==null||i.updatePlaying(!1),(r=this.controlsApi)==null||r.updateTime(this._currentTime,this._duration)}get currentTime(){return this._currentTime}set currentTime(t){this.seek(t)}get duration(){return this._duration}get paused(){return this._paused}get ready(){return this._ready}get playbackRate(){return V(parseFloat(this.getAttribute("playback-rate")||"1"))}set playbackRate(t){this.setAttribute("playback-rate",String(V(t)))}get shaderCaptureScale(){return je(this)}set shaderCaptureScale(t){this.setAttribute(C,String(t))}get shaderLoading(){return S(this)}set shaderLoading(t){t==="composition"?this.removeAttribute(k):this.setAttribute(k,t)}get muted(){return this.hasAttribute("muted")}set muted(t){t?this.setAttribute("muted",""):this.removeAttribute("muted")}get volume(){return this._volume}set volume(t){this.setAttribute("volume",String(Math.max(0,Math.min(1,t))))}get loop(){return this.hasAttribute("loop")}set loop(t){t?this.setAttribute("loop",""):this.removeAttribute("loop")}_sendControl(t,i={}){var r;try{(r=this.iframe.contentWindow)==null||r.postMessage({source:"hf-parent",type:"control",action:t,...i},"*")}catch{}}_reloadShaderOptions(){if(S(this)!=="player"&&this.shaderLoader.reset(),this.hasAttribute("srcdoc")){this.iframe.srcdoc=U(this,this.getAttribute("srcdoc")||"");return}this.hasAttribute("src")&&(this.iframe.src=F(this,this.getAttribute("src")||""))}_trySyncSeek(t){try{const i=this.iframe.contentWindow,r=i==null?void 0:i.__player;return typeof(r==null?void 0:r.seek)!="function"?!1:(r.seek.call(r,t),!0)}catch{return!1}}_withDirectTimeline(t){const i=this._directTimelineAdapter||this.probe.resolveDirectTimelineAdapter();if(!i)return!1;try{return t(i),this._directTimelineAdapter=i,!0}catch{return!1}}_tryDirectTimelineSeek(t){return this._withDirectTimeline(i=>{i.seek(t),i.pause()})}_tryDirectTimelinePlay(){return this._withDirectTimeline(t=>void t.play())}_tryDirectTimelinePause(){return this._withDirectTimeline(t=>void t.pause())}_startParentTickClock(){this._stopParentTickClock();const t=()=>{if(this._paused){this._parentTickRaf=null;return}this._sendControl("tick"),this._parentTickRaf=requestAnimationFrame(t)};this._parentTickRaf=requestAnimationFrame(t)}_stopParentTickClock(){this._parentTickRaf!==null&&(cancelAnimationFrame(this._parentTickRaf),this._parentTickRaf=null)}_onMessage(t){Fe(t,this.iframe.contentWindow,{getPlaybackState:()=>({currentTime:this._currentTime,duration:this._duration,paused:this._paused,lastUpdateMs:this._lastUpdateMs}),setPlaybackState:({currentTime:i,duration:r,paused:s,lastUpdateMs:a})=>{this._currentTime=i,this._duration=r,this._paused=s,this._lastUpdateMs=a},getShaderLoadingMode:()=>S(this),shaderLoader:this.shaderLoader,setCompositionSize:(i,r)=>{this._compositionWidth=i,this._compositionHeight=r,this._rescale()},sendControl:(i,r)=>this._sendControl(i,r),getIframeDoc:()=>this.iframe.contentDocument,updateControlsTime:(i,r)=>{var s;return(s=this.controlsApi)==null?void 0:s.updateTime(i,r)},updateControlsPlaying:i=>{var r;return(r=this.controlsApi)==null?void 0:r.updatePlaying(i)},dispatchEvent:i=>this.dispatchEvent(i),seek:i=>this.seek(i),play:()=>this.play(),getLoop:()=>this.loop,media:this._media})}_onProbeReady({duration:t,adapter:i,compositionSize:r}){var s;this._duration=t,this._directTimelineAdapter=i.kind==="direct-timeline"?i.timeline:null,this._ready=!0,(s=this.controlsApi)==null||s.updateTime(0,t),this.dispatchEvent(new CustomEvent("ready",{detail:{duration:t}})),r&&(this._compositionWidth=r.width,this._compositionHeight=r.height,this._rescale());try{const a=this.iframe.contentDocument;a&&this._media.setupFromIframe(a)}catch{}this.hasAttribute("autoplay")&&this.play()}_rescale(){xe(this,this.iframe,this._compositionWidth,this._compositionHeight)}_onIframeLoad(){this._directTimelineAdapter=null,this._directTimelineClock.stop(),this._stopParentTickClock(),this.shaderLoader.reset(),this._media.resetForIframeLoad(),this.probe.start()}_setupControls(){this.controlsApi||(this.controlsApi=Ae(this.shadow,this.muted,this._volume,this.getAttribute("speed-presets"),{onPlay:()=>this.play(),onPause:()=>this.pause(),onSeek:t=>this.seek(t*this._duration),onSpeedChange:t=>void(this.playbackRate=t),onMuteToggle:()=>void(this.muted=!this.muted),onVolumeChange:t=>void(this.volume=t)}))}get _audioOwner(){return this._media.audioOwner}get _parentMedia(){return this._media.entries}_mirrorParentMediaTime(t,i){this._media.mirrorTime(t,i)}_promoteToParentProxy(){let t=null;try{t=this.iframe.contentDocument}catch{}this._media.promoteToParentProxy(t,(i,r)=>this._mirrorParentMediaTime(i,r)),this._sendControl("set-media-output-muted",{muted:!0})}_observeDynamicMedia(t){this._media.setupFromIframe(t)}}customElements.get("hyperframes-player")||customElements.define("hyperframes-player",Ye);export{Ye as HyperframesPlayer,ye as SPEED_PRESETS,N as formatSpeed,ne as formatTime};