@shotstack/shotstack-studio 1.4.1 → 1.5.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.
@@ -1,4 +1,4 @@
1
- (function(M,V){typeof exports=="object"&&typeof module<"u"?V(exports,require("pixi.js"),require("howler"),require("opentype.js"),require("@ffmpeg/ffmpeg")):typeof define=="function"&&define.amd?define(["exports","pixi.js","howler","opentype.js","@ffmpeg/ffmpeg"],V):(M=typeof globalThis<"u"?globalThis:M||self,V(M.ShotstackStudio={},M.PIXI,M.Howler,M.opentype,M.ffmpeg))})(this,function(M,V,je,Ue,$e){"use strict";function Xt(a){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(a){for(const e in a)if(e!=="default"){const i=Object.getOwnPropertyDescriptor(a,e);Object.defineProperty(t,e,i.get?i:{enumerable:!0,get:()=>a[e]})}}return t.default=a,Object.freeze(t)}const y=Xt(V),We=Xt(je),me=Xt(Ue);class Xe{curves={};constructor(){this.initializeCurves()}initializeCurves(){this.curves={ease:[[.25,.1],[.25,1]],easeIn:[[.42,0],[1,1]],easeOut:[[0,0],[.58,1]],easeInOut:[[.42,0],[.58,1]],easeInQuad:[[.55,.085],[.68,.53]],easeInCubic:[[.55,.055],[.675,.19]],easeInQuart:[[.895,.03],[.685,.22]],easeInQuint:[[.755,.05],[.855,.06]],easeInSine:[[.47,0],[.745,.715]],easeInExpo:[[.95,.05],[.795,.035]],easeInCirc:[[.6,.04],[.98,.335]],easeInBack:[[.6,-.28],[.735,.045]],easeOutQuad:[[.25,.46],[.45,.94]],easeOutCubic:[[.215,.61],[.355,1]],easeOutQuart:[[.165,.84],[.44,1]],easeOutQuint:[[.23,1],[.32,1]],easeOutSine:[[.39,.575],[.565,1]],easeOutExpo:[[.19,1],[.22,1]],easeOutCirc:[[.075,.82],[.165,1]],easeOutBack:[[.175,.885],[.32,1.275]],easeInOutQuad:[[.455,.03],[.515,.955]],easeInOutCubic:[[.645,.045],[.355,1]],easeInOutQuart:[[.77,0],[.175,1]],easeInOutQuint:[[.86,0],[.07,1]],easeInOutSine:[[.445,.05],[.55,.95]],easeInOutExpo:[[1,0],[0,1]],easeInOutCirc:[[.785,.135],[.15,.86]],easeInOutBack:[[.68,-.55],[.265,1.55]]}}getValue(t,e,i,s){const n=this.curves[s??""]??this.curves.ease,[[r,o],[h,c]]=n,l=i+(3*r-3*h+1)*i*(1-i),g=t,p=t+(e-t)*o,w=t+(e-t)*c,I=e,_=l,D=1-_;return D**3*g+3*D**2*_*p+3*D*_**2*w+_**3*I}}class E{property;length;cubicBuilder;constructor(t,e,i=0){this.property=this.createKeyframes(t,e,i),this.length=e,this.cubicBuilder=new Xe}getValue(t){const e=this.property.find(s=>t>=s.start&&t<s.start+s.length);if(!e){if(this.property.length>0){if(t>=this.length)return this.property[this.property.length-1].to;if(t<0)return this.property[0].from}return 1}const i=(t-e.start)/e.length;switch(e.interpolation){case"bezier":return this.cubicBuilder.getValue(e.from,e.to,i,e.easing);case"constant":return e.from;case"linear":default:return e.from+(e.to-e.from)*i}}createKeyframes(t,e,i=0){if(typeof t=="number")return[{start:0,length:e,from:t,to:t}];if(!t.length)throw new Error("Keyframes should have at least one value.");const s=this.createNormalizedKeyframes(t);try{this.validateKeyframes(s)}catch(n){console.warn("Keyframe configuration issues detected:",n)}return this.insertFillerKeyframes(s,e,i)}createNormalizedKeyframes(t){return t.toSorted((e,i)=>e.start-i.start).map(e=>({...e,start:e.start*1e3,length:e.length*1e3}))}validateKeyframes(t){for(let e=0;e<t.length;e+=1){const i=t[e],s=t[e+1];if(!s){if(i.start+i.length>this.length)throw new Error("Last keyframe exceeds the maximum duration.");break}if(i.start+i.length>s.start)throw new Error("Overlapping keyframes detected.")}}insertFillerKeyframes(t,e,i=0){const s=[];for(let n=0;n<t.length;n+=1){const r=t[n],o=t[n+1];if(n===0&&r.start!==0){const l={start:0,length:r.start,from:i,to:r.from};s.push(l)}if(s.push(r),!o){if(r.start+r.length<e){const g=r.start+r.length,p={start:g,length:e-g,from:r.to,to:r.to};s.push(p)}break}if(r.start+r.length!==o.start){const l={start:r.start+r.length,length:o.start,from:r.to,to:o.from};s.push(l)}}return s}}class Ot{static Name="AudioLoadParser";name;extension;validAudioExtensions;constructor(){this.name=Ot.Name,this.extension={type:[y.ExtensionType.LoadParser],priority:y.LoaderParserPriority.Normal,ref:null},this.validAudioExtensions=["mp3","mpeg","ogg","wav"]}test(t){const e=t.split("?")[0]?.split(".").pop()??"";return this.validAudioExtensions.includes(e)}async load(t,e,i){return new Promise(s=>{const n={src:t},r=new Howl(n);r.on("load",()=>s(r)),r.on("loaderror",()=>s(null))})}unload(t){t?.unload()}}class Ye{clipConfiguration;constructor(t){this.clipConfiguration=t}build(t,e){const i=[],s=[],n=[],r=[],o=[],{effect:h,length:c}=this.clipConfiguration;if(!h)return{offsetXKeyframes:i,offsetYKeyframes:s,opacityKeyframes:n,scaleKeyframes:r,rotationKeyframes:o};const l=0;switch(this.getPresetName()){case"zoomIn":{const p=this.getZoomSpeed(),w=1*this.clipConfiguration.scale,I=p*this.clipConfiguration.scale;r.push({from:w,to:I,start:l,length:c,interpolation:"linear"});break}case"zoomOut":{const w=this.getZoomSpeed()*this.clipConfiguration.scale,I=1*this.clipConfiguration.scale;r.push({from:w,to:I,start:l,length:c,interpolation:"linear"});break}case"slideLeft":{let p=this.getSlideStart();const w=t.width+t.width*p*2,I=e.height/e.width*t.height;if(I<w){const _=Math.abs(w/t.width);r.push({from:_,to:_,start:l,length:c,interpolation:"linear"})}else p=(I-t.width)/2/t.width;i.push({from:p,to:-p,start:l,length:c});break}case"slideRight":{let p=this.getSlideStart();const w=t.width+t.width*p*2,I=e.height/e.width*t.height;if(I<w){const _=Math.abs(w/t.width);r.push({from:_,to:_,start:l,length:c,interpolation:"linear"})}else p=(I-t.width)/2/t.width;i.push({from:-p,to:p,start:l,length:c});break}case"slideUp":{let p=this.getSlideStart();const w=t.height+t.height*p*2,I=e.height/e.width*t.width;if(I<w){const _=Math.abs(w/t.height);r.push({from:_,to:_,start:l,length:c,interpolation:"linear"})}else p=(I-t.height)/2/t.height;s.push({from:p,to:-p,start:l,length:c});break}case"slideDown":{let p=this.getSlideStart();const w=t.height+t.height*p*2,I=e.height/e.width*t.width;if(I<w){const _=Math.abs(w/t.height);r.push({from:_,to:_,start:l,length:c,interpolation:"linear"})}else p=(I-t.height)/2/t.height;s.push({from:-p,to:p,start:l,length:c});break}}return{offsetXKeyframes:i,offsetYKeyframes:s,opacityKeyframes:n,scaleKeyframes:r,rotationKeyframes:o}}getPresetName(){const[t]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);return t}getZoomSpeed(){const[t,e]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);if(t.startsWith("zoom"))switch(e){case"Slow":return 1.1;case"Fast":return 1.7;default:return 1.3}return 0}getSlideStart(){const[t,e]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);if(t.startsWith("slide"))switch(e){case"Slow":return .03;case"Fast":return 1.7;default:return .12}return 0}}class Ge{clipConfiguration;constructor(t){this.clipConfiguration=t}build(){const t=[],e=[],i=[],s=[],n=[],r=this.buildInPreset();t.push(...r.offsetXKeyframes),e.push(...r.offsetYKeyframes),i.push(...r.opacityKeyframes),s.push(...r.scaleKeyframes),n.push(...r.rotationKeyframes);const o=this.buildOutPreset();return t.push(...o.offsetXKeyframes),e.push(...o.offsetYKeyframes),i.push(...o.opacityKeyframes),s.push(...o.scaleKeyframes),n.push(...o.rotationKeyframes),{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n}}buildInPreset(){const t=[],e=[],i=[],s=[],n=[];if(!this.clipConfiguration.transition?.in)return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n};const r=0,o=this.getInPresetLength();switch(this.getInPresetName()){case"fade":{const l=Math.max(0,Math.min(this.clipConfiguration.opacity??1,1));i.push({from:0,to:l,start:r,length:o,interpolation:"linear"});break}case"zoom":{const l=this.clipConfiguration.scale+9,g=this.clipConfiguration.scale;s.push({from:l,to:g,start:r,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:r,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideLeft":{const c=this.clipConfiguration.offset?.x+.025,l=this.clipConfiguration.offset?.x;t.push({from:c,to:l,start:r,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:r,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideRight":{const c=this.clipConfiguration.offset?.x-.025,l=this.clipConfiguration.offset?.x;t.push({from:c,to:l,start:r,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:r,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideUp":{const c=this.clipConfiguration.offset?.y+.025,l=this.clipConfiguration.offset?.y;e.push({from:c,to:l,start:r,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:r,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideDown":{const c=this.clipConfiguration.offset?.y-.025,l=this.clipConfiguration.offset?.y;e.push({from:c,to:l,start:r,length:o,interpolation:"bezier",easing:"easeOut"}),i.push({from:0,to:1,start:r,length:o,interpolation:"bezier",easing:"easeOut"});break}case"carouselLeft":case"carouselRight":case"carouselUp":case"carouselDown":case"shuffleTopRight":case"shuffleRightTop":case"shuffleRightBottom":case"shuffleBottomRight":case"shuffleBottomLeft":case"shuffleLeftBottom":case"shuffleLeftTop":case"shuffleTopLeft":default:console.warn(`Unimplemented transition:in preset "${this.clipConfiguration.transition.in}"`);break}return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n}}buildOutPreset(){const t=[],e=[],i=[],s=[],n=[];if(!this.clipConfiguration.transition?.out)return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n};const r=this.getOutPresetLength(),o=this.clipConfiguration.length-r;switch(this.getOutPresetName()){case"fade":{const c=Math.max(0,Math.min(this.clipConfiguration.opacity??1,1));i.push({from:c,to:0,start:o,length:r,interpolation:"linear"});break}case"zoom":{const l=this.clipConfiguration.scale,g=l+9;s.push({from:l,to:g,start:o,length:r,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:o,length:r,interpolation:"bezier",easing:"easeOut"});break}case"slideLeft":{const c=this.clipConfiguration.offset?.x,l=c-.025;t.push({from:c,to:l,start:o,length:r,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:o,length:r,interpolation:"bezier",easing:"easeOut"});break}case"slideRight":{const c=this.clipConfiguration.offset?.x,l=c+.025;t.push({from:c,to:l,start:o,length:r,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:o,length:r,interpolation:"bezier",easing:"easeOut"});break}case"slideUp":{const c=this.clipConfiguration.offset?.y,l=c-.025;e.push({from:c,to:l,start:o,length:r,interpolation:"bezier",easing:"easeIn"}),i.push({from:1,to:0,start:o,length:r,interpolation:"bezier",easing:"easeIn"});break}case"slideDown":{const c=this.clipConfiguration.offset?.y,l=c+.025;e.push({from:c,to:l,start:o,length:r,interpolation:"bezier",easing:"easeIn"}),i.push({from:1,to:0,start:o,length:r,interpolation:"bezier",easing:"easeIn"});break}case"carouselLeft":case"carouselRight":case"carouselUp":case"carouselDown":case"shuffleTopRight":case"shuffleRightTop":case"shuffleRightBottom":case"shuffleBottomRight":case"shuffleBottomLeft":case"shuffleLeftBottom":case"shuffleLeftTop":case"shuffleTopLeft":default:console.warn(`Unimplemented transition:out preset "${this.clipConfiguration.transition.out}"`);break}return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n}}getInPresetName(){const[t]=(this.clipConfiguration.transition?.in??"").split(/(Slow|Fast|VeryFast)/);return t}getOutPresetName(){const[t]=(this.clipConfiguration.transition?.out??"").split(/(Slow|Fast|VeryFast)/);return t}getInPresetLength(){const[,t]=(this.clipConfiguration.transition?.in??"").split(/(Slow|Fast|VeryFast)/);switch(t){case"Slow":return 2;case"Fast":return .5;case"VeryFast":return .25;default:return 1}}getOutPresetLength(){const[,t]=(this.clipConfiguration.transition?.out??"").split(/(Slow|Fast|VeryFast)/);switch(t){case"Slow":return 2;case"Fast":return .5;case"VeryFast":return .25;default:return 1}}}class qe{static ButtonLeftClick=0;static ButtonRightClick=3}class Qe{containerSize;constructor(t){this.containerSize=t}relativeToAbsolute(t,e,i){switch(e){case"topLeft":return{x:i.x*this.containerSize.width,y:-i.y*this.containerSize.height};case"topRight":return{x:(i.x+1)*this.containerSize.width-t.width,y:-i.y*this.containerSize.height};case"bottomLeft":return{x:i.x*this.containerSize.width,y:(-i.y+1)*this.containerSize.height-t.height};case"bottomRight":return{x:(i.x+1)*this.containerSize.width-t.width,y:(-i.y+1)*this.containerSize.height-t.height};case"left":return{x:i.x*this.containerSize.width,y:(-i.y+.5)*this.containerSize.height-t.height/2};case"right":return{x:(i.x+1)*this.containerSize.width-t.width,y:(-i.y+.5)*this.containerSize.height-t.height/2};case"top":return{x:(i.x+.5)*this.containerSize.width-t.width/2,y:-i.y*this.containerSize.height};case"bottom":return{x:(i.x+.5)*this.containerSize.width-t.width/2,y:(-i.y+1)*this.containerSize.height-t.height};case"center":default:return{x:(i.x+.5)*this.containerSize.width-t.width/2,y:(-i.y+.5)*this.containerSize.height-t.height/2}}}absoluteToRelative(t,e,i){switch(e){case"topLeft":return{x:i.x/this.containerSize.width,y:-(i.y/this.containerSize.height)};case"topRight":return{x:(i.x+t.width)/this.containerSize.width-1,y:-(i.y/this.containerSize.height)};case"bottomLeft":return{x:i.x/this.containerSize.width,y:-((i.y+t.height)/this.containerSize.height-1)};case"bottomRight":return{x:(i.x+t.width)/this.containerSize.width-1,y:-((i.y+t.height)/this.containerSize.height-1)};case"left":return{x:i.x/this.containerSize.width,y:-((i.y+t.height/2)/this.containerSize.height-.5)};case"right":return{x:(i.x+t.width)/this.containerSize.width-1,y:-((i.y+t.height/2)/this.containerSize.height-.5)};case"top":return{x:(i.x+t.width/2)/this.containerSize.width-.5,y:-(i.y/this.containerSize.height)};case"bottom":return{x:(i.x+t.width/2)/this.containerSize.width-.5,y:-((i.y+t.height)/this.containerSize.height-1)};case"center":default:return{x:(i.x+t.width/2)/this.containerSize.width-.5,y:-((i.y+t.height/2)/this.containerSize.height-.5)}}}}class Yt{container;constructor(){this.container=new y.Container}getContainer(){return this.container}}class P extends Yt{static SnapThreshold=20;static DiscardedFrameCount=Math.ceil(1/30*1e3);static ScaleHandleRadius=10;static RotationHandleRadius=10;static RotationHandleOffset=50;static OutlineWidth=5;static MinScale=.1;static MaxScale=5;layer;shouldDispose;edit;clipConfiguration;positionBuilder;offsetXKeyframeBuilder;offsetYKeyframeBuilder;scaleKeyframeBuilder;opacityKeyframeBuilder;rotationKeyframeBuilder;outline;topLeftScaleHandle;topRightScaleHandle;bottomLeftScaleHandle;bottomRightScaleHandle;rotationHandle;isHovering;isDragging;dragOffset;scaleDirection;scaleStart;scaleOffset;isRotating;rotationStart;rotationOffset;initialClipConfiguration;constructor(t,e){super(),this.edit=t,this.layer=0,this.shouldDispose=!1,this.clipConfiguration=e,this.positionBuilder=new Qe(t.size),this.outline=null,this.topLeftScaleHandle=null,this.topRightScaleHandle=null,this.bottomRightScaleHandle=null,this.bottomLeftScaleHandle=null,this.rotationHandle=null,this.isHovering=!1,this.isDragging=!1,this.dragOffset={x:0,y:0},this.scaleDirection=null,this.scaleStart=null,this.scaleOffset={x:0,y:0},this.isRotating=!1,this.rotationStart=null,this.rotationOffset={x:0,y:0},this.initialClipConfiguration=null}reconfigureAfterRestore(){this.configureKeyframes()}configureKeyframes(){if(this.offsetXKeyframeBuilder=new E(this.clipConfiguration.offset?.x??0,this.getLength()),this.offsetYKeyframeBuilder=new E(this.clipConfiguration.offset?.y??0,this.getLength()),this.scaleKeyframeBuilder=new E(this.clipConfiguration.scale??1,this.getLength(),1),this.opacityKeyframeBuilder=new E(this.clipConfiguration.opacity??1,this.getLength(),1),this.rotationKeyframeBuilder=new E(this.clipConfiguration.transform?.rotate?.angle??0,this.getLength()),this.clipHasKeyframes())return;const t=[],e=[],i=[],s=[],n=[],r=new Ye(this.clipConfiguration).build(this.edit.size,this.getSize());t.push(...r.offsetXKeyframes),e.push(...r.offsetYKeyframes),i.push(...r.opacityKeyframes),s.push(...r.scaleKeyframes),n.push(...r.rotationKeyframes);const o=new Ge(this.clipConfiguration).build();t.push(...o.offsetXKeyframes),e.push(...o.offsetYKeyframes),i.push(...o.opacityKeyframes),s.push(...o.scaleKeyframes),n.push(...o.rotationKeyframes),t.length&&(this.offsetXKeyframeBuilder=new E(t,this.getLength())),e.length&&(this.offsetYKeyframeBuilder=new E(e,this.getLength())),i.length&&(this.opacityKeyframeBuilder=new E(i,this.getLength(),1)),s.length&&(this.scaleKeyframeBuilder=new E(s,this.getLength(),1)),n.length&&(this.rotationKeyframeBuilder=new E(n,this.getLength()))}async load(){this.outline=new y.Graphics,this.getContainer().addChild(this.outline),this.topLeftScaleHandle=new y.Graphics,this.topRightScaleHandle=new y.Graphics,this.bottomRightScaleHandle=new y.Graphics,this.bottomLeftScaleHandle=new y.Graphics,this.getContainer().addChild(this.topLeftScaleHandle),this.getContainer().addChild(this.topRightScaleHandle),this.getContainer().addChild(this.bottomRightScaleHandle),this.getContainer().addChild(this.bottomLeftScaleHandle),this.rotationHandle=new y.Graphics,this.getContainer().addChild(this.rotationHandle),this.getContainer().cursor="pointer",this.getContainer().eventMode="static",this.getContainer().on("pointerdown",this.onPointerStart.bind(this)),this.getContainer().on("pointermove",this.onPointerMove.bind(this)),this.getContainer().on("globalpointermove",this.onPointerMove.bind(this)),this.getContainer().on("pointerup",this.onPointerUp.bind(this)),this.getContainer().on("pointerupoutside",this.onPointerUp.bind(this)),this.getContainer().on("pointerover",this.onPointerOver.bind(this)),this.getContainer().on("pointerout",this.onPointerOut.bind(this))}update(t,e){if(this.getContainer().visible=this.isActive(),this.getContainer().zIndex=this.layer,!this.isActive())return;const i=this.getPivot(),s=this.getPosition(),n=this.getScale();this.getContainer().scale.set(n),this.getContainer().pivot.set(i.x,i.y),this.getContainer().position.set(s.x+i.x,s.y+i.y);const r=this.getRotation();this.getContainer().alpha=this.getOpacity(),this.getContainer().angle=r,this.shouldDiscardFrame()&&(this.getContainer().alpha=0)}draw(){if(!this.outline)return;if((!this.isActive()||this.edit.getSelectedClip()!==this)&&!this.isHovering){this.outline.clear(),this.topLeftScaleHandle?.clear(),this.topRightScaleHandle?.clear(),this.bottomRightScaleHandle?.clear(),this.bottomLeftScaleHandle?.clear(),this.rotationHandle?.clear();return}const t=this.isHovering||this.isDragging?65535:16777215,e=this.getSize(),i=this.getScale();if(this.outline.clear(),this.outline.strokeStyle={width:P.OutlineWidth/i,color:t},this.outline.rect(0,0,e.width,e.height),this.outline.stroke(),!this.topLeftScaleHandle||!this.topRightScaleHandle||!this.bottomRightScaleHandle||!this.bottomLeftScaleHandle||!this.isActive()||this.edit.getSelectedClip()!==this)return;this.topLeftScaleHandle.fillStyle={color:t},this.topLeftScaleHandle.clear();const s=P.ScaleHandleRadius*2/i;if(this.topLeftScaleHandle.rect(-s/2,-s/2,s,s),this.topLeftScaleHandle.fill(),this.topRightScaleHandle.fillStyle={color:t},this.topRightScaleHandle.clear(),this.topRightScaleHandle.rect(e.width-s/2,-s/2,s,s),this.topRightScaleHandle.fill(),this.bottomRightScaleHandle.fillStyle={color:t},this.bottomRightScaleHandle.clear(),this.bottomRightScaleHandle.rect(e.width-s/2,e.height-s/2,s,s),this.bottomRightScaleHandle.fill(),this.bottomLeftScaleHandle.fillStyle={color:t},this.bottomLeftScaleHandle.clear(),this.bottomLeftScaleHandle.rect(-s/2,e.height-s/2,s,s),this.bottomLeftScaleHandle.fill(),!this.rotationHandle)return;const n=e.width/2,r=-50/i;this.rotationHandle.clear(),this.rotationHandle.fillStyle={color:t},this.rotationHandle.circle(n,r,P.RotationHandleRadius/i),this.rotationHandle.fill(),this.outline.strokeStyle={width:P.OutlineWidth/i,color:t},this.outline.moveTo(n,0),this.outline.lineTo(n,r),this.outline.stroke()}dispose(){this.outline?.destroy(),this.outline=null,this.topLeftScaleHandle?.destroy(),this.topLeftScaleHandle=null,this.topRightScaleHandle?.destroy(),this.topRightScaleHandle=null,this.bottomLeftScaleHandle?.destroy(),this.bottomLeftScaleHandle=null,this.bottomRightScaleHandle?.destroy(),this.bottomRightScaleHandle=null,this.rotationHandle?.destroy(),this.rotationHandle=null}getStart(){return this.clipConfiguration.start*1e3}getLength(){return this.clipConfiguration.length*1e3}getEnd(){return this.getStart()+this.getLength()}getPlaybackTime(){const t=this.edit.playbackTime-this.getStart();return t<0?0:t>this.getLength()?this.getLength():t}getOpacity(){return this.opacityKeyframeBuilder?.getValue(this.getPlaybackTime())??1}getPosition(){const t={x:this.offsetXKeyframeBuilder?.getValue(this.getPlaybackTime())??0,y:this.offsetYKeyframeBuilder?.getValue(this.getPlaybackTime())??0};return this.positionBuilder.relativeToAbsolute(this.getSize(),this.clipConfiguration.position??"center",t)}getPivot(){const t=this.getSize();return{x:t.width/2,y:t.height/2}}getFitScale(){switch(this.clipConfiguration.fit??"crop"){case"crop":return Math.max(this.edit.size.width/this.getSize().width,this.edit.size.height/this.getSize().height);case"cover":return Math.max(this.edit.size.width/this.getSize().width,this.edit.size.height/this.getSize().height);case"contain":return Math.min(this.edit.size.width/this.getSize().width,this.edit.size.height/this.getSize().height);case"none":default:return 1}}getScale(){return(this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1)*this.getFitScale()}getRotation(){return this.rotationKeyframeBuilder?.getValue(this.getPlaybackTime())??0}isActive(){return this.edit.playbackTime>=this.getStart()&&this.edit.playbackTime<this.getEnd()}shouldDiscardFrame(){return this.getPlaybackTime()<P.DiscardedFrameCount}onPointerStart(t){if(t.button!==qe.ButtonLeftClick||(this.edit.setSelectedClip(this),this.initialClipConfiguration=structuredClone(this.clipConfiguration),this.clipHasKeyframes()))return;if(this.scaleDirection=null,this.topLeftScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="topLeft"),this.topRightScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="topRight"),this.bottomRightScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="bottomRight"),this.bottomLeftScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="bottomLeft"),this.scaleDirection!==null){this.scaleStart=this.getScale()/this.getFitScale();const h=t.getLocalPosition(this.edit.getContainer());this.scaleOffset=h;return}if(this.rotationHandle?.getBounds().containsPoint(t.globalX,t.globalY)){this.isRotating=!0,this.rotationStart=this.getRotation();const h=t.getLocalPosition(this.edit.getContainer());this.rotationOffset=h;return}this.isDragging=!0;const o=t.getLocalPosition(this.edit.getContainer());this.dragOffset={x:o.x-this.getContainer().position.x,y:o.y-this.getContainer().position.y}}onPointerMove(t){if(this.scaleDirection!==null&&this.scaleStart!==null){const e=t.getLocalPosition(this.edit.getContainer()),i=this.getPosition(),s=this.getPivot(),n={x:i.x+s.x,y:i.y+s.y},r=Math.sqrt((this.scaleOffset.x-n.x)**2+(this.scaleOffset.y-n.y)**2),h=Math.sqrt((e.x-n.x)**2+(e.y-n.y)**2)/r,c=this.scaleStart*h;this.clipConfiguration.scale=Math.max(P.MinScale,Math.min(c,P.MaxScale)),this.scaleKeyframeBuilder=new E(this.clipConfiguration.scale,this.getLength(),1);return}if(this.isRotating&&this.rotationStart!==null){const e=t.getLocalPosition(this.edit.getContainer()),i=this.getPosition(),s=this.getPivot(),n={x:i.x+s.x,y:i.y+s.y},r=Math.atan2(this.rotationOffset.y-n.y,this.rotationOffset.x-n.x),h=(Math.atan2(e.y-n.y,e.x-n.x)-r)*(180/Math.PI);let c=this.rotationStart+h;const l=45,g=c%l,p=2;Math.abs(g)<p?c=Math.floor(c/l)*l:Math.abs(g-l)<p&&(c=Math.ceil(c/l)*l),this.clipConfiguration.transform||(this.clipConfiguration.transform={rotate:{angle:0}}),this.clipConfiguration.transform.rotate||(this.clipConfiguration.transform.rotate={angle:0}),this.clipConfiguration.transform.rotate.angle=c,this.rotationKeyframeBuilder=new E(this.clipConfiguration.transform.rotate.angle,this.getLength());return}if(this.isDragging){const e=t.getLocalPosition(this.edit.getContainer()),i=this.getPivot(),s={x:e.x-this.dragOffset.x,y:e.y-this.dragOffset.y},n={x:s.x-i.x,y:s.y-i.y},r=[{x:0,y:0},{x:this.edit.size.width,y:0},{x:0,y:this.edit.size.height},{x:this.edit.size.width,y:this.edit.size.height}],o={x:this.edit.size.width/2,y:this.edit.size.height/2},h=[...r,o],c=[{x:n.x,y:n.y},{x:n.x+this.getSize().width,y:n.y},{x:n.x,y:n.y+this.getSize().height},{x:n.x+this.getSize().width,y:n.y+this.getSize().height}],l={x:n.x+this.getSize().width/2,y:n.y+this.getSize().height/2},g=[...c,l];let p=P.SnapThreshold,w=P.SnapThreshold,I=null,_=null;for(const N of g)for(const yt of h){const G=Math.abs(N.x-yt.x);G<p&&(p=G,I=n.x+(yt.x-N.x));const vt=Math.abs(N.y-yt.y);vt<w&&(w=vt,_=n.y+(yt.y-N.y))}I!==null&&(n.x=I),_!==null&&(n.y=_);const D=this.positionBuilder.absoluteToRelative(this.getSize(),this.clipConfiguration.position??"center",n);this.clipConfiguration.offset||(this.clipConfiguration.offset={x:0,y:0}),this.clipConfiguration.offset.x=D.x,this.clipConfiguration.offset.y=D.y,this.offsetXKeyframeBuilder=new E(this.clipConfiguration.offset.x,this.getLength()),this.offsetYKeyframeBuilder=new E(this.clipConfiguration.offset.y,this.getLength())}}onPointerUp(){(this.isDragging||this.scaleDirection!==null||this.isRotating)&&this.hasStateChanged()&&this.edit.setUpdatedClip(this,this.initialClipConfiguration,structuredClone(this.clipConfiguration)),this.isDragging=!1,this.dragOffset={x:0,y:0},this.scaleDirection=null,this.scaleStart=null,this.scaleOffset={x:0,y:0},this.isRotating=!1,this.rotationStart=null,this.rotationOffset={x:0,y:0},this.initialClipConfiguration=null}onPointerOver(){this.isHovering=!0}onPointerOut(){this.isHovering=!1}clipHasPresets(){return!!this.clipConfiguration.effect||!!this.clipConfiguration.transition?.in||!!this.clipConfiguration.transition?.out}clipHasKeyframes(){return[this.clipConfiguration.scale,this.clipConfiguration.offset?.x,this.clipConfiguration.offset?.y,this.clipConfiguration.transform?.rotate?.angle].some(t=>t&&typeof t!="number")}hasStateChanged(){if(!this.initialClipConfiguration)return!1;const t=this.clipConfiguration.offset?.x,e=this.clipConfiguration.offset?.y,i=this.clipConfiguration.scale,s=Number(this.clipConfiguration.transform?.rotate?.angle??0),n=this.initialClipConfiguration.offset?.x,r=this.initialClipConfiguration.offset?.y,o=this.initialClipConfiguration.scale,h=Number(this.initialClipConfiguration.transform?.rotate?.angle??0);return n!==void 0&&t!==n||r!==void 0&&e!==r||o!==void 0&&i!==o||s!==h}}class Gt extends P{audioResource;isPlaying;volumeKeyframeBuilder;syncTimer;constructor(t,e){super(t,e),this.audioResource=null,this.isPlaying=!1;const i=e.asset;this.volumeKeyframeBuilder=new E(i.volume??1,this.getLength()),this.syncTimer=0}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src,i={src:e,loadParser:Ot.Name},s=await this.edit.assetLoader.load(e,i);if(!(s instanceof We.Howl))throw new Error(`Invalid audio source '${t.src}'.`);this.audioResource=s,this.configureKeyframes()}update(t,e){super.update(t,e);const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=e,this.getContainer().alpha=0,!this.audioResource)return;const s=this.edit.isPlaying&&this.isActive(),n=this.getPlaybackTime();s&&(this.isPlaying||(this.isPlaying=!0,this.audioResource.seek(n/1e3+i),this.audioResource.play()),this.audioResource.volume()!==this.getVolume()&&this.audioResource.volume(this.getVolume()),Math.abs((this.audioResource.seek()-i)*1e3-n)>100&&this.audioResource.seek(n/1e3+i)),this.isPlaying&&!s&&(this.isPlaying=!1,this.audioResource.pause());const r=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&r&&(this.syncTimer=0,this.audioResource.seek(n/1e3+i))}draw(){super.draw()}dispose(){this.audioResource?.unload(),this.audioResource=null}getSize(){return{width:0,height:0}}getVolume(){return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}}var Je=`in vec2 aPosition;
1
+ (function(H,Z){typeof exports=="object"&&typeof module<"u"?Z(exports,require("pixi.js"),require("howler"),require("opentype.js"),require("@ffmpeg/ffmpeg")):typeof define=="function"&&define.amd?define(["exports","pixi.js","howler","opentype.js","@ffmpeg/ffmpeg"],Z):(H=typeof globalThis<"u"?globalThis:H||self,Z(H.ShotstackStudio={},H.PIXI,H.Howler,H.opentype,H.FFmpeg))})(this,function(H,Z,ci,hi,di){"use strict";function ae(r){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const e in r)if(e!=="default"){const i=Object.getOwnPropertyDescriptor(r,e);Object.defineProperty(t,e,i.get?i:{enumerable:!0,get:()=>r[e]})}}return t.default=r,Object.freeze(t)}const d=ae(Z),ui=ae(ci),Ie=ae(hi);class pi{curves={};constructor(){this.initializeCurves()}initializeCurves(){this.curves={ease:[[.25,.1],[.25,1]],easeIn:[[.42,0],[1,1]],easeOut:[[0,0],[.58,1]],easeInOut:[[.42,0],[.58,1]],easeInQuad:[[.55,.085],[.68,.53]],easeInCubic:[[.55,.055],[.675,.19]],easeInQuart:[[.895,.03],[.685,.22]],easeInQuint:[[.755,.05],[.855,.06]],easeInSine:[[.47,0],[.745,.715]],easeInExpo:[[.95,.05],[.795,.035]],easeInCirc:[[.6,.04],[.98,.335]],easeInBack:[[.6,-.28],[.735,.045]],easeOutQuad:[[.25,.46],[.45,.94]],easeOutCubic:[[.215,.61],[.355,1]],easeOutQuart:[[.165,.84],[.44,1]],easeOutQuint:[[.23,1],[.32,1]],easeOutSine:[[.39,.575],[.565,1]],easeOutExpo:[[.19,1],[.22,1]],easeOutCirc:[[.075,.82],[.165,1]],easeOutBack:[[.175,.885],[.32,1.275]],easeInOutQuad:[[.455,.03],[.515,.955]],easeInOutCubic:[[.645,.045],[.355,1]],easeInOutQuart:[[.77,0],[.175,1]],easeInOutQuint:[[.86,0],[.07,1]],easeInOutSine:[[.445,.05],[.55,.95]],easeInOutExpo:[[1,0],[0,1]],easeInOutCirc:[[.785,.135],[.15,.86]],easeInOutBack:[[.68,-.55],[.265,1.55]]}}getValue(t,e,i,s){const n=this.curves[s??""]??this.curves.ease,[[a,o],[l,c]]=n,h=i+(3*a-3*l+1)*i*(1-i),p=t,f=t+(e-t)*o,v=t+(e-t)*c,I=e,b=h,O=1-b;return O**3*p+3*O**2*b*f+3*O*b**2*v+b**3*I}}class R{property;length;cubicBuilder;constructor(t,e,i=0){this.property=this.createKeyframes(t,e,i),this.length=e,this.cubicBuilder=new pi}getValue(t){const e=this.property.find(s=>t>=s.start&&t<s.start+s.length);if(!e){if(this.property.length>0){if(t>=this.length)return this.property[this.property.length-1].to;if(t<0)return this.property[0].from}return 1}const i=(t-e.start)/e.length;switch(e.interpolation){case"bezier":return this.cubicBuilder.getValue(e.from,e.to,i,e.easing);case"constant":return e.from;case"linear":default:return e.from+(e.to-e.from)*i}}createKeyframes(t,e,i=0){if(typeof t=="number")return[{start:0,length:e,from:t,to:t}];if(!t.length)throw new Error("Keyframes should have at least one value.");const s=this.createNormalizedKeyframes(t);try{this.validateKeyframes(s)}catch(n){console.warn("Keyframe configuration issues detected:",n)}return this.insertFillerKeyframes(s,e,i)}createNormalizedKeyframes(t){return t.toSorted((e,i)=>e.start-i.start).map(e=>({...e,start:e.start*1e3,length:e.length*1e3}))}validateKeyframes(t){for(let e=0;e<t.length;e+=1){const i=t[e],s=t[e+1];if(!s){if(i.start+i.length>this.length)throw new Error("Last keyframe exceeds the maximum duration.");break}if(i.start+i.length>s.start)throw new Error("Overlapping keyframes detected.")}}insertFillerKeyframes(t,e,i=0){const s=[];for(let n=0;n<t.length;n+=1){const a=t[n],o=t[n+1];if(n===0&&a.start!==0){const h={start:0,length:a.start,from:i,to:a.from};s.push(h)}if(s.push(a),!o){if(a.start+a.length<e){const p=a.start+a.length,f={start:p,length:e-p,from:a.to,to:a.to};s.push(f)}break}if(a.start+a.length!==o.start){const h={start:a.start+a.length,length:o.start,from:a.to,to:o.from};s.push(h)}}return s}}class Bt{static Name="AudioLoadParser";name;extension;validAudioExtensions;constructor(){this.name=Bt.Name,this.extension={type:[d.ExtensionType.LoadParser],priority:d.LoaderParserPriority.Normal,ref:null},this.validAudioExtensions=["mp3","mpeg","ogg","wav"]}test(t){const e=t.split("?")[0]?.split(".").pop()??"";return this.validAudioExtensions.includes(e)}async load(t,e,i){return new Promise(s=>{const n={src:t},a=new Howl(n);a.on("load",()=>s(a)),a.on("loaderror",()=>s(null))})}unload(t){t?.unload()}}class fi{clipConfiguration;constructor(t){this.clipConfiguration=t}build(t,e){const i=[],s=[],n=[],a=[],o=[],{effect:l,length:c}=this.clipConfiguration;if(!l)return{offsetXKeyframes:i,offsetYKeyframes:s,opacityKeyframes:n,scaleKeyframes:a,rotationKeyframes:o};const h=0;switch(this.getPresetName()){case"zoomIn":{const f=this.getZoomSpeed(),v=1*this.clipConfiguration.scale,I=f*this.clipConfiguration.scale;a.push({from:v,to:I,start:h,length:c,interpolation:"linear"});break}case"zoomOut":{const v=this.getZoomSpeed()*this.clipConfiguration.scale,I=1*this.clipConfiguration.scale;a.push({from:v,to:I,start:h,length:c,interpolation:"linear"});break}case"slideLeft":{let f=this.getSlideStart();const v=t.width+t.width*f*2,I=e.height/e.width*t.height;if(I<v){const b=Math.abs(v/t.width);a.push({from:b,to:b,start:h,length:c,interpolation:"linear"})}else f=(I-t.width)/2/t.width;i.push({from:f,to:-f,start:h,length:c});break}case"slideRight":{let f=this.getSlideStart();const v=t.width+t.width*f*2,I=e.height/e.width*t.height;if(I<v){const b=Math.abs(v/t.width);a.push({from:b,to:b,start:h,length:c,interpolation:"linear"})}else f=(I-t.width)/2/t.width;i.push({from:-f,to:f,start:h,length:c});break}case"slideUp":{let f=this.getSlideStart();const v=t.height+t.height*f*2,I=e.height/e.width*t.width;if(I<v){const b=Math.abs(v/t.height);a.push({from:b,to:b,start:h,length:c,interpolation:"linear"})}else f=(I-t.height)/2/t.height;s.push({from:f,to:-f,start:h,length:c});break}case"slideDown":{let f=this.getSlideStart();const v=t.height+t.height*f*2,I=e.height/e.width*t.width;if(I<v){const b=Math.abs(v/t.height);a.push({from:b,to:b,start:h,length:c,interpolation:"linear"})}else f=(I-t.height)/2/t.height;s.push({from:-f,to:f,start:h,length:c});break}}return{offsetXKeyframes:i,offsetYKeyframes:s,opacityKeyframes:n,scaleKeyframes:a,rotationKeyframes:o}}getPresetName(){const[t]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);return t}getZoomSpeed(){const[t,e]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);if(t.startsWith("zoom"))switch(e){case"Slow":return 1.1;case"Fast":return 1.7;default:return 1.3}return 0}getSlideStart(){const[t,e]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);if(t.startsWith("slide"))switch(e){case"Slow":return .03;case"Fast":return 1.7;default:return .12}return 0}}class gi{clipConfiguration;constructor(t){this.clipConfiguration=t}build(){const t=[],e=[],i=[],s=[],n=[],a=this.buildInPreset();t.push(...a.offsetXKeyframes),e.push(...a.offsetYKeyframes),i.push(...a.opacityKeyframes),s.push(...a.scaleKeyframes),n.push(...a.rotationKeyframes);const o=this.buildOutPreset();return t.push(...o.offsetXKeyframes),e.push(...o.offsetYKeyframes),i.push(...o.opacityKeyframes),s.push(...o.scaleKeyframes),n.push(...o.rotationKeyframes),{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n}}buildInPreset(){const t=[],e=[],i=[],s=[],n=[];if(!this.clipConfiguration.transition?.in)return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n};const a=0,o=this.getInPresetLength();switch(this.getInPresetName()){case"fade":{const h=Math.max(0,Math.min(this.clipConfiguration.opacity??1,1));i.push({from:0,to:h,start:a,length:o,interpolation:"linear"});break}case"zoom":{const h=this.clipConfiguration.scale+9,p=this.clipConfiguration.scale;s.push({from:h,to:p,start:a,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:a,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideLeft":{const c=this.clipConfiguration.offset?.x+.025,h=this.clipConfiguration.offset?.x;t.push({from:c,to:h,start:a,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:a,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideRight":{const c=this.clipConfiguration.offset?.x-.025,h=this.clipConfiguration.offset?.x;t.push({from:c,to:h,start:a,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:a,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideUp":{const c=this.clipConfiguration.offset?.y+.025,h=this.clipConfiguration.offset?.y;e.push({from:c,to:h,start:a,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:a,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideDown":{const c=this.clipConfiguration.offset?.y-.025,h=this.clipConfiguration.offset?.y;e.push({from:c,to:h,start:a,length:o,interpolation:"bezier",easing:"easeOut"}),i.push({from:0,to:1,start:a,length:o,interpolation:"bezier",easing:"easeOut"});break}case"carouselLeft":case"carouselRight":case"carouselUp":case"carouselDown":case"shuffleTopRight":case"shuffleRightTop":case"shuffleRightBottom":case"shuffleBottomRight":case"shuffleBottomLeft":case"shuffleLeftBottom":case"shuffleLeftTop":case"shuffleTopLeft":default:console.warn(`Unimplemented transition:in preset "${this.clipConfiguration.transition.in}"`);break}return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n}}buildOutPreset(){const t=[],e=[],i=[],s=[],n=[];if(!this.clipConfiguration.transition?.out)return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n};const a=this.getOutPresetLength(),o=this.clipConfiguration.length-a;switch(this.getOutPresetName()){case"fade":{const c=Math.max(0,Math.min(this.clipConfiguration.opacity??1,1));i.push({from:c,to:0,start:o,length:a,interpolation:"linear"});break}case"zoom":{const h=this.clipConfiguration.scale,p=h+9;s.push({from:h,to:p,start:o,length:a,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:o,length:a,interpolation:"bezier",easing:"easeOut"});break}case"slideLeft":{const c=this.clipConfiguration.offset?.x,h=c-.025;t.push({from:c,to:h,start:o,length:a,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:o,length:a,interpolation:"bezier",easing:"easeOut"});break}case"slideRight":{const c=this.clipConfiguration.offset?.x,h=c+.025;t.push({from:c,to:h,start:o,length:a,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:o,length:a,interpolation:"bezier",easing:"easeOut"});break}case"slideUp":{const c=this.clipConfiguration.offset?.y,h=c-.025;e.push({from:c,to:h,start:o,length:a,interpolation:"bezier",easing:"easeIn"}),i.push({from:1,to:0,start:o,length:a,interpolation:"bezier",easing:"easeIn"});break}case"slideDown":{const c=this.clipConfiguration.offset?.y,h=c+.025;e.push({from:c,to:h,start:o,length:a,interpolation:"bezier",easing:"easeIn"}),i.push({from:1,to:0,start:o,length:a,interpolation:"bezier",easing:"easeIn"});break}case"carouselLeft":case"carouselRight":case"carouselUp":case"carouselDown":case"shuffleTopRight":case"shuffleRightTop":case"shuffleRightBottom":case"shuffleBottomRight":case"shuffleBottomLeft":case"shuffleLeftBottom":case"shuffleLeftTop":case"shuffleTopLeft":default:console.warn(`Unimplemented transition:out preset "${this.clipConfiguration.transition.out}"`);break}return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n}}getInPresetName(){const[t]=(this.clipConfiguration.transition?.in??"").split(/(Slow|Fast|VeryFast)/);return t}getOutPresetName(){const[t]=(this.clipConfiguration.transition?.out??"").split(/(Slow|Fast|VeryFast)/);return t}getInPresetLength(){const[,t]=(this.clipConfiguration.transition?.in??"").split(/(Slow|Fast|VeryFast)/);switch(t){case"Slow":return 2;case"Fast":return .5;case"VeryFast":return .25;default:return 1}}getOutPresetLength(){const[,t]=(this.clipConfiguration.transition?.out??"").split(/(Slow|Fast|VeryFast)/);switch(t){case"Slow":return 2;case"Fast":return .5;case"VeryFast":return .25;default:return 1}}}class mi{static ButtonLeftClick=0;static ButtonRightClick=3}class yi{containerSize;constructor(t){this.containerSize=t}relativeToAbsolute(t,e,i){switch(e){case"topLeft":return{x:i.x*this.containerSize.width,y:-i.y*this.containerSize.height};case"topRight":return{x:(i.x+1)*this.containerSize.width-t.width,y:-i.y*this.containerSize.height};case"bottomLeft":return{x:i.x*this.containerSize.width,y:(-i.y+1)*this.containerSize.height-t.height};case"bottomRight":return{x:(i.x+1)*this.containerSize.width-t.width,y:(-i.y+1)*this.containerSize.height-t.height};case"left":return{x:i.x*this.containerSize.width,y:(-i.y+.5)*this.containerSize.height-t.height/2};case"right":return{x:(i.x+1)*this.containerSize.width-t.width,y:(-i.y+.5)*this.containerSize.height-t.height/2};case"top":return{x:(i.x+.5)*this.containerSize.width-t.width/2,y:-i.y*this.containerSize.height};case"bottom":return{x:(i.x+.5)*this.containerSize.width-t.width/2,y:(-i.y+1)*this.containerSize.height-t.height};case"center":default:return{x:(i.x+.5)*this.containerSize.width-t.width/2,y:(-i.y+.5)*this.containerSize.height-t.height/2}}}absoluteToRelative(t,e,i){switch(e){case"topLeft":return{x:i.x/this.containerSize.width,y:-(i.y/this.containerSize.height)};case"topRight":return{x:(i.x+t.width)/this.containerSize.width-1,y:-(i.y/this.containerSize.height)};case"bottomLeft":return{x:i.x/this.containerSize.width,y:-((i.y+t.height)/this.containerSize.height-1)};case"bottomRight":return{x:(i.x+t.width)/this.containerSize.width-1,y:-((i.y+t.height)/this.containerSize.height-1)};case"left":return{x:i.x/this.containerSize.width,y:-((i.y+t.height/2)/this.containerSize.height-.5)};case"right":return{x:(i.x+t.width)/this.containerSize.width-1,y:-((i.y+t.height/2)/this.containerSize.height-.5)};case"top":return{x:(i.x+t.width/2)/this.containerSize.width-.5,y:-(i.y/this.containerSize.height)};case"bottom":return{x:(i.x+t.width/2)/this.containerSize.width-.5,y:-((i.y+t.height)/this.containerSize.height-1)};case"center":default:return{x:(i.x+t.width/2)/this.containerSize.width-.5,y:-((i.y+t.height/2)/this.containerSize.height-.5)}}}}class nt{container;constructor(){this.container=new d.Container}getContainer(){return this.container}}class D extends nt{static SnapThreshold=20;static DiscardedFrameCount=Math.ceil(1/30*1e3);static ScaleHandleRadius=10;static RotationHandleRadius=10;static RotationHandleOffset=50;static OutlineWidth=5;static MinScale=.1;static MaxScale=5;layer;shouldDispose;edit;clipConfiguration;positionBuilder;offsetXKeyframeBuilder;offsetYKeyframeBuilder;scaleKeyframeBuilder;opacityKeyframeBuilder;rotationKeyframeBuilder;outline;topLeftScaleHandle;topRightScaleHandle;bottomLeftScaleHandle;bottomRightScaleHandle;rotationHandle;isHovering;isDragging;dragOffset;scaleDirection;scaleStart;scaleOffset;isRotating;rotationStart;rotationOffset;initialClipConfiguration;contentContainer;constructor(t,e){super(),this.edit=t,this.layer=0,this.shouldDispose=!1,this.clipConfiguration=e,this.positionBuilder=new yi(t.size),this.outline=null,this.topLeftScaleHandle=null,this.topRightScaleHandle=null,this.bottomRightScaleHandle=null,this.bottomLeftScaleHandle=null,this.rotationHandle=null,this.isHovering=!1,this.isDragging=!1,this.dragOffset={x:0,y:0},this.scaleDirection=null,this.scaleStart=null,this.scaleOffset={x:0,y:0},this.isRotating=!1,this.rotationStart=null,this.rotationOffset={x:0,y:0},this.initialClipConfiguration=null,this.contentContainer=new d.Container,this.getContainer().addChild(this.contentContainer)}reconfigureAfterRestore(){this.configureKeyframes()}configureKeyframes(){if(this.offsetXKeyframeBuilder=new R(this.clipConfiguration.offset?.x??0,this.getLength()),this.offsetYKeyframeBuilder=new R(this.clipConfiguration.offset?.y??0,this.getLength()),this.scaleKeyframeBuilder=new R(this.clipConfiguration.scale??1,this.getLength(),1),this.opacityKeyframeBuilder=new R(this.clipConfiguration.opacity??1,this.getLength(),1),this.rotationKeyframeBuilder=new R(this.clipConfiguration.transform?.rotate?.angle??0,this.getLength()),this.clipHasKeyframes())return;const t=[],e=[],i=[],s=[],n=[],a=new fi(this.clipConfiguration).build(this.edit.size,this.getSize());t.push(...a.offsetXKeyframes),e.push(...a.offsetYKeyframes),i.push(...a.opacityKeyframes),s.push(...a.scaleKeyframes),n.push(...a.rotationKeyframes);const o=new gi(this.clipConfiguration).build();t.push(...o.offsetXKeyframes),e.push(...o.offsetYKeyframes),i.push(...o.opacityKeyframes),s.push(...o.scaleKeyframes),n.push(...o.rotationKeyframes),t.length&&(this.offsetXKeyframeBuilder=new R(t,this.getLength())),e.length&&(this.offsetYKeyframeBuilder=new R(e,this.getLength())),i.length&&(this.opacityKeyframeBuilder=new R(i,this.getLength(),1)),s.length&&(this.scaleKeyframeBuilder=new R(s,this.getLength(),1)),n.length&&(this.rotationKeyframeBuilder=new R(n,this.getLength()))}async load(){this.outline=new d.Graphics,this.getContainer().addChild(this.outline),this.topLeftScaleHandle=new d.Graphics,this.topRightScaleHandle=new d.Graphics,this.bottomRightScaleHandle=new d.Graphics,this.bottomLeftScaleHandle=new d.Graphics,this.rotationHandle=new d.Graphics,this.topLeftScaleHandle.zIndex=1e3,this.topRightScaleHandle.zIndex=1e3,this.bottomRightScaleHandle.zIndex=1e3,this.bottomLeftScaleHandle.zIndex=1e3,this.rotationHandle.zIndex=1e3,this.getContainer().addChild(this.topLeftScaleHandle),this.getContainer().addChild(this.topRightScaleHandle),this.getContainer().addChild(this.bottomRightScaleHandle),this.getContainer().addChild(this.bottomLeftScaleHandle),this.getContainer().addChild(this.rotationHandle),this.getContainer().sortableChildren=!0,this.getContainer().cursor="pointer",this.getContainer().eventMode="static",this.getContainer().on("pointerdown",this.onPointerStart.bind(this)),this.getContainer().on("pointermove",this.onPointerMove.bind(this)),this.getContainer().on("globalpointermove",this.onPointerMove.bind(this)),this.getContainer().on("pointerup",this.onPointerUp.bind(this)),this.getContainer().on("pointerupoutside",this.onPointerUp.bind(this)),this.getContainer().on("pointerover",this.onPointerOver.bind(this)),this.getContainer().on("pointerout",this.onPointerOut.bind(this))}update(t,e){if(this.getContainer().visible=this.isActive(),this.getContainer().zIndex=1e5-this.layer*100,!this.isActive())return;const i=this.getPivot(),s=this.getPosition(),n=this.getContainerScale();this.getContainer().scale.set(n.x,n.y),this.getContainer().pivot.set(i.x,i.y),this.getContainer().position.set(s.x+i.x,s.y+i.y);const a=this.getRotation();this.contentContainer.alpha=this.getOpacity(),this.getContainer().angle=a,this.shouldDiscardFrame()&&(this.contentContainer.alpha=0)}draw(){if(!this.outline)return;const t=this.edit.isPlayerSelected(this);if((!this.isActive()||!t)&&!this.isHovering){this.outline.clear(),this.topLeftScaleHandle?.clear(),this.topRightScaleHandle?.clear(),this.bottomRightScaleHandle?.clear(),this.bottomLeftScaleHandle?.clear(),this.rotationHandle?.clear();return}const e=this.isHovering||this.isDragging?65535:16777215,i=this.getSize(),s=this.getScale();if(this.outline.clear(),this.outline.strokeStyle={width:D.OutlineWidth/s,color:e},this.outline.rect(0,0,i.width,i.height),this.outline.stroke(),!this.topLeftScaleHandle||!this.topRightScaleHandle||!this.bottomRightScaleHandle||!this.bottomLeftScaleHandle||!this.isActive()||!t)return;this.topLeftScaleHandle.fillStyle={color:e},this.topLeftScaleHandle.clear();const n=D.ScaleHandleRadius*2/s;if(this.topLeftScaleHandle.rect(-n/2,-n/2,n,n),this.topLeftScaleHandle.fill(),this.topRightScaleHandle.fillStyle={color:e},this.topRightScaleHandle.clear(),this.topRightScaleHandle.rect(i.width-n/2,-n/2,n,n),this.topRightScaleHandle.fill(),this.bottomRightScaleHandle.fillStyle={color:e},this.bottomRightScaleHandle.clear(),this.bottomRightScaleHandle.rect(i.width-n/2,i.height-n/2,n,n),this.bottomRightScaleHandle.fill(),this.bottomLeftScaleHandle.fillStyle={color:e},this.bottomLeftScaleHandle.clear(),this.bottomLeftScaleHandle.rect(-n/2,i.height-n/2,n,n),this.bottomLeftScaleHandle.fill(),!this.rotationHandle)return;const a=i.width/2,o=-50/s;this.rotationHandle.clear(),this.rotationHandle.fillStyle={color:e},this.rotationHandle.circle(a,o,D.RotationHandleRadius/s),this.rotationHandle.fill(),this.outline.strokeStyle={width:D.OutlineWidth/s,color:e},this.outline.moveTo(a,0),this.outline.lineTo(a,o),this.outline.stroke()}dispose(){this.outline?.destroy(),this.outline=null,this.topLeftScaleHandle?.destroy(),this.topLeftScaleHandle=null,this.topRightScaleHandle?.destroy(),this.topRightScaleHandle=null,this.bottomLeftScaleHandle?.destroy(),this.bottomLeftScaleHandle=null,this.bottomRightScaleHandle?.destroy(),this.bottomRightScaleHandle=null,this.rotationHandle?.destroy(),this.rotationHandle=null,this.contentContainer?.destroy()}getStart(){return this.clipConfiguration.start*1e3}getLength(){return this.clipConfiguration.length*1e3}getEnd(){return this.getStart()+this.getLength()}getPlaybackTime(){const t=this.edit.playbackTime-this.getStart();return t<0?0:t>this.getLength()?this.getLength():t}getOpacity(){return this.opacityKeyframeBuilder?.getValue(this.getPlaybackTime())??1}getPosition(){const t={x:this.offsetXKeyframeBuilder?.getValue(this.getPlaybackTime())??0,y:this.offsetYKeyframeBuilder?.getValue(this.getPlaybackTime())??0};return this.positionBuilder.relativeToAbsolute(this.getSize(),this.clipConfiguration.position??"center",t)}getPivot(){const t=this.getSize();return{x:t.width/2,y:t.height/2}}getFitScale(){switch(this.clipConfiguration.fit??"crop"){case"crop":{const t=this.edit.size.width/this.getSize().width,e=this.edit.size.height/this.getSize().height;return this.edit.size.height>=this.edit.size.width?e:t}case"cover":return Math.max(this.edit.size.width/this.getSize().width,this.edit.size.height/this.getSize().height);case"contain":return Math.min(this.edit.size.width/this.getSize().width,this.edit.size.height/this.getSize().height);case"none":default:return 1}}getScale(){return(this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1)*this.getFitScale()}getContainerScale(){const t=this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1,e=this.getSize(),i=this.clipConfiguration.fit??"crop";if(e.width===0||e.height===0)return{x:t,y:t};const s=this.edit.size.width/e.width,n=this.edit.size.height/e.height;switch(i){case"contain":{const a=Math.min(s,n)*t;return{x:a,y:a}}case"crop":{const o=(this.edit.size.height>=this.edit.size.width?n:s)*t;return{x:o,y:o}}case"cover":return{x:s*t,y:n*t};case"none":default:return{x:t,y:t}}}getRotation(){return this.rotationKeyframeBuilder?.getValue(this.getPlaybackTime())??0}isActive(){return this.edit.playbackTime>=this.getStart()&&this.edit.playbackTime<this.getEnd()}shouldDiscardFrame(){return this.getPlaybackTime()<D.DiscardedFrameCount}onPointerStart(t){if(t.button!==mi.ButtonLeftClick||(this.edit.events.emit("canvas:clip:clicked",{player:this}),this.initialClipConfiguration=structuredClone(this.clipConfiguration),this.clipHasKeyframes()))return;if(this.scaleDirection=null,this.topLeftScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="topLeft"),this.topRightScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="topRight"),this.bottomRightScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="bottomRight"),this.bottomLeftScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="bottomLeft"),this.scaleDirection!==null){this.scaleStart=this.getScale()/this.getFitScale();const l=t.getLocalPosition(this.edit.getContainer());this.scaleOffset=l;return}if(this.rotationHandle?.getBounds().containsPoint(t.globalX,t.globalY)){this.isRotating=!0,this.rotationStart=this.getRotation();const l=t.getLocalPosition(this.edit.getContainer());this.rotationOffset=l;return}this.isDragging=!0;const o=t.getLocalPosition(this.edit.getContainer());this.dragOffset={x:o.x-this.getContainer().position.x,y:o.y-this.getContainer().position.y}}onPointerMove(t){if(this.scaleDirection!==null&&this.scaleStart!==null){const e=t.getLocalPosition(this.edit.getContainer()),i=this.getPosition(),s=this.getPivot(),n={x:i.x+s.x,y:i.y+s.y},a=Math.sqrt((this.scaleOffset.x-n.x)**2+(this.scaleOffset.y-n.y)**2),l=Math.sqrt((e.x-n.x)**2+(e.y-n.y)**2)/a,c=this.scaleStart*l;this.clipConfiguration.scale=Math.max(D.MinScale,Math.min(c,D.MaxScale)),this.scaleKeyframeBuilder=new R(this.clipConfiguration.scale,this.getLength(),1);return}if(this.isRotating&&this.rotationStart!==null){const e=t.getLocalPosition(this.edit.getContainer()),i=this.getPosition(),s=this.getPivot(),n={x:i.x+s.x,y:i.y+s.y},a=Math.atan2(this.rotationOffset.y-n.y,this.rotationOffset.x-n.x),l=(Math.atan2(e.y-n.y,e.x-n.x)-a)*(180/Math.PI);let c=this.rotationStart+l;const h=45,p=c%h,f=2;Math.abs(p)<f?c=Math.floor(c/h)*h:Math.abs(p-h)<f&&(c=Math.ceil(c/h)*h),this.clipConfiguration.transform||(this.clipConfiguration.transform={rotate:{angle:0}}),this.clipConfiguration.transform.rotate||(this.clipConfiguration.transform.rotate={angle:0}),this.clipConfiguration.transform.rotate.angle=c,this.rotationKeyframeBuilder=new R(this.clipConfiguration.transform.rotate.angle,this.getLength());return}if(this.isDragging){const e=t.getLocalPosition(this.edit.getContainer()),i=this.getPivot(),s={x:e.x-this.dragOffset.x,y:e.y-this.dragOffset.y},n={x:s.x-i.x,y:s.y-i.y},a=[{x:0,y:0},{x:this.edit.size.width,y:0},{x:0,y:this.edit.size.height},{x:this.edit.size.width,y:this.edit.size.height}],o={x:this.edit.size.width/2,y:this.edit.size.height/2},l=[...a,o],c=[{x:n.x,y:n.y},{x:n.x+this.getSize().width,y:n.y},{x:n.x,y:n.y+this.getSize().height},{x:n.x+this.getSize().width,y:n.y+this.getSize().height}],h={x:n.x+this.getSize().width/2,y:n.y+this.getSize().height/2},p=[...c,h];let f=D.SnapThreshold,v=D.SnapThreshold,I=null,b=null;for(const N of p)for(const lt of l){const et=Math.abs(N.x-lt.x);et<f&&(f=et,I=n.x+(lt.x-N.x));const It=Math.abs(N.y-lt.y);It<v&&(v=It,b=n.y+(lt.y-N.y))}I!==null&&(n.x=I),b!==null&&(n.y=b);const O=this.positionBuilder.absoluteToRelative(this.getSize(),this.clipConfiguration.position??"center",n);this.clipConfiguration.offset||(this.clipConfiguration.offset={x:0,y:0}),this.clipConfiguration.offset.x=O.x,this.clipConfiguration.offset.y=O.y,this.offsetXKeyframeBuilder=new R(this.clipConfiguration.offset.x,this.getLength()),this.offsetYKeyframeBuilder=new R(this.clipConfiguration.offset.y,this.getLength())}}onPointerUp(){(this.isDragging||this.scaleDirection!==null||this.isRotating)&&this.hasStateChanged()&&this.edit.setUpdatedClip(this,this.initialClipConfiguration,structuredClone(this.clipConfiguration)),this.isDragging=!1,this.dragOffset={x:0,y:0},this.scaleDirection=null,this.scaleStart=null,this.scaleOffset={x:0,y:0},this.isRotating=!1,this.rotationStart=null,this.rotationOffset={x:0,y:0},this.initialClipConfiguration=null}onPointerOver(){this.isHovering=!0}onPointerOut(){this.isHovering=!1}clipHasPresets(){return!!this.clipConfiguration.effect||!!this.clipConfiguration.transition?.in||!!this.clipConfiguration.transition?.out}clipHasKeyframes(){return[this.clipConfiguration.scale,this.clipConfiguration.offset?.x,this.clipConfiguration.offset?.y,this.clipConfiguration.transform?.rotate?.angle].some(t=>t&&typeof t!="number")}hasStateChanged(){if(!this.initialClipConfiguration)return!1;const t=this.clipConfiguration.offset?.x,e=this.clipConfiguration.offset?.y,i=this.clipConfiguration.scale,s=Number(this.clipConfiguration.transform?.rotate?.angle??0),n=this.initialClipConfiguration.offset?.x,a=this.initialClipConfiguration.offset?.y,o=this.initialClipConfiguration.scale,l=Number(this.initialClipConfiguration.transform?.rotate?.angle??0);return n!==void 0&&t!==n||a!==void 0&&e!==a||o!==void 0&&i!==o||s!==l}}class oe extends D{audioResource;isPlaying;volumeKeyframeBuilder;syncTimer;constructor(t,e){super(t,e),this.audioResource=null,this.isPlaying=!1;const i=e.asset;this.volumeKeyframeBuilder=new R(i.volume??1,this.getLength()),this.syncTimer=0}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src,i={src:e,loadParser:Bt.Name},s=await this.edit.assetLoader.load(e,i);if(!(s instanceof ui.Howl))throw new Error(`Invalid audio source '${t.src}'.`);this.audioResource=s,this.configureKeyframes()}update(t,e){super.update(t,e);const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=e,this.getContainer().alpha=0,!this.audioResource)return;const s=this.edit.isPlaying&&this.isActive(),n=this.getPlaybackTime();s&&(this.isPlaying||(this.isPlaying=!0,this.audioResource.seek(n/1e3+i),this.audioResource.play()),this.audioResource.volume()!==this.getVolume()&&this.audioResource.volume(this.getVolume()),Math.abs((this.audioResource.seek()-i)*1e3-n)>100&&this.audioResource.seek(n/1e3+i)),this.isPlaying&&!s&&(this.isPlaying=!1,this.audioResource.pause());const a=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&a&&(this.syncTimer=0,this.audioResource.seek(n/1e3+i))}draw(){super.draw()}dispose(){this.audioResource?.unload(),this.audioResource=null}getSize(){return{width:0,height:0}}getVolume(){return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}}var vi=`in vec2 aPosition;
2
2
  out vec2 vTextureCoord;
3
3
 
4
4
  uniform vec4 uInputSize;
@@ -25,7 +25,7 @@ void main(void)
25
25
  gl_Position = filterVertexPosition();
26
26
  vTextureCoord = filterTextureCoord();
27
27
  }
28
- `,ti=`struct GlobalFilterUniforms {
28
+ `,Ci=`struct GlobalFilterUniforms {
29
29
  uInputSize:vec4<f32>,
30
30
  uInputPixel:vec4<f32>,
31
31
  uInputClamp:vec4<f32>,
@@ -74,7 +74,7 @@ fn mainVertex(
74
74
  filterVertexPosition(aPosition),
75
75
  filterTextureCoord(aPosition)
76
76
  );
77
- }`,ei=`precision highp float;
77
+ }`,xi=`precision highp float;
78
78
  in vec2 vTextureCoord;
79
79
  out vec4 finalColor;
80
80
 
@@ -115,7 +115,7 @@ void main(void) {
115
115
  vec4 outlineColor = vec4(vec3(uColor) * outlineAlpha, outlineAlpha);
116
116
  finalColor = contentColor + outlineColor;
117
117
  }
118
- `,ii=`struct OutlineUniforms {
118
+ `,ki=`struct OutlineUniforms {
119
119
  uThickness:vec2<f32>,
120
120
  uColor:vec3<f32>,
121
121
  uAlpha:f32,
@@ -179,7 +179,7 @@ fn outlineMaxAlphaAtPos(uv: vec2<f32>) -> f32 {
179
179
  return maxAlpha;
180
180
  }
181
181
 
182
- const DOUBLE_PI: f32 = 3.14159265358979323846264 * 2.;`,si=Object.defineProperty,ni=(a,t,e)=>t in a?si(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,st=(a,t,e)=>(ni(a,typeof t!="symbol"?t+"":t,e),e);const At=class lt extends V.Filter{constructor(...t){let e=t[0]??{};typeof e=="number"&&(V.deprecation("6.0.0","OutlineFilter constructor params are now options object. See params: { thickness, color, quality, alpha, knockout }"),e={thickness:e},t[1]!==void 0&&(e.color=t[1]),t[2]!==void 0&&(e.quality=t[2]),t[3]!==void 0&&(e.alpha=t[3]),t[4]!==void 0&&(e.knockout=t[4])),e={...lt.DEFAULT_OPTIONS,...e};const i=e.quality??.1,s=V.GpuProgram.from({vertex:{source:ti,entryPoint:"mainVertex"},fragment:{source:ii,entryPoint:"mainFragment"}}),n=V.GlProgram.from({vertex:Je,fragment:ei.replace(/\$\{ANGLE_STEP\}/,lt.getAngleStep(i).toFixed(7)),name:"outline-filter"});super({gpuProgram:s,glProgram:n,resources:{outlineUniforms:{uThickness:{value:new Float32Array(2),type:"vec2<f32>"},uColor:{value:new Float32Array(3),type:"vec3<f32>"},uAlpha:{value:e.alpha,type:"f32"},uAngleStep:{value:0,type:"f32"},uKnockout:{value:e.knockout?1:0,type:"f32"}}}}),st(this,"uniforms"),st(this,"_thickness"),st(this,"_quality"),st(this,"_color"),this.uniforms=this.resources.outlineUniforms.uniforms,this.uniforms.uAngleStep=lt.getAngleStep(i),this._color=new V.Color,this.color=e.color??0,Object.assign(this,e)}apply(t,e,i,s){this.uniforms.uThickness[0]=this.thickness/e.source.width,this.uniforms.uThickness[1]=this.thickness/e.source.height,t.applyFilter(this,e,i,s)}static getAngleStep(t){return parseFloat((Math.PI*2/Math.max(t*lt.MAX_SAMPLES,lt.MIN_SAMPLES)).toFixed(7))}get thickness(){return this._thickness}set thickness(t){this._thickness=this.padding=t}get color(){return this._color.value}set color(t){this._color.setValue(t);const[e,i,s]=this._color.toArray();this.uniforms.uColor[0]=e,this.uniforms.uColor[1]=i,this.uniforms.uColor[2]=s}get alpha(){return this.uniforms.uAlpha}set alpha(t){this.uniforms.uAlpha=t}get quality(){return this._quality}set quality(t){this._quality=t,this.uniforms.uAngleStep=lt.getAngleStep(t)}get knockout(){return this.uniforms.uKnockout===1}set knockout(t){this.uniforms.uKnockout=t?1:0}};st(At,"DEFAULT_OPTIONS",{thickness:1,color:0,alpha:1,quality:.1,knockout:!1}),st(At,"MIN_SAMPLES",1),st(At,"MAX_SAMPLES",100);let qt=At;class ai extends P{background;text;constructor(t,e){super(t,e),this.background=null,this.text=null}async load(){await super.load();const t=this.clipConfiguration.asset,e=await this.parseDocument();if(!e)return;const i=new y.Graphics;e.background.color&&(i.fillStyle={color:e.background.color,alpha:e.background.opacity??1},i.rect(0,0,t.width??this.edit.size.width,t.height??this.edit.size.height),i.fill());const s=new y.Text;s.text=e.text;const{horizontal:n,vertical:r}=e.alignment;s.style={fontFamily:e.font?.family??"Open Sans",fontSize:e.font?.size??32,fill:e.font?.color??"#ffffff",fontWeight:(e.font?.weight??"400").toString(),wordWrap:!0,wordWrapWidth:t.width??this.edit.size.width,lineHeight:(e.font?.lineHeight??1)*(e.font?.size??32),align:n};let o=(t.width??this.edit.size.width)/2-s.width/2,h=(t.height??this.edit.size.height)/2-s.height/2;if(n==="left"&&(o=0),n==="right"&&(o=(t.width??this.edit.size.width)-s.width),r==="top"&&(h=0),r==="bottom"&&(h=(t.height??this.edit.size.height)-s.height),s.position={x:o,y:h},e.stroke.color&&e.stroke.width){const c=new qt({thickness:e.stroke.width,color:e.stroke.color});s.filters=[c]}this.background=i,this.text=s,this.getContainer().addChild(i),this.getContainer().addChild(s),this.configureKeyframes()}update(t,e){super.update(t,e)}draw(){super.draw()}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=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}async parseDocument(){const t=this.clipConfiguration.asset,{html:e,css:i,position:s}=t;if(!e.includes('data-html-type="text"'))return console.warn("Unsupported html format."),null;const r=new DOMParser().parseFromString(e,"text/html").body.textContent??"",h=(await new CSSStyleSheet().replace(i)).cssRules[0],c={text:r,font:{},alignment:{},background:{},stroke:{}};if(h?.constructor.name!=="CSSStyleRule"||!("style"in h))return console.warn("Unsupported css format."),c;const l=h.style,g=this.parseAlignment(s??"center");c.font={color:l.color.length?l.color:void 0,family:l.fontFamily.length?l.fontFamily:void 0,size:l.fontSize.length?parseInt(l.fontSize,10):void 0,weight:l.fontWeight.length?parseInt(l.fontWeight,10):void 0,lineHeight:l.lineHeight.length?parseInt(l.lineHeight,10):void 0},c.alignment=g;let p="";return l.background.length&&(p=l.background),l.backgroundColor.length&&(p=l.backgroundColor),c.background={color:p.length?p:void 0,opacity:l.opacity.length?parseInt(l.opacity,10):void 0},c.stroke={width:l.strokeWidth.length?parseInt(l.strokeWidth,10):void 0,color:l.stroke.length?l.stroke:void 0},c}parseAlignment(t){switch(t){case"topLeft":return{horizontal:"left",vertical:"top"};case"top":return{horizontal:"center",vertical:"top"};case"topRight":return{horizontal:"right",vertical:"top"};case"left":return{horizontal:"left",vertical:"center"};case"right":return{horizontal:"right",vertical:"center"};case"bottomLeft":return{horizontal:"left",vertical:"bottom"};case"bottom":return{horizontal:"center",vertical:"bottom"};case"bottomRight":return{horizontal:"right",vertical:"bottom"};case"center":default:return{horizontal:"center",vertical:"center"}}}}class ri extends P{texture;sprite;constructor(t,e){super(t,e),this.texture=null,this.sprite=null}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src,i={src:e,crossovern:"anonymous",data:{}},s=await this.edit.assetLoader.load(e,i);if(!(s?.source instanceof y.ImageSource))throw new Error(`Invalid image source '${t.src}'.`);this.texture=this.createCroppedTexture(s),this.sprite=new y.Sprite(this.texture),this.getContainer().addChild(this.sprite),this.configureKeyframes()}update(t,e){super.update(t,e)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null}getSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}createCroppedTexture(t){const e=this.clipConfiguration.asset;if(!e.crop)return t;const i=t.width,s=t.height,n=Math.floor((e.crop?.left??0)*i),r=Math.floor((e.crop?.right??0)*i),o=Math.floor((e.crop?.top??0)*s),h=Math.floor((e.crop?.bottom??0)*s),c=n,l=o,g=i-n-r,p=s-o-h,w=new y.Rectangle(c,l,g,p);return new y.Texture({source:t.source,frame:w})}}class ge extends P{texture;sprite;isPlaying;constructor(t,e){super(t,e),this.texture=null,this.sprite=null,this.isPlaying=!1}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src,i={src:e,data:{autoPlay:!1,muted:!0}},s=await this.edit.assetLoader.load(e,i);if(!(s?.source instanceof y.ImageSource||s?.source instanceof y.VideoSource))throw new Error(`Invalid luma source '${t.src}'.`);this.texture=s,this.sprite=new y.Sprite(this.texture),this.getContainer().addChild(this.sprite),this.configureKeyframes()}update(t,e){if(super.update(t,e),!this.texture||!(this.texture.source instanceof y.VideoSource))return;const i=this.getPlaybackTime(),s=this.edit.isPlaying&&this.isActive();s&&(this.isPlaying||(this.isPlaying=!0,this.texture.source.resource.currentTime=i/1e3,this.texture.source.resource.play().catch(console.error)),this.texture.source.resource.volume!==this.getVolume()&&(this.texture.source.resource.volume=this.getVolume()),Math.abs(this.texture.source.resource.currentTime*1e3-i)>100&&(this.texture.source.resource.currentTime=i/1e3)),!s&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause()),!this.edit.isPlaying&&this.isActive()&&(this.texture.source.resource.currentTime=i/1e3)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null}getSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}getVolume(){return 0}getMask(){return this.sprite}}class oi extends P{shape;shapeBackground;constructor(t,e){super(t,e),this.shape=null,this.shapeBackground=null}async load(){await super.load();const t=this.clipConfiguration.asset,e=new y.Graphics,i=t.width??this.edit.size.width,s=t.height??this.edit.size.height;e.fillStyle={color:"transparent"},e.rect(0,0,i,s),e.fill();const n=new y.Graphics;switch(t.shape){case"rectangle":{const r=t.rectangle,o=i/2-r.width/2,h=s/2-r.height/2;n.rect(o,h,r.width,r.height);break}case"circle":{const r=t.circle,o=i/2,h=s/2;n.circle(o,h,r.radius);break}case"line":{const r=t.line,o=i/2-r.length/2,h=s/2-r.thickness/2;n.rect(o,h,r.length,r.thickness);break}default:console.warn("Unsupported shape asset type.");break}if(n.fillStyle={color:t.fill?.color??"#ffffff",alpha:t.fill?.opacity??1},n.fill(),t.stroke){const r=new qt({thickness:t.stroke.width,color:t.stroke.color});n.filters=[r]}this.shapeBackground=e,this.shape=n,this.getContainer().addChild(e),e.addChild(n),this.configureKeyframes()}update(t,e){super.update(t,e)}draw(){super.draw()}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}}class xt{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,e,i,s){this.parent=t,this.textElement=e,this.clipConfig=i,this.width=s?.width??xt.DEFAULT_CURSOR_WIDTH_PX,this.color=s?.color??xt.DEFAULT_CURSOR_COLOR,this.blinkIntervalMs=s?.blinkInterval??xt.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,e){if(!this.cursor){console.warn("TextCursor: Cannot set position, cursor not initialized");return}this.pixelX=t,this.pixelY=e,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 y.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,e=this.textElement.style,i=t.substring(0,this.textPosition),s=i.match(/\n/g);this.currentLine=s?s.length:0;const n=t.split(`
183
- `),r=this.currentLine<n.length?n[this.currentLine]:"",o=i.lastIndexOf(`
184
- `),h=o===-1?this.textPosition:this.textPosition-o-1,c=r.substring(0,h);let l;c.length>0&&c.endsWith(" ")?l=this.measureText(`${c}x`,e)-this.measureText("x",e):l=this.measureText(c,e);const g=e.lineHeight;this.pixelY=this.currentLine*g;const w=this.clipConfig.asset.alignment?.horizontal??"center";let I=l;if(w!=="left"){const _=this.measureText(r,e),D=this.textElement.width;let N=0;w==="center"?N=(D-_)/2:w==="right"&&(N=D-_),I=N+l}this.pixelX=I}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,e){const i=new y.Text(t,e),{width:s}=i;return i.destroy(),s}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 Pt{static DEFAULT_FOCUS_DELAY_MS=50;hiddenInput=null;isFocused=!1;focusRetryCount=0;maxFocusRetries=3;focusDelay=Pt.DEFAULT_FOCUS_DELAY_MS;eventHandlers={};abortController=null;textChangeCallback=null;lastSyncedText="";isComposing=!1;setupInput(t,e){this.focusDelay=e?.focusDelay??Pt.DEFAULT_FOCUS_DELAY_MS,this.createHiddenTextarea(),this.hiddenInput&&(this.hiddenInput.value=t,this.lastSyncedText=t),this.setupEventListeners(),e?.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,e){if(!this.hiddenInput)return;const i=this.hiddenInput.value.length,s=Math.max(0,Math.min(t,i)),n=Math.max(s,Math.min(e,i));this.hiddenInput.setSelectionRange(s,n)}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:"999",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 e=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.lastSyncedText=e,this.textChangeCallback?.(e,i)};handleKeyDown=t=>{if(document.activeElement!==this.hiddenInput)return;let e=!1;if((t.ctrlKey||t.metaKey)&&(e=this.handleKeyboardShortcuts(t),e)){t.preventDefault();return}if(t.key==="Tab"){const i=t.shiftKey?"backward":"forward";this.eventHandlers.onTabNavigation?.(i),t.preventDefault();return}switch(t.key){case"Escape":this.eventHandlers.onEscape?.(t),e=!0;break;case"Enter":e=!1;break;case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":setTimeout(()=>{if(this.hiddenInput){const i=this.hiddenInput.value,s=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(i,s)}},0),e=!1;break;case"Backspace":case"Delete":e=!1;break;default:e=this.eventHandlers.onCustomKey?.(t.key,t)||!1;break}e&&t.preventDefault()};handleKeyboardShortcuts(t){const{key:e}=t;switch(e.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 e=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(e,i)}};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 K{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,e,i){this.parent=t,this.targetText=e,this.clipConfig=i,this.parent.getContainer().eventMode="static",this.parent.getContainer().on("click",this.checkForDoubleClick)}dispose(){this.parent.getContainer().off("click",this.checkForDoubleClick),this.stopEditing(),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null)}startEditing(){if(this.isEditing||!this.targetText)return;const t=structuredClone(this.clipConfig);this.targetText.visible=!1,this.createEditingEnvironment(),this.setupOutsideClickHandler(t),this.isEditing=!0}stopEditing(t=!1,e){if(!this.isEditing)return;let i="";this.editableText&&(i=this.editableText.text),this.editingContainer&&(this.parent.getContainer().removeChild(this.editingContainer),this.editingContainer.destroy(),this.editingContainer=null),this.editableText=null,this.textCursor&&(this.textCursor.dispose(),this.textCursor=null),this.textInputHandler&&(this.textInputHandler.dispose(),this.textInputHandler=null),this.targetText.visible=!0,t&&e&&i!==""&&this.parent.updateTextContent(i,e),this.isEditing=!1}checkForDoubleClick=t=>{const e=Date.now();e-this.lastClickTime<K.DOUBLE_CLICK_THRESHOLD_MS&&this.startEditing(),this.lastClickTime=e};setupOutsideClickHandler(t){this.outsideClickHandler=e=>{const s=this.parent.getContainer().getBounds(),n=e.clientX,r=e.clientY;(n<s.x||n>s.x+s.width||r<s.y||r>s.y+s.height)&&(this.stopEditing(!0,t),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null))},setTimeout(()=>{this.outsideClickHandler&&window.addEventListener("click",this.outsideClickHandler)},K.CLICK_HANDLER_DELAY_MS)}createEditingEnvironment(){this.setupEditingContainer(),this.editingContainer&&this.editableText&&(this.textCursor=new xt(this.editingContainer,this.editableText,this.clipConfig),this.textCursor.updatePosition(this.targetText.text.length),this.textCursor.startBlinking()),this.setupTextInputHandler(),this.updateTextAlignment()}setupEditingContainer(){this.editingContainer=new y.Container,this.parent.getContainer().addChild(this.editingContainer);const t=new y.Graphics;t.fillStyle={color:0,alpha:K.EDITING_BG_ALPHA},t.rect(-5,-5,this.targetText.width+2*K.EDITING_BG_PADDING_PX,this.targetText.height+2*K.EDITING_BG_PADDING_PX),t.fill(),this.editingContainer.addChild(t),this.editableText=new y.Text(this.targetText.text,this.targetText.style),this.editableText.eventMode="static",this.editableText.cursor="text",this.editingContainer.addChild(this.editableText)}setupTextInputHandler(){this.textInputHandler=new Pt,this.textInputHandler.setTextInputHandler((t,e)=>{this.editableText&&(this.editableText.text=t,this.updateTextAlignment()),this.textCursor?.updatePosition(e)}),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(),e=this.getAlignmentSettings(),i=this.calculateHorizontalPosition({width:this.editableText.width},t,e.horizontal),s=this.calculateVerticalPosition({height:this.editableText.height},t,e.vertical);if(this.editingContainer.position.set(i,s),this.editingContainer.children.length>0){const n=this.editingContainer.getChildAt(0);n instanceof y.Graphics&&(n.clear(),n.fillStyle={color:0,alpha:K.EDITING_BG_ALPHA},n.rect(-5,-5,this.editableText.width+2*K.EDITING_BG_PADDING_PX,this.editableText.height+2*K.EDITING_BG_PADDING_PX),n.fill())}}calculateHorizontalPosition(t,e,i="center"){switch(i){case"center":return e.width/2-t.width/2;case"right":return e.width-t.width;case"left":default:return 0}}calculateVerticalPosition(t,e,i="center"){switch(i){case"center":return e.height/2-t.height/2;case"bottom":return e.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 ci extends P{background=null;text=null;textEditor=null;async load(){await super.load();const t=this.clipConfiguration.asset;if(this.background=new y.Graphics,t.background&&(this.background.fillStyle={color:t.background.color,alpha:t.background.opacity},this.background.rect(0,0,t.width??this.edit.size.width,t.height??this.edit.size.height),this.background.fill()),this.text=new y.Text(t.text,this.createTextStyle(t)),this.positionText(t),t.stroke){const e=new qt({thickness:t.stroke.width,color:t.stroke.color});this.text.filters=[e]}this.getContainer().addChild(this.background),this.getContainer().addChild(this.text),this.configureKeyframes(),this.textEditor=new K(this,this.text,this.clipConfiguration)}update(t,e){super.update(t,e)}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:t.width??this.edit.size.width,height:t.height??this.edit.size.height}}getFitScale(){return 1}createTextStyle(t){return new y.TextStyle({fontFamily:t.font?.family??"Open Sans",fontSize:t.font?.size??32,fill:t.font?.color??"#ffffff",fontWeight:(t.font?.weight??"400").toString(),wordWrap:!0,wordWrapWidth:t.width??this.edit.size.width,lineHeight:(t.font?.lineHeight??1)*(t.font?.size??32),align:t.alignment?.horizontal??"center"})}positionText(t){if(!this.text)return;const e=t.alignment?.horizontal??"center",i=t.alignment?.vertical??"center",s=t.width??this.edit.size.width,n=t.height??this.edit.size.height;let r=s/2-this.text.width/2,o=n/2-this.text.height/2;e==="left"?r=0:e==="right"&&(r=s-this.text.width),i==="top"?o=0:i==="bottom"&&(o=n-this.text.height),this.text.position.set(r,o)}updateTextContent(t,e){this.edit.updateTextContent(this,t,e)}}class li extends P{texture;sprite;isPlaying;volumeKeyframeBuilder;syncTimer;constructor(t,e){super(t,e),this.texture=null,this.sprite=null,this.isPlaying=!1;const i=this.clipConfiguration.asset;this.volumeKeyframeBuilder=new E(i.volume??1,this.getLength()),this.syncTimer=0}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src;if(e.endsWith(".mov")||e.endsWith(".webm"))throw new Error(`Video source '${t.src}' is not supported. .mov and .webm files are currently not supported.`);const i={src:e,data:{autoPlay:!1,muted:!1}},s=await this.edit.assetLoader.load(e,i);if(!(s?.source instanceof y.VideoSource))throw new Error(`Invalid video source '${t.src}'.`);this.texture=this.createCroppedTexture(s),this.sprite=new y.Sprite(this.texture),this.getContainer().addChild(this.sprite),this.configureKeyframes()}update(t,e){super.update(t,e);const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=e,!this.texture)return;const s=this.getPlaybackTime(),n=this.edit.isPlaying&&this.isActive();n&&(this.isPlaying||(this.isPlaying=!0,this.texture.source.resource.currentTime=s/1e3+i,this.texture.source.resource.play().catch(console.error)),this.texture.source.resource.volume!==this.getVolume()&&(this.texture.source.resource.volume=this.getVolume()),Math.abs((this.texture.source.resource.currentTime-i)*1e3-s)>100&&(this.texture.source.resource.currentTime=s/1e3+i)),!n&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause());const r=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&r&&(this.syncTimer=0,this.texture.source.resource.currentTime=s/1e3+i)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null}getSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}getVolume(){return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}createCroppedTexture(t){const e=this.clipConfiguration.asset;if(!e.crop)return t;const i=t.width,s=t.height,n=Math.floor((e.crop?.left??0)*i),r=Math.floor((e.crop?.right??0)*i),o=Math.floor((e.crop?.top??0)*s),h=Math.floor((e.crop?.bottom??0)*s),c=n,l=o,g=i-n-r,p=s-o-h,w=new y.Rectangle(c,l,g,p);return new y.Texture({source:t.source,frame:w})}}var S;(function(a){a.assertEqual=s=>s;function t(s){}a.assertIs=t;function e(s){throw new Error}a.assertNever=e,a.arrayToEnum=s=>{const n={};for(const r of s)n[r]=r;return n},a.getValidEnumValues=s=>{const n=a.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),r={};for(const o of n)r[o]=s[o];return a.objectValues(r)},a.objectValues=s=>a.objectKeys(s).map(function(n){return s[n]}),a.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const n=[];for(const r in s)Object.prototype.hasOwnProperty.call(s,r)&&n.push(r);return n},a.find=(s,n)=>{for(const r of s)if(n(r))return r},a.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function i(s,n=" | "){return s.map(r=>typeof r=="string"?`'${r}'`:r).join(n)}a.joinValues=i,a.jsonStringifyReplacer=(s,n)=>typeof n=="bigint"?n.toString():n})(S||(S={}));var ye;(function(a){a.mergeShapes=(t,e)=>({...t,...e})})(ye||(ye={}));const f=S.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),J=a=>{switch(typeof a){case"undefined":return f.undefined;case"string":return f.string;case"number":return isNaN(a)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(a)?f.array:a===null?f.null:a.then&&typeof a.then=="function"&&a.catch&&typeof a.catch=="function"?f.promise:typeof Map<"u"&&a instanceof Map?f.map:typeof Set<"u"&&a instanceof Set?f.set:typeof Date<"u"&&a instanceof Date?f.date:f.object;default:return f.unknown}},u=S.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class H extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const e=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,e):this.__proto__=e,this.name="ZodError",this.issues=t}format(t){const e=t||function(n){return n.message},i={_errors:[]},s=n=>{for(const r of n.issues)if(r.code==="invalid_union")r.unionErrors.map(s);else if(r.code==="invalid_return_type")s(r.returnTypeError);else if(r.code==="invalid_arguments")s(r.argumentsError);else if(r.path.length===0)i._errors.push(e(r));else{let o=i,h=0;for(;h<r.path.length;){const c=r.path[h];h===r.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(e(r))):o[c]=o[c]||{_errors:[]},o=o[c],h++}}};return s(this),i}static assert(t){if(!(t instanceof H))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,S.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=e=>e.message){const e={},i=[];for(const s of this.issues)s.path.length>0?(e[s.path[0]]=e[s.path[0]]||[],e[s.path[0]].push(t(s))):i.push(t(s));return{formErrors:i,fieldErrors:e}}get formErrors(){return this.flatten()}}H.create=a=>new H(a);const Ct=(a,t)=>{let e;switch(a.code){case u.invalid_type:a.received===f.undefined?e="Required":e=`Expected ${a.expected}, received ${a.received}`;break;case u.invalid_literal:e=`Invalid literal value, expected ${JSON.stringify(a.expected,S.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:e=`Unrecognized key(s) in object: ${S.joinValues(a.keys,", ")}`;break;case u.invalid_union:e="Invalid input";break;case u.invalid_union_discriminator:e=`Invalid discriminator value. Expected ${S.joinValues(a.options)}`;break;case u.invalid_enum_value:e=`Invalid enum value. Expected ${S.joinValues(a.options)}, received '${a.received}'`;break;case u.invalid_arguments:e="Invalid function arguments";break;case u.invalid_return_type:e="Invalid function return type";break;case u.invalid_date:e="Invalid date";break;case u.invalid_string:typeof a.validation=="object"?"includes"in a.validation?(e=`Invalid input: must include "${a.validation.includes}"`,typeof a.validation.position=="number"&&(e=`${e} at one or more positions greater than or equal to ${a.validation.position}`)):"startsWith"in a.validation?e=`Invalid input: must start with "${a.validation.startsWith}"`:"endsWith"in a.validation?e=`Invalid input: must end with "${a.validation.endsWith}"`:S.assertNever(a.validation):a.validation!=="regex"?e=`Invalid ${a.validation}`:e="Invalid";break;case u.too_small:a.type==="array"?e=`Array must contain ${a.exact?"exactly":a.inclusive?"at least":"more than"} ${a.minimum} element(s)`:a.type==="string"?e=`String must contain ${a.exact?"exactly":a.inclusive?"at least":"over"} ${a.minimum} character(s)`:a.type==="number"?e=`Number must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${a.minimum}`:a.type==="date"?e=`Date must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(a.minimum))}`:e="Invalid input";break;case u.too_big:a.type==="array"?e=`Array must contain ${a.exact?"exactly":a.inclusive?"at most":"less than"} ${a.maximum} element(s)`:a.type==="string"?e=`String must contain ${a.exact?"exactly":a.inclusive?"at most":"under"} ${a.maximum} character(s)`:a.type==="number"?e=`Number must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="bigint"?e=`BigInt must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="date"?e=`Date must be ${a.exact?"exactly":a.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(a.maximum))}`:e="Invalid input";break;case u.custom:e="Invalid input";break;case u.invalid_intersection_types:e="Intersection results could not be merged";break;case u.not_multiple_of:e=`Number must be a multiple of ${a.multipleOf}`;break;case u.not_finite:e="Number must be finite";break;default:e=t.defaultError,S.assertNever(a)}return{message:e}};let hi=Ct;function Qt(){return hi}const Jt=a=>{const{data:t,path:e,errorMaps:i,issueData:s}=a,n=[...e,...s.path||[]],r={...s,path:n};if(s.message!==void 0)return{...s,path:n,message:s.message};let o="";const h=i.filter(c=>!!c).slice().reverse();for(const c of h)o=c(r,{data:t,defaultError:o}).message;return{...s,path:n,message:o}};function d(a,t){const e=Qt(),i=Jt({issueData:t,data:a.data,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,e,e===Ct?void 0:Ct].filter(s=>!!s)});a.common.issues.push(i)}class L{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,e){const i=[];for(const s of e){if(s.status==="aborted")return C;s.status==="dirty"&&t.dirty(),i.push(s.value)}return{status:t.value,value:i}}static async mergeObjectAsync(t,e){const i=[];for(const s of e){const n=await s.key,r=await s.value;i.push({key:n,value:r})}return L.mergeObjectSync(t,i)}static mergeObjectSync(t,e){const i={};for(const s of e){const{key:n,value:r}=s;if(n.status==="aborted"||r.status==="aborted")return C;n.status==="dirty"&&t.dirty(),r.status==="dirty"&&t.dirty(),n.value!=="__proto__"&&(typeof r.value<"u"||s.alwaysSet)&&(i[n.value]=r.value)}return{status:t.value,value:i}}}const C=Object.freeze({status:"aborted"}),kt=a=>({status:"dirty",value:a}),z=a=>({status:"valid",value:a}),ve=a=>a.status==="aborted",xe=a=>a.status==="dirty",ht=a=>a.status==="valid",Et=a=>typeof Promise<"u"&&a instanceof Promise;function Lt(a,t,e,i){if(typeof t=="function"?a!==t||!0:!t.has(a))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(a)}function Ce(a,t,e,i,s){if(typeof t=="function"?a!==t||!0:!t.has(a))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(a,e),e}typeof SuppressedError=="function"&&SuppressedError;var m;(function(a){a.errToObj=t=>typeof t=="string"?{message:t}:t||{},a.toString=t=>typeof t=="string"?t:t?.message})(m||(m={}));var wt,bt;class Z{constructor(t,e,i,s){this._cachedPath=[],this.parent=t,this.data=e,this._path=i,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const ke=(a,t)=>{if(ht(t))return{success:!0,data:t.value};if(!a.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const e=new H(a.common.issues);return this._error=e,this._error}}};function k(a){if(!a)return{};const{errorMap:t,invalid_type_error:e,required_error:i,description:s}=a;if(t&&(e||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(r,o)=>{var h,c;const{message:l}=a;return r.code==="invalid_enum_value"?{message:l??o.defaultError}:typeof o.data>"u"?{message:(h=l??i)!==null&&h!==void 0?h:o.defaultError}:r.code!=="invalid_type"?{message:o.defaultError}:{message:(c=l??e)!==null&&c!==void 0?c:o.defaultError}},description:s}}class b{get description(){return this._def.description}_getType(t){return J(t.data)}_getOrReturnCtx(t,e){return e||{common:t.parent.common,data:t.data,parsedType:J(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new L,ctx:{common:t.parent.common,data:t.data,parsedType:J(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const e=this._parse(t);if(Et(e))throw new Error("Synchronous parse encountered promise.");return e}_parseAsync(t){const e=this._parse(t);return Promise.resolve(e)}parse(t,e){const i=this.safeParse(t,e);if(i.success)return i.data;throw i.error}safeParse(t,e){var i;const s={common:{issues:[],async:(i=e?.async)!==null&&i!==void 0?i:!1,contextualErrorMap:e?.errorMap},path:e?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:J(t)},n=this._parseSync({data:t,path:s.path,parent:s});return ke(s,n)}"~validate"(t){var e,i;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:J(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:s});return ht(n)?{value:n.value}:{issues:s.common.issues}}catch(n){!((i=(e=n?.message)===null||e===void 0?void 0:e.toLowerCase())===null||i===void 0)&&i.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:s}).then(n=>ht(n)?{value:n.value}:{issues:s.common.issues})}async parseAsync(t,e){const i=await this.safeParseAsync(t,e);if(i.success)return i.data;throw i.error}async safeParseAsync(t,e){const i={common:{issues:[],contextualErrorMap:e?.errorMap,async:!0},path:e?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:J(t)},s=this._parse({data:t,path:i.path,parent:i}),n=await(Et(s)?s:Promise.resolve(s));return ke(i,n)}refine(t,e){const i=s=>typeof e=="string"||typeof e>"u"?{message:e}:typeof e=="function"?e(s):e;return this._refinement((s,n)=>{const r=t(s),o=()=>n.addIssue({code:u.custom,...i(s)});return typeof Promise<"u"&&r instanceof Promise?r.then(h=>h?!0:(o(),!1)):r?!0:(o(),!1)})}refinement(t,e){return this._refinement((i,s)=>t(i)?!0:(s.addIssue(typeof e=="function"?e(i,s):e),!1))}_refinement(t){return new X({schema:this,typeName:x.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Y.create(this,this._def)}nullable(){return at.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return j.create(this)}promise(){return Tt.create(this,this._def)}or(t){return Dt.create([this,t],this._def)}and(t){return Ft.create(this,t,this._def)}transform(t){return new X({...k(this._def),schema:this,typeName:x.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const e=typeof t=="function"?t:()=>t;return new Vt({...k(this._def),innerType:this,defaultValue:e,typeName:x.ZodDefault})}brand(){return new Se({typeName:x.ZodBranded,type:this,...k(this._def)})}catch(t){const e=typeof t=="function"?t:()=>t;return new Kt({...k(this._def),innerType:this,catchValue:e,typeName:x.ZodCatch})}describe(t){const e=this.constructor;return new e({...this._def,description:t})}pipe(t){return Zt.create(this,t)}readonly(){return jt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const ui=/^c[^\s-]{8,}$/i,di=/^[0-9a-z]+$/,fi=/^[0-9A-HJKMNP-TV-Z]{26}$/i,pi=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,mi=/^[a-z0-9_-]{21}$/i,gi=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,yi=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,vi=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,xi="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let te;const Ci=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ki=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,wi=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,bi=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,_i=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Si=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,we="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Ti=new RegExp(`^${we}$`);function be(a){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return a.precision?t=`${t}\\.\\d{${a.precision}}`:a.precision==null&&(t=`${t}(\\.\\d+)?`),t}function Ii(a){return new RegExp(`^${be(a)}$`)}function Oi(a){let t=`${we}T${be(a)}`;const e=[];return e.push(a.local?"Z?":"Z"),a.offset&&e.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${e.join("|")})`,new RegExp(`^${t}$`)}function Ai(a,t){return!!((t==="v4"||!t)&&Ci.test(a)||(t==="v6"||!t)&&wi.test(a))}function Pi(a,t){if(!gi.test(a))return!1;try{const[e]=a.split("."),i=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(e.length+(4-e.length%4)%4,"="),s=JSON.parse(atob(i));return!(typeof s!="object"||s===null||!s.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function Ei(a,t){return!!((t==="v4"||!t)&&ki.test(a)||(t==="v6"||!t)&&bi.test(a))}class U extends b{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==f.string){const n=this._getOrReturnCtx(t);return d(n,{code:u.invalid_type,expected:f.string,received:n.parsedType}),C}const i=new L;let s;for(const n of this._def.checks)if(n.kind==="min")t.data.length<n.value&&(s=this._getOrReturnCtx(t,s),d(s,{code:u.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),i.dirty());else if(n.kind==="max")t.data.length>n.value&&(s=this._getOrReturnCtx(t,s),d(s,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),i.dirty());else if(n.kind==="length"){const r=t.data.length>n.value,o=t.data.length<n.value;(r||o)&&(s=this._getOrReturnCtx(t,s),r?d(s,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):o&&d(s,{code:u.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),i.dirty())}else if(n.kind==="email")vi.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"email",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="emoji")te||(te=new RegExp(xi,"u")),te.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"emoji",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="uuid")pi.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"uuid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="nanoid")mi.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"nanoid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="cuid")ui.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"cuid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="cuid2")di.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"cuid2",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="ulid")fi.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"ulid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),d(s,{validation:"url",code:u.invalid_string,message:n.message}),i.dirty()}else n.kind==="regex"?(n.regex.lastIndex=0,n.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"regex",code:u.invalid_string,message:n.message}),i.dirty())):n.kind==="trim"?t.data=t.data.trim():n.kind==="includes"?t.data.includes(n.value,n.position)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),i.dirty()):n.kind==="toLowerCase"?t.data=t.data.toLowerCase():n.kind==="toUpperCase"?t.data=t.data.toUpperCase():n.kind==="startsWith"?t.data.startsWith(n.value)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:{startsWith:n.value},message:n.message}),i.dirty()):n.kind==="endsWith"?t.data.endsWith(n.value)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:{endsWith:n.value},message:n.message}),i.dirty()):n.kind==="datetime"?Oi(n).test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:"datetime",message:n.message}),i.dirty()):n.kind==="date"?Ti.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:"date",message:n.message}),i.dirty()):n.kind==="time"?Ii(n).test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:"time",message:n.message}),i.dirty()):n.kind==="duration"?yi.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"duration",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="ip"?Ai(t.data,n.version)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"ip",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="jwt"?Pi(t.data,n.alg)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"jwt",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="cidr"?Ei(t.data,n.version)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"cidr",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="base64"?_i.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"base64",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="base64url"?Si.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"base64url",code:u.invalid_string,message:n.message}),i.dirty()):S.assertNever(n);return{status:i.value,value:t.data}}_regex(t,e,i){return this.refinement(s=>t.test(s),{validation:e,code:u.invalid_string,...m.errToObj(i)})}_addCheck(t){return new U({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...m.errToObj(t)})}url(t){return this._addCheck({kind:"url",...m.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...m.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...m.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...m.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...m.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...m.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...m.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...m.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...m.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...m.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...m.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...m.errToObj(t)})}datetime(t){var e,i;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:(e=t?.offset)!==null&&e!==void 0?e:!1,local:(i=t?.local)!==null&&i!==void 0?i:!1,...m.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...m.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...m.errToObj(t)})}regex(t,e){return this._addCheck({kind:"regex",regex:t,...m.errToObj(e)})}includes(t,e){return this._addCheck({kind:"includes",value:t,position:e?.position,...m.errToObj(e?.message)})}startsWith(t,e){return this._addCheck({kind:"startsWith",value:t,...m.errToObj(e)})}endsWith(t,e){return this._addCheck({kind:"endsWith",value:t,...m.errToObj(e)})}min(t,e){return this._addCheck({kind:"min",value:t,...m.errToObj(e)})}max(t,e){return this._addCheck({kind:"max",value:t,...m.errToObj(e)})}length(t,e){return this._addCheck({kind:"length",value:t,...m.errToObj(e)})}nonempty(t){return this.min(1,m.errToObj(t))}trim(){return new U({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new U({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new U({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t}get maxLength(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t}}U.create=a=>{var t;return new U({checks:[],typeName:x.ZodString,coerce:(t=a?.coerce)!==null&&t!==void 0?t:!1,...k(a)})};function Li(a,t){const e=(a.toString().split(".")[1]||"").length,i=(t.toString().split(".")[1]||"").length,s=e>i?e:i,n=parseInt(a.toFixed(s).replace(".","")),r=parseInt(t.toFixed(s).replace(".",""));return n%r/Math.pow(10,s)}class ut extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==f.number){const n=this._getOrReturnCtx(t);return d(n,{code:u.invalid_type,expected:f.number,received:n.parsedType}),C}let i;const s=new L;for(const n of this._def.checks)n.kind==="int"?S.isInteger(t.data)||(i=this._getOrReturnCtx(t,i),d(i,{code:u.invalid_type,expected:"integer",received:"float",message:n.message}),s.dirty()):n.kind==="min"?(n.inclusive?t.data<n.value:t.data<=n.value)&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),s.dirty()):n.kind==="max"?(n.inclusive?t.data>n.value:t.data>=n.value)&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),s.dirty()):n.kind==="multipleOf"?Li(t.data,n.value)!==0&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),s.dirty()):n.kind==="finite"?Number.isFinite(t.data)||(i=this._getOrReturnCtx(t,i),d(i,{code:u.not_finite,message:n.message}),s.dirty()):S.assertNever(n);return{status:s.value,value:t.data}}gte(t,e){return this.setLimit("min",t,!0,m.toString(e))}gt(t,e){return this.setLimit("min",t,!1,m.toString(e))}lte(t,e){return this.setLimit("max",t,!0,m.toString(e))}lt(t,e){return this.setLimit("max",t,!1,m.toString(e))}setLimit(t,e,i,s){return new ut({...this._def,checks:[...this._def.checks,{kind:t,value:e,inclusive:i,message:m.toString(s)}]})}_addCheck(t){return new ut({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:m.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:m.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:m.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:m.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:m.toString(t)})}multipleOf(t,e){return this._addCheck({kind:"multipleOf",value:t,message:m.toString(e)})}finite(t){return this._addCheck({kind:"finite",message:m.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:m.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:m.toString(t)})}get minValue(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t}get maxValue(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&S.isInteger(t.value))}get isFinite(){let t=null,e=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(e===null||i.value>e)&&(e=i.value):i.kind==="max"&&(t===null||i.value<t)&&(t=i.value)}return Number.isFinite(e)&&Number.isFinite(t)}}ut.create=a=>new ut({checks:[],typeName:x.ZodNumber,coerce:a?.coerce||!1,...k(a)});class dt extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==f.bigint)return this._getInvalidInput(t);let i;const s=new L;for(const n of this._def.checks)n.kind==="min"?(n.inclusive?t.data<n.value:t.data<=n.value)&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),s.dirty()):n.kind==="max"?(n.inclusive?t.data>n.value:t.data>=n.value)&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),s.dirty()):n.kind==="multipleOf"?t.data%n.value!==BigInt(0)&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),s.dirty()):S.assertNever(n);return{status:s.value,value:t.data}}_getInvalidInput(t){const e=this._getOrReturnCtx(t);return d(e,{code:u.invalid_type,expected:f.bigint,received:e.parsedType}),C}gte(t,e){return this.setLimit("min",t,!0,m.toString(e))}gt(t,e){return this.setLimit("min",t,!1,m.toString(e))}lte(t,e){return this.setLimit("max",t,!0,m.toString(e))}lt(t,e){return this.setLimit("max",t,!1,m.toString(e))}setLimit(t,e,i,s){return new dt({...this._def,checks:[...this._def.checks,{kind:t,value:e,inclusive:i,message:m.toString(s)}]})}_addCheck(t){return new dt({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:m.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:m.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:m.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:m.toString(t)})}multipleOf(t,e){return this._addCheck({kind:"multipleOf",value:t,message:m.toString(e)})}get minValue(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t}get maxValue(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t}}dt.create=a=>{var t;return new dt({checks:[],typeName:x.ZodBigInt,coerce:(t=a?.coerce)!==null&&t!==void 0?t:!1,...k(a)})};class ee extends b{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==f.boolean){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.boolean,received:i.parsedType}),C}return z(t.data)}}ee.create=a=>new ee({typeName:x.ZodBoolean,coerce:a?.coerce||!1,...k(a)});class _t extends b{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==f.date){const n=this._getOrReturnCtx(t);return d(n,{code:u.invalid_type,expected:f.date,received:n.parsedType}),C}if(isNaN(t.data.getTime())){const n=this._getOrReturnCtx(t);return d(n,{code:u.invalid_date}),C}const i=new L;let s;for(const n of this._def.checks)n.kind==="min"?t.data.getTime()<n.value&&(s=this._getOrReturnCtx(t,s),d(s,{code:u.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),i.dirty()):n.kind==="max"?t.data.getTime()>n.value&&(s=this._getOrReturnCtx(t,s),d(s,{code:u.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),i.dirty()):S.assertNever(n);return{status:i.value,value:new Date(t.data.getTime())}}_addCheck(t){return new _t({...this._def,checks:[...this._def.checks,t]})}min(t,e){return this._addCheck({kind:"min",value:t.getTime(),message:m.toString(e)})}max(t,e){return this._addCheck({kind:"max",value:t.getTime(),message:m.toString(e)})}get minDate(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t!=null?new Date(t):null}}_t.create=a=>new _t({checks:[],coerce:a?.coerce||!1,typeName:x.ZodDate,...k(a)});class ie extends b{_parse(t){if(this._getType(t)!==f.symbol){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.symbol,received:i.parsedType}),C}return z(t.data)}}ie.create=a=>new ie({typeName:x.ZodSymbol,...k(a)});class Rt extends b{_parse(t){if(this._getType(t)!==f.undefined){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.undefined,received:i.parsedType}),C}return z(t.data)}}Rt.create=a=>new Rt({typeName:x.ZodUndefined,...k(a)});class zt extends b{_parse(t){if(this._getType(t)!==f.null){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.null,received:i.parsedType}),C}return z(t.data)}}zt.create=a=>new zt({typeName:x.ZodNull,...k(a)});class se extends b{constructor(){super(...arguments),this._any=!0}_parse(t){return z(t.data)}}se.create=a=>new se({typeName:x.ZodAny,...k(a)});class ft extends b{constructor(){super(...arguments),this._unknown=!0}_parse(t){return z(t.data)}}ft.create=a=>new ft({typeName:x.ZodUnknown,...k(a)});class tt extends b{_parse(t){const e=this._getOrReturnCtx(t);return d(e,{code:u.invalid_type,expected:f.never,received:e.parsedType}),C}}tt.create=a=>new tt({typeName:x.ZodNever,...k(a)});class ne extends b{_parse(t){if(this._getType(t)!==f.undefined){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.void,received:i.parsedType}),C}return z(t.data)}}ne.create=a=>new ne({typeName:x.ZodVoid,...k(a)});class j extends b{_parse(t){const{ctx:e,status:i}=this._processInputParams(t),s=this._def;if(e.parsedType!==f.array)return d(e,{code:u.invalid_type,expected:f.array,received:e.parsedType}),C;if(s.exactLength!==null){const r=e.data.length>s.exactLength.value,o=e.data.length<s.exactLength.value;(r||o)&&(d(e,{code:r?u.too_big:u.too_small,minimum:o?s.exactLength.value:void 0,maximum:r?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty())}if(s.minLength!==null&&e.data.length<s.minLength.value&&(d(e,{code:u.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()),s.maxLength!==null&&e.data.length>s.maxLength.value&&(d(e,{code:u.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()),e.common.async)return Promise.all([...e.data].map((r,o)=>s.type._parseAsync(new Z(e,r,e.path,o)))).then(r=>L.mergeArray(i,r));const n=[...e.data].map((r,o)=>s.type._parseSync(new Z(e,r,e.path,o)));return L.mergeArray(i,n)}get element(){return this._def.type}min(t,e){return new j({...this._def,minLength:{value:t,message:m.toString(e)}})}max(t,e){return new j({...this._def,maxLength:{value:t,message:m.toString(e)}})}length(t,e){return new j({...this._def,exactLength:{value:t,message:m.toString(e)}})}nonempty(t){return this.min(1,t)}}j.create=(a,t)=>new j({type:a,minLength:null,maxLength:null,exactLength:null,typeName:x.ZodArray,...k(t)});function pt(a){if(a instanceof A){const t={};for(const e in a.shape){const i=a.shape[e];t[e]=Y.create(pt(i))}return new A({...a._def,shape:()=>t})}else return a instanceof j?new j({...a._def,type:pt(a.element)}):a instanceof Y?Y.create(pt(a.unwrap())):a instanceof at?at.create(pt(a.unwrap())):a instanceof W?W.create(a.items.map(t=>pt(t))):a}class A extends b{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),e=S.objectKeys(t);return this._cached={shape:t,keys:e}}_parse(t){if(this._getType(t)!==f.object){const c=this._getOrReturnCtx(t);return d(c,{code:u.invalid_type,expected:f.object,received:c.parsedType}),C}const{status:i,ctx:s}=this._processInputParams(t),{shape:n,keys:r}=this._getCached(),o=[];if(!(this._def.catchall instanceof tt&&this._def.unknownKeys==="strip"))for(const c in s.data)r.includes(c)||o.push(c);const h=[];for(const c of r){const l=n[c],g=s.data[c];h.push({key:{status:"valid",value:c},value:l._parse(new Z(s,g,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof tt){const c=this._def.unknownKeys;if(c==="passthrough")for(const l of o)h.push({key:{status:"valid",value:l},value:{status:"valid",value:s.data[l]}});else if(c==="strict")o.length>0&&(d(s,{code:u.unrecognized_keys,keys:o}),i.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const l of o){const g=s.data[l];h.push({key:{status:"valid",value:l},value:c._parse(new Z(s,g,s.path,l)),alwaysSet:l in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const c=[];for(const l of h){const g=await l.key,p=await l.value;c.push({key:g,value:p,alwaysSet:l.alwaysSet})}return c}).then(c=>L.mergeObjectSync(i,c)):L.mergeObjectSync(i,h)}get shape(){return this._def.shape()}strict(t){return m.errToObj,new A({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(e,i)=>{var s,n,r,o;const h=(r=(n=(s=this._def).errorMap)===null||n===void 0?void 0:n.call(s,e,i).message)!==null&&r!==void 0?r:i.defaultError;return e.code==="unrecognized_keys"?{message:(o=m.errToObj(t).message)!==null&&o!==void 0?o:h}:{message:h}}}:{}})}strip(){return new A({...this._def,unknownKeys:"strip"})}passthrough(){return new A({...this._def,unknownKeys:"passthrough"})}extend(t){return new A({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new A({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:x.ZodObject})}setKey(t,e){return this.augment({[t]:e})}catchall(t){return new A({...this._def,catchall:t})}pick(t){const e={};return S.objectKeys(t).forEach(i=>{t[i]&&this.shape[i]&&(e[i]=this.shape[i])}),new A({...this._def,shape:()=>e})}omit(t){const e={};return S.objectKeys(this.shape).forEach(i=>{t[i]||(e[i]=this.shape[i])}),new A({...this._def,shape:()=>e})}deepPartial(){return pt(this)}partial(t){const e={};return S.objectKeys(this.shape).forEach(i=>{const s=this.shape[i];t&&!t[i]?e[i]=s:e[i]=s.optional()}),new A({...this._def,shape:()=>e})}required(t){const e={};return S.objectKeys(this.shape).forEach(i=>{if(t&&!t[i])e[i]=this.shape[i];else{let n=this.shape[i];for(;n instanceof Y;)n=n._def.innerType;e[i]=n}}),new A({...this._def,shape:()=>e})}keyof(){return _e(S.objectKeys(this.shape))}}A.create=(a,t)=>new A({shape:()=>a,unknownKeys:"strip",catchall:tt.create(),typeName:x.ZodObject,...k(t)}),A.strictCreate=(a,t)=>new A({shape:()=>a,unknownKeys:"strict",catchall:tt.create(),typeName:x.ZodObject,...k(t)}),A.lazycreate=(a,t)=>new A({shape:a,unknownKeys:"strip",catchall:tt.create(),typeName:x.ZodObject,...k(t)});class Dt extends b{_parse(t){const{ctx:e}=this._processInputParams(t),i=this._def.options;function s(n){for(const o of n)if(o.result.status==="valid")return o.result;for(const o of n)if(o.result.status==="dirty")return e.common.issues.push(...o.ctx.common.issues),o.result;const r=n.map(o=>new H(o.ctx.common.issues));return d(e,{code:u.invalid_union,unionErrors:r}),C}if(e.common.async)return Promise.all(i.map(async n=>{const r={...e,common:{...e.common,issues:[]},parent:null};return{result:await n._parseAsync({data:e.data,path:e.path,parent:r}),ctx:r}})).then(s);{let n;const r=[];for(const h of i){const c={...e,common:{...e.common,issues:[]},parent:null},l=h._parseSync({data:e.data,path:e.path,parent:c});if(l.status==="valid")return l;l.status==="dirty"&&!n&&(n={result:l,ctx:c}),c.common.issues.length&&r.push(c.common.issues)}if(n)return e.common.issues.push(...n.ctx.common.issues),n.result;const o=r.map(h=>new H(h));return d(e,{code:u.invalid_union,unionErrors:o}),C}}get options(){return this._def.options}}Dt.create=(a,t)=>new Dt({options:a,typeName:x.ZodUnion,...k(t)});const $=a=>a instanceof Ht?$(a.schema):a instanceof X?$(a.innerType()):a instanceof Nt?[a.value]:a instanceof nt?a.options:a instanceof Bt?S.objectValues(a.enum):a instanceof Vt?$(a._def.innerType):a instanceof Rt?[void 0]:a instanceof zt?[null]:a instanceof Y?[void 0,...$(a.unwrap())]:a instanceof at?[null,...$(a.unwrap())]:a instanceof Se||a instanceof jt?$(a.unwrap()):a instanceof Kt?$(a._def.innerType):[];class ae extends b{_parse(t){const{ctx:e}=this._processInputParams(t);if(e.parsedType!==f.object)return d(e,{code:u.invalid_type,expected:f.object,received:e.parsedType}),C;const i=this.discriminator,s=e.data[i],n=this.optionsMap.get(s);return n?e.common.async?n._parseAsync({data:e.data,path:e.path,parent:e}):n._parseSync({data:e.data,path:e.path,parent:e}):(d(e,{code:u.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),C)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,e,i){const s=new Map;for(const n of e){const r=$(n.shape[t]);if(!r.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const o of r){if(s.has(o))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(o)}`);s.set(o,n)}}return new ae({typeName:x.ZodDiscriminatedUnion,discriminator:t,options:e,optionsMap:s,...k(i)})}}function re(a,t){const e=J(a),i=J(t);if(a===t)return{valid:!0,data:a};if(e===f.object&&i===f.object){const s=S.objectKeys(t),n=S.objectKeys(a).filter(o=>s.indexOf(o)!==-1),r={...a,...t};for(const o of n){const h=re(a[o],t[o]);if(!h.valid)return{valid:!1};r[o]=h.data}return{valid:!0,data:r}}else if(e===f.array&&i===f.array){if(a.length!==t.length)return{valid:!1};const s=[];for(let n=0;n<a.length;n++){const r=a[n],o=t[n],h=re(r,o);if(!h.valid)return{valid:!1};s.push(h.data)}return{valid:!0,data:s}}else return e===f.date&&i===f.date&&+a==+t?{valid:!0,data:a}:{valid:!1}}class Ft extends b{_parse(t){const{status:e,ctx:i}=this._processInputParams(t),s=(n,r)=>{if(ve(n)||ve(r))return C;const o=re(n.value,r.value);return o.valid?((xe(n)||xe(r))&&e.dirty(),{status:e.value,value:o.data}):(d(i,{code:u.invalid_intersection_types}),C)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([n,r])=>s(n,r)):s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}Ft.create=(a,t,e)=>new Ft({left:a,right:t,typeName:x.ZodIntersection,...k(e)});class W extends b{_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==f.array)return d(i,{code:u.invalid_type,expected:f.array,received:i.parsedType}),C;if(i.data.length<this._def.items.length)return d(i,{code:u.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),C;!this._def.rest&&i.data.length>this._def.items.length&&(d(i,{code:u.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),e.dirty());const n=[...i.data].map((r,o)=>{const h=this._def.items[o]||this._def.rest;return h?h._parse(new Z(i,r,i.path,o)):null}).filter(r=>!!r);return i.common.async?Promise.all(n).then(r=>L.mergeArray(e,r)):L.mergeArray(e,n)}get items(){return this._def.items}rest(t){return new W({...this._def,rest:t})}}W.create=(a,t)=>{if(!Array.isArray(a))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new W({items:a,typeName:x.ZodTuple,rest:null,...k(t)})};class Mt extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==f.object)return d(i,{code:u.invalid_type,expected:f.object,received:i.parsedType}),C;const s=[],n=this._def.keyType,r=this._def.valueType;for(const o in i.data)s.push({key:n._parse(new Z(i,o,i.path,o)),value:r._parse(new Z(i,i.data[o],i.path,o)),alwaysSet:o in i.data});return i.common.async?L.mergeObjectAsync(e,s):L.mergeObjectSync(e,s)}get element(){return this._def.valueType}static create(t,e,i){return e instanceof b?new Mt({keyType:t,valueType:e,typeName:x.ZodRecord,...k(i)}):new Mt({keyType:U.create(),valueType:t,typeName:x.ZodRecord,...k(e)})}}class oe extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==f.map)return d(i,{code:u.invalid_type,expected:f.map,received:i.parsedType}),C;const s=this._def.keyType,n=this._def.valueType,r=[...i.data.entries()].map(([o,h],c)=>({key:s._parse(new Z(i,o,i.path,[c,"key"])),value:n._parse(new Z(i,h,i.path,[c,"value"]))}));if(i.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const h of r){const c=await h.key,l=await h.value;if(c.status==="aborted"||l.status==="aborted")return C;(c.status==="dirty"||l.status==="dirty")&&e.dirty(),o.set(c.value,l.value)}return{status:e.value,value:o}})}else{const o=new Map;for(const h of r){const c=h.key,l=h.value;if(c.status==="aborted"||l.status==="aborted")return C;(c.status==="dirty"||l.status==="dirty")&&e.dirty(),o.set(c.value,l.value)}return{status:e.value,value:o}}}}oe.create=(a,t,e)=>new oe({valueType:t,keyType:a,typeName:x.ZodMap,...k(e)});class mt extends b{_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==f.set)return d(i,{code:u.invalid_type,expected:f.set,received:i.parsedType}),C;const s=this._def;s.minSize!==null&&i.data.size<s.minSize.value&&(d(i,{code:u.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),e.dirty()),s.maxSize!==null&&i.data.size>s.maxSize.value&&(d(i,{code:u.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),e.dirty());const n=this._def.valueType;function r(h){const c=new Set;for(const l of h){if(l.status==="aborted")return C;l.status==="dirty"&&e.dirty(),c.add(l.value)}return{status:e.value,value:c}}const o=[...i.data.values()].map((h,c)=>n._parse(new Z(i,h,i.path,c)));return i.common.async?Promise.all(o).then(h=>r(h)):r(o)}min(t,e){return new mt({...this._def,minSize:{value:t,message:m.toString(e)}})}max(t,e){return new mt({...this._def,maxSize:{value:t,message:m.toString(e)}})}size(t,e){return this.min(t,e).max(t,e)}nonempty(t){return this.min(1,t)}}mt.create=(a,t)=>new mt({valueType:a,minSize:null,maxSize:null,typeName:x.ZodSet,...k(t)});class St extends b{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:e}=this._processInputParams(t);if(e.parsedType!==f.function)return d(e,{code:u.invalid_type,expected:f.function,received:e.parsedType}),C;function i(o,h){return Jt({data:o,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,Qt(),Ct].filter(c=>!!c),issueData:{code:u.invalid_arguments,argumentsError:h}})}function s(o,h){return Jt({data:o,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,Qt(),Ct].filter(c=>!!c),issueData:{code:u.invalid_return_type,returnTypeError:h}})}const n={errorMap:e.common.contextualErrorMap},r=e.data;if(this._def.returns instanceof Tt){const o=this;return z(async function(...h){const c=new H([]),l=await o._def.args.parseAsync(h,n).catch(w=>{throw c.addIssue(i(h,w)),c}),g=await Reflect.apply(r,this,l);return await o._def.returns._def.type.parseAsync(g,n).catch(w=>{throw c.addIssue(s(g,w)),c})})}else{const o=this;return z(function(...h){const c=o._def.args.safeParse(h,n);if(!c.success)throw new H([i(h,c.error)]);const l=Reflect.apply(r,this,c.data),g=o._def.returns.safeParse(l,n);if(!g.success)throw new H([s(l,g.error)]);return g.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new St({...this._def,args:W.create(t).rest(ft.create())})}returns(t){return new St({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,e,i){return new St({args:t||W.create([]).rest(ft.create()),returns:e||ft.create(),typeName:x.ZodFunction,...k(i)})}}class Ht extends b{get schema(){return this._def.getter()}_parse(t){const{ctx:e}=this._processInputParams(t);return this._def.getter()._parse({data:e.data,path:e.path,parent:e})}}Ht.create=(a,t)=>new Ht({getter:a,typeName:x.ZodLazy,...k(t)});class Nt extends b{_parse(t){if(t.data!==this._def.value){const e=this._getOrReturnCtx(t);return d(e,{received:e.data,code:u.invalid_literal,expected:this._def.value}),C}return{status:"valid",value:t.data}}get value(){return this._def.value}}Nt.create=(a,t)=>new Nt({value:a,typeName:x.ZodLiteral,...k(t)});function _e(a,t){return new nt({values:a,typeName:x.ZodEnum,...k(t)})}class nt extends b{constructor(){super(...arguments),wt.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const e=this._getOrReturnCtx(t),i=this._def.values;return d(e,{expected:S.joinValues(i),received:e.parsedType,code:u.invalid_type}),C}if(Lt(this,wt)||Ce(this,wt,new Set(this._def.values)),!Lt(this,wt).has(t.data)){const e=this._getOrReturnCtx(t),i=this._def.values;return d(e,{received:e.data,code:u.invalid_enum_value,options:i}),C}return z(t.data)}get options(){return this._def.values}get enum(){const t={};for(const e of this._def.values)t[e]=e;return t}get Values(){const t={};for(const e of this._def.values)t[e]=e;return t}get Enum(){const t={};for(const e of this._def.values)t[e]=e;return t}extract(t,e=this._def){return nt.create(t,{...this._def,...e})}exclude(t,e=this._def){return nt.create(this.options.filter(i=>!t.includes(i)),{...this._def,...e})}}wt=new WeakMap,nt.create=_e;class Bt extends b{constructor(){super(...arguments),bt.set(this,void 0)}_parse(t){const e=S.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==f.string&&i.parsedType!==f.number){const s=S.objectValues(e);return d(i,{expected:S.joinValues(s),received:i.parsedType,code:u.invalid_type}),C}if(Lt(this,bt)||Ce(this,bt,new Set(S.getValidEnumValues(this._def.values))),!Lt(this,bt).has(t.data)){const s=S.objectValues(e);return d(i,{received:i.data,code:u.invalid_enum_value,options:s}),C}return z(t.data)}get enum(){return this._def.values}}bt=new WeakMap,Bt.create=(a,t)=>new Bt({values:a,typeName:x.ZodNativeEnum,...k(t)});class Tt extends b{unwrap(){return this._def.type}_parse(t){const{ctx:e}=this._processInputParams(t);if(e.parsedType!==f.promise&&e.common.async===!1)return d(e,{code:u.invalid_type,expected:f.promise,received:e.parsedType}),C;const i=e.parsedType===f.promise?e.data:Promise.resolve(e.data);return z(i.then(s=>this._def.type.parseAsync(s,{path:e.path,errorMap:e.common.contextualErrorMap})))}}Tt.create=(a,t)=>new Tt({type:a,typeName:x.ZodPromise,...k(t)});class X extends b{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===x.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:e,ctx:i}=this._processInputParams(t),s=this._def.effect||null,n={addIssue:r=>{d(i,r),r.fatal?e.abort():e.dirty()},get path(){return i.path}};if(n.addIssue=n.addIssue.bind(n),s.type==="preprocess"){const r=s.transform(i.data,n);if(i.common.async)return Promise.resolve(r).then(async o=>{if(e.value==="aborted")return C;const h=await this._def.schema._parseAsync({data:o,path:i.path,parent:i});return h.status==="aborted"?C:h.status==="dirty"||e.value==="dirty"?kt(h.value):h});{if(e.value==="aborted")return C;const o=this._def.schema._parseSync({data:r,path:i.path,parent:i});return o.status==="aborted"?C:o.status==="dirty"||e.value==="dirty"?kt(o.value):o}}if(s.type==="refinement"){const r=o=>{const h=s.refinement(o,n);if(i.common.async)return Promise.resolve(h);if(h instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(i.common.async===!1){const o=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return o.status==="aborted"?C:(o.status==="dirty"&&e.dirty(),r(o.value),{status:e.value,value:o.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(o=>o.status==="aborted"?C:(o.status==="dirty"&&e.dirty(),r(o.value).then(()=>({status:e.value,value:o.value}))))}if(s.type==="transform")if(i.common.async===!1){const r=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!ht(r))return r;const o=s.transform(r.value,n);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:e.value,value:o}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(r=>ht(r)?Promise.resolve(s.transform(r.value,n)).then(o=>({status:e.value,value:o})):r);S.assertNever(s)}}X.create=(a,t,e)=>new X({schema:a,typeName:x.ZodEffects,effect:t,...k(e)}),X.createWithPreprocess=(a,t,e)=>new X({schema:t,effect:{type:"preprocess",transform:a},typeName:x.ZodEffects,...k(e)});class Y extends b{_parse(t){return this._getType(t)===f.undefined?z(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Y.create=(a,t)=>new Y({innerType:a,typeName:x.ZodOptional,...k(t)});class at extends b{_parse(t){return this._getType(t)===f.null?z(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}at.create=(a,t)=>new at({innerType:a,typeName:x.ZodNullable,...k(t)});class Vt extends b{_parse(t){const{ctx:e}=this._processInputParams(t);let i=e.data;return e.parsedType===f.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:e.path,parent:e})}removeDefault(){return this._def.innerType}}Vt.create=(a,t)=>new Vt({innerType:a,typeName:x.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...k(t)});class Kt extends b{_parse(t){const{ctx:e}=this._processInputParams(t),i={...e,common:{...e.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return Et(s)?s.then(n=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new H(i.common.issues)},input:i.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new H(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Kt.create=(a,t)=>new Kt({innerType:a,typeName:x.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...k(t)});class ce extends b{_parse(t){if(this._getType(t)!==f.nan){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.nan,received:i.parsedType}),C}return{status:"valid",value:t.data}}}ce.create=a=>new ce({typeName:x.ZodNaN,...k(a)});class Se extends b{_parse(t){const{ctx:e}=this._processInputParams(t),i=e.data;return this._def.type._parse({data:i,path:e.path,parent:e})}unwrap(){return this._def.type}}class Zt extends b{_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.common.async)return(async()=>{const n=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return n.status==="aborted"?C:n.status==="dirty"?(e.dirty(),kt(n.value)):this._def.out._parseAsync({data:n.value,path:i.path,parent:i})})();{const s=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?C:s.status==="dirty"?(e.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:i.path,parent:i})}}static create(t,e){return new Zt({in:t,out:e,typeName:x.ZodPipeline})}}class jt extends b{_parse(t){const e=this._def.innerType._parse(t),i=s=>(ht(s)&&(s.value=Object.freeze(s.value)),s);return Et(e)?e.then(s=>i(s)):i(e)}unwrap(){return this._def.innerType}}jt.create=(a,t)=>new jt({innerType:a,typeName:x.ZodReadonly,...k(t)}),A.lazycreate;var x;(function(a){a.ZodString="ZodString",a.ZodNumber="ZodNumber",a.ZodNaN="ZodNaN",a.ZodBigInt="ZodBigInt",a.ZodBoolean="ZodBoolean",a.ZodDate="ZodDate",a.ZodSymbol="ZodSymbol",a.ZodUndefined="ZodUndefined",a.ZodNull="ZodNull",a.ZodAny="ZodAny",a.ZodUnknown="ZodUnknown",a.ZodNever="ZodNever",a.ZodVoid="ZodVoid",a.ZodArray="ZodArray",a.ZodObject="ZodObject",a.ZodUnion="ZodUnion",a.ZodDiscriminatedUnion="ZodDiscriminatedUnion",a.ZodIntersection="ZodIntersection",a.ZodTuple="ZodTuple",a.ZodRecord="ZodRecord",a.ZodMap="ZodMap",a.ZodSet="ZodSet",a.ZodFunction="ZodFunction",a.ZodLazy="ZodLazy",a.ZodLiteral="ZodLiteral",a.ZodEnum="ZodEnum",a.ZodEffects="ZodEffects",a.ZodNativeEnum="ZodNativeEnum",a.ZodOptional="ZodOptional",a.ZodNullable="ZodNullable",a.ZodDefault="ZodDefault",a.ZodCatch="ZodCatch",a.ZodPromise="ZodPromise",a.ZodBranded="ZodBranded",a.ZodPipeline="ZodPipeline",a.ZodReadonly="ZodReadonly"})(x||(x={}));const R=U.create,v=ut.create;ce.create,dt.create,ee.create,_t.create,ie.create,Rt.create,zt.create,se.create,ft.create,tt.create,ne.create,j.create;const T=A.create;A.strictCreate;const Ri=Dt.create;ae.create,Ft.create,W.create,Mt.create,oe.create,mt.create,St.create,Ht.create;const rt=Nt.create,et=nt.create;Bt.create,Tt.create,X.create,Y.create,at.create,X.createWithPreprocess,Zt.create;const zi=et(["linear","bezier","constant"]),Di=et(["ease","easeIn","easeOut","easeInOut","easeInQuad","easeInCubic","easeInQuart","easeInQuint","easeInSine","easeInExpo","easeInCirc","easeInBack","easeOutQuad","easeOutCubic","easeOutQuart","easeOutQuint","easeOutSine","easeOutExpo","easeOutCirc","easeOutBack","easeInOutQuad","easeInOutCubic","easeInOutQuart","easeInOutQuint","easeInOutSine","easeInOutExpo","easeInOutCirc","easeInOutBack"]),ot=T({from:v(),to:v(),start:v().min(0),length:v().positive(),interpolation:zi.optional(),easing:Di.optional()}),Fi=R().url("Invalid audio url format."),Mi=ot.extend({from:v().min(0).max(1),to:v().min(0).max(1)}).array().or(v().min(0).max(1)),Te=T({type:rt("audio"),src:Fi,trim:v().optional(),volume:Mi.optional()}),Hi=et(["top","topRight","right","bottomRight","bottom","bottomLeft","left","topLeft","center"]),Ie=T({type:rt("html"),html:R(),css:R(),width:v().positive().optional(),height:v().positive().optional(),position:Hi.optional()}),Ni=R().url("Invalid image url format."),Bi=T({top:v().min(0).optional(),right:v().min(0).optional(),bottom:v().min(0).optional(),left:v().min(0).optional()}),Oe=T({type:rt("image"),src:Ni,crop:Bi.optional()}),Vi=R().url("Invalid luma url format."),Ae=T({type:rt("luma"),src:Vi}),Pe=R().regex(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})|transparent$/,"Invalid color format."),Ee=T({width:v().positive(),height:v().positive()}),Le=T({radius:v().positive()}),Re=T({length:v().positive(),thickness:v().positive()}),Ki=T({color:Pe,opacity:v().min(0).max(1)}),Zi=T({color:Pe,width:v().positive()}),ze=T({type:rt("shape"),width:v().positive().optional(),height:v().positive().optional(),shape:et(["rectangle","circle","line"]),fill:Ki.optional(),stroke:Zi.optional(),rectangle:Ee.optional(),circle:Le.optional(),line:Re.optional()}).refine(a=>a.shape==="rectangle"?Ee.safeParse(a.rectangle):a.shape==="circle"?Le.safeParse(a.circle):a.shape==="line"?Re.safeParse(a.line):!1),le=R().regex(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})|transparent$/,"Invalid color format."),ji=T({color:le.optional(),family:R().optional(),size:v().positive().optional(),weight:v().optional(),lineHeight:v().optional()}),Ui=T({horizontal:et(["left","center","right"]).optional(),vertical:et(["top","center","bottom"]).optional()}),$i=T({color:le,opacity:v().min(0).max(1)}),Wi=T({width:v().positive(),color:le}),De=T({type:rt("text"),text:R(),width:v().positive().optional(),height:v().positive().optional(),font:ji.optional(),alignment:Ui.optional(),background:$i.optional(),stroke:Wi.optional()}),Xi=R().url("Invalid video url format."),Yi=T({top:v().min(0).optional(),right:v().min(0).optional(),bottom:v().min(0).optional(),left:v().min(0).optional()}),Gi=ot.extend({from:v().min(0).max(1),to:v().min(0).max(1)}).array().or(v().min(0).max(1)),Fe=T({type:rt("video"),src:Xi,trim:v().optional(),crop:Yi.optional(),volume:Gi.optional()}),qi=Ri([De,ze,Ie,Oe,Fe,Ae,Te]).refine(a=>a.type==="text"?De.safeParse(a):a.type==="shape"?ze.safeParse(a):a.type==="html"?Ie.safeParse(a):a.type==="image"?Oe.safeParse(a):a.type==="video"?Fe.safeParse(a):a.type==="luma"?Ae.safeParse(a):a.type==="audio"?Te.safeParse(a):!1),Qi=et(["topLeft","top","topRight","left","center","right","bottomLeft","bottom","bottomRight"]),Ji=et(["crop","cover","contain","none"]),gt=v().min(-10).max(10).default(0),ts=ot.extend({from:gt,to:gt}).array().or(gt),es=ot.extend({from:gt,to:gt}).array().or(gt),is=T({x:ts.default(0),y:es.default(0)}),ss=ot.extend({from:v().min(0).max(1),to:v().min(0).max(1)}).array().or(v().min(0).max(1)),ns=ot.extend({from:v().min(0),to:v().min(0)}).array().or(v().min(0)),as=T({angle:ot.extend({from:v(),to:v()}).array().or(v())}),rs=R(),Me=R(),os=T({in:Me.optional(),out:Me.optional()}),cs=T({rotate:as.default({angle:0})}),He=T({asset:qi,start:v().min(0),length:v().positive(),position:Qi.default("center").optional(),fit:Ji.default("crop").optional(),offset:is.default({x:0,y:0}).optional(),opacity:ss.default(1).optional(),scale:ns.default(1).optional(),transform:cs.default({rotate:{angle:0}}).optional(),effect:rs.optional(),transition:os.optional()});class ls{constructor(t,e){this.trackIdx=t,this.clip=e}name="addClip";addedPlayer;async execute(t){if(!t)return;const e=He.parse(this.clip),i=t.createPlayerFromAssetType(e);i.layer=this.trackIdx+1,await t.addPlayer(this.trackIdx,i),t.updateDuration(),this.addedPlayer=i}async undo(t){!t||!this.addedPlayer||(t.queueDisposeClip(this.addedPlayer),t.updateDuration())}}class hs{constructor(t){this.trackIdx=t}name="addTrack";execute(t){if(!t)return;const e=t.getTracks(),i=t.getClips();e.splice(this.trackIdx,0,[]);const s=i.filter(r=>r.layer>=this.trackIdx+1),n=t.getContainer();i.forEach((r,o)=>{r.layer>=this.trackIdx+1&&(n.getChildByLabel(`shotstack-track-${1e5-r.layer*100}`,!1)?.removeChild(r.getContainer()),i[o].layer+=1)}),s.forEach(r=>{const o=1e5-r.layer*100;let h=n.getChildByLabel(`shotstack-track-${o}`,!1);h||(h=new y.Container({label:`shotstack-track-${o}`,zIndex:o}),n.addChild(h)),h.addChild(r.getContainer())}),t.updateDuration()}undo(t){if(!t)return;const e=t.getTracks(),i=t.getClips();e.splice(this.trackIdx,1),i.forEach((s,n)=>{s.layer>this.trackIdx+1&&(i[n].layer-=1)}),t.updateDuration()}}class us{constructor(t,e){this.trackIdx=t,this.clipIdx=e}name="deleteClip";deletedClip;execute(t){if(!t)return;const i=t.getClips().filter(s=>s.layer===this.trackIdx+1);this.deletedClip=i[this.clipIdx],this.deletedClip&&(t.queueDisposeClip(this.deletedClip),t.updateDuration())}undo(t){!t||!this.deletedClip||t.undeleteClip(this.trackIdx,this.deletedClip)}}class ds{constructor(t){this.trackIdx=t}name="deleteTrack";deletedClips=[];execute(t){if(!t)return;const e=t.getClips(),i=t.getTracks();this.deletedClips=e.filter(r=>r.layer===this.trackIdx+1).map(r=>({config:structuredClone(r.clipConfiguration)})),e.forEach((r,o)=>{r.layer===this.trackIdx+1&&(e[o].shouldDispose=!0)}),t.disposeClips(),i.splice(this.trackIdx,1);const s=t.getClips(),n=t.getContainer();s.forEach((r,o)=>{if(r.layer>this.trackIdx+1){n.getChildByLabel(`shotstack-track-${1e5-r.layer*100}`,!1)?.removeChild(r.getContainer()),s[o].layer-=1;const c=1e5-s[o].layer*100;let l=n.getChildByLabel(`shotstack-track-${c}`,!1);l||(l=new y.Container({label:`shotstack-track-${c}`,zIndex:c}),n.addChild(l)),l.addChild(s[o].getContainer())}}),t.updateDuration()}async undo(t){if(!t||this.deletedClips.length===0)return;const e=t.getTracks(),i=t.getClips();e.splice(this.trackIdx,0,[]),i.forEach((s,n)=>{s.layer>=this.trackIdx+1&&(i[n].layer+=1)});for(const{config:s}of this.deletedClips){const n=t.createPlayerFromAssetType(s);n.layer=this.trackIdx+1,await t.addPlayer(this.trackIdx,n)}t.updateDuration()}}class fs{constructor(t,e,i){this.clip=t,this.initialClipConfig=e,this.finalClipConfig=i,this.storedInitialConfig=e?structuredClone(e):null,this.storedFinalConfig=i?structuredClone(i):structuredClone(this.clip.clipConfiguration)}name="setUpdatedClip";storedInitialConfig;storedFinalConfig;execute(t){if(!t)return;this.storedFinalConfig&&t.restoreClipConfiguration(this.clip,this.storedFinalConfig),t.setUpdatedClip(this.clip);const e=this.clip.layer-1,n=t.getClips().filter(r=>r.layer===this.clip.layer).indexOf(this.clip);t.emitEvent("clip:updated",{previous:{clip:this.storedInitialConfig||this.initialClipConfig,trackIndex:e,clipIndex:n},current:{clip:this.storedFinalConfig||this.clip.clipConfiguration,trackIndex:e,clipIndex:n}})}undo(t){if(!t||!this.storedInitialConfig)return;t.restoreClipConfiguration(this.clip,this.storedInitialConfig),t.setUpdatedClip(this.clip);const e=this.clip.layer-1,n=t.getClips().filter(r=>r.layer===this.clip.layer).indexOf(this.clip);t.emitEvent("clip:updated",{previous:{clip:this.storedFinalConfig,trackIndex:e,clipIndex:n},current:{clip:this.storedInitialConfig,trackIndex:e,clipIndex:n}})}}class ps{constructor(t,e,i){this.clip=t,this.newText=e,this.initialConfig=i;const{asset:s}=this.clip.clipConfiguration;this.previousText=s&&"text"in s?s.text:""}name="updateTextContent";previousText;execute(t){if(t&&this.clip.clipConfiguration.asset&&"text"in this.clip.clipConfiguration.asset){this.clip.clipConfiguration.asset.text=this.newText;const e=this.clip.text;e&&(e.text=this.newText,this.clip.positionText(this.clip.clipConfiguration.asset)),t.setUpdatedClip(this.clip);const i=this.clip.layer-1,r=t.getClips().filter(o=>o.layer===this.clip.layer).indexOf(this.clip);t.emitEvent("clip:updated",{previous:{clip:this.initialConfig,trackIndex:i,clipIndex:r},current:{clip:this.clip.clipConfiguration,trackIndex:i,clipIndex:r}})}}undo(t){if(t&&this.clip.clipConfiguration.asset&&"text"in this.clip.clipConfiguration.asset){this.clip.clipConfiguration.asset.text=this.previousText;const e=this.clip.text;e&&(e.text=this.previousText,this.clip.positionText(this.clip.clipConfiguration.asset)),t.setUpdatedClip(this.clip);const i=this.clip.layer-1,r=t.getClips().filter(o=>o.layer===this.clip.layer).indexOf(this.clip);t.emitEvent("clip:updated",{previous:{clip:this.clip.clipConfiguration,trackIndex:i,clipIndex:r},current:{clip:this.initialConfig,trackIndex:i,clipIndex:r}})}}}class Ne{events;constructor(){this.events={}}on(t,e){this.events[t]||(this.events[t]=new Set),this.events[t].add(e)}off(t,e){this.events[t]&&(this.events[t].delete(e),!(this.events[t].size>0)&&delete this.events[t])}clear(t){delete this.events[t]}emit(t,e){if(this.events[t])for(const i of this.events[t])i(e)}}class ms extends Ne{registry;constructor(){super(),this.registry={}}}class Ut{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 ms;async load(t,e){this.updateAssetLoadMetadata(t,"pending",0);try{if(await this.shouldUseSafariVideoLoader(e))return await this.loadVideoForSafari(t,e);const i=await y.Assets.load(e,s=>{this.updateAssetLoadMetadata(t,"loading",s)});return this.updateAssetLoadMetadata(t,"success",1),i}catch{return this.updateAssetLoadMetadata(t,"failed",1),null}}getProgress(){const t=Object.keys(this.loadTracker.registry);return t.length===0?0:t.reduce((i,s)=>i+this.loadTracker.registry[s].progress,0)/t.length}extractUrl(t){if(typeof t=="string")return t;const e=Array.isArray(t.src)?t.src[0]:t.src;return typeof e=="string"?e:e?.src}hasVideoExtension(t){const e=new URL(t,window.location.origin).pathname.toLowerCase();return Ut.VIDEO_EXTENSIONS.some(i=>e.endsWith(i))}async getContentType(t){try{return(await fetch(t,{method:"HEAD"})).headers.get("content-type")}catch{return null}}canPlayVideo(t){const e=new URL(t,window.location.origin).pathname.toLowerCase(),i=e.slice(e.lastIndexOf(".")),s=Ut.VIDEO_MIME[i];return s?document.createElement("video").canPlayType(s)!=="":!1}async isPlayableVideo(t){if(this.hasVideoExtension(t))return this.canPlayVideo(t);const e=await this.getContentType(t);return e?.startsWith("video/")?document.createElement("video").canPlayType(e)!=="":!1}async shouldUseSafariVideoLoader(t){const e=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),i=this.extractUrl(t);return e&&i!==void 0&&await this.isPlayableVideo(i)}async loadVideoForSafari(t,e){const i=this.extractUrl(e),s=typeof e=="object"?e.data??{}:{},n=await new Promise((r,o)=>{const h=document.createElement("video");h.crossOrigin="anonymous",h.playsInline=!0,h.muted=!0,h.preload="metadata",h.addEventListener("loadedmetadata",()=>{try{const c=new y.VideoSource({resource:h,autoPlay:s.autoPlay??!1,...s});r(new y.Texture({source:c}))}catch(c){o(c)}},{once:!0}),h.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(t,"loading",.5),h.src=i});return this.updateAssetLoadMetadata(t,"success",1),n}updateAssetLoadMetadata(t,e,i){this.loadTracker.registry[t]?(this.loadTracker.registry[t].progress=i,this.loadTracker.registry[t].status=e):this.loadTracker.registry[t]={progress:i,status:e};const s={...this.loadTracker.registry};this.loadTracker.emit("onAssetLoadInfoUpdated",{registry:s})}}class $t{static Name="FontLoadParser";name;extension;validFontExtensions;woff2Decompressor;constructor(){this.name=$t.Name,this.extension={type:[y.ExtensionType.LoadParser],priority:y.LoaderParserPriority.High,ref:null},this.validFontExtensions=["ttf","otf","woff","woff2"],this.woff2Decompressor=null}test(t){const e=t.split("?")[0]?.split(".").pop()?.toLowerCase()??"";return this.validFontExtensions.includes(e)}async load(t,e,i){const s=t.split("?")[0]?.split(".").pop()?.toLowerCase()??"",n=await fetch(t).then(p=>p.arrayBuffer());if(s!=="woff2"){const p=me.parse(new Uint8Array(n).buffer),w=p.names.fontFamily.en||p.names.fontFamily[Object.keys(p.names.fontFamily)[0]],I=new FontFace(w,`url(${t})`);return await I.load(),document.fonts.add(I),I}if(await this.loadWoff2Decompressor(),!this.woff2Decompressor)throw new Error("Cannot initialize Woff2 decompressor.");const r=this.woff2Decompressor.decompress(n),o=me.parse(new Uint8Array(r).buffer),h=o.names.fontFamily.en||o.names.fontFamily[Object.keys(o.names.fontFamily)[0]],c=new Blob([r],{type:"font/ttf"}),l=URL.createObjectURL(c),g=new FontFace(h,`url(${l})`);return await g.load(),document.fonts.add(g),g}async loadWoff2Decompressor(){if(this.woff2Decompressor)return;const e=`${await fetch("https://unpkg.com/wawoff2@2.0.1/build/decompress_binding.js").then(i=>i.text())}; return Module`;this.woff2Decompressor=new Function(e)(),await new Promise(i=>{this.woff2Decompressor.onRuntimeInitialized=i})}unload(t){t&&document.fonts.delete(t)}}const gs=T({clips:He.array()}),ys=R().url("Invalid image url format."),vs=T({src:ys}),xs=T({background:R().optional(),fonts:vs.array().optional(),tracks:gs.array()}),Cs=T({size:T({width:v().positive(),height:v().positive()}),fps:v().positive().optional(),format:R()}),ks=T({timeline:xs,output:Cs});class he extends Yt{static ZIndexPadding=100;assetLoader;events;edit;tracks;clipsToDispose;clips;commandHistory=[];commandIndex=-1;playbackTime;size;backgroundColor;totalDuration;isPlaying;selectedClip;updatedClip;constructor(t,e="#ffffff"){super(),this.assetLoader=new Ut,this.edit=null,this.tracks=[],this.clipsToDispose=[],this.clips=[],this.events=new Ne,this.size=t,this.playbackTime=0,this.totalDuration=0,this.isPlaying=!1,this.selectedClip=null,this.updatedClip=null,this.backgroundColor=e}async load(){const t=new y.Graphics;t.fillStyle={color:this.backgroundColor},t.rect(0,0,this.size.width,this.size.height),t.fill(),this.getContainer().addChild(t)}update(t,e){for(const i of this.clips)i.shouldDispose&&this.queueDisposeClip(i),i.update(t,e);this.disposeClips(),this.isPlaying&&(this.playbackTime=Math.max(0,Math.min(this.playbackTime+e,this.totalDuration)),this.playbackTime===this.totalDuration&&this.pause())}draw(){for(const t of this.clips)t.draw()}dispose(){this.clearClips()}play(){this.isPlaying=!0}pause(){this.isPlaying=!1}seek(t){this.playbackTime=Math.max(0,Math.min(t,this.totalDuration)),this.pause()}stop(){this.seek(0)}async loadEdit(t){this.clearClips(),this.edit=ks.parse(t),this.backgroundColor=this.edit.timeline.background||"#000000",await Promise.all((this.edit.timeline.fonts??[]).map(async e=>{const i=e.src,s={src:i,loadParser:$t.Name};return this.assetLoader.load(i,s)}));for(const[e,i]of this.edit.timeline.tracks.entries())for(const s of i.clips){const n=this.createPlayerFromAssetType(s);n.layer=e+1,await this.addPlayer(e,n)}this.updateTotalDuration()}getEdit(){const t=[],e=new Map;for(const s of this.clips)e.has(s.layer)||e.set(s.layer,{clips:[]}),e.get(s.layer).clips.push(s.clipConfiguration);const i=Math.max(...e.keys(),0);for(let s=1;s<=i;s+=1)t[s-1]=e.get(s)||{clips:[]};return{timeline:{background:this.backgroundColor,tracks:t,fonts:this.edit?.timeline.fonts||[]},output:this.edit?.output||{size:this.size,format:"mp4"}}}addClip(t,e){const i=new ls(t,e);this.executeCommand(i)}getClip(t,e){const i=this.clips.filter(s=>s.layer===t+1);return e<0||e>=i.length?null:i[e].clipConfiguration}deleteClip(t,e){const i=new us(t,e);this.executeCommand(i)}addTrack(t,e){const i=new hs(t);this.executeCommand(i),e?.clips?.forEach(s=>this.addClip(t,s))}getTrack(t){const e=this.clips.filter(i=>i.layer===t+1);return e.length===0?null:{clips:e.map(i=>i.clipConfiguration)}}deleteTrack(t){const e=new ds(t);this.executeCommand(e)}getTotalDuration(){return this.totalDuration}undo(){if(this.commandIndex>=0){const t=this.commandHistory[this.commandIndex];if(t.undo){const e=this.createCommandContext();t.undo(e),this.commandIndex-=1,this.events.emit("edit:undo",{command:t.name})}}}redo(){if(this.commandIndex<this.commandHistory.length-1){this.commandIndex+=1;const t=this.commandHistory[this.commandIndex],e=this.createCommandContext();t.execute(e),this.events.emit("edit:redo",{command:t.name})}}getSelectedClip(){return this.selectedClip}setSelectedClip(t){this.selectedClip=t;const e=t.layer-1,s=this.clips.filter(r=>r.layer===t.layer).indexOf(t),n={clip:t.clipConfiguration,trackIndex:e,clipIndex:s};this.events.emit("clip:selected",n)}setUpdatedClip(t,e=null,i=null){const s=new fs(t,e,i);this.executeCommand(s)}updateTextContent(t,e,i){const s=new ps(t,e,i);this.executeCommand(s)}executeCommand(t){const e=this.createCommandContext(),i=t.execute(e);return this.commandHistory=this.commandHistory.slice(0,this.commandIndex+1),this.commandHistory.push(t),this.commandIndex+=1,i}createCommandContext(){return{getClips:()=>[...this.clips],getTracks:()=>this.tracks,getContainer:()=>this.getContainer(),addPlayer:(t,e)=>this.addPlayer(t,e),createPlayerFromAssetType:t=>this.createPlayerFromAssetType(t),queueDisposeClip:t=>this.queueDisposeClip(t),disposeClips:()=>this.disposeClips(),undeleteClip:(t,e)=>{this.clips.push(e),this.updateTotalDuration()},setUpdatedClip:t=>{this.updatedClip=t},restoreClipConfiguration:(t,e)=>{Object.assign(t.clipConfiguration,structuredClone(e)),t.reconfigureAfterRestore(),t.draw()},updateDuration:()=>this.updateTotalDuration(),emitEvent:(t,e)=>this.events.emit(t,e)}}queueDisposeClip(t){this.clipsToDispose.push(t)}disposeClips(){if(this.clipsToDispose.length!==0){for(const t of this.clipsToDispose)this.disposeClip(t);this.clips=this.clips.filter(t=>!this.clipsToDispose.includes(t)),this.clipsToDispose=[],this.updateTotalDuration()}}disposeClip(t){try{if(this.getContainer().children.includes(t.getContainer())){const e=this.getContainer().getChildIndex(t.getContainer());this.getContainer().removeChildAt(e)}else for(const e of this.getContainer().children)if(e instanceof y.Container&&e.label?.toString().startsWith("shotstack-track-")&&e.children.includes(t.getContainer())){e.removeChild(t.getContainer());break}}catch{console.warn("Attempting to unmount an unmounted clip.")}this.unloadClipAssets(t),t.dispose()}unloadClipAssets(t){const{asset:e}=t.clipConfiguration;if(e&&"src"in e&&typeof e.src=="string")try{y.Assets.unload(e.src)}catch(i){console.warn(`Failed to unload asset: ${e.src}`,i)}}clearClips(){for(const t of this.clips)this.disposeClip(t);this.clips=[],this.clipsToDispose=[],this.updateTotalDuration()}updateTotalDuration(){let t=0;for(const e of this.tracks)for(const i of e)t=Math.max(t,i.getEnd());this.totalDuration=t}createPlayerFromAssetType(t){if(!t.asset?.type)throw new Error("Invalid clip configuration: missing asset type");let e;switch(t.asset.type){case"text":{e=new ci(this,t);break}case"shape":{e=new oi(this,t);break}case"html":{e=new ai(this,t);break}case"image":{e=new ri(this,t);break}case"video":{e=new li(this,t);break}case"audio":{e=new Gt(this,t);break}case"luma":{e=new ge(this,t);break}default:throw new Error(`Unsupported clip type: ${t.asset.type}`)}return e}async addPlayer(t,e){for(;this.tracks.length<=t;)this.tracks.push([]);this.tracks[t].push(e),this.clips.push(e);const i=1e5-(t+1)*he.ZIndexPadding,s=`shotstack-track-${i}`;let n=this.getContainer().getChildByLabel(s,!1);n||(n=new y.Container({label:s,zIndex:i}),this.getContainer().addChild(n)),n.addChild(e.getContainer());const r=e instanceof ge;await e.load(),r&&n.setMask({mask:e.getMask(),inverse:!0}),this.updateTotalDuration()}}class It extends Yt{static Width=250;static Height=100;fps;playbackTime;playbackDuration;isPlaying;background;text;constructor(){super(),this.background=null,this.text=null,this.fps=0,this.playbackTime=0,this.playbackDuration=0,this.isPlaying=!1}async load(){const t=new y.Graphics;t.fillStyle={color:"#424242",alpha:.5},t.rect(0,0,It.Width,It.Height),t.fill(),this.getContainer().addChild(t),this.background=t;const e=new y.Text;e.text="",e.style={fontFamily:"monospace",fontSize:14,fill:"#ffffff",wordWrap:!0,wordWrapWidth:It.Width},this.getContainer().addChild(e),this.text=e}update(t,e){if(!this.text)return;const i=this.getMemoryInfo(),s=[`FPS: ${this.fps}`,`Playback: ${(this.playbackTime/1e3).toFixed(2)}/${(this.playbackDuration/1e3).toFixed(2)}`,`Playing: ${this.isPlaying}`,`Total Heap Size: ${i.totalHeapSize?`${this.bytesToMegabytes(i.totalHeapSize)}MB`:"N/A"}`,`Used Heap Size: ${i.usedHeapSize?`${this.bytesToMegabytes(i.usedHeapSize)}MB`:"N/A"}`,`Heap Size Limit: ${i.heapSizeLimit?`${this.bytesToMegabytes(i.heapSizeLimit)}MB`:"N/A"}`];this.text.text=s.join(`
185
- `)}draw(){}dispose(){this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null}getMemoryInfo(){const t={};return"memory"in performance&&(t.totalHeapSize=performance.memory.totalJSHeapSize,t.usedHeapSize=performance.memory.usedJSHeapSize,t.heapSizeLimit=performance.memory.jsHeapSizeLimit),t}bytesToMegabytes(t){return Math.round(t/1024/1024)}}class ct{static CanvasSelector="[data-shotstack-studio]";static extensionsRegistered=!1;size;application;edit;inspector;container;background;minZoom=.1;maxZoom=4;currentZoom=.8;constructor(t,e){this.size=t,this.application=new y.Application,this.edit=e,this.inspector=new It}async load(){const t=document.querySelector(ct.CanvasSelector);if(!t)throw new Error(`Shotstack canvas root element '${ct.CanvasSelector}' not found.`);this.registerExtensions(),this.container=new y.Container,this.background=new y.Graphics,this.background.fillStyle={color:"#424242"},this.background.rect(0,0,this.size.width,this.size.height),this.background.fill(),await this.configureApplication(),this.configureStage(),this.setupTouchHandling(t),this.edit.getContainer().scale=this.currentZoom,t.appendChild(this.application.canvas)}setupTouchHandling(t){const e=this.edit.getContainer();t.addEventListener("wheel",i=>{if(i.preventDefault(),i.stopPropagation(),i.ctrlKey){const s=Math.exp(-i.deltaY/100),n=this.currentZoom*s,r=this.currentZoom;this.currentZoom=Math.min(Math.max(n,this.minZoom),this.maxZoom);const o={x:this.application.canvas.width/2,y:this.application.canvas.height/2},h={x:e.position.x-o.x,y:e.position.y-o.y},c=this.currentZoom/r;e.position.x=o.x+h.x*c,e.position.y=o.y+h.y*c,e.scale.x=this.currentZoom,e.scale.y=this.currentZoom}},{passive:!1,capture:!0})}centerEdit(){if(!this.edit)return;const t=this.edit.getContainer();t.position={x:this.application.canvas.width/2-this.edit.size.width*this.currentZoom/2,y:this.application.canvas.height/2-this.edit.size.height*this.currentZoom/2}}zoomToFit(){if(!this.edit)return;const t=this.application.canvas.width/this.edit.size.width,e=this.application.canvas.height/this.edit.size.height,i=Math.min(t,e);this.currentZoom=Math.min(Math.max(i,this.minZoom),this.maxZoom);const s=this.edit.getContainer();s.scale.x=this.currentZoom,s.scale.y=this.currentZoom,this.centerEdit()}setZoom(t){this.currentZoom=Math.min(Math.max(t,this.minZoom),this.maxZoom);const e=this.edit.getContainer();e.scale.x=this.currentZoom,e.scale.y=this.currentZoom}registerExtensions(){ct.extensionsRegistered||(y.extensions.add(new Ot),y.extensions.add(new $t),ct.extensionsRegistered=!0)}async configureApplication(){const t={background:"#000000",width:this.size.width,height:this.size.height,antialias:!0};await this.application.init(t),this.application.ticker.add(this.onTick.bind(this)),this.application.ticker.minFPS=60,this.application.ticker.maxFPS=60}onTick(t){this.edit.update(t.deltaTime,t.deltaMS),this.edit.draw(),this.inspector.fps=Math.ceil(t.FPS),this.inspector.playbackTime=this.edit.playbackTime,this.inspector.playbackDuration=this.edit.totalDuration,this.inspector.isPlaying=this.edit.isPlaying,this.inspector.update(t.deltaTime,t.deltaMS),this.inspector.draw()}configureStage(){if(!this.container||!this.background)throw new Error("Shotstack canvas container not set up.");this.container.addChild(this.background),this.container.addChild(this.edit.getContainer()),this.container.addChild(this.inspector.getContainer()),this.application.stage.addChild(this.container),this.application.stage.eventMode="static",this.application.stage.hitArea=new y.Rectangle(0,0,this.size.width,this.size.height),this.application.stage.on("click",this.onClick.bind(this)),this.edit.getContainer().position={x:this.application.canvas.width/2-this.edit.size.width*this.currentZoom/2,y:this.application.canvas.height/2-this.edit.size.height*this.currentZoom/2}}onClick(){this.edit.pause()}dispose(){const t=document.querySelector(ct.CanvasSelector);t&&t.contains(this.application.canvas)&&t.removeChild(this.application.canvas),this.application.ticker.remove(this.onTick,this),this.application.stage.off("click",this.onClick,this),this.background?.destroy(),this.container?.destroy(),this.inspector.dispose(),this.application.destroy(!0,{children:!0,texture:!0})}}class ws{edit;seekDistance=50;seekDistanceLarge=500;frameTime=16.67;constructor(t){this.edit=t}async load(){document.addEventListener("keydown",this.handleKeyDown),document.addEventListener("keyup",this.handleKeyUp)}dispose(){document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("keyup",this.handleKeyUp)}handleKeyDown=t=>{if(!(t.target instanceof HTMLInputElement||t.target instanceof HTMLTextAreaElement))switch(t.code){case"Space":{this.edit.isPlaying?this.edit.pause():this.edit.play();break}case"ArrowLeft":{if(t.metaKey)this.edit.seek(0);else{const e=t.shiftKey?this.seekDistanceLarge:this.seekDistance;this.edit.seek(this.edit.playbackTime-e)}break}case"ArrowRight":{if(t.metaKey)this.edit.seek(this.edit.getTotalDuration());else{const e=t.shiftKey?this.seekDistanceLarge:this.seekDistance;this.edit.seek(this.edit.playbackTime+e)}break}case"KeyJ":{this.edit.stop();break}case"KeyK":{this.edit.pause();break}case"KeyL":{this.edit.play();break}case"Comma":{this.edit.seek(this.edit.playbackTime-this.frameTime);break}case"Period":{this.edit.seek(this.edit.playbackTime+this.frameTime);break}case"KeyZ":{(t.metaKey||t.ctrlKey)&&(t.preventDefault(),t.shiftKey?this.edit.redo():this.edit.undo());break}}};handleKeyUp=t=>{if(!(t.target instanceof HTMLInputElement||t.target instanceof HTMLTextAreaElement))switch(t.code){case"KeyI":console.log(this.edit.getEdit());break}}}class bs{ffmpeg;isReady=!1;edit;application;constructor(t,e){this.edit=t,this.application=e.application,this.ffmpeg=new $e.FFmpeg}async init(){if(!this.isReady)try{await this.ffmpeg.load(),this.isReady=!0}catch(t){throw console.error("FFmpeg initialization failed:",t),t}}async export(t="shotstack-export.mp4",e=30){this.isReady||await this.init();const i=this.edit.isPlaying,s=this.edit.playbackTime;this.edit.pause();const n=this.edit.getContainer(),r=n.visible,{x:o,y:h}=n.position,{x:c,y:l}=n.scale;n.visible=!1;const g=this.createProgressOverlay();try{const p=this.edit.getSize?this.edit.getSize():{width:1920,height:1080},w=Math.ceil(this.edit.totalDuration*e/1e3),I=1e3/e,_=100,D=50,N=50,yt=O=>Math.round(O/w*D);this.updateProgressOverlay(g,0,_);const G=document.createElement("canvas");G.width=p.width,G.height=p.height;const vt=G.getContext("2d");if(!vt)throw new Error("Could not get 2D context for canvas");const ue=this.findAudioPlayers();this.updateProgressOverlay(g,2,_);const q=[];if(ue.length>0){this.updateProgressOverlay(g,3,_);for(let O=0;O<ue.length;O+=1){const B=await this.processAudioTrack(ue[O],O);B&&q.push(B),this.updateProgressOverlay(g,4+O,_)}}n.position.x=0,n.position.y=0,n.scale.x=1,n.scale.y=1;for(let O=0;O<w;O+=1){this.edit.seek(O*I),this.edit.tick?this.edit.tick(0,0):(this.edit.update?.(0,0),this.edit.draw?.());try{const{extract:B}=this.application.renderer,F=B.canvas(n);vt.clearRect(0,0,G.width,G.height),vt.drawImage(F,0,0);const Q=G.toDataURL("image/png"),Wt=await(await fetch(Q)).arrayBuffer(),Ts=`frame_${O.toString().padStart(6,"0")}.png`;await this.ffmpeg.writeFile(Ts,new Uint8Array(Wt))}catch(B){console.error(`Error capturing frame ${O}:`,B)}this.updateProgressOverlay(g,yt(O+1),_)}this.updateProgressOverlay(g,D,_);let it=["-framerate",e.toString(),"-i","frame_%06d.png"];for(const O of q)it=it.concat(["-i",O.filename]);if(it=it.concat(["-c:v","libx264","-pix_fmt","yuv420p","-crf","23"]),q.length>0){let O="";for(let F=0;F<q.length;F+=1){const Q=q[F],Ze=F+1,Wt=Math.max(0,Q.start);O+=`[${Ze}:a]aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo,apad,afade=t=in:st=0:d=0.05,atrim=start=0:end=${Q.duration/1e3+.1},adelay=${Wt}|${Wt},volume=${Q.volume}[a${F}];`}const B=q.length>1?`${q.map((F,Q)=>`[a${Q}]`).join("")}amix=inputs=${q.length}:duration=longest:dropout_transition=0.5:normalize=0[aout]`:"[a0]aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo[aout]";O+=B,it=it.concat(["-filter_complex",O,"-map","0:v","-map","[aout]","-c:a","aac","-b:a","192k","-shortest"])}const de="output.mp4";it.push(de);let Be=0;const Ve=({message:O})=>{const B=O.includes("frame=")&&O.includes("fps=")?O.match(/frame=\s*(\d+)/):null;if(B?.[1]){const F=parseInt(B[1],10);if(!Number.isNaN(F)&&F>Be&&(Be=F,F<=w)){const Q=Math.round(F/w*N);this.updateProgressOverlay(g,D+Q,_)}}};this.ffmpeg.on("log",Ve),await this.ffmpeg.exec(it),this.ffmpeg.off("log",Ve),this.updateProgressOverlay(g,D+N,_);const fe=await this.ffmpeg.readFile(de),_s=fe instanceof Uint8Array?fe:new TextEncoder().encode(fe.toString()),Ss=new Blob([_s],{type:"video/mp4"}),Ke=URL.createObjectURL(Ss),pe=document.createElement("a");pe.href=Ke,pe.download=t,pe.click(),URL.revokeObjectURL(Ke);for(let O=0;O<w;O+=1)try{await this.ffmpeg.deleteFile(`frame_${O.toString().padStart(6,"0")}.png`)}catch{}for(const O of q)try{await this.ffmpeg.deleteFile(O.filename)}catch{}await this.ffmpeg.deleteFile(de),this.updateProgressOverlay(g,_,_)}catch(p){throw console.error("Error during export:",p),p}finally{this.removeProgressOverlay(g),n.position.x=o,n.position.y=h,n.scale.x=c,n.scale.y=l,n.visible=r,this.edit.seek(s),i&&this.edit.play()}}findAudioPlayers(){const t=[],e=this.edit.tracks;if(e&&Array.isArray(e))for(let i=0;i<e.length;i+=1){const s=e[i];if(Array.isArray(s))for(let n=0;n<s.length;n+=1){const r=s[n];(r instanceof Gt||r.constructor.name==="AudioPlayer"||r.clipConfiguration?.asset?.type==="audio")&&(t.includes(r)||t.push(r))}}return this.searchContainerForPlayers(this.edit.getContainer(),t),t}searchContainerForPlayers(t,e){if(t){for(const i of t.children)if(i instanceof y.Container){if(i.label?.startsWith("shotstack-track-")){for(const n of i.children)if(n instanceof y.Container){const r=n,o=["player","clip","audioPlayer","entity"];for(const h of o){const c=r[h];c instanceof Gt&&!e.includes(c)&&e.push(c)}}}this.searchContainerForPlayers(i,e)}}}async processAudioTrack(t,e){try{const{clipConfiguration:i}=t;if(!i?.asset)return null;const s=i.asset;if(!s.src)return console.warn("Audio asset does not have a valid src property"),null;const n=await fetch(s.src);if(!n.ok)return console.error(`Failed to fetch audio file: ${s.src}`),null;const r=await n.arrayBuffer(),o=`audio_${e}.mp3`;return await this.ffmpeg.writeFile(o,new Uint8Array(r)),{filename:o,start:t.getStart(),duration:t.getLength(),volume:t.getVolume()}}catch(i){return console.error(`Error processing audio track ${e}:`,i),null}}createProgressOverlay(){const t=document.createElement("div");t.className="video-export-progress-overlay",Object.assign(t.style,{position:"fixed",top:"0",left:"0",width:"100%",height:"100%",backgroundColor:"rgba(0, 0, 0, 0.5)",zIndex:"9999",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",color:"white",fontFamily:"Arial, sans-serif"});const e=document.createElement("div");Object.assign(e.style,{backgroundColor:"#222",borderRadius:"8px",padding:"20px",boxShadow:"0 4px 8px rgba(0, 0, 0, 0.2)",width:"300px",textAlign:"center"}),t.appendChild(e);const i=document.createElement("h3");i.innerText="Exporting Video",i.style.margin="0 0 15px 0",i.style.fontWeight="normal",e.appendChild(i);const s=document.createElement("div");Object.assign(s.style,{width:"100%",height:"6px",backgroundColor:"#444",borderRadius:"3px",overflow:"hidden",marginBottom:"10px"}),e.appendChild(s);const n=document.createElement("div");n.className="video-export-progress-bar",Object.assign(n.style,{width:"0%",height:"100%",backgroundColor:"#3498db",transition:"width 0.3s"}),s.appendChild(n);const r=document.createElement("div");return r.className="video-export-percent",r.innerText="0%",r.style.fontSize="12px",e.appendChild(r),document.body.appendChild(t),t}updateProgressOverlay(t,e,i){if(!t)return;const s=Math.round(e/i*100),n=t.querySelector(".video-export-progress-bar"),r=t.querySelector(".video-export-percent");n&&(n.style.width=`${s}%`),r&&(r.innerText=`${s}%`)}removeProgressOverlay(t){t?.parentNode?.removeChild(t)}}M.Canvas=ct,M.Controls=ws,M.Edit=he,M.VideoExporter=bs,Object.defineProperty(M,Symbol.toStringTag,{value:"Module"})});
182
+ const DOUBLE_PI: f32 = 3.14159265358979323846264 * 2.;`,Ti=Object.defineProperty,wi=(r,t,e)=>t in r?Ti(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,ht=(r,t,e)=>(wi(r,typeof t!="symbol"?t+"":t,e),e);const Ft=class mt extends Z.Filter{constructor(...t){let e=t[0]??{};typeof e=="number"&&(Z.deprecation("6.0.0","OutlineFilter constructor params are now options object. See params: { thickness, color, quality, alpha, knockout }"),e={thickness:e},t[1]!==void 0&&(e.color=t[1]),t[2]!==void 0&&(e.quality=t[2]),t[3]!==void 0&&(e.alpha=t[3]),t[4]!==void 0&&(e.knockout=t[4])),e={...mt.DEFAULT_OPTIONS,...e};const i=e.quality??.1,s=Z.GpuProgram.from({vertex:{source:Ci,entryPoint:"mainVertex"},fragment:{source:ki,entryPoint:"mainFragment"}}),n=Z.GlProgram.from({vertex:vi,fragment:xi.replace(/\$\{ANGLE_STEP\}/,mt.getAngleStep(i).toFixed(7)),name:"outline-filter"});super({gpuProgram:s,glProgram:n,resources:{outlineUniforms:{uThickness:{value:new Float32Array(2),type:"vec2<f32>"},uColor:{value:new Float32Array(3),type:"vec3<f32>"},uAlpha:{value:e.alpha,type:"f32"},uAngleStep:{value:0,type:"f32"},uKnockout:{value:e.knockout?1:0,type:"f32"}}}}),ht(this,"uniforms"),ht(this,"_thickness"),ht(this,"_quality"),ht(this,"_color"),this.uniforms=this.resources.outlineUniforms.uniforms,this.uniforms.uAngleStep=mt.getAngleStep(i),this._color=new Z.Color,this.color=e.color??0,Object.assign(this,e)}apply(t,e,i,s){this.uniforms.uThickness[0]=this.thickness/e.source.width,this.uniforms.uThickness[1]=this.thickness/e.source.height,t.applyFilter(this,e,i,s)}static getAngleStep(t){return parseFloat((Math.PI*2/Math.max(t*mt.MAX_SAMPLES,mt.MIN_SAMPLES)).toFixed(7))}get thickness(){return this._thickness}set thickness(t){this._thickness=this.padding=t}get color(){return this._color.value}set color(t){this._color.setValue(t);const[e,i,s]=this._color.toArray();this.uniforms.uColor[0]=e,this.uniforms.uColor[1]=i,this.uniforms.uColor[2]=s}get alpha(){return this.uniforms.uAlpha}set alpha(t){this.uniforms.uAlpha=t}get quality(){return this._quality}set quality(t){this._quality=t,this.uniforms.uAngleStep=mt.getAngleStep(t)}get knockout(){return this.uniforms.uKnockout===1}set knockout(t){this.uniforms.uKnockout=t?1:0}};ht(Ft,"DEFAULT_OPTIONS",{thickness:1,color:0,alpha:1,quality:.1,knockout:!1}),ht(Ft,"MIN_SAMPLES",1),ht(Ft,"MAX_SAMPLES",100);let le=Ft;class bi extends D{background;text;constructor(t,e){super(t,e),this.background=null,this.text=null}async load(){await super.load();const t=this.clipConfiguration.asset,e=await this.parseDocument();if(!e)return;const i=new d.Graphics;e.background.color&&(i.fillStyle={color:e.background.color,alpha:e.background.opacity??1},i.rect(0,0,t.width??this.edit.size.width,t.height??this.edit.size.height),i.fill());const s=new d.Text;s.text=e.text;const{horizontal:n,vertical:a}=e.alignment;s.style={fontFamily:e.font?.family??"Open Sans",fontSize:e.font?.size??32,fill:e.font?.color??"#ffffff",fontWeight:(e.font?.weight??"400").toString(),wordWrap:!0,wordWrapWidth:t.width??this.edit.size.width,lineHeight:(e.font?.lineHeight??1)*(e.font?.size??32),align:n};let o=(t.width??this.edit.size.width)/2-s.width/2,l=(t.height??this.edit.size.height)/2-s.height/2;if(n==="left"&&(o=0),n==="right"&&(o=(t.width??this.edit.size.width)-s.width),a==="top"&&(l=0),a==="bottom"&&(l=(t.height??this.edit.size.height)-s.height),s.position={x:o,y:l},e.stroke.color&&e.stroke.width){const c=new le({thickness:e.stroke.width,color:e.stroke.color});s.filters=[c]}this.background=i,this.text=s,this.contentContainer.addChild(i),this.contentContainer.addChild(s),this.configureKeyframes()}update(t,e){super.update(t,e)}draw(){super.draw()}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=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}async parseDocument(){const t=this.clipConfiguration.asset,{html:e,css:i,position:s}=t;if(!e.includes('data-html-type="text"'))return console.warn("Unsupported html format."),null;const a=new DOMParser().parseFromString(e,"text/html").body.textContent??"",l=(await new CSSStyleSheet().replace(i)).cssRules[0],c={text:a,font:{},alignment:{},background:{},stroke:{}};if(l?.constructor.name!=="CSSStyleRule"||!("style"in l))return console.warn("Unsupported css format."),c;const h=l.style,p=this.parseAlignment(s??"center");c.font={color:h.color.length?h.color:void 0,family:h.fontFamily.length?h.fontFamily:void 0,size:h.fontSize.length?parseInt(h.fontSize,10):void 0,weight:h.fontWeight.length?parseInt(h.fontWeight,10):void 0,lineHeight:h.lineHeight.length?parseInt(h.lineHeight,10):void 0},c.alignment=p;let f="";return h.background.length&&(f=h.background),h.backgroundColor.length&&(f=h.backgroundColor),c.background={color:f.length?f:void 0,opacity:h.opacity.length?parseInt(h.opacity,10):void 0},c.stroke={width:h.strokeWidth.length?parseInt(h.strokeWidth,10):void 0,color:h.stroke.length?h.stroke:void 0},c}parseAlignment(t){switch(t){case"topLeft":return{horizontal:"left",vertical:"top"};case"top":return{horizontal:"center",vertical:"top"};case"topRight":return{horizontal:"right",vertical:"top"};case"left":return{horizontal:"left",vertical:"center"};case"right":return{horizontal:"right",vertical:"center"};case"bottomLeft":return{horizontal:"left",vertical:"bottom"};case"bottom":return{horizontal:"center",vertical:"bottom"};case"bottomRight":return{horizontal:"right",vertical:"bottom"};case"center":default:return{horizontal:"center",vertical:"center"}}}}class Si extends D{texture;sprite;constructor(t,e){super(t,e),this.texture=null,this.sprite=null}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src,i={src:e,crossovern:"anonymous",data:{}},s=await this.edit.assetLoader.load(e,i);if(!(s?.source instanceof d.ImageSource))throw new Error(`Invalid image source '${t.src}'.`);this.texture=this.createCroppedTexture(s),this.sprite=new d.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.configureKeyframes()}update(t,e){super.update(t,e)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null}getSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}createCroppedTexture(t){const e=this.clipConfiguration.asset;if(!e.crop)return t;const i=t.width,s=t.height,n=Math.floor((e.crop?.left??0)*i),a=Math.floor((e.crop?.right??0)*i),o=Math.floor((e.crop?.top??0)*s),l=Math.floor((e.crop?.bottom??0)*s),c=n,h=o,p=i-n-a,f=s-o-l,v=new d.Rectangle(c,h,p,f);return new d.Texture({source:t.source,frame:v})}}class _e extends D{texture;sprite;isPlaying;constructor(t,e){super(t,e),this.texture=null,this.sprite=null,this.isPlaying=!1}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src,i={src:e,data:{autoPlay:!1,muted:!0}},s=await this.edit.assetLoader.load(e,i);if(!(s?.source instanceof d.ImageSource||s?.source instanceof d.VideoSource))throw new Error(`Invalid luma source '${t.src}'.`);this.texture=s,this.sprite=new d.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.configureKeyframes()}update(t,e){if(super.update(t,e),!this.texture||!(this.texture.source instanceof d.VideoSource))return;const i=this.getPlaybackTime(),s=this.edit.isPlaying&&this.isActive();s&&(this.isPlaying||(this.isPlaying=!0,this.texture.source.resource.currentTime=i/1e3,this.texture.source.resource.play().catch(console.error)),this.texture.source.resource.volume!==this.getVolume()&&(this.texture.source.resource.volume=this.getVolume()),Math.abs(this.texture.source.resource.currentTime*1e3-i)>100&&(this.texture.source.resource.currentTime=i/1e3)),!s&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause()),!this.edit.isPlaying&&this.isActive()&&(this.texture.source.resource.currentTime=i/1e3)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null}getSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}getVolume(){return 0}getMask(){return this.sprite}}class Ii extends D{shape;shapeBackground;constructor(t,e){super(t,e),this.shape=null,this.shapeBackground=null}async load(){await super.load();const t=this.clipConfiguration.asset,e=new d.Graphics,i=t.width??this.edit.size.width,s=t.height??this.edit.size.height;e.fillStyle={color:"transparent"},e.rect(0,0,i,s),e.fill();const n=new d.Graphics;switch(t.shape){case"rectangle":{const a=t.rectangle,o=i/2-a.width/2,l=s/2-a.height/2;n.rect(o,l,a.width,a.height);break}case"circle":{const a=t.circle,o=i/2,l=s/2;n.circle(o,l,a.radius);break}case"line":{const a=t.line,o=i/2-a.length/2,l=s/2-a.thickness/2;n.rect(o,l,a.length,a.thickness);break}default:console.warn("Unsupported shape asset type.");break}if(n.fillStyle={color:t.fill?.color??"#ffffff",alpha:t.fill?.opacity??1},n.fill(),t.stroke){const a=new le({thickness:t.stroke.width,color:t.stroke.color});n.filters=[a]}this.shapeBackground=e,this.shape=n,this.contentContainer.addChild(e),e.addChild(n),this.configureKeyframes()}update(t,e){super.update(t,e)}draw(){super.draw()}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}}class _t{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,e,i,s){this.parent=t,this.textElement=e,this.clipConfig=i,this.width=s?.width??_t.DEFAULT_CURSOR_WIDTH_PX,this.color=s?.color??_t.DEFAULT_CURSOR_COLOR,this.blinkIntervalMs=s?.blinkInterval??_t.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,e){if(!this.cursor){console.warn("TextCursor: Cannot set position, cursor not initialized");return}this.pixelX=t,this.pixelY=e,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 d.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,e=this.textElement.style,i=t.substring(0,this.textPosition),s=i.match(/\n/g);this.currentLine=s?s.length:0;const n=t.split(`
183
+ `),a=this.currentLine<n.length?n[this.currentLine]:"",o=i.lastIndexOf(`
184
+ `),l=o===-1?this.textPosition:this.textPosition-o-1,c=a.substring(0,l);let h;c.length>0&&c.endsWith(" ")?h=this.measureText(`${c}x`,e)-this.measureText("x",e):h=this.measureText(c,e);const p=e.lineHeight;this.pixelY=this.currentLine*p;const v=this.clipConfig.asset.alignment?.horizontal??"center";let I=h;if(v!=="left"){const b=this.measureText(a,e),O=this.textElement.width;let N=0;v==="center"?N=(O-b)/2:v==="right"&&(N=O-b),I=N+h}this.pixelX=I}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,e){const i=new d.Text(t,e),{width:s}=i;return i.destroy(),s}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 Nt{static DEFAULT_FOCUS_DELAY_MS=50;hiddenInput=null;isFocused=!1;focusRetryCount=0;maxFocusRetries=3;focusDelay=Nt.DEFAULT_FOCUS_DELAY_MS;eventHandlers={};abortController=null;textChangeCallback=null;lastSyncedText="";isComposing=!1;setupInput(t,e){this.focusDelay=e?.focusDelay??Nt.DEFAULT_FOCUS_DELAY_MS,this.createHiddenTextarea(),this.hiddenInput&&(this.hiddenInput.value=t,this.lastSyncedText=t),this.setupEventListeners(),e?.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,e){if(!this.hiddenInput)return;const i=this.hiddenInput.value.length,s=Math.max(0,Math.min(t,i)),n=Math.max(s,Math.min(e,i));this.hiddenInput.setSelectionRange(s,n)}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:"999",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 e=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.lastSyncedText=e,this.textChangeCallback?.(e,i)};handleKeyDown=t=>{if(document.activeElement!==this.hiddenInput)return;let e=!1;if((t.ctrlKey||t.metaKey)&&(e=this.handleKeyboardShortcuts(t),e)){t.preventDefault();return}if(t.key==="Tab"){const i=t.shiftKey?"backward":"forward";this.eventHandlers.onTabNavigation?.(i),t.preventDefault();return}switch(t.key){case"Escape":this.eventHandlers.onEscape?.(t),e=!0;break;case"Enter":e=!1;break;case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":setTimeout(()=>{if(this.hiddenInput){const i=this.hiddenInput.value,s=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(i,s)}},0),e=!1;break;case"Backspace":case"Delete":e=!1;break;default:e=this.eventHandlers.onCustomKey?.(t.key,t)||!1;break}e&&t.preventDefault()};handleKeyboardShortcuts(t){const{key:e}=t;switch(e.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 e=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(e,i)}};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 W{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,e,i){this.parent=t,this.targetText=e,this.clipConfig=i,this.parent.getContainer().eventMode="static",this.parent.getContainer().on("click",this.checkForDoubleClick)}dispose(){this.parent.getContainer().off("click",this.checkForDoubleClick),this.stopEditing(),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null)}startEditing(){if(this.isEditing||!this.targetText)return;const t=structuredClone(this.clipConfig);this.targetText.visible=!1,this.createEditingEnvironment(),this.setupOutsideClickHandler(t),this.isEditing=!0}stopEditing(t=!1,e){if(!this.isEditing)return;let i="";this.editableText&&(i=this.editableText.text),this.editingContainer&&(this.parent.getContainer().removeChild(this.editingContainer),this.editingContainer.destroy(),this.editingContainer=null),this.editableText=null,this.textCursor&&(this.textCursor.dispose(),this.textCursor=null),this.textInputHandler&&(this.textInputHandler.dispose(),this.textInputHandler=null),this.targetText.visible=!0,t&&e&&i!==""&&this.parent.updateTextContent(i,e),this.isEditing=!1}checkForDoubleClick=t=>{const e=Date.now();e-this.lastClickTime<W.DOUBLE_CLICK_THRESHOLD_MS&&this.startEditing(),this.lastClickTime=e};setupOutsideClickHandler(t){this.outsideClickHandler=e=>{const s=this.parent.getContainer().getBounds(),n=e.clientX,a=e.clientY;(n<s.x||n>s.x+s.width||a<s.y||a>s.y+s.height)&&(this.stopEditing(!0,t),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null))},setTimeout(()=>{this.outsideClickHandler&&window.addEventListener("click",this.outsideClickHandler)},W.CLICK_HANDLER_DELAY_MS)}createEditingEnvironment(){this.setupEditingContainer(),this.editingContainer&&this.editableText&&(this.textCursor=new _t(this.editingContainer,this.editableText,this.clipConfig),this.textCursor.updatePosition(this.targetText.text.length),this.textCursor.startBlinking()),this.setupTextInputHandler(),this.updateTextAlignment()}setupEditingContainer(){this.editingContainer=new d.Container,this.parent.getContainer().addChild(this.editingContainer);const t=new d.Graphics;t.fillStyle={color:0,alpha:W.EDITING_BG_ALPHA},t.rect(-5,-5,this.targetText.width+2*W.EDITING_BG_PADDING_PX,this.targetText.height+2*W.EDITING_BG_PADDING_PX),t.fill(),this.editingContainer.addChild(t),this.editableText=new d.Text(this.targetText.text,this.targetText.style),this.editableText.eventMode="static",this.editableText.cursor="text",this.editingContainer.addChild(this.editableText)}setupTextInputHandler(){this.textInputHandler=new Nt,this.textInputHandler.setTextInputHandler((t,e)=>{this.editableText&&(this.editableText.text=t,this.updateTextAlignment()),this.textCursor?.updatePosition(e)}),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(),e=this.getAlignmentSettings(),i=this.calculateHorizontalPosition({width:this.editableText.width},t,e.horizontal),s=this.calculateVerticalPosition({height:this.editableText.height},t,e.vertical);if(this.editingContainer.position.set(i,s),this.editingContainer.children.length>0){const n=this.editingContainer.getChildAt(0);n instanceof d.Graphics&&(n.clear(),n.fillStyle={color:0,alpha:W.EDITING_BG_ALPHA},n.rect(-5,-5,this.editableText.width+2*W.EDITING_BG_PADDING_PX,this.editableText.height+2*W.EDITING_BG_PADDING_PX),n.fill())}}calculateHorizontalPosition(t,e,i="center"){switch(i){case"center":return e.width/2-t.width/2;case"right":return e.width-t.width;case"left":default:return 0}}calculateVerticalPosition(t,e,i="center"){switch(i){case"center":return e.height/2-t.height/2;case"bottom":return e.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 _i extends D{background=null;text=null;textEditor=null;async load(){await super.load();const t=this.clipConfiguration.asset;if(this.background=new d.Graphics,t.background&&(this.background.fillStyle={color:t.background.color,alpha:t.background.opacity},this.background.rect(0,0,t.width??this.edit.size.width,t.height??this.edit.size.height),this.background.fill()),this.text=new d.Text(t.text,this.createTextStyle(t)),this.positionText(t),t.stroke){const e=new le({thickness:t.stroke.width,color:t.stroke.color});this.text.filters=[e]}this.contentContainer.addChild(this.background),this.contentContainer.addChild(this.text),this.configureKeyframes(),this.textEditor=new W(this,this.text,this.clipConfiguration)}update(t,e){super.update(t,e)}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:t.width??this.edit.size.width,height:t.height??this.edit.size.height}}getFitScale(){return 1}createTextStyle(t){return new d.TextStyle({fontFamily:t.font?.family??"Open Sans",fontSize:t.font?.size??32,fill:t.font?.color??"#ffffff",fontWeight:(t.font?.weight??"400").toString(),wordWrap:!0,wordWrapWidth:t.width??this.edit.size.width,lineHeight:(t.font?.lineHeight??1)*(t.font?.size??32),align:t.alignment?.horizontal??"center"})}positionText(t){if(!this.text)return;const e=t.alignment?.horizontal??"center",i=t.alignment?.vertical??"center",s=t.width??this.edit.size.width,n=t.height??this.edit.size.height;let a=s/2-this.text.width/2,o=n/2-this.text.height/2;e==="left"?a=0:e==="right"&&(a=s-this.text.width),i==="top"?o=0:i==="bottom"&&(o=n-this.text.height),this.text.position.set(a,o)}updateTextContent(t,e){this.edit.updateTextContent(this,t,e)}}class Pi extends D{texture;sprite;isPlaying;volumeKeyframeBuilder;syncTimer;constructor(t,e){super(t,e),this.texture=null,this.sprite=null,this.isPlaying=!1;const i=this.clipConfiguration.asset;this.volumeKeyframeBuilder=new R(i.volume??1,this.getLength()),this.syncTimer=0}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src;if(e.endsWith(".mov")||e.endsWith(".webm"))throw new Error(`Video source '${t.src}' is not supported. .mov and .webm files are currently not supported.`);const i={src:e,data:{autoPlay:!1,muted:!1}},s=await this.edit.assetLoader.load(e,i);if(!(s?.source instanceof d.VideoSource))throw new Error(`Invalid video source '${t.src}'.`);this.texture=this.createCroppedTexture(s),this.sprite=new d.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.configureKeyframes()}update(t,e){super.update(t,e);const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=e,!this.texture)return;const s=this.getPlaybackTime(),n=this.edit.isPlaying&&this.isActive();n&&(this.isPlaying||(this.isPlaying=!0,this.texture.source.resource.currentTime=s/1e3+i,this.texture.source.resource.play().catch(console.error)),this.texture.source.resource.volume!==this.getVolume()&&(this.texture.source.resource.volume=this.getVolume()),Math.abs((this.texture.source.resource.currentTime-i)*1e3-s)>100&&(this.texture.source.resource.currentTime=s/1e3+i)),!n&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause());const a=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&a&&(this.syncTimer=0,this.texture.source.resource.currentTime=s/1e3+i)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null}getSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}getVolume(){return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}createCroppedTexture(t){const e=this.clipConfiguration.asset;if(!e.crop)return t;const i=t.width,s=t.height,n=Math.floor((e.crop?.left??0)*i),a=Math.floor((e.crop?.right??0)*i),o=Math.floor((e.crop?.top??0)*s),l=Math.floor((e.crop?.bottom??0)*s),c=n,h=o,p=i-n-a,f=s-o-l,v=new d.Rectangle(c,h,p,f);return new d.Texture({source:t.source,frame:v})}}var S;(function(r){r.assertEqual=s=>s;function t(s){}r.assertIs=t;function e(s){throw new Error}r.assertNever=e,r.arrayToEnum=s=>{const n={};for(const a of s)n[a]=a;return n},r.getValidEnumValues=s=>{const n=r.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),a={};for(const o of n)a[o]=s[o];return r.objectValues(a)},r.objectValues=s=>r.objectKeys(s).map(function(n){return s[n]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const n=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&n.push(a);return n},r.find=(s,n)=>{for(const a of s)if(n(a))return a},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function i(s,n=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(n)}r.joinValues=i,r.jsonStringifyReplacer=(s,n)=>typeof n=="bigint"?n.toString():n})(S||(S={}));var Pe;(function(r){r.mergeShapes=(t,e)=>({...t,...e})})(Pe||(Pe={}));const m=S.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),rt=r=>{switch(typeof r){case"undefined":return m.undefined;case"string":return m.string;case"number":return isNaN(r)?m.nan:m.number;case"boolean":return m.boolean;case"function":return m.function;case"bigint":return m.bigint;case"symbol":return m.symbol;case"object":return Array.isArray(r)?m.array:r===null?m.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?m.promise:typeof Map<"u"&&r instanceof Map?m.map:typeof Set<"u"&&r instanceof Set?m.set:typeof Date<"u"&&r instanceof Date?m.date:m.object;default:return m.unknown}},u=S.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class V extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const e=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,e):this.__proto__=e,this.name="ZodError",this.issues=t}format(t){const e=t||function(n){return n.message},i={_errors:[]},s=n=>{for(const a of n.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)i._errors.push(e(a));else{let o=i,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(e(a))):o[c]=o[c]||{_errors:[]},o=o[c],l++}}};return s(this),i}static assert(t){if(!(t instanceof V))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,S.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=e=>e.message){const e={},i=[];for(const s of this.issues)s.path.length>0?(e[s.path[0]]=e[s.path[0]]||[],e[s.path[0]].push(t(s))):i.push(t(s));return{formErrors:i,fieldErrors:e}}get formErrors(){return this.flatten()}}V.create=r=>new V(r);const Pt=(r,t)=>{let e;switch(r.code){case u.invalid_type:r.received===m.undefined?e="Required":e=`Expected ${r.expected}, received ${r.received}`;break;case u.invalid_literal:e=`Invalid literal value, expected ${JSON.stringify(r.expected,S.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:e=`Unrecognized key(s) in object: ${S.joinValues(r.keys,", ")}`;break;case u.invalid_union:e="Invalid input";break;case u.invalid_union_discriminator:e=`Invalid discriminator value. Expected ${S.joinValues(r.options)}`;break;case u.invalid_enum_value:e=`Invalid enum value. Expected ${S.joinValues(r.options)}, received '${r.received}'`;break;case u.invalid_arguments:e="Invalid function arguments";break;case u.invalid_return_type:e="Invalid function return type";break;case u.invalid_date:e="Invalid date";break;case u.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(e=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(e=`${e} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?e=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?e=`Invalid input: must end with "${r.validation.endsWith}"`:S.assertNever(r.validation):r.validation!=="regex"?e=`Invalid ${r.validation}`:e="Invalid";break;case u.too_small:r.type==="array"?e=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?e=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?e=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?e=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:e="Invalid input";break;case u.too_big:r.type==="array"?e=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?e=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?e=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?e=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?e=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:e="Invalid input";break;case u.custom:e="Invalid input";break;case u.invalid_intersection_types:e="Intersection results could not be merged";break;case u.not_multiple_of:e=`Number must be a multiple of ${r.multipleOf}`;break;case u.not_finite:e="Number must be finite";break;default:e=t.defaultError,S.assertNever(r)}return{message:e}};let Ei=Pt;function ce(){return Ei}const he=r=>{const{data:t,path:e,errorMaps:i,issueData:s}=r,n=[...e,...s.path||[]],a={...s,path:n};if(s.message!==void 0)return{...s,path:n,message:s.message};let o="";const l=i.filter(c=>!!c).slice().reverse();for(const c of l)o=c(a,{data:t,defaultError:o}).message;return{...s,path:n,message:o}};function g(r,t){const e=ce(),i=he({issueData:t,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,e,e===Pt?void 0:Pt].filter(s=>!!s)});r.common.issues.push(i)}class L{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,e){const i=[];for(const s of e){if(s.status==="aborted")return k;s.status==="dirty"&&t.dirty(),i.push(s.value)}return{status:t.value,value:i}}static async mergeObjectAsync(t,e){const i=[];for(const s of e){const n=await s.key,a=await s.value;i.push({key:n,value:a})}return L.mergeObjectSync(t,i)}static mergeObjectSync(t,e){const i={};for(const s of e){const{key:n,value:a}=s;if(n.status==="aborted"||a.status==="aborted")return k;n.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),n.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(i[n.value]=a.value)}return{status:t.value,value:i}}}const k=Object.freeze({status:"aborted"}),Et=r=>({status:"dirty",value:r}),z=r=>({status:"valid",value:r}),Ee=r=>r.status==="aborted",Ae=r=>r.status==="dirty",yt=r=>r.status==="valid",Vt=r=>typeof Promise<"u"&&r instanceof Promise;function Gt(r,t,e,i){if(typeof t=="function"?r!==t||!0:!t.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(r)}function Oe(r,t,e,i,s){if(typeof t=="function"?r!==t||!0:!t.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(r,e),e}typeof SuppressedError=="function"&&SuppressedError;var y;(function(r){r.errToObj=t=>typeof t=="string"?{message:t}:t||{},r.toString=t=>typeof t=="string"?t:t?.message})(y||(y={}));var At,Ot;class K{constructor(t,e,i,s){this._cachedPath=[],this.parent=t,this.data=e,this._path=i,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const De=(r,t)=>{if(yt(t))return{success:!0,data:t.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const e=new V(r.common.issues);return this._error=e,this._error}}};function T(r){if(!r)return{};const{errorMap:t,invalid_type_error:e,required_error:i,description:s}=r;if(t&&(e||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(a,o)=>{var l,c;const{message:h}=r;return a.code==="invalid_enum_value"?{message:h??o.defaultError}:typeof o.data>"u"?{message:(l=h??i)!==null&&l!==void 0?l:o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:(c=h??e)!==null&&c!==void 0?c:o.defaultError}},description:s}}class w{get description(){return this._def.description}_getType(t){return rt(t.data)}_getOrReturnCtx(t,e){return e||{common:t.parent.common,data:t.data,parsedType:rt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new L,ctx:{common:t.parent.common,data:t.data,parsedType:rt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const e=this._parse(t);if(Vt(e))throw new Error("Synchronous parse encountered promise.");return e}_parseAsync(t){const e=this._parse(t);return Promise.resolve(e)}parse(t,e){const i=this.safeParse(t,e);if(i.success)return i.data;throw i.error}safeParse(t,e){var i;const s={common:{issues:[],async:(i=e?.async)!==null&&i!==void 0?i:!1,contextualErrorMap:e?.errorMap},path:e?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:rt(t)},n=this._parseSync({data:t,path:s.path,parent:s});return De(s,n)}"~validate"(t){var e,i;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:rt(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:s});return yt(n)?{value:n.value}:{issues:s.common.issues}}catch(n){!((i=(e=n?.message)===null||e===void 0?void 0:e.toLowerCase())===null||i===void 0)&&i.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:s}).then(n=>yt(n)?{value:n.value}:{issues:s.common.issues})}async parseAsync(t,e){const i=await this.safeParseAsync(t,e);if(i.success)return i.data;throw i.error}async safeParseAsync(t,e){const i={common:{issues:[],contextualErrorMap:e?.errorMap,async:!0},path:e?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:rt(t)},s=this._parse({data:t,path:i.path,parent:i}),n=await(Vt(s)?s:Promise.resolve(s));return De(i,n)}refine(t,e){const i=s=>typeof e=="string"||typeof e>"u"?{message:e}:typeof e=="function"?e(s):e;return this._refinement((s,n)=>{const a=t(s),o=()=>n.addIssue({code:u.custom,...i(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(t,e){return this._refinement((i,s)=>t(i)?!0:(s.addIssue(typeof e=="function"?e(i,s):e),!1))}_refinement(t){return new Q({schema:this,typeName:x.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return J.create(this,this._def)}nullable(){return ut.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $.create(this)}promise(){return Lt.create(this,this._def)}or(t){return Wt.create([this,t],this._def)}and(t){return Kt.create(this,t,this._def)}transform(t){return new Q({...T(this._def),schema:this,typeName:x.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const e=typeof t=="function"?t:()=>t;return new qt({...T(this._def),innerType:this,defaultValue:e,typeName:x.ZodDefault})}brand(){return new He({typeName:x.ZodBranded,type:this,...T(this._def)})}catch(t){const e=typeof t=="function"?t:()=>t;return new Qt({...T(this._def),innerType:this,catchValue:e,typeName:x.ZodCatch})}describe(t){const e=this.constructor;return new e({...this._def,description:t})}pipe(t){return Jt.create(this,t)}readonly(){return te.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Ai=/^c[^\s-]{8,}$/i,Oi=/^[0-9a-z]+$/,Di=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ri=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Li=/^[a-z0-9_-]{21}$/i,Mi=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Hi=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,zi=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Bi="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let de;const Fi=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ni=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Vi=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Gi=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ui=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Zi=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Re="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Wi=new RegExp(`^${Re}$`);function Le(r){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return r.precision?t=`${t}\\.\\d{${r.precision}}`:r.precision==null&&(t=`${t}(\\.\\d+)?`),t}function Ki(r){return new RegExp(`^${Le(r)}$`)}function $i(r){let t=`${Re}T${Le(r)}`;const e=[];return e.push(r.local?"Z?":"Z"),r.offset&&e.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${e.join("|")})`,new RegExp(`^${t}$`)}function Yi(r,t){return!!((t==="v4"||!t)&&Fi.test(r)||(t==="v6"||!t)&&Vi.test(r))}function Xi(r,t){if(!Mi.test(r))return!1;try{const[e]=r.split("."),i=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(e.length+(4-e.length%4)%4,"="),s=JSON.parse(atob(i));return!(typeof s!="object"||s===null||!s.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function ji(r,t){return!!((t==="v4"||!t)&&Ni.test(r)||(t==="v6"||!t)&&Gi.test(r))}class X extends w{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==m.string){const n=this._getOrReturnCtx(t);return g(n,{code:u.invalid_type,expected:m.string,received:n.parsedType}),k}const i=new L;let s;for(const n of this._def.checks)if(n.kind==="min")t.data.length<n.value&&(s=this._getOrReturnCtx(t,s),g(s,{code:u.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),i.dirty());else if(n.kind==="max")t.data.length>n.value&&(s=this._getOrReturnCtx(t,s),g(s,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),i.dirty());else if(n.kind==="length"){const a=t.data.length>n.value,o=t.data.length<n.value;(a||o)&&(s=this._getOrReturnCtx(t,s),a?g(s,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):o&&g(s,{code:u.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),i.dirty())}else if(n.kind==="email")zi.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"email",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="emoji")de||(de=new RegExp(Bi,"u")),de.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"emoji",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="uuid")Ri.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"uuid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="nanoid")Li.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"nanoid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="cuid")Ai.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"cuid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="cuid2")Oi.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"cuid2",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="ulid")Di.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"ulid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),g(s,{validation:"url",code:u.invalid_string,message:n.message}),i.dirty()}else n.kind==="regex"?(n.regex.lastIndex=0,n.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"regex",code:u.invalid_string,message:n.message}),i.dirty())):n.kind==="trim"?t.data=t.data.trim():n.kind==="includes"?t.data.includes(n.value,n.position)||(s=this._getOrReturnCtx(t,s),g(s,{code:u.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),i.dirty()):n.kind==="toLowerCase"?t.data=t.data.toLowerCase():n.kind==="toUpperCase"?t.data=t.data.toUpperCase():n.kind==="startsWith"?t.data.startsWith(n.value)||(s=this._getOrReturnCtx(t,s),g(s,{code:u.invalid_string,validation:{startsWith:n.value},message:n.message}),i.dirty()):n.kind==="endsWith"?t.data.endsWith(n.value)||(s=this._getOrReturnCtx(t,s),g(s,{code:u.invalid_string,validation:{endsWith:n.value},message:n.message}),i.dirty()):n.kind==="datetime"?$i(n).test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{code:u.invalid_string,validation:"datetime",message:n.message}),i.dirty()):n.kind==="date"?Wi.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{code:u.invalid_string,validation:"date",message:n.message}),i.dirty()):n.kind==="time"?Ki(n).test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{code:u.invalid_string,validation:"time",message:n.message}),i.dirty()):n.kind==="duration"?Hi.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"duration",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="ip"?Yi(t.data,n.version)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"ip",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="jwt"?Xi(t.data,n.alg)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"jwt",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="cidr"?ji(t.data,n.version)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"cidr",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="base64"?Ui.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"base64",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="base64url"?Zi.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"base64url",code:u.invalid_string,message:n.message}),i.dirty()):S.assertNever(n);return{status:i.value,value:t.data}}_regex(t,e,i){return this.refinement(s=>t.test(s),{validation:e,code:u.invalid_string,...y.errToObj(i)})}_addCheck(t){return new X({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...y.errToObj(t)})}url(t){return this._addCheck({kind:"url",...y.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...y.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...y.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...y.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...y.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...y.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...y.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...y.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...y.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...y.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...y.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...y.errToObj(t)})}datetime(t){var e,i;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:(e=t?.offset)!==null&&e!==void 0?e:!1,local:(i=t?.local)!==null&&i!==void 0?i:!1,...y.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...y.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...y.errToObj(t)})}regex(t,e){return this._addCheck({kind:"regex",regex:t,...y.errToObj(e)})}includes(t,e){return this._addCheck({kind:"includes",value:t,position:e?.position,...y.errToObj(e?.message)})}startsWith(t,e){return this._addCheck({kind:"startsWith",value:t,...y.errToObj(e)})}endsWith(t,e){return this._addCheck({kind:"endsWith",value:t,...y.errToObj(e)})}min(t,e){return this._addCheck({kind:"min",value:t,...y.errToObj(e)})}max(t,e){return this._addCheck({kind:"max",value:t,...y.errToObj(e)})}length(t,e){return this._addCheck({kind:"length",value:t,...y.errToObj(e)})}nonempty(t){return this.min(1,y.errToObj(t))}trim(){return new X({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new X({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new X({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t}get maxLength(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t}}X.create=r=>{var t;return new X({checks:[],typeName:x.ZodString,coerce:(t=r?.coerce)!==null&&t!==void 0?t:!1,...T(r)})};function qi(r,t){const e=(r.toString().split(".")[1]||"").length,i=(t.toString().split(".")[1]||"").length,s=e>i?e:i,n=parseInt(r.toFixed(s).replace(".","")),a=parseInt(t.toFixed(s).replace(".",""));return n%a/Math.pow(10,s)}class vt extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==m.number){const n=this._getOrReturnCtx(t);return g(n,{code:u.invalid_type,expected:m.number,received:n.parsedType}),k}let i;const s=new L;for(const n of this._def.checks)n.kind==="int"?S.isInteger(t.data)||(i=this._getOrReturnCtx(t,i),g(i,{code:u.invalid_type,expected:"integer",received:"float",message:n.message}),s.dirty()):n.kind==="min"?(n.inclusive?t.data<n.value:t.data<=n.value)&&(i=this._getOrReturnCtx(t,i),g(i,{code:u.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),s.dirty()):n.kind==="max"?(n.inclusive?t.data>n.value:t.data>=n.value)&&(i=this._getOrReturnCtx(t,i),g(i,{code:u.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),s.dirty()):n.kind==="multipleOf"?qi(t.data,n.value)!==0&&(i=this._getOrReturnCtx(t,i),g(i,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),s.dirty()):n.kind==="finite"?Number.isFinite(t.data)||(i=this._getOrReturnCtx(t,i),g(i,{code:u.not_finite,message:n.message}),s.dirty()):S.assertNever(n);return{status:s.value,value:t.data}}gte(t,e){return this.setLimit("min",t,!0,y.toString(e))}gt(t,e){return this.setLimit("min",t,!1,y.toString(e))}lte(t,e){return this.setLimit("max",t,!0,y.toString(e))}lt(t,e){return this.setLimit("max",t,!1,y.toString(e))}setLimit(t,e,i,s){return new vt({...this._def,checks:[...this._def.checks,{kind:t,value:e,inclusive:i,message:y.toString(s)}]})}_addCheck(t){return new vt({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:y.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:y.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:y.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:y.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:y.toString(t)})}multipleOf(t,e){return this._addCheck({kind:"multipleOf",value:t,message:y.toString(e)})}finite(t){return this._addCheck({kind:"finite",message:y.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:y.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:y.toString(t)})}get minValue(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t}get maxValue(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&S.isInteger(t.value))}get isFinite(){let t=null,e=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(e===null||i.value>e)&&(e=i.value):i.kind==="max"&&(t===null||i.value<t)&&(t=i.value)}return Number.isFinite(e)&&Number.isFinite(t)}}vt.create=r=>new vt({checks:[],typeName:x.ZodNumber,coerce:r?.coerce||!1,...T(r)});class Ct extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==m.bigint)return this._getInvalidInput(t);let i;const s=new L;for(const n of this._def.checks)n.kind==="min"?(n.inclusive?t.data<n.value:t.data<=n.value)&&(i=this._getOrReturnCtx(t,i),g(i,{code:u.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),s.dirty()):n.kind==="max"?(n.inclusive?t.data>n.value:t.data>=n.value)&&(i=this._getOrReturnCtx(t,i),g(i,{code:u.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),s.dirty()):n.kind==="multipleOf"?t.data%n.value!==BigInt(0)&&(i=this._getOrReturnCtx(t,i),g(i,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),s.dirty()):S.assertNever(n);return{status:s.value,value:t.data}}_getInvalidInput(t){const e=this._getOrReturnCtx(t);return g(e,{code:u.invalid_type,expected:m.bigint,received:e.parsedType}),k}gte(t,e){return this.setLimit("min",t,!0,y.toString(e))}gt(t,e){return this.setLimit("min",t,!1,y.toString(e))}lte(t,e){return this.setLimit("max",t,!0,y.toString(e))}lt(t,e){return this.setLimit("max",t,!1,y.toString(e))}setLimit(t,e,i,s){return new Ct({...this._def,checks:[...this._def.checks,{kind:t,value:e,inclusive:i,message:y.toString(s)}]})}_addCheck(t){return new Ct({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:y.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:y.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:y.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:y.toString(t)})}multipleOf(t,e){return this._addCheck({kind:"multipleOf",value:t,message:y.toString(e)})}get minValue(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t}get maxValue(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t}}Ct.create=r=>{var t;return new Ct({checks:[],typeName:x.ZodBigInt,coerce:(t=r?.coerce)!==null&&t!==void 0?t:!1,...T(r)})};class ue extends w{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==m.boolean){const i=this._getOrReturnCtx(t);return g(i,{code:u.invalid_type,expected:m.boolean,received:i.parsedType}),k}return z(t.data)}}ue.create=r=>new ue({typeName:x.ZodBoolean,coerce:r?.coerce||!1,...T(r)});class Dt extends w{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==m.date){const n=this._getOrReturnCtx(t);return g(n,{code:u.invalid_type,expected:m.date,received:n.parsedType}),k}if(isNaN(t.data.getTime())){const n=this._getOrReturnCtx(t);return g(n,{code:u.invalid_date}),k}const i=new L;let s;for(const n of this._def.checks)n.kind==="min"?t.data.getTime()<n.value&&(s=this._getOrReturnCtx(t,s),g(s,{code:u.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),i.dirty()):n.kind==="max"?t.data.getTime()>n.value&&(s=this._getOrReturnCtx(t,s),g(s,{code:u.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),i.dirty()):S.assertNever(n);return{status:i.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Dt({...this._def,checks:[...this._def.checks,t]})}min(t,e){return this._addCheck({kind:"min",value:t.getTime(),message:y.toString(e)})}max(t,e){return this._addCheck({kind:"max",value:t.getTime(),message:y.toString(e)})}get minDate(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t!=null?new Date(t):null}}Dt.create=r=>new Dt({checks:[],coerce:r?.coerce||!1,typeName:x.ZodDate,...T(r)});class pe extends w{_parse(t){if(this._getType(t)!==m.symbol){const i=this._getOrReturnCtx(t);return g(i,{code:u.invalid_type,expected:m.symbol,received:i.parsedType}),k}return z(t.data)}}pe.create=r=>new pe({typeName:x.ZodSymbol,...T(r)});class Ut extends w{_parse(t){if(this._getType(t)!==m.undefined){const i=this._getOrReturnCtx(t);return g(i,{code:u.invalid_type,expected:m.undefined,received:i.parsedType}),k}return z(t.data)}}Ut.create=r=>new Ut({typeName:x.ZodUndefined,...T(r)});class Zt extends w{_parse(t){if(this._getType(t)!==m.null){const i=this._getOrReturnCtx(t);return g(i,{code:u.invalid_type,expected:m.null,received:i.parsedType}),k}return z(t.data)}}Zt.create=r=>new Zt({typeName:x.ZodNull,...T(r)});class fe extends w{constructor(){super(...arguments),this._any=!0}_parse(t){return z(t.data)}}fe.create=r=>new fe({typeName:x.ZodAny,...T(r)});class xt extends w{constructor(){super(...arguments),this._unknown=!0}_parse(t){return z(t.data)}}xt.create=r=>new xt({typeName:x.ZodUnknown,...T(r)});class at extends w{_parse(t){const e=this._getOrReturnCtx(t);return g(e,{code:u.invalid_type,expected:m.never,received:e.parsedType}),k}}at.create=r=>new at({typeName:x.ZodNever,...T(r)});class ge extends w{_parse(t){if(this._getType(t)!==m.undefined){const i=this._getOrReturnCtx(t);return g(i,{code:u.invalid_type,expected:m.void,received:i.parsedType}),k}return z(t.data)}}ge.create=r=>new ge({typeName:x.ZodVoid,...T(r)});class $ extends w{_parse(t){const{ctx:e,status:i}=this._processInputParams(t),s=this._def;if(e.parsedType!==m.array)return g(e,{code:u.invalid_type,expected:m.array,received:e.parsedType}),k;if(s.exactLength!==null){const a=e.data.length>s.exactLength.value,o=e.data.length<s.exactLength.value;(a||o)&&(g(e,{code:a?u.too_big:u.too_small,minimum:o?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty())}if(s.minLength!==null&&e.data.length<s.minLength.value&&(g(e,{code:u.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()),s.maxLength!==null&&e.data.length>s.maxLength.value&&(g(e,{code:u.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()),e.common.async)return Promise.all([...e.data].map((a,o)=>s.type._parseAsync(new K(e,a,e.path,o)))).then(a=>L.mergeArray(i,a));const n=[...e.data].map((a,o)=>s.type._parseSync(new K(e,a,e.path,o)));return L.mergeArray(i,n)}get element(){return this._def.type}min(t,e){return new $({...this._def,minLength:{value:t,message:y.toString(e)}})}max(t,e){return new $({...this._def,maxLength:{value:t,message:y.toString(e)}})}length(t,e){return new $({...this._def,exactLength:{value:t,message:y.toString(e)}})}nonempty(t){return this.min(1,t)}}$.create=(r,t)=>new $({type:r,minLength:null,maxLength:null,exactLength:null,typeName:x.ZodArray,...T(t)});function kt(r){if(r instanceof A){const t={};for(const e in r.shape){const i=r.shape[e];t[e]=J.create(kt(i))}return new A({...r._def,shape:()=>t})}else return r instanceof $?new $({...r._def,type:kt(r.element)}):r instanceof J?J.create(kt(r.unwrap())):r instanceof ut?ut.create(kt(r.unwrap())):r instanceof q?q.create(r.items.map(t=>kt(t))):r}class A extends w{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),e=S.objectKeys(t);return this._cached={shape:t,keys:e}}_parse(t){if(this._getType(t)!==m.object){const c=this._getOrReturnCtx(t);return g(c,{code:u.invalid_type,expected:m.object,received:c.parsedType}),k}const{status:i,ctx:s}=this._processInputParams(t),{shape:n,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof at&&this._def.unknownKeys==="strip"))for(const c in s.data)a.includes(c)||o.push(c);const l=[];for(const c of a){const h=n[c],p=s.data[c];l.push({key:{status:"valid",value:c},value:h._parse(new K(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof at){const c=this._def.unknownKeys;if(c==="passthrough")for(const h of o)l.push({key:{status:"valid",value:h},value:{status:"valid",value:s.data[h]}});else if(c==="strict")o.length>0&&(g(s,{code:u.unrecognized_keys,keys:o}),i.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const h of o){const p=s.data[h];l.push({key:{status:"valid",value:h},value:c._parse(new K(s,p,s.path,h)),alwaysSet:h in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const c=[];for(const h of l){const p=await h.key,f=await h.value;c.push({key:p,value:f,alwaysSet:h.alwaysSet})}return c}).then(c=>L.mergeObjectSync(i,c)):L.mergeObjectSync(i,l)}get shape(){return this._def.shape()}strict(t){return y.errToObj,new A({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(e,i)=>{var s,n,a,o;const l=(a=(n=(s=this._def).errorMap)===null||n===void 0?void 0:n.call(s,e,i).message)!==null&&a!==void 0?a:i.defaultError;return e.code==="unrecognized_keys"?{message:(o=y.errToObj(t).message)!==null&&o!==void 0?o:l}:{message:l}}}:{}})}strip(){return new A({...this._def,unknownKeys:"strip"})}passthrough(){return new A({...this._def,unknownKeys:"passthrough"})}extend(t){return new A({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new A({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:x.ZodObject})}setKey(t,e){return this.augment({[t]:e})}catchall(t){return new A({...this._def,catchall:t})}pick(t){const e={};return S.objectKeys(t).forEach(i=>{t[i]&&this.shape[i]&&(e[i]=this.shape[i])}),new A({...this._def,shape:()=>e})}omit(t){const e={};return S.objectKeys(this.shape).forEach(i=>{t[i]||(e[i]=this.shape[i])}),new A({...this._def,shape:()=>e})}deepPartial(){return kt(this)}partial(t){const e={};return S.objectKeys(this.shape).forEach(i=>{const s=this.shape[i];t&&!t[i]?e[i]=s:e[i]=s.optional()}),new A({...this._def,shape:()=>e})}required(t){const e={};return S.objectKeys(this.shape).forEach(i=>{if(t&&!t[i])e[i]=this.shape[i];else{let n=this.shape[i];for(;n instanceof J;)n=n._def.innerType;e[i]=n}}),new A({...this._def,shape:()=>e})}keyof(){return Me(S.objectKeys(this.shape))}}A.create=(r,t)=>new A({shape:()=>r,unknownKeys:"strip",catchall:at.create(),typeName:x.ZodObject,...T(t)}),A.strictCreate=(r,t)=>new A({shape:()=>r,unknownKeys:"strict",catchall:at.create(),typeName:x.ZodObject,...T(t)}),A.lazycreate=(r,t)=>new A({shape:r,unknownKeys:"strip",catchall:at.create(),typeName:x.ZodObject,...T(t)});class Wt extends w{_parse(t){const{ctx:e}=this._processInputParams(t),i=this._def.options;function s(n){for(const o of n)if(o.result.status==="valid")return o.result;for(const o of n)if(o.result.status==="dirty")return e.common.issues.push(...o.ctx.common.issues),o.result;const a=n.map(o=>new V(o.ctx.common.issues));return g(e,{code:u.invalid_union,unionErrors:a}),k}if(e.common.async)return Promise.all(i.map(async n=>{const a={...e,common:{...e.common,issues:[]},parent:null};return{result:await n._parseAsync({data:e.data,path:e.path,parent:a}),ctx:a}})).then(s);{let n;const a=[];for(const l of i){const c={...e,common:{...e.common,issues:[]},parent:null},h=l._parseSync({data:e.data,path:e.path,parent:c});if(h.status==="valid")return h;h.status==="dirty"&&!n&&(n={result:h,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(n)return e.common.issues.push(...n.ctx.common.issues),n.result;const o=a.map(l=>new V(l));return g(e,{code:u.invalid_union,unionErrors:o}),k}}get options(){return this._def.options}}Wt.create=(r,t)=>new Wt({options:r,typeName:x.ZodUnion,...T(t)});const j=r=>r instanceof Yt?j(r.schema):r instanceof Q?j(r.innerType()):r instanceof Xt?[r.value]:r instanceof dt?r.options:r instanceof jt?S.objectValues(r.enum):r instanceof qt?j(r._def.innerType):r instanceof Ut?[void 0]:r instanceof Zt?[null]:r instanceof J?[void 0,...j(r.unwrap())]:r instanceof ut?[null,...j(r.unwrap())]:r instanceof He||r instanceof te?j(r.unwrap()):r instanceof Qt?j(r._def.innerType):[];class me extends w{_parse(t){const{ctx:e}=this._processInputParams(t);if(e.parsedType!==m.object)return g(e,{code:u.invalid_type,expected:m.object,received:e.parsedType}),k;const i=this.discriminator,s=e.data[i],n=this.optionsMap.get(s);return n?e.common.async?n._parseAsync({data:e.data,path:e.path,parent:e}):n._parseSync({data:e.data,path:e.path,parent:e}):(g(e,{code:u.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),k)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,e,i){const s=new Map;for(const n of e){const a=j(n.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const o of a){if(s.has(o))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(o)}`);s.set(o,n)}}return new me({typeName:x.ZodDiscriminatedUnion,discriminator:t,options:e,optionsMap:s,...T(i)})}}function ye(r,t){const e=rt(r),i=rt(t);if(r===t)return{valid:!0,data:r};if(e===m.object&&i===m.object){const s=S.objectKeys(t),n=S.objectKeys(r).filter(o=>s.indexOf(o)!==-1),a={...r,...t};for(const o of n){const l=ye(r[o],t[o]);if(!l.valid)return{valid:!1};a[o]=l.data}return{valid:!0,data:a}}else if(e===m.array&&i===m.array){if(r.length!==t.length)return{valid:!1};const s=[];for(let n=0;n<r.length;n++){const a=r[n],o=t[n],l=ye(a,o);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return e===m.date&&i===m.date&&+r==+t?{valid:!0,data:r}:{valid:!1}}class Kt extends w{_parse(t){const{status:e,ctx:i}=this._processInputParams(t),s=(n,a)=>{if(Ee(n)||Ee(a))return k;const o=ye(n.value,a.value);return o.valid?((Ae(n)||Ae(a))&&e.dirty(),{status:e.value,value:o.data}):(g(i,{code:u.invalid_intersection_types}),k)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([n,a])=>s(n,a)):s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}Kt.create=(r,t,e)=>new Kt({left:r,right:t,typeName:x.ZodIntersection,...T(e)});class q extends w{_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==m.array)return g(i,{code:u.invalid_type,expected:m.array,received:i.parsedType}),k;if(i.data.length<this._def.items.length)return g(i,{code:u.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),k;!this._def.rest&&i.data.length>this._def.items.length&&(g(i,{code:u.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),e.dirty());const n=[...i.data].map((a,o)=>{const l=this._def.items[o]||this._def.rest;return l?l._parse(new K(i,a,i.path,o)):null}).filter(a=>!!a);return i.common.async?Promise.all(n).then(a=>L.mergeArray(e,a)):L.mergeArray(e,n)}get items(){return this._def.items}rest(t){return new q({...this._def,rest:t})}}q.create=(r,t)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new q({items:r,typeName:x.ZodTuple,rest:null,...T(t)})};class $t extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==m.object)return g(i,{code:u.invalid_type,expected:m.object,received:i.parsedType}),k;const s=[],n=this._def.keyType,a=this._def.valueType;for(const o in i.data)s.push({key:n._parse(new K(i,o,i.path,o)),value:a._parse(new K(i,i.data[o],i.path,o)),alwaysSet:o in i.data});return i.common.async?L.mergeObjectAsync(e,s):L.mergeObjectSync(e,s)}get element(){return this._def.valueType}static create(t,e,i){return e instanceof w?new $t({keyType:t,valueType:e,typeName:x.ZodRecord,...T(i)}):new $t({keyType:X.create(),valueType:t,typeName:x.ZodRecord,...T(e)})}}class ve extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==m.map)return g(i,{code:u.invalid_type,expected:m.map,received:i.parsedType}),k;const s=this._def.keyType,n=this._def.valueType,a=[...i.data.entries()].map(([o,l],c)=>({key:s._parse(new K(i,o,i.path,[c,"key"])),value:n._parse(new K(i,l,i.path,[c,"value"]))}));if(i.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const l of a){const c=await l.key,h=await l.value;if(c.status==="aborted"||h.status==="aborted")return k;(c.status==="dirty"||h.status==="dirty")&&e.dirty(),o.set(c.value,h.value)}return{status:e.value,value:o}})}else{const o=new Map;for(const l of a){const c=l.key,h=l.value;if(c.status==="aborted"||h.status==="aborted")return k;(c.status==="dirty"||h.status==="dirty")&&e.dirty(),o.set(c.value,h.value)}return{status:e.value,value:o}}}}ve.create=(r,t,e)=>new ve({valueType:t,keyType:r,typeName:x.ZodMap,...T(e)});class Tt extends w{_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==m.set)return g(i,{code:u.invalid_type,expected:m.set,received:i.parsedType}),k;const s=this._def;s.minSize!==null&&i.data.size<s.minSize.value&&(g(i,{code:u.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),e.dirty()),s.maxSize!==null&&i.data.size>s.maxSize.value&&(g(i,{code:u.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),e.dirty());const n=this._def.valueType;function a(l){const c=new Set;for(const h of l){if(h.status==="aborted")return k;h.status==="dirty"&&e.dirty(),c.add(h.value)}return{status:e.value,value:c}}const o=[...i.data.values()].map((l,c)=>n._parse(new K(i,l,i.path,c)));return i.common.async?Promise.all(o).then(l=>a(l)):a(o)}min(t,e){return new Tt({...this._def,minSize:{value:t,message:y.toString(e)}})}max(t,e){return new Tt({...this._def,maxSize:{value:t,message:y.toString(e)}})}size(t,e){return this.min(t,e).max(t,e)}nonempty(t){return this.min(1,t)}}Tt.create=(r,t)=>new Tt({valueType:r,minSize:null,maxSize:null,typeName:x.ZodSet,...T(t)});class Rt extends w{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:e}=this._processInputParams(t);if(e.parsedType!==m.function)return g(e,{code:u.invalid_type,expected:m.function,received:e.parsedType}),k;function i(o,l){return he({data:o,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,ce(),Pt].filter(c=>!!c),issueData:{code:u.invalid_arguments,argumentsError:l}})}function s(o,l){return he({data:o,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,ce(),Pt].filter(c=>!!c),issueData:{code:u.invalid_return_type,returnTypeError:l}})}const n={errorMap:e.common.contextualErrorMap},a=e.data;if(this._def.returns instanceof Lt){const o=this;return z(async function(...l){const c=new V([]),h=await o._def.args.parseAsync(l,n).catch(v=>{throw c.addIssue(i(l,v)),c}),p=await Reflect.apply(a,this,h);return await o._def.returns._def.type.parseAsync(p,n).catch(v=>{throw c.addIssue(s(p,v)),c})})}else{const o=this;return z(function(...l){const c=o._def.args.safeParse(l,n);if(!c.success)throw new V([i(l,c.error)]);const h=Reflect.apply(a,this,c.data),p=o._def.returns.safeParse(h,n);if(!p.success)throw new V([s(h,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Rt({...this._def,args:q.create(t).rest(xt.create())})}returns(t){return new Rt({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,e,i){return new Rt({args:t||q.create([]).rest(xt.create()),returns:e||xt.create(),typeName:x.ZodFunction,...T(i)})}}class Yt extends w{get schema(){return this._def.getter()}_parse(t){const{ctx:e}=this._processInputParams(t);return this._def.getter()._parse({data:e.data,path:e.path,parent:e})}}Yt.create=(r,t)=>new Yt({getter:r,typeName:x.ZodLazy,...T(t)});class Xt extends w{_parse(t){if(t.data!==this._def.value){const e=this._getOrReturnCtx(t);return g(e,{received:e.data,code:u.invalid_literal,expected:this._def.value}),k}return{status:"valid",value:t.data}}get value(){return this._def.value}}Xt.create=(r,t)=>new Xt({value:r,typeName:x.ZodLiteral,...T(t)});function Me(r,t){return new dt({values:r,typeName:x.ZodEnum,...T(t)})}class dt extends w{constructor(){super(...arguments),At.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const e=this._getOrReturnCtx(t),i=this._def.values;return g(e,{expected:S.joinValues(i),received:e.parsedType,code:u.invalid_type}),k}if(Gt(this,At)||Oe(this,At,new Set(this._def.values)),!Gt(this,At).has(t.data)){const e=this._getOrReturnCtx(t),i=this._def.values;return g(e,{received:e.data,code:u.invalid_enum_value,options:i}),k}return z(t.data)}get options(){return this._def.values}get enum(){const t={};for(const e of this._def.values)t[e]=e;return t}get Values(){const t={};for(const e of this._def.values)t[e]=e;return t}get Enum(){const t={};for(const e of this._def.values)t[e]=e;return t}extract(t,e=this._def){return dt.create(t,{...this._def,...e})}exclude(t,e=this._def){return dt.create(this.options.filter(i=>!t.includes(i)),{...this._def,...e})}}At=new WeakMap,dt.create=Me;class jt extends w{constructor(){super(...arguments),Ot.set(this,void 0)}_parse(t){const e=S.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==m.string&&i.parsedType!==m.number){const s=S.objectValues(e);return g(i,{expected:S.joinValues(s),received:i.parsedType,code:u.invalid_type}),k}if(Gt(this,Ot)||Oe(this,Ot,new Set(S.getValidEnumValues(this._def.values))),!Gt(this,Ot).has(t.data)){const s=S.objectValues(e);return g(i,{received:i.data,code:u.invalid_enum_value,options:s}),k}return z(t.data)}get enum(){return this._def.values}}Ot=new WeakMap,jt.create=(r,t)=>new jt({values:r,typeName:x.ZodNativeEnum,...T(t)});class Lt extends w{unwrap(){return this._def.type}_parse(t){const{ctx:e}=this._processInputParams(t);if(e.parsedType!==m.promise&&e.common.async===!1)return g(e,{code:u.invalid_type,expected:m.promise,received:e.parsedType}),k;const i=e.parsedType===m.promise?e.data:Promise.resolve(e.data);return z(i.then(s=>this._def.type.parseAsync(s,{path:e.path,errorMap:e.common.contextualErrorMap})))}}Lt.create=(r,t)=>new Lt({type:r,typeName:x.ZodPromise,...T(t)});class Q extends w{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===x.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:e,ctx:i}=this._processInputParams(t),s=this._def.effect||null,n={addIssue:a=>{g(i,a),a.fatal?e.abort():e.dirty()},get path(){return i.path}};if(n.addIssue=n.addIssue.bind(n),s.type==="preprocess"){const a=s.transform(i.data,n);if(i.common.async)return Promise.resolve(a).then(async o=>{if(e.value==="aborted")return k;const l=await this._def.schema._parseAsync({data:o,path:i.path,parent:i});return l.status==="aborted"?k:l.status==="dirty"||e.value==="dirty"?Et(l.value):l});{if(e.value==="aborted")return k;const o=this._def.schema._parseSync({data:a,path:i.path,parent:i});return o.status==="aborted"?k:o.status==="dirty"||e.value==="dirty"?Et(o.value):o}}if(s.type==="refinement"){const a=o=>{const l=s.refinement(o,n);if(i.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(i.common.async===!1){const o=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return o.status==="aborted"?k:(o.status==="dirty"&&e.dirty(),a(o.value),{status:e.value,value:o.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(o=>o.status==="aborted"?k:(o.status==="dirty"&&e.dirty(),a(o.value).then(()=>({status:e.value,value:o.value}))))}if(s.type==="transform")if(i.common.async===!1){const a=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!yt(a))return a;const o=s.transform(a.value,n);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:e.value,value:o}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(a=>yt(a)?Promise.resolve(s.transform(a.value,n)).then(o=>({status:e.value,value:o})):a);S.assertNever(s)}}Q.create=(r,t,e)=>new Q({schema:r,typeName:x.ZodEffects,effect:t,...T(e)}),Q.createWithPreprocess=(r,t,e)=>new Q({schema:t,effect:{type:"preprocess",transform:r},typeName:x.ZodEffects,...T(e)});class J extends w{_parse(t){return this._getType(t)===m.undefined?z(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}J.create=(r,t)=>new J({innerType:r,typeName:x.ZodOptional,...T(t)});class ut extends w{_parse(t){return this._getType(t)===m.null?z(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}ut.create=(r,t)=>new ut({innerType:r,typeName:x.ZodNullable,...T(t)});class qt extends w{_parse(t){const{ctx:e}=this._processInputParams(t);let i=e.data;return e.parsedType===m.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:e.path,parent:e})}removeDefault(){return this._def.innerType}}qt.create=(r,t)=>new qt({innerType:r,typeName:x.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...T(t)});class Qt extends w{_parse(t){const{ctx:e}=this._processInputParams(t),i={...e,common:{...e.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return Vt(s)?s.then(n=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new V(i.common.issues)},input:i.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new V(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Qt.create=(r,t)=>new Qt({innerType:r,typeName:x.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...T(t)});class Ce extends w{_parse(t){if(this._getType(t)!==m.nan){const i=this._getOrReturnCtx(t);return g(i,{code:u.invalid_type,expected:m.nan,received:i.parsedType}),k}return{status:"valid",value:t.data}}}Ce.create=r=>new Ce({typeName:x.ZodNaN,...T(r)});class He extends w{_parse(t){const{ctx:e}=this._processInputParams(t),i=e.data;return this._def.type._parse({data:i,path:e.path,parent:e})}unwrap(){return this._def.type}}class Jt extends w{_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.common.async)return(async()=>{const n=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return n.status==="aborted"?k:n.status==="dirty"?(e.dirty(),Et(n.value)):this._def.out._parseAsync({data:n.value,path:i.path,parent:i})})();{const s=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?k:s.status==="dirty"?(e.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:i.path,parent:i})}}static create(t,e){return new Jt({in:t,out:e,typeName:x.ZodPipeline})}}class te extends w{_parse(t){const e=this._def.innerType._parse(t),i=s=>(yt(s)&&(s.value=Object.freeze(s.value)),s);return Vt(e)?e.then(s=>i(s)):i(e)}unwrap(){return this._def.innerType}}te.create=(r,t)=>new te({innerType:r,typeName:x.ZodReadonly,...T(t)}),A.lazycreate;var x;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(x||(x={}));const M=X.create,C=vt.create;Ce.create,Ct.create,ue.create,Dt.create,pe.create,Ut.create,Zt.create,fe.create,xt.create,at.create,ge.create,$.create;const _=A.create;A.strictCreate;const Qi=Wt.create;me.create,Kt.create,q.create,$t.create,ve.create,Tt.create,Rt.create,Yt.create;const pt=Xt.create,ot=dt.create;jt.create,Lt.create,Q.create,J.create,ut.create,Q.createWithPreprocess,Jt.create;const Ji=ot(["linear","bezier","constant"]),ts=ot(["ease","easeIn","easeOut","easeInOut","easeInQuad","easeInCubic","easeInQuart","easeInQuint","easeInSine","easeInExpo","easeInCirc","easeInBack","easeOutQuad","easeOutCubic","easeOutQuart","easeOutQuint","easeOutSine","easeOutExpo","easeOutCirc","easeOutBack","easeInOutQuad","easeInOutCubic","easeInOutQuart","easeInOutQuint","easeInOutSine","easeInOutExpo","easeInOutCirc","easeInOutBack"]),ft=_({from:C(),to:C(),start:C().min(0),length:C().positive(),interpolation:Ji.optional(),easing:ts.optional()}),es=M().url("Invalid audio url format."),is=ft.extend({from:C().min(0).max(1),to:C().min(0).max(1)}).array().or(C().min(0).max(1)),ze=_({type:pt("audio"),src:es,trim:C().optional(),volume:is.optional()}),ss=ot(["top","topRight","right","bottomRight","bottom","bottomLeft","left","topLeft","center"]),Be=_({type:pt("html"),html:M(),css:M(),width:C().positive().optional(),height:C().positive().optional(),position:ss.optional()}),ns=M().url("Invalid image url format."),rs=_({top:C().min(0).optional(),right:C().min(0).optional(),bottom:C().min(0).optional(),left:C().min(0).optional()}),Fe=_({type:pt("image"),src:ns,crop:rs.optional()}),as=M().url("Invalid luma url format."),Ne=_({type:pt("luma"),src:as}),Ve=M().regex(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})|transparent$/,"Invalid color format."),Ge=_({width:C().positive(),height:C().positive()}),Ue=_({radius:C().positive()}),Ze=_({length:C().positive(),thickness:C().positive()}),os=_({color:Ve,opacity:C().min(0).max(1)}),ls=_({color:Ve,width:C().positive()}),We=_({type:pt("shape"),width:C().positive().optional(),height:C().positive().optional(),shape:ot(["rectangle","circle","line"]),fill:os.optional(),stroke:ls.optional(),rectangle:Ge.optional(),circle:Ue.optional(),line:Ze.optional()}).refine(r=>r.shape==="rectangle"?Ge.safeParse(r.rectangle):r.shape==="circle"?Ue.safeParse(r.circle):r.shape==="line"?Ze.safeParse(r.line):!1),xe=M().regex(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})|transparent$/,"Invalid color format."),cs=_({color:xe.optional(),family:M().optional(),size:C().positive().optional(),weight:C().optional(),lineHeight:C().optional()}),hs=_({horizontal:ot(["left","center","right"]).optional(),vertical:ot(["top","center","bottom"]).optional()}),ds=_({color:xe,opacity:C().min(0).max(1)}),us=_({width:C().positive(),color:xe}),Ke=_({type:pt("text"),text:M(),width:C().positive().optional(),height:C().positive().optional(),font:cs.optional(),alignment:hs.optional(),background:ds.optional(),stroke:us.optional()}),ps=M().url("Invalid video url format."),fs=_({top:C().min(0).optional(),right:C().min(0).optional(),bottom:C().min(0).optional(),left:C().min(0).optional()}),gs=ft.extend({from:C().min(0).max(1),to:C().min(0).max(1)}).array().or(C().min(0).max(1)),$e=_({type:pt("video"),src:ps,trim:C().optional(),crop:fs.optional(),volume:gs.optional()}),ms=Qi([Ke,We,Be,Fe,$e,Ne,ze]).refine(r=>r.type==="text"?Ke.safeParse(r):r.type==="shape"?We.safeParse(r):r.type==="html"?Be.safeParse(r):r.type==="image"?Fe.safeParse(r):r.type==="video"?$e.safeParse(r):r.type==="luma"?Ne.safeParse(r):r.type==="audio"?ze.safeParse(r):!1),ys=ot(["topLeft","top","topRight","left","center","right","bottomLeft","bottom","bottomRight"]),vs=ot(["crop","cover","contain","none"]),wt=C().min(-10).max(10).default(0),Cs=ft.extend({from:wt,to:wt}).array().or(wt),xs=ft.extend({from:wt,to:wt}).array().or(wt),ks=_({x:Cs.default(0),y:xs.default(0)}),Ts=ft.extend({from:C().min(0).max(1),to:C().min(0).max(1)}).array().or(C().min(0).max(1)),ws=ft.extend({from:C().min(0),to:C().min(0)}).array().or(C().min(0)),bs=_({angle:ft.extend({from:C(),to:C()}).array().or(C())}),Ss=M(),Ye=M(),Is=_({in:Ye.optional(),out:Ye.optional()}),_s=_({rotate:bs.default({angle:0})}),Xe=_({asset:ms,start:C().min(0),length:C().positive(),position:ys.default("center").optional(),fit:vs.default("crop").optional(),offset:ks.default({x:0,y:0}).optional(),opacity:Ts.default(1).optional(),scale:ws.default(1).optional(),transform:_s.default({rotate:{angle:0}}).optional(),effect:Ss.optional(),transition:Is.optional()});class Ps{constructor(t,e){this.trackIdx=t,this.clip=e}name="addClip";addedPlayer;async execute(t){if(!t)return;const e=Xe.parse(this.clip),i=t.createPlayerFromAssetType(e);i.layer=this.trackIdx+1,await t.addPlayer(this.trackIdx,i),t.updateDuration(),this.addedPlayer=i}async undo(t){!t||!this.addedPlayer||(t.queueDisposeClip(this.addedPlayer),t.updateDuration())}}class je{constructor(t){this.trackIdx=t}name="addTrack";execute(t){if(!t)return;const e=t.getTracks(),i=t.getClips();e.splice(this.trackIdx,0,[]),i.forEach(s=>{if(s.layer>=this.trackIdx){const n=1e5-s.layer*100,a=t.getContainer().getChildByLabel(`shotstack-track-${n}`,!1);a&&a.removeChild(s.getContainer()),s.layer+=1;const o=1e5-s.layer*100;let l=t.getContainer().getChildByLabel(`shotstack-track-${o}`,!1);l||(l=new d.Container({label:`shotstack-track-${o}`,zIndex:o}),t.getContainer().addChild(l)),l.addChild(s.getContainer())}}),t.updateDuration(),t.emitEvent("track:added",{trackIndex:this.trackIdx,totalTracks:e.length})}undo(t){if(!t)return;const e=t.getTracks(),i=t.getClips();e.splice(this.trackIdx,1),i.forEach(s=>{s.layer>this.trackIdx&&(s.layer-=1)}),t.updateDuration()}}class Es{name="ClearSelection";previousSelection=null;execute(t){const e=t.getSelectedClip();if(e){const i=t.findClipIndices(e);i&&(this.previousSelection={player:e,trackIndex:i.trackIndex,clipIndex:i.clipIndex})}t.setSelectedClip(null),t.emitEvent("selection:cleared",{})}undo(t){if(this.previousSelection){const e=t.getClipAt(this.previousSelection.trackIndex,this.previousSelection.clipIndex);e&&(t.setSelectedClip(e),t.emitEvent("clip:selected",{clip:e.clipConfiguration,trackIndex:this.previousSelection.trackIndex,clipIndex:this.previousSelection.clipIndex}))}}}class As{constructor(t,e){this.trackIdx=t,this.clipIdx=e}name="deleteClip";deletedClip;execute(t){if(!t)return;const i=t.getClips().filter(s=>s.layer===this.trackIdx+1);this.deletedClip=i[this.clipIdx],this.deletedClip&&(t.queueDisposeClip(this.deletedClip),t.updateDuration())}undo(t){!t||!this.deletedClip||t.undeleteClip(this.trackIdx,this.deletedClip)}}class Os{constructor(t){this.trackIdx=t}name="deleteTrack";deletedClips=[];execute(t){if(!t)return;const e=t.getClips(),i=t.getTracks();this.deletedClips=e.filter(a=>a.layer===this.trackIdx+1).map(a=>({config:structuredClone(a.clipConfiguration)})),e.forEach((a,o)=>{a.layer===this.trackIdx+1&&(e[o].shouldDispose=!0)}),t.disposeClips(),i.splice(this.trackIdx,1);const s=t.getClips(),n=t.getContainer();s.forEach((a,o)=>{if(a.layer>this.trackIdx+1){n.getChildByLabel(`shotstack-track-${1e5-a.layer*100}`,!1)?.removeChild(a.getContainer()),s[o].layer-=1;const c=1e5-s[o].layer*100;let h=n.getChildByLabel(`shotstack-track-${c}`,!1);h||(h=new d.Container({label:`shotstack-track-${c}`,zIndex:c}),n.addChild(h)),h.addChild(s[o].getContainer())}}),t.updateDuration()}async undo(t){if(!t||this.deletedClips.length===0)return;const e=t.getTracks(),i=t.getClips();e.splice(this.trackIdx,0,[]),i.forEach((s,n)=>{s.layer>=this.trackIdx+1&&(i[n].layer+=1)});for(const{config:s}of this.deletedClips){const n=t.createPlayerFromAssetType(s);n.layer=this.trackIdx+1,await t.addPlayer(this.trackIdx,n)}t.updateDuration()}}class Ds{constructor(t,e){this.trackIndex=t,this.clipIndex=e}name="SelectClip";previousSelection=null;execute(t){const e=t.getSelectedClip();if(e){const s=t.findClipIndices(e);s&&(this.previousSelection=s)}const i=t.getClipAt(this.trackIndex,this.clipIndex);i&&(t.setSelectedClip(i),t.emitEvent("clip:selected",{clip:i.clipConfiguration,trackIndex:this.trackIndex,clipIndex:this.clipIndex}))}undo(t){if(t.setSelectedClip(null),this.previousSelection){const e=t.getClipAt(this.previousSelection.trackIndex,this.previousSelection.clipIndex);e&&(t.setSelectedClip(e),t.emitEvent("clip:selected",{clip:e.clipConfiguration,trackIndex:this.previousSelection.trackIndex,clipIndex:this.previousSelection.clipIndex}))}else t.emitEvent("selection:cleared",{})}}class Rs{constructor(t,e,i){this.clip=t,this.initialClipConfig=e,this.finalClipConfig=i,this.storedInitialConfig=e?structuredClone(e):null,this.storedFinalConfig=i?structuredClone(i):structuredClone(this.clip.clipConfiguration)}name="setUpdatedClip";storedInitialConfig;storedFinalConfig;execute(t){if(!t)return;this.storedFinalConfig&&t.restoreClipConfiguration(this.clip,this.storedFinalConfig),t.setUpdatedClip(this.clip);const e=this.clip.layer-1,n=t.getClips().filter(a=>a.layer===this.clip.layer).indexOf(this.clip);t.emitEvent("clip:updated",{previous:{clip:this.storedInitialConfig||this.initialClipConfig,trackIndex:e,clipIndex:n},current:{clip:this.storedFinalConfig||this.clip.clipConfiguration,trackIndex:e,clipIndex:n}})}undo(t){if(!t||!this.storedInitialConfig)return;t.restoreClipConfiguration(this.clip,this.storedInitialConfig),t.setUpdatedClip(this.clip);const e=this.clip.layer-1,n=t.getClips().filter(a=>a.layer===this.clip.layer).indexOf(this.clip);t.emitEvent("clip:updated",{previous:{clip:this.storedFinalConfig,trackIndex:e,clipIndex:n},current:{clip:this.storedInitialConfig,trackIndex:e,clipIndex:n}})}}class Ls{constructor(t,e,i){this.trackIndex=t,this.clipIndex=e,this.splitTime=i}name="SplitClip";originalClipConfig=null;rightClipPlayer=null;splitSuccessful=!1;execute(t){const e=t.getClipAt(this.trackIndex,this.clipIndex);if(!e||!e.clipConfiguration)throw new Error("Cannot split clip: invalid player or clip configuration");const i=e.clipConfiguration,s=i.start||0,n=i.length,a=.1,o=this.splitTime-s;if(o<=a||o>=n-a)throw new Error("Cannot split clip: split point too close to clip boundaries");this.originalClipConfig={...i};const l={...i,length:o},c={...i,start:s+o,length:n-o};if(i.asset&&(l.asset={...i.asset},c.asset={...i.asset}),i.asset&&(i.asset.type==="video"||i.asset.type==="audio")){const v=i.asset.trim||0;l.asset&&(l.asset.type==="video"||l.asset.type==="audio")&&(l.asset.trim=v),c.asset&&(c.asset.type==="video"||c.asset.type==="audio")&&(c.asset.trim=v+o)}if(Object.assign(e.clipConfiguration,l),e.reconfigureAfterRestore(),e.draw(),this.rightClipPlayer=t.createPlayerFromAssetType(c),!this.rightClipPlayer)throw Object.assign(e.clipConfiguration,this.originalClipConfig),e.reconfigureAfterRestore(),new Error("Failed to create right clip player");this.rightClipPlayer.layer=this.trackIndex+1;const h=t.getTrack(this.trackIndex);if(!h)throw new Error("Invalid track index");h.splice(this.clipIndex+1,0,this.rightClipPlayer);const p=t.getClips(),f=p.indexOf(e);f!==-1&&p.splice(f+1,0,this.rightClipPlayer),t.addPlayerToContainer(this.trackIndex,this.rightClipPlayer),this.rightClipPlayer.reconfigureAfterRestore(),this.rightClipPlayer.load().then(()=>{this.splitSuccessful=!0,this.rightClipPlayer&&this.rightClipPlayer.draw(),t.updateDuration(),t.emitEvent("timeline:updated",{current:t.getEditState()})}).catch(v=>{console.error("Failed to load split clip:",v)})}undo(t){if(!this.originalClipConfig)return;const e=t.getClipAt(this.trackIndex,this.clipIndex);if(e){if(Object.assign(e.clipConfiguration,this.originalClipConfig),e.reconfigureAfterRestore(),this.rightClipPlayer){const i=t.getTrack(this.trackIndex);if(i){const a=i.indexOf(this.rightClipPlayer);a!==-1&&i.splice(a,1)}const s=t.getClips(),n=s.indexOf(this.rightClipPlayer);n!==-1&&s.splice(n,1),t.queueDisposeClip(this.rightClipPlayer),this.rightClipPlayer=null}t.updateDuration(),t.emitEvent("timeline:updated",{current:t.getEditState()})}}}class Ms{constructor(t,e,i){this.clip=t,this.newText=e,this.initialConfig=i;const{asset:s}=this.clip.clipConfiguration;this.previousText=s&&"text"in s?s.text:""}name="updateTextContent";previousText;execute(t){if(t&&this.clip.clipConfiguration.asset&&"text"in this.clip.clipConfiguration.asset){this.clip.clipConfiguration.asset.text=this.newText;const e=this.clip.text;e&&(e.text=this.newText,this.clip.positionText(this.clip.clipConfiguration.asset)),t.setUpdatedClip(this.clip);const i=this.clip.layer-1,a=t.getClips().filter(o=>o.layer===this.clip.layer).indexOf(this.clip);t.emitEvent("clip:updated",{previous:{clip:this.initialConfig,trackIndex:i,clipIndex:a},current:{clip:this.clip.clipConfiguration,trackIndex:i,clipIndex:a}})}}undo(t){if(t&&this.clip.clipConfiguration.asset&&"text"in this.clip.clipConfiguration.asset){this.clip.clipConfiguration.asset.text=this.previousText;const e=this.clip.text;e&&(e.text=this.previousText,this.clip.positionText(this.clip.clipConfiguration.asset)),t.setUpdatedClip(this.clip);const i=this.clip.layer-1,a=t.getClips().filter(o=>o.layer===this.clip.layer).indexOf(this.clip);t.emitEvent("clip:updated",{previous:{clip:this.clip.clipConfiguration,trackIndex:i,clipIndex:a},current:{clip:this.initialConfig,trackIndex:i,clipIndex:a}})}}}class Mt{events;constructor(){this.events={}}on(t,e){this.events[t]||(this.events[t]=new Set),this.events[t].add(e)}off(t,e){this.events[t]&&(this.events[t].delete(e),!(this.events[t].size>0)&&delete this.events[t])}clear(t){delete this.events[t]}emit(t,e){if(this.events[t])for(const i of this.events[t])i(e)}}class Hs extends Mt{registry;constructor(){super(),this.registry={}}}class ee{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 Hs;async load(t,e){this.updateAssetLoadMetadata(t,"pending",0);try{if(await this.shouldUseSafariVideoLoader(e))return await this.loadVideoForSafari(t,e);const i=await d.Assets.load(e,s=>{this.updateAssetLoadMetadata(t,"loading",s)});return this.updateAssetLoadMetadata(t,"success",1),i}catch{return this.updateAssetLoadMetadata(t,"failed",1),null}}getProgress(){const t=Object.keys(this.loadTracker.registry);return t.length===0?0:t.reduce((i,s)=>i+this.loadTracker.registry[s].progress,0)/t.length}extractUrl(t){if(typeof t=="string")return t;const e=Array.isArray(t.src)?t.src[0]:t.src;return typeof e=="string"?e:e?.src}hasVideoExtension(t){const e=new URL(t,window.location.origin).pathname.toLowerCase();return ee.VIDEO_EXTENSIONS.some(i=>e.endsWith(i))}async getContentType(t){try{return(await fetch(t,{method:"HEAD"})).headers.get("content-type")}catch{return null}}canPlayVideo(t){const e=new URL(t,window.location.origin).pathname.toLowerCase(),i=e.slice(e.lastIndexOf(".")),s=ee.VIDEO_MIME[i];return s?document.createElement("video").canPlayType(s)!=="":!1}async isPlayableVideo(t){if(this.hasVideoExtension(t))return this.canPlayVideo(t);const e=await this.getContentType(t);return e?.startsWith("video/")?document.createElement("video").canPlayType(e)!=="":!1}async shouldUseSafariVideoLoader(t){const e=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),i=this.extractUrl(t);return e&&i!==void 0&&await this.isPlayableVideo(i)}async loadVideoForSafari(t,e){const i=this.extractUrl(e),s=typeof e=="object"?e.data??{}:{},n=await new Promise((a,o)=>{const l=document.createElement("video");l.crossOrigin="anonymous",l.playsInline=!0,l.muted=!0,l.preload="metadata",l.addEventListener("loadedmetadata",()=>{try{const c=new d.VideoSource({resource:l,autoPlay:s.autoPlay??!1,...s});a(new d.Texture({source:c}))}catch(c){o(c)}},{once:!0}),l.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(t,"loading",.5),l.src=i});return this.updateAssetLoadMetadata(t,"success",1),n}updateAssetLoadMetadata(t,e,i){this.loadTracker.registry[t]?(this.loadTracker.registry[t].progress=i,this.loadTracker.registry[t].status=e):this.loadTracker.registry[t]={progress:i,status:e};const s={...this.loadTracker.registry};this.loadTracker.emit("onAssetLoadInfoUpdated",{registry:s})}}class ie{static Name="FontLoadParser";name;extension;validFontExtensions;woff2Decompressor;constructor(){this.name=ie.Name,this.extension={type:[d.ExtensionType.LoadParser],priority:d.LoaderParserPriority.High,ref:null},this.validFontExtensions=["ttf","otf","woff","woff2"],this.woff2Decompressor=null}test(t){const e=t.split("?")[0]?.split(".").pop()?.toLowerCase()??"";return this.validFontExtensions.includes(e)}async load(t,e,i){const s=t.split("?")[0]?.split(".").pop()?.toLowerCase()??"",n=await fetch(t).then(f=>f.arrayBuffer());if(s!=="woff2"){const f=Ie.parse(new Uint8Array(n).buffer),v=f.names.fontFamily.en||f.names.fontFamily[Object.keys(f.names.fontFamily)[0]],I=new FontFace(v,`url(${t})`);return await I.load(),document.fonts.add(I),I}if(await this.loadWoff2Decompressor(),!this.woff2Decompressor)throw new Error("Cannot initialize Woff2 decompressor.");const a=this.woff2Decompressor.decompress(n),o=Ie.parse(new Uint8Array(a).buffer),l=o.names.fontFamily.en||o.names.fontFamily[Object.keys(o.names.fontFamily)[0]],c=new Blob([a],{type:"font/ttf"}),h=URL.createObjectURL(c),p=new FontFace(l,`url(${h})`);return await p.load(),document.fonts.add(p),p}async loadWoff2Decompressor(){if(this.woff2Decompressor)return;const e=`${await fetch("https://unpkg.com/wawoff2@2.0.1/build/decompress_binding.js").then(i=>i.text())}; return Module`;this.woff2Decompressor=new Function(e)(),await new Promise(i=>{this.woff2Decompressor.onRuntimeInitialized=i})}unload(t){t&&document.fonts.delete(t)}}const zs=_({clips:Xe.array()}),Bs=M().url("Invalid image url format."),Fs=_({src:Bs}),Ns=_({background:M().optional(),fonts:Fs.array().optional(),tracks:zs.array()}),Vs=_({size:_({width:C().positive(),height:C().positive()}),fps:C().positive().optional(),format:M()}),Gs=_({timeline:Ns,output:Vs});class bt extends nt{static ZIndexPadding=100;assetLoader;events;edit;tracks;clipsToDispose;clips;commandHistory=[];commandIndex=-1;playbackTime;size;backgroundColor;totalDuration;isPlaying;selectedClip;updatedClip;viewportMask;constructor(t,e="#ffffff"){super(),this.assetLoader=new ee,this.edit=null,this.tracks=[],this.clipsToDispose=[],this.clips=[],this.events=new Mt,this.size=t,this.playbackTime=0,this.totalDuration=0,this.isPlaying=!1,this.selectedClip=null,this.updatedClip=null,this.backgroundColor=e,this.setupIntentListeners()}async load(){const t=new d.Graphics;t.fillStyle={color:this.backgroundColor},t.rect(0,0,this.size.width,this.size.height),t.fill(),this.getContainer().addChild(t),this.viewportMask=new d.Graphics,this.viewportMask.rect(0,0,this.size.width,this.size.height),this.viewportMask.fill(16777215),this.getContainer().addChild(this.viewportMask),this.getContainer().setMask({mask:this.viewportMask})}update(t,e){for(const i of this.clips)i.shouldDispose&&this.queueDisposeClip(i),i.update(t,e);this.disposeClips(),this.isPlaying&&(this.playbackTime=Math.max(0,Math.min(this.playbackTime+e,this.totalDuration)),this.playbackTime===this.totalDuration&&this.pause())}draw(){for(const t of this.clips)t.draw()}dispose(){if(this.clearClips(),this.viewportMask){try{this.getContainer().setMask(null)}catch{}this.viewportMask.destroy(),this.viewportMask=void 0}}play(){this.isPlaying=!0,this.events.emit("playback:play",{})}pause(){this.isPlaying=!1,this.events.emit("playback:pause",{})}seek(t){this.playbackTime=Math.max(0,Math.min(t,this.totalDuration)),this.pause()}stop(){this.seek(0)}async loadEdit(t){this.clearClips(),this.edit=Gs.parse(t),this.backgroundColor=this.edit.timeline.background||"#000000",await Promise.all((this.edit.timeline.fonts??[]).map(async e=>{const i=e.src,s={src:i,loadParser:ie.Name};return this.assetLoader.load(i,s)}));for(const[e,i]of this.edit.timeline.tracks.entries())for(const s of i.clips){const n=this.createPlayerFromAssetType(s);n.layer=e+1,await this.addPlayer(e,n)}this.updateTotalDuration()}getEdit(){const t=this.tracks.map((e,i)=>({clips:e.filter(n=>n&&!this.clipsToDispose.includes(n)).map(n=>n.clipConfiguration)}));return{timeline:{background:this.backgroundColor,tracks:t,fonts:this.edit?.timeline.fonts||[]},output:this.edit?.output||{size:this.size,format:"mp4"}}}addClip(t,e){const i=new Ps(t,e);this.executeCommand(i)}getClip(t,e){const i=this.clips.filter(s=>s.layer===t+1);return e<0||e>=i.length?null:i[e].clipConfiguration}getPlayerClip(t,e){const i=this.clips.filter(s=>s.layer===t+1);return e<0||e>=i.length?null:i[e]}deleteClip(t,e){const i=new As(t,e);this.executeCommand(i)}splitClip(t,e,i){const s=new Ls(t,e,i);this.executeCommand(s)}addTrack(t,e){const i=new je(t);this.executeCommand(i),e?.clips?.forEach(s=>this.addClip(t,s))}getTrack(t){const e=this.clips.filter(i=>i.layer===t+1);return e.length===0?null:{clips:e.map(i=>i.clipConfiguration)}}deleteTrack(t){const e=new Os(t);this.executeCommand(e)}getTotalDuration(){return this.totalDuration}undo(){if(this.commandIndex>=0){const t=this.commandHistory[this.commandIndex];if(t.undo){const e=this.createCommandContext();t.undo(e),this.commandIndex-=1,this.events.emit("edit:undo",{command:t.name})}}}redo(){if(this.commandIndex<this.commandHistory.length-1){this.commandIndex+=1;const t=this.commandHistory[this.commandIndex],e=this.createCommandContext();t.execute(e),this.events.emit("edit:redo",{command:t.name})}}setUpdatedClip(t,e=null,i=null){const s=new Rs(t,e,i);this.executeCommand(s)}updateTextContent(t,e,i){const s=new Ms(t,e,i);this.executeCommand(s)}executeEditCommand(t){return this.executeCommand(t)}executeCommand(t){const e=this.createCommandContext(),i=t.execute(e);return this.commandHistory=this.commandHistory.slice(0,this.commandIndex+1),this.commandHistory.push(t),this.commandIndex+=1,i}createCommandContext(){return{getClips:()=>this.clips,getTracks:()=>this.tracks,getTrack:t=>t>=0&&t<this.tracks.length?this.tracks[t]:null,getContainer:()=>this.getContainer(),addPlayer:(t,e)=>this.addPlayer(t,e),addPlayerToContainer:(t,e)=>{this.addPlayerToContainer(t,e)},createPlayerFromAssetType:t=>this.createPlayerFromAssetType(t),queueDisposeClip:t=>this.queueDisposeClip(t),disposeClips:()=>this.disposeClips(),undeleteClip:(t,e)=>{this.clips.push(e),this.updateTotalDuration()},setUpdatedClip:t=>{this.updatedClip=t},restoreClipConfiguration:(t,e)=>{Object.assign(t.clipConfiguration,structuredClone(e)),t.reconfigureAfterRestore(),t.draw()},updateDuration:()=>this.updateTotalDuration(),emitEvent:(t,e)=>this.events.emit(t,e),findClipIndices:t=>this.findClipIndices(t),getClipAt:(t,e)=>this.getClipAt(t,e),getSelectedClip:()=>this.selectedClip,setSelectedClip:t=>{this.selectedClip=t},movePlayerToTrackContainer:(t,e,i)=>this.movePlayerToTrackContainer(t,e,i),getEditState:()=>this.getEdit()}}queueDisposeClip(t){this.clipsToDispose.push(t)}disposeClips(){if(this.clipsToDispose.length!==0){for(const t of this.clipsToDispose)this.disposeClip(t);this.clips=this.clips.filter(t=>!this.clipsToDispose.includes(t)),this.clipsToDispose=[],this.updateTotalDuration()}}disposeClip(t){try{if(this.getContainer().children.includes(t.getContainer())){const e=this.getContainer().getChildIndex(t.getContainer());this.getContainer().removeChildAt(e)}else for(const e of this.getContainer().children)if(e instanceof d.Container&&e.label?.toString().startsWith("shotstack-track-")&&e.children.includes(t.getContainer())){e.removeChild(t.getContainer());break}}catch(e){console.warn(`Attempting to unmount an unmounted clip: ${e}`)}this.unloadClipAssets(t),t.dispose()}unloadClipAssets(t){const{asset:e}=t.clipConfiguration;if(e&&"src"in e&&typeof e.src=="string")try{d.Assets.unload(e.src)}catch(i){console.warn(`Failed to unload asset: ${e.src}`,i)}}clearClips(){for(const t of this.clips)this.disposeClip(t);this.clips=[],this.clipsToDispose=[],this.updateTotalDuration()}updateTotalDuration(){let t=0;for(const i of this.tracks)for(const s of i)t=Math.max(t,s.getEnd());const e=this.totalDuration;this.totalDuration=t,e!==this.totalDuration&&this.events.emit("duration:changed",{duration:this.totalDuration})}addPlayerToContainer(t,e){const i=1e5-(t+1)*bt.ZIndexPadding,s=`shotstack-track-${i}`;let n=this.getContainer().getChildByLabel(s,!1);n||(n=new d.Container({label:s,zIndex:i}),this.getContainer().addChild(n)),n.addChild(e.getContainer())}movePlayerToTrackContainer(t,e,i){if(e===i)return;const s=1e5-(e+1)*bt.ZIndexPadding,n=1e5-(i+1)*bt.ZIndexPadding,a=`shotstack-track-${s}`,o=`shotstack-track-${n}`,l=this.getContainer().getChildByLabel(a,!1);let c=this.getContainer().getChildByLabel(o,!1);c||(c=new d.Container({label:o,zIndex:n}),this.getContainer().addChild(c)),l&&l.removeChild(t.getContainer()),c.addChild(t.getContainer())}createPlayerFromAssetType(t){if(!t.asset?.type)throw new Error("Invalid clip configuration: missing asset type");let e;switch(t.asset.type){case"text":{e=new _i(this,t);break}case"shape":{e=new Ii(this,t);break}case"html":{e=new bi(this,t);break}case"image":{e=new Si(this,t);break}case"video":{e=new Pi(this,t);break}case"audio":{e=new oe(this,t);break}case"luma":{e=new _e(this,t);break}default:throw new Error(`Unsupported clip type: ${t.asset.type}`)}return e}async addPlayer(t,e){for(;this.tracks.length<=t;)this.tracks.push([]);this.tracks[t].push(e),this.clips.push(e);const i=1e5-(t+1)*bt.ZIndexPadding,s=`shotstack-track-${i}`;let n=this.getContainer().getChildByLabel(s,!1);n||(n=new d.Container({label:s,zIndex:i}),this.getContainer().addChild(n)),n.addChild(e.getContainer());const a=e instanceof _e;await e.load(),a&&n.setMask({mask:e.getMask(),inverse:!0}),this.updateTotalDuration()}selectClip(t,e){const i=new Ds(t,e);this.executeCommand(i)}clearSelection(){const t=new Es;this.executeCommand(t)}isClipSelected(t,e){if(!this.selectedClip)return!1;const i=this.selectedClip.layer-1,s=this.tracks[i].indexOf(this.selectedClip);return t===i&&e===s}getSelectedClipInfo(){if(!this.selectedClip)return null;const t=this.selectedClip.layer-1,e=this.tracks[t].indexOf(this.selectedClip);return{trackIndex:t,clipIndex:e,player:this.selectedClip}}findClipIndices(t){for(let e=0;e<this.tracks.length;e+=1){const i=this.tracks[e].indexOf(t);if(i!==-1)return{trackIndex:e,clipIndex:i}}return null}getClipAt(t,e){return t>=0&&t<this.tracks.length&&e>=0&&e<this.tracks[t].length?this.tracks[t][e]:null}selectPlayer(t){const e=this.findClipIndices(t);e&&this.selectClip(e.trackIndex,e.clipIndex)}isPlayerSelected(t){return this.selectedClip===t}setupIntentListeners(){this.events.on("timeline:clip:clicked",t=>{t.player?this.selectPlayer(t.player):this.selectClip(t.trackIndex,t.clipIndex)}),this.events.on("timeline:background:clicked",()=>{this.clearSelection()}),this.events.on("canvas:clip:clicked",t=>{this.selectPlayer(t.player)}),this.events.on("canvas:background:clicked",()=>{this.clearSelection()})}}class Ht extends nt{static Width=250;static Height=100;fps;playbackTime;playbackDuration;isPlaying;background;text;constructor(){super(),this.background=null,this.text=null,this.fps=0,this.playbackTime=0,this.playbackDuration=0,this.isPlaying=!1}async load(){const t=new d.Graphics;t.fillStyle={color:"#424242",alpha:.5},t.rect(0,0,Ht.Width,Ht.Height),t.fill(),this.getContainer().addChild(t),this.background=t;const e=new d.Text;e.text="",e.style={fontFamily:"monospace",fontSize:14,fill:"#ffffff",wordWrap:!0,wordWrapWidth:Ht.Width},this.getContainer().addChild(e),this.text=e}update(t,e){if(!this.text)return;const i=this.getMemoryInfo(),s=[`FPS: ${this.fps}`,`Playback: ${(this.playbackTime/1e3).toFixed(2)}/${(this.playbackDuration/1e3).toFixed(2)}`,`Playing: ${this.isPlaying}`,`Total Heap Size: ${i.totalHeapSize?`${this.bytesToMegabytes(i.totalHeapSize)}MB`:"N/A"}`,`Used Heap Size: ${i.usedHeapSize?`${this.bytesToMegabytes(i.usedHeapSize)}MB`:"N/A"}`,`Heap Size Limit: ${i.heapSizeLimit?`${this.bytesToMegabytes(i.heapSizeLimit)}MB`:"N/A"}`];this.text.text=s.join(`
185
+ `)}draw(){}dispose(){this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null}getMemoryInfo(){const t={};return"memory"in performance&&(t.totalHeapSize=performance.memory.totalJSHeapSize,t.usedHeapSize=performance.memory.usedJSHeapSize,t.heapSizeLimit=performance.memory.jsHeapSizeLimit),t}bytesToMegabytes(t){return Math.round(t/1024/1024)}}class gt{static CanvasSelector="[data-shotstack-studio]";static extensionsRegistered=!1;size;application;edit;inspector;container;background;timeline;minZoom=.1;maxZoom=4;currentZoom=.8;constructor(t,e){this.size=t,this.application=new d.Application,this.edit=e,this.inspector=new Ht}async load(){const t=document.querySelector(gt.CanvasSelector);if(!t)throw new Error(`Shotstack canvas root element '${gt.CanvasSelector}' not found.`);this.registerExtensions(),this.container=new d.Container,this.background=new d.Graphics,this.background.fillStyle={color:"#424242"},this.background.rect(0,0,this.size.width,this.size.height),this.background.fill(),await this.configureApplication(),this.configureStage(),this.setupTouchHandling(t),this.edit.getContainer().scale=this.currentZoom,t.appendChild(this.application.canvas)}setupTouchHandling(t){const e=this.edit.getContainer();t.addEventListener("wheel",i=>{if(i.preventDefault(),i.stopPropagation(),i.ctrlKey){const s=Math.exp(-i.deltaY/100),n=this.currentZoom*s,a=this.currentZoom;this.currentZoom=Math.min(Math.max(n,this.minZoom),this.maxZoom);const o={x:this.application.canvas.width/2,y:this.application.canvas.height/2},l={x:e.position.x-o.x,y:e.position.y-o.y},c=this.currentZoom/a;e.position.x=o.x+l.x*c,e.position.y=o.y+l.y*c,e.scale.x=this.currentZoom,e.scale.y=this.currentZoom}},{passive:!1,capture:!0})}centerEdit(){if(!this.edit)return;const t=this.edit.getContainer();t.position={x:this.application.canvas.width/2-this.edit.size.width*this.currentZoom/2,y:this.application.canvas.height/2-this.edit.size.height*this.currentZoom/2}}zoomToFit(){if(!this.edit)return;const t=this.application.canvas.width/this.edit.size.width,e=this.application.canvas.height/this.edit.size.height,i=Math.min(t,e);this.currentZoom=Math.min(Math.max(i,this.minZoom),this.maxZoom);const s=this.edit.getContainer();s.scale.x=this.currentZoom,s.scale.y=this.currentZoom,this.centerEdit()}setZoom(t){this.currentZoom=Math.min(Math.max(t,this.minZoom),this.maxZoom);const e=this.edit.getContainer();e.scale.x=this.currentZoom,e.scale.y=this.currentZoom}registerTimeline(t){this.timeline=t}registerExtensions(){gt.extensionsRegistered||(d.extensions.add(new Bt),d.extensions.add(new ie),gt.extensionsRegistered=!0)}async configureApplication(){const t={background:"#000000",width:this.size.width,height:this.size.height,antialias:!0};await this.application.init(t),this.application.ticker.add(this.onTick.bind(this)),this.application.ticker.minFPS=60,this.application.ticker.maxFPS=60}onTick(t){this.edit.update(t.deltaTime,t.deltaMS),this.edit.draw(),this.inspector.fps=Math.ceil(t.FPS),this.inspector.playbackTime=this.edit.playbackTime,this.inspector.playbackDuration=this.edit.totalDuration,this.inspector.isPlaying=this.edit.isPlaying,this.inspector.update(t.deltaTime,t.deltaMS),this.inspector.draw(),this.timeline&&(this.timeline.update(t.deltaTime,t.deltaMS),this.timeline.draw())}configureStage(){if(!this.container||!this.background)throw new Error("Shotstack canvas container not set up.");this.container.addChild(this.background),this.container.addChild(this.edit.getContainer()),this.container.addChild(this.inspector.getContainer()),this.application.stage.addChild(this.container),this.application.stage.eventMode="static",this.application.stage.hitArea=new d.Rectangle(0,0,this.size.width,this.size.height),this.background.eventMode="static",this.background.on("pointerdown",this.onBackgroundClick.bind(this)),this.application.stage.on("click",this.onClick.bind(this)),this.edit.getContainer().position={x:this.application.canvas.width/2-this.edit.size.width*this.currentZoom/2,y:this.application.canvas.height/2-this.edit.size.height*this.currentZoom/2}}onClick(){this.edit.pause()}onBackgroundClick(t){t.target===this.background&&this.edit.events.emit("canvas:background:clicked",{})}dispose(){const t=document.querySelector(gt.CanvasSelector);t&&t.contains(this.application.canvas)&&t.removeChild(this.application.canvas),this.application.ticker.remove(this.onTick,this),this.application.stage.off("click",this.onClick,this),this.background?.off("pointerdown",this.onBackgroundClick,this),this.background?.destroy(),this.container?.destroy(),this.inspector.dispose(),this.application.destroy(!0,{children:!0,texture:!0})}}class Us{edit;seekDistance=50;seekDistanceLarge=500;frameTime=16.67;constructor(t){this.edit=t}async load(){document.addEventListener("keydown",this.handleKeyDown),document.addEventListener("keyup",this.handleKeyUp)}dispose(){document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("keyup",this.handleKeyUp)}handleKeyDown=t=>{if(!(t.target instanceof HTMLInputElement||t.target instanceof HTMLTextAreaElement))switch(t.code){case"Space":{this.edit.isPlaying?this.edit.pause():this.edit.play();break}case"ArrowLeft":{if(t.metaKey)this.edit.seek(0);else{const e=t.shiftKey?this.seekDistanceLarge:this.seekDistance;this.edit.seek(this.edit.playbackTime-e)}break}case"ArrowRight":{if(t.metaKey)this.edit.seek(this.edit.getTotalDuration());else{const e=t.shiftKey?this.seekDistanceLarge:this.seekDistance;this.edit.seek(this.edit.playbackTime+e)}break}case"KeyJ":{this.edit.stop();break}case"KeyK":{this.edit.pause();break}case"KeyL":{this.edit.play();break}case"Comma":{this.edit.seek(this.edit.playbackTime-this.frameTime);break}case"Period":{this.edit.seek(this.edit.playbackTime+this.frameTime);break}case"KeyZ":{(t.metaKey||t.ctrlKey)&&(t.preventDefault(),t.shiftKey?this.edit.redo():this.edit.undo());break}case"Delete":case"Backspace":{const e=this.edit.getSelectedClipInfo();e&&(t.preventDefault(),this.edit.deleteClip(e.trackIndex,e.clipIndex));break}}};handleKeyUp=t=>{if(!(t.target instanceof HTMLInputElement||t.target instanceof HTMLTextAreaElement))switch(t.code){case"KeyI":console.log(this.edit.getEdit());break}}}class Zs{ffmpeg;isReady=!1;edit;application;constructor(t,e){this.edit=t,this.application=e.application,this.ffmpeg=new di.FFmpeg}async init(){if(!this.isReady)try{await this.ffmpeg.load(),this.isReady=!0}catch(t){throw console.error("FFmpeg initialization failed:",t),t}}async export(t="shotstack-export.mp4",e=30){this.isReady||await this.init();const i=this.edit.isPlaying,s=this.edit.playbackTime;this.edit.pause();const n=this.edit.getContainer(),a=n.visible,{x:o,y:l}=n.position,{x:c,y:h}=n.scale;n.visible=!1;const p=this.createProgressOverlay();try{const f=this.edit.getSize?this.edit.getSize():{width:1920,height:1080},v=Math.ceil(this.edit.totalDuration*e/1e3),I=1e3/e,b=100,O=50,N=50,lt=P=>Math.round(P/v*O);this.updateProgressOverlay(p,0,b);const et=document.createElement("canvas");et.width=f.width,et.height=f.height;const It=et.getContext("2d");if(!It)throw new Error("Could not get 2D context for canvas");const Te=this.findAudioPlayers();this.updateProgressOverlay(p,2,b);const it=[];if(Te.length>0){this.updateProgressOverlay(p,3,b);for(let P=0;P<Te.length;P+=1){const U=await this.processAudioTrack(Te[P],P);U&&it.push(U),this.updateProgressOverlay(p,4+P,b)}}n.position.x=0,n.position.y=0,n.scale.x=1,n.scale.y=1;for(let P=0;P<v;P+=1){this.edit.seek(P*I),this.edit.tick?this.edit.tick(0,0):(this.edit.update?.(0,0),this.edit.draw?.());try{const{extract:U}=this.application.renderer,B=U.canvas(n);It.clearRect(0,0,et.width,et.height),It.drawImage(B,0,0);const st=et.toDataURL("image/png"),re=await(await fetch(st)).arrayBuffer(),Cn=`frame_${P.toString().padStart(6,"0")}.png`;await this.ffmpeg.writeFile(Cn,new Uint8Array(re))}catch(U){console.error(`Error capturing frame ${P}:`,U)}this.updateProgressOverlay(p,lt(P+1),b)}this.updateProgressOverlay(p,O,b);let ct=["-framerate",e.toString(),"-i","frame_%06d.png"];for(const P of it)ct=ct.concat(["-i",P.filename]);if(ct=ct.concat(["-c:v","libx264","-pix_fmt","yuv420p","-crf","23"]),it.length>0){let P="";for(let B=0;B<it.length;B+=1){const st=it[B],li=B+1,re=Math.max(0,st.start);P+=`[${li}:a]aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo,apad,afade=t=in:st=0:d=0.05,atrim=start=0:end=${st.duration/1e3+.1},adelay=${re}|${re},volume=${st.volume}[a${B}];`}const U=it.length>1?`${it.map((B,st)=>`[a${st}]`).join("")}amix=inputs=${it.length}:duration=longest:dropout_transition=0.5:normalize=0[aout]`:"[a0]aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo[aout]";P+=U,ct=ct.concat(["-filter_complex",P,"-map","0:v","-map","[aout]","-c:a","aac","-b:a","192k","-shortest"])}const we="output.mp4";ct.push(we);let ri=0;const ai=({message:P})=>{const U=P.includes("frame=")&&P.includes("fps=")?P.match(/frame=\s*(\d+)/):null;if(U?.[1]){const B=parseInt(U[1],10);if(!Number.isNaN(B)&&B>ri&&(ri=B,B<=v)){const st=Math.round(B/v*N);this.updateProgressOverlay(p,O+st,b)}}};this.ffmpeg.on("log",ai),await this.ffmpeg.exec(ct),this.ffmpeg.off("log",ai),this.updateProgressOverlay(p,O+N,b);const be=await this.ffmpeg.readFile(we),yn=be instanceof Uint8Array?be:new TextEncoder().encode(be.toString()),vn=new Blob([yn],{type:"video/mp4"}),oi=URL.createObjectURL(vn),Se=document.createElement("a");Se.href=oi,Se.download=t,Se.click(),URL.revokeObjectURL(oi);for(let P=0;P<v;P+=1)try{await this.ffmpeg.deleteFile(`frame_${P.toString().padStart(6,"0")}.png`)}catch{}for(const P of it)try{await this.ffmpeg.deleteFile(P.filename)}catch{}await this.ffmpeg.deleteFile(we),this.updateProgressOverlay(p,b,b)}catch(f){throw console.error("Error during export:",f),f}finally{this.removeProgressOverlay(p),n.position.x=o,n.position.y=l,n.scale.x=c,n.scale.y=h,n.visible=a,this.edit.seek(s),i&&this.edit.play()}}findAudioPlayers(){const t=[],e=this.edit.tracks;if(e&&Array.isArray(e))for(let i=0;i<e.length;i+=1){const s=e[i];if(Array.isArray(s))for(let n=0;n<s.length;n+=1){const a=s[n];(a instanceof oe||a.constructor.name==="AudioPlayer"||a.clipConfiguration?.asset?.type==="audio")&&(t.includes(a)||t.push(a))}}return this.searchContainerForPlayers(this.edit.getContainer(),t),t}searchContainerForPlayers(t,e){if(t){for(const i of t.children)if(i instanceof d.Container){if(i.label?.startsWith("shotstack-track-")){for(const n of i.children)if(n instanceof d.Container){const a=n,o=["player","clip","audioPlayer","entity"];for(const l of o){const c=a[l];c instanceof oe&&!e.includes(c)&&e.push(c)}}}this.searchContainerForPlayers(i,e)}}}async processAudioTrack(t,e){try{const{clipConfiguration:i}=t;if(!i?.asset)return null;const s=i.asset;if(!s.src)return console.warn("Audio asset does not have a valid src property"),null;const n=await fetch(s.src);if(!n.ok)return console.error(`Failed to fetch audio file: ${s.src}`),null;const a=await n.arrayBuffer(),o=`audio_${e}.mp3`;return await this.ffmpeg.writeFile(o,new Uint8Array(a)),{filename:o,start:t.getStart(),duration:t.getLength(),volume:t.getVolume()}}catch(i){return console.error(`Error processing audio track ${e}:`,i),null}}createProgressOverlay(){const t=document.createElement("div");t.className="video-export-progress-overlay",Object.assign(t.style,{position:"fixed",top:"0",left:"0",width:"100%",height:"100%",backgroundColor:"rgba(0, 0, 0, 0.5)",zIndex:"9999",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",color:"white",fontFamily:"Arial, sans-serif"});const e=document.createElement("div");Object.assign(e.style,{backgroundColor:"#222",borderRadius:"8px",padding:"20px",boxShadow:"0 4px 8px rgba(0, 0, 0, 0.2)",width:"300px",textAlign:"center"}),t.appendChild(e);const i=document.createElement("h3");i.innerText="Exporting Video",i.style.margin="0 0 15px 0",i.style.fontWeight="normal",e.appendChild(i);const s=document.createElement("div");Object.assign(s.style,{width:"100%",height:"6px",backgroundColor:"#444",borderRadius:"3px",overflow:"hidden",marginBottom:"10px"}),e.appendChild(s);const n=document.createElement("div");n.className="video-export-progress-bar",Object.assign(n.style,{width:"0%",height:"100%",backgroundColor:"#3498db",transition:"width 0.3s"}),s.appendChild(n);const a=document.createElement("div");return a.className="video-export-percent",a.innerText="0%",a.style.fontSize="12px",e.appendChild(a),document.body.appendChild(t),t}updateProgressOverlay(t,e,i){if(!t)return;const s=Math.round(e/i*100),n=t.querySelector(".video-export-progress-bar"),a=t.querySelector(".video-export-percent");n&&(n.style.width=`${s}%`),a&&(a.innerText=`${s}%`)}removeProgressOverlay(t){t?.parentNode?.removeChild(t)}}function qe(r){const t=r.replace("#",""),e=parseInt(t,16);return Number.isNaN(e)?(console.warn(`Invalid hex color: ${r}, defaulting to black`),0):e}function Ws(r){const t=e=>{if(typeof e=="string")return qe(e);if(typeof e=="object"&&e!==null){const i=Array.isArray(e)?[]:{};for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(i[s]=t(e[s]));return i}return e};return t(r)}function Qe(r){if(typeof r=="string")return qe(r);if(typeof r=="object"&&r!==null){const t=Array.isArray(r)?[]:{};for(const e in r)Object.prototype.hasOwnProperty.call(r,e)&&(t[e]=Qe(r[e]));return t}return r}const Je=Ws({timeline:{background:"#1a1a1a",divider:"#1a1a1a",toolbar:{background:"#1a1a1a",surface:"#2a2a2a",hover:"#3a3a3a",active:"#007acc",divider:"#3a3a3a",icon:"#888888",text:"#ffffff",height:36},ruler:{background:"#404040",text:"#ffffff",markers:"#666666",height:40},tracks:{surface:"#2a2a2a",surfaceAlt:"#242424",border:"#3a3a3a",height:60},clips:{video:"#4a90e2",audio:"#7ed321",image:"#f5a623",text:"#d0021b",shape:"#9013fe",html:"#50e3c2",luma:"#b8e986",default:"#8e8e93",selected:"#007acc",radius:4},playhead:"#ff4444",snapGuide:"#888888",dropZone:"#00ff00",trackInsertion:"#00ff00"}});class ti{static resolveTheme(t){if(!t||!t.theme)return this.deepClone(Je);const e=Qe(t.theme),i=this.deepClone(Je);return this.deepMerge(i,e)}static validateTheme(t){try{if(!t.timeline)return!1;const{timeline:e}=t;if(typeof e.background!="number"||typeof e.divider!="number"||typeof e.playhead!="number"||typeof e.snapGuide!="number"||typeof e.dropZone!="number"||typeof e.trackInsertion!="number"||!e.toolbar)return!1;const i=e.toolbar;if(typeof i.background!="number"||typeof i.surface!="number"||typeof i.hover!="number"||typeof i.active!="number"||typeof i.divider!="number"||typeof i.icon!="number"||typeof i.text!="number"||typeof i.height!="number"||i.height<=0||!e.ruler)return!1;const s=e.ruler;if(typeof s.background!="number"||typeof s.text!="number"||typeof s.markers!="number"||typeof s.height!="number"||s.height<=0||!e.tracks)return!1;const n=e.tracks;if(typeof n.surface!="number"||typeof n.surfaceAlt!="number"||typeof n.border!="number"||typeof n.height!="number"||n.height<=0||!e.clips)return!1;const a=e.clips,o=["video","audio","image","text","shape","html","luma","default","selected"];for(const l of o)if(typeof a[l]!="number")return!1;return!(typeof a.radius!="number"||a.radius<0)}catch(e){return console.error("Theme validation error:",e),!1}}static deepClone(t){if(t===null||typeof t!="object")return t;if(t instanceof Array)return t.map(i=>this.deepClone(i));const e={};for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=this.deepClone(t[i]));return e}static deepMerge(t,e){const i={...t};for(const s in e)if(Object.prototype.hasOwnProperty.call(e,s)){const n=e[s],a=i[s];n!==void 0&&(typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof a=="object"&&a!==null&&!Array.isArray(a)?i[s]=this.deepMerge(a,n):i[s]=n)}return i}}class Ks{timeline;constructor(t){this.timeline=t}getValidDropPosition(t,e,i,s){const n=this.timeline.getVisualTracks()[i];if(!n)return{validTime:t,wouldOverlap:!1};const a=this.getOtherClipBounds(n,s),o=t+e,l=a.find(v=>!(o<=v.start||t>=v.end));if(!l)return{validTime:t,wouldOverlap:!1};const c=l.start-e,h=l.end,p=Math.abs(t-c)<Math.abs(t-h)&&c>=0?c:h;return{validTime:this.getValidDropPosition(p,e,i,s).validTime,wouldOverlap:!0}}checkOverlap(t,e,i,s){const n=this.timeline.getVisualTracks()[i];if(!n)return!1;const a=this.getOtherClipBounds(n,s),o=t+e;return a.some(l=>!(o<=l.start||t>=l.end))}getOtherClipBounds(t,e){return t.getClips().map((i,s)=>({clip:i,index:s})).filter(({index:i})=>i!==e).map(({clip:i})=>{const s=i.getClipConfig();return s?{start:s.start||0,end:(s.start||0)+(s.length||0)}:null}).filter(i=>i!==null).sort((i,s)=>i.start-s.start)}findAvailableGaps(t,e){const i=this.timeline.getVisualTracks()[t];if(!i)return[];const s=this.getOtherClipBounds(i),n=[];s.length>0&&s[0].start>=e&&n.push({start:0,end:s[0].start});for(let a=0;a<s.length-1;a+=1)s[a+1].start-s[a].end>=e&&n.push({start:s[a].end,end:s[a+1].start});return n}}class ei{constructor(t,e,i,s){this.fromTrackIndex=t,this.fromClipIndex=e,this.toTrackIndex=i,this.newStart=s,this.originalTrackIndex=t,this.originalClipIndex=e}name="moveClip";player;originalTrackIndex;originalClipIndex;originalStart;execute(t){if(!t)return;const e=t.getTracks();if(this.fromTrackIndex<0||this.fromTrackIndex>=e.length){console.warn(`Invalid source track index: ${this.fromTrackIndex}`);return}const i=e[this.fromTrackIndex];if(this.fromClipIndex<0||this.fromClipIndex>=i.length){console.warn(`Invalid clip index: ${this.fromClipIndex}`);return}if(this.player=i[this.fromClipIndex],this.originalStart=this.player.clipConfiguration.start,this.fromTrackIndex!==this.toTrackIndex){if(this.toTrackIndex<0||this.toTrackIndex>=e.length){console.warn(`Invalid destination track index: ${this.toTrackIndex}`);return}i.splice(this.fromClipIndex,1),this.player.layer=this.toTrackIndex+1;const s=e[this.toTrackIndex];let n=0;for(let a=0;a<s.length;a+=1){const o=s[a];if(o.clipConfiguration&&o.clipConfiguration.start!==void 0&&this.newStart<o.clipConfiguration.start)break;n+=1}s.splice(n,0,this.player),this.originalClipIndex=n}if(this.player.clipConfiguration.start=this.newStart,t.movePlayerToTrackContainer(this.player,this.fromTrackIndex,this.toTrackIndex),this.player.reconfigureAfterRestore(),this.player.draw(),t.updateDuration(),this.fromTrackIndex!==this.toTrackIndex){const s=e[this.fromTrackIndex],n=e[this.toTrackIndex];[...s,...n].forEach(a=>{a&&a!==this.player&&a.draw()})}t.emitEvent("clip:updated",{previous:{clip:{...this.player.clipConfiguration,start:this.originalStart},trackIndex:this.fromTrackIndex,clipIndex:this.fromClipIndex},current:{clip:this.player.clipConfiguration,trackIndex:this.toTrackIndex,clipIndex:this.originalClipIndex}})}undo(t){if(!t||!this.player||this.originalStart===void 0)return;const e=t.getTracks();if(this.fromTrackIndex!==this.toTrackIndex){const i=e[this.toTrackIndex],s=i.indexOf(this.player);s!==-1&&i.splice(s,1),this.player.layer=this.fromTrackIndex+1,e[this.fromTrackIndex].splice(this.fromClipIndex,0,this.player)}this.player.clipConfiguration.start=this.originalStart,t.movePlayerToTrackContainer(this.player,this.toTrackIndex,this.fromTrackIndex),this.player.reconfigureAfterRestore(),this.player.draw(),t.updateDuration(),t.emitEvent("clip:updated",{previous:{clip:{...this.player.clipConfiguration,start:this.newStart},trackIndex:this.toTrackIndex,clipIndex:this.originalClipIndex},current:{clip:this.player.clipConfiguration,trackIndex:this.fromTrackIndex,clipIndex:this.fromClipIndex}})}}class $s{constructor(t,e,i,s){this.insertionIndex=t,this.fromTrackIndex=e,this.fromClipIndex=i,this.newStart=s,this.addTrackCommand=new je(t);const n=e>=t?e+1:e;this.moveClipCommand=new ei(n,i,t,s)}name="createTrackAndMoveClip";addTrackCommand;moveClipCommand;wasExecuted=!1;async execute(t){if(t)try{this.addTrackCommand.execute(t),this.moveClipCommand.execute(t),this.wasExecuted=!0}catch(e){if(this.wasExecuted)try{this.undo(t)}catch{}throw e}}undo(t){!t||!this.wasExecuted||(this.moveClipCommand.undo(t),this.addTrackCommand.undo(t),this.wasExecuted=!1,t.emitEvent("track:created:undone",{trackIndex:this.insertionIndex}))}}class Ys{timeline;thresholds;snapManager;collisionDetector;visualFeedback;dragInfo=null;currentDropZone=null;constructor(t,e,i,s,n){this.timeline=t,this.thresholds=e,this.snapManager=i,this.collisionDetector=s,this.visualFeedback=n}activate(){}deactivate(){this.endDrag()}canStartDrag(t,e){const i=Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2),{trackHeight:s}=this.timeline.getLayout(),n=s<20?2:this.thresholds.drag.base;return i>n}startDrag(t,e){const i=this.timeline.getClipData(t.trackIndex,t.clipIndex);if(!i)return console.warn(`Clip data not found for track ${t.trackIndex}, clip ${t.clipIndex}`),!1;const s=this.timeline.getContainer().toLocal(e.global),n=this.timeline.getLayout(),a=n.getXAtTime(i.start||0),o=t.trackIndex*n.trackHeight;return this.dragInfo={trackIndex:t.trackIndex,clipIndex:t.clipIndex,startTime:i.start||0,offsetX:s.x-a,offsetY:s.y-o},this.timeline.getPixiApp().canvas.style.cursor="grabbing",this.timeline.getEdit().events.emit("drag:started",this.dragInfo),!0}updateDrag(t){if(!this.dragInfo)return;const e=this.calculateDragPosition(t),i=this.detectDropZone(e.y);i?this.handleDropZonePreview(i,e):this.handleNormalDragPreview(e),this.emitDragUpdate(e,i)}completeDrag(t){if(!this.dragInfo)return;const e={...this.dragInfo},i=this.calculateDragPosition(t),s=this.detectDropZone(i.y);this.endDrag(),s?this.executeDropZoneMove(s,e,i):this.executeNormalMove(e,i)}calculateDragPosition(t){if(!this.dragInfo)throw new Error("No drag info available");const e=this.timeline.getContainer().toLocal(t.global),i=this.timeline.getLayout(),s=Math.max(0,i.getTimeAtX(e.x-this.dragInfo.offsetX)),n=e.y-this.dragInfo.offsetY,a=n+i.trackHeight/2,o=Math.max(0,Math.floor(a/i.trackHeight)),l=this.timeline.getVisualTracks().length-1,c=Math.max(0,Math.min(l,o));return{x:e.x,y:e.y+i.viewportY,time:s,track:c,ghostY:n}}detectDropZone(t){const e=this.timeline.getLayout(),i=this.timeline.getVisualTracks(),s=e.trackHeight*this.thresholds.dropZone.ratio;for(let n=0;n<=i.length;n+=1){const a=e.tracksY+n*e.trackHeight;if(Math.abs(t-a)<s){let o;return n===0?o="above":n===i.length?o="below":o="between",{type:o,position:n}}}return null}handleDropZonePreview(t,e){(!this.currentDropZone||this.currentDropZone.type!==t.type||this.currentDropZone.position!==t.position)&&(this.currentDropZone=t,this.visualFeedback.showDropZone(t)),this.timeline.hideDragGhost(),this.visualFeedback.hideSnapGuidelines(),this.visualFeedback.hideTargetTrack()}handleNormalDragPreview(t){if(!this.dragInfo)return;this.currentDropZone&&(this.visualFeedback.hideDropZone(),this.currentDropZone=null);const e=this.timeline.getClipData(this.dragInfo.trackIndex,this.dragInfo.clipIndex);if(!e)return;const i=e.length||0,s=t.track===this.dragInfo.trackIndex?this.dragInfo.clipIndex:void 0,n=this.calculateFinalPosition(t.time,t.track,i,s),a=this.snapManager.findAlignedElements(n,i,t.track,s);a.length>0?this.visualFeedback.showSnapGuidelines(a):this.visualFeedback.hideSnapGuidelines(),this.visualFeedback.showTargetTrack(t.track),this.timeline.showDragGhost(t.track,n,t.ghostY)}calculateFinalPosition(t,e,i,s){const n=this.snapManager.calculateSnapPosition(t,e,i,s);return this.collisionDetector.getValidDropPosition(n.time,i,e,s).validTime}emitDragUpdate(t,e){if(!this.dragInfo)return;const i=this.timeline.getClipData(this.dragInfo.trackIndex,this.dragInfo.clipIndex);if(!i)return;const s=i.length||0,n=e?t.time:this.calculateFinalPosition(t.time,t.track,s,t.track===this.dragInfo.trackIndex?this.dragInfo.clipIndex:void 0);this.timeline.getEdit().events.emit("drag:moved",{...this.dragInfo,currentTime:n,currentTrack:e?-1:t.track})}executeDropZoneMove(t,e,i){const s=new $s(t.position,e.trackIndex,e.clipIndex,i.time);this.timeline.getEdit().executeEditCommand(s)}executeNormalMove(t,e){const i=this.timeline.getClipData(t.trackIndex,t.clipIndex);if(!i)return;const s=i.length||0,n=e.track===t.trackIndex?t.clipIndex:void 0,a=this.calculateFinalPosition(e.time,e.track,s,n);if(e.track!==t.trackIndex||Math.abs(a-t.startTime)>.01){const l=new ei(t.trackIndex,t.clipIndex,e.track,a);this.timeline.getEdit().executeEditCommand(l)}}endDrag(){this.dragInfo=null,this.currentDropZone=null,this.visualFeedback.hideAll(),this.timeline.getPixiApp().canvas.style.cursor="default",this.timeline.getEdit().events.emit("drag:ended",{})}getDragInfo(){return this.dragInfo}dispose(){this.endDrag()}}class Xs{constructor(t,e,i){this.trackIndex=t,this.clipIndex=e,this.newLength=i}name="resizeClip";originalLength;player;execute(t){if(!t)return;const e=t.getTrack(this.trackIndex);if(!e){console.warn(`Invalid track index: ${this.trackIndex}`);return}if(this.clipIndex<0||this.clipIndex>=e.length){console.warn(`Invalid clip index: ${this.clipIndex} for track ${this.trackIndex}`);return}this.player=e[this.clipIndex],this.originalLength=this.player.clipConfiguration.length,this.player.clipConfiguration.length=this.newLength,this.player.reconfigureAfterRestore(),this.player.draw(),t.updateDuration(),t.emitEvent("clip:updated",{previous:{clip:{...this.player.clipConfiguration,length:this.originalLength},trackIndex:this.trackIndex,clipIndex:this.clipIndex},current:{clip:this.player.clipConfiguration,trackIndex:this.trackIndex,clipIndex:this.clipIndex}})}undo(t){!t||!this.player||this.originalLength===void 0||(this.player.clipConfiguration.length=this.originalLength,this.player.reconfigureAfterRestore(),this.player.draw(),t.updateDuration(),t.emitEvent("clip:updated",{previous:{clip:{...this.player.clipConfiguration,length:this.newLength},trackIndex:this.trackIndex,clipIndex:this.clipIndex},current:{clip:this.player.clipConfiguration,trackIndex:this.trackIndex,clipIndex:this.clipIndex}}))}}class js{timeline;thresholds;resizeInfo=null;constructor(t,e){this.timeline=t,this.thresholds=e}activate(){}deactivate(){this.endResize()}isOnClipRightEdge(t,e){const i=this.timeline.getVisualTracks()[t.trackIndex];if(!i)return!1;const s=i.getClip(t.clipIndex);if(!s)return!1;const a=s.getContainer().getBounds(),o=a.x+a.width,l=Math.abs(e.global.x-o),c=this.getResizeThreshold();return l<=c}startResize(t,e){const i=this.timeline.getClipData(t.trackIndex,t.clipIndex);if(!i)return!1;this.resizeInfo={trackIndex:t.trackIndex,clipIndex:t.clipIndex,originalLength:i.length||0,startX:e.global.x},this.timeline.getPixiApp().canvas.style.cursor="ew-resize";const s=this.timeline.getVisualTracks()[t.trackIndex];if(s){const n=s.getClip(t.clipIndex);n&&n.setResizing(!0)}return this.timeline.getEdit().events.emit("resize:started",this.resizeInfo),!0}updateResize(t){if(!this.resizeInfo)return;const e=t.global.x-this.resizeInfo.startX,i=this.timeline.getOptions().pixelsPerSecond||50,s=e/i,n=Math.max(.1,this.resizeInfo.originalLength+s),a=this.timeline.getVisualTracks()[this.resizeInfo.trackIndex];if(a){const o=a.getClip(this.resizeInfo.clipIndex);if(o){const l=n*i;o.setPreviewWidth(l),this.timeline.getEdit().events.emit("resize:updated",{width:l})}}}completeResize(t){if(!this.resizeInfo)return;const e=t.global.x-this.resizeInfo.startX,i=this.timeline.getOptions().pixelsPerSecond||50,s=e/i,n=Math.max(.1,this.resizeInfo.originalLength+s),a=this.timeline.getVisualTracks()[this.resizeInfo.trackIndex];if(a){const o=a.getClip(this.resizeInfo.clipIndex);o&&(o.setResizing(!1),o.setPreviewWidth(null))}if(Math.abs(n-this.resizeInfo.originalLength)>.01){const o=new Xs(this.resizeInfo.trackIndex,this.resizeInfo.clipIndex,n);this.timeline.getEdit().executeEditCommand(o),this.timeline.getEdit().events.emit("resize:ended",{newLength:n})}this.endResize()}getCursorForPosition(t,e){return t&&this.isOnClipRightEdge(t,e)?"ew-resize":""}getResizeThreshold(){const{trackHeight:t}=this.timeline.getLayout();return Math.max(this.thresholds.resize.min,Math.min(this.thresholds.resize.max,t*this.thresholds.resize.ratio))}endResize(){this.resizeInfo=null,this.timeline.getPixiApp().canvas.style.cursor="default"}getResizeInfo(){return this.resizeInfo}dispose(){this.endResize()}}class qs{timeline;thresholds;constructor(t,e){this.timeline=t,this.thresholds=e}getAllSnapPoints(t,e){const i=[];this.timeline.getVisualTracks().forEach((a,o)=>{a.getClips().forEach((c,h)=>{if(o===t&&h===e)return;const p=c.getClipConfig();p&&(i.push({time:p.start||0,type:"clip-start",trackIndex:o,clipIndex:h}),i.push({time:(p.start||0)+(p.length||0),type:"clip-end",trackIndex:o,clipIndex:h}))})});const n=this.timeline.getPlayheadTime();return i.push({time:n,type:"playhead"}),i}getTrackSnapPoints(t,e){return this.getAllSnapPoints(t,e).filter(i=>i.trackIndex===void 0||i.trackIndex===t)}calculateSnapPosition(t,e,i,s){const n=this.timeline.getOptions().pixelsPerSecond||50,a=this.thresholds.snap.pixels/n,o=this.getTrackSnapPoints(e,s);let l=null;for(const c of o){const h=Math.abs(t-c.time);h<a&&(!l||h<l.distance)&&(l={time:c.time,type:c.type,distance:h});const p=Math.abs(t+i-c.time);p<a&&(!l||p<l.distance)&&(l={time:c.time-i,type:c.type,distance:p})}return l?{time:l.time,snapped:!0,snapType:l.type}:{time:t,snapped:!1}}findAlignedElements(t,e,i,s){const a=t+e,o=new Map;this.timeline.getVisualTracks().forEach((c,h)=>{c.getClips().forEach((p,f)=>{if(h===i&&f===s)return;const v=p.getClipConfig();if(!v)return;const I=v.start||0,b=I+(v.length||0);[{time:I,aligns:[t,a]},{time:b,aligns:[t,a]}].forEach(({time:O,aligns:N})=>{N.some(lt=>Math.abs(lt-O)<.1)&&(o.has(O)||o.set(O,{tracks:new Set,isPlayhead:!1}),o.get(O).tracks.add(h))})})});const l=this.timeline.getPlayheadTime();return(Math.abs(t-l)<.1||Math.abs(a-l)<.1)&&(o.has(l)||o.set(l,{tracks:new Set,isPlayhead:!0}),o.get(l).isPlayhead=!0),Array.from(o.entries()).map(([c,h])=>({time:c,tracks:Array.from(h.tracks).concat(i),isPlayhead:h.isPlayhead}))}}class Qs{timeline;graphics=new Map;constructor(t){this.timeline=t}showDropZone(t){this.hideDropZone();const e=new d.Graphics,i=this.timeline.getLayout(),s=this.timeline.getExtendedTimelineWidth(),n=t.position*i.trackHeight,o=this.timeline.getTheme().timeline.trackInsertion;e.setStrokeStyle({width:4,color:o,alpha:.8}),e.moveTo(0,n),e.lineTo(s,n),e.stroke(),e.setStrokeStyle({width:8,color:o,alpha:.3}),e.moveTo(0,n),e.lineTo(s,n),e.stroke(),this.timeline.getContainer().addChild(e),this.graphics.set("dropZone",e)}hideDropZone(){this.hideGraphics("dropZone")}showSnapGuidelines(t){this.hideSnapGuidelines();const e=new d.Graphics,i=this.timeline.getLayout(),s=this.timeline.getTheme();t.forEach(({time:n,tracks:a,isPlayhead:o})=>{const l=i.getXAtTime(n),c=Math.min(...a),h=Math.max(...a),p=c*i.trackHeight,f=(h+1)*i.trackHeight,v=o?s.timeline.playhead:s.timeline.snapGuide;e.setStrokeStyle({width:3,color:v,alpha:.3}),e.moveTo(l,p),e.lineTo(l,f),e.stroke(),e.setStrokeStyle({width:1,color:v,alpha:.8}),e.moveTo(l,p),e.lineTo(l,f),e.stroke()}),this.timeline.getContainer().addChild(e),this.graphics.set("snapGuidelines",e)}hideSnapGuidelines(){this.hideGraphics("snapGuidelines")}showTargetTrack(t){this.hideTargetTrack();const e=new d.Graphics,i=this.timeline.getLayout(),s=this.timeline.getExtendedTimelineWidth(),n=t*i.trackHeight,a=i.trackHeight,l=this.timeline.getTheme().timeline.dropZone;e.rect(0,n,s,a),e.fill({color:l,alpha:.1}),e.setStrokeStyle({width:1,color:l,alpha:.3}),e.rect(0,n,s,a),e.stroke(),this.timeline.getContainer().addChild(e),this.graphics.set("targetTrack",e)}hideTargetTrack(){this.hideGraphics("targetTrack")}hideAll(){this.graphics.forEach((t,e)=>this.hideGraphics(e))}hideGraphics(t){const e=this.graphics.get(t);e&&(e.clear(),e.parent&&e.parent.removeChild(e),e.destroy(),this.graphics.delete(t))}dispose(){this.hideAll(),this.graphics.clear()}}class Js{timeline;state={type:"idle"};abortController;dragHandler;resizeHandler;snapManager;collisionDetector;visualFeedback;thresholds={drag:{base:3,small:2},resize:{min:12,max:20,ratio:.4},dropZone:{ratio:.15},snap:{pixels:10,time:.1}};constructor(t,e){if(this.timeline=t,e){const i=structuredClone(this.thresholds);e.drag&&Object.assign(i.drag,e.drag),e.resize&&Object.assign(i.resize,e.resize),e.dropZone&&Object.assign(i.dropZone,e.dropZone),e.snap&&Object.assign(i.snap,e.snap),this.thresholds=i}this.snapManager=new qs(t,this.thresholds),this.collisionDetector=new Ks(t),this.visualFeedback=new Qs(t),this.dragHandler=new Ys(t,this.thresholds,this.snapManager,this.collisionDetector,this.visualFeedback),this.resizeHandler=new js(t,this.thresholds)}activate(){this.abortController=new AbortController,this.setupEventListeners(),this.dragHandler.activate(),this.resizeHandler.activate()}deactivate(){this.abortController&&(this.abortController.abort(),this.abortController=void 0),this.resetState(),this.dragHandler.deactivate(),this.resizeHandler.deactivate()}setupEventListeners(){const t=this.timeline.getPixiApp();t.stage.interactive=!0,t.stage.on("pointerdown",this.handlePointerDown.bind(this),{signal:this.abortController?.signal}),t.stage.on("pointermove",this.handlePointerMove.bind(this),{signal:this.abortController?.signal}),t.stage.on("pointerup",this.handlePointerUp.bind(this),{signal:this.abortController?.signal}),t.stage.on("pointerupoutside",this.handlePointerUp.bind(this),{signal:this.abortController?.signal})}handlePointerDown(t){const e=t.target;if(e.label){const i=this.parseClipLabel(e.label);if(i){if(this.resizeHandler.isOnClipRightEdge(i,t)){if(this.resizeHandler.startResize(i,t)){const s=this.resizeHandler.getResizeInfo();s&&(this.state={type:"resizing",resizeInfo:s})}return}this.state={type:"selecting",startPos:{x:t.global.x,y:t.global.y},clipInfo:i},this.timeline.getPixiApp().canvas.style.cursor="grab";return}}this.timeline.getEdit().clearSelection()}handlePointerMove(t){switch(this.state.type){case"selecting":this.handleSelectingMove(t);break;case"dragging":this.timeline.getPixiApp().canvas.style.cursor="grabbing",this.dragHandler.updateDrag(t);break;case"resizing":this.timeline.getPixiApp().canvas.style.cursor="ew-resize",this.resizeHandler.updateResize(t);break;case"idle":this.updateCursorForPosition(t);break}}handlePointerUp(t){switch(this.state.type){case"selecting":this.timeline.getEdit().selectClip(this.state.clipInfo.trackIndex,this.state.clipInfo.clipIndex);break;case"dragging":this.dragHandler.completeDrag(t);break;case"resizing":this.resizeHandler.completeResize(t);break}this.resetState()}handleSelectingMove(t){if(this.state.type!=="selecting")return;const e={x:t.global.x,y:t.global.y};if(this.dragHandler.canStartDrag(this.state.startPos,e)&&this.dragHandler.startDrag(this.state.clipInfo,t)){const i=this.dragHandler.getDragInfo();i&&(this.state={type:"dragging",dragInfo:i})}}updateCursorForPosition(t){const e=t.target;if(e.label){const i=this.parseClipLabel(e.label);if(i){const s=this.resizeHandler.getCursorForPosition(i,t);if(s){this.timeline.getPixiApp().canvas.style.cursor=s;return}this.timeline.getPixiApp().canvas.style.cursor="grab";return}}this.timeline.getPixiApp().canvas.style.cursor="default"}parseClipLabel(t){if(!t?.startsWith("clip-"))return null;const e=t.split("-");if(e.length!==3)return null;const i=parseInt(e[1],10),s=parseInt(e[2],10);return Number.isNaN(i)||Number.isNaN(s)?null:{trackIndex:i,clipIndex:s}}resetState(){this.state={type:"idle"},this.visualFeedback.hideAll(),this.timeline.getPixiApp().canvas.style.cursor="default"}dispose(){this.deactivate(),this.dragHandler.dispose(),this.resizeHandler.dispose(),this.visualFeedback.dispose()}}class tn{constructor(t,e,i,s,n){this.container=t,this.layout=e,this.getPixelsPerSecond=i,this.getTrackHeight=s,this.getVisualTracks=n}dragPreviewContainer=null;dragPreviewGraphics=null;draggedClipInfo=null;showDragPreview(t,e,i){if(!i)return;this.draggedClipInfo={trackIndex:t,clipIndex:e,clipConfig:i},this.dragPreviewContainer=new d.Container,this.dragPreviewGraphics=new d.Graphics,this.dragPreviewContainer.addChild(this.dragPreviewGraphics),this.container.addChild(this.dragPreviewContainer),this.getVisualTracks()[t]?.getClip(e)?.setDragging(!0),this.drawDragPreview(t,i.start||0)}drawDragPreview(t,e){if(!this.dragPreviewContainer||!this.dragPreviewGraphics||!this.draggedClipInfo)return;const{clipConfig:i}=this.draggedClipInfo,s=this.layout.getXAtTime(e),n=t*this.layout.trackHeight,a=(i.length||0)*this.getPixelsPerSecond();this.dragPreviewGraphics.clear(),this.dragPreviewGraphics.roundRect(0,0,a,this.getTrackHeight(),4),this.dragPreviewGraphics.fill({color:9342611,alpha:.6}),this.dragPreviewGraphics.stroke({width:2,color:65280}),this.dragPreviewContainer.position.set(s,n)}drawDragPreviewAtPosition(t,e,i){if(!this.dragPreviewContainer||!this.dragPreviewGraphics||!this.draggedClipInfo)return;const{clipConfig:s}=this.draggedClipInfo,n=this.layout.getXAtTime(t),a=(s.length||0)*this.getPixelsPerSecond(),o=this.getTrackHeight();this.dragPreviewGraphics.clear(),this.dragPreviewGraphics.roundRect(0,0,a,o,4),this.dragPreviewGraphics.fill({color:9342611,alpha:.6});const l=i*this.layout.trackHeight,h=Math.abs(e-l)<5?65280:16755200;this.dragPreviewGraphics.stroke({width:2,color:h}),this.dragPreviewContainer.position.set(n,e)}hideDragPreview(){this.dragPreviewContainer&&(this.dragPreviewContainer.destroy({children:!0}),this.dragPreviewContainer=null,this.dragPreviewGraphics=null),this.draggedClipInfo&&(this.getVisualTracks()[this.draggedClipInfo.trackIndex]?.getClip(this.draggedClipInfo.clipIndex)?.setDragging(!1),this.draggedClipInfo=null)}hideDragGhost(){this.dragPreviewContainer&&(this.dragPreviewContainer.visible=!1)}showDragGhost(t,e,i){!this.dragPreviewContainer||!this.draggedClipInfo||(this.dragPreviewContainer.visible=!0,i!==void 0?this.drawDragPreviewAtPosition(e,i,t):this.drawDragPreview(t,e))}getDraggedClipInfo(){return this.draggedClipInfo}hasActivePreview(){return this.dragPreviewContainer!==null}dispose(){this.hideDragPreview()}}class en{constructor(t,e,i,s,n){this.layout=t,this.trackLayer=e,this.overlayLayer=i,this.entityContainer=s,this.onRender=n}scrollX=0;scrollY=0;zoomLevel=1;viewport;rulerViewport;playheadContainer;async setupViewport(){this.rulerViewport=new d.Container,this.rulerViewport.label="ruler-viewport",this.overlayLayer.addChild(this.rulerViewport),this.playheadContainer=new d.Container,this.playheadContainer.label="playhead-container",this.overlayLayer.addChild(this.playheadContainer),this.viewport=new d.Container,this.viewport.label="viewport",this.trackLayer.addChild(this.viewport),this.viewport.addChild(this.entityContainer)}updateViewportTransform(){const t=this.layout.calculateViewportPosition(this.scrollX,this.scrollY);this.viewport.position.set(t.x,t.y),this.viewport.scale.set(this.zoomLevel,this.zoomLevel),this.rulerViewport.position.x=t.x,this.rulerViewport.scale.x=this.zoomLevel,this.playheadContainer.position.x=t.x,this.playheadContainer.scale.x=this.zoomLevel}setScroll(t,e){this.scrollX=t,this.scrollY=e,this.updateViewportTransform(),this.onRender()}setZoom(t){this.zoomLevel=Math.max(.1,Math.min(10,t)),this.updateViewportTransform(),this.onRender()}getViewport(){return{x:this.scrollX,y:this.scrollY,zoom:this.zoomLevel}}getMainViewport(){return this.viewport}getRulerViewport(){return this.rulerViewport}getPlayheadContainer(){return this.playheadContainer}}const F={MIN_WIDTH:50,PADDING:4,DEFAULT_ALPHA:1,DRAG_OPACITY:.6,RESIZE_OPACITY:.9,BORDER_WIDTH:2,CORNER_RADIUS:4,SELECTED_BORDER_MULTIPLIER:2,TEXT_FONT_SIZE:12,TEXT_TRUNCATE_SUFFIX_LENGTH:3},zt={PADDING:2,LABEL_PADDING:8,DEFAULT_OPACITY:.8,BORDER_WIDTH:1},G={TOOLBAR_HEIGHT_RATIO:.12,RULER_HEIGHT_RATIO:.133,TOOLBAR_HEIGHT_DEFAULT:36,RULER_HEIGHT_DEFAULT:40,TRACK_HEIGHT_DEFAULT:80,BORDER_WIDTH:2,CORNER_RADIUS:4,CLIP_PADDING:4,LABEL_PADDING:8,TRACK_PADDING:2,MIN_CLIP_WIDTH:50};function se(r){const t=r.split("/");return t[t.length-1]||r}function sn(r){switch(r.type){case"video":return r.src?se(r.src):"Video";case"audio":return r.src?se(r.src):"Audio";case"image":return r.src?se(r.src):"Image";case"text":return r.text||"Text";case"shape":return r.shape||"Shape";case"html":return"HTML";case"luma":return r.src?se(r.src):"Luma";default:return"Unknown Asset"}}class nn extends nt{clipConfig;options;graphics;background;text;selectionRenderer;lastGlobalX=-1;lastGlobalY=-1;visualState={mode:"normal"};CLIP_PADDING=F.PADDING;BORDER_WIDTH=F.BORDER_WIDTH;get CORNER_RADIUS(){return this.options.theme.timeline.clips.radius||F.CORNER_RADIUS}constructor(t,e){super(),this.clipConfig=t,this.options=e,this.selectionRenderer=e.selectionRenderer,this.graphics=new d.Graphics,this.background=new d.Graphics,this.text=new d.Text,this.setupContainer()}async load(){this.setupGraphics(),this.updateVisualState()}setupContainer(){const t=this.getContainer();t.label=`clip-${this.options.trackIndex}-${this.options.clipIndex}`,t.interactive=!0,t.cursor="pointer",t.addChild(this.background),t.addChild(this.graphics),t.addChild(this.text)}setupGraphics(){this.text.style=new d.TextStyle({fontSize:F.TEXT_FONT_SIZE,fill:this.options.theme.timeline.toolbar.text,fontWeight:"bold",wordWrap:!1,fontFamily:"Arial, sans-serif"}),this.text.anchor.set(0,0),this.text.x=this.CLIP_PADDING,this.text.y=this.CLIP_PADDING}updateFromConfig(t){this.clipConfig=t,this.updateVisualState()}updateVisualState(){this.updatePosition(),this.updateAppearance(),this.updateSize(),this.updateText()}setVisualState(t){this.visualState={...this.visualState,...t},this.updateVisualState()}updatePosition(){const t=this.getContainer(),e=this.clipConfig.start||0;t.x=e*this.options.pixelsPerSecond,t.y=0}updateSize(){const t=this.getEffectiveWidth(),e=this.options.trackHeight;this.drawClipBackground(t,e),this.drawClipBorder(t,e)}getEffectiveWidth(){if(this.visualState.previewWidth!==void 0)return this.visualState.previewWidth;const e=(this.clipConfig.length||0)*this.options.pixelsPerSecond;return Math.max(F.MIN_WIDTH,e)}drawClipBackground(t,e){const i=this.getClipColor(),s=this.getStateStyles();this.background.clear(),this.background.roundRect(0,0,t,e,this.CORNER_RADIUS),this.background.fill({color:i,alpha:s.alpha})}drawClipBorder(t,e){const i=this.getStateStyles(),s=this.BORDER_WIDTH;this.graphics.clear(),this.graphics.roundRect(0,0,t,e,this.CORNER_RADIUS),this.graphics.stroke({width:s,color:i.borderColor}),this.updateSelectionState(t,e)}updateSelectionState(t,e){if(!this.selectionRenderer)return;const i=this.visualState.mode==="selected",s=this.getClipId();if(!i){this.selectionRenderer.clearSelection(s);return}const a=this.getContainer().toGlobal(new d.Point(0,0)),l=this.selectionRenderer.getOverlay().toLocal(a);this.selectionRenderer.renderSelection(s,{x:l.x,y:l.y,width:t,height:e,cornerRadius:this.CORNER_RADIUS,borderWidth:this.BORDER_WIDTH},i)}getClipColor(){const t=this.clipConfig.asset?.type,e=this.options.theme.timeline.clips;switch(t){case"video":return e.video;case"audio":return e.audio;case"image":return e.image;case"text":return e.text;case"shape":return e.shape;case"html":return e.html;case"luma":return e.luma;default:return e.default}}updateAppearance(){const t=this.getContainer();t.alpha=this.visualState.mode==="dragging"?F.DRAG_OPACITY:F.DEFAULT_ALPHA}updateText(){const t=this.clipConfig.asset?sn(this.clipConfig.asset):"Clip";this.text.text=t;const i=(this.clipConfig.length||0)*this.options.pixelsPerSecond-this.CLIP_PADDING*2;if(this.text.width>i){const s=i/this.text.width,n=Math.floor(t.length*s)-F.TEXT_TRUNCATE_SUFFIX_LENGTH;this.text.text=`${t.substring(0,Math.max(1,n))}...`}}getStateStyles(){const{theme:t}=this.options;switch(this.visualState.mode){case"dragging":return{alpha:F.DRAG_OPACITY,borderColor:t.timeline.tracks.border};case"resizing":return{alpha:F.RESIZE_OPACITY,borderColor:t.timeline.dropZone};case"selected":return{alpha:F.DEFAULT_ALPHA,borderColor:t.timeline.clips.selected};default:return{alpha:F.DEFAULT_ALPHA,borderColor:t.timeline.tracks.border}}}setSelected(t){this.setVisualState({mode:t?"selected":"normal"})}setDragging(t){this.setVisualState({mode:t?"dragging":"normal"})}setResizing(t){this.setVisualState({mode:t?"resizing":"normal",...t?{}:{previewWidth:void 0}})}setPreviewWidth(t){this.setVisualState({previewWidth:t||void 0})}setPixelsPerSecond(t){if(this.updateOptions({pixelsPerSecond:t}),this.visualState.mode==="selected"){const e=this.getEffectiveWidth(),i=this.options.trackHeight;this.updateSelectionState(e,i)}}updateOptions(t){this.options={...this.options,...t},this.updateVisualState()}getClipConfig(){return this.clipConfig}getOptions(){return{...this.options}}getVisualState(){return{...this.visualState}}getSelected(){return this.visualState.mode==="selected"}getClipId(){return`${this.options.trackIndex}-${this.options.clipIndex}`}getDragging(){return this.visualState.mode==="dragging"}getRightEdgeX(){const t=this.getEffectiveWidth();return(this.clipConfig.start||0)*this.options.pixelsPerSecond+t}update(t,e){if(this.visualState.mode==="selected"&&this.selectionRenderer){const s=this.getContainer().toGlobal(new d.Point(0,0));if(s.x!==this.lastGlobalX||s.y!==this.lastGlobalY){this.lastGlobalX=s.x,this.lastGlobalY=s.y;const n=this.getEffectiveWidth(),a=this.options.trackHeight;this.updateSelectionState(n,a)}}}draw(){}dispose(){this.selectionRenderer&&this.selectionRenderer.clearSelection(this.getClipId()),this.background.destroy(),this.graphics.destroy(),this.text.destroy()}}class rn extends nt{clips=[];options;background;TRACK_PADDING=zt.PADDING;LABEL_PADDING=zt.LABEL_PADDING;constructor(t){super(),this.options=t,this.background=new d.Graphics,this.setupContainer()}async load(){this.updateTrackAppearance()}setupContainer(){const t=this.getContainer();t.label=`track-${this.options.trackIndex}`,t.addChild(this.background),t.y=this.options.trackIndex*this.options.trackHeight}updateTrackAppearance(){const{width:t}=this.options,e=this.options.trackHeight,{theme:i}=this.options;this.background.clear();const s=this.options.trackIndex%2===0?i.timeline.tracks.surface:i.timeline.tracks.surfaceAlt;this.background.rect(0,0,t,e),this.background.fill({color:s,alpha:zt.DEFAULT_OPACITY}),this.background.rect(0,0,t,e),this.background.stroke({width:zt.BORDER_WIDTH,color:i.timeline.tracks.border}),this.background.moveTo(0,e-1),this.background.lineTo(t,e-1),this.background.stroke({width:zt.BORDER_WIDTH,color:i.timeline.divider})}rebuildFromTrackData(t,e){this.options={...this.options,pixelsPerSecond:e},this.clearAllClips(),t.clips&&t.clips.forEach((i,s)=>{const n={pixelsPerSecond:this.options.pixelsPerSecond,trackHeight:this.options.trackHeight,trackIndex:this.options.trackIndex,clipIndex:s,theme:this.options.theme,selectionRenderer:this.options.selectionRenderer},a=new nn(i,n);this.addClip(a)}),this.updateTrackAppearance()}async addClip(t){this.clips.push(t),await t.load(),this.getContainer().addChild(t.getContainer())}clearAllClips(){const t=this.getContainer();for(const e of this.clips)t.removeChild(e.getContainer()),e.dispose();this.clips=[]}removeClip(t){if(t>=0&&t<this.clips.length){const e=this.clips[t];this.getContainer().removeChild(e.getContainer()),e.dispose(),this.clips.splice(t,1)}}updateClip(t,e){t>=0&&t<this.clips.length&&this.clips[t].updateFromConfig(e)}setPixelsPerSecond(t){this.options={...this.options,pixelsPerSecond:t},this.clips.forEach(e=>{e.setPixelsPerSecond(t)})}setWidth(t){this.options={...this.options,width:t},this.updateTrackAppearance()}setTrackIndex(t){this.options={...this.options,trackIndex:t};const e=this.getContainer();e.y=t*this.options.trackHeight,this.clips.forEach((i,s)=>{i.updateOptions({trackIndex:t})})}selectClip(t){this.clearAllSelections(),t>=0&&t<this.clips.length&&this.clips[t].setSelected(!0)}clearAllSelections(){this.clips.forEach(t=>{t.setSelected(!1)})}getSelectedClip(){return this.clips.find(t=>t.getSelected())||null}getSelectedClipIndex(){return this.clips.findIndex(t=>t.getSelected())}getClips(){return[...this.clips]}getClip(t){return this.clips[t]||null}getClipCount(){return this.clips.length}getTrackIndex(){return this.options.trackIndex}getTrackHeight(){return this.options.trackHeight}getOptions(){return{...this.options}}findClipAtPosition(t,e){if(e<0||e>this.options.trackHeight)return null;const i=t/this.options.pixelsPerSecond;for(let s=0;s<this.clips.length;s+=1){const n=this.clips[s],a=n.getClipConfig(),o=a.start||0,l=o+(a.length||0);if(i>=o&&i<=l)return{clip:n,clipIndex:s}}return null}update(t,e){this.clips.forEach(i=>{i.update(t,e)})}draw(){this.clips.forEach(t=>{t.draw()})}dispose(){this.clearAllClips(),this.background.destroy()}}class an{constructor(t,e){this.overlay=t,this.theme=e}selectionGraphics=new Map;renderSelection(t,e,i){if(!i){this.clearSelection(t);return}let s=this.selectionGraphics.get(t);s||(s=new d.Graphics,s.label=`selection-border-${t}`,this.selectionGraphics.set(t,s),this.overlay.addChild(s)),s.position.set(e.x,e.y),s.clear(),s.setStrokeStyle({width:e.borderWidth*F.SELECTED_BORDER_MULTIPLIER,color:this.theme.timeline.clips.selected}),s.roundRect(0,0,e.width,e.height,e.cornerRadius),s.stroke()}clearSelection(t){const e=this.selectionGraphics.get(t);e&&(this.overlay.removeChild(e),e.destroy(),this.selectionGraphics.delete(t))}clearAllSelections(){this.selectionGraphics.forEach((t,e)=>{this.clearSelection(e)})}updateTheme(t){this.theme=t,this.selectionGraphics.forEach(e=>{e.clear()})}getOverlay(){return this.overlay}dispose(){this.clearAllSelections()}}class on{constructor(t,e,i,s,n){this.container=t,this.layout=e,this.theme=i,this.getPixelsPerSecond=s,this.getExtendedTimelineWidth=n,this.selectionOverlay=new d.Container,this.selectionOverlay.label="selectionOverlay",this.container.addChild(this.selectionOverlay),this.selectionRenderer=new an(this.selectionOverlay,this.theme)}visualTracks=[];selectionOverlay;selectionRenderer;async rebuildFromEdit(t,e){if(t?.timeline?.tracks){this.clearAllVisualState();for(let i=0;i<t.timeline.tracks.length;i+=1){const s=t.timeline.tracks[i],n={pixelsPerSecond:e,trackHeight:this.layout.trackHeight,trackIndex:i,width:this.getExtendedTimelineWidth(),theme:this.theme,selectionRenderer:this.selectionRenderer},a=new rn(n);await a.load(),a.rebuildFromTrackData(s,e),this.container.addChild(a.getContainer()),this.visualTracks.push(a)}this.container.setChildIndex(this.selectionOverlay,this.container.children.length-1)}}clearAllVisualState(){this.visualTracks.forEach(t=>{this.container.removeChild(t.getContainer()),t.dispose()}),this.visualTracks=[],this.selectionRenderer.clearAllSelections()}updateVisualSelection(t,e){this.clearVisualSelection();const i=this.visualTracks[t];if(i){const s=i.getClip(e);s&&s.setSelected(!0)}}clearVisualSelection(){this.visualTracks.forEach(t=>{t.getClips().forEach(i=>{i.setSelected(!1)})})}findClipAtPosition(t,e){const i=Math.floor(e/this.layout.trackHeight);if(i<0||i>=this.visualTracks.length)return null;const s=this.visualTracks[i],n=e-i*this.layout.trackHeight,a=s.findClipAtPosition(t,n);return a?{trackIndex:i,clipIndex:a.clipIndex,clipConfig:a.clip.getClipConfig(),x:(a.clip.getClipConfig().start||0)*this.getPixelsPerSecond(),y:i*this.layout.trackHeight,width:(a.clip.getClipConfig().length||0)*this.getPixelsPerSecond(),height:this.layout.trackHeight}:null}updateTrackWidths(t){this.visualTracks.forEach(e=>{e.setWidth(t)})}getVisualTracks(){return this.visualTracks}updatePixelsPerSecond(t){this.visualTracks.forEach(e=>{e.setPixelsPerSecond(t)})}getSelectionOverlay(){return this.selectionOverlay}getSelectionRenderer(){return this.selectionRenderer}dispose(){this.clearAllVisualState(),this.selectionRenderer&&this.selectionRenderer.dispose(),this.selectionOverlay&&this.container&&(this.container.removeChild(this.selectionOverlay),this.selectionOverlay.destroy())}}class ln{constructor(t,e){this.edit=t,this.callbacks=e}setupEventListeners(){this.edit.events.on("timeline:updated",this.handleTimelineUpdated.bind(this)),this.edit.events.on("clip:updated",this.handleClipUpdated.bind(this)),this.edit.events.on("clip:selected",this.handleClipSelected.bind(this)),this.edit.events.on("selection:cleared",this.handleSelectionCleared.bind(this)),this.edit.events.on("drag:started",this.handleDragStarted.bind(this)),this.edit.events.on("drag:ended",this.handleDragEnded.bind(this)),this.edit.events.on("track:created",this.handleTrackCreated.bind(this))}async handleTimelineUpdated(t){await this.callbacks.onEditChange(t.current)}async handleClipUpdated(){await this.callbacks.onEditChange()}handleClipSelected(t){this.callbacks.onClipSelected(t.trackIndex,t.clipIndex)}handleSelectionCleared(){this.callbacks.onSelectionCleared()}handleDragStarted(t){this.callbacks.onDragStarted(t.trackIndex,t.clipIndex)}handleDragEnded(){this.callbacks.onDragEnded()}async handleTrackCreated(){await this.callbacks.onEditChange()}handleSeek(t){this.callbacks.onSeek(t.time*1e3)}dispose(){this.edit.events.off("timeline:updated",this.handleTimelineUpdated.bind(this)),this.edit.events.off("clip:updated",this.handleClipUpdated.bind(this)),this.edit.events.off("clip:selected",this.handleClipSelected.bind(this)),this.edit.events.off("selection:cleared",this.handleSelectionCleared.bind(this)),this.edit.events.off("drag:started",this.handleDragStarted.bind(this)),this.edit.events.off("drag:ended",this.handleDragEnded.bind(this)),this.edit.events.off("track:created",this.handleTrackCreated.bind(this))}}class cn{constructor(t,e){this.options=t,this.onUpdate=e}app;trackLayer;overlayLayer;animationFrameId=null;async initializePixiApp(){this.app=new d.Application,await this.app.init({width:this.options.width,height:this.options.height,backgroundColor:this.options.backgroundColor,antialias:this.options.antialias,resolution:this.options.resolution,autoDensity:!0,preference:"webgl"});const t=document.querySelector("[data-shotstack-timeline]");if(!t)throw new Error("Timeline container element [data-shotstack-timeline] not found");t.appendChild(this.app.canvas)}async setupRenderLayers(){this.trackLayer=new d.Container,this.overlayLayer=new d.Container,this.trackLayer.label="track-layer",this.overlayLayer.label="overlay-layer",this.app.stage.addChild(this.trackLayer),this.app.stage.addChild(this.overlayLayer)}startAnimationLoop(){let t=performance.now();const e=i=>{const s=i-t;t=i;const n=s/16.667;this.onUpdate(n,s),this.draw(),this.animationFrameId=requestAnimationFrame(e)};this.animationFrameId=requestAnimationFrame(e)}draw(){this.app.render()}render(){this.app.render()}updateBackgroundColor(t){this.app&&(this.app.renderer.background.color=t)}getApp(){return this.app}getStage(){return this.app.stage}getTrackLayer(){return this.trackLayer}getOverlayLayer(){return this.overlayLayer}dispose(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.app&&this.app.destroy(!0)}}const St={RULER:{DEFAULT_HEIGHT:40,LABEL_FONT_SIZE:10,LABEL_PADDING_X:2},PLAYHEAD:{LINE_WIDTH:2},SCROLL:{HORIZONTAL_SPEED:2,VERTICAL_SPEED:.5}};class ii extends nt{events;rulerContainer;rulerBackground;timeMarkers;timeLabels;pixelsPerSecond;timelineDuration;rulerHeight;theme;constructor(t){super(),this.events=new Mt,this.pixelsPerSecond=t.pixelsPerSecond,this.timelineDuration=t.timelineDuration,this.rulerHeight=t.rulerHeight??St.RULER.DEFAULT_HEIGHT,this.theme=t.theme,this.rulerContainer=new d.Container,this.rulerBackground=new d.Graphics,this.timeMarkers=new d.Graphics,this.timeLabels=new d.Container}async load(){this.setupRuler(),this.draw()}setupRuler(){this.rulerContainer.label="ruler",this.rulerContainer.addChild(this.rulerBackground),this.rulerContainer.addChild(this.timeMarkers),this.rulerContainer.addChild(this.timeLabels),this.rulerContainer.eventMode="static",this.rulerContainer.cursor="pointer",this.rulerContainer.on("pointerdown",this.onRulerPointerDown.bind(this)),this.getContainer().addChild(this.rulerContainer)}drawRulerBackground(){this.rulerBackground.clear();const t=this.calculateRulerWidth(),e=this.theme?.timeline.ruler.background||4210752,i=this.theme?.timeline.tracks.border||6316128;this.rulerBackground.rect(0,0,t,this.rulerHeight),this.rulerBackground.fill(e),this.rulerBackground.rect(0,this.rulerHeight-1,t,1),this.rulerBackground.fill(i)}drawTimeMarkers(){this.timeMarkers.clear();const t=this.getTimeInterval(),e=this.getVisibleDuration(),i=this.theme?.timeline.ruler.markers||6710886,s=this.rulerHeight*.5;let n=4;t===10?n=9:(t===30||t===60)&&(n=5);const a=t/(n+1);for(let o=0;o<=e;o+=t)for(let l=1;l<=n;l+=1){const c=o+l*a;if(c<=e){const h=c*this.pixelsPerSecond;this.timeMarkers.circle(h,s,1.5),this.timeMarkers.fill(i)}}}drawTimeLabels(){this.timeLabels.removeChildren();const t=this.getTimeInterval(),e=this.getVisibleDuration(),i=this.theme?.timeline.ruler.text||16777215,s={fontSize:St.RULER.LABEL_FONT_SIZE,fill:i,fontFamily:"Arial"};for(let n=0;n<=e;n+=t){const a=new d.Text({text:this.formatTime(n),style:s}),o=n*this.pixelsPerSecond;n===0?(a.anchor.set(0,.5),a.x=o+St.RULER.LABEL_PADDING_X):(a.anchor.set(.5,.5),a.x=o),a.y=this.rulerHeight*.5,this.timeLabels.addChild(a)}}onRulerPointerDown(t){const e=this.rulerContainer.toLocal(t.global),i=Math.max(0,e.x/this.pixelsPerSecond);this.events.emit("ruler:seeked",{time:i})}updateRuler(t,e){this.pixelsPerSecond=t,this.timelineDuration=e,this.draw()}update(t,e){}draw(){this.drawRulerBackground(),this.drawTimeMarkers(),this.drawTimeLabels()}dispose(){this.timeLabels.removeChildren(),this.rulerContainer.removeChildren(),this.events.clear("*")}getViewportWidth(){return this.getContainer().parent?.width||800}calculateRulerWidth(){const t=this.timelineDuration*this.pixelsPerSecond;return Math.max(t,this.getViewportWidth())}getVisibleDuration(){return Math.max(this.timelineDuration,this.getViewportWidth()/this.pixelsPerSecond)}getTimeInterval(){const t=[1,5,10,30,60,120,300,600],e=80;for(const i of t)if(i*this.pixelsPerSecond>=e)return i;return Math.ceil(this.getVisibleDuration()/10)}formatTime(t){if(t===0)return"0s";const e=Math.floor(t/60),i=t%60;if(t<60)return`${t}s`;if(i===0)return`${e}m`;const s=i.toString().padStart(2,"0");return`${e}:${s}`}}class si extends nt{constructor(t){super(),this.options=t,this.graphics=new d.Graphics}events=new Mt;graphics;currentTime=0;isDragging=!1;async load(){this.setupPlayhead(),this.draw()}setupPlayhead(){this.graphics.label="playhead",this.graphics.eventMode="static",this.graphics.cursor="pointer",this.graphics.on("pointerdown",this.onPointerDown.bind(this)).on("pointermove",this.onPointerMove.bind(this)).on("pointerup",this.onPointerUp.bind(this)).on("pointerupoutside",this.onPointerUp.bind(this)),this.getContainer().addChild(this.graphics)}drawPlayhead(){const t=this.currentTime*this.options.pixelsPerSecond,e=this.options.theme?.timeline.playhead??16729156,i=St.PLAYHEAD.LINE_WIDTH,s=t+i/2;this.graphics.clear(),this.graphics.fill(e),this.graphics.rect(t,0,i,this.options.timelineHeight);const n=8;this.graphics.moveTo(s,10),this.graphics.lineTo(s-n,0),this.graphics.lineTo(s+n,0),this.graphics.closePath(),this.graphics.fill()}onPointerDown(t){this.isDragging=!0,this.graphics.cursor="grabbing",this.updateTimeFromPointer(t)}onPointerMove(t){this.isDragging&&this.updateTimeFromPointer(t)}onPointerUp(){this.isDragging=!1,this.graphics.cursor="pointer"}updateTimeFromPointer(t){const e=this.graphics.parent.toLocal(t.global),i=Math.max(0,e.x/this.options.pixelsPerSecond);this.setTime(i),this.events.emit("playhead:seeked",{time:i})}setTime(t){this.currentTime=t,this.draw(),this.events.emit("playhead:timeChanged",{time:t})}getTime(){return this.currentTime}updatePlayhead(t,e){this.options.pixelsPerSecond=t,this.options.timelineHeight=e,this.draw()}update(){}draw(){this.drawPlayhead()}dispose(){this.graphics.removeAllListeners(),this.events.clear("*")}}class hn{events;timeline;abortController;scrollX=0;scrollY=0;constructor(t){this.events=new Mt,this.timeline=t.timeline}async initialize(){this.setupEventListeners()}setupEventListeners(){this.abortController=new AbortController;const{canvas:t}=this.timeline.getPixiApp();t.addEventListener("wheel",this.handleWheel.bind(this),{passive:!1,signal:this.abortController.signal})}handleWheel(t){if(t.preventDefault(),t.ctrlKey||t.metaKey){this.handleZoom(t);return}this.handleScroll(t)}handleZoom(t){const e=t.deltaY>0?"out":"in",i=this.timeline.getPlayheadTime(),s=this.timeline.getActualEditDuration();e==="in"?this.timeline.zoomIn():this.timeline.zoomOut();const n=this.timeline.getOptions().pixelsPerSecond||50,a=i*n,o=this.timeline.getOptions().width||800,c=this.timeline.timeRange.endTime*n,h=s*n,p=this.calculateZoomScrollPosition({playheadXAfterZoom:a,viewportWidth:o,contentWidth:c,maxPlayheadX:h,actualEditDuration:s,playheadTime:i});this.scrollX=p,this.timeline.setScroll(this.scrollX,this.scrollY);const f=a-p;this.events.emit("zoom",{pixelsPerSecond:n,focusX:f,focusTime:i})}handleScroll(t){let{deltaX:e}=t,{deltaY:i}=t;t.shiftKey&&(e=i,i=0);const s=St.SCROLL.HORIZONTAL_SPEED,n=St.SCROLL.VERTICAL_SPEED;this.scrollX+=e*s,this.scrollY+=i*n,this.scrollX=this.clampScrollX(this.scrollX),this.scrollY=this.clampScrollY(this.scrollY),this.timeline.setScroll(this.scrollX,this.scrollY),this.events.emit("scroll",{x:this.scrollX,y:this.scrollY})}setScroll(t,e){this.scrollX=this.clampScrollX(t),this.scrollY=this.clampScrollY(e),this.timeline.setScroll(this.scrollX,this.scrollY),this.events.emit("scroll",{x:this.scrollX,y:this.scrollY})}clampScrollX(t){const e=this.timeline.getExtendedTimelineWidth(),i=this.timeline.getOptions().width||0,s=Math.max(0,e-i);return Math.max(0,Math.min(t,s))}clampScrollY(t){const e=this.timeline.getLayout(),i=this.timeline.getVisualTracks().length,s=this.timeline.getOptions().height||0,n=Math.max(0,i*e.trackHeight-(s-e.rulerHeight));return Math.max(0,Math.min(t,n))}getScroll(){return{x:this.scrollX,y:this.scrollY}}calculateZoomScrollPosition(t){const{playheadXAfterZoom:e,viewportWidth:i,contentWidth:s,maxPlayheadX:n,actualEditDuration:a,playheadTime:o}=t,l=e-i/2,c=Math.max(0,s-i);let h;const p=l+i,f=Math.max(0,n-i);s<=i||l<0?h=0:p>n&&o<=a?h=Math.min(f,c):l>c?h=c:h=l;const v=e-h;return(v<0||v>i)&&(e>s-i?h=Math.max(0,e-i+50):h=Math.max(0,e-50),h=Math.max(0,Math.min(h,c))),h}dispose(){this.abortController&&(this.abortController.abort(),this.abortController=void 0),this.events.clear("*")}}const E={BUTTON_SIZE:24,BUTTON_HOVER_PADDING:4,BORDER_RADIUS:4,TEXT_SPACING:16,EDGE_MARGIN:10,FRAME_TIME_MS:16.67,ICON:{PLAY:{LEFT:6,TOP:4,RIGHT:18,MIDDLE:12,BOTTOM:20},PAUSE:{RECT1_X:6,RECT2_X:14,TOP:4,WIDTH:4,HEIGHT:16},FRAME_STEP:{TRIANGLE1:{BACK:{LEFT:11,RIGHT:3,MIDDLE:12},FORWARD:{LEFT:4,RIGHT:12,MIDDLE:12}},TRIANGLE2:{BACK:{LEFT:20,RIGHT:12,MIDDLE:12},FORWARD:{LEFT:13,RIGHT:21,MIDDLE:12}},TOP:4,BOTTOM:20}},CUT_BUTTON:{WIDTH:60,HEIGHT:24,FONT_SIZE:12},TIME_DISPLAY:{FONT_SIZE:14,FONT_FAMILY:"monospace"},HOVER_ANIMATION_ALPHA:1,ACTIVE_ANIMATION_ALPHA:.3,DIVIDER_ALPHA:.5};class ne{static createIcon(t,e,i){const s=i?i/E.BUTTON_SIZE:1;switch(t){case"play":return this.createPlayIcon(e,s);case"pause":return this.createPauseIcon(e,s);case"frame-back":return this.createFrameBackIcon(e,s);case"frame-forward":return this.createFrameForwardIcon(e,s);default:throw new Error(`Unknown icon type: ${t}`)}}static createPlayIcon(t,e=1){const i=new d.Graphics,{PLAY:s}=E.ICON;return i.fill({color:t.timeline.toolbar.icon}),i.moveTo(s.LEFT*e,s.TOP*e),i.lineTo(s.RIGHT*e,s.MIDDLE*e),i.lineTo(s.LEFT*e,s.BOTTOM*e),i.closePath(),i.fill(),i}static createPauseIcon(t,e=1){const i=new d.Graphics,{PAUSE:s}=E.ICON;return i.fill({color:t.timeline.toolbar.icon}),i.rect(s.RECT1_X*e,s.TOP*e,s.WIDTH*e,s.HEIGHT*e),i.rect(s.RECT2_X*e,s.TOP*e,s.WIDTH*e,s.HEIGHT*e),i.fill(),i}static createFrameBackIcon(t,e=1){const i=new d.Graphics,{FRAME_STEP:s}=E.ICON;return i.fill({color:t.timeline.toolbar.icon}),i.moveTo(s.TRIANGLE1.BACK.LEFT*e,s.TOP*e),i.lineTo(s.TRIANGLE1.BACK.RIGHT*e,s.TRIANGLE1.BACK.MIDDLE*e),i.lineTo(s.TRIANGLE1.BACK.LEFT*e,s.BOTTOM*e),i.closePath(),i.moveTo(s.TRIANGLE2.BACK.LEFT*e,s.TOP*e),i.lineTo(s.TRIANGLE2.BACK.RIGHT*e,s.TRIANGLE2.BACK.MIDDLE*e),i.lineTo(s.TRIANGLE2.BACK.LEFT*e,s.BOTTOM*e),i.closePath(),i.fill(),i}static createFrameForwardIcon(t,e=1){const i=new d.Graphics,{FRAME_STEP:s}=E.ICON;return i.fill({color:t.timeline.toolbar.icon}),i.moveTo(s.TRIANGLE1.FORWARD.LEFT*e,s.TOP*e),i.lineTo(s.TRIANGLE1.FORWARD.RIGHT*e,s.TRIANGLE1.FORWARD.MIDDLE*e),i.lineTo(s.TRIANGLE1.FORWARD.LEFT*e,s.BOTTOM*e),i.closePath(),i.moveTo(s.TRIANGLE2.FORWARD.LEFT*e,s.TOP*e),i.lineTo(s.TRIANGLE2.FORWARD.RIGHT*e,s.TRIANGLE2.FORWARD.MIDDLE*e),i.lineTo(s.TRIANGLE2.FORWARD.LEFT*e,s.BOTTOM*e),i.closePath(),i.fill(),i}static updateIconColor(t,e){const i=t.getBounds();t.clear(),t.position.set(i.x,i.y)}}class ni extends d.Container{background;hoverBackground;icon;alternateIcon;state={isHovering:!1,isPressed:!1,isActive:!1};size;theme;onClick;constructor(t){super(),this.size=t.size||E.BUTTON_SIZE,this.theme=t.theme,this.onClick=t.onClick,this.eventMode="static",this.cursor="pointer",this.background=new d.Graphics,this.addChild(this.background),this.hoverBackground=new d.Graphics,this.addChild(this.hoverBackground);const i=this.size*.6,s=(this.size-i)/2;t.iconType&&(this.icon=ne.createIcon(t.iconType,this.theme,i),this.icon.position.set(s,s),this.addChild(this.icon)),t.alternateIconType&&(this.alternateIcon=ne.createIcon(t.alternateIconType,this.theme,i),this.alternateIcon.position.set(s,s),this.alternateIcon.visible=!1,this.addChild(this.alternateIcon)),this.setupEventListeners(),this.updateVisuals()}setupEventListeners(){this.on("pointerdown",this.handlePointerDown,this),this.on("pointerup",this.handlePointerUp,this),this.on("pointerupoutside",this.handlePointerUp,this),this.on("pointerover",this.handlePointerOver,this),this.on("pointerout",this.handlePointerOut,this)}handlePointerDown(){this.state.isPressed=!0,this.updateVisuals()}handlePointerUp(){this.state.isPressed&&this.onClick(),this.state.isPressed=!1,this.updateVisuals()}handlePointerOver(){this.state.isHovering=!0,this.updateVisuals()}handlePointerOut(){this.state.isHovering=!1,this.state.isPressed=!1,this.updateVisuals()}updateVisuals(){const t=E.BUTTON_HOVER_PADDING,e=this.size/2;this.background.clear(),this.background.circle(e,e,e),this.background.fill({color:this.theme.timeline.toolbar.surface,alpha:.8}),this.hoverBackground.clear(),this.hoverBackground.circle(e,e,e+t),this.state.isPressed?this.hoverBackground.fill({color:this.theme.timeline.toolbar.active,alpha:E.ACTIVE_ANIMATION_ALPHA}):this.state.isHovering?this.hoverBackground.fill({color:this.theme.timeline.toolbar.hover,alpha:E.HOVER_ANIMATION_ALPHA}):this.hoverBackground.fill({color:this.theme.timeline.toolbar.hover,alpha:0})}setActive(t){this.state.isActive=t,this.icon&&this.alternateIcon&&(this.icon.visible=!t,this.alternateIcon.visible=t)}updateTheme(t){this.theme=t;const i=this.size*.6,s=(this.size-i)/2;if(this.icon){const n=this.getIconType(this.icon);n&&(this.removeChild(this.icon),this.icon=ne.createIcon(n,t,i),this.icon.position.set(s,s),this.addChild(this.icon))}if(this.alternateIcon){const n=this.getIconType(this.alternateIcon);n&&(this.removeChild(this.alternateIcon),this.alternateIcon=ne.createIcon(n,t,i),this.alternateIcon.position.set(s,s),this.alternateIcon.visible=this.state.isActive,this.addChild(this.alternateIcon))}this.updateVisuals()}getIconType(t){return null}destroy(){this.removeAllListeners(),super.destroy()}}class dn extends d.Container{edit;theme;toolbarHeight;frameBackButton;playPauseButton;frameForwardButton;constructor(t,e,i){super(),this.edit=t,this.theme=e,this.toolbarHeight=i||36,this.createButtons(),this.subscribeToEditEvents(),this.updatePlayPauseState()}createButtons(){const t=this.calculateButtonSizes(),e=(t.playButton-t.regularButton)/2,i=(s,n,a,o)=>new ni({iconType:s,onClick:n,tooltip:a,theme:this.theme,size:o});this.frameBackButton=i("frame-back",()=>this.handleFrameBack(),"Previous frame",t.regularButton),this.frameBackButton.position.set(0,e),this.playPauseButton=new ni({iconType:"play",alternateIconType:"pause",onClick:()=>this.handlePlayPause(),tooltip:"Play/Pause",theme:this.theme,size:t.playButton}),this.playPauseButton.position.set(t.regularButton+t.spacing,0),this.frameForwardButton=i("frame-forward",()=>this.handleFrameForward(),"Next frame",t.regularButton),this.frameForwardButton.position.set(t.regularButton+t.spacing+t.playButton+t.spacing,e),this.addChild(this.frameBackButton,this.playPauseButton,this.frameForwardButton)}calculateButtonSizes(){const t=Math.round(this.toolbarHeight*.5);return{regularButton:t,playButton:Math.round(t*1.5),spacing:Math.round(this.toolbarHeight*.15)}}handleFrameBack(){this.edit.seek(this.edit.playbackTime-E.FRAME_TIME_MS)}handlePlayPause(){this.edit.isPlaying?this.edit.pause():this.edit.play()}handleFrameForward(){this.edit.seek(this.edit.playbackTime+E.FRAME_TIME_MS)}subscribeToEditEvents(){this.edit.events.on("playback:play",this.updatePlayPauseState),this.edit.events.on("playback:pause",this.updatePlayPauseState)}updatePlayPauseState=()=>{this.playPauseButton.setActive(this.edit.isPlaying)};update(){}resize(t){}updateTheme(t){this.theme=t,this.frameBackButton.updateTheme(t),this.playPauseButton.updateTheme(t),this.frameForwardButton.updateTheme(t)}destroy(){this.edit.events.off("playback:play",this.updatePlayPauseState),this.edit.events.off("playback:pause",this.updatePlayPauseState),this.frameBackButton.destroy(),this.playPauseButton.destroy(),this.frameForwardButton.destroy(),super.destroy()}getWidth(){const t=this.calculateButtonSizes();return t.regularButton*2+t.playButton+t.spacing*2}}class un extends d.Container{edit;theme;timeText;formatOptions;constructor(t,e,i={}){super(),this.edit=t,this.theme=e,this.formatOptions={showMilliseconds:!1,showHours:!1,...i},this.createDisplay(),this.subscribeToEditEvents(),this.updateTimeDisplay()}createDisplay(){const t=new d.TextStyle({fontFamily:E.TIME_DISPLAY.FONT_FAMILY,fontSize:E.TIME_DISPLAY.FONT_SIZE,fill:this.theme.timeline.toolbar.text});this.timeText=new d.Text("0:00 / 0:00",t),this.timeText.anchor.set(0,.5),this.addChild(this.timeText)}subscribeToEditEvents(){this.edit.events.on("playback:time",this.updateTimeDisplay),this.edit.events.on("duration:changed",this.updateTimeDisplay)}updateTimeDisplay=()=>{const t=this.formatTime(this.edit.playbackTime/1e3),e=this.formatTime(this.edit.getTotalDuration()/1e3);this.timeText.text=`${t} / ${e}`};formatTime(t){const e=Math.floor(t/3600),i=Math.floor(t%3600/60),s=Math.floor(t%60),n=Math.floor(t%1*10);let a="";return this.formatOptions.showHours||e>0?a+=`${e}:${i.toString().padStart(2,"0")}`:a+=`${i}`,a+=`:${s.toString().padStart(2,"0")}`,this.formatOptions.showMilliseconds?a+=`.${n}`:a+=`.${n}`,a}update(){this.updateTimeDisplay()}resize(t){}updateTheme(t){this.theme=t,this.timeText.style.fill=t.timeline.toolbar.text}destroy(){this.edit.events.off("playback:time",this.updateTimeDisplay),this.edit.events.off("duration:changed",this.updateTimeDisplay),super.destroy()}getWidth(){return this.timeText.width}}class pn extends d.Container{edit;theme;cutButton;cutButtonBackground;cutButtonText;constructor(t,e){super(),this.edit=t,this.theme=e,this.createCutButton()}createCutButton(){this.cutButton=new d.Container,this.cutButton.eventMode="static",this.cutButton.cursor="pointer";const{WIDTH:t,HEIGHT:e,FONT_SIZE:i}=E.CUT_BUTTON;this.cutButtonBackground=new d.Graphics,this.cutButtonBackground.roundRect(0,0,t,e,E.BORDER_RADIUS),this.cutButtonBackground.fill({color:this.theme.timeline.toolbar.surface||4473924}),this.cutButtonBackground.stroke({color:this.theme.timeline.tracks.border||6710886,width:1}),this.cutButton.addChild(this.cutButtonBackground);const s=new d.TextStyle({fontFamily:"Arial",fontSize:i,fill:this.theme.timeline.toolbar.text||16777215});this.cutButtonText=new d.Text("SPLIT",s),this.cutButtonText.anchor.set(.5),this.cutButtonText.position.set(t/2,e/2),this.cutButton.addChild(this.cutButtonText),this.cutButton.on("click",this.handleCutClick,this),this.cutButton.on("pointerdown",this.handlePointerDown,this),this.cutButton.on("pointerover",this.handlePointerOver,this),this.cutButton.on("pointerout",this.handlePointerOut,this),this.addChild(this.cutButton)}handleCutClick=t=>{t.stopPropagation(),this.performCutClip()};handlePointerDown=t=>{t.stopPropagation(),this.updateButtonVisual(!0,!1)};handlePointerOver=()=>{this.updateButtonVisual(!1,!0)};handlePointerOut=()=>{this.updateButtonVisual(!1,!1)};updateButtonVisual(t,e){this.cutButtonBackground.clear(),this.cutButtonBackground.roundRect(0,0,E.CUT_BUTTON.WIDTH,E.CUT_BUTTON.HEIGHT,E.BORDER_RADIUS);let i=this.theme.timeline.toolbar.surface||4473924;const s=1;t?i=this.theme.timeline.toolbar.active||3355443:e&&(i=this.theme.timeline.toolbar.hover||5592405),this.cutButtonBackground.fill({color:i,alpha:s}),this.cutButtonBackground.stroke({color:this.theme.timeline.tracks.border||6710886,width:1})}performCutClip(){const t=this.edit.getSelectedClipInfo();if(!t)return;const{trackIndex:e,clipIndex:i}=t,s=this.edit.playbackTime/1e3;this.edit.splitClip(e,i,s)}update(){const t=this.edit.getSelectedClipInfo()!==null;this.cutButton.alpha=t?1:.5,this.cutButton.eventMode=t?"static":"none",this.cutButton.cursor=t?"pointer":"default"}resize(t){}updateTheme(t){this.theme=t,this.updateButtonVisual(!1,!1),this.cutButtonText.style.fill=t.timeline.toolbar.text||16777215}destroy(){this.cutButton.removeAllListeners(),super.destroy()}getWidth(){return E.CUT_BUTTON.WIDTH}}class fn{config;constructor(t,e){this.config={width:t,height:e,buttonSize:Math.round(e*.5),buttonSpacing:Math.round(e*.15),edgeMargin:E.EDGE_MARGIN}}getPlaybackControlsPosition(){const t=this.calculatePlaybackControlsWidth(),e=(this.config.width-t)/2,i=(this.config.height-this.getMaxButtonHeight())/2;return{x:e,y:i}}getMaxButtonHeight(){const t=this.config.buttonSize;return Math.round(t*1.5)}getTimeDisplayPosition(t){const i=(this.config.width-t)/2+t+E.TEXT_SPACING,s=this.config.height/2;return{x:i,y:s}}getEditControlsPosition(){const t=this.config.width-E.CUT_BUTTON.WIDTH-this.config.edgeMargin,e=(this.config.height-E.CUT_BUTTON.HEIGHT)/2;return{x:t,y:e}}calculatePlaybackControlsWidth(){const t=this.config.buttonSize,e=Math.round(t*1.5);return t*2+e+this.config.buttonSpacing*2}updateWidth(t){this.config.width=t}getConfig(){return{...this.config}}}class gn extends d.Container{constructor(t,e,i,s){super(),this.edit=t,this.theme=e,this.layout=i,this.toolbarWidth=s,this.toolbarHeight=i.toolbarHeight,this.position.set(0,i.toolbarY),this.toolbarLayout=new fn(s,this.toolbarHeight),this.createBackground(),this.createComponents(),this.positionComponents(),this.subscribeToEditEvents()}background;playbackControls;timeDisplay;editControls;toolbarLayout;toolbarWidth;toolbarHeight;get width(){return this.toolbarWidth}get height(){return this.toolbarHeight}createBackground(){this.background=new d.Graphics,this.drawBackground(),this.addChild(this.background)}drawBackground(){this.background.clear(),this.background.rect(0,0,this.toolbarWidth,this.toolbarHeight),this.background.fill({color:this.theme.timeline.toolbar.background}),this.background.setStrokeStyle({width:1,color:this.theme.timeline.toolbar.divider,alpha:E.DIVIDER_ALPHA}),this.background.moveTo(0,this.toolbarHeight-.5),this.background.lineTo(this.toolbarWidth,this.toolbarHeight-.5),this.background.stroke()}createComponents(){this.playbackControls=new dn(this.edit,this.theme,this.toolbarHeight),this.addChild(this.playbackControls),this.timeDisplay=new un(this.edit,this.theme),this.addChild(this.timeDisplay),this.editControls=new pn(this.edit,this.theme),this.addChild(this.editControls)}positionComponents(){const t=this.toolbarLayout.getPlaybackControlsPosition();this.playbackControls.position.set(t.x,t.y);const e=this.toolbarLayout.getTimeDisplayPosition(this.playbackControls.getWidth());this.timeDisplay.position.set(e.x,e.y);const i=this.toolbarLayout.getEditControlsPosition();this.editControls.position.set(i.x,i.y)}subscribeToEditEvents(){this.edit.events.on("clip:selected",this.updateEditControls),this.edit.events.on("selection:cleared",this.updateEditControls)}updateEditControls=()=>{this.editControls.update()};resize(t){this.toolbarWidth=t,this.toolbarLayout.updateWidth(t),this.drawBackground(),this.positionComponents(),this.playbackControls.resize(t),this.timeDisplay.resize(t),this.editControls.resize(t)}updateTheme(t){this.theme=t,this.drawBackground(),this.playbackControls.updateTheme(t),this.timeDisplay.updateTheme(t),this.editControls.updateTheme(t)}updateTimeDisplay=()=>{this.timeDisplay.update()};destroy(){this.edit.events.off("clip:selected",this.updateEditControls),this.edit.events.off("selection:cleared",this.updateEditControls),this.playbackControls.destroy(),this.timeDisplay.destroy(),this.editControls.destroy(),super.destroy()}}class mn{constructor(t,e,i,s,n,a){this.edit=t,this.layout=e,this.renderer=i,this.viewportManager=s,this.eventHandler=n,this.getTimelineContext=a}toolbar;ruler;playhead;scroll;async setupTimelineFeatures(t,e,i,s,n){this.toolbar=new gn(this.edit,t,this.layout,i),this.renderer.getStage().addChild(this.toolbar);const a={pixelsPerSecond:e,timelineDuration:n,rulerHeight:this.layout.rulerHeight,theme:t};this.ruler=new ii(a),await this.ruler.load(),this.ruler.getContainer().y=this.layout.rulerY,this.viewportManager.getRulerViewport().addChild(this.ruler.getContainer()),this.ruler.events.on("ruler:seeked",this.eventHandler.handleSeek.bind(this.eventHandler));const o={pixelsPerSecond:e,timelineHeight:s,theme:t};this.playhead=new si(o),await this.playhead.load(),this.playhead.getContainer().y=this.layout.rulerY,this.viewportManager.getPlayheadContainer().addChild(this.playhead.getContainer()),this.playhead.events.on("playhead:seeked",this.eventHandler.handleSeek.bind(this.eventHandler));const l={timeline:this.getTimelineContext()};this.scroll=new hn(l),await this.scroll.initialize(),this.viewportManager.updateViewportTransform()}recreateTimelineFeatures(t,e,i,s){if(this.ruler){this.ruler.dispose();const n=t.dimensions?.rulerHeight||this.layout.rulerHeight,a={pixelsPerSecond:e,timelineDuration:s,rulerHeight:n,theme:t};this.ruler=new ii(a),this.ruler.load(),this.ruler.getContainer().y=this.layout.rulerY,this.viewportManager.getRulerViewport().addChild(this.ruler.getContainer()),this.ruler.events.on("ruler:seeked",this.eventHandler.handleSeek.bind(this.eventHandler))}if(this.playhead){this.playhead.dispose();const n={pixelsPerSecond:e,timelineHeight:i,theme:t};this.playhead=new si(n),this.playhead.load(),this.playhead.getContainer().y=this.layout.rulerY,this.viewportManager.getPlayheadContainer().addChild(this.playhead.getContainer()),this.playhead.events.on("playhead:seeked",this.eventHandler.handleSeek.bind(this.eventHandler))}}updateRuler(t,e){this.ruler.updateRuler(t,e)}updatePlayhead(t,e){this.playhead&&this.playhead.updatePlayhead(t,e)}getFeatures(){return{toolbar:this.toolbar,ruler:this.ruler,playhead:this.playhead,scroll:this.scroll}}getToolbar(){return this.toolbar}getPlayhead(){return this.playhead}dispose(){this.toolbar&&this.toolbar.destroy(),this.ruler&&this.ruler.dispose(),this.playhead&&this.playhead.dispose(),this.scroll&&this.scroll.dispose()}}class tt{constructor(t,e){this.options=t,this.theme=e,this.config=this.calculateLayout()}static TOOLBAR_HEIGHT_RATIO=G.TOOLBAR_HEIGHT_RATIO;static RULER_HEIGHT_RATIO=G.RULER_HEIGHT_RATIO;static TOOLBAR_HEIGHT_DEFAULT=G.TOOLBAR_HEIGHT_DEFAULT;static RULER_HEIGHT_DEFAULT=G.RULER_HEIGHT_DEFAULT;static TRACK_HEIGHT_DEFAULT=G.TRACK_HEIGHT_DEFAULT;static CLIP_PADDING=G.CLIP_PADDING;static BORDER_WIDTH=G.BORDER_WIDTH;static CORNER_RADIUS=G.CORNER_RADIUS;static LABEL_PADDING=G.LABEL_PADDING;static TRACK_PADDING=G.TRACK_PADDING;config;calculateLayout(){const t=this.options.height;let e=this.theme?.timeline.toolbar.height||Math.round(t*tt.TOOLBAR_HEIGHT_RATIO),i=this.theme?.timeline.ruler.height||Math.round(t*tt.RULER_HEIGHT_RATIO);e=Math.max(e,tt.TOOLBAR_HEIGHT_DEFAULT),i=Math.max(i,tt.RULER_HEIGHT_DEFAULT);const{trackHeight:s}=this.options;return{toolbarHeight:e,rulerHeight:i,trackHeight:s,toolbarY:0,rulerY:e,tracksY:e+i,gridY:e+i,playheadY:e,viewportY:e+i}}get toolbarHeight(){return this.config.toolbarHeight}get toolbarY(){return this.config.toolbarY}get rulerHeight(){return this.config.rulerHeight}get trackHeight(){return this.config.trackHeight}get rulerY(){return this.config.rulerY}get tracksY(){return this.config.tracksY}get gridY(){return this.config.gridY}get playheadY(){return this.config.playheadY}get viewportY(){return this.config.viewportY}positionTrack(t){return t*this.trackHeight}positionClip(t){return t*this.options.pixelsPerSecond}calculateClipWidth(t){return Math.max(G.MIN_CLIP_WIDTH,t*this.options.pixelsPerSecond)}calculateDropPosition(t,e){const i=e-this.tracksY,s=Math.floor(i/this.trackHeight),n=Math.max(0,t/this.options.pixelsPerSecond);return{track:Math.max(0,s),time:n,x:t,y:i}}getTrackAtY(t){const e=t-this.tracksY;return Math.floor(e/this.trackHeight)}getTimeAtX(t){return t/this.options.pixelsPerSecond}getXAtTime(t){return t*this.options.pixelsPerSecond}getYAtTrack(t){return this.tracksY+t*this.trackHeight}getGridHeight(){return this.options.height-this.toolbarHeight-this.rulerHeight}getRulerWidth(){return this.options.width}getGridWidth(){return this.options.width}calculateViewportPosition(t,e){return{x:-t,y:this.viewportY-e}}updateOptions(t,e){this.options=t,this.theme=e,this.config=this.calculateLayout()}isPointInToolbar(t,e){return e>=this.toolbarY&&e<=this.toolbarY+this.toolbarHeight}isPointInRuler(t,e){return e>=this.rulerY&&e<=this.rulerY+this.rulerHeight}isPointInTracks(t,e){return e>=this.tracksY&&e<=this.options.height}getVisibleTrackRange(t,e){const i=t,s=Math.floor(i/this.trackHeight),n=Math.ceil((i+e)/this.trackHeight);return{start:Math.max(0,s),end:Math.max(0,n)}}}class Y{constructor(t,e,i,s){this.layout=i,this.onResize=s,this.width=t.width,this.height=t.height,this.pixelsPerSecond=50;const n=e.timeline.tracks.height||tt.TRACK_HEIGHT_DEFAULT;this.trackHeight=Math.max(40,n),this.backgroundColor=e.timeline.background,this.antialias=!0,this.resolution=window.devicePixelRatio||1}pixelsPerSecond;trackHeight;backgroundColor;antialias;resolution;width;height;static MIN_PIXELS_PER_SECOND=10;static MAX_PIXELS_PER_SECOND=500;static ZOOM_FACTOR=1.1;getOptions(){return{width:this.width,height:this.height,pixelsPerSecond:this.pixelsPerSecond,trackHeight:this.trackHeight,backgroundColor:this.backgroundColor,antialias:this.antialias,resolution:this.resolution}}setOptions(t){t.width!==void 0&&(this.width=t.width,this.onResize&&this.onResize(this.width)),t.height!==void 0&&(this.height=t.height),t.pixelsPerSecond!==void 0&&(this.pixelsPerSecond=t.pixelsPerSecond),t.trackHeight!==void 0&&(this.trackHeight=t.trackHeight),t.backgroundColor!==void 0&&(this.backgroundColor=t.backgroundColor),t.antialias!==void 0&&(this.antialias=t.antialias),t.resolution!==void 0&&(this.resolution=t.resolution),this.layout.updateOptions(this.getOptions())}updateFromTheme(t){this.backgroundColor=t.timeline.background;const e=t.timeline.tracks.height||tt.TRACK_HEIGHT_DEFAULT;this.trackHeight=Math.max(40,e),this.layout.updateOptions(this.getOptions(),t)}getWidth(){return this.width}getHeight(){return this.height}getPixelsPerSecond(){return this.pixelsPerSecond}getTrackHeight(){return this.trackHeight}getBackgroundColor(){return this.backgroundColor}getAntialias(){return this.antialias}getResolution(){return this.resolution}zoomIn(){const t=Math.min(this.pixelsPerSecond*Y.ZOOM_FACTOR,Y.MAX_PIXELS_PER_SECOND);this.setPixelsPerSecond(t)}zoomOut(){const t=Math.max(this.pixelsPerSecond/Y.ZOOM_FACTOR,Y.MIN_PIXELS_PER_SECOND);this.setPixelsPerSecond(t)}setPixelsPerSecond(t){this.pixelsPerSecond=Math.max(Y.MIN_PIXELS_PER_SECOND,Math.min(Y.MAX_PIXELS_PER_SECOND,t)),this.layout.updateOptions(this.getOptions())}canZoomIn(){return this.pixelsPerSecond<Y.MAX_PIXELS_PER_SECOND}canZoomOut(){return this.pixelsPerSecond>Y.MIN_PIXELS_PER_SECOND}}class ke extends nt{constructor(t,e,i){super(),this.edit=t,this.theme=ti.resolveTheme(i),this.layout=new tt({width:e.width,height:e.height,pixelsPerSecond:50,trackHeight:Math.max(40,this.theme.timeline.tracks.height||tt.TRACK_HEIGHT_DEFAULT),backgroundColor:this.theme.timeline.background,antialias:!0,resolution:window.devicePixelRatio||1},this.theme),this.optionsManager=new Y(e,this.theme,this.layout,s=>this.featureManager?.getToolbar()?.resize(s)),this.initializeManagers(),this.setupInteraction()}currentEditType=null;layout;theme;lastPlaybackTime=0;static TIMELINE_BUFFER_MULTIPLIER=1.5;interaction;dragPreviewManager;viewportManager;visualTrackManager;eventHandler;renderer;featureManager;optionsManager;initializeManagers(){const t=this.optionsManager.getOptions();this.renderer=new cn({width:t.width||800,height:t.height||600,backgroundColor:t.backgroundColor||0,antialias:t.antialias??!0,resolution:t.resolution||window.devicePixelRatio||1},(e,i)=>this.update(e,i)),this.eventHandler=new ln(this.edit,{onEditChange:this.handleEditChange.bind(this),onSeek:e=>this.edit.seek(e),onClipSelected:(e,i)=>this.visualTrackManager.updateVisualSelection(e,i),onSelectionCleared:()=>this.visualTrackManager.clearVisualSelection(),onDragStarted:(e,i)=>{const s=this.getClipData(e,i);s&&this.dragPreviewManager.showDragPreview(e,i,s)},onDragEnded:()=>this.dragPreviewManager.hideDragPreview()}),this.eventHandler.setupEventListeners()}async load(){await this.renderer.initializePixiApp(),await this.renderer.setupRenderLayers(),await this.setupViewport(),await this.setupTimelineFeatures(),this.interaction.activate();try{const t=this.edit.getEdit();t&&(this.currentEditType=t,await this.rebuildFromEdit(t))}catch{}this.renderer.startAnimationLoop()}async setupViewport(){this.viewportManager=new en(this.layout,this.renderer.getTrackLayer(),this.renderer.getOverlayLayer(),this.getContainer(),()=>this.renderer.render()),await this.viewportManager.setupViewport(),this.visualTrackManager=new on(this.getContainer(),this.layout,this.theme,()=>this.optionsManager.getPixelsPerSecond(),()=>this.getExtendedTimelineWidth()),this.dragPreviewManager=new tn(this.getContainer(),this.layout,()=>this.optionsManager.getPixelsPerSecond(),()=>this.optionsManager.getTrackHeight(),()=>this.visualTrackManager.getVisualTracks()),this.featureManager=new mn(this.edit,this.layout,this.renderer,this.viewportManager,this.eventHandler,()=>this)}async setupTimelineFeatures(){const t=this.getExtendedTimelineDuration();await this.featureManager.setupTimelineFeatures(this.theme,this.optionsManager.getPixelsPerSecond(),this.optionsManager.getWidth(),this.optionsManager.getHeight(),t)}recreateTimelineFeatures(){const t=this.getExtendedTimelineDuration();this.featureManager.recreateTimelineFeatures(this.theme,this.optionsManager.getPixelsPerSecond(),this.optionsManager.getHeight(),t)}setScroll(t,e){this.viewportManager.setScroll(t,e)}setZoom(t){this.viewportManager.setZoom(t)}getViewport(){return this.viewportManager.getViewport()}getPixiApp(){return this.renderer.getApp()}getTrackLayer(){return this.renderer.getTrackLayer()}getOverlayLayer(){return this.renderer.getOverlayLayer()}getClipData(t,e){return this.currentEditType?.timeline?.tracks&&this.currentEditType.timeline.tracks[t]?.clips?.[e]||null}getLayout(){return this.layout}getVisualTracks(){return this.visualTrackManager.getVisualTracks()}getEdit(){return this.edit}getExtendedTimelineWidth(){const t=this.getExtendedTimelineDuration()*this.optionsManager.getPixelsPerSecond(),e=this.optionsManager.getWidth();return Math.max(t,e)}hideDragGhost(){this.dragPreviewManager.hideDragGhost()}showDragGhost(t,e,i){this.dragPreviewManager.showDragGhost(t,e,i)}setPlayheadTime(t){this.featureManager.getPlayhead().setTime(t)}getPlayheadTime(){return this.featureManager.getPlayhead().getTime()}getActualEditDuration(){return this.edit.totalDuration/1e3||60}setupInteraction(){this.interaction=new Js(this)}async handleEditChange(t){this.dragPreviewManager.hideDragPreview();const e=t||this.edit.getEdit();e&&(this.currentEditType=e,this.updateRulerDuration(),this.clearAllVisualState(),await this.rebuildFromEdit(e))}getExtendedTimelineDuration(){const t=this.edit.totalDuration/1e3||60;return Math.max(60,t*ke.TIMELINE_BUFFER_MULTIPLIER)}updateRulerDuration(){const t=this.getExtendedTimelineDuration(),e=this.getExtendedTimelineWidth();this.featureManager.updateRuler(this.optionsManager.getPixelsPerSecond(),t),this.visualTrackManager.updateTrackWidths(e)}clearAllVisualState(){this.dragPreviewManager.hideDragPreview(),this.visualTrackManager.clearAllVisualState()}async rebuildFromEdit(t){await this.visualTrackManager.rebuildFromEdit(t,this.optionsManager.getPixelsPerSecond()),this.renderer.render()}findClipAtPosition(t,e){return this.currentEditType?this.visualTrackManager.findClipAtPosition(t,e):null}setTheme(t){this.theme=ti.resolveTheme(t),this.optionsManager.updateFromTheme(this.theme),this.featureManager.getToolbar()&&this.featureManager.getToolbar().updateTheme(this.theme),this.recreateTimelineFeatures(),this.currentEditType&&(this.clearAllVisualState(),this.rebuildFromEdit(this.currentEditType)),this.renderer.updateBackgroundColor(this.optionsManager.getBackgroundColor()),this.renderer.render()}getTheme(){return this.theme}getCurrentEditType(){return this.currentEditType}getOptions(){return this.optionsManager.getOptions()}setOptions(t){this.optionsManager.setOptions(t)}update(t,e){(this.edit.isPlaying||this.lastPlaybackTime!==this.edit.playbackTime)&&(this.featureManager.getPlayhead().setTime(this.edit.playbackTime/1e3),this.lastPlaybackTime=this.edit.playbackTime,this.featureManager.getToolbar()&&this.featureManager.getToolbar().updateTimeDisplay())}draw(){this.renderer.draw()}getTimeDisplay(){return this.featureManager.getToolbar()}updateTime(t,e){this.setPlayheadTime(t),e&&this.edit.seek(t*1e3)}get timeRange(){return{startTime:0,endTime:this.getExtendedTimelineDuration()}}get viewportHeight(){return this.optionsManager.getHeight()}get zoomLevelIndex(){const t=this.viewportManager.getViewport();return Math.round(Math.log2(t.zoom)+5)}zoomIn(){this.optionsManager.zoomIn(),this.onZoomChanged()}zoomOut(){this.optionsManager.zoomOut(),this.onZoomChanged()}onZoomChanged(){const t=this.optionsManager.getPixelsPerSecond();this.visualTrackManager.updatePixelsPerSecond(t);const e=this.getExtendedTimelineWidth();this.visualTrackManager.updateTrackWidths(e),this.featureManager.updateRuler(t,this.getExtendedTimelineDuration()),this.featureManager.updatePlayhead(t,this.optionsManager.getHeight()),this.renderer.render()}dispose(){this.dragPreviewManager.dispose(),this.visualTrackManager.dispose(),this.eventHandler.dispose(),this.featureManager.dispose(),this.interaction&&this.interaction.dispose(),this.renderer.dispose()}}H.Canvas=gt,H.Controls=Us,H.Edit=bt,H.Timeline=ke,H.VideoExporter=Zs,Object.defineProperty(H,Symbol.toStringTag,{value:"Module"})});