@shotstack/shotstack-studio 2.1.0 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/internal.umd.js
CHANGED
|
@@ -264,4 +264,4 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
264
264
|
`){h.push({glyphs:g,width:m,y:0}),g=[],m=0,_=k;continue}if(m+x>s&&g.length>0){if(_>-1){const D=_-(k-g.length)+1,b=g.splice(D),$=g.reduce((G,J)=>G+J.xAdvance,0);h.push({glyphs:g,width:$,y:0}),g=b,m=b.reduce((G,J)=>G+J.xAdvance,0)}else h.push({glyphs:g,width:m,y:0}),g=[],m=0;_=-1}g.push(w),m+=x,v.has(w.cluster)&&(_=k)}g.length>0&&h.push({glyphs:g,width:m,y:0});const C=e.lineHeight*r;for(let k=0;k<h.length;k++)h[k].y=(k+1)*C;return h}catch(t){throw t instanceof Error?t:new Error(`Layout failed: ${String(t)}`)}}};function tI(e,t){return e.type==="linear"?{kind:"linear",angle:e.angle,stops:e.stops,opacity:t}:{kind:"radial",stops:e.stops,opacity:t}}function iI(e,t){const i=Math.max(1,Math.round(t.fontSize*.05));let r=t.baselineY+Math.round(t.fontSize*.1);return e==="line-through"&&(r=t.baselineY-Math.round(t.fontSize*.3)),{x1:t.xStart,x2:t.xStart+t.lineWidth,y:r,width:i}}function aI(e){return e==null?{top:0,right:0,bottom:0,left:0}:typeof e=="number"?{top:e,right:e,bottom:e,left:e}:e}async function rI(e){const t=[],i=aI(e.padding),r=e.border?.width??0;if(t.push({op:"BeginFrame",width:e.canvas.width,height:e.canvas.height,pixelRatio:e.canvas.pixelRatio,clear:!0,bg:void 0}),e.lines.length===0)return t;const a=Math.max(1,await e.getUnitsPerEm()),s=e.font.size/a,n=e.lines.length,o=e.font.size*e.style.lineHeight;let u;switch(e.align.vertical){case"top":u=e.font.size;break;case"bottom":u=e.textRect.height-(n-1)*o;break;case"middle":default:const k=e.font.size*.35;u=(e.textRect.height-(n-1)*o)/2+k;break}u+=r+i.top;const l=e.style.gradient?tI(e.style.gradient,1):{kind:"solid",color:e.font.color,opacity:e.font.opacity},c=e.style.gradient?e.style.gradient.stops[e.style.gradient.stops.length-1]?.color??e.font.color:e.font.color,d=[],h=[];let g=1/0,m=1/0,v=-1/0,_=-1/0;for(const C of e.lines){let k;switch(e.align.horizontal){case"left":k=0;break;case"right":k=e.textRect.width-C.width;break;case"center":default:k=(e.textRect.width-C.width)/2;break}k+=r+i.left;let w=k;const x=e.lines.indexOf(C),D=u+x*o;if(e.font.background){const b=e.font.size*.15,$=e.font.size*.12,G=e.font.size*.92+$*2,J=D-e.font.size*.78-$;h.push({op:"Rectangle",x:k-b,y:J,width:C.width+b*2,height:G,fill:{kind:"solid",color:e.font.background,opacity:1}})}for(const b of C.glyphs){const $=w+b.xOffset,G=D+b.yOffset,J=b.fontDesc?.family;if((b.isColorEmoji||J&&e.isColorEmojiFont&&e.isColorEmojiFont(J))&&b.char){d.push({op:"DrawColorEmoji",char:b.char,x:$,y:G,fontSize:e.font.size,fontFamily:J||"NotoColorEmoji"}),w+=b.xAdvance;continue}const Y=await e.glyphPathProvider(b.id,b.fontDesc);if(!Y||Y==="M 0 0"){w+=b.xAdvance;continue}const O=nI(Y),re=$+s*O.x,q=$+s*(O.x+O.w),pe=G-s*(O.y+O.h),ce=G-s*O.y;re<g&&(g=re),pe<m&&(m=pe),q>v&&(v=q),ce>_&&(_=ce),e.shadow&&e.shadow.blur>0&&d.push({isShadow:!0,op:"FillPath",path:Y,x:$+e.shadow.offsetX,y:G+e.shadow.offsetY,scale:s,fill:{kind:"solid",color:e.shadow.color,opacity:e.shadow.opacity}}),e.stroke&&e.stroke.width>0&&d.push({op:"StrokePath",path:Y,x:$,y:G,scale:s,width:e.stroke.width,color:e.stroke.color,opacity:e.stroke.opacity}),d.push({op:"FillPath",path:Y,x:$,y:G,scale:s,fill:l}),w+=b.xAdvance}if(e.style.textDecoration!=="none"){const b=iI(e.style.textDecoration,{baselineY:D,fontSize:e.font.size,lineWidth:C.width,xStart:k});d.push({op:"DecorationLine",from:{x:b.x1,y:b.y},to:{x:b.x2,y:b.y},width:b.width,color:c,opacity:e.font.opacity})}}if(g!==1/0){const C={x:g,y:m,w:Math.max(1,v-g),h:Math.max(1,_-m)};for(const k of d)k.op==="FillPath"&&!k.isShadow&&(k.gradientBBox=C)}if(e.background||e.border){const C=e.contentRect?.width??e.canvas.width,k=e.contentRect?.height??e.canvas.height,w=e.border?.width??0,x=e.border?.radius??0,D=w/2,b=e.canvas.width/2,$=e.canvas.height/2,G=b-C/2,J=$-k/2,T=Math.min(C-w,k-w)/2,Y=Math.min(x,T),O=Math.max(0,Y-D);e.background?.color&&t.push({op:"Rectangle",x:G+w,y:J+w,width:C-w*2,height:k-w*2,fill:{kind:"solid",color:e.background.color,opacity:e.background.opacity},borderRadius:O}),e.border&&e.border.width>0&&t.push({op:"RectangleStroke",x:G+D,y:J+D,width:C-w,height:k-w,stroke:{width:e.border.width,color:e.border.color,opacity:e.border.opacity},borderRadius:Y})}return t.push(...h),t.push(...d),t}function sI(e){return e.match(/[MLCQZ]|-?\d*\.?\d+(?:e[-+]?\d+)?/gi)??[]}function nI(e){const t=sI(e);let i=0,r=1/0,a=1/0,s=-1/0,n=-1/0;const o=(u,l)=>{u<r&&(r=u),l<a&&(a=l),u>s&&(s=u),l>n&&(n=l)};for(;i<t.length;)switch(t[i++]){case"M":case"L":{const l=parseFloat(t[i++]),c=parseFloat(t[i++]);o(l,c);break}case"C":{const l=parseFloat(t[i++]),c=parseFloat(t[i++]),d=parseFloat(t[i++]),h=parseFloat(t[i++]),g=parseFloat(t[i++]),m=parseFloat(t[i++]);o(l,c),o(d,h),o(g,m);break}case"Q":{const l=parseFloat(t[i++]),c=parseFloat(t[i++]),d=parseFloat(t[i++]),h=parseFloat(t[i++]);o(l,c),o(d,h);break}}return r===1/0?{x:0,y:0,w:0,h:0}:{x:r,y:a,w:s-r,h:n-a}}var Ec=.999;function oI(e,t,i){if(!i.anim||!i.anim.preset)return e;const{preset:r}=i.anim,a=t.reduce((u,l)=>u+l.glyphs.length,0);let s=Math.max(.3,a/(30*i.anim.speed));i.clipDuration&&!i.anim.duration&&(s=Math.min(s,i.clipDuration*.9));const n=i.anim.duration??s,o=Math.max(0,Math.min(1,i.t/n));switch(r){case"typewriter":return lI(e,t,o,i.anim.style,i.fontSize,i.t);case"fadeIn":return dI(e,t,o,i.anim.style,i.fontSize,n);case"slideIn":return hI(e,t,o,i.anim.direction??"left",i.fontSize,i.anim.style,n);case"shift":return fI(e,t,o,i.anim.direction??"left",i.fontSize,i.anim.style,n);case"ascend":return cI(e,t,o,i.anim.direction??"up",i.fontSize,n);case"movingLetters":return gI(e,i.t,i.anim.direction??"up",i.fontSize);default:return e}}var Wo=e=>e.op==="FillPath"&&e.isShadow===!0,Yo=e=>e.op==="FillPath"&&!e.isShadow;function uI(e){for(const t of e)if(t.op==="FillPath"){const i=t.fill;if(i?.kind==="solid")return i.color;if((i?.kind==="linear"||i?.kind==="radial")&&Array.isArray(i.stops)&&i.stops.length)return i.stops[i.stops.length-1].color||"#000000"}return"#000000"}function lI(e,t,i,r,a,s,n){if(r==="word"){const u=ws(t),l=u.length,c=Math.floor(i*l);if(c===0)return e.filter(m=>m.op==="BeginFrame"||m.op==="Rectangle"||m.op==="RectangleStroke");let d=0;for(let m=0;m<Math.min(c,u.length);m++)d+=u[m].glyphCount;const h=Nb(e,d),g=i>=Ec?h:h.filter(m=>m.op!=="DecorationLine");return i<1&&d>0?Bb(g,d,a):g}else{const u=t.reduce((h,g)=>h+g.glyphs.length,0),l=Math.floor(i*u);if(l===0)return e.filter(h=>h.op==="BeginFrame"||h.op==="Rectangle"||h.op==="RectangleStroke");const c=Nb(e,l),d=i>=Ec?c:c.filter(h=>h.op!=="DecorationLine");return i<1&&l>0?Bb(d,l,a):d}}function cI(e,t,i,r,a,s){const n=ws(t),o=n.length;if(o===0)return e;const u=[];let l=0;for(const c of e)if((c.op==="BeginFrame"||c.op==="Rectangle"||c.op==="RectangleStroke")&&u.push(c),c.op==="FillPath"||c.op==="StrokePath")break;for(const c of e)if(c.op==="FillPath"||c.op==="StrokePath"){let d=-1,h=0;for(let g=0;g<n.length;g++){const m=n[g].glyphCount;if(l>=h&&l<h+m){d=g;break}h+=m}if(d>=0){const g=d/Math.max(1,o)*(s/s),m=Math.min(1,g+.3);if(i>=m)u.push(c);else if(i>g){const v=(i-g)/Math.max(1e-6,m-g),_=Ko(Math.min(1,v)),C=r==="up"?a*.4:-a*.4,k={...c,y:c.y+C*(1-_)};c.op==="FillPath"?k.fill.kind==="solid"?k.fill={...k.fill,opacity:k.fill.opacity*_}:k.fill={...k.fill,opacity:(k.fill.opacity??1)*_}:k.opacity=k.opacity*_,u.push(k)}}Yo(c)&&l++}else c.op==="DecorationLine"&&i>=Ec&&u.push(c);return u}function fI(e,t,i,r,a,s,n){const o=s==="word",l={left:{x:a*.6,y:0},right:{x:-a*.6,y:0},up:{x:0,y:a*.6},down:{x:0,y:-a*.6}}[r],c=o?ws(t):[],d=t.reduce((w,x)=>w+x.glyphs.length,0),h=o?c.length:d;if(h===0)return e;const g=[];for(const w of e)if((w.op==="BeginFrame"||w.op==="Rectangle"||w.op==="RectangleStroke")&&g.push(w),w.op==="FillPath"||w.op==="StrokePath")break;const m=.3,_=n*.7/Math.max(1,h-1),C=w=>{const x=w*_,D=x/n,b=Math.min(1,(x+m)/n);return{startF:D,endF:b}};let k=0;for(const w of e){if(w.op!=="FillPath"&&w.op!=="StrokePath"){w.op==="DecorationLine"&&i>.8&&g.push(w);continue}let x;if(!o)x=k;else{let $=-1,G=0;for(let J=0;J<c.length;J++){const T=c[J].glyphCount;if(k>=G&&k<G+T){$=J;break}G+=T}x=Math.max(0,$)}const{startF:D,endF:b}=C(x);if(i<=D){const $={...w,x:w.x+l.x,y:w.y+l.y};w.op==="FillPath"?$.fill.kind==="solid"?$.fill={...$.fill,opacity:0}:$.fill={...$.fill,opacity:0}:$.opacity=0,g.push($)}else if(i>=b)g.push(w);else{const $=(i-D)/Math.max(1e-6,b-D),G=Ko(Math.min(1,$)),J=l.x*(1-G),T=l.y*(1-G),Y={...w,x:w.x+J,y:w.y+T};if(w.op==="FillPath"){const O=Y.fill.kind==="solid"?Y.fill.opacity:Y.fill.opacity??1;Y.fill.kind==="solid"?Y.fill={...Y.fill,opacity:O*G}:Y.fill={...Y.fill,opacity:O*G}}else Y.opacity=Y.opacity*G;g.push(Y)}Yo(w)&&k++}return g}function dI(e,t,i,r,a,s){const n=r==="word";if(!n&&!(r==="character")){const C=Ac(i),k=.95+.05*C;return mI(e,C,k)}const u=n?ws(t):[],l=t.reduce((C,k)=>C+k.glyphs.length,0),c=n?u.length:l;if(c===0)return e;const d=[];for(const C of e)if(C.op==="BeginFrame"){d.push(C);break}const h=.3,m=s*.7/Math.max(1,c-1),v=C=>{const k=C*m,w=k/s,x=Math.min(1,(k+h)/s);return{startF:w,endF:x}};let _=0;for(const C of e){if(C.op!=="FillPath"&&C.op!=="StrokePath"){C.op==="DecorationLine"&&i>.8&&d.push(C);continue}let k;if(!n)k=_;else{let D=-1,b=0;for(let $=0;$<u.length;$++){const G=u[$].glyphCount;if(_>=b&&_<b+G){D=$;break}b+=G}k=Math.max(0,D)}const{startF:w,endF:x}=v(k);if(i<=w){const D={...C};C.op==="FillPath"?D.fill.kind==="solid"?D.fill={...D.fill,opacity:0}:D.fill={...D.fill,opacity:0}:D.opacity=0,d.push(D)}else if(i>=x)d.push(C);else{const D=(i-w)/Math.max(1e-6,x-w),b=Ac(Math.min(1,D)),$={...C};if(C.op==="FillPath"){const G=$.fill.kind==="solid"?$.fill.opacity:$.fill.opacity??1;$.fill.kind==="solid"?$.fill={...$.fill,opacity:G*b}:$.fill={...$.fill,opacity:G*b}}else $.opacity=$.opacity*b;d.push($)}Yo(C)&&_++}return d}function hI(e,t,i,r,a,s,n){const o=s==="word";if(!o&&!(s==="character")){const x=Ko(i),D=vI(1-x,r,a*2),b=Ac(i);return yI(e,D.dx,D.dy,b)}const c={left:{x:a*2,y:0},right:{x:-a*2,y:0},up:{x:0,y:a*2},down:{x:0,y:-a*2}}[r],d=o?ws(t):[],h=t.reduce((x,D)=>x+D.glyphs.length,0),g=o?d.length:h;if(g===0)return e;const m=[];for(const x of e)if(x.op==="BeginFrame"){m.push(x);break}const v=.3,C=n*.7/Math.max(1,g-1),k=x=>{const D=x*C,b=D/n,$=Math.min(1,(D+v)/n);return{startF:b,endF:$}};let w=0;for(const x of e){if(x.op!=="FillPath"&&x.op!=="StrokePath"){x.op==="DecorationLine"&&i>.8&&m.push(x);continue}let D;if(!o)D=w;else{let G=-1,J=0;for(let T=0;T<d.length;T++){const Y=d[T].glyphCount;if(w>=J&&w<J+Y){G=T;break}J+=Y}D=Math.max(0,G)}const{startF:b,endF:$}=k(D);if(i<=b){const G={...x,x:x.x+c.x,y:x.y+c.y};x.op==="FillPath"?G.fill.kind==="solid"?G.fill={...G.fill,opacity:0}:G.fill={...G.fill,opacity:0}:G.opacity=0,m.push(G)}else if(i>=$)m.push(x);else{const G=(i-b)/Math.max(1e-6,$-b),J=Ko(Math.min(1,G)),T=c.x*(1-J),Y=c.y*(1-J),O={...x,x:x.x+T,y:x.y+Y};if(x.op==="FillPath"){const re=O.fill.kind==="solid"?O.fill.opacity:O.fill.opacity??1;O.fill.kind==="solid"?O.fill={...O.fill,opacity:re*J}:O.fill={...O.fill,opacity:re*J}}else O.opacity=O.opacity*J;m.push(O)}Yo(x)&&w++}return m}function gI(e,t,i,r){const a=r*.3;return bI(e,i,a,t)}function ws(e){const t=[];let i=0;for(let r=0;r<e.length;r++){const a=e[r],s=pI(a);for(const n of s)n.length>0&&t.push({startGlyph:i,glyphCount:n.length,lineIndex:r}),i+=n.length}return t}function pI(e){const t=[];let i=[];for(const r of e.glyphs)r.char===" "||r.char===" "||r.char===`
|
|
265
265
|
`?i.length&&(t.push([...i]),i=[]):i.push(r);return i.length&&t.push(i),t}function Nb(e,t){const i=[];let r=0,a=!1;for(const s of e){if(s.op==="BeginFrame"||s.op==="Rectangle"||s.op==="RectangleStroke"){i.push(s);continue}if(s.op==="FillPath"&&!Wo(s)){r<t&&(i.push(s),a=!0),r++;continue}if(s.op==="StrokePath"){r<t&&i.push(s);continue}if(s.op==="FillPath"&&Wo(s)){r<t&&i.push(s);continue}if(s.op==="DecorationLine"&&a){i.push(s);continue}}return i}function Bb(e,t,i,r){if(t===0)return e;let a=null,s=0;for(const n of e)if(n.op==="FillPath"&&!Wo(n)&&(s++,s===t)){a=n;break}if(a&&a.op==="FillPath"){const n=uI(e),o=a.x+i*.5,u=a.y,l=Math.max(3,i/15),c={op:"DecorationLine",from:{x:o,y:u-i*.75},to:{x:o,y:u+i*.15},width:l,color:n,opacity:1};return[...e,c]}return e}function mI(e,t,i){let r=0,a=0,s=0;return e.forEach(n=>{n.op==="FillPath"&&(r+=n.x,a+=n.y,s++)}),s>0&&(r/=s,a/=s),e.map(n=>{if(n.op==="FillPath"){const o={...n};if(o.fill.kind==="solid"?o.fill={...o.fill,opacity:o.fill.opacity*t}:o.fill={...o.fill,opacity:(o.fill.opacity??1)*t},i!==1&&s>0){const u=n.x-r,l=n.y-a;o.x=r+u*i,o.y=a+l*i}return o}if(n.op==="StrokePath"){const o={...n,opacity:n.opacity*t};if(i!==1&&s>0){const u=n.x-r,l=n.y-a;o.x=r+u*i,o.y=a+l*i}return o}return n.op==="DecorationLine"?{...n,opacity:n.opacity*t}:n})}function yI(e,t,i,r=1){return e.map(a=>{if(a.op==="FillPath"){const s={...a,x:a.x+t,y:a.y+i};return r<1&&(s.fill.kind==="solid"?s.fill={...s.fill,opacity:s.fill.opacity*r}:s.fill={...s.fill,opacity:(s.fill.opacity??1)*r}),s}return a.op==="StrokePath"?{...a,x:a.x+t,y:a.y+i,opacity:a.opacity*r}:a.op==="DecorationLine"?{...a,from:{x:a.from.x+t,y:a.from.y+i},to:{x:a.to.x+t,y:a.to.y+i},opacity:a.opacity*r}:a})}function bI(e,t,i,r){let a=0;const n=Math.min(1,r/.5);return e.map(o=>{if(o.op==="FillPath"||o.op==="StrokePath"){const u=Math.sin(a/5*Math.PI+r*Math.PI*2),l=t==="left"||t==="right"?u*i*(t==="left"?-1:1):0,c=t==="up"||t==="down"?u*i*(t==="up"?-1:1):0;if(o.op==="FillPath"){Wo(o)||a++;const d={...o,x:o.x+l,y:o.y+c};return d.fill.kind==="solid"?d.fill={...d.fill,opacity:d.fill.opacity*n}:d.fill={...d.fill,opacity:(d.fill.opacity??1)*n},d}return{...o,x:o.x+l,y:o.y+c,opacity:o.opacity*n}}return o})}function vI(e,t,i){const r=e*i;switch(t){case"left":return{dx:-r,dy:0};case"right":return{dx:r,dy:0};case"up":return{dx:0,dy:-r};case"down":return{dx:0,dy:r}}}function Ac(e){return e*(2-e)}function Ko(e){return 1-Math.pow(1-e,3)}function Mt(e,t=1){const i=/^#?([a-f0-9]{6})$/i.exec(e);if(!i)throw new Error(`Invalid color ${e}`);const r=parseInt(i[1],16),a=r>>16&255,s=r>>8&255,n=r&255;return{r:a,g:s,b:n,a:t}}var Ib=.8,Fb=.2;function wI(e){const t=e.getContext("2d");if(!t)throw new Error("2D context unavailable");return{async render(i){const r=CI(i),a=new Map;for(let s=0;s<i.length;s++){const n=i[s];if(n.op==="BeginFrame"){n.pixelRatio;const o=n.width,u=n.height;if("width"in e&&"height"in e&&(e.width=Math.floor(o),e.height=Math.floor(u)),"style"in e&&(e.style.width=`${o}px`,e.style.height=`${u}px`),t.setTransform(1,0,0,1,0,0),t.globalAlpha=1,n.clear&&t.clearRect(0,0,o,u),n.bg&&n.bg.color){const{color:l,opacity:c,radius:d}=n.bg;if(l){const h=Mt(l,c);d&&d>0?(t.fillStyle=`rgba(${h.r},${h.g},${h.b},${h.a})`,Xo(t,0,0,o,u,d),t.fill()):(t.fillStyle=`rgba(${h.r},${h.g},${h.b},${h.a})`,t.fillRect(0,0,o,u))}}continue}if(n.op==="FillPath"){const o=n,u=new Path2D(o.path);t.save(),t.translate(o.x,o.y);const l=o.scale??1;t.scale(l,-l);const c=o.gradientBBox??r,d={x:(c.x-o.x)/l,y:-(c.y-o.y)/l,w:c.w/l,h:c.h/l},h=JSON.stringify({fill:o.fill,bbox:d});let g=a.get(h);g||(g=Cs(t,o.fill,d),a.set(h,g)),t.fillStyle=g,t.fill(u),t.restore();continue}if(n.op==="StrokePath"){const o=n,u=new Path2D(o.path);t.save(),t.translate(o.x,o.y);const l=o.scale??1;t.scale(l,-l);const c=1/Math.abs(l),d=Mt(o.color,o.opacity);t.strokeStyle=`rgba(${d.r},${d.g},${d.b},${d.a})`,t.lineWidth=o.width*c,t.lineJoin="round",t.lineCap="round",t.stroke(u),t.restore();continue}if(n.op==="DecorationLine"){t.save();const o=Mt(n.color,n.opacity);t.strokeStyle=`rgba(${o.r},${o.g},${o.b},${o.a})`,t.lineWidth=n.width,t.beginPath(),t.moveTo(n.from.x,n.from.y),t.lineTo(n.to.x,n.to.y),t.stroke(),t.restore();continue}if(n.op==="Rectangle"){t.save();const o=Cs(t,n.fill,{x:n.x,y:n.y,w:n.width,h:n.height});t.fillStyle=o,n.borderRadius&&n.borderRadius>0?Xo(t,n.x,n.y,n.width,n.height,n.borderRadius):t.fillRect(n.x,n.y,n.width,n.height),t.restore();continue}if(n.op==="RectangleStroke"){t.save();const o=Mt(n.stroke.color,n.stroke.opacity);if(t.strokeStyle=`rgba(${o.r},${o.g},${o.b},${o.a})`,t.lineWidth=n.stroke.width*2,n.borderRadius&&n.borderRadius>0){const u=new Path2D,l=n.x,c=n.y,d=n.width,h=n.height,g=Math.min(d,h)/2,m=Math.min(n.borderRadius,g);u.moveTo(l+m,c),u.arcTo(l+d,c,l+d,c+h,m),u.arcTo(l+d,c+h,l,c+h,m),u.arcTo(l,c+h,l,c,m),u.arcTo(l,c,l+d,c,m),u.closePath(),t.stroke(u)}else t.strokeRect(n.x,n.y,n.width,n.height);t.restore();continue}if(n.op==="DrawColorEmoji"){t.save(),t.font=`${n.fontSize}px "${n.fontFamily}"`,t.textBaseline="alphabetic",t.fillText(n.char,n.x,n.y),t.restore();continue}if(n.op==="Ellipse"){t.save();const o=n.gradientBBox??{x:n.cx-n.rx,y:n.cy-n.ry,w:n.rx*2,h:n.ry*2},u=Cs(t,n.fill,o);t.fillStyle=u,t.beginPath();const l=(n.rotation??0)*Math.PI/180;t.ellipse(n.cx,n.cy,n.rx,n.ry,l,0,Math.PI*2),t.fill(),t.restore();continue}if(n.op==="EllipseStroke"){t.save(),kc(t,n.stroke),t.beginPath();const o=(n.rotation??0)*Math.PI/180;t.ellipse(n.cx,n.cy,n.rx,n.ry,o,0,Math.PI*2),t.stroke(),t.restore();continue}if(n.op==="Polygon"){t.save();const o=n.gradientBBox??EI(n.points),u=Cs(t,n.fill,o);t.fillStyle=u,t.beginPath(),zb(t,n.points,n.closed??!0),t.fill(),t.restore();continue}if(n.op==="PolygonStroke"){t.save(),kc(t,n.stroke),t.beginPath(),zb(t,n.points,n.closed??!0),t.stroke(),t.restore();continue}if(n.op==="ShapePath"){t.save(),t.translate(n.x,n.y);const o=n.gradientBBox??Vb(n.path),u=Cs(t,n.fill,o);t.fillStyle=u;const l=new Path2D(n.path);t.fill(l),t.restore();continue}if(n.op==="ShapePathStroke"){t.save(),t.translate(n.x,n.y),kc(t,n.stroke);const o=new Path2D(n.path);t.stroke(o),t.restore();continue}if(n.op==="DrawCaptionBackground"){t.save();const o=Mt(n.color,n.opacity);t.fillStyle=`rgba(${o.r},${o.g},${o.b},${o.a})`,Xo(t,n.x,n.y,n.width,n.height,n.borderRadius),t.restore();continue}if(n.op==="DrawCaptionWord"){const o=[n];for(;s+1<i.length;){const u=i[s+1];if(u.op!=="DrawCaptionWord")break;o.push(u),s++}for(const u of o){if(!u.background||(u.visibleCharacters>=0&&u.visibleCharacters<u.text.length?u.text.slice(0,u.visibleCharacters):u.text).length===0)continue;t.save();const c=Math.round(u.x+u.transform.translateX),d=Math.round(u.y+u.transform.translateY);if(t.translate(c,d),u.transform.scale!==1){const D=u.width/2;t.translate(D,0),t.scale(u.transform.scale,u.transform.scale),t.translate(-D,0)}t.globalAlpha=u.transform.opacity,t.font=`${u.fontWeight} ${u.fontSize}px "${u.fontFamily}"`,t.textBaseline="alphabetic",u.letterSpacing&&(t.letterSpacing=`${u.letterSpacing}px`);const h=u.width,g=u.fontSize*Ib,m=u.fontSize*Fb,v=g+m,_=-u.background.padding,C=-g-u.background.padding,k=h+u.background.padding*2,w=v+u.background.padding*2,x=Mt(u.background.color,u.background.opacity);t.fillStyle=`rgba(${x.r},${x.g},${x.b},${x.a})`,Xo(t,_,C,k,w,u.background.borderRadius),t.restore()}for(const u of o){const l=u.visibleCharacters>=0&&u.visibleCharacters<u.text.length?u.text.slice(0,u.visibleCharacters):u.text;if(l.length===0)continue;t.save();const c=Math.round(u.x+u.transform.translateX),d=Math.round(u.y+u.transform.translateY);if(t.translate(c,d),u.transform.scale!==1){const C=u.width/2;t.translate(C,0),t.scale(u.transform.scale,u.transform.scale),t.translate(-C,0)}t.globalAlpha=u.transform.opacity,t.font=`${u.fontWeight} ${u.fontSize}px "${u.fontFamily}"`,t.textBaseline="alphabetic",u.letterSpacing&&(t.letterSpacing=`${u.letterSpacing}px`);const h=t.measureText(l),g=h.width,m=h.actualBoundingBoxAscent??u.fontSize*Ib,v=h.actualBoundingBoxDescent??u.fontSize*Fb,_=m+v;if(u.shadow){const C=Mt(u.shadow.color,u.shadow.opacity);t.fillStyle=`rgba(${C.r},${C.g},${C.b},${C.a})`,t.shadowColor=`rgba(${C.r},${C.g},${C.b},${C.a})`,t.shadowOffsetX=u.shadow.offsetX,t.shadowOffsetY=u.shadow.offsetY,t.shadowBlur=u.shadow.blur,t.fillText(l,0,0),t.shadowColor="transparent",t.shadowOffsetX=0,t.shadowOffsetY=0,t.shadowBlur=0}if(u.stroke&&u.stroke.width>0){const C=Mt(u.stroke.color,u.stroke.opacity);t.strokeStyle=`rgba(${C.r},${C.g},${C.b},${C.a})`,t.lineWidth=u.stroke.width*2,t.lineJoin="round",t.lineCap="round",t.strokeText(l,0,0)}if(u.fillProgress<=0){const C=Mt(u.baseColor,u.baseOpacity);t.fillStyle=`rgba(${C.r},${C.g},${C.b},${C.a})`,t.fillText(l,0,0)}else if(u.fillProgress>=1){const C=Mt(u.activeColor,u.activeOpacity);t.fillStyle=`rgba(${C.r},${C.g},${C.b},${C.a})`,t.fillText(l,0,0)}else{const C=Mt(u.baseColor,u.baseOpacity);t.fillStyle=`rgba(${C.r},${C.g},${C.b},${C.a})`,t.fillText(l,0,0),t.save(),t.beginPath();const k=g*u.fillProgress;if(u.isRTL){const x=g-k;t.rect(x,-m-5,k+5,_+10)}else t.rect(-5,-m-5,k+5,_+10);t.clip();const w=Mt(u.activeColor,u.activeOpacity);t.fillStyle=`rgba(${w.r},${w.g},${w.b},${w.a})`,t.fillText(l,0,0),t.restore()}t.restore()}continue}}},getImageData(){return t.getImageData(0,0,e.width,e.height)},toRawRGBA(){return{data:t.getImageData(0,0,e.width,e.height).data,width:e.width,height:e.height}},getCanvas(){return e},getCanvasSize(){return{width:e.width,height:e.height}}}}function Xo(e,t,i,r,a,s){const n=Math.min(r,a)/2,o=Math.min(s,n),u=new Path2D;u.moveTo(t+o,i),u.arcTo(t+r,i,t+r,i+a,o),u.arcTo(t+r,i+a,t,i+a,o),u.arcTo(t,i+a,t,i,o),u.arcTo(t,i,t+r,i,o),u.closePath(),e.fill(u)}function Cs(e,t,i){if(t.kind==="solid"){const o=Mt(t.color,t.opacity);return`rgba(${o.r},${o.g},${o.b},${o.a})`}const r=i.x+i.w/2,a=i.y+i.h/2,s=Math.max(i.w,i.h)/2,n=o=>{const u=t.kind==="linear"||t.kind==="radial"?t.opacity:1,l=t.kind==="linear"||t.kind==="radial"?t.stops:[];for(const c of l){const d=Mt(c.color,u);o.addColorStop(c.offset,`rgba(${d.r},${d.g},${d.b},${d.a})`)}return o};if(t.kind==="linear"){const o=t.angle*Math.PI/180,u=r+Math.cos(o+Math.PI)*s,l=a+Math.sin(o+Math.PI)*s,c=r+Math.cos(o)*s,d=a+Math.sin(o)*s;return n(e.createLinearGradient(u,l,c,d))}else return n(e.createRadialGradient(r,a,0,r,a,s))}function CI(e){let t=1/0,i=1/0,r=-1/0,a=-1/0;for(const s of e){if(s.op!=="FillPath")continue;const n=s;if(n.isShadow)continue;const o=Vb(n.path),u=n.scale??1,l=n.x+u*o.x,c=n.x+u*(o.x+o.w),d=n.y-u*(o.y+o.h),h=n.y-u*o.y;l<t&&(t=l),d<i&&(i=d),c>r&&(r=c),h>a&&(a=h)}return t===1/0?{x:0,y:0,w:1,h:1}:{x:t,y:i,w:Math.max(1,r-t),h:Math.max(1,a-i)}}function Vb(e){const t=xI(e);let i=0,r=1/0,a=1/0,s=-1/0,n=-1/0;const o=(u,l)=>{u<r&&(r=u),l<a&&(a=l),u>s&&(s=u),l>n&&(n=l)};for(;i<t.length;)switch(t[i++]){case"M":case"L":{const l=parseFloat(t[i++]),c=parseFloat(t[i++]);o(l,c);break}case"C":{const l=parseFloat(t[i++]),c=parseFloat(t[i++]),d=parseFloat(t[i++]),h=parseFloat(t[i++]),g=parseFloat(t[i++]),m=parseFloat(t[i++]);o(l,c),o(d,h),o(g,m);break}case"Q":{const l=parseFloat(t[i++]),c=parseFloat(t[i++]),d=parseFloat(t[i++]),h=parseFloat(t[i++]);o(l,c),o(d,h);break}}return r===1/0?{x:0,y:0,w:0,h:0}:{x:r,y:a,w:s-r,h:n-a}}function xI(e){return e.match(/[MLCQZ]|-?\d*\.?\d+(?:e[-+]?\d+)?/gi)??[]}function kc(e,t){const i=Mt(t.color,t.opacity);e.strokeStyle=`rgba(${i.r},${i.g},${i.b},${i.a})`,e.lineWidth=t.width,e.lineCap=t.lineCap??"butt",e.lineJoin=t.lineJoin??"miter",t.dashArray&&t.dashArray.length>0&&e.setLineDash(t.dashArray)}function EI(e){if(e.length===0)return{x:0,y:0,w:0,h:0};let t=e[0].x,i=e[0].y,r=e[0].x,a=e[0].y;for(let s=1;s<e.length;s++){const n=e[s];n.x<t&&(t=n.x),n.y<i&&(i=n.y),n.x>r&&(r=n.x),n.y>a&&(a=n.y)}return{x:t,y:i,w:r-t,h:a-i}}function zb(e,t,i){if(t.length!==0){e.moveTo(t[0].x,t[0].y);for(let r=1;r<t.length;r++)e.lineTo(t[r].x,t[r].y);i&&e.closePath()}}async function Ho(e){try{const t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch ${e}: ${t.status} ${t.statusText}`);try{return await t.arrayBuffer()}catch(i){throw new Error(`Failed to read response body as ArrayBuffer from ${e}: ${i instanceof Error?i.message:String(i)}`)}}catch(t){throw t instanceof Error?t.message.includes("Failed to fetch")||t.message.includes("Failed to read")?t:new Error(`Failed to fetch ${e}: ${t.message}`):new Error(`Failed to fetch ${e}: ${String(t)}`)}}function ai(e,t){return e===void 0?t:typeof e=="string"?parseFloat(e):e}var Pa=null,xs=!1,Pb="https://unpkg.com/@resvg/resvg-wasm@2.6.2/index_bg.wasm";async function Dc(e){try{const t=await fetch(e);if(t.ok){const i=await t.arrayBuffer(),r=new Uint8Array(i);if(r.length>=4&&r[0]===0&&r[1]===97&&r[2]===115&&r[3]===109)return i;console.error(`Invalid WASM magic number from URL: ${e}`)}else console.error(`Failed to fetch resvg WASM from URL: ${e}, status: ${t.status}`);return}catch(t){console.error(`Error fetching resvg WASM from ${e}:`,t);return}}async function Tb(e){try{if(e){const t=e.endsWith(".wasm")?e:e.endsWith("/")?`${e}resvg.wasm`:`${e}/resvg.wasm`,i=await Dc(t);if(i)return i}return}catch(t){console.error("Error in loadResvgWasmWeb:",t);return}}async function AI(e){if(Pa&&xs)return Pa;if(Pa=await Promise.resolve().then(()=>sv),!xs){let i=await Tb(e);if(i||(i=await Dc(Pb)),!i)throw new Error("Failed to load resvg WASM from any source");const r=await WebAssembly.compile(i);await Pa.initWasm(r),xs=!0}return Pa}async function kI(e){if(xs)return;Pa=await Promise.resolve().then(()=>sv);let i;if(e instanceof ArrayBuffer?i=e:(i=await Tb(e),i||(i=await Dc(Pb))),!i)throw new Error("Failed to load resvg WASM from any source");const r=await WebAssembly.compile(i);await Pa.initWasm(r),xs=!0}async function DI(e,t={}){const{Resvg:i}=await AI(),r={};t.background&&(r.background=t.background),t.fitTo?r.fitTo=t.fitTo:t.width?r.fitTo={mode:"width",value:t.width}:t.height&&(r.fitTo={mode:"height",value:t.height});const a=new i(e,r);try{const s=a.render();try{return{png:s.asPng(),width:s.width,height:s.height}}finally{s.free()}}finally{a.free()}}function _I(e,t,i){if(!e.shape)throw new Error("Shape is required for shape mode");const r=ai(e.width,t),a=ai(e.height,i),s=NI(e.shape),n=ZI(s),o=r/2,u=a/2,l=n.x+n.w/2,c=n.y+n.h/2;let d=o-l,h=u-c;e.transform&&(d+=ai(e.transform.x,0),h+=ai(e.transform.y,0));const g=[];if(e.shadow){const v=ai(e.shadow.offsetX,4),_=ai(e.shadow.offsetY,4),C=e.shadow.color??"#000000",k=ai(e.shadow.opacity,.5);g.push(`<path d="${s}" transform="translate(${d+v}, ${h+_})" fill="${C}" fill-opacity="${k}"/>`)}const m=[`d="${s}"`,`transform="translate(${d}, ${h})"`];if(e.fill){const v=`fill-${Date.now()}`,_=SI(e.fill,v);_.defs&&g.unshift(_.defs),m.push(`fill="${_.fill}"`),e.fill.opacity!==void 0&&e.fill.opacity!==1&&m.push(`fill-opacity="${e.fill.opacity}"`)}else m.push('fill="none"');return e.stroke&&e.stroke.width&&ai(e.stroke.width,0)>0&&(m.push(`stroke="${e.stroke.color??"#000000"}"`),m.push(`stroke-width="${e.stroke.width}"`),e.stroke.opacity!==void 0&&e.stroke.opacity!==1&&m.push(`stroke-opacity="${e.stroke.opacity}"`),e.stroke.dashArray&&e.stroke.dashArray.length>0&&m.push(`stroke-dasharray="${e.stroke.dashArray.join(" ")}"`),e.stroke.lineCap&&m.push(`stroke-linecap="${e.stroke.lineCap}"`),e.stroke.lineJoin&&m.push(`stroke-linejoin="${e.stroke.lineJoin}"`)),e.opacity!==void 0&&e.opacity!==1&&m.push(`opacity="${e.opacity}"`),g.push(`<path ${m.join(" ")}/>`),`<svg xmlns="http://www.w3.org/2000/svg" width="${r}" height="${a}" viewBox="0 0 ${r} ${a}">${g.join("")}</svg>`}function SI(e,t,i){if(e.type==="solid")return{fill:e.color};if(e.type==="linear"){const a=ai(e.angle,0)*Math.PI/180,s=50-Math.cos(a)*50,n=50-Math.sin(a)*50,o=50+Math.cos(a)*50,u=50+Math.sin(a)*50,l=e.stops.map(d=>`<stop offset="${ai(d.offset,0)*100}%" stop-color="${d.color}"/>`).join(""),c=`<defs><linearGradient id="${t}" x1="${s}%" y1="${n}%" x2="${o}%" y2="${u}%">${l}</linearGradient></defs>`;return{fill:`url(#${t})`,defs:c}}if(e.type==="radial"){const r=e.stops.map(s=>`<stop offset="${ai(s.offset,0)*100}%" stop-color="${s.color}"/>`).join(""),a=`<defs><radialGradient id="${t}" cx="50%" cy="50%" r="50%">${r}</radialGradient></defs>`;return{fill:`url(#${t})`,defs:a}}return{fill:"#000000"}}function NI(e){const t=e.type;switch(t){case"rectangle":{const i=e;return BI(i.width,i.height,i.cornerRadius??0)}case"circle":return Ob(e.radius);case"ellipse":{const i=e;return FI(i.radiusX,i.radiusY)}case"line":{const i=e;return VI(i.length,i.thickness??2)}case"polygon":{const i=e;return zI(i.sides,i.radius)}case"star":{const i=e;return PI(i.points,i.outerRadius,i.innerRadius)}case"arrow":{const i=e;return TI(i.length,i.headWidth??30,i.headLength??25,i.shaftWidth??10)}case"heart":return OI(e.size);case"cross":{const i=e;return $I(i.width,i.height,i.thickness)}case"ring":{const i=e;return RI(i.outerRadius,i.innerRadius)}case"path":return e.d;default:throw new Error(`Unknown shape type: ${t}`)}}var Jo=.5522847498307936;function BI(e,t,i){const r=-e/2,a=-t/2,s=Math.min(i,e/2,t/2);return s===0?`M ${r} ${a} L ${r+e} ${a} L ${r+e} ${a+t} L ${r} ${a+t} Z`:[`M ${r+s} ${a}`,`L ${r+e-s} ${a}`,`Q ${r+e} ${a} ${r+e} ${a+s}`,`L ${r+e} ${a+t-s}`,`Q ${r+e} ${a+t} ${r+e-s} ${a+t}`,`L ${r+s} ${a+t}`,`Q ${r} ${a+t} ${r} ${a+t-s}`,`L ${r} ${a+s}`,`Q ${r} ${a} ${r+s} ${a}`,"Z"].join(" ")}function Ob(e){const t=e*Jo;return[`M ${e} 0`,`C ${e} ${t} ${t} ${e} 0 ${e}`,`C ${-t} ${e} ${-e} ${t} ${-e} 0`,`C ${-e} ${-t} ${-t} ${-e} 0 ${-e}`,`C ${t} ${-e} ${e} ${-t} ${e} 0`,"Z"].join(" ")}function II(e){const t=e*Jo;return[`M ${e} 0`,`C ${e} ${-t} ${t} ${-e} 0 ${-e}`,`C ${-t} ${-e} ${-e} ${-t} ${-e} 0`,`C ${-e} ${t} ${-t} ${e} 0 ${e}`,`C ${t} ${e} ${e} ${t} ${e} 0`,"Z"].join(" ")}function FI(e,t){const i=e*Jo,r=t*Jo;return[`M ${e} 0`,`C ${e} ${r} ${i} ${t} 0 ${t}`,`C ${-i} ${t} ${-e} ${r} ${-e} 0`,`C ${-e} ${-r} ${-i} ${-t} 0 ${-t}`,`C ${i} ${-t} ${e} ${-r} ${e} 0`,"Z"].join(" ")}function VI(e,t){const i=e/2,r=t/2;return`M ${-i} ${-r} L ${i} ${-r} L ${i} ${r} L ${-i} ${r} Z`}function zI(e,t){const i=2*Math.PI/e,r=-Math.PI/2,a=[];for(let s=0;s<e;s++){const n=r+s*i,o=Math.cos(n)*t,u=Math.sin(n)*t;a.push(s===0?`M ${o} ${u}`:`L ${o} ${u}`)}return a.push("Z"),a.join(" ")}function PI(e,t,i){const r=Math.PI/e,a=-Math.PI/2,s=[];for(let n=0;n<e*2;n++){const o=a+n*r,u=n%2===0?t:i,l=Math.cos(o)*u,c=Math.sin(o)*u;s.push(n===0?`M ${l} ${c}`:`L ${l} ${c}`)}return s.push("Z"),s.join(" ")}function TI(e,t,i,r){const a=r/2,s=t/2,n=e-i,o=-e/2;return[`M ${o} ${-a}`,`L ${o+n} ${-a}`,`L ${o+n} ${-s}`,`L ${o+e} 0`,`L ${o+n} ${s}`,`L ${o+n} ${a}`,`L ${o} ${a}`,"Z"].join(" ")}function OI(e){const t=e/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(r=>r.replace(/-?\d+(\.\d+)?/g,a=>String(parseFloat(a)*t))).join(" ")}function $I(e,t,i){const r=e/2,a=t/2,s=i/2;return[`M ${-s} ${-a}`,`L ${s} ${-a}`,`L ${s} ${-s}`,`L ${r} ${-s}`,`L ${r} ${s}`,`L ${s} ${s}`,`L ${s} ${a}`,`L ${-s} ${a}`,`L ${-s} ${s}`,`L ${-r} ${s}`,`L ${-r} ${-s}`,`L ${-s} ${-s}`,"Z"].join(" ")}function RI(e,t){const i=Ob(e),r=II(t);return`${i} ${r}`}function ZI(e){const t=/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/g,i=[];let r;for(;(r=t.exec(e))!==null;){const g=parseFloat(r[0]);!isNaN(g)&&isFinite(g)&&i.push(g)}if(i.length<2)return{x:0,y:0,w:0,h:0};let a=1/0,s=1/0,n=-1/0,o=-1/0,u=0,l=0;const c=e.match(/[MmLlHhVvCcSsQqTtAaZz]/g)||[];let d=0,h=0;for(;d<c.length;){switch(c[d]){case"M":case"L":case"T":h+1<i.length&&(u=i[h++],l=i[h++],a=Math.min(a,u),n=Math.max(n,u),s=Math.min(s,l),o=Math.max(o,l));break;case"m":case"l":case"t":h+1<i.length&&(u+=i[h++],l+=i[h++],a=Math.min(a,u),n=Math.max(n,u),s=Math.min(s,l),o=Math.max(o,l));break;case"H":h<i.length&&(u=i[h++],a=Math.min(a,u),n=Math.max(n,u));break;case"h":h<i.length&&(u+=i[h++],a=Math.min(a,u),n=Math.max(n,u));break;case"V":h<i.length&&(l=i[h++],s=Math.min(s,l),o=Math.max(o,l));break;case"v":h<i.length&&(l+=i[h++],s=Math.min(s,l),o=Math.max(o,l));break;case"C":if(h+5<i.length)for(let m=0;m<3;m++){const v=i[h++],_=i[h++];a=Math.min(a,v),n=Math.max(n,v),s=Math.min(s,_),o=Math.max(o,_),m===2&&(u=v,l=_)}break;case"c":if(h+5<i.length)for(let m=0;m<3;m++){const v=u+i[h++],_=l+i[h++];a=Math.min(a,v),n=Math.max(n,v),s=Math.min(s,_),o=Math.max(o,_),m===2&&(u=v,l=_)}break;case"S":case"Q":if(h+3<i.length)for(let m=0;m<2;m++){const v=i[h++],_=i[h++];a=Math.min(a,v),n=Math.max(n,v),s=Math.min(s,_),o=Math.max(o,_),m===1&&(u=v,l=_)}break;case"s":case"q":if(h+3<i.length)for(let m=0;m<2;m++){const v=u+i[h++],_=l+i[h++];a=Math.min(a,v),n=Math.max(n,v),s=Math.min(s,_),o=Math.max(o,_),m===1&&(u=v,l=_)}break;case"A":h+6<i.length&&(h+=5,u=i[h++],l=i[h++],a=Math.min(a,u),n=Math.max(n,u),s=Math.min(s,l),o=Math.max(o,l));break;case"a":h+6<i.length&&(h+=5,u+=i[h++],l+=i[h++],a=Math.min(a,u),n=Math.max(n,u),s=Math.min(s,l),o=Math.max(o,l));break}d++}return a===1/0?{x:0,y:0,w:0,h:0}:{x:a,y:s,w:n-a,h:o-s}}async function MI(e,t={}){const i=t.defaultWidth??1920,r=t.defaultHeight??1080;let a,s,n;if(e.src){a=e.src;const o=UI(a);s=o.width||i,n=o.height||r}else if(e.shape)s=ai(e.width,i),n=ai(e.height,r),a=_I(e,s,n);else throw new Error("Either 'src' or 'shape' must be provided");return DI(a,{width:s,height:n,background:t.background})}function UI(e){const t=e.match(/width\s*=\s*["']?(\d+(?:\.\d+)?)/i),i=e.match(/height\s*=\s*["']?(\d+(?:\.\d+)?)/i);let r=t?parseFloat(t[1]):0,a=i?parseFloat(i[1]):0;if(!r||!a){const s=e.match(/viewBox\s*=\s*["']([^"']+)["']/i);if(s){const n=s[1].trim().split(/[\s,]+/).map(parseFloat);n.length===4&&(r=r||n[2],a=a||n[3])}}return{width:r,height:a}}var _c=typeof process=="object"&&process?process:{},LI=(e,t,i,r)=>{typeof _c.emitWarning=="function"?_c.emitWarning(e,t,i,r):console.error(`[${i}] ${t}: ${e}`)},$b=globalThis.AbortController,Rb=globalThis.AbortSignal;if(typeof $b>"u"){Rb=class{constructor(){ft(this,"onabort"),ft(this,"_onabort",[]),ft(this,"reason"),ft(this,"aborted",!1)}addEventListener(i,r){this._onabort.push(r)}},$b=class{constructor(){ft(this,"signal",new Rb),t()}abort(i){if(!this.signal.aborted){this.signal.reason=i,this.signal.aborted=!0;for(let r of this.signal._onabort)r(i);this.signal.onabort?.(i)}}};let e=_c.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{e&&(e=!1,LI("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}var jI=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),GI=e=>jI(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?WI:null:null,WI=class extends Array{constructor(e){super(e),this.fill(0)}},Ta,Es;Ta=class{constructor(e,t){if(ft(this,"heap"),ft(this,"length"),!PE(Ta,Es))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}static create(e){let t=GI(e);if(!t)return[];xd(Ta,Es,!0);let i=new Ta(e,t);return xd(Ta,Es,!1),i}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Es=new WeakMap,TE(Ta,Es,!1);var Zb="https://fonts.gstatic.com/s/opensans/v44/mem8YaGs126MiZpBA-U1UpcaXcl0Aw.ttf";Sb.setFallbackLoader(async e=>{const t=(e.family??"Open Sans").toLowerCase(),i=`${e.weight??"400"}`;if(t==="open sans"&&i==="400")return Ho(Zb)});async function YI(e={}){const t=e.width??At.DEFAULTS.width,i=e.height??At.DEFAULTS.height,r=e.pixelRatio??At.DEFAULTS.pixelRatio,a="https://shotstack-ingest-api-dev-sources.s3.ap-southeast-2.amazonaws.com/euo5r93oyr/zzz01k9h-yycyx-2x2y6-qx9bj-7n567b/source.wasm";let s;try{s=await Sb.getSharedInstance(a)}catch(m){throw new Error(`Failed to initialize font registry: ${m instanceof Error?m.message:String(m)}`)}const n=new eI(s),o=new Map,u=new Map,l=m=>`${m??"400"}`,c=(m,v)=>`${m}__${l(v)}`,d=async(m,v)=>{const _={family:v.family,weight:l(v.weight)},C=`${m}|${c(_.family,_.weight)}`,k=u.get(C);if(k)return k;const w=(async()=>{if(s.hasRegisteredFace(_))return;const x=await Ho(m);await s.registerFromBytes(x,_)})();return u.set(C,w),w},h=async m=>{const v={family:m.family,weight:l(m.weight)},_=`${m.src}|${c(v.family,v.weight)}`,C=o.get(_);if(C)return C;const k=(async()=>{if(s.hasRegisteredFace(v))return;const w=await Ho(m.src);await s.registerFromBytes(w,v)})();return o.set(_,k),k};async function g(m){try{if(m.customFonts)for(const k of m.customFonts)try{await h(k)}catch(w){throw new Error(`Failed to load custom font "${k.family}" from ${k.src}: ${w instanceof Error?w.message:String(w)}`)}const v=m.font??{family:"Open Sans",weight:"400",size:48,color:"#000000",opacity:1},_={family:v.family,weight:`${v.weight}`};return await(async()=>{try{await s.getFace(_)}catch{if((v.family||"Open Sans").toLowerCase()==="open sans"&&`${v.weight}`=="400"){if(!s.hasRegisteredFace({family:"Open Sans",weight:"400"})){const w=await Ho(Zb);await s.registerFromBytes(w,{family:"Open Sans",weight:"400"})}}else throw new Error(`Font not registered for ${_.family}__${_.weight}`)}})(),v}catch(v){throw v instanceof Error?v:new Error(`Failed to ensure fonts: ${String(v)}`)}}return{validate(m){const v=S9.safeParse(m);if(!v.success){const _=v.error.issues.map(C=>C.message).join(". ");throw new Error(`Validation failed: ${_}`)}return{value:v.data}},async registerFontFromUrl(m,v){try{await d(m,v)}catch(_){throw new Error(`Failed to register font "${v.family}" from URL ${m}: ${_ instanceof Error?_.message:String(_)}`)}},async registerFontFromFile(m,v){try{let _;if(typeof m=="string"){await d(m,v);return}else try{_=await m.arrayBuffer()}catch(k){throw new Error(`Failed to read Blob as ArrayBuffer: ${k instanceof Error?k.message:String(k)}`)}const C={family:v.family,weight:l(v.weight)};if(s.hasRegisteredFace(C))return;await s.registerFromBytes(_,C)}catch(_){throw _ instanceof Error?_:new Error(`Failed to register font "${v.family}" from ${typeof m=="string"?m:"Blob"}: ${String(_)}`)}},async renderFrame(m,v,_){try{const C=await g(m),k={family:C.family,weight:`${C.weight}`};let w;try{let re;const q=s.getColorEmojiFontFamilies();if(q.length>0)re={family:q[0],weight:"400"};else{const ce={family:"NotoEmoji",weight:"400"};try{await s.getFace(ce),re=ce}catch{}}const pe=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??t)-pe.left-pe.right,letterSpacing:m.style?.letterSpacing??0,fontSize:C.size,lineHeight:m.style?.lineHeight??1.2,desc:k,textTransform:m.style?.textTransform??"none",emojiFallback:re})}catch(re){throw new Error(`Failed to layout text: ${re instanceof Error?re.message:String(re)}`)}const x=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},D=m.border?.width??0,b=(m.width??t)+D*2,$=(m.height??i)+D*2,G=r,J={x:0,y:0,width:(m.width??t)-x.left-x.right,height:(m.height??i)-x.top-x.bottom},T=m.width??t,Y=m.height??i;let O;try{O=await rI({canvas:{width:b,height:$,pixelRatio:G},textRect:J,lines:w,contentRect:{width:T,height:Y},font:{family:C.family,size:C.size,weight:`${C.weight}`,color:C.color,opacity:C.opacity,background:C.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,q)=>s.glyphPath(q||k,re),getUnitsPerEm:re=>s.getUnitsPerEm(re||k),isColorEmojiFont:re=>s.isColorEmojiFont(re)})}catch(re){throw new Error(`Failed to build draw operations: ${re instanceof Error?re.message:String(re)}`)}try{return oI(O,w,{t:v,fontSize:C.size,clipDuration:_,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(C){throw C instanceof Error?C:new Error(`Failed to render frame at time ${v}s: ${String(C)}`)}},createRenderer(m){try{return wI(m)}catch(v){throw new Error(`Failed to create renderer: ${v instanceof Error?v.message:String(v)}`)}},destroy(){try{s.release()}catch(m){console.error(`Error during cleanup: ${m instanceof Error?m.message:String(m)}`)}}}}const Mb=e=>{const i=(e.split("/").pop()||"").replace(/\.(ttf|otf|woff|woff2)$/i,""),r=i.replace(/-(Bold|Light|Regular|Italic|Medium|SemiBold|Black|Thin|ExtraLight|ExtraBold|Heavy)$/i,"");return{full:i,base:r}},KI=e=>e.includes("fonts.gstatic.com");class Ii extends Ot{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(t){return t.split("#",1)[0].split("?",1)[0]}constructor(t,i){const{fit:r,...a}=i;super(t,a,ht.RichText)}resolveFontWeight(t,i){const r=t.font?.weight;return typeof r=="string"?parseInt(r,10)||i:typeof r=="number"?r:i}buildCanvasPayload(t,i){const r=this.clipConfiguration.width||this.edit.size.width,a=this.clipConfiguration.height||this.edit.size.height,s=t.font?.family,{baseFontFamily:n,fontWeight:o}=i??(s?pi(s):{baseFontFamily:s,fontWeight:400}),u=this.resolveFontWeight(t,o),l=this.edit.getTimelineFonts(),c=s?l.find(m=>{const{full:v,base:_}=Mb(m.src),C=s.toLowerCase();return v.toLowerCase()===C||_.toLowerCase()===C}):void 0;let d;if(c&&s)d=[{src:c.src,family:n||s,weight:u.toString()}];else if(s){const m=this.edit.getFontMetadata(),v=(n||s).toLowerCase(),C=l.filter(k=>!KI(k.src)).find(k=>m.get(k.src)?.baseFamilyName.toLowerCase()===v);C&&(d=[{src:C.src,family:n||s,weight:u.toString()}])}const g=d||s&&Rs(s)?n||s:void 0;return{...t,width:r,height:a,font:t.font?{...t.font,family:g||"Roboto",weight:u}:void 0,stroke:t.font?.stroke,...d&&{customFonts:d}}}async registerFont(t,i,r){if(!this.textEngine)return!1;const a=Ii.getFontSourceCacheKey(r.path),s=`${r.type}:${a}|${t}|${i}`,n=this.fontRegistrationCache.get(s);if(n)return n;const o=(async()=>{try{const u={family:t,weight:i.toString()};return r.type==="url"?await this.textEngine.registerFontFromUrl(r.path,u):await this.textEngine.registerFontFromFile(r.path,u),!0}catch{return!1}})();return this.fontRegistrationCache.set(s,o),o}createFontCapabilityCheckPromise(t){return(async()=>{try{const i=await fetch(t);if(!i.ok)throw new Error(`Failed to fetch font: ${i.status}`);const r=await i.arrayBuffer();return!!yu.parse(r).tables.fvar?.axes?.find(n=>n.tag==="wght")}catch(i){return console.warn("Failed to check font capabilities:",i),!1}})()}async prepareFontForAsset(t,i){const r=await this.ensureFontRegistered(t);if(!r)return;const a=Ii.getFontSourceCacheKey(r),s=Ii.fontCapabilityCache.get(a),n=s??this.createFontCapabilityCheckPromise(r);s||Ii.fontCapabilityCache.set(a,n),this.fontSupportsBold=await n,i&&this.edit.getInternalEvents().emit(yt.FontCapabilitiesChanged,{supportsBold:this.fontSupportsBold})}supportsBold(){return this.fontSupportsBold}resolveFont(t){const{baseFontFamily:i,fontWeight:r}=pi(t),a=this.edit.getFontUrlByFamilyAndWeight(i,r);if(a)return{url:a,baseFontFamily:i,fontWeight:r};const o=(this.edit.getEdit()?.timeline?.fonts||[]).find(l=>{const{full:c,base:d}=Mb(l.src),h=t.toLowerCase();return c.toLowerCase()===h||d.toLowerCase()===h});if(o)return{url:o.src,baseFontFamily:i,fontWeight:r};const u=Rs(t);return u?{url:u,baseFontFamily:i,fontWeight:r}:null}reconfigureAfterRestore(){super.reconfigureAfterRestore(),this.reconfigure(this.clipConfiguration.asset)}async reconfigure(t){try{await this.prepareFontForAsset(t,!0);for(const i of this.cachedFrames.values())i.destroy();if(this.cachedFrames.clear(),this.lastRenderedTime=-1,this.textEngine){const i=this.buildCanvasPayload(t),{value:r}=this.textEngine.validate(i);this.validatedAsset=r}this.textEngine&&this.renderer&&this.renderFrameSafe(this.getPlaybackTime())}catch{}}async ensureFontRegistered(t){if(!this.textEngine)return null;const i=t.font?.family;if(!i)return null;const r=this.resolveFont(i);if(!r)return null;const a=this.resolveFontWeight(t,r.fontWeight);return await this.registerFont(r.baseFontFamily,a,{type:"url",path:r.url}),r.url}async load(){await super.load();const t=this.clipConfiguration.asset;try{if(!od.safeParse(t).success){this.createFallbackText(t);return}const r=t.font?.family,a=r?pi(r):void 0,s=this.buildCanvasPayload(t,a);this.textEngine=await YI({width:s.width,height:s.height,fps:Ii.PREVIEW_FPS});const{value:n}=this.textEngine.validate(s);this.validatedAsset=n,this.canvas=document.createElement("canvas"),this.canvas.width=s.width,this.canvas.height=s.height,this.renderer=this.textEngine.createRenderer(this.canvas),await this.prepareFontForAsset(t,!1),await this.renderFrame(0),this.configureKeyframes(),this.loadComplete=!0}catch{this.cleanupResources(),this.createFallbackText(t)}}cleanupResources(){if(this.textEngine){try{this.textEngine.destroy()}catch(t){console.warn("Error destroying text engine:",t)}this.textEngine=null}this.renderer=null,this.canvas=null,this.validatedAsset=null}async renderFrame(t){if(!this.textEngine||!this.renderer||!this.canvas||!this.validatedAsset)return;const i=Math.floor(t*Ii.PREVIEW_FPS);if(this.cachedFrames.has(i)){const r=this.cachedFrames.get(i);this.sprite&&this.sprite.texture!==r&&(this.sprite.texture=r),this.lastRenderedTime=t;return}try{const r=this.getLength(),a=await this.textEngine.renderFrame(this.validatedAsset,t,r),s=this.canvas.getContext("2d");s&&s.clearRect(0,0,this.canvas.width,this.canvas.height),await this.renderer.render(a);const n=se.Texture.from(this.canvas);this.sprite?(this.texture&&!this.cachedFrames.has(i)&&this.texture.destroy(),this.sprite.texture=n):(this.sprite=new se.Sprite(n),this.contentContainer.addChild(this.sprite)),this.texture=n,this.cachedFrames.size<150&&this.cachedFrames.set(i,n),this.lastRenderedTime=t}catch(r){console.error("Failed to render rich text frame:",r)}}createFallbackText(t){const i=this.edit.getEdit(),r=this.clipConfiguration.width||i?.output?.size?.width||this.edit.size.width,a=this.clipConfiguration.height||i?.output?.size?.height||this.edit.size.height,s=new se.TextStyle({fontFamily:t.font?.family||"Arial",fontSize:t.font?.size||48,fill:t.font?.color||"#ffffff",align:t.align?.horizontal||"center",wordWrap:!0,wordWrapWidth:r}),n=new se.Text(t.text,s);switch(t.align?.horizontal){case"left":n.anchor.set(0,.5),n.x=0;break;case"right":n.anchor.set(1,.5),n.x=r;break;default:n.anchor.set(.5,.5),n.x=r/2}switch(t.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),this.configureKeyframes()}renderFrameSafe(t){if(this.isRendering){this.pendingRenderTime=t;const i=Math.floor(t*Ii.PREVIEW_FPS),r=this.cachedFrames.get(i);r&&this.sprite&&this.sprite.texture!==r&&(this.sprite.texture=r);return}this.isRendering=!0,this.pendingRenderTime=null,this.renderFrame(t).catch(i=>console.error("Failed to render rich text frame:",i)).finally(()=>{if(this.isRendering=!1,this.pendingRenderTime!==null&&this.pendingRenderTime!==t){const i=this.pendingRenderTime;this.pendingRenderTime=null,this.renderFrameSafe(i)}})}update(t,i){if(super.update(t,i),i===dr.SEEK_ELAPSED_MARKER&&(this.isRendering=!1,this.pendingRenderTime=null,this.lastRenderedTime=-1),!!this.isActive()&&this.loadComplete&&this.textEngine&&this.renderer&&!this.isRendering){const r=this.getPlaybackTime(),a=1/60;Math.abs(r-this.lastRenderedTime)>a&&this.renderFrameSafe(r)}}dispose(){super.dispose(),this.loadComplete=!1;for(const t of this.cachedFrames.values())t.destroy();this.cachedFrames.clear(),this.texture&&!this.cachedFrames.has(Math.floor(this.lastRenderedTime*Ii.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 t=this.edit.getEdit();return{width:this.clipConfiguration.width||t?.output?.size?.width||this.edit.size.width,height:this.clipConfiguration.height||t?.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 t=this.getScale();return{x:t,y:t}}supportsEdgeResize(){return!0}onDimensionsChanged(){if(!this.textEngine||!this.renderer||!this.canvas)return;const t=this.clipConfiguration.asset,{width:i,height:r}=this.getSize();this.canvas.width=i,this.canvas.height=r;for(const n of this.cachedFrames.values())n.destroy();this.cachedFrames.clear(),this.lastRenderedTime=-1;const a=this.buildCanvasPayload(t),{value:s}=this.textEngine.validate(a);this.validatedAsset=s,this.renderFrameSafe(this.getPlaybackTime())}updateTextContent(t){const i=this.clipConfiguration.asset;if(i.text=t,this.textEngine){const r=this.buildCanvasPayload(i),{value:a}=this.textEngine.validate(r);this.validatedAsset=a}for(const r of this.cachedFrames.values())r.destroy();this.cachedFrames.clear(),this.lastRenderedTime=-1,this.textEngine&&this.renderer&&this.renderFrameSafe(this.getPlaybackTime())}getCacheSize(){return this.cachedFrames.size}}class XI extends Ot{shape;shapeBackground;constructor(t,i){super(t,i,ht.Shape),this.shape=null,this.shapeBackground=null}async load(){await super.load();const t=this.clipConfiguration.asset,i=new se.Graphics,r=t.width??this.edit.size.width,a=t.height??this.edit.size.height;i.fillStyle={color:"transparent"},i.rect(0,0,r,a),i.fill();const s=new se.Graphics;switch(t.shape){case"rectangle":{const n=t.rectangle,o=r/2-n.width/2,u=a/2-n.height/2;s.rect(o,u,n.width,n.height);break}case"circle":{const n=t.circle,o=r/2,u=a/2;s.circle(o,u,n.radius);break}case"line":{const n=t.line,o=r/2-n.length/2,u=a/2-n.thickness/2;s.rect(o,u,n.length,n.thickness);break}default:console.warn("Unsupported shape asset type.");break}if(s.fillStyle={color:t.fill?.color??"#ffffff",alpha:t.fill?.opacity??1},s.fill(),t.stroke){const n=new Cr({thickness:t.stroke.width,color:t.stroke.color});s.filters=[n]}this.shapeBackground=i,this.shape=s,this.contentContainer.addChild(i),i.addChild(s),this.configureKeyframes()}update(t,i){super.update(t,i)}dispose(){super.dispose(),this.shape?.destroy(),this.shape=null,this.shapeBackground?.destroy(),this.shapeBackground=null}getSize(){const t=this.clipConfiguration.asset;return{width:t.width??this.edit.size.width,height:t.height??this.edit.size.height}}getFitScale(){return 1}}const HI="https://unpkg.com/@resvg/resvg-wasm@2.6.2/index_bg.wasm";class Gi extends Ot{static resvgInitialized=!1;static resvgInitPromise=null;texture=null;sprite=null;renderedWidth=0;renderedHeight=0;pendingRender=null;constructor(t,i){super(t,i,ht.Svg)}static async initializeResvg(){if(!Gi.resvgInitialized){if(Gi.resvgInitPromise){await Gi.resvgInitPromise;return}Gi.resvgInitPromise=(async()=>{const i=await(await fetch(HI)).arrayBuffer();await kI(i),Gi.resvgInitialized=!0})(),await Gi.resvgInitPromise}}async load(){await super.load();let t=this.clipConfiguration.asset;if(t.src){const i=this.edit.resolveMergeFields(t.src);i!==t.src&&(t={...t,src:i})}try{if(!Jx.safeParse(t).success){this.createFallbackGraphic();return}await Gi.initializeResvg(),await this.doRender(),this.configureKeyframes()}catch(i){console.error("Failed to render SVG asset:",i),this.createFallbackGraphic()}}async reloadAsset(){await this.rerenderAtCurrentDimensions()}createFallbackGraphic(){const t=this.clipConfiguration.width||this.edit.size.width,i=this.clipConfiguration.height||this.edit.size.height,r=Jc(t,i);this.renderedWidth=t,this.renderedHeight=i,this.contentContainer.addChild(r),this.configureKeyframes()}update(t,i){super.update(t,i)}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 t=this.clipConfiguration.asset,i=this.clipConfiguration.width||this.edit.size.width,r=this.clipConfiguration.height||this.edit.size.height,a=await MI(t,{defaultWidth:i,defaultHeight:r});this.renderedWidth=a.width,this.renderedHeight=a.height;const s=new Blob([a.png],{type:"image/png"}),n=URL.createObjectURL(s),o=new Image;o.src=n,await new Promise((u,l)=>{o.onload=()=>u(),o.onerror=()=>l(new Error("Failed to load SVG image"))}),URL.revokeObjectURL(n),this.texture=se.Texture.from(o),this.sprite=new se.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.clipConfiguration.width&&this.clipConfiguration.height&&this.applyFixedDimensions()}}class As{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(t,i,r,a){this.parent=t,this.textElement=i,this.clipConfig=r,this.width=a?.width??As.DEFAULT_CURSOR_WIDTH_PX,this.color=a?.color??As.DEFAULT_CURSOR_COLOR,this.blinkIntervalMs=a?.blinkInterval??As.DEFAULT_BLINK_INTERVAL_MS,this.textPosition=0,this.isBlinking=!1,this.isVisible=!0,this.blinkInterval=null,this.createCursor()}updatePosition(t){if(!this.cursor||!this.textElement){console.warn("TextCursor: Cannot update position, cursor not initialized");return}this.textPosition=this.validateTextPosition(t),this.calculateAndApplyPixelPosition()}setPosition(t,i){if(!this.cursor){console.warn("TextCursor: Cannot set position, cursor not initialized");return}this.pixelX=t,this.pixelY=i,this.updateGraphicsPosition()}show(){this.setVisible(!0)}hide(){this.setVisible(!1)}setVisible(t){this.isVisible=t,this.cursor&&!this.isBlinking&&(this.cursor.visible=t)}startBlinking(){if(!this.cursor){console.warn("TextCursor: Cannot start blinking, cursor not initialized");return}this.isBlinking||this.startBlinkingAnimation()}stopBlinking(){this.stopBlinkingAnimation()}setBlinkInterval(t){this.blinkIntervalMs=t,this.isBlinking&&(this.stopBlinking(),this.startBlinking())}dispose(){if(this.stopBlinkingAnimation(),this.cursor&&this.parent)try{this.parent.removeChild(this.cursor)}catch(t){console.warn("TextCursor: Error removing cursor from parent:",t)}if(this.cursor)try{this.cursor.destroy()}catch(t){console.warn("TextCursor: Error destroying cursor graphics:",t)}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 se.Graphics,this.cursor.fillStyle={color:this.color};const t=this.textElement.style.fontSize;this.cursor.rect(0,0,this.width,t),this.cursor.fill(),this.parent.addChild(this.cursor),this.cursor.visible=this.isVisible}validateTextPosition(t){return this.textElement?Math.max(0,Math.min(t,this.textElement.text.length)):0}calculateAndApplyPixelPosition(){this.calculatePixelPositionFromText(),this.updateGraphicsPosition()}calculatePixelPositionFromText(){if(!this.textElement)return;const{text:t}=this.textElement,i=this.textElement.style,r=t.substring(0,this.textPosition),a=r.match(/\n/g);this.currentLine=a?a.length:0;const s=t.split(`
|
|
266
266
|
`),n=this.currentLine<s.length?s[this.currentLine]:"",o=r.lastIndexOf(`
|
|
267
|
-
`),u=o===-1?this.textPosition:this.textPosition-o-1,l=n.substring(0,u);let c;l.length>0&&l.endsWith(" ")?c=this.measureText(`${l}x`,i)-this.measureText("x",i):c=this.measureText(l,i);const d=i.lineHeight;this.pixelY=this.currentLine*d;const g=this.clipConfig.asset.alignment?.horizontal??"center";let m=c;if(g!=="left"){const v=this.measureText(n,i),_=this.textElement.width;let C=0;g==="center"?C=(_-v)/2:g==="right"&&(C=_-v),m=C+c}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(t,i){const r=new se.Text(t,i),{width:a}=r;return r.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 qo{static DEFAULT_FOCUS_DELAY_MS=50;hiddenInput=null;isFocused=!1;focusRetryCount=0;maxFocusRetries=3;focusDelay=qo.DEFAULT_FOCUS_DELAY_MS;eventHandlers={};abortController=null;textChangeCallback=null;lastSyncedText="";isComposing=!1;setupInput(t,i){this.focusDelay=i?.focusDelay??qo.DEFAULT_FOCUS_DELAY_MS,this.createHiddenTextarea(),this.hiddenInput&&(this.hiddenInput.value=t,this.lastSyncedText=t),this.setupEventListeners(),i?.autoFocus!==!1&&this.focusInput()}updateInputValue(t){this.hiddenInput&&(this.hiddenInput.value=t,this.lastSyncedText=t)}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(t,i){if(!this.hiddenInput)return;const r=this.hiddenInput.value.length,a=Math.max(0,Math.min(t,r)),s=Math.max(a,Math.min(i,r));this.hiddenInput.setSelectionRange(a,s)}getCursorPosition(){return this.hiddenInput?.selectionStart||0}getValue(){return this.hiddenInput?.value||""}setTextInputHandler(t){this.textChangeCallback=t}setEventHandlers(t){this.eventHandlers={...this.eventHandlers,...t}}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 t={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,t),this.hiddenInput.tabIndex=0,document.body.appendChild(this.hiddenInput)}setupEventListeners(){if(!this.hiddenInput)return;this.abortController=new AbortController;const{signal:t}=this.abortController;this.hiddenInput.addEventListener("input",this.handleTextInput,{signal:t}),this.hiddenInput.addEventListener("keydown",this.handleKeyDown,{signal:t}),this.hiddenInput.addEventListener("compositionstart",this.handleCompositionStart,{signal:t}),this.hiddenInput.addEventListener("compositionend",this.handleCompositionEnd,{signal:t}),this.hiddenInput.addEventListener("focus",this.handleFocus,{signal:t}),this.hiddenInput.addEventListener("blur",this.handleBlur,{signal:t}),this.hiddenInput.addEventListener("paste",this.handlePaste,{signal:t})}removeAllEventListeners(){this.abortController?.abort(),this.abortController=null}handleTextInput=t=>{if(!this.hiddenInput||this.isComposing)return;const i=this.hiddenInput.value,r=this.hiddenInput.selectionStart||0;this.lastSyncedText=i,this.textChangeCallback?.(i,r)};handleKeyDown=t=>{if(document.activeElement!==this.hiddenInput)return;let i=!1;if((t.ctrlKey||t.metaKey)&&(i=this.handleKeyboardShortcuts(t),i)){t.preventDefault();return}if(t.key==="Tab"){const r=t.shiftKey?"backward":"forward";this.eventHandlers.onTabNavigation?.(r),t.preventDefault();return}switch(t.key){case"Escape":this.eventHandlers.onEscape?.(t),i=!0;break;case"Enter":i=!1;break;case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":setTimeout(()=>{if(this.hiddenInput){const r=this.hiddenInput.value,a=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(r,a)}},0),i=!1;break;case"Backspace":case"Delete":i=!1;break;default:i=this.eventHandlers.onCustomKey?.(t.key,t)||!1;break}i&&t.preventDefault()};handleKeyboardShortcuts(t){const{key:i}=t;switch(i.toLowerCase()){case"a":return this.selectAll(),!0;case"c":case"v":return!1;case"z":return this.eventHandlers.onCustomKey?.("undo",t),!0;case"y":return this.eventHandlers.onCustomKey?.("redo",t),!0;default:return!1}}handleCompositionStart=t=>{this.isComposing=!0};handleCompositionEnd=t=>{if(this.isComposing=!1,this.hiddenInput){const i=this.hiddenInput.value,r=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(i,r)}};handleFocus=t=>{this.isFocused=!0,this.focusRetryCount=0,this.eventHandlers.onFocus?.(t)};handleBlur=t=>{this.isFocused=!1,this.eventHandlers.onBlur?.(t)};handlePaste=t=>{setTimeout(()=>{this.handleTextInput(t)},0)};selectAll(){this.hiddenInput&&this.hiddenInput.select()}}class Fi{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(t,i,r){this.parent=t,this.targetText=i,this.clipConfig=r,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 t=structuredClone(this.clipConfig);this.targetText.visible=!1,this.createEditingEnvironment(),this.setupOutsideClickHandler(t),this.isEditing=!0}stopEditing(t=!1,i){if(!this.isEditing)return;let r="";this.editableText&&(r=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,t&&i&&r!==""&&this.parent.updateTextContent(r,i),this.isEditing=!1}checkForDoubleClick=t=>{const i=Date.now();i-this.lastClickTime<Fi.DOUBLE_CLICK_THRESHOLD_MS&&this.startEditing(),this.lastClickTime=i};setupOutsideClickHandler(t){this.outsideClickHandler=i=>{const a=this.parent.getContainer().getBounds(),s=i.clientX,n=i.clientY;(s<a.x||s>a.x+a.width||n<a.y||n>a.y+a.height)&&(this.stopEditing(!0,t),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null))},setTimeout(()=>{this.outsideClickHandler&&window.addEventListener("click",this.outsideClickHandler)},Fi.CLICK_HANDLER_DELAY_MS)}createEditingEnvironment(){this.setupEditingContainer(),this.editingContainer&&this.editableText&&(this.textCursor=new As(this.editingContainer,this.editableText,this.clipConfig),this.textCursor.updatePosition(this.targetText.text.length),this.textCursor.startBlinking()),this.setupTextInputHandler(),this.updateTextAlignment()}setupEditingContainer(){this.editingContainer=new se.Container,this.parent.getContainer().addChild(this.editingContainer);const t=new se.Graphics;t.fillStyle={color:0,alpha:Fi.EDITING_BG_ALPHA},t.rect(-5,-5,this.targetText.width+2*Fi.EDITING_BG_PADDING_PX,this.targetText.height+2*Fi.EDITING_BG_PADDING_PX),t.fill(),this.editingContainer.addChild(t),this.editableText=new se.Text(this.targetText.text,this.targetText.style),this.editableText.eventMode="static",this.editableText.cursor="text",this.editingContainer.addChild(this.editableText)}setupTextInputHandler(){this.textInputHandler=new qo,this.textInputHandler.setTextInputHandler((t,i)=>{this.editableText&&(this.editableText.text=t,this.updateTextAlignment()),this.textCursor?.updatePosition(i)}),this.textInputHandler.setEventHandlers({onEscape:t=>this.stopEditing(!1),onTabNavigation:t=>this.stopEditing(!0)}),this.textInputHandler.setupInput(this.targetText.text,{autoFocus:!0})}updateTextAlignment(){if(!this.editableText||!this.editingContainer)return;const t=this.getContainerDimensions(),i=this.getAlignmentSettings(),r=this.calculateHorizontalPosition({width:this.editableText.width},t,i.horizontal),a=this.calculateVerticalPosition({height:this.editableText.height},t,i.vertical);if(this.editingContainer.position.set(r,a),this.editingContainer.children.length>0){const s=this.editingContainer.getChildAt(0);s instanceof se.Graphics&&(s.clear(),s.fillStyle={color:0,alpha:Fi.EDITING_BG_ALPHA},s.rect(-5,-5,this.editableText.width+2*Fi.EDITING_BG_PADDING_PX,this.editableText.height+2*Fi.EDITING_BG_PADDING_PX),s.fill())}}calculateHorizontalPosition(t,i,r="center"){switch(r){case"center":return i.width/2-t.width/2;case"right":return i.width-t.width;case"left":default:return 0}}calculateVerticalPosition(t,i,r="center"){switch(r){case"center":return i.height/2-t.height/2;case"bottom":return i.height-t.height;case"top":default:return 0}}getContainerDimensions(){const t=this.clipConfig.asset;return{width:t.width??this.parent.getSize().width,height:t.height??this.parent.getSize().height}}getAlignmentSettings(){const t=this.clipConfig.asset;return{horizontal:t.alignment?.horizontal??"center",vertical:t.alignment?.vertical??"center"}}}class cr extends Ot{static loadedFonts=new Set;background=null;text=null;textEditor=null;constructor(t,i){super(t,i,ht.Text)}async load(){await super.load();const t=this.clipConfiguration.asset,i=t.font?.family??"Open Sans";if(await this.loadFont(i),this.background=new se.Graphics,this.drawBackground(),this.text=new se.Text({text:t.text??"",style:this.createTextStyle(t)}),this.positionText(t),t.stroke?.width&&t.stroke.width>0&&t.stroke.color){const r=new Cr({thickness:t.stroke.width,color:t.stroke.color});this.text.filters=[r]}this.contentContainer.addChild(this.background),this.contentContainer.addChild(this.text),this.configureKeyframes(),this.textEditor=new Fi(this,this.text,this.clipConfiguration)}update(t,i){super.update(t,i)}reconfigureAfterRestore(){super.reconfigureAfterRestore(),this.reconfigure()}async reconfigure(){const t=this.clipConfiguration.asset,i=t.font?.family??"Open Sans";if(await this.loadFont(i),this.drawBackground(),this.text){if(this.text.text=t.text??"",this.text.style=this.createTextStyle(t),t.stroke?.width&&t.stroke.width>0&&t.stroke.color){const r=new Cr({thickness:t.stroke.width,color:t.stroke.color});this.text.filters=[r]}else this.text.filters=[];this.positionText(t)}}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null,this.textEditor?.dispose(),this.textEditor=null}getSize(){const t=this.clipConfiguration.asset;return{width:this.clipConfiguration.width??t.width??this.edit.size.width,height:this.clipConfiguration.height??t.height??this.edit.size.height}}getFitScale(){return 1}getContainerScale(){const t=this.getScale();return{x:t,y:t}}supportsEdgeResize(){return!0}onDimensionsChanged(){if(this.drawBackground(),this.text){const t=this.clipConfiguration.asset;this.text.style.wordWrapWidth=this.getSize().width,this.positionText(t)}}applyFixedDimensions(){}createTextStyle(t){const i=t.font?.family??"Open Sans",{baseFontFamily:r,fontWeight:a}=pi(i),{width:s}=this.getSize();return new se.TextStyle({fontFamily:r,fontSize:t.font?.size??32,fill:t.font?.color??"#ffffff",fontWeight:a.toString(),wordWrap:!0,wordWrapWidth:s,lineHeight:(t.font?.lineHeight??1)*(t.font?.size??32),align:t.alignment?.horizontal??"center"})}positionText(t){if(!this.text)return;const i=t.alignment?.horizontal??"center",r=t.alignment?.vertical??"center",{width:a,height:s}=this.getSize();let n=a/2-this.text.width/2,o=s/2-this.text.height/2;i==="left"?n=0:i==="right"&&(n=a-this.text.width),r==="top"?o=0:r==="bottom"&&(o=s-this.text.height),this.text.position.set(n,o)}drawBackground(){const t=this.clipConfiguration.asset;if(!this.background||!t.background||!t.background.color)return;const{width:i,height:r}=this.getSize();this.background.clear(),this.background.fillStyle={color:t.background.color,alpha:t.background.opacity??1},this.background.rect(0,0,i,r),this.background.fill()}updateTextContent(t,i){this.edit.updateTextContent(this,t,i)}async loadFont(t){const{baseFontFamily:i,fontWeight:r}=pi(t),a=`${i}-${r}`;if(cr.loadedFonts.has(a))return;const s=Rs(t);if(s){const n=new FontFace(i,`url(${s})`,{weight:r.toString()});await n.load(),document.fonts.add(n),cr.loadedFonts.add(a)}}static resetFontCache(){cr.loadedFonts.clear()}}class JI extends Ot{aiOverlay=null;lastPrompt="";constructor(t,i){super(t,i,ht.TextToImage)}async load(){await super.load();const{width:t,height:i}=this.getSize(),r=this.edit.getResolvedEdit()?.timeline.tracks.flatMap(u=>u.clips)??[],a=Xc(r,this.clipId??""),{asset:s}=this.clipConfiguration,n=ya(s)&&s.prompt||"",o=ya(s)?s.type:"text-to-image";this.aiOverlay=new wu({mode:"panel",icon:"image",width:t,height:i,assetNumber:a??void 0,prompt:n,assetType:o}),this.contentContainer.addChild(this.aiOverlay.getContainer()),this.configureKeyframes()}update(t,i){super.update(t,i);const{width:r,height:a}=this.getSize();this.aiOverlay?.resize(r,a);const{asset:s}=this.clipConfiguration,n=ya(s)&&s.prompt||"";n!==this.lastPrompt&&(this.aiOverlay?.updatePrompt(n),this.lastPrompt=n)}getSize(){const t=this.clipConfiguration.asset;return{width:this.clipConfiguration.width??t.width??this.edit.size.width,height:this.clipConfiguration.height??t.height??this.edit.size.height}}dispose(){this.aiOverlay?.dispose(),this.aiOverlay=null,super.dispose()}}class qI extends Ot{constructor(t,i){super(t,i,ht.TextToSpeech)}async load(){await super.load(),this.configureKeyframes()}update(t,i){super.update(t,i),this.getContainer().alpha=0}getSize(){return{width:0,height:0}}}class QI extends Ot{texture;sprite;isPlaying;volumeKeyframeBuilder;syncTimer;activeSyncTimer;skipVideoUpdate;constructor(t,i){super(t,i,ht.Video),this.texture=null,this.sprite=null,this.isPlaying=!1;const r=this.clipConfiguration.asset;this.volumeKeyframeBuilder=new Ra(r.volume??1,this.getLength()),this.syncTimer=0,this.activeSyncTimer=0,this.skipVideoUpdate=!1}async load(){await super.load(),await this.loadVideo(),this.configureKeyframes()}update(t,i){if(super.update(t,i),this.skipVideoUpdate)return;const{trim:r=0}=this.clipConfiguration.asset;if(this.syncTimer+=i,!this.texture)return;const a=this.getPlaybackTime(),s=this.edit.isPlaying&&this.isActive();s&&(this.isPlaying||(this.isPlaying=!0,this.activeSyncTimer=0,this.texture.source.resource.volume=this.getVolume(),this.texture.source.resource.currentTime=a+r,this.texture.source.resource.play().catch(console.error)),this.texture.source.resource.volume!==this.getVolume()&&(this.texture.source.resource.volume=this.getVolume()),this.activeSyncTimer+=i,this.activeSyncTimer>1e3&&(this.activeSyncTimer=0,Math.abs(this.texture.source.resource.currentTime-r-a)>.3&&(this.texture.source.resource.currentTime=a+r))),!s&&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+r)}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}reconfigureAfterRestore(){super.reconfigureAfterRestore();const t=this.clipConfiguration.asset;this.volumeKeyframeBuilder=new Ra(t.volume??1,this.getLength())}async loadVideo(){const t=this.clipConfiguration.asset,{src:i}=t;if(i.endsWith(".mov"))throw new Error(`Video source '${i}' is not supported. .mov files cannot be played in the browser. Please convert to .webm or .mp4 first.`);const r=`${i}${i.includes("?")?"&":"?"}x-cors=1`,a={src:r,data:{autoPlay:!1,muted:!1}},s=await this.edit.assetLoader.loadVideoUnique(r,a);if(!s||!(s.source instanceof se.VideoSource))throw new Error(`Invalid video source '${i}'.`);s.source.alphaMode="no-premultiply-alpha",this.texture=this.createCroppedTexture(s);const n=this.texture.source.resource;n instanceof HTMLVideoElement&&n.readyState<2&&await new Promise(o=>{const u=()=>{n.removeEventListener("loadeddata",u),o()};n.addEventListener("loadeddata",u),n.readyState>=2&&o()}),this.sprite=new se.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.texture.source.resource.volume=this.getVolume()}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:t=0}=this.clipConfiguration.asset,i=this.texture.source.resource.currentTime,r=this.getPlaybackTime();return Math.abs(i-t-r)}createCroppedTexture(t){const i=this.clipConfiguration.asset;if(!i.crop)return t;const r=t.width,a=t.height;if(r<=0||a<=0)return t;const s=Math.floor((i.crop?.left??0)*r),n=Math.floor((i.crop?.right??0)*r),o=Math.floor((i.crop?.top??0)*a),u=Math.floor((i.crop?.bottom??0)*a),l=s,c=o,d=r-s-n,h=a-o-u,g=new se.Rectangle(l,c,d,h);return new se.Texture({source:t.source,frame:g})}}class Ub{static create(t,i){if(!i.asset?.type)throw new Error("Invalid clip configuration: missing asset type");switch(i.asset.type){case"text":return new cr(t,i);case"rich-text":return new Ii(t,i);case"shape":return new XI(t,i);case"html":return new Xv(t,i);case"image":return new Hv(t,i);case"video":return new QI(t,i);case"audio":return new Vv(t,i);case"luma":return new n3(t,i);case"caption":return new Us(t,i);case"svg":return new Gi(t,i);case"text-to-image":return new JI(t,i);case"image-to-video":return new s3(t,i);case"text-to-speech":return new qI(t,i);default:throw new Error(`Unsupported asset type: ${i.asset.type}`)}}static cleanup(){cr.resetFontCache()}}function Sc(e,t,i,r){const a=new Map,s=`alias://${i}`;for(let n=0;n<e.getTrackCount();n+=1){const o=e.getClipsInTrack(n);for(let u=0;u<o.length;u+=1)if(!r?.has(`${n}:${u}`)){const l=o[u],c=l.id,d=t.timeline.tracks[n]?.clips[u];let h=!1;const g={};if(l.start===s&&(g.start=l.start,h=!0),l.length===s&&(g.length=l.length,h=!0),h&&c&&d){a.set(c,g);const m={};g.start&&(m.start=d.start),g.length&&(m.length=d.length),e.updateClip(n,u,m)}}}return a}function eF(e,t,i,r){const a=new Map;for(const s of i){const n=Sc(e,t,s,r);for(const[o,u]of n){const l=a.get(o);l?a.set(o,{...l,...u}):a.set(o,u)}}return a}function Nc(e,t){for(const[i,r]of t){const a=e.getClipById(i);if(a){const s={};r.start&&(s.start=r.start),r.length&&(s.length=r.length),e.updateClip(a.trackIndex,a.clipIndex,s)}}}function tF(e){const t=[];for(const i of e){const{alias:r}=i;r&&t.push(r)}return t}const Ke=()=>({status:"success"}),vt=e=>({status:"noop",message:e});class iF{constructor(t,i){this.trackIdx=t,this.clip=i}name="addClip";addedClipId;convertedReferences;execute(t){if(!t)throw new Error("AddClipCommand.execute: context is required");const i=t.getDocument();if(!i)throw new Error("AddClipCommand.execute: no document");const r=t.documentAddClip(this.trackIdx,this.clip);this.addedClipId=r.id,this.convertedReferences&&this.convertedReferences.size>0&&Nc(i,this.convertedReferences),t.resolve(),t.updateDuration();const n=t.getDocumentTrack(this.trackIdx)?.clips?.findIndex(o=>o.id===this.addedClipId)??-1;return t.emitEvent(Ae.ClipAdded,{trackIndex:this.trackIdx,clipIndex:n}),Ke()}undo(t){if(!t)throw new Error("AddClipCommand.undo: context is required");if(!this.addedClipId)return vt("No clip ID stored");const i=t.getDocument();if(!i)throw new Error("AddClipCommand.undo: no document");const a=t.getDocumentTrack(this.trackIdx)?.clips,s=a?.findIndex(o=>o.id===this.addedClipId)??-1;if(s===-1)return vt(`Clip ${this.addedClipId} not found in track ${this.trackIdx}`);const n=a?.[s]?.alias;if(n){const o=new Set([`${this.trackIdx}:${s}`]);this.convertedReferences=Sc(i,t.getEditState(),n,o)}return t.documentRemoveClip(this.trackIdx,s),t.resolve(),t.updateDuration(),t.emitEvent(Ae.ClipDeleted,{trackIndex:this.trackIdx,clipIndex:s}),Ke()}dispose(){this.addedClipId=void 0,this.convertedReferences=void 0}}class aF{constructor(t){this.trackIdx=t}name="addTrack";execute(t){if(!t)throw new Error("AddTrackCommand.execute: context is required");const i=t.getDocument();if(!i)throw new Error("AddTrackCommand.execute: document is required");return i.addTrack(this.trackIdx),t.resolve(),t.updateDuration(),t.emitEvent(Ae.TrackAdded,{trackIndex:this.trackIdx,totalTracks:i.getTrackCount()}),Ke()}undo(t){if(!t)throw new Error("AddTrackCommand.undo: context is required");const i=t.getDocument();if(!i)throw new Error("AddTrackCommand.undo: document is required");return i.removeTrack(this.trackIdx),t.resolve(),t.updateDuration(),Ke()}dispose(){}}class Lb{constructor(t){this.trackIdx=t}name="deleteTrack";deletedClips=[];convertedReferences;execute(t){if(!t)throw new Error("DeleteTrackCommand.execute: context is required");const i=t.getDocument();if(!i)throw new Error("DeleteTrackCommand: no document");if(i.getTrackCount()<=1)return vt("Cannot delete the last track");const r=i.getTrack(this.trackIdx);r&&(this.deletedClips=r.clips.map(s=>structuredClone(s)));const a=tF(this.deletedClips);if(a.length>0){const s=new Set;for(let n=0;n<this.deletedClips.length;n+=1)s.add(`${this.trackIdx}:${n}`);this.convertedReferences=eF(i,t.getEditState(),a,s)}return i.removeTrack(this.trackIdx),t.resolve(),t.updateDuration(),t.emitEvent(Ae.TrackRemoved,{trackIndex:this.trackIdx}),Ke()}undo(t){if(!t)throw new Error("DeleteTrackCommand.undo: context is required");const i=t.getDocument();if(!i)throw new Error("DeleteTrackCommand.undo: no document");i.addTrack(this.trackIdx);for(let r=0;r<this.deletedClips.length;r+=1)i.addClip(this.trackIdx,this.deletedClips[r],r);return this.convertedReferences&&this.convertedReferences.size>0&&Nc(i,this.convertedReferences),t.resolve(),t.updateDuration(),t.emitEvent(Ae.TrackAdded,{trackIndex:this.trackIdx,totalTracks:i.getTrackCount()}),Ke()}dispose(){this.deletedClips=[],this.convertedReferences=void 0}}class Bc{constructor(t,i){this.trackIdx=t,this.clipIdx=i}name="deleteClip";deletedClipConfig;deletedClipId;deleteTrackCommand;trackWasDeleted=!1;storedBindings;convertedReferences;execute(t){if(!t)throw new Error("DeleteClipCommand.execute: context is required");const i=t.getDocument();if(!i)throw new Error("DeleteClipCommand: no document");const r=i.getClip(this.trackIdx,this.clipIdx);if(!r)return vt(`No clip at track ${this.trackIdx}, index ${this.clipIdx}`);if(i.getClipCount()<=1)return vt("Cannot delete the last clip");if(this.deletedClipConfig=structuredClone(r),this.deletedClipId=r.id,this.deletedClipId){const o=t.getClipBindings(this.deletedClipId);this.storedBindings=o?new Map(o):void 0,i.clearClipBindings(this.deletedClipId)}const a=r.alias;if(a){const o=new Set([`${this.trackIdx}:${this.clipIdx}`]);this.convertedReferences=Sc(i,t.getEditState(),a,o)}t.clearClipError(this.trackIdx,this.clipIdx);const s=t.getSelectedClip();s&&this.deletedClipId&&s.clipId===this.deletedClipId&&(t.setSelectedClip(null),t.emitEvent(Ae.SelectionCleared)),t.documentRemoveClip(this.trackIdx,this.clipIdx);const n=i.getTrack(this.trackIdx);return n&&n.clips.length===0&&(this.deleteTrackCommand=new Lb(this.trackIdx),this.deleteTrackCommand.execute(t).status==="success"&&(this.trackWasDeleted=!0)),t.resolve(),t.updateDuration(),t.emitEvent(Ae.ClipDeleted,{trackIndex:this.trackIdx,clipIndex:this.clipIdx}),Ke()}undo(t){if(!t)throw new Error("DeleteClipCommand.undo: context is required");if(!this.deletedClipConfig)return vt("No deleted clip config");const i=t.getDocument();if(!i)throw new Error("DeleteClipCommand.undo: no document");this.trackWasDeleted&&i.addTrack(this.trackIdx);const a=t.documentAddClip(this.trackIdx,this.deletedClipConfig,this.clipIdx).id;return a&&this.storedBindings&&this.storedBindings.size>0&&i.setClipBindingsForClip(a,this.storedBindings),this.convertedReferences&&this.convertedReferences.size>0&&Nc(i,this.convertedReferences),t.resolve(),t.updateDuration(),this.trackWasDeleted&&(t.emitEvent(Ae.TrackAdded,{trackIndex:this.trackIdx,totalTracks:i.getTrackCount()}),this.trackWasDeleted=!1),t.emitEvent(Ae.ClipRestored,{trackIndex:this.trackIdx,clipIndex:this.clipIdx}),Ke()}dispose(){this.deletedClipConfig=void 0,this.deletedClipId=void 0,this.deleteTrackCommand=void 0,this.storedBindings=void 0,this.convertedReferences=void 0}}class rF{constructor(t){this.aspectRatio=t}name="setOutputAspectRatio";previousAspectRatio;execute(t){if(!t)throw new Error("SetOutputAspectRatioCommand requires context");return this.previousAspectRatio=t.getOutputAspectRatio(),t.setOutputAspectRatio(this.aspectRatio),Ke()}undo(t){if(!t)throw new Error("SetOutputAspectRatioCommand requires context");return this.previousAspectRatio===void 0?vt("No previous aspect ratio stored"):(t.setOutputAspectRatio(this.previousAspectRatio),Ke())}dispose(){this.previousAspectRatio=void 0}}class sF{constructor(t){this.destinations=t}name="setOutputDestinations";previousDestinations;execute(t){if(!t)throw new Error("SetOutputDestinationsCommand requires context");return this.previousDestinations=t.getOutputDestinations(),t.setOutputDestinations(this.destinations),Ke()}undo(t){if(!t)throw new Error("SetOutputDestinationsCommand requires context");return this.previousDestinations===void 0?vt("No previous destinations stored"):(t.setOutputDestinations(this.previousDestinations),Ke())}dispose(){this.previousDestinations=void 0}}class nF{constructor(t){this.format=t}name="setOutputFormat";previousFormat;execute(t){if(!t)throw new Error("SetOutputFormatCommand requires context");return this.previousFormat=t.getOutputFormat(),t.setOutputFormat(this.format),Ke()}undo(t){if(!t)throw new Error("SetOutputFormatCommand requires context");return this.previousFormat===void 0?vt("No previous format stored"):(t.setOutputFormat(this.previousFormat),Ke())}dispose(){this.previousFormat=void 0}}class oF{constructor(t){this.fps=t}name="setOutputFps";previousFps;execute(t){if(!t)throw new Error("SetOutputFpsCommand requires context");return this.previousFps=t.getOutputFps(),t.setOutputFps(this.fps),Ke()}undo(t){if(!t)throw new Error("SetOutputFpsCommand requires context");return this.previousFps===void 0?vt("No previous FPS stored"):(t.setOutputFps(this.previousFps),Ke())}dispose(){this.previousFps=void 0}}class uF{constructor(t){this.resolution=t}name="setOutputResolution";previousResolution;execute(t){if(!t)throw new Error("SetOutputResolutionCommand requires context");return this.previousResolution=t.getOutputResolution(),t.setOutputResolution(this.resolution),Ke()}undo(t){if(!t)throw new Error("SetOutputResolutionCommand requires context");return this.previousResolution===void 0?vt("No previous resolution stored"):(t.setOutputResolution(this.previousResolution),Ke())}dispose(){this.previousResolution=void 0}}class lF{constructor(t,i){this.width=t,this.height=i}name="setOutputSize";previousSize;execute(t){if(!t)throw new Error("SetOutputSizeCommand requires context");return this.previousSize=t.getOutputSize(),t.setOutputSize(this.width,this.height),Ke()}undo(t){if(!t)throw new Error("SetOutputSizeCommand requires context");return this.previousSize?(t.setOutputSize(this.previousSize.width,this.previousSize.height),Ke()):vt("No previous size stored")}dispose(){this.previousSize=void 0}}class cF{constructor(t){this.color=t}name="setTimelineBackground";previousColor;execute(t){if(!t)throw new Error("SetTimelineBackgroundCommand requires context");return this.previousColor=t.getTimelineBackground(),t.setTimelineBackground(this.color),Ke()}undo(t){if(!t)throw new Error("SetTimelineBackgroundCommand requires context");return this.previousColor===void 0?vt("No previous color stored"):(t.setTimelineBackground(this.previousColor),Ke())}dispose(){this.previousColor=void 0}}function ri(e){const{id:t,...i}=e;return i}function Qo(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function Ic(e,t){const i={...e};return Qo(e)&&Qo(t)&&Object.keys(t).forEach(r=>{if(r==="__proto__"||r==="constructor"||r==="prototype")return;const a=t[r],s=e[r];Qo(a)?r in e&&Qo(s)?i[r]=Ic(s,a):i[r]=Ic({},a):i[r]=a}),i}function Wi(e,t,i){const r=t.split(".");let a=e;for(let s=0;s<r.length-1;s+=1){if(a==null||typeof a!="object")return;const n=r[s],o=a[n];(o==null||typeof o!="object")&&(a[n]={}),a=a[n]}a!=null&&typeof a=="object"&&(a[r[r.length-1]]=i)}function eu(e,t){const i=t.split(".");let r=e;for(const a of i){if(r==null||typeof r!="object")return;r=r[a]}return r}class Fc{constructor(t,i,r){this.initialClipConfig=t,this.finalClipConfig=i,this.trackIndex=r?.trackIndex??-1,this.clipIndex=r?.clipIndex??-1}name="setUpdatedClip";clipId=null;storedInitialConfig=null;storedFinalConfig=null;storedInitialBindings=new Map;previousDocClip=null;trackIndex;clipIndex;async execute(t){if(!t)throw new Error("SetUpdatedClipCommand.execute: context is required");const i=t.getDocument();if(!i)throw new Error("SetUpdatedClipCommand.execute: document is required");const r=t.getClipAt(this.trackIndex,this.clipIndex);if(!r)return vt(`Invalid clip at ${this.trackIndex}/${this.clipIndex}`);this.clipId=r.clipId,this.storedInitialConfig||(this.storedInitialConfig=this.initialClipConfig?structuredClone(this.initialClipConfig):structuredClone(r.clipConfiguration)),this.storedFinalConfig||(this.storedFinalConfig=this.finalClipConfig?structuredClone(this.finalClipConfig):structuredClone(r.clipConfiguration));const a=t.getDocumentClip(this.trackIndex>=0?this.trackIndex:r.layer-1,this.clipIndex>=0?this.clipIndex:t.getTracks()[r.layer-1]?.indexOf(r)??-1);this.previousDocClip=a?structuredClone(a):null;const s=this.clipId?t.getClipBindings(this.clipId):void 0;this.storedInitialBindings=s?new Map(s):new Map;const n=this.trackIndex>=0?this.trackIndex:r.layer-1,o=this.clipIndex>=0?this.clipIndex:t.getTracks()[n]?.indexOf(r)??-1,u=this.storedFinalConfig??this.finalClipConfig;u&&i.replaceClipProperties(n,o,u),t.resolve();const l=t.getClipAt(n,o);for(const[v,{resolvedValue:_}]of this.storedInitialBindings)(l?eu(l.clipConfiguration,v):void 0)!==_&&this.clipId&&t.removeClipBinding(this.clipId,v);const c=this.storedInitialConfig??this.initialClipConfig,d=this.storedFinalConfig??this.finalClipConfig,h=c?.asset,g=d?.asset;if(h?.src!==g?.src){const v=t.getClipAt(n,o);v&&v.getTimingIntent().length==="auto"&&await t.resolveClipAutoLength(v)}const m=t.getDocumentClip(n,o);if(!this.previousDocClip||!m)throw new Error(`SetUpdatedClipCommand: document clip not found after mutation at ${n}/${o}`);return t.emitEvent(Ae.ClipUpdated,{previous:{clip:ri(this.previousDocClip),trackIndex:n,clipIndex:o},current:{clip:ri(m),trackIndex:n,clipIndex:o}}),Ke()}async undo(t){if(!t)throw new Error("SetUpdatedClipCommand.undo: context is required");const i=this.storedInitialConfig??this.initialClipConfig;if(!i)return vt("No stored initial config");const r=t.getDocument();if(!r)throw new Error("SetUpdatedClipCommand.undo: document is required");const a=this.clipId?t.getPlayerByClipId(this.clipId):t.getClipAt(this.trackIndex,this.clipIndex);if(!a)return vt("Clip not found for undo");const s=this.trackIndex>=0?this.trackIndex:a.layer-1,n=this.clipIndex>=0?this.clipIndex:t.getTracks()[s]?.indexOf(a)??-1,o=structuredClone(t.getDocumentClip(s,n));if(r.replaceClipProperties(s,n,i),t.resolve(),this.clipId){const h=new Map(this.storedInitialBindings);h.size>0?t.getDocument()?.setClipBindingsForClip(this.clipId,h):t.getDocument()?.clearClipBindings(this.clipId)}const l=(this.storedFinalConfig??this.finalClipConfig)?.asset,c=i?.asset;if(l?.src!==c?.src){const h=t.getClipAt(s,n);h&&h.getTimingIntent().length==="auto"&&await t.resolveClipAutoLength(h)}const d=t.getDocumentClip(s,n);if(!o||!d)throw new Error(`SetUpdatedClipCommand: document clip not found after undo at ${s}/${n}`);return t.emitEvent(Ae.ClipUpdated,{previous:{clip:ri(o),trackIndex:s,clipIndex:n},current:{clip:ri(d),trackIndex:s,clipIndex:n}}),Ke()}dispose(){this.clipId=null,this.storedInitialConfig=null,this.storedFinalConfig=null,this.storedInitialBindings.clear(),this.previousDocClip=null}}class fF{constructor(t,i,r){this.trackIndex=t,this.clipIndex=i,this.params=r}name="UpdateClipTiming";originalStart;originalLength;clipId;execute(t){if(!t)throw new Error("UpdateClipTimingCommand.execute: context is required");const i=t.getDocument();if(!i)throw new Error("UpdateClipTimingCommand.execute: document is required");const a=t.getDocumentTrack(this.trackIndex)?.clips[this.clipIndex];if(!a)return vt(`Invalid clip at ${this.trackIndex}/${this.clipIndex}`);const s=t.getClipAt(this.trackIndex,this.clipIndex);if(!s)return vt(`Player not found at ${this.trackIndex}/${this.clipIndex}`);this.originalStart=a.start,this.originalLength=a.length,this.clipId=s.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),i.updateClip(this.trackIndex,this.clipIndex,o),this.clipId?t.resolveClip(this.clipId):t.resolve(),o.length==="auto"&&t.resolveClipAutoLength(s).then(()=>{t.updateDuration(),t.propagateTimingChanges(this.trackIndex,this.clipIndex)}),t.updateDuration();const u=t.getDocumentClip(this.trackIndex,this.clipIndex);if(!u)throw new Error(`UpdateClipTimingCommand: document clip not found after mutation at ${this.trackIndex}/${this.clipIndex}`);return t.emitEvent(Ae.ClipUpdated,{previous:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:ri(n)},current:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:ri(u)}}),t.propagateTimingChanges(this.trackIndex,this.clipIndex),Ke()}undo(t){if(!t)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 i=t.getDocument();if(!i)throw new Error("UpdateClipTimingCommand.undo: document is required");const r=t.getClipAt(this.trackIndex,this.clipIndex);if(!r)throw new Error("UpdateClipTimingCommand.undo: player not found");const a=structuredClone(t.getDocumentClip(this.trackIndex,this.clipIndex)),s={};this.originalStart!==void 0&&(s.start=this.originalStart),this.originalLength!==void 0&&(s.length=this.originalLength),i.updateClip(this.trackIndex,this.clipIndex,s),this.clipId?t.resolveClip(this.clipId):t.resolve(),this.originalLength==="auto"&&t.resolveClipAutoLength(r).then(()=>{t.updateDuration(),t.propagateTimingChanges(this.trackIndex,this.clipIndex)}),t.updateDuration();const n=t.getDocumentClip(this.trackIndex,this.clipIndex);if(!a||!n)throw new Error(`UpdateClipTimingCommand: document clip not found after undo at ${this.trackIndex}/${this.clipIndex}`);return t.emitEvent(Ae.ClipUpdated,{previous:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:ri(a)},current:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:ri(n)}}),t.propagateTimingChanges(this.trackIndex,this.clipIndex),Ke()}}class dF{constructor(t,i,r){this.trackIndex=t,this.clipIndex=i,this.newText=r}name="updateTextContent";clipId=null;previousText="";previousDocClip;execute(t){if(!t)throw new Error("UpdateTextContentCommand.execute: context is required");const i=t.getDocument();if(!i)throw new Error("UpdateTextContentCommand.execute: document is required");const r=t.getClipAt(this.trackIndex,this.clipIndex);if(!r)return vt(`Invalid clip at ${this.trackIndex}/${this.clipIndex}`);const a=i.getClip(this.trackIndex,this.clipIndex);if(!a)return vt("Clip not found in document");this.clipId=r.clipId,this.previousDocClip=structuredClone(a);const s=a.asset;this.previousText=s&&"text"in s?s.text??"":"";const o={...a.asset,text:this.newText};i.updateClip(this.trackIndex,this.clipIndex,{asset:o}),this.clipId?t.resolveClip(this.clipId):t.resolve();const u=t.getDocumentClip(this.trackIndex,this.clipIndex);if(!this.previousDocClip||!u)throw new Error(`UpdateTextContentCommand: document clip not found after mutation at ${this.trackIndex}/${this.clipIndex}`);return t.emitEvent(Ae.ClipUpdated,{previous:{clip:ri(this.previousDocClip),trackIndex:this.trackIndex,clipIndex:this.clipIndex},current:{clip:ri(u),trackIndex:this.trackIndex,clipIndex:this.clipIndex}}),Ke()}undo(t){if(!t)throw new Error("UpdateTextContentCommand.undo: context is required");const i=t.getDocument();if(!i)throw new Error("UpdateTextContentCommand.undo: document is required");const r=structuredClone(t.getDocumentClip(this.trackIndex,this.clipIndex)),a=i.getClip(this.trackIndex,this.clipIndex);if(!a)return vt("Clip not found for undo");const n={...a.asset,text:this.previousText};i.updateClip(this.trackIndex,this.clipIndex,{asset:n}),this.clipId?t.resolveClip(this.clipId):t.resolve();const o=t.getDocumentClip(this.trackIndex,this.clipIndex);if(this.previousDocClip){if(!r||!o)throw new Error(`UpdateTextContentCommand: document clip not found after undo at ${this.trackIndex}/${this.clipIndex}`);t.emitEvent(Ae.ClipUpdated,{previous:{clip:ri(r),trackIndex:this.trackIndex,clipIndex:this.clipIndex},current:{clip:ri(o),trackIndex:this.trackIndex,clipIndex:this.clipIndex}})}return Ke()}dispose(){this.clipId=null,this.previousDocClip=void 0}}class jb{events;constructor(){this.events={}}on(t,i){return this.events[t]||(this.events[t]=new Set),this.events[t].add(i),()=>this.off(t,i)}once(t,i){const r=a=>{this.off(t,r),i(a)};return this.on(t,r)}off(t,i){this.events[t]&&(this.events[t].delete(i),!(this.events[t].size>0)&&delete this.events[t])}clear(t){delete this.events[t]}emit(t,...i){if(!this.events[t])return;const r=i[0];for(const a of this.events[t])a(r)}}const Gb=.5,hF=1/30;class gF{constructor(t,i,r){this.getCanvas=t,this.getTracks=i,this.events=r,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 t of this.activeLumaMasks)t.tempContainer.destroy({children:!0}),t.maskSprite.destroy({texture:!0});this.activeLumaMasks=[];for(const t of this.pendingMaskCleanup)try{t.maskSprite.parent?.removeChild(t.maskSprite),t.maskSprite.destroy({texture:!0})}catch{}this.pendingMaskCleanup=[]}cleanupForPlayer(t){const i=this.activeLumaMasks.findIndex(a=>a.lumaPlayer===t);if(i===-1)return;const r=this.activeLumaMasks[i];r.contentClip&&(r.contentClip.getLumaWrapper().mask=null),r.maskSprite.parent?.removeChild(r.maskSprite),r.tempContainer.destroy({children:!0}),this.activeLumaMasks.splice(i,1),this.pendingMaskCleanup.push({maskSprite:r.maskSprite,frameCount:0})}onPlayerLoaded(t){const{player:i,trackIndex:r}=t;if(i.playerType!==ht.Luma)return;const a=i,s=a.getSprite();if(!s?.texture){console.warn("PlayerLoaded fired for luma player before texture ready");return}const n=this.getTracks();if(r>=n.length)return;const u=n[r].filter(c=>c.playerType!==ht.Luma);u.length===0||this.activeLumaMasks.find(c=>c.lumaPlayer===a)||(this.setupLumaMask(a,s.texture,u[0]),a.getContainer().parent?.removeChild(a.getContainer()))}setupLumaMask(t,i,r){const a=this.getCanvas();if(!a)return;const{renderer:s}=a.application,{width:n,height:o}=r.getSize(),u=new se.Container,l=new se.Sprite(i);l.width=n,l.height=o;const c=new se.ColorMatrixFilter;c.negative(!1),l.filters=[c],u.addChild(l);const d=s.generateTexture({target:u,resolution:Gb}),h=new se.Sprite(d);r.getContainer().addChild(h);const g=r.getLumaWrapper();g.mask=h,this.activeLumaMasks.push({lumaPlayer:t,maskSprite:h,tempContainer:u,contentClip:r,lastVideoTime:-1})}updateLumaMasks(){const t=this.getCanvas();if(!t)return;const{renderer:i}=t.application;for(const r of this.activeLumaMasks)if(r.lumaPlayer.isVideoSource()){const a=r.lumaPlayer.getVideoCurrentTime();if(Math.abs(a-r.lastVideoTime)>=hF){r.lastVideoTime=a;const n=r.maskSprite.texture;r.maskSprite.texture=i.generateTexture({target:r.tempContainer,resolution:Gb}),n.destroy(!0)}}}setupEventListeners(){this.events.on(yt.PlayerLoaded,this.onPlayerLoadedBound),this.events.on(Ae.ClipUpdated,this.onClipChangedBound),this.events.on(yt.PlayerMovedBetweenTracks,this.onClipChangedBound)}removeEventListeners(){this.events.off(yt.PlayerLoaded,this.onPlayerLoadedBound),this.events.off(Ae.ClipUpdated,this.onClipChangedBound),this.events.off(yt.PlayerMovedBetweenTracks,this.onClipChangedBound)}processPendingMaskCleanup(){for(let t=this.pendingMaskCleanup.length-1;t>=0;t-=1){const i=this.pendingMaskCleanup[t];if(i.frameCount+=1,i.frameCount>=3){try{i.maskSprite.parent?.removeChild(i.maskSprite),i.maskSprite.destroy({texture:!0})}catch{}this.pendingMaskCleanup.splice(t,1)}}}rebuildLumaMasksIfNeeded(){if(!this.getCanvas())return;const i=this.getTracks();for(let r=0;r<i.length;r+=1){const a=i[r],s=a.find(u=>u.playerType===ht.Luma),n=a.filter(u=>u.playerType!==ht.Luma);s&&s.getContainer().parent?.removeChild(s.getContainer());const o=s&&this.activeLumaMasks.find(u=>u.lumaPlayer===s);if(s&&!o&&n.length>0){const u=s.getSprite();u?.texture&&this.setupLumaMask(s,u.texture,n[0])}}}}function pF(e){return{find:e.name,replace:e.defaultValue}}function mF(e){const t=typeof e.replace=="string"?e.replace:JSON.stringify(e.replace);return{name:e.find,defaultValue:t}}const yF=/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi,Vc=/\{\{\s*[A-Z_0-9]+\s*\}\}/i;class bF{fields=new Map;events;constructor(t){this.events=t}register(t,i){this.fields.set(t.name,t),i?.silent||this.events.emit(Ae.MergeFieldChanged,{fields:this.getAll()})}remove(t,i){const r=this.fields.delete(t);return r&&!i?.silent&&this.events.emit(Ae.MergeFieldChanged,{fields:this.getAll()}),r}get(t){return this.fields.get(t)}getAll(){return Array.from(this.fields.values())}clear(){this.fields.clear()}resolve(t){return!t||this.fields.size===0?t:t.replace(yF,(i,r)=>this.fields.get(r)?.defaultValue??i)}resolveToNumber(t){if(!this.isMergeFieldTemplate(t))return null;const i=this.resolve(t),r=parseFloat(i);return Number.isFinite(r)?r:null}hasUnresolved(t){if(!t)return!1;const i=this.resolve(t);return Vc.test(i)}extractFieldName(t){if(!t)return null;const i=Vc.exec(t);if(!i)return null;const r=i[0].match(/\{\{\s*([A-Z_0-9]+)\s*\}\}/i);return r?r[1]:null}isMergeFieldTemplate(t){return Vc.test(t)}createTemplate(t){return`{{ ${t} }}`}toSerializedArray(){return this.getAll().map(pF)}loadFromSerialized(t){this.fields.clear();for(const i of t){const r=mF(i);this.fields.set(i.find,r)}}generateUniqueName(t){const i=new Set(this.fields.keys());let r=1;for(;i.has(`${t}_${r}`);)r+=1;return`${t}_${r}`}}const vF={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 tu(e,t="16:9"){const i=vF[e];if(!i)throw new Error(`Unknown resolution: ${e}`);switch(t){case"16:9":return{width:i.width,height:i.height};case"9:16":return{width:i.height,height:i.width};case"1:1":return{width:i.height,height:i.height};case"4:5":return{width:Math.round(i.height*4/5),height:i.height};case"4:3":return{width:Math.round(i.height*4/3),height:i.height};default:throw new Error(`Unknown aspectRatio: ${t}`)}}class wF{constructor(t){this.edit=t}setSize(t,i){CE.parse({width:t,height:i});const r={width:t,height:i};this.edit.size=r;const a=this.edit.getResolvedEdit();a&&(a.output={...a.output,size:r},delete a.output.resolution,delete a.output.aspectRatio);const s=this.edit.getDocument();s?.setSize(r),s?.clearResolution(),s?.clearAspectRatio(),this.edit.updateCanvasForSize(),this.edit.getInternalEvents().emit(Ae.OutputResized,r)}getSize(){return this.edit.size}setFps(t){const i=EE.parse(t),r=this.edit.getResolvedEdit();r&&(r.output={...r.output,fps:i}),this.edit.getDocument()?.setFps(i),this.edit.getInternalEvents().emit(Ae.OutputFpsChanged,{fps:t})}getFps(){return this.edit.getResolvedEdit()?.output?.fps??30}setFormat(t){const i=xE.parse(t),r=this.edit.getResolvedEdit();r&&(r.output={...r.output,format:i}),this.edit.getDocument()?.setFormat(i),this.edit.getInternalEvents().emit(Ae.OutputFormatChanged,{format:i})}getFormat(){return this.edit.getResolvedEdit()?.output?.format??"mp4"}setDestinations(t){const i=wE.array().parse(t),r=this.edit.getResolvedEdit();r&&(r.output={...r.output,destinations:i}),this.edit.getInternalEvents().emit(Ae.OutputDestinationsChanged,{destinations:i})}getDestinations(){return this.edit.getResolvedEdit()?.output?.destinations??[]}setResolution(t){const i=AE.parse(t),r=this.edit.getResolvedEdit(),a=r?.output?.aspectRatio??"16:9",s=tu(i,a);this.edit.size=s,r&&(r.output={...r.output,resolution:i},delete r.output.size);const n=this.edit.getDocument();n?.setResolution(i),n?.clearSize(),this.edit.updateCanvasForSize(),this.edit.getInternalEvents().emit(Ae.OutputResolutionChanged,{resolution:i}),this.edit.getInternalEvents().emit(Ae.OutputResized,{width:s.width,height:s.height})}getResolution(){return this.edit.getResolvedEdit()?.output?.resolution}setAspectRatio(t){const i=kE.parse(t),r=this.edit.getResolvedEdit(),a=r?.output?.resolution;if(!a){r&&(r.output={...r.output,aspectRatio:i}),this.edit.getDocument()?.setAspectRatio(i),this.edit.getInternalEvents().emit(Ae.OutputAspectRatioChanged,{aspectRatio:i});return}const s=tu(a,i);this.edit.size=s,r&&(r.output={...r.output,aspectRatio:i},delete r.output.size);const n=this.edit.getDocument();n?.setAspectRatio(i),n?.clearSize(),this.edit.updateCanvasForSize(),this.edit.getInternalEvents().emit(Ae.OutputAspectRatioChanged,{aspectRatio:i}),this.edit.getInternalEvents().emit(Ae.OutputResized,{width:s.width,height:s.height})}getAspectRatio(){return this.edit.getResolvedEdit()?.output?.aspectRatio}}class CF{constructor(t){this.edit=t}selectedClip=null;copiedClip=null;selectClip(t,i){const r=this.edit.getPlayerClip(t,i);if(r){this.selectedClip=r;const a=this.edit.getDocumentClip(t,i);a&&this.edit.getInternalEvents().emit(Ae.ClipSelected,{clip:ri(a),trackIndex:t,clipIndex:i})}}selectPlayer(t){const i=this.findClipIndices(t);i&&this.selectClip(i.trackIndex,i.clipIndex)}clearSelection(){this.selectedClip=null,this.edit.getInternalEvents().emit(Ae.SelectionCleared)}isClipSelected(t,i){if(!this.selectedClip)return!1;const r=this.selectedClip.layer-1,s=this.edit.getTracks()[r];if(!s)return!1;const n=s.indexOf(this.selectedClip);return t===r&&i===n}isPlayerSelected(t){return this.edit.isInExportMode()?!1:this.selectedClip===t}getSelectedClipInfo(){if(!this.selectedClip)return null;const t=this.selectedClip.layer-1,r=this.edit.getTracks()[t];if(!r)return null;const a=r.indexOf(this.selectedClip);return{trackIndex:t,clipIndex:a,player:this.selectedClip}}getSelectedClip(){return this.selectedClip}setSelectedClip(t){this.selectedClip=t}copyClip(t,i){const r=this.edit.getResolvedClip(t,i);r&&(this.copiedClip={trackIndex:t,clipConfiguration:structuredClone(r)},this.edit.getInternalEvents().emit(Ae.ClipCopied,{trackIndex:t,clipIndex:i}))}pasteClip(){if(!this.copiedClip)return;const t=structuredClone(this.copiedClip.clipConfiguration);t.start=this.edit.playbackTime,delete t.id,this.edit.addClip(this.copiedClip.trackIndex,t)}hasCopiedClip(){return this.copiedClip!==null}findClipIndices(t){const i=this.edit.getTracks();for(let r=0;r<i.length;r+=1){const a=i[r].indexOf(t);if(a!==-1)return{trackIndex:r,clipIndex:a}}return null}}const xF=3;function EF(e){return new Promise(t=>{const i=document.createElement("video");i.preload="metadata",i.crossOrigin="anonymous",i.onloadedmetadata=()=>t(i.duration),i.onerror=()=>t(null),i.src=e})}async function Wb(e){const t=e;if(["video","audio","luma"].includes(t.type)&&t.src){const i=await EF(t.src);if(i!==null&&!Number.isNaN(i)){const r=t.trim??0;return i-r}}return xF}function Yb(e,t,i){return t===0?0:i[e][t-1].getEnd()}function Kb(e,t){return Math.max(0,t-e)}function zc(e){let t=0;for(const i of e)for(const r of i)r.getTimingIntent().length!=="end"&&(t=Math.max(t,r.getEnd()));return t}class AF{constructor(t){this.edit=t}cachedTimelineEnd=0;getTimelineEnd(){return this.cachedTimelineEnd}invalidateTimelineEndCache(){this.cachedTimelineEnd=0}async resolveAllTiming(){const t=this.edit.getTracks(),i=this.edit.getResolvedEdit();for(let s=0;s<t.length;s+=1){const n=t[s],o=i.timeline.tracks[s];for(let u=0;u<n.length;u+=1){const l=n[u],c=o?.clips[u];if(c){const d=l.getTimingIntent(),h=c.start;let g=c.length;d.length==="auto"&&(g=await Wb(l.clipConfiguration.asset)),l.setResolvedTiming({start:h,length:g})}}}const r=zc(t);this.cachedTimelineEnd=r;const a=this.getEndLengthClips();for(const s of a){const n=s.getResolvedTiming();s.setResolvedTiming({start:n.start,length:Kb(n.start,r)})}for(const s of a)s.reconfigureAfterRestore()}propagateTimingChanges(t,i){const r=this.edit.getTracks(),a=r[t];if(!a)return;for(let n=Math.max(0,i);n<a.length;n+=1){const o=a[n];if(o.getTimingIntent().start==="auto"){const u=Yb(t,n,r);o.setResolvedTiming({start:u,length:o.getLength()}),o.reconfigureAfterRestore()}}this.propagateAliasChanges();const s=zc(r);if(s!==this.cachedTimelineEnd){this.cachedTimelineEnd=s;const n=this.getEndLengthClips();for(const o of n){const u=Kb(o.getStart(),s),l=o.getLength();Math.abs(u-l)>.001&&(o.setResolvedTiming({start:o.getStart(),length:u}),o.reconfigureAfterRestore())}}this.edit.updateTotalDuration(),this.edit.getInternalEvents().emit(Ae.TimelineUpdated,{current:this.edit.getEdit()})}propagateAliasChanges(){const t=this.edit.getTracks(),i=this.edit.getResolvedEdit();for(let r=0;r<t.length;r+=1){const a=t[r],s=i.timeline.tracks[r];for(let n=0;n<a.length;n+=1){const o=a[n],u=s?.clips[n],l=o.getTimingIntent(),c=gi(l.start),d=gi(l.length);if((c||d)&&u){const h=o.getStart(),g=o.getLength(),m=Math.abs(u.start-h)>.001,v=Math.abs(u.length-g)>.001;(m||v)&&(o.setResolvedTiming({start:u.start,length:u.length}),o.reconfigureAfterRestore())}}}}getEndLengthClips(){const t=this.edit.getTracks(),i=[];for(const r of t)for(const a of r)a.getTimingIntent().length==="end"&&i.push(a);return i}}class kF extends jb{registry;constructor(){super(),this.registry={}}}class iu{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 kF;refCounts=new Map;incrementRef(t){this.refCounts.set(t,(this.refCounts.get(t)??0)+1)}decrementRef(t){const i=this.refCounts.get(t)??0;return i<=1?(this.refCounts.delete(t),!0):(this.refCounts.set(t,i-1),!1)}constructor(){se.Assets.setPreferences({crossOrigin:"anonymous"})}async load(t,i){this.updateAssetLoadMetadata(t,"pending",0),this.incrementRef(t);try{if(await this.shouldUseSafariVideoLoader(i))return await this.loadVideoForSafari(t,i);const a=await se.Assets.load(i,s=>{this.updateAssetLoadMetadata(t,"loading",s)});return this.updateAssetLoadMetadata(t,"success",1),a}catch(r){return console.warn(`[AssetLoader] Failed to load asset "${t}":`,r),this.updateAssetLoadMetadata(t,"failed",1),this.decrementRef(t),null}}async loadVideoUnique(t,i){this.updateAssetLoadMetadata(t,"pending",0);try{const r=this.extractUrl(i);if(!r)throw new Error("No URL provided for video loading");const a=typeof i=="object"?i.data??{}:{},s=await new Promise((n,o)=>{const u=document.createElement("video");u.crossOrigin="anonymous",u.playsInline=!0,u.muted=a.muted??!1,u.preload="auto",u.addEventListener("loadedmetadata",()=>{try{const l=new se.VideoSource({resource:u,autoPlay:a.autoPlay??!1,...a});n(new se.Texture({source:l}))}catch(l){o(l)}},{once:!0}),u.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(t,"loading",.5),u.src=r});return this.updateAssetLoadMetadata(t,"success",1),s}catch{return this.updateAssetLoadMetadata(t,"failed",1),null}}getProgress(){const t=Object.keys(this.loadTracker.registry);return t.length===0?0:t.reduce((r,a)=>r+this.loadTracker.registry[a].progress,0)/t.length}extractUrl(t){if(typeof t=="string")return t;const i=Array.isArray(t.src)?t.src[0]:t.src;return typeof i=="string"?i:i?.src}hasVideoExtension(t){const i=new URL(t,window.location.origin).pathname.toLowerCase();return iu.VIDEO_EXTENSIONS.some(r=>i.endsWith(r))}async getContentType(t){try{return(await fetch(t,{method:"HEAD"})).headers.get("content-type")}catch{return null}}canPlayVideo(t){const i=new URL(t,window.location.origin).pathname.toLowerCase(),r=i.slice(i.lastIndexOf(".")),a=iu.VIDEO_MIME[r];return a?document.createElement("video").canPlayType(a)!=="":!1}async isPlayableVideo(t){if(this.hasVideoExtension(t))return this.canPlayVideo(t);const i=await this.getContentType(t);return i?.startsWith("video/")?document.createElement("video").canPlayType(i)!=="":!1}async shouldUseSafariVideoLoader(t){const i=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),r=this.extractUrl(t);return i&&r!==void 0&&await this.isPlayableVideo(r)}async loadVideoForSafari(t,i){const r=this.extractUrl(i),a=typeof i=="object"?i.data??{}:{},s=await new Promise((n,o)=>{const u=document.createElement("video");u.crossOrigin="anonymous",u.playsInline=!0,u.muted=!0,u.preload="metadata",u.addEventListener("loadedmetadata",()=>{try{const l=new se.VideoSource({resource:u,autoPlay:a.autoPlay??!1,...a});n(new se.Texture({source:l}))}catch(l){o(l)}},{once:!0}),u.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(t,"loading",.5),u.src=r});return this.updateAssetLoadMetadata(t,"success",1),s}updateAssetLoadMetadata(t,i,r){this.loadTracker.registry[t]?(this.loadTracker.registry[t].progress=r,this.loadTracker.registry[t].status=i):this.loadTracker.registry[t]={progress:r,status:i};const a={...this.loadTracker.registry};this.loadTracker.emit("onAssetLoadInfoUpdated",{registry:a})}}class au{static Name="FontLoadParser";id;name;extension;validFontExtensions;woff2Decompressor;constructor(){this.id=au.Name,this.name=au.Name,this.extension={type:[se.ExtensionType.LoadParser],priority:se.LoaderParserPriority.High,ref:null},this.validFontExtensions=["ttf","otf","woff","woff2"],this.woff2Decompressor=null}test(t){const i=t.split("?")[0]?.split(".").pop()?.toLowerCase()??"";return this.validFontExtensions.includes(i)}async load(t,i,r){const a=t.split("?")[0]?.split(".").pop()?.toLowerCase()??"",s=await fetch(t).then(h=>h.arrayBuffer());if(a!=="woff2"){const h=yu.parse(new Uint8Array(s).buffer),g=h.names.fontFamily.en||h.names.fontFamily[Object.keys(h.names.fontFamily)[0]],m=new FontFace(g,`url(${t})`);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(s),o=yu.parse(new Uint8Array(n).buffer),u=o.names.fontFamily.en||o.names.fontFamily[Object.keys(o.names.fontFamily)[0]],l=new Blob([n],{type:"font/ttf"}),c=URL.createObjectURL(l),d=new FontFace(u,`url(${c})`);return await d.load(),document.fonts.add(d),d}async loadWoff2Decompressor(){if(this.woff2Decompressor)return;const i=`${await fetch("https://unpkg.com/wawoff2@2.0.1/build/decompress_binding.js").then(r=>r.text())}; return Module`;this.woff2Decompressor=new Function(i)(),await new Promise(r=>{this.woff2Decompressor.onRuntimeInitialized=r})}unload(t){t&&document.fonts.delete(t)}}function DF(e,t,i,r){const a=Math.max(e,i),s=Math.min(t,r);return Math.max(0,s-a)}class _F{queue=[];isProcessing=!1;async enqueue(t){return new Promise((i,r)=>{this.queue.push(async()=>{try{const a=await t();i(a)}catch(a){r(a)}}),this.processQueue()})}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;){const t=this.queue.shift();if(t)try{await t()}catch{}}this.isProcessing=!1}}}class fr{data;clipBindings=new Map;constructor(t){this.data=structuredClone(t),this.hydrateIds()}hydrateIds(){const t=new Set;for(const i of this.data.timeline.tracks)for(let r=0;r<i.clips.length;r+=1){const a=i.clips[r];if(t.has(a)){const s=structuredClone(a);s.id=crypto.randomUUID(),i.clips[r]=s}else t.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(t){return this.data.timeline.tracks[t]??null}getTrackCount(){return this.data.timeline.tracks.length}getSoundtrack(){return this.data.timeline.soundtrack}getClip(t,i){const r=this.data.timeline.tracks[t];return r?r.clips[i]??null:null}getClipsInTrack(t){return this.data.timeline.tracks[t]?.clips??[]}getClipCount(){return this.data.timeline.tracks.reduce((t,i)=>t+i.clips.length,0)}getClipCountInTrack(t){return this.data.timeline.tracks[t]?.clips.length??0}getClipById(t){for(let i=0;i<this.data.timeline.tracks.length;i+=1){const r=this.data.timeline.tracks[i].clips;for(let a=0;a<r.length;a+=1)if(r[a].id===t)return{clip:r[a],trackIndex:i,clipIndex:a}}return null}updateClipById(t,i){const r=this.getClipById(t);r&&Object.assign(r.clip,i)}removeClipById(t){const i=this.getClipById(t);return i?this.removeClip(i.trackIndex,i.clipIndex):null}getClipId(t,i){return this.getClip(t,i)?.id??null}getOutput(){return this.data.output}getSize(){const{size:t}=this.data.output;if(!t?.width||!t?.height)throw new Error("Output size is not defined");return{width:t.width,height:t.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(t,i){const r=i??{clips:[]};return this.data.timeline.tracks.splice(t,0,r),r}removeTrack(t){if(t<0||t>=this.data.timeline.tracks.length)return null;if(this.data.timeline.tracks.length<=1)return console.warn("Cannot remove the last track"),null;const[i]=this.data.timeline.tracks.splice(t,1);return i??null}addClip(t,i,r){const a=this.data.timeline.tracks[t];if(!a)throw new Error(`Track ${t} does not exist`);const s=i;s.id||(s.id=crypto.randomUUID());const n=r??a.clips.length;return a.clips.splice(n,0,i),i}removeClip(t,i){const r=this.data.timeline.tracks[t];if(!r||i<0||i>=r.clips.length)return null;const[a]=r.clips.splice(i,1);return a??null}updateClip(t,i,r){const a=this.getClip(t,i);if(!a)throw new Error(`Clip at track ${t}, index ${i} does not exist`);Object.assign(a,r)}replaceClipProperties(t,i,r){const a=this.getClip(t,i);if(!a)throw new Error(`Clip at track ${t}, index ${i} does not exist`);const{id:s}=a;for(const n of Object.keys(a))n!=="id"&&delete a[n];Object.assign(a,r),s&&(a.id=s)}replaceClip(t,i,r){const a=this.data.timeline.tracks[t];if(!a||i<0||i>=a.clips.length)return null;const s=a.clips[i];return a.clips[i]=r,s}moveClip(t,i,r,a){const s=this.data.timeline.tracks[t];if(!s||i<0||i>=s.clips.length)return null;const n=this.data.timeline.tracks[r];if(!n)return null;const[o]=s.clips.splice(i,1);if(!o)return null;a&&Object.assign(o,a);const u=typeof o.start=="number"?o.start:0;let l=0;for(let c=0;c<n.clips.length;c+=1){const d=n.clips[c].start;if(u<(typeof d=="number"?d:0))break;l+=1}return n.clips.splice(l,0,o),o}setBackground(t){this.data.timeline.background=t}setSoundtrack(t){this.data.timeline.soundtrack=t}getFonts(){return this.data.timeline.fonts??[]}addFont(t){this.data.timeline.fonts||(this.data.timeline.fonts=[]),this.data.timeline.fonts.some(i=>i.src===t)||this.data.timeline.fonts.push({src:t})}removeFont(t){this.data.timeline.fonts&&(this.data.timeline.fonts=this.data.timeline.fonts.filter(i=>i.src!==t))}setFonts(t){this.data.timeline.fonts=t}setSize(t){this.data.output.size={width:t.width,height:t.height}}setFormat(t){this.data.output.format=t}setFps(t){this.data.output.fps=t}setResolution(t){this.data.output.resolution=t}clearResolution(){delete this.data.output.resolution}setAspectRatio(t){this.data.output.aspectRatio=t}clearAspectRatio(){delete this.data.output.aspectRatio}clearSize(){delete this.data.output.size}setMergeFields(t){this.data.merge=t}setClipBinding(t,i,r){let a=this.clipBindings.get(t);a||(a=new Map,this.clipBindings.set(t,a)),a.set(i,r)}getClipBinding(t,i){return this.clipBindings.get(t)?.get(i)}removeClipBinding(t,i){const r=this.clipBindings.get(t);r&&(r.delete(i),r.size===0&&this.clipBindings.delete(t))}getClipBindings(t){return this.clipBindings.get(t)}setClipBindingsForClip(t,i){i.size===0?this.clipBindings.delete(t):this.clipBindings.set(t,new Map(i))}clearClipBindings(t){this.clipBindings.delete(t)}getClipIdsWithBindings(){return Array.from(this.clipBindings.keys())}toJSON(){const t=structuredClone(this.data);for(const i of t.timeline.tracks)for(const r of i.clips){const a=r.id;if(a){const s=this.clipBindings.get(a);if(s)for(const[n,{placeholder:o}]of s)Wi(r,n,o)}delete r.id}return t.merge?.length===0&&delete t.merge,t}static fromJSON(t){return new fr(t)}clone(){return new fr(this.data)}}const Xb=new Set(["asset","start","length","id"]),SF=new Set(["text-to-image","image-to-video","text-to-speech"]);class NF{constructor(t){this.edit=t,this.edit.getInternalEvents().on(yt.Resolved,this.onResolved)}isReconciling=!1;enableCreation=!0;onResolved=({edit:t})=>{this.reconcile(t)};async reconcileInitial(t){const i=this.reconcile(t);return await Promise.all(i.pendingLoads),i}reconcile(t){if(this.isReconciling)return{created:[],updated:[],disposed:[],pendingLoads:[]};this.isReconciling=!0;try{const i=[],r={created:[],updated:[],disposed:[],pendingLoads:i},a=new Set;for(let n=0;n<t.timeline.tracks.length;n+=1){const o=t.timeline.tracks[n];for(let u=0;u<o.clips.length;u+=1){const l=o.clips[u],c=l.id;if(c){a.add(c);const d=this.edit.getPlayerByClipId(c);if(d){const h=this.updatePlayer(d,l,n);h==="recreate"?(this.disposePlayer(c),i.push(this.createPlayer(l,c,n,u)),r.disposed.push(c),r.created.push(c)):h&&r.updated.push(c)}else this.enableCreation&&(this.createPlayer(l,c,n,u),r.created.push(c))}}}const s=this.findOrphanedPlayers(a);for(const n of s)this.disposePlayer(n),r.disposed.push(n);return(r.created.length>0||r.disposed.length>0||r.updated.length>0)&&this.rebuildTracksOrdering(t),this.syncTrackContainers(t.timeline.tracks.length),r}finally{this.isReconciling=!1}}updateSinglePlayer(t,i,r,a=0){const s=this.updatePlayer(t,i,r);if(s==="recreate"){const{clipId:n}=t;return n&&(this.disposePlayer(n),this.createPlayer(i,n,r,a)),"recreate"}return s}createPlayer(t,i,r,a){const s=this.edit.createPlayerFromAssetType(t);s.layer=r+1,s.clipId=i,this.edit.registerPlayerByClipId(i,s),this.edit.addPlayerToTracksArray(r,s),this.edit.addPlayerToContainer(r,s);const n=t.asset?.type??"unknown";return s.load().then(()=>{this.edit.getInternalEvents().emit(yt.PlayerLoaded,{player:s,trackIndex:r,clipIndex:a}),SF.has(n)&&this.edit.getInternalEvents().emit(Ae.ClipUnresolved,{trackIndex:r,clipIndex:a,assetType:n,clipId:i})}).catch(u=>{const l=u instanceof Error?u.message:String(u);this.edit.getInternalEvents().emit(Ae.ClipLoadFailed,{trackIndex:r,clipIndex:a,error:l,assetType:n})})}updatePlayer(t,i,r){const a=t.clipConfiguration.asset?.type,s=i.asset?.type;if(a!==s)return"recreate";let n=!1;const o=t.layer-1,u=t.clipConfiguration.start,l=t.clipConfiguration.length;return(u!==i.start||l!==i.length)&&(t.setResolvedTiming({start:i.start,length:i.length}),t.reconfigureAfterRestore(),n=!0),o!==r&&(t.layer=r+1,this.edit.movePlayerBetweenTracks(t,o,r),n=!0),this.assetChanged(t.clipConfiguration.asset,i.asset)&&(this.updateAsset(t,i.asset),n=!0),this.clipPropertiesChanged(t.clipConfiguration,i)&&(this.updateClipProperties(t,i),n=!0),n}clipPropertiesChanged(t,i){const r=t,a=i,s=new Set([...Object.keys(r),...Object.keys(a)]);for(const n of s)if(!Xb.has(n)&&JSON.stringify(r[n])!==JSON.stringify(a[n]))return!0;return!1}updateClipProperties(t,i){const r=t.clipConfiguration,a=i,s=new Set([...Object.keys(r),...Object.keys(a)]);for(const n of s)Xb.has(n)||(a[n]!==void 0?r[n]=a[n]:delete r[n]);t.reconfigureAfterRestore()}assetChanged(t,i){return JSON.stringify(t)!==JSON.stringify(i)}updateAsset(t,i){const r=t.clipConfiguration.asset?.src,a=i?.src;t.clipConfiguration.asset=i,r!==a&&t.reloadAsset?t.reloadAsset().then(()=>{t.reconfigureAfterRestore()}).catch(s=>{console.error("Failed to reload asset:",s)}):t.reconfigureAfterRestore()}syncTrackContainers(t){const i=this.edit.getTracks().length;if(t>i)for(let r=i;r<t;r+=1)this.edit.ensureTrackExists(r);else if(t<i)for(let r=i-1;r>=t;r-=1)this.edit.removeEmptyTrack(r)}findOrphanedPlayers(t){const i=[];for(const[r]of this.edit.getPlayerMap())t.has(r)||i.push(r);return i}disposePlayer(t){const i=this.edit.getPlayerByClipId(t);i&&(this.edit.unregisterPlayerByClipId(t),this.edit.queuePlayerForDisposal(i))}rebuildTracksOrdering(t){const i=this.edit.getTracks();for(let r=0;r<i.length;r+=1)i[r]=[];for(let r=0;r<t.timeline.tracks.length;r+=1){for(;i.length<=r;)i.push([]);for(const a of t.timeline.tracks[r].clips){const s=a.id;if(s){const n=this.edit.getPlayerByClipId(s);n&&i[r].push(n)}}}}dispose(){this.edit.getInternalEvents().off(yt.Resolved,this.onResolved)}}const BF=new Set(["text","src"]);function Hb(e,t){function i(r,a){if(typeof r=="string"&&t.isMergeFieldTemplate(r)){if(a&&BF.has(a))return t.resolve(r);const s=t.resolveToNumber(r);return s!==null?s:t.resolve(r)}if(Array.isArray(r))return r.map(s=>i(s,a));if(r!==null&&typeof r=="object"){const s={};for(const[n,o]of Object.entries(r))s[n]=i(o,n);return s}return r}return i(structuredClone(e))}function IF(e){const t=new Map,i=new Map,r=[];for(let a=0;a<e.getTrackCount();a+=1){const s=e.getClipsInTrack(a);for(let n=0;n<s.length;n+=1){const o=s[n];if(!o.id)throw new Error(`Clip at track ${a}, index ${n} is missing an ID. EditDocument hydration may have been skipped.`);const u=o.alias??o.id,l={clip:o,trackIndex:a,clipIndex:n};if(r.push({...l,id:u}),o.alias){if(i.has(o.alias))throw new Error(`Duplicate alias "${o.alias}" found. Each alias must be unique.`);i.set(o.alias,l)}}}for(let a=0;a<e.getTrackCount();a+=1){const s=e.getClipsInTrack(a);for(let n=0;n<s.length;n+=1){const o=s[n],u=o.alias??o.id,l=new Set;if(gi(o.start)){const c=Ps(o.start);if(!i.has(c))throw new Error(`Alias reference "alias://${c}" not found. No clip defines alias "${c}".`);l.add(c)}if(gi(o.length)){const c=Ps(o.length);if(!i.has(c))throw new Error(`Alias reference "alias://${c}" not found. No clip defines alias "${c}".`);l.add(c)}if(o.start==="auto"&&n>0){const c=s[n-1],d=c.alias??c.id;l.add(d)}l.size>0&&t.set(u,l)}}return{dependencies:t,clipsByAlias:i,allClips:r}}function FF(e){const t=new Set,i=new Set;function r(a,s){t.add(a),i.add(a);const n=e.get(a);if(n)for(const o of n){if(i.has(o))return[...s,o];if(!t.has(o)){const u=r(o,[...s,o]);if(u)return u}}return i.delete(a),null}for(const a of e.keys())if(!t.has(a)){const s=r(a,[a]);if(s)return s}return null}function VF(e,t){const i=[],r=new Set;function a(s){if(r.has(s))return;r.add(s);const n=e.get(s);if(n)for(const o of n)a(o);i.push(s)}for(const s of e.keys())a(s);for(const s of t)a(s);return i}function Jb(e,t,i){let r;if(e.start==="auto")r=t;else if(gi(e.start)){const n=Ps(e.start),o=i.get(n);if(!o)throw new Error(`Internal error: Alias "${n}" not resolved.`);r=o.start}else r=e.start;let a,s=!1;if(e.length==="end")a=1,s=!0;else if(e.length==="auto")a=3;else if(gi(e.length)){const n=Ps(e.length),o=i.get(n);if(!o)throw new Error(`Internal error: Alias "${n}" not resolved.`);a=o.length}else a=e.length;return{...e,id:e.id??crypto.randomUUID(),start:r,length:a,pendingEndLength:s||void 0}}function zF(e){let t=0;for(const i of e)for(const r of i.clips)if(!r.pendingEndLength){const a=r.start+r.length;a>t&&(t=a)}return t}function Pc(e){const{pendingEndLength:t,...i}=e;return i}function PF(e,t,i){const r=e.getClipById(t);if(!r)return null;const{clip:a,trackIndex:s,clipIndex:n}=r,u=Hb(a,i.mergeFields),l=i.resolvedAliases??new Map,c=Jb(u,i.previousClipEnd,l);return c.pendingEndLength&&i.cachedTimelineEnd!==void 0&&(c.length=Math.max(i.cachedTimelineEnd-c.start,.1)),{resolved:Pc(c),trackIndex:s,clipIndex:n}}function qb(e,t){const{dependencies:i,allClips:r}=IF(e);if(i.size>0){const g=FF(i);if(g)throw new Error(`Circular alias reference detected: ${g.join(" -> ")}`)}const a=r.map(g=>g.id),s=VF(i,a),n=new Map;for(const g of r)n.set(g.id,g);const o=new Map,u=new Map,l=new Map;for(const g of s){const m=n.get(g);if(m){const{clip:v,trackIndex:_,clipIndex:C}=m,k=Hb(v,t.mergeFields),w=l.get(_)??0,x=Jb(k,w,u);o.set(`${_}-${C}`,x);const D=x.start+x.length,b=l.get(_)??0;D>b&&l.set(_,D),v.alias&&u.set(v.alias,{start:x.start,length:x.length})}}const c=[];for(let g=0;g<e.getTrackCount();g+=1){const m=e.getClipsInTrack(g).length,v=[];for(let _=0;_<m;_+=1){const C=o.get(`${g}-${_}`);if(!C)throw new Error(`Internal error: Clip at track ${g}, index ${_} was not resolved.`);v.push(C)}c.push({clips:v})}const d=zF(c),h=c.map(g=>({clips:g.clips.map(m=>{if(m.pendingEndLength){const v=Math.max(d-m.start,.1);return Pc({...m,length:v})}return Pc(m)})}));return{timeline:{background:e.getBackground(),tracks:h,fonts:e.getFonts()},output:e.getOutput()}}class dr{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 _F;clipsToDispose=new Set;clipErrors=new Map;playerByClipId=new Map;lumaContentRelations=new Map;fontMetadata=new Map;isBatchingEvents=!1;isExporting=!1;lastResolved=null;constructor(t){Sr.parse(t),this.tracks=[],this.playbackTime=0,this.totalDuration=0,this.isPlaying=!1,this.document=new fr(t);const i=this.document.getResolution(),r=this.document.getAspectRatio();this.backgroundColor=this.document.getBackground()??"#000000",this.size=i?tu(i,r):this.document.getSize(),this.assetLoader=new iu,this.internalEvents=new jb,this.events=this.internalEvents,this.lumaMaskController=new gF(()=>this.canvas,()=>this.tracks,this.internalEvents),this.playerReconciler=new NF(this),this.mergeFieldService=new bF(this.internalEvents),this.outputSettings=new wF(this),this.selectionManager=new CF(this),this.timingManager=new AF(this),this.setupIntentListeners()}async load(){await this.initializeFromDocument()}async initializeFromDocument(t="load"){const i=this.document.toJSON(),r=i.merge??[];this.mergeFieldService.loadFromSerialized(r),this.lastResolved=null;const a=this.detectMergeFieldBindings(r),s=Sr.parse(i);await Promise.all((s.timeline.fonts??[]).map(async o=>{const u=o.src,l={src:u,parser:au.Name},c=await this.assetLoader.load(u,l);if(c?.family){const d=c.family.replace(/^["']|["']$/g,""),{baseFontFamily:h,fontWeight:g}=pi(d);this.fontMetadata.set(u,{baseFamilyName:h,weight:g})}return c}));const n=this.getResolvedEdit();this.lumaMaskController.initialize(),await this.playerReconciler.reconcileInitial(n),this.normalizeLumaAttachments();for(const[o,u]of a)u.size>0&&this.document.setClipBindingsForClip(o,u);await this.timingManager.resolveAllTiming(),this.updateTotalDuration(),s.timeline.soundtrack&&await this.loadSoundtrack(s.timeline.soundtrack),this.internalEvents.emit(Ae.TimelineUpdated,{current:this.getEdit()}),this.emitEditChanged(t)}getInternalEvents(){return this.internalEvents}update(t,i){for(const r of this.clips)r.shouldDispose&&this.queueDisposeClip(r),r.update(t,i);this.disposeClips(),this.lumaMaskController.update(),this.isPlaying&&(this.playbackTime=Math.max(0,Math.min(this.playbackTime+Nv(i),this.totalDuration)),this.playbackTime===this.totalDuration&&this.pause())}dispose(){this.clearClips(),this.lumaMaskController.dispose(),this.playerReconciler.dispose();for(const t of this.commandHistory)t.dispose?.();this.commandHistory=[],this.commandIndex=-1,this.lumaContentRelations.clear(),Ub.cleanup()}updateCanvasForSize(){this.internalEvents.emit(yt.ViewportSizeChanged,{width:this.size.width,height:this.size.height,backgroundColor:this.backgroundColor}),this.internalEvents.emit(yt.ViewportNeedsZoomToFit)}play(){this.isPlaying=!0,this.internalEvents.emit(Ae.PlaybackPlay)}pause(){this.isPlaying=!1,this.internalEvents.emit(Ae.PlaybackPause)}seek(t){this.playbackTime=Math.max(0,Math.min(t,this.totalDuration)),this.pause(),this.update(0,dr.SEEK_ELAPSED_MARKER)}stop(){this.seek(0)}async loadEdit(t){if(Sr.parse(t),this.tracks.length>0&&!this.hasStructuralChanges(t)){this.lastResolved=null;const n=structuredClone(t);this.preserveClipIdsForGranularUpdate(n);const o=this.document.getTracks(),u=this.document.getOutput();this.document=new fr(n),this.isBatchingEvents=!0,await this.applyGranularChanges(n,o,u),this.isBatchingEvents=!1,this.emitEditChanged("loadEdit:granular");return}const i=this.document,r=this.lastResolved,a=this.size,s=this.backgroundColor;try{this.lastResolved=null,this.document=new fr(t);const n=this.document.getResolution(),o=this.document.getAspectRatio();this.size=n?tu(n,o):this.document.getSize(),this.backgroundColor=this.document.getBackground()??"#000000",this.internalEvents.emit(yt.ViewportSizeChanged,{width:this.size.width,height:this.size.height,backgroundColor:this.backgroundColor}),this.internalEvents.emit(yt.ViewportNeedsZoomToFit),this.clearClips(),await this.initializeFromDocument("loadEdit")}catch(n){throw this.document=i,this.lastResolved=r,this.size=a,this.backgroundColor=s,n}}async loadSoundtrack(t){const i={id:crypto.randomUUID(),asset:{type:"audio",src:t.src,effect:t.effect,volume:t.volume??1},fit:"crop",start:0,length:this.totalDuration},r=this.createPlayerFromAssetType(i);r.layer=this.tracks.length+1,await this.addPlayer(this.tracks.length,r)}getEdit(){const t=this.document.toJSON(),i=this.mergeFieldService.toSerializedArray();return i.length>0&&(t.merge=i),t}validateEdit(t){const i=Sr.safeParse(t);return i.success?{valid:!0,errors:[]}:{valid:!1,errors:i.error.issues.map(r=>({path:r.path.join("."),message:r.message}))}}getResolvedEdit(){return this.lastResolved||(this.lastResolved=qb(this.document,{mergeFields:this.mergeFieldService})),this.lastResolved}getResolvedClip(t,i){return this.getResolvedEdit()?.timeline?.tracks?.[t]?.clips?.[i]??null}getResolvedClipById(t){const i=this.getResolvedEdit();for(const r of i.timeline.tracks)for(const a of r.clips)if(a.id===t)return a;return null}getClipId(t,i){return this.document?.getClipId(t,i)??null}getDocumentClip(t,i){return this.document?.getClip(t,i)??null}getDocument(){return this.document}resolve(){return this.lastResolved=qb(this.document,{mergeFields:this.mergeFieldService}),this.internalEvents.emit(yt.Resolved,{edit:this.lastResolved}),this.lastResolved}resolveClip(t){const i=this.getPlayerByClipId(t);if(!i)return!1;const r=this.document.getClipById(t);if(r?.clip.alias)return this.resolve(),!0;const a=r?.clip;if(a&&(gi(a.start)||gi(a.length)))return this.resolve(),!0;const s=i.layer-1,n=this.tracks[s],o=n?n.indexOf(i):-1;if(o<0)return!1;const u=o>0?n[o-1]:null,l=u?u.getEnd():0,c={mergeFields:this.mergeFieldService,previousClipEnd:l,cachedTimelineEnd:this.timingManager.getTimelineEnd()},d=PF(this.document,t,c);if(!d)return!1;if(this.lastResolved){const g=this.lastResolved.timeline.tracks[d.trackIndex];g&&g.clips[d.clipIndex]&&(g.clips[d.clipIndex]=d.resolved)}return this.playerReconciler.updateSinglePlayer(i,d.resolved,d.trackIndex,d.clipIndex)!==!1}addClip(t,i){rn.parse(i);const r=new iF(t,i);return this.executeCommand(r)}getClip(t,i){const r=this.tracks[t];return!r||i<0||i>=r.length?null:r[i].clipConfiguration}getClipError(t,i){return this.clipErrors.get(`${t}-${i}`)??null}clearClipErrorAndShift(t,i){this.clipErrors.delete(`${t}-${i}`);const r=[];for(const[a,s]of this.clipErrors){const[n,o]=a.split("-").map(Number);n===t&&o>i&&r.push({oldKey:a,newKey:`${n}-${o-1}`,value:s})}for(const{oldKey:a,newKey:s,value:n}of r)this.clipErrors.delete(a),this.clipErrors.set(s,n)}getPlayerClip(t,i){const r=this.tracks[t];return!r||i<0||i>=r.length?null:r[i]}getPlayerByClipId(t){return this.playerByClipId.get(t)??null}getDocumentClipById(t){return this.document?.getClipById(t)?.clip??null}registerPlayerByClipId(t,i){this.playerByClipId.set(t,i)}unregisterPlayerByClipId(t){this.playerByClipId.delete(t)}getPlayerMap(){return this.playerByClipId}addPlayerToTracksArray(t,i){for(;this.tracks.length<=t;)this.tracks.push([]);this.tracks[t].push(i)}movePlayerBetweenTracks(t,i,r){const a=this.tracks[i];if(a){const s=a.indexOf(t);s!==-1&&a.splice(s,1)}for(;this.tracks.length<=r;)this.tracks.push([]);this.tracks[r].push(t),this.movePlayerToTrackContainer(t,i,r)}queuePlayerForDisposal(t){this.queueDisposeClip(t),this.disposeClips()}ensureTrackExists(t){for(;this.tracks.length<=t;)this.tracks.push([])}removeEmptyTrack(t){if(t<0||t>=this.tracks.length)return;const i=this.tracks[t];if(i&&i.length>0){console.warn(`Cannot remove non-empty track ${t}`);return}this.tracks.splice(t,1),this.internalEvents.emit(yt.TrackContainerRemoved,{trackIndex:t});for(let r=t;r<this.tracks.length;r+=1)for(const a of this.tracks[r])a.layer=r+1}getOriginalAsset(t,i){const r=this.getPlayerClip(t,i);if(!r)return;const a=r.getExportableClip();if(!a)return;const{clipId:s}=r;if(s&&this.document){const n=this.document.getClipBindings(s);if(n){for(const[o,{placeholder:u}]of n)if(o.startsWith("asset.")){const l=o.slice(6);Wi(a.asset,l,u)}}}return a.asset}async deleteClip(t,i){const r=this.tracks[t];if(!r)return;const a=r[i];if(!a)return;if(a.playerType!==ht.Luma){const o=r.findIndex(u=>u.playerType===ht.Luma);if(o!==-1){const u=o<i?i-1:i,l=new Bc(t,o);await this.executeCommand(l);const c=new Bc(t,u);await this.executeCommand(c);return}}const n=new Bc(t,i);await this.executeCommand(n)}async addTrack(t,i){md.parse(i);const r=new aF(t);await this.executeCommand(r);for(const a of i.clips)await this.addClip(t,a)}getTrack(t){const i=this.clips.filter(r=>r.layer===t+1);return i.length===0?null:{clips:i.map(r=>r.clipConfiguration)}}deleteTrack(t){const i=new Lb(t);this.executeCommand(i)}undo(){return this.commandQueue.enqueue(async()=>{if(this.commandIndex>=0){const t=this.commandHistory[this.commandIndex];if(t.undo){const i=this.createCommandContext();await Promise.resolve(t.undo(i)),this.commandIndex-=1,this.internalEvents.emit(Ae.EditUndo,{command:t.name}),this.emitEditChanged(`undo:${t.name}`)}}})}redo(){return this.commandQueue.enqueue(async()=>{if(this.commandIndex<this.commandHistory.length-1){const t=this.commandIndex+1,i=this.commandHistory[t],r=this.createCommandContext();await Promise.resolve(i.execute(r)),this.commandIndex=t,this.internalEvents.emit(Ae.EditRedo,{command:i.name}),this.emitEditChanged(`redo:${i.name}`)}})}setUpdatedClip(t,i=null,r=null){const a=t.layer-1,s=this.tracks[a],n=s?s.indexOf(t):-1,o=new Fc(i,r,{trackIndex:a,clipIndex:n});this.executeCommand(o)}updateClipInDocument(t,i){const r=this.document.getClipById(t);r&&this.document.updateClip(r.trackIndex,r.clipIndex,i)}commitClipUpdate(t,i,r){const a=this.document.getClipById(t);if(!a){console.warn(`commitClipUpdate: clip ${t} not found in document`);return}Zu.parse(r);const s=new Fc(i,structuredClone(r),{trackIndex:a.trackIndex,clipIndex:a.clipIndex});this.addCommandToHistory(s)}pushCommandToHistory(t){const i=this.commandHistory.slice(this.commandIndex+1);for(const r of i)r.dispose?.();for(this.commandHistory=this.commandHistory.slice(0,this.commandIndex+1),this.commandHistory.push(t),this.commandIndex+=1;this.commandHistory.length>dr.MAX_HISTORY_SIZE;)this.commandHistory.shift()?.dispose?.(),this.commandIndex-=1}addCommandToHistory(t){this.pushCommandToHistory(t),this.emitEditChanged(`commit:${t.name}`)}updateClip(t,i,r){const a=this.getPlayerClip(t,i);if(!a)return console.warn(`Clip not found at track ${t}, index ${i}`),Promise.resolve();const s=this.document?.getClip(t,i),n=structuredClone(s??a.clipConfiguration),o=structuredClone(s??a.clipConfiguration),u=Ic(o,r);Zu.parse(u);const l=new Fc(n,u,{trackIndex:t,clipIndex:i});return this.executeCommand(l)}updateClipTiming(t,i,r){if(!this.getPlayerClip(t,i)){console.warn(`Clip not found at track ${t}, index ${i}`);return}const s=new fF(t,i,r);this.executeCommand(s)}updateTextContent(t,i,r){const a=t.layer-1,s=this.tracks[a]?.indexOf(t)??-1;if(s<0){console.warn("UpdateTextContent: clip not found in track");return}const n=new dF(a,s,i);this.executeCommand(n)}executeEditCommand(t){return this.executeCommand(t)}executeCommand(t){return this.commandQueue.enqueue(async()=>{const i=this.createCommandContext(),r=await Promise.resolve(t.execute(i));this.handleCommandResult(t,r)})}handleCommandResult(t,i){i.status==="success"&&(this.pushCommandToHistory(t),this.emitEditChanged(t.name))}emitEditChanged(t){this.isBatchingEvents||this.internalEvents.emit(Ae.EditChanged,{source:t,timestamp:Date.now()})}detectMergeFieldBindings(t){const i=new Map;if(!t.length)return i;const r=new Map;for(const{find:a,replace:s}of t){const n=typeof s=="string"?s:JSON.stringify(s);r.set(a.toUpperCase(),n)}for(let a=0;a<this.document.getTrackCount();a+=1){const s=this.document.getClipsInTrack(a);for(let n=0;n<s.length;n+=1){const o=this.document.getClipId(a,n);if(o){const u=this.detectBindingsInObject(s[n],"",r);u.size>0&&i.set(o,u)}}}return i}detectBindingsInObject(t,i,r){const a=new Map;if(typeof t=="string"){if(/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi.test(t)){const o=t.replace(/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi,(u,l)=>r.get(l.toUpperCase())??u);a.set(i,{placeholder:t,resolvedValue:o})}return a}if(Array.isArray(t)){for(let s=0;s<t.length;s+=1){const n=i?`${i}[${s}]`:`[${s}]`,o=this.detectBindingsInObject(t[s],n,r);for(const[u,l]of o)a.set(u,l)}return a}if(t!==null&&typeof t=="object")for(const[s,n]of Object.entries(t)){const o=i?`${i}.${s}`:s,u=this.detectBindingsInObject(n,o,r);for(const[l,c]of u)a.set(l,c)}return a}hasStructuralChanges(t){if(!this.document)return!0;const i=this.document.getTracks(),r=t.timeline.tracks;if(i.length!==r.length)return!0;for(let a=0;a<i.length;a+=1){if(i[a].clips.length!==r[a].clips.length)return!0;for(let s=0;s<i[a].clips.length;s+=1){const n=i[a].clips[s]?.asset?.type,o=r[a].clips[s]?.asset?.type;if(n!==o)return!0}}return JSON.stringify(this.document.getMergeFields()??[])!==JSON.stringify(t.merge??[])||JSON.stringify(this.document.getFonts())!==JSON.stringify(t.timeline.fonts??[])||JSON.stringify(this.document.getSoundtrack())!==JSON.stringify(t.timeline.soundtrack)}preserveClipIdsForGranularUpdate(t){if(!this.document)return;const i=this.document.getTracks();for(let r=0;r<t.timeline.tracks.length;r+=1){const a=i[r],s=t.timeline.tracks[r];if(a&&s)for(let n=0;n<s.clips.length;n+=1){const o=this.document.getClipId(r,n);o&&(s.clips[n].id=o)}}}async applyGranularChanges(t,i,r){const a=t.output;if(a?.size&&(r?.size?.width!==a.size.width||r?.size?.height!==a.size.height)){const o=a.size.width??this.size.width,u=a.size.height??this.size.height;await this.setOutputSize(o,u)}a?.fps!==void 0&&r?.fps!==a.fps&&await this.setOutputFps(a.fps),a?.format!==void 0&&r?.format!==a.format&&await this.setOutputFormat(a.format),a?.destinations&&JSON.stringify(r?.destinations)!==JSON.stringify(a.destinations)&&await this.setOutputDestinations(a.destinations),a?.resolution!==void 0&&r?.resolution!==a.resolution&&await this.setOutputResolution(a.resolution),a?.aspectRatio!==void 0&&r?.aspectRatio!==a.aspectRatio&&await this.setOutputAspectRatio(a.aspectRatio);const s=t.timeline?.background;s&&this.backgroundColor!==s&&await this.setTimelineBackground(s);const n=t.timeline.tracks;for(let o=0;o<n.length;o+=1){const u=i[o].clips,l=n[o].clips;for(let c=0;c<l.length;c+=1){const d=u[c],h=l[c];JSON.stringify(d)!==JSON.stringify(h)&&await this.updateClip(o,c,h)}}}createCommandContext(){return{getClips:()=>this.clips,getTracks:()=>this.tracks,getTrack:t=>t>=0&&t<this.tracks.length?this.tracks[t]:null,getContainer:()=>this.getViewportContainer(),addPlayer:(t,i)=>this.addPlayer(t,i),addPlayerToContainer:(t,i)=>{this.addPlayerToContainer(t,i)},createPlayerFromAssetType:t=>this.createPlayerFromAssetType(t),queueDisposeClip:t=>this.queueDisposeClip(t),disposeClips:()=>this.disposeClips(),clearClipError:(t,i)=>this.clearClipErrorAndShift(t,i),undeleteClip:(t,i)=>{let r=0;if(t>=0&&t<this.tracks.length){const a=this.tracks[t];r=a.length;for(let s=0;s<a.length;s+=1)if(a[s].getStart()>i.getStart()){r=s;break}a.splice(r,0,i)}if(this.document){const a=i.getExportableClip();this.document.addClip(t,a,r);const s=this.document.getClipId(t,r);s&&(i.clipId=s,this.playerByClipId.set(s,i))}this.addPlayerToContainer(t,i),i.load().catch(a=>{const s=i.clipConfiguration?.asset?.type??"unknown",n=a instanceof Error?a.message:String(a);this.clipErrors.set(`${t}-${r}`,{error:n,assetType:s}),this.internalEvents.emit(Ae.ClipLoadFailed,{trackIndex:t,clipIndex:r,error:n,assetType:s})}),this.updateTotalDuration()},setUpdatedClip:()=>{},restoreClipConfiguration:(t,i)=>{const r=structuredClone(i),a=t.clipConfiguration;for(const s of Object.keys(a))delete a[s];if(Object.assign(a,r),t.reconfigureAfterRestore(),this.document){const s=this.findClipIndices(t);if(s){const n=t.getExportableClip();this.document.replaceClip(s.trackIndex,s.clipIndex,n)}}},updateDuration:()=>this.updateTotalDuration(),emitEvent:(t,...i)=>this.internalEvents.emit(t,...i),findClipIndices:t=>this.selectionManager.findClipIndices(t),getClipAt:(t,i)=>this.getClipAt(t,i),getSelectedClip:()=>this.selectionManager.getSelectedClip(),setSelectedClip:t=>{this.selectionManager.setSelectedClip(t)},movePlayerToTrackContainer:(t,i,r)=>this.movePlayerToTrackContainer(t,i,r),getEditState:()=>this.getResolvedEdit(),propagateTimingChanges:(t,i)=>this.propagateTimingChanges(t,i),resolveClipAutoLength:t=>this.resolveClipAutoLength(t),getMergeFields:()=>this.mergeFieldService,getOutputSize:()=>this.outputSettings.getSize(),setOutputSize:(t,i)=>this.outputSettings.setSize(t,i),getOutputFps:()=>this.outputSettings.getFps(),setOutputFps:t=>this.outputSettings.setFps(t),getOutputFormat:()=>this.outputSettings.getFormat(),setOutputFormat:t=>this.outputSettings.setFormat(t),getOutputResolution:()=>this.outputSettings.getResolution(),setOutputResolution:t=>this.outputSettings.setResolution(t),getOutputAspectRatio:()=>this.outputSettings.getAspectRatio(),setOutputAspectRatio:t=>this.outputSettings.setAspectRatio(t),getOutputDestinations:()=>this.outputSettings.getDestinations(),setOutputDestinations:t=>this.outputSettings.setDestinations(t),getTimelineBackground:()=>this.getTimelineBackground(),setTimelineBackground:t=>this.setTimelineBackgroundInternal(t),getDocument:()=>this.document,getDocumentTrack:t=>this.document?.getTrack(t)??null,getDocumentClip:(t,i)=>this.document?.getClip(t,i)??null,documentUpdateClip:(t,i,r)=>{if(!this.document)throw new Error("Document not initialized - cannot update clip");this.document.updateClip(t,i,r)},documentAddClip:(t,i,r)=>{if(!this.document)throw new Error("Document not initialized - cannot add clip");for(;this.document.getTrackCount()<=t;)this.document.addTrack(this.document.getTrackCount());return this.document.addClip(t,i,r)},documentRemoveClip:(t,i)=>{if(!this.document)throw new Error("Document not initialized - cannot remove clip");return this.document.removeClip(t,i)},derivePlayerFromDocument:(t,i)=>{const r=this.document?.getClip(t,i);if(!r)throw new Error(`derivePlayerFromDocument: No document clip at ${t}/${i} - state desync`);const a=this.getClipAt(t,i);if(!a)throw new Error(`derivePlayerFromDocument: No player at ${t}/${i} - state desync`);const{asset:s,...n}=r;Object.assign(a.clipConfiguration,n),a.reconfigureAfterRestore()},buildResolutionContext:(t,i)=>{let r=0;if(i>0){const o=this.tracks[t];o&&o[i-1]&&(r=o[i-1].getEnd())}const a=zc(this.tracks);let s=null;const n=this.getClipAt(t,i);return n&&n.getTimingIntent().length==="auto"&&(s=n.getLength()),{previousClipEnd:r,timelineEnd:a,intrinsicDuration:s}},resolve:()=>this.resolve(),resolveClip:t=>this.resolveClip(t),getPlayerByClipId:t=>this.playerByClipId.get(t)??null,registerPlayerByClipId:(t,i)=>{this.playerByClipId.set(t,i)},unregisterPlayerByClipId:t=>{this.playerByClipId.delete(t)},setClipBinding:(t,i,r)=>{this.document?.setClipBinding(t,i,r)},getClipBinding:(t,i)=>this.document?.getClipBinding(t,i),removeClipBinding:(t,i)=>{this.document?.removeClipBinding(t,i)},getClipBindings:t=>this.document?.getClipBindings(t),getEditSession:()=>this}}queueDisposeClip(t){this.clipsToDispose.add(t)}disposeClips(){if(this.clipsToDispose.size!==0){for(const t of this.clipsToDispose)t.playerType===ht.Luma&&(this.lumaMaskController.cleanupForPlayer(t),t.clipId&&this.lumaContentRelations.delete(t.clipId));for(const t of this.clipsToDispose)t.clipId&&this.playerByClipId.delete(t.clipId);for(const t of this.clipsToDispose)this.disposeClip(t);for(const t of this.clipsToDispose){const i=t.layer-1;if(i>=0&&i<this.tracks.length){const r=this.tracks[i].indexOf(t);r!==-1&&this.tracks[i].splice(r,1)}}this.clipsToDispose.clear(),this.updateTotalDuration(),this.cleanupUnusedFonts()}}cleanupUnusedFonts(){if(!this.document)return;const t=this.document.getFonts();if(t.length===0)return;const i=new Set;for(const r of this.clips){const{asset:a}=r.clipConfiguration;a&&a.type==="rich-text"&&a.font?.family&&i.add(a.font.family)}for(const r of t)if(r.src.includes("fonts.gstatic.com")){const s=this.extractFilenameFromUrl(r.src);s&&!i.has(s)&&this.document.removeFont(r.src)}}extractFilenameFromUrl(t){try{const{pathname:i}=new URL(t),r=i.split("/").pop();return r?r.replace(/\.[^.]+$/,""):null}catch{return null}}disposeClip(t){try{const i=this.canvas?.getViewportContainer();if(i){for(const r of i.children)if(r instanceof se.Container&&r.label?.toString().startsWith("shotstack-track-")&&r.children.includes(t.getContainer())){r.removeChild(t.getContainer());break}}}catch(i){console.warn(`Attempting to unmount an unmounted clip: ${i}`)}this.unloadClipAssets(t),this.timingManager.invalidateTimelineEndCache(),t.dispose()}unloadClipAssets(t){const{asset:i}=t.clipConfiguration;i&&"src"in i&&typeof i.src=="string"&&this.assetLoader.decrementRef(i.src)&&se.Assets.cache.has(i.src)&&se.Assets.unload(i.src)}clearClips(){for(const t of this.clips)this.disposeClip(t);this.tracks=[],this.clipsToDispose.clear(),this.clipErrors.clear(),this.lumaContentRelations.clear(),this.updateTotalDuration()}updateTotalDuration(){let t=0;for(const r of this.tracks)for(const a of r)t=Math.max(t,a.getEnd());const i=this.totalDuration;this.totalDuration=t,i!==this.totalDuration&&this.internalEvents.emit(Ae.DurationChanged,{duration:this.totalDuration})}propagateTimingChanges(t,i){this.timingManager.propagateTimingChanges(t,i)}async resolveClipAutoLength(t){const i=t.getTimingIntent();if(i.length!=="auto")return;const r=this.findClipIndices(t);let a=t.getStart();i.start==="auto"&&r&&(a=Yb(r.trackIndex,r.clipIndex,this.tracks));const s=await Wb(t.clipConfiguration.asset);t.setResolvedTiming({start:a,length:s}),t.reconfigureAfterRestore(),r&&this.propagateTimingChanges(r.trackIndex,r.clipIndex)}addPlayerToContainer(t,i){this.internalEvents.emit(yt.PlayerAddedToTrack,{player:i,trackIndex:t})}movePlayerToTrackContainer(t,i,r){this.internalEvents.emit(yt.PlayerMovedBetweenTracks,{player:t,fromTrackIndex:i,toTrackIndex:r})}createPlayerFromAssetType(t){return Ub.create(this,t)}async addPlayer(t,i){for(;this.tracks.length<=t;)this.tracks.push([]);this.tracks[t].push(i),this.internalEvents.emit(yt.PlayerAddedToTrack,{player:i,trackIndex:t}),await i.load(),this.updateTotalDuration()}selectClip(t,i){this.selectionManager.selectClip(t,i)}clearSelection(){this.selectionManager.clearSelection()}isClipSelected(t,i){return this.selectionManager.isClipSelected(t,i)}getSelectedClipInfo(){return this.selectionManager.getSelectedClipInfo()}copyClip(t,i){this.selectionManager.copyClip(t,i)}pasteClip(){this.selectionManager.pasteClip()}hasCopiedClip(){return this.selectionManager.hasCopiedClip()}findClipIndices(t){return this.selectionManager.findClipIndices(t)}getClipAt(t,i){return t>=0&&t<this.tracks.length&&i>=0&&i<this.tracks[t].length?this.tracks[t][i]:null}selectPlayer(t){this.selectionManager.selectPlayer(t)}isPlayerSelected(t){return this.selectionManager.isPlayerSelected(t)}getActivePlayersExcept(t){const i=[];for(const r of this.tracks)for(const a of r)a!==t&&a.isActive()&&i.push(a);return i}showAlignmentGuide(t,i,r,a){this.canvas?.showAlignmentGuide(t,i,r,a)}clearAlignmentGuides(){this.canvas?.clearAlignmentGuides()}moveSelectedClip(t,i){const r=this.getSelectedClipInfo();if(!r)return;const{player:a,trackIndex:s,clipIndex:n}=r,o=this.getResolvedClip(s,n);if(!o)return;const u=structuredClone(o),l=a.calculateMoveOffset(t,i),c=structuredClone(u);c.offset=l,this.setUpdatedClip(a,u,c)}setExportMode(t){this.isExporting=t}isInExportMode(){return this.isExporting}setCanvas(t){this.canvas=t}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(t,i){const r=new lF(t,i);return this.executeCommand(r)}setOutputFps(t){const i=new oF(t);return this.executeCommand(i)}getOutputFps(){return this.outputSettings.getFps()}setOutputFormat(t){const i=new nF(t);return this.executeCommand(i)}getOutputFormat(){return this.outputSettings.getFormat()}setOutputDestinations(t){const i=new sF(t);return this.executeCommand(i)}getOutputDestinations(){return this.outputSettings.getDestinations()}setOutputResolution(t){const i=new uF(t);return this.executeCommand(i)}getOutputResolution(){return this.outputSettings.getResolution()}setOutputAspectRatio(t){const i=new rF(t);return this.executeCommand(i)}getOutputAspectRatio(){return this.outputSettings.getAspectRatio()}getTimelineFonts(){return this.document.getFonts()}getFontMetadata(){return this.fontMetadata}getFontUrlByFamilyAndWeight(t,i){const{baseFontFamily:r}=pi(t),a=r.toLowerCase();for(const[s,n]of this.fontMetadata)if(n.baseFamilyName.toLowerCase()===a&&n.weight===i)return s;for(const[s,n]of this.fontMetadata)if(n.baseFamilyName.toLowerCase()===a)return s;return null}pruneUnusedFonts(){this.cleanupUnusedFonts()}setTimelineBackground(t){const i=new cF(t);return this.executeCommand(i)}setTimelineBackgroundInternal(t){DE.parse(t),this.backgroundColor=t,this.document.setBackground(t),this.internalEvents.emit(yt.ViewportSizeChanged,{width:this.size.width,height:this.size.height,backgroundColor:this.backgroundColor}),this.internalEvents.emit(Ae.TimelineBackgroundChanged,{color:t})}getTimelineBackground(){return this.backgroundColor}resolveMergeFields(t){return this.mergeFieldService.resolve(t)}getTemplateClip(t,i){const r=this.getPlayerClip(t,i);if(!r)return null;const a=r.getExportableClip();if(!a)return null;const{clipId:s}=r;if(s&&this.document){const n=this.document.getClipBindings(s);if(n)for(const[o,{placeholder:u}]of n)Wi(a,o,u)}return a}getTemplateClipById(t){const i=this.getPlayerByClipId(t);if(!i)return null;const r=i.getExportableClip();if(!r||!this.document)return null;const a=this.document.getClipBindings(t);if(a)for(const[s,{placeholder:n}]of a)Wi(r,s,n);return r}getTemplateClipText(t,i){const r=this.getTemplateClip(t,i);return r?r.asset?.text??null:null}getLumaClipIdForContent(t){for(const[i,r]of this.lumaContentRelations)if(r===t)return i;return null}getContentClipIdForLuma(t){return this.lumaContentRelations.get(t)??null}setLumaContentRelationship(t,i){this.lumaContentRelations.set(t,i)}clearLumaContentRelationship(t){this.lumaContentRelations.delete(t)}getLumaContentRelationship(t){return this.lumaContentRelations.get(t)}normalizeLumaAttachments(){let t=!1;for(let i=0;i<this.tracks.length;i+=1){const r=this.tracks[i];for(const a of r)if(a.playerType===ht.Luma){const s=this.findBestContentMatch(i,a);if(s){a.clipId&&s.clipId&&this.lumaContentRelations.set(a.clipId,s.clipId);const n=r.indexOf(a);this.document.updateClip(i,n,{start:s.getStart(),length:s.getLength()}),t=!0}}}t&&this.resolve()}findBestContentMatch(t,i){const r=this.tracks[t],a=i.getStart(),s=a+i.getLength();let n=null,o=0;for(const u of r)if(u.playerType!==ht.Luma){const l=u.getStart(),c=l+u.getLength(),d=DF(a,s,l,c);d>o&&(o=d,n=u)}return n}setupIntentListeners(){this.internalEvents.on(yt.CanvasClipClicked,t=>{this.selectPlayer(t.player)}),this.internalEvents.on(yt.CanvasBackgroundClicked,()=>{this.clearSelection()})}getTracks(){return this.tracks}}class Qb{constructor(t,i,r,a,s,n){this.clipId=t,this.propertyPath=i,this.fieldName=r,this.previousFieldName=a,this.storedPreviousValue=s,this.storedNewValue=n}name="setMergeField";storedPreviousValue;storedNewValue;storedPreviousBinding;updateDocumentClip(t,i,r){const a=t.getDocument();if(!a)return;const s=a.getClipById(this.clipId);if(!s)return;const n=s.clip;if(r)Wi(n,this.propertyPath,i);else{const u=(typeof i=="string"?i.trim():"").length>0?Number(i):NaN;Wi(n,this.propertyPath,Number.isFinite(u)?u:i)}}async execute(t){if(!t)throw new Error("SetMergeFieldCommand.execute: context is required");const i=t.getMergeFields();if(this.storedPreviousBinding=t.getClipBinding(this.clipId,this.propertyPath),this.fieldName){const r={placeholder:i.createTemplate(this.fieldName),resolvedValue:this.storedNewValue};t.setClipBinding(this.clipId,this.propertyPath,r)}else t.removeClipBinding(this.clipId,this.propertyPath);if(this.fieldName?i.register({name:this.fieldName,defaultValue:this.storedNewValue},{silent:!0}):this.previousFieldName&&i.remove(this.previousFieldName,{silent:!0}),this.fieldName){const r=i.createTemplate(this.fieldName);this.updateDocumentClip(t,r,!0)}else this.updateDocumentClip(t,this.storedNewValue,!1);return t.resolve(),t.emitEvent(Ae.MergeFieldChanged,{fields:i.getAll()}),Ke()}async undo(t){if(!t)throw new Error("SetMergeFieldCommand.undo: context is required");const i=t.getMergeFields();return this.storedPreviousBinding?t.setClipBinding(this.clipId,this.propertyPath,this.storedPreviousBinding):t.removeClipBinding(this.clipId,this.propertyPath),this.previousFieldName&&i.register({name:this.previousFieldName,defaultValue:this.storedPreviousValue},{silent:!0}),this.storedPreviousBinding?this.updateDocumentClip(t,this.storedPreviousBinding.placeholder,!0):this.updateDocumentClip(t,this.storedPreviousValue,!1),t.resolve(),t.emitEvent(Ae.MergeFieldChanged,{fields:i.getAll()}),Ke()}dispose(){this.storedPreviousBinding=void 0}}function TF(e){if(typeof e!="object"||e===null)return!1;const t=e;return t.type==="text"&&(!t.text||t.text.trim()==="")}function ev(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function OF(e){const t=e.width??100,i=e.height??100,r=ev(e.background?.color??"#000000"),a=e.background?.opacity??1,s=e.background?.borderRadius??0,n=[`width="${t}"`,`height="${i}"`,`fill="${r}"`];if(a!==1&&n.push(`fill-opacity="${a}"`),s>0&&n.push(`rx="${s}"`,`ry="${s}"`),e.stroke?.width&&e.stroke.width>0){const o=ev(e.stroke.color??"#000000");n.push(`stroke="${o}"`),n.push(`stroke-width="${e.stroke.width}"`)}return`<svg viewBox="0 0 ${t} ${i}" xmlns="http://www.w3.org/2000/svg"><rect ${n.join(" ")}/></svg>`}function $F(e){const t=e.asset,i=OF(t),r={...e,asset:{type:"svg",src:i,opacity:1}};return t.width!==void 0&&r.width===void 0&&(r.width=t.width),t.height!==void 0&&r.height===void 0&&(r.height=t.height),r}class RF extends dr{isUpdatingMergeFields=!1;get mergeFields(){return this.mergeFieldService}applyMergeField(t,i,r,a,s){const n=this.getResolvedClipById(t),o=n?eu(n,i):null,u=s??(o!=null?String(o):""),l=this.getTemplateClipById(t),c=l?eu(l,i):null,d=typeof c=="string"?this.mergeFieldService.extractFieldName(c):null,h=new Qb(t,i,r,d,u,a);return this.executeCommand(h)}removeMergeField(t,i,r){const a=this.getMergeFieldForProperty(t,i);if(!a)return Promise.resolve();const s=new Qb(t,i,null,a,r,r);return this.executeCommand(s)}getMergeFieldForProperty(t,i){const r=this.getTemplateClipById(t);if(!r)return null;const a=eu(r,i);return typeof a=="string"?this.mergeFieldService.extractFieldName(a):null}updateMergeFieldValueLive(t,i){if(!this.isUpdatingMergeFields){this.isUpdatingMergeFields=!0;try{const r=this.mergeFieldService.get(t);if(!r)return;this.mergeFieldService.register({...r,defaultValue:i},{silent:!0});for(const[,a]of this.getPlayerMap())this.updateMergeFieldBindings(a,t,i);this.resolve(),this.getInternalEvents().emit(Ae.TimelineUpdated,{current:this.getEdit()})}finally{this.isUpdatingMergeFields=!1}}}isSrcMergeField(t){for(const[i,r]of this.getPlayerMap())if(r.clipId){const a=this.getTemplateClipById(i);if(a){const s=a.asset?.type;if(s==="image"||s==="video"||s==="audio"){const o=this.getMergeFieldUsage(a,t);if(o.used&&o.isSrcField)return!0}}}return!1}validateMergeFieldValue(t,i){const r=this.getDocument();if(!r)return null;const a=this.mergeFieldService.get(t);if(!a)return null;const s=a.defaultValue;this.mergeFieldService.register({...a,defaultValue:i},{silent:!0});try{for(const n of r.getClipIdsWithBindings()){const o=r.getClipBindings(n);if(o&&this.clipUsesField(o,t)){const u=r.getClipById(n);if(u){const l=structuredClone(u.clip);for(const[d,h]of o){const g=this.mergeFieldService.resolve(h.placeholder);Wi(l,d,g)}delete l.id;const c=rn.safeParse(l);if(!c.success)return c.error.issues[0]?.message??"Invalid value"}}}return null}finally{this.mergeFieldService.register({...a,defaultValue:s},{silent:!0})}}isValueCompatibleWithClipProperty(t,i,r){const a=this.getResolvedClipById(t);if(!a)return!0;const s=structuredClone(a);return Wi(s,i,r),delete s.id,rn.safeParse(s).success}clipUsesField(t,i){for(const[,r]of t)if(this.mergeFieldService.extractFieldName(r.placeholder)===i)return!0;return!1}async deleteMergeFieldGlobally(t){const i=this.mergeFieldService.get(t);if(!i)return;const r=this.mergeFieldService.createTemplate(t),a=i.defaultValue;for(const[n]of this.getPlayerMap()){const o=this.getTemplateClipById(n);o&&await this.restoreMergeFieldInClip(n,o,r,a)}this.mergeFieldService.remove(t)||this.getInternalEvents().emit(Ae.MergeFieldChanged,{fields:this.mergeFieldService.getAll()})}async convertAllTextAssets(){const t=this.getDocument();if(!t)return console.error("No document available for conversion"),{richText:0,svg:0};const i=JSON.parse(JSON.stringify(t.toJSON()));let r=0,a=0;const s=i.timeline?.tracks;if(s){for(const n of s)if(n.clips)for(let o=0;o<n.clips.length;o+=1){const u=n.clips[o],l=u.asset;l?.type==="text"&&(TF(l)?(n.clips[o]=$F(u),a+=1):(n.clips[o]=this.convertTextClipToRichText(u),r+=1))}}return console.log("CONVERTED TEMPLATE - Copy the JSON below:"),console.log(JSON.stringify(i,null," ")),{richText:r,svg:a}}mapVerticalAlign(t){return t==="center"?"middle":t==="top"||t==="bottom"?t:"middle"}convertTextClipToRichText(t){const i=t.asset,r=i.font?.family??"Open Sans",{fontWeight:a}=pi(r),s={family:r,size:typeof i.font?.size=="string"?Number(i.font.size):i.font?.size??32,weight:i.font?.weight??a,color:i.font?.color??"#ffffff",opacity:i.font?.opacity??1};i.stroke?.width&&i.stroke.width>0&&(s.stroke={width:i.stroke.width,color:i.stroke.color??"#000000",opacity:1});const n={letterSpacing:0,wordSpacing:0,lineHeight:i.font?.lineHeight??1.2,textTransform:"none",textDecoration:"none"},o={type:"rich-text",text:i.text??"",font:s,style:n,align:{horizontal:i.alignment?.horizontal??"center",vertical:this.mapVerticalAlign(i.alignment?.vertical)}};i.background&&(o.background={color:i.background.color,opacity:i.background.opacity??1,borderRadius:i.background.borderRadius??0},i.background.padding&&(o.padding=i.background.padding)),i.animation&&(o.animation={preset:i.animation.preset,duration:i.animation.duration}),i.ellipsis!==void 0&&console.warn("TextAsset ellipsis property not supported in RichTextAsset, value dropped");const u={...t,asset:o};return i.width!==void 0&&u.width===void 0&&(u.width=i.width),i.height!==void 0&&u.height===void 0&&(u.height=i.height),u}updateMergeFieldBindings(t,i,r){if(!t)return;const{clipId:a}=t;if(!a)return;const s=this.getDocument();if(!s)return;const n=s.getClipBindings(a);if(!n)return;const o=s.getClipById(a);for(const[u,l]of n)if(this.mergeFieldService.extractFieldName(l.placeholder)===i){const d=this.mergeFieldService.resolve(l.placeholder),h={placeholder:l.placeholder,resolvedValue:d};if(s.setClipBinding(a,u,h),o){const m=(typeof d=="string"?d.trim():"").length>0?Number(d):NaN,v=Number.isFinite(m)?m:d;Wi(o.clip,u,v)}}}getMergeFieldUsage(t,i,r=""){if(!t||typeof t!="object")return{used:!1,isSrcField:!1};for(const[a,s]of Object.entries(t)){const n=r?`${r}.${a}`:a;if(typeof s=="string"){if(this.mergeFieldService.extractFieldName(s)===i)return{used:!0,isSrcField:n==="asset.src"||n.endsWith(".src")}}else if(typeof s=="object"&&s!==null){const o=this.getMergeFieldUsage(s,i,n);if(o.used)return o}}return{used:!1,isSrcField:!1}}async restoreMergeFieldInClip(t,i,r,a,s=""){if(!(!i||typeof i!="object"))for(const n of Object.keys(i)){const o=i[n],u=s?`${s}.${n}`:n;if(typeof o=="string"){const l=this.mergeFieldService.extractFieldName(o),c=this.mergeFieldService.extractFieldName(r);if(l&&c&&l===c){const d=o.replace(new RegExp(`\\{\\{\\s*${l}\\s*\\}\\}`,"gi"),a);await this.removeMergeField(t,u,d)}}else typeof o=="object"&&o!==null&&await this.restoreMergeFieldInClip(t,o,r,a,u)}}}const ru=Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"}));var ZF=xt({"node_modules/.pnpm/harfbuzzjs@0.4.12/node_modules/harfbuzzjs/hb.js"(e,t){var i=(()=>{var r=typeof document<"u"?document.currentScript?.src:void 0;return async function(a={}){var s,n=a,o=typeof window=="object",u=typeof WorkerGlobalScope<"u",l=typeof process=="object"&&process.versions?.node&&process.type!="renderer",c=(S,ue)=>{throw ue};typeof __filename<"u"?r=__filename:u&&(r=self.location.href);var d="";function h(S){return n.locateFile?n.locateFile(S,d):d+S}var g,m;if(l){var v=VE("fs");d=__dirname+"/",m=S=>{S=x(S)?new URL(S):S;var ue=v.readFileSync(S);return ue},g=async(S,ue=!0)=>{S=x(S)?new URL(S):S;var Me=v.readFileSync(S,ue?void 0:"utf8");return Me},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),c=(S,ue)=>{throw process.exitCode=S,ue}}else if(o||u){try{d=new URL(".",r).href}catch{}u&&(m=S=>{var ue=new XMLHttpRequest;return ue.open("GET",S,!1),ue.responseType="arraybuffer",ue.send(null),new Uint8Array(ue.response)}),g=async S=>{if(x(S))return new Promise((Me,st)=>{var Le=new XMLHttpRequest;Le.open("GET",S,!0),Le.responseType="arraybuffer",Le.onload=()=>{if(Le.status==200||Le.status==0&&Le.response){Me(Le.response);return}st(Le.status)},Le.onerror=st,Le.send(null)});var ue=await fetch(S,{credentials:"same-origin"});if(ue.ok)return ue.arrayBuffer();throw new Error(ue.status+" : "+ue.url)}}console.log.bind(console);var _=console.error.bind(console),C,k=!1,w,x=S=>S.startsWith("file://"),D,b,$,G,J=!1;function T(){var S=$.buffer;n.HEAP8=new Int8Array(S),n.HEAPU8=G=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 Y(){if(n.preRun)for(typeof n.preRun=="function"&&(n.preRun=[n.preRun]);n.preRun.length;)Z(n.preRun.shift());rt(X)}function O(){J=!0,hi.__wasm_call_ctors()}function re(){if(n.postRun)for(typeof n.postRun=="function"&&(n.postRun=[n.postRun]);n.postRun.length;)R(n.postRun.shift());rt(M)}var q=0,pe=null;function ce(S){q++,n.monitorRunDependencies?.(q)}function ye(S){if(q--,n.monitorRunDependencies?.(q),q==0&&pe){var ue=pe;pe=null,ue()}}function L(S){n.onAbort?.(S),S="Aborted("+S+")",_(S),k=!0,S+=". Build with -sASSERTIONS for more info.";var ue=new WebAssembly.RuntimeError(S);throw b?.(ue),ue}var Q;function ie(){return h("hb.wasm")}function ve(S){if(S==Q&&C)return new Uint8Array(C);if(m)return m(S);throw"both async and sync fetching of the wasm failed"}async function _e(S){if(!C)try{var ue=await g(S);return new Uint8Array(ue)}catch{}return ve(S)}async function Oe(S,ue){try{var Me=await _e(S),st=await WebAssembly.instantiate(Me,ue);return st}catch(Le){_(`failed to asynchronously prepare wasm: ${Le}`),L(Le)}}async function qe(S,ue,Me){if(!S&&!x(ue)&&!l)try{var st=fetch(ue,{credentials:"same-origin"}),Le=await WebAssembly.instantiateStreaming(st,Me);return Le}catch(Nt){_(`wasm streaming compile failed: ${Nt}`),_("falling back to ArrayBuffer instantiation")}return Oe(ue,Me)}function Xe(){return{env:Bs,wasi_snapshot_preview1:Bs}}async function Ze(){function S(Nt,ga){return hi=Nt.exports,n.wasmExports=hi,$=hi.memory,n.wasmMemory=$,T(),Vt=hi.__indirect_function_table,fu(hi),ye(),hi}ce();function ue(Nt){return S(Nt.instance)}var Me=Xe();if(n.instantiateWasm)return new Promise((Nt,ga)=>{n.instantiateWasm(Me,(hu,Mc)=>{Nt(S(hu))})});Q??(Q=ie());var st=await qe(C,Q,Me),Le=ue(st);return Le}class St{constructor(ue){ft(this,"name","ExitStatus"),this.message=`Program terminated with exit(${ue})`,this.status=ue}}var rt=S=>{for(;S.length>0;)S.shift()(n)},M=[],R=S=>M.push(S),X=[],Z=S=>X.push(S),le=!0,he=()=>L(""),fe=0,ge=()=>{le=!1,fe=0},Ce={},de=S=>{if(S instanceof St||S=="unwind")return w;c(1,S)},oe=()=>le||fe>0,$e=S=>{w=S,oe()||(n.onExit?.(S),k=!0),c(S,new St(S))},He=(S,ue)=>{w=S,$e(S)},Dt=He,Lt=()=>{if(!oe())try{Dt(w)}catch(S){de(S)}},jt=S=>{if(!k)try{S(),Lt()}catch(ue){de(ue)}},wt=()=>performance.now(),Tt=(S,ue)=>{if(Ce[S]&&(clearTimeout(Ce[S].id),delete Ce[S]),!ue)return 0;var Me=setTimeout(()=>{delete Ce[S],jt(()=>Ns(S,wt()))},ue);return Ce[S]={id:Me,timeout_ms:ue},0},Jt=()=>2147483648,Ve=(S,ue)=>Math.ceil(S/ue)*ue,Zc=S=>{var ue=$.buffer.byteLength,Me=(S-ue+65535)/65536|0;try{return $.grow(Me),T(),1}catch{}},hr=S=>{var ue=G.length;S>>>=0;var Me=Jt();if(S>Me)return!1;for(var st=1;st<=4;st*=2){var Le=ue*(1+.2/st);Le=Math.min(Le,S+100663296);var Nt=Math.min(Me,Ve(Math.max(S,Le),65536)),ga=Zc(Nt);if(ga)return!0}return!1},Et=S=>{const ue=S.length;return[ue%128|128,ue>>7,...S]},uu={i:127,p:127,j:126,f:125,d:124,e:111},si=S=>Et(Array.from(S,ue=>{var Me=uu[ue];return Me})),Vi=(S,ue)=>{var Me=Uint8Array.of(0,97,115,109,1,0,0,0,1,...Et([1,96,...si(ue.slice(1)),...si(ue[0]==="v"?"":ue[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0),st=new WebAssembly.Module(Me),Le=new WebAssembly.Instance(st,{e:{f:S}}),Nt=Le.exports.f;return Nt},Vt,gr=S=>Vt.get(S),pr=(S,ue)=>{if(qt)for(var Me=S;Me<S+ue;Me++){var st=gr(Me);st&&qt.set(st,Me)}},qt,Oa=S=>(qt||(qt=new WeakMap,pr(0,Vt.length)),qt.get(S)||0),mr=[],lu=()=>mr.length?mr.pop():Vt.grow(1),yr=(S,ue)=>Vt.set(S,ue),br=(S,ue)=>{var Me=Oa(S);if(Me)return Me;var st=lu();try{yr(st,S)}catch(Nt){if(!(Nt instanceof TypeError))throw Nt;var Le=Vi(S,ue);yr(st,Le)}return qt.set(S,st),st},cu=S=>{qt.delete(gr(S)),yr(S,null),mr.push(S)};n.noExitRuntime&&(le=n.noExitRuntime),n.print&&n.print,n.printErr&&(_=n.printErr),n.wasmBinary&&(C=n.wasmBinary),n.arguments&&n.arguments,n.thisProgram&&n.thisProgram,n.wasmMemory=$,n.wasmExports=hi,n.addFunction=br,n.removeFunction=cu;var Ns;function fu(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,Ns=S._emscripten_timeout}var Bs={_abort_js:he,_emscripten_runtime_keepalive_clear:ge,_setitimer_js:Tt,emscripten_resize_heap:hr,proc_exit:$e},hi=await Ze();function vr(){if(q>0){pe=vr;return}if(Y(),q>0){pe=vr;return}function S(){n.calledRun=!0,!k&&(O(),D?.(n),n.onRuntimeInitialized?.(),re())}n.setStatus?(n.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>n.setStatus(""),1),S()},1)):S()}function du(){if(n.preInit)for(typeof n.preInit=="function"&&(n.preInit=[n.preInit]);n.preInit.length>0;)n.preInit.shift()()}return du(),vr(),J?s=n:s=new Promise((S,ue)=>{D=S,b=ue}),s}})();typeof e=="object"&&typeof t=="object"?(t.exports=i,t.exports.default=i):typeof define=="function"&&define.amd&&define([],()=>i)}});const MF=ZF(),UF=Object.freeze(Object.defineProperty({__proto__:null,default:MF},Symbol.toStringTag,{value:"Module"}));var LF=xt({"node_modules/.pnpm/harfbuzzjs@0.4.12/node_modules/harfbuzzjs/hbjs.js"(e,t){function i(r){var a=r.wasmExports,s=new TextDecoder("utf8");let n=r.addFunction,o=r.removeFunction;var u=n(function(L){a.free(L)},"vi"),l=2,c=-1,d=2,h=0,g=1,m=2;function v(L){return(L.charCodeAt(0)&255)<<24|(L.charCodeAt(1)&255)<<16|(L.charCodeAt(2)&255)<<8|(L.charCodeAt(3)&255)<<0}var _=v("JSON"),C=4;function k(L){return[String.fromCharCode(L>>24&255),String.fromCharCode(L>>16&255),String.fromCharCode(L>>8&255),String.fromCharCode(L>>0&255)].join("")}function w(L){return L=="BOT"?1:L=="EOT"?2:L=="PRESERVE_DEFAULT_IGNORABLES"?4:L=="REMOVE_DEFAULT_IGNORABLES"?8:L=="DO_NOT_INSERT_DOTTED_CIRCLE"?16:L=="PRODUCE_UNSAFE_TO_CONCAT"?64:0}function x(L){var Q=a.malloc(L.byteLength);r.HEAPU8.set(new Uint8Array(L),Q);var ie=a.hb_blob_create(Q,L.byteLength,l,Q,u);return{ptr:ie,destroy:function(){a.hb_blob_destroy(ie)}}}function D(L){const Q=a.hb_set_get_population(L),ie=a.malloc(Q<<2),ve=ie>>2,_e=r.HEAPU32.subarray(ve,ve+Q);return r.HEAPU32.set(_e,ve),a.hb_set_next_many(L,c,ie,Q),_e}function b(L,Q){var ie=a.hb_face_create(L.ptr,Q);const ve=a.hb_face_get_upem(ie);return{ptr:ie,upem:ve,reference_table:function(_e){var Oe=a.hb_face_reference_table(ie,v(_e)),qe=a.hb_blob_get_length(Oe);if(qe){var Xe=a.hb_blob_get_data(Oe,null),Ze=r.HEAPU8.subarray(Xe,Xe+qe);return Ze}},getAxisInfos:function(){var _e=a.malloc(2048),Oe=a.malloc(4);r.HEAPU32[Oe/4]=64,a.hb_ot_var_get_axis_infos(ie,0,Oe,_e);var qe={};return Array.from({length:r.HEAPU32[Oe/4]}).forEach(function(Xe,Ze){qe[k(r.HEAPU32[_e/4+Ze*8+1])]={min:r.HEAPF32[_e/4+Ze*8+4],default:r.HEAPF32[_e/4+Ze*8+5],max:r.HEAPF32[_e/4+Ze*8+6]}}),a.free(Oe),a.free(_e),qe},collectUnicodes:function(){var _e=a.hb_set_create();a.hb_face_collect_unicodes(ie,_e);var Oe=D(_e);return a.hb_set_destroy(_e),Oe},destroy:function(){a.hb_face_destroy(ie)}}}var $="",G=256,J=a.malloc(G);function T(L){var Q=a.hb_font_create(L.ptr),ie=null,ve=null,_e=null,Oe=null,qe=null,Xe=null;function Ze(rt){if(!ie){var M=function(he,fe,ge,Ce,de,oe){$+=`M${Ce},${de}`},R=function(he,fe,ge,Ce,de,oe){$+=`L${Ce},${de}`},X=function(he,fe,ge,Ce,de,oe,$e,He,Dt,Lt){$+=`C${Ce},${de} ${oe},${$e} ${He},${Dt}`},Z=function(he,fe,ge,Ce,de,oe,$e,He){$+=`Q${Ce},${de} ${oe},${$e}`},le=function(he,fe,ge,Ce){$+="Z"};ve=n(M,"viiiffi"),_e=n(R,"viiiffi"),Oe=n(X,"viiiffffffi"),qe=n(Z,"viiiffffi"),Xe=n(le,"viiii"),ie=a.hb_draw_funcs_create(),a.hb_draw_funcs_set_move_to_func(ie,ve,0,0),a.hb_draw_funcs_set_line_to_func(ie,_e,0,0),a.hb_draw_funcs_set_cubic_to_func(ie,Oe,0,0),a.hb_draw_funcs_set_quadratic_to_func(ie,qe,0,0),a.hb_draw_funcs_set_close_path_func(ie,Xe,0,0)}return $="",a.hb_font_draw_glyph(Q,rt,ie,0),$}function St(rt){a.hb_font_glyph_to_string(Q,rt,J,G);var M=r.HEAPU8.subarray(J,J+G);return s.decode(M.slice(0,M.indexOf(0)))}return{ptr:Q,glyphName:St,glyphToPath:Ze,glyphToJson:function(rt){var M=Ze(rt);return M.replace(/([MLQCZ])/g,"|$1 ").split("|").filter(function(R){return R.length}).map(function(R){var X=R.split(/[ ,]/g);return{type:X[0],values:X.slice(1).filter(function(Z){return Z.length}).map(function(Z){return+Z})}})},setScale:function(rt,M){a.hb_font_set_scale(Q,rt,M)},setVariations:function(rt){var M=Object.entries(rt),R=a.malloc(8*M.length);M.forEach(function(X,Z){r.HEAPU32[R/4+Z*2+0]=v(X[0]),r.HEAPF32[R/4+Z*2+1]=X[1]}),a.hb_font_set_variations(Q,R,M.length),a.free(R)},destroy:function(){a.hb_font_destroy(Q),ie&&(a.hb_draw_funcs_destroy(ie),ie=null,o(ve),o(_e),o(Oe),o(qe),o(Xe))}}}function Y(L){var Q=a.malloc(L.length+1);for(let ie=0;ie<L.length;++ie){const ve=L.charCodeAt(ie);if(ve>127)throw new Error("Expected ASCII text");r.HEAPU8[Q+ie]=ve}return r.HEAPU8[Q+L.length]=0,{ptr:Q,length:L.length,free:function(){a.free(Q)}}}function O(L){const Q=a.malloc(L.length*2),ie=new Uint16Array(r.wasmMemory.buffer,Q,L.length);for(let ve=0;ve<ie.length;++ve)ie[ve]=L.charCodeAt(ve);return{ptr:Q,length:ie.length,free:function(){a.free(Q)}}}function re(){var L=a.hb_buffer_create();return{ptr:L,addText:function(Q){const ie=O(Q);a.hb_buffer_add_utf16(L,ie.ptr,ie.length,0,ie.length),ie.free()},guessSegmentProperties:function(){return a.hb_buffer_guess_segment_properties(L)},setDirection:function(Q){a.hb_buffer_set_direction(L,{ltr:4,rtl:5,ttb:6,btt:7}[Q]||0)},setFlags:function(Q){var ie=0;Q.forEach(function(ve){ie|=w(ve)}),a.hb_buffer_set_flags(L,ie)},setLanguage:function(Q){var ie=Y(Q);a.hb_buffer_set_language(L,a.hb_language_from_string(ie.ptr,-1)),ie.free()},setScript:function(Q){var ie=Y(Q);a.hb_buffer_set_script(L,a.hb_script_from_string(ie.ptr,-1)),ie.free()},setClusterLevel:function(Q){a.hb_buffer_set_cluster_level(L,Q)},json:function(){for(var Q=a.hb_buffer_get_length(L),ie=[],ve=a.hb_buffer_get_glyph_infos(L,0),_e=ve/4,Oe=a.hb_buffer_get_glyph_positions(L,0)/4,qe=r.HEAPU32.subarray(_e,_e+5*Q),Xe=r.HEAP32.subarray(Oe,Oe+5*Q),Ze=0;Ze<Q;++Ze)ie.push({g:qe[Ze*5+0],cl:qe[Ze*5+2],ax:Xe[Ze*5+0],ay:Xe[Ze*5+1],dx:Xe[Ze*5+2],dy:Xe[Ze*5+3],flags:a.hb_glyph_info_get_glyph_flags(ve+Ze*20)});return ie},destroy:function(){a.hb_buffer_destroy(L)}}}function q(L,Q,ie){var ve=0,_e=0;ie&&(ie=ie.split(","),ve=a.malloc(16*ie.length),ie.forEach(function(Oe,qe){var Xe=Y(Oe);a.hb_feature_from_string(Xe.ptr,-1,ve+_e*16)&&_e++,Xe.free()})),a.hb_shape(L.ptr,Q.ptr,ve,_e),ve&&a.free(ve)}function pe(L,Q,ie,ve,_e){var Oe=[],qe=h,Xe=!1,Ze=1024*1024,St=a.malloc(Ze),rt=function(R,X,Z,le){var he=s.decode(r.HEAPU8.subarray(Z,r.HEAPU8.indexOf(0,Z)));return he.startsWith("start table GSUB")?qe=g:he.startsWith("start table GPOS")&&(qe=m),qe!=_e&&(Xe=!1),_e!=h&&qe==_e&&he.startsWith("end lookup "+ve)&&(Xe=!0),Xe?0:(a.hb_buffer_serialize_glyphs(R,0,a.hb_buffer_get_length(R),St,Ze,0,X,_,C),Oe.push({m:he,t:JSON.parse(s.decode(r.HEAPU8.subarray(St,r.HEAPU8.indexOf(0,St)))),glyphs:a.hb_buffer_get_content_type(R)==d}),1)},M=n(rt,"iiiii");return a.hb_buffer_set_message_func(Q.ptr,M,0,0),q(L,Q,ie),a.free(St),o(M),Oe}function ce(){var L=a.malloc(12);a.hb_version(L,L+4,L+8);var Q={major:r.HEAPU32[L/4],minor:r.HEAPU32[(L+4)/4],micro:r.HEAPU32[(L+8)/4]};return a.free(L),Q}function ye(){var L=a.hb_version_string(),Q=s.decode(r.HEAPU8.subarray(L,r.HEAPU8.indexOf(0,L)));return Q}return{createBlob:x,createFace:b,createFont:T,createBuffer:re,shape:q,shapeWithTrace:pe,version:ce,version_string:ye}}try{t.exports=i}catch{}}});const jF=LF(),GF=Object.freeze(Object.defineProperty({__proto__:null,default:jF},Symbol.toStringTag,{value:"Module"}));var be,Yi=new Array(128).fill(void 0);Yi.push(void 0,null,!0,!1);var ks=Yi.length;function Ht(e){ks===Yi.length&&Yi.push(Yi.length+1);const t=ks;return ks=Yi[t],Yi[t]=e,t}function Ut(e){return Yi[e]}function WF(e){e<132||(Yi[e]=ks,ks=e)}function Ki(e){const t=Ut(e);return WF(e),t}var Ds=0,_s=null;function su(){return(_s===null||_s.byteLength===0)&&(_s=new Uint8Array(be.memory.buffer)),_s}var nu=typeof TextEncoder<"u"?new TextEncoder("utf-8"):{encode:()=>{throw Error("TextEncoder not available")}},YF=typeof nu.encodeInto=="function"?function(e,t){return nu.encodeInto(e,t)}:function(e,t){const i=nu.encode(e);return t.set(i),{read:e.length,written:i.length}};function Tc(e,t,i){if(i===void 0){const o=nu.encode(e),u=t(o.length,1)>>>0;return su().subarray(u,u+o.length).set(o),Ds=o.length,u}let r=e.length,a=t(r,1)>>>0;const s=su();let n=0;for(;n<r;n++){const o=e.charCodeAt(n);if(o>127)break;s[a+n]=o}if(n!==r){n!==0&&(e=e.slice(n)),a=i(a,r,r=n+e.length*3,1)>>>0;const o=su().subarray(a+n,a+r),u=YF(e,o);n+=u.written,a=i(a,r,n,1)>>>0}return Ds=n,a}function Oc(e){return e==null}var Ss=null;function _t(){return(Ss===null||Ss.byteLength===0)&&(Ss=new Int32Array(be.memory.buffer)),Ss}var tv=typeof TextDecoder<"u"?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}};typeof TextDecoder<"u"&&tv.decode();function ou(e,t){return e=e>>>0,tv.decode(su().subarray(e,e+t))}function KF(e,t){if(!(e instanceof t))throw new Error(`expected instance of ${t.name}`);return e.ptr}function XF(e,t){try{return e.apply(this,t)}catch(i){be.__wbindgen_exn_store(Ht(i))}}var iv=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>be.__wbg_bbox_free(e>>>0)),$c=class bv{static __wrap(t){t=t>>>0;const i=Object.create(bv.prototype);return i.__wbg_ptr=t,iv.register(i,i.__wbg_ptr,i),i}__destroy_into_raw(){const t=this.__wbg_ptr;return this.__wbg_ptr=0,iv.unregister(this),t}free(){const t=this.__destroy_into_raw();be.__wbg_bbox_free(t)}get x(){return be.__wbg_get_bbox_x(this.__wbg_ptr)}set x(t){be.__wbg_set_bbox_x(this.__wbg_ptr,t)}get y(){return be.__wbg_get_bbox_y(this.__wbg_ptr)}set y(t){be.__wbg_set_bbox_y(this.__wbg_ptr,t)}get width(){return be.__wbg_get_bbox_width(this.__wbg_ptr)}set width(t){be.__wbg_set_bbox_width(this.__wbg_ptr,t)}get height(){return be.__wbg_get_bbox_height(this.__wbg_ptr)}set height(t){be.__wbg_set_bbox_height(this.__wbg_ptr,t)}},av=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>be.__wbg_renderedimage_free(e>>>0)),HF=class vv{static __wrap(t){t=t>>>0;const i=Object.create(vv.prototype);return i.__wbg_ptr=t,av.register(i,i.__wbg_ptr,i),i}__destroy_into_raw(){const t=this.__wbg_ptr;return this.__wbg_ptr=0,av.unregister(this),t}free(){const t=this.__destroy_into_raw();be.__wbg_renderedimage_free(t)}get width(){return be.renderedimage_width(this.__wbg_ptr)>>>0}get height(){return be.renderedimage_height(this.__wbg_ptr)>>>0}asPng(){try{const a=be.__wbindgen_add_to_stack_pointer(-16);be.renderedimage_asPng(a,this.__wbg_ptr);var t=_t()[a/4+0],i=_t()[a/4+1],r=_t()[a/4+2];if(r)throw Ki(i);return Ki(t)}finally{be.__wbindgen_add_to_stack_pointer(16)}}get pixels(){const t=be.renderedimage_pixels(this.__wbg_ptr);return Ki(t)}},JF=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>be.__wbg_resvg_free(e>>>0)),qF=class{__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,JF.unregister(this),e}free(){const e=this.__destroy_into_raw();be.__wbg_resvg_free(e)}constructor(e,t,i){try{const u=be.__wbindgen_add_to_stack_pointer(-16);var r=Oc(t)?0:Tc(t,be.__wbindgen_malloc,be.__wbindgen_realloc),a=Ds;be.resvg_new(u,Ht(e),r,a,Oc(i)?0:Ht(i));var s=_t()[u/4+0],n=_t()[u/4+1],o=_t()[u/4+2];if(o)throw Ki(n);return this.__wbg_ptr=s>>>0,this}finally{be.__wbindgen_add_to_stack_pointer(16)}}get width(){return be.resvg_width(this.__wbg_ptr)}get height(){return be.resvg_height(this.__wbg_ptr)}render(){try{const r=be.__wbindgen_add_to_stack_pointer(-16);be.resvg_render(r,this.__wbg_ptr);var e=_t()[r/4+0],t=_t()[r/4+1],i=_t()[r/4+2];if(i)throw Ki(t);return HF.__wrap(e)}finally{be.__wbindgen_add_to_stack_pointer(16)}}toString(){let e,t;try{const a=be.__wbindgen_add_to_stack_pointer(-16);be.resvg_toString(a,this.__wbg_ptr);var i=_t()[a/4+0],r=_t()[a/4+1];return e=i,t=r,ou(i,r)}finally{be.__wbindgen_add_to_stack_pointer(16),be.__wbindgen_free(e,t,1)}}innerBBox(){const e=be.resvg_innerBBox(this.__wbg_ptr);return e===0?void 0:$c.__wrap(e)}getBBox(){const e=be.resvg_getBBox(this.__wbg_ptr);return e===0?void 0:$c.__wrap(e)}cropByBBox(e){KF(e,$c),be.resvg_cropByBBox(this.__wbg_ptr,e.__wbg_ptr)}imagesToResolve(){try{const r=be.__wbindgen_add_to_stack_pointer(-16);be.resvg_imagesToResolve(r,this.__wbg_ptr);var e=_t()[r/4+0],t=_t()[r/4+1],i=_t()[r/4+2];if(i)throw Ki(t);return Ki(e)}finally{be.__wbindgen_add_to_stack_pointer(16)}}resolveImage(e,t){try{const a=be.__wbindgen_add_to_stack_pointer(-16),s=Tc(e,be.__wbindgen_malloc,be.__wbindgen_realloc),n=Ds;be.resvg_resolveImage(a,this.__wbg_ptr,s,n,Ht(t));var i=_t()[a/4+0],r=_t()[a/4+1];if(r)throw Ki(i)}finally{be.__wbindgen_add_to_stack_pointer(16)}}};async function QF(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(r){if(e.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",r);else throw r}const i=await e.arrayBuffer();return await WebAssembly.instantiate(i,t)}else{const i=await WebAssembly.instantiate(e,t);return i instanceof WebAssembly.Instance?{instance:i,module:e}:i}}function eV(){const e={};return e.wbg={},e.wbg.__wbg_new_28c511d9baebfa89=function(t,i){const r=new Error(ou(t,i));return Ht(r)},e.wbg.__wbindgen_memory=function(){const t=be.memory;return Ht(t)},e.wbg.__wbg_buffer_12d079cc21e14bdb=function(t){const i=Ut(t).buffer;return Ht(i)},e.wbg.__wbg_newwithbyteoffsetandlength_aa4a17c33a06e5cb=function(t,i,r){const a=new Uint8Array(Ut(t),i>>>0,r>>>0);return Ht(a)},e.wbg.__wbindgen_object_drop_ref=function(t){Ki(t)},e.wbg.__wbg_new_63b92bc8671ed464=function(t){const i=new Uint8Array(Ut(t));return Ht(i)},e.wbg.__wbg_values_839f3396d5aac002=function(t){const i=Ut(t).values();return Ht(i)},e.wbg.__wbg_next_196c84450b364254=function(){return XF(function(t){const i=Ut(t).next();return Ht(i)},arguments)},e.wbg.__wbg_done_298b57d23c0fc80c=function(t){return Ut(t).done},e.wbg.__wbg_value_d93c65011f51a456=function(t){const i=Ut(t).value;return Ht(i)},e.wbg.__wbg_instanceof_Uint8Array_2b3bbecd033d19f6=function(t){let i;try{i=Ut(t)instanceof Uint8Array}catch{i=!1}return i},e.wbg.__wbindgen_string_get=function(t,i){const r=Ut(i),a=typeof r=="string"?r:void 0;var s=Oc(a)?0:Tc(a,be.__wbindgen_malloc,be.__wbindgen_realloc),n=Ds;_t()[t/4+1]=n,_t()[t/4+0]=s},e.wbg.__wbg_new_16b304a2cfa7ff4a=function(){const t=new Array;return Ht(t)},e.wbg.__wbindgen_string_new=function(t,i){const r=ou(t,i);return Ht(r)},e.wbg.__wbg_push_a5b05aedc7234f9f=function(t,i){return Ut(t).push(Ut(i))},e.wbg.__wbg_length_c20a40f15020d68a=function(t){return Ut(t).length},e.wbg.__wbg_set_a47bac70306a19a7=function(t,i,r){Ut(t).set(Ut(i),r>>>0)},e.wbg.__wbindgen_throw=function(t,i){throw new Error(ou(t,i))},e}function tV(e,t){return be=e.exports,rv.__wbindgen_wasm_module=t,Ss=null,_s=null,be}async function rv(e){if(be!==void 0)return be;typeof e>"u"&&(e=new URL("index_bg.wasm",void 0));const t=eV();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));const{instance:i,module:r}=await QF(await e,t);return tV(i,r)}var iV=rv,Rc=!1,aV=async e=>{if(Rc)throw new Error("Already initialized. The `initWasm()` function can be used only once.");await iV(await e),Rc=!0},rV=class extends qF{constructor(e,t){if(!Rc)throw new Error("Wasm has not been initialized. Call `initWasm()` function.");const i=t?.font;if(i&&sV(i)){const r={...t,font:{...i,fontBuffers:void 0}};super(e,JSON.stringify(r),i.fontBuffers)}else super(e,JSON.stringify(t))}};function sV(e){return Object.prototype.hasOwnProperty.call(e,"fontBuffers")}const sv=Object.freeze(Object.defineProperty({__proto__:null,Resvg:rV,initWasm:aV},Symbol.toStringTag,{value:"Module"}));vi.Edit=dr,vi.ShotstackEdit=RF,Object.defineProperty(vi,Symbol.toStringTag,{value:"Module"})});
|
|
267
|
+
`),u=o===-1?this.textPosition:this.textPosition-o-1,l=n.substring(0,u);let c;l.length>0&&l.endsWith(" ")?c=this.measureText(`${l}x`,i)-this.measureText("x",i):c=this.measureText(l,i);const d=i.lineHeight;this.pixelY=this.currentLine*d;const g=this.clipConfig.asset.alignment?.horizontal??"center";let m=c;if(g!=="left"){const v=this.measureText(n,i),_=this.textElement.width;let C=0;g==="center"?C=(_-v)/2:g==="right"&&(C=_-v),m=C+c}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(t,i){const r=new se.Text(t,i),{width:a}=r;return r.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 qo{static DEFAULT_FOCUS_DELAY_MS=50;hiddenInput=null;isFocused=!1;focusRetryCount=0;maxFocusRetries=3;focusDelay=qo.DEFAULT_FOCUS_DELAY_MS;eventHandlers={};abortController=null;textChangeCallback=null;lastSyncedText="";isComposing=!1;setupInput(t,i){this.focusDelay=i?.focusDelay??qo.DEFAULT_FOCUS_DELAY_MS,this.createHiddenTextarea(),this.hiddenInput&&(this.hiddenInput.value=t,this.lastSyncedText=t),this.setupEventListeners(),i?.autoFocus!==!1&&this.focusInput()}updateInputValue(t){this.hiddenInput&&(this.hiddenInput.value=t,this.lastSyncedText=t)}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(t,i){if(!this.hiddenInput)return;const r=this.hiddenInput.value.length,a=Math.max(0,Math.min(t,r)),s=Math.max(a,Math.min(i,r));this.hiddenInput.setSelectionRange(a,s)}getCursorPosition(){return this.hiddenInput?.selectionStart||0}getValue(){return this.hiddenInput?.value||""}setTextInputHandler(t){this.textChangeCallback=t}setEventHandlers(t){this.eventHandlers={...this.eventHandlers,...t}}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 t={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,t),this.hiddenInput.tabIndex=0,document.body.appendChild(this.hiddenInput)}setupEventListeners(){if(!this.hiddenInput)return;this.abortController=new AbortController;const{signal:t}=this.abortController;this.hiddenInput.addEventListener("input",this.handleTextInput,{signal:t}),this.hiddenInput.addEventListener("keydown",this.handleKeyDown,{signal:t}),this.hiddenInput.addEventListener("compositionstart",this.handleCompositionStart,{signal:t}),this.hiddenInput.addEventListener("compositionend",this.handleCompositionEnd,{signal:t}),this.hiddenInput.addEventListener("focus",this.handleFocus,{signal:t}),this.hiddenInput.addEventListener("blur",this.handleBlur,{signal:t}),this.hiddenInput.addEventListener("paste",this.handlePaste,{signal:t})}removeAllEventListeners(){this.abortController?.abort(),this.abortController=null}handleTextInput=t=>{if(!this.hiddenInput||this.isComposing)return;const i=this.hiddenInput.value,r=this.hiddenInput.selectionStart||0;this.lastSyncedText=i,this.textChangeCallback?.(i,r)};handleKeyDown=t=>{if(document.activeElement!==this.hiddenInput)return;let i=!1;if((t.ctrlKey||t.metaKey)&&(i=this.handleKeyboardShortcuts(t),i)){t.preventDefault();return}if(t.key==="Tab"){const r=t.shiftKey?"backward":"forward";this.eventHandlers.onTabNavigation?.(r),t.preventDefault();return}switch(t.key){case"Escape":this.eventHandlers.onEscape?.(t),i=!0;break;case"Enter":i=!1;break;case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":setTimeout(()=>{if(this.hiddenInput){const r=this.hiddenInput.value,a=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(r,a)}},0),i=!1;break;case"Backspace":case"Delete":i=!1;break;default:i=this.eventHandlers.onCustomKey?.(t.key,t)||!1;break}i&&t.preventDefault()};handleKeyboardShortcuts(t){const{key:i}=t;switch(i.toLowerCase()){case"a":return this.selectAll(),!0;case"c":case"v":return!1;case"z":return this.eventHandlers.onCustomKey?.("undo",t),!0;case"y":return this.eventHandlers.onCustomKey?.("redo",t),!0;default:return!1}}handleCompositionStart=t=>{this.isComposing=!0};handleCompositionEnd=t=>{if(this.isComposing=!1,this.hiddenInput){const i=this.hiddenInput.value,r=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(i,r)}};handleFocus=t=>{this.isFocused=!0,this.focusRetryCount=0,this.eventHandlers.onFocus?.(t)};handleBlur=t=>{this.isFocused=!1,this.eventHandlers.onBlur?.(t)};handlePaste=t=>{setTimeout(()=>{this.handleTextInput(t)},0)};selectAll(){this.hiddenInput&&this.hiddenInput.select()}}class Fi{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(t,i,r){this.parent=t,this.targetText=i,this.clipConfig=r,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 t=structuredClone(this.clipConfig);this.targetText.visible=!1,this.createEditingEnvironment(),this.setupOutsideClickHandler(t),this.isEditing=!0}stopEditing(t=!1,i){if(!this.isEditing)return;let r="";this.editableText&&(r=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,t&&i&&r!==""&&this.parent.updateTextContent(r,i),this.isEditing=!1}checkForDoubleClick=t=>{const i=Date.now();i-this.lastClickTime<Fi.DOUBLE_CLICK_THRESHOLD_MS&&this.startEditing(),this.lastClickTime=i};setupOutsideClickHandler(t){this.outsideClickHandler=i=>{const a=this.parent.getContainer().getBounds(),s=i.clientX,n=i.clientY;(s<a.x||s>a.x+a.width||n<a.y||n>a.y+a.height)&&(this.stopEditing(!0,t),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null))},setTimeout(()=>{this.outsideClickHandler&&window.addEventListener("click",this.outsideClickHandler)},Fi.CLICK_HANDLER_DELAY_MS)}createEditingEnvironment(){this.setupEditingContainer(),this.editingContainer&&this.editableText&&(this.textCursor=new As(this.editingContainer,this.editableText,this.clipConfig),this.textCursor.updatePosition(this.targetText.text.length),this.textCursor.startBlinking()),this.setupTextInputHandler(),this.updateTextAlignment()}setupEditingContainer(){this.editingContainer=new se.Container,this.parent.getContainer().addChild(this.editingContainer);const t=new se.Graphics;t.fillStyle={color:0,alpha:Fi.EDITING_BG_ALPHA},t.rect(-5,-5,this.targetText.width+2*Fi.EDITING_BG_PADDING_PX,this.targetText.height+2*Fi.EDITING_BG_PADDING_PX),t.fill(),this.editingContainer.addChild(t),this.editableText=new se.Text(this.targetText.text,this.targetText.style),this.editableText.eventMode="static",this.editableText.cursor="text",this.editingContainer.addChild(this.editableText)}setupTextInputHandler(){this.textInputHandler=new qo,this.textInputHandler.setTextInputHandler((t,i)=>{this.editableText&&(this.editableText.text=t,this.updateTextAlignment()),this.textCursor?.updatePosition(i)}),this.textInputHandler.setEventHandlers({onEscape:t=>this.stopEditing(!1),onTabNavigation:t=>this.stopEditing(!0)}),this.textInputHandler.setupInput(this.targetText.text,{autoFocus:!0})}updateTextAlignment(){if(!this.editableText||!this.editingContainer)return;const t=this.getContainerDimensions(),i=this.getAlignmentSettings(),r=this.calculateHorizontalPosition({width:this.editableText.width},t,i.horizontal),a=this.calculateVerticalPosition({height:this.editableText.height},t,i.vertical);if(this.editingContainer.position.set(r,a),this.editingContainer.children.length>0){const s=this.editingContainer.getChildAt(0);s instanceof se.Graphics&&(s.clear(),s.fillStyle={color:0,alpha:Fi.EDITING_BG_ALPHA},s.rect(-5,-5,this.editableText.width+2*Fi.EDITING_BG_PADDING_PX,this.editableText.height+2*Fi.EDITING_BG_PADDING_PX),s.fill())}}calculateHorizontalPosition(t,i,r="center"){switch(r){case"center":return i.width/2-t.width/2;case"right":return i.width-t.width;case"left":default:return 0}}calculateVerticalPosition(t,i,r="center"){switch(r){case"center":return i.height/2-t.height/2;case"bottom":return i.height-t.height;case"top":default:return 0}}getContainerDimensions(){const t=this.clipConfig.asset;return{width:t.width??this.parent.getSize().width,height:t.height??this.parent.getSize().height}}getAlignmentSettings(){const t=this.clipConfig.asset;return{horizontal:t.alignment?.horizontal??"center",vertical:t.alignment?.vertical??"center"}}}class cr extends Ot{static loadedFonts=new Set;background=null;text=null;textEditor=null;constructor(t,i){super(t,i,ht.Text)}async load(){await super.load();const t=this.clipConfiguration.asset,i=t.font?.family??"Open Sans";if(await this.loadFont(i),this.background=new se.Graphics,this.drawBackground(),this.text=new se.Text({text:t.text??"",style:this.createTextStyle(t)}),this.positionText(t),t.stroke?.width&&t.stroke.width>0&&t.stroke.color){const r=new Cr({thickness:t.stroke.width,color:t.stroke.color});this.text.filters=[r]}this.contentContainer.addChild(this.background),this.contentContainer.addChild(this.text),this.configureKeyframes(),this.textEditor=new Fi(this,this.text,this.clipConfiguration)}update(t,i){super.update(t,i)}reconfigureAfterRestore(){super.reconfigureAfterRestore(),this.reconfigure()}async reconfigure(){const t=this.clipConfiguration.asset,i=t.font?.family??"Open Sans";if(await this.loadFont(i),this.drawBackground(),this.text){if(this.text.text=t.text??"",this.text.style=this.createTextStyle(t),t.stroke?.width&&t.stroke.width>0&&t.stroke.color){const r=new Cr({thickness:t.stroke.width,color:t.stroke.color});this.text.filters=[r]}else this.text.filters=[];this.positionText(t)}}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null,this.textEditor?.dispose(),this.textEditor=null}getSize(){const t=this.clipConfiguration.asset;return{width:this.clipConfiguration.width??t.width??this.edit.size.width,height:this.clipConfiguration.height??t.height??this.edit.size.height}}getFitScale(){return 1}getContainerScale(){const t=this.getScale();return{x:t,y:t}}supportsEdgeResize(){return!0}onDimensionsChanged(){if(this.drawBackground(),this.text){const t=this.clipConfiguration.asset;this.text.style.wordWrapWidth=this.getSize().width,this.positionText(t)}}applyFixedDimensions(){}createTextStyle(t){const i=t.font?.family??"Open Sans",{baseFontFamily:r,fontWeight:a}=pi(i),{width:s}=this.getSize();return new se.TextStyle({fontFamily:r,fontSize:t.font?.size??32,fill:t.font?.color??"#ffffff",fontWeight:a.toString(),wordWrap:!0,wordWrapWidth:s,lineHeight:(t.font?.lineHeight??1)*(t.font?.size??32),align:t.alignment?.horizontal??"center"})}positionText(t){if(!this.text)return;const i=t.alignment?.horizontal??"center",r=t.alignment?.vertical??"center",{width:a,height:s}=this.getSize();let n=a/2-this.text.width/2,o=s/2-this.text.height/2;i==="left"?n=0:i==="right"&&(n=a-this.text.width),r==="top"?o=0:r==="bottom"&&(o=s-this.text.height),this.text.position.set(n,o)}drawBackground(){const t=this.clipConfiguration.asset;if(!this.background||!t.background||!t.background.color)return;const{width:i,height:r}=this.getSize();this.background.clear(),this.background.fillStyle={color:t.background.color,alpha:t.background.opacity??1},this.background.rect(0,0,i,r),this.background.fill()}updateTextContent(t,i){this.edit.updateTextContent(this,t,i)}async loadFont(t){const{baseFontFamily:i,fontWeight:r}=pi(t),a=`${i}-${r}`;if(cr.loadedFonts.has(a))return;const s=Rs(t);if(s){const n=new FontFace(i,`url(${s})`,{weight:r.toString()});await n.load(),document.fonts.add(n),cr.loadedFonts.add(a)}}static resetFontCache(){cr.loadedFonts.clear()}}class JI extends Ot{aiOverlay=null;lastPrompt="";constructor(t,i){super(t,i,ht.TextToImage)}async load(){await super.load();const{width:t,height:i}=this.getSize(),r=this.edit.getResolvedEdit()?.timeline.tracks.flatMap(u=>u.clips)??[],a=Xc(r,this.clipId??""),{asset:s}=this.clipConfiguration,n=ya(s)&&s.prompt||"",o=ya(s)?s.type:"text-to-image";this.aiOverlay=new wu({mode:"panel",icon:"image",width:t,height:i,assetNumber:a??void 0,prompt:n,assetType:o}),this.contentContainer.addChild(this.aiOverlay.getContainer()),this.configureKeyframes()}update(t,i){super.update(t,i);const{width:r,height:a}=this.getSize();this.aiOverlay?.resize(r,a);const{asset:s}=this.clipConfiguration,n=ya(s)&&s.prompt||"";n!==this.lastPrompt&&(this.aiOverlay?.updatePrompt(n),this.lastPrompt=n)}getSize(){const t=this.clipConfiguration.asset;return{width:this.clipConfiguration.width??t.width??this.edit.size.width,height:this.clipConfiguration.height??t.height??this.edit.size.height}}dispose(){this.aiOverlay?.dispose(),this.aiOverlay=null,super.dispose()}}class qI extends Ot{constructor(t,i){super(t,i,ht.TextToSpeech)}async load(){await super.load(),this.configureKeyframes()}update(t,i){super.update(t,i),this.getContainer().alpha=0}getSize(){return{width:0,height:0}}}class QI extends Ot{texture;sprite;isPlaying;volumeKeyframeBuilder;syncTimer;activeSyncTimer;skipVideoUpdate;constructor(t,i){super(t,i,ht.Video),this.texture=null,this.sprite=null,this.isPlaying=!1;const r=this.clipConfiguration.asset;this.volumeKeyframeBuilder=new Ra(r.volume??1,this.getLength()),this.syncTimer=0,this.activeSyncTimer=0,this.skipVideoUpdate=!1}async load(){await super.load(),await this.loadVideo(),this.configureKeyframes()}update(t,i){if(super.update(t,i),this.skipVideoUpdate)return;const{trim:r=0}=this.clipConfiguration.asset;if(this.syncTimer+=i,!this.texture)return;const a=this.getPlaybackTime(),s=this.edit.isPlaying&&this.isActive();s&&(this.isPlaying||(this.isPlaying=!0,this.activeSyncTimer=0,this.texture.source.resource.volume=this.getVolume(),this.texture.source.resource.currentTime=a+r,this.texture.source.resource.play().catch(console.error)),this.texture.source.resource.volume!==this.getVolume()&&(this.texture.source.resource.volume=this.getVolume()),this.activeSyncTimer+=i,this.activeSyncTimer>1e3&&(this.activeSyncTimer=0,Math.abs(this.texture.source.resource.currentTime-r-a)>.3&&(this.texture.source.resource.currentTime=a+r))),!s&&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+r)}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}reconfigureAfterRestore(){super.reconfigureAfterRestore();const t=this.clipConfiguration.asset;this.volumeKeyframeBuilder=new Ra(t.volume??1,this.getLength())}async loadVideo(){const t=this.clipConfiguration.asset,{src:i}=t;if(i.endsWith(".mov"))throw new Error(`Video source '${i}' is not supported. .mov files cannot be played in the browser. Please convert to .webm or .mp4 first.`);const r=`${i}${i.includes("?")?"&":"?"}x-cors=1`,a={src:r,data:{autoPlay:!1,muted:!1}},s=await this.edit.assetLoader.loadVideoUnique(r,a);if(!s||!(s.source instanceof se.VideoSource))throw new Error(`Invalid video source '${i}'.`);s.source.alphaMode="no-premultiply-alpha",this.texture=this.createCroppedTexture(s);const n=this.texture.source.resource;n instanceof HTMLVideoElement&&n.readyState<2&&await new Promise(o=>{const u=()=>{n.removeEventListener("loadeddata",u),o()};n.addEventListener("loadeddata",u),n.readyState>=2&&o()}),this.sprite=new se.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.texture.source.resource.volume=this.getVolume()}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:t=0}=this.clipConfiguration.asset,i=this.texture.source.resource.currentTime,r=this.getPlaybackTime();return Math.abs(i-t-r)}createCroppedTexture(t){const i=this.clipConfiguration.asset;if(!i.crop)return t;const r=t.width,a=t.height;if(r<=0||a<=0)return t;const s=Math.floor((i.crop?.left??0)*r),n=Math.floor((i.crop?.right??0)*r),o=Math.floor((i.crop?.top??0)*a),u=Math.floor((i.crop?.bottom??0)*a),l=s,c=o,d=r-s-n,h=a-o-u,g=new se.Rectangle(l,c,d,h);return new se.Texture({source:t.source,frame:g})}}class Ub{static create(t,i){if(!i.asset?.type)throw new Error("Invalid clip configuration: missing asset type");switch(i.asset.type){case"text":return new cr(t,i);case"rich-text":return new Ii(t,i);case"shape":return new XI(t,i);case"html":return new Xv(t,i);case"image":return new Hv(t,i);case"video":return new QI(t,i);case"audio":return new Vv(t,i);case"luma":return new n3(t,i);case"caption":return new Us(t,i);case"svg":return new Gi(t,i);case"text-to-image":return new JI(t,i);case"image-to-video":return new s3(t,i);case"text-to-speech":return new qI(t,i);default:throw new Error(`Unsupported asset type: ${i.asset.type}`)}}static cleanup(){cr.resetFontCache()}}function Sc(e,t,i,r){const a=new Map,s=`alias://${i}`;for(let n=0;n<e.getTrackCount();n+=1){const o=e.getClipsInTrack(n);for(let u=0;u<o.length;u+=1)if(!r?.has(`${n}:${u}`)){const l=o[u],c=l.id,d=t.timeline.tracks[n]?.clips[u];let h=!1;const g={};if(l.start===s&&(g.start=l.start,h=!0),l.length===s&&(g.length=l.length,h=!0),h&&c&&d){a.set(c,g);const m={};g.start&&(m.start=d.start),g.length&&(m.length=d.length),e.updateClip(n,u,m)}}}return a}function eF(e,t,i,r){const a=new Map;for(const s of i){const n=Sc(e,t,s,r);for(const[o,u]of n){const l=a.get(o);l?a.set(o,{...l,...u}):a.set(o,u)}}return a}function Nc(e,t){for(const[i,r]of t){const a=e.getClipById(i);if(a){const s={};r.start&&(s.start=r.start),r.length&&(s.length=r.length),e.updateClip(a.trackIndex,a.clipIndex,s)}}}function tF(e){const t=[];for(const i of e){const{alias:r}=i;r&&t.push(r)}return t}const Ke=()=>({status:"success"}),vt=e=>({status:"noop",message:e});class iF{constructor(t,i){this.trackIdx=t,this.clip=i}name="addClip";addedClipId;convertedReferences;execute(t){if(!t)throw new Error("AddClipCommand.execute: context is required");const i=t.getDocument();if(!i)throw new Error("AddClipCommand.execute: no document");const r=t.documentAddClip(this.trackIdx,this.clip);this.addedClipId=r.id,this.convertedReferences&&this.convertedReferences.size>0&&Nc(i,this.convertedReferences),t.resolve(),t.updateDuration();const n=t.getDocumentTrack(this.trackIdx)?.clips?.findIndex(o=>o.id===this.addedClipId)??-1;return t.emitEvent(Ae.ClipAdded,{trackIndex:this.trackIdx,clipIndex:n}),Ke()}undo(t){if(!t)throw new Error("AddClipCommand.undo: context is required");if(!this.addedClipId)return vt("No clip ID stored");const i=t.getDocument();if(!i)throw new Error("AddClipCommand.undo: no document");const a=t.getDocumentTrack(this.trackIdx)?.clips,s=a?.findIndex(o=>o.id===this.addedClipId)??-1;if(s===-1)return vt(`Clip ${this.addedClipId} not found in track ${this.trackIdx}`);const n=a?.[s]?.alias;if(n){const o=new Set([`${this.trackIdx}:${s}`]);this.convertedReferences=Sc(i,t.getEditState(),n,o)}return t.documentRemoveClip(this.trackIdx,s),t.resolve(),t.updateDuration(),t.emitEvent(Ae.ClipDeleted,{trackIndex:this.trackIdx,clipIndex:s}),Ke()}dispose(){this.addedClipId=void 0,this.convertedReferences=void 0}}class aF{constructor(t){this.trackIdx=t}name="addTrack";execute(t){if(!t)throw new Error("AddTrackCommand.execute: context is required");const i=t.getDocument();if(!i)throw new Error("AddTrackCommand.execute: document is required");return i.addTrack(this.trackIdx),t.resolve(),t.updateDuration(),t.emitEvent(Ae.TrackAdded,{trackIndex:this.trackIdx,totalTracks:i.getTrackCount()}),Ke()}undo(t){if(!t)throw new Error("AddTrackCommand.undo: context is required");const i=t.getDocument();if(!i)throw new Error("AddTrackCommand.undo: document is required");return i.removeTrack(this.trackIdx),t.resolve(),t.updateDuration(),Ke()}dispose(){}}class Lb{constructor(t){this.trackIdx=t}name="deleteTrack";deletedClips=[];convertedReferences;execute(t){if(!t)throw new Error("DeleteTrackCommand.execute: context is required");const i=t.getDocument();if(!i)throw new Error("DeleteTrackCommand: no document");if(i.getTrackCount()<=1)return vt("Cannot delete the last track");const r=i.getTrack(this.trackIdx);r&&(this.deletedClips=r.clips.map(s=>structuredClone(s)));const a=tF(this.deletedClips);if(a.length>0){const s=new Set;for(let n=0;n<this.deletedClips.length;n+=1)s.add(`${this.trackIdx}:${n}`);this.convertedReferences=eF(i,t.getEditState(),a,s)}return i.removeTrack(this.trackIdx),t.resolve(),t.updateDuration(),t.emitEvent(Ae.TrackRemoved,{trackIndex:this.trackIdx}),Ke()}undo(t){if(!t)throw new Error("DeleteTrackCommand.undo: context is required");const i=t.getDocument();if(!i)throw new Error("DeleteTrackCommand.undo: no document");i.addTrack(this.trackIdx);for(let r=0;r<this.deletedClips.length;r+=1)i.addClip(this.trackIdx,this.deletedClips[r],r);return this.convertedReferences&&this.convertedReferences.size>0&&Nc(i,this.convertedReferences),t.resolve(),t.updateDuration(),t.emitEvent(Ae.TrackAdded,{trackIndex:this.trackIdx,totalTracks:i.getTrackCount()}),Ke()}dispose(){this.deletedClips=[],this.convertedReferences=void 0}}class Bc{constructor(t,i){this.trackIdx=t,this.clipIdx=i}name="deleteClip";deletedClipConfig;deletedClipId;deleteTrackCommand;trackWasDeleted=!1;storedBindings;convertedReferences;execute(t){if(!t)throw new Error("DeleteClipCommand.execute: context is required");const i=t.getDocument();if(!i)throw new Error("DeleteClipCommand: no document");const r=i.getClip(this.trackIdx,this.clipIdx);if(!r)return vt(`No clip at track ${this.trackIdx}, index ${this.clipIdx}`);if(i.getClipCount()<=1)return vt("Cannot delete the last clip");if(this.deletedClipConfig=structuredClone(r),this.deletedClipId=r.id,this.deletedClipId){const o=t.getClipBindings(this.deletedClipId);this.storedBindings=o?new Map(o):void 0,i.clearClipBindings(this.deletedClipId)}const a=r.alias;if(a){const o=new Set([`${this.trackIdx}:${this.clipIdx}`]);this.convertedReferences=Sc(i,t.getEditState(),a,o)}t.clearClipError(this.trackIdx,this.clipIdx);const s=t.getSelectedClip();s&&this.deletedClipId&&s.clipId===this.deletedClipId&&(t.setSelectedClip(null),t.emitEvent(Ae.SelectionCleared)),t.documentRemoveClip(this.trackIdx,this.clipIdx);const n=i.getTrack(this.trackIdx);return n&&n.clips.length===0&&(this.deleteTrackCommand=new Lb(this.trackIdx),this.deleteTrackCommand.execute(t).status==="success"&&(this.trackWasDeleted=!0)),t.resolve(),t.updateDuration(),t.emitEvent(Ae.ClipDeleted,{trackIndex:this.trackIdx,clipIndex:this.clipIdx}),Ke()}undo(t){if(!t)throw new Error("DeleteClipCommand.undo: context is required");if(!this.deletedClipConfig)return vt("No deleted clip config");const i=t.getDocument();if(!i)throw new Error("DeleteClipCommand.undo: no document");this.trackWasDeleted&&i.addTrack(this.trackIdx);const a=t.documentAddClip(this.trackIdx,this.deletedClipConfig,this.clipIdx).id;return a&&this.storedBindings&&this.storedBindings.size>0&&i.setClipBindingsForClip(a,this.storedBindings),this.convertedReferences&&this.convertedReferences.size>0&&Nc(i,this.convertedReferences),t.resolve(),t.updateDuration(),this.trackWasDeleted&&(t.emitEvent(Ae.TrackAdded,{trackIndex:this.trackIdx,totalTracks:i.getTrackCount()}),this.trackWasDeleted=!1),t.emitEvent(Ae.ClipRestored,{trackIndex:this.trackIdx,clipIndex:this.clipIdx}),Ke()}dispose(){this.deletedClipConfig=void 0,this.deletedClipId=void 0,this.deleteTrackCommand=void 0,this.storedBindings=void 0,this.convertedReferences=void 0}}class rF{constructor(t){this.aspectRatio=t}name="setOutputAspectRatio";previousAspectRatio;execute(t){if(!t)throw new Error("SetOutputAspectRatioCommand requires context");return this.previousAspectRatio=t.getOutputAspectRatio(),t.setOutputAspectRatio(this.aspectRatio),Ke()}undo(t){if(!t)throw new Error("SetOutputAspectRatioCommand requires context");return this.previousAspectRatio===void 0?vt("No previous aspect ratio stored"):(t.setOutputAspectRatio(this.previousAspectRatio),Ke())}dispose(){this.previousAspectRatio=void 0}}class sF{constructor(t){this.destinations=t}name="setOutputDestinations";previousDestinations;execute(t){if(!t)throw new Error("SetOutputDestinationsCommand requires context");return this.previousDestinations=t.getOutputDestinations(),t.setOutputDestinations(this.destinations),Ke()}undo(t){if(!t)throw new Error("SetOutputDestinationsCommand requires context");return this.previousDestinations===void 0?vt("No previous destinations stored"):(t.setOutputDestinations(this.previousDestinations),Ke())}dispose(){this.previousDestinations=void 0}}class nF{constructor(t){this.format=t}name="setOutputFormat";previousFormat;execute(t){if(!t)throw new Error("SetOutputFormatCommand requires context");return this.previousFormat=t.getOutputFormat(),t.setOutputFormat(this.format),Ke()}undo(t){if(!t)throw new Error("SetOutputFormatCommand requires context");return this.previousFormat===void 0?vt("No previous format stored"):(t.setOutputFormat(this.previousFormat),Ke())}dispose(){this.previousFormat=void 0}}class oF{constructor(t){this.fps=t}name="setOutputFps";previousFps;execute(t){if(!t)throw new Error("SetOutputFpsCommand requires context");return this.previousFps=t.getOutputFps(),t.setOutputFps(this.fps),Ke()}undo(t){if(!t)throw new Error("SetOutputFpsCommand requires context");return this.previousFps===void 0?vt("No previous FPS stored"):(t.setOutputFps(this.previousFps),Ke())}dispose(){this.previousFps=void 0}}class uF{constructor(t){this.resolution=t}name="setOutputResolution";previousResolution;execute(t){if(!t)throw new Error("SetOutputResolutionCommand requires context");return this.previousResolution=t.getOutputResolution(),t.setOutputResolution(this.resolution),Ke()}undo(t){if(!t)throw new Error("SetOutputResolutionCommand requires context");return this.previousResolution===void 0?vt("No previous resolution stored"):(t.setOutputResolution(this.previousResolution),Ke())}dispose(){this.previousResolution=void 0}}class lF{constructor(t,i){this.width=t,this.height=i}name="setOutputSize";previousSize;execute(t){if(!t)throw new Error("SetOutputSizeCommand requires context");return this.previousSize=t.getOutputSize(),t.setOutputSize(this.width,this.height),Ke()}undo(t){if(!t)throw new Error("SetOutputSizeCommand requires context");return this.previousSize?(t.setOutputSize(this.previousSize.width,this.previousSize.height),Ke()):vt("No previous size stored")}dispose(){this.previousSize=void 0}}class cF{constructor(t){this.color=t}name="setTimelineBackground";previousColor;execute(t){if(!t)throw new Error("SetTimelineBackgroundCommand requires context");return this.previousColor=t.getTimelineBackground(),t.setTimelineBackground(this.color),Ke()}undo(t){if(!t)throw new Error("SetTimelineBackgroundCommand requires context");return this.previousColor===void 0?vt("No previous color stored"):(t.setTimelineBackground(this.previousColor),Ke())}dispose(){this.previousColor=void 0}}function ri(e){const{id:t,...i}=e;return i}function Qo(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function Ic(e,t){const i={...e};return Qo(e)&&Qo(t)&&Object.keys(t).forEach(r=>{if(r==="__proto__"||r==="constructor"||r==="prototype")return;const a=t[r],s=e[r];Qo(a)?r in e&&Qo(s)?i[r]=Ic(s,a):i[r]=Ic({},a):i[r]=a}),i}function Wi(e,t,i){const r=t.split(".");let a=e;for(let s=0;s<r.length-1;s+=1){if(a==null||typeof a!="object")return;const n=r[s],o=a[n];(o==null||typeof o!="object")&&(a[n]={}),a=a[n]}a!=null&&typeof a=="object"&&(a[r[r.length-1]]=i)}function eu(e,t){const i=t.split(".");let r=e;for(const a of i){if(r==null||typeof r!="object")return;r=r[a]}return r}class Fc{constructor(t,i,r){this.initialClipConfig=t,this.finalClipConfig=i,this.trackIndex=r?.trackIndex??-1,this.clipIndex=r?.clipIndex??-1}name="setUpdatedClip";clipId=null;storedInitialConfig=null;storedFinalConfig=null;storedInitialBindings=new Map;previousDocClip=null;trackIndex;clipIndex;async execute(t){if(!t)throw new Error("SetUpdatedClipCommand.execute: context is required");const i=t.getDocument();if(!i)throw new Error("SetUpdatedClipCommand.execute: document is required");const r=t.getClipAt(this.trackIndex,this.clipIndex);if(!r)return vt(`Invalid clip at ${this.trackIndex}/${this.clipIndex}`);this.clipId=r.clipId,this.storedInitialConfig||(this.storedInitialConfig=this.initialClipConfig?structuredClone(this.initialClipConfig):structuredClone(r.clipConfiguration)),this.storedFinalConfig||(this.storedFinalConfig=this.finalClipConfig?structuredClone(this.finalClipConfig):structuredClone(r.clipConfiguration));const a=t.getDocumentClip(this.trackIndex>=0?this.trackIndex:r.layer-1,this.clipIndex>=0?this.clipIndex:t.getTracks()[r.layer-1]?.indexOf(r)??-1);this.previousDocClip=a?structuredClone(a):null;const s=this.clipId?t.getClipBindings(this.clipId):void 0;this.storedInitialBindings=s?new Map(s):new Map;const n=this.trackIndex>=0?this.trackIndex:r.layer-1,o=this.clipIndex>=0?this.clipIndex:t.getTracks()[n]?.indexOf(r)??-1,u=this.storedFinalConfig??this.finalClipConfig;u&&i.replaceClipProperties(n,o,u),t.resolve();const l=t.getClipAt(n,o);for(const[v,{resolvedValue:_}]of this.storedInitialBindings)(l?eu(l.clipConfiguration,v):void 0)!==_&&this.clipId&&t.removeClipBinding(this.clipId,v);const c=this.storedInitialConfig??this.initialClipConfig,d=this.storedFinalConfig??this.finalClipConfig,h=c?.asset,g=d?.asset;if(h?.src!==g?.src){const v=t.getClipAt(n,o);v&&v.getTimingIntent().length==="auto"&&await t.resolveClipAutoLength(v)}const m=t.getDocumentClip(n,o);if(!this.previousDocClip||!m)throw new Error(`SetUpdatedClipCommand: document clip not found after mutation at ${n}/${o}`);return t.emitEvent(Ae.ClipUpdated,{previous:{clip:ri(this.previousDocClip),trackIndex:n,clipIndex:o},current:{clip:ri(m),trackIndex:n,clipIndex:o}}),Ke()}async undo(t){if(!t)throw new Error("SetUpdatedClipCommand.undo: context is required");const i=this.storedInitialConfig??this.initialClipConfig;if(!i)return vt("No stored initial config");const r=t.getDocument();if(!r)throw new Error("SetUpdatedClipCommand.undo: document is required");const a=this.clipId?t.getPlayerByClipId(this.clipId):t.getClipAt(this.trackIndex,this.clipIndex);if(!a)return vt("Clip not found for undo");const s=this.trackIndex>=0?this.trackIndex:a.layer-1,n=this.clipIndex>=0?this.clipIndex:t.getTracks()[s]?.indexOf(a)??-1,o=structuredClone(t.getDocumentClip(s,n));if(r.replaceClipProperties(s,n,i),t.resolve(),this.clipId){const h=new Map(this.storedInitialBindings);h.size>0?t.getDocument()?.setClipBindingsForClip(this.clipId,h):t.getDocument()?.clearClipBindings(this.clipId)}const l=(this.storedFinalConfig??this.finalClipConfig)?.asset,c=i?.asset;if(l?.src!==c?.src){const h=t.getClipAt(s,n);h&&h.getTimingIntent().length==="auto"&&await t.resolveClipAutoLength(h)}const d=t.getDocumentClip(s,n);if(!o||!d)throw new Error(`SetUpdatedClipCommand: document clip not found after undo at ${s}/${n}`);return t.emitEvent(Ae.ClipUpdated,{previous:{clip:ri(o),trackIndex:s,clipIndex:n},current:{clip:ri(d),trackIndex:s,clipIndex:n}}),Ke()}dispose(){this.clipId=null,this.storedInitialConfig=null,this.storedFinalConfig=null,this.storedInitialBindings.clear(),this.previousDocClip=null}}class fF{constructor(t,i,r){this.trackIndex=t,this.clipIndex=i,this.params=r}name="UpdateClipTiming";originalStart;originalLength;clipId;execute(t){if(!t)throw new Error("UpdateClipTimingCommand.execute: context is required");const i=t.getDocument();if(!i)throw new Error("UpdateClipTimingCommand.execute: document is required");const a=t.getDocumentTrack(this.trackIndex)?.clips[this.clipIndex];if(!a)return vt(`Invalid clip at ${this.trackIndex}/${this.clipIndex}`);const s=t.getClipAt(this.trackIndex,this.clipIndex);if(!s)return vt(`Player not found at ${this.trackIndex}/${this.clipIndex}`);this.originalStart=a.start,this.originalLength=a.length,this.clipId=s.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),i.updateClip(this.trackIndex,this.clipIndex,o),this.clipId?t.resolveClip(this.clipId):t.resolve(),o.length==="auto"&&t.resolveClipAutoLength(s).then(()=>{t.updateDuration(),t.propagateTimingChanges(this.trackIndex,this.clipIndex)}),t.updateDuration();const u=t.getDocumentClip(this.trackIndex,this.clipIndex);if(!u)throw new Error(`UpdateClipTimingCommand: document clip not found after mutation at ${this.trackIndex}/${this.clipIndex}`);return t.emitEvent(Ae.ClipUpdated,{previous:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:ri(n)},current:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:ri(u)}}),t.propagateTimingChanges(this.trackIndex,this.clipIndex),Ke()}undo(t){if(!t)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 i=t.getDocument();if(!i)throw new Error("UpdateClipTimingCommand.undo: document is required");const r=t.getClipAt(this.trackIndex,this.clipIndex);if(!r)throw new Error("UpdateClipTimingCommand.undo: player not found");const a=structuredClone(t.getDocumentClip(this.trackIndex,this.clipIndex)),s={};this.originalStart!==void 0&&(s.start=this.originalStart),this.originalLength!==void 0&&(s.length=this.originalLength),i.updateClip(this.trackIndex,this.clipIndex,s),this.clipId?t.resolveClip(this.clipId):t.resolve(),this.originalLength==="auto"&&t.resolveClipAutoLength(r).then(()=>{t.updateDuration(),t.propagateTimingChanges(this.trackIndex,this.clipIndex)}),t.updateDuration();const n=t.getDocumentClip(this.trackIndex,this.clipIndex);if(!a||!n)throw new Error(`UpdateClipTimingCommand: document clip not found after undo at ${this.trackIndex}/${this.clipIndex}`);return t.emitEvent(Ae.ClipUpdated,{previous:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:ri(a)},current:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:ri(n)}}),t.propagateTimingChanges(this.trackIndex,this.clipIndex),Ke()}}class dF{constructor(t,i,r){this.trackIndex=t,this.clipIndex=i,this.newText=r}name="updateTextContent";clipId=null;previousText="";previousDocClip;execute(t){if(!t)throw new Error("UpdateTextContentCommand.execute: context is required");const i=t.getDocument();if(!i)throw new Error("UpdateTextContentCommand.execute: document is required");const r=t.getClipAt(this.trackIndex,this.clipIndex);if(!r)return vt(`Invalid clip at ${this.trackIndex}/${this.clipIndex}`);const a=i.getClip(this.trackIndex,this.clipIndex);if(!a)return vt("Clip not found in document");this.clipId=r.clipId,this.previousDocClip=structuredClone(a);const s=a.asset;this.previousText=s&&"text"in s?s.text??"":"";const o={...a.asset,text:this.newText};i.updateClip(this.trackIndex,this.clipIndex,{asset:o}),this.clipId?t.resolveClip(this.clipId):t.resolve();const u=t.getDocumentClip(this.trackIndex,this.clipIndex);if(!this.previousDocClip||!u)throw new Error(`UpdateTextContentCommand: document clip not found after mutation at ${this.trackIndex}/${this.clipIndex}`);return t.emitEvent(Ae.ClipUpdated,{previous:{clip:ri(this.previousDocClip),trackIndex:this.trackIndex,clipIndex:this.clipIndex},current:{clip:ri(u),trackIndex:this.trackIndex,clipIndex:this.clipIndex}}),Ke()}undo(t){if(!t)throw new Error("UpdateTextContentCommand.undo: context is required");const i=t.getDocument();if(!i)throw new Error("UpdateTextContentCommand.undo: document is required");const r=structuredClone(t.getDocumentClip(this.trackIndex,this.clipIndex)),a=i.getClip(this.trackIndex,this.clipIndex);if(!a)return vt("Clip not found for undo");const n={...a.asset,text:this.previousText};i.updateClip(this.trackIndex,this.clipIndex,{asset:n}),this.clipId?t.resolveClip(this.clipId):t.resolve();const o=t.getDocumentClip(this.trackIndex,this.clipIndex);if(this.previousDocClip){if(!r||!o)throw new Error(`UpdateTextContentCommand: document clip not found after undo at ${this.trackIndex}/${this.clipIndex}`);t.emitEvent(Ae.ClipUpdated,{previous:{clip:ri(r),trackIndex:this.trackIndex,clipIndex:this.clipIndex},current:{clip:ri(o),trackIndex:this.trackIndex,clipIndex:this.clipIndex}})}return Ke()}dispose(){this.clipId=null,this.previousDocClip=void 0}}class jb{events;constructor(){this.events={}}on(t,i){return this.events[t]||(this.events[t]=new Set),this.events[t].add(i),()=>this.off(t,i)}once(t,i){const r=a=>{this.off(t,r),i(a)};return this.on(t,r)}off(t,i){this.events[t]&&(this.events[t].delete(i),!(this.events[t].size>0)&&delete this.events[t])}clear(t){delete this.events[t]}emit(t,...i){if(!this.events[t])return;const r=i[0];for(const a of this.events[t])a(r)}}const Gb=.5,hF=1/30;class gF{constructor(t,i,r){this.getCanvas=t,this.getTracks=i,this.events=r,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 t of this.activeLumaMasks)t.tempContainer.destroy({children:!0}),t.maskSprite.destroy({texture:!0});this.activeLumaMasks=[];for(const t of this.pendingMaskCleanup)try{t.maskSprite.parent?.removeChild(t.maskSprite),t.maskSprite.destroy({texture:!0})}catch{}this.pendingMaskCleanup=[]}cleanupForPlayer(t){const i=this.activeLumaMasks.findIndex(a=>a.lumaPlayer===t);if(i===-1)return;const r=this.activeLumaMasks[i];r.contentClip&&(r.contentClip.getLumaWrapper().mask=null),r.maskSprite.parent?.removeChild(r.maskSprite),r.tempContainer.destroy({children:!0}),this.activeLumaMasks.splice(i,1),this.pendingMaskCleanup.push({maskSprite:r.maskSprite,frameCount:0})}onPlayerLoaded(t){const{player:i,trackIndex:r}=t;if(i.playerType!==ht.Luma)return;const a=i,s=a.getSprite();if(!s?.texture){console.warn("PlayerLoaded fired for luma player before texture ready");return}const n=this.getTracks();if(r>=n.length)return;const u=n[r].filter(c=>c.playerType!==ht.Luma);u.length===0||this.activeLumaMasks.find(c=>c.lumaPlayer===a)||(this.setupLumaMask(a,s.texture,u[0]),a.getContainer().parent?.removeChild(a.getContainer()))}setupLumaMask(t,i,r){const a=this.getCanvas();if(!a)return;const{renderer:s}=a.application,{width:n,height:o}=r.getSize(),u=new se.Container,l=new se.Sprite(i);l.width=n,l.height=o;const c=new se.ColorMatrixFilter;c.negative(!1),l.filters=[c],u.addChild(l);const d=s.generateTexture({target:u,resolution:Gb}),h=new se.Sprite(d);r.getContainer().addChild(h);const g=r.getLumaWrapper();g.mask=h,this.activeLumaMasks.push({lumaPlayer:t,maskSprite:h,tempContainer:u,contentClip:r,lastVideoTime:-1})}updateLumaMasks(){const t=this.getCanvas();if(!t)return;const{renderer:i}=t.application;for(const r of this.activeLumaMasks)if(r.lumaPlayer.isVideoSource()){const a=r.lumaPlayer.getVideoCurrentTime();if(Math.abs(a-r.lastVideoTime)>=hF){r.lastVideoTime=a;const n=r.maskSprite.texture;r.maskSprite.texture=i.generateTexture({target:r.tempContainer,resolution:Gb}),n.destroy(!0)}}}setupEventListeners(){this.events.on(yt.PlayerLoaded,this.onPlayerLoadedBound),this.events.on(Ae.ClipUpdated,this.onClipChangedBound),this.events.on(yt.PlayerMovedBetweenTracks,this.onClipChangedBound)}removeEventListeners(){this.events.off(yt.PlayerLoaded,this.onPlayerLoadedBound),this.events.off(Ae.ClipUpdated,this.onClipChangedBound),this.events.off(yt.PlayerMovedBetweenTracks,this.onClipChangedBound)}processPendingMaskCleanup(){for(let t=this.pendingMaskCleanup.length-1;t>=0;t-=1){const i=this.pendingMaskCleanup[t];if(i.frameCount+=1,i.frameCount>=3){try{i.maskSprite.parent?.removeChild(i.maskSprite),i.maskSprite.destroy({texture:!0})}catch{}this.pendingMaskCleanup.splice(t,1)}}}rebuildLumaMasksIfNeeded(){if(!this.getCanvas())return;const i=this.getTracks();for(let r=0;r<i.length;r+=1){const a=i[r],s=a.find(u=>u.playerType===ht.Luma),n=a.filter(u=>u.playerType!==ht.Luma);s&&s.getContainer().parent?.removeChild(s.getContainer());const o=s&&this.activeLumaMasks.find(u=>u.lumaPlayer===s);if(s&&!o&&n.length>0){const u=s.getSprite();u?.texture&&this.setupLumaMask(s,u.texture,n[0])}}}}function pF(e){return{find:e.name,replace:e.defaultValue}}function mF(e){const t=typeof e.replace=="string"?e.replace:JSON.stringify(e.replace);return{name:e.find,defaultValue:t}}const yF=/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi,Vc=/\{\{\s*[A-Z_0-9]+\s*\}\}/i;class bF{fields=new Map;events;constructor(t){this.events=t}register(t,i){this.fields.set(t.name,t),i?.silent||this.events.emit(Ae.MergeFieldChanged,{fields:this.getAll()})}remove(t,i){const r=this.fields.delete(t);return r&&!i?.silent&&this.events.emit(Ae.MergeFieldChanged,{fields:this.getAll()}),r}get(t){return this.fields.get(t)}getAll(){return Array.from(this.fields.values())}clear(){this.fields.clear()}resolve(t){return!t||this.fields.size===0?t:t.replace(yF,(i,r)=>this.fields.get(r)?.defaultValue??i)}resolveToNumber(t){if(!this.isMergeFieldTemplate(t))return null;const i=this.resolve(t),r=parseFloat(i);return Number.isFinite(r)?r:null}hasUnresolved(t){if(!t)return!1;const i=this.resolve(t);return Vc.test(i)}extractFieldName(t){if(!t)return null;const i=Vc.exec(t);if(!i)return null;const r=i[0].match(/\{\{\s*([A-Z_0-9]+)\s*\}\}/i);return r?r[1]:null}isMergeFieldTemplate(t){return Vc.test(t)}createTemplate(t){return`{{ ${t} }}`}toSerializedArray(){return this.getAll().map(pF)}loadFromSerialized(t){this.fields.clear();for(const i of t){const r=mF(i);this.fields.set(i.find,r)}}generateUniqueName(t){const i=new Set(this.fields.keys());let r=1;for(;i.has(`${t}_${r}`);)r+=1;return`${t}_${r}`}}const vF={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 tu(e,t="16:9"){const i=vF[e];if(!i)throw new Error(`Unknown resolution: ${e}`);switch(t){case"16:9":return{width:i.width,height:i.height};case"9:16":return{width:i.height,height:i.width};case"1:1":return{width:i.height,height:i.height};case"4:5":return{width:Math.round(i.height*4/5),height:i.height};case"4:3":return{width:Math.round(i.height*4/3),height:i.height};default:throw new Error(`Unknown aspectRatio: ${t}`)}}class wF{constructor(t){this.edit=t}setSize(t,i){CE.parse({width:t,height:i});const r={width:t,height:i};this.edit.size=r;const a=this.edit.getResolvedEdit();a&&(a.output={...a.output,size:r},delete a.output.resolution,delete a.output.aspectRatio);const s=this.edit.getDocument();s?.setSize(r),s?.clearResolution(),s?.clearAspectRatio(),this.edit.updateCanvasForSize(),this.edit.getInternalEvents().emit(Ae.OutputResized,r)}getSize(){return this.edit.size}setFps(t){const i=EE.parse(t),r=this.edit.getResolvedEdit();r&&(r.output={...r.output,fps:i}),this.edit.getDocument()?.setFps(i),this.edit.getInternalEvents().emit(Ae.OutputFpsChanged,{fps:t})}getFps(){return this.edit.getResolvedEdit()?.output?.fps??30}setFormat(t){const i=xE.parse(t),r=this.edit.getResolvedEdit();r&&(r.output={...r.output,format:i}),this.edit.getDocument()?.setFormat(i),this.edit.getInternalEvents().emit(Ae.OutputFormatChanged,{format:i})}getFormat(){return this.edit.getResolvedEdit()?.output?.format??"mp4"}setDestinations(t){const i=wE.array().parse(t),r=this.edit.getResolvedEdit();r&&(r.output={...r.output,destinations:i}),this.edit.getInternalEvents().emit(Ae.OutputDestinationsChanged,{destinations:i})}getDestinations(){return this.edit.getResolvedEdit()?.output?.destinations??[]}setResolution(t){const i=AE.parse(t),r=this.edit.getResolvedEdit(),a=r?.output?.aspectRatio??"16:9",s=tu(i,a);this.edit.size=s,r&&(r.output={...r.output,resolution:i},delete r.output.size);const n=this.edit.getDocument();n?.setResolution(i),n?.clearSize(),this.edit.updateCanvasForSize(),this.edit.getInternalEvents().emit(Ae.OutputResolutionChanged,{resolution:i}),this.edit.getInternalEvents().emit(Ae.OutputResized,{width:s.width,height:s.height})}getResolution(){return this.edit.getResolvedEdit()?.output?.resolution}setAspectRatio(t){const i=kE.parse(t),r=this.edit.getResolvedEdit(),a=r?.output?.resolution;if(!a){r&&(r.output={...r.output,aspectRatio:i}),this.edit.getDocument()?.setAspectRatio(i),this.edit.getInternalEvents().emit(Ae.OutputAspectRatioChanged,{aspectRatio:i});return}const s=tu(a,i);this.edit.size=s,r&&(r.output={...r.output,aspectRatio:i},delete r.output.size);const n=this.edit.getDocument();n?.setAspectRatio(i),n?.clearSize(),this.edit.updateCanvasForSize(),this.edit.getInternalEvents().emit(Ae.OutputAspectRatioChanged,{aspectRatio:i}),this.edit.getInternalEvents().emit(Ae.OutputResized,{width:s.width,height:s.height})}getAspectRatio(){return this.edit.getResolvedEdit()?.output?.aspectRatio}}class CF{constructor(t){this.edit=t}selectedClip=null;copiedClip=null;selectClip(t,i){const r=this.edit.getPlayerClip(t,i);if(r){this.selectedClip=r;const a=this.edit.getDocumentClip(t,i);a&&this.edit.getInternalEvents().emit(Ae.ClipSelected,{clip:ri(a),trackIndex:t,clipIndex:i})}}selectPlayer(t){const i=this.findClipIndices(t);i&&this.selectClip(i.trackIndex,i.clipIndex)}clearSelection(){this.selectedClip=null,this.edit.getInternalEvents().emit(Ae.SelectionCleared)}isClipSelected(t,i){if(!this.selectedClip)return!1;const r=this.selectedClip.layer-1,s=this.edit.getTracks()[r];if(!s)return!1;const n=s.indexOf(this.selectedClip);return t===r&&i===n}isPlayerSelected(t){return this.edit.isInExportMode()?!1:this.selectedClip===t}getSelectedClipInfo(){if(!this.selectedClip)return null;const t=this.selectedClip.layer-1,r=this.edit.getTracks()[t];if(!r)return null;const a=r.indexOf(this.selectedClip);return{trackIndex:t,clipIndex:a,player:this.selectedClip}}getSelectedClip(){return this.selectedClip}setSelectedClip(t){this.selectedClip=t}copyClip(t,i){const r=this.edit.getResolvedClip(t,i);r&&(this.copiedClip={trackIndex:t,clipConfiguration:structuredClone(r)},this.edit.getInternalEvents().emit(Ae.ClipCopied,{trackIndex:t,clipIndex:i}))}pasteClip(){if(!this.copiedClip)return;const t=structuredClone(this.copiedClip.clipConfiguration);t.start=this.edit.playbackTime,delete t.id,this.edit.addClip(this.copiedClip.trackIndex,t)}hasCopiedClip(){return this.copiedClip!==null}findClipIndices(t){const i=this.edit.getTracks();for(let r=0;r<i.length;r+=1){const a=i[r].indexOf(t);if(a!==-1)return{trackIndex:r,clipIndex:a}}return null}}const xF=3;function EF(e){return new Promise(t=>{const i=document.createElement("video");i.preload="metadata",i.crossOrigin="anonymous",i.onloadedmetadata=()=>t(i.duration),i.onerror=()=>t(null),i.src=e})}async function Wb(e){const t=e;if(["video","audio","luma"].includes(t.type)&&t.src){const i=await EF(t.src);if(i!==null&&!Number.isNaN(i)){const r=t.trim??0;return i-r}}return xF}function Yb(e,t,i){return t===0?0:i[e][t-1].getEnd()}function Kb(e,t){return Math.max(0,t-e)}function zc(e){let t=0;for(const i of e)for(const r of i)r.getTimingIntent().length!=="end"&&(t=Math.max(t,r.getEnd()));return t}class AF{constructor(t){this.edit=t}cachedTimelineEnd=0;getTimelineEnd(){return this.cachedTimelineEnd}invalidateTimelineEndCache(){this.cachedTimelineEnd=0}async resolveAllTiming(){const t=this.edit.getTracks(),i=this.edit.getResolvedEdit();for(let s=0;s<t.length;s+=1){const n=t[s],o=i.timeline.tracks[s];for(let u=0;u<n.length;u+=1){const l=n[u],c=o?.clips[u];if(c){const d=l.getTimingIntent(),h=c.start;let g=c.length;d.length==="auto"&&(g=await Wb(l.clipConfiguration.asset)),l.setResolvedTiming({start:h,length:g})}}}const r=zc(t);this.cachedTimelineEnd=r;const a=this.getEndLengthClips();for(const s of a){const n=s.getResolvedTiming();s.setResolvedTiming({start:n.start,length:Kb(n.start,r)})}for(const s of a)s.reconfigureAfterRestore()}propagateTimingChanges(t,i){const r=this.edit.getTracks(),a=r[t];if(!a)return;for(let n=Math.max(0,i);n<a.length;n+=1){const o=a[n];if(o.getTimingIntent().start==="auto"){const u=Yb(t,n,r);o.setResolvedTiming({start:u,length:o.getLength()}),o.reconfigureAfterRestore()}}this.propagateAliasChanges();const s=zc(r);if(s!==this.cachedTimelineEnd){this.cachedTimelineEnd=s;const n=this.getEndLengthClips();for(const o of n){const u=Kb(o.getStart(),s),l=o.getLength();Math.abs(u-l)>.001&&(o.setResolvedTiming({start:o.getStart(),length:u}),o.reconfigureAfterRestore())}}this.edit.updateTotalDuration(),this.edit.getInternalEvents().emit(Ae.TimelineUpdated,{current:this.edit.getEdit()})}propagateAliasChanges(){const t=this.edit.getTracks(),i=this.edit.getResolvedEdit();for(let r=0;r<t.length;r+=1){const a=t[r],s=i.timeline.tracks[r];for(let n=0;n<a.length;n+=1){const o=a[n],u=s?.clips[n],l=o.getTimingIntent(),c=gi(l.start),d=gi(l.length);if((c||d)&&u){const h=o.getStart(),g=o.getLength(),m=Math.abs(u.start-h)>.001,v=Math.abs(u.length-g)>.001;(m||v)&&(o.setResolvedTiming({start:u.start,length:u.length}),o.reconfigureAfterRestore())}}}}getEndLengthClips(){const t=this.edit.getTracks(),i=[];for(const r of t)for(const a of r)a.getTimingIntent().length==="end"&&i.push(a);return i}}class kF extends jb{registry;constructor(){super(),this.registry={}}}class iu{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 kF;refCounts=new Map;incrementRef(t){this.refCounts.set(t,(this.refCounts.get(t)??0)+1)}decrementRef(t){const i=this.refCounts.get(t)??0;return i<=1?(this.refCounts.delete(t),!0):(this.refCounts.set(t,i-1),!1)}constructor(){se.Assets.setPreferences({crossOrigin:"anonymous"})}async load(t,i){this.updateAssetLoadMetadata(t,"pending",0),this.incrementRef(t);try{if(await this.shouldUseSafariVideoLoader(i))return await this.loadVideoForSafari(t,i);const a=await se.Assets.load(i,s=>{this.updateAssetLoadMetadata(t,"loading",s)});return this.updateAssetLoadMetadata(t,"success",1),a}catch(r){return console.warn(`[AssetLoader] Failed to load asset "${t}":`,r),this.updateAssetLoadMetadata(t,"failed",1),this.decrementRef(t),null}}async loadVideoUnique(t,i){this.updateAssetLoadMetadata(t,"pending",0);try{const r=this.extractUrl(i);if(!r)throw new Error("No URL provided for video loading");const a=typeof i=="object"?i.data??{}:{},s=await new Promise((n,o)=>{const u=document.createElement("video");u.crossOrigin="anonymous",u.playsInline=!0,u.muted=a.muted??!1,u.preload="auto",u.addEventListener("loadedmetadata",()=>{try{const l=new se.VideoSource({resource:u,autoPlay:a.autoPlay??!1,...a});n(new se.Texture({source:l}))}catch(l){o(l)}},{once:!0}),u.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(t,"loading",.5),u.src=r});return this.updateAssetLoadMetadata(t,"success",1),s}catch{return this.updateAssetLoadMetadata(t,"failed",1),null}}getProgress(){const t=Object.keys(this.loadTracker.registry);return t.length===0?0:t.reduce((r,a)=>r+this.loadTracker.registry[a].progress,0)/t.length}extractUrl(t){if(typeof t=="string")return t;const i=Array.isArray(t.src)?t.src[0]:t.src;return typeof i=="string"?i:i?.src}hasVideoExtension(t){const i=new URL(t,window.location.origin).pathname.toLowerCase();return iu.VIDEO_EXTENSIONS.some(r=>i.endsWith(r))}async getContentType(t){try{return(await fetch(t,{method:"HEAD"})).headers.get("content-type")}catch{return null}}canPlayVideo(t){const i=new URL(t,window.location.origin).pathname.toLowerCase(),r=i.slice(i.lastIndexOf(".")),a=iu.VIDEO_MIME[r];return a?document.createElement("video").canPlayType(a)!=="":!1}async isPlayableVideo(t){if(this.hasVideoExtension(t))return this.canPlayVideo(t);const i=await this.getContentType(t);return i?.startsWith("video/")?document.createElement("video").canPlayType(i)!=="":!1}async shouldUseSafariVideoLoader(t){const i=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),r=this.extractUrl(t);return i&&r!==void 0&&await this.isPlayableVideo(r)}async loadVideoForSafari(t,i){const r=this.extractUrl(i),a=typeof i=="object"?i.data??{}:{},s=await new Promise((n,o)=>{const u=document.createElement("video");u.crossOrigin="anonymous",u.playsInline=!0,u.muted=!0,u.preload="metadata",u.addEventListener("loadedmetadata",()=>{try{const l=new se.VideoSource({resource:u,autoPlay:a.autoPlay??!1,...a});n(new se.Texture({source:l}))}catch(l){o(l)}},{once:!0}),u.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(t,"loading",.5),u.src=r});return this.updateAssetLoadMetadata(t,"success",1),s}updateAssetLoadMetadata(t,i,r){this.loadTracker.registry[t]?(this.loadTracker.registry[t].progress=r,this.loadTracker.registry[t].status=i):this.loadTracker.registry[t]={progress:r,status:i};const a={...this.loadTracker.registry};this.loadTracker.emit("onAssetLoadInfoUpdated",{registry:a})}}class au{static Name="FontLoadParser";id;name;extension;validFontExtensions;woff2Decompressor;constructor(){this.id=au.Name,this.name=au.Name,this.extension={type:[se.ExtensionType.LoadParser],priority:se.LoaderParserPriority.High,ref:null},this.validFontExtensions=["ttf","otf","woff","woff2"],this.woff2Decompressor=null}test(t){const i=t.split("?")[0]?.split(".").pop()?.toLowerCase()??"";return this.validFontExtensions.includes(i)}async load(t,i,r){const a=t.split("?")[0]?.split(".").pop()?.toLowerCase()??"",s=await fetch(t).then(h=>h.arrayBuffer());if(a!=="woff2"){const h=yu.parse(new Uint8Array(s).buffer),g=h.names.fontFamily.en||h.names.fontFamily[Object.keys(h.names.fontFamily)[0]],m=new FontFace(g,`url(${t})`);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(s),o=yu.parse(new Uint8Array(n).buffer),u=o.names.fontFamily.en||o.names.fontFamily[Object.keys(o.names.fontFamily)[0]],l=new Blob([n],{type:"font/ttf"}),c=URL.createObjectURL(l),d=new FontFace(u,`url(${c})`);return await d.load(),document.fonts.add(d),d}async loadWoff2Decompressor(){if(this.woff2Decompressor)return;const i=`${await fetch("https://unpkg.com/wawoff2@2.0.1/build/decompress_binding.js").then(r=>r.text())}; return Module`;this.woff2Decompressor=new Function(i)(),await new Promise(r=>{this.woff2Decompressor.onRuntimeInitialized=r})}unload(t){t&&document.fonts.delete(t)}}function DF(e,t,i,r){const a=Math.max(e,i),s=Math.min(t,r);return Math.max(0,s-a)}class _F{queue=[];isProcessing=!1;async enqueue(t){return new Promise((i,r)=>{this.queue.push(async()=>{try{const a=await t();i(a)}catch(a){r(a)}}),this.processQueue()})}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;){const t=this.queue.shift();if(t)try{await t()}catch{}}this.isProcessing=!1}}}class fr{data;clipBindings=new Map;constructor(t){this.data=structuredClone(t),this.hydrateIds()}hydrateIds(){const t=new Set;for(const i of this.data.timeline.tracks)for(let r=0;r<i.clips.length;r+=1){const a=i.clips[r];if(t.has(a)){const s=structuredClone(a);s.id=crypto.randomUUID(),i.clips[r]=s}else t.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(t){return this.data.timeline.tracks[t]??null}getTrackCount(){return this.data.timeline.tracks.length}getSoundtrack(){return this.data.timeline.soundtrack}getClip(t,i){const r=this.data.timeline.tracks[t];return r?r.clips[i]??null:null}getClipsInTrack(t){return this.data.timeline.tracks[t]?.clips??[]}getClipCount(){return this.data.timeline.tracks.reduce((t,i)=>t+i.clips.length,0)}getClipCountInTrack(t){return this.data.timeline.tracks[t]?.clips.length??0}getClipById(t){for(let i=0;i<this.data.timeline.tracks.length;i+=1){const r=this.data.timeline.tracks[i].clips;for(let a=0;a<r.length;a+=1)if(r[a].id===t)return{clip:r[a],trackIndex:i,clipIndex:a}}return null}updateClipById(t,i){const r=this.getClipById(t);r&&Object.assign(r.clip,i)}removeClipById(t){const i=this.getClipById(t);return i?this.removeClip(i.trackIndex,i.clipIndex):null}getClipId(t,i){return this.getClip(t,i)?.id??null}getOutput(){return this.data.output}getSize(){const{size:t}=this.data.output;if(!t?.width||!t?.height)throw new Error("Output size is not defined");return{width:t.width,height:t.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(t,i){const r=i??{clips:[]};return this.data.timeline.tracks.splice(t,0,r),r}removeTrack(t){if(t<0||t>=this.data.timeline.tracks.length)return null;if(this.data.timeline.tracks.length<=1)return console.warn("Cannot remove the last track"),null;const[i]=this.data.timeline.tracks.splice(t,1);return i??null}addClip(t,i,r){const a=this.data.timeline.tracks[t];if(!a)throw new Error(`Track ${t} does not exist`);const s=i;s.id||(s.id=crypto.randomUUID());const n=r??a.clips.length;return a.clips.splice(n,0,i),i}removeClip(t,i){const r=this.data.timeline.tracks[t];if(!r||i<0||i>=r.clips.length)return null;const[a]=r.clips.splice(i,1);return a??null}updateClip(t,i,r){const a=this.getClip(t,i);if(!a)throw new Error(`Clip at track ${t}, index ${i} does not exist`);Object.assign(a,r)}replaceClipProperties(t,i,r){const a=this.getClip(t,i);if(!a)throw new Error(`Clip at track ${t}, index ${i} does not exist`);const{id:s}=a;for(const n of Object.keys(a))n!=="id"&&delete a[n];Object.assign(a,r),s&&(a.id=s)}replaceClip(t,i,r){const a=this.data.timeline.tracks[t];if(!a||i<0||i>=a.clips.length)return null;const s=a.clips[i];return a.clips[i]=r,s}moveClip(t,i,r,a){const s=this.data.timeline.tracks[t];if(!s||i<0||i>=s.clips.length)return null;const n=this.data.timeline.tracks[r];if(!n)return null;const[o]=s.clips.splice(i,1);if(!o)return null;a&&Object.assign(o,a);const u=typeof o.start=="number"?o.start:0;let l=0;for(let c=0;c<n.clips.length;c+=1){const d=n.clips[c].start;if(u<(typeof d=="number"?d:0))break;l+=1}return n.clips.splice(l,0,o),o}setBackground(t){this.data.timeline.background=t}setSoundtrack(t){this.data.timeline.soundtrack=t}getFonts(){return this.data.timeline.fonts??[]}addFont(t){this.data.timeline.fonts||(this.data.timeline.fonts=[]),this.data.timeline.fonts.some(i=>i.src===t)||this.data.timeline.fonts.push({src:t})}removeFont(t){this.data.timeline.fonts&&(this.data.timeline.fonts=this.data.timeline.fonts.filter(i=>i.src!==t))}setFonts(t){this.data.timeline.fonts=t}setSize(t){this.data.output.size={width:t.width,height:t.height}}setFormat(t){this.data.output.format=t}setFps(t){this.data.output.fps=t}setResolution(t){this.data.output.resolution=t}clearResolution(){delete this.data.output.resolution}setAspectRatio(t){this.data.output.aspectRatio=t}clearAspectRatio(){delete this.data.output.aspectRatio}clearSize(){delete this.data.output.size}setMergeFields(t){this.data.merge=t}setClipBinding(t,i,r){let a=this.clipBindings.get(t);a||(a=new Map,this.clipBindings.set(t,a)),a.set(i,r)}getClipBinding(t,i){return this.clipBindings.get(t)?.get(i)}removeClipBinding(t,i){const r=this.clipBindings.get(t);r&&(r.delete(i),r.size===0&&this.clipBindings.delete(t))}getClipBindings(t){return this.clipBindings.get(t)}setClipBindingsForClip(t,i){i.size===0?this.clipBindings.delete(t):this.clipBindings.set(t,new Map(i))}clearClipBindings(t){this.clipBindings.delete(t)}getClipIdsWithBindings(){return Array.from(this.clipBindings.keys())}toJSON(){const t=structuredClone(this.data);for(const i of t.timeline.tracks)for(const r of i.clips){const a=r.id;if(a){const s=this.clipBindings.get(a);if(s)for(const[n,{placeholder:o}]of s)Wi(r,n,o)}delete r.id}return t.merge?.length===0&&delete t.merge,t}static fromJSON(t){return new fr(t)}clone(){return new fr(this.data)}}const Xb=new Set(["asset","start","length","id"]),SF=new Set(["text-to-image","image-to-video","text-to-speech"]);class NF{constructor(t){this.edit=t,this.edit.getInternalEvents().on(yt.Resolved,this.onResolved)}isReconciling=!1;enableCreation=!0;onResolved=({edit:t})=>{this.reconcile(t)};async reconcileInitial(t){const i=this.reconcile(t);return await Promise.all(i.pendingLoads),i}reconcile(t){if(this.isReconciling)return{created:[],updated:[],disposed:[],pendingLoads:[]};this.isReconciling=!0;try{const i=[],r={created:[],updated:[],disposed:[],pendingLoads:i},a=new Set;for(let n=0;n<t.timeline.tracks.length;n+=1){const o=t.timeline.tracks[n];for(let u=0;u<o.clips.length;u+=1){const l=o.clips[u],c=l.id;if(c){a.add(c);const d=this.edit.getPlayerByClipId(c);if(d){const h=this.updatePlayer(d,l,n);h==="recreate"?(this.disposePlayer(c),i.push(this.createPlayer(l,c,n,u)),r.disposed.push(c),r.created.push(c)):h&&r.updated.push(c)}else this.enableCreation&&(this.createPlayer(l,c,n,u),r.created.push(c))}}}const s=this.findOrphanedPlayers(a);for(const n of s)this.disposePlayer(n),r.disposed.push(n);return(r.created.length>0||r.disposed.length>0||r.updated.length>0)&&this.rebuildTracksOrdering(t),this.syncTrackContainers(t.timeline.tracks.length),r}finally{this.isReconciling=!1}}updateSinglePlayer(t,i,r,a=0){const s=this.updatePlayer(t,i,r);if(s==="recreate"){const{clipId:n}=t;return n&&(this.disposePlayer(n),this.createPlayer(i,n,r,a)),"recreate"}return s}createPlayer(t,i,r,a){const s=this.edit.createPlayerFromAssetType(t);s.layer=r+1,s.clipId=i,this.edit.registerPlayerByClipId(i,s),this.edit.addPlayerToTracksArray(r,s),this.edit.addPlayerToContainer(r,s);const n=t.asset?.type??"unknown";return s.load().then(()=>{this.edit.getInternalEvents().emit(yt.PlayerLoaded,{player:s,trackIndex:r,clipIndex:a}),SF.has(n)&&this.edit.getInternalEvents().emit(Ae.ClipUnresolved,{trackIndex:r,clipIndex:a,assetType:n,clipId:i})}).catch(u=>{const l=u instanceof Error?u.message:String(u);this.edit.getInternalEvents().emit(Ae.ClipLoadFailed,{trackIndex:r,clipIndex:a,error:l,assetType:n})})}updatePlayer(t,i,r){const a=t.clipConfiguration.asset?.type,s=i.asset?.type;if(a!==s)return"recreate";let n=!1;const o=t.layer-1,u=t.clipConfiguration.start,l=t.clipConfiguration.length;return(u!==i.start||l!==i.length)&&(t.setResolvedTiming({start:i.start,length:i.length}),t.reconfigureAfterRestore(),n=!0),o!==r&&(t.layer=r+1,this.edit.movePlayerBetweenTracks(t,o,r),n=!0),this.assetChanged(t.clipConfiguration.asset,i.asset)&&(this.updateAsset(t,i.asset),n=!0),this.clipPropertiesChanged(t.clipConfiguration,i)&&(this.updateClipProperties(t,i),n=!0),n}clipPropertiesChanged(t,i){const r=t,a=i,s=new Set([...Object.keys(r),...Object.keys(a)]);for(const n of s)if(!Xb.has(n)&&JSON.stringify(r[n])!==JSON.stringify(a[n]))return!0;return!1}updateClipProperties(t,i){const r=t.clipConfiguration,a=i,s=new Set([...Object.keys(r),...Object.keys(a)]);for(const n of s)Xb.has(n)||(a[n]!==void 0?r[n]=a[n]:delete r[n]);t.reconfigureAfterRestore()}assetChanged(t,i){return JSON.stringify(t)!==JSON.stringify(i)}updateAsset(t,i){const r=t.clipConfiguration.asset?.src,a=i?.src;t.clipConfiguration.asset=i,r!==a&&t.reloadAsset?t.reloadAsset().then(()=>{t.reconfigureAfterRestore()}).catch(s=>{console.error("Failed to reload asset:",s)}):t.reconfigureAfterRestore()}syncTrackContainers(t){const i=this.edit.getTracks().length;if(t>i)for(let r=i;r<t;r+=1)this.edit.ensureTrackExists(r);else if(t<i)for(let r=i-1;r>=t;r-=1)this.edit.removeEmptyTrack(r)}findOrphanedPlayers(t){const i=[];for(const[r]of this.edit.getPlayerMap())t.has(r)||i.push(r);return i}disposePlayer(t){const i=this.edit.getPlayerByClipId(t);i&&(this.edit.unregisterPlayerByClipId(t),this.edit.queuePlayerForDisposal(i))}rebuildTracksOrdering(t){const i=this.edit.getTracks();for(let r=0;r<i.length;r+=1)i[r]=[];for(let r=0;r<t.timeline.tracks.length;r+=1){for(;i.length<=r;)i.push([]);for(const a of t.timeline.tracks[r].clips){const s=a.id;if(s){const n=this.edit.getPlayerByClipId(s);n&&i[r].push(n)}}}}dispose(){this.edit.getInternalEvents().off(yt.Resolved,this.onResolved)}}const BF=new Set(["text","src"]);function Hb(e,t){function i(r,a){if(typeof r=="string"&&t.isMergeFieldTemplate(r)){if(a&&BF.has(a))return t.resolve(r);const s=t.resolveToNumber(r);return s!==null?s:t.resolve(r)}if(Array.isArray(r))return r.map(s=>i(s,a));if(r!==null&&typeof r=="object"){const s={};for(const[n,o]of Object.entries(r))s[n]=i(o,n);return s}return r}return i(structuredClone(e))}function IF(e){const t=new Map,i=new Map,r=[];for(let a=0;a<e.getTrackCount();a+=1){const s=e.getClipsInTrack(a);for(let n=0;n<s.length;n+=1){const o=s[n];if(!o.id)throw new Error(`Clip at track ${a}, index ${n} is missing an ID. EditDocument hydration may have been skipped.`);const u=o.alias??o.id,l={clip:o,trackIndex:a,clipIndex:n};if(r.push({...l,id:u}),o.alias){if(i.has(o.alias))throw new Error(`Duplicate alias "${o.alias}" found. Each alias must be unique.`);i.set(o.alias,l)}}}for(let a=0;a<e.getTrackCount();a+=1){const s=e.getClipsInTrack(a);for(let n=0;n<s.length;n+=1){const o=s[n],u=o.alias??o.id,l=new Set;if(gi(o.start)){const c=Ps(o.start);if(!i.has(c))throw new Error(`Alias reference "alias://${c}" not found. No clip defines alias "${c}".`);l.add(c)}if(gi(o.length)){const c=Ps(o.length);if(!i.has(c))throw new Error(`Alias reference "alias://${c}" not found. No clip defines alias "${c}".`);l.add(c)}if(o.start==="auto"&&n>0){const c=s[n-1],d=c.alias??c.id;l.add(d)}l.size>0&&t.set(u,l)}}return{dependencies:t,clipsByAlias:i,allClips:r}}function FF(e){const t=new Set,i=new Set;function r(a,s){t.add(a),i.add(a);const n=e.get(a);if(n)for(const o of n){if(i.has(o))return[...s,o];if(!t.has(o)){const u=r(o,[...s,o]);if(u)return u}}return i.delete(a),null}for(const a of e.keys())if(!t.has(a)){const s=r(a,[a]);if(s)return s}return null}function VF(e,t){const i=[],r=new Set;function a(s){if(r.has(s))return;r.add(s);const n=e.get(s);if(n)for(const o of n)a(o);i.push(s)}for(const s of e.keys())a(s);for(const s of t)a(s);return i}function Jb(e,t,i){let r;if(e.start==="auto")r=t;else if(gi(e.start)){const n=Ps(e.start),o=i.get(n);if(!o)throw new Error(`Internal error: Alias "${n}" not resolved.`);r=o.start}else r=e.start;let a,s=!1;if(e.length==="end")a=1,s=!0;else if(e.length==="auto")a=3;else if(gi(e.length)){const n=Ps(e.length),o=i.get(n);if(!o)throw new Error(`Internal error: Alias "${n}" not resolved.`);a=o.length}else a=e.length;return{...e,id:e.id??crypto.randomUUID(),start:r,length:a,pendingEndLength:s||void 0}}function zF(e){let t=0;for(const i of e)for(const r of i.clips)if(!r.pendingEndLength){const a=r.start+r.length;a>t&&(t=a)}return t}function Pc(e){const{pendingEndLength:t,...i}=e;return i}function PF(e,t,i){const r=e.getClipById(t);if(!r)return null;const{clip:a,trackIndex:s,clipIndex:n}=r,u=Hb(a,i.mergeFields),l=i.resolvedAliases??new Map,c=Jb(u,i.previousClipEnd,l);return c.pendingEndLength&&i.cachedTimelineEnd!==void 0&&(c.length=Math.max(i.cachedTimelineEnd-c.start,.1)),{resolved:Pc(c),trackIndex:s,clipIndex:n}}function qb(e,t){const{dependencies:i,allClips:r}=IF(e);if(i.size>0){const g=FF(i);if(g)throw new Error(`Circular alias reference detected: ${g.join(" -> ")}`)}const a=r.map(g=>g.id),s=VF(i,a),n=new Map;for(const g of r)n.set(g.id,g);const o=new Map,u=new Map,l=new Map;for(const g of s){const m=n.get(g);if(m){const{clip:v,trackIndex:_,clipIndex:C}=m,k=Hb(v,t.mergeFields),w=l.get(_)??0,x=Jb(k,w,u);o.set(`${_}-${C}`,x);const D=x.start+x.length,b=l.get(_)??0;D>b&&l.set(_,D),v.alias&&u.set(v.alias,{start:x.start,length:x.length})}}const c=[];for(let g=0;g<e.getTrackCount();g+=1){const m=e.getClipsInTrack(g).length,v=[];for(let _=0;_<m;_+=1){const C=o.get(`${g}-${_}`);if(!C)throw new Error(`Internal error: Clip at track ${g}, index ${_} was not resolved.`);v.push(C)}c.push({clips:v})}const d=zF(c),h=c.map(g=>({clips:g.clips.map(m=>{if(m.pendingEndLength){const v=Math.max(d-m.start,.1);return Pc({...m,length:v})}return Pc(m)})}));return{timeline:{background:e.getBackground(),tracks:h,fonts:e.getFonts()},output:e.getOutput()}}class dr{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 _F;clipsToDispose=new Set;clipErrors=new Map;playerByClipId=new Map;lumaContentRelations=new Map;fontMetadata=new Map;isBatchingEvents=!1;isExporting=!1;lastResolved=null;constructor(t){Sr.parse(t),this.tracks=[],this.playbackTime=0,this.totalDuration=0,this.isPlaying=!1,this.document=new fr(t);const i=this.document.getResolution(),r=this.document.getAspectRatio();this.backgroundColor=this.document.getBackground()??"#000000",this.size=i?tu(i,r):this.document.getSize(),this.assetLoader=new iu,this.internalEvents=new jb,this.events=this.internalEvents,this.lumaMaskController=new gF(()=>this.canvas,()=>this.tracks,this.internalEvents),this.playerReconciler=new NF(this),this.mergeFieldService=new bF(this.internalEvents),this.outputSettings=new wF(this),this.selectionManager=new CF(this),this.timingManager=new AF(this),this.setupIntentListeners()}async load(){await this.initializeFromDocument()}async initializeFromDocument(t="load"){const i=this.document.toJSON(),r=i.merge??[];this.mergeFieldService.loadFromSerialized(r),this.lastResolved=null;const a=this.detectMergeFieldBindings(r),s=Sr.parse(i);await Promise.all((s.timeline.fonts??[]).map(async o=>{const u=o.src,l={src:u,parser:au.Name},c=await this.assetLoader.load(u,l);if(c?.family){const d=c.family.replace(/^["']|["']$/g,""),{baseFontFamily:h,fontWeight:g}=pi(d);this.fontMetadata.set(u,{baseFamilyName:h,weight:g})}return c}));const n=this.getResolvedEdit();this.lumaMaskController.initialize(),await this.playerReconciler.reconcileInitial(n),this.normalizeLumaAttachments();for(const[o,u]of a)u.size>0&&this.document.setClipBindingsForClip(o,u);await this.timingManager.resolveAllTiming(),this.updateTotalDuration(),s.timeline.soundtrack&&await this.loadSoundtrack(s.timeline.soundtrack),this.internalEvents.emit(Ae.TimelineUpdated,{current:this.getEdit()}),this.emitEditChanged(t)}getInternalEvents(){return this.internalEvents}update(t,i){for(const r of this.clips)r.shouldDispose&&this.queueDisposeClip(r),r.update(t,i);this.disposeClips(),this.lumaMaskController.update(),this.isPlaying&&(this.playbackTime=Math.max(0,Math.min(this.playbackTime+Nv(i),this.totalDuration)),this.playbackTime===this.totalDuration&&this.pause())}dispose(){this.clearClips(),this.lumaMaskController.dispose(),this.playerReconciler.dispose();for(const t of this.commandHistory)t.dispose?.();this.commandHistory=[],this.commandIndex=-1,this.lumaContentRelations.clear(),Ub.cleanup()}updateCanvasForSize(){this.internalEvents.emit(yt.ViewportSizeChanged,{width:this.size.width,height:this.size.height,backgroundColor:this.backgroundColor}),this.internalEvents.emit(yt.ViewportNeedsZoomToFit)}play(){this.isPlaying=!0,this.internalEvents.emit(Ae.PlaybackPlay)}pause(){this.isPlaying=!1,this.internalEvents.emit(Ae.PlaybackPause)}seek(t){this.playbackTime=Math.max(0,Math.min(t,this.totalDuration)),this.pause(),this.update(0,dr.SEEK_ELAPSED_MARKER)}stop(){this.seek(0)}async loadEdit(t){if(Sr.parse(t),this.tracks.length>0&&!this.hasStructuralChanges(t)){this.lastResolved=null;const n=structuredClone(t);this.preserveClipIdsForGranularUpdate(n);const o=this.document.getTracks(),u=this.document.getOutput();this.document=new fr(n),this.isBatchingEvents=!0,await this.applyGranularChanges(n,o,u),this.updateTotalDuration(),this.isBatchingEvents=!1,this.emitEditChanged("loadEdit:granular");return}const i=this.document,r=this.lastResolved,a=this.size,s=this.backgroundColor;try{this.lastResolved=null,this.document=new fr(t);const n=this.document.getResolution(),o=this.document.getAspectRatio();this.size=n?tu(n,o):this.document.getSize(),this.backgroundColor=this.document.getBackground()??"#000000",this.internalEvents.emit(yt.ViewportSizeChanged,{width:this.size.width,height:this.size.height,backgroundColor:this.backgroundColor}),this.internalEvents.emit(yt.ViewportNeedsZoomToFit),this.clearClips(),await this.initializeFromDocument("loadEdit")}catch(n){throw this.document=i,this.lastResolved=r,this.size=a,this.backgroundColor=s,n}}async loadSoundtrack(t){const i={id:crypto.randomUUID(),asset:{type:"audio",src:t.src,effect:t.effect,volume:t.volume??1},fit:"crop",start:0,length:this.totalDuration},r=this.createPlayerFromAssetType(i);r.layer=this.tracks.length+1,await this.addPlayer(this.tracks.length,r)}getEdit(){const t=this.document.toJSON(),i=this.mergeFieldService.toSerializedArray();return i.length>0&&(t.merge=i),t}validateEdit(t){const i=Sr.safeParse(t);return i.success?{valid:!0,errors:[]}:{valid:!1,errors:i.error.issues.map(r=>({path:r.path.join("."),message:r.message}))}}getResolvedEdit(){return this.lastResolved||(this.lastResolved=qb(this.document,{mergeFields:this.mergeFieldService})),this.lastResolved}getResolvedClip(t,i){return this.getResolvedEdit()?.timeline?.tracks?.[t]?.clips?.[i]??null}getResolvedClipById(t){const i=this.getResolvedEdit();for(const r of i.timeline.tracks)for(const a of r.clips)if(a.id===t)return a;return null}getClipId(t,i){return this.document?.getClipId(t,i)??null}getDocumentClip(t,i){return this.document?.getClip(t,i)??null}getDocument(){return this.document}resolve(){return this.lastResolved=qb(this.document,{mergeFields:this.mergeFieldService}),this.internalEvents.emit(yt.Resolved,{edit:this.lastResolved}),this.lastResolved}resolveClip(t){const i=this.getPlayerByClipId(t);if(!i)return!1;const r=this.document.getClipById(t);if(r?.clip.alias)return this.resolve(),!0;const a=r?.clip;if(a&&(gi(a.start)||gi(a.length)))return this.resolve(),!0;const s=i.layer-1,n=this.tracks[s],o=n?n.indexOf(i):-1;if(o<0)return!1;const u=o>0?n[o-1]:null,l=u?u.getEnd():0,c={mergeFields:this.mergeFieldService,previousClipEnd:l,cachedTimelineEnd:this.timingManager.getTimelineEnd()},d=PF(this.document,t,c);if(!d)return!1;if(this.lastResolved){const g=this.lastResolved.timeline.tracks[d.trackIndex];g&&g.clips[d.clipIndex]&&(g.clips[d.clipIndex]=d.resolved)}return this.playerReconciler.updateSinglePlayer(i,d.resolved,d.trackIndex,d.clipIndex)!==!1}addClip(t,i){rn.parse(i);const r=new iF(t,i);return this.executeCommand(r)}getClip(t,i){const r=this.tracks[t];return!r||i<0||i>=r.length?null:r[i].clipConfiguration}getClipError(t,i){return this.clipErrors.get(`${t}-${i}`)??null}clearClipErrorAndShift(t,i){this.clipErrors.delete(`${t}-${i}`);const r=[];for(const[a,s]of this.clipErrors){const[n,o]=a.split("-").map(Number);n===t&&o>i&&r.push({oldKey:a,newKey:`${n}-${o-1}`,value:s})}for(const{oldKey:a,newKey:s,value:n}of r)this.clipErrors.delete(a),this.clipErrors.set(s,n)}getPlayerClip(t,i){const r=this.tracks[t];return!r||i<0||i>=r.length?null:r[i]}getPlayerByClipId(t){return this.playerByClipId.get(t)??null}getDocumentClipById(t){return this.document?.getClipById(t)?.clip??null}registerPlayerByClipId(t,i){this.playerByClipId.set(t,i)}unregisterPlayerByClipId(t){this.playerByClipId.delete(t)}getPlayerMap(){return this.playerByClipId}addPlayerToTracksArray(t,i){for(;this.tracks.length<=t;)this.tracks.push([]);this.tracks[t].push(i)}movePlayerBetweenTracks(t,i,r){const a=this.tracks[i];if(a){const s=a.indexOf(t);s!==-1&&a.splice(s,1)}for(;this.tracks.length<=r;)this.tracks.push([]);this.tracks[r].push(t),this.movePlayerToTrackContainer(t,i,r)}queuePlayerForDisposal(t){this.queueDisposeClip(t),this.disposeClips()}ensureTrackExists(t){for(;this.tracks.length<=t;)this.tracks.push([])}removeEmptyTrack(t){if(t<0||t>=this.tracks.length)return;const i=this.tracks[t];if(i&&i.length>0){console.warn(`Cannot remove non-empty track ${t}`);return}this.tracks.splice(t,1),this.internalEvents.emit(yt.TrackContainerRemoved,{trackIndex:t});for(let r=t;r<this.tracks.length;r+=1)for(const a of this.tracks[r])a.layer=r+1}getOriginalAsset(t,i){const r=this.getPlayerClip(t,i);if(!r)return;const a=r.getExportableClip();if(!a)return;const{clipId:s}=r;if(s&&this.document){const n=this.document.getClipBindings(s);if(n){for(const[o,{placeholder:u}]of n)if(o.startsWith("asset.")){const l=o.slice(6);Wi(a.asset,l,u)}}}return a.asset}async deleteClip(t,i){const r=this.tracks[t];if(!r)return;const a=r[i];if(!a)return;if(a.playerType!==ht.Luma){const o=r.findIndex(u=>u.playerType===ht.Luma);if(o!==-1){const u=o<i?i-1:i,l=new Bc(t,o);await this.executeCommand(l);const c=new Bc(t,u);await this.executeCommand(c);return}}const n=new Bc(t,i);await this.executeCommand(n)}async addTrack(t,i){md.parse(i);const r=new aF(t);await this.executeCommand(r);for(const a of i.clips)await this.addClip(t,a)}getTrack(t){const i=this.clips.filter(r=>r.layer===t+1);return i.length===0?null:{clips:i.map(r=>r.clipConfiguration)}}deleteTrack(t){const i=new Lb(t);this.executeCommand(i)}undo(){return this.commandQueue.enqueue(async()=>{if(this.commandIndex>=0){const t=this.commandHistory[this.commandIndex];if(t.undo){const i=this.createCommandContext();await Promise.resolve(t.undo(i)),this.commandIndex-=1,this.internalEvents.emit(Ae.EditUndo,{command:t.name}),this.emitEditChanged(`undo:${t.name}`)}}})}redo(){return this.commandQueue.enqueue(async()=>{if(this.commandIndex<this.commandHistory.length-1){const t=this.commandIndex+1,i=this.commandHistory[t],r=this.createCommandContext();await Promise.resolve(i.execute(r)),this.commandIndex=t,this.internalEvents.emit(Ae.EditRedo,{command:i.name}),this.emitEditChanged(`redo:${i.name}`)}})}setUpdatedClip(t,i=null,r=null){const a=t.layer-1,s=this.tracks[a],n=s?s.indexOf(t):-1,o=new Fc(i,r,{trackIndex:a,clipIndex:n});this.executeCommand(o)}updateClipInDocument(t,i){const r=this.document.getClipById(t);r&&this.document.updateClip(r.trackIndex,r.clipIndex,i)}commitClipUpdate(t,i,r){const a=this.document.getClipById(t);if(!a){console.warn(`commitClipUpdate: clip ${t} not found in document`);return}Zu.parse(r);const s=new Fc(i,structuredClone(r),{trackIndex:a.trackIndex,clipIndex:a.clipIndex});this.addCommandToHistory(s)}pushCommandToHistory(t){const i=this.commandHistory.slice(this.commandIndex+1);for(const r of i)r.dispose?.();for(this.commandHistory=this.commandHistory.slice(0,this.commandIndex+1),this.commandHistory.push(t),this.commandIndex+=1;this.commandHistory.length>dr.MAX_HISTORY_SIZE;)this.commandHistory.shift()?.dispose?.(),this.commandIndex-=1}addCommandToHistory(t){this.pushCommandToHistory(t),this.emitEditChanged(`commit:${t.name}`)}updateClip(t,i,r){const a=this.getPlayerClip(t,i);if(!a)return console.warn(`Clip not found at track ${t}, index ${i}`),Promise.resolve();const s=this.document?.getClip(t,i),n=structuredClone(s??a.clipConfiguration),o=structuredClone(s??a.clipConfiguration),u=Ic(o,r);Zu.parse(u);const l=new Fc(n,u,{trackIndex:t,clipIndex:i});return this.executeCommand(l)}updateClipTiming(t,i,r){if(!this.getPlayerClip(t,i)){console.warn(`Clip not found at track ${t}, index ${i}`);return}const s=new fF(t,i,r);this.executeCommand(s)}updateTextContent(t,i,r){const a=t.layer-1,s=this.tracks[a]?.indexOf(t)??-1;if(s<0){console.warn("UpdateTextContent: clip not found in track");return}const n=new dF(a,s,i);this.executeCommand(n)}executeEditCommand(t){return this.executeCommand(t)}executeCommand(t){return this.commandQueue.enqueue(async()=>{const i=this.createCommandContext(),r=await Promise.resolve(t.execute(i));this.handleCommandResult(t,r)})}handleCommandResult(t,i){i.status==="success"&&(this.pushCommandToHistory(t),this.emitEditChanged(t.name))}emitEditChanged(t){this.isBatchingEvents||this.internalEvents.emit(Ae.EditChanged,{source:t,timestamp:Date.now()})}detectMergeFieldBindings(t){const i=new Map;if(!t.length)return i;const r=new Map;for(const{find:a,replace:s}of t){const n=typeof s=="string"?s:JSON.stringify(s);r.set(a.toUpperCase(),n)}for(let a=0;a<this.document.getTrackCount();a+=1){const s=this.document.getClipsInTrack(a);for(let n=0;n<s.length;n+=1){const o=this.document.getClipId(a,n);if(o){const u=this.detectBindingsInObject(s[n],"",r);u.size>0&&i.set(o,u)}}}return i}detectBindingsInObject(t,i,r){const a=new Map;if(typeof t=="string"){if(/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi.test(t)){const o=t.replace(/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi,(u,l)=>r.get(l.toUpperCase())??u);a.set(i,{placeholder:t,resolvedValue:o})}return a}if(Array.isArray(t)){for(let s=0;s<t.length;s+=1){const n=i?`${i}[${s}]`:`[${s}]`,o=this.detectBindingsInObject(t[s],n,r);for(const[u,l]of o)a.set(u,l)}return a}if(t!==null&&typeof t=="object")for(const[s,n]of Object.entries(t)){const o=i?`${i}.${s}`:s,u=this.detectBindingsInObject(n,o,r);for(const[l,c]of u)a.set(l,c)}return a}hasStructuralChanges(t){if(!this.document)return!0;const i=this.document.getTracks(),r=t.timeline.tracks;if(i.length!==r.length)return!0;for(let a=0;a<i.length;a+=1){if(i[a].clips.length!==r[a].clips.length)return!0;for(let s=0;s<i[a].clips.length;s+=1){const n=i[a].clips[s]?.asset?.type,o=r[a].clips[s]?.asset?.type;if(n!==o)return!0}}return JSON.stringify(this.document.getMergeFields()??[])!==JSON.stringify(t.merge??[])||JSON.stringify(this.document.getFonts())!==JSON.stringify(t.timeline.fonts??[])||JSON.stringify(this.document.getSoundtrack())!==JSON.stringify(t.timeline.soundtrack)}preserveClipIdsForGranularUpdate(t){if(!this.document)return;const i=this.document.getTracks();for(let r=0;r<t.timeline.tracks.length;r+=1){const a=i[r],s=t.timeline.tracks[r];if(a&&s)for(let n=0;n<s.clips.length;n+=1){const o=this.document.getClipId(r,n);o&&(s.clips[n].id=o)}}}async applyGranularChanges(t,i,r){const a=t.output;if(a?.size&&(r?.size?.width!==a.size.width||r?.size?.height!==a.size.height)){const o=a.size.width??this.size.width,u=a.size.height??this.size.height;await this.setOutputSize(o,u)}a?.fps!==void 0&&r?.fps!==a.fps&&await this.setOutputFps(a.fps),a?.format!==void 0&&r?.format!==a.format&&await this.setOutputFormat(a.format),a?.destinations&&JSON.stringify(r?.destinations)!==JSON.stringify(a.destinations)&&await this.setOutputDestinations(a.destinations),a?.resolution!==void 0&&r?.resolution!==a.resolution&&await this.setOutputResolution(a.resolution),a?.aspectRatio!==void 0&&r?.aspectRatio!==a.aspectRatio&&await this.setOutputAspectRatio(a.aspectRatio);const s=t.timeline?.background;s&&this.backgroundColor!==s&&await this.setTimelineBackground(s);const n=t.timeline.tracks;for(let o=0;o<n.length;o+=1){const u=i[o].clips,l=n[o].clips;for(let c=0;c<l.length;c+=1){const d=u[c],h=l[c];JSON.stringify(d)!==JSON.stringify(h)&&await this.updateClip(o,c,h)}}}createCommandContext(){return{getClips:()=>this.clips,getTracks:()=>this.tracks,getTrack:t=>t>=0&&t<this.tracks.length?this.tracks[t]:null,getContainer:()=>this.getViewportContainer(),addPlayer:(t,i)=>this.addPlayer(t,i),addPlayerToContainer:(t,i)=>{this.addPlayerToContainer(t,i)},createPlayerFromAssetType:t=>this.createPlayerFromAssetType(t),queueDisposeClip:t=>this.queueDisposeClip(t),disposeClips:()=>this.disposeClips(),clearClipError:(t,i)=>this.clearClipErrorAndShift(t,i),undeleteClip:(t,i)=>{let r=0;if(t>=0&&t<this.tracks.length){const a=this.tracks[t];r=a.length;for(let s=0;s<a.length;s+=1)if(a[s].getStart()>i.getStart()){r=s;break}a.splice(r,0,i)}if(this.document){const a=i.getExportableClip();this.document.addClip(t,a,r);const s=this.document.getClipId(t,r);s&&(i.clipId=s,this.playerByClipId.set(s,i))}this.addPlayerToContainer(t,i),i.load().catch(a=>{const s=i.clipConfiguration?.asset?.type??"unknown",n=a instanceof Error?a.message:String(a);this.clipErrors.set(`${t}-${r}`,{error:n,assetType:s}),this.internalEvents.emit(Ae.ClipLoadFailed,{trackIndex:t,clipIndex:r,error:n,assetType:s})}),this.updateTotalDuration()},setUpdatedClip:()=>{},restoreClipConfiguration:(t,i)=>{const r=structuredClone(i),a=t.clipConfiguration;for(const s of Object.keys(a))delete a[s];if(Object.assign(a,r),t.reconfigureAfterRestore(),this.document){const s=this.findClipIndices(t);if(s){const n=t.getExportableClip();this.document.replaceClip(s.trackIndex,s.clipIndex,n)}}},updateDuration:()=>this.updateTotalDuration(),emitEvent:(t,...i)=>this.internalEvents.emit(t,...i),findClipIndices:t=>this.selectionManager.findClipIndices(t),getClipAt:(t,i)=>this.getClipAt(t,i),getSelectedClip:()=>this.selectionManager.getSelectedClip(),setSelectedClip:t=>{this.selectionManager.setSelectedClip(t)},movePlayerToTrackContainer:(t,i,r)=>this.movePlayerToTrackContainer(t,i,r),getEditState:()=>this.getResolvedEdit(),propagateTimingChanges:(t,i)=>this.propagateTimingChanges(t,i),resolveClipAutoLength:t=>this.resolveClipAutoLength(t),getMergeFields:()=>this.mergeFieldService,getOutputSize:()=>this.outputSettings.getSize(),setOutputSize:(t,i)=>this.outputSettings.setSize(t,i),getOutputFps:()=>this.outputSettings.getFps(),setOutputFps:t=>this.outputSettings.setFps(t),getOutputFormat:()=>this.outputSettings.getFormat(),setOutputFormat:t=>this.outputSettings.setFormat(t),getOutputResolution:()=>this.outputSettings.getResolution(),setOutputResolution:t=>this.outputSettings.setResolution(t),getOutputAspectRatio:()=>this.outputSettings.getAspectRatio(),setOutputAspectRatio:t=>this.outputSettings.setAspectRatio(t),getOutputDestinations:()=>this.outputSettings.getDestinations(),setOutputDestinations:t=>this.outputSettings.setDestinations(t),getTimelineBackground:()=>this.getTimelineBackground(),setTimelineBackground:t=>this.setTimelineBackgroundInternal(t),getDocument:()=>this.document,getDocumentTrack:t=>this.document?.getTrack(t)??null,getDocumentClip:(t,i)=>this.document?.getClip(t,i)??null,documentUpdateClip:(t,i,r)=>{if(!this.document)throw new Error("Document not initialized - cannot update clip");this.document.updateClip(t,i,r)},documentAddClip:(t,i,r)=>{if(!this.document)throw new Error("Document not initialized - cannot add clip");for(;this.document.getTrackCount()<=t;)this.document.addTrack(this.document.getTrackCount());return this.document.addClip(t,i,r)},documentRemoveClip:(t,i)=>{if(!this.document)throw new Error("Document not initialized - cannot remove clip");return this.document.removeClip(t,i)},derivePlayerFromDocument:(t,i)=>{const r=this.document?.getClip(t,i);if(!r)throw new Error(`derivePlayerFromDocument: No document clip at ${t}/${i} - state desync`);const a=this.getClipAt(t,i);if(!a)throw new Error(`derivePlayerFromDocument: No player at ${t}/${i} - state desync`);const{asset:s,...n}=r;Object.assign(a.clipConfiguration,n),a.reconfigureAfterRestore()},buildResolutionContext:(t,i)=>{let r=0;if(i>0){const o=this.tracks[t];o&&o[i-1]&&(r=o[i-1].getEnd())}const a=zc(this.tracks);let s=null;const n=this.getClipAt(t,i);return n&&n.getTimingIntent().length==="auto"&&(s=n.getLength()),{previousClipEnd:r,timelineEnd:a,intrinsicDuration:s}},resolve:()=>this.resolve(),resolveClip:t=>this.resolveClip(t),getPlayerByClipId:t=>this.playerByClipId.get(t)??null,registerPlayerByClipId:(t,i)=>{this.playerByClipId.set(t,i)},unregisterPlayerByClipId:t=>{this.playerByClipId.delete(t)},setClipBinding:(t,i,r)=>{this.document?.setClipBinding(t,i,r)},getClipBinding:(t,i)=>this.document?.getClipBinding(t,i),removeClipBinding:(t,i)=>{this.document?.removeClipBinding(t,i)},getClipBindings:t=>this.document?.getClipBindings(t),getEditSession:()=>this}}queueDisposeClip(t){this.clipsToDispose.add(t)}disposeClips(){if(this.clipsToDispose.size!==0){for(const t of this.clipsToDispose)t.playerType===ht.Luma&&(this.lumaMaskController.cleanupForPlayer(t),t.clipId&&this.lumaContentRelations.delete(t.clipId));for(const t of this.clipsToDispose)t.clipId&&this.playerByClipId.delete(t.clipId);for(const t of this.clipsToDispose)this.disposeClip(t);for(const t of this.clipsToDispose){const i=t.layer-1;if(i>=0&&i<this.tracks.length){const r=this.tracks[i].indexOf(t);r!==-1&&this.tracks[i].splice(r,1)}}this.clipsToDispose.clear(),this.updateTotalDuration(),this.cleanupUnusedFonts()}}cleanupUnusedFonts(){if(!this.document)return;const t=this.document.getFonts();if(t.length===0)return;const i=new Set;for(const r of this.clips){const{asset:a}=r.clipConfiguration;a&&a.type==="rich-text"&&a.font?.family&&i.add(a.font.family)}for(const r of t)if(r.src.includes("fonts.gstatic.com")){const s=this.extractFilenameFromUrl(r.src);s&&!i.has(s)&&this.document.removeFont(r.src)}}extractFilenameFromUrl(t){try{const{pathname:i}=new URL(t),r=i.split("/").pop();return r?r.replace(/\.[^.]+$/,""):null}catch{return null}}disposeClip(t){try{const i=this.canvas?.getViewportContainer();if(i){for(const r of i.children)if(r instanceof se.Container&&r.label?.toString().startsWith("shotstack-track-")&&r.children.includes(t.getContainer())){r.removeChild(t.getContainer());break}}}catch(i){console.warn(`Attempting to unmount an unmounted clip: ${i}`)}this.unloadClipAssets(t),this.timingManager.invalidateTimelineEndCache(),t.dispose()}unloadClipAssets(t){const{asset:i}=t.clipConfiguration;i&&"src"in i&&typeof i.src=="string"&&this.assetLoader.decrementRef(i.src)&&se.Assets.cache.has(i.src)&&se.Assets.unload(i.src)}clearClips(){for(const t of this.clips)this.disposeClip(t);this.tracks=[],this.clipsToDispose.clear(),this.clipErrors.clear(),this.lumaContentRelations.clear(),this.updateTotalDuration()}updateTotalDuration(){let t=0;for(const r of this.tracks)for(const a of r)t=Math.max(t,a.getEnd());const i=this.totalDuration;this.totalDuration=t,i!==this.totalDuration&&this.internalEvents.emit(Ae.DurationChanged,{duration:this.totalDuration})}propagateTimingChanges(t,i){this.timingManager.propagateTimingChanges(t,i)}async resolveClipAutoLength(t){const i=t.getTimingIntent();if(i.length!=="auto")return;const r=this.findClipIndices(t);let a=t.getStart();i.start==="auto"&&r&&(a=Yb(r.trackIndex,r.clipIndex,this.tracks));const s=await Wb(t.clipConfiguration.asset);t.setResolvedTiming({start:a,length:s}),t.reconfigureAfterRestore(),r&&this.propagateTimingChanges(r.trackIndex,r.clipIndex)}addPlayerToContainer(t,i){this.internalEvents.emit(yt.PlayerAddedToTrack,{player:i,trackIndex:t})}movePlayerToTrackContainer(t,i,r){this.internalEvents.emit(yt.PlayerMovedBetweenTracks,{player:t,fromTrackIndex:i,toTrackIndex:r})}createPlayerFromAssetType(t){return Ub.create(this,t)}async addPlayer(t,i){for(;this.tracks.length<=t;)this.tracks.push([]);this.tracks[t].push(i),this.internalEvents.emit(yt.PlayerAddedToTrack,{player:i,trackIndex:t}),await i.load(),this.updateTotalDuration()}selectClip(t,i){this.selectionManager.selectClip(t,i)}clearSelection(){this.selectionManager.clearSelection()}isClipSelected(t,i){return this.selectionManager.isClipSelected(t,i)}getSelectedClipInfo(){return this.selectionManager.getSelectedClipInfo()}copyClip(t,i){this.selectionManager.copyClip(t,i)}pasteClip(){this.selectionManager.pasteClip()}hasCopiedClip(){return this.selectionManager.hasCopiedClip()}findClipIndices(t){return this.selectionManager.findClipIndices(t)}getClipAt(t,i){return t>=0&&t<this.tracks.length&&i>=0&&i<this.tracks[t].length?this.tracks[t][i]:null}selectPlayer(t){this.selectionManager.selectPlayer(t)}isPlayerSelected(t){return this.selectionManager.isPlayerSelected(t)}getActivePlayersExcept(t){const i=[];for(const r of this.tracks)for(const a of r)a!==t&&a.isActive()&&i.push(a);return i}showAlignmentGuide(t,i,r,a){this.canvas?.showAlignmentGuide(t,i,r,a)}clearAlignmentGuides(){this.canvas?.clearAlignmentGuides()}moveSelectedClip(t,i){const r=this.getSelectedClipInfo();if(!r)return;const{player:a,trackIndex:s,clipIndex:n}=r,o=this.getResolvedClip(s,n);if(!o)return;const u=structuredClone(o),l=a.calculateMoveOffset(t,i),c=structuredClone(u);c.offset=l,this.setUpdatedClip(a,u,c)}setExportMode(t){this.isExporting=t}isInExportMode(){return this.isExporting}setCanvas(t){this.canvas=t}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(t,i){const r=new lF(t,i);return this.executeCommand(r)}setOutputFps(t){const i=new oF(t);return this.executeCommand(i)}getOutputFps(){return this.outputSettings.getFps()}setOutputFormat(t){const i=new nF(t);return this.executeCommand(i)}getOutputFormat(){return this.outputSettings.getFormat()}setOutputDestinations(t){const i=new sF(t);return this.executeCommand(i)}getOutputDestinations(){return this.outputSettings.getDestinations()}setOutputResolution(t){const i=new uF(t);return this.executeCommand(i)}getOutputResolution(){return this.outputSettings.getResolution()}setOutputAspectRatio(t){const i=new rF(t);return this.executeCommand(i)}getOutputAspectRatio(){return this.outputSettings.getAspectRatio()}getTimelineFonts(){return this.document.getFonts()}getFontMetadata(){return this.fontMetadata}getFontUrlByFamilyAndWeight(t,i){const{baseFontFamily:r}=pi(t),a=r.toLowerCase();for(const[s,n]of this.fontMetadata)if(n.baseFamilyName.toLowerCase()===a&&n.weight===i)return s;for(const[s,n]of this.fontMetadata)if(n.baseFamilyName.toLowerCase()===a)return s;return null}pruneUnusedFonts(){this.cleanupUnusedFonts()}setTimelineBackground(t){const i=new cF(t);return this.executeCommand(i)}setTimelineBackgroundInternal(t){DE.parse(t),this.backgroundColor=t,this.document.setBackground(t),this.internalEvents.emit(yt.ViewportSizeChanged,{width:this.size.width,height:this.size.height,backgroundColor:this.backgroundColor}),this.internalEvents.emit(Ae.TimelineBackgroundChanged,{color:t})}getTimelineBackground(){return this.backgroundColor}resolveMergeFields(t){return this.mergeFieldService.resolve(t)}getTemplateClip(t,i){const r=this.getPlayerClip(t,i);if(!r)return null;const a=r.getExportableClip();if(!a)return null;const{clipId:s}=r;if(s&&this.document){const n=this.document.getClipBindings(s);if(n)for(const[o,{placeholder:u}]of n)Wi(a,o,u)}return a}getTemplateClipById(t){const i=this.getPlayerByClipId(t);if(!i)return null;const r=i.getExportableClip();if(!r||!this.document)return null;const a=this.document.getClipBindings(t);if(a)for(const[s,{placeholder:n}]of a)Wi(r,s,n);return r}getTemplateClipText(t,i){const r=this.getTemplateClip(t,i);return r?r.asset?.text??null:null}getLumaClipIdForContent(t){for(const[i,r]of this.lumaContentRelations)if(r===t)return i;return null}getContentClipIdForLuma(t){return this.lumaContentRelations.get(t)??null}setLumaContentRelationship(t,i){this.lumaContentRelations.set(t,i)}clearLumaContentRelationship(t){this.lumaContentRelations.delete(t)}getLumaContentRelationship(t){return this.lumaContentRelations.get(t)}normalizeLumaAttachments(){let t=!1;for(let i=0;i<this.tracks.length;i+=1){const r=this.tracks[i];for(const a of r)if(a.playerType===ht.Luma){const s=this.findBestContentMatch(i,a);if(s){a.clipId&&s.clipId&&this.lumaContentRelations.set(a.clipId,s.clipId);const n=r.indexOf(a);this.document.updateClip(i,n,{start:s.getStart(),length:s.getLength()}),t=!0}}}t&&this.resolve()}findBestContentMatch(t,i){const r=this.tracks[t],a=i.getStart(),s=a+i.getLength();let n=null,o=0;for(const u of r)if(u.playerType!==ht.Luma){const l=u.getStart(),c=l+u.getLength(),d=DF(a,s,l,c);d>o&&(o=d,n=u)}return n}setupIntentListeners(){this.internalEvents.on(yt.CanvasClipClicked,t=>{this.selectPlayer(t.player)}),this.internalEvents.on(yt.CanvasBackgroundClicked,()=>{this.clearSelection()})}getTracks(){return this.tracks}}class Qb{constructor(t,i,r,a,s,n){this.clipId=t,this.propertyPath=i,this.fieldName=r,this.previousFieldName=a,this.storedPreviousValue=s,this.storedNewValue=n}name="setMergeField";storedPreviousValue;storedNewValue;storedPreviousBinding;updateDocumentClip(t,i,r){const a=t.getDocument();if(!a)return;const s=a.getClipById(this.clipId);if(!s)return;const n=s.clip;if(r)Wi(n,this.propertyPath,i);else{const u=(typeof i=="string"?i.trim():"").length>0?Number(i):NaN;Wi(n,this.propertyPath,Number.isFinite(u)?u:i)}}async execute(t){if(!t)throw new Error("SetMergeFieldCommand.execute: context is required");const i=t.getMergeFields();if(this.storedPreviousBinding=t.getClipBinding(this.clipId,this.propertyPath),this.fieldName){const r={placeholder:i.createTemplate(this.fieldName),resolvedValue:this.storedNewValue};t.setClipBinding(this.clipId,this.propertyPath,r)}else t.removeClipBinding(this.clipId,this.propertyPath);if(this.fieldName?i.register({name:this.fieldName,defaultValue:this.storedNewValue},{silent:!0}):this.previousFieldName&&i.remove(this.previousFieldName,{silent:!0}),this.fieldName){const r=i.createTemplate(this.fieldName);this.updateDocumentClip(t,r,!0)}else this.updateDocumentClip(t,this.storedNewValue,!1);return t.resolve(),t.emitEvent(Ae.MergeFieldChanged,{fields:i.getAll()}),Ke()}async undo(t){if(!t)throw new Error("SetMergeFieldCommand.undo: context is required");const i=t.getMergeFields();return this.storedPreviousBinding?t.setClipBinding(this.clipId,this.propertyPath,this.storedPreviousBinding):t.removeClipBinding(this.clipId,this.propertyPath),this.previousFieldName&&i.register({name:this.previousFieldName,defaultValue:this.storedPreviousValue},{silent:!0}),this.storedPreviousBinding?this.updateDocumentClip(t,this.storedPreviousBinding.placeholder,!0):this.updateDocumentClip(t,this.storedPreviousValue,!1),t.resolve(),t.emitEvent(Ae.MergeFieldChanged,{fields:i.getAll()}),Ke()}dispose(){this.storedPreviousBinding=void 0}}function TF(e){if(typeof e!="object"||e===null)return!1;const t=e;return t.type==="text"&&(!t.text||t.text.trim()==="")}function ev(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function OF(e){const t=e.width??100,i=e.height??100,r=ev(e.background?.color??"#000000"),a=e.background?.opacity??1,s=e.background?.borderRadius??0,n=[`width="${t}"`,`height="${i}"`,`fill="${r}"`];if(a!==1&&n.push(`fill-opacity="${a}"`),s>0&&n.push(`rx="${s}"`,`ry="${s}"`),e.stroke?.width&&e.stroke.width>0){const o=ev(e.stroke.color??"#000000");n.push(`stroke="${o}"`),n.push(`stroke-width="${e.stroke.width}"`)}return`<svg viewBox="0 0 ${t} ${i}" xmlns="http://www.w3.org/2000/svg"><rect ${n.join(" ")}/></svg>`}function $F(e){const t=e.asset,i=OF(t),r={...e,asset:{type:"svg",src:i,opacity:1}};return t.width!==void 0&&r.width===void 0&&(r.width=t.width),t.height!==void 0&&r.height===void 0&&(r.height=t.height),r}class RF extends dr{isUpdatingMergeFields=!1;get mergeFields(){return this.mergeFieldService}applyMergeField(t,i,r,a,s){const n=this.getResolvedClipById(t),o=n?eu(n,i):null,u=s??(o!=null?String(o):""),l=this.getTemplateClipById(t),c=l?eu(l,i):null,d=typeof c=="string"?this.mergeFieldService.extractFieldName(c):null,h=new Qb(t,i,r,d,u,a);return this.executeCommand(h)}removeMergeField(t,i,r){const a=this.getMergeFieldForProperty(t,i);if(!a)return Promise.resolve();const s=new Qb(t,i,null,a,r,r);return this.executeCommand(s)}getMergeFieldForProperty(t,i){const r=this.getTemplateClipById(t);if(!r)return null;const a=eu(r,i);return typeof a=="string"?this.mergeFieldService.extractFieldName(a):null}updateMergeFieldValueLive(t,i){if(!this.isUpdatingMergeFields){this.isUpdatingMergeFields=!0;try{const r=this.mergeFieldService.get(t);if(!r)return;this.mergeFieldService.register({...r,defaultValue:i},{silent:!0});for(const[,a]of this.getPlayerMap())this.updateMergeFieldBindings(a,t,i);this.resolve(),this.getInternalEvents().emit(Ae.TimelineUpdated,{current:this.getEdit()})}finally{this.isUpdatingMergeFields=!1}}}isSrcMergeField(t){for(const[i,r]of this.getPlayerMap())if(r.clipId){const a=this.getTemplateClipById(i);if(a){const s=a.asset?.type;if(s==="image"||s==="video"||s==="audio"){const o=this.getMergeFieldUsage(a,t);if(o.used&&o.isSrcField)return!0}}}return!1}validateMergeFieldValue(t,i){const r=this.getDocument();if(!r)return null;const a=this.mergeFieldService.get(t);if(!a)return null;const s=a.defaultValue;this.mergeFieldService.register({...a,defaultValue:i},{silent:!0});try{for(const n of r.getClipIdsWithBindings()){const o=r.getClipBindings(n);if(o&&this.clipUsesField(o,t)){const u=r.getClipById(n);if(u){const l=structuredClone(u.clip);for(const[d,h]of o){const g=this.mergeFieldService.resolve(h.placeholder);Wi(l,d,g)}delete l.id;const c=rn.safeParse(l);if(!c.success)return c.error.issues[0]?.message??"Invalid value"}}}return null}finally{this.mergeFieldService.register({...a,defaultValue:s},{silent:!0})}}isValueCompatibleWithClipProperty(t,i,r){const a=this.getResolvedClipById(t);if(!a)return!0;const s=structuredClone(a);return Wi(s,i,r),delete s.id,rn.safeParse(s).success}clipUsesField(t,i){for(const[,r]of t)if(this.mergeFieldService.extractFieldName(r.placeholder)===i)return!0;return!1}async deleteMergeFieldGlobally(t){const i=this.mergeFieldService.get(t);if(!i)return;const r=this.mergeFieldService.createTemplate(t),a=i.defaultValue;for(const[n]of this.getPlayerMap()){const o=this.getTemplateClipById(n);o&&await this.restoreMergeFieldInClip(n,o,r,a)}this.mergeFieldService.remove(t)||this.getInternalEvents().emit(Ae.MergeFieldChanged,{fields:this.mergeFieldService.getAll()})}async convertAllTextAssets(){const t=this.getDocument();if(!t)return console.error("No document available for conversion"),{richText:0,svg:0};const i=JSON.parse(JSON.stringify(t.toJSON()));let r=0,a=0;const s=i.timeline?.tracks;if(s){for(const n of s)if(n.clips)for(let o=0;o<n.clips.length;o+=1){const u=n.clips[o],l=u.asset;l?.type==="text"&&(TF(l)?(n.clips[o]=$F(u),a+=1):(n.clips[o]=this.convertTextClipToRichText(u),r+=1))}}return console.log("CONVERTED TEMPLATE - Copy the JSON below:"),console.log(JSON.stringify(i,null," ")),{richText:r,svg:a}}mapVerticalAlign(t){return t==="center"?"middle":t==="top"||t==="bottom"?t:"middle"}convertTextClipToRichText(t){const i=t.asset,r=i.font?.family??"Open Sans",{fontWeight:a}=pi(r),s={family:r,size:typeof i.font?.size=="string"?Number(i.font.size):i.font?.size??32,weight:i.font?.weight??a,color:i.font?.color??"#ffffff",opacity:i.font?.opacity??1};i.stroke?.width&&i.stroke.width>0&&(s.stroke={width:i.stroke.width,color:i.stroke.color??"#000000",opacity:1});const n={letterSpacing:0,wordSpacing:0,lineHeight:i.font?.lineHeight??1.2,textTransform:"none",textDecoration:"none"},o={type:"rich-text",text:i.text??"",font:s,style:n,align:{horizontal:i.alignment?.horizontal??"center",vertical:this.mapVerticalAlign(i.alignment?.vertical)}};i.background&&(o.background={color:i.background.color,opacity:i.background.opacity??1,borderRadius:i.background.borderRadius??0},i.background.padding&&(o.padding=i.background.padding)),i.animation&&(o.animation={preset:i.animation.preset,duration:i.animation.duration}),i.ellipsis!==void 0&&console.warn("TextAsset ellipsis property not supported in RichTextAsset, value dropped");const u={...t,asset:o};return i.width!==void 0&&u.width===void 0&&(u.width=i.width),i.height!==void 0&&u.height===void 0&&(u.height=i.height),u}updateMergeFieldBindings(t,i,r){if(!t)return;const{clipId:a}=t;if(!a)return;const s=this.getDocument();if(!s)return;const n=s.getClipBindings(a);if(!n)return;const o=s.getClipById(a);for(const[u,l]of n)if(this.mergeFieldService.extractFieldName(l.placeholder)===i){const d=this.mergeFieldService.resolve(l.placeholder),h={placeholder:l.placeholder,resolvedValue:d};if(s.setClipBinding(a,u,h),o){const m=(typeof d=="string"?d.trim():"").length>0?Number(d):NaN,v=Number.isFinite(m)?m:d;Wi(o.clip,u,v)}}}getMergeFieldUsage(t,i,r=""){if(!t||typeof t!="object")return{used:!1,isSrcField:!1};for(const[a,s]of Object.entries(t)){const n=r?`${r}.${a}`:a;if(typeof s=="string"){if(this.mergeFieldService.extractFieldName(s)===i)return{used:!0,isSrcField:n==="asset.src"||n.endsWith(".src")}}else if(typeof s=="object"&&s!==null){const o=this.getMergeFieldUsage(s,i,n);if(o.used)return o}}return{used:!1,isSrcField:!1}}async restoreMergeFieldInClip(t,i,r,a,s=""){if(!(!i||typeof i!="object"))for(const n of Object.keys(i)){const o=i[n],u=s?`${s}.${n}`:n;if(typeof o=="string"){const l=this.mergeFieldService.extractFieldName(o),c=this.mergeFieldService.extractFieldName(r);if(l&&c&&l===c){const d=o.replace(new RegExp(`\\{\\{\\s*${l}\\s*\\}\\}`,"gi"),a);await this.removeMergeField(t,u,d)}}else typeof o=="object"&&o!==null&&await this.restoreMergeFieldInClip(t,o,r,a,u)}}}const ru=Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"}));var ZF=xt({"node_modules/.pnpm/harfbuzzjs@0.4.12/node_modules/harfbuzzjs/hb.js"(e,t){var i=(()=>{var r=typeof document<"u"?document.currentScript?.src:void 0;return async function(a={}){var s,n=a,o=typeof window=="object",u=typeof WorkerGlobalScope<"u",l=typeof process=="object"&&process.versions?.node&&process.type!="renderer",c=(S,ue)=>{throw ue};typeof __filename<"u"?r=__filename:u&&(r=self.location.href);var d="";function h(S){return n.locateFile?n.locateFile(S,d):d+S}var g,m;if(l){var v=VE("fs");d=__dirname+"/",m=S=>{S=x(S)?new URL(S):S;var ue=v.readFileSync(S);return ue},g=async(S,ue=!0)=>{S=x(S)?new URL(S):S;var Me=v.readFileSync(S,ue?void 0:"utf8");return Me},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),c=(S,ue)=>{throw process.exitCode=S,ue}}else if(o||u){try{d=new URL(".",r).href}catch{}u&&(m=S=>{var ue=new XMLHttpRequest;return ue.open("GET",S,!1),ue.responseType="arraybuffer",ue.send(null),new Uint8Array(ue.response)}),g=async S=>{if(x(S))return new Promise((Me,st)=>{var Le=new XMLHttpRequest;Le.open("GET",S,!0),Le.responseType="arraybuffer",Le.onload=()=>{if(Le.status==200||Le.status==0&&Le.response){Me(Le.response);return}st(Le.status)},Le.onerror=st,Le.send(null)});var ue=await fetch(S,{credentials:"same-origin"});if(ue.ok)return ue.arrayBuffer();throw new Error(ue.status+" : "+ue.url)}}console.log.bind(console);var _=console.error.bind(console),C,k=!1,w,x=S=>S.startsWith("file://"),D,b,$,G,J=!1;function T(){var S=$.buffer;n.HEAP8=new Int8Array(S),n.HEAPU8=G=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 Y(){if(n.preRun)for(typeof n.preRun=="function"&&(n.preRun=[n.preRun]);n.preRun.length;)Z(n.preRun.shift());rt(X)}function O(){J=!0,hi.__wasm_call_ctors()}function re(){if(n.postRun)for(typeof n.postRun=="function"&&(n.postRun=[n.postRun]);n.postRun.length;)R(n.postRun.shift());rt(M)}var q=0,pe=null;function ce(S){q++,n.monitorRunDependencies?.(q)}function ye(S){if(q--,n.monitorRunDependencies?.(q),q==0&&pe){var ue=pe;pe=null,ue()}}function L(S){n.onAbort?.(S),S="Aborted("+S+")",_(S),k=!0,S+=". Build with -sASSERTIONS for more info.";var ue=new WebAssembly.RuntimeError(S);throw b?.(ue),ue}var Q;function ie(){return h("hb.wasm")}function ve(S){if(S==Q&&C)return new Uint8Array(C);if(m)return m(S);throw"both async and sync fetching of the wasm failed"}async function _e(S){if(!C)try{var ue=await g(S);return new Uint8Array(ue)}catch{}return ve(S)}async function Oe(S,ue){try{var Me=await _e(S),st=await WebAssembly.instantiate(Me,ue);return st}catch(Le){_(`failed to asynchronously prepare wasm: ${Le}`),L(Le)}}async function qe(S,ue,Me){if(!S&&!x(ue)&&!l)try{var st=fetch(ue,{credentials:"same-origin"}),Le=await WebAssembly.instantiateStreaming(st,Me);return Le}catch(Nt){_(`wasm streaming compile failed: ${Nt}`),_("falling back to ArrayBuffer instantiation")}return Oe(ue,Me)}function Xe(){return{env:Bs,wasi_snapshot_preview1:Bs}}async function Ze(){function S(Nt,ga){return hi=Nt.exports,n.wasmExports=hi,$=hi.memory,n.wasmMemory=$,T(),Vt=hi.__indirect_function_table,fu(hi),ye(),hi}ce();function ue(Nt){return S(Nt.instance)}var Me=Xe();if(n.instantiateWasm)return new Promise((Nt,ga)=>{n.instantiateWasm(Me,(hu,Mc)=>{Nt(S(hu))})});Q??(Q=ie());var st=await qe(C,Q,Me),Le=ue(st);return Le}class St{constructor(ue){ft(this,"name","ExitStatus"),this.message=`Program terminated with exit(${ue})`,this.status=ue}}var rt=S=>{for(;S.length>0;)S.shift()(n)},M=[],R=S=>M.push(S),X=[],Z=S=>X.push(S),le=!0,he=()=>L(""),fe=0,ge=()=>{le=!1,fe=0},Ce={},de=S=>{if(S instanceof St||S=="unwind")return w;c(1,S)},oe=()=>le||fe>0,$e=S=>{w=S,oe()||(n.onExit?.(S),k=!0),c(S,new St(S))},He=(S,ue)=>{w=S,$e(S)},Dt=He,Lt=()=>{if(!oe())try{Dt(w)}catch(S){de(S)}},jt=S=>{if(!k)try{S(),Lt()}catch(ue){de(ue)}},wt=()=>performance.now(),Tt=(S,ue)=>{if(Ce[S]&&(clearTimeout(Ce[S].id),delete Ce[S]),!ue)return 0;var Me=setTimeout(()=>{delete Ce[S],jt(()=>Ns(S,wt()))},ue);return Ce[S]={id:Me,timeout_ms:ue},0},Jt=()=>2147483648,Ve=(S,ue)=>Math.ceil(S/ue)*ue,Zc=S=>{var ue=$.buffer.byteLength,Me=(S-ue+65535)/65536|0;try{return $.grow(Me),T(),1}catch{}},hr=S=>{var ue=G.length;S>>>=0;var Me=Jt();if(S>Me)return!1;for(var st=1;st<=4;st*=2){var Le=ue*(1+.2/st);Le=Math.min(Le,S+100663296);var Nt=Math.min(Me,Ve(Math.max(S,Le),65536)),ga=Zc(Nt);if(ga)return!0}return!1},Et=S=>{const ue=S.length;return[ue%128|128,ue>>7,...S]},uu={i:127,p:127,j:126,f:125,d:124,e:111},si=S=>Et(Array.from(S,ue=>{var Me=uu[ue];return Me})),Vi=(S,ue)=>{var Me=Uint8Array.of(0,97,115,109,1,0,0,0,1,...Et([1,96,...si(ue.slice(1)),...si(ue[0]==="v"?"":ue[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0),st=new WebAssembly.Module(Me),Le=new WebAssembly.Instance(st,{e:{f:S}}),Nt=Le.exports.f;return Nt},Vt,gr=S=>Vt.get(S),pr=(S,ue)=>{if(qt)for(var Me=S;Me<S+ue;Me++){var st=gr(Me);st&&qt.set(st,Me)}},qt,Oa=S=>(qt||(qt=new WeakMap,pr(0,Vt.length)),qt.get(S)||0),mr=[],lu=()=>mr.length?mr.pop():Vt.grow(1),yr=(S,ue)=>Vt.set(S,ue),br=(S,ue)=>{var Me=Oa(S);if(Me)return Me;var st=lu();try{yr(st,S)}catch(Nt){if(!(Nt instanceof TypeError))throw Nt;var Le=Vi(S,ue);yr(st,Le)}return qt.set(S,st),st},cu=S=>{qt.delete(gr(S)),yr(S,null),mr.push(S)};n.noExitRuntime&&(le=n.noExitRuntime),n.print&&n.print,n.printErr&&(_=n.printErr),n.wasmBinary&&(C=n.wasmBinary),n.arguments&&n.arguments,n.thisProgram&&n.thisProgram,n.wasmMemory=$,n.wasmExports=hi,n.addFunction=br,n.removeFunction=cu;var Ns;function fu(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,Ns=S._emscripten_timeout}var Bs={_abort_js:he,_emscripten_runtime_keepalive_clear:ge,_setitimer_js:Tt,emscripten_resize_heap:hr,proc_exit:$e},hi=await Ze();function vr(){if(q>0){pe=vr;return}if(Y(),q>0){pe=vr;return}function S(){n.calledRun=!0,!k&&(O(),D?.(n),n.onRuntimeInitialized?.(),re())}n.setStatus?(n.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>n.setStatus(""),1),S()},1)):S()}function du(){if(n.preInit)for(typeof n.preInit=="function"&&(n.preInit=[n.preInit]);n.preInit.length>0;)n.preInit.shift()()}return du(),vr(),J?s=n:s=new Promise((S,ue)=>{D=S,b=ue}),s}})();typeof e=="object"&&typeof t=="object"?(t.exports=i,t.exports.default=i):typeof define=="function"&&define.amd&&define([],()=>i)}});const MF=ZF(),UF=Object.freeze(Object.defineProperty({__proto__:null,default:MF},Symbol.toStringTag,{value:"Module"}));var LF=xt({"node_modules/.pnpm/harfbuzzjs@0.4.12/node_modules/harfbuzzjs/hbjs.js"(e,t){function i(r){var a=r.wasmExports,s=new TextDecoder("utf8");let n=r.addFunction,o=r.removeFunction;var u=n(function(L){a.free(L)},"vi"),l=2,c=-1,d=2,h=0,g=1,m=2;function v(L){return(L.charCodeAt(0)&255)<<24|(L.charCodeAt(1)&255)<<16|(L.charCodeAt(2)&255)<<8|(L.charCodeAt(3)&255)<<0}var _=v("JSON"),C=4;function k(L){return[String.fromCharCode(L>>24&255),String.fromCharCode(L>>16&255),String.fromCharCode(L>>8&255),String.fromCharCode(L>>0&255)].join("")}function w(L){return L=="BOT"?1:L=="EOT"?2:L=="PRESERVE_DEFAULT_IGNORABLES"?4:L=="REMOVE_DEFAULT_IGNORABLES"?8:L=="DO_NOT_INSERT_DOTTED_CIRCLE"?16:L=="PRODUCE_UNSAFE_TO_CONCAT"?64:0}function x(L){var Q=a.malloc(L.byteLength);r.HEAPU8.set(new Uint8Array(L),Q);var ie=a.hb_blob_create(Q,L.byteLength,l,Q,u);return{ptr:ie,destroy:function(){a.hb_blob_destroy(ie)}}}function D(L){const Q=a.hb_set_get_population(L),ie=a.malloc(Q<<2),ve=ie>>2,_e=r.HEAPU32.subarray(ve,ve+Q);return r.HEAPU32.set(_e,ve),a.hb_set_next_many(L,c,ie,Q),_e}function b(L,Q){var ie=a.hb_face_create(L.ptr,Q);const ve=a.hb_face_get_upem(ie);return{ptr:ie,upem:ve,reference_table:function(_e){var Oe=a.hb_face_reference_table(ie,v(_e)),qe=a.hb_blob_get_length(Oe);if(qe){var Xe=a.hb_blob_get_data(Oe,null),Ze=r.HEAPU8.subarray(Xe,Xe+qe);return Ze}},getAxisInfos:function(){var _e=a.malloc(2048),Oe=a.malloc(4);r.HEAPU32[Oe/4]=64,a.hb_ot_var_get_axis_infos(ie,0,Oe,_e);var qe={};return Array.from({length:r.HEAPU32[Oe/4]}).forEach(function(Xe,Ze){qe[k(r.HEAPU32[_e/4+Ze*8+1])]={min:r.HEAPF32[_e/4+Ze*8+4],default:r.HEAPF32[_e/4+Ze*8+5],max:r.HEAPF32[_e/4+Ze*8+6]}}),a.free(Oe),a.free(_e),qe},collectUnicodes:function(){var _e=a.hb_set_create();a.hb_face_collect_unicodes(ie,_e);var Oe=D(_e);return a.hb_set_destroy(_e),Oe},destroy:function(){a.hb_face_destroy(ie)}}}var $="",G=256,J=a.malloc(G);function T(L){var Q=a.hb_font_create(L.ptr),ie=null,ve=null,_e=null,Oe=null,qe=null,Xe=null;function Ze(rt){if(!ie){var M=function(he,fe,ge,Ce,de,oe){$+=`M${Ce},${de}`},R=function(he,fe,ge,Ce,de,oe){$+=`L${Ce},${de}`},X=function(he,fe,ge,Ce,de,oe,$e,He,Dt,Lt){$+=`C${Ce},${de} ${oe},${$e} ${He},${Dt}`},Z=function(he,fe,ge,Ce,de,oe,$e,He){$+=`Q${Ce},${de} ${oe},${$e}`},le=function(he,fe,ge,Ce){$+="Z"};ve=n(M,"viiiffi"),_e=n(R,"viiiffi"),Oe=n(X,"viiiffffffi"),qe=n(Z,"viiiffffi"),Xe=n(le,"viiii"),ie=a.hb_draw_funcs_create(),a.hb_draw_funcs_set_move_to_func(ie,ve,0,0),a.hb_draw_funcs_set_line_to_func(ie,_e,0,0),a.hb_draw_funcs_set_cubic_to_func(ie,Oe,0,0),a.hb_draw_funcs_set_quadratic_to_func(ie,qe,0,0),a.hb_draw_funcs_set_close_path_func(ie,Xe,0,0)}return $="",a.hb_font_draw_glyph(Q,rt,ie,0),$}function St(rt){a.hb_font_glyph_to_string(Q,rt,J,G);var M=r.HEAPU8.subarray(J,J+G);return s.decode(M.slice(0,M.indexOf(0)))}return{ptr:Q,glyphName:St,glyphToPath:Ze,glyphToJson:function(rt){var M=Ze(rt);return M.replace(/([MLQCZ])/g,"|$1 ").split("|").filter(function(R){return R.length}).map(function(R){var X=R.split(/[ ,]/g);return{type:X[0],values:X.slice(1).filter(function(Z){return Z.length}).map(function(Z){return+Z})}})},setScale:function(rt,M){a.hb_font_set_scale(Q,rt,M)},setVariations:function(rt){var M=Object.entries(rt),R=a.malloc(8*M.length);M.forEach(function(X,Z){r.HEAPU32[R/4+Z*2+0]=v(X[0]),r.HEAPF32[R/4+Z*2+1]=X[1]}),a.hb_font_set_variations(Q,R,M.length),a.free(R)},destroy:function(){a.hb_font_destroy(Q),ie&&(a.hb_draw_funcs_destroy(ie),ie=null,o(ve),o(_e),o(Oe),o(qe),o(Xe))}}}function Y(L){var Q=a.malloc(L.length+1);for(let ie=0;ie<L.length;++ie){const ve=L.charCodeAt(ie);if(ve>127)throw new Error("Expected ASCII text");r.HEAPU8[Q+ie]=ve}return r.HEAPU8[Q+L.length]=0,{ptr:Q,length:L.length,free:function(){a.free(Q)}}}function O(L){const Q=a.malloc(L.length*2),ie=new Uint16Array(r.wasmMemory.buffer,Q,L.length);for(let ve=0;ve<ie.length;++ve)ie[ve]=L.charCodeAt(ve);return{ptr:Q,length:ie.length,free:function(){a.free(Q)}}}function re(){var L=a.hb_buffer_create();return{ptr:L,addText:function(Q){const ie=O(Q);a.hb_buffer_add_utf16(L,ie.ptr,ie.length,0,ie.length),ie.free()},guessSegmentProperties:function(){return a.hb_buffer_guess_segment_properties(L)},setDirection:function(Q){a.hb_buffer_set_direction(L,{ltr:4,rtl:5,ttb:6,btt:7}[Q]||0)},setFlags:function(Q){var ie=0;Q.forEach(function(ve){ie|=w(ve)}),a.hb_buffer_set_flags(L,ie)},setLanguage:function(Q){var ie=Y(Q);a.hb_buffer_set_language(L,a.hb_language_from_string(ie.ptr,-1)),ie.free()},setScript:function(Q){var ie=Y(Q);a.hb_buffer_set_script(L,a.hb_script_from_string(ie.ptr,-1)),ie.free()},setClusterLevel:function(Q){a.hb_buffer_set_cluster_level(L,Q)},json:function(){for(var Q=a.hb_buffer_get_length(L),ie=[],ve=a.hb_buffer_get_glyph_infos(L,0),_e=ve/4,Oe=a.hb_buffer_get_glyph_positions(L,0)/4,qe=r.HEAPU32.subarray(_e,_e+5*Q),Xe=r.HEAP32.subarray(Oe,Oe+5*Q),Ze=0;Ze<Q;++Ze)ie.push({g:qe[Ze*5+0],cl:qe[Ze*5+2],ax:Xe[Ze*5+0],ay:Xe[Ze*5+1],dx:Xe[Ze*5+2],dy:Xe[Ze*5+3],flags:a.hb_glyph_info_get_glyph_flags(ve+Ze*20)});return ie},destroy:function(){a.hb_buffer_destroy(L)}}}function q(L,Q,ie){var ve=0,_e=0;ie&&(ie=ie.split(","),ve=a.malloc(16*ie.length),ie.forEach(function(Oe,qe){var Xe=Y(Oe);a.hb_feature_from_string(Xe.ptr,-1,ve+_e*16)&&_e++,Xe.free()})),a.hb_shape(L.ptr,Q.ptr,ve,_e),ve&&a.free(ve)}function pe(L,Q,ie,ve,_e){var Oe=[],qe=h,Xe=!1,Ze=1024*1024,St=a.malloc(Ze),rt=function(R,X,Z,le){var he=s.decode(r.HEAPU8.subarray(Z,r.HEAPU8.indexOf(0,Z)));return he.startsWith("start table GSUB")?qe=g:he.startsWith("start table GPOS")&&(qe=m),qe!=_e&&(Xe=!1),_e!=h&&qe==_e&&he.startsWith("end lookup "+ve)&&(Xe=!0),Xe?0:(a.hb_buffer_serialize_glyphs(R,0,a.hb_buffer_get_length(R),St,Ze,0,X,_,C),Oe.push({m:he,t:JSON.parse(s.decode(r.HEAPU8.subarray(St,r.HEAPU8.indexOf(0,St)))),glyphs:a.hb_buffer_get_content_type(R)==d}),1)},M=n(rt,"iiiii");return a.hb_buffer_set_message_func(Q.ptr,M,0,0),q(L,Q,ie),a.free(St),o(M),Oe}function ce(){var L=a.malloc(12);a.hb_version(L,L+4,L+8);var Q={major:r.HEAPU32[L/4],minor:r.HEAPU32[(L+4)/4],micro:r.HEAPU32[(L+8)/4]};return a.free(L),Q}function ye(){var L=a.hb_version_string(),Q=s.decode(r.HEAPU8.subarray(L,r.HEAPU8.indexOf(0,L)));return Q}return{createBlob:x,createFace:b,createFont:T,createBuffer:re,shape:q,shapeWithTrace:pe,version:ce,version_string:ye}}try{t.exports=i}catch{}}});const jF=LF(),GF=Object.freeze(Object.defineProperty({__proto__:null,default:jF},Symbol.toStringTag,{value:"Module"}));var be,Yi=new Array(128).fill(void 0);Yi.push(void 0,null,!0,!1);var ks=Yi.length;function Ht(e){ks===Yi.length&&Yi.push(Yi.length+1);const t=ks;return ks=Yi[t],Yi[t]=e,t}function Ut(e){return Yi[e]}function WF(e){e<132||(Yi[e]=ks,ks=e)}function Ki(e){const t=Ut(e);return WF(e),t}var Ds=0,_s=null;function su(){return(_s===null||_s.byteLength===0)&&(_s=new Uint8Array(be.memory.buffer)),_s}var nu=typeof TextEncoder<"u"?new TextEncoder("utf-8"):{encode:()=>{throw Error("TextEncoder not available")}},YF=typeof nu.encodeInto=="function"?function(e,t){return nu.encodeInto(e,t)}:function(e,t){const i=nu.encode(e);return t.set(i),{read:e.length,written:i.length}};function Tc(e,t,i){if(i===void 0){const o=nu.encode(e),u=t(o.length,1)>>>0;return su().subarray(u,u+o.length).set(o),Ds=o.length,u}let r=e.length,a=t(r,1)>>>0;const s=su();let n=0;for(;n<r;n++){const o=e.charCodeAt(n);if(o>127)break;s[a+n]=o}if(n!==r){n!==0&&(e=e.slice(n)),a=i(a,r,r=n+e.length*3,1)>>>0;const o=su().subarray(a+n,a+r),u=YF(e,o);n+=u.written,a=i(a,r,n,1)>>>0}return Ds=n,a}function Oc(e){return e==null}var Ss=null;function _t(){return(Ss===null||Ss.byteLength===0)&&(Ss=new Int32Array(be.memory.buffer)),Ss}var tv=typeof TextDecoder<"u"?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}};typeof TextDecoder<"u"&&tv.decode();function ou(e,t){return e=e>>>0,tv.decode(su().subarray(e,e+t))}function KF(e,t){if(!(e instanceof t))throw new Error(`expected instance of ${t.name}`);return e.ptr}function XF(e,t){try{return e.apply(this,t)}catch(i){be.__wbindgen_exn_store(Ht(i))}}var iv=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>be.__wbg_bbox_free(e>>>0)),$c=class bv{static __wrap(t){t=t>>>0;const i=Object.create(bv.prototype);return i.__wbg_ptr=t,iv.register(i,i.__wbg_ptr,i),i}__destroy_into_raw(){const t=this.__wbg_ptr;return this.__wbg_ptr=0,iv.unregister(this),t}free(){const t=this.__destroy_into_raw();be.__wbg_bbox_free(t)}get x(){return be.__wbg_get_bbox_x(this.__wbg_ptr)}set x(t){be.__wbg_set_bbox_x(this.__wbg_ptr,t)}get y(){return be.__wbg_get_bbox_y(this.__wbg_ptr)}set y(t){be.__wbg_set_bbox_y(this.__wbg_ptr,t)}get width(){return be.__wbg_get_bbox_width(this.__wbg_ptr)}set width(t){be.__wbg_set_bbox_width(this.__wbg_ptr,t)}get height(){return be.__wbg_get_bbox_height(this.__wbg_ptr)}set height(t){be.__wbg_set_bbox_height(this.__wbg_ptr,t)}},av=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>be.__wbg_renderedimage_free(e>>>0)),HF=class vv{static __wrap(t){t=t>>>0;const i=Object.create(vv.prototype);return i.__wbg_ptr=t,av.register(i,i.__wbg_ptr,i),i}__destroy_into_raw(){const t=this.__wbg_ptr;return this.__wbg_ptr=0,av.unregister(this),t}free(){const t=this.__destroy_into_raw();be.__wbg_renderedimage_free(t)}get width(){return be.renderedimage_width(this.__wbg_ptr)>>>0}get height(){return be.renderedimage_height(this.__wbg_ptr)>>>0}asPng(){try{const a=be.__wbindgen_add_to_stack_pointer(-16);be.renderedimage_asPng(a,this.__wbg_ptr);var t=_t()[a/4+0],i=_t()[a/4+1],r=_t()[a/4+2];if(r)throw Ki(i);return Ki(t)}finally{be.__wbindgen_add_to_stack_pointer(16)}}get pixels(){const t=be.renderedimage_pixels(this.__wbg_ptr);return Ki(t)}},JF=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>be.__wbg_resvg_free(e>>>0)),qF=class{__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,JF.unregister(this),e}free(){const e=this.__destroy_into_raw();be.__wbg_resvg_free(e)}constructor(e,t,i){try{const u=be.__wbindgen_add_to_stack_pointer(-16);var r=Oc(t)?0:Tc(t,be.__wbindgen_malloc,be.__wbindgen_realloc),a=Ds;be.resvg_new(u,Ht(e),r,a,Oc(i)?0:Ht(i));var s=_t()[u/4+0],n=_t()[u/4+1],o=_t()[u/4+2];if(o)throw Ki(n);return this.__wbg_ptr=s>>>0,this}finally{be.__wbindgen_add_to_stack_pointer(16)}}get width(){return be.resvg_width(this.__wbg_ptr)}get height(){return be.resvg_height(this.__wbg_ptr)}render(){try{const r=be.__wbindgen_add_to_stack_pointer(-16);be.resvg_render(r,this.__wbg_ptr);var e=_t()[r/4+0],t=_t()[r/4+1],i=_t()[r/4+2];if(i)throw Ki(t);return HF.__wrap(e)}finally{be.__wbindgen_add_to_stack_pointer(16)}}toString(){let e,t;try{const a=be.__wbindgen_add_to_stack_pointer(-16);be.resvg_toString(a,this.__wbg_ptr);var i=_t()[a/4+0],r=_t()[a/4+1];return e=i,t=r,ou(i,r)}finally{be.__wbindgen_add_to_stack_pointer(16),be.__wbindgen_free(e,t,1)}}innerBBox(){const e=be.resvg_innerBBox(this.__wbg_ptr);return e===0?void 0:$c.__wrap(e)}getBBox(){const e=be.resvg_getBBox(this.__wbg_ptr);return e===0?void 0:$c.__wrap(e)}cropByBBox(e){KF(e,$c),be.resvg_cropByBBox(this.__wbg_ptr,e.__wbg_ptr)}imagesToResolve(){try{const r=be.__wbindgen_add_to_stack_pointer(-16);be.resvg_imagesToResolve(r,this.__wbg_ptr);var e=_t()[r/4+0],t=_t()[r/4+1],i=_t()[r/4+2];if(i)throw Ki(t);return Ki(e)}finally{be.__wbindgen_add_to_stack_pointer(16)}}resolveImage(e,t){try{const a=be.__wbindgen_add_to_stack_pointer(-16),s=Tc(e,be.__wbindgen_malloc,be.__wbindgen_realloc),n=Ds;be.resvg_resolveImage(a,this.__wbg_ptr,s,n,Ht(t));var i=_t()[a/4+0],r=_t()[a/4+1];if(r)throw Ki(i)}finally{be.__wbindgen_add_to_stack_pointer(16)}}};async function QF(e,t){if(typeof Response=="function"&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(e,t)}catch(r){if(e.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",r);else throw r}const i=await e.arrayBuffer();return await WebAssembly.instantiate(i,t)}else{const i=await WebAssembly.instantiate(e,t);return i instanceof WebAssembly.Instance?{instance:i,module:e}:i}}function eV(){const e={};return e.wbg={},e.wbg.__wbg_new_28c511d9baebfa89=function(t,i){const r=new Error(ou(t,i));return Ht(r)},e.wbg.__wbindgen_memory=function(){const t=be.memory;return Ht(t)},e.wbg.__wbg_buffer_12d079cc21e14bdb=function(t){const i=Ut(t).buffer;return Ht(i)},e.wbg.__wbg_newwithbyteoffsetandlength_aa4a17c33a06e5cb=function(t,i,r){const a=new Uint8Array(Ut(t),i>>>0,r>>>0);return Ht(a)},e.wbg.__wbindgen_object_drop_ref=function(t){Ki(t)},e.wbg.__wbg_new_63b92bc8671ed464=function(t){const i=new Uint8Array(Ut(t));return Ht(i)},e.wbg.__wbg_values_839f3396d5aac002=function(t){const i=Ut(t).values();return Ht(i)},e.wbg.__wbg_next_196c84450b364254=function(){return XF(function(t){const i=Ut(t).next();return Ht(i)},arguments)},e.wbg.__wbg_done_298b57d23c0fc80c=function(t){return Ut(t).done},e.wbg.__wbg_value_d93c65011f51a456=function(t){const i=Ut(t).value;return Ht(i)},e.wbg.__wbg_instanceof_Uint8Array_2b3bbecd033d19f6=function(t){let i;try{i=Ut(t)instanceof Uint8Array}catch{i=!1}return i},e.wbg.__wbindgen_string_get=function(t,i){const r=Ut(i),a=typeof r=="string"?r:void 0;var s=Oc(a)?0:Tc(a,be.__wbindgen_malloc,be.__wbindgen_realloc),n=Ds;_t()[t/4+1]=n,_t()[t/4+0]=s},e.wbg.__wbg_new_16b304a2cfa7ff4a=function(){const t=new Array;return Ht(t)},e.wbg.__wbindgen_string_new=function(t,i){const r=ou(t,i);return Ht(r)},e.wbg.__wbg_push_a5b05aedc7234f9f=function(t,i){return Ut(t).push(Ut(i))},e.wbg.__wbg_length_c20a40f15020d68a=function(t){return Ut(t).length},e.wbg.__wbg_set_a47bac70306a19a7=function(t,i,r){Ut(t).set(Ut(i),r>>>0)},e.wbg.__wbindgen_throw=function(t,i){throw new Error(ou(t,i))},e}function tV(e,t){return be=e.exports,rv.__wbindgen_wasm_module=t,Ss=null,_s=null,be}async function rv(e){if(be!==void 0)return be;typeof e>"u"&&(e=new URL("index_bg.wasm",void 0));const t=eV();(typeof e=="string"||typeof Request=="function"&&e instanceof Request||typeof URL=="function"&&e instanceof URL)&&(e=fetch(e));const{instance:i,module:r}=await QF(await e,t);return tV(i,r)}var iV=rv,Rc=!1,aV=async e=>{if(Rc)throw new Error("Already initialized. The `initWasm()` function can be used only once.");await iV(await e),Rc=!0},rV=class extends qF{constructor(e,t){if(!Rc)throw new Error("Wasm has not been initialized. Call `initWasm()` function.");const i=t?.font;if(i&&sV(i)){const r={...t,font:{...i,fontBuffers:void 0}};super(e,JSON.stringify(r),i.fontBuffers)}else super(e,JSON.stringify(t))}};function sV(e){return Object.prototype.hasOwnProperty.call(e,"fontBuffers")}const sv=Object.freeze(Object.defineProperty({__proto__:null,Resvg:rV,initWasm:aV},Symbol.toStringTag,{value:"Module"}));vi.Edit=dr,vi.ShotstackEdit=RF,Object.defineProperty(vi,Symbol.toStringTag,{value:"Module"})});
|