@shotstack/shotstack-studio 2.0.0-beta.38 → 2.0.0-beta.39

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.
@@ -274,4 +274,4 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
274
274
  `){d.push({glyphs:y,width:m,y:0}),y=[],m=0,E=N;continue}if(m+T>r&&y.length>0){if(E>-1){const b=E-(N-y.length)+1,U=y.splice(b),D=y.reduce((B,J)=>B+J.xAdvance,0);d.push({glyphs:y,width:D,y:0}),y=U,m=U.reduce((B,J)=>B+J.xAdvance,0)}else d.push({glyphs:y,width:m,y:0}),y=[],m=0;E=-1}y.push(w),m+=T,C.has(w.cluster)&&(E=N)}y.length>0&&d.push({glyphs:y,width:m,y:0});const F=t.lineHeight*i;for(let N=0;N<d.length;N++)d[N].y=(N+1)*F;return d}catch(e){throw e instanceof Error?e:new Error(`Layout failed: ${String(e)}`)}}};function IC(t,e){return t.type==="linear"?{kind:"linear",angle:t.angle,stops:t.stops,opacity:e}:{kind:"radial",stops:t.stops,opacity:e}}function _C(t,e){const s=Math.max(1,Math.round(e.fontSize*.05));let i=e.baselineY+Math.round(e.fontSize*.1);return t==="line-through"&&(i=e.baselineY-Math.round(e.fontSize*.3)),{x1:e.xStart,x2:e.xStart+e.lineWidth,y:i,width:s}}function FC(t){return t==null?{top:0,right:0,bottom:0,left:0}:typeof t=="number"?{top:t,right:t,bottom:t,left:t}:t}async function TC(t){const e=[],s=FC(t.padding),i=t.border?.width??0;if(e.push({op:"BeginFrame",width:t.canvas.width,height:t.canvas.height,pixelRatio:t.canvas.pixelRatio,clear:!0,bg:void 0}),t.lines.length===0)return e;const a=Math.max(1,await t.getUnitsPerEm()),r=t.font.size/a,n=t.lines.length,o=t.font.size*t.style.lineHeight;let l;switch(t.align.vertical){case"top":l=t.font.size;break;case"bottom":l=t.textRect.height-(n-1)*o;break;case"middle":default:const N=t.font.size*.35;l=(t.textRect.height-(n-1)*o)/2+N;break}l+=i+s.top;const c=t.style.gradient?IC(t.style.gradient,1):{kind:"solid",color:t.font.color,opacity:t.font.opacity},f=t.style.gradient?t.style.gradient.stops[t.style.gradient.stops.length-1]?.color??t.font.color:t.font.color,h=[],d=[];let y=1/0,m=1/0,C=-1/0,E=-1/0;for(const F of t.lines){let N;switch(t.align.horizontal){case"left":N=0;break;case"right":N=t.textRect.width-F.width;break;case"center":default:N=(t.textRect.width-F.width)/2;break}N+=i+s.left;let w=N;const T=t.lines.indexOf(F),b=l+T*o;if(t.font.background){const U=t.font.size*.15,D=t.font.size*.12,B=t.font.size*.92+D*2,J=b-t.font.size*.78-D;d.push({op:"Rectangle",x:N-U,y:J,width:F.width+U*2,height:B,fill:{kind:"solid",color:t.font.background,opacity:1}})}for(const U of F.glyphs){const D=w+U.xOffset,B=b+U.yOffset,J=U.fontDesc?.family;if((U.isColorEmoji||J&&t.isColorEmojiFont&&t.isColorEmojiFont(J))&&U.char){h.push({op:"DrawColorEmoji",char:U.char,x:D,y:B,fontSize:t.font.size,fontFamily:J||"NotoColorEmoji"}),w+=U.xAdvance;continue}const te=await t.glyphPathProvider(U.id,U.fontDesc);if(!te||te==="M 0 0"){w+=U.xAdvance;continue}const he=PC(te),re=D+r*he.x,Se=D+r*(he.x+he.w),ke=B-r*(he.y+he.h),Fe=B-r*he.y;re<y&&(y=re),ke<m&&(m=ke),Se>C&&(C=Se),Fe>E&&(E=Fe),t.shadow&&t.shadow.blur>0&&h.push({isShadow:!0,op:"FillPath",path:te,x:D+t.shadow.offsetX,y:B+t.shadow.offsetY,scale:r,fill:{kind:"solid",color:t.shadow.color,opacity:t.shadow.opacity}}),t.stroke&&t.stroke.width>0&&h.push({op:"StrokePath",path:te,x:D,y:B,scale:r,width:t.stroke.width,color:t.stroke.color,opacity:t.stroke.opacity}),h.push({op:"FillPath",path:te,x:D,y:B,scale:r,fill:c}),w+=U.xAdvance}if(t.style.textDecoration!=="none"){const U=_C(t.style.textDecoration,{baselineY:b,fontSize:t.font.size,lineWidth:F.width,xStart:N});h.push({op:"DecorationLine",from:{x:U.x1,y:U.y},to:{x:U.x2,y:U.y},width:U.width,color:f,opacity:t.font.opacity})}}if(y!==1/0){const F={x:y,y:m,w:Math.max(1,C-y),h:Math.max(1,E-m)};for(const N of h)N.op==="FillPath"&&!N.isShadow&&(N.gradientBBox=F)}if(t.background||t.border){const F=t.contentRect?.width??t.canvas.width,N=t.contentRect?.height??t.canvas.height,w=t.border?.width??0,T=t.border?.radius??0,b=w/2,U=t.canvas.width/2,D=t.canvas.height/2,B=U-F/2,J=D-N/2,ee=Math.min(F-w,N-w)/2,te=Math.min(T,ee),he=Math.max(0,te-b);t.background?.color&&e.push({op:"Rectangle",x:B+w,y:J+w,width:F-w*2,height:N-w*2,fill:{kind:"solid",color:t.background.color,opacity:t.background.opacity},borderRadius:he}),t.border&&t.border.width>0&&e.push({op:"RectangleStroke",x:B+b,y:J+b,width:F-w,height:N-w,stroke:{width:t.border.width,color:t.border.color,opacity:t.border.opacity},borderRadius:te})}return e.push(...d),e.push(...h),e}function EC(t){return t.match(/[MLCQZ]|-?\d*\.?\d+(?:e[-+]?\d+)?/gi)??[]}function PC(t){const e=EC(t);let s=0,i=1/0,a=1/0,r=-1/0,n=-1/0;const o=(l,c)=>{l<i&&(i=l),c<a&&(a=c),l>r&&(r=l),c>n&&(n=c)};for(;s<e.length;)switch(e[s++]){case"M":case"L":{const c=parseFloat(e[s++]),f=parseFloat(e[s++]);o(c,f);break}case"C":{const c=parseFloat(e[s++]),f=parseFloat(e[s++]),h=parseFloat(e[s++]),d=parseFloat(e[s++]),y=parseFloat(e[s++]),m=parseFloat(e[s++]);o(c,f),o(h,d),o(y,m);break}case"Q":{const c=parseFloat(e[s++]),f=parseFloat(e[s++]),h=parseFloat(e[s++]),d=parseFloat(e[s++]);o(c,f),o(h,d);break}}return i===1/0?{x:0,y:0,w:0,h:0}:{x:i,y:a,w:r-i,h:n-a}}var wo=.999;function OC(t,e,s){if(!s.anim||!s.anim.preset)return t;const{preset:i}=s.anim,a=e.reduce((l,c)=>l+c.glyphs.length,0);let r=Math.max(.3,a/(30*s.anim.speed));s.clipDuration&&!s.anim.duration&&(r=Math.min(r,s.clipDuration*.9));const n=s.anim.duration??r,o=Math.max(0,Math.min(1,s.t/n));switch(i){case"typewriter":return RC(t,e,o,s.anim.style,s.fontSize,s.t);case"fadeIn":return DC(t,e,o,s.anim.style,s.fontSize,n);case"slideIn":return BC(t,e,o,s.anim.direction??"left",s.fontSize,s.anim.style,n);case"shift":return LC(t,e,o,s.anim.direction??"left",s.fontSize,s.anim.style,n);case"ascend":return zC(t,e,o,s.anim.direction??"up",s.fontSize,n);case"movingLetters":return ZC(t,s.t,s.anim.direction??"up",s.fontSize);default:return t}}var _r=t=>t.op==="FillPath"&&t.isShadow===!0,Fr=t=>t.op==="FillPath"&&!t.isShadow;function MC(t){for(const e of t)if(e.op==="FillPath"){const s=e.fill;if(s?.kind==="solid")return s.color;if((s?.kind==="linear"||s?.kind==="radial")&&Array.isArray(s.stops)&&s.stops.length)return s.stops[s.stops.length-1].color||"#000000"}return"#000000"}function RC(t,e,s,i,a,r,n){if(i==="word"){const l=la(e),c=l.length,f=Math.floor(s*c);if(f===0)return t.filter(m=>m.op==="BeginFrame"||m.op==="Rectangle"||m.op==="RectangleStroke");let h=0;for(let m=0;m<Math.min(f,l.length);m++)h+=l[m].glyphCount;const d=A0(t,h),y=s>=wo?d:d.filter(m=>m.op!=="DecorationLine");return s<1&&h>0?S0(y,h,a):y}else{const l=e.reduce((d,y)=>d+y.glyphs.length,0),c=Math.floor(s*l);if(c===0)return t.filter(d=>d.op==="BeginFrame"||d.op==="Rectangle"||d.op==="RectangleStroke");const f=A0(t,c),h=s>=wo?f:f.filter(d=>d.op!=="DecorationLine");return s<1&&c>0?S0(h,c,a):h}}function zC(t,e,s,i,a,r){const n=la(e),o=n.length;if(o===0)return t;const l=[];let c=0;for(const f of t)if((f.op==="BeginFrame"||f.op==="Rectangle"||f.op==="RectangleStroke")&&l.push(f),f.op==="FillPath"||f.op==="StrokePath")break;for(const f of t)if(f.op==="FillPath"||f.op==="StrokePath"){let h=-1,d=0;for(let y=0;y<n.length;y++){const m=n[y].glyphCount;if(c>=d&&c<d+m){h=y;break}d+=m}if(h>=0){const y=h/Math.max(1,o)*(r/r),m=Math.min(1,y+.3);if(s>=m)l.push(f);else if(s>y){const C=(s-y)/Math.max(1e-6,m-y),E=Tr(Math.min(1,C)),F=i==="up"?a*.4:-a*.4,N={...f,y:f.y+F*(1-E)};f.op==="FillPath"?N.fill.kind==="solid"?N.fill={...N.fill,opacity:N.fill.opacity*E}:N.fill={...N.fill,opacity:(N.fill.opacity??1)*E}:N.opacity=N.opacity*E,l.push(N)}}Fr(f)&&c++}else f.op==="DecorationLine"&&s>=wo&&l.push(f);return l}function LC(t,e,s,i,a,r,n){const o=r==="word",c={left:{x:a*.6,y:0},right:{x:-a*.6,y:0},up:{x:0,y:a*.6},down:{x:0,y:-a*.6}}[i],f=o?la(e):[],h=e.reduce((w,T)=>w+T.glyphs.length,0),d=o?f.length:h;if(d===0)return t;const y=[];for(const w of t)if((w.op==="BeginFrame"||w.op==="Rectangle"||w.op==="RectangleStroke")&&y.push(w),w.op==="FillPath"||w.op==="StrokePath")break;const m=.3,E=n*.7/Math.max(1,d-1),F=w=>{const T=w*E,b=T/n,U=Math.min(1,(T+m)/n);return{startF:b,endF:U}};let N=0;for(const w of t){if(w.op!=="FillPath"&&w.op!=="StrokePath"){w.op==="DecorationLine"&&s>.8&&y.push(w);continue}let T;if(!o)T=N;else{let D=-1,B=0;for(let J=0;J<f.length;J++){const ee=f[J].glyphCount;if(N>=B&&N<B+ee){D=J;break}B+=ee}T=Math.max(0,D)}const{startF:b,endF:U}=F(T);if(s<=b){const D={...w,x:w.x+c.x,y:w.y+c.y};w.op==="FillPath"?D.fill.kind==="solid"?D.fill={...D.fill,opacity:0}:D.fill={...D.fill,opacity:0}:D.opacity=0,y.push(D)}else if(s>=U)y.push(w);else{const D=(s-b)/Math.max(1e-6,U-b),B=Tr(Math.min(1,D)),J=c.x*(1-B),ee=c.y*(1-B),te={...w,x:w.x+J,y:w.y+ee};if(w.op==="FillPath"){const he=te.fill.kind==="solid"?te.fill.opacity:te.fill.opacity??1;te.fill.kind==="solid"?te.fill={...te.fill,opacity:he*B}:te.fill={...te.fill,opacity:he*B}}else te.opacity=te.opacity*B;y.push(te)}Fr(w)&&N++}return y}function DC(t,e,s,i,a,r){const n=i==="word";if(!n&&!(i==="character")){const F=vo(s),N=.95+.05*F;return GC(t,F,N)}const l=n?la(e):[],c=e.reduce((F,N)=>F+N.glyphs.length,0),f=n?l.length:c;if(f===0)return t;const h=[];for(const F of t)if(F.op==="BeginFrame"){h.push(F);break}const d=.3,m=r*.7/Math.max(1,f-1),C=F=>{const N=F*m,w=N/r,T=Math.min(1,(N+d)/r);return{startF:w,endF:T}};let E=0;for(const F of t){if(F.op!=="FillPath"&&F.op!=="StrokePath"){F.op==="DecorationLine"&&s>.8&&h.push(F);continue}let N;if(!n)N=E;else{let b=-1,U=0;for(let D=0;D<l.length;D++){const B=l[D].glyphCount;if(E>=U&&E<U+B){b=D;break}U+=B}N=Math.max(0,b)}const{startF:w,endF:T}=C(N);if(s<=w){const b={...F};F.op==="FillPath"?b.fill.kind==="solid"?b.fill={...b.fill,opacity:0}:b.fill={...b.fill,opacity:0}:b.opacity=0,h.push(b)}else if(s>=T)h.push(F);else{const b=(s-w)/Math.max(1e-6,T-w),U=vo(Math.min(1,b)),D={...F};if(F.op==="FillPath"){const B=D.fill.kind==="solid"?D.fill.opacity:D.fill.opacity??1;D.fill.kind==="solid"?D.fill={...D.fill,opacity:B*U}:D.fill={...D.fill,opacity:B*U}}else D.opacity=D.opacity*U;h.push(D)}Fr(F)&&E++}return h}function BC(t,e,s,i,a,r,n){const o=r==="word";if(!o&&!(r==="character")){const T=Tr(s),b=HC(1-T,i,a*2),U=vo(s);return WC(t,b.dx,b.dy,U)}const f={left:{x:a*2,y:0},right:{x:-a*2,y:0},up:{x:0,y:a*2},down:{x:0,y:-a*2}}[i],h=o?la(e):[],d=e.reduce((T,b)=>T+b.glyphs.length,0),y=o?h.length:d;if(y===0)return t;const m=[];for(const T of t)if(T.op==="BeginFrame"){m.push(T);break}const C=.3,F=n*.7/Math.max(1,y-1),N=T=>{const b=T*F,U=b/n,D=Math.min(1,(b+C)/n);return{startF:U,endF:D}};let w=0;for(const T of t){if(T.op!=="FillPath"&&T.op!=="StrokePath"){T.op==="DecorationLine"&&s>.8&&m.push(T);continue}let b;if(!o)b=w;else{let B=-1,J=0;for(let ee=0;ee<h.length;ee++){const te=h[ee].glyphCount;if(w>=J&&w<J+te){B=ee;break}J+=te}b=Math.max(0,B)}const{startF:U,endF:D}=N(b);if(s<=U){const B={...T,x:T.x+f.x,y:T.y+f.y};T.op==="FillPath"?B.fill.kind==="solid"?B.fill={...B.fill,opacity:0}:B.fill={...B.fill,opacity:0}:B.opacity=0,m.push(B)}else if(s>=D)m.push(T);else{const B=(s-U)/Math.max(1e-6,D-U),J=Tr(Math.min(1,B)),ee=f.x*(1-J),te=f.y*(1-J),he={...T,x:T.x+ee,y:T.y+te};if(T.op==="FillPath"){const re=he.fill.kind==="solid"?he.fill.opacity:he.fill.opacity??1;he.fill.kind==="solid"?he.fill={...he.fill,opacity:re*J}:he.fill={...he.fill,opacity:re*J}}else he.opacity=he.opacity*J;m.push(he)}Fr(T)&&w++}return m}function ZC(t,e,s,i){const a=i*.3;return YC(t,s,a,e)}function la(t){const e=[];let s=0;for(let i=0;i<t.length;i++){const a=t[i],r=UC(a);for(const n of r)n.length>0&&e.push({startGlyph:s,glyphCount:n.length,lineIndex:i}),s+=n.length}return e}function UC(t){const e=[];let s=[];for(const i of t.glyphs)i.char===" "||i.char===" "||i.char===`
275
275
  `?s.length&&(e.push([...s]),s=[]):s.push(i);return s.length&&e.push(s),e}function A0(t,e){const s=[];let i=0,a=!1;for(const r of t){if(r.op==="BeginFrame"||r.op==="Rectangle"||r.op==="RectangleStroke"){s.push(r);continue}if(r.op==="FillPath"&&!_r(r)){i<e&&(s.push(r),a=!0),i++;continue}if(r.op==="StrokePath"){i<e&&s.push(r);continue}if(r.op==="FillPath"&&_r(r)){i<e&&s.push(r);continue}if(r.op==="DecorationLine"&&a){s.push(r);continue}}return s}function S0(t,e,s,i){if(e===0)return t;let a=null,r=0;for(const n of t)if(n.op==="FillPath"&&!_r(n)&&(r++,r===e)){a=n;break}if(a&&a.op==="FillPath"){const n=MC(t),o=a.x+s*.5,l=a.y,c=Math.max(3,s/15),f={op:"DecorationLine",from:{x:o,y:l-s*.75},to:{x:o,y:l+s*.15},width:c,color:n,opacity:1};return[...t,f]}return t}function GC(t,e,s){let i=0,a=0,r=0;return t.forEach(n=>{n.op==="FillPath"&&(i+=n.x,a+=n.y,r++)}),r>0&&(i/=r,a/=r),t.map(n=>{if(n.op==="FillPath"){const o={...n};if(o.fill.kind==="solid"?o.fill={...o.fill,opacity:o.fill.opacity*e}:o.fill={...o.fill,opacity:(o.fill.opacity??1)*e},s!==1&&r>0){const l=n.x-i,c=n.y-a;o.x=i+l*s,o.y=a+c*s}return o}if(n.op==="StrokePath"){const o={...n,opacity:n.opacity*e};if(s!==1&&r>0){const l=n.x-i,c=n.y-a;o.x=i+l*s,o.y=a+c*s}return o}return n.op==="DecorationLine"?{...n,opacity:n.opacity*e}:n})}function WC(t,e,s,i=1){return t.map(a=>{if(a.op==="FillPath"){const r={...a,x:a.x+e,y:a.y+s};return i<1&&(r.fill.kind==="solid"?r.fill={...r.fill,opacity:r.fill.opacity*i}:r.fill={...r.fill,opacity:(r.fill.opacity??1)*i}),r}return a.op==="StrokePath"?{...a,x:a.x+e,y:a.y+s,opacity:a.opacity*i}:a.op==="DecorationLine"?{...a,from:{x:a.from.x+e,y:a.from.y+s},to:{x:a.to.x+e,y:a.to.y+s},opacity:a.opacity*i}:a})}function YC(t,e,s,i){let a=0;const n=Math.min(1,i/.5);return t.map(o=>{if(o.op==="FillPath"||o.op==="StrokePath"){const l=Math.sin(a/5*Math.PI+i*Math.PI*2),c=e==="left"||e==="right"?l*s*(e==="left"?-1:1):0,f=e==="up"||e==="down"?l*s*(e==="up"?-1:1):0;if(o.op==="FillPath"){_r(o)||a++;const h={...o,x:o.x+c,y:o.y+f};return h.fill.kind==="solid"?h.fill={...h.fill,opacity:h.fill.opacity*n}:h.fill={...h.fill,opacity:(h.fill.opacity??1)*n},h}return{...o,x:o.x+c,y:o.y+f,opacity:o.opacity*n}}return o})}function HC(t,e,s){const i=t*s;switch(e){case"left":return{dx:-i,dy:0};case"right":return{dx:i,dy:0};case"up":return{dx:0,dy:-i};case"down":return{dx:0,dy:i}}}function vo(t){return t*(2-t)}function Tr(t){return 1-Math.pow(1-t,3)}function ei(t,e=1){const s=/^#?([a-f0-9]{6})$/i.exec(t);if(!s)throw new Error(`Invalid color ${t}`);const i=parseInt(s[1],16),a=i>>16&255,r=i>>8&255,n=i&255;return{r:a,g:r,b:n,a:e}}function jC(t){const e=t.getContext("2d");if(!e)throw new Error("2D context unavailable");return{async render(s){const i=KC(s),a=new Map;for(const r of s){if(r.op==="BeginFrame"){r.pixelRatio;const n=r.width,o=r.height;if("width"in t&&"height"in t&&(t.width=Math.floor(n),t.height=Math.floor(o)),"style"in t&&(t.style.width=`${n}px`,t.style.height=`${o}px`),e.setTransform(1,0,0,1,0,0),r.clear&&e.clearRect(0,0,n,o),r.bg&&r.bg.color){const{color:l,opacity:c,radius:f}=r.bg;if(l){const h=ei(l,c);f&&f>0?(e.fillStyle=`rgba(${h.r},${h.g},${h.b},${h.a})`,V0(e,0,0,n,o,f),e.fill()):(e.fillStyle=`rgba(${h.r},${h.g},${h.b},${h.a})`,e.fillRect(0,0,n,o))}}continue}if(r.op==="FillPath"){const n=r,o=new Path2D(n.path);e.save(),e.translate(n.x,n.y);const l=n.scale??1;e.scale(l,-l);const c=n.gradientBBox??i,f={x:(c.x-n.x)/l,y:-(c.y-n.y)/l,w:c.w/l,h:c.h/l},h=JSON.stringify({fill:n.fill,bbox:f});let d=a.get(h);d||(d=ca(e,n.fill,f),a.set(h,d)),e.fillStyle=d,e.fill(o),e.restore();continue}if(r.op==="StrokePath"){const n=r,o=new Path2D(n.path);e.save(),e.translate(n.x,n.y);const l=n.scale??1;e.scale(l,-l);const c=1/Math.abs(l),f=ei(n.color,n.opacity);e.strokeStyle=`rgba(${f.r},${f.g},${f.b},${f.a})`,e.lineWidth=n.width*c,e.lineJoin="round",e.lineCap="round",e.stroke(o),e.restore();continue}if(r.op==="DecorationLine"){e.save();const n=ei(r.color,r.opacity);e.strokeStyle=`rgba(${n.r},${n.g},${n.b},${n.a})`,e.lineWidth=r.width,e.beginPath(),e.moveTo(r.from.x,r.from.y),e.lineTo(r.to.x,r.to.y),e.stroke(),e.restore();continue}if(r.op==="Rectangle"){e.save();const n=ca(e,r.fill,{x:r.x,y:r.y,w:r.width,h:r.height});e.fillStyle=n,r.borderRadius&&r.borderRadius>0?V0(e,r.x,r.y,r.width,r.height,r.borderRadius):e.fillRect(r.x,r.y,r.width,r.height),e.restore();continue}if(r.op==="RectangleStroke"){e.save();const n=ei(r.stroke.color,r.stroke.opacity);if(e.strokeStyle=`rgba(${n.r},${n.g},${n.b},${n.a})`,e.lineWidth=r.stroke.width,r.borderRadius&&r.borderRadius>0){const o=new Path2D,l=r.x,c=r.y,f=r.width,h=r.height,d=Math.min(f,h)/2,y=Math.min(r.borderRadius,d);o.moveTo(l+y,c),o.arcTo(l+f,c,l+f,c+h,y),o.arcTo(l+f,c+h,l,c+h,y),o.arcTo(l,c+h,l,c,y),o.arcTo(l,c,l+f,c,y),o.closePath(),e.stroke(o)}else e.strokeRect(r.x,r.y,r.width,r.height);e.restore();continue}if(r.op==="DrawColorEmoji"){e.save(),e.font=`${r.fontSize}px "${r.fontFamily}"`,e.textBaseline="alphabetic",e.fillText(r.char,r.x,r.y),e.restore();continue}if(r.op==="Ellipse"){e.save();const n=r.gradientBBox??{x:r.cx-r.rx,y:r.cy-r.ry,w:r.rx*2,h:r.ry*2},o=ca(e,r.fill,n);e.fillStyle=o,e.beginPath();const l=(r.rotation??0)*Math.PI/180;e.ellipse(r.cx,r.cy,r.rx,r.ry,l,0,Math.PI*2),e.fill(),e.restore();continue}if(r.op==="EllipseStroke"){e.save(),xo(e,r.stroke),e.beginPath();const n=(r.rotation??0)*Math.PI/180;e.ellipse(r.cx,r.cy,r.rx,r.ry,n,0,Math.PI*2),e.stroke(),e.restore();continue}if(r.op==="Polygon"){e.save();const n=r.gradientBBox??qC(r.points),o=ca(e,r.fill,n);e.fillStyle=o,e.beginPath(),_0(e,r.points,r.closed??!0),e.fill(),e.restore();continue}if(r.op==="PolygonStroke"){e.save(),xo(e,r.stroke),e.beginPath(),_0(e,r.points,r.closed??!0),e.stroke(),e.restore();continue}if(r.op==="ShapePath"){e.save(),e.translate(r.x,r.y);const n=r.gradientBBox??I0(r.path),o=ca(e,r.fill,n);e.fillStyle=o;const l=new Path2D(r.path);e.fill(l),e.restore();continue}if(r.op==="ShapePathStroke"){e.save(),e.translate(r.x,r.y),xo(e,r.stroke);const n=new Path2D(r.path);e.stroke(n),e.restore();continue}}}}}function V0(t,e,s,i,a,r){const n=Math.min(i,a)/2,o=Math.min(r,n),l=new Path2D;l.moveTo(e+o,s),l.arcTo(e+i,s,e+i,s+a,o),l.arcTo(e+i,s+a,e,s+a,o),l.arcTo(e,s+a,e,s,o),l.arcTo(e,s,e+i,s,o),l.closePath(),t.save(),t.fill(l),t.restore()}function ca(t,e,s){if(e.kind==="solid"){const o=ei(e.color,e.opacity);return`rgba(${o.r},${o.g},${o.b},${o.a})`}const i=s.x+s.w/2,a=s.y+s.h/2,r=Math.max(s.w,s.h)/2,n=o=>{const l=e.kind==="linear"||e.kind==="radial"?e.opacity:1,c=e.kind==="linear"||e.kind==="radial"?e.stops:[];for(const f of c){const h=ei(f.color,l);o.addColorStop(f.offset,`rgba(${h.r},${h.g},${h.b},${h.a})`)}return o};if(e.kind==="linear"){const o=e.angle*Math.PI/180,l=i+Math.cos(o+Math.PI)*r,c=a+Math.sin(o+Math.PI)*r,f=i+Math.cos(o)*r,h=a+Math.sin(o)*r;return n(t.createLinearGradient(l,c,f,h))}else return n(t.createRadialGradient(i,a,0,i,a,r))}function KC(t){let e=1/0,s=1/0,i=-1/0,a=-1/0;for(const r of t){if(r.op!=="FillPath")continue;const n=r;if(n.isShadow)continue;const o=I0(n.path),l=n.scale??1,c=n.x+l*o.x,f=n.x+l*(o.x+o.w),h=n.y-l*(o.y+o.h),d=n.y-l*o.y;c<e&&(e=c),h<s&&(s=h),f>i&&(i=f),d>a&&(a=d)}return e===1/0?{x:0,y:0,w:1,h:1}:{x:e,y:s,w:Math.max(1,i-e),h:Math.max(1,a-s)}}function I0(t){const e=XC(t);let s=0,i=1/0,a=1/0,r=-1/0,n=-1/0;const o=(l,c)=>{l<i&&(i=l),c<a&&(a=c),l>r&&(r=l),c>n&&(n=c)};for(;s<e.length;)switch(e[s++]){case"M":case"L":{const c=parseFloat(e[s++]),f=parseFloat(e[s++]);o(c,f);break}case"C":{const c=parseFloat(e[s++]),f=parseFloat(e[s++]),h=parseFloat(e[s++]),d=parseFloat(e[s++]),y=parseFloat(e[s++]),m=parseFloat(e[s++]);o(c,f),o(h,d),o(y,m);break}case"Q":{const c=parseFloat(e[s++]),f=parseFloat(e[s++]),h=parseFloat(e[s++]),d=parseFloat(e[s++]);o(c,f),o(h,d);break}}return i===1/0?{x:0,y:0,w:0,h:0}:{x:i,y:a,w:r-i,h:n-a}}function XC(t){return t.match(/[MLCQZ]|-?\d*\.?\d+(?:e[-+]?\d+)?/gi)??[]}function xo(t,e){const s=ei(e.color,e.opacity);t.strokeStyle=`rgba(${s.r},${s.g},${s.b},${s.a})`,t.lineWidth=e.width,t.lineCap=e.lineCap??"butt",t.lineJoin=e.lineJoin??"miter",e.dashArray&&e.dashArray.length>0&&t.setLineDash(e.dashArray)}function qC(t){if(t.length===0)return{x:0,y:0,w:0,h:0};let e=t[0].x,s=t[0].y,i=t[0].x,a=t[0].y;for(let r=1;r<t.length;r++){const n=t[r];n.x<e&&(e=n.x),n.y<s&&(s=n.y),n.x>i&&(i=n.x),n.y>a&&(a=n.y)}return{x:e,y:s,w:i-e,h:a-s}}function _0(t,e,s){if(e.length!==0){t.moveTo(e[0].x,e[0].y);for(let i=1;i<e.length;i++)t.lineTo(e[i].x,e[i].y);s&&t.closePath()}}async function Er(t){try{const e=await fetch(t);if(!e.ok)throw new Error(`Failed to fetch ${t}: ${e.status} ${e.statusText}`);try{return await e.arrayBuffer()}catch(s){throw new Error(`Failed to read response body as ArrayBuffer from ${t}: ${s instanceof Error?s.message:String(s)}`)}}catch(e){throw e instanceof Error?e.message.includes("Failed to fetch")||e.message.includes("Failed to read")?e:new Error(`Failed to fetch ${t}: ${e.message}`):new Error(`Failed to fetch ${t}: ${String(e)}`)}}function Tt(t,e){return t===void 0?e:typeof t=="string"?parseFloat(t):t}var ti=null,fa=!1,F0="https://unpkg.com/@resvg/resvg-wasm@2.6.2/index_bg.wasm";async function Co(t){try{const e=await fetch(t);if(e.ok){const s=await e.arrayBuffer(),i=new Uint8Array(s);if(i.length>=4&&i[0]===0&&i[1]===97&&i[2]===115&&i[3]===109)return s;console.error(`Invalid WASM magic number from URL: ${t}`)}else console.error(`Failed to fetch resvg WASM from URL: ${t}, status: ${e.status}`);return}catch(e){console.error(`Error fetching resvg WASM from ${t}:`,e);return}}async function T0(t){try{if(t){const e=t.endsWith(".wasm")?t:t.endsWith("/")?`${t}resvg.wasm`:`${t}/resvg.wasm`,s=await Co(e);if(s)return s}return}catch(e){console.error("Error in loadResvgWasmWeb:",e);return}}async function JC(t){if(ti&&fa)return ti;if(ti=await Promise.resolve().then(()=>Q0),!fa){let s=await T0(t);if(s||(s=await Co(F0)),!s)throw new Error("Failed to load resvg WASM from any source");const i=await WebAssembly.compile(s);await ti.initWasm(i),fa=!0}return ti}async function QC(t){if(fa)return;ti=await Promise.resolve().then(()=>Q0);let s;if(t instanceof ArrayBuffer?s=t:(s=await T0(t),s||(s=await Co(F0))),!s)throw new Error("Failed to load resvg WASM from any source");const i=await WebAssembly.compile(s);await ti.initWasm(i),fa=!0}async function $C(t,e={}){const{Resvg:s}=await JC(),i={};e.background&&(i.background=e.background),e.fitTo?i.fitTo=e.fitTo:e.width?i.fitTo={mode:"width",value:e.width}:e.height&&(i.fitTo={mode:"height",value:e.height});const a=new s(t,i);try{const r=a.render();try{return{png:r.asPng(),width:r.width,height:r.height}}finally{r.free()}}finally{a.free()}}function ek(t,e,s){if(!t.shape)throw new Error("Shape is required for shape mode");const i=Tt(t.width,e),a=Tt(t.height,s),r=sk(t.shape),n=dk(r),o=i/2,l=a/2,c=n.x+n.w/2,f=n.y+n.h/2;let h=o-c,d=l-f;t.transform&&(h+=Tt(t.transform.x,0),d+=Tt(t.transform.y,0));const y=[];if(t.shadow){const C=Tt(t.shadow.offsetX,4),E=Tt(t.shadow.offsetY,4),F=t.shadow.color??"#000000",N=Tt(t.shadow.opacity,.5);y.push(`<path d="${r}" transform="translate(${h+C}, ${d+E})" fill="${F}" fill-opacity="${N}"/>`)}const m=[`d="${r}"`,`transform="translate(${h}, ${d})"`];if(t.fill){const C=`fill-${Date.now()}`,E=tk(t.fill,C);E.defs&&y.unshift(E.defs),m.push(`fill="${E.fill}"`),t.fill.opacity!==void 0&&t.fill.opacity!==1&&m.push(`fill-opacity="${t.fill.opacity}"`)}else m.push('fill="none"');return t.stroke&&t.stroke.width&&Tt(t.stroke.width,0)>0&&(m.push(`stroke="${t.stroke.color??"#000000"}"`),m.push(`stroke-width="${t.stroke.width}"`),t.stroke.opacity!==void 0&&t.stroke.opacity!==1&&m.push(`stroke-opacity="${t.stroke.opacity}"`),t.stroke.dashArray&&t.stroke.dashArray.length>0&&m.push(`stroke-dasharray="${t.stroke.dashArray.join(" ")}"`),t.stroke.lineCap&&m.push(`stroke-linecap="${t.stroke.lineCap}"`),t.stroke.lineJoin&&m.push(`stroke-linejoin="${t.stroke.lineJoin}"`)),t.opacity!==void 0&&t.opacity!==1&&m.push(`opacity="${t.opacity}"`),y.push(`<path ${m.join(" ")}/>`),`<svg xmlns="http://www.w3.org/2000/svg" width="${i}" height="${a}" viewBox="0 0 ${i} ${a}">${y.join("")}</svg>`}function tk(t,e,s){if(t.type==="solid")return{fill:t.color};if(t.type==="linear"){const a=Tt(t.angle,0)*Math.PI/180,r=50-Math.cos(a)*50,n=50-Math.sin(a)*50,o=50+Math.cos(a)*50,l=50+Math.sin(a)*50,c=t.stops.map(h=>`<stop offset="${Tt(h.offset,0)*100}%" stop-color="${h.color}"/>`).join(""),f=`<defs><linearGradient id="${e}" x1="${r}%" y1="${n}%" x2="${o}%" y2="${l}%">${c}</linearGradient></defs>`;return{fill:`url(#${e})`,defs:f}}if(t.type==="radial"){const i=t.stops.map(r=>`<stop offset="${Tt(r.offset,0)*100}%" stop-color="${r.color}"/>`).join(""),a=`<defs><radialGradient id="${e}" cx="50%" cy="50%" r="50%">${i}</radialGradient></defs>`;return{fill:`url(#${e})`,defs:a}}return{fill:"#000000"}}function sk(t){const e=t.type;switch(e){case"rectangle":{const s=t;return ik(s.width,s.height,s.cornerRadius??0)}case"circle":return E0(t.radius);case"ellipse":{const s=t;return rk(s.radiusX,s.radiusY)}case"line":{const s=t;return nk(s.length,s.thickness??2)}case"polygon":{const s=t;return ok(s.sides,s.radius)}case"star":{const s=t;return lk(s.points,s.outerRadius,s.innerRadius)}case"arrow":{const s=t;return ck(s.length,s.headWidth??30,s.headLength??25,s.shaftWidth??10)}case"heart":return fk(t.size);case"cross":{const s=t;return uk(s.width,s.height,s.thickness)}case"ring":{const s=t;return hk(s.outerRadius,s.innerRadius)}case"path":return t.d;default:throw new Error(`Unknown shape type: ${e}`)}}var Pr=.5522847498307936;function ik(t,e,s){const i=-t/2,a=-e/2,r=Math.min(s,t/2,e/2);return r===0?`M ${i} ${a} L ${i+t} ${a} L ${i+t} ${a+e} L ${i} ${a+e} Z`:[`M ${i+r} ${a}`,`L ${i+t-r} ${a}`,`Q ${i+t} ${a} ${i+t} ${a+r}`,`L ${i+t} ${a+e-r}`,`Q ${i+t} ${a+e} ${i+t-r} ${a+e}`,`L ${i+r} ${a+e}`,`Q ${i} ${a+e} ${i} ${a+e-r}`,`L ${i} ${a+r}`,`Q ${i} ${a} ${i+r} ${a}`,"Z"].join(" ")}function E0(t){const e=t*Pr;return[`M ${t} 0`,`C ${t} ${e} ${e} ${t} 0 ${t}`,`C ${-e} ${t} ${-t} ${e} ${-t} 0`,`C ${-t} ${-e} ${-e} ${-t} 0 ${-t}`,`C ${e} ${-t} ${t} ${-e} ${t} 0`,"Z"].join(" ")}function ak(t){const e=t*Pr;return[`M ${t} 0`,`C ${t} ${-e} ${e} ${-t} 0 ${-t}`,`C ${-e} ${-t} ${-t} ${-e} ${-t} 0`,`C ${-t} ${e} ${-e} ${t} 0 ${t}`,`C ${e} ${t} ${t} ${e} ${t} 0`,"Z"].join(" ")}function rk(t,e){const s=t*Pr,i=e*Pr;return[`M ${t} 0`,`C ${t} ${i} ${s} ${e} 0 ${e}`,`C ${-s} ${e} ${-t} ${i} ${-t} 0`,`C ${-t} ${-i} ${-s} ${-e} 0 ${-e}`,`C ${s} ${-e} ${t} ${-i} ${t} 0`,"Z"].join(" ")}function nk(t,e){const s=t/2,i=e/2;return`M ${-s} ${-i} L ${s} ${-i} L ${s} ${i} L ${-s} ${i} Z`}function ok(t,e){const s=2*Math.PI/t,i=-Math.PI/2,a=[];for(let r=0;r<t;r++){const n=i+r*s,o=Math.cos(n)*e,l=Math.sin(n)*e;a.push(r===0?`M ${o} ${l}`:`L ${o} ${l}`)}return a.push("Z"),a.join(" ")}function lk(t,e,s){const i=Math.PI/t,a=-Math.PI/2,r=[];for(let n=0;n<t*2;n++){const o=a+n*i,l=n%2===0?e:s,c=Math.cos(o)*l,f=Math.sin(o)*l;r.push(n===0?`M ${c} ${f}`:`L ${c} ${f}`)}return r.push("Z"),r.join(" ")}function ck(t,e,s,i){const a=i/2,r=e/2,n=t-s,o=-t/2;return[`M ${o} ${-a}`,`L ${o+n} ${-a}`,`L ${o+n} ${-r}`,`L ${o+t} 0`,`L ${o+n} ${r}`,`L ${o+n} ${a}`,`L ${o} ${a}`,"Z"].join(" ")}function fk(t){const e=t/32;return["M 0 6","C -0.5 -3 -12 -3 -12 6","C -12 12 0 18 0 24","C 0 18 12 12 12 6","C 12 -3 0.5 -3 0 6","Z"].map(i=>i.replace(/-?\d+(\.\d+)?/g,a=>String(parseFloat(a)*e))).join(" ")}function uk(t,e,s){const i=t/2,a=e/2,r=s/2;return[`M ${-r} ${-a}`,`L ${r} ${-a}`,`L ${r} ${-r}`,`L ${i} ${-r}`,`L ${i} ${r}`,`L ${r} ${r}`,`L ${r} ${a}`,`L ${-r} ${a}`,`L ${-r} ${r}`,`L ${-i} ${r}`,`L ${-i} ${-r}`,`L ${-r} ${-r}`,"Z"].join(" ")}function hk(t,e){const s=E0(t),i=ak(e);return`${s} ${i}`}function dk(t){const e=/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/g,s=[];let i;for(;(i=e.exec(t))!==null;){const y=parseFloat(i[0]);!isNaN(y)&&isFinite(y)&&s.push(y)}if(s.length<2)return{x:0,y:0,w:0,h:0};let a=1/0,r=1/0,n=-1/0,o=-1/0,l=0,c=0;const f=t.match(/[MmLlHhVvCcSsQqTtAaZz]/g)||[];let h=0,d=0;for(;h<f.length;){switch(f[h]){case"M":case"L":case"T":d+1<s.length&&(l=s[d++],c=s[d++],a=Math.min(a,l),n=Math.max(n,l),r=Math.min(r,c),o=Math.max(o,c));break;case"m":case"l":case"t":d+1<s.length&&(l+=s[d++],c+=s[d++],a=Math.min(a,l),n=Math.max(n,l),r=Math.min(r,c),o=Math.max(o,c));break;case"H":d<s.length&&(l=s[d++],a=Math.min(a,l),n=Math.max(n,l));break;case"h":d<s.length&&(l+=s[d++],a=Math.min(a,l),n=Math.max(n,l));break;case"V":d<s.length&&(c=s[d++],r=Math.min(r,c),o=Math.max(o,c));break;case"v":d<s.length&&(c+=s[d++],r=Math.min(r,c),o=Math.max(o,c));break;case"C":if(d+5<s.length)for(let m=0;m<3;m++){const C=s[d++],E=s[d++];a=Math.min(a,C),n=Math.max(n,C),r=Math.min(r,E),o=Math.max(o,E),m===2&&(l=C,c=E)}break;case"c":if(d+5<s.length)for(let m=0;m<3;m++){const C=l+s[d++],E=c+s[d++];a=Math.min(a,C),n=Math.max(n,C),r=Math.min(r,E),o=Math.max(o,E),m===2&&(l=C,c=E)}break;case"S":case"Q":if(d+3<s.length)for(let m=0;m<2;m++){const C=s[d++],E=s[d++];a=Math.min(a,C),n=Math.max(n,C),r=Math.min(r,E),o=Math.max(o,E),m===1&&(l=C,c=E)}break;case"s":case"q":if(d+3<s.length)for(let m=0;m<2;m++){const C=l+s[d++],E=c+s[d++];a=Math.min(a,C),n=Math.max(n,C),r=Math.min(r,E),o=Math.max(o,E),m===1&&(l=C,c=E)}break;case"A":d+6<s.length&&(d+=5,l=s[d++],c=s[d++],a=Math.min(a,l),n=Math.max(n,l),r=Math.min(r,c),o=Math.max(o,c));break;case"a":d+6<s.length&&(d+=5,l+=s[d++],c+=s[d++],a=Math.min(a,l),n=Math.max(n,l),r=Math.min(r,c),o=Math.max(o,c));break}h++}return a===1/0?{x:0,y:0,w:0,h:0}:{x:a,y:r,w:n-a,h:o-r}}async function gk(t,e={}){const s=e.defaultWidth??1920,i=e.defaultHeight??1080;let a,r,n;if(t.src){a=t.src;const o=pk(a);r=o.width||s,n=o.height||i}else if(t.shape)r=Tt(t.width,s),n=Tt(t.height,i),a=ek(t,r,n);else throw new Error("Either 'src' or 'shape' must be provided");return $C(a,{width:r,height:n,background:e.background})}function pk(t){const e=t.match(/width\s*=\s*["']?(\d+(?:\.\d+)?)/i),s=t.match(/height\s*=\s*["']?(\d+(?:\.\d+)?)/i);let i=e?parseFloat(e[1]):0,a=s?parseFloat(s[1]):0;if(!i||!a){const r=t.match(/viewBox\s*=\s*["']([^"']+)["']/i);if(r){const n=r[1].trim().split(/[\s,]+/).map(parseFloat);n.length===4&&(i=i||n[2],a=a||n[3])}}return{width:i,height:a}}var P0="https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxP.ttf";async function mk(t={}){const e=t.width??ct.DEFAULTS.width,s=t.height??ct.DEFAULTS.height,i=t.pixelRatio??ct.DEFAULTS.pixelRatio,a="https://shotstack-ingest-api-dev-sources.s3.ap-southeast-2.amazonaws.com/euo5r93oyr/zzz01k9h-yycyx-2x2y6-qx9bj-7n567b/source.wasm";N0.setFallbackLoader(async m=>{const C=(m.family??"Roboto").toLowerCase(),E=`${m.weight??"400"}`;if(C==="roboto"&&E==="400")return Er(P0)});let r;try{r=await N0.getSharedInstance(a)}catch(m){throw new Error(`Failed to initialize font registry: ${m instanceof Error?m.message:String(m)}`)}const n=new VC(r),o=new Map,l=new Map,c=m=>`${m??"400"}`,f=(m,C)=>`${m}__${c(C)}`,h=async(m,C)=>{const E={family:C.family,weight:c(C.weight)},F=`${m}|${f(E.family,E.weight)}`,N=l.get(F);if(N)return N;const w=(async()=>{if(r.hasRegisteredFace(E))return;const T=await Er(m);await r.registerFromBytes(T,E)})();return l.set(F,w),w},d=async m=>{const C={family:m.family,weight:c(m.weight)},E=`${m.src}|${f(C.family,C.weight)}`,F=o.get(E);if(F)return F;const N=(async()=>{if(r.hasRegisteredFace(C))return;const w=await Er(m.src);await r.registerFromBytes(w,C)})();return o.set(E,N),N};async function y(m){try{if(m.customFonts)for(const N of m.customFonts)try{await d(N)}catch(w){throw new Error(`Failed to load custom font "${N.family}" from ${N.src}: ${w instanceof Error?w.message:String(w)}`)}const C=m.font??{family:"Roboto",weight:"400",size:48,color:"#000000",opacity:1},E={family:C.family,weight:`${C.weight}`};return await(async()=>{try{await r.getFace(E)}catch{if((C.family||"Roboto").toLowerCase()==="roboto"&&`${C.weight}`=="400"){if(!r.hasRegisteredFace({family:"Roboto",weight:"400"})){const w=await Er(P0);await r.registerFromBytes(w,{family:"Roboto",weight:"400"})}}else throw new Error(`Font not registered for ${E.family}__${E.weight}`)}})(),C}catch(C){throw C instanceof Error?C:new Error(`Failed to ensure fonts: ${String(C)}`)}}return{validate(m){const C=vC.safeParse(m);if(!C.success){const E=C.error.issues.map(F=>F.message).join(". ");throw new Error(`Validation failed: ${E}`)}return{value:C.data}},async registerFontFromUrl(m,C){try{await h(m,C)}catch(E){throw new Error(`Failed to register font "${C.family}" from URL ${m}: ${E instanceof Error?E.message:String(E)}`)}},async registerFontFromFile(m,C){try{let E;if(typeof m=="string"){await h(m,C);return}else try{E=await m.arrayBuffer()}catch(N){throw new Error(`Failed to read Blob as ArrayBuffer: ${N instanceof Error?N.message:String(N)}`)}const F={family:C.family,weight:c(C.weight)};if(r.hasRegisteredFace(F))return;await r.registerFromBytes(E,F)}catch(E){throw E instanceof Error?E:new Error(`Failed to register font "${C.family}" from ${typeof m=="string"?m:"Blob"}: ${String(E)}`)}},async renderFrame(m,C,E){try{const F=await y(m),N={family:F.family,weight:`${F.weight}`};let w;try{let re;const Se=r.getColorEmojiFontFamilies();if(Se.length>0)re={family:Se[0],weight:"400"};else{const Fe={family:"NotoEmoji",weight:"400"};try{await r.getFace(Fe),re=Fe}catch{}}const ke=m.padding?typeof m.padding=="number"?{top:m.padding,right:m.padding,bottom:m.padding,left:m.padding}:m.padding:{top:0,right:0,bottom:0,left:0};w=await n.layout({text:m.text,width:(m.width??e)-ke.left-ke.right,letterSpacing:m.style?.letterSpacing??0,fontSize:F.size,lineHeight:m.style?.lineHeight??1.2,desc:N,textTransform:m.style?.textTransform??"none",emojiFallback:re})}catch(re){throw new Error(`Failed to layout text: ${re instanceof Error?re.message:String(re)}`)}const T=m.padding?typeof m.padding=="number"?{top:m.padding,right:m.padding,bottom:m.padding,left:m.padding}:m.padding:{top:0,right:0,bottom:0,left:0},b=m.border?.width??0,U=(m.width??e)+b*2,D=(m.height??s)+b*2,B=i,J={x:0,y:0,width:(m.width??e)-T.left-T.right,height:(m.height??s)-T.top-T.bottom},ee=m.width??e,te=m.height??s;let he;try{he=await TC({canvas:{width:U,height:D,pixelRatio:B},textRect:J,lines:w,contentRect:{width:ee,height:te},font:{family:F.family,size:F.size,weight:`${F.weight}`,color:F.color,opacity:F.opacity,background:F.background},style:{lineHeight:m.style?.lineHeight??1.2,textDecoration:m.style?.textDecoration??"none",gradient:m.style?.gradient},stroke:m.stroke,shadow:m.shadow,align:{horizontal:m.align?.horizontal??"center",vertical:m.align?.vertical??"middle"},background:m.background,border:m.border,padding:m.padding,glyphPathProvider:(re,Se)=>r.glyphPath(Se||N,re),getUnitsPerEm:re=>r.getUnitsPerEm(re||N),isColorEmojiFont:re=>r.isColorEmojiFont(re)})}catch(re){throw new Error(`Failed to build draw operations: ${re instanceof Error?re.message:String(re)}`)}try{return OC(he,w,{t:C,fontSize:F.size,clipDuration:E,anim:m.animation?{preset:m.animation.preset,speed:m.animation.speed,duration:m.animation.duration,style:m.animation.style,direction:m.animation.direction}:void 0})}catch(re){throw new Error(`Failed to apply animation: ${re instanceof Error?re.message:String(re)}`)}}catch(F){throw F instanceof Error?F:new Error(`Failed to render frame at time ${C}s: ${String(F)}`)}},createRenderer(m){try{return jC(m)}catch(C){throw new Error(`Failed to create renderer: ${C instanceof Error?C.message:String(C)}`)}},destroy(){try{r.release()}catch(m){console.error(`Error during cleanup: ${m instanceof Error?m.message:String(m)}`)}}}}const O0=t=>{const s=(t.split("/").pop()||"").replace(/\.(ttf|otf|woff|woff2)$/i,""),i=s.replace(/-(Bold|Light|Regular|Italic|Medium|SemiBold|Black|Thin|ExtraLight|ExtraBold|Heavy)$/i,"");return{full:s,base:i}},yk=t=>t.includes("fonts.gstatic.com");class os extends xt{static PREVIEW_FPS=60;static fontCapabilityCache=new Map;textEngine=null;renderer=null;canvas=null;texture=null;sprite=null;lastRenderedTime=-1;cachedFrames=new Map;isRendering=!1;pendingRenderTime=null;validatedAsset=null;fontSupportsBold=!1;loadComplete=!1;fontRegistrationCache=new Map;static getFontSourceCacheKey(e){return e.split("#",1)[0].split("?",1)[0]}constructor(e,s){const{fit:i,...a}=s;super(e,a,Qe.RichText)}resolveFontWeight(e,s){const i=e.font?.weight;return typeof i=="string"?parseInt(i,10)||s:typeof i=="number"?i:s}buildCanvasPayload(e,s){const i=this.clipConfiguration.width||this.edit.size.width,a=this.clipConfiguration.height||this.edit.size.height,r=e.font?.family,{baseFontFamily:n,fontWeight:o}=s??(r?Dt(r):{baseFontFamily:r,fontWeight:400}),l=this.resolveFontWeight(e,o),c=this.edit.getTimelineFonts(),f=r?c.find(m=>{const{full:C,base:E}=O0(m.src),F=r.toLowerCase();return C.toLowerCase()===F||E.toLowerCase()===F}):void 0;let h;if(f&&r)h=[{src:f.src,family:n||r,weight:l.toString()}];else if(r){const m=this.edit.getFontMetadata(),C=(n||r).toLowerCase(),F=c.filter(N=>!yk(N.src)).find(N=>m.get(N.src)?.baseFamilyName.toLowerCase()===C);F&&(h=[{src:F.src,family:n||r,weight:l.toString()}])}const y=h||r&&Va(r)?n||r:void 0;return{...e,width:i,height:a,font:e.font?{...e.font,family:y||"Roboto",weight:l}:void 0,stroke:e.font?.stroke,...h&&{customFonts:h}}}async registerFont(e,s,i){if(!this.textEngine)return!1;const a=os.getFontSourceCacheKey(i.path),r=`${i.type}:${a}|${e}|${s}`,n=this.fontRegistrationCache.get(r);if(n)return n;const o=(async()=>{try{const l={family:e,weight:s.toString()};return i.type==="url"?await this.textEngine.registerFontFromUrl(i.path,l):await this.textEngine.registerFontFromFile(i.path,l),!0}catch{return!1}})();return this.fontRegistrationCache.set(r,o),o}createFontCapabilityCheckPromise(e){return(async()=>{try{const s=await fetch(e);if(!s.ok)throw new Error(`Failed to fetch font: ${s.status}`);const i=await s.arrayBuffer();return!!$r.parse(i).tables.fvar?.axes?.find(n=>n.tag==="wght")}catch(s){return console.warn("Failed to check font capabilities:",s),!1}})()}async prepareFontForAsset(e,s){const i=await this.ensureFontRegistered(e);if(!i)return;const a=os.getFontSourceCacheKey(i),r=os.fontCapabilityCache.get(a),n=r??this.createFontCapabilityCheckPromise(i);r||os.fontCapabilityCache.set(a,n),this.fontSupportsBold=await n,s&&this.edit.getInternalEvents().emit(ot.FontCapabilitiesChanged,{supportsBold:this.fontSupportsBold})}supportsBold(){return this.fontSupportsBold}resolveFont(e){const{baseFontFamily:s,fontWeight:i}=Dt(e),a=this.edit.getFontUrlByFamilyAndWeight(s,i);if(a)return{url:a,baseFontFamily:s,fontWeight:i};const o=(this.edit.getEdit()?.timeline?.fonts||[]).find(c=>{const{full:f,base:h}=O0(c.src),d=e.toLowerCase();return f.toLowerCase()===d||h.toLowerCase()===d});if(o)return{url:o.src,baseFontFamily:s,fontWeight:i};const l=Va(e);return l?{url:l,baseFontFamily:s,fontWeight:i}:null}reconfigureAfterRestore(){super.reconfigureAfterRestore(),this.reconfigure(this.clipConfiguration.asset)}async reconfigure(e){try{await this.prepareFontForAsset(e,!0);for(const s of this.cachedFrames.values())s.destroy();if(this.cachedFrames.clear(),this.lastRenderedTime=-1,this.textEngine){const s=this.buildCanvasPayload(e),{value:i}=this.textEngine.validate(s);this.validatedAsset=i}this.textEngine&&this.renderer&&this.renderFrameSafe(this.getPlaybackTime())}catch{}}async ensureFontRegistered(e){if(!this.textEngine)return null;const s=e.font?.family;if(!s)return null;const i=this.resolveFont(s);if(!i)return null;const a=this.resolveFontWeight(e,i.fontWeight);return await this.registerFont(i.baseFontFamily,a,{type:"url",path:i.url}),i.url}async load(){await super.load();const e=this.clipConfiguration.asset;try{if(!Ql.safeParse(e).success){this.createFallbackText(e);return}const i=e.font?.family,a=i?Dt(i):void 0,r=this.buildCanvasPayload(e,a);this.textEngine=await mk({width:r.width,height:r.height,fps:os.PREVIEW_FPS});const{value:n}=this.textEngine.validate(r);this.validatedAsset=n,this.canvas=document.createElement("canvas"),this.canvas.width=r.width,this.canvas.height=r.height,this.renderer=this.textEngine.createRenderer(this.canvas),await this.prepareFontForAsset(e,!1),await this.renderFrame(0),this.configureKeyframes(),this.loadComplete=!0}catch{this.cleanupResources(),this.createFallbackText(e)}}cleanupResources(){if(this.textEngine){try{this.textEngine.destroy()}catch(e){console.warn("Error destroying text engine:",e)}this.textEngine=null}this.renderer=null,this.canvas=null,this.validatedAsset=null}async renderFrame(e){if(!this.textEngine||!this.renderer||!this.canvas||!this.validatedAsset)return;const s=Math.floor(e*os.PREVIEW_FPS);if(this.cachedFrames.has(s)){const i=this.cachedFrames.get(s);this.sprite&&this.sprite.texture!==i&&(this.sprite.texture=i),this.lastRenderedTime=e;return}try{const i=this.getLength(),a=await this.textEngine.renderFrame(this.validatedAsset,e,i),r=this.canvas.getContext("2d");r&&r.clearRect(0,0,this.canvas.width,this.canvas.height),await this.renderer.render(a);const n=X.Texture.from(this.canvas);this.sprite?(this.texture&&!this.cachedFrames.has(s)&&this.texture.destroy(),this.sprite.texture=n):(this.sprite=new X.Sprite(n),this.contentContainer.addChild(this.sprite)),this.texture=n,this.cachedFrames.size<150&&this.cachedFrames.set(s,n),this.lastRenderedTime=e}catch(i){console.error("Failed to render rich text frame:",i)}}createFallbackText(e){const s=this.edit.getEdit(),i=this.clipConfiguration.width||s?.output?.size?.width||this.edit.size.width,a=this.clipConfiguration.height||s?.output?.size?.height||this.edit.size.height,r=new X.TextStyle({fontFamily:e.font?.family||"Arial",fontSize:e.font?.size||48,fill:e.font?.color||"#ffffff",align:e.align?.horizontal||"center",wordWrap:!0,wordWrapWidth:i}),n=new X.Text(e.text,r);switch(e.align?.horizontal){case"left":n.anchor.set(0,.5),n.x=0;break;case"right":n.anchor.set(1,.5),n.x=i;break;default:n.anchor.set(.5,.5),n.x=i/2}switch(e.align?.vertical){case"top":n.anchor.set(n.anchor.x,0),n.y=0;break;case"bottom":n.anchor.set(n.anchor.x,1),n.y=a;break;default:n.anchor.set(n.anchor.x,.5),n.y=a/2}this.contentContainer.addChild(n)}renderFrameSafe(e){if(this.isRendering){this.pendingRenderTime=e;const s=Math.floor(e*os.PREVIEW_FPS),i=this.cachedFrames.get(s);i&&this.sprite&&this.sprite.texture!==i&&(this.sprite.texture=i);return}this.isRendering=!0,this.pendingRenderTime=null,this.renderFrame(e).catch(s=>console.error("Failed to render rich text frame:",s)).finally(()=>{if(this.isRendering=!1,this.pendingRenderTime!==null&&this.pendingRenderTime!==e){const s=this.pendingRenderTime;this.pendingRenderTime=null,this.renderFrameSafe(s)}})}update(e,s){if(super.update(e,s),s===Si.SEEK_ELAPSED_MARKER&&(this.isRendering=!1,this.pendingRenderTime=null,this.lastRenderedTime=-1),!!this.isActive()&&this.loadComplete&&this.textEngine&&this.renderer&&!this.isRendering){const i=this.getPlaybackTime(),a=1/60;Math.abs(i-this.lastRenderedTime)>a&&this.renderFrameSafe(i)}}dispose(){super.dispose(),this.loadComplete=!1;for(const e of this.cachedFrames.values())e.destroy();this.cachedFrames.clear(),this.texture&&!this.cachedFrames.has(Math.floor(this.lastRenderedTime*os.PREVIEW_FPS))&&this.texture.destroy(),this.texture=null,this.sprite&&(this.sprite.destroy(),this.sprite=null),this.canvas&&(this.canvas=null),this.textEngine&&(this.textEngine.destroy(),this.textEngine=null),this.renderer=null,this.validatedAsset=null}getSize(){const e=this.edit.getEdit();return{width:this.clipConfiguration.width||e?.output?.size?.width||this.edit.size.width,height:this.clipConfiguration.height||e?.output?.size?.height||this.edit.size.height}}getContentSize(){return{width:this.clipConfiguration.width||this.canvas?.width||this.edit.size.width,height:this.clipConfiguration.height||this.canvas?.height||this.edit.size.height}}getFitScale(){return 1}getContainerScale(){const e=this.getScale();return{x:e,y:e}}supportsEdgeResize(){return!0}onDimensionsChanged(){if(!this.textEngine||!this.renderer||!this.canvas)return;const e=this.clipConfiguration.asset,{width:s,height:i}=this.getSize();this.canvas.width=s,this.canvas.height=i;for(const n of this.cachedFrames.values())n.destroy();this.cachedFrames.clear(),this.lastRenderedTime=-1;const a=this.buildCanvasPayload(e),{value:r}=this.textEngine.validate(a);this.validatedAsset=r,this.renderFrameSafe(this.getPlaybackTime())}updateTextContent(e){const s=this.clipConfiguration.asset;if(s.text=e,this.textEngine){const i=this.buildCanvasPayload(s),{value:a}=this.textEngine.validate(i);this.validatedAsset=a}for(const i of this.cachedFrames.values())i.destroy();this.cachedFrames.clear(),this.lastRenderedTime=-1,this.textEngine&&this.renderer&&this.renderFrameSafe(this.getPlaybackTime())}getCacheSize(){return this.cachedFrames.size}}class bk extends xt{shape;shapeBackground;constructor(e,s){super(e,s,Qe.Shape),this.shape=null,this.shapeBackground=null}async load(){await super.load();const e=this.clipConfiguration.asset,s=new X.Graphics,i=e.width??this.edit.size.width,a=e.height??this.edit.size.height;s.fillStyle={color:"transparent"},s.rect(0,0,i,a),s.fill();const r=new X.Graphics;switch(e.shape){case"rectangle":{const n=e.rectangle,o=i/2-n.width/2,l=a/2-n.height/2;r.rect(o,l,n.width,n.height);break}case"circle":{const n=e.circle,o=i/2,l=a/2;r.circle(o,l,n.radius);break}case"line":{const n=e.line,o=i/2-n.length/2,l=a/2-n.thickness/2;r.rect(o,l,n.length,n.thickness);break}default:console.warn("Unsupported shape asset type.");break}if(r.fillStyle={color:e.fill?.color??"#ffffff",alpha:e.fill?.opacity??1},r.fill(),e.stroke){const n=new Mi({thickness:e.stroke.width,color:e.stroke.color});r.filters=[n]}this.shapeBackground=s,this.shape=r,this.contentContainer.addChild(s),s.addChild(r),this.configureKeyframes()}update(e,s){super.update(e,s)}dispose(){super.dispose(),this.shape?.destroy(),this.shape=null,this.shapeBackground?.destroy(),this.shapeBackground=null}getSize(){const e=this.clipConfiguration.asset;return{width:e.width??this.edit.size.width,height:e.height??this.edit.size.height}}getFitScale(){return 1}}const wk="https://unpkg.com/@resvg/resvg-wasm@2.6.2/index_bg.wasm";class gs extends xt{static resvgInitialized=!1;static resvgInitPromise=null;texture=null;sprite=null;renderedWidth=0;renderedHeight=0;pendingRender=null;constructor(e,s){super(e,s,Qe.Svg)}static async initializeResvg(){if(!gs.resvgInitialized){if(gs.resvgInitPromise){await gs.resvgInitPromise;return}gs.resvgInitPromise=(async()=>{const s=await(await fetch(wk)).arrayBuffer();await QC(s),gs.resvgInitialized=!0})(),await gs.resvgInitPromise}}async load(){await super.load();let e=this.clipConfiguration.asset;if(e.src){const s=this.edit.resolveMergeFields(e.src);s!==e.src&&(e={...e,src:s})}try{if(!Bb.safeParse(e).success){this.createFallbackGraphic();return}await gs.initializeResvg(),await this.doRender(),this.configureKeyframes()}catch(s){console.error("Failed to render SVG asset:",s),this.createFallbackGraphic()}}async reloadAsset(){await this.rerenderAtCurrentDimensions()}createFallbackGraphic(){const e=this.clipConfiguration.width||this.edit.size.width,s=this.clipConfiguration.height||this.edit.size.height,i=jo(e,s);this.renderedWidth=e,this.renderedHeight=s,this.contentContainer.addChild(i),this.configureKeyframes()}update(e,s){super.update(e,s)}dispose(){super.dispose(),this.pendingRender=null,this.sprite&&(this.sprite.destroy(),this.sprite=null),this.texture&&(this.texture.destroy(!0),this.texture=null)}getSize(){return this.clipConfiguration.width&&this.clipConfiguration.height?{width:this.clipConfiguration.width,height:this.clipConfiguration.height}:{width:this.renderedWidth||this.edit.size.width,height:this.renderedHeight||this.edit.size.height}}getContentSize(){return{width:this.renderedWidth||this.edit.size.width,height:this.renderedHeight||this.edit.size.height}}getFitScale(){return 1}supportsEdgeResize(){return!0}onDimensionsChanged(){this.rerenderAtCurrentDimensions()}async rerenderAtCurrentDimensions(){this.pendingRender&&await this.pendingRender,this.sprite&&(this.contentContainer.removeChild(this.sprite),this.sprite.destroy(),this.sprite=null),this.texture&&(this.texture.destroy(!0),this.texture=null),this.pendingRender=this.doRender(),await this.pendingRender,this.pendingRender=null}async doRender(){const e=this.clipConfiguration.asset,s=this.clipConfiguration.width||this.edit.size.width,i=this.clipConfiguration.height||this.edit.size.height,a=await gk(e,{defaultWidth:s,defaultHeight:i});this.renderedWidth=a.width,this.renderedHeight=a.height;const r=new Blob([a.png],{type:"image/png"}),n=URL.createObjectURL(r),o=new Image;o.src=n,await new Promise((l,c)=>{o.onload=()=>l(),o.onerror=()=>c(new Error("Failed to load SVG image"))}),URL.revokeObjectURL(n),this.texture=X.Texture.from(o),this.sprite=new X.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.clipConfiguration.width&&this.clipConfiguration.height&&this.applyFixedDimensions()}}class ua{static DEFAULT_BLINK_INTERVAL_MS=500;static DEFAULT_CURSOR_WIDTH_PX=2;static DEFAULT_CURSOR_COLOR=16777215;cursor=null;parent;textElement;clipConfig;textPosition=0;pixelX=0;pixelY=0;currentLine=0;isBlinking=!1;blinkInterval=null;blinkIntervalMs=500;width=2;color=16777215;isVisible=!0;constructor(e,s,i,a){this.parent=e,this.textElement=s,this.clipConfig=i,this.width=a?.width??ua.DEFAULT_CURSOR_WIDTH_PX,this.color=a?.color??ua.DEFAULT_CURSOR_COLOR,this.blinkIntervalMs=a?.blinkInterval??ua.DEFAULT_BLINK_INTERVAL_MS,this.textPosition=0,this.isBlinking=!1,this.isVisible=!0,this.blinkInterval=null,this.createCursor()}updatePosition(e){if(!this.cursor||!this.textElement){console.warn("TextCursor: Cannot update position, cursor not initialized");return}this.textPosition=this.validateTextPosition(e),this.calculateAndApplyPixelPosition()}setPosition(e,s){if(!this.cursor){console.warn("TextCursor: Cannot set position, cursor not initialized");return}this.pixelX=e,this.pixelY=s,this.updateGraphicsPosition()}show(){this.setVisible(!0)}hide(){this.setVisible(!1)}setVisible(e){this.isVisible=e,this.cursor&&!this.isBlinking&&(this.cursor.visible=e)}startBlinking(){if(!this.cursor){console.warn("TextCursor: Cannot start blinking, cursor not initialized");return}this.isBlinking||this.startBlinkingAnimation()}stopBlinking(){this.stopBlinkingAnimation()}setBlinkInterval(e){this.blinkIntervalMs=e,this.isBlinking&&(this.stopBlinking(),this.startBlinking())}dispose(){if(this.stopBlinkingAnimation(),this.cursor&&this.parent)try{this.parent.removeChild(this.cursor)}catch(e){console.warn("TextCursor: Error removing cursor from parent:",e)}if(this.cursor)try{this.cursor.destroy()}catch(e){console.warn("TextCursor: Error destroying cursor graphics:",e)}finally{this.cursor=null}this.textPosition=0,this.pixelX=0,this.pixelY=0,this.currentLine=0,this.isVisible=!0}createCursor(){if(!this.textElement)return;this.cursor=new X.Graphics,this.cursor.fillStyle={color:this.color};const e=this.textElement.style.fontSize;this.cursor.rect(0,0,this.width,e),this.cursor.fill(),this.parent.addChild(this.cursor),this.cursor.visible=this.isVisible}validateTextPosition(e){return this.textElement?Math.max(0,Math.min(e,this.textElement.text.length)):0}calculateAndApplyPixelPosition(){this.calculatePixelPositionFromText(),this.updateGraphicsPosition()}calculatePixelPositionFromText(){if(!this.textElement)return;const{text:e}=this.textElement,s=this.textElement.style,i=e.substring(0,this.textPosition),a=i.match(/\n/g);this.currentLine=a?a.length:0;const r=e.split(`
276
276
  `),n=this.currentLine<r.length?r[this.currentLine]:"",o=i.lastIndexOf(`
277
- `),l=o===-1?this.textPosition:this.textPosition-o-1,c=n.substring(0,l);let f;c.length>0&&c.endsWith(" ")?f=this.measureText(`${c}x`,s)-this.measureText("x",s):f=this.measureText(c,s);const h=s.lineHeight;this.pixelY=this.currentLine*h;const y=this.clipConfig.asset.alignment?.horizontal??"center";let m=f;if(y!=="left"){const C=this.measureText(n,s),E=this.textElement.width;let F=0;y==="center"?F=(E-C)/2:y==="right"&&(F=E-C),m=F+f}this.pixelX=m}updateGraphicsPosition(){this.cursor&&this.cursor.position.set(this.pixelX,this.pixelY)}startBlinkingAnimation(){!this.cursor||this.isBlinking||(this.isBlinking=!0,this.blinkInterval=window.setInterval(()=>{this.cursor&&this.isBlinking&&(this.cursor.visible=!this.cursor.visible)},this.blinkIntervalMs))}stopBlinkingAnimation(){this.blinkInterval!==null&&(window.clearInterval(this.blinkInterval),this.blinkInterval=null),this.isBlinking=!1,this.cursor&&(this.cursor.visible=this.isVisible)}measureText(e,s){const i=new X.Text(e,s),{width:a}=i;return i.destroy(),a}isInitialized(){return this.cursor!==null}getState(){return{isInitialized:this.isInitialized(),isBlinking:this.isBlinking,isVisible:this.isVisible,textPosition:this.textPosition,pixelPosition:{x:this.pixelX,y:this.pixelY},currentLine:this.currentLine}}}class Or{static DEFAULT_FOCUS_DELAY_MS=50;hiddenInput=null;isFocused=!1;focusRetryCount=0;maxFocusRetries=3;focusDelay=Or.DEFAULT_FOCUS_DELAY_MS;eventHandlers={};abortController=null;textChangeCallback=null;lastSyncedText="";isComposing=!1;setupInput(e,s){this.focusDelay=s?.focusDelay??Or.DEFAULT_FOCUS_DELAY_MS,this.createHiddenTextarea(),this.hiddenInput&&(this.hiddenInput.value=e,this.lastSyncedText=e),this.setupEventListeners(),s?.autoFocus!==!1&&this.focusInput()}updateInputValue(e){this.hiddenInput&&(this.hiddenInput.value=e,this.lastSyncedText=e)}focusInput(){this.hiddenInput&&setTimeout(()=>{this.hiddenInput&&!this.isFocused&&(this.hiddenInput.focus(),setTimeout(()=>{!this.isFocused&&this.focusRetryCount<this.maxFocusRetries&&(this.focusRetryCount+=1,this.focusInput())},10))},this.focusDelay)}blurInput(){this.hiddenInput&&this.hiddenInput.blur()}setSelectionRange(e,s){if(!this.hiddenInput)return;const i=this.hiddenInput.value.length,a=Math.max(0,Math.min(e,i)),r=Math.max(a,Math.min(s,i));this.hiddenInput.setSelectionRange(a,r)}getCursorPosition(){return this.hiddenInput?.selectionStart||0}getValue(){return this.hiddenInput?.value||""}setTextInputHandler(e){this.textChangeCallback=e}setEventHandlers(e){this.eventHandlers={...this.eventHandlers,...e}}isFocusedInput(){return this.isFocused}dispose(){this.removeAllEventListeners(),this.hiddenInput&&this.hiddenInput.parentNode&&this.hiddenInput.parentNode.removeChild(this.hiddenInput),this.hiddenInput=null,this.isFocused=!1,this.focusRetryCount=0,this.textChangeCallback=null,this.eventHandlers={}}createHiddenTextarea(){this.hiddenInput=document.createElement("textarea");const e={position:"absolute",opacity:"0.01",pointerEvents:"none",zIndex:"18",left:"0px",top:"0px",width:"1px",height:"1px",border:"none",outline:"none",resize:"none",backgroundColor:"transparent"};Object.assign(this.hiddenInput.style,e),this.hiddenInput.tabIndex=0,document.body.appendChild(this.hiddenInput)}setupEventListeners(){if(!this.hiddenInput)return;this.abortController=new AbortController;const{signal:e}=this.abortController;this.hiddenInput.addEventListener("input",this.handleTextInput,{signal:e}),this.hiddenInput.addEventListener("keydown",this.handleKeyDown,{signal:e}),this.hiddenInput.addEventListener("compositionstart",this.handleCompositionStart,{signal:e}),this.hiddenInput.addEventListener("compositionend",this.handleCompositionEnd,{signal:e}),this.hiddenInput.addEventListener("focus",this.handleFocus,{signal:e}),this.hiddenInput.addEventListener("blur",this.handleBlur,{signal:e}),this.hiddenInput.addEventListener("paste",this.handlePaste,{signal:e})}removeAllEventListeners(){this.abortController?.abort(),this.abortController=null}handleTextInput=e=>{if(!this.hiddenInput||this.isComposing)return;const s=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.lastSyncedText=s,this.textChangeCallback?.(s,i)};handleKeyDown=e=>{if(document.activeElement!==this.hiddenInput)return;let s=!1;if((e.ctrlKey||e.metaKey)&&(s=this.handleKeyboardShortcuts(e),s)){e.preventDefault();return}if(e.key==="Tab"){const i=e.shiftKey?"backward":"forward";this.eventHandlers.onTabNavigation?.(i),e.preventDefault();return}switch(e.key){case"Escape":this.eventHandlers.onEscape?.(e),s=!0;break;case"Enter":s=!1;break;case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":setTimeout(()=>{if(this.hiddenInput){const i=this.hiddenInput.value,a=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(i,a)}},0),s=!1;break;case"Backspace":case"Delete":s=!1;break;default:s=this.eventHandlers.onCustomKey?.(e.key,e)||!1;break}s&&e.preventDefault()};handleKeyboardShortcuts(e){const{key:s}=e;switch(s.toLowerCase()){case"a":return this.selectAll(),!0;case"c":case"v":return!1;case"z":return this.eventHandlers.onCustomKey?.("undo",e),!0;case"y":return this.eventHandlers.onCustomKey?.("redo",e),!0;default:return!1}}handleCompositionStart=e=>{this.isComposing=!0};handleCompositionEnd=e=>{if(this.isComposing=!1,this.hiddenInput){const s=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(s,i)}};handleFocus=e=>{this.isFocused=!0,this.focusRetryCount=0,this.eventHandlers.onFocus?.(e)};handleBlur=e=>{this.isFocused=!1,this.eventHandlers.onBlur?.(e)};handlePaste=e=>{setTimeout(()=>{this.handleTextInput(e)},0)};selectAll(){this.hiddenInput&&this.hiddenInput.select()}}class ls{static DOUBLE_CLICK_THRESHOLD_MS=300;static EDITING_BG_PADDING_PX=5;static EDITING_BG_ALPHA=.2;static CLICK_HANDLER_DELAY_MS=100;parent;targetText;clipConfig;isEditing=!1;lastClickTime=0;editingContainer=null;editableText=null;textCursor=null;textInputHandler=null;outsideClickHandler=null;constructor(e,s,i){this.parent=e,this.targetText=s,this.clipConfig=i,this.parent.getContainer().eventMode="static",this.parent.getContainer().on("click",this.checkForDoubleClick)}dispose(){this.parent.getContainer().off("click",this.checkForDoubleClick),this.stopEditing(),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null)}startEditing(){if(this.isEditing||!this.targetText)return;const e=structuredClone(this.clipConfig);this.targetText.visible=!1,this.createEditingEnvironment(),this.setupOutsideClickHandler(e),this.isEditing=!0}stopEditing(e=!1,s){if(!this.isEditing)return;let i="";this.editableText&&(i=this.editableText.text),this.editingContainer&&(this.parent.getContainer().removeChild(this.editingContainer),this.editingContainer.destroy(),this.editingContainer=null),this.editableText=null,this.textCursor&&(this.textCursor.dispose(),this.textCursor=null),this.textInputHandler&&(this.textInputHandler.dispose(),this.textInputHandler=null),this.targetText.visible=!0,e&&s&&i!==""&&this.parent.updateTextContent(i,s),this.isEditing=!1}checkForDoubleClick=e=>{const s=Date.now();s-this.lastClickTime<ls.DOUBLE_CLICK_THRESHOLD_MS&&this.startEditing(),this.lastClickTime=s};setupOutsideClickHandler(e){this.outsideClickHandler=s=>{const a=this.parent.getContainer().getBounds(),r=s.clientX,n=s.clientY;(r<a.x||r>a.x+a.width||n<a.y||n>a.y+a.height)&&(this.stopEditing(!0,e),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null))},setTimeout(()=>{this.outsideClickHandler&&window.addEventListener("click",this.outsideClickHandler)},ls.CLICK_HANDLER_DELAY_MS)}createEditingEnvironment(){this.setupEditingContainer(),this.editingContainer&&this.editableText&&(this.textCursor=new ua(this.editingContainer,this.editableText,this.clipConfig),this.textCursor.updatePosition(this.targetText.text.length),this.textCursor.startBlinking()),this.setupTextInputHandler(),this.updateTextAlignment()}setupEditingContainer(){this.editingContainer=new X.Container,this.parent.getContainer().addChild(this.editingContainer);const e=new X.Graphics;e.fillStyle={color:0,alpha:ls.EDITING_BG_ALPHA},e.rect(-5,-5,this.targetText.width+2*ls.EDITING_BG_PADDING_PX,this.targetText.height+2*ls.EDITING_BG_PADDING_PX),e.fill(),this.editingContainer.addChild(e),this.editableText=new X.Text(this.targetText.text,this.targetText.style),this.editableText.eventMode="static",this.editableText.cursor="text",this.editingContainer.addChild(this.editableText)}setupTextInputHandler(){this.textInputHandler=new Or,this.textInputHandler.setTextInputHandler((e,s)=>{this.editableText&&(this.editableText.text=e,this.updateTextAlignment()),this.textCursor?.updatePosition(s)}),this.textInputHandler.setEventHandlers({onEscape:e=>this.stopEditing(!1),onTabNavigation:e=>this.stopEditing(!0)}),this.textInputHandler.setupInput(this.targetText.text,{autoFocus:!0})}updateTextAlignment(){if(!this.editableText||!this.editingContainer)return;const e=this.getContainerDimensions(),s=this.getAlignmentSettings(),i=this.calculateHorizontalPosition({width:this.editableText.width},e,s.horizontal),a=this.calculateVerticalPosition({height:this.editableText.height},e,s.vertical);if(this.editingContainer.position.set(i,a),this.editingContainer.children.length>0){const r=this.editingContainer.getChildAt(0);r instanceof X.Graphics&&(r.clear(),r.fillStyle={color:0,alpha:ls.EDITING_BG_ALPHA},r.rect(-5,-5,this.editableText.width+2*ls.EDITING_BG_PADDING_PX,this.editableText.height+2*ls.EDITING_BG_PADDING_PX),r.fill())}}calculateHorizontalPosition(e,s,i="center"){switch(i){case"center":return s.width/2-e.width/2;case"right":return s.width-e.width;case"left":default:return 0}}calculateVerticalPosition(e,s,i="center"){switch(i){case"center":return s.height/2-e.height/2;case"bottom":return s.height-e.height;case"top":default:return 0}}getContainerDimensions(){const e=this.clipConfig.asset;return{width:e.width??this.parent.getSize().width,height:e.height??this.parent.getSize().height}}getAlignmentSettings(){const e=this.clipConfig.asset;return{horizontal:e.alignment?.horizontal??"center",vertical:e.alignment?.vertical??"center"}}}class Ni extends xt{static loadedFonts=new Set;background=null;text=null;textEditor=null;constructor(e,s){super(e,s,Qe.Text)}async load(){await super.load();const e=this.clipConfiguration.asset,s=e.font?.family??"Open Sans";if(await this.loadFont(s),this.background=new X.Graphics,this.drawBackground(),this.text=new X.Text({text:e.text??"",style:this.createTextStyle(e)}),this.positionText(e),e.stroke?.width&&e.stroke.width>0&&e.stroke.color){const i=new Mi({thickness:e.stroke.width,color:e.stroke.color});this.text.filters=[i]}this.contentContainer.addChild(this.background),this.contentContainer.addChild(this.text),this.configureKeyframes(),this.textEditor=new ls(this,this.text,this.clipConfiguration)}update(e,s){super.update(e,s)}reconfigureAfterRestore(){super.reconfigureAfterRestore(),this.reconfigure()}async reconfigure(){const e=this.clipConfiguration.asset,s=e.font?.family??"Open Sans";if(await this.loadFont(s),this.drawBackground(),this.text){if(this.text.text=e.text??"",this.text.style=this.createTextStyle(e),e.stroke?.width&&e.stroke.width>0&&e.stroke.color){const i=new Mi({thickness:e.stroke.width,color:e.stroke.color});this.text.filters=[i]}else this.text.filters=[];this.positionText(e)}}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null,this.textEditor?.dispose(),this.textEditor=null}getSize(){const e=this.clipConfiguration.asset;return{width:this.clipConfiguration.width??e.width??this.edit.size.width,height:this.clipConfiguration.height??e.height??this.edit.size.height}}getFitScale(){return 1}getContainerScale(){const e=this.getScale();return{x:e,y:e}}supportsEdgeResize(){return!0}onDimensionsChanged(){if(this.drawBackground(),this.text){const e=this.clipConfiguration.asset;this.text.style.wordWrapWidth=this.getSize().width,this.positionText(e)}}applyFixedDimensions(){}createTextStyle(e){const s=e.font?.family??"Open Sans",{baseFontFamily:i,fontWeight:a}=Dt(s),{width:r}=this.getSize();return new X.TextStyle({fontFamily:i,fontSize:e.font?.size??32,fill:e.font?.color??"#ffffff",fontWeight:a.toString(),wordWrap:!0,wordWrapWidth:r,lineHeight:(e.font?.lineHeight??1)*(e.font?.size??32),align:e.alignment?.horizontal??"center"})}positionText(e){if(!this.text)return;const s=e.alignment?.horizontal??"center",i=e.alignment?.vertical??"center",{width:a,height:r}=this.getSize();let n=a/2-this.text.width/2,o=r/2-this.text.height/2;s==="left"?n=0:s==="right"&&(n=a-this.text.width),i==="top"?o=0:i==="bottom"&&(o=r-this.text.height),this.text.position.set(n,o)}drawBackground(){const e=this.clipConfiguration.asset;if(!this.background||!e.background||!e.background.color)return;const{width:s,height:i}=this.getSize();this.background.clear(),this.background.fillStyle={color:e.background.color,alpha:e.background.opacity??1},this.background.rect(0,0,s,i),this.background.fill()}updateTextContent(e,s){this.edit.updateTextContent(this,e,s)}async loadFont(e){const{baseFontFamily:s,fontWeight:i}=Dt(e),a=`${s}-${i}`;if(Ni.loadedFonts.has(a))return;const r=Va(e);if(r){const n=new FontFace(s,`url(${r})`,{weight:i.toString()});await n.load(),document.fonts.add(n),Ni.loadedFonts.add(a)}}static resetFontCache(){Ni.loadedFonts.clear()}}class vk extends xt{aiOverlay=null;lastPrompt="";constructor(e,s){super(e,s,Qe.TextToImage)}async load(){await super.load();const{width:e,height:s}=this.getSize(),i=this.edit.getResolvedEdit()?.timeline.tracks.flatMap(l=>l.clips)??[],a=Yo(i,this.clipId??""),{asset:r}=this.clipConfiguration,n=Bs(r)&&r.prompt||"",o=Bs(r)?r.type:"text-to-image";this.aiOverlay=new sn({mode:"panel",icon:"image",width:e,height:s,assetNumber:a??void 0,prompt:n,assetType:o}),this.contentContainer.addChild(this.aiOverlay.getContainer()),this.configureKeyframes()}update(e,s){super.update(e,s);const{width:i,height:a}=this.getSize();this.aiOverlay?.resize(i,a);const{asset:r}=this.clipConfiguration,n=Bs(r)&&r.prompt||"";n!==this.lastPrompt&&(this.aiOverlay?.updatePrompt(n),this.lastPrompt=n)}getSize(){const e=this.clipConfiguration.asset;return{width:this.clipConfiguration.width??e.width??this.edit.size.width,height:this.clipConfiguration.height??e.height??this.edit.size.height}}dispose(){this.aiOverlay?.dispose(),this.aiOverlay=null,super.dispose()}}class xk extends xt{constructor(e,s){super(e,s,Qe.TextToSpeech)}async load(){await super.load(),this.configureKeyframes()}update(e,s){super.update(e,s),this.getContainer().alpha=0}getSize(){return{width:0,height:0}}}class Ck extends xt{texture;sprite;isPlaying;volumeKeyframeBuilder;syncTimer;activeSyncTimer;skipVideoUpdate;constructor(e,s){super(e,s,Qe.Video),this.texture=null,this.sprite=null,this.isPlaying=!1;const i=this.clipConfiguration.asset;this.volumeKeyframeBuilder=new Pi(i.volume??1,this.getLength()),this.syncTimer=0,this.activeSyncTimer=0,this.skipVideoUpdate=!1}async load(){await super.load(),await this.loadVideo(),this.configureKeyframes()}update(e,s){if(super.update(e,s),this.skipVideoUpdate)return;const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=s,!this.texture)return;const a=this.getPlaybackTime(),r=this.edit.isPlaying&&this.isActive();r&&(this.isPlaying||(this.isPlaying=!0,this.activeSyncTimer=0,this.texture.source.resource.currentTime=a+i,this.texture.source.resource.play().catch(console.error)),this.texture.source.resource.volume!==this.getVolume()&&(this.texture.source.resource.volume=this.getVolume()),this.activeSyncTimer+=s,this.activeSyncTimer>1e3&&(this.activeSyncTimer=0,Math.abs(this.texture.source.resource.currentTime-i-a)>.3&&(this.texture.source.resource.currentTime=a+i,this.edit.recordSyncCorrection()))),!r&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause());const n=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&n&&(this.syncTimer=0,this.texture.source.resource.currentTime=a+i)}dispose(){super.dispose(),this.disposeVideo()}getSize(){return this.clipConfiguration.width&&this.clipConfiguration.height?{width:this.clipConfiguration.width,height:this.clipConfiguration.height}:{width:this.sprite?.width??0,height:this.sprite?.height??0}}supportsEdgeResize(){return!0}async reloadAsset(){this.skipVideoUpdate=!0,this.disposeVideo(),await this.loadVideo(),this.isPlaying=!1,this.syncTimer=0,this.activeSyncTimer=0,this.skipVideoUpdate=!1}async loadVideo(){const e=this.clipConfiguration.asset,{src:s}=e;if(s.endsWith(".mov"))throw new Error(`Video source '${s}' is not supported. .mov files cannot be played in the browser. Please convert to .webm or .mp4 first.`);const i=`${s}${s.includes("?")?"&":"?"}x-cors=1`,a={src:i,data:{autoPlay:!1,muted:!1}},r=await this.edit.assetLoader.loadVideoUnique(i,a);if(!r||!(r.source instanceof X.VideoSource))throw new Error(`Invalid video source '${s}'.`);r.source.alphaMode="no-premultiply-alpha",this.texture=this.createCroppedTexture(r);const n=this.texture.source.resource;n instanceof HTMLVideoElement&&n.readyState<2&&await new Promise(o=>{const l=()=>{n.removeEventListener("loadeddata",l),o()};n.addEventListener("loadeddata",l),n.readyState>=2&&o()}),this.sprite=new X.Sprite(this.texture),this.contentContainer.addChild(this.sprite)}disposeVideo(){this.texture?.source?.resource&&(this.texture.source.resource.pause(),this.texture.source.resource.src="",this.texture.source.resource.load()),this.sprite&&(this.contentContainer.removeChild(this.sprite),this.sprite.destroy(),this.sprite=null),this.texture&&(this.texture.destroy(!0),this.texture=null)}getVolume(){return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}getCurrentDrift(){if(!this.texture?.source?.resource)return 0;const{trim:e=0}=this.clipConfiguration.asset,s=this.texture.source.resource.currentTime,i=this.getPlaybackTime();return Math.abs(s-e-i)}createCroppedTexture(e){const s=this.clipConfiguration.asset;if(!s.crop)return e;const i=e.width,a=e.height;if(i<=0||a<=0)return e;const r=Math.floor((s.crop?.left??0)*i),n=Math.floor((s.crop?.right??0)*i),o=Math.floor((s.crop?.top??0)*a),l=Math.floor((s.crop?.bottom??0)*a),c=r,f=o,h=i-r-n,d=a-o-l,y=new X.Rectangle(c,f,h,d);return new X.Texture({source:e.source,frame:y})}}class M0{static create(e,s){if(!s.asset?.type)throw new Error("Invalid clip configuration: missing asset type");switch(s.asset.type){case"text":return new Ni(e,s);case"rich-text":return new os(e,s);case"shape":return new bk(e,s);case"html":return new Zu(e,s);case"image":return new Uu(e,s);case"video":return new Ck(e,s);case"audio":return new bu(e,s);case"luma":return new Qu(e,s);case"caption":return new _a(e,s);case"svg":return new gs(e,s);case"text-to-image":return new vk(e,s);case"image-to-video":return new Ju(e,s);case"text-to-speech":return new xk(e,s);default:throw new Error(`Unsupported asset type: ${s.asset.type}`)}}static cleanup(){Ni.resetFontCache()}}function ko(t,e,s,i){const a=new Map,r=`alias://${s}`;for(let n=0;n<t.getTrackCount();n+=1){const o=t.getClipsInTrack(n);for(let l=0;l<o.length;l+=1)if(!i?.has(`${n}:${l}`)){const c=o[l],f=c.id,h=e.timeline.tracks[n]?.clips[l];let d=!1;const y={};if(c.start===r&&(y.start=c.start,d=!0),c.length===r&&(y.length=c.length,d=!0),d&&f&&h){a.set(f,y);const m={};y.start&&(m.start=h.start),y.length&&(m.length=h.length),t.updateClip(n,l,m)}}}return a}function kk(t,e,s,i){const a=new Map;for(const r of s){const n=ko(t,e,r,i);for(const[o,l]of n){const c=a.get(o);c?a.set(o,{...c,...l}):a.set(o,l)}}return a}function No(t,e){for(const[s,i]of e){const a=t.getClipById(s);if(a){const r={};i.start&&(r.start=i.start),i.length&&(r.length=i.length),t.updateClip(a.trackIndex,a.clipIndex,r)}}}function Nk(t){const e=[];for(const s of t){const{alias:i}=s;i&&e.push(i)}return e}const Ee=()=>({status:"success"}),et=t=>({status:"noop",message:t});class Ak{constructor(e,s){this.trackIdx=e,this.clip=s}name="addClip";addedClipId;convertedReferences;execute(e){if(!e)throw new Error("AddClipCommand.execute: context is required");const s=e.getDocument();if(!s)throw new Error("AddClipCommand.execute: no document");const i=e.documentAddClip(this.trackIdx,this.clip);this.addedClipId=i.id,this.convertedReferences&&this.convertedReferences.size>0&&No(s,this.convertedReferences),e.resolve(),e.updateDuration();const n=e.getDocumentTrack(this.trackIdx)?.clips?.findIndex(o=>o.id===this.addedClipId)??-1;return e.emitEvent(fe.ClipAdded,{trackIndex:this.trackIdx,clipIndex:n}),Ee()}undo(e){if(!e)throw new Error("AddClipCommand.undo: context is required");if(!this.addedClipId)return et("No clip ID stored");const s=e.getDocument();if(!s)throw new Error("AddClipCommand.undo: no document");const a=e.getDocumentTrack(this.trackIdx)?.clips,r=a?.findIndex(o=>o.id===this.addedClipId)??-1;if(r===-1)return et(`Clip ${this.addedClipId} not found in track ${this.trackIdx}`);const n=a?.[r]?.alias;if(n){const o=new Set([`${this.trackIdx}:${r}`]);this.convertedReferences=ko(s,e.getEditState(),n,o)}return e.documentRemoveClip(this.trackIdx,r),e.resolve(),e.updateDuration(),e.emitEvent(fe.ClipDeleted,{trackIndex:this.trackIdx,clipIndex:r}),Ee()}dispose(){this.addedClipId=void 0,this.convertedReferences=void 0}}class Sk{constructor(e){this.trackIdx=e}name="addTrack";execute(e){if(!e)throw new Error("AddTrackCommand.execute: context is required");const s=e.getDocument();if(!s)throw new Error("AddTrackCommand.execute: document is required");return s.addTrack(this.trackIdx),e.resolve(),e.updateDuration(),e.emitEvent(fe.TrackAdded,{trackIndex:this.trackIdx,totalTracks:s.getTrackCount()}),Ee()}undo(e){if(!e)throw new Error("AddTrackCommand.undo: context is required");const s=e.getDocument();if(!s)throw new Error("AddTrackCommand.undo: document is required");return s.removeTrack(this.trackIdx),e.resolve(),e.updateDuration(),Ee()}dispose(){}}class R0{constructor(e){this.trackIdx=e}name="deleteTrack";deletedClips=[];convertedReferences;execute(e){if(!e)throw new Error("DeleteTrackCommand.execute: context is required");const s=e.getDocument();if(!s)throw new Error("DeleteTrackCommand: no document");if(s.getTrackCount()<=1)return et("Cannot delete the last track");const i=s.getTrack(this.trackIdx);i&&(this.deletedClips=i.clips.map(r=>structuredClone(r)));const a=Nk(this.deletedClips);if(a.length>0){const r=new Set;for(let n=0;n<this.deletedClips.length;n+=1)r.add(`${this.trackIdx}:${n}`);this.convertedReferences=kk(s,e.getEditState(),a,r)}return s.removeTrack(this.trackIdx),e.resolve(),e.updateDuration(),e.emitEvent(fe.TrackRemoved,{trackIndex:this.trackIdx}),Ee()}undo(e){if(!e)throw new Error("DeleteTrackCommand.undo: context is required");const s=e.getDocument();if(!s)throw new Error("DeleteTrackCommand.undo: no document");s.addTrack(this.trackIdx);for(let i=0;i<this.deletedClips.length;i+=1)s.addClip(this.trackIdx,this.deletedClips[i],i);return this.convertedReferences&&this.convertedReferences.size>0&&No(s,this.convertedReferences),e.resolve(),e.updateDuration(),e.emitEvent(fe.TrackAdded,{trackIndex:this.trackIdx,totalTracks:s.getTrackCount()}),Ee()}dispose(){this.deletedClips=[],this.convertedReferences=void 0}}class Ao{constructor(e,s){this.trackIdx=e,this.clipIdx=s}name="deleteClip";deletedClipConfig;deletedClipId;deleteTrackCommand;trackWasDeleted=!1;storedBindings;convertedReferences;execute(e){if(!e)throw new Error("DeleteClipCommand.execute: context is required");const s=e.getDocument();if(!s)throw new Error("DeleteClipCommand: no document");const i=s.getClip(this.trackIdx,this.clipIdx);if(!i)return et(`No clip at track ${this.trackIdx}, index ${this.clipIdx}`);if(this.deletedClipConfig=structuredClone(i),this.deletedClipId=i.id,this.deletedClipId){const o=e.getClipBindings(this.deletedClipId);this.storedBindings=o?new Map(o):void 0,s.clearClipBindings(this.deletedClipId)}const a=i.alias;if(a){const o=new Set([`${this.trackIdx}:${this.clipIdx}`]);this.convertedReferences=ko(s,e.getEditState(),a,o)}e.clearClipError(this.trackIdx,this.clipIdx);const r=e.getSelectedClip();r&&this.deletedClipId&&r.clipId===this.deletedClipId&&(e.setSelectedClip(null),e.emitEvent(fe.SelectionCleared)),e.documentRemoveClip(this.trackIdx,this.clipIdx);const n=s.getTrack(this.trackIdx);return n&&n.clips.length===0&&(this.deleteTrackCommand=new R0(this.trackIdx),this.deleteTrackCommand.execute(e).status==="success"&&(this.trackWasDeleted=!0)),e.resolve(),e.updateDuration(),e.emitEvent(fe.ClipDeleted,{trackIndex:this.trackIdx,clipIndex:this.clipIdx}),Ee()}undo(e){if(!e)throw new Error("DeleteClipCommand.undo: context is required");if(!this.deletedClipConfig)return et("No deleted clip config");const s=e.getDocument();if(!s)throw new Error("DeleteClipCommand.undo: no document");this.trackWasDeleted&&s.addTrack(this.trackIdx);const a=e.documentAddClip(this.trackIdx,this.deletedClipConfig,this.clipIdx).id;return a&&this.storedBindings&&this.storedBindings.size>0&&s.setClipBindingsForClip(a,this.storedBindings),this.convertedReferences&&this.convertedReferences.size>0&&No(s,this.convertedReferences),e.resolve(),e.updateDuration(),this.trackWasDeleted&&(e.emitEvent(fe.TrackAdded,{trackIndex:this.trackIdx,totalTracks:s.getTrackCount()}),this.trackWasDeleted=!1),e.emitEvent(fe.ClipRestored,{trackIndex:this.trackIdx,clipIndex:this.clipIdx}),Ee()}dispose(){this.deletedClipConfig=void 0,this.deletedClipId=void 0,this.deleteTrackCommand=void 0,this.storedBindings=void 0,this.convertedReferences=void 0}}class Vk{constructor(e){this.aspectRatio=e}name="setOutputAspectRatio";previousAspectRatio;execute(e){if(!e)throw new Error("SetOutputAspectRatioCommand requires context");return this.previousAspectRatio=e.getOutputAspectRatio(),e.setOutputAspectRatio(this.aspectRatio),Ee()}undo(e){if(!e)throw new Error("SetOutputAspectRatioCommand requires context");return this.previousAspectRatio===void 0?et("No previous aspect ratio stored"):(e.setOutputAspectRatio(this.previousAspectRatio),Ee())}dispose(){this.previousAspectRatio=void 0}}class Ik{constructor(e){this.destinations=e}name="setOutputDestinations";previousDestinations;execute(e){if(!e)throw new Error("SetOutputDestinationsCommand requires context");return this.previousDestinations=e.getOutputDestinations(),e.setOutputDestinations(this.destinations),Ee()}undo(e){if(!e)throw new Error("SetOutputDestinationsCommand requires context");return this.previousDestinations===void 0?et("No previous destinations stored"):(e.setOutputDestinations(this.previousDestinations),Ee())}dispose(){this.previousDestinations=void 0}}class _k{constructor(e){this.format=e}name="setOutputFormat";previousFormat;execute(e){if(!e)throw new Error("SetOutputFormatCommand requires context");return this.previousFormat=e.getOutputFormat(),e.setOutputFormat(this.format),Ee()}undo(e){if(!e)throw new Error("SetOutputFormatCommand requires context");return this.previousFormat===void 0?et("No previous format stored"):(e.setOutputFormat(this.previousFormat),Ee())}dispose(){this.previousFormat=void 0}}class Fk{constructor(e){this.fps=e}name="setOutputFps";previousFps;execute(e){if(!e)throw new Error("SetOutputFpsCommand requires context");return this.previousFps=e.getOutputFps(),e.setOutputFps(this.fps),Ee()}undo(e){if(!e)throw new Error("SetOutputFpsCommand requires context");return this.previousFps===void 0?et("No previous FPS stored"):(e.setOutputFps(this.previousFps),Ee())}dispose(){this.previousFps=void 0}}class Tk{constructor(e){this.resolution=e}name="setOutputResolution";previousResolution;execute(e){if(!e)throw new Error("SetOutputResolutionCommand requires context");return this.previousResolution=e.getOutputResolution(),e.setOutputResolution(this.resolution),Ee()}undo(e){if(!e)throw new Error("SetOutputResolutionCommand requires context");return this.previousResolution===void 0?et("No previous resolution stored"):(e.setOutputResolution(this.previousResolution),Ee())}dispose(){this.previousResolution=void 0}}class Ek{constructor(e,s){this.width=e,this.height=s}name="setOutputSize";previousSize;execute(e){if(!e)throw new Error("SetOutputSizeCommand requires context");return this.previousSize=e.getOutputSize(),e.setOutputSize(this.width,this.height),Ee()}undo(e){if(!e)throw new Error("SetOutputSizeCommand requires context");return this.previousSize?(e.setOutputSize(this.previousSize.width,this.previousSize.height),Ee()):et("No previous size stored")}dispose(){this.previousSize=void 0}}class Pk{constructor(e){this.color=e}name="setTimelineBackground";previousColor;execute(e){if(!e)throw new Error("SetTimelineBackgroundCommand requires context");return this.previousColor=e.getTimelineBackground(),e.setTimelineBackground(this.color),Ee()}undo(e){if(!e)throw new Error("SetTimelineBackgroundCommand requires context");return this.previousColor===void 0?et("No previous color stored"):(e.setTimelineBackground(this.previousColor),Ee())}dispose(){this.previousColor=void 0}}function Et(t){const{id:e,...s}=t;return s}function Mr(t){return!!(t&&typeof t=="object"&&!Array.isArray(t))}function So(t,e){const s={...t};return Mr(t)&&Mr(e)&&Object.keys(e).forEach(i=>{if(i==="__proto__"||i==="constructor"||i==="prototype")return;const a=e[i],r=t[i];Mr(a)?i in t&&Mr(r)?s[i]=So(r,a):s[i]=So({},a):s[i]=a}),s}function ps(t,e,s){const i=e.split(".");let a=t;for(let r=0;r<i.length-1;r+=1){if(a==null||typeof a!="object")return;a=a[i[r]]}a!=null&&typeof a=="object"&&(a[i[i.length-1]]=s)}function Rr(t,e){const s=e.split(".");let i=t;for(const a of s){if(i==null||typeof i!="object")return;i=i[a]}return i}class Vo{constructor(e,s,i){this.initialClipConfig=e,this.finalClipConfig=s,this.trackIndex=i?.trackIndex??-1,this.clipIndex=i?.clipIndex??-1}name="setUpdatedClip";clipId=null;storedInitialConfig=null;storedFinalConfig=null;storedInitialBindings=new Map;previousDocClip=null;trackIndex;clipIndex;async execute(e){if(!e)throw new Error("SetUpdatedClipCommand.execute: context is required");const s=e.getDocument();if(!s)throw new Error("SetUpdatedClipCommand.execute: document is required");const i=e.getClipAt(this.trackIndex,this.clipIndex);if(!i)return et(`Invalid clip at ${this.trackIndex}/${this.clipIndex}`);this.clipId=i.clipId,this.storedInitialConfig||(this.storedInitialConfig=this.initialClipConfig?structuredClone(this.initialClipConfig):structuredClone(i.clipConfiguration)),this.storedFinalConfig||(this.storedFinalConfig=this.finalClipConfig?structuredClone(this.finalClipConfig):structuredClone(i.clipConfiguration));const a=e.getDocumentClip(this.trackIndex>=0?this.trackIndex:i.layer-1,this.clipIndex>=0?this.clipIndex:e.getTracks()[i.layer-1]?.indexOf(i)??-1);this.previousDocClip=a?structuredClone(a):null;const r=this.clipId?e.getClipBindings(this.clipId):void 0;this.storedInitialBindings=r?new Map(r):new Map;const n=this.trackIndex>=0?this.trackIndex:i.layer-1,o=this.clipIndex>=0?this.clipIndex:e.getTracks()[n]?.indexOf(i)??-1,l=this.storedFinalConfig??this.finalClipConfig;l&&s.replaceClipProperties(n,o,l),e.resolve();const c=e.getClipAt(n,o);for(const[C,{resolvedValue:E}]of this.storedInitialBindings)(c?Rr(c.clipConfiguration,C):void 0)!==E&&this.clipId&&e.removeClipBinding(this.clipId,C);const f=this.storedInitialConfig??this.initialClipConfig,h=this.storedFinalConfig??this.finalClipConfig,d=f?.asset,y=h?.asset;if(d?.src!==y?.src){const C=e.getClipAt(n,o);C&&C.getTimingIntent().length==="auto"&&await e.resolveClipAutoLength(C)}const m=e.getDocumentClip(n,o);if(!this.previousDocClip||!m)throw new Error(`SetUpdatedClipCommand: document clip not found after mutation at ${n}/${o}`);return e.emitEvent(fe.ClipUpdated,{previous:{clip:Et(this.previousDocClip),trackIndex:n,clipIndex:o},current:{clip:Et(m),trackIndex:n,clipIndex:o}}),Ee()}async undo(e){if(!e)throw new Error("SetUpdatedClipCommand.undo: context is required");const s=this.storedInitialConfig??this.initialClipConfig;if(!s)return et("No stored initial config");const i=e.getDocument();if(!i)throw new Error("SetUpdatedClipCommand.undo: document is required");const a=this.clipId?e.getPlayerByClipId(this.clipId):e.getClipAt(this.trackIndex,this.clipIndex);if(!a)return et("Clip not found for undo");const r=this.trackIndex>=0?this.trackIndex:a.layer-1,n=this.clipIndex>=0?this.clipIndex:e.getTracks()[r]?.indexOf(a)??-1,o=structuredClone(e.getDocumentClip(r,n));if(i.replaceClipProperties(r,n,s),e.resolve(),this.clipId){const d=new Map(this.storedInitialBindings);d.size>0?e.getDocument()?.setClipBindingsForClip(this.clipId,d):e.getDocument()?.clearClipBindings(this.clipId)}const c=(this.storedFinalConfig??this.finalClipConfig)?.asset,f=s?.asset;if(c?.src!==f?.src){const d=e.getClipAt(r,n);d&&d.getTimingIntent().length==="auto"&&await e.resolveClipAutoLength(d)}const h=e.getDocumentClip(r,n);if(!o||!h)throw new Error(`SetUpdatedClipCommand: document clip not found after undo at ${r}/${n}`);return e.emitEvent(fe.ClipUpdated,{previous:{clip:Et(o),trackIndex:r,clipIndex:n},current:{clip:Et(h),trackIndex:r,clipIndex:n}}),Ee()}dispose(){this.clipId=null,this.storedInitialConfig=null,this.storedFinalConfig=null,this.storedInitialBindings.clear(),this.previousDocClip=null}}class Ok{constructor(e,s,i){this.trackIndex=e,this.clipIndex=s,this.splitTime=i}name="SplitClip";originalClipConfig=null;rightClipId=null;execute(e){const s=e.getDocument();if(!s)throw new Error("Cannot split clip: no document");const i=s.getClip(this.trackIndex,this.clipIndex);if(!i)return et(`No clip at ${this.trackIndex}/${this.clipIndex}`);const a=e.getClipAt(this.trackIndex,this.clipIndex),r=a?.clipConfiguration.start??0,n=a?.clipConfiguration.length??0,o=.1,l=this.splitTime-r;if(l<=o||l>=n-o)return et("Split point too close to clip boundaries");this.originalClipConfig=structuredClone(i);const c=l,f=structuredClone(i);if(i.start==="auto"?f.start="auto":f.start=r+l,f.length=n-l,i.asset&&(i.asset.type==="video"||i.asset.type==="audio")){const d=i.asset.trim||0;f.asset&&(f.asset.type==="video"||f.asset.type==="audio")&&(f.asset.trim=d+l)}e.documentUpdateClip(this.trackIndex,this.clipIndex,{length:c});const h=e.documentAddClip(this.trackIndex,f,this.clipIndex+1);return this.rightClipId=h.id??null,e.resolve(),e.updateDuration(),e.emitEvent(fe.ClipSplit,{trackIndex:this.trackIndex,originalClipIndex:this.clipIndex,newClipIndex:this.clipIndex+1}),Ee()}undo(e){return this.originalClipConfig?(e.documentRemoveClip(this.trackIndex,this.clipIndex+1),e.documentUpdateClip(this.trackIndex,this.clipIndex,this.originalClipConfig),e.resolve(),e.updateDuration(),e.emitEvent(fe.ClipDeleted,{trackIndex:this.trackIndex,clipIndex:this.clipIndex+1}),Ee()):et("No original clip config stored")}dispose(){this.originalClipConfig=null,this.rightClipId=null}}class Mk{constructor(e,s,i){this.trackIndex=e,this.clipIndex=s,this.params=i}name="UpdateClipTiming";originalStart;originalLength;clipId;execute(e){if(!e)throw new Error("UpdateClipTimingCommand.execute: context is required");const s=e.getDocument();if(!s)throw new Error("UpdateClipTimingCommand.execute: document is required");const a=e.getDocumentTrack(this.trackIndex)?.clips[this.clipIndex];if(!a)return et(`Invalid clip at ${this.trackIndex}/${this.clipIndex}`);const r=e.getClipAt(this.trackIndex,this.clipIndex);if(!r)return et(`Player not found at ${this.trackIndex}/${this.clipIndex}`);this.originalStart=a.start,this.originalLength=a.length,this.clipId=r.clipId??void 0;const n=structuredClone(a),o={};this.params.start!==void 0&&(o.start=this.params.start),this.params.length!==void 0&&(o.length=this.params.length),s.updateClip(this.trackIndex,this.clipIndex,o),this.clipId?e.resolveClip(this.clipId):e.resolve(),o.length==="auto"&&e.resolveClipAutoLength(r).then(()=>{e.updateDuration(),e.propagateTimingChanges(this.trackIndex,this.clipIndex)}),e.updateDuration();const l=e.getDocumentClip(this.trackIndex,this.clipIndex);if(!l)throw new Error(`UpdateClipTimingCommand: document clip not found after mutation at ${this.trackIndex}/${this.clipIndex}`);return e.emitEvent(fe.ClipUpdated,{previous:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:Et(n)},current:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:Et(l)}}),e.propagateTimingChanges(this.trackIndex,this.clipIndex),Ee()}undo(e){if(!e)throw new Error("UpdateClipTimingCommand.undo: context is required");if(this.originalStart===void 0&&this.originalLength===void 0)throw new Error("UpdateClipTimingCommand.undo: no original values");const s=e.getDocument();if(!s)throw new Error("UpdateClipTimingCommand.undo: document is required");const i=e.getClipAt(this.trackIndex,this.clipIndex);if(!i)throw new Error("UpdateClipTimingCommand.undo: player not found");const a=structuredClone(e.getDocumentClip(this.trackIndex,this.clipIndex)),r={};this.originalStart!==void 0&&(r.start=this.originalStart),this.originalLength!==void 0&&(r.length=this.originalLength),s.updateClip(this.trackIndex,this.clipIndex,r),this.clipId?e.resolveClip(this.clipId):e.resolve(),this.originalLength==="auto"&&e.resolveClipAutoLength(i).then(()=>{e.updateDuration(),e.propagateTimingChanges(this.trackIndex,this.clipIndex)}),e.updateDuration();const n=e.getDocumentClip(this.trackIndex,this.clipIndex);if(!a||!n)throw new Error(`UpdateClipTimingCommand: document clip not found after undo at ${this.trackIndex}/${this.clipIndex}`);return e.emitEvent(fe.ClipUpdated,{previous:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:Et(a)},current:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:Et(n)}}),e.propagateTimingChanges(this.trackIndex,this.clipIndex),Ee()}}class Rk{constructor(e,s,i){this.trackIndex=e,this.clipIndex=s,this.newText=i}name="updateTextContent";clipId=null;previousText="";previousDocClip;execute(e){if(!e)throw new Error("UpdateTextContentCommand.execute: context is required");const s=e.getDocument();if(!s)throw new Error("UpdateTextContentCommand.execute: document is required");const i=e.getClipAt(this.trackIndex,this.clipIndex);if(!i)return et(`Invalid clip at ${this.trackIndex}/${this.clipIndex}`);const a=s.getClip(this.trackIndex,this.clipIndex);if(!a)return et("Clip not found in document");this.clipId=i.clipId,this.previousDocClip=structuredClone(a);const r=a.asset;this.previousText=r&&"text"in r?r.text??"":"";const o={...a.asset,text:this.newText};s.updateClip(this.trackIndex,this.clipIndex,{asset:o}),this.clipId?e.resolveClip(this.clipId):e.resolve();const l=e.getDocumentClip(this.trackIndex,this.clipIndex);if(!this.previousDocClip||!l)throw new Error(`UpdateTextContentCommand: document clip not found after mutation at ${this.trackIndex}/${this.clipIndex}`);return e.emitEvent(fe.ClipUpdated,{previous:{clip:Et(this.previousDocClip),trackIndex:this.trackIndex,clipIndex:this.clipIndex},current:{clip:Et(l),trackIndex:this.trackIndex,clipIndex:this.clipIndex}}),Ee()}undo(e){if(!e)throw new Error("UpdateTextContentCommand.undo: context is required");const s=e.getDocument();if(!s)throw new Error("UpdateTextContentCommand.undo: document is required");const i=structuredClone(e.getDocumentClip(this.trackIndex,this.clipIndex)),a=s.getClip(this.trackIndex,this.clipIndex);if(!a)return et("Clip not found for undo");const n={...a.asset,text:this.previousText};s.updateClip(this.trackIndex,this.clipIndex,{asset:n}),this.clipId?e.resolveClip(this.clipId):e.resolve();const o=e.getDocumentClip(this.trackIndex,this.clipIndex);if(this.previousDocClip){if(!i||!o)throw new Error(`UpdateTextContentCommand: document clip not found after undo at ${this.trackIndex}/${this.clipIndex}`);e.emitEvent(fe.ClipUpdated,{previous:{clip:Et(i),trackIndex:this.trackIndex,clipIndex:this.clipIndex},current:{clip:Et(o),trackIndex:this.trackIndex,clipIndex:this.clipIndex}})}return Ee()}dispose(){this.clipId=null,this.previousDocClip=void 0}}class z0{events;constructor(){this.events={}}on(e,s){return this.events[e]||(this.events[e]=new Set),this.events[e].add(s),()=>this.off(e,s)}once(e,s){const i=a=>{this.off(e,i),s(a)};return this.on(e,i)}off(e,s){this.events[e]&&(this.events[e].delete(s),!(this.events[e].size>0)&&delete this.events[e])}clear(e){delete this.events[e]}emit(e,...s){if(!this.events[e])return;const i=s[0];for(const a of this.events[e])a(i)}}const L0=.5,zk=1/30;class Lk{constructor(e,s,i){this.getCanvas=e,this.getTracks=s,this.events=i,this.onClipChangedBound=()=>this.rebuildLumaMasksIfNeeded(),this.onPlayerLoadedBound=a=>this.onPlayerLoaded(a)}activeLumaMasks=[];pendingMaskCleanup=[];onClipChangedBound;onPlayerLoadedBound;initialize(){this.setupEventListeners()}update(){this.updateLumaMasks(),this.processPendingMaskCleanup()}getActiveMaskCount(){return this.activeLumaMasks.length}dispose(){this.removeEventListeners();for(const e of this.activeLumaMasks)e.tempContainer.destroy({children:!0}),e.maskSprite.destroy({texture:!0});this.activeLumaMasks=[];for(const e of this.pendingMaskCleanup)try{e.maskSprite.parent?.removeChild(e.maskSprite),e.maskSprite.destroy({texture:!0})}catch{}this.pendingMaskCleanup=[]}cleanupForPlayer(e){const s=this.activeLumaMasks.findIndex(a=>a.lumaPlayer===e);if(s===-1)return;const i=this.activeLumaMasks[s];i.contentClip&&(i.contentClip.getContentContainer().mask=null),i.maskSprite.parent?.removeChild(i.maskSprite),i.tempContainer.destroy({children:!0}),this.activeLumaMasks.splice(s,1),this.pendingMaskCleanup.push({maskSprite:i.maskSprite,frameCount:0})}onPlayerLoaded(e){const{player:s,trackIndex:i}=e;if(s.playerType!==Qe.Luma)return;const a=s,r=a.getSprite();if(!r?.texture){console.warn("PlayerLoaded fired for luma player before texture ready");return}const n=this.getTracks();if(i>=n.length)return;const l=n[i].filter(f=>f.playerType!==Qe.Luma);l.length===0||this.activeLumaMasks.find(f=>f.lumaPlayer===a)||(this.setupLumaMask(a,r.texture,l[0]),a.getContainer().parent?.removeChild(a.getContainer()))}setupLumaMask(e,s,i){const a=this.getCanvas();if(!a)return;const{renderer:r}=a.application,{width:n,height:o}=i.getSize(),l=new X.Container,c=new X.Sprite(s);c.width=n,c.height=o;const f=new X.ColorMatrixFilter;f.negative(!1),c.filters=[f],l.addChild(c);const h=r.generateTexture({target:l,resolution:L0}),d=new X.Sprite(h);i.getContainer().addChild(d);const y=i.getContentContainer();y.mask=d,this.activeLumaMasks.push({lumaPlayer:e,maskSprite:d,tempContainer:l,contentClip:i,lastVideoTime:-1})}updateLumaMasks(){const e=this.getCanvas();if(!e)return;const{renderer:s}=e.application;for(const i of this.activeLumaMasks)if(i.lumaPlayer.isVideoSource()){const a=i.lumaPlayer.getVideoCurrentTime();if(Math.abs(a-i.lastVideoTime)>=zk){i.lastVideoTime=a;const n=i.maskSprite.texture;i.maskSprite.texture=s.generateTexture({target:i.tempContainer,resolution:L0}),n.destroy(!0)}}}setupEventListeners(){this.events.on(ot.PlayerLoaded,this.onPlayerLoadedBound),this.events.on(fe.ClipUpdated,this.onClipChangedBound)}removeEventListeners(){this.events.off(ot.PlayerLoaded,this.onPlayerLoadedBound),this.events.off(fe.ClipUpdated,this.onClipChangedBound)}processPendingMaskCleanup(){for(let e=this.pendingMaskCleanup.length-1;e>=0;e-=1){const s=this.pendingMaskCleanup[e];if(s.frameCount+=1,s.frameCount>=3){try{s.maskSprite.parent?.removeChild(s.maskSprite),s.maskSprite.destroy({texture:!0})}catch{}this.pendingMaskCleanup.splice(e,1)}}}rebuildLumaMasksIfNeeded(){if(!this.getCanvas())return;const s=this.getTracks();for(let i=0;i<s.length;i+=1){const a=s[i],r=a.find(l=>l.playerType===Qe.Luma),n=a.filter(l=>l.playerType!==Qe.Luma);r&&r.getContainer().parent?.removeChild(r.getContainer());const o=r&&this.activeLumaMasks.find(l=>l.lumaPlayer===r);if(r&&!o&&n.length>0){const l=r.getSprite();l?.texture&&this.setupLumaMask(r,l.texture,n[0])}}}}function Dk(t){return{find:t.name,replace:t.defaultValue}}function Bk(t){const e=typeof t.replace=="string"?t.replace:JSON.stringify(t.replace);return{name:t.find,defaultValue:e}}const Zk=/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi,Io=/\{\{\s*[A-Z_0-9]+\s*\}\}/i;class Uk{fields=new Map;events;constructor(e){this.events=e}register(e,s){this.fields.set(e.name,e),s?.silent||this.events.emit(fe.MergeFieldChanged,{fields:this.getAll()})}remove(e,s){const i=this.fields.delete(e);return i&&!s?.silent&&this.events.emit(fe.MergeFieldChanged,{fields:this.getAll()}),i}get(e){return this.fields.get(e)}getAll(){return Array.from(this.fields.values())}clear(){this.fields.clear()}resolve(e){return!e||this.fields.size===0?e:e.replace(Zk,(s,i)=>this.fields.get(i)?.defaultValue??s)}resolveToNumber(e){if(!this.isMergeFieldTemplate(e))return null;const s=this.resolve(e),i=parseFloat(s);return Number.isFinite(i)?i:null}hasUnresolved(e){if(!e)return!1;const s=this.resolve(e);return Io.test(s)}extractFieldName(e){if(!e)return null;const s=Io.exec(e);if(!s)return null;const i=s[0].match(/\{\{\s*([A-Z_0-9]+)\s*\}\}/i);return i?i[1]:null}isMergeFieldTemplate(e){return Io.test(e)}createTemplate(e){return`{{ ${e} }}`}toSerializedArray(){return this.getAll().map(Dk)}loadFromSerialized(e){this.fields.clear();for(const s of e){const i=Bk(s);this.fields.set(s.find,i)}}generateUniqueName(e){const s=new Set(this.fields.keys());let i=1;for(;s.has(`${e}_${i}`);)i+=1;return`${e}_${i}`}}const Gk={preview:{width:512,height:288},mobile:{width:640,height:360},sd:{width:1024,height:576},hd:{width:1280,height:720},1080:{width:1920,height:1080},"4k":{width:3840,height:2160}};function zr(t,e="16:9"){const s=Gk[t];if(!s)throw new Error(`Unknown resolution: ${t}`);switch(e){case"16:9":return{width:s.width,height:s.height};case"9:16":return{width:s.height,height:s.width};case"1:1":return{width:s.height,height:s.height};case"4:5":return{width:Math.round(s.height*4/5),height:s.height};case"4:3":return{width:Math.round(s.height*4/3),height:s.height};default:throw new Error(`Unknown aspectRatio: ${e}`)}}class Wk{constructor(e){this.edit=e}setSize(e,s){fw.parse({width:e,height:s});const i={width:e,height:s};this.edit.size=i;const a=this.edit.getResolvedEdit();a&&(a.output={...a.output,size:i},delete a.output.resolution,delete a.output.aspectRatio);const r=this.edit.getDocument();r?.setSize(i),r?.clearResolution(),r?.clearAspectRatio(),this.edit.updateCanvasForSize(),this.edit.getInternalEvents().emit(fe.OutputResized,i)}getSize(){return this.edit.size}setFps(e){const s=hw.parse(e),i=this.edit.getResolvedEdit();i&&(i.output={...i.output,fps:s}),this.edit.getDocument()?.setFps(s),this.edit.getInternalEvents().emit(fe.OutputFpsChanged,{fps:e})}getFps(){return this.edit.getResolvedEdit()?.output?.fps??30}setFormat(e){const s=uw.parse(e),i=this.edit.getResolvedEdit();i&&(i.output={...i.output,format:s}),this.edit.getDocument()?.setFormat(s),this.edit.getInternalEvents().emit(fe.OutputFormatChanged,{format:s})}getFormat(){return this.edit.getResolvedEdit()?.output?.format??"mp4"}setDestinations(e){const s=cw.array().parse(e),i=this.edit.getResolvedEdit();i&&(i.output={...i.output,destinations:s}),this.edit.getInternalEvents().emit(fe.OutputDestinationsChanged,{destinations:s})}getDestinations(){return this.edit.getResolvedEdit()?.output?.destinations??[]}setResolution(e){const s=dw.parse(e),i=this.edit.getResolvedEdit(),a=i?.output?.aspectRatio??"16:9",r=zr(s,a);this.edit.size=r,i&&(i.output={...i.output,resolution:s},delete i.output.size);const n=this.edit.getDocument();n?.setResolution(s),n?.clearSize(),this.edit.updateCanvasForSize(),this.edit.getInternalEvents().emit(fe.OutputResolutionChanged,{resolution:s}),this.edit.getInternalEvents().emit(fe.OutputResized,{width:r.width,height:r.height})}getResolution(){return this.edit.getResolvedEdit()?.output?.resolution}setAspectRatio(e){const s=gw.parse(e),i=this.edit.getResolvedEdit(),a=i?.output?.resolution;if(!a){i&&(i.output={...i.output,aspectRatio:s}),this.edit.getDocument()?.setAspectRatio(s),this.edit.getInternalEvents().emit(fe.OutputAspectRatioChanged,{aspectRatio:s});return}const r=zr(a,s);this.edit.size=r,i&&(i.output={...i.output,aspectRatio:s},delete i.output.size);const n=this.edit.getDocument();n?.setAspectRatio(s),n?.clearSize(),this.edit.updateCanvasForSize(),this.edit.getInternalEvents().emit(fe.OutputAspectRatioChanged,{aspectRatio:s}),this.edit.getInternalEvents().emit(fe.OutputResized,{width:r.width,height:r.height})}getAspectRatio(){return this.edit.getResolvedEdit()?.output?.aspectRatio}}class Yk{constructor(e){this.edit=e}selectedClip=null;copiedClip=null;selectClip(e,s){const i=this.edit.getPlayerClip(e,s);if(i){this.selectedClip=i;const a=this.edit.getDocumentClip(e,s);a&&this.edit.getInternalEvents().emit(fe.ClipSelected,{clip:Et(a),trackIndex:e,clipIndex:s})}}selectPlayer(e){const s=this.findClipIndices(e);s&&this.selectClip(s.trackIndex,s.clipIndex)}clearSelection(){this.selectedClip=null,this.edit.getInternalEvents().emit(fe.SelectionCleared)}isClipSelected(e,s){if(!this.selectedClip)return!1;const i=this.selectedClip.layer-1,r=this.edit.getTracks()[i];if(!r)return!1;const n=r.indexOf(this.selectedClip);return e===i&&s===n}isPlayerSelected(e){return this.edit.isInExportMode()?!1:this.selectedClip===e}getSelectedClipInfo(){if(!this.selectedClip)return null;const e=this.selectedClip.layer-1,i=this.edit.getTracks()[e];if(!i)return null;const a=i.indexOf(this.selectedClip);return{trackIndex:e,clipIndex:a,player:this.selectedClip}}getSelectedClip(){return this.selectedClip}setSelectedClip(e){this.selectedClip=e}copyClip(e,s){const i=this.edit.getResolvedClip(e,s);i&&(this.copiedClip={trackIndex:e,clipConfiguration:structuredClone(i)},this.edit.getInternalEvents().emit(fe.ClipCopied,{trackIndex:e,clipIndex:s}))}pasteClip(){if(!this.copiedClip)return;const e=structuredClone(this.copiedClip.clipConfiguration);e.start=this.edit.playbackTime,delete e.id,this.edit.addClip(this.copiedClip.trackIndex,e)}hasCopiedClip(){return this.copiedClip!==null}findClipIndices(e){const s=this.edit.getTracks();for(let i=0;i<s.length;i+=1){const a=s[i].indexOf(e);if(a!==-1)return{trackIndex:i,clipIndex:a}}return null}}const Hk=3;function jk(t){return new Promise(e=>{const s=document.createElement("video");s.preload="metadata",s.crossOrigin="anonymous",s.onloadedmetadata=()=>e(s.duration),s.onerror=()=>e(null),s.src=t})}async function D0(t){const e=t;if(["video","audio","luma"].includes(e.type)&&e.src){const s=await jk(e.src);if(s!==null&&!Number.isNaN(s)){const i=e.trim??0;return s-i}}return Hk}function B0(t,e,s){return e===0?0:s[t][e-1].getEnd()}function Z0(t,e){return Math.max(0,e-t)}function _o(t){let e=0;for(const s of t)for(const i of s)i.getTimingIntent().length!=="end"&&(e=Math.max(e,i.getEnd()));return e}class Kk{constructor(e){this.edit=e}cachedTimelineEnd=0;getTimelineEnd(){return this.cachedTimelineEnd}invalidateTimelineEndCache(){this.cachedTimelineEnd=0}async resolveAllTiming(){const e=this.edit.getTracks(),s=this.edit.getResolvedEdit();for(let r=0;r<e.length;r+=1){const n=e[r],o=s.timeline.tracks[r];for(let l=0;l<n.length;l+=1){const c=n[l],f=o?.clips[l];if(f){const h=c.getTimingIntent(),d=f.start;let y=f.length;h.length==="auto"&&(y=await D0(c.clipConfiguration.asset)),c.setResolvedTiming({start:d,length:y})}}}const i=_o(e);this.cachedTimelineEnd=i;const a=this.getEndLengthClips();for(const r of a){const n=r.getResolvedTiming();r.setResolvedTiming({start:n.start,length:Z0(n.start,i)})}for(const r of a)r.reconfigureAfterRestore()}propagateTimingChanges(e,s){const i=this.edit.getTracks(),a=i[e];if(!a)return;for(let n=Math.max(0,s);n<a.length;n+=1){const o=a[n];if(o.getTimingIntent().start==="auto"){const l=B0(e,n,i);o.setResolvedTiming({start:l,length:o.getLength()}),o.reconfigureAfterRestore()}}this.propagateAliasChanges();const r=_o(i);if(r!==this.cachedTimelineEnd){this.cachedTimelineEnd=r;const n=this.getEndLengthClips();for(const o of n){const l=Z0(o.getStart(),r),c=o.getLength();Math.abs(l-c)>.001&&(o.setResolvedTiming({start:o.getStart(),length:l}),o.reconfigureAfterRestore())}}this.edit.updateTotalDuration(),this.edit.getInternalEvents().emit(fe.TimelineUpdated,{current:this.edit.getEdit()})}propagateAliasChanges(){const e=this.edit.getTracks(),s=this.edit.getResolvedEdit();for(let i=0;i<e.length;i+=1){const a=e[i],r=s.timeline.tracks[i];for(let n=0;n<a.length;n+=1){const o=a[n],l=r?.clips[n],c=o.getTimingIntent(),f=Kt(c.start),h=Kt(c.length);if((f||h)&&l){const d=o.getStart(),y=o.getLength(),m=Math.abs(l.start-d)>.001,C=Math.abs(l.length-y)>.001;(m||C)&&(o.setResolvedTiming({start:l.start,length:l.length}),o.reconfigureAfterRestore())}}}}getEndLengthClips(){const e=this.edit.getTracks(),s=[];for(const i of e)for(const a of i)a.getTimingIntent().length==="end"&&s.push(a);return s}}class Xk extends z0{registry;constructor(){super(),this.registry={}}}class Lr{static VIDEO_EXTENSIONS=[".mp4",".m4v",".webm",".ogg",".ogv"];static VIDEO_MIME={".mp4":"video/mp4",".m4v":"video/mp4",".webm":"video/webm",".ogg":"video/ogg",".ogv":"video/ogg"};loadTracker=new Xk;refCounts=new Map;incrementRef(e){this.refCounts.set(e,(this.refCounts.get(e)??0)+1)}decrementRef(e){const s=this.refCounts.get(e)??0;return s<=1?(this.refCounts.delete(e),!0):(this.refCounts.set(e,s-1),!1)}constructor(){X.Assets.setPreferences({crossOrigin:"anonymous"})}async load(e,s){this.updateAssetLoadMetadata(e,"pending",0),this.incrementRef(e);try{if(await this.shouldUseSafariVideoLoader(s))return await this.loadVideoForSafari(e,s);const a=await X.Assets.load(s,r=>{this.updateAssetLoadMetadata(e,"loading",r)});return this.updateAssetLoadMetadata(e,"success",1),a}catch(i){return console.warn(`[AssetLoader] Failed to load asset "${e}":`,i),this.updateAssetLoadMetadata(e,"failed",1),this.decrementRef(e),null}}async loadVideoUnique(e,s){this.updateAssetLoadMetadata(e,"pending",0);try{const i=this.extractUrl(s);if(!i)throw new Error("No URL provided for video loading");const a=typeof s=="object"?s.data??{}:{},r=await new Promise((n,o)=>{const l=document.createElement("video");l.crossOrigin="anonymous",l.playsInline=!0,l.muted=a.muted??!1,l.preload="auto",l.addEventListener("loadedmetadata",()=>{try{const c=new X.VideoSource({resource:l,autoPlay:a.autoPlay??!1,...a});n(new X.Texture({source:c}))}catch(c){o(c)}},{once:!0}),l.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(e,"loading",.5),l.src=i});return this.updateAssetLoadMetadata(e,"success",1),r}catch{return this.updateAssetLoadMetadata(e,"failed",1),null}}getProgress(){const e=Object.keys(this.loadTracker.registry);return e.length===0?0:e.reduce((i,a)=>i+this.loadTracker.registry[a].progress,0)/e.length}extractUrl(e){if(typeof e=="string")return e;const s=Array.isArray(e.src)?e.src[0]:e.src;return typeof s=="string"?s:s?.src}hasVideoExtension(e){const s=new URL(e,window.location.origin).pathname.toLowerCase();return Lr.VIDEO_EXTENSIONS.some(i=>s.endsWith(i))}async getContentType(e){try{return(await fetch(e,{method:"HEAD"})).headers.get("content-type")}catch{return null}}canPlayVideo(e){const s=new URL(e,window.location.origin).pathname.toLowerCase(),i=s.slice(s.lastIndexOf(".")),a=Lr.VIDEO_MIME[i];return a?document.createElement("video").canPlayType(a)!=="":!1}async isPlayableVideo(e){if(this.hasVideoExtension(e))return this.canPlayVideo(e);const s=await this.getContentType(e);return s?.startsWith("video/")?document.createElement("video").canPlayType(s)!=="":!1}async shouldUseSafariVideoLoader(e){const s=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),i=this.extractUrl(e);return s&&i!==void 0&&await this.isPlayableVideo(i)}async loadVideoForSafari(e,s){const i=this.extractUrl(s),a=typeof s=="object"?s.data??{}:{},r=await new Promise((n,o)=>{const l=document.createElement("video");l.crossOrigin="anonymous",l.playsInline=!0,l.muted=!0,l.preload="metadata",l.addEventListener("loadedmetadata",()=>{try{const c=new X.VideoSource({resource:l,autoPlay:a.autoPlay??!1,...a});n(new X.Texture({source:c}))}catch(c){o(c)}},{once:!0}),l.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(e,"loading",.5),l.src=i});return this.updateAssetLoadMetadata(e,"success",1),r}updateAssetLoadMetadata(e,s,i){this.loadTracker.registry[e]?(this.loadTracker.registry[e].progress=i,this.loadTracker.registry[e].status=s):this.loadTracker.registry[e]={progress:i,status:s};const a={...this.loadTracker.registry};this.loadTracker.emit("onAssetLoadInfoUpdated",{registry:a})}}class Dr{static Name="FontLoadParser";id;name;extension;validFontExtensions;woff2Decompressor;constructor(){this.id=Dr.Name,this.name=Dr.Name,this.extension={type:[X.ExtensionType.LoadParser],priority:X.LoaderParserPriority.High,ref:null},this.validFontExtensions=["ttf","otf","woff","woff2"],this.woff2Decompressor=null}test(e){const s=e.split("?")[0]?.split(".").pop()?.toLowerCase()??"";return this.validFontExtensions.includes(s)}async load(e,s,i){const a=e.split("?")[0]?.split(".").pop()?.toLowerCase()??"",r=await fetch(e).then(d=>d.arrayBuffer());if(a!=="woff2"){const d=$r.parse(new Uint8Array(r).buffer),y=d.names.fontFamily.en||d.names.fontFamily[Object.keys(d.names.fontFamily)[0]],m=new FontFace(y,`url(${e})`);return await m.load(),document.fonts.add(m),m}if(await this.loadWoff2Decompressor(),!this.woff2Decompressor)throw new Error("Cannot initialize Woff2 decompressor.");const n=this.woff2Decompressor.decompress(r),o=$r.parse(new Uint8Array(n).buffer),l=o.names.fontFamily.en||o.names.fontFamily[Object.keys(o.names.fontFamily)[0]],c=new Blob([n],{type:"font/ttf"}),f=URL.createObjectURL(c),h=new FontFace(l,`url(${f})`);return await h.load(),document.fonts.add(h),h}async loadWoff2Decompressor(){if(this.woff2Decompressor)return;const s=`${await fetch("https://unpkg.com/wawoff2@2.0.1/build/decompress_binding.js").then(i=>i.text())}; return Module`;this.woff2Decompressor=new Function(s)(),await new Promise(i=>{this.woff2Decompressor.onRuntimeInitialized=i})}unload(e){e&&document.fonts.delete(e)}}function qk(t,e,s,i){const a=Math.max(t,s),r=Math.min(e,i);return Math.max(0,r-a)}class Jk{queue=[];isProcessing=!1;async enqueue(e){return new Promise((s,i)=>{this.queue.push(async()=>{try{const a=await e();s(a)}catch(a){i(a)}}),this.processQueue()})}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;){const e=this.queue.shift();if(e)try{await e()}catch{}}this.isProcessing=!1}}}class Ai{data;clipBindings=new Map;constructor(e){this.data=structuredClone(e),this.hydrateIds()}hydrateIds(){const e=new Set;for(const s of this.data.timeline.tracks)for(let i=0;i<s.clips.length;i+=1){const a=s.clips[i];if(e.has(a)){const r=structuredClone(a);r.id=crypto.randomUUID(),s.clips[i]=r}else e.add(a),a.id||(a.id=crypto.randomUUID())}}getTimeline(){return this.data.timeline}getBackground(){return this.data.timeline.background}getTracks(){return this.data.timeline.tracks}getTrack(e){return this.data.timeline.tracks[e]??null}getTrackCount(){return this.data.timeline.tracks.length}getSoundtrack(){return this.data.timeline.soundtrack}getClip(e,s){const i=this.data.timeline.tracks[e];return i?i.clips[s]??null:null}getClipsInTrack(e){return this.data.timeline.tracks[e]?.clips??[]}getClipCount(){return this.data.timeline.tracks.reduce((e,s)=>e+s.clips.length,0)}getClipCountInTrack(e){return this.data.timeline.tracks[e]?.clips.length??0}getClipById(e){for(let s=0;s<this.data.timeline.tracks.length;s+=1){const i=this.data.timeline.tracks[s].clips;for(let a=0;a<i.length;a+=1)if(i[a].id===e)return{clip:i[a],trackIndex:s,clipIndex:a}}return null}updateClipById(e,s){const i=this.getClipById(e);i&&Object.assign(i.clip,s)}removeClipById(e){const s=this.getClipById(e);return s?this.removeClip(s.trackIndex,s.clipIndex):null}getClipId(e,s){return this.getClip(e,s)?.id??null}getOutput(){return this.data.output}getSize(){const{size:e}=this.data.output;if(!e?.width||!e?.height)throw new Error("Output size is not defined");return{width:e.width,height:e.height}}getFormat(){return this.data.output.format}getFps(){return this.data.output.fps}getResolution(){return this.data.output.resolution}getAspectRatio(){return this.data.output.aspectRatio}getMergeFields(){return this.data.merge}addTrack(e,s){const i=s??{clips:[]};return this.data.timeline.tracks.splice(e,0,i),i}removeTrack(e){if(e<0||e>=this.data.timeline.tracks.length)return null;if(this.data.timeline.tracks.length<=1)return console.warn("Cannot remove the last track"),null;const[s]=this.data.timeline.tracks.splice(e,1);return s??null}addClip(e,s,i){const a=this.data.timeline.tracks[e];if(!a)throw new Error(`Track ${e} does not exist`);const r=s;r.id||(r.id=crypto.randomUUID());const n=i??a.clips.length;return a.clips.splice(n,0,s),s}removeClip(e,s){const i=this.data.timeline.tracks[e];if(!i||s<0||s>=i.clips.length)return null;const[a]=i.clips.splice(s,1);return a??null}updateClip(e,s,i){const a=this.getClip(e,s);if(!a)throw new Error(`Clip at track ${e}, index ${s} does not exist`);Object.assign(a,i)}replaceClipProperties(e,s,i){const a=this.getClip(e,s);if(!a)throw new Error(`Clip at track ${e}, index ${s} does not exist`);const{id:r}=a;for(const n of Object.keys(a))n!=="id"&&delete a[n];Object.assign(a,i),r&&(a.id=r)}replaceClip(e,s,i){const a=this.data.timeline.tracks[e];if(!a||s<0||s>=a.clips.length)return null;const r=a.clips[s];return a.clips[s]=i,r}moveClip(e,s,i,a){const r=this.data.timeline.tracks[e];if(!r||s<0||s>=r.clips.length)return null;const n=this.data.timeline.tracks[i];if(!n)return null;const[o]=r.clips.splice(s,1);if(!o)return null;a&&Object.assign(o,a);const l=typeof o.start=="number"?o.start:0;let c=0;for(let f=0;f<n.clips.length;f+=1){const h=n.clips[f].start;if(l<(typeof h=="number"?h:0))break;c+=1}return n.clips.splice(c,0,o),o}setBackground(e){this.data.timeline.background=e}setSoundtrack(e){this.data.timeline.soundtrack=e}getFonts(){return this.data.timeline.fonts??[]}addFont(e){this.data.timeline.fonts||(this.data.timeline.fonts=[]),this.data.timeline.fonts.some(s=>s.src===e)||this.data.timeline.fonts.push({src:e})}removeFont(e){this.data.timeline.fonts&&(this.data.timeline.fonts=this.data.timeline.fonts.filter(s=>s.src!==e))}setFonts(e){this.data.timeline.fonts=e}setSize(e){this.data.output.size={width:e.width,height:e.height}}setFormat(e){this.data.output.format=e}setFps(e){this.data.output.fps=e}setResolution(e){this.data.output.resolution=e}clearResolution(){delete this.data.output.resolution}setAspectRatio(e){this.data.output.aspectRatio=e}clearAspectRatio(){delete this.data.output.aspectRatio}clearSize(){delete this.data.output.size}setMergeFields(e){this.data.merge=e}setClipBinding(e,s,i){let a=this.clipBindings.get(e);a||(a=new Map,this.clipBindings.set(e,a)),a.set(s,i)}getClipBinding(e,s){return this.clipBindings.get(e)?.get(s)}removeClipBinding(e,s){const i=this.clipBindings.get(e);i&&(i.delete(s),i.size===0&&this.clipBindings.delete(e))}getClipBindings(e){return this.clipBindings.get(e)}setClipBindingsForClip(e,s){s.size===0?this.clipBindings.delete(e):this.clipBindings.set(e,new Map(s))}clearClipBindings(e){this.clipBindings.delete(e)}getClipIdsWithBindings(){return Array.from(this.clipBindings.keys())}toJSON(){const e=structuredClone(this.data);for(const s of e.timeline.tracks)for(const i of s.clips){const a=i.id;if(a){const r=this.clipBindings.get(a);if(r)for(const[n,{placeholder:o}]of r)ps(i,n,o)}delete i.id}return e.merge?.length===0&&delete e.merge,e}static fromJSON(e){return new Ai(e)}clone(){return new Ai(this.data)}}const U0=new Set(["asset","start","length","id"]),Qk=new Set(["text-to-image","image-to-video","text-to-speech"]);class $k{constructor(e){this.edit=e,this.edit.getInternalEvents().on(ot.Resolved,this.onResolved)}isReconciling=!1;enableCreation=!0;onResolved=({edit:e})=>{this.reconcile(e)};async reconcileInitial(e){const s=this.reconcile(e);return await Promise.all(s.pendingLoads),s}reconcile(e){if(this.isReconciling)return{created:[],updated:[],disposed:[],pendingLoads:[]};this.isReconciling=!0;try{const s=[],i={created:[],updated:[],disposed:[],pendingLoads:s},a=new Set;for(let n=0;n<e.timeline.tracks.length;n+=1){const o=e.timeline.tracks[n];for(let l=0;l<o.clips.length;l+=1){const c=o.clips[l],f=c.id;if(f){a.add(f);const h=this.edit.getPlayerByClipId(f);if(h){const d=this.updatePlayer(h,c,n);d==="recreate"?(this.disposePlayer(f),s.push(this.createPlayer(c,f,n,l)),i.disposed.push(f),i.created.push(f)):d&&i.updated.push(f)}else this.enableCreation&&(this.createPlayer(c,f,n,l),i.created.push(f))}}}const r=this.findOrphanedPlayers(a);for(const n of r)this.disposePlayer(n),i.disposed.push(n);return(i.created.length>0||i.disposed.length>0||i.updated.length>0)&&this.rebuildTracksOrdering(e),this.syncTrackContainers(e.timeline.tracks.length),i}finally{this.isReconciling=!1}}updateSinglePlayer(e,s,i,a=0){const r=this.updatePlayer(e,s,i);if(r==="recreate"){const{clipId:n}=e;return n&&(this.disposePlayer(n),this.createPlayer(s,n,i,a)),"recreate"}return r}createPlayer(e,s,i,a){const r=this.edit.createPlayerFromAssetType(e);r.layer=i+1,r.clipId=s,this.edit.registerPlayerByClipId(s,r),this.edit.addPlayerToTracksArray(i,r),this.edit.addPlayerToContainer(i,r);const n=e.asset?.type??"unknown";return r.load().then(()=>{this.edit.getInternalEvents().emit(ot.PlayerLoaded,{player:r,trackIndex:i,clipIndex:a}),Qk.has(n)&&this.edit.getInternalEvents().emit(fe.ClipUnresolved,{trackIndex:i,clipIndex:a,assetType:n,clipId:s})}).catch(l=>{const c=l instanceof Error?l.message:String(l);this.edit.getInternalEvents().emit(fe.ClipLoadFailed,{trackIndex:i,clipIndex:a,error:c,assetType:n})})}updatePlayer(e,s,i){const a=e.clipConfiguration.asset?.type,r=s.asset?.type;if(a!==r)return"recreate";let n=!1;const o=e.layer-1,l=e.clipConfiguration.start,c=e.clipConfiguration.length;return(l!==s.start||c!==s.length)&&(e.setResolvedTiming({start:s.start,length:s.length}),e.reconfigureAfterRestore(),n=!0),o!==i&&(e.layer=i+1,this.edit.movePlayerBetweenTracks(e,o,i),n=!0),this.assetChanged(e.clipConfiguration.asset,s.asset)&&(this.updateAsset(e,s.asset),n=!0),this.clipPropertiesChanged(e.clipConfiguration,s)&&(this.updateClipProperties(e,s),n=!0),n}clipPropertiesChanged(e,s){const i=e,a=s,r=new Set([...Object.keys(i),...Object.keys(a)]);for(const n of r)if(!U0.has(n)&&JSON.stringify(i[n])!==JSON.stringify(a[n]))return!0;return!1}updateClipProperties(e,s){const i=e.clipConfiguration,a=s,r=new Set([...Object.keys(i),...Object.keys(a)]);for(const n of r)U0.has(n)||(a[n]!==void 0?i[n]=a[n]:delete i[n]);e.reconfigureAfterRestore()}assetChanged(e,s){return JSON.stringify(e)!==JSON.stringify(s)}updateAsset(e,s){const i=e.clipConfiguration.asset?.src,a=s?.src;e.clipConfiguration.asset=s,i!==a&&e.reloadAsset?e.reloadAsset().then(()=>{e.reconfigureAfterRestore()}).catch(r=>{console.error("Failed to reload asset:",r)}):e.reconfigureAfterRestore()}syncTrackContainers(e){const s=this.edit.getTracks().length;if(e>s)for(let i=s;i<e;i+=1)this.edit.ensureTrackExists(i);else if(e<s)for(let i=s-1;i>=e;i-=1)this.edit.removeEmptyTrack(i)}findOrphanedPlayers(e){const s=[];for(const[i]of this.edit.getPlayerMap())e.has(i)||s.push(i);return s}disposePlayer(e){const s=this.edit.getPlayerByClipId(e);s&&(this.edit.unregisterPlayerByClipId(e),this.edit.queuePlayerForDisposal(s))}rebuildTracksOrdering(e){const s=this.edit.getTracks();for(let i=0;i<s.length;i+=1)s[i]=[];for(let i=0;i<e.timeline.tracks.length;i+=1){for(;s.length<=i;)s.push([]);for(const a of e.timeline.tracks[i].clips){const r=a.id;if(r){const n=this.edit.getPlayerByClipId(r);n&&s[i].push(n)}}}}dispose(){this.edit.getInternalEvents().off(ot.Resolved,this.onResolved)}}function G0(t,e){function s(i){if(typeof i=="string"&&e.isMergeFieldTemplate(i)){const a=e.resolveToNumber(i);return a!==null?a:e.resolve(i)}if(Array.isArray(i))return i.map(s);if(i!==null&&typeof i=="object"){const a={};for(const[r,n]of Object.entries(i))a[r]=s(n);return a}return i}return s(structuredClone(t))}function eN(t){const e=new Map,s=new Map,i=[];for(let a=0;a<t.getTrackCount();a+=1){const r=t.getClipsInTrack(a);for(let n=0;n<r.length;n+=1){const o=r[n];if(!o.id)throw new Error(`Clip at track ${a}, index ${n} is missing an ID. EditDocument hydration may have been skipped.`);const l=o.alias??o.id,c={clip:o,trackIndex:a,clipIndex:n};if(i.push({...c,id:l}),o.alias){if(s.has(o.alias))throw new Error(`Duplicate alias "${o.alias}" found. Each alias must be unique.`);s.set(o.alias,c)}}}for(let a=0;a<t.getTrackCount();a+=1){const r=t.getClipsInTrack(a);for(let n=0;n<r.length;n+=1){const o=r[n],l=o.alias??o.id,c=new Set;if(Kt(o.start)){const f=ka(o.start);if(!s.has(f))throw new Error(`Alias reference "alias://${f}" not found. No clip defines alias "${f}".`);c.add(f)}if(Kt(o.length)){const f=ka(o.length);if(!s.has(f))throw new Error(`Alias reference "alias://${f}" not found. No clip defines alias "${f}".`);c.add(f)}if(o.start==="auto"&&n>0){const f=r[n-1],h=f.alias??f.id;c.add(h)}c.size>0&&e.set(l,c)}}return{dependencies:e,clipsByAlias:s,allClips:i}}function tN(t){const e=new Set,s=new Set;function i(a,r){e.add(a),s.add(a);const n=t.get(a);if(n)for(const o of n){if(s.has(o))return[...r,o];if(!e.has(o)){const l=i(o,[...r,o]);if(l)return l}}return s.delete(a),null}for(const a of t.keys())if(!e.has(a)){const r=i(a,[a]);if(r)return r}return null}function sN(t,e){const s=[],i=new Set;function a(r){if(i.has(r))return;i.add(r);const n=t.get(r);if(n)for(const o of n)a(o);s.push(r)}for(const r of t.keys())a(r);for(const r of e)a(r);return s}function W0(t,e,s){let i;if(t.start==="auto")i=e;else if(Kt(t.start)){const n=ka(t.start),o=s.get(n);if(!o)throw new Error(`Internal error: Alias "${n}" not resolved.`);i=o.start}else i=t.start;let a,r=!1;if(t.length==="end")a=1,r=!0;else if(t.length==="auto")a=3;else if(Kt(t.length)){const n=ka(t.length),o=s.get(n);if(!o)throw new Error(`Internal error: Alias "${n}" not resolved.`);a=o.length}else a=t.length;return{...t,id:t.id??crypto.randomUUID(),start:i,length:a,pendingEndLength:r||void 0}}function iN(t){let e=0;for(const s of t)for(const i of s.clips)if(!i.pendingEndLength){const a=i.start+i.length;a>e&&(e=a)}return e}function Fo(t){const{pendingEndLength:e,...s}=t;return s}function aN(t,e,s){const i=t.getClipById(e);if(!i)return null;const{clip:a,trackIndex:r,clipIndex:n}=i,l=G0(a,s.mergeFields),c=s.resolvedAliases??new Map,f=W0(l,s.previousClipEnd,c);return f.pendingEndLength&&s.cachedTimelineEnd!==void 0&&(f.length=Math.max(s.cachedTimelineEnd-f.start,.1)),{resolved:Fo(f),trackIndex:r,clipIndex:n}}function Y0(t,e){const{dependencies:s,allClips:i}=eN(t);if(s.size>0){const y=tN(s);if(y)throw new Error(`Circular alias reference detected: ${y.join(" -> ")}`)}const a=i.map(y=>y.id),r=sN(s,a),n=new Map;for(const y of i)n.set(y.id,y);const o=new Map,l=new Map,c=new Map;for(const y of r){const m=n.get(y);if(m){const{clip:C,trackIndex:E,clipIndex:F}=m,N=G0(C,e.mergeFields),w=c.get(E)??0,T=W0(N,w,l);o.set(`${E}-${F}`,T);const b=T.start+T.length,U=c.get(E)??0;b>U&&c.set(E,b),C.alias&&l.set(C.alias,{start:T.start,length:T.length})}}const f=[];for(let y=0;y<t.getTrackCount();y+=1){const m=t.getClipsInTrack(y).length,C=[];for(let E=0;E<m;E+=1){const F=o.get(`${y}-${E}`);if(!F)throw new Error(`Internal error: Clip at track ${y}, index ${E} was not resolved.`);C.push(F)}f.push({clips:C})}const h=iN(f),d=f.map(y=>({clips:y.clips.map(m=>{if(m.pendingEndLength){const C=Math.max(h-m.start,.1);return Fo({...m,length:C})}return Fo(m)})}));return{timeline:{background:t.getBackground(),tracks:d,fonts:t.getFonts()},output:t.getOutput()}}class Si{static MAX_HISTORY_SIZE=100;static SEEK_ELAPSED_MARKER=101;document;size;backgroundColor;tracks;playbackTime;totalDuration;isPlaying;get clips(){return this.tracks.flat()}assetLoader;internalEvents;events;canvas=null;timingManager;lumaMaskController;playerReconciler;outputSettings;selectionManager;mergeFieldService;commandHistory=[];commandIndex=-1;commandQueue=new Jk;clipsToDispose=new Set;clipErrors=new Map;playerByClipId=new Map;lumaContentRelations=new Map;fontMetadata=new Map;isBatchingEvents=!1;syncCorrectionCount=0;isExporting=!1;lastResolved=null;constructor(e){Ui.parse(e),this.tracks=[],this.playbackTime=0,this.totalDuration=0,this.isPlaying=!1,this.document=new Ai(e);const s=this.document.getResolution(),i=this.document.getAspectRatio();this.backgroundColor=this.document.getBackground()??"#000000",this.size=s?zr(s,i):this.document.getSize(),this.assetLoader=new Lr,this.internalEvents=new z0,this.events=this.internalEvents,this.lumaMaskController=new Lk(()=>this.canvas,()=>this.tracks,this.internalEvents),this.playerReconciler=new $k(this),this.mergeFieldService=new Uk(this.internalEvents),this.outputSettings=new Wk(this),this.selectionManager=new Yk(this),this.timingManager=new Kk(this),this.setupIntentListeners()}async load(){await this.initializeFromDocument()}async initializeFromDocument(e="load"){const s=this.document.toJSON(),i=s.merge??[];this.mergeFieldService.loadFromSerialized(i),this.lastResolved=null;const a=this.detectMergeFieldBindings(i),r=Ui.parse(s);await Promise.all((r.timeline.fonts??[]).map(async o=>{const l=o.src,c={src:l,parser:Dr.Name},f=await this.assetLoader.load(l,c);if(f?.family){const h=f.family.replace(/^["']|["']$/g,""),{baseFontFamily:d,fontWeight:y}=Dt(h);this.fontMetadata.set(l,{baseFamilyName:d,weight:y})}return f}));const n=this.getResolvedEdit();this.lumaMaskController.initialize(),await this.playerReconciler.reconcileInitial(n),this.normalizeLumaAttachments();for(const[o,l]of a)l.size>0&&this.document.setClipBindingsForClip(o,l);await this.timingManager.resolveAllTiming(),this.updateTotalDuration(),r.timeline.soundtrack&&await this.loadSoundtrack(r.timeline.soundtrack),this.internalEvents.emit(fe.TimelineUpdated,{current:this.getEdit()}),this.emitEditChanged(e)}getInternalEvents(){return this.internalEvents}update(e,s){for(const i of this.clips)i.shouldDispose&&this.queueDisposeClip(i),i.update(e,s);this.disposeClips(),this.lumaMaskController.update(),this.isPlaying&&(this.playbackTime=Math.max(0,Math.min(this.playbackTime+gu(s),this.totalDuration)),this.playbackTime===this.totalDuration&&this.pause())}dispose(){this.clearClips(),this.lumaMaskController.dispose(),this.playerReconciler.dispose();for(const e of this.commandHistory)e.dispose?.();this.commandHistory=[],this.commandIndex=-1,this.lumaContentRelations.clear(),M0.cleanup()}updateCanvasForSize(){this.internalEvents.emit(ot.ViewportSizeChanged,{width:this.size.width,height:this.size.height,backgroundColor:this.backgroundColor}),this.internalEvents.emit(ot.ViewportNeedsZoomToFit)}play(){this.isPlaying=!0,this.internalEvents.emit(fe.PlaybackPlay)}pause(){this.isPlaying=!1,this.internalEvents.emit(fe.PlaybackPause)}seek(e){this.playbackTime=Math.max(0,Math.min(e,this.totalDuration)),this.pause(),this.update(0,Si.SEEK_ELAPSED_MARKER)}stop(){this.seek(0)}async loadEdit(e){if(Ui.parse(e),this.tracks.length>0&&!this.hasStructuralChanges(e)){this.lastResolved=null;const n=structuredClone(e);this.preserveClipIdsForGranularUpdate(n);const o=this.document.getTracks(),l=this.document.getOutput();this.document=new Ai(n),this.isBatchingEvents=!0,await this.applyGranularChanges(n,o,l),this.isBatchingEvents=!1,this.emitEditChanged("loadEdit:granular");return}const s=this.document,i=this.lastResolved,a=this.size,r=this.backgroundColor;try{this.lastResolved=null,this.document=new Ai(e);const n=this.document.getResolution(),o=this.document.getAspectRatio();this.size=n?zr(n,o):this.document.getSize(),this.backgroundColor=this.document.getBackground()??"#000000",this.internalEvents.emit(ot.ViewportSizeChanged,{width:this.size.width,height:this.size.height,backgroundColor:this.backgroundColor}),this.internalEvents.emit(ot.ViewportNeedsZoomToFit),this.clearClips(),await this.initializeFromDocument("loadEdit")}catch(n){throw this.document=s,this.lastResolved=i,this.size=a,this.backgroundColor=r,n}}async loadSoundtrack(e){const s={id:crypto.randomUUID(),asset:{type:"audio",src:e.src,effect:e.effect,volume:e.volume??1},fit:"crop",start:0,length:this.totalDuration},i=this.createPlayerFromAssetType(s);i.layer=this.tracks.length+1,await this.addPlayer(this.tracks.length,i)}getEdit(){const e=this.document.toJSON(),s=this.mergeFieldService.toSerializedArray();return s.length>0&&(e.merge=s),e}validateEdit(e){const s=Ui.safeParse(e);return s.success?{valid:!0,errors:[]}:{valid:!1,errors:s.error.issues.map(i=>({path:i.path.join("."),message:i.message}))}}getResolvedEdit(){return this.lastResolved||(this.lastResolved=Y0(this.document,{mergeFields:this.mergeFieldService})),this.lastResolved}getResolvedClip(e,s){return this.getResolvedEdit()?.timeline?.tracks?.[e]?.clips?.[s]??null}getResolvedClipById(e){const s=this.getResolvedEdit();for(const i of s.timeline.tracks)for(const a of i.clips)if(a.id===e)return a;return null}getClipId(e,s){return this.document?.getClipId(e,s)??null}getDocumentClip(e,s){return this.document?.getClip(e,s)??null}getDocument(){return this.document}resolve(){return this.lastResolved=Y0(this.document,{mergeFields:this.mergeFieldService}),this.internalEvents.emit(ot.Resolved,{edit:this.lastResolved}),this.lastResolved}resolveClip(e){const s=this.getPlayerByClipId(e);if(!s)return!1;const i=this.document.getClipById(e);if(i?.clip.alias)return this.resolve(),!0;const a=i?.clip;if(a&&(Kt(a.start)||Kt(a.length)))return this.resolve(),!0;const r=s.layer-1,n=this.tracks[r],o=n?n.indexOf(s):-1;if(o<0)return!1;const l=o>0?n[o-1]:null,c=l?l.getEnd():0,f={mergeFields:this.mergeFieldService,previousClipEnd:c,cachedTimelineEnd:this.timingManager.getTimelineEnd()},h=aN(this.document,e,f);if(!h)return!1;if(this.lastResolved){const y=this.lastResolved.timeline.tracks[h.trackIndex];y&&y.clips[h.clipIndex]&&(y.clips[h.clipIndex]=h.resolved)}return this.playerReconciler.updateSinglePlayer(s,h.resolved,h.trackIndex,h.clipIndex)!==!1}addClip(e,s){Wa.parse(s);const i=new Ak(e,s);return this.executeCommand(i)}getClip(e,s){const i=this.tracks[e];return!i||s<0||s>=i.length?null:i[s].clipConfiguration}getClipError(e,s){return this.clipErrors.get(`${e}-${s}`)??null}clearClipErrorAndShift(e,s){this.clipErrors.delete(`${e}-${s}`);const i=[];for(const[a,r]of this.clipErrors){const[n,o]=a.split("-").map(Number);n===e&&o>s&&i.push({oldKey:a,newKey:`${n}-${o-1}`,value:r})}for(const{oldKey:a,newKey:r,value:n}of i)this.clipErrors.delete(a),this.clipErrors.set(r,n)}getPlayerClip(e,s){const i=this.tracks[e];return!i||s<0||s>=i.length?null:i[s]}getPlayerByClipId(e){return this.playerByClipId.get(e)??null}getDocumentClipById(e){return this.document?.getClipById(e)?.clip??null}registerPlayerByClipId(e,s){this.playerByClipId.set(e,s)}unregisterPlayerByClipId(e){this.playerByClipId.delete(e)}getPlayerMap(){return this.playerByClipId}addPlayerToTracksArray(e,s){for(;this.tracks.length<=e;)this.tracks.push([]);this.tracks[e].push(s)}movePlayerBetweenTracks(e,s,i){const a=this.tracks[s];if(a){const r=a.indexOf(e);r!==-1&&a.splice(r,1)}for(;this.tracks.length<=i;)this.tracks.push([]);this.tracks[i].push(e),this.movePlayerToTrackContainer(e,s,i)}queuePlayerForDisposal(e){this.queueDisposeClip(e),this.disposeClips()}ensureTrackExists(e){for(;this.tracks.length<=e;)this.tracks.push([])}removeEmptyTrack(e){if(e<0||e>=this.tracks.length)return;const s=this.tracks[e];if(s&&s.length>0){console.warn(`Cannot remove non-empty track ${e}`);return}this.tracks.splice(e,1),this.internalEvents.emit(ot.TrackContainerRemoved,{trackIndex:e});for(let i=e;i<this.tracks.length;i+=1)for(const a of this.tracks[i])a.layer=i+1}getOriginalAsset(e,s){const i=this.getPlayerClip(e,s);if(!i)return;const a=i.getExportableClip();if(!a)return;const{clipId:r}=i;if(r&&this.document){const n=this.document.getClipBindings(r);if(n){for(const[o,{placeholder:l}]of n)if(o.startsWith("asset.")){const c=o.slice(6);ps(a.asset,c,l)}}}return a.asset}async deleteClip(e,s){const i=this.tracks[e];if(!i)return;const a=i[s];if(!a)return;if(a.playerType!==Qe.Luma){const o=i.findIndex(l=>l.playerType===Qe.Luma);if(o!==-1){const l=o<s?s-1:s,c=new Ao(e,o);await this.executeCommand(c);const f=new Ao(e,l);await this.executeCommand(f);return}}const n=new Ao(e,s);await this.executeCommand(n)}splitClip(e,s,i){const a=new Ok(e,s,i);return this.executeCommand(a)}async addTrack(e,s){oc.parse(s);const i=new Sk(e);await this.executeCommand(i);for(const a of s.clips)await this.addClip(e,a)}getTrack(e){const s=this.clips.filter(i=>i.layer===e+1);return s.length===0?null:{clips:s.map(i=>i.clipConfiguration)}}deleteTrack(e){const s=new R0(e);this.executeCommand(s)}recordSyncCorrection(){this.syncCorrectionCount+=1}undo(){return this.commandQueue.enqueue(async()=>{if(this.commandIndex>=0){const e=this.commandHistory[this.commandIndex];if(e.undo){const s=this.createCommandContext();await Promise.resolve(e.undo(s)),this.commandIndex-=1,this.internalEvents.emit(fe.EditUndo,{command:e.name}),this.emitEditChanged(`undo:${e.name}`)}}})}redo(){return this.commandQueue.enqueue(async()=>{if(this.commandIndex<this.commandHistory.length-1){const e=this.commandIndex+1,s=this.commandHistory[e],i=this.createCommandContext();await Promise.resolve(s.execute(i)),this.commandIndex=e,this.internalEvents.emit(fe.EditRedo,{command:s.name}),this.emitEditChanged(`redo:${s.name}`)}})}setUpdatedClip(e,s=null,i=null){const a=e.layer-1,r=this.tracks[a],n=r?r.indexOf(e):-1,o=new Vo(s,i,{trackIndex:a,clipIndex:n});this.executeCommand(o)}updateClipInDocument(e,s){const i=this.document.getClipById(e);i&&this.document.updateClip(i.trackIndex,i.clipIndex,s)}commitClipUpdate(e,s,i){const a=this.document.getClipById(e);if(!a){console.warn(`commitClipUpdate: clip ${e} not found in document`);return}kn.parse(i);const r=new Vo(s,structuredClone(i),{trackIndex:a.trackIndex,clipIndex:a.clipIndex});this.addCommandToHistory(r)}pushCommandToHistory(e){const s=this.commandHistory.slice(this.commandIndex+1);for(const i of s)i.dispose?.();for(this.commandHistory=this.commandHistory.slice(0,this.commandIndex+1),this.commandHistory.push(e),this.commandIndex+=1;this.commandHistory.length>Si.MAX_HISTORY_SIZE;)this.commandHistory.shift()?.dispose?.(),this.commandIndex-=1}addCommandToHistory(e){this.pushCommandToHistory(e),this.emitEditChanged(`commit:${e.name}`)}updateClip(e,s,i){const a=this.getPlayerClip(e,s);if(!a)return console.warn(`Clip not found at track ${e}, index ${s}`),Promise.resolve();const r=this.document?.getClip(e,s),n=structuredClone(r??a.clipConfiguration),o=structuredClone(r??a.clipConfiguration),l=So(o,i);kn.parse(l);const c=new Vo(n,l,{trackIndex:e,clipIndex:s});return this.executeCommand(c)}updateClipTiming(e,s,i){if(!this.getPlayerClip(e,s)){console.warn(`Clip not found at track ${e}, index ${s}`);return}const r=new Mk(e,s,i);this.executeCommand(r)}updateTextContent(e,s,i){const a=e.layer-1,r=this.tracks[a]?.indexOf(e)??-1;if(r<0){console.warn("UpdateTextContent: clip not found in track");return}const n=new Rk(a,r,s);this.executeCommand(n)}executeEditCommand(e){return this.executeCommand(e)}executeCommand(e){return this.commandQueue.enqueue(async()=>{const s=this.createCommandContext(),i=await Promise.resolve(e.execute(s));this.handleCommandResult(e,i)})}handleCommandResult(e,s){s.status==="success"&&(this.pushCommandToHistory(e),this.emitEditChanged(e.name))}emitEditChanged(e){this.isBatchingEvents||this.internalEvents.emit(fe.EditChanged,{source:e,timestamp:Date.now()})}detectMergeFieldBindings(e){const s=new Map;if(!e.length)return s;const i=new Map;for(const{find:a,replace:r}of e){const n=typeof r=="string"?r:JSON.stringify(r);i.set(a.toUpperCase(),n)}for(let a=0;a<this.document.getTrackCount();a+=1){const r=this.document.getClipsInTrack(a);for(let n=0;n<r.length;n+=1){const o=this.document.getClipId(a,n);if(o){const l=this.detectBindingsInObject(r[n],"",i);l.size>0&&s.set(o,l)}}}return s}detectBindingsInObject(e,s,i){const a=new Map;if(typeof e=="string"){if(/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi.test(e)){const o=e.replace(/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi,(l,c)=>i.get(c.toUpperCase())??l);a.set(s,{placeholder:e,resolvedValue:o})}return a}if(Array.isArray(e)){for(let r=0;r<e.length;r+=1){const n=s?`${s}[${r}]`:`[${r}]`,o=this.detectBindingsInObject(e[r],n,i);for(const[l,c]of o)a.set(l,c)}return a}if(e!==null&&typeof e=="object")for(const[r,n]of Object.entries(e)){const o=s?`${s}.${r}`:r,l=this.detectBindingsInObject(n,o,i);for(const[c,f]of l)a.set(c,f)}return a}hasStructuralChanges(e){if(!this.document)return!0;const s=this.document.getTracks(),i=e.timeline.tracks;if(s.length!==i.length)return!0;for(let a=0;a<s.length;a+=1){if(s[a].clips.length!==i[a].clips.length)return!0;for(let r=0;r<s[a].clips.length;r+=1){const n=s[a].clips[r]?.asset?.type,o=i[a].clips[r]?.asset?.type;if(n!==o)return!0}}return JSON.stringify(this.document.getMergeFields()??[])!==JSON.stringify(e.merge??[])||JSON.stringify(this.document.getFonts())!==JSON.stringify(e.timeline.fonts??[])||JSON.stringify(this.document.getSoundtrack())!==JSON.stringify(e.timeline.soundtrack)}preserveClipIdsForGranularUpdate(e){if(!this.document)return;const s=this.document.getTracks();for(let i=0;i<e.timeline.tracks.length;i+=1){const a=s[i],r=e.timeline.tracks[i];if(a&&r)for(let n=0;n<r.clips.length;n+=1){const o=this.document.getClipId(i,n);o&&(r.clips[n].id=o)}}}async applyGranularChanges(e,s,i){const a=e.output;if(a?.size&&(i?.size?.width!==a.size.width||i?.size?.height!==a.size.height)){const o=a.size.width??this.size.width,l=a.size.height??this.size.height;await this.setOutputSize(o,l)}a?.fps!==void 0&&i?.fps!==a.fps&&await this.setOutputFps(a.fps),a?.format!==void 0&&i?.format!==a.format&&await this.setOutputFormat(a.format),a?.destinations&&JSON.stringify(i?.destinations)!==JSON.stringify(a.destinations)&&await this.setOutputDestinations(a.destinations),a?.resolution!==void 0&&i?.resolution!==a.resolution&&await this.setOutputResolution(a.resolution),a?.aspectRatio!==void 0&&i?.aspectRatio!==a.aspectRatio&&await this.setOutputAspectRatio(a.aspectRatio);const r=e.timeline?.background;r&&this.backgroundColor!==r&&await this.setTimelineBackground(r);const n=e.timeline.tracks;for(let o=0;o<n.length;o+=1){const l=s[o].clips,c=n[o].clips;for(let f=0;f<c.length;f+=1){const h=l[f],d=c[f];JSON.stringify(h)!==JSON.stringify(d)&&await this.updateClip(o,f,d)}}}createCommandContext(){return{getClips:()=>this.clips,getTracks:()=>this.tracks,getTrack:e=>e>=0&&e<this.tracks.length?this.tracks[e]:null,getContainer:()=>this.getViewportContainer(),addPlayer:(e,s)=>this.addPlayer(e,s),addPlayerToContainer:(e,s)=>{this.addPlayerToContainer(e,s)},createPlayerFromAssetType:e=>this.createPlayerFromAssetType(e),queueDisposeClip:e=>this.queueDisposeClip(e),disposeClips:()=>this.disposeClips(),clearClipError:(e,s)=>this.clearClipErrorAndShift(e,s),undeleteClip:(e,s)=>{let i=0;if(e>=0&&e<this.tracks.length){const a=this.tracks[e];i=a.length;for(let r=0;r<a.length;r+=1)if(a[r].getStart()>s.getStart()){i=r;break}a.splice(i,0,s)}if(this.document){const a=s.getExportableClip();this.document.addClip(e,a,i);const r=this.document.getClipId(e,i);r&&(s.clipId=r,this.playerByClipId.set(r,s))}this.addPlayerToContainer(e,s),s.load().catch(a=>{const r=s.clipConfiguration?.asset?.type??"unknown",n=a instanceof Error?a.message:String(a);this.clipErrors.set(`${e}-${i}`,{error:n,assetType:r}),this.internalEvents.emit(fe.ClipLoadFailed,{trackIndex:e,clipIndex:i,error:n,assetType:r})}),this.updateTotalDuration()},setUpdatedClip:()=>{},restoreClipConfiguration:(e,s)=>{const i=structuredClone(s),a=e.clipConfiguration;for(const r of Object.keys(a))delete a[r];if(Object.assign(a,i),e.reconfigureAfterRestore(),this.document){const r=this.findClipIndices(e);if(r){const n=e.getExportableClip();this.document.replaceClip(r.trackIndex,r.clipIndex,n)}}},updateDuration:()=>this.updateTotalDuration(),emitEvent:(e,...s)=>this.internalEvents.emit(e,...s),findClipIndices:e=>this.selectionManager.findClipIndices(e),getClipAt:(e,s)=>this.getClipAt(e,s),getSelectedClip:()=>this.selectionManager.getSelectedClip(),setSelectedClip:e=>{this.selectionManager.setSelectedClip(e)},movePlayerToTrackContainer:(e,s,i)=>this.movePlayerToTrackContainer(e,s,i),getEditState:()=>this.getResolvedEdit(),propagateTimingChanges:(e,s)=>this.propagateTimingChanges(e,s),resolveClipAutoLength:e=>this.resolveClipAutoLength(e),getMergeFields:()=>this.mergeFieldService,getOutputSize:()=>this.outputSettings.getSize(),setOutputSize:(e,s)=>this.outputSettings.setSize(e,s),getOutputFps:()=>this.outputSettings.getFps(),setOutputFps:e=>this.outputSettings.setFps(e),getOutputFormat:()=>this.outputSettings.getFormat(),setOutputFormat:e=>this.outputSettings.setFormat(e),getOutputResolution:()=>this.outputSettings.getResolution(),setOutputResolution:e=>this.outputSettings.setResolution(e),getOutputAspectRatio:()=>this.outputSettings.getAspectRatio(),setOutputAspectRatio:e=>this.outputSettings.setAspectRatio(e),getOutputDestinations:()=>this.outputSettings.getDestinations(),setOutputDestinations:e=>this.outputSettings.setDestinations(e),getTimelineBackground:()=>this.getTimelineBackground(),setTimelineBackground:e=>this.setTimelineBackgroundInternal(e),getDocument:()=>this.document,getDocumentTrack:e=>this.document?.getTrack(e)??null,getDocumentClip:(e,s)=>this.document?.getClip(e,s)??null,documentUpdateClip:(e,s,i)=>{if(!this.document)throw new Error("Document not initialized - cannot update clip");this.document.updateClip(e,s,i)},documentAddClip:(e,s,i)=>{if(!this.document)throw new Error("Document not initialized - cannot add clip");for(;this.document.getTrackCount()<=e;)this.document.addTrack(this.document.getTrackCount());return this.document.addClip(e,s,i)},documentRemoveClip:(e,s)=>{if(!this.document)throw new Error("Document not initialized - cannot remove clip");return this.document.removeClip(e,s)},derivePlayerFromDocument:(e,s)=>{const i=this.document?.getClip(e,s);if(!i)throw new Error(`derivePlayerFromDocument: No document clip at ${e}/${s} - state desync`);const a=this.getClipAt(e,s);if(!a)throw new Error(`derivePlayerFromDocument: No player at ${e}/${s} - state desync`);const{asset:r,...n}=i;Object.assign(a.clipConfiguration,n),a.reconfigureAfterRestore()},buildResolutionContext:(e,s)=>{let i=0;if(s>0){const o=this.tracks[e];o&&o[s-1]&&(i=o[s-1].getEnd())}const a=_o(this.tracks);let r=null;const n=this.getClipAt(e,s);return n&&n.getTimingIntent().length==="auto"&&(r=n.getLength()),{previousClipEnd:i,timelineEnd:a,intrinsicDuration:r}},resolve:()=>this.resolve(),resolveClip:e=>this.resolveClip(e),getPlayerByClipId:e=>this.playerByClipId.get(e)??null,registerPlayerByClipId:(e,s)=>{this.playerByClipId.set(e,s)},unregisterPlayerByClipId:e=>{this.playerByClipId.delete(e)},setClipBinding:(e,s,i)=>{this.document?.setClipBinding(e,s,i)},getClipBinding:(e,s)=>this.document?.getClipBinding(e,s),removeClipBinding:(e,s)=>{this.document?.removeClipBinding(e,s)},getClipBindings:e=>this.document?.getClipBindings(e),getEditSession:()=>this}}queueDisposeClip(e){this.clipsToDispose.add(e)}disposeClips(){if(this.clipsToDispose.size!==0){for(const e of this.clipsToDispose)e.playerType===Qe.Luma&&(this.lumaMaskController.cleanupForPlayer(e),e.clipId&&this.lumaContentRelations.delete(e.clipId));for(const e of this.clipsToDispose)e.clipId&&this.playerByClipId.delete(e.clipId);for(const e of this.clipsToDispose)this.disposeClip(e);for(const e of this.clipsToDispose){const s=e.layer-1;if(s>=0&&s<this.tracks.length){const i=this.tracks[s].indexOf(e);i!==-1&&this.tracks[s].splice(i,1)}}this.clipsToDispose.clear(),this.updateTotalDuration(),this.cleanupUnusedFonts()}}cleanupUnusedFonts(){if(!this.document)return;const e=this.document.getFonts();if(e.length===0)return;const s=new Set;for(const i of this.clips){const{asset:a}=i.clipConfiguration;a&&a.type==="rich-text"&&a.font?.family&&s.add(a.font.family)}for(const i of e)if(i.src.includes("fonts.gstatic.com")){const r=this.extractFilenameFromUrl(i.src);r&&!s.has(r)&&this.document.removeFont(i.src)}}extractFilenameFromUrl(e){try{const{pathname:s}=new URL(e),i=s.split("/").pop();return i?i.replace(/\.[^.]+$/,""):null}catch{return null}}disposeClip(e){try{const s=this.canvas?.getViewportContainer();if(s){for(const i of s.children)if(i instanceof X.Container&&i.label?.toString().startsWith("shotstack-track-")&&i.children.includes(e.getContainer())){i.removeChild(e.getContainer());break}}}catch(s){console.warn(`Attempting to unmount an unmounted clip: ${s}`)}this.unloadClipAssets(e),this.timingManager.invalidateTimelineEndCache(),e.dispose()}unloadClipAssets(e){const{asset:s}=e.clipConfiguration;s&&"src"in s&&typeof s.src=="string"&&this.assetLoader.decrementRef(s.src)&&X.Assets.cache.has(s.src)&&X.Assets.unload(s.src)}clearClips(){for(const e of this.clips)this.disposeClip(e);this.tracks=[],this.clipsToDispose.clear(),this.clipErrors.clear(),this.lumaContentRelations.clear(),this.updateTotalDuration()}updateTotalDuration(){let e=0;for(const i of this.tracks)for(const a of i)e=Math.max(e,a.getEnd());const s=this.totalDuration;this.totalDuration=e,s!==this.totalDuration&&this.internalEvents.emit(fe.DurationChanged,{duration:this.totalDuration})}propagateTimingChanges(e,s){this.timingManager.propagateTimingChanges(e,s)}async resolveClipAutoLength(e){const s=e.getTimingIntent();if(s.length!=="auto")return;const i=this.findClipIndices(e);let a=e.getStart();s.start==="auto"&&i&&(a=B0(i.trackIndex,i.clipIndex,this.tracks));const r=await D0(e.clipConfiguration.asset);e.setResolvedTiming({start:a,length:r}),e.reconfigureAfterRestore(),i&&this.propagateTimingChanges(i.trackIndex,i.clipIndex)}addPlayerToContainer(e,s){this.internalEvents.emit(ot.PlayerAddedToTrack,{player:s,trackIndex:e})}movePlayerToTrackContainer(e,s,i){this.internalEvents.emit(ot.PlayerMovedBetweenTracks,{player:e,fromTrackIndex:s,toTrackIndex:i})}createPlayerFromAssetType(e){return M0.create(this,e)}async addPlayer(e,s){for(;this.tracks.length<=e;)this.tracks.push([]);this.tracks[e].push(s),this.internalEvents.emit(ot.PlayerAddedToTrack,{player:s,trackIndex:e}),await s.load(),this.updateTotalDuration()}selectClip(e,s){this.selectionManager.selectClip(e,s)}clearSelection(){this.selectionManager.clearSelection()}isClipSelected(e,s){return this.selectionManager.isClipSelected(e,s)}getSelectedClipInfo(){return this.selectionManager.getSelectedClipInfo()}copyClip(e,s){this.selectionManager.copyClip(e,s)}pasteClip(){this.selectionManager.pasteClip()}hasCopiedClip(){return this.selectionManager.hasCopiedClip()}findClipIndices(e){return this.selectionManager.findClipIndices(e)}getClipAt(e,s){return e>=0&&e<this.tracks.length&&s>=0&&s<this.tracks[e].length?this.tracks[e][s]:null}selectPlayer(e){this.selectionManager.selectPlayer(e)}isPlayerSelected(e){return this.selectionManager.isPlayerSelected(e)}getActivePlayersExcept(e){const s=[];for(const i of this.tracks)for(const a of i)a!==e&&a.isActive()&&s.push(a);return s}showAlignmentGuide(e,s,i,a){this.canvas?.showAlignmentGuide(e,s,i,a)}clearAlignmentGuides(){this.canvas?.clearAlignmentGuides()}moveSelectedClip(e,s){const i=this.getSelectedClipInfo();if(!i)return;const{player:a,trackIndex:r,clipIndex:n}=i,o=this.getResolvedClip(r,n);if(!o)return;const l=structuredClone(o),c=a.calculateMoveOffset(e,s),f=structuredClone(l);f.offset=c,this.setUpdatedClip(a,l,f)}setExportMode(e){this.isExporting=e}isInExportMode(){return this.isExporting}setCanvas(e){this.canvas=e}getCanvas(){return this.canvas}getCanvasZoom(){return this.canvas?.getZoom()??1}getViewportContainer(){if(!this.canvas)throw new Error("Canvas not attached. Viewport container requires Canvas.");return this.canvas.getViewportContainer()}setOutputSize(e,s){const i=new Ek(e,s);return this.executeCommand(i)}setOutputFps(e){const s=new Fk(e);return this.executeCommand(s)}getOutputFps(){return this.outputSettings.getFps()}setOutputFormat(e){const s=new _k(e);return this.executeCommand(s)}getOutputFormat(){return this.outputSettings.getFormat()}setOutputDestinations(e){const s=new Ik(e);return this.executeCommand(s)}getOutputDestinations(){return this.outputSettings.getDestinations()}setOutputResolution(e){const s=new Tk(e);return this.executeCommand(s)}getOutputResolution(){return this.outputSettings.getResolution()}setOutputAspectRatio(e){const s=new Vk(e);return this.executeCommand(s)}getOutputAspectRatio(){return this.outputSettings.getAspectRatio()}getTimelineFonts(){return this.document.getFonts()}getFontMetadata(){return this.fontMetadata}getFontUrlByFamilyAndWeight(e,s){const{baseFontFamily:i}=Dt(e),a=i.toLowerCase();for(const[r,n]of this.fontMetadata)if(n.baseFamilyName.toLowerCase()===a&&n.weight===s)return r;for(const[r,n]of this.fontMetadata)if(n.baseFamilyName.toLowerCase()===a)return r;return null}pruneUnusedFonts(){this.cleanupUnusedFonts()}setTimelineBackground(e){const s=new Pk(e);return this.executeCommand(s)}setTimelineBackgroundInternal(e){pw.parse(e),this.backgroundColor=e,this.document.setBackground(e),this.internalEvents.emit(ot.ViewportSizeChanged,{width:this.size.width,height:this.size.height,backgroundColor:this.backgroundColor}),this.internalEvents.emit(fe.TimelineBackgroundChanged,{color:e})}getTimelineBackground(){return this.backgroundColor}resolveMergeFields(e){return this.mergeFieldService.resolve(e)}getTemplateClip(e,s){const i=this.getPlayerClip(e,s);if(!i)return null;const a=i.getExportableClip();if(!a)return null;const{clipId:r}=i;if(r&&this.document){const n=this.document.getClipBindings(r);if(n)for(const[o,{placeholder:l}]of n)ps(a,o,l)}return a}getTemplateClipById(e){const s=this.getPlayerByClipId(e);if(!s)return null;const i=s.getExportableClip();if(!i||!this.document)return null;const a=this.document.getClipBindings(e);if(a)for(const[r,{placeholder:n}]of a)ps(i,r,n);return i}getTemplateClipText(e,s){const i=this.getTemplateClip(e,s);return i?i.asset?.text??null:null}getLumaClipIdForContent(e){for(const[s,i]of this.lumaContentRelations)if(i===e)return s;return null}getContentClipIdForLuma(e){return this.lumaContentRelations.get(e)??null}setLumaContentRelationship(e,s){this.lumaContentRelations.set(e,s)}clearLumaContentRelationship(e){this.lumaContentRelations.delete(e)}getLumaContentRelationship(e){return this.lumaContentRelations.get(e)}normalizeLumaAttachments(){let e=!1;for(let s=0;s<this.tracks.length;s+=1){const i=this.tracks[s];for(const a of i)if(a.playerType===Qe.Luma){const r=this.findBestContentMatch(s,a);if(r){a.clipId&&r.clipId&&this.lumaContentRelations.set(a.clipId,r.clipId);const n=i.indexOf(a);this.document.updateClip(s,n,{start:r.getStart(),length:r.getLength()}),e=!0}}}e&&this.resolve()}findBestContentMatch(e,s){const i=this.tracks[e],a=s.getStart(),r=a+s.getLength();let n=null,o=0;for(const l of i)if(l.playerType!==Qe.Luma){const c=l.getStart(),f=c+l.getLength(),h=qk(a,r,c,f);h>o&&(o=h,n=l)}return n}setupIntentListeners(){this.internalEvents.on(ot.CanvasClipClicked,e=>{this.selectPlayer(e.player)}),this.internalEvents.on(ot.CanvasBackgroundClicked,()=>{this.clearSelection()})}getTracks(){return this.tracks}getTrackCount(){return this.document.getTrackCount()}getClipCountInTrack(e){return this.document.getClipCountInTrack(e)}}class H0{constructor(e,s,i,a,r,n){this.clipId=e,this.propertyPath=s,this.fieldName=i,this.previousFieldName=a,this.storedPreviousValue=r,this.storedNewValue=n}name="setMergeField";storedPreviousValue;storedNewValue;storedPreviousBinding;updateDocumentClip(e,s,i){const a=e.getDocument();if(!a)return;const r=a.getClipById(this.clipId);if(!r)return;const n=r.clip;if(i)ps(n,this.propertyPath,s);else{const l=(typeof s=="string"?s.trim():"").length>0?Number(s):NaN;ps(n,this.propertyPath,Number.isFinite(l)?l:s)}}async execute(e){if(!e)throw new Error("SetMergeFieldCommand.execute: context is required");const s=e.getMergeFields();if(this.storedPreviousBinding=e.getClipBinding(this.clipId,this.propertyPath),this.fieldName){const i={placeholder:s.createTemplate(this.fieldName),resolvedValue:this.storedNewValue};e.setClipBinding(this.clipId,this.propertyPath,i)}else e.removeClipBinding(this.clipId,this.propertyPath);if(this.fieldName?s.register({name:this.fieldName,defaultValue:this.storedNewValue},{silent:!0}):this.previousFieldName&&s.remove(this.previousFieldName,{silent:!0}),this.fieldName){const i=s.createTemplate(this.fieldName);this.updateDocumentClip(e,i,!0)}else this.updateDocumentClip(e,this.storedNewValue,!1);return e.resolve(),e.emitEvent(fe.MergeFieldChanged,{fields:s.getAll()}),Ee()}async undo(e){if(!e)throw new Error("SetMergeFieldCommand.undo: context is required");const s=e.getMergeFields();return this.storedPreviousBinding?e.setClipBinding(this.clipId,this.propertyPath,this.storedPreviousBinding):e.removeClipBinding(this.clipId,this.propertyPath),this.previousFieldName&&s.register({name:this.previousFieldName,defaultValue:this.storedPreviousValue},{silent:!0}),this.storedPreviousBinding?this.updateDocumentClip(e,this.storedPreviousBinding.placeholder,!0):this.updateDocumentClip(e,this.storedPreviousValue,!1),e.resolve(),e.emitEvent(fe.MergeFieldChanged,{fields:s.getAll()}),Ee()}dispose(){this.storedPreviousBinding=void 0}}function rN(t){if(typeof t!="object"||t===null)return!1;const e=t;return e.type==="text"&&(!e.text||e.text.trim()==="")}function j0(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function nN(t){const e=t.width??100,s=t.height??100,i=j0(t.background?.color??"#000000"),a=t.background?.opacity??1,r=t.background?.borderRadius??0,n=[`width="${e}"`,`height="${s}"`,`fill="${i}"`];if(a!==1&&n.push(`fill-opacity="${a}"`),r>0&&n.push(`rx="${r}"`,`ry="${r}"`),t.stroke?.width&&t.stroke.width>0){const o=j0(t.stroke.color??"#000000");n.push(`stroke="${o}"`),n.push(`stroke-width="${t.stroke.width}"`)}return`<svg viewBox="0 0 ${e} ${s}" xmlns="http://www.w3.org/2000/svg"><rect ${n.join(" ")}/></svg>`}function oN(t){const e=t.asset,s=nN(e),i={...t,asset:{type:"svg",src:s,opacity:1}};return e.width!==void 0&&i.width===void 0&&(i.width=e.width),e.height!==void 0&&i.height===void 0&&(i.height=e.height),i}class lN extends Si{isUpdatingMergeFields=!1;get mergeFields(){return this.mergeFieldService}applyMergeField(e,s,i,a,r){const n=this.getResolvedClipById(e),o=n?Rr(n,s):null,l=r??(o!=null?String(o):""),c=this.getTemplateClipById(e),f=c?Rr(c,s):null,h=typeof f=="string"?this.mergeFieldService.extractFieldName(f):null,d=new H0(e,s,i,h,l,a);return this.executeCommand(d)}removeMergeField(e,s,i){const a=this.getMergeFieldForProperty(e,s);if(!a)return Promise.resolve();const r=new H0(e,s,null,a,i,i);return this.executeCommand(r)}getMergeFieldForProperty(e,s){const i=this.getTemplateClipById(e);if(!i)return null;const a=Rr(i,s);return typeof a=="string"?this.mergeFieldService.extractFieldName(a):null}updateMergeFieldValueLive(e,s){if(!this.isUpdatingMergeFields){this.isUpdatingMergeFields=!0;try{const i=this.mergeFieldService.get(e);if(!i)return;this.mergeFieldService.register({...i,defaultValue:s},{silent:!0});for(const[,a]of this.getPlayerMap())this.updateMergeFieldBindings(a,e,s);this.resolve(),this.getInternalEvents().emit(fe.TimelineUpdated,{current:this.getEdit()})}finally{this.isUpdatingMergeFields=!1}}}isSrcMergeField(e){for(const[s,i]of this.getPlayerMap())if(i.clipId){const a=this.getTemplateClipById(s);if(a){const r=a.asset?.type;if(r==="image"||r==="video"||r==="audio"){const o=this.getMergeFieldUsage(a,e);if(o.used&&o.isSrcField)return!0}}}return!1}validateMergeFieldValue(e,s){const i=this.getDocument();if(!i)return null;const a=this.mergeFieldService.get(e);if(!a)return null;const r=a.defaultValue;this.mergeFieldService.register({...a,defaultValue:s},{silent:!0});try{for(const n of i.getClipIdsWithBindings()){const o=i.getClipBindings(n);if(o&&this.clipUsesField(o,e)){const l=i.getClipById(n);if(l){const c=structuredClone(l.clip);for(const[h,d]of o){const y=this.mergeFieldService.resolve(d.placeholder);ps(c,h,y)}delete c.id;const f=Wa.safeParse(c);if(!f.success)return f.error.issues[0]?.message??"Invalid value"}}}return null}finally{this.mergeFieldService.register({...a,defaultValue:r},{silent:!0})}}isValueCompatibleWithClipProperty(e,s,i){const a=this.getResolvedClipById(e);if(!a)return!0;const r=structuredClone(a);return ps(r,s,i),delete r.id,Wa.safeParse(r).success}clipUsesField(e,s){for(const[,i]of e)if(this.mergeFieldService.extractFieldName(i.placeholder)===s)return!0;return!1}async deleteMergeFieldGlobally(e){const s=this.mergeFieldService.get(e);if(!s)return;const i=this.mergeFieldService.createTemplate(e),a=s.defaultValue;for(const[n]of this.getPlayerMap()){const o=this.getTemplateClipById(n);o&&await this.restoreMergeFieldInClip(n,o,i,a)}this.mergeFieldService.remove(e)||this.getInternalEvents().emit(fe.MergeFieldChanged,{fields:this.mergeFieldService.getAll()})}async convertAllTextAssets(){const e=this.getDocument();if(!e)return console.error("No document available for conversion"),{richText:0,svg:0};const s=JSON.parse(JSON.stringify(e.toJSON()));let i=0,a=0;const r=s.timeline?.tracks;if(r){for(const n of r)if(n.clips)for(let o=0;o<n.clips.length;o+=1){const l=n.clips[o],c=l.asset;c?.type==="text"&&(rN(c)?(n.clips[o]=oN(l),a+=1):(n.clips[o]=this.convertTextClipToRichText(l),i+=1))}}return console.log("CONVERTED TEMPLATE - Copy the JSON below:"),console.log(JSON.stringify(s,null," ")),{richText:i,svg:a}}mapVerticalAlign(e){return e==="center"?"middle":e==="top"||e==="bottom"?e:"middle"}convertTextClipToRichText(e){const s=e.asset,i=s.font?.family??"Open Sans",{fontWeight:a}=Dt(i),r={family:i,size:typeof s.font?.size=="string"?Number(s.font.size):s.font?.size??32,weight:s.font?.weight??a,color:s.font?.color??"#ffffff",opacity:s.font?.opacity??1};s.stroke?.width&&s.stroke.width>0&&(r.stroke={width:s.stroke.width,color:s.stroke.color??"#000000",opacity:1});const n={letterSpacing:0,wordSpacing:0,lineHeight:s.font?.lineHeight??1.2,textTransform:"none",textDecoration:"none"},o={type:"rich-text",text:s.text??"",font:r,style:n,align:{horizontal:s.alignment?.horizontal??"center",vertical:this.mapVerticalAlign(s.alignment?.vertical)}};s.background&&(o.background={color:s.background.color,opacity:s.background.opacity??1,borderRadius:s.background.borderRadius??0},s.background.padding&&(o.padding=s.background.padding)),s.animation&&(o.animation={preset:s.animation.preset,duration:s.animation.duration}),s.ellipsis!==void 0&&console.warn("TextAsset ellipsis property not supported in RichTextAsset, value dropped");const l={...e,asset:o};return s.width!==void 0&&l.width===void 0&&(l.width=s.width),s.height!==void 0&&l.height===void 0&&(l.height=s.height),l}updateMergeFieldBindings(e,s,i){if(!e)return;const{clipId:a}=e;if(!a)return;const r=this.getDocument();if(!r)return;const n=r.getClipBindings(a);if(!n)return;const o=r.getClipById(a);for(const[l,c]of n)if(this.mergeFieldService.extractFieldName(c.placeholder)===s){const h=this.mergeFieldService.resolve(c.placeholder),d={placeholder:c.placeholder,resolvedValue:h};if(r.setClipBinding(a,l,d),o){const m=(typeof h=="string"?h.trim():"").length>0?Number(h):NaN,C=Number.isFinite(m)?m:h;ps(o.clip,l,C)}}}getMergeFieldUsage(e,s,i=""){if(!e||typeof e!="object")return{used:!1,isSrcField:!1};for(const[a,r]of Object.entries(e)){const n=i?`${i}.${a}`:a;if(typeof r=="string"){if(this.mergeFieldService.extractFieldName(r)===s)return{used:!0,isSrcField:n==="asset.src"||n.endsWith(".src")}}else if(typeof r=="object"&&r!==null){const o=this.getMergeFieldUsage(r,s,n);if(o.used)return o}}return{used:!1,isSrcField:!1}}async restoreMergeFieldInClip(e,s,i,a,r=""){if(!(!s||typeof s!="object"))for(const n of Object.keys(s)){const o=s[n],l=r?`${r}.${n}`:n;if(typeof o=="string"){const c=this.mergeFieldService.extractFieldName(o),f=this.mergeFieldService.extractFieldName(i);if(c&&f&&c===f){const h=o.replace(new RegExp(`\\{\\{\\s*${c}\\s*\\}\\}`,"gi"),a);await this.removeMergeField(e,l,h)}}else typeof o=="object"&&o!==null&&await this.restoreMergeFieldInClip(e,o,i,a,l)}}}const Br=Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"}));var cN=fc({"node_modules/.pnpm/harfbuzzjs@0.4.12/node_modules/harfbuzzjs/hb.js"(t,e){var s=(()=>{var i=typeof document<"u"?document.currentScript?.src:void 0;return async function(a={}){var r,n=a,o=typeof window=="object",l=typeof WorkerGlobalScope<"u",c=typeof process=="object"&&process.versions?.node&&process.type!="renderer",f=(S,se)=>{throw se};typeof __filename<"u"?i=__filename:l&&(i=self.location.href);var h="";function d(S){return n.locateFile?n.locateFile(S,h):h+S}var y,m;if(c){var C=vw("fs");h=__dirname+"/",m=S=>{S=T(S)?new URL(S):S;var se=C.readFileSync(S);return se},y=async(S,se=!0)=>{S=T(S)?new URL(S):S;var _e=C.readFileSync(S,se?void 0:"utf8");return _e},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),f=(S,se)=>{throw process.exitCode=S,se}}else if(o||l){try{h=new URL(".",i).href}catch{}l&&(m=S=>{var se=new XMLHttpRequest;return se.open("GET",S,!1),se.responseType="arraybuffer",se.send(null),new Uint8Array(se.response)}),y=async S=>{if(T(S))return new Promise((_e,De)=>{var Ue=new XMLHttpRequest;Ue.open("GET",S,!0),Ue.responseType="arraybuffer",Ue.onload=()=>{if(Ue.status==200||Ue.status==0&&Ue.response){_e(Ue.response);return}De(Ue.status)},Ue.onerror=De,Ue.send(null)});var se=await fetch(S,{credentials:"same-origin"});if(se.ok)return se.arrayBuffer();throw new Error(se.status+" : "+se.url)}}console.log.bind(console);var E=console.error.bind(console),F,N=!1,w,T=S=>S.startsWith("file://"),b,U,D,B,J=!1;function ee(){var S=D.buffer;n.HEAP8=new Int8Array(S),n.HEAPU8=B=new Uint8Array(S),n.HEAP32=new Int32Array(S),n.HEAPU32=new Uint32Array(S),n.HEAPF32=new Float32Array(S),new BigInt64Array(S),new BigUint64Array(S)}function te(){if(n.preRun)for(typeof n.preRun=="function"&&(n.preRun=[n.preRun]);n.preRun.length;)$(n.preRun.shift());H(O)}function he(){J=!0,Yt.__wasm_call_ctors()}function re(){if(n.postRun)for(typeof n.postRun=="function"&&(n.postRun=[n.postRun]);n.postRun.length;)M(n.postRun.shift());H(R)}var Se=0,ke=null;function Fe(S){Se++,n.monitorRunDependencies?.(Se)}function be(S){if(Se--,n.monitorRunDependencies?.(Se),Se==0&&ke){var se=ke;ke=null,se()}}function G(S){n.onAbort?.(S),S="Aborted("+S+")",E(S),N=!0,S+=". Build with -sASSERTIONS for more info.";var se=new WebAssembly.RuntimeError(S);throw U?.(se),se}var Y;function W(){return d("hb.wasm")}function me(S){if(S==Y&&F)return new Uint8Array(F);if(m)return m(S);throw"both async and sync fetching of the wasm failed"}async function pe(S){if(!F)try{var se=await y(S);return new Uint8Array(se)}catch{}return me(S)}async function Pe(S,se){try{var _e=await pe(S),De=await WebAssembly.instantiate(_e,se);return De}catch(Ue){E(`failed to asynchronously prepare wasm: ${Ue}`),G(Ue)}}async function Ze(S,se,_e){if(!S&&!T(se)&&!c)try{var De=fetch(se,{credentials:"same-origin"}),Ue=await WebAssembly.instantiateStreaming(De,_e);return Ue}catch(ht){E(`wasm streaming compile failed: ${ht}`),E("falling back to ArrayBuffer instantiation")}return Pe(se,_e)}function Me(){return{env:_i,wasi_snapshot_preview1:_i}}async function Te(){function S(ht,Ti){return Yt=ht.exports,n.wasmExports=Yt,D=Yt.memory,n.wasmMemory=D,ee(),bs=Yt.__indirect_function_table,Kr(Yt),be(),Yt}Fe();function se(ht){return S(ht.instance)}var _e=Me();if(n.instantiateWasm)return new Promise((ht,Ti)=>{n.instantiateWasm(_e,(Xr,Ro)=>{ht(S(Xr))})});Y??(Y=W());var De=await Ze(F,Y,_e),Ue=se(De);return Ue}class ft{constructor(se){bt(this,"name","ExitStatus"),this.message=`Program terminated with exit(${se})`,this.status=se}}var H=S=>{for(;S.length>0;)S.shift()(n)},R=[],M=S=>R.push(S),O=[],$=S=>O.push(S),oe=!0,ie=()=>G(""),ne=0,ye=()=>{oe=!1,ne=0},ae={},q=S=>{if(S instanceof ft||S=="unwind")return w;f(1,S)},ve=()=>oe||ne>0,Je=S=>{w=S,ve()||(n.onExit?.(S),N=!0),f(S,new ft(S))},gt=(S,se)=>{w=S,Je(S)},Ye=gt,at=()=>{if(!ve())try{Ye(w)}catch(S){q(S)}},rt=S=>{if(!N)try{S(),at()}catch(se){q(se)}},vt=()=>performance.now(),_t=(S,se)=>{if(ae[S]&&(clearTimeout(ae[S].id),delete ae[S]),!se)return 0;var _e=setTimeout(()=>{delete ae[S],rt(()=>ya(S,vt()))},se);return ae[S]={id:_e,timeout_ms:se},0},Ne=()=>2147483648,Mo=(S,se)=>Math.ceil(S/se)*se,Vi=S=>{var se=D.buffer.byteLength,_e=(S-se+65535)/65536|0;try{return D.grow(_e),ee(),1}catch{}},ut=S=>{var se=B.length;S>>>=0;var _e=Ne();if(S>_e)return!1;for(var De=1;De<=4;De*=2){var Ue=se*(1+.2/De);Ue=Math.min(Ue,S+100663296);var ht=Math.min(_e,Mo(Math.max(S,Ue),65536)),Ti=Vi(ht);if(Ti)return!0}return!1},ma=S=>{const se=S.length;return[se%128|128,se>>7,...S]},Lt={i:127,p:127,j:126,f:125,d:124,e:111},Wt=S=>ma(Array.from(S,se=>{var _e=Lt[se];return _e})),Pt=(S,se)=>{var _e=Uint8Array.of(0,97,115,109,1,0,0,0,1,...ma([1,96,...Wt(se.slice(1)),...Wt(se[0]==="v"?"":se[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0),De=new WebAssembly.Module(_e),Ue=new WebAssembly.Instance(De,{e:{f:S}}),ht=Ue.exports.f;return ht},bs,si=S=>bs.get(S),Rs=(S,se)=>{if(Ot)for(var _e=S;_e<S+se;_e++){var De=si(_e);De&&Ot.set(De,_e)}},Ot,Wr=S=>(Ot||(Ot=new WeakMap,Rs(0,bs.length)),Ot.get(S)||0),Ii=[],Yr=()=>Ii.length?Ii.pop():bs.grow(1),zs=(S,se)=>bs.set(S,se),Hr=(S,se)=>{var _e=Wr(S);if(_e)return _e;var De=Yr();try{zs(De,S)}catch(ht){if(!(ht instanceof TypeError))throw ht;var Ue=Pt(S,se);zs(De,Ue)}return Ot.set(S,De),De},jr=S=>{Ot.delete(si(S)),zs(S,null),Ii.push(S)};n.noExitRuntime&&(oe=n.noExitRuntime),n.print&&n.print,n.printErr&&(E=n.printErr),n.wasmBinary&&(F=n.wasmBinary),n.arguments&&n.arguments,n.thisProgram&&n.thisProgram,n.wasmMemory=D,n.wasmExports=Yt,n.addFunction=Hr,n.removeFunction=jr;var ya;function Kr(S){n._hb_blob_create=S.hb_blob_create,n._hb_blob_destroy=S.hb_blob_destroy,n._hb_blob_get_length=S.hb_blob_get_length,n._hb_blob_get_data=S.hb_blob_get_data,n._hb_buffer_serialize_glyphs=S.hb_buffer_serialize_glyphs,n._hb_buffer_create=S.hb_buffer_create,n._hb_buffer_destroy=S.hb_buffer_destroy,n._hb_buffer_get_content_type=S.hb_buffer_get_content_type,n._hb_buffer_set_direction=S.hb_buffer_set_direction,n._hb_buffer_set_script=S.hb_buffer_set_script,n._hb_buffer_set_language=S.hb_buffer_set_language,n._hb_buffer_set_flags=S.hb_buffer_set_flags,n._hb_buffer_set_cluster_level=S.hb_buffer_set_cluster_level,n._hb_buffer_get_length=S.hb_buffer_get_length,n._hb_buffer_get_glyph_infos=S.hb_buffer_get_glyph_infos,n._hb_buffer_get_glyph_positions=S.hb_buffer_get_glyph_positions,n._hb_glyph_info_get_glyph_flags=S.hb_glyph_info_get_glyph_flags,n._hb_buffer_guess_segment_properties=S.hb_buffer_guess_segment_properties,n._hb_buffer_add_utf8=S.hb_buffer_add_utf8,n._hb_buffer_add_utf16=S.hb_buffer_add_utf16,n._hb_buffer_set_message_func=S.hb_buffer_set_message_func,n._hb_language_from_string=S.hb_language_from_string,n._hb_script_from_string=S.hb_script_from_string,n._hb_version=S.hb_version,n._hb_version_string=S.hb_version_string,n._hb_feature_from_string=S.hb_feature_from_string,n._malloc=S.malloc,n._free=S.free,n._hb_draw_funcs_set_move_to_func=S.hb_draw_funcs_set_move_to_func,n._hb_draw_funcs_set_line_to_func=S.hb_draw_funcs_set_line_to_func,n._hb_draw_funcs_set_quadratic_to_func=S.hb_draw_funcs_set_quadratic_to_func,n._hb_draw_funcs_set_cubic_to_func=S.hb_draw_funcs_set_cubic_to_func,n._hb_draw_funcs_set_close_path_func=S.hb_draw_funcs_set_close_path_func,n._hb_draw_funcs_create=S.hb_draw_funcs_create,n._hb_draw_funcs_destroy=S.hb_draw_funcs_destroy,n._hb_face_create=S.hb_face_create,n._hb_face_destroy=S.hb_face_destroy,n._hb_face_reference_table=S.hb_face_reference_table,n._hb_face_get_upem=S.hb_face_get_upem,n._hb_face_collect_unicodes=S.hb_face_collect_unicodes,n._hb_font_draw_glyph=S.hb_font_draw_glyph,n._hb_font_glyph_to_string=S.hb_font_glyph_to_string,n._hb_font_create=S.hb_font_create,n._hb_font_set_variations=S.hb_font_set_variations,n._hb_font_destroy=S.hb_font_destroy,n._hb_font_set_scale=S.hb_font_set_scale,n._hb_set_create=S.hb_set_create,n._hb_set_destroy=S.hb_set_destroy,n._hb_ot_var_get_axis_infos=S.hb_ot_var_get_axis_infos,n._hb_set_get_population=S.hb_set_get_population,n._hb_set_next_many=S.hb_set_next_many,n._hb_shape=S.hb_shape,ya=S._emscripten_timeout}var _i={_abort_js:ie,_emscripten_runtime_keepalive_clear:ye,_setitimer_js:_t,emscripten_resize_heap:ut,proc_exit:Je},Yt=await Te();function Fi(){if(Se>0){ke=Fi;return}if(te(),Se>0){ke=Fi;return}function S(){n.calledRun=!0,!N&&(he(),b?.(n),n.onRuntimeInitialized?.(),re())}n.setStatus?(n.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>n.setStatus(""),1),S()},1)):S()}function ba(){if(n.preInit)for(typeof n.preInit=="function"&&(n.preInit=[n.preInit]);n.preInit.length>0;)n.preInit.shift()()}return ba(),Fi(),J?r=n:r=new Promise((S,se)=>{b=S,U=se}),r}})();typeof t=="object"&&typeof e=="object"?(e.exports=s,e.exports.default=s):typeof define=="function"&&define.amd&&define([],()=>s)}});const fN=cN(),uN=Object.freeze(Object.defineProperty({__proto__:null,default:fN},Symbol.toStringTag,{value:"Module"}));var hN=fc({"node_modules/.pnpm/harfbuzzjs@0.4.12/node_modules/harfbuzzjs/hbjs.js"(t,e){function s(i){var a=i.wasmExports,r=new TextDecoder("utf8");let n=i.addFunction,o=i.removeFunction;var l=n(function(G){a.free(G)},"vi"),c=2,f=-1,h=2,d=0,y=1,m=2;function C(G){return(G.charCodeAt(0)&255)<<24|(G.charCodeAt(1)&255)<<16|(G.charCodeAt(2)&255)<<8|(G.charCodeAt(3)&255)<<0}var E=C("JSON"),F=4;function N(G){return[String.fromCharCode(G>>24&255),String.fromCharCode(G>>16&255),String.fromCharCode(G>>8&255),String.fromCharCode(G>>0&255)].join("")}function w(G){return G=="BOT"?1:G=="EOT"?2:G=="PRESERVE_DEFAULT_IGNORABLES"?4:G=="REMOVE_DEFAULT_IGNORABLES"?8:G=="DO_NOT_INSERT_DOTTED_CIRCLE"?16:G=="PRODUCE_UNSAFE_TO_CONCAT"?64:0}function T(G){var Y=a.malloc(G.byteLength);i.HEAPU8.set(new Uint8Array(G),Y);var W=a.hb_blob_create(Y,G.byteLength,c,Y,l);return{ptr:W,destroy:function(){a.hb_blob_destroy(W)}}}function b(G){const Y=a.hb_set_get_population(G),W=a.malloc(Y<<2),me=W>>2,pe=i.HEAPU32.subarray(me,me+Y);return i.HEAPU32.set(pe,me),a.hb_set_next_many(G,f,W,Y),pe}function U(G,Y){var W=a.hb_face_create(G.ptr,Y);const me=a.hb_face_get_upem(W);return{ptr:W,upem:me,reference_table:function(pe){var Pe=a.hb_face_reference_table(W,C(pe)),Ze=a.hb_blob_get_length(Pe);if(Ze){var Me=a.hb_blob_get_data(Pe,null),Te=i.HEAPU8.subarray(Me,Me+Ze);return Te}},getAxisInfos:function(){var pe=a.malloc(2048),Pe=a.malloc(4);i.HEAPU32[Pe/4]=64,a.hb_ot_var_get_axis_infos(W,0,Pe,pe);var Ze={};return Array.from({length:i.HEAPU32[Pe/4]}).forEach(function(Me,Te){Ze[N(i.HEAPU32[pe/4+Te*8+1])]={min:i.HEAPF32[pe/4+Te*8+4],default:i.HEAPF32[pe/4+Te*8+5],max:i.HEAPF32[pe/4+Te*8+6]}}),a.free(Pe),a.free(pe),Ze},collectUnicodes:function(){var pe=a.hb_set_create();a.hb_face_collect_unicodes(W,pe);var Pe=b(pe);return a.hb_set_destroy(pe),Pe},destroy:function(){a.hb_face_destroy(W)}}}var D="",B=256,J=a.malloc(B);function ee(G){var Y=a.hb_font_create(G.ptr),W=null,me=null,pe=null,Pe=null,Ze=null,Me=null;function Te(H){if(!W){var R=function(ie,ne,ye,ae,q,ve){D+=`M${ae},${q}`},M=function(ie,ne,ye,ae,q,ve){D+=`L${ae},${q}`},O=function(ie,ne,ye,ae,q,ve,Je,gt,Ye,at){D+=`C${ae},${q} ${ve},${Je} ${gt},${Ye}`},$=function(ie,ne,ye,ae,q,ve,Je,gt){D+=`Q${ae},${q} ${ve},${Je}`},oe=function(ie,ne,ye,ae){D+="Z"};me=n(R,"viiiffi"),pe=n(M,"viiiffi"),Pe=n(O,"viiiffffffi"),Ze=n($,"viiiffffi"),Me=n(oe,"viiii"),W=a.hb_draw_funcs_create(),a.hb_draw_funcs_set_move_to_func(W,me,0,0),a.hb_draw_funcs_set_line_to_func(W,pe,0,0),a.hb_draw_funcs_set_cubic_to_func(W,Pe,0,0),a.hb_draw_funcs_set_quadratic_to_func(W,Ze,0,0),a.hb_draw_funcs_set_close_path_func(W,Me,0,0)}return D="",a.hb_font_draw_glyph(Y,H,W,0),D}function ft(H){a.hb_font_glyph_to_string(Y,H,J,B);var R=i.HEAPU8.subarray(J,J+B);return r.decode(R.slice(0,R.indexOf(0)))}return{ptr:Y,glyphName:ft,glyphToPath:Te,glyphToJson:function(H){var R=Te(H);return R.replace(/([MLQCZ])/g,"|$1 ").split("|").filter(function(M){return M.length}).map(function(M){var O=M.split(/[ ,]/g);return{type:O[0],values:O.slice(1).filter(function($){return $.length}).map(function($){return+$})}})},setScale:function(H,R){a.hb_font_set_scale(Y,H,R)},setVariations:function(H){var R=Object.entries(H),M=a.malloc(8*R.length);R.forEach(function(O,$){i.HEAPU32[M/4+$*2+0]=C(O[0]),i.HEAPF32[M/4+$*2+1]=O[1]}),a.hb_font_set_variations(Y,M,R.length),a.free(M)},destroy:function(){a.hb_font_destroy(Y),W&&(a.hb_draw_funcs_destroy(W),W=null,o(me),o(pe),o(Pe),o(Ze),o(Me))}}}function te(G){var Y=a.malloc(G.length+1);for(let W=0;W<G.length;++W){const me=G.charCodeAt(W);if(me>127)throw new Error("Expected ASCII text");i.HEAPU8[Y+W]=me}return i.HEAPU8[Y+G.length]=0,{ptr:Y,length:G.length,free:function(){a.free(Y)}}}function he(G){const Y=a.malloc(G.length*2),W=new Uint16Array(i.wasmMemory.buffer,Y,G.length);for(let me=0;me<W.length;++me)W[me]=G.charCodeAt(me);return{ptr:Y,length:W.length,free:function(){a.free(Y)}}}function re(){var G=a.hb_buffer_create();return{ptr:G,addText:function(Y){const W=he(Y);a.hb_buffer_add_utf16(G,W.ptr,W.length,0,W.length),W.free()},guessSegmentProperties:function(){return a.hb_buffer_guess_segment_properties(G)},setDirection:function(Y){a.hb_buffer_set_direction(G,{ltr:4,rtl:5,ttb:6,btt:7}[Y]||0)},setFlags:function(Y){var W=0;Y.forEach(function(me){W|=w(me)}),a.hb_buffer_set_flags(G,W)},setLanguage:function(Y){var W=te(Y);a.hb_buffer_set_language(G,a.hb_language_from_string(W.ptr,-1)),W.free()},setScript:function(Y){var W=te(Y);a.hb_buffer_set_script(G,a.hb_script_from_string(W.ptr,-1)),W.free()},setClusterLevel:function(Y){a.hb_buffer_set_cluster_level(G,Y)},json:function(){for(var Y=a.hb_buffer_get_length(G),W=[],me=a.hb_buffer_get_glyph_infos(G,0),pe=me/4,Pe=a.hb_buffer_get_glyph_positions(G,0)/4,Ze=i.HEAPU32.subarray(pe,pe+5*Y),Me=i.HEAP32.subarray(Pe,Pe+5*Y),Te=0;Te<Y;++Te)W.push({g:Ze[Te*5+0],cl:Ze[Te*5+2],ax:Me[Te*5+0],ay:Me[Te*5+1],dx:Me[Te*5+2],dy:Me[Te*5+3],flags:a.hb_glyph_info_get_glyph_flags(me+Te*20)});return W},destroy:function(){a.hb_buffer_destroy(G)}}}function Se(G,Y,W){var me=0,pe=0;W&&(W=W.split(","),me=a.malloc(16*W.length),W.forEach(function(Pe,Ze){var Me=te(Pe);a.hb_feature_from_string(Me.ptr,-1,me+pe*16)&&pe++,Me.free()})),a.hb_shape(G.ptr,Y.ptr,me,pe),me&&a.free(me)}function ke(G,Y,W,me,pe){var Pe=[],Ze=d,Me=!1,Te=1024*1024,ft=a.malloc(Te),H=function(M,O,$,oe){var ie=r.decode(i.HEAPU8.subarray($,i.HEAPU8.indexOf(0,$)));return ie.startsWith("start table GSUB")?Ze=y:ie.startsWith("start table GPOS")&&(Ze=m),Ze!=pe&&(Me=!1),pe!=d&&Ze==pe&&ie.startsWith("end lookup "+me)&&(Me=!0),Me?0:(a.hb_buffer_serialize_glyphs(M,0,a.hb_buffer_get_length(M),ft,Te,0,O,E,F),Pe.push({m:ie,t:JSON.parse(r.decode(i.HEAPU8.subarray(ft,i.HEAPU8.indexOf(0,ft)))),glyphs:a.hb_buffer_get_content_type(M)==h}),1)},R=n(H,"iiiii");return a.hb_buffer_set_message_func(Y.ptr,R,0,0),Se(G,Y,W),a.free(ft),o(R),Pe}function Fe(){var G=a.malloc(12);a.hb_version(G,G+4,G+8);var Y={major:i.HEAPU32[G/4],minor:i.HEAPU32[(G+4)/4],micro:i.HEAPU32[(G+8)/4]};return a.free(G),Y}function be(){var G=a.hb_version_string(),Y=r.decode(i.HEAPU8.subarray(G,i.HEAPU8.indexOf(0,G)));return Y}return{createBlob:T,createFace:U,createFont:ee,createBuffer:re,shape:Se,shapeWithTrace:ke,version:Fe,version_string:be}}try{e.exports=s}catch{}}});const dN=hN(),gN=Object.freeze(Object.defineProperty({__proto__:null,default:dN},Symbol.toStringTag,{value:"Module"}));var ce,ms=new Array(128).fill(void 0);ms.push(void 0,null,!0,!1);var ha=ms.length;function It(t){ha===ms.length&&ms.push(ms.length+1);const e=ha;return ha=ms[e],ms[e]=t,e}function Nt(t){return ms[t]}function pN(t){t<132||(ms[t]=ha,ha=t)}function ys(t){const e=Nt(t);return pN(t),e}var da=0,ga=null;function Zr(){return(ga===null||ga.byteLength===0)&&(ga=new Uint8Array(ce.memory.buffer)),ga}var Ur=typeof TextEncoder<"u"?new TextEncoder("utf-8"):{encode:()=>{throw Error("TextEncoder not available")}},mN=typeof Ur.encodeInto=="function"?function(t,e){return Ur.encodeInto(t,e)}:function(t,e){const s=Ur.encode(t);return e.set(s),{read:t.length,written:s.length}};function To(t,e,s){if(s===void 0){const o=Ur.encode(t),l=e(o.length,1)>>>0;return Zr().subarray(l,l+o.length).set(o),da=o.length,l}let i=t.length,a=e(i,1)>>>0;const r=Zr();let n=0;for(;n<i;n++){const o=t.charCodeAt(n);if(o>127)break;r[a+n]=o}if(n!==i){n!==0&&(t=t.slice(n)),a=s(a,i,i=n+t.length*3,1)>>>0;const o=Zr().subarray(a+n,a+i),l=mN(t,o);n+=l.written,a=s(a,i,n,1)>>>0}return da=n,a}function Eo(t){return t==null}var pa=null;function dt(){return(pa===null||pa.byteLength===0)&&(pa=new Int32Array(ce.memory.buffer)),pa}var K0=typeof TextDecoder<"u"?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}};typeof TextDecoder<"u"&&K0.decode();function Gr(t,e){return t=t>>>0,K0.decode(Zr().subarray(t,t+e))}function yN(t,e){if(!(t instanceof e))throw new Error(`expected instance of ${e.name}`);return t.ptr}function bN(t,e){try{return t.apply(this,e)}catch(s){ce.__wbindgen_exn_store(It(s))}}var X0=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(t=>ce.__wbg_bbox_free(t>>>0)),Po=class iu{static __wrap(e){e=e>>>0;const s=Object.create(iu.prototype);return s.__wbg_ptr=e,X0.register(s,s.__wbg_ptr,s),s}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,X0.unregister(this),e}free(){const e=this.__destroy_into_raw();ce.__wbg_bbox_free(e)}get x(){return ce.__wbg_get_bbox_x(this.__wbg_ptr)}set x(e){ce.__wbg_set_bbox_x(this.__wbg_ptr,e)}get y(){return ce.__wbg_get_bbox_y(this.__wbg_ptr)}set y(e){ce.__wbg_set_bbox_y(this.__wbg_ptr,e)}get width(){return ce.__wbg_get_bbox_width(this.__wbg_ptr)}set width(e){ce.__wbg_set_bbox_width(this.__wbg_ptr,e)}get height(){return ce.__wbg_get_bbox_height(this.__wbg_ptr)}set height(e){ce.__wbg_set_bbox_height(this.__wbg_ptr,e)}},q0=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(t=>ce.__wbg_renderedimage_free(t>>>0)),wN=class au{static __wrap(e){e=e>>>0;const s=Object.create(au.prototype);return s.__wbg_ptr=e,q0.register(s,s.__wbg_ptr,s),s}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,q0.unregister(this),e}free(){const e=this.__destroy_into_raw();ce.__wbg_renderedimage_free(e)}get width(){return ce.renderedimage_width(this.__wbg_ptr)>>>0}get height(){return ce.renderedimage_height(this.__wbg_ptr)>>>0}asPng(){try{const a=ce.__wbindgen_add_to_stack_pointer(-16);ce.renderedimage_asPng(a,this.__wbg_ptr);var e=dt()[a/4+0],s=dt()[a/4+1],i=dt()[a/4+2];if(i)throw ys(s);return ys(e)}finally{ce.__wbindgen_add_to_stack_pointer(16)}}get pixels(){const e=ce.renderedimage_pixels(this.__wbg_ptr);return ys(e)}},vN=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(t=>ce.__wbg_resvg_free(t>>>0)),xN=class{__destroy_into_raw(){const t=this.__wbg_ptr;return this.__wbg_ptr=0,vN.unregister(this),t}free(){const t=this.__destroy_into_raw();ce.__wbg_resvg_free(t)}constructor(t,e,s){try{const l=ce.__wbindgen_add_to_stack_pointer(-16);var i=Eo(e)?0:To(e,ce.__wbindgen_malloc,ce.__wbindgen_realloc),a=da;ce.resvg_new(l,It(t),i,a,Eo(s)?0:It(s));var r=dt()[l/4+0],n=dt()[l/4+1],o=dt()[l/4+2];if(o)throw ys(n);return this.__wbg_ptr=r>>>0,this}finally{ce.__wbindgen_add_to_stack_pointer(16)}}get width(){return ce.resvg_width(this.__wbg_ptr)}get height(){return ce.resvg_height(this.__wbg_ptr)}render(){try{const i=ce.__wbindgen_add_to_stack_pointer(-16);ce.resvg_render(i,this.__wbg_ptr);var t=dt()[i/4+0],e=dt()[i/4+1],s=dt()[i/4+2];if(s)throw ys(e);return wN.__wrap(t)}finally{ce.__wbindgen_add_to_stack_pointer(16)}}toString(){let t,e;try{const a=ce.__wbindgen_add_to_stack_pointer(-16);ce.resvg_toString(a,this.__wbg_ptr);var s=dt()[a/4+0],i=dt()[a/4+1];return t=s,e=i,Gr(s,i)}finally{ce.__wbindgen_add_to_stack_pointer(16),ce.__wbindgen_free(t,e,1)}}innerBBox(){const t=ce.resvg_innerBBox(this.__wbg_ptr);return t===0?void 0:Po.__wrap(t)}getBBox(){const t=ce.resvg_getBBox(this.__wbg_ptr);return t===0?void 0:Po.__wrap(t)}cropByBBox(t){yN(t,Po),ce.resvg_cropByBBox(this.__wbg_ptr,t.__wbg_ptr)}imagesToResolve(){try{const i=ce.__wbindgen_add_to_stack_pointer(-16);ce.resvg_imagesToResolve(i,this.__wbg_ptr);var t=dt()[i/4+0],e=dt()[i/4+1],s=dt()[i/4+2];if(s)throw ys(e);return ys(t)}finally{ce.__wbindgen_add_to_stack_pointer(16)}}resolveImage(t,e){try{const a=ce.__wbindgen_add_to_stack_pointer(-16),r=To(t,ce.__wbindgen_malloc,ce.__wbindgen_realloc),n=da;ce.resvg_resolveImage(a,this.__wbg_ptr,r,n,It(e));var s=dt()[a/4+0],i=dt()[a/4+1];if(i)throw ys(s)}finally{ce.__wbindgen_add_to_stack_pointer(16)}}};async function CN(t,e){if(typeof Response=="function"&&t instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(t,e)}catch(i){if(t.headers.get("Content-Type")!="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",i);else throw i}const s=await t.arrayBuffer();return await WebAssembly.instantiate(s,e)}else{const s=await WebAssembly.instantiate(t,e);return s instanceof WebAssembly.Instance?{instance:s,module:t}:s}}function kN(){const t={};return t.wbg={},t.wbg.__wbg_new_28c511d9baebfa89=function(e,s){const i=new Error(Gr(e,s));return It(i)},t.wbg.__wbindgen_memory=function(){const e=ce.memory;return It(e)},t.wbg.__wbg_buffer_12d079cc21e14bdb=function(e){const s=Nt(e).buffer;return It(s)},t.wbg.__wbg_newwithbyteoffsetandlength_aa4a17c33a06e5cb=function(e,s,i){const a=new Uint8Array(Nt(e),s>>>0,i>>>0);return It(a)},t.wbg.__wbindgen_object_drop_ref=function(e){ys(e)},t.wbg.__wbg_new_63b92bc8671ed464=function(e){const s=new Uint8Array(Nt(e));return It(s)},t.wbg.__wbg_values_839f3396d5aac002=function(e){const s=Nt(e).values();return It(s)},t.wbg.__wbg_next_196c84450b364254=function(){return bN(function(e){const s=Nt(e).next();return It(s)},arguments)},t.wbg.__wbg_done_298b57d23c0fc80c=function(e){return Nt(e).done},t.wbg.__wbg_value_d93c65011f51a456=function(e){const s=Nt(e).value;return It(s)},t.wbg.__wbg_instanceof_Uint8Array_2b3bbecd033d19f6=function(e){let s;try{s=Nt(e)instanceof Uint8Array}catch{s=!1}return s},t.wbg.__wbindgen_string_get=function(e,s){const i=Nt(s),a=typeof i=="string"?i:void 0;var r=Eo(a)?0:To(a,ce.__wbindgen_malloc,ce.__wbindgen_realloc),n=da;dt()[e/4+1]=n,dt()[e/4+0]=r},t.wbg.__wbg_new_16b304a2cfa7ff4a=function(){const e=new Array;return It(e)},t.wbg.__wbindgen_string_new=function(e,s){const i=Gr(e,s);return It(i)},t.wbg.__wbg_push_a5b05aedc7234f9f=function(e,s){return Nt(e).push(Nt(s))},t.wbg.__wbg_length_c20a40f15020d68a=function(e){return Nt(e).length},t.wbg.__wbg_set_a47bac70306a19a7=function(e,s,i){Nt(e).set(Nt(s),i>>>0)},t.wbg.__wbindgen_throw=function(e,s){throw new Error(Gr(e,s))},t}function NN(t,e){return ce=t.exports,J0.__wbindgen_wasm_module=e,pa=null,ga=null,ce}async function J0(t){if(ce!==void 0)return ce;typeof t>"u"&&(t=new URL("index_bg.wasm",void 0));const e=kN();(typeof t=="string"||typeof Request=="function"&&t instanceof Request||typeof URL=="function"&&t instanceof URL)&&(t=fetch(t));const{instance:s,module:i}=await CN(await t,e);return NN(s,i)}var AN=J0,Oo=!1,SN=async t=>{if(Oo)throw new Error("Already initialized. The `initWasm()` function can be used only once.");await AN(await t),Oo=!0},VN=class extends xN{constructor(t,e){if(!Oo)throw new Error("Wasm has not been initialized. Call `initWasm()` function.");const s=e?.font;if(s&&IN(s)){const i={...e,font:{...s,fontBuffers:void 0}};super(t,JSON.stringify(i),s.fontBuffers)}else super(t,JSON.stringify(e))}};function IN(t){return Object.prototype.hasOwnProperty.call(t,"fontBuffers")}const Q0=Object.freeze(Object.defineProperty({__proto__:null,Resvg:VN,initWasm:SN},Symbol.toStringTag,{value:"Module"}));Ht.Edit=Si,Ht.ShotstackEdit=lN,Object.defineProperty(Ht,Symbol.toStringTag,{value:"Module"})});
277
+ `),l=o===-1?this.textPosition:this.textPosition-o-1,c=n.substring(0,l);let f;c.length>0&&c.endsWith(" ")?f=this.measureText(`${c}x`,s)-this.measureText("x",s):f=this.measureText(c,s);const h=s.lineHeight;this.pixelY=this.currentLine*h;const y=this.clipConfig.asset.alignment?.horizontal??"center";let m=f;if(y!=="left"){const C=this.measureText(n,s),E=this.textElement.width;let F=0;y==="center"?F=(E-C)/2:y==="right"&&(F=E-C),m=F+f}this.pixelX=m}updateGraphicsPosition(){this.cursor&&this.cursor.position.set(this.pixelX,this.pixelY)}startBlinkingAnimation(){!this.cursor||this.isBlinking||(this.isBlinking=!0,this.blinkInterval=window.setInterval(()=>{this.cursor&&this.isBlinking&&(this.cursor.visible=!this.cursor.visible)},this.blinkIntervalMs))}stopBlinkingAnimation(){this.blinkInterval!==null&&(window.clearInterval(this.blinkInterval),this.blinkInterval=null),this.isBlinking=!1,this.cursor&&(this.cursor.visible=this.isVisible)}measureText(e,s){const i=new X.Text(e,s),{width:a}=i;return i.destroy(),a}isInitialized(){return this.cursor!==null}getState(){return{isInitialized:this.isInitialized(),isBlinking:this.isBlinking,isVisible:this.isVisible,textPosition:this.textPosition,pixelPosition:{x:this.pixelX,y:this.pixelY},currentLine:this.currentLine}}}class Or{static DEFAULT_FOCUS_DELAY_MS=50;hiddenInput=null;isFocused=!1;focusRetryCount=0;maxFocusRetries=3;focusDelay=Or.DEFAULT_FOCUS_DELAY_MS;eventHandlers={};abortController=null;textChangeCallback=null;lastSyncedText="";isComposing=!1;setupInput(e,s){this.focusDelay=s?.focusDelay??Or.DEFAULT_FOCUS_DELAY_MS,this.createHiddenTextarea(),this.hiddenInput&&(this.hiddenInput.value=e,this.lastSyncedText=e),this.setupEventListeners(),s?.autoFocus!==!1&&this.focusInput()}updateInputValue(e){this.hiddenInput&&(this.hiddenInput.value=e,this.lastSyncedText=e)}focusInput(){this.hiddenInput&&setTimeout(()=>{this.hiddenInput&&!this.isFocused&&(this.hiddenInput.focus(),setTimeout(()=>{!this.isFocused&&this.focusRetryCount<this.maxFocusRetries&&(this.focusRetryCount+=1,this.focusInput())},10))},this.focusDelay)}blurInput(){this.hiddenInput&&this.hiddenInput.blur()}setSelectionRange(e,s){if(!this.hiddenInput)return;const i=this.hiddenInput.value.length,a=Math.max(0,Math.min(e,i)),r=Math.max(a,Math.min(s,i));this.hiddenInput.setSelectionRange(a,r)}getCursorPosition(){return this.hiddenInput?.selectionStart||0}getValue(){return this.hiddenInput?.value||""}setTextInputHandler(e){this.textChangeCallback=e}setEventHandlers(e){this.eventHandlers={...this.eventHandlers,...e}}isFocusedInput(){return this.isFocused}dispose(){this.removeAllEventListeners(),this.hiddenInput&&this.hiddenInput.parentNode&&this.hiddenInput.parentNode.removeChild(this.hiddenInput),this.hiddenInput=null,this.isFocused=!1,this.focusRetryCount=0,this.textChangeCallback=null,this.eventHandlers={}}createHiddenTextarea(){this.hiddenInput=document.createElement("textarea");const e={position:"absolute",opacity:"0.01",pointerEvents:"none",zIndex:"18",left:"0px",top:"0px",width:"1px",height:"1px",border:"none",outline:"none",resize:"none",backgroundColor:"transparent"};Object.assign(this.hiddenInput.style,e),this.hiddenInput.tabIndex=0,document.body.appendChild(this.hiddenInput)}setupEventListeners(){if(!this.hiddenInput)return;this.abortController=new AbortController;const{signal:e}=this.abortController;this.hiddenInput.addEventListener("input",this.handleTextInput,{signal:e}),this.hiddenInput.addEventListener("keydown",this.handleKeyDown,{signal:e}),this.hiddenInput.addEventListener("compositionstart",this.handleCompositionStart,{signal:e}),this.hiddenInput.addEventListener("compositionend",this.handleCompositionEnd,{signal:e}),this.hiddenInput.addEventListener("focus",this.handleFocus,{signal:e}),this.hiddenInput.addEventListener("blur",this.handleBlur,{signal:e}),this.hiddenInput.addEventListener("paste",this.handlePaste,{signal:e})}removeAllEventListeners(){this.abortController?.abort(),this.abortController=null}handleTextInput=e=>{if(!this.hiddenInput||this.isComposing)return;const s=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.lastSyncedText=s,this.textChangeCallback?.(s,i)};handleKeyDown=e=>{if(document.activeElement!==this.hiddenInput)return;let s=!1;if((e.ctrlKey||e.metaKey)&&(s=this.handleKeyboardShortcuts(e),s)){e.preventDefault();return}if(e.key==="Tab"){const i=e.shiftKey?"backward":"forward";this.eventHandlers.onTabNavigation?.(i),e.preventDefault();return}switch(e.key){case"Escape":this.eventHandlers.onEscape?.(e),s=!0;break;case"Enter":s=!1;break;case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":setTimeout(()=>{if(this.hiddenInput){const i=this.hiddenInput.value,a=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(i,a)}},0),s=!1;break;case"Backspace":case"Delete":s=!1;break;default:s=this.eventHandlers.onCustomKey?.(e.key,e)||!1;break}s&&e.preventDefault()};handleKeyboardShortcuts(e){const{key:s}=e;switch(s.toLowerCase()){case"a":return this.selectAll(),!0;case"c":case"v":return!1;case"z":return this.eventHandlers.onCustomKey?.("undo",e),!0;case"y":return this.eventHandlers.onCustomKey?.("redo",e),!0;default:return!1}}handleCompositionStart=e=>{this.isComposing=!0};handleCompositionEnd=e=>{if(this.isComposing=!1,this.hiddenInput){const s=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(s,i)}};handleFocus=e=>{this.isFocused=!0,this.focusRetryCount=0,this.eventHandlers.onFocus?.(e)};handleBlur=e=>{this.isFocused=!1,this.eventHandlers.onBlur?.(e)};handlePaste=e=>{setTimeout(()=>{this.handleTextInput(e)},0)};selectAll(){this.hiddenInput&&this.hiddenInput.select()}}class ls{static DOUBLE_CLICK_THRESHOLD_MS=300;static EDITING_BG_PADDING_PX=5;static EDITING_BG_ALPHA=.2;static CLICK_HANDLER_DELAY_MS=100;parent;targetText;clipConfig;isEditing=!1;lastClickTime=0;editingContainer=null;editableText=null;textCursor=null;textInputHandler=null;outsideClickHandler=null;constructor(e,s,i){this.parent=e,this.targetText=s,this.clipConfig=i,this.parent.getContainer().eventMode="static",this.parent.getContainer().on("click",this.checkForDoubleClick)}dispose(){this.parent.getContainer().off("click",this.checkForDoubleClick),this.stopEditing(),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null)}startEditing(){if(this.isEditing||!this.targetText)return;const e=structuredClone(this.clipConfig);this.targetText.visible=!1,this.createEditingEnvironment(),this.setupOutsideClickHandler(e),this.isEditing=!0}stopEditing(e=!1,s){if(!this.isEditing)return;let i="";this.editableText&&(i=this.editableText.text),this.editingContainer&&(this.parent.getContainer().removeChild(this.editingContainer),this.editingContainer.destroy(),this.editingContainer=null),this.editableText=null,this.textCursor&&(this.textCursor.dispose(),this.textCursor=null),this.textInputHandler&&(this.textInputHandler.dispose(),this.textInputHandler=null),this.targetText.visible=!0,e&&s&&i!==""&&this.parent.updateTextContent(i,s),this.isEditing=!1}checkForDoubleClick=e=>{const s=Date.now();s-this.lastClickTime<ls.DOUBLE_CLICK_THRESHOLD_MS&&this.startEditing(),this.lastClickTime=s};setupOutsideClickHandler(e){this.outsideClickHandler=s=>{const a=this.parent.getContainer().getBounds(),r=s.clientX,n=s.clientY;(r<a.x||r>a.x+a.width||n<a.y||n>a.y+a.height)&&(this.stopEditing(!0,e),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null))},setTimeout(()=>{this.outsideClickHandler&&window.addEventListener("click",this.outsideClickHandler)},ls.CLICK_HANDLER_DELAY_MS)}createEditingEnvironment(){this.setupEditingContainer(),this.editingContainer&&this.editableText&&(this.textCursor=new ua(this.editingContainer,this.editableText,this.clipConfig),this.textCursor.updatePosition(this.targetText.text.length),this.textCursor.startBlinking()),this.setupTextInputHandler(),this.updateTextAlignment()}setupEditingContainer(){this.editingContainer=new X.Container,this.parent.getContainer().addChild(this.editingContainer);const e=new X.Graphics;e.fillStyle={color:0,alpha:ls.EDITING_BG_ALPHA},e.rect(-5,-5,this.targetText.width+2*ls.EDITING_BG_PADDING_PX,this.targetText.height+2*ls.EDITING_BG_PADDING_PX),e.fill(),this.editingContainer.addChild(e),this.editableText=new X.Text(this.targetText.text,this.targetText.style),this.editableText.eventMode="static",this.editableText.cursor="text",this.editingContainer.addChild(this.editableText)}setupTextInputHandler(){this.textInputHandler=new Or,this.textInputHandler.setTextInputHandler((e,s)=>{this.editableText&&(this.editableText.text=e,this.updateTextAlignment()),this.textCursor?.updatePosition(s)}),this.textInputHandler.setEventHandlers({onEscape:e=>this.stopEditing(!1),onTabNavigation:e=>this.stopEditing(!0)}),this.textInputHandler.setupInput(this.targetText.text,{autoFocus:!0})}updateTextAlignment(){if(!this.editableText||!this.editingContainer)return;const e=this.getContainerDimensions(),s=this.getAlignmentSettings(),i=this.calculateHorizontalPosition({width:this.editableText.width},e,s.horizontal),a=this.calculateVerticalPosition({height:this.editableText.height},e,s.vertical);if(this.editingContainer.position.set(i,a),this.editingContainer.children.length>0){const r=this.editingContainer.getChildAt(0);r instanceof X.Graphics&&(r.clear(),r.fillStyle={color:0,alpha:ls.EDITING_BG_ALPHA},r.rect(-5,-5,this.editableText.width+2*ls.EDITING_BG_PADDING_PX,this.editableText.height+2*ls.EDITING_BG_PADDING_PX),r.fill())}}calculateHorizontalPosition(e,s,i="center"){switch(i){case"center":return s.width/2-e.width/2;case"right":return s.width-e.width;case"left":default:return 0}}calculateVerticalPosition(e,s,i="center"){switch(i){case"center":return s.height/2-e.height/2;case"bottom":return s.height-e.height;case"top":default:return 0}}getContainerDimensions(){const e=this.clipConfig.asset;return{width:e.width??this.parent.getSize().width,height:e.height??this.parent.getSize().height}}getAlignmentSettings(){const e=this.clipConfig.asset;return{horizontal:e.alignment?.horizontal??"center",vertical:e.alignment?.vertical??"center"}}}class Ni extends xt{static loadedFonts=new Set;background=null;text=null;textEditor=null;constructor(e,s){super(e,s,Qe.Text)}async load(){await super.load();const e=this.clipConfiguration.asset,s=e.font?.family??"Open Sans";if(await this.loadFont(s),this.background=new X.Graphics,this.drawBackground(),this.text=new X.Text({text:e.text??"",style:this.createTextStyle(e)}),this.positionText(e),e.stroke?.width&&e.stroke.width>0&&e.stroke.color){const i=new Mi({thickness:e.stroke.width,color:e.stroke.color});this.text.filters=[i]}this.contentContainer.addChild(this.background),this.contentContainer.addChild(this.text),this.configureKeyframes(),this.textEditor=new ls(this,this.text,this.clipConfiguration)}update(e,s){super.update(e,s)}reconfigureAfterRestore(){super.reconfigureAfterRestore(),this.reconfigure()}async reconfigure(){const e=this.clipConfiguration.asset,s=e.font?.family??"Open Sans";if(await this.loadFont(s),this.drawBackground(),this.text){if(this.text.text=e.text??"",this.text.style=this.createTextStyle(e),e.stroke?.width&&e.stroke.width>0&&e.stroke.color){const i=new Mi({thickness:e.stroke.width,color:e.stroke.color});this.text.filters=[i]}else this.text.filters=[];this.positionText(e)}}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null,this.textEditor?.dispose(),this.textEditor=null}getSize(){const e=this.clipConfiguration.asset;return{width:this.clipConfiguration.width??e.width??this.edit.size.width,height:this.clipConfiguration.height??e.height??this.edit.size.height}}getFitScale(){return 1}getContainerScale(){const e=this.getScale();return{x:e,y:e}}supportsEdgeResize(){return!0}onDimensionsChanged(){if(this.drawBackground(),this.text){const e=this.clipConfiguration.asset;this.text.style.wordWrapWidth=this.getSize().width,this.positionText(e)}}applyFixedDimensions(){}createTextStyle(e){const s=e.font?.family??"Open Sans",{baseFontFamily:i,fontWeight:a}=Dt(s),{width:r}=this.getSize();return new X.TextStyle({fontFamily:i,fontSize:e.font?.size??32,fill:e.font?.color??"#ffffff",fontWeight:a.toString(),wordWrap:!0,wordWrapWidth:r,lineHeight:(e.font?.lineHeight??1)*(e.font?.size??32),align:e.alignment?.horizontal??"center"})}positionText(e){if(!this.text)return;const s=e.alignment?.horizontal??"center",i=e.alignment?.vertical??"center",{width:a,height:r}=this.getSize();let n=a/2-this.text.width/2,o=r/2-this.text.height/2;s==="left"?n=0:s==="right"&&(n=a-this.text.width),i==="top"?o=0:i==="bottom"&&(o=r-this.text.height),this.text.position.set(n,o)}drawBackground(){const e=this.clipConfiguration.asset;if(!this.background||!e.background||!e.background.color)return;const{width:s,height:i}=this.getSize();this.background.clear(),this.background.fillStyle={color:e.background.color,alpha:e.background.opacity??1},this.background.rect(0,0,s,i),this.background.fill()}updateTextContent(e,s){this.edit.updateTextContent(this,e,s)}async loadFont(e){const{baseFontFamily:s,fontWeight:i}=Dt(e),a=`${s}-${i}`;if(Ni.loadedFonts.has(a))return;const r=Va(e);if(r){const n=new FontFace(s,`url(${r})`,{weight:i.toString()});await n.load(),document.fonts.add(n),Ni.loadedFonts.add(a)}}static resetFontCache(){Ni.loadedFonts.clear()}}class vk extends xt{aiOverlay=null;lastPrompt="";constructor(e,s){super(e,s,Qe.TextToImage)}async load(){await super.load();const{width:e,height:s}=this.getSize(),i=this.edit.getResolvedEdit()?.timeline.tracks.flatMap(l=>l.clips)??[],a=Yo(i,this.clipId??""),{asset:r}=this.clipConfiguration,n=Bs(r)&&r.prompt||"",o=Bs(r)?r.type:"text-to-image";this.aiOverlay=new sn({mode:"panel",icon:"image",width:e,height:s,assetNumber:a??void 0,prompt:n,assetType:o}),this.contentContainer.addChild(this.aiOverlay.getContainer()),this.configureKeyframes()}update(e,s){super.update(e,s);const{width:i,height:a}=this.getSize();this.aiOverlay?.resize(i,a);const{asset:r}=this.clipConfiguration,n=Bs(r)&&r.prompt||"";n!==this.lastPrompt&&(this.aiOverlay?.updatePrompt(n),this.lastPrompt=n)}getSize(){const e=this.clipConfiguration.asset;return{width:this.clipConfiguration.width??e.width??this.edit.size.width,height:this.clipConfiguration.height??e.height??this.edit.size.height}}dispose(){this.aiOverlay?.dispose(),this.aiOverlay=null,super.dispose()}}class xk extends xt{constructor(e,s){super(e,s,Qe.TextToSpeech)}async load(){await super.load(),this.configureKeyframes()}update(e,s){super.update(e,s),this.getContainer().alpha=0}getSize(){return{width:0,height:0}}}class Ck extends xt{texture;sprite;isPlaying;volumeKeyframeBuilder;syncTimer;activeSyncTimer;skipVideoUpdate;constructor(e,s){super(e,s,Qe.Video),this.texture=null,this.sprite=null,this.isPlaying=!1;const i=this.clipConfiguration.asset;this.volumeKeyframeBuilder=new Pi(i.volume??1,this.getLength()),this.syncTimer=0,this.activeSyncTimer=0,this.skipVideoUpdate=!1}async load(){await super.load(),await this.loadVideo(),this.configureKeyframes()}update(e,s){if(super.update(e,s),this.skipVideoUpdate)return;const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=s,!this.texture)return;const a=this.getPlaybackTime(),r=this.edit.isPlaying&&this.isActive();r&&(this.isPlaying||(this.isPlaying=!0,this.activeSyncTimer=0,this.texture.source.resource.currentTime=a+i,this.texture.source.resource.play().catch(console.error)),this.texture.source.resource.volume!==this.getVolume()&&(this.texture.source.resource.volume=this.getVolume()),this.activeSyncTimer+=s,this.activeSyncTimer>1e3&&(this.activeSyncTimer=0,Math.abs(this.texture.source.resource.currentTime-i-a)>.3&&(this.texture.source.resource.currentTime=a+i,this.edit.recordSyncCorrection()))),!r&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause());const n=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&n&&(this.syncTimer=0,this.texture.source.resource.currentTime=a+i)}dispose(){super.dispose(),this.disposeVideo()}getSize(){return this.clipConfiguration.width&&this.clipConfiguration.height?{width:this.clipConfiguration.width,height:this.clipConfiguration.height}:{width:this.sprite?.width??0,height:this.sprite?.height??0}}supportsEdgeResize(){return!0}async reloadAsset(){this.skipVideoUpdate=!0,this.disposeVideo(),await this.loadVideo(),this.isPlaying=!1,this.syncTimer=0,this.activeSyncTimer=0,this.skipVideoUpdate=!1}async loadVideo(){const e=this.clipConfiguration.asset,{src:s}=e;if(s.endsWith(".mov"))throw new Error(`Video source '${s}' is not supported. .mov files cannot be played in the browser. Please convert to .webm or .mp4 first.`);const i=`${s}${s.includes("?")?"&":"?"}x-cors=1`,a={src:i,data:{autoPlay:!1,muted:!1}},r=await this.edit.assetLoader.loadVideoUnique(i,a);if(!r||!(r.source instanceof X.VideoSource))throw new Error(`Invalid video source '${s}'.`);r.source.alphaMode="no-premultiply-alpha",this.texture=this.createCroppedTexture(r);const n=this.texture.source.resource;n instanceof HTMLVideoElement&&n.readyState<2&&await new Promise(o=>{const l=()=>{n.removeEventListener("loadeddata",l),o()};n.addEventListener("loadeddata",l),n.readyState>=2&&o()}),this.sprite=new X.Sprite(this.texture),this.contentContainer.addChild(this.sprite)}disposeVideo(){this.texture?.source?.resource&&(this.texture.source.resource.pause(),this.texture.source.resource.src="",this.texture.source.resource.load()),this.sprite&&(this.contentContainer.removeChild(this.sprite),this.sprite.destroy(),this.sprite=null),this.texture&&(this.texture.destroy(!0),this.texture=null)}getVolume(){return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}getCurrentDrift(){if(!this.texture?.source?.resource)return 0;const{trim:e=0}=this.clipConfiguration.asset,s=this.texture.source.resource.currentTime,i=this.getPlaybackTime();return Math.abs(s-e-i)}createCroppedTexture(e){const s=this.clipConfiguration.asset;if(!s.crop)return e;const i=e.width,a=e.height;if(i<=0||a<=0)return e;const r=Math.floor((s.crop?.left??0)*i),n=Math.floor((s.crop?.right??0)*i),o=Math.floor((s.crop?.top??0)*a),l=Math.floor((s.crop?.bottom??0)*a),c=r,f=o,h=i-r-n,d=a-o-l,y=new X.Rectangle(c,f,h,d);return new X.Texture({source:e.source,frame:y})}}class M0{static create(e,s){if(!s.asset?.type)throw new Error("Invalid clip configuration: missing asset type");switch(s.asset.type){case"text":return new Ni(e,s);case"rich-text":return new os(e,s);case"shape":return new bk(e,s);case"html":return new Zu(e,s);case"image":return new Uu(e,s);case"video":return new Ck(e,s);case"audio":return new bu(e,s);case"luma":return new Qu(e,s);case"caption":return new _a(e,s);case"svg":return new gs(e,s);case"text-to-image":return new vk(e,s);case"image-to-video":return new Ju(e,s);case"text-to-speech":return new xk(e,s);default:throw new Error(`Unsupported asset type: ${s.asset.type}`)}}static cleanup(){Ni.resetFontCache()}}function ko(t,e,s,i){const a=new Map,r=`alias://${s}`;for(let n=0;n<t.getTrackCount();n+=1){const o=t.getClipsInTrack(n);for(let l=0;l<o.length;l+=1)if(!i?.has(`${n}:${l}`)){const c=o[l],f=c.id,h=e.timeline.tracks[n]?.clips[l];let d=!1;const y={};if(c.start===r&&(y.start=c.start,d=!0),c.length===r&&(y.length=c.length,d=!0),d&&f&&h){a.set(f,y);const m={};y.start&&(m.start=h.start),y.length&&(m.length=h.length),t.updateClip(n,l,m)}}}return a}function kk(t,e,s,i){const a=new Map;for(const r of s){const n=ko(t,e,r,i);for(const[o,l]of n){const c=a.get(o);c?a.set(o,{...c,...l}):a.set(o,l)}}return a}function No(t,e){for(const[s,i]of e){const a=t.getClipById(s);if(a){const r={};i.start&&(r.start=i.start),i.length&&(r.length=i.length),t.updateClip(a.trackIndex,a.clipIndex,r)}}}function Nk(t){const e=[];for(const s of t){const{alias:i}=s;i&&e.push(i)}return e}const Ee=()=>({status:"success"}),et=t=>({status:"noop",message:t});class Ak{constructor(e,s){this.trackIdx=e,this.clip=s}name="addClip";addedClipId;convertedReferences;execute(e){if(!e)throw new Error("AddClipCommand.execute: context is required");const s=e.getDocument();if(!s)throw new Error("AddClipCommand.execute: no document");const i=e.documentAddClip(this.trackIdx,this.clip);this.addedClipId=i.id,this.convertedReferences&&this.convertedReferences.size>0&&No(s,this.convertedReferences),e.resolve(),e.updateDuration();const n=e.getDocumentTrack(this.trackIdx)?.clips?.findIndex(o=>o.id===this.addedClipId)??-1;return e.emitEvent(fe.ClipAdded,{trackIndex:this.trackIdx,clipIndex:n}),Ee()}undo(e){if(!e)throw new Error("AddClipCommand.undo: context is required");if(!this.addedClipId)return et("No clip ID stored");const s=e.getDocument();if(!s)throw new Error("AddClipCommand.undo: no document");const a=e.getDocumentTrack(this.trackIdx)?.clips,r=a?.findIndex(o=>o.id===this.addedClipId)??-1;if(r===-1)return et(`Clip ${this.addedClipId} not found in track ${this.trackIdx}`);const n=a?.[r]?.alias;if(n){const o=new Set([`${this.trackIdx}:${r}`]);this.convertedReferences=ko(s,e.getEditState(),n,o)}return e.documentRemoveClip(this.trackIdx,r),e.resolve(),e.updateDuration(),e.emitEvent(fe.ClipDeleted,{trackIndex:this.trackIdx,clipIndex:r}),Ee()}dispose(){this.addedClipId=void 0,this.convertedReferences=void 0}}class Sk{constructor(e){this.trackIdx=e}name="addTrack";execute(e){if(!e)throw new Error("AddTrackCommand.execute: context is required");const s=e.getDocument();if(!s)throw new Error("AddTrackCommand.execute: document is required");return s.addTrack(this.trackIdx),e.resolve(),e.updateDuration(),e.emitEvent(fe.TrackAdded,{trackIndex:this.trackIdx,totalTracks:s.getTrackCount()}),Ee()}undo(e){if(!e)throw new Error("AddTrackCommand.undo: context is required");const s=e.getDocument();if(!s)throw new Error("AddTrackCommand.undo: document is required");return s.removeTrack(this.trackIdx),e.resolve(),e.updateDuration(),Ee()}dispose(){}}class R0{constructor(e){this.trackIdx=e}name="deleteTrack";deletedClips=[];convertedReferences;execute(e){if(!e)throw new Error("DeleteTrackCommand.execute: context is required");const s=e.getDocument();if(!s)throw new Error("DeleteTrackCommand: no document");if(s.getTrackCount()<=1)return et("Cannot delete the last track");const i=s.getTrack(this.trackIdx);i&&(this.deletedClips=i.clips.map(r=>structuredClone(r)));const a=Nk(this.deletedClips);if(a.length>0){const r=new Set;for(let n=0;n<this.deletedClips.length;n+=1)r.add(`${this.trackIdx}:${n}`);this.convertedReferences=kk(s,e.getEditState(),a,r)}return s.removeTrack(this.trackIdx),e.resolve(),e.updateDuration(),e.emitEvent(fe.TrackRemoved,{trackIndex:this.trackIdx}),Ee()}undo(e){if(!e)throw new Error("DeleteTrackCommand.undo: context is required");const s=e.getDocument();if(!s)throw new Error("DeleteTrackCommand.undo: no document");s.addTrack(this.trackIdx);for(let i=0;i<this.deletedClips.length;i+=1)s.addClip(this.trackIdx,this.deletedClips[i],i);return this.convertedReferences&&this.convertedReferences.size>0&&No(s,this.convertedReferences),e.resolve(),e.updateDuration(),e.emitEvent(fe.TrackAdded,{trackIndex:this.trackIdx,totalTracks:s.getTrackCount()}),Ee()}dispose(){this.deletedClips=[],this.convertedReferences=void 0}}class Ao{constructor(e,s){this.trackIdx=e,this.clipIdx=s}name="deleteClip";deletedClipConfig;deletedClipId;deleteTrackCommand;trackWasDeleted=!1;storedBindings;convertedReferences;execute(e){if(!e)throw new Error("DeleteClipCommand.execute: context is required");const s=e.getDocument();if(!s)throw new Error("DeleteClipCommand: no document");const i=s.getClip(this.trackIdx,this.clipIdx);if(!i)return et(`No clip at track ${this.trackIdx}, index ${this.clipIdx}`);if(this.deletedClipConfig=structuredClone(i),this.deletedClipId=i.id,this.deletedClipId){const o=e.getClipBindings(this.deletedClipId);this.storedBindings=o?new Map(o):void 0,s.clearClipBindings(this.deletedClipId)}const a=i.alias;if(a){const o=new Set([`${this.trackIdx}:${this.clipIdx}`]);this.convertedReferences=ko(s,e.getEditState(),a,o)}e.clearClipError(this.trackIdx,this.clipIdx);const r=e.getSelectedClip();r&&this.deletedClipId&&r.clipId===this.deletedClipId&&(e.setSelectedClip(null),e.emitEvent(fe.SelectionCleared)),e.documentRemoveClip(this.trackIdx,this.clipIdx);const n=s.getTrack(this.trackIdx);return n&&n.clips.length===0&&(this.deleteTrackCommand=new R0(this.trackIdx),this.deleteTrackCommand.execute(e).status==="success"&&(this.trackWasDeleted=!0)),e.resolve(),e.updateDuration(),e.emitEvent(fe.ClipDeleted,{trackIndex:this.trackIdx,clipIndex:this.clipIdx}),Ee()}undo(e){if(!e)throw new Error("DeleteClipCommand.undo: context is required");if(!this.deletedClipConfig)return et("No deleted clip config");const s=e.getDocument();if(!s)throw new Error("DeleteClipCommand.undo: no document");this.trackWasDeleted&&s.addTrack(this.trackIdx);const a=e.documentAddClip(this.trackIdx,this.deletedClipConfig,this.clipIdx).id;return a&&this.storedBindings&&this.storedBindings.size>0&&s.setClipBindingsForClip(a,this.storedBindings),this.convertedReferences&&this.convertedReferences.size>0&&No(s,this.convertedReferences),e.resolve(),e.updateDuration(),this.trackWasDeleted&&(e.emitEvent(fe.TrackAdded,{trackIndex:this.trackIdx,totalTracks:s.getTrackCount()}),this.trackWasDeleted=!1),e.emitEvent(fe.ClipRestored,{trackIndex:this.trackIdx,clipIndex:this.clipIdx}),Ee()}dispose(){this.deletedClipConfig=void 0,this.deletedClipId=void 0,this.deleteTrackCommand=void 0,this.storedBindings=void 0,this.convertedReferences=void 0}}class Vk{constructor(e){this.aspectRatio=e}name="setOutputAspectRatio";previousAspectRatio;execute(e){if(!e)throw new Error("SetOutputAspectRatioCommand requires context");return this.previousAspectRatio=e.getOutputAspectRatio(),e.setOutputAspectRatio(this.aspectRatio),Ee()}undo(e){if(!e)throw new Error("SetOutputAspectRatioCommand requires context");return this.previousAspectRatio===void 0?et("No previous aspect ratio stored"):(e.setOutputAspectRatio(this.previousAspectRatio),Ee())}dispose(){this.previousAspectRatio=void 0}}class Ik{constructor(e){this.destinations=e}name="setOutputDestinations";previousDestinations;execute(e){if(!e)throw new Error("SetOutputDestinationsCommand requires context");return this.previousDestinations=e.getOutputDestinations(),e.setOutputDestinations(this.destinations),Ee()}undo(e){if(!e)throw new Error("SetOutputDestinationsCommand requires context");return this.previousDestinations===void 0?et("No previous destinations stored"):(e.setOutputDestinations(this.previousDestinations),Ee())}dispose(){this.previousDestinations=void 0}}class _k{constructor(e){this.format=e}name="setOutputFormat";previousFormat;execute(e){if(!e)throw new Error("SetOutputFormatCommand requires context");return this.previousFormat=e.getOutputFormat(),e.setOutputFormat(this.format),Ee()}undo(e){if(!e)throw new Error("SetOutputFormatCommand requires context");return this.previousFormat===void 0?et("No previous format stored"):(e.setOutputFormat(this.previousFormat),Ee())}dispose(){this.previousFormat=void 0}}class Fk{constructor(e){this.fps=e}name="setOutputFps";previousFps;execute(e){if(!e)throw new Error("SetOutputFpsCommand requires context");return this.previousFps=e.getOutputFps(),e.setOutputFps(this.fps),Ee()}undo(e){if(!e)throw new Error("SetOutputFpsCommand requires context");return this.previousFps===void 0?et("No previous FPS stored"):(e.setOutputFps(this.previousFps),Ee())}dispose(){this.previousFps=void 0}}class Tk{constructor(e){this.resolution=e}name="setOutputResolution";previousResolution;execute(e){if(!e)throw new Error("SetOutputResolutionCommand requires context");return this.previousResolution=e.getOutputResolution(),e.setOutputResolution(this.resolution),Ee()}undo(e){if(!e)throw new Error("SetOutputResolutionCommand requires context");return this.previousResolution===void 0?et("No previous resolution stored"):(e.setOutputResolution(this.previousResolution),Ee())}dispose(){this.previousResolution=void 0}}class Ek{constructor(e,s){this.width=e,this.height=s}name="setOutputSize";previousSize;execute(e){if(!e)throw new Error("SetOutputSizeCommand requires context");return this.previousSize=e.getOutputSize(),e.setOutputSize(this.width,this.height),Ee()}undo(e){if(!e)throw new Error("SetOutputSizeCommand requires context");return this.previousSize?(e.setOutputSize(this.previousSize.width,this.previousSize.height),Ee()):et("No previous size stored")}dispose(){this.previousSize=void 0}}class Pk{constructor(e){this.color=e}name="setTimelineBackground";previousColor;execute(e){if(!e)throw new Error("SetTimelineBackgroundCommand requires context");return this.previousColor=e.getTimelineBackground(),e.setTimelineBackground(this.color),Ee()}undo(e){if(!e)throw new Error("SetTimelineBackgroundCommand requires context");return this.previousColor===void 0?et("No previous color stored"):(e.setTimelineBackground(this.previousColor),Ee())}dispose(){this.previousColor=void 0}}function Et(t){const{id:e,...s}=t;return s}function Mr(t){return!!(t&&typeof t=="object"&&!Array.isArray(t))}function So(t,e){const s={...t};return Mr(t)&&Mr(e)&&Object.keys(e).forEach(i=>{if(i==="__proto__"||i==="constructor"||i==="prototype")return;const a=e[i],r=t[i];Mr(a)?i in t&&Mr(r)?s[i]=So(r,a):s[i]=So({},a):s[i]=a}),s}function ps(t,e,s){const i=e.split(".");let a=t;for(let r=0;r<i.length-1;r+=1){if(a==null||typeof a!="object")return;const n=i[r],o=a[n];(o==null||typeof o!="object")&&(a[n]={}),a=a[n]}a!=null&&typeof a=="object"&&(a[i[i.length-1]]=s)}function Rr(t,e){const s=e.split(".");let i=t;for(const a of s){if(i==null||typeof i!="object")return;i=i[a]}return i}class Vo{constructor(e,s,i){this.initialClipConfig=e,this.finalClipConfig=s,this.trackIndex=i?.trackIndex??-1,this.clipIndex=i?.clipIndex??-1}name="setUpdatedClip";clipId=null;storedInitialConfig=null;storedFinalConfig=null;storedInitialBindings=new Map;previousDocClip=null;trackIndex;clipIndex;async execute(e){if(!e)throw new Error("SetUpdatedClipCommand.execute: context is required");const s=e.getDocument();if(!s)throw new Error("SetUpdatedClipCommand.execute: document is required");const i=e.getClipAt(this.trackIndex,this.clipIndex);if(!i)return et(`Invalid clip at ${this.trackIndex}/${this.clipIndex}`);this.clipId=i.clipId,this.storedInitialConfig||(this.storedInitialConfig=this.initialClipConfig?structuredClone(this.initialClipConfig):structuredClone(i.clipConfiguration)),this.storedFinalConfig||(this.storedFinalConfig=this.finalClipConfig?structuredClone(this.finalClipConfig):structuredClone(i.clipConfiguration));const a=e.getDocumentClip(this.trackIndex>=0?this.trackIndex:i.layer-1,this.clipIndex>=0?this.clipIndex:e.getTracks()[i.layer-1]?.indexOf(i)??-1);this.previousDocClip=a?structuredClone(a):null;const r=this.clipId?e.getClipBindings(this.clipId):void 0;this.storedInitialBindings=r?new Map(r):new Map;const n=this.trackIndex>=0?this.trackIndex:i.layer-1,o=this.clipIndex>=0?this.clipIndex:e.getTracks()[n]?.indexOf(i)??-1,l=this.storedFinalConfig??this.finalClipConfig;l&&s.replaceClipProperties(n,o,l),e.resolve();const c=e.getClipAt(n,o);for(const[C,{resolvedValue:E}]of this.storedInitialBindings)(c?Rr(c.clipConfiguration,C):void 0)!==E&&this.clipId&&e.removeClipBinding(this.clipId,C);const f=this.storedInitialConfig??this.initialClipConfig,h=this.storedFinalConfig??this.finalClipConfig,d=f?.asset,y=h?.asset;if(d?.src!==y?.src){const C=e.getClipAt(n,o);C&&C.getTimingIntent().length==="auto"&&await e.resolveClipAutoLength(C)}const m=e.getDocumentClip(n,o);if(!this.previousDocClip||!m)throw new Error(`SetUpdatedClipCommand: document clip not found after mutation at ${n}/${o}`);return e.emitEvent(fe.ClipUpdated,{previous:{clip:Et(this.previousDocClip),trackIndex:n,clipIndex:o},current:{clip:Et(m),trackIndex:n,clipIndex:o}}),Ee()}async undo(e){if(!e)throw new Error("SetUpdatedClipCommand.undo: context is required");const s=this.storedInitialConfig??this.initialClipConfig;if(!s)return et("No stored initial config");const i=e.getDocument();if(!i)throw new Error("SetUpdatedClipCommand.undo: document is required");const a=this.clipId?e.getPlayerByClipId(this.clipId):e.getClipAt(this.trackIndex,this.clipIndex);if(!a)return et("Clip not found for undo");const r=this.trackIndex>=0?this.trackIndex:a.layer-1,n=this.clipIndex>=0?this.clipIndex:e.getTracks()[r]?.indexOf(a)??-1,o=structuredClone(e.getDocumentClip(r,n));if(i.replaceClipProperties(r,n,s),e.resolve(),this.clipId){const d=new Map(this.storedInitialBindings);d.size>0?e.getDocument()?.setClipBindingsForClip(this.clipId,d):e.getDocument()?.clearClipBindings(this.clipId)}const c=(this.storedFinalConfig??this.finalClipConfig)?.asset,f=s?.asset;if(c?.src!==f?.src){const d=e.getClipAt(r,n);d&&d.getTimingIntent().length==="auto"&&await e.resolveClipAutoLength(d)}const h=e.getDocumentClip(r,n);if(!o||!h)throw new Error(`SetUpdatedClipCommand: document clip not found after undo at ${r}/${n}`);return e.emitEvent(fe.ClipUpdated,{previous:{clip:Et(o),trackIndex:r,clipIndex:n},current:{clip:Et(h),trackIndex:r,clipIndex:n}}),Ee()}dispose(){this.clipId=null,this.storedInitialConfig=null,this.storedFinalConfig=null,this.storedInitialBindings.clear(),this.previousDocClip=null}}class Ok{constructor(e,s,i){this.trackIndex=e,this.clipIndex=s,this.splitTime=i}name="SplitClip";originalClipConfig=null;rightClipId=null;execute(e){const s=e.getDocument();if(!s)throw new Error("Cannot split clip: no document");const i=s.getClip(this.trackIndex,this.clipIndex);if(!i)return et(`No clip at ${this.trackIndex}/${this.clipIndex}`);const a=e.getClipAt(this.trackIndex,this.clipIndex),r=a?.clipConfiguration.start??0,n=a?.clipConfiguration.length??0,o=.1,l=this.splitTime-r;if(l<=o||l>=n-o)return et("Split point too close to clip boundaries");this.originalClipConfig=structuredClone(i);const c=l,f=structuredClone(i);if(i.start==="auto"?f.start="auto":f.start=r+l,f.length=n-l,i.asset&&(i.asset.type==="video"||i.asset.type==="audio")){const d=i.asset.trim||0;f.asset&&(f.asset.type==="video"||f.asset.type==="audio")&&(f.asset.trim=d+l)}e.documentUpdateClip(this.trackIndex,this.clipIndex,{length:c});const h=e.documentAddClip(this.trackIndex,f,this.clipIndex+1);return this.rightClipId=h.id??null,e.resolve(),e.updateDuration(),e.emitEvent(fe.ClipSplit,{trackIndex:this.trackIndex,originalClipIndex:this.clipIndex,newClipIndex:this.clipIndex+1}),Ee()}undo(e){return this.originalClipConfig?(e.documentRemoveClip(this.trackIndex,this.clipIndex+1),e.documentUpdateClip(this.trackIndex,this.clipIndex,this.originalClipConfig),e.resolve(),e.updateDuration(),e.emitEvent(fe.ClipDeleted,{trackIndex:this.trackIndex,clipIndex:this.clipIndex+1}),Ee()):et("No original clip config stored")}dispose(){this.originalClipConfig=null,this.rightClipId=null}}class Mk{constructor(e,s,i){this.trackIndex=e,this.clipIndex=s,this.params=i}name="UpdateClipTiming";originalStart;originalLength;clipId;execute(e){if(!e)throw new Error("UpdateClipTimingCommand.execute: context is required");const s=e.getDocument();if(!s)throw new Error("UpdateClipTimingCommand.execute: document is required");const a=e.getDocumentTrack(this.trackIndex)?.clips[this.clipIndex];if(!a)return et(`Invalid clip at ${this.trackIndex}/${this.clipIndex}`);const r=e.getClipAt(this.trackIndex,this.clipIndex);if(!r)return et(`Player not found at ${this.trackIndex}/${this.clipIndex}`);this.originalStart=a.start,this.originalLength=a.length,this.clipId=r.clipId??void 0;const n=structuredClone(a),o={};this.params.start!==void 0&&(o.start=this.params.start),this.params.length!==void 0&&(o.length=this.params.length),s.updateClip(this.trackIndex,this.clipIndex,o),this.clipId?e.resolveClip(this.clipId):e.resolve(),o.length==="auto"&&e.resolveClipAutoLength(r).then(()=>{e.updateDuration(),e.propagateTimingChanges(this.trackIndex,this.clipIndex)}),e.updateDuration();const l=e.getDocumentClip(this.trackIndex,this.clipIndex);if(!l)throw new Error(`UpdateClipTimingCommand: document clip not found after mutation at ${this.trackIndex}/${this.clipIndex}`);return e.emitEvent(fe.ClipUpdated,{previous:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:Et(n)},current:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:Et(l)}}),e.propagateTimingChanges(this.trackIndex,this.clipIndex),Ee()}undo(e){if(!e)throw new Error("UpdateClipTimingCommand.undo: context is required");if(this.originalStart===void 0&&this.originalLength===void 0)throw new Error("UpdateClipTimingCommand.undo: no original values");const s=e.getDocument();if(!s)throw new Error("UpdateClipTimingCommand.undo: document is required");const i=e.getClipAt(this.trackIndex,this.clipIndex);if(!i)throw new Error("UpdateClipTimingCommand.undo: player not found");const a=structuredClone(e.getDocumentClip(this.trackIndex,this.clipIndex)),r={};this.originalStart!==void 0&&(r.start=this.originalStart),this.originalLength!==void 0&&(r.length=this.originalLength),s.updateClip(this.trackIndex,this.clipIndex,r),this.clipId?e.resolveClip(this.clipId):e.resolve(),this.originalLength==="auto"&&e.resolveClipAutoLength(i).then(()=>{e.updateDuration(),e.propagateTimingChanges(this.trackIndex,this.clipIndex)}),e.updateDuration();const n=e.getDocumentClip(this.trackIndex,this.clipIndex);if(!a||!n)throw new Error(`UpdateClipTimingCommand: document clip not found after undo at ${this.trackIndex}/${this.clipIndex}`);return e.emitEvent(fe.ClipUpdated,{previous:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:Et(a)},current:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:Et(n)}}),e.propagateTimingChanges(this.trackIndex,this.clipIndex),Ee()}}class Rk{constructor(e,s,i){this.trackIndex=e,this.clipIndex=s,this.newText=i}name="updateTextContent";clipId=null;previousText="";previousDocClip;execute(e){if(!e)throw new Error("UpdateTextContentCommand.execute: context is required");const s=e.getDocument();if(!s)throw new Error("UpdateTextContentCommand.execute: document is required");const i=e.getClipAt(this.trackIndex,this.clipIndex);if(!i)return et(`Invalid clip at ${this.trackIndex}/${this.clipIndex}`);const a=s.getClip(this.trackIndex,this.clipIndex);if(!a)return et("Clip not found in document");this.clipId=i.clipId,this.previousDocClip=structuredClone(a);const r=a.asset;this.previousText=r&&"text"in r?r.text??"":"";const o={...a.asset,text:this.newText};s.updateClip(this.trackIndex,this.clipIndex,{asset:o}),this.clipId?e.resolveClip(this.clipId):e.resolve();const l=e.getDocumentClip(this.trackIndex,this.clipIndex);if(!this.previousDocClip||!l)throw new Error(`UpdateTextContentCommand: document clip not found after mutation at ${this.trackIndex}/${this.clipIndex}`);return e.emitEvent(fe.ClipUpdated,{previous:{clip:Et(this.previousDocClip),trackIndex:this.trackIndex,clipIndex:this.clipIndex},current:{clip:Et(l),trackIndex:this.trackIndex,clipIndex:this.clipIndex}}),Ee()}undo(e){if(!e)throw new Error("UpdateTextContentCommand.undo: context is required");const s=e.getDocument();if(!s)throw new Error("UpdateTextContentCommand.undo: document is required");const i=structuredClone(e.getDocumentClip(this.trackIndex,this.clipIndex)),a=s.getClip(this.trackIndex,this.clipIndex);if(!a)return et("Clip not found for undo");const n={...a.asset,text:this.previousText};s.updateClip(this.trackIndex,this.clipIndex,{asset:n}),this.clipId?e.resolveClip(this.clipId):e.resolve();const o=e.getDocumentClip(this.trackIndex,this.clipIndex);if(this.previousDocClip){if(!i||!o)throw new Error(`UpdateTextContentCommand: document clip not found after undo at ${this.trackIndex}/${this.clipIndex}`);e.emitEvent(fe.ClipUpdated,{previous:{clip:Et(i),trackIndex:this.trackIndex,clipIndex:this.clipIndex},current:{clip:Et(o),trackIndex:this.trackIndex,clipIndex:this.clipIndex}})}return Ee()}dispose(){this.clipId=null,this.previousDocClip=void 0}}class z0{events;constructor(){this.events={}}on(e,s){return this.events[e]||(this.events[e]=new Set),this.events[e].add(s),()=>this.off(e,s)}once(e,s){const i=a=>{this.off(e,i),s(a)};return this.on(e,i)}off(e,s){this.events[e]&&(this.events[e].delete(s),!(this.events[e].size>0)&&delete this.events[e])}clear(e){delete this.events[e]}emit(e,...s){if(!this.events[e])return;const i=s[0];for(const a of this.events[e])a(i)}}const L0=.5,zk=1/30;class Lk{constructor(e,s,i){this.getCanvas=e,this.getTracks=s,this.events=i,this.onClipChangedBound=()=>this.rebuildLumaMasksIfNeeded(),this.onPlayerLoadedBound=a=>this.onPlayerLoaded(a)}activeLumaMasks=[];pendingMaskCleanup=[];onClipChangedBound;onPlayerLoadedBound;initialize(){this.setupEventListeners()}update(){this.updateLumaMasks(),this.processPendingMaskCleanup()}getActiveMaskCount(){return this.activeLumaMasks.length}dispose(){this.removeEventListeners();for(const e of this.activeLumaMasks)e.tempContainer.destroy({children:!0}),e.maskSprite.destroy({texture:!0});this.activeLumaMasks=[];for(const e of this.pendingMaskCleanup)try{e.maskSprite.parent?.removeChild(e.maskSprite),e.maskSprite.destroy({texture:!0})}catch{}this.pendingMaskCleanup=[]}cleanupForPlayer(e){const s=this.activeLumaMasks.findIndex(a=>a.lumaPlayer===e);if(s===-1)return;const i=this.activeLumaMasks[s];i.contentClip&&(i.contentClip.getContentContainer().mask=null),i.maskSprite.parent?.removeChild(i.maskSprite),i.tempContainer.destroy({children:!0}),this.activeLumaMasks.splice(s,1),this.pendingMaskCleanup.push({maskSprite:i.maskSprite,frameCount:0})}onPlayerLoaded(e){const{player:s,trackIndex:i}=e;if(s.playerType!==Qe.Luma)return;const a=s,r=a.getSprite();if(!r?.texture){console.warn("PlayerLoaded fired for luma player before texture ready");return}const n=this.getTracks();if(i>=n.length)return;const l=n[i].filter(f=>f.playerType!==Qe.Luma);l.length===0||this.activeLumaMasks.find(f=>f.lumaPlayer===a)||(this.setupLumaMask(a,r.texture,l[0]),a.getContainer().parent?.removeChild(a.getContainer()))}setupLumaMask(e,s,i){const a=this.getCanvas();if(!a)return;const{renderer:r}=a.application,{width:n,height:o}=i.getSize(),l=new X.Container,c=new X.Sprite(s);c.width=n,c.height=o;const f=new X.ColorMatrixFilter;f.negative(!1),c.filters=[f],l.addChild(c);const h=r.generateTexture({target:l,resolution:L0}),d=new X.Sprite(h);i.getContainer().addChild(d);const y=i.getContentContainer();y.mask=d,this.activeLumaMasks.push({lumaPlayer:e,maskSprite:d,tempContainer:l,contentClip:i,lastVideoTime:-1})}updateLumaMasks(){const e=this.getCanvas();if(!e)return;const{renderer:s}=e.application;for(const i of this.activeLumaMasks)if(i.lumaPlayer.isVideoSource()){const a=i.lumaPlayer.getVideoCurrentTime();if(Math.abs(a-i.lastVideoTime)>=zk){i.lastVideoTime=a;const n=i.maskSprite.texture;i.maskSprite.texture=s.generateTexture({target:i.tempContainer,resolution:L0}),n.destroy(!0)}}}setupEventListeners(){this.events.on(ot.PlayerLoaded,this.onPlayerLoadedBound),this.events.on(fe.ClipUpdated,this.onClipChangedBound)}removeEventListeners(){this.events.off(ot.PlayerLoaded,this.onPlayerLoadedBound),this.events.off(fe.ClipUpdated,this.onClipChangedBound)}processPendingMaskCleanup(){for(let e=this.pendingMaskCleanup.length-1;e>=0;e-=1){const s=this.pendingMaskCleanup[e];if(s.frameCount+=1,s.frameCount>=3){try{s.maskSprite.parent?.removeChild(s.maskSprite),s.maskSprite.destroy({texture:!0})}catch{}this.pendingMaskCleanup.splice(e,1)}}}rebuildLumaMasksIfNeeded(){if(!this.getCanvas())return;const s=this.getTracks();for(let i=0;i<s.length;i+=1){const a=s[i],r=a.find(l=>l.playerType===Qe.Luma),n=a.filter(l=>l.playerType!==Qe.Luma);r&&r.getContainer().parent?.removeChild(r.getContainer());const o=r&&this.activeLumaMasks.find(l=>l.lumaPlayer===r);if(r&&!o&&n.length>0){const l=r.getSprite();l?.texture&&this.setupLumaMask(r,l.texture,n[0])}}}}function Dk(t){return{find:t.name,replace:t.defaultValue}}function Bk(t){const e=typeof t.replace=="string"?t.replace:JSON.stringify(t.replace);return{name:t.find,defaultValue:e}}const Zk=/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi,Io=/\{\{\s*[A-Z_0-9]+\s*\}\}/i;class Uk{fields=new Map;events;constructor(e){this.events=e}register(e,s){this.fields.set(e.name,e),s?.silent||this.events.emit(fe.MergeFieldChanged,{fields:this.getAll()})}remove(e,s){const i=this.fields.delete(e);return i&&!s?.silent&&this.events.emit(fe.MergeFieldChanged,{fields:this.getAll()}),i}get(e){return this.fields.get(e)}getAll(){return Array.from(this.fields.values())}clear(){this.fields.clear()}resolve(e){return!e||this.fields.size===0?e:e.replace(Zk,(s,i)=>this.fields.get(i)?.defaultValue??s)}resolveToNumber(e){if(!this.isMergeFieldTemplate(e))return null;const s=this.resolve(e),i=parseFloat(s);return Number.isFinite(i)?i:null}hasUnresolved(e){if(!e)return!1;const s=this.resolve(e);return Io.test(s)}extractFieldName(e){if(!e)return null;const s=Io.exec(e);if(!s)return null;const i=s[0].match(/\{\{\s*([A-Z_0-9]+)\s*\}\}/i);return i?i[1]:null}isMergeFieldTemplate(e){return Io.test(e)}createTemplate(e){return`{{ ${e} }}`}toSerializedArray(){return this.getAll().map(Dk)}loadFromSerialized(e){this.fields.clear();for(const s of e){const i=Bk(s);this.fields.set(s.find,i)}}generateUniqueName(e){const s=new Set(this.fields.keys());let i=1;for(;s.has(`${e}_${i}`);)i+=1;return`${e}_${i}`}}const Gk={preview:{width:512,height:288},mobile:{width:640,height:360},sd:{width:1024,height:576},hd:{width:1280,height:720},1080:{width:1920,height:1080},"4k":{width:3840,height:2160}};function zr(t,e="16:9"){const s=Gk[t];if(!s)throw new Error(`Unknown resolution: ${t}`);switch(e){case"16:9":return{width:s.width,height:s.height};case"9:16":return{width:s.height,height:s.width};case"1:1":return{width:s.height,height:s.height};case"4:5":return{width:Math.round(s.height*4/5),height:s.height};case"4:3":return{width:Math.round(s.height*4/3),height:s.height};default:throw new Error(`Unknown aspectRatio: ${e}`)}}class Wk{constructor(e){this.edit=e}setSize(e,s){fw.parse({width:e,height:s});const i={width:e,height:s};this.edit.size=i;const a=this.edit.getResolvedEdit();a&&(a.output={...a.output,size:i},delete a.output.resolution,delete a.output.aspectRatio);const r=this.edit.getDocument();r?.setSize(i),r?.clearResolution(),r?.clearAspectRatio(),this.edit.updateCanvasForSize(),this.edit.getInternalEvents().emit(fe.OutputResized,i)}getSize(){return this.edit.size}setFps(e){const s=hw.parse(e),i=this.edit.getResolvedEdit();i&&(i.output={...i.output,fps:s}),this.edit.getDocument()?.setFps(s),this.edit.getInternalEvents().emit(fe.OutputFpsChanged,{fps:e})}getFps(){return this.edit.getResolvedEdit()?.output?.fps??30}setFormat(e){const s=uw.parse(e),i=this.edit.getResolvedEdit();i&&(i.output={...i.output,format:s}),this.edit.getDocument()?.setFormat(s),this.edit.getInternalEvents().emit(fe.OutputFormatChanged,{format:s})}getFormat(){return this.edit.getResolvedEdit()?.output?.format??"mp4"}setDestinations(e){const s=cw.array().parse(e),i=this.edit.getResolvedEdit();i&&(i.output={...i.output,destinations:s}),this.edit.getInternalEvents().emit(fe.OutputDestinationsChanged,{destinations:s})}getDestinations(){return this.edit.getResolvedEdit()?.output?.destinations??[]}setResolution(e){const s=dw.parse(e),i=this.edit.getResolvedEdit(),a=i?.output?.aspectRatio??"16:9",r=zr(s,a);this.edit.size=r,i&&(i.output={...i.output,resolution:s},delete i.output.size);const n=this.edit.getDocument();n?.setResolution(s),n?.clearSize(),this.edit.updateCanvasForSize(),this.edit.getInternalEvents().emit(fe.OutputResolutionChanged,{resolution:s}),this.edit.getInternalEvents().emit(fe.OutputResized,{width:r.width,height:r.height})}getResolution(){return this.edit.getResolvedEdit()?.output?.resolution}setAspectRatio(e){const s=gw.parse(e),i=this.edit.getResolvedEdit(),a=i?.output?.resolution;if(!a){i&&(i.output={...i.output,aspectRatio:s}),this.edit.getDocument()?.setAspectRatio(s),this.edit.getInternalEvents().emit(fe.OutputAspectRatioChanged,{aspectRatio:s});return}const r=zr(a,s);this.edit.size=r,i&&(i.output={...i.output,aspectRatio:s},delete i.output.size);const n=this.edit.getDocument();n?.setAspectRatio(s),n?.clearSize(),this.edit.updateCanvasForSize(),this.edit.getInternalEvents().emit(fe.OutputAspectRatioChanged,{aspectRatio:s}),this.edit.getInternalEvents().emit(fe.OutputResized,{width:r.width,height:r.height})}getAspectRatio(){return this.edit.getResolvedEdit()?.output?.aspectRatio}}class Yk{constructor(e){this.edit=e}selectedClip=null;copiedClip=null;selectClip(e,s){const i=this.edit.getPlayerClip(e,s);if(i){this.selectedClip=i;const a=this.edit.getDocumentClip(e,s);a&&this.edit.getInternalEvents().emit(fe.ClipSelected,{clip:Et(a),trackIndex:e,clipIndex:s})}}selectPlayer(e){const s=this.findClipIndices(e);s&&this.selectClip(s.trackIndex,s.clipIndex)}clearSelection(){this.selectedClip=null,this.edit.getInternalEvents().emit(fe.SelectionCleared)}isClipSelected(e,s){if(!this.selectedClip)return!1;const i=this.selectedClip.layer-1,r=this.edit.getTracks()[i];if(!r)return!1;const n=r.indexOf(this.selectedClip);return e===i&&s===n}isPlayerSelected(e){return this.edit.isInExportMode()?!1:this.selectedClip===e}getSelectedClipInfo(){if(!this.selectedClip)return null;const e=this.selectedClip.layer-1,i=this.edit.getTracks()[e];if(!i)return null;const a=i.indexOf(this.selectedClip);return{trackIndex:e,clipIndex:a,player:this.selectedClip}}getSelectedClip(){return this.selectedClip}setSelectedClip(e){this.selectedClip=e}copyClip(e,s){const i=this.edit.getResolvedClip(e,s);i&&(this.copiedClip={trackIndex:e,clipConfiguration:structuredClone(i)},this.edit.getInternalEvents().emit(fe.ClipCopied,{trackIndex:e,clipIndex:s}))}pasteClip(){if(!this.copiedClip)return;const e=structuredClone(this.copiedClip.clipConfiguration);e.start=this.edit.playbackTime,delete e.id,this.edit.addClip(this.copiedClip.trackIndex,e)}hasCopiedClip(){return this.copiedClip!==null}findClipIndices(e){const s=this.edit.getTracks();for(let i=0;i<s.length;i+=1){const a=s[i].indexOf(e);if(a!==-1)return{trackIndex:i,clipIndex:a}}return null}}const Hk=3;function jk(t){return new Promise(e=>{const s=document.createElement("video");s.preload="metadata",s.crossOrigin="anonymous",s.onloadedmetadata=()=>e(s.duration),s.onerror=()=>e(null),s.src=t})}async function D0(t){const e=t;if(["video","audio","luma"].includes(e.type)&&e.src){const s=await jk(e.src);if(s!==null&&!Number.isNaN(s)){const i=e.trim??0;return s-i}}return Hk}function B0(t,e,s){return e===0?0:s[t][e-1].getEnd()}function Z0(t,e){return Math.max(0,e-t)}function _o(t){let e=0;for(const s of t)for(const i of s)i.getTimingIntent().length!=="end"&&(e=Math.max(e,i.getEnd()));return e}class Kk{constructor(e){this.edit=e}cachedTimelineEnd=0;getTimelineEnd(){return this.cachedTimelineEnd}invalidateTimelineEndCache(){this.cachedTimelineEnd=0}async resolveAllTiming(){const e=this.edit.getTracks(),s=this.edit.getResolvedEdit();for(let r=0;r<e.length;r+=1){const n=e[r],o=s.timeline.tracks[r];for(let l=0;l<n.length;l+=1){const c=n[l],f=o?.clips[l];if(f){const h=c.getTimingIntent(),d=f.start;let y=f.length;h.length==="auto"&&(y=await D0(c.clipConfiguration.asset)),c.setResolvedTiming({start:d,length:y})}}}const i=_o(e);this.cachedTimelineEnd=i;const a=this.getEndLengthClips();for(const r of a){const n=r.getResolvedTiming();r.setResolvedTiming({start:n.start,length:Z0(n.start,i)})}for(const r of a)r.reconfigureAfterRestore()}propagateTimingChanges(e,s){const i=this.edit.getTracks(),a=i[e];if(!a)return;for(let n=Math.max(0,s);n<a.length;n+=1){const o=a[n];if(o.getTimingIntent().start==="auto"){const l=B0(e,n,i);o.setResolvedTiming({start:l,length:o.getLength()}),o.reconfigureAfterRestore()}}this.propagateAliasChanges();const r=_o(i);if(r!==this.cachedTimelineEnd){this.cachedTimelineEnd=r;const n=this.getEndLengthClips();for(const o of n){const l=Z0(o.getStart(),r),c=o.getLength();Math.abs(l-c)>.001&&(o.setResolvedTiming({start:o.getStart(),length:l}),o.reconfigureAfterRestore())}}this.edit.updateTotalDuration(),this.edit.getInternalEvents().emit(fe.TimelineUpdated,{current:this.edit.getEdit()})}propagateAliasChanges(){const e=this.edit.getTracks(),s=this.edit.getResolvedEdit();for(let i=0;i<e.length;i+=1){const a=e[i],r=s.timeline.tracks[i];for(let n=0;n<a.length;n+=1){const o=a[n],l=r?.clips[n],c=o.getTimingIntent(),f=Kt(c.start),h=Kt(c.length);if((f||h)&&l){const d=o.getStart(),y=o.getLength(),m=Math.abs(l.start-d)>.001,C=Math.abs(l.length-y)>.001;(m||C)&&(o.setResolvedTiming({start:l.start,length:l.length}),o.reconfigureAfterRestore())}}}}getEndLengthClips(){const e=this.edit.getTracks(),s=[];for(const i of e)for(const a of i)a.getTimingIntent().length==="end"&&s.push(a);return s}}class Xk extends z0{registry;constructor(){super(),this.registry={}}}class Lr{static VIDEO_EXTENSIONS=[".mp4",".m4v",".webm",".ogg",".ogv"];static VIDEO_MIME={".mp4":"video/mp4",".m4v":"video/mp4",".webm":"video/webm",".ogg":"video/ogg",".ogv":"video/ogg"};loadTracker=new Xk;refCounts=new Map;incrementRef(e){this.refCounts.set(e,(this.refCounts.get(e)??0)+1)}decrementRef(e){const s=this.refCounts.get(e)??0;return s<=1?(this.refCounts.delete(e),!0):(this.refCounts.set(e,s-1),!1)}constructor(){X.Assets.setPreferences({crossOrigin:"anonymous"})}async load(e,s){this.updateAssetLoadMetadata(e,"pending",0),this.incrementRef(e);try{if(await this.shouldUseSafariVideoLoader(s))return await this.loadVideoForSafari(e,s);const a=await X.Assets.load(s,r=>{this.updateAssetLoadMetadata(e,"loading",r)});return this.updateAssetLoadMetadata(e,"success",1),a}catch(i){return console.warn(`[AssetLoader] Failed to load asset "${e}":`,i),this.updateAssetLoadMetadata(e,"failed",1),this.decrementRef(e),null}}async loadVideoUnique(e,s){this.updateAssetLoadMetadata(e,"pending",0);try{const i=this.extractUrl(s);if(!i)throw new Error("No URL provided for video loading");const a=typeof s=="object"?s.data??{}:{},r=await new Promise((n,o)=>{const l=document.createElement("video");l.crossOrigin="anonymous",l.playsInline=!0,l.muted=a.muted??!1,l.preload="auto",l.addEventListener("loadedmetadata",()=>{try{const c=new X.VideoSource({resource:l,autoPlay:a.autoPlay??!1,...a});n(new X.Texture({source:c}))}catch(c){o(c)}},{once:!0}),l.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(e,"loading",.5),l.src=i});return this.updateAssetLoadMetadata(e,"success",1),r}catch{return this.updateAssetLoadMetadata(e,"failed",1),null}}getProgress(){const e=Object.keys(this.loadTracker.registry);return e.length===0?0:e.reduce((i,a)=>i+this.loadTracker.registry[a].progress,0)/e.length}extractUrl(e){if(typeof e=="string")return e;const s=Array.isArray(e.src)?e.src[0]:e.src;return typeof s=="string"?s:s?.src}hasVideoExtension(e){const s=new URL(e,window.location.origin).pathname.toLowerCase();return Lr.VIDEO_EXTENSIONS.some(i=>s.endsWith(i))}async getContentType(e){try{return(await fetch(e,{method:"HEAD"})).headers.get("content-type")}catch{return null}}canPlayVideo(e){const s=new URL(e,window.location.origin).pathname.toLowerCase(),i=s.slice(s.lastIndexOf(".")),a=Lr.VIDEO_MIME[i];return a?document.createElement("video").canPlayType(a)!=="":!1}async isPlayableVideo(e){if(this.hasVideoExtension(e))return this.canPlayVideo(e);const s=await this.getContentType(e);return s?.startsWith("video/")?document.createElement("video").canPlayType(s)!=="":!1}async shouldUseSafariVideoLoader(e){const s=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),i=this.extractUrl(e);return s&&i!==void 0&&await this.isPlayableVideo(i)}async loadVideoForSafari(e,s){const i=this.extractUrl(s),a=typeof s=="object"?s.data??{}:{},r=await new Promise((n,o)=>{const l=document.createElement("video");l.crossOrigin="anonymous",l.playsInline=!0,l.muted=!0,l.preload="metadata",l.addEventListener("loadedmetadata",()=>{try{const c=new X.VideoSource({resource:l,autoPlay:a.autoPlay??!1,...a});n(new X.Texture({source:c}))}catch(c){o(c)}},{once:!0}),l.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(e,"loading",.5),l.src=i});return this.updateAssetLoadMetadata(e,"success",1),r}updateAssetLoadMetadata(e,s,i){this.loadTracker.registry[e]?(this.loadTracker.registry[e].progress=i,this.loadTracker.registry[e].status=s):this.loadTracker.registry[e]={progress:i,status:s};const a={...this.loadTracker.registry};this.loadTracker.emit("onAssetLoadInfoUpdated",{registry:a})}}class Dr{static Name="FontLoadParser";id;name;extension;validFontExtensions;woff2Decompressor;constructor(){this.id=Dr.Name,this.name=Dr.Name,this.extension={type:[X.ExtensionType.LoadParser],priority:X.LoaderParserPriority.High,ref:null},this.validFontExtensions=["ttf","otf","woff","woff2"],this.woff2Decompressor=null}test(e){const s=e.split("?")[0]?.split(".").pop()?.toLowerCase()??"";return this.validFontExtensions.includes(s)}async load(e,s,i){const a=e.split("?")[0]?.split(".").pop()?.toLowerCase()??"",r=await fetch(e).then(d=>d.arrayBuffer());if(a!=="woff2"){const d=$r.parse(new Uint8Array(r).buffer),y=d.names.fontFamily.en||d.names.fontFamily[Object.keys(d.names.fontFamily)[0]],m=new FontFace(y,`url(${e})`);return await m.load(),document.fonts.add(m),m}if(await this.loadWoff2Decompressor(),!this.woff2Decompressor)throw new Error("Cannot initialize Woff2 decompressor.");const n=this.woff2Decompressor.decompress(r),o=$r.parse(new Uint8Array(n).buffer),l=o.names.fontFamily.en||o.names.fontFamily[Object.keys(o.names.fontFamily)[0]],c=new Blob([n],{type:"font/ttf"}),f=URL.createObjectURL(c),h=new FontFace(l,`url(${f})`);return await h.load(),document.fonts.add(h),h}async loadWoff2Decompressor(){if(this.woff2Decompressor)return;const s=`${await fetch("https://unpkg.com/wawoff2@2.0.1/build/decompress_binding.js").then(i=>i.text())}; return Module`;this.woff2Decompressor=new Function(s)(),await new Promise(i=>{this.woff2Decompressor.onRuntimeInitialized=i})}unload(e){e&&document.fonts.delete(e)}}function qk(t,e,s,i){const a=Math.max(t,s),r=Math.min(e,i);return Math.max(0,r-a)}class Jk{queue=[];isProcessing=!1;async enqueue(e){return new Promise((s,i)=>{this.queue.push(async()=>{try{const a=await e();s(a)}catch(a){i(a)}}),this.processQueue()})}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;){const e=this.queue.shift();if(e)try{await e()}catch{}}this.isProcessing=!1}}}class Ai{data;clipBindings=new Map;constructor(e){this.data=structuredClone(e),this.hydrateIds()}hydrateIds(){const e=new Set;for(const s of this.data.timeline.tracks)for(let i=0;i<s.clips.length;i+=1){const a=s.clips[i];if(e.has(a)){const r=structuredClone(a);r.id=crypto.randomUUID(),s.clips[i]=r}else e.add(a),a.id||(a.id=crypto.randomUUID())}}getTimeline(){return this.data.timeline}getBackground(){return this.data.timeline.background}getTracks(){return this.data.timeline.tracks}getTrack(e){return this.data.timeline.tracks[e]??null}getTrackCount(){return this.data.timeline.tracks.length}getSoundtrack(){return this.data.timeline.soundtrack}getClip(e,s){const i=this.data.timeline.tracks[e];return i?i.clips[s]??null:null}getClipsInTrack(e){return this.data.timeline.tracks[e]?.clips??[]}getClipCount(){return this.data.timeline.tracks.reduce((e,s)=>e+s.clips.length,0)}getClipCountInTrack(e){return this.data.timeline.tracks[e]?.clips.length??0}getClipById(e){for(let s=0;s<this.data.timeline.tracks.length;s+=1){const i=this.data.timeline.tracks[s].clips;for(let a=0;a<i.length;a+=1)if(i[a].id===e)return{clip:i[a],trackIndex:s,clipIndex:a}}return null}updateClipById(e,s){const i=this.getClipById(e);i&&Object.assign(i.clip,s)}removeClipById(e){const s=this.getClipById(e);return s?this.removeClip(s.trackIndex,s.clipIndex):null}getClipId(e,s){return this.getClip(e,s)?.id??null}getOutput(){return this.data.output}getSize(){const{size:e}=this.data.output;if(!e?.width||!e?.height)throw new Error("Output size is not defined");return{width:e.width,height:e.height}}getFormat(){return this.data.output.format}getFps(){return this.data.output.fps}getResolution(){return this.data.output.resolution}getAspectRatio(){return this.data.output.aspectRatio}getMergeFields(){return this.data.merge}addTrack(e,s){const i=s??{clips:[]};return this.data.timeline.tracks.splice(e,0,i),i}removeTrack(e){if(e<0||e>=this.data.timeline.tracks.length)return null;if(this.data.timeline.tracks.length<=1)return console.warn("Cannot remove the last track"),null;const[s]=this.data.timeline.tracks.splice(e,1);return s??null}addClip(e,s,i){const a=this.data.timeline.tracks[e];if(!a)throw new Error(`Track ${e} does not exist`);const r=s;r.id||(r.id=crypto.randomUUID());const n=i??a.clips.length;return a.clips.splice(n,0,s),s}removeClip(e,s){const i=this.data.timeline.tracks[e];if(!i||s<0||s>=i.clips.length)return null;const[a]=i.clips.splice(s,1);return a??null}updateClip(e,s,i){const a=this.getClip(e,s);if(!a)throw new Error(`Clip at track ${e}, index ${s} does not exist`);Object.assign(a,i)}replaceClipProperties(e,s,i){const a=this.getClip(e,s);if(!a)throw new Error(`Clip at track ${e}, index ${s} does not exist`);const{id:r}=a;for(const n of Object.keys(a))n!=="id"&&delete a[n];Object.assign(a,i),r&&(a.id=r)}replaceClip(e,s,i){const a=this.data.timeline.tracks[e];if(!a||s<0||s>=a.clips.length)return null;const r=a.clips[s];return a.clips[s]=i,r}moveClip(e,s,i,a){const r=this.data.timeline.tracks[e];if(!r||s<0||s>=r.clips.length)return null;const n=this.data.timeline.tracks[i];if(!n)return null;const[o]=r.clips.splice(s,1);if(!o)return null;a&&Object.assign(o,a);const l=typeof o.start=="number"?o.start:0;let c=0;for(let f=0;f<n.clips.length;f+=1){const h=n.clips[f].start;if(l<(typeof h=="number"?h:0))break;c+=1}return n.clips.splice(c,0,o),o}setBackground(e){this.data.timeline.background=e}setSoundtrack(e){this.data.timeline.soundtrack=e}getFonts(){return this.data.timeline.fonts??[]}addFont(e){this.data.timeline.fonts||(this.data.timeline.fonts=[]),this.data.timeline.fonts.some(s=>s.src===e)||this.data.timeline.fonts.push({src:e})}removeFont(e){this.data.timeline.fonts&&(this.data.timeline.fonts=this.data.timeline.fonts.filter(s=>s.src!==e))}setFonts(e){this.data.timeline.fonts=e}setSize(e){this.data.output.size={width:e.width,height:e.height}}setFormat(e){this.data.output.format=e}setFps(e){this.data.output.fps=e}setResolution(e){this.data.output.resolution=e}clearResolution(){delete this.data.output.resolution}setAspectRatio(e){this.data.output.aspectRatio=e}clearAspectRatio(){delete this.data.output.aspectRatio}clearSize(){delete this.data.output.size}setMergeFields(e){this.data.merge=e}setClipBinding(e,s,i){let a=this.clipBindings.get(e);a||(a=new Map,this.clipBindings.set(e,a)),a.set(s,i)}getClipBinding(e,s){return this.clipBindings.get(e)?.get(s)}removeClipBinding(e,s){const i=this.clipBindings.get(e);i&&(i.delete(s),i.size===0&&this.clipBindings.delete(e))}getClipBindings(e){return this.clipBindings.get(e)}setClipBindingsForClip(e,s){s.size===0?this.clipBindings.delete(e):this.clipBindings.set(e,new Map(s))}clearClipBindings(e){this.clipBindings.delete(e)}getClipIdsWithBindings(){return Array.from(this.clipBindings.keys())}toJSON(){const e=structuredClone(this.data);for(const s of e.timeline.tracks)for(const i of s.clips){const a=i.id;if(a){const r=this.clipBindings.get(a);if(r)for(const[n,{placeholder:o}]of r)ps(i,n,o)}delete i.id}return e.merge?.length===0&&delete e.merge,e}static fromJSON(e){return new Ai(e)}clone(){return new Ai(this.data)}}const U0=new Set(["asset","start","length","id"]),Qk=new Set(["text-to-image","image-to-video","text-to-speech"]);class $k{constructor(e){this.edit=e,this.edit.getInternalEvents().on(ot.Resolved,this.onResolved)}isReconciling=!1;enableCreation=!0;onResolved=({edit:e})=>{this.reconcile(e)};async reconcileInitial(e){const s=this.reconcile(e);return await Promise.all(s.pendingLoads),s}reconcile(e){if(this.isReconciling)return{created:[],updated:[],disposed:[],pendingLoads:[]};this.isReconciling=!0;try{const s=[],i={created:[],updated:[],disposed:[],pendingLoads:s},a=new Set;for(let n=0;n<e.timeline.tracks.length;n+=1){const o=e.timeline.tracks[n];for(let l=0;l<o.clips.length;l+=1){const c=o.clips[l],f=c.id;if(f){a.add(f);const h=this.edit.getPlayerByClipId(f);if(h){const d=this.updatePlayer(h,c,n);d==="recreate"?(this.disposePlayer(f),s.push(this.createPlayer(c,f,n,l)),i.disposed.push(f),i.created.push(f)):d&&i.updated.push(f)}else this.enableCreation&&(this.createPlayer(c,f,n,l),i.created.push(f))}}}const r=this.findOrphanedPlayers(a);for(const n of r)this.disposePlayer(n),i.disposed.push(n);return(i.created.length>0||i.disposed.length>0||i.updated.length>0)&&this.rebuildTracksOrdering(e),this.syncTrackContainers(e.timeline.tracks.length),i}finally{this.isReconciling=!1}}updateSinglePlayer(e,s,i,a=0){const r=this.updatePlayer(e,s,i);if(r==="recreate"){const{clipId:n}=e;return n&&(this.disposePlayer(n),this.createPlayer(s,n,i,a)),"recreate"}return r}createPlayer(e,s,i,a){const r=this.edit.createPlayerFromAssetType(e);r.layer=i+1,r.clipId=s,this.edit.registerPlayerByClipId(s,r),this.edit.addPlayerToTracksArray(i,r),this.edit.addPlayerToContainer(i,r);const n=e.asset?.type??"unknown";return r.load().then(()=>{this.edit.getInternalEvents().emit(ot.PlayerLoaded,{player:r,trackIndex:i,clipIndex:a}),Qk.has(n)&&this.edit.getInternalEvents().emit(fe.ClipUnresolved,{trackIndex:i,clipIndex:a,assetType:n,clipId:s})}).catch(l=>{const c=l instanceof Error?l.message:String(l);this.edit.getInternalEvents().emit(fe.ClipLoadFailed,{trackIndex:i,clipIndex:a,error:c,assetType:n})})}updatePlayer(e,s,i){const a=e.clipConfiguration.asset?.type,r=s.asset?.type;if(a!==r)return"recreate";let n=!1;const o=e.layer-1,l=e.clipConfiguration.start,c=e.clipConfiguration.length;return(l!==s.start||c!==s.length)&&(e.setResolvedTiming({start:s.start,length:s.length}),e.reconfigureAfterRestore(),n=!0),o!==i&&(e.layer=i+1,this.edit.movePlayerBetweenTracks(e,o,i),n=!0),this.assetChanged(e.clipConfiguration.asset,s.asset)&&(this.updateAsset(e,s.asset),n=!0),this.clipPropertiesChanged(e.clipConfiguration,s)&&(this.updateClipProperties(e,s),n=!0),n}clipPropertiesChanged(e,s){const i=e,a=s,r=new Set([...Object.keys(i),...Object.keys(a)]);for(const n of r)if(!U0.has(n)&&JSON.stringify(i[n])!==JSON.stringify(a[n]))return!0;return!1}updateClipProperties(e,s){const i=e.clipConfiguration,a=s,r=new Set([...Object.keys(i),...Object.keys(a)]);for(const n of r)U0.has(n)||(a[n]!==void 0?i[n]=a[n]:delete i[n]);e.reconfigureAfterRestore()}assetChanged(e,s){return JSON.stringify(e)!==JSON.stringify(s)}updateAsset(e,s){const i=e.clipConfiguration.asset?.src,a=s?.src;e.clipConfiguration.asset=s,i!==a&&e.reloadAsset?e.reloadAsset().then(()=>{e.reconfigureAfterRestore()}).catch(r=>{console.error("Failed to reload asset:",r)}):e.reconfigureAfterRestore()}syncTrackContainers(e){const s=this.edit.getTracks().length;if(e>s)for(let i=s;i<e;i+=1)this.edit.ensureTrackExists(i);else if(e<s)for(let i=s-1;i>=e;i-=1)this.edit.removeEmptyTrack(i)}findOrphanedPlayers(e){const s=[];for(const[i]of this.edit.getPlayerMap())e.has(i)||s.push(i);return s}disposePlayer(e){const s=this.edit.getPlayerByClipId(e);s&&(this.edit.unregisterPlayerByClipId(e),this.edit.queuePlayerForDisposal(s))}rebuildTracksOrdering(e){const s=this.edit.getTracks();for(let i=0;i<s.length;i+=1)s[i]=[];for(let i=0;i<e.timeline.tracks.length;i+=1){for(;s.length<=i;)s.push([]);for(const a of e.timeline.tracks[i].clips){const r=a.id;if(r){const n=this.edit.getPlayerByClipId(r);n&&s[i].push(n)}}}}dispose(){this.edit.getInternalEvents().off(ot.Resolved,this.onResolved)}}function G0(t,e){function s(i){if(typeof i=="string"&&e.isMergeFieldTemplate(i)){const a=e.resolveToNumber(i);return a!==null?a:e.resolve(i)}if(Array.isArray(i))return i.map(s);if(i!==null&&typeof i=="object"){const a={};for(const[r,n]of Object.entries(i))a[r]=s(n);return a}return i}return s(structuredClone(t))}function eN(t){const e=new Map,s=new Map,i=[];for(let a=0;a<t.getTrackCount();a+=1){const r=t.getClipsInTrack(a);for(let n=0;n<r.length;n+=1){const o=r[n];if(!o.id)throw new Error(`Clip at track ${a}, index ${n} is missing an ID. EditDocument hydration may have been skipped.`);const l=o.alias??o.id,c={clip:o,trackIndex:a,clipIndex:n};if(i.push({...c,id:l}),o.alias){if(s.has(o.alias))throw new Error(`Duplicate alias "${o.alias}" found. Each alias must be unique.`);s.set(o.alias,c)}}}for(let a=0;a<t.getTrackCount();a+=1){const r=t.getClipsInTrack(a);for(let n=0;n<r.length;n+=1){const o=r[n],l=o.alias??o.id,c=new Set;if(Kt(o.start)){const f=ka(o.start);if(!s.has(f))throw new Error(`Alias reference "alias://${f}" not found. No clip defines alias "${f}".`);c.add(f)}if(Kt(o.length)){const f=ka(o.length);if(!s.has(f))throw new Error(`Alias reference "alias://${f}" not found. No clip defines alias "${f}".`);c.add(f)}if(o.start==="auto"&&n>0){const f=r[n-1],h=f.alias??f.id;c.add(h)}c.size>0&&e.set(l,c)}}return{dependencies:e,clipsByAlias:s,allClips:i}}function tN(t){const e=new Set,s=new Set;function i(a,r){e.add(a),s.add(a);const n=t.get(a);if(n)for(const o of n){if(s.has(o))return[...r,o];if(!e.has(o)){const l=i(o,[...r,o]);if(l)return l}}return s.delete(a),null}for(const a of t.keys())if(!e.has(a)){const r=i(a,[a]);if(r)return r}return null}function sN(t,e){const s=[],i=new Set;function a(r){if(i.has(r))return;i.add(r);const n=t.get(r);if(n)for(const o of n)a(o);s.push(r)}for(const r of t.keys())a(r);for(const r of e)a(r);return s}function W0(t,e,s){let i;if(t.start==="auto")i=e;else if(Kt(t.start)){const n=ka(t.start),o=s.get(n);if(!o)throw new Error(`Internal error: Alias "${n}" not resolved.`);i=o.start}else i=t.start;let a,r=!1;if(t.length==="end")a=1,r=!0;else if(t.length==="auto")a=3;else if(Kt(t.length)){const n=ka(t.length),o=s.get(n);if(!o)throw new Error(`Internal error: Alias "${n}" not resolved.`);a=o.length}else a=t.length;return{...t,id:t.id??crypto.randomUUID(),start:i,length:a,pendingEndLength:r||void 0}}function iN(t){let e=0;for(const s of t)for(const i of s.clips)if(!i.pendingEndLength){const a=i.start+i.length;a>e&&(e=a)}return e}function Fo(t){const{pendingEndLength:e,...s}=t;return s}function aN(t,e,s){const i=t.getClipById(e);if(!i)return null;const{clip:a,trackIndex:r,clipIndex:n}=i,l=G0(a,s.mergeFields),c=s.resolvedAliases??new Map,f=W0(l,s.previousClipEnd,c);return f.pendingEndLength&&s.cachedTimelineEnd!==void 0&&(f.length=Math.max(s.cachedTimelineEnd-f.start,.1)),{resolved:Fo(f),trackIndex:r,clipIndex:n}}function Y0(t,e){const{dependencies:s,allClips:i}=eN(t);if(s.size>0){const y=tN(s);if(y)throw new Error(`Circular alias reference detected: ${y.join(" -> ")}`)}const a=i.map(y=>y.id),r=sN(s,a),n=new Map;for(const y of i)n.set(y.id,y);const o=new Map,l=new Map,c=new Map;for(const y of r){const m=n.get(y);if(m){const{clip:C,trackIndex:E,clipIndex:F}=m,N=G0(C,e.mergeFields),w=c.get(E)??0,T=W0(N,w,l);o.set(`${E}-${F}`,T);const b=T.start+T.length,U=c.get(E)??0;b>U&&c.set(E,b),C.alias&&l.set(C.alias,{start:T.start,length:T.length})}}const f=[];for(let y=0;y<t.getTrackCount();y+=1){const m=t.getClipsInTrack(y).length,C=[];for(let E=0;E<m;E+=1){const F=o.get(`${y}-${E}`);if(!F)throw new Error(`Internal error: Clip at track ${y}, index ${E} was not resolved.`);C.push(F)}f.push({clips:C})}const h=iN(f),d=f.map(y=>({clips:y.clips.map(m=>{if(m.pendingEndLength){const C=Math.max(h-m.start,.1);return Fo({...m,length:C})}return Fo(m)})}));return{timeline:{background:t.getBackground(),tracks:d,fonts:t.getFonts()},output:t.getOutput()}}class Si{static MAX_HISTORY_SIZE=100;static SEEK_ELAPSED_MARKER=101;document;size;backgroundColor;tracks;playbackTime;totalDuration;isPlaying;get clips(){return this.tracks.flat()}assetLoader;internalEvents;events;canvas=null;timingManager;lumaMaskController;playerReconciler;outputSettings;selectionManager;mergeFieldService;commandHistory=[];commandIndex=-1;commandQueue=new Jk;clipsToDispose=new Set;clipErrors=new Map;playerByClipId=new Map;lumaContentRelations=new Map;fontMetadata=new Map;isBatchingEvents=!1;syncCorrectionCount=0;isExporting=!1;lastResolved=null;constructor(e){Ui.parse(e),this.tracks=[],this.playbackTime=0,this.totalDuration=0,this.isPlaying=!1,this.document=new Ai(e);const s=this.document.getResolution(),i=this.document.getAspectRatio();this.backgroundColor=this.document.getBackground()??"#000000",this.size=s?zr(s,i):this.document.getSize(),this.assetLoader=new Lr,this.internalEvents=new z0,this.events=this.internalEvents,this.lumaMaskController=new Lk(()=>this.canvas,()=>this.tracks,this.internalEvents),this.playerReconciler=new $k(this),this.mergeFieldService=new Uk(this.internalEvents),this.outputSettings=new Wk(this),this.selectionManager=new Yk(this),this.timingManager=new Kk(this),this.setupIntentListeners()}async load(){await this.initializeFromDocument()}async initializeFromDocument(e="load"){const s=this.document.toJSON(),i=s.merge??[];this.mergeFieldService.loadFromSerialized(i),this.lastResolved=null;const a=this.detectMergeFieldBindings(i),r=Ui.parse(s);await Promise.all((r.timeline.fonts??[]).map(async o=>{const l=o.src,c={src:l,parser:Dr.Name},f=await this.assetLoader.load(l,c);if(f?.family){const h=f.family.replace(/^["']|["']$/g,""),{baseFontFamily:d,fontWeight:y}=Dt(h);this.fontMetadata.set(l,{baseFamilyName:d,weight:y})}return f}));const n=this.getResolvedEdit();this.lumaMaskController.initialize(),await this.playerReconciler.reconcileInitial(n),this.normalizeLumaAttachments();for(const[o,l]of a)l.size>0&&this.document.setClipBindingsForClip(o,l);await this.timingManager.resolveAllTiming(),this.updateTotalDuration(),r.timeline.soundtrack&&await this.loadSoundtrack(r.timeline.soundtrack),this.internalEvents.emit(fe.TimelineUpdated,{current:this.getEdit()}),this.emitEditChanged(e)}getInternalEvents(){return this.internalEvents}update(e,s){for(const i of this.clips)i.shouldDispose&&this.queueDisposeClip(i),i.update(e,s);this.disposeClips(),this.lumaMaskController.update(),this.isPlaying&&(this.playbackTime=Math.max(0,Math.min(this.playbackTime+gu(s),this.totalDuration)),this.playbackTime===this.totalDuration&&this.pause())}dispose(){this.clearClips(),this.lumaMaskController.dispose(),this.playerReconciler.dispose();for(const e of this.commandHistory)e.dispose?.();this.commandHistory=[],this.commandIndex=-1,this.lumaContentRelations.clear(),M0.cleanup()}updateCanvasForSize(){this.internalEvents.emit(ot.ViewportSizeChanged,{width:this.size.width,height:this.size.height,backgroundColor:this.backgroundColor}),this.internalEvents.emit(ot.ViewportNeedsZoomToFit)}play(){this.isPlaying=!0,this.internalEvents.emit(fe.PlaybackPlay)}pause(){this.isPlaying=!1,this.internalEvents.emit(fe.PlaybackPause)}seek(e){this.playbackTime=Math.max(0,Math.min(e,this.totalDuration)),this.pause(),this.update(0,Si.SEEK_ELAPSED_MARKER)}stop(){this.seek(0)}async loadEdit(e){if(Ui.parse(e),this.tracks.length>0&&!this.hasStructuralChanges(e)){this.lastResolved=null;const n=structuredClone(e);this.preserveClipIdsForGranularUpdate(n);const o=this.document.getTracks(),l=this.document.getOutput();this.document=new Ai(n),this.isBatchingEvents=!0,await this.applyGranularChanges(n,o,l),this.isBatchingEvents=!1,this.emitEditChanged("loadEdit:granular");return}const s=this.document,i=this.lastResolved,a=this.size,r=this.backgroundColor;try{this.lastResolved=null,this.document=new Ai(e);const n=this.document.getResolution(),o=this.document.getAspectRatio();this.size=n?zr(n,o):this.document.getSize(),this.backgroundColor=this.document.getBackground()??"#000000",this.internalEvents.emit(ot.ViewportSizeChanged,{width:this.size.width,height:this.size.height,backgroundColor:this.backgroundColor}),this.internalEvents.emit(ot.ViewportNeedsZoomToFit),this.clearClips(),await this.initializeFromDocument("loadEdit")}catch(n){throw this.document=s,this.lastResolved=i,this.size=a,this.backgroundColor=r,n}}async loadSoundtrack(e){const s={id:crypto.randomUUID(),asset:{type:"audio",src:e.src,effect:e.effect,volume:e.volume??1},fit:"crop",start:0,length:this.totalDuration},i=this.createPlayerFromAssetType(s);i.layer=this.tracks.length+1,await this.addPlayer(this.tracks.length,i)}getEdit(){const e=this.document.toJSON(),s=this.mergeFieldService.toSerializedArray();return s.length>0&&(e.merge=s),e}validateEdit(e){const s=Ui.safeParse(e);return s.success?{valid:!0,errors:[]}:{valid:!1,errors:s.error.issues.map(i=>({path:i.path.join("."),message:i.message}))}}getResolvedEdit(){return this.lastResolved||(this.lastResolved=Y0(this.document,{mergeFields:this.mergeFieldService})),this.lastResolved}getResolvedClip(e,s){return this.getResolvedEdit()?.timeline?.tracks?.[e]?.clips?.[s]??null}getResolvedClipById(e){const s=this.getResolvedEdit();for(const i of s.timeline.tracks)for(const a of i.clips)if(a.id===e)return a;return null}getClipId(e,s){return this.document?.getClipId(e,s)??null}getDocumentClip(e,s){return this.document?.getClip(e,s)??null}getDocument(){return this.document}resolve(){return this.lastResolved=Y0(this.document,{mergeFields:this.mergeFieldService}),this.internalEvents.emit(ot.Resolved,{edit:this.lastResolved}),this.lastResolved}resolveClip(e){const s=this.getPlayerByClipId(e);if(!s)return!1;const i=this.document.getClipById(e);if(i?.clip.alias)return this.resolve(),!0;const a=i?.clip;if(a&&(Kt(a.start)||Kt(a.length)))return this.resolve(),!0;const r=s.layer-1,n=this.tracks[r],o=n?n.indexOf(s):-1;if(o<0)return!1;const l=o>0?n[o-1]:null,c=l?l.getEnd():0,f={mergeFields:this.mergeFieldService,previousClipEnd:c,cachedTimelineEnd:this.timingManager.getTimelineEnd()},h=aN(this.document,e,f);if(!h)return!1;if(this.lastResolved){const y=this.lastResolved.timeline.tracks[h.trackIndex];y&&y.clips[h.clipIndex]&&(y.clips[h.clipIndex]=h.resolved)}return this.playerReconciler.updateSinglePlayer(s,h.resolved,h.trackIndex,h.clipIndex)!==!1}addClip(e,s){Wa.parse(s);const i=new Ak(e,s);return this.executeCommand(i)}getClip(e,s){const i=this.tracks[e];return!i||s<0||s>=i.length?null:i[s].clipConfiguration}getClipError(e,s){return this.clipErrors.get(`${e}-${s}`)??null}clearClipErrorAndShift(e,s){this.clipErrors.delete(`${e}-${s}`);const i=[];for(const[a,r]of this.clipErrors){const[n,o]=a.split("-").map(Number);n===e&&o>s&&i.push({oldKey:a,newKey:`${n}-${o-1}`,value:r})}for(const{oldKey:a,newKey:r,value:n}of i)this.clipErrors.delete(a),this.clipErrors.set(r,n)}getPlayerClip(e,s){const i=this.tracks[e];return!i||s<0||s>=i.length?null:i[s]}getPlayerByClipId(e){return this.playerByClipId.get(e)??null}getDocumentClipById(e){return this.document?.getClipById(e)?.clip??null}registerPlayerByClipId(e,s){this.playerByClipId.set(e,s)}unregisterPlayerByClipId(e){this.playerByClipId.delete(e)}getPlayerMap(){return this.playerByClipId}addPlayerToTracksArray(e,s){for(;this.tracks.length<=e;)this.tracks.push([]);this.tracks[e].push(s)}movePlayerBetweenTracks(e,s,i){const a=this.tracks[s];if(a){const r=a.indexOf(e);r!==-1&&a.splice(r,1)}for(;this.tracks.length<=i;)this.tracks.push([]);this.tracks[i].push(e),this.movePlayerToTrackContainer(e,s,i)}queuePlayerForDisposal(e){this.queueDisposeClip(e),this.disposeClips()}ensureTrackExists(e){for(;this.tracks.length<=e;)this.tracks.push([])}removeEmptyTrack(e){if(e<0||e>=this.tracks.length)return;const s=this.tracks[e];if(s&&s.length>0){console.warn(`Cannot remove non-empty track ${e}`);return}this.tracks.splice(e,1),this.internalEvents.emit(ot.TrackContainerRemoved,{trackIndex:e});for(let i=e;i<this.tracks.length;i+=1)for(const a of this.tracks[i])a.layer=i+1}getOriginalAsset(e,s){const i=this.getPlayerClip(e,s);if(!i)return;const a=i.getExportableClip();if(!a)return;const{clipId:r}=i;if(r&&this.document){const n=this.document.getClipBindings(r);if(n){for(const[o,{placeholder:l}]of n)if(o.startsWith("asset.")){const c=o.slice(6);ps(a.asset,c,l)}}}return a.asset}async deleteClip(e,s){const i=this.tracks[e];if(!i)return;const a=i[s];if(!a)return;if(a.playerType!==Qe.Luma){const o=i.findIndex(l=>l.playerType===Qe.Luma);if(o!==-1){const l=o<s?s-1:s,c=new Ao(e,o);await this.executeCommand(c);const f=new Ao(e,l);await this.executeCommand(f);return}}const n=new Ao(e,s);await this.executeCommand(n)}splitClip(e,s,i){const a=new Ok(e,s,i);return this.executeCommand(a)}async addTrack(e,s){oc.parse(s);const i=new Sk(e);await this.executeCommand(i);for(const a of s.clips)await this.addClip(e,a)}getTrack(e){const s=this.clips.filter(i=>i.layer===e+1);return s.length===0?null:{clips:s.map(i=>i.clipConfiguration)}}deleteTrack(e){const s=new R0(e);this.executeCommand(s)}recordSyncCorrection(){this.syncCorrectionCount+=1}undo(){return this.commandQueue.enqueue(async()=>{if(this.commandIndex>=0){const e=this.commandHistory[this.commandIndex];if(e.undo){const s=this.createCommandContext();await Promise.resolve(e.undo(s)),this.commandIndex-=1,this.internalEvents.emit(fe.EditUndo,{command:e.name}),this.emitEditChanged(`undo:${e.name}`)}}})}redo(){return this.commandQueue.enqueue(async()=>{if(this.commandIndex<this.commandHistory.length-1){const e=this.commandIndex+1,s=this.commandHistory[e],i=this.createCommandContext();await Promise.resolve(s.execute(i)),this.commandIndex=e,this.internalEvents.emit(fe.EditRedo,{command:s.name}),this.emitEditChanged(`redo:${s.name}`)}})}setUpdatedClip(e,s=null,i=null){const a=e.layer-1,r=this.tracks[a],n=r?r.indexOf(e):-1,o=new Vo(s,i,{trackIndex:a,clipIndex:n});this.executeCommand(o)}updateClipInDocument(e,s){const i=this.document.getClipById(e);i&&this.document.updateClip(i.trackIndex,i.clipIndex,s)}commitClipUpdate(e,s,i){const a=this.document.getClipById(e);if(!a){console.warn(`commitClipUpdate: clip ${e} not found in document`);return}kn.parse(i);const r=new Vo(s,structuredClone(i),{trackIndex:a.trackIndex,clipIndex:a.clipIndex});this.addCommandToHistory(r)}pushCommandToHistory(e){const s=this.commandHistory.slice(this.commandIndex+1);for(const i of s)i.dispose?.();for(this.commandHistory=this.commandHistory.slice(0,this.commandIndex+1),this.commandHistory.push(e),this.commandIndex+=1;this.commandHistory.length>Si.MAX_HISTORY_SIZE;)this.commandHistory.shift()?.dispose?.(),this.commandIndex-=1}addCommandToHistory(e){this.pushCommandToHistory(e),this.emitEditChanged(`commit:${e.name}`)}updateClip(e,s,i){const a=this.getPlayerClip(e,s);if(!a)return console.warn(`Clip not found at track ${e}, index ${s}`),Promise.resolve();const r=this.document?.getClip(e,s),n=structuredClone(r??a.clipConfiguration),o=structuredClone(r??a.clipConfiguration),l=So(o,i);kn.parse(l);const c=new Vo(n,l,{trackIndex:e,clipIndex:s});return this.executeCommand(c)}updateClipTiming(e,s,i){if(!this.getPlayerClip(e,s)){console.warn(`Clip not found at track ${e}, index ${s}`);return}const r=new Mk(e,s,i);this.executeCommand(r)}updateTextContent(e,s,i){const a=e.layer-1,r=this.tracks[a]?.indexOf(e)??-1;if(r<0){console.warn("UpdateTextContent: clip not found in track");return}const n=new Rk(a,r,s);this.executeCommand(n)}executeEditCommand(e){return this.executeCommand(e)}executeCommand(e){return this.commandQueue.enqueue(async()=>{const s=this.createCommandContext(),i=await Promise.resolve(e.execute(s));this.handleCommandResult(e,i)})}handleCommandResult(e,s){s.status==="success"&&(this.pushCommandToHistory(e),this.emitEditChanged(e.name))}emitEditChanged(e){this.isBatchingEvents||this.internalEvents.emit(fe.EditChanged,{source:e,timestamp:Date.now()})}detectMergeFieldBindings(e){const s=new Map;if(!e.length)return s;const i=new Map;for(const{find:a,replace:r}of e){const n=typeof r=="string"?r:JSON.stringify(r);i.set(a.toUpperCase(),n)}for(let a=0;a<this.document.getTrackCount();a+=1){const r=this.document.getClipsInTrack(a);for(let n=0;n<r.length;n+=1){const o=this.document.getClipId(a,n);if(o){const l=this.detectBindingsInObject(r[n],"",i);l.size>0&&s.set(o,l)}}}return s}detectBindingsInObject(e,s,i){const a=new Map;if(typeof e=="string"){if(/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi.test(e)){const o=e.replace(/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi,(l,c)=>i.get(c.toUpperCase())??l);a.set(s,{placeholder:e,resolvedValue:o})}return a}if(Array.isArray(e)){for(let r=0;r<e.length;r+=1){const n=s?`${s}[${r}]`:`[${r}]`,o=this.detectBindingsInObject(e[r],n,i);for(const[l,c]of o)a.set(l,c)}return a}if(e!==null&&typeof e=="object")for(const[r,n]of Object.entries(e)){const o=s?`${s}.${r}`:r,l=this.detectBindingsInObject(n,o,i);for(const[c,f]of l)a.set(c,f)}return a}hasStructuralChanges(e){if(!this.document)return!0;const s=this.document.getTracks(),i=e.timeline.tracks;if(s.length!==i.length)return!0;for(let a=0;a<s.length;a+=1){if(s[a].clips.length!==i[a].clips.length)return!0;for(let r=0;r<s[a].clips.length;r+=1){const n=s[a].clips[r]?.asset?.type,o=i[a].clips[r]?.asset?.type;if(n!==o)return!0}}return JSON.stringify(this.document.getMergeFields()??[])!==JSON.stringify(e.merge??[])||JSON.stringify(this.document.getFonts())!==JSON.stringify(e.timeline.fonts??[])||JSON.stringify(this.document.getSoundtrack())!==JSON.stringify(e.timeline.soundtrack)}preserveClipIdsForGranularUpdate(e){if(!this.document)return;const s=this.document.getTracks();for(let i=0;i<e.timeline.tracks.length;i+=1){const a=s[i],r=e.timeline.tracks[i];if(a&&r)for(let n=0;n<r.clips.length;n+=1){const o=this.document.getClipId(i,n);o&&(r.clips[n].id=o)}}}async applyGranularChanges(e,s,i){const a=e.output;if(a?.size&&(i?.size?.width!==a.size.width||i?.size?.height!==a.size.height)){const o=a.size.width??this.size.width,l=a.size.height??this.size.height;await this.setOutputSize(o,l)}a?.fps!==void 0&&i?.fps!==a.fps&&await this.setOutputFps(a.fps),a?.format!==void 0&&i?.format!==a.format&&await this.setOutputFormat(a.format),a?.destinations&&JSON.stringify(i?.destinations)!==JSON.stringify(a.destinations)&&await this.setOutputDestinations(a.destinations),a?.resolution!==void 0&&i?.resolution!==a.resolution&&await this.setOutputResolution(a.resolution),a?.aspectRatio!==void 0&&i?.aspectRatio!==a.aspectRatio&&await this.setOutputAspectRatio(a.aspectRatio);const r=e.timeline?.background;r&&this.backgroundColor!==r&&await this.setTimelineBackground(r);const n=e.timeline.tracks;for(let o=0;o<n.length;o+=1){const l=s[o].clips,c=n[o].clips;for(let f=0;f<c.length;f+=1){const h=l[f],d=c[f];JSON.stringify(h)!==JSON.stringify(d)&&await this.updateClip(o,f,d)}}}createCommandContext(){return{getClips:()=>this.clips,getTracks:()=>this.tracks,getTrack:e=>e>=0&&e<this.tracks.length?this.tracks[e]:null,getContainer:()=>this.getViewportContainer(),addPlayer:(e,s)=>this.addPlayer(e,s),addPlayerToContainer:(e,s)=>{this.addPlayerToContainer(e,s)},createPlayerFromAssetType:e=>this.createPlayerFromAssetType(e),queueDisposeClip:e=>this.queueDisposeClip(e),disposeClips:()=>this.disposeClips(),clearClipError:(e,s)=>this.clearClipErrorAndShift(e,s),undeleteClip:(e,s)=>{let i=0;if(e>=0&&e<this.tracks.length){const a=this.tracks[e];i=a.length;for(let r=0;r<a.length;r+=1)if(a[r].getStart()>s.getStart()){i=r;break}a.splice(i,0,s)}if(this.document){const a=s.getExportableClip();this.document.addClip(e,a,i);const r=this.document.getClipId(e,i);r&&(s.clipId=r,this.playerByClipId.set(r,s))}this.addPlayerToContainer(e,s),s.load().catch(a=>{const r=s.clipConfiguration?.asset?.type??"unknown",n=a instanceof Error?a.message:String(a);this.clipErrors.set(`${e}-${i}`,{error:n,assetType:r}),this.internalEvents.emit(fe.ClipLoadFailed,{trackIndex:e,clipIndex:i,error:n,assetType:r})}),this.updateTotalDuration()},setUpdatedClip:()=>{},restoreClipConfiguration:(e,s)=>{const i=structuredClone(s),a=e.clipConfiguration;for(const r of Object.keys(a))delete a[r];if(Object.assign(a,i),e.reconfigureAfterRestore(),this.document){const r=this.findClipIndices(e);if(r){const n=e.getExportableClip();this.document.replaceClip(r.trackIndex,r.clipIndex,n)}}},updateDuration:()=>this.updateTotalDuration(),emitEvent:(e,...s)=>this.internalEvents.emit(e,...s),findClipIndices:e=>this.selectionManager.findClipIndices(e),getClipAt:(e,s)=>this.getClipAt(e,s),getSelectedClip:()=>this.selectionManager.getSelectedClip(),setSelectedClip:e=>{this.selectionManager.setSelectedClip(e)},movePlayerToTrackContainer:(e,s,i)=>this.movePlayerToTrackContainer(e,s,i),getEditState:()=>this.getResolvedEdit(),propagateTimingChanges:(e,s)=>this.propagateTimingChanges(e,s),resolveClipAutoLength:e=>this.resolveClipAutoLength(e),getMergeFields:()=>this.mergeFieldService,getOutputSize:()=>this.outputSettings.getSize(),setOutputSize:(e,s)=>this.outputSettings.setSize(e,s),getOutputFps:()=>this.outputSettings.getFps(),setOutputFps:e=>this.outputSettings.setFps(e),getOutputFormat:()=>this.outputSettings.getFormat(),setOutputFormat:e=>this.outputSettings.setFormat(e),getOutputResolution:()=>this.outputSettings.getResolution(),setOutputResolution:e=>this.outputSettings.setResolution(e),getOutputAspectRatio:()=>this.outputSettings.getAspectRatio(),setOutputAspectRatio:e=>this.outputSettings.setAspectRatio(e),getOutputDestinations:()=>this.outputSettings.getDestinations(),setOutputDestinations:e=>this.outputSettings.setDestinations(e),getTimelineBackground:()=>this.getTimelineBackground(),setTimelineBackground:e=>this.setTimelineBackgroundInternal(e),getDocument:()=>this.document,getDocumentTrack:e=>this.document?.getTrack(e)??null,getDocumentClip:(e,s)=>this.document?.getClip(e,s)??null,documentUpdateClip:(e,s,i)=>{if(!this.document)throw new Error("Document not initialized - cannot update clip");this.document.updateClip(e,s,i)},documentAddClip:(e,s,i)=>{if(!this.document)throw new Error("Document not initialized - cannot add clip");for(;this.document.getTrackCount()<=e;)this.document.addTrack(this.document.getTrackCount());return this.document.addClip(e,s,i)},documentRemoveClip:(e,s)=>{if(!this.document)throw new Error("Document not initialized - cannot remove clip");return this.document.removeClip(e,s)},derivePlayerFromDocument:(e,s)=>{const i=this.document?.getClip(e,s);if(!i)throw new Error(`derivePlayerFromDocument: No document clip at ${e}/${s} - state desync`);const a=this.getClipAt(e,s);if(!a)throw new Error(`derivePlayerFromDocument: No player at ${e}/${s} - state desync`);const{asset:r,...n}=i;Object.assign(a.clipConfiguration,n),a.reconfigureAfterRestore()},buildResolutionContext:(e,s)=>{let i=0;if(s>0){const o=this.tracks[e];o&&o[s-1]&&(i=o[s-1].getEnd())}const a=_o(this.tracks);let r=null;const n=this.getClipAt(e,s);return n&&n.getTimingIntent().length==="auto"&&(r=n.getLength()),{previousClipEnd:i,timelineEnd:a,intrinsicDuration:r}},resolve:()=>this.resolve(),resolveClip:e=>this.resolveClip(e),getPlayerByClipId:e=>this.playerByClipId.get(e)??null,registerPlayerByClipId:(e,s)=>{this.playerByClipId.set(e,s)},unregisterPlayerByClipId:e=>{this.playerByClipId.delete(e)},setClipBinding:(e,s,i)=>{this.document?.setClipBinding(e,s,i)},getClipBinding:(e,s)=>this.document?.getClipBinding(e,s),removeClipBinding:(e,s)=>{this.document?.removeClipBinding(e,s)},getClipBindings:e=>this.document?.getClipBindings(e),getEditSession:()=>this}}queueDisposeClip(e){this.clipsToDispose.add(e)}disposeClips(){if(this.clipsToDispose.size!==0){for(const e of this.clipsToDispose)e.playerType===Qe.Luma&&(this.lumaMaskController.cleanupForPlayer(e),e.clipId&&this.lumaContentRelations.delete(e.clipId));for(const e of this.clipsToDispose)e.clipId&&this.playerByClipId.delete(e.clipId);for(const e of this.clipsToDispose)this.disposeClip(e);for(const e of this.clipsToDispose){const s=e.layer-1;if(s>=0&&s<this.tracks.length){const i=this.tracks[s].indexOf(e);i!==-1&&this.tracks[s].splice(i,1)}}this.clipsToDispose.clear(),this.updateTotalDuration(),this.cleanupUnusedFonts()}}cleanupUnusedFonts(){if(!this.document)return;const e=this.document.getFonts();if(e.length===0)return;const s=new Set;for(const i of this.clips){const{asset:a}=i.clipConfiguration;a&&a.type==="rich-text"&&a.font?.family&&s.add(a.font.family)}for(const i of e)if(i.src.includes("fonts.gstatic.com")){const r=this.extractFilenameFromUrl(i.src);r&&!s.has(r)&&this.document.removeFont(i.src)}}extractFilenameFromUrl(e){try{const{pathname:s}=new URL(e),i=s.split("/").pop();return i?i.replace(/\.[^.]+$/,""):null}catch{return null}}disposeClip(e){try{const s=this.canvas?.getViewportContainer();if(s){for(const i of s.children)if(i instanceof X.Container&&i.label?.toString().startsWith("shotstack-track-")&&i.children.includes(e.getContainer())){i.removeChild(e.getContainer());break}}}catch(s){console.warn(`Attempting to unmount an unmounted clip: ${s}`)}this.unloadClipAssets(e),this.timingManager.invalidateTimelineEndCache(),e.dispose()}unloadClipAssets(e){const{asset:s}=e.clipConfiguration;s&&"src"in s&&typeof s.src=="string"&&this.assetLoader.decrementRef(s.src)&&X.Assets.cache.has(s.src)&&X.Assets.unload(s.src)}clearClips(){for(const e of this.clips)this.disposeClip(e);this.tracks=[],this.clipsToDispose.clear(),this.clipErrors.clear(),this.lumaContentRelations.clear(),this.updateTotalDuration()}updateTotalDuration(){let e=0;for(const i of this.tracks)for(const a of i)e=Math.max(e,a.getEnd());const s=this.totalDuration;this.totalDuration=e,s!==this.totalDuration&&this.internalEvents.emit(fe.DurationChanged,{duration:this.totalDuration})}propagateTimingChanges(e,s){this.timingManager.propagateTimingChanges(e,s)}async resolveClipAutoLength(e){const s=e.getTimingIntent();if(s.length!=="auto")return;const i=this.findClipIndices(e);let a=e.getStart();s.start==="auto"&&i&&(a=B0(i.trackIndex,i.clipIndex,this.tracks));const r=await D0(e.clipConfiguration.asset);e.setResolvedTiming({start:a,length:r}),e.reconfigureAfterRestore(),i&&this.propagateTimingChanges(i.trackIndex,i.clipIndex)}addPlayerToContainer(e,s){this.internalEvents.emit(ot.PlayerAddedToTrack,{player:s,trackIndex:e})}movePlayerToTrackContainer(e,s,i){this.internalEvents.emit(ot.PlayerMovedBetweenTracks,{player:e,fromTrackIndex:s,toTrackIndex:i})}createPlayerFromAssetType(e){return M0.create(this,e)}async addPlayer(e,s){for(;this.tracks.length<=e;)this.tracks.push([]);this.tracks[e].push(s),this.internalEvents.emit(ot.PlayerAddedToTrack,{player:s,trackIndex:e}),await s.load(),this.updateTotalDuration()}selectClip(e,s){this.selectionManager.selectClip(e,s)}clearSelection(){this.selectionManager.clearSelection()}isClipSelected(e,s){return this.selectionManager.isClipSelected(e,s)}getSelectedClipInfo(){return this.selectionManager.getSelectedClipInfo()}copyClip(e,s){this.selectionManager.copyClip(e,s)}pasteClip(){this.selectionManager.pasteClip()}hasCopiedClip(){return this.selectionManager.hasCopiedClip()}findClipIndices(e){return this.selectionManager.findClipIndices(e)}getClipAt(e,s){return e>=0&&e<this.tracks.length&&s>=0&&s<this.tracks[e].length?this.tracks[e][s]:null}selectPlayer(e){this.selectionManager.selectPlayer(e)}isPlayerSelected(e){return this.selectionManager.isPlayerSelected(e)}getActivePlayersExcept(e){const s=[];for(const i of this.tracks)for(const a of i)a!==e&&a.isActive()&&s.push(a);return s}showAlignmentGuide(e,s,i,a){this.canvas?.showAlignmentGuide(e,s,i,a)}clearAlignmentGuides(){this.canvas?.clearAlignmentGuides()}moveSelectedClip(e,s){const i=this.getSelectedClipInfo();if(!i)return;const{player:a,trackIndex:r,clipIndex:n}=i,o=this.getResolvedClip(r,n);if(!o)return;const l=structuredClone(o),c=a.calculateMoveOffset(e,s),f=structuredClone(l);f.offset=c,this.setUpdatedClip(a,l,f)}setExportMode(e){this.isExporting=e}isInExportMode(){return this.isExporting}setCanvas(e){this.canvas=e}getCanvas(){return this.canvas}getCanvasZoom(){return this.canvas?.getZoom()??1}getViewportContainer(){if(!this.canvas)throw new Error("Canvas not attached. Viewport container requires Canvas.");return this.canvas.getViewportContainer()}setOutputSize(e,s){const i=new Ek(e,s);return this.executeCommand(i)}setOutputFps(e){const s=new Fk(e);return this.executeCommand(s)}getOutputFps(){return this.outputSettings.getFps()}setOutputFormat(e){const s=new _k(e);return this.executeCommand(s)}getOutputFormat(){return this.outputSettings.getFormat()}setOutputDestinations(e){const s=new Ik(e);return this.executeCommand(s)}getOutputDestinations(){return this.outputSettings.getDestinations()}setOutputResolution(e){const s=new Tk(e);return this.executeCommand(s)}getOutputResolution(){return this.outputSettings.getResolution()}setOutputAspectRatio(e){const s=new Vk(e);return this.executeCommand(s)}getOutputAspectRatio(){return this.outputSettings.getAspectRatio()}getTimelineFonts(){return this.document.getFonts()}getFontMetadata(){return this.fontMetadata}getFontUrlByFamilyAndWeight(e,s){const{baseFontFamily:i}=Dt(e),a=i.toLowerCase();for(const[r,n]of this.fontMetadata)if(n.baseFamilyName.toLowerCase()===a&&n.weight===s)return r;for(const[r,n]of this.fontMetadata)if(n.baseFamilyName.toLowerCase()===a)return r;return null}pruneUnusedFonts(){this.cleanupUnusedFonts()}setTimelineBackground(e){const s=new Pk(e);return this.executeCommand(s)}setTimelineBackgroundInternal(e){pw.parse(e),this.backgroundColor=e,this.document.setBackground(e),this.internalEvents.emit(ot.ViewportSizeChanged,{width:this.size.width,height:this.size.height,backgroundColor:this.backgroundColor}),this.internalEvents.emit(fe.TimelineBackgroundChanged,{color:e})}getTimelineBackground(){return this.backgroundColor}resolveMergeFields(e){return this.mergeFieldService.resolve(e)}getTemplateClip(e,s){const i=this.getPlayerClip(e,s);if(!i)return null;const a=i.getExportableClip();if(!a)return null;const{clipId:r}=i;if(r&&this.document){const n=this.document.getClipBindings(r);if(n)for(const[o,{placeholder:l}]of n)ps(a,o,l)}return a}getTemplateClipById(e){const s=this.getPlayerByClipId(e);if(!s)return null;const i=s.getExportableClip();if(!i||!this.document)return null;const a=this.document.getClipBindings(e);if(a)for(const[r,{placeholder:n}]of a)ps(i,r,n);return i}getTemplateClipText(e,s){const i=this.getTemplateClip(e,s);return i?i.asset?.text??null:null}getLumaClipIdForContent(e){for(const[s,i]of this.lumaContentRelations)if(i===e)return s;return null}getContentClipIdForLuma(e){return this.lumaContentRelations.get(e)??null}setLumaContentRelationship(e,s){this.lumaContentRelations.set(e,s)}clearLumaContentRelationship(e){this.lumaContentRelations.delete(e)}getLumaContentRelationship(e){return this.lumaContentRelations.get(e)}normalizeLumaAttachments(){let e=!1;for(let s=0;s<this.tracks.length;s+=1){const i=this.tracks[s];for(const a of i)if(a.playerType===Qe.Luma){const r=this.findBestContentMatch(s,a);if(r){a.clipId&&r.clipId&&this.lumaContentRelations.set(a.clipId,r.clipId);const n=i.indexOf(a);this.document.updateClip(s,n,{start:r.getStart(),length:r.getLength()}),e=!0}}}e&&this.resolve()}findBestContentMatch(e,s){const i=this.tracks[e],a=s.getStart(),r=a+s.getLength();let n=null,o=0;for(const l of i)if(l.playerType!==Qe.Luma){const c=l.getStart(),f=c+l.getLength(),h=qk(a,r,c,f);h>o&&(o=h,n=l)}return n}setupIntentListeners(){this.internalEvents.on(ot.CanvasClipClicked,e=>{this.selectPlayer(e.player)}),this.internalEvents.on(ot.CanvasBackgroundClicked,()=>{this.clearSelection()})}getTracks(){return this.tracks}getTrackCount(){return this.document.getTrackCount()}getClipCountInTrack(e){return this.document.getClipCountInTrack(e)}}class H0{constructor(e,s,i,a,r,n){this.clipId=e,this.propertyPath=s,this.fieldName=i,this.previousFieldName=a,this.storedPreviousValue=r,this.storedNewValue=n}name="setMergeField";storedPreviousValue;storedNewValue;storedPreviousBinding;updateDocumentClip(e,s,i){const a=e.getDocument();if(!a)return;const r=a.getClipById(this.clipId);if(!r)return;const n=r.clip;if(i)ps(n,this.propertyPath,s);else{const l=(typeof s=="string"?s.trim():"").length>0?Number(s):NaN;ps(n,this.propertyPath,Number.isFinite(l)?l:s)}}async execute(e){if(!e)throw new Error("SetMergeFieldCommand.execute: context is required");const s=e.getMergeFields();if(this.storedPreviousBinding=e.getClipBinding(this.clipId,this.propertyPath),this.fieldName){const i={placeholder:s.createTemplate(this.fieldName),resolvedValue:this.storedNewValue};e.setClipBinding(this.clipId,this.propertyPath,i)}else e.removeClipBinding(this.clipId,this.propertyPath);if(this.fieldName?s.register({name:this.fieldName,defaultValue:this.storedNewValue},{silent:!0}):this.previousFieldName&&s.remove(this.previousFieldName,{silent:!0}),this.fieldName){const i=s.createTemplate(this.fieldName);this.updateDocumentClip(e,i,!0)}else this.updateDocumentClip(e,this.storedNewValue,!1);return e.resolve(),e.emitEvent(fe.MergeFieldChanged,{fields:s.getAll()}),Ee()}async undo(e){if(!e)throw new Error("SetMergeFieldCommand.undo: context is required");const s=e.getMergeFields();return this.storedPreviousBinding?e.setClipBinding(this.clipId,this.propertyPath,this.storedPreviousBinding):e.removeClipBinding(this.clipId,this.propertyPath),this.previousFieldName&&s.register({name:this.previousFieldName,defaultValue:this.storedPreviousValue},{silent:!0}),this.storedPreviousBinding?this.updateDocumentClip(e,this.storedPreviousBinding.placeholder,!0):this.updateDocumentClip(e,this.storedPreviousValue,!1),e.resolve(),e.emitEvent(fe.MergeFieldChanged,{fields:s.getAll()}),Ee()}dispose(){this.storedPreviousBinding=void 0}}function rN(t){if(typeof t!="object"||t===null)return!1;const e=t;return e.type==="text"&&(!e.text||e.text.trim()==="")}function j0(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function nN(t){const e=t.width??100,s=t.height??100,i=j0(t.background?.color??"#000000"),a=t.background?.opacity??1,r=t.background?.borderRadius??0,n=[`width="${e}"`,`height="${s}"`,`fill="${i}"`];if(a!==1&&n.push(`fill-opacity="${a}"`),r>0&&n.push(`rx="${r}"`,`ry="${r}"`),t.stroke?.width&&t.stroke.width>0){const o=j0(t.stroke.color??"#000000");n.push(`stroke="${o}"`),n.push(`stroke-width="${t.stroke.width}"`)}return`<svg viewBox="0 0 ${e} ${s}" xmlns="http://www.w3.org/2000/svg"><rect ${n.join(" ")}/></svg>`}function oN(t){const e=t.asset,s=nN(e),i={...t,asset:{type:"svg",src:s,opacity:1}};return e.width!==void 0&&i.width===void 0&&(i.width=e.width),e.height!==void 0&&i.height===void 0&&(i.height=e.height),i}class lN extends Si{isUpdatingMergeFields=!1;get mergeFields(){return this.mergeFieldService}applyMergeField(e,s,i,a,r){const n=this.getResolvedClipById(e),o=n?Rr(n,s):null,l=r??(o!=null?String(o):""),c=this.getTemplateClipById(e),f=c?Rr(c,s):null,h=typeof f=="string"?this.mergeFieldService.extractFieldName(f):null,d=new H0(e,s,i,h,l,a);return this.executeCommand(d)}removeMergeField(e,s,i){const a=this.getMergeFieldForProperty(e,s);if(!a)return Promise.resolve();const r=new H0(e,s,null,a,i,i);return this.executeCommand(r)}getMergeFieldForProperty(e,s){const i=this.getTemplateClipById(e);if(!i)return null;const a=Rr(i,s);return typeof a=="string"?this.mergeFieldService.extractFieldName(a):null}updateMergeFieldValueLive(e,s){if(!this.isUpdatingMergeFields){this.isUpdatingMergeFields=!0;try{const i=this.mergeFieldService.get(e);if(!i)return;this.mergeFieldService.register({...i,defaultValue:s},{silent:!0});for(const[,a]of this.getPlayerMap())this.updateMergeFieldBindings(a,e,s);this.resolve(),this.getInternalEvents().emit(fe.TimelineUpdated,{current:this.getEdit()})}finally{this.isUpdatingMergeFields=!1}}}isSrcMergeField(e){for(const[s,i]of this.getPlayerMap())if(i.clipId){const a=this.getTemplateClipById(s);if(a){const r=a.asset?.type;if(r==="image"||r==="video"||r==="audio"){const o=this.getMergeFieldUsage(a,e);if(o.used&&o.isSrcField)return!0}}}return!1}validateMergeFieldValue(e,s){const i=this.getDocument();if(!i)return null;const a=this.mergeFieldService.get(e);if(!a)return null;const r=a.defaultValue;this.mergeFieldService.register({...a,defaultValue:s},{silent:!0});try{for(const n of i.getClipIdsWithBindings()){const o=i.getClipBindings(n);if(o&&this.clipUsesField(o,e)){const l=i.getClipById(n);if(l){const c=structuredClone(l.clip);for(const[h,d]of o){const y=this.mergeFieldService.resolve(d.placeholder);ps(c,h,y)}delete c.id;const f=Wa.safeParse(c);if(!f.success)return f.error.issues[0]?.message??"Invalid value"}}}return null}finally{this.mergeFieldService.register({...a,defaultValue:r},{silent:!0})}}isValueCompatibleWithClipProperty(e,s,i){const a=this.getResolvedClipById(e);if(!a)return!0;const r=structuredClone(a);return ps(r,s,i),delete r.id,Wa.safeParse(r).success}clipUsesField(e,s){for(const[,i]of e)if(this.mergeFieldService.extractFieldName(i.placeholder)===s)return!0;return!1}async deleteMergeFieldGlobally(e){const s=this.mergeFieldService.get(e);if(!s)return;const i=this.mergeFieldService.createTemplate(e),a=s.defaultValue;for(const[n]of this.getPlayerMap()){const o=this.getTemplateClipById(n);o&&await this.restoreMergeFieldInClip(n,o,i,a)}this.mergeFieldService.remove(e)||this.getInternalEvents().emit(fe.MergeFieldChanged,{fields:this.mergeFieldService.getAll()})}async convertAllTextAssets(){const e=this.getDocument();if(!e)return console.error("No document available for conversion"),{richText:0,svg:0};const s=JSON.parse(JSON.stringify(e.toJSON()));let i=0,a=0;const r=s.timeline?.tracks;if(r){for(const n of r)if(n.clips)for(let o=0;o<n.clips.length;o+=1){const l=n.clips[o],c=l.asset;c?.type==="text"&&(rN(c)?(n.clips[o]=oN(l),a+=1):(n.clips[o]=this.convertTextClipToRichText(l),i+=1))}}return console.log("CONVERTED TEMPLATE - Copy the JSON below:"),console.log(JSON.stringify(s,null," ")),{richText:i,svg:a}}mapVerticalAlign(e){return e==="center"?"middle":e==="top"||e==="bottom"?e:"middle"}convertTextClipToRichText(e){const s=e.asset,i=s.font?.family??"Open Sans",{fontWeight:a}=Dt(i),r={family:i,size:typeof s.font?.size=="string"?Number(s.font.size):s.font?.size??32,weight:s.font?.weight??a,color:s.font?.color??"#ffffff",opacity:s.font?.opacity??1};s.stroke?.width&&s.stroke.width>0&&(r.stroke={width:s.stroke.width,color:s.stroke.color??"#000000",opacity:1});const n={letterSpacing:0,wordSpacing:0,lineHeight:s.font?.lineHeight??1.2,textTransform:"none",textDecoration:"none"},o={type:"rich-text",text:s.text??"",font:r,style:n,align:{horizontal:s.alignment?.horizontal??"center",vertical:this.mapVerticalAlign(s.alignment?.vertical)}};s.background&&(o.background={color:s.background.color,opacity:s.background.opacity??1,borderRadius:s.background.borderRadius??0},s.background.padding&&(o.padding=s.background.padding)),s.animation&&(o.animation={preset:s.animation.preset,duration:s.animation.duration}),s.ellipsis!==void 0&&console.warn("TextAsset ellipsis property not supported in RichTextAsset, value dropped");const l={...e,asset:o};return s.width!==void 0&&l.width===void 0&&(l.width=s.width),s.height!==void 0&&l.height===void 0&&(l.height=s.height),l}updateMergeFieldBindings(e,s,i){if(!e)return;const{clipId:a}=e;if(!a)return;const r=this.getDocument();if(!r)return;const n=r.getClipBindings(a);if(!n)return;const o=r.getClipById(a);for(const[l,c]of n)if(this.mergeFieldService.extractFieldName(c.placeholder)===s){const h=this.mergeFieldService.resolve(c.placeholder),d={placeholder:c.placeholder,resolvedValue:h};if(r.setClipBinding(a,l,d),o){const m=(typeof h=="string"?h.trim():"").length>0?Number(h):NaN,C=Number.isFinite(m)?m:h;ps(o.clip,l,C)}}}getMergeFieldUsage(e,s,i=""){if(!e||typeof e!="object")return{used:!1,isSrcField:!1};for(const[a,r]of Object.entries(e)){const n=i?`${i}.${a}`:a;if(typeof r=="string"){if(this.mergeFieldService.extractFieldName(r)===s)return{used:!0,isSrcField:n==="asset.src"||n.endsWith(".src")}}else if(typeof r=="object"&&r!==null){const o=this.getMergeFieldUsage(r,s,n);if(o.used)return o}}return{used:!1,isSrcField:!1}}async restoreMergeFieldInClip(e,s,i,a,r=""){if(!(!s||typeof s!="object"))for(const n of Object.keys(s)){const o=s[n],l=r?`${r}.${n}`:n;if(typeof o=="string"){const c=this.mergeFieldService.extractFieldName(o),f=this.mergeFieldService.extractFieldName(i);if(c&&f&&c===f){const h=o.replace(new RegExp(`\\{\\{\\s*${c}\\s*\\}\\}`,"gi"),a);await this.removeMergeField(e,l,h)}}else typeof o=="object"&&o!==null&&await this.restoreMergeFieldInClip(e,o,i,a,l)}}}const Br=Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"}));var cN=fc({"node_modules/.pnpm/harfbuzzjs@0.4.12/node_modules/harfbuzzjs/hb.js"(t,e){var s=(()=>{var i=typeof document<"u"?document.currentScript?.src:void 0;return async function(a={}){var r,n=a,o=typeof window=="object",l=typeof WorkerGlobalScope<"u",c=typeof process=="object"&&process.versions?.node&&process.type!="renderer",f=(S,se)=>{throw se};typeof __filename<"u"?i=__filename:l&&(i=self.location.href);var h="";function d(S){return n.locateFile?n.locateFile(S,h):h+S}var y,m;if(c){var C=vw("fs");h=__dirname+"/",m=S=>{S=T(S)?new URL(S):S;var se=C.readFileSync(S);return se},y=async(S,se=!0)=>{S=T(S)?new URL(S):S;var _e=C.readFileSync(S,se?void 0:"utf8");return _e},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),f=(S,se)=>{throw process.exitCode=S,se}}else if(o||l){try{h=new URL(".",i).href}catch{}l&&(m=S=>{var se=new XMLHttpRequest;return se.open("GET",S,!1),se.responseType="arraybuffer",se.send(null),new Uint8Array(se.response)}),y=async S=>{if(T(S))return new Promise((_e,De)=>{var Ue=new XMLHttpRequest;Ue.open("GET",S,!0),Ue.responseType="arraybuffer",Ue.onload=()=>{if(Ue.status==200||Ue.status==0&&Ue.response){_e(Ue.response);return}De(Ue.status)},Ue.onerror=De,Ue.send(null)});var se=await fetch(S,{credentials:"same-origin"});if(se.ok)return se.arrayBuffer();throw new Error(se.status+" : "+se.url)}}console.log.bind(console);var E=console.error.bind(console),F,N=!1,w,T=S=>S.startsWith("file://"),b,U,D,B,J=!1;function ee(){var S=D.buffer;n.HEAP8=new Int8Array(S),n.HEAPU8=B=new Uint8Array(S),n.HEAP32=new Int32Array(S),n.HEAPU32=new Uint32Array(S),n.HEAPF32=new Float32Array(S),new BigInt64Array(S),new BigUint64Array(S)}function te(){if(n.preRun)for(typeof n.preRun=="function"&&(n.preRun=[n.preRun]);n.preRun.length;)$(n.preRun.shift());H(O)}function he(){J=!0,Yt.__wasm_call_ctors()}function re(){if(n.postRun)for(typeof n.postRun=="function"&&(n.postRun=[n.postRun]);n.postRun.length;)M(n.postRun.shift());H(R)}var Se=0,ke=null;function Fe(S){Se++,n.monitorRunDependencies?.(Se)}function be(S){if(Se--,n.monitorRunDependencies?.(Se),Se==0&&ke){var se=ke;ke=null,se()}}function G(S){n.onAbort?.(S),S="Aborted("+S+")",E(S),N=!0,S+=". Build with -sASSERTIONS for more info.";var se=new WebAssembly.RuntimeError(S);throw U?.(se),se}var Y;function W(){return d("hb.wasm")}function me(S){if(S==Y&&F)return new Uint8Array(F);if(m)return m(S);throw"both async and sync fetching of the wasm failed"}async function pe(S){if(!F)try{var se=await y(S);return new Uint8Array(se)}catch{}return me(S)}async function Pe(S,se){try{var _e=await pe(S),De=await WebAssembly.instantiate(_e,se);return De}catch(Ue){E(`failed to asynchronously prepare wasm: ${Ue}`),G(Ue)}}async function Ze(S,se,_e){if(!S&&!T(se)&&!c)try{var De=fetch(se,{credentials:"same-origin"}),Ue=await WebAssembly.instantiateStreaming(De,_e);return Ue}catch(ht){E(`wasm streaming compile failed: ${ht}`),E("falling back to ArrayBuffer instantiation")}return Pe(se,_e)}function Me(){return{env:_i,wasi_snapshot_preview1:_i}}async function Te(){function S(ht,Ti){return Yt=ht.exports,n.wasmExports=Yt,D=Yt.memory,n.wasmMemory=D,ee(),bs=Yt.__indirect_function_table,Kr(Yt),be(),Yt}Fe();function se(ht){return S(ht.instance)}var _e=Me();if(n.instantiateWasm)return new Promise((ht,Ti)=>{n.instantiateWasm(_e,(Xr,Ro)=>{ht(S(Xr))})});Y??(Y=W());var De=await Ze(F,Y,_e),Ue=se(De);return Ue}class ft{constructor(se){bt(this,"name","ExitStatus"),this.message=`Program terminated with exit(${se})`,this.status=se}}var H=S=>{for(;S.length>0;)S.shift()(n)},R=[],M=S=>R.push(S),O=[],$=S=>O.push(S),oe=!0,ie=()=>G(""),ne=0,ye=()=>{oe=!1,ne=0},ae={},q=S=>{if(S instanceof ft||S=="unwind")return w;f(1,S)},ve=()=>oe||ne>0,Je=S=>{w=S,ve()||(n.onExit?.(S),N=!0),f(S,new ft(S))},gt=(S,se)=>{w=S,Je(S)},Ye=gt,at=()=>{if(!ve())try{Ye(w)}catch(S){q(S)}},rt=S=>{if(!N)try{S(),at()}catch(se){q(se)}},vt=()=>performance.now(),_t=(S,se)=>{if(ae[S]&&(clearTimeout(ae[S].id),delete ae[S]),!se)return 0;var _e=setTimeout(()=>{delete ae[S],rt(()=>ya(S,vt()))},se);return ae[S]={id:_e,timeout_ms:se},0},Ne=()=>2147483648,Mo=(S,se)=>Math.ceil(S/se)*se,Vi=S=>{var se=D.buffer.byteLength,_e=(S-se+65535)/65536|0;try{return D.grow(_e),ee(),1}catch{}},ut=S=>{var se=B.length;S>>>=0;var _e=Ne();if(S>_e)return!1;for(var De=1;De<=4;De*=2){var Ue=se*(1+.2/De);Ue=Math.min(Ue,S+100663296);var ht=Math.min(_e,Mo(Math.max(S,Ue),65536)),Ti=Vi(ht);if(Ti)return!0}return!1},ma=S=>{const se=S.length;return[se%128|128,se>>7,...S]},Lt={i:127,p:127,j:126,f:125,d:124,e:111},Wt=S=>ma(Array.from(S,se=>{var _e=Lt[se];return _e})),Pt=(S,se)=>{var _e=Uint8Array.of(0,97,115,109,1,0,0,0,1,...ma([1,96,...Wt(se.slice(1)),...Wt(se[0]==="v"?"":se[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0),De=new WebAssembly.Module(_e),Ue=new WebAssembly.Instance(De,{e:{f:S}}),ht=Ue.exports.f;return ht},bs,si=S=>bs.get(S),Rs=(S,se)=>{if(Ot)for(var _e=S;_e<S+se;_e++){var De=si(_e);De&&Ot.set(De,_e)}},Ot,Wr=S=>(Ot||(Ot=new WeakMap,Rs(0,bs.length)),Ot.get(S)||0),Ii=[],Yr=()=>Ii.length?Ii.pop():bs.grow(1),zs=(S,se)=>bs.set(S,se),Hr=(S,se)=>{var _e=Wr(S);if(_e)return _e;var De=Yr();try{zs(De,S)}catch(ht){if(!(ht instanceof TypeError))throw ht;var Ue=Pt(S,se);zs(De,Ue)}return Ot.set(S,De),De},jr=S=>{Ot.delete(si(S)),zs(S,null),Ii.push(S)};n.noExitRuntime&&(oe=n.noExitRuntime),n.print&&n.print,n.printErr&&(E=n.printErr),n.wasmBinary&&(F=n.wasmBinary),n.arguments&&n.arguments,n.thisProgram&&n.thisProgram,n.wasmMemory=D,n.wasmExports=Yt,n.addFunction=Hr,n.removeFunction=jr;var ya;function Kr(S){n._hb_blob_create=S.hb_blob_create,n._hb_blob_destroy=S.hb_blob_destroy,n._hb_blob_get_length=S.hb_blob_get_length,n._hb_blob_get_data=S.hb_blob_get_data,n._hb_buffer_serialize_glyphs=S.hb_buffer_serialize_glyphs,n._hb_buffer_create=S.hb_buffer_create,n._hb_buffer_destroy=S.hb_buffer_destroy,n._hb_buffer_get_content_type=S.hb_buffer_get_content_type,n._hb_buffer_set_direction=S.hb_buffer_set_direction,n._hb_buffer_set_script=S.hb_buffer_set_script,n._hb_buffer_set_language=S.hb_buffer_set_language,n._hb_buffer_set_flags=S.hb_buffer_set_flags,n._hb_buffer_set_cluster_level=S.hb_buffer_set_cluster_level,n._hb_buffer_get_length=S.hb_buffer_get_length,n._hb_buffer_get_glyph_infos=S.hb_buffer_get_glyph_infos,n._hb_buffer_get_glyph_positions=S.hb_buffer_get_glyph_positions,n._hb_glyph_info_get_glyph_flags=S.hb_glyph_info_get_glyph_flags,n._hb_buffer_guess_segment_properties=S.hb_buffer_guess_segment_properties,n._hb_buffer_add_utf8=S.hb_buffer_add_utf8,n._hb_buffer_add_utf16=S.hb_buffer_add_utf16,n._hb_buffer_set_message_func=S.hb_buffer_set_message_func,n._hb_language_from_string=S.hb_language_from_string,n._hb_script_from_string=S.hb_script_from_string,n._hb_version=S.hb_version,n._hb_version_string=S.hb_version_string,n._hb_feature_from_string=S.hb_feature_from_string,n._malloc=S.malloc,n._free=S.free,n._hb_draw_funcs_set_move_to_func=S.hb_draw_funcs_set_move_to_func,n._hb_draw_funcs_set_line_to_func=S.hb_draw_funcs_set_line_to_func,n._hb_draw_funcs_set_quadratic_to_func=S.hb_draw_funcs_set_quadratic_to_func,n._hb_draw_funcs_set_cubic_to_func=S.hb_draw_funcs_set_cubic_to_func,n._hb_draw_funcs_set_close_path_func=S.hb_draw_funcs_set_close_path_func,n._hb_draw_funcs_create=S.hb_draw_funcs_create,n._hb_draw_funcs_destroy=S.hb_draw_funcs_destroy,n._hb_face_create=S.hb_face_create,n._hb_face_destroy=S.hb_face_destroy,n._hb_face_reference_table=S.hb_face_reference_table,n._hb_face_get_upem=S.hb_face_get_upem,n._hb_face_collect_unicodes=S.hb_face_collect_unicodes,n._hb_font_draw_glyph=S.hb_font_draw_glyph,n._hb_font_glyph_to_string=S.hb_font_glyph_to_string,n._hb_font_create=S.hb_font_create,n._hb_font_set_variations=S.hb_font_set_variations,n._hb_font_destroy=S.hb_font_destroy,n._hb_font_set_scale=S.hb_font_set_scale,n._hb_set_create=S.hb_set_create,n._hb_set_destroy=S.hb_set_destroy,n._hb_ot_var_get_axis_infos=S.hb_ot_var_get_axis_infos,n._hb_set_get_population=S.hb_set_get_population,n._hb_set_next_many=S.hb_set_next_many,n._hb_shape=S.hb_shape,ya=S._emscripten_timeout}var _i={_abort_js:ie,_emscripten_runtime_keepalive_clear:ye,_setitimer_js:_t,emscripten_resize_heap:ut,proc_exit:Je},Yt=await Te();function Fi(){if(Se>0){ke=Fi;return}if(te(),Se>0){ke=Fi;return}function S(){n.calledRun=!0,!N&&(he(),b?.(n),n.onRuntimeInitialized?.(),re())}n.setStatus?(n.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>n.setStatus(""),1),S()},1)):S()}function ba(){if(n.preInit)for(typeof n.preInit=="function"&&(n.preInit=[n.preInit]);n.preInit.length>0;)n.preInit.shift()()}return ba(),Fi(),J?r=n:r=new Promise((S,se)=>{b=S,U=se}),r}})();typeof t=="object"&&typeof e=="object"?(e.exports=s,e.exports.default=s):typeof define=="function"&&define.amd&&define([],()=>s)}});const fN=cN(),uN=Object.freeze(Object.defineProperty({__proto__:null,default:fN},Symbol.toStringTag,{value:"Module"}));var hN=fc({"node_modules/.pnpm/harfbuzzjs@0.4.12/node_modules/harfbuzzjs/hbjs.js"(t,e){function s(i){var a=i.wasmExports,r=new TextDecoder("utf8");let n=i.addFunction,o=i.removeFunction;var l=n(function(G){a.free(G)},"vi"),c=2,f=-1,h=2,d=0,y=1,m=2;function C(G){return(G.charCodeAt(0)&255)<<24|(G.charCodeAt(1)&255)<<16|(G.charCodeAt(2)&255)<<8|(G.charCodeAt(3)&255)<<0}var E=C("JSON"),F=4;function N(G){return[String.fromCharCode(G>>24&255),String.fromCharCode(G>>16&255),String.fromCharCode(G>>8&255),String.fromCharCode(G>>0&255)].join("")}function w(G){return G=="BOT"?1:G=="EOT"?2:G=="PRESERVE_DEFAULT_IGNORABLES"?4:G=="REMOVE_DEFAULT_IGNORABLES"?8:G=="DO_NOT_INSERT_DOTTED_CIRCLE"?16:G=="PRODUCE_UNSAFE_TO_CONCAT"?64:0}function T(G){var Y=a.malloc(G.byteLength);i.HEAPU8.set(new Uint8Array(G),Y);var W=a.hb_blob_create(Y,G.byteLength,c,Y,l);return{ptr:W,destroy:function(){a.hb_blob_destroy(W)}}}function b(G){const Y=a.hb_set_get_population(G),W=a.malloc(Y<<2),me=W>>2,pe=i.HEAPU32.subarray(me,me+Y);return i.HEAPU32.set(pe,me),a.hb_set_next_many(G,f,W,Y),pe}function U(G,Y){var W=a.hb_face_create(G.ptr,Y);const me=a.hb_face_get_upem(W);return{ptr:W,upem:me,reference_table:function(pe){var Pe=a.hb_face_reference_table(W,C(pe)),Ze=a.hb_blob_get_length(Pe);if(Ze){var Me=a.hb_blob_get_data(Pe,null),Te=i.HEAPU8.subarray(Me,Me+Ze);return Te}},getAxisInfos:function(){var pe=a.malloc(2048),Pe=a.malloc(4);i.HEAPU32[Pe/4]=64,a.hb_ot_var_get_axis_infos(W,0,Pe,pe);var Ze={};return Array.from({length:i.HEAPU32[Pe/4]}).forEach(function(Me,Te){Ze[N(i.HEAPU32[pe/4+Te*8+1])]={min:i.HEAPF32[pe/4+Te*8+4],default:i.HEAPF32[pe/4+Te*8+5],max:i.HEAPF32[pe/4+Te*8+6]}}),a.free(Pe),a.free(pe),Ze},collectUnicodes:function(){var pe=a.hb_set_create();a.hb_face_collect_unicodes(W,pe);var Pe=b(pe);return a.hb_set_destroy(pe),Pe},destroy:function(){a.hb_face_destroy(W)}}}var D="",B=256,J=a.malloc(B);function ee(G){var Y=a.hb_font_create(G.ptr),W=null,me=null,pe=null,Pe=null,Ze=null,Me=null;function Te(H){if(!W){var R=function(ie,ne,ye,ae,q,ve){D+=`M${ae},${q}`},M=function(ie,ne,ye,ae,q,ve){D+=`L${ae},${q}`},O=function(ie,ne,ye,ae,q,ve,Je,gt,Ye,at){D+=`C${ae},${q} ${ve},${Je} ${gt},${Ye}`},$=function(ie,ne,ye,ae,q,ve,Je,gt){D+=`Q${ae},${q} ${ve},${Je}`},oe=function(ie,ne,ye,ae){D+="Z"};me=n(R,"viiiffi"),pe=n(M,"viiiffi"),Pe=n(O,"viiiffffffi"),Ze=n($,"viiiffffi"),Me=n(oe,"viiii"),W=a.hb_draw_funcs_create(),a.hb_draw_funcs_set_move_to_func(W,me,0,0),a.hb_draw_funcs_set_line_to_func(W,pe,0,0),a.hb_draw_funcs_set_cubic_to_func(W,Pe,0,0),a.hb_draw_funcs_set_quadratic_to_func(W,Ze,0,0),a.hb_draw_funcs_set_close_path_func(W,Me,0,0)}return D="",a.hb_font_draw_glyph(Y,H,W,0),D}function ft(H){a.hb_font_glyph_to_string(Y,H,J,B);var R=i.HEAPU8.subarray(J,J+B);return r.decode(R.slice(0,R.indexOf(0)))}return{ptr:Y,glyphName:ft,glyphToPath:Te,glyphToJson:function(H){var R=Te(H);return R.replace(/([MLQCZ])/g,"|$1 ").split("|").filter(function(M){return M.length}).map(function(M){var O=M.split(/[ ,]/g);return{type:O[0],values:O.slice(1).filter(function($){return $.length}).map(function($){return+$})}})},setScale:function(H,R){a.hb_font_set_scale(Y,H,R)},setVariations:function(H){var R=Object.entries(H),M=a.malloc(8*R.length);R.forEach(function(O,$){i.HEAPU32[M/4+$*2+0]=C(O[0]),i.HEAPF32[M/4+$*2+1]=O[1]}),a.hb_font_set_variations(Y,M,R.length),a.free(M)},destroy:function(){a.hb_font_destroy(Y),W&&(a.hb_draw_funcs_destroy(W),W=null,o(me),o(pe),o(Pe),o(Ze),o(Me))}}}function te(G){var Y=a.malloc(G.length+1);for(let W=0;W<G.length;++W){const me=G.charCodeAt(W);if(me>127)throw new Error("Expected ASCII text");i.HEAPU8[Y+W]=me}return i.HEAPU8[Y+G.length]=0,{ptr:Y,length:G.length,free:function(){a.free(Y)}}}function he(G){const Y=a.malloc(G.length*2),W=new Uint16Array(i.wasmMemory.buffer,Y,G.length);for(let me=0;me<W.length;++me)W[me]=G.charCodeAt(me);return{ptr:Y,length:W.length,free:function(){a.free(Y)}}}function re(){var G=a.hb_buffer_create();return{ptr:G,addText:function(Y){const W=he(Y);a.hb_buffer_add_utf16(G,W.ptr,W.length,0,W.length),W.free()},guessSegmentProperties:function(){return a.hb_buffer_guess_segment_properties(G)},setDirection:function(Y){a.hb_buffer_set_direction(G,{ltr:4,rtl:5,ttb:6,btt:7}[Y]||0)},setFlags:function(Y){var W=0;Y.forEach(function(me){W|=w(me)}),a.hb_buffer_set_flags(G,W)},setLanguage:function(Y){var W=te(Y);a.hb_buffer_set_language(G,a.hb_language_from_string(W.ptr,-1)),W.free()},setScript:function(Y){var W=te(Y);a.hb_buffer_set_script(G,a.hb_script_from_string(W.ptr,-1)),W.free()},setClusterLevel:function(Y){a.hb_buffer_set_cluster_level(G,Y)},json:function(){for(var Y=a.hb_buffer_get_length(G),W=[],me=a.hb_buffer_get_glyph_infos(G,0),pe=me/4,Pe=a.hb_buffer_get_glyph_positions(G,0)/4,Ze=i.HEAPU32.subarray(pe,pe+5*Y),Me=i.HEAP32.subarray(Pe,Pe+5*Y),Te=0;Te<Y;++Te)W.push({g:Ze[Te*5+0],cl:Ze[Te*5+2],ax:Me[Te*5+0],ay:Me[Te*5+1],dx:Me[Te*5+2],dy:Me[Te*5+3],flags:a.hb_glyph_info_get_glyph_flags(me+Te*20)});return W},destroy:function(){a.hb_buffer_destroy(G)}}}function Se(G,Y,W){var me=0,pe=0;W&&(W=W.split(","),me=a.malloc(16*W.length),W.forEach(function(Pe,Ze){var Me=te(Pe);a.hb_feature_from_string(Me.ptr,-1,me+pe*16)&&pe++,Me.free()})),a.hb_shape(G.ptr,Y.ptr,me,pe),me&&a.free(me)}function ke(G,Y,W,me,pe){var Pe=[],Ze=d,Me=!1,Te=1024*1024,ft=a.malloc(Te),H=function(M,O,$,oe){var ie=r.decode(i.HEAPU8.subarray($,i.HEAPU8.indexOf(0,$)));return ie.startsWith("start table GSUB")?Ze=y:ie.startsWith("start table GPOS")&&(Ze=m),Ze!=pe&&(Me=!1),pe!=d&&Ze==pe&&ie.startsWith("end lookup "+me)&&(Me=!0),Me?0:(a.hb_buffer_serialize_glyphs(M,0,a.hb_buffer_get_length(M),ft,Te,0,O,E,F),Pe.push({m:ie,t:JSON.parse(r.decode(i.HEAPU8.subarray(ft,i.HEAPU8.indexOf(0,ft)))),glyphs:a.hb_buffer_get_content_type(M)==h}),1)},R=n(H,"iiiii");return a.hb_buffer_set_message_func(Y.ptr,R,0,0),Se(G,Y,W),a.free(ft),o(R),Pe}function Fe(){var G=a.malloc(12);a.hb_version(G,G+4,G+8);var Y={major:i.HEAPU32[G/4],minor:i.HEAPU32[(G+4)/4],micro:i.HEAPU32[(G+8)/4]};return a.free(G),Y}function be(){var G=a.hb_version_string(),Y=r.decode(i.HEAPU8.subarray(G,i.HEAPU8.indexOf(0,G)));return Y}return{createBlob:T,createFace:U,createFont:ee,createBuffer:re,shape:Se,shapeWithTrace:ke,version:Fe,version_string:be}}try{e.exports=s}catch{}}});const dN=hN(),gN=Object.freeze(Object.defineProperty({__proto__:null,default:dN},Symbol.toStringTag,{value:"Module"}));var ce,ms=new Array(128).fill(void 0);ms.push(void 0,null,!0,!1);var ha=ms.length;function It(t){ha===ms.length&&ms.push(ms.length+1);const e=ha;return ha=ms[e],ms[e]=t,e}function Nt(t){return ms[t]}function pN(t){t<132||(ms[t]=ha,ha=t)}function ys(t){const e=Nt(t);return pN(t),e}var da=0,ga=null;function Zr(){return(ga===null||ga.byteLength===0)&&(ga=new Uint8Array(ce.memory.buffer)),ga}var Ur=typeof TextEncoder<"u"?new TextEncoder("utf-8"):{encode:()=>{throw Error("TextEncoder not available")}},mN=typeof Ur.encodeInto=="function"?function(t,e){return Ur.encodeInto(t,e)}:function(t,e){const s=Ur.encode(t);return e.set(s),{read:t.length,written:s.length}};function To(t,e,s){if(s===void 0){const o=Ur.encode(t),l=e(o.length,1)>>>0;return Zr().subarray(l,l+o.length).set(o),da=o.length,l}let i=t.length,a=e(i,1)>>>0;const r=Zr();let n=0;for(;n<i;n++){const o=t.charCodeAt(n);if(o>127)break;r[a+n]=o}if(n!==i){n!==0&&(t=t.slice(n)),a=s(a,i,i=n+t.length*3,1)>>>0;const o=Zr().subarray(a+n,a+i),l=mN(t,o);n+=l.written,a=s(a,i,n,1)>>>0}return da=n,a}function Eo(t){return t==null}var pa=null;function dt(){return(pa===null||pa.byteLength===0)&&(pa=new Int32Array(ce.memory.buffer)),pa}var K0=typeof TextDecoder<"u"?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}};typeof TextDecoder<"u"&&K0.decode();function Gr(t,e){return t=t>>>0,K0.decode(Zr().subarray(t,t+e))}function yN(t,e){if(!(t instanceof e))throw new Error(`expected instance of ${e.name}`);return t.ptr}function bN(t,e){try{return t.apply(this,e)}catch(s){ce.__wbindgen_exn_store(It(s))}}var X0=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(t=>ce.__wbg_bbox_free(t>>>0)),Po=class iu{static __wrap(e){e=e>>>0;const s=Object.create(iu.prototype);return s.__wbg_ptr=e,X0.register(s,s.__wbg_ptr,s),s}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,X0.unregister(this),e}free(){const e=this.__destroy_into_raw();ce.__wbg_bbox_free(e)}get x(){return ce.__wbg_get_bbox_x(this.__wbg_ptr)}set x(e){ce.__wbg_set_bbox_x(this.__wbg_ptr,e)}get y(){return ce.__wbg_get_bbox_y(this.__wbg_ptr)}set y(e){ce.__wbg_set_bbox_y(this.__wbg_ptr,e)}get width(){return ce.__wbg_get_bbox_width(this.__wbg_ptr)}set width(e){ce.__wbg_set_bbox_width(this.__wbg_ptr,e)}get height(){return ce.__wbg_get_bbox_height(this.__wbg_ptr)}set height(e){ce.__wbg_set_bbox_height(this.__wbg_ptr,e)}},q0=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(t=>ce.__wbg_renderedimage_free(t>>>0)),wN=class au{static __wrap(e){e=e>>>0;const s=Object.create(au.prototype);return s.__wbg_ptr=e,q0.register(s,s.__wbg_ptr,s),s}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,q0.unregister(this),e}free(){const e=this.__destroy_into_raw();ce.__wbg_renderedimage_free(e)}get width(){return ce.renderedimage_width(this.__wbg_ptr)>>>0}get height(){return ce.renderedimage_height(this.__wbg_ptr)>>>0}asPng(){try{const a=ce.__wbindgen_add_to_stack_pointer(-16);ce.renderedimage_asPng(a,this.__wbg_ptr);var e=dt()[a/4+0],s=dt()[a/4+1],i=dt()[a/4+2];if(i)throw ys(s);return ys(e)}finally{ce.__wbindgen_add_to_stack_pointer(16)}}get pixels(){const e=ce.renderedimage_pixels(this.__wbg_ptr);return ys(e)}},vN=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(t=>ce.__wbg_resvg_free(t>>>0)),xN=class{__destroy_into_raw(){const t=this.__wbg_ptr;return this.__wbg_ptr=0,vN.unregister(this),t}free(){const t=this.__destroy_into_raw();ce.__wbg_resvg_free(t)}constructor(t,e,s){try{const l=ce.__wbindgen_add_to_stack_pointer(-16);var i=Eo(e)?0:To(e,ce.__wbindgen_malloc,ce.__wbindgen_realloc),a=da;ce.resvg_new(l,It(t),i,a,Eo(s)?0:It(s));var r=dt()[l/4+0],n=dt()[l/4+1],o=dt()[l/4+2];if(o)throw ys(n);return this.__wbg_ptr=r>>>0,this}finally{ce.__wbindgen_add_to_stack_pointer(16)}}get width(){return ce.resvg_width(this.__wbg_ptr)}get height(){return ce.resvg_height(this.__wbg_ptr)}render(){try{const i=ce.__wbindgen_add_to_stack_pointer(-16);ce.resvg_render(i,this.__wbg_ptr);var t=dt()[i/4+0],e=dt()[i/4+1],s=dt()[i/4+2];if(s)throw ys(e);return wN.__wrap(t)}finally{ce.__wbindgen_add_to_stack_pointer(16)}}toString(){let t,e;try{const a=ce.__wbindgen_add_to_stack_pointer(-16);ce.resvg_toString(a,this.__wbg_ptr);var s=dt()[a/4+0],i=dt()[a/4+1];return t=s,e=i,Gr(s,i)}finally{ce.__wbindgen_add_to_stack_pointer(16),ce.__wbindgen_free(t,e,1)}}innerBBox(){const t=ce.resvg_innerBBox(this.__wbg_ptr);return t===0?void 0:Po.__wrap(t)}getBBox(){const t=ce.resvg_getBBox(this.__wbg_ptr);return t===0?void 0:Po.__wrap(t)}cropByBBox(t){yN(t,Po),ce.resvg_cropByBBox(this.__wbg_ptr,t.__wbg_ptr)}imagesToResolve(){try{const i=ce.__wbindgen_add_to_stack_pointer(-16);ce.resvg_imagesToResolve(i,this.__wbg_ptr);var t=dt()[i/4+0],e=dt()[i/4+1],s=dt()[i/4+2];if(s)throw ys(e);return ys(t)}finally{ce.__wbindgen_add_to_stack_pointer(16)}}resolveImage(t,e){try{const a=ce.__wbindgen_add_to_stack_pointer(-16),r=To(t,ce.__wbindgen_malloc,ce.__wbindgen_realloc),n=da;ce.resvg_resolveImage(a,this.__wbg_ptr,r,n,It(e));var s=dt()[a/4+0],i=dt()[a/4+1];if(i)throw ys(s)}finally{ce.__wbindgen_add_to_stack_pointer(16)}}};async function CN(t,e){if(typeof Response=="function"&&t instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(t,e)}catch(i){if(t.headers.get("Content-Type")!="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",i);else throw i}const s=await t.arrayBuffer();return await WebAssembly.instantiate(s,e)}else{const s=await WebAssembly.instantiate(t,e);return s instanceof WebAssembly.Instance?{instance:s,module:t}:s}}function kN(){const t={};return t.wbg={},t.wbg.__wbg_new_28c511d9baebfa89=function(e,s){const i=new Error(Gr(e,s));return It(i)},t.wbg.__wbindgen_memory=function(){const e=ce.memory;return It(e)},t.wbg.__wbg_buffer_12d079cc21e14bdb=function(e){const s=Nt(e).buffer;return It(s)},t.wbg.__wbg_newwithbyteoffsetandlength_aa4a17c33a06e5cb=function(e,s,i){const a=new Uint8Array(Nt(e),s>>>0,i>>>0);return It(a)},t.wbg.__wbindgen_object_drop_ref=function(e){ys(e)},t.wbg.__wbg_new_63b92bc8671ed464=function(e){const s=new Uint8Array(Nt(e));return It(s)},t.wbg.__wbg_values_839f3396d5aac002=function(e){const s=Nt(e).values();return It(s)},t.wbg.__wbg_next_196c84450b364254=function(){return bN(function(e){const s=Nt(e).next();return It(s)},arguments)},t.wbg.__wbg_done_298b57d23c0fc80c=function(e){return Nt(e).done},t.wbg.__wbg_value_d93c65011f51a456=function(e){const s=Nt(e).value;return It(s)},t.wbg.__wbg_instanceof_Uint8Array_2b3bbecd033d19f6=function(e){let s;try{s=Nt(e)instanceof Uint8Array}catch{s=!1}return s},t.wbg.__wbindgen_string_get=function(e,s){const i=Nt(s),a=typeof i=="string"?i:void 0;var r=Eo(a)?0:To(a,ce.__wbindgen_malloc,ce.__wbindgen_realloc),n=da;dt()[e/4+1]=n,dt()[e/4+0]=r},t.wbg.__wbg_new_16b304a2cfa7ff4a=function(){const e=new Array;return It(e)},t.wbg.__wbindgen_string_new=function(e,s){const i=Gr(e,s);return It(i)},t.wbg.__wbg_push_a5b05aedc7234f9f=function(e,s){return Nt(e).push(Nt(s))},t.wbg.__wbg_length_c20a40f15020d68a=function(e){return Nt(e).length},t.wbg.__wbg_set_a47bac70306a19a7=function(e,s,i){Nt(e).set(Nt(s),i>>>0)},t.wbg.__wbindgen_throw=function(e,s){throw new Error(Gr(e,s))},t}function NN(t,e){return ce=t.exports,J0.__wbindgen_wasm_module=e,pa=null,ga=null,ce}async function J0(t){if(ce!==void 0)return ce;typeof t>"u"&&(t=new URL("index_bg.wasm",void 0));const e=kN();(typeof t=="string"||typeof Request=="function"&&t instanceof Request||typeof URL=="function"&&t instanceof URL)&&(t=fetch(t));const{instance:s,module:i}=await CN(await t,e);return NN(s,i)}var AN=J0,Oo=!1,SN=async t=>{if(Oo)throw new Error("Already initialized. The `initWasm()` function can be used only once.");await AN(await t),Oo=!0},VN=class extends xN{constructor(t,e){if(!Oo)throw new Error("Wasm has not been initialized. Call `initWasm()` function.");const s=e?.font;if(s&&IN(s)){const i={...e,font:{...s,fontBuffers:void 0}};super(t,JSON.stringify(i),s.fontBuffers)}else super(t,JSON.stringify(e))}};function IN(t){return Object.prototype.hasOwnProperty.call(t,"fontBuffers")}const Q0=Object.freeze(Object.defineProperty({__proto__:null,Resvg:VN,initWasm:SN},Symbol.toStringTag,{value:"Module"}));Ht.Edit=Si,Ht.ShotstackEdit=lN,Object.defineProperty(Ht,Symbol.toStringTag,{value:"Module"})});