@shotstack/shotstack-studio 1.5.1 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +19 -10
- package/dist/shotstack-studio.es.js +7904 -3911
- package/dist/shotstack-studio.umd.js +122 -8
- package/package.json +2 -4
- package/readme.md +5 -14
|
@@ -1,4 +1,4 @@
|
|
|
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;
|
|
1
|
+
(function(ee,re){typeof exports=="object"&&typeof module<"u"?re(exports,require("pixi.js"),require("howler"),require("opentype.js")):typeof define=="function"&&define.amd?define(["exports","pixi.js","howler","opentype.js"],re):(ee=typeof globalThis<"u"?globalThis:ee||self,re(ee.ShotstackStudio={},ee.PIXI,ee.Howler,ee.opentype))})(this,function(ee,re,Xs,Ys){"use strict";function Qt(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const f=Qt(re),qs=Qt(Xs),Pi=Qt(Ys);class Qs{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(e,t,i,n){const r=this.curves[n??""]??this.curves.ease,[[a,o],[l,c]]=r,h=i+(3*a-3*l+1)*i*(1-i),d=e,u=e+(t-e)*o,p=e+(t-e)*c,g=t,b=h,_=1-b;return _**3*d+3*_**2*b*u+3*_*b**2*p+b**3*g}}class K{property;length;cubicBuilder;constructor(e,t,i=0){this.property=this.createKeyframes(e,t,i),this.length=t,this.cubicBuilder=new Qs}getValue(e){const t=this.property.find(n=>e>=n.start&&e<n.start+n.length);if(!t){if(this.property.length>0){if(e>=this.length)return this.property[this.property.length-1].to;if(e<0)return this.property[0].from}return 1}const i=(e-t.start)/t.length;switch(t.interpolation){case"bezier":return this.cubicBuilder.getValue(t.from,t.to,i,t.easing);case"constant":return t.from;case"linear":default:return t.from+(t.to-t.from)*i}}createKeyframes(e,t,i=0){if(typeof e=="number")return[{start:0,length:t,from:e,to:e}];if(!e.length)throw new Error("Keyframes should have at least one value.");const n=this.createNormalizedKeyframes(e);try{this.validateKeyframes(n)}catch(r){console.warn("Keyframe configuration issues detected:",r)}return this.insertFillerKeyframes(n,t,i)}createNormalizedKeyframes(e){return e.toSorted((t,i)=>t.start-i.start).map(t=>({...t,start:t.start*1e3,length:t.length*1e3}))}validateKeyframes(e){for(let t=0;t<e.length;t+=1){const i=e[t],n=e[t+1];if(!n){if(i.start+i.length>this.length)throw new Error("Last keyframe exceeds the maximum duration.");break}if(i.start+i.length>n.start)throw new Error("Overlapping keyframes detected.")}}insertFillerKeyframes(e,t,i=0){const n=[];for(let r=0;r<e.length;r+=1){const a=e[r],o=e[r+1];if(r===0&&a.start!==0){const h={start:0,length:a.start,from:i,to:a.from};n.push(h)}if(n.push(a),!o){if(a.start+a.length<t){const d=a.start+a.length,u={start:d,length:t-d,from:a.to,to:a.to};n.push(u)}break}if(a.start+a.length!==o.start){const h={start:a.start+a.length,length:o.start,from:a.to,to:o.from};n.push(h)}}return n}}class Tt{static Name="AudioLoadParser";name;extension;validAudioExtensions;constructor(){this.name=Tt.Name,this.extension={type:[f.ExtensionType.LoadParser],priority:f.LoaderParserPriority.Normal,ref:null},this.validAudioExtensions=["mp3","mpeg","ogg","wav"]}test(e){const t=e.split("?")[0]?.split(".").pop()??"";return this.validAudioExtensions.includes(t)}async load(e,t,i){return new Promise(n=>{const r={src:e},a=new Howl(r);a.on("load",()=>n(a)),a.on("loaderror",()=>n(null))})}unload(e){e?.unload()}}class Js{clipConfiguration;constructor(e){this.clipConfiguration=e}build(e,t){const i=[],n=[],r=[],a=[],o=[],{effect:l,length:c}=this.clipConfiguration;if(!l)return{offsetXKeyframes:i,offsetYKeyframes:n,opacityKeyframes:r,scaleKeyframes:a,rotationKeyframes:o};const h=0;switch(this.getPresetName()){case"zoomIn":{const u=this.getZoomSpeed(),p=1*this.clipConfiguration.scale,g=u*this.clipConfiguration.scale;a.push({from:p,to:g,start:h,length:c,interpolation:"linear"});break}case"zoomOut":{const p=this.getZoomSpeed()*this.clipConfiguration.scale,g=1*this.clipConfiguration.scale;a.push({from:p,to:g,start:h,length:c,interpolation:"linear"});break}case"slideLeft":{let u=this.getSlideStart();const p=e.width+e.width*u*2,g=t.height/t.width*e.height;if(g<p){const b=Math.abs(p/e.width);a.push({from:b,to:b,start:h,length:c,interpolation:"linear"})}else u=(g-e.width)/2/e.width;i.push({from:u,to:-u,start:h,length:c});break}case"slideRight":{let u=this.getSlideStart();const p=e.width+e.width*u*2,g=t.height/t.width*e.height;if(g<p){const b=Math.abs(p/e.width);a.push({from:b,to:b,start:h,length:c,interpolation:"linear"})}else u=(g-e.width)/2/e.width;i.push({from:-u,to:u,start:h,length:c});break}case"slideUp":{let u=this.getSlideStart();const p=e.height+e.height*u*2,g=t.height/t.width*e.width;if(g<p){const b=Math.abs(p/e.height);a.push({from:b,to:b,start:h,length:c,interpolation:"linear"})}else u=(g-e.height)/2/e.height;n.push({from:u,to:-u,start:h,length:c});break}case"slideDown":{let u=this.getSlideStart();const p=e.height+e.height*u*2,g=t.height/t.width*e.width;if(g<p){const b=Math.abs(p/e.height);a.push({from:b,to:b,start:h,length:c,interpolation:"linear"})}else u=(g-e.height)/2/e.height;n.push({from:-u,to:u,start:h,length:c});break}}return{offsetXKeyframes:i,offsetYKeyframes:n,opacityKeyframes:r,scaleKeyframes:a,rotationKeyframes:o}}getPresetName(){const[e]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);return e}getZoomSpeed(){const[e,t]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);if(e.startsWith("zoom"))switch(t){case"Slow":return 1.1;case"Fast":return 1.7;default:return 1.3}return 0}getSlideStart(){const[e,t]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);if(e.startsWith("slide"))switch(t){case"Slow":return .03;case"Fast":return 1.7;default:return .12}return 0}}class en{clipConfiguration;constructor(e){this.clipConfiguration=e}build(){const e=[],t=[],i=[],n=[],r=[],a=this.buildInPreset();e.push(...a.offsetXKeyframes),t.push(...a.offsetYKeyframes),i.push(...a.opacityKeyframes),n.push(...a.scaleKeyframes),r.push(...a.rotationKeyframes);const o=this.buildOutPreset();return e.push(...o.offsetXKeyframes),t.push(...o.offsetYKeyframes),i.push(...o.opacityKeyframes),n.push(...o.scaleKeyframes),r.push(...o.rotationKeyframes),{offsetXKeyframes:e,offsetYKeyframes:t,opacityKeyframes:i,scaleKeyframes:n,rotationKeyframes:r}}buildInPreset(){const e=[],t=[],i=[],n=[],r=[];if(!this.clipConfiguration.transition?.in)return{offsetXKeyframes:e,offsetYKeyframes:t,opacityKeyframes:i,scaleKeyframes:n,rotationKeyframes:r};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,d=this.clipConfiguration.scale;n.push({from:h,to:d,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;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"slideRight":{const c=this.clipConfiguration.offset?.x-.025,h=this.clipConfiguration.offset?.x;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"slideUp":{const c=this.clipConfiguration.offset?.y+.025,h=this.clipConfiguration.offset?.y;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"slideDown":{const c=this.clipConfiguration.offset?.y-.025,h=this.clipConfiguration.offset?.y;t.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:e,offsetYKeyframes:t,opacityKeyframes:i,scaleKeyframes:n,rotationKeyframes:r}}buildOutPreset(){const e=[],t=[],i=[],n=[],r=[];if(!this.clipConfiguration.transition?.out)return{offsetXKeyframes:e,offsetYKeyframes:t,opacityKeyframes:i,scaleKeyframes:n,rotationKeyframes:r};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,d=h+9;n.push({from:h,to:d,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;e.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;e.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;t.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;t.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:e,offsetYKeyframes:t,opacityKeyframes:i,scaleKeyframes:n,rotationKeyframes:r}}getInPresetName(){const[e]=(this.clipConfiguration.transition?.in??"").split(/(Slow|Fast|VeryFast)/);return e}getOutPresetName(){const[e]=(this.clipConfiguration.transition?.out??"").split(/(Slow|Fast|VeryFast)/);return e}getInPresetLength(){const[,e]=(this.clipConfiguration.transition?.in??"").split(/(Slow|Fast|VeryFast)/);switch(e){case"Slow":return 2;case"Fast":return .5;case"VeryFast":return .25;default:return 1}}getOutPresetLength(){const[,e]=(this.clipConfiguration.transition?.out??"").split(/(Slow|Fast|VeryFast)/);switch(e){case"Slow":return 2;case"Fast":return .5;case"VeryFast":return .25;default:return 1}}}class tn{static ButtonLeftClick=0;static ButtonRightClick=3}class sn{containerSize;constructor(e){this.containerSize=e}relativeToAbsolute(e,t,i){switch(t){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-e.width,y:-i.y*this.containerSize.height};case"bottomLeft":return{x:i.x*this.containerSize.width,y:(-i.y+1)*this.containerSize.height-e.height};case"bottomRight":return{x:(i.x+1)*this.containerSize.width-e.width,y:(-i.y+1)*this.containerSize.height-e.height};case"left":return{x:i.x*this.containerSize.width,y:(-i.y+.5)*this.containerSize.height-e.height/2};case"right":return{x:(i.x+1)*this.containerSize.width-e.width,y:(-i.y+.5)*this.containerSize.height-e.height/2};case"top":return{x:(i.x+.5)*this.containerSize.width-e.width/2,y:-i.y*this.containerSize.height};case"bottom":return{x:(i.x+.5)*this.containerSize.width-e.width/2,y:(-i.y+1)*this.containerSize.height-e.height};case"center":default:return{x:(i.x+.5)*this.containerSize.width-e.width/2,y:(-i.y+.5)*this.containerSize.height-e.height/2}}}absoluteToRelative(e,t,i){switch(t){case"topLeft":return{x:i.x/this.containerSize.width,y:-(i.y/this.containerSize.height)};case"topRight":return{x:(i.x+e.width)/this.containerSize.width-1,y:-(i.y/this.containerSize.height)};case"bottomLeft":return{x:i.x/this.containerSize.width,y:-((i.y+e.height)/this.containerSize.height-1)};case"bottomRight":return{x:(i.x+e.width)/this.containerSize.width-1,y:-((i.y+e.height)/this.containerSize.height-1)};case"left":return{x:i.x/this.containerSize.width,y:-((i.y+e.height/2)/this.containerSize.height-.5)};case"right":return{x:(i.x+e.width)/this.containerSize.width-1,y:-((i.y+e.height/2)/this.containerSize.height-.5)};case"top":return{x:(i.x+e.width/2)/this.containerSize.width-.5,y:-(i.y/this.containerSize.height)};case"bottom":return{x:(i.x+e.width/2)/this.containerSize.width-.5,y:-((i.y+e.height)/this.containerSize.height-1)};case"center":default:return{x:(i.x+e.width/2)/this.containerSize.width-.5,y:-((i.y+e.height/2)/this.containerSize.height-.5)}}}}class be{container;constructor(){this.container=new f.Container}getContainer(){return this.container}}class G extends be{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(e,t){super(),this.edit=e,this.layer=0,this.shouldDispose=!1,this.clipConfiguration=t,this.positionBuilder=new sn(e.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 f.Container,this.getContainer().addChild(this.contentContainer)}reconfigureAfterRestore(){this.configureKeyframes()}configureKeyframes(){if(this.offsetXKeyframeBuilder=new K(this.clipConfiguration.offset?.x??0,this.getLength()),this.offsetYKeyframeBuilder=new K(this.clipConfiguration.offset?.y??0,this.getLength()),this.scaleKeyframeBuilder=new K(this.clipConfiguration.scale??1,this.getLength(),1),this.opacityKeyframeBuilder=new K(this.clipConfiguration.opacity??1,this.getLength(),1),this.rotationKeyframeBuilder=new K(this.clipConfiguration.transform?.rotate?.angle??0,this.getLength()),this.clipHasKeyframes())return;const e=[],t=[],i=[],n=[],r=[],a=new Js(this.clipConfiguration).build(this.edit.size,this.getSize());e.push(...a.offsetXKeyframes),t.push(...a.offsetYKeyframes),i.push(...a.opacityKeyframes),n.push(...a.scaleKeyframes),r.push(...a.rotationKeyframes);const o=new en(this.clipConfiguration).build();e.push(...o.offsetXKeyframes),t.push(...o.offsetYKeyframes),i.push(...o.opacityKeyframes),n.push(...o.scaleKeyframes),r.push(...o.rotationKeyframes),e.length&&(this.offsetXKeyframeBuilder=new K(e,this.getLength())),t.length&&(this.offsetYKeyframeBuilder=new K(t,this.getLength())),i.length&&(this.opacityKeyframeBuilder=new K(i,this.getLength(),1)),n.length&&(this.scaleKeyframeBuilder=new K(n,this.getLength(),1)),r.length&&(this.rotationKeyframeBuilder=new K(r,this.getLength()))}async load(){this.outline=new f.Graphics,this.getContainer().addChild(this.outline),this.topLeftScaleHandle=new f.Graphics,this.topRightScaleHandle=new f.Graphics,this.bottomRightScaleHandle=new f.Graphics,this.bottomLeftScaleHandle=new f.Graphics,this.rotationHandle=new f.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(e,t){if(this.getContainer().visible=this.isActive(),this.getContainer().zIndex=1e5-this.layer*100,!this.isActive())return;const i=this.getPivot(),n=this.getPosition(),r=this.getContainerScale();this.getContainer().scale.set(r.x,r.y),this.getContainer().pivot.set(i.x,i.y),this.getContainer().position.set(n.x+i.x,n.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 e=this.edit.isPlayerSelected(this),t=this.edit.isInExportMode();if((!this.isActive()||!e)&&!this.isHovering||t){this.outline.clear(),this.topLeftScaleHandle?.clear(),this.topRightScaleHandle?.clear(),this.bottomRightScaleHandle?.clear(),this.bottomLeftScaleHandle?.clear(),this.rotationHandle?.clear();return}const i=this.isHovering||this.isDragging?65535:16777215,n=this.getSize(),r=this.getScale();if(this.outline.clear(),this.outline.strokeStyle={width:G.OutlineWidth/r,color:i},this.outline.rect(0,0,n.width,n.height),this.outline.stroke(),!this.topLeftScaleHandle||!this.topRightScaleHandle||!this.bottomRightScaleHandle||!this.bottomLeftScaleHandle||!this.isActive()||!e)return;this.topLeftScaleHandle.fillStyle={color:i},this.topLeftScaleHandle.clear();const a=G.ScaleHandleRadius*2/r;if(this.topLeftScaleHandle.rect(-a/2,-a/2,a,a),this.topLeftScaleHandle.fill(),this.topRightScaleHandle.fillStyle={color:i},this.topRightScaleHandle.clear(),this.topRightScaleHandle.rect(n.width-a/2,-a/2,a,a),this.topRightScaleHandle.fill(),this.bottomRightScaleHandle.fillStyle={color:i},this.bottomRightScaleHandle.clear(),this.bottomRightScaleHandle.rect(n.width-a/2,n.height-a/2,a,a),this.bottomRightScaleHandle.fill(),this.bottomLeftScaleHandle.fillStyle={color:i},this.bottomLeftScaleHandle.clear(),this.bottomLeftScaleHandle.rect(-a/2,n.height-a/2,a,a),this.bottomLeftScaleHandle.fill(),!this.rotationHandle)return;const o=n.width/2,l=-50/r;this.rotationHandle.clear(),this.rotationHandle.fillStyle={color:i},this.rotationHandle.circle(o,l,G.RotationHandleRadius/r),this.rotationHandle.fill(),this.outline.strokeStyle={width:G.OutlineWidth/r,color:i},this.outline.moveTo(o,0),this.outline.lineTo(o,l),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 e=this.edit.playbackTime-this.getStart();return e<0?0:e>this.getLength()?this.getLength():e}getOpacity(){return this.opacityKeyframeBuilder?.getValue(this.getPlaybackTime())??1}getPosition(){const e={x:this.offsetXKeyframeBuilder?.getValue(this.getPlaybackTime())??0,y:this.offsetYKeyframeBuilder?.getValue(this.getPlaybackTime())??0};return this.positionBuilder.relativeToAbsolute(this.getSize(),this.clipConfiguration.position??"center",e)}getPivot(){const e=this.getSize();return{x:e.width/2,y:e.height/2}}getFitScale(){switch(this.clipConfiguration.fit??"crop"){case"crop":{const e=this.edit.size.width/this.getSize().width,t=this.edit.size.height/this.getSize().height;return this.edit.size.height>=this.edit.size.width?t:e}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 e=this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1,t=this.getSize(),i=this.clipConfiguration.fit??"crop";if(t.width===0||t.height===0)return{x:e,y:e};const n=this.edit.size.width/t.width,r=this.edit.size.height/t.height;switch(i){case"contain":{const a=Math.min(n,r)*e;return{x:a,y:a}}case"crop":{const o=(this.edit.size.height>=this.edit.size.width?r:n)*e;return{x:o,y:o}}case"cover":return{x:n*e,y:r*e};case"none":default:return{x:e,y:e}}}getRotation(){return this.rotationKeyframeBuilder?.getValue(this.getPlaybackTime())??0}isActive(){return this.edit.playbackTime>=this.getStart()&&this.edit.playbackTime<this.getEnd()}shouldDiscardFrame(){return this.getPlaybackTime()<G.DiscardedFrameCount}onPointerStart(e){if(e.button!==tn.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(e.globalX,e.globalY)&&(this.scaleDirection="topLeft"),this.topRightScaleHandle?.getBounds().containsPoint(e.globalX,e.globalY)&&(this.scaleDirection="topRight"),this.bottomRightScaleHandle?.getBounds().containsPoint(e.globalX,e.globalY)&&(this.scaleDirection="bottomRight"),this.bottomLeftScaleHandle?.getBounds().containsPoint(e.globalX,e.globalY)&&(this.scaleDirection="bottomLeft"),this.scaleDirection!==null){this.scaleStart=this.getScale()/this.getFitScale();const l=e.getLocalPosition(this.edit.getContainer());this.scaleOffset=l;return}if(this.rotationHandle?.getBounds().containsPoint(e.globalX,e.globalY)){this.isRotating=!0,this.rotationStart=this.getRotation();const l=e.getLocalPosition(this.edit.getContainer());this.rotationOffset=l;return}this.isDragging=!0;const o=e.getLocalPosition(this.edit.getContainer());this.dragOffset={x:o.x-this.getContainer().position.x,y:o.y-this.getContainer().position.y}}onPointerMove(e){if(this.scaleDirection!==null&&this.scaleStart!==null){const t=e.getLocalPosition(this.edit.getContainer()),i=this.getPosition(),n=this.getPivot(),r={x:i.x+n.x,y:i.y+n.y},a=Math.sqrt((this.scaleOffset.x-r.x)**2+(this.scaleOffset.y-r.y)**2),l=Math.sqrt((t.x-r.x)**2+(t.y-r.y)**2)/a,c=this.scaleStart*l;this.clipConfiguration.scale=Math.max(G.MinScale,Math.min(c,G.MaxScale)),this.scaleKeyframeBuilder=new K(this.clipConfiguration.scale,this.getLength(),1);return}if(this.isRotating&&this.rotationStart!==null){const t=e.getLocalPosition(this.edit.getContainer()),i=this.getPosition(),n=this.getPivot(),r={x:i.x+n.x,y:i.y+n.y},a=Math.atan2(this.rotationOffset.y-r.y,this.rotationOffset.x-r.x),l=(Math.atan2(t.y-r.y,t.x-r.x)-a)*(180/Math.PI);let c=this.rotationStart+l;const h=45,d=c%h,u=2;Math.abs(d)<u?c=Math.floor(c/h)*h:Math.abs(d-h)<u&&(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 K(this.clipConfiguration.transform.rotate.angle,this.getLength());return}if(this.isDragging){const t=e.getLocalPosition(this.edit.getContainer()),i=this.getPivot(),n={x:t.x-this.dragOffset.x,y:t.y-this.dragOffset.y},r={x:n.x-i.x,y:n.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:r.x,y:r.y},{x:r.x+this.getSize().width,y:r.y},{x:r.x,y:r.y+this.getSize().height},{x:r.x+this.getSize().width,y:r.y+this.getSize().height}],h={x:r.x+this.getSize().width/2,y:r.y+this.getSize().height/2},d=[...c,h];let u=G.SnapThreshold,p=G.SnapThreshold,g=null,b=null;for(const B of d)for(const N of l){const J=Math.abs(B.x-N.x);J<u&&(u=J,g=r.x+(N.x-B.x));const $=Math.abs(B.y-N.y);$<p&&(p=$,b=r.y+(N.y-B.y))}g!==null&&(r.x=g),b!==null&&(r.y=b);const _=this.positionBuilder.absoluteToRelative(this.getSize(),this.clipConfiguration.position??"center",r);this.clipConfiguration.offset||(this.clipConfiguration.offset={x:0,y:0}),this.clipConfiguration.offset.x=_.x,this.clipConfiguration.offset.y=_.y,this.offsetXKeyframeBuilder=new K(this.clipConfiguration.offset.x,this.getLength()),this.offsetYKeyframeBuilder=new K(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(e=>e&&typeof e!="number")}hasStateChanged(){if(!this.initialClipConfiguration)return!1;const e=this.clipConfiguration.offset?.x,t=this.clipConfiguration.offset?.y,i=this.clipConfiguration.scale,n=Number(this.clipConfiguration.transform?.rotate?.angle??0),r=this.initialClipConfiguration.offset?.x,a=this.initialClipConfiguration.offset?.y,o=this.initialClipConfiguration.scale,l=Number(this.initialClipConfiguration.transform?.rotate?.angle??0);return r!==void 0&&e!==r||a!==void 0&&t!==a||o!==void 0&&i!==o||n!==l}}class Ai extends G{audioResource;isPlaying;volumeKeyframeBuilder;syncTimer;constructor(e,t){super(e,t),this.audioResource=null,this.isPlaying=!1;const i=t.asset;this.volumeKeyframeBuilder=new K(i.volume??1,this.getLength()),this.syncTimer=0}async load(){await super.load();const e=this.clipConfiguration.asset,t=e.src,i={src:t,loadParser:Tt.Name},n=await this.edit.assetLoader.load(t,i);if(!(n instanceof qs.Howl))throw new Error(`Invalid audio source '${e.src}'.`);this.audioResource=n,this.configureKeyframes()}update(e,t){super.update(e,t);const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=t,this.getContainer().alpha=0,!this.audioResource)return;const n=this.edit.isPlaying&&this.isActive(),r=this.getPlaybackTime();n&&(this.isPlaying||(this.isPlaying=!0,this.audioResource.seek(r/1e3+i),this.audioResource.play()),this.audioResource.volume()!==this.getVolume()&&this.audioResource.volume(this.getVolume()),Math.abs((this.audioResource.seek()-i)*1e3-r)>100&&this.audioResource.seek(r/1e3+i)),this.isPlaying&&!n&&(this.isPlaying=!1,this.audioResource.pause());const a=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&a&&(this.syncTimer=0,this.audioResource.seek(r/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 nn=`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
|
-
`,
|
|
28
|
+
`,rn=`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
|
-
}`,
|
|
77
|
+
}`,an=`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
|
-
`,
|
|
118
|
+
`,on=`struct OutlineUniforms {
|
|
119
119
|
uThickness:vec2<f32>,
|
|
120
120
|
uColor:vec3<f32>,
|
|
121
121
|
uAlpha:f32,
|
|
@@ -179,7 +179,121 @@ fn outlineMaxAlphaAtPos(uv: vec2<f32>) -> f32 {
|
|
|
179
179
|
return maxAlpha;
|
|
180
180
|
}
|
|
181
181
|
|
|
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<
|
|
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"})});
|
|
182
|
+
const DOUBLE_PI: f32 = 3.14159265358979323846264 * 2.;`,cn=Object.defineProperty,ln=(s,e,t)=>e in s?cn(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Re=(s,e,t)=>(ln(s,typeof e!="symbol"?e+"":e,t),t);const bt=class $e extends re.Filter{constructor(...e){let t=e[0]??{};typeof t=="number"&&(re.deprecation("6.0.0","OutlineFilter constructor params are now options object. See params: { thickness, color, quality, alpha, knockout }"),t={thickness:t},e[1]!==void 0&&(t.color=e[1]),e[2]!==void 0&&(t.quality=e[2]),e[3]!==void 0&&(t.alpha=e[3]),e[4]!==void 0&&(t.knockout=e[4])),t={...$e.DEFAULT_OPTIONS,...t};const i=t.quality??.1,n=re.GpuProgram.from({vertex:{source:rn,entryPoint:"mainVertex"},fragment:{source:on,entryPoint:"mainFragment"}}),r=re.GlProgram.from({vertex:nn,fragment:an.replace(/\$\{ANGLE_STEP\}/,$e.getAngleStep(i).toFixed(7)),name:"outline-filter"});super({gpuProgram:n,glProgram:r,resources:{outlineUniforms:{uThickness:{value:new Float32Array(2),type:"vec2<f32>"},uColor:{value:new Float32Array(3),type:"vec3<f32>"},uAlpha:{value:t.alpha,type:"f32"},uAngleStep:{value:0,type:"f32"},uKnockout:{value:t.knockout?1:0,type:"f32"}}}}),Re(this,"uniforms"),Re(this,"_thickness"),Re(this,"_quality"),Re(this,"_color"),this.uniforms=this.resources.outlineUniforms.uniforms,this.uniforms.uAngleStep=$e.getAngleStep(i),this._color=new re.Color,this.color=t.color??0,Object.assign(this,t)}apply(e,t,i,n){this.uniforms.uThickness[0]=this.thickness/t.source.width,this.uniforms.uThickness[1]=this.thickness/t.source.height,e.applyFilter(this,t,i,n)}static getAngleStep(e){return parseFloat((Math.PI*2/Math.max(e*$e.MAX_SAMPLES,$e.MIN_SAMPLES)).toFixed(7))}get thickness(){return this._thickness}set thickness(e){this._thickness=this.padding=e}get color(){return this._color.value}set color(e){this._color.setValue(e);const[t,i,n]=this._color.toArray();this.uniforms.uColor[0]=t,this.uniforms.uColor[1]=i,this.uniforms.uColor[2]=n}get alpha(){return this.uniforms.uAlpha}set alpha(e){this.uniforms.uAlpha=e}get quality(){return this._quality}set quality(e){this._quality=e,this.uniforms.uAngleStep=$e.getAngleStep(e)}get knockout(){return this.uniforms.uKnockout===1}set knockout(e){this.uniforms.uKnockout=e?1:0}};Re(bt,"DEFAULT_OPTIONS",{thickness:1,color:0,alpha:1,quality:.1,knockout:!1}),Re(bt,"MIN_SAMPLES",1),Re(bt,"MAX_SAMPLES",100);let Jt=bt;class hn extends G{background;text;constructor(e,t){super(e,t),this.background=null,this.text=null}async load(){await super.load();const e=this.clipConfiguration.asset,t=await this.parseDocument();if(!t)return;const i=new f.Graphics;t.background.color&&(i.fillStyle={color:t.background.color,alpha:t.background.opacity??1},i.rect(0,0,e.width??this.edit.size.width,e.height??this.edit.size.height),i.fill());const n=new f.Text;n.text=t.text;const{horizontal:r,vertical:a}=t.alignment;n.style={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:e.width??this.edit.size.width,lineHeight:(t.font?.lineHeight??1)*(t.font?.size??32),align:r};let o=(e.width??this.edit.size.width)/2-n.width/2,l=(e.height??this.edit.size.height)/2-n.height/2;if(r==="left"&&(o=0),r==="right"&&(o=(e.width??this.edit.size.width)-n.width),a==="top"&&(l=0),a==="bottom"&&(l=(e.height??this.edit.size.height)-n.height),n.position={x:o,y:l},t.stroke.color&&t.stroke.width){const c=new Jt({thickness:t.stroke.width,color:t.stroke.color});n.filters=[c]}this.background=i,this.text=n,this.contentContainer.addChild(i),this.contentContainer.addChild(n),this.configureKeyframes()}update(e,t){super.update(e,t)}draw(){super.draw()}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null}getSize(){const e=this.clipConfiguration.asset;return{width:e.width??this.edit.size.width,height:e.height??this.edit.size.height}}getFitScale(){return 1}async parseDocument(){const e=this.clipConfiguration.asset,{html:t,css:i,position:n}=e;if(!t.includes('data-html-type="text"'))return console.warn("Unsupported html format."),null;const a=new DOMParser().parseFromString(t,"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,d=this.parseAlignment(n??"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=d;let u="";return h.background.length&&(u=h.background),h.backgroundColor.length&&(u=h.backgroundColor),c.background={color:u.length?u: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(e){switch(e){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 dn extends G{texture;sprite;constructor(e,t){super(e,t),this.texture=null,this.sprite=null}async load(){await super.load();const e=this.clipConfiguration.asset,t=e.src,i={src:t,crossovern:"anonymous",data:{}},n=await this.edit.assetLoader.load(t,i);if(!(n?.source instanceof f.ImageSource))throw new Error(`Invalid image source '${e.src}'.`);this.texture=this.createCroppedTexture(n),this.sprite=new f.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.configureKeyframes()}update(e,t){super.update(e,t)}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(e){const t=this.clipConfiguration.asset;if(!t.crop)return e;const i=e.width,n=e.height,r=Math.floor((t.crop?.left??0)*i),a=Math.floor((t.crop?.right??0)*i),o=Math.floor((t.crop?.top??0)*n),l=Math.floor((t.crop?.bottom??0)*n),c=r,h=o,d=i-r-a,u=n-o-l,p=new f.Rectangle(c,h,d,u);return new f.Texture({source:e.source,frame:p})}}class Oi extends G{texture;sprite;isPlaying;constructor(e,t){super(e,t),this.texture=null,this.sprite=null,this.isPlaying=!1}async load(){await super.load();const e=this.clipConfiguration.asset,t=e.src,i={src:t,data:{autoPlay:!1,muted:!0}},n=await this.edit.assetLoader.load(t,i);if(!(n?.source instanceof f.ImageSource||n?.source instanceof f.VideoSource))throw new Error(`Invalid luma source '${e.src}'.`);this.texture=n,this.sprite=new f.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.configureKeyframes()}update(e,t){if(super.update(e,t),!this.texture||!(this.texture.source instanceof f.VideoSource))return;const i=this.getPlaybackTime(),n=this.edit.isPlaying&&this.isActive();n&&(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)),!n&&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 un extends G{shape;shapeBackground;constructor(e,t){super(e,t),this.shape=null,this.shapeBackground=null}async load(){await super.load();const e=this.clipConfiguration.asset,t=new f.Graphics,i=e.width??this.edit.size.width,n=e.height??this.edit.size.height;t.fillStyle={color:"transparent"},t.rect(0,0,i,n),t.fill();const r=new f.Graphics;switch(e.shape){case"rectangle":{const a=e.rectangle,o=i/2-a.width/2,l=n/2-a.height/2;r.rect(o,l,a.width,a.height);break}case"circle":{const a=e.circle,o=i/2,l=n/2;r.circle(o,l,a.radius);break}case"line":{const a=e.line,o=i/2-a.length/2,l=n/2-a.thickness/2;r.rect(o,l,a.length,a.thickness);break}default:console.warn("Unsupported shape asset type.");break}if(r.fillStyle={color:e.fill?.color??"#ffffff",alpha:e.fill?.opacity??1},r.fill(),e.stroke){const a=new Jt({thickness:e.stroke.width,color:e.stroke.color});r.filters=[a]}this.shapeBackground=t,this.shape=r,this.contentContainer.addChild(t),t.addChild(r),this.configureKeyframes()}update(e,t){super.update(e,t)}draw(){super.draw()}dispose(){super.dispose(),this.shape?.destroy(),this.shape=null,this.shapeBackground?.destroy(),this.shapeBackground=null}getSize(){const e=this.clipConfiguration.asset;return{width:e.width??this.edit.size.width,height:e.height??this.edit.size.height}}getFitScale(){return 1}}class rt{static DEFAULT_BLINK_INTERVAL_MS=500;static DEFAULT_CURSOR_WIDTH_PX=2;static DEFAULT_CURSOR_COLOR=16777215;cursor=null;parent;textElement;clipConfig;textPosition=0;pixelX=0;pixelY=0;currentLine=0;isBlinking=!1;blinkInterval=null;blinkIntervalMs=500;width=2;color=16777215;isVisible=!0;constructor(e,t,i,n){this.parent=e,this.textElement=t,this.clipConfig=i,this.width=n?.width??rt.DEFAULT_CURSOR_WIDTH_PX,this.color=n?.color??rt.DEFAULT_CURSOR_COLOR,this.blinkIntervalMs=n?.blinkInterval??rt.DEFAULT_BLINK_INTERVAL_MS,this.textPosition=0,this.isBlinking=!1,this.isVisible=!0,this.blinkInterval=null,this.createCursor()}updatePosition(e){if(!this.cursor||!this.textElement){console.warn("TextCursor: Cannot update position, cursor not initialized");return}this.textPosition=this.validateTextPosition(e),this.calculateAndApplyPixelPosition()}setPosition(e,t){if(!this.cursor){console.warn("TextCursor: Cannot set position, cursor not initialized");return}this.pixelX=e,this.pixelY=t,this.updateGraphicsPosition()}show(){this.setVisible(!0)}hide(){this.setVisible(!1)}setVisible(e){this.isVisible=e,this.cursor&&!this.isBlinking&&(this.cursor.visible=e)}startBlinking(){if(!this.cursor){console.warn("TextCursor: Cannot start blinking, cursor not initialized");return}this.isBlinking||this.startBlinkingAnimation()}stopBlinking(){this.stopBlinkingAnimation()}setBlinkInterval(e){this.blinkIntervalMs=e,this.isBlinking&&(this.stopBlinking(),this.startBlinking())}dispose(){if(this.stopBlinkingAnimation(),this.cursor&&this.parent)try{this.parent.removeChild(this.cursor)}catch(e){console.warn("TextCursor: Error removing cursor from parent:",e)}if(this.cursor)try{this.cursor.destroy()}catch(e){console.warn("TextCursor: Error destroying cursor graphics:",e)}finally{this.cursor=null}this.textPosition=0,this.pixelX=0,this.pixelY=0,this.currentLine=0,this.isVisible=!0}createCursor(){if(!this.textElement)return;this.cursor=new f.Graphics,this.cursor.fillStyle={color:this.color};const e=this.textElement.style.fontSize;this.cursor.rect(0,0,this.width,e),this.cursor.fill(),this.parent.addChild(this.cursor),this.cursor.visible=this.isVisible}validateTextPosition(e){return this.textElement?Math.max(0,Math.min(e,this.textElement.text.length)):0}calculateAndApplyPixelPosition(){this.calculatePixelPositionFromText(),this.updateGraphicsPosition()}calculatePixelPositionFromText(){if(!this.textElement)return;const{text:e}=this.textElement,t=this.textElement.style,i=e.substring(0,this.textPosition),n=i.match(/\n/g);this.currentLine=n?n.length:0;const r=e.split(`
|
|
183
|
+
`),a=this.currentLine<r.length?r[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`,t)-this.measureText("x",t):h=this.measureText(c,t);const d=t.lineHeight;this.pixelY=this.currentLine*d;const p=this.clipConfig.asset.alignment?.horizontal??"center";let g=h;if(p!=="left"){const b=this.measureText(a,t),_=this.textElement.width;let B=0;p==="center"?B=(_-b)/2:p==="right"&&(B=_-b),g=B+h}this.pixelX=g}updateGraphicsPosition(){this.cursor&&this.cursor.position.set(this.pixelX,this.pixelY)}startBlinkingAnimation(){!this.cursor||this.isBlinking||(this.isBlinking=!0,this.blinkInterval=window.setInterval(()=>{this.cursor&&this.isBlinking&&(this.cursor.visible=!this.cursor.visible)},this.blinkIntervalMs))}stopBlinkingAnimation(){this.blinkInterval!==null&&(window.clearInterval(this.blinkInterval),this.blinkInterval=null),this.isBlinking=!1,this.cursor&&(this.cursor.visible=this.isVisible)}measureText(e,t){const i=new f.Text(e,t),{width:n}=i;return i.destroy(),n}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 kt{static DEFAULT_FOCUS_DELAY_MS=50;hiddenInput=null;isFocused=!1;focusRetryCount=0;maxFocusRetries=3;focusDelay=kt.DEFAULT_FOCUS_DELAY_MS;eventHandlers={};abortController=null;textChangeCallback=null;lastSyncedText="";isComposing=!1;setupInput(e,t){this.focusDelay=t?.focusDelay??kt.DEFAULT_FOCUS_DELAY_MS,this.createHiddenTextarea(),this.hiddenInput&&(this.hiddenInput.value=e,this.lastSyncedText=e),this.setupEventListeners(),t?.autoFocus!==!1&&this.focusInput()}updateInputValue(e){this.hiddenInput&&(this.hiddenInput.value=e,this.lastSyncedText=e)}focusInput(){this.hiddenInput&&setTimeout(()=>{this.hiddenInput&&!this.isFocused&&(this.hiddenInput.focus(),setTimeout(()=>{!this.isFocused&&this.focusRetryCount<this.maxFocusRetries&&(this.focusRetryCount+=1,this.focusInput())},10))},this.focusDelay)}blurInput(){this.hiddenInput&&this.hiddenInput.blur()}setSelectionRange(e,t){if(!this.hiddenInput)return;const i=this.hiddenInput.value.length,n=Math.max(0,Math.min(e,i)),r=Math.max(n,Math.min(t,i));this.hiddenInput.setSelectionRange(n,r)}getCursorPosition(){return this.hiddenInput?.selectionStart||0}getValue(){return this.hiddenInput?.value||""}setTextInputHandler(e){this.textChangeCallback=e}setEventHandlers(e){this.eventHandlers={...this.eventHandlers,...e}}isFocusedInput(){return this.isFocused}dispose(){this.removeAllEventListeners(),this.hiddenInput&&this.hiddenInput.parentNode&&this.hiddenInput.parentNode.removeChild(this.hiddenInput),this.hiddenInput=null,this.isFocused=!1,this.focusRetryCount=0,this.textChangeCallback=null,this.eventHandlers={}}createHiddenTextarea(){this.hiddenInput=document.createElement("textarea");const e={position:"absolute",opacity:"0.01",pointerEvents:"none",zIndex:"999",left:"0px",top:"0px",width:"1px",height:"1px",border:"none",outline:"none",resize:"none",backgroundColor:"transparent"};Object.assign(this.hiddenInput.style,e),this.hiddenInput.tabIndex=0,document.body.appendChild(this.hiddenInput)}setupEventListeners(){if(!this.hiddenInput)return;this.abortController=new AbortController;const{signal:e}=this.abortController;this.hiddenInput.addEventListener("input",this.handleTextInput,{signal:e}),this.hiddenInput.addEventListener("keydown",this.handleKeyDown,{signal:e}),this.hiddenInput.addEventListener("compositionstart",this.handleCompositionStart,{signal:e}),this.hiddenInput.addEventListener("compositionend",this.handleCompositionEnd,{signal:e}),this.hiddenInput.addEventListener("focus",this.handleFocus,{signal:e}),this.hiddenInput.addEventListener("blur",this.handleBlur,{signal:e}),this.hiddenInput.addEventListener("paste",this.handlePaste,{signal:e})}removeAllEventListeners(){this.abortController?.abort(),this.abortController=null}handleTextInput=e=>{if(!this.hiddenInput||this.isComposing)return;const t=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.lastSyncedText=t,this.textChangeCallback?.(t,i)};handleKeyDown=e=>{if(document.activeElement!==this.hiddenInput)return;let t=!1;if((e.ctrlKey||e.metaKey)&&(t=this.handleKeyboardShortcuts(e),t)){e.preventDefault();return}if(e.key==="Tab"){const i=e.shiftKey?"backward":"forward";this.eventHandlers.onTabNavigation?.(i),e.preventDefault();return}switch(e.key){case"Escape":this.eventHandlers.onEscape?.(e),t=!0;break;case"Enter":t=!1;break;case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":setTimeout(()=>{if(this.hiddenInput){const i=this.hiddenInput.value,n=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(i,n)}},0),t=!1;break;case"Backspace":case"Delete":t=!1;break;default:t=this.eventHandlers.onCustomKey?.(e.key,e)||!1;break}t&&e.preventDefault()};handleKeyboardShortcuts(e){const{key:t}=e;switch(t.toLowerCase()){case"a":return this.selectAll(),!0;case"c":case"v":return!1;case"z":return this.eventHandlers.onCustomKey?.("undo",e),!0;case"y":return this.eventHandlers.onCustomKey?.("redo",e),!0;default:return!1}}handleCompositionStart=e=>{this.isComposing=!0};handleCompositionEnd=e=>{if(this.isComposing=!1,this.hiddenInput){const t=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(t,i)}};handleFocus=e=>{this.isFocused=!0,this.focusRetryCount=0,this.eventHandlers.onFocus?.(e)};handleBlur=e=>{this.isFocused=!1,this.eventHandlers.onBlur?.(e)};handlePaste=e=>{setTimeout(()=>{this.handleTextInput(e)},0)};selectAll(){this.hiddenInput&&this.hiddenInput.select()}}class ae{static DOUBLE_CLICK_THRESHOLD_MS=300;static EDITING_BG_PADDING_PX=5;static EDITING_BG_ALPHA=.2;static CLICK_HANDLER_DELAY_MS=100;parent;targetText;clipConfig;isEditing=!1;lastClickTime=0;editingContainer=null;editableText=null;textCursor=null;textInputHandler=null;outsideClickHandler=null;constructor(e,t,i){this.parent=e,this.targetText=t,this.clipConfig=i,this.parent.getContainer().eventMode="static",this.parent.getContainer().on("click",this.checkForDoubleClick)}dispose(){this.parent.getContainer().off("click",this.checkForDoubleClick),this.stopEditing(),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null)}startEditing(){if(this.isEditing||!this.targetText)return;const e=structuredClone(this.clipConfig);this.targetText.visible=!1,this.createEditingEnvironment(),this.setupOutsideClickHandler(e),this.isEditing=!0}stopEditing(e=!1,t){if(!this.isEditing)return;let i="";this.editableText&&(i=this.editableText.text),this.editingContainer&&(this.parent.getContainer().removeChild(this.editingContainer),this.editingContainer.destroy(),this.editingContainer=null),this.editableText=null,this.textCursor&&(this.textCursor.dispose(),this.textCursor=null),this.textInputHandler&&(this.textInputHandler.dispose(),this.textInputHandler=null),this.targetText.visible=!0,e&&t&&i!==""&&this.parent.updateTextContent(i,t),this.isEditing=!1}checkForDoubleClick=e=>{const t=Date.now();t-this.lastClickTime<ae.DOUBLE_CLICK_THRESHOLD_MS&&this.startEditing(),this.lastClickTime=t};setupOutsideClickHandler(e){this.outsideClickHandler=t=>{const n=this.parent.getContainer().getBounds(),r=t.clientX,a=t.clientY;(r<n.x||r>n.x+n.width||a<n.y||a>n.y+n.height)&&(this.stopEditing(!0,e),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null))},setTimeout(()=>{this.outsideClickHandler&&window.addEventListener("click",this.outsideClickHandler)},ae.CLICK_HANDLER_DELAY_MS)}createEditingEnvironment(){this.setupEditingContainer(),this.editingContainer&&this.editableText&&(this.textCursor=new rt(this.editingContainer,this.editableText,this.clipConfig),this.textCursor.updatePosition(this.targetText.text.length),this.textCursor.startBlinking()),this.setupTextInputHandler(),this.updateTextAlignment()}setupEditingContainer(){this.editingContainer=new f.Container,this.parent.getContainer().addChild(this.editingContainer);const e=new f.Graphics;e.fillStyle={color:0,alpha:ae.EDITING_BG_ALPHA},e.rect(-5,-5,this.targetText.width+2*ae.EDITING_BG_PADDING_PX,this.targetText.height+2*ae.EDITING_BG_PADDING_PX),e.fill(),this.editingContainer.addChild(e),this.editableText=new f.Text(this.targetText.text,this.targetText.style),this.editableText.eventMode="static",this.editableText.cursor="text",this.editingContainer.addChild(this.editableText)}setupTextInputHandler(){this.textInputHandler=new kt,this.textInputHandler.setTextInputHandler((e,t)=>{this.editableText&&(this.editableText.text=e,this.updateTextAlignment()),this.textCursor?.updatePosition(t)}),this.textInputHandler.setEventHandlers({onEscape:e=>this.stopEditing(!1),onTabNavigation:e=>this.stopEditing(!0)}),this.textInputHandler.setupInput(this.targetText.text,{autoFocus:!0})}updateTextAlignment(){if(!this.editableText||!this.editingContainer)return;const e=this.getContainerDimensions(),t=this.getAlignmentSettings(),i=this.calculateHorizontalPosition({width:this.editableText.width},e,t.horizontal),n=this.calculateVerticalPosition({height:this.editableText.height},e,t.vertical);if(this.editingContainer.position.set(i,n),this.editingContainer.children.length>0){const r=this.editingContainer.getChildAt(0);r instanceof f.Graphics&&(r.clear(),r.fillStyle={color:0,alpha:ae.EDITING_BG_ALPHA},r.rect(-5,-5,this.editableText.width+2*ae.EDITING_BG_PADDING_PX,this.editableText.height+2*ae.EDITING_BG_PADDING_PX),r.fill())}}calculateHorizontalPosition(e,t,i="center"){switch(i){case"center":return t.width/2-e.width/2;case"right":return t.width-e.width;case"left":default:return 0}}calculateVerticalPosition(e,t,i="center"){switch(i){case"center":return t.height/2-e.height/2;case"bottom":return t.height-e.height;case"top":default:return 0}}getContainerDimensions(){const e=this.clipConfig.asset;return{width:e.width??this.parent.getSize().width,height:e.height??this.parent.getSize().height}}getAlignmentSettings(){const e=this.clipConfig.asset;return{horizontal:e.alignment?.horizontal??"center",vertical:e.alignment?.vertical??"center"}}}class pn extends G{background=null;text=null;textEditor=null;async load(){await super.load();const e=this.clipConfiguration.asset;if(this.background=new f.Graphics,e.background&&(this.background.fillStyle={color:e.background.color,alpha:e.background.opacity},this.background.rect(0,0,e.width??this.edit.size.width,e.height??this.edit.size.height),this.background.fill()),this.text=new f.Text(e.text,this.createTextStyle(e)),this.positionText(e),e.stroke){const t=new Jt({thickness:e.stroke.width,color:e.stroke.color});this.text.filters=[t]}this.contentContainer.addChild(this.background),this.contentContainer.addChild(this.text),this.configureKeyframes(),this.textEditor=new ae(this,this.text,this.clipConfiguration)}update(e,t){super.update(e,t)}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null,this.textEditor?.dispose(),this.textEditor=null}getSize(){const e=this.clipConfiguration.asset;return{width:e.width??this.edit.size.width,height:e.height??this.edit.size.height}}getFitScale(){return 1}createTextStyle(e){return new f.TextStyle({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:e.width??this.edit.size.width,lineHeight:(e.font?.lineHeight??1)*(e.font?.size??32),align:e.alignment?.horizontal??"center"})}positionText(e){if(!this.text)return;const t=e.alignment?.horizontal??"center",i=e.alignment?.vertical??"center",n=e.width??this.edit.size.width,r=e.height??this.edit.size.height;let a=n/2-this.text.width/2,o=r/2-this.text.height/2;t==="left"?a=0:t==="right"&&(a=n-this.text.width),i==="top"?o=0:i==="bottom"&&(o=r-this.text.height),this.text.position.set(a,o)}updateTextContent(e,t){this.edit.updateTextContent(this,e,t)}}class fn extends G{texture;sprite;isPlaying;volumeKeyframeBuilder;syncTimer;skipVideoUpdate;constructor(e,t){super(e,t),this.texture=null,this.sprite=null,this.isPlaying=!1;const i=this.clipConfiguration.asset;this.volumeKeyframeBuilder=new K(i.volume??1,this.getLength()),this.syncTimer=0,this.skipVideoUpdate=!1}async load(){await super.load();const e=this.clipConfiguration.asset,t=e.src;if(t.endsWith(".mov")||t.endsWith(".webm"))throw new Error(`Video source '${e.src}' is not supported. .mov and .webm files are currently not supported.`);const i={src:t,data:{autoPlay:!1,muted:!1}},n=await this.edit.assetLoader.load(t,i);if(!(n?.source instanceof f.VideoSource))throw new Error(`Invalid video source '${e.src}'.`);this.texture=this.createCroppedTexture(n),this.sprite=new f.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.configureKeyframes()}update(e,t){if(super.update(e,t),this.skipVideoUpdate)return;const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=t,!this.texture)return;const n=this.getPlaybackTime(),r=this.edit.isPlaying&&this.isActive();r&&(this.isPlaying||(this.isPlaying=!0,this.texture.source.resource.currentTime=n/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-n)>100&&(this.texture.source.resource.currentTime=n/1e3+i)),!r&&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=n/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(e){const t=this.clipConfiguration.asset;if(!t.crop)return e;const i=e.width,n=e.height,r=Math.floor((t.crop?.left??0)*i),a=Math.floor((t.crop?.right??0)*i),o=Math.floor((t.crop?.top??0)*n),l=Math.floor((t.crop?.bottom??0)*n),c=r,h=o,d=i-r-a,u=n-o-l,p=new f.Rectangle(c,h,d,u);return new f.Texture({source:e.source,frame:p})}}var R;(function(s){s.assertEqual=n=>n;function e(n){}s.assertIs=e;function t(n){throw new Error}s.assertNever=t,s.arrayToEnum=n=>{const r={};for(const a of n)r[a]=a;return r},s.getValidEnumValues=n=>{const r=s.objectKeys(n).filter(o=>typeof n[n[o]]!="number"),a={};for(const o of r)a[o]=n[o];return s.objectValues(a)},s.objectValues=n=>s.objectKeys(n).map(function(r){return n[r]}),s.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const r=[];for(const a in n)Object.prototype.hasOwnProperty.call(n,a)&&r.push(a);return r},s.find=(n,r)=>{for(const a of n)if(r(a))return a},s.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&isFinite(n)&&Math.floor(n)===n;function i(n,r=" | "){return n.map(a=>typeof a=="string"?`'${a}'`:a).join(r)}s.joinValues=i,s.jsonStringifyReplacer=(n,r)=>typeof r=="bigint"?r.toString():r})(R||(R={}));var Mi;(function(s){s.mergeShapes=(e,t)=>({...e,...t})})(Mi||(Mi={}));const C=R.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ke=s=>{switch(typeof s){case"undefined":return C.undefined;case"string":return C.string;case"number":return isNaN(s)?C.nan:C.number;case"boolean":return C.boolean;case"function":return C.function;case"bigint":return C.bigint;case"symbol":return C.symbol;case"object":return Array.isArray(s)?C.array:s===null?C.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?C.promise:typeof Map<"u"&&s instanceof Map?C.map:typeof Set<"u"&&s instanceof Set?C.set:typeof Date<"u"&&s instanceof Date?C.date:C.object;default:return C.unknown}},m=R.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 ie extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(r){return r.message},i={_errors:[]},n=r=>{for(const a of r.issues)if(a.code==="invalid_union")a.unionErrors.map(n);else if(a.code==="invalid_return_type")n(a.returnTypeError);else if(a.code==="invalid_arguments")n(a.argumentsError);else if(a.path.length===0)i._errors.push(t(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(t(a))):o[c]=o[c]||{_errors:[]},o=o[c],l++}}};return n(this),i}static assert(e){if(!(e instanceof ie))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,R.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},i=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):i.push(e(n));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}ie.create=s=>new ie(s);const at=(s,e)=>{let t;switch(s.code){case m.invalid_type:s.received===C.undefined?t="Required":t=`Expected ${s.expected}, received ${s.received}`;break;case m.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(s.expected,R.jsonStringifyReplacer)}`;break;case m.unrecognized_keys:t=`Unrecognized key(s) in object: ${R.joinValues(s.keys,", ")}`;break;case m.invalid_union:t="Invalid input";break;case m.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${R.joinValues(s.options)}`;break;case m.invalid_enum_value:t=`Invalid enum value. Expected ${R.joinValues(s.options)}, received '${s.received}'`;break;case m.invalid_arguments:t="Invalid function arguments";break;case m.invalid_return_type:t="Invalid function return type";break;case m.invalid_date:t="Invalid date";break;case m.invalid_string:typeof s.validation=="object"?"includes"in s.validation?(t=`Invalid input: must include "${s.validation.includes}"`,typeof s.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${s.validation.position}`)):"startsWith"in s.validation?t=`Invalid input: must start with "${s.validation.startsWith}"`:"endsWith"in s.validation?t=`Invalid input: must end with "${s.validation.endsWith}"`:R.assertNever(s.validation):s.validation!=="regex"?t=`Invalid ${s.validation}`:t="Invalid";break;case m.too_small:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at least":"more than"} ${s.minimum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at least":"over"} ${s.minimum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(s.minimum))}`:t="Invalid input";break;case m.too_big:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at most":"less than"} ${s.maximum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at most":"under"} ${s.maximum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="bigint"?t=`BigInt must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly":s.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(s.maximum))}`:t="Invalid input";break;case m.custom:t="Invalid input";break;case m.invalid_intersection_types:t="Intersection results could not be merged";break;case m.not_multiple_of:t=`Number must be a multiple of ${s.multipleOf}`;break;case m.not_finite:t="Number must be finite";break;default:t=e.defaultError,R.assertNever(s)}return{message:t}};let mn=at;function ei(){return mn}const ti=s=>{const{data:e,path:t,errorMaps:i,issueData:n}=s,r=[...t,...n.path||[]],a={...n,path:r};if(n.message!==void 0)return{...n,path:r,message:n.message};let o="";const l=i.filter(c=>!!c).slice().reverse();for(const c of l)o=c(a,{data:e,defaultError:o}).message;return{...n,path:r,message:o}};function y(s,e){const t=ei(),i=ti({issueData:e,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,t,t===at?void 0:at].filter(n=>!!n)});s.common.issues.push(i)}class j{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const i=[];for(const n of t){if(n.status==="aborted")return E;n.status==="dirty"&&e.dirty(),i.push(n.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const n of t){const r=await n.key,a=await n.value;i.push({key:r,value:a})}return j.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const n of t){const{key:r,value:a}=n;if(r.status==="aborted"||a.status==="aborted")return E;r.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),r.value!=="__proto__"&&(typeof a.value<"u"||n.alwaysSet)&&(i[r.value]=a.value)}return{status:e.value,value:i}}}const E=Object.freeze({status:"aborted"}),ot=s=>({status:"dirty",value:s}),q=s=>({status:"valid",value:s}),Ri=s=>s.status==="aborted",Bi=s=>s.status==="dirty",Ze=s=>s.status==="valid",St=s=>typeof Promise<"u"&&s instanceof Promise;function _t(s,e,t,i){if(typeof e=="function"?s!==e||!0:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(s)}function Li(s,e,t,i,n){if(typeof e=="function"?s!==e||!0:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(s,t),t}typeof SuppressedError=="function"&&SuppressedError;var v;(function(s){s.errToObj=e=>typeof e=="string"?{message:e}:e||{},s.toString=e=>typeof e=="string"?e:e?.message})(v||(v={}));var ct,lt;class oe{constructor(e,t,i,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=n}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 Fi=(s,e)=>{if(Ze(e))return{success:!0,data:e.value};if(!s.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ie(s.common.issues);return this._error=t,this._error}}};function P(s){if(!s)return{};const{errorMap:e,invalid_type_error:t,required_error:i,description:n}=s;if(e&&(t||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(a,o)=>{var l,c;const{message:h}=s;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??t)!==null&&c!==void 0?c:o.defaultError}},description:n}}class A{get description(){return this._def.description}_getType(e){return ke(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ke(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new j,ctx:{common:e.parent.common,data:e.data,parsedType:ke(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(St(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){var i;const n={common:{issues:[],async:(i=t?.async)!==null&&i!==void 0?i:!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ke(e)},r=this._parseSync({data:e,path:n.path,parent:n});return Fi(n,r)}"~validate"(e){var t,i;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ke(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:n});return Ze(r)?{value:r.value}:{issues:n.common.issues}}catch(r){!((i=(t=r?.message)===null||t===void 0?void 0:t.toLowerCase())===null||i===void 0)&&i.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>Ze(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,t){const i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){const i={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ke(e)},n=this._parse({data:e,path:i.path,parent:i}),r=await(St(n)?n:Promise.resolve(n));return Fi(i,r)}refine(e,t){const i=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,r)=>{const a=e(n),o=()=>r.addIssue({code:m.custom,...i(n)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,t){return this._refinement((i,n)=>e(i)?!0:(n.addIssue(typeof t=="function"?t(i,n):t),!1))}_refinement(e){return new Ce({schema:this,typeName:S.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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:t=>this["~validate"](t)}}optional(){return xe.create(this,this._def)}nullable(){return Le.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ce.create(this)}promise(){return ut.create(this,this._def)}or(e){return Pt.create([this,e],this._def)}and(e){return At.create(this,e,this._def)}transform(e){return new Ce({...P(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Lt({...P(this._def),innerType:this,defaultValue:t,typeName:S.ZodDefault})}brand(){return new Vi({typeName:S.ZodBranded,type:this,...P(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Ft({...P(this._def),innerType:this,catchValue:t,typeName:S.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return zt.create(this,e)}readonly(){return Dt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const gn=/^c[^\s-]{8,}$/i,yn=/^[0-9a-z]+$/,wn=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Cn=/^[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,xn=/^[a-z0-9_-]{21}$/i,vn=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Tn=/^[-+]?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)?)??$/,bn=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,kn="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ii;const Sn=/^(?:(?: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])$/,_n=/^(?:(?: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])$/,En=/^(([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]))$/,In=/^(([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])$/,Pn=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,An=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,zi="((\\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])))",On=new RegExp(`^${zi}$`);function Di(s){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return s.precision?e=`${e}\\.\\d{${s.precision}}`:s.precision==null&&(e=`${e}(\\.\\d+)?`),e}function Mn(s){return new RegExp(`^${Di(s)}$`)}function Rn(s){let e=`${zi}T${Di(s)}`;const t=[];return t.push(s.local?"Z?":"Z"),s.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Bn(s,e){return!!((e==="v4"||!e)&&Sn.test(s)||(e==="v6"||!e)&&En.test(s))}function Ln(s,e){if(!vn.test(s))return!1;try{const[t]=s.split("."),i=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(i));return!(typeof n!="object"||n===null||!n.typ||!n.alg||e&&n.alg!==e)}catch{return!1}}function Fn(s,e){return!!((e==="v4"||!e)&&_n.test(s)||(e==="v6"||!e)&&In.test(s))}class ge extends A{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==C.string){const r=this._getOrReturnCtx(e);return y(r,{code:m.invalid_type,expected:C.string,received:r.parsedType}),E}const i=new j;let n;for(const r of this._def.checks)if(r.kind==="min")e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),y(n,{code:m.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),i.dirty());else if(r.kind==="max")e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),y(n,{code:m.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),i.dirty());else if(r.kind==="length"){const a=e.data.length>r.value,o=e.data.length<r.value;(a||o)&&(n=this._getOrReturnCtx(e,n),a?y(n,{code:m.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):o&&y(n,{code:m.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),i.dirty())}else if(r.kind==="email")bn.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"email",code:m.invalid_string,message:r.message}),i.dirty());else if(r.kind==="emoji")ii||(ii=new RegExp(kn,"u")),ii.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"emoji",code:m.invalid_string,message:r.message}),i.dirty());else if(r.kind==="uuid")Cn.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"uuid",code:m.invalid_string,message:r.message}),i.dirty());else if(r.kind==="nanoid")xn.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"nanoid",code:m.invalid_string,message:r.message}),i.dirty());else if(r.kind==="cuid")gn.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"cuid",code:m.invalid_string,message:r.message}),i.dirty());else if(r.kind==="cuid2")yn.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"cuid2",code:m.invalid_string,message:r.message}),i.dirty());else if(r.kind==="ulid")wn.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"ulid",code:m.invalid_string,message:r.message}),i.dirty());else if(r.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),y(n,{validation:"url",code:m.invalid_string,message:r.message}),i.dirty()}else r.kind==="regex"?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"regex",code:m.invalid_string,message:r.message}),i.dirty())):r.kind==="trim"?e.data=e.data.trim():r.kind==="includes"?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),y(n,{code:m.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),i.dirty()):r.kind==="toLowerCase"?e.data=e.data.toLowerCase():r.kind==="toUpperCase"?e.data=e.data.toUpperCase():r.kind==="startsWith"?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),y(n,{code:m.invalid_string,validation:{startsWith:r.value},message:r.message}),i.dirty()):r.kind==="endsWith"?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),y(n,{code:m.invalid_string,validation:{endsWith:r.value},message:r.message}),i.dirty()):r.kind==="datetime"?Rn(r).test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{code:m.invalid_string,validation:"datetime",message:r.message}),i.dirty()):r.kind==="date"?On.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{code:m.invalid_string,validation:"date",message:r.message}),i.dirty()):r.kind==="time"?Mn(r).test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{code:m.invalid_string,validation:"time",message:r.message}),i.dirty()):r.kind==="duration"?Tn.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"duration",code:m.invalid_string,message:r.message}),i.dirty()):r.kind==="ip"?Bn(e.data,r.version)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"ip",code:m.invalid_string,message:r.message}),i.dirty()):r.kind==="jwt"?Ln(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"jwt",code:m.invalid_string,message:r.message}),i.dirty()):r.kind==="cidr"?Fn(e.data,r.version)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"cidr",code:m.invalid_string,message:r.message}),i.dirty()):r.kind==="base64"?Pn.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"base64",code:m.invalid_string,message:r.message}),i.dirty()):r.kind==="base64url"?An.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"base64url",code:m.invalid_string,message:r.message}),i.dirty()):R.assertNever(r);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(n=>e.test(n),{validation:t,code:m.invalid_string,...v.errToObj(i)})}_addCheck(e){return new ge({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...v.errToObj(e)})}url(e){return this._addCheck({kind:"url",...v.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...v.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...v.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...v.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...v.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...v.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...v.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...v.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...v.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...v.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...v.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...v.errToObj(e)})}datetime(e){var t,i;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:(t=e?.offset)!==null&&t!==void 0?t:!1,local:(i=e?.local)!==null&&i!==void 0?i:!1,...v.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...v.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...v.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...v.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...v.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...v.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...v.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...v.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...v.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...v.errToObj(t)})}nonempty(e){return this.min(1,v.errToObj(e))}trim(){return new ge({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ge({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ge({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ge.create=s=>{var e;return new ge({checks:[],typeName:S.ZodString,coerce:(e=s?.coerce)!==null&&e!==void 0?e:!1,...P(s)})};function zn(s,e){const t=(s.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,n=t>i?t:i,r=parseInt(s.toFixed(n).replace(".","")),a=parseInt(e.toFixed(n).replace(".",""));return r%a/Math.pow(10,n)}class Ke extends A{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==C.number){const r=this._getOrReturnCtx(e);return y(r,{code:m.invalid_type,expected:C.number,received:r.parsedType}),E}let i;const n=new j;for(const r of this._def.checks)r.kind==="int"?R.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),y(i,{code:m.invalid_type,expected:"integer",received:"float",message:r.message}),n.dirty()):r.kind==="min"?(r.inclusive?e.data<r.value:e.data<=r.value)&&(i=this._getOrReturnCtx(e,i),y(i,{code:m.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind==="max"?(r.inclusive?e.data>r.value:e.data>=r.value)&&(i=this._getOrReturnCtx(e,i),y(i,{code:m.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind==="multipleOf"?zn(e.data,r.value)!==0&&(i=this._getOrReturnCtx(e,i),y(i,{code:m.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),y(i,{code:m.not_finite,message:r.message}),n.dirty()):R.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,i,n){return new Ke({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:v.toString(n)}]})}_addCheck(e){return new Ke({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:v.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:v.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:v.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:v.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&R.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(t===null||i.value>t)&&(t=i.value):i.kind==="max"&&(e===null||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Ke.create=s=>new Ke({checks:[],typeName:S.ZodNumber,coerce:s?.coerce||!1,...P(s)});class je extends A{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==C.bigint)return this._getInvalidInput(e);let i;const n=new j;for(const r of this._def.checks)r.kind==="min"?(r.inclusive?e.data<r.value:e.data<=r.value)&&(i=this._getOrReturnCtx(e,i),y(i,{code:m.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind==="max"?(r.inclusive?e.data>r.value:e.data>=r.value)&&(i=this._getOrReturnCtx(e,i),y(i,{code:m.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind==="multipleOf"?e.data%r.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),y(i,{code:m.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):R.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return y(t,{code:m.invalid_type,expected:C.bigint,received:t.parsedType}),E}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,i,n){return new je({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:v.toString(n)}]})}_addCheck(e){return new je({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}je.create=s=>{var e;return new je({checks:[],typeName:S.ZodBigInt,coerce:(e=s?.coerce)!==null&&e!==void 0?e:!1,...P(s)})};class si extends A{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==C.boolean){const i=this._getOrReturnCtx(e);return y(i,{code:m.invalid_type,expected:C.boolean,received:i.parsedType}),E}return q(e.data)}}si.create=s=>new si({typeName:S.ZodBoolean,coerce:s?.coerce||!1,...P(s)});class ht extends A{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==C.date){const r=this._getOrReturnCtx(e);return y(r,{code:m.invalid_type,expected:C.date,received:r.parsedType}),E}if(isNaN(e.data.getTime())){const r=this._getOrReturnCtx(e);return y(r,{code:m.invalid_date}),E}const i=new j;let n;for(const r of this._def.checks)r.kind==="min"?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),y(n,{code:m.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),i.dirty()):r.kind==="max"?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),y(n,{code:m.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),i.dirty()):R.assertNever(r);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ht({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:v.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:v.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}ht.create=s=>new ht({checks:[],coerce:s?.coerce||!1,typeName:S.ZodDate,...P(s)});class ni extends A{_parse(e){if(this._getType(e)!==C.symbol){const i=this._getOrReturnCtx(e);return y(i,{code:m.invalid_type,expected:C.symbol,received:i.parsedType}),E}return q(e.data)}}ni.create=s=>new ni({typeName:S.ZodSymbol,...P(s)});class Et extends A{_parse(e){if(this._getType(e)!==C.undefined){const i=this._getOrReturnCtx(e);return y(i,{code:m.invalid_type,expected:C.undefined,received:i.parsedType}),E}return q(e.data)}}Et.create=s=>new Et({typeName:S.ZodUndefined,...P(s)});class It extends A{_parse(e){if(this._getType(e)!==C.null){const i=this._getOrReturnCtx(e);return y(i,{code:m.invalid_type,expected:C.null,received:i.parsedType}),E}return q(e.data)}}It.create=s=>new It({typeName:S.ZodNull,...P(s)});class ri extends A{constructor(){super(...arguments),this._any=!0}_parse(e){return q(e.data)}}ri.create=s=>new ri({typeName:S.ZodAny,...P(s)});class Xe extends A{constructor(){super(...arguments),this._unknown=!0}_parse(e){return q(e.data)}}Xe.create=s=>new Xe({typeName:S.ZodUnknown,...P(s)});class Se extends A{_parse(e){const t=this._getOrReturnCtx(e);return y(t,{code:m.invalid_type,expected:C.never,received:t.parsedType}),E}}Se.create=s=>new Se({typeName:S.ZodNever,...P(s)});class ai extends A{_parse(e){if(this._getType(e)!==C.undefined){const i=this._getOrReturnCtx(e);return y(i,{code:m.invalid_type,expected:C.void,received:i.parsedType}),E}return q(e.data)}}ai.create=s=>new ai({typeName:S.ZodVoid,...P(s)});class ce extends A{_parse(e){const{ctx:t,status:i}=this._processInputParams(e),n=this._def;if(t.parsedType!==C.array)return y(t,{code:m.invalid_type,expected:C.array,received:t.parsedType}),E;if(n.exactLength!==null){const a=t.data.length>n.exactLength.value,o=t.data.length<n.exactLength.value;(a||o)&&(y(t,{code:a?m.too_big:m.too_small,minimum:o?n.exactLength.value:void 0,maximum:a?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),i.dirty())}if(n.minLength!==null&&t.data.length<n.minLength.value&&(y(t,{code:m.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),i.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(y(t,{code:m.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((a,o)=>n.type._parseAsync(new oe(t,a,t.path,o)))).then(a=>j.mergeArray(i,a));const r=[...t.data].map((a,o)=>n.type._parseSync(new oe(t,a,t.path,o)));return j.mergeArray(i,r)}get element(){return this._def.type}min(e,t){return new ce({...this._def,minLength:{value:e,message:v.toString(t)}})}max(e,t){return new ce({...this._def,maxLength:{value:e,message:v.toString(t)}})}length(e,t){return new ce({...this._def,exactLength:{value:e,message:v.toString(t)}})}nonempty(e){return this.min(1,e)}}ce.create=(s,e)=>new ce({type:s,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...P(e)});function Ye(s){if(s instanceof H){const e={};for(const t in s.shape){const i=s.shape[t];e[t]=xe.create(Ye(i))}return new H({...s._def,shape:()=>e})}else return s instanceof ce?new ce({...s._def,type:Ye(s.element)}):s instanceof xe?xe.create(Ye(s.unwrap())):s instanceof Le?Le.create(Ye(s.unwrap())):s instanceof we?we.create(s.items.map(e=>Ye(e))):s}class H extends A{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=R.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==C.object){const c=this._getOrReturnCtx(e);return y(c,{code:m.invalid_type,expected:C.object,received:c.parsedType}),E}const{status:i,ctx:n}=this._processInputParams(e),{shape:r,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof Se&&this._def.unknownKeys==="strip"))for(const c in n.data)a.includes(c)||o.push(c);const l=[];for(const c of a){const h=r[c],d=n.data[c];l.push({key:{status:"valid",value:c},value:h._parse(new oe(n,d,n.path,c)),alwaysSet:c in n.data})}if(this._def.catchall instanceof Se){const c=this._def.unknownKeys;if(c==="passthrough")for(const h of o)l.push({key:{status:"valid",value:h},value:{status:"valid",value:n.data[h]}});else if(c==="strict")o.length>0&&(y(n,{code:m.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 d=n.data[h];l.push({key:{status:"valid",value:h},value:c._parse(new oe(n,d,n.path,h)),alwaysSet:h in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const c=[];for(const h of l){const d=await h.key,u=await h.value;c.push({key:d,value:u,alwaysSet:h.alwaysSet})}return c}).then(c=>j.mergeObjectSync(i,c)):j.mergeObjectSync(i,l)}get shape(){return this._def.shape()}strict(e){return v.errToObj,new H({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{var n,r,a,o;const l=(a=(r=(n=this._def).errorMap)===null||r===void 0?void 0:r.call(n,t,i).message)!==null&&a!==void 0?a:i.defaultError;return t.code==="unrecognized_keys"?{message:(o=v.errToObj(e).message)!==null&&o!==void 0?o:l}:{message:l}}}:{}})}strip(){return new H({...this._def,unknownKeys:"strip"})}passthrough(){return new H({...this._def,unknownKeys:"passthrough"})}extend(e){return new H({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new H({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:S.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new H({...this._def,catchall:e})}pick(e){const t={};return R.objectKeys(e).forEach(i=>{e[i]&&this.shape[i]&&(t[i]=this.shape[i])}),new H({...this._def,shape:()=>t})}omit(e){const t={};return R.objectKeys(this.shape).forEach(i=>{e[i]||(t[i]=this.shape[i])}),new H({...this._def,shape:()=>t})}deepPartial(){return Ye(this)}partial(e){const t={};return R.objectKeys(this.shape).forEach(i=>{const n=this.shape[i];e&&!e[i]?t[i]=n:t[i]=n.optional()}),new H({...this._def,shape:()=>t})}required(e){const t={};return R.objectKeys(this.shape).forEach(i=>{if(e&&!e[i])t[i]=this.shape[i];else{let r=this.shape[i];for(;r instanceof xe;)r=r._def.innerType;t[i]=r}}),new H({...this._def,shape:()=>t})}keyof(){return Hi(R.objectKeys(this.shape))}}H.create=(s,e)=>new H({shape:()=>s,unknownKeys:"strip",catchall:Se.create(),typeName:S.ZodObject,...P(e)}),H.strictCreate=(s,e)=>new H({shape:()=>s,unknownKeys:"strict",catchall:Se.create(),typeName:S.ZodObject,...P(e)}),H.lazycreate=(s,e)=>new H({shape:s,unknownKeys:"strip",catchall:Se.create(),typeName:S.ZodObject,...P(e)});class Pt extends A{_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;function n(r){for(const o of r)if(o.result.status==="valid")return o.result;for(const o of r)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const a=r.map(o=>new ie(o.ctx.common.issues));return y(t,{code:m.invalid_union,unionErrors:a}),E}if(t.common.async)return Promise.all(i.map(async r=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await r._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(n);{let r;const a=[];for(const l of i){const c={...t,common:{...t.common,issues:[]},parent:null},h=l._parseSync({data:t.data,path:t.path,parent:c});if(h.status==="valid")return h;h.status==="dirty"&&!r&&(r={result:h,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(r)return t.common.issues.push(...r.ctx.common.issues),r.result;const o=a.map(l=>new ie(l));return y(t,{code:m.invalid_union,unionErrors:o}),E}}get options(){return this._def.options}}Pt.create=(s,e)=>new Pt({options:s,typeName:S.ZodUnion,...P(e)});const ye=s=>s instanceof Mt?ye(s.schema):s instanceof Ce?ye(s.innerType()):s instanceof Rt?[s.value]:s instanceof Be?s.options:s instanceof Bt?R.objectValues(s.enum):s instanceof Lt?ye(s._def.innerType):s instanceof Et?[void 0]:s instanceof It?[null]:s instanceof xe?[void 0,...ye(s.unwrap())]:s instanceof Le?[null,...ye(s.unwrap())]:s instanceof Vi||s instanceof Dt?ye(s.unwrap()):s instanceof Ft?ye(s._def.innerType):[];class oi extends A{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==C.object)return y(t,{code:m.invalid_type,expected:C.object,received:t.parsedType}),E;const i=this.discriminator,n=t.data[i],r=this.optionsMap.get(n);return r?t.common.async?r._parseAsync({data:t.data,path:t.path,parent:t}):r._parseSync({data:t.data,path:t.path,parent:t}):(y(t,{code:m.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),E)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,i){const n=new Map;for(const r of t){const a=ye(r.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(n.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);n.set(o,r)}}return new oi({typeName:S.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...P(i)})}}function ci(s,e){const t=ke(s),i=ke(e);if(s===e)return{valid:!0,data:s};if(t===C.object&&i===C.object){const n=R.objectKeys(e),r=R.objectKeys(s).filter(o=>n.indexOf(o)!==-1),a={...s,...e};for(const o of r){const l=ci(s[o],e[o]);if(!l.valid)return{valid:!1};a[o]=l.data}return{valid:!0,data:a}}else if(t===C.array&&i===C.array){if(s.length!==e.length)return{valid:!1};const n=[];for(let r=0;r<s.length;r++){const a=s[r],o=e[r],l=ci(a,o);if(!l.valid)return{valid:!1};n.push(l.data)}return{valid:!0,data:n}}else return t===C.date&&i===C.date&&+s==+e?{valid:!0,data:s}:{valid:!1}}class At extends A{_parse(e){const{status:t,ctx:i}=this._processInputParams(e),n=(r,a)=>{if(Ri(r)||Ri(a))return E;const o=ci(r.value,a.value);return o.valid?((Bi(r)||Bi(a))&&t.dirty(),{status:t.value,value:o.data}):(y(i,{code:m.invalid_intersection_types}),E)};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(([r,a])=>n(r,a)):n(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}At.create=(s,e,t)=>new At({left:s,right:e,typeName:S.ZodIntersection,...P(t)});class we extends A{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==C.array)return y(i,{code:m.invalid_type,expected:C.array,received:i.parsedType}),E;if(i.data.length<this._def.items.length)return y(i,{code:m.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),E;!this._def.rest&&i.data.length>this._def.items.length&&(y(i,{code:m.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const r=[...i.data].map((a,o)=>{const l=this._def.items[o]||this._def.rest;return l?l._parse(new oe(i,a,i.path,o)):null}).filter(a=>!!a);return i.common.async?Promise.all(r).then(a=>j.mergeArray(t,a)):j.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new we({...this._def,rest:e})}}we.create=(s,e)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new we({items:s,typeName:S.ZodTuple,rest:null,...P(e)})};class Ot extends A{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==C.object)return y(i,{code:m.invalid_type,expected:C.object,received:i.parsedType}),E;const n=[],r=this._def.keyType,a=this._def.valueType;for(const o in i.data)n.push({key:r._parse(new oe(i,o,i.path,o)),value:a._parse(new oe(i,i.data[o],i.path,o)),alwaysSet:o in i.data});return i.common.async?j.mergeObjectAsync(t,n):j.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,i){return t instanceof A?new Ot({keyType:e,valueType:t,typeName:S.ZodRecord,...P(i)}):new Ot({keyType:ge.create(),valueType:e,typeName:S.ZodRecord,...P(t)})}}class li extends A{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==C.map)return y(i,{code:m.invalid_type,expected:C.map,received:i.parsedType}),E;const n=this._def.keyType,r=this._def.valueType,a=[...i.data.entries()].map(([o,l],c)=>({key:n._parse(new oe(i,o,i.path,[c,"key"])),value:r._parse(new oe(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 E;(c.status==="dirty"||h.status==="dirty")&&t.dirty(),o.set(c.value,h.value)}return{status:t.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 E;(c.status==="dirty"||h.status==="dirty")&&t.dirty(),o.set(c.value,h.value)}return{status:t.value,value:o}}}}li.create=(s,e,t)=>new li({valueType:e,keyType:s,typeName:S.ZodMap,...P(t)});class qe extends A{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==C.set)return y(i,{code:m.invalid_type,expected:C.set,received:i.parsedType}),E;const n=this._def;n.minSize!==null&&i.data.size<n.minSize.value&&(y(i,{code:m.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),n.maxSize!==null&&i.data.size>n.maxSize.value&&(y(i,{code:m.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const r=this._def.valueType;function a(l){const c=new Set;for(const h of l){if(h.status==="aborted")return E;h.status==="dirty"&&t.dirty(),c.add(h.value)}return{status:t.value,value:c}}const o=[...i.data.values()].map((l,c)=>r._parse(new oe(i,l,i.path,c)));return i.common.async?Promise.all(o).then(l=>a(l)):a(o)}min(e,t){return new qe({...this._def,minSize:{value:e,message:v.toString(t)}})}max(e,t){return new qe({...this._def,maxSize:{value:e,message:v.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}qe.create=(s,e)=>new qe({valueType:s,minSize:null,maxSize:null,typeName:S.ZodSet,...P(e)});class dt extends A{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==C.function)return y(t,{code:m.invalid_type,expected:C.function,received:t.parsedType}),E;function i(o,l){return ti({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ei(),at].filter(c=>!!c),issueData:{code:m.invalid_arguments,argumentsError:l}})}function n(o,l){return ti({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ei(),at].filter(c=>!!c),issueData:{code:m.invalid_return_type,returnTypeError:l}})}const r={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof ut){const o=this;return q(async function(...l){const c=new ie([]),h=await o._def.args.parseAsync(l,r).catch(p=>{throw c.addIssue(i(l,p)),c}),d=await Reflect.apply(a,this,h);return await o._def.returns._def.type.parseAsync(d,r).catch(p=>{throw c.addIssue(n(d,p)),c})})}else{const o=this;return q(function(...l){const c=o._def.args.safeParse(l,r);if(!c.success)throw new ie([i(l,c.error)]);const h=Reflect.apply(a,this,c.data),d=o._def.returns.safeParse(h,r);if(!d.success)throw new ie([n(h,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new dt({...this._def,args:we.create(e).rest(Xe.create())})}returns(e){return new dt({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,i){return new dt({args:e||we.create([]).rest(Xe.create()),returns:t||Xe.create(),typeName:S.ZodFunction,...P(i)})}}class Mt extends A{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Mt.create=(s,e)=>new Mt({getter:s,typeName:S.ZodLazy,...P(e)});class Rt extends A{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return y(t,{received:t.data,code:m.invalid_literal,expected:this._def.value}),E}return{status:"valid",value:e.data}}get value(){return this._def.value}}Rt.create=(s,e)=>new Rt({value:s,typeName:S.ZodLiteral,...P(e)});function Hi(s,e){return new Be({values:s,typeName:S.ZodEnum,...P(e)})}class Be extends A{constructor(){super(...arguments),ct.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),i=this._def.values;return y(t,{expected:R.joinValues(i),received:t.parsedType,code:m.invalid_type}),E}if(_t(this,ct)||Li(this,ct,new Set(this._def.values)),!_t(this,ct).has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return y(t,{received:t.data,code:m.invalid_enum_value,options:i}),E}return q(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Be.create(e,{...this._def,...t})}exclude(e,t=this._def){return Be.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}}ct=new WeakMap,Be.create=Hi;class Bt extends A{constructor(){super(...arguments),lt.set(this,void 0)}_parse(e){const t=R.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==C.string&&i.parsedType!==C.number){const n=R.objectValues(t);return y(i,{expected:R.joinValues(n),received:i.parsedType,code:m.invalid_type}),E}if(_t(this,lt)||Li(this,lt,new Set(R.getValidEnumValues(this._def.values))),!_t(this,lt).has(e.data)){const n=R.objectValues(t);return y(i,{received:i.data,code:m.invalid_enum_value,options:n}),E}return q(e.data)}get enum(){return this._def.values}}lt=new WeakMap,Bt.create=(s,e)=>new Bt({values:s,typeName:S.ZodNativeEnum,...P(e)});class ut extends A{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==C.promise&&t.common.async===!1)return y(t,{code:m.invalid_type,expected:C.promise,received:t.parsedType}),E;const i=t.parsedType===C.promise?t.data:Promise.resolve(t.data);return q(i.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ut.create=(s,e)=>new ut({type:s,typeName:S.ZodPromise,...P(e)});class Ce extends A{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:i}=this._processInputParams(e),n=this._def.effect||null,r={addIssue:a=>{y(i,a),a.fatal?t.abort():t.dirty()},get path(){return i.path}};if(r.addIssue=r.addIssue.bind(r),n.type==="preprocess"){const a=n.transform(i.data,r);if(i.common.async)return Promise.resolve(a).then(async o=>{if(t.value==="aborted")return E;const l=await this._def.schema._parseAsync({data:o,path:i.path,parent:i});return l.status==="aborted"?E:l.status==="dirty"||t.value==="dirty"?ot(l.value):l});{if(t.value==="aborted")return E;const o=this._def.schema._parseSync({data:a,path:i.path,parent:i});return o.status==="aborted"?E:o.status==="dirty"||t.value==="dirty"?ot(o.value):o}}if(n.type==="refinement"){const a=o=>{const l=n.refinement(o,r);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"?E:(o.status==="dirty"&&t.dirty(),a(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(o=>o.status==="aborted"?E:(o.status==="dirty"&&t.dirty(),a(o.value).then(()=>({status:t.value,value:o.value}))))}if(n.type==="transform")if(i.common.async===!1){const a=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!Ze(a))return a;const o=n.transform(a.value,r);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(a=>Ze(a)?Promise.resolve(n.transform(a.value,r)).then(o=>({status:t.value,value:o})):a);R.assertNever(n)}}Ce.create=(s,e,t)=>new Ce({schema:s,typeName:S.ZodEffects,effect:e,...P(t)}),Ce.createWithPreprocess=(s,e,t)=>new Ce({schema:e,effect:{type:"preprocess",transform:s},typeName:S.ZodEffects,...P(t)});class xe extends A{_parse(e){return this._getType(e)===C.undefined?q(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}xe.create=(s,e)=>new xe({innerType:s,typeName:S.ZodOptional,...P(e)});class Le extends A{_parse(e){return this._getType(e)===C.null?q(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Le.create=(s,e)=>new Le({innerType:s,typeName:S.ZodNullable,...P(e)});class Lt extends A{_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===C.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Lt.create=(s,e)=>new Lt({innerType:s,typeName:S.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...P(e)});class Ft extends A{_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return St(n)?n.then(r=>({status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new ie(i.common.issues)},input:i.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new ie(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Ft.create=(s,e)=>new Ft({innerType:s,typeName:S.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...P(e)});class hi extends A{_parse(e){if(this._getType(e)!==C.nan){const i=this._getOrReturnCtx(e);return y(i,{code:m.invalid_type,expected:C.nan,received:i.parsedType}),E}return{status:"valid",value:e.data}}}hi.create=s=>new hi({typeName:S.ZodNaN,...P(s)});class Vi extends A{_parse(e){const{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class zt extends A{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const r=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return r.status==="aborted"?E:r.status==="dirty"?(t.dirty(),ot(r.value)):this._def.out._parseAsync({data:r.value,path:i.path,parent:i})})();{const n=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return n.status==="aborted"?E:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:i.path,parent:i})}}static create(e,t){return new zt({in:e,out:t,typeName:S.ZodPipeline})}}class Dt extends A{_parse(e){const t=this._def.innerType._parse(e),i=n=>(Ze(n)&&(n.value=Object.freeze(n.value)),n);return St(t)?t.then(n=>i(n)):i(t)}unwrap(){return this._def.innerType}}Dt.create=(s,e)=>new Dt({innerType:s,typeName:S.ZodReadonly,...P(e)}),H.lazycreate;var S;(function(s){s.ZodString="ZodString",s.ZodNumber="ZodNumber",s.ZodNaN="ZodNaN",s.ZodBigInt="ZodBigInt",s.ZodBoolean="ZodBoolean",s.ZodDate="ZodDate",s.ZodSymbol="ZodSymbol",s.ZodUndefined="ZodUndefined",s.ZodNull="ZodNull",s.ZodAny="ZodAny",s.ZodUnknown="ZodUnknown",s.ZodNever="ZodNever",s.ZodVoid="ZodVoid",s.ZodArray="ZodArray",s.ZodObject="ZodObject",s.ZodUnion="ZodUnion",s.ZodDiscriminatedUnion="ZodDiscriminatedUnion",s.ZodIntersection="ZodIntersection",s.ZodTuple="ZodTuple",s.ZodRecord="ZodRecord",s.ZodMap="ZodMap",s.ZodSet="ZodSet",s.ZodFunction="ZodFunction",s.ZodLazy="ZodLazy",s.ZodLiteral="ZodLiteral",s.ZodEnum="ZodEnum",s.ZodEffects="ZodEffects",s.ZodNativeEnum="ZodNativeEnum",s.ZodOptional="ZodOptional",s.ZodNullable="ZodNullable",s.ZodDefault="ZodDefault",s.ZodCatch="ZodCatch",s.ZodPromise="ZodPromise",s.ZodBranded="ZodBranded",s.ZodPipeline="ZodPipeline",s.ZodReadonly="ZodReadonly"})(S||(S={}));const X=ge.create,k=Ke.create;hi.create,je.create,si.create,ht.create,ni.create,Et.create,It.create,ri.create,Xe.create,Se.create,ai.create,ce.create;const L=H.create;H.strictCreate;const Dn=Pt.create;oi.create,At.create,we.create,Ot.create,li.create,qe.create,dt.create,Mt.create;const Fe=Rt.create,_e=Be.create;Bt.create,ut.create,Ce.create,xe.create,Le.create,Ce.createWithPreprocess,zt.create;const Hn=_e(["linear","bezier","constant"]),Vn=_e(["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"]),ze=L({from:k(),to:k(),start:k().min(0),length:k().positive(),interpolation:Hn.optional(),easing:Vn.optional()}),Nn=X().url("Invalid audio url format."),Un=ze.extend({from:k().min(0).max(1),to:k().min(0).max(1)}).array().or(k().min(0).max(1)),Ni=L({type:Fe("audio"),src:Nn,trim:k().optional(),volume:Un.optional()}),Wn=_e(["top","topRight","right","bottomRight","bottom","bottomLeft","left","topLeft","center"]),Ui=L({type:Fe("html"),html:X(),css:X(),width:k().positive().optional(),height:k().positive().optional(),position:Wn.optional()}),Gn=X().url("Invalid image url format."),$n=L({top:k().min(0).optional(),right:k().min(0).optional(),bottom:k().min(0).optional(),left:k().min(0).optional()}),Wi=L({type:Fe("image"),src:Gn,crop:$n.optional()}),Zn=X().url("Invalid luma url format."),Gi=L({type:Fe("luma"),src:Zn}),$i=X().regex(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})|transparent$/,"Invalid color format."),Zi=L({width:k().positive(),height:k().positive()}),Ki=L({radius:k().positive()}),ji=L({length:k().positive(),thickness:k().positive()}),Kn=L({color:$i,opacity:k().min(0).max(1)}),jn=L({color:$i,width:k().positive()}),Xi=L({type:Fe("shape"),width:k().positive().optional(),height:k().positive().optional(),shape:_e(["rectangle","circle","line"]),fill:Kn.optional(),stroke:jn.optional(),rectangle:Zi.optional(),circle:Ki.optional(),line:ji.optional()}).refine(s=>s.shape==="rectangle"?Zi.safeParse(s.rectangle):s.shape==="circle"?Ki.safeParse(s.circle):s.shape==="line"?ji.safeParse(s.line):!1),di=X().regex(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})|transparent$/,"Invalid color format."),Xn=L({color:di.optional(),family:X().optional(),size:k().positive().optional(),weight:k().optional(),lineHeight:k().optional()}),Yn=L({horizontal:_e(["left","center","right"]).optional(),vertical:_e(["top","center","bottom"]).optional()}),qn=L({color:di,opacity:k().min(0).max(1)}),Qn=L({width:k().positive(),color:di}),Yi=L({type:Fe("text"),text:X(),width:k().positive().optional(),height:k().positive().optional(),font:Xn.optional(),alignment:Yn.optional(),background:qn.optional(),stroke:Qn.optional()}),Jn=X().url("Invalid video url format."),er=L({top:k().min(0).optional(),right:k().min(0).optional(),bottom:k().min(0).optional(),left:k().min(0).optional()}),tr=ze.extend({from:k().min(0).max(1),to:k().min(0).max(1)}).array().or(k().min(0).max(1)),qi=L({type:Fe("video"),src:Jn,trim:k().optional(),crop:er.optional(),volume:tr.optional()}),ir=Dn([Yi,Xi,Ui,Wi,qi,Gi,Ni]).refine(s=>s.type==="text"?Yi.safeParse(s):s.type==="shape"?Xi.safeParse(s):s.type==="html"?Ui.safeParse(s):s.type==="image"?Wi.safeParse(s):s.type==="video"?qi.safeParse(s):s.type==="luma"?Gi.safeParse(s):s.type==="audio"?Ni.safeParse(s):!1),sr=_e(["topLeft","top","topRight","left","center","right","bottomLeft","bottom","bottomRight"]),nr=_e(["crop","cover","contain","none"]),Qe=k().min(-10).max(10).default(0),rr=ze.extend({from:Qe,to:Qe}).array().or(Qe),ar=ze.extend({from:Qe,to:Qe}).array().or(Qe),or=L({x:rr.default(0),y:ar.default(0)}),cr=ze.extend({from:k().min(0).max(1),to:k().min(0).max(1)}).array().or(k().min(0).max(1)),lr=ze.extend({from:k().min(0),to:k().min(0)}).array().or(k().min(0)),hr=L({angle:ze.extend({from:k(),to:k()}).array().or(k())}),dr=X(),Qi=X(),ur=L({in:Qi.optional(),out:Qi.optional()}),pr=L({rotate:hr.default({angle:0})}),Ji=L({asset:ir,start:k().min(0),length:k().positive(),position:sr.default("center").optional(),fit:nr.default("crop").optional(),offset:or.default({x:0,y:0}).optional(),opacity:cr.default(1).optional(),scale:lr.default(1).optional(),transform:pr.default({rotate:{angle:0}}).optional(),effect:dr.optional(),transition:ur.optional()});class fr{constructor(e,t){this.trackIdx=e,this.clip=t}name="addClip";addedPlayer;async execute(e){if(!e)return;const t=Ji.parse(this.clip),i=e.createPlayerFromAssetType(t);i.layer=this.trackIdx+1,await e.addPlayer(this.trackIdx,i),e.updateDuration(),this.addedPlayer=i}async undo(e){!e||!this.addedPlayer||(e.queueDisposeClip(this.addedPlayer),e.updateDuration())}}class es{constructor(e){this.trackIdx=e}name="addTrack";execute(e){if(!e)return;const t=e.getTracks(),i=e.getClips();t.splice(this.trackIdx,0,[]),i.forEach(n=>{if(n.layer>=this.trackIdx){const r=1e5-n.layer*100,a=e.getContainer().getChildByLabel(`shotstack-track-${r}`,!1);a&&a.removeChild(n.getContainer()),n.layer+=1;const o=1e5-n.layer*100;let l=e.getContainer().getChildByLabel(`shotstack-track-${o}`,!1);l||(l=new f.Container({label:`shotstack-track-${o}`,zIndex:o}),e.getContainer().addChild(l)),l.addChild(n.getContainer())}}),e.updateDuration(),e.emitEvent("track:added",{trackIndex:this.trackIdx,totalTracks:t.length})}undo(e){if(!e)return;const t=e.getTracks(),i=e.getClips();t.splice(this.trackIdx,1),i.forEach(n=>{n.layer>this.trackIdx&&(n.layer-=1)}),e.updateDuration()}}class mr{name="ClearSelection";previousSelection=null;execute(e){const t=e.getSelectedClip();if(t){const i=e.findClipIndices(t);i&&(this.previousSelection={player:t,trackIndex:i.trackIndex,clipIndex:i.clipIndex})}e.setSelectedClip(null),e.emitEvent("selection:cleared",{})}undo(e){if(this.previousSelection){const t=e.getClipAt(this.previousSelection.trackIndex,this.previousSelection.clipIndex);t&&(e.setSelectedClip(t),e.emitEvent("clip:selected",{clip:t.clipConfiguration,trackIndex:this.previousSelection.trackIndex,clipIndex:this.previousSelection.clipIndex}))}}}class gr{constructor(e,t){this.trackIdx=e,this.clipIdx=t}name="deleteClip";deletedClip;execute(e){if(!e)return;const i=e.getClips().filter(n=>n.layer===this.trackIdx+1);this.deletedClip=i[this.clipIdx],this.deletedClip&&(e.queueDisposeClip(this.deletedClip),e.updateDuration())}undo(e){!e||!this.deletedClip||e.undeleteClip(this.trackIdx,this.deletedClip)}}class yr{constructor(e){this.trackIdx=e}name="deleteTrack";deletedClips=[];execute(e){if(!e)return;const t=e.getClips(),i=e.getTracks();this.deletedClips=t.filter(a=>a.layer===this.trackIdx+1).map(a=>({config:structuredClone(a.clipConfiguration)})),t.forEach((a,o)=>{a.layer===this.trackIdx+1&&(t[o].shouldDispose=!0)}),e.disposeClips(),i.splice(this.trackIdx,1);const n=e.getClips(),r=e.getContainer();n.forEach((a,o)=>{if(a.layer>this.trackIdx+1){r.getChildByLabel(`shotstack-track-${1e5-a.layer*100}`,!1)?.removeChild(a.getContainer()),n[o].layer-=1;const c=1e5-n[o].layer*100;let h=r.getChildByLabel(`shotstack-track-${c}`,!1);h||(h=new f.Container({label:`shotstack-track-${c}`,zIndex:c}),r.addChild(h)),h.addChild(n[o].getContainer())}}),e.updateDuration()}async undo(e){if(!e||this.deletedClips.length===0)return;const t=e.getTracks(),i=e.getClips();t.splice(this.trackIdx,0,[]),i.forEach((n,r)=>{n.layer>=this.trackIdx+1&&(i[r].layer+=1)});for(const{config:n}of this.deletedClips){const r=e.createPlayerFromAssetType(n);r.layer=this.trackIdx+1,await e.addPlayer(this.trackIdx,r)}e.updateDuration()}}class wr{constructor(e,t){this.trackIndex=e,this.clipIndex=t}name="SelectClip";previousSelection=null;execute(e){const t=e.getSelectedClip();if(t){const n=e.findClipIndices(t);n&&(this.previousSelection=n)}const i=e.getClipAt(this.trackIndex,this.clipIndex);i&&(e.setSelectedClip(i),e.emitEvent("clip:selected",{clip:i.clipConfiguration,trackIndex:this.trackIndex,clipIndex:this.clipIndex}))}undo(e){if(e.setSelectedClip(null),this.previousSelection){const t=e.getClipAt(this.previousSelection.trackIndex,this.previousSelection.clipIndex);t&&(e.setSelectedClip(t),e.emitEvent("clip:selected",{clip:t.clipConfiguration,trackIndex:this.previousSelection.trackIndex,clipIndex:this.previousSelection.clipIndex}))}else e.emitEvent("selection:cleared",{})}}class Cr{constructor(e,t,i){this.clip=e,this.initialClipConfig=t,this.finalClipConfig=i,this.storedInitialConfig=t?structuredClone(t):null,this.storedFinalConfig=i?structuredClone(i):structuredClone(this.clip.clipConfiguration)}name="setUpdatedClip";storedInitialConfig;storedFinalConfig;execute(e){if(!e)return;this.storedFinalConfig&&e.restoreClipConfiguration(this.clip,this.storedFinalConfig),e.setUpdatedClip(this.clip);const t=this.clip.layer-1,r=e.getClips().filter(a=>a.layer===this.clip.layer).indexOf(this.clip);e.emitEvent("clip:updated",{previous:{clip:this.storedInitialConfig||this.initialClipConfig,trackIndex:t,clipIndex:r},current:{clip:this.storedFinalConfig||this.clip.clipConfiguration,trackIndex:t,clipIndex:r}})}undo(e){if(!e||!this.storedInitialConfig)return;e.restoreClipConfiguration(this.clip,this.storedInitialConfig),e.setUpdatedClip(this.clip);const t=this.clip.layer-1,r=e.getClips().filter(a=>a.layer===this.clip.layer).indexOf(this.clip);e.emitEvent("clip:updated",{previous:{clip:this.storedFinalConfig,trackIndex:t,clipIndex:r},current:{clip:this.storedInitialConfig,trackIndex:t,clipIndex:r}})}}class xr{constructor(e,t,i){this.trackIndex=e,this.clipIndex=t,this.splitTime=i}name="SplitClip";originalClipConfig=null;rightClipPlayer=null;splitSuccessful=!1;execute(e){const t=e.getClipAt(this.trackIndex,this.clipIndex);if(!t||!t.clipConfiguration)throw new Error("Cannot split clip: invalid player or clip configuration");const i=t.clipConfiguration,n=i.start||0,r=i.length,a=.1,o=this.splitTime-n;if(o<=a||o>=r-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:n+o,length:r-o};if(i.asset&&(l.asset={...i.asset},c.asset={...i.asset}),i.asset&&(i.asset.type==="video"||i.asset.type==="audio")){const p=i.asset.trim||0;l.asset&&(l.asset.type==="video"||l.asset.type==="audio")&&(l.asset.trim=p),c.asset&&(c.asset.type==="video"||c.asset.type==="audio")&&(c.asset.trim=p+o)}if(Object.assign(t.clipConfiguration,l),t.reconfigureAfterRestore(),t.draw(),this.rightClipPlayer=e.createPlayerFromAssetType(c),!this.rightClipPlayer)throw Object.assign(t.clipConfiguration,this.originalClipConfig),t.reconfigureAfterRestore(),new Error("Failed to create right clip player");this.rightClipPlayer.layer=this.trackIndex+1;const h=e.getTrack(this.trackIndex);if(!h)throw new Error("Invalid track index");h.splice(this.clipIndex+1,0,this.rightClipPlayer);const d=e.getClips(),u=d.indexOf(t);u!==-1&&d.splice(u+1,0,this.rightClipPlayer),e.addPlayerToContainer(this.trackIndex,this.rightClipPlayer),this.rightClipPlayer.reconfigureAfterRestore(),this.rightClipPlayer.load().then(()=>{this.splitSuccessful=!0,this.rightClipPlayer&&this.rightClipPlayer.draw(),e.updateDuration(),e.emitEvent("timeline:updated",{current:e.getEditState()})}).catch(p=>{console.error("Failed to load split clip:",p)})}undo(e){if(!this.originalClipConfig)return;const t=e.getClipAt(this.trackIndex,this.clipIndex);if(t){if(Object.assign(t.clipConfiguration,this.originalClipConfig),t.reconfigureAfterRestore(),this.rightClipPlayer){const i=e.getTrack(this.trackIndex);if(i){const a=i.indexOf(this.rightClipPlayer);a!==-1&&i.splice(a,1)}const n=e.getClips(),r=n.indexOf(this.rightClipPlayer);r!==-1&&n.splice(r,1),e.queueDisposeClip(this.rightClipPlayer),this.rightClipPlayer=null}e.updateDuration(),e.emitEvent("timeline:updated",{current:e.getEditState()})}}}class vr{constructor(e,t,i){this.clip=e,this.newText=t,this.initialConfig=i;const{asset:n}=this.clip.clipConfiguration;this.previousText=n&&"text"in n?n.text:""}name="updateTextContent";previousText;execute(e){if(e&&this.clip.clipConfiguration.asset&&"text"in this.clip.clipConfiguration.asset){this.clip.clipConfiguration.asset.text=this.newText;const t=this.clip.text;t&&(t.text=this.newText,this.clip.positionText(this.clip.clipConfiguration.asset)),e.setUpdatedClip(this.clip);const i=this.clip.layer-1,a=e.getClips().filter(o=>o.layer===this.clip.layer).indexOf(this.clip);e.emitEvent("clip:updated",{previous:{clip:this.initialConfig,trackIndex:i,clipIndex:a},current:{clip:this.clip.clipConfiguration,trackIndex:i,clipIndex:a}})}}undo(e){if(e&&this.clip.clipConfiguration.asset&&"text"in this.clip.clipConfiguration.asset){this.clip.clipConfiguration.asset.text=this.previousText;const t=this.clip.text;t&&(t.text=this.previousText,this.clip.positionText(this.clip.clipConfiguration.asset)),e.setUpdatedClip(this.clip);const i=this.clip.layer-1,a=e.getClips().filter(o=>o.layer===this.clip.layer).indexOf(this.clip);e.emitEvent("clip:updated",{previous:{clip:this.clip.clipConfiguration,trackIndex:i,clipIndex:a},current:{clip:this.initialConfig,trackIndex:i,clipIndex:a}})}}}class pt{events;constructor(){this.events={}}on(e,t){this.events[e]||(this.events[e]=new Set),this.events[e].add(t)}off(e,t){this.events[e]&&(this.events[e].delete(t),!(this.events[e].size>0)&&delete this.events[e])}clear(e){delete this.events[e]}emit(e,t){if(this.events[e])for(const i of this.events[e])i(t)}}class Tr extends pt{registry;constructor(){super(),this.registry={}}}class Ht{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 Tr;async load(e,t){this.updateAssetLoadMetadata(e,"pending",0);try{if(await this.shouldUseSafariVideoLoader(t))return await this.loadVideoForSafari(e,t);const i=await f.Assets.load(t,n=>{this.updateAssetLoadMetadata(e,"loading",n)});return this.updateAssetLoadMetadata(e,"success",1),i}catch{return this.updateAssetLoadMetadata(e,"failed",1),null}}getProgress(){const e=Object.keys(this.loadTracker.registry);return e.length===0?0:e.reduce((i,n)=>i+this.loadTracker.registry[n].progress,0)/e.length}extractUrl(e){if(typeof e=="string")return e;const t=Array.isArray(e.src)?e.src[0]:e.src;return typeof t=="string"?t:t?.src}hasVideoExtension(e){const t=new URL(e,window.location.origin).pathname.toLowerCase();return Ht.VIDEO_EXTENSIONS.some(i=>t.endsWith(i))}async getContentType(e){try{return(await fetch(e,{method:"HEAD"})).headers.get("content-type")}catch{return null}}canPlayVideo(e){const t=new URL(e,window.location.origin).pathname.toLowerCase(),i=t.slice(t.lastIndexOf(".")),n=Ht.VIDEO_MIME[i];return n?document.createElement("video").canPlayType(n)!=="":!1}async isPlayableVideo(e){if(this.hasVideoExtension(e))return this.canPlayVideo(e);const t=await this.getContentType(e);return t?.startsWith("video/")?document.createElement("video").canPlayType(t)!=="":!1}async shouldUseSafariVideoLoader(e){const t=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),i=this.extractUrl(e);return t&&i!==void 0&&await this.isPlayableVideo(i)}async loadVideoForSafari(e,t){const i=this.extractUrl(t),n=typeof t=="object"?t.data??{}:{},r=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 f.VideoSource({resource:l,autoPlay:n.autoPlay??!1,...n});a(new f.Texture({source:c}))}catch(c){o(c)}},{once:!0}),l.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(e,"loading",.5),l.src=i});return this.updateAssetLoadMetadata(e,"success",1),r}updateAssetLoadMetadata(e,t,i){this.loadTracker.registry[e]?(this.loadTracker.registry[e].progress=i,this.loadTracker.registry[e].status=t):this.loadTracker.registry[e]={progress:i,status:t};const n={...this.loadTracker.registry};this.loadTracker.emit("onAssetLoadInfoUpdated",{registry:n})}}class Vt{static Name="FontLoadParser";name;extension;validFontExtensions;woff2Decompressor;constructor(){this.name=Vt.Name,this.extension={type:[f.ExtensionType.LoadParser],priority:f.LoaderParserPriority.High,ref:null},this.validFontExtensions=["ttf","otf","woff","woff2"],this.woff2Decompressor=null}test(e){const t=e.split("?")[0]?.split(".").pop()?.toLowerCase()??"";return this.validFontExtensions.includes(t)}async load(e,t,i){const n=e.split("?")[0]?.split(".").pop()?.toLowerCase()??"",r=await fetch(e).then(u=>u.arrayBuffer());if(n!=="woff2"){const u=Pi.parse(new Uint8Array(r).buffer),p=u.names.fontFamily.en||u.names.fontFamily[Object.keys(u.names.fontFamily)[0]],g=new FontFace(p,`url(${e})`);return await g.load(),document.fonts.add(g),g}if(await this.loadWoff2Decompressor(),!this.woff2Decompressor)throw new Error("Cannot initialize Woff2 decompressor.");const a=this.woff2Decompressor.decompress(r),o=Pi.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),d=new FontFace(l,`url(${h})`);return await d.load(),document.fonts.add(d),d}async loadWoff2Decompressor(){if(this.woff2Decompressor)return;const t=`${await fetch("https://unpkg.com/wawoff2@2.0.1/build/decompress_binding.js").then(i=>i.text())}; return Module`;this.woff2Decompressor=new Function(t)(),await new Promise(i=>{this.woff2Decompressor.onRuntimeInitialized=i})}unload(e){e&&document.fonts.delete(e)}}const br=L({clips:Ji.array()}),kr=X().url("Invalid image url format."),Sr=L({src:kr}),_r=L({background:X().optional(),fonts:Sr.array().optional(),tracks:br.array()}),Er=L({size:L({width:k().positive(),height:k().positive()}),fps:k().positive().optional(),format:X()}),Ir=L({timeline:_r,output:Er});class Je extends be{static ZIndexPadding=100;assetLoader;events;edit;tracks;clipsToDispose;clips;commandHistory=[];commandIndex=-1;playbackTime;size;backgroundColor;totalDuration;isPlaying;selectedClip;updatedClip;viewportMask;isExporting=!1;constructor(e,t="#ffffff"){super(),this.assetLoader=new Ht,this.edit=null,this.tracks=[],this.clipsToDispose=[],this.clips=[],this.events=new pt,this.size=e,this.playbackTime=0,this.totalDuration=0,this.isPlaying=!1,this.selectedClip=null,this.updatedClip=null,this.backgroundColor=t,this.setupIntentListeners()}async load(){const e=new f.Graphics;e.fillStyle={color:this.backgroundColor},e.rect(0,0,this.size.width,this.size.height),e.fill(),this.getContainer().addChild(e),this.viewportMask=new f.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(e,t){for(const i of this.clips)i.shouldDispose&&this.queueDisposeClip(i),i.update(e,t);this.disposeClips(),this.isPlaying&&(this.playbackTime=Math.max(0,Math.min(this.playbackTime+t,this.totalDuration)),this.playbackTime===this.totalDuration&&this.pause())}draw(){for(const e of this.clips)e.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(e){this.playbackTime=Math.max(0,Math.min(e,this.totalDuration)),this.pause()}stop(){this.seek(0)}async loadEdit(e){this.clearClips(),this.edit=Ir.parse(e),this.backgroundColor=this.edit.timeline.background||"#000000",await Promise.all((this.edit.timeline.fonts??[]).map(async t=>{const i=t.src,n={src:i,loadParser:Vt.Name};return this.assetLoader.load(i,n)}));for(const[t,i]of this.edit.timeline.tracks.entries())for(const n of i.clips){const r=this.createPlayerFromAssetType(n);r.layer=t+1,await this.addPlayer(t,r)}this.updateTotalDuration()}getEdit(){const e=this.tracks.map((t,i)=>({clips:t.filter(r=>r&&!this.clipsToDispose.includes(r)).map(r=>r.clipConfiguration)}));return{timeline:{background:this.backgroundColor,tracks:e,fonts:this.edit?.timeline.fonts||[]},output:this.edit?.output||{size:this.size,format:"mp4"}}}addClip(e,t){const i=new fr(e,t);this.executeCommand(i)}getClip(e,t){const i=this.clips.filter(n=>n.layer===e+1);return t<0||t>=i.length?null:i[t].clipConfiguration}getPlayerClip(e,t){const i=this.clips.filter(n=>n.layer===e+1);return t<0||t>=i.length?null:i[t]}deleteClip(e,t){const i=new gr(e,t);this.executeCommand(i)}splitClip(e,t,i){const n=new xr(e,t,i);this.executeCommand(n)}addTrack(e,t){const i=new es(e);this.executeCommand(i),t?.clips?.forEach(n=>this.addClip(e,n))}getTrack(e){const t=this.clips.filter(i=>i.layer===e+1);return t.length===0?null:{clips:t.map(i=>i.clipConfiguration)}}deleteTrack(e){const t=new yr(e);this.executeCommand(t)}getTotalDuration(){return this.totalDuration}undo(){if(this.commandIndex>=0){const e=this.commandHistory[this.commandIndex];if(e.undo){const t=this.createCommandContext();e.undo(t),this.commandIndex-=1,this.events.emit("edit:undo",{command:e.name})}}}redo(){if(this.commandIndex<this.commandHistory.length-1){this.commandIndex+=1;const e=this.commandHistory[this.commandIndex],t=this.createCommandContext();e.execute(t),this.events.emit("edit:redo",{command:e.name})}}setUpdatedClip(e,t=null,i=null){const n=new Cr(e,t,i);this.executeCommand(n)}updateTextContent(e,t,i){const n=new vr(e,t,i);this.executeCommand(n)}executeEditCommand(e){return this.executeCommand(e)}executeCommand(e){const t=this.createCommandContext(),i=e.execute(t);return this.commandHistory=this.commandHistory.slice(0,this.commandIndex+1),this.commandHistory.push(e),this.commandIndex+=1,i}createCommandContext(){return{getClips:()=>this.clips,getTracks:()=>this.tracks,getTrack:e=>e>=0&&e<this.tracks.length?this.tracks[e]:null,getContainer:()=>this.getContainer(),addPlayer:(e,t)=>this.addPlayer(e,t),addPlayerToContainer:(e,t)=>{this.addPlayerToContainer(e,t)},createPlayerFromAssetType:e=>this.createPlayerFromAssetType(e),queueDisposeClip:e=>this.queueDisposeClip(e),disposeClips:()=>this.disposeClips(),undeleteClip:(e,t)=>{this.clips.push(t),this.updateTotalDuration()},setUpdatedClip:e=>{this.updatedClip=e},restoreClipConfiguration:(e,t)=>{Object.assign(e.clipConfiguration,structuredClone(t)),e.reconfigureAfterRestore(),e.draw()},updateDuration:()=>this.updateTotalDuration(),emitEvent:(e,t)=>this.events.emit(e,t),findClipIndices:e=>this.findClipIndices(e),getClipAt:(e,t)=>this.getClipAt(e,t),getSelectedClip:()=>this.selectedClip,setSelectedClip:e=>{this.selectedClip=e},movePlayerToTrackContainer:(e,t,i)=>this.movePlayerToTrackContainer(e,t,i),getEditState:()=>this.getEdit()}}queueDisposeClip(e){this.clipsToDispose.push(e)}disposeClips(){if(this.clipsToDispose.length!==0){for(const e of this.clipsToDispose)this.disposeClip(e);this.clips=this.clips.filter(e=>!this.clipsToDispose.includes(e)),this.clipsToDispose=[],this.updateTotalDuration()}}disposeClip(e){try{if(this.getContainer().children.includes(e.getContainer())){const t=this.getContainer().getChildIndex(e.getContainer());this.getContainer().removeChildAt(t)}else for(const t of this.getContainer().children)if(t instanceof f.Container&&t.label?.toString().startsWith("shotstack-track-")&&t.children.includes(e.getContainer())){t.removeChild(e.getContainer());break}}catch(t){console.warn(`Attempting to unmount an unmounted clip: ${t}`)}this.unloadClipAssets(e),e.dispose()}unloadClipAssets(e){const{asset:t}=e.clipConfiguration;if(t&&"src"in t&&typeof t.src=="string")try{f.Assets.unload(t.src)}catch(i){console.warn(`Failed to unload asset: ${t.src}`,i)}}clearClips(){for(const e of this.clips)this.disposeClip(e);this.clips=[],this.clipsToDispose=[],this.updateTotalDuration()}updateTotalDuration(){let e=0;for(const i of this.tracks)for(const n of i)e=Math.max(e,n.getEnd());const t=this.totalDuration;this.totalDuration=e,t!==this.totalDuration&&this.events.emit("duration:changed",{duration:this.totalDuration})}addPlayerToContainer(e,t){const i=1e5-(e+1)*Je.ZIndexPadding,n=`shotstack-track-${i}`;let r=this.getContainer().getChildByLabel(n,!1);r||(r=new f.Container({label:n,zIndex:i}),this.getContainer().addChild(r)),r.addChild(t.getContainer())}movePlayerToTrackContainer(e,t,i){if(t===i)return;const n=1e5-(t+1)*Je.ZIndexPadding,r=1e5-(i+1)*Je.ZIndexPadding,a=`shotstack-track-${n}`,o=`shotstack-track-${r}`,l=this.getContainer().getChildByLabel(a,!1);let c=this.getContainer().getChildByLabel(o,!1);c||(c=new f.Container({label:o,zIndex:r}),this.getContainer().addChild(c)),l&&l.removeChild(e.getContainer()),c.addChild(e.getContainer())}createPlayerFromAssetType(e){if(!e.asset?.type)throw new Error("Invalid clip configuration: missing asset type");let t;switch(e.asset.type){case"text":{t=new pn(this,e);break}case"shape":{t=new un(this,e);break}case"html":{t=new hn(this,e);break}case"image":{t=new dn(this,e);break}case"video":{t=new fn(this,e);break}case"audio":{t=new Ai(this,e);break}case"luma":{t=new Oi(this,e);break}default:throw new Error(`Unsupported clip type: ${e.asset.type}`)}return t}async addPlayer(e,t){for(;this.tracks.length<=e;)this.tracks.push([]);this.tracks[e].push(t),this.clips.push(t);const i=1e5-(e+1)*Je.ZIndexPadding,n=`shotstack-track-${i}`;let r=this.getContainer().getChildByLabel(n,!1);r||(r=new f.Container({label:n,zIndex:i}),this.getContainer().addChild(r)),r.addChild(t.getContainer());const a=t instanceof Oi;await t.load(),a&&r.setMask({mask:t.getMask(),inverse:!0}),this.updateTotalDuration()}selectClip(e,t){const i=new wr(e,t);this.executeCommand(i)}clearSelection(){const e=new mr;this.executeCommand(e)}isClipSelected(e,t){if(!this.selectedClip)return!1;const i=this.selectedClip.layer-1,n=this.tracks[i].indexOf(this.selectedClip);return e===i&&t===n}getSelectedClipInfo(){if(!this.selectedClip)return null;const e=this.selectedClip.layer-1,t=this.tracks[e].indexOf(this.selectedClip);return{trackIndex:e,clipIndex:t,player:this.selectedClip}}findClipIndices(e){for(let t=0;t<this.tracks.length;t+=1){const i=this.tracks[t].indexOf(e);if(i!==-1)return{trackIndex:t,clipIndex:i}}return null}getClipAt(e,t){return e>=0&&e<this.tracks.length&&t>=0&&t<this.tracks[e].length?this.tracks[e][t]:null}selectPlayer(e){const t=this.findClipIndices(e);t&&this.selectClip(t.trackIndex,t.clipIndex)}isPlayerSelected(e){return this.isExporting?!1:this.selectedClip===e}setExportMode(e){this.isExporting=e}isInExportMode(){return this.isExporting}setupIntentListeners(){this.events.on("timeline:clip:clicked",e=>{e.player?this.selectPlayer(e.player):this.selectClip(e.trackIndex,e.clipIndex)}),this.events.on("timeline:background:clicked",()=>{this.clearSelection()}),this.events.on("canvas:clip:clicked",e=>{this.selectPlayer(e.player)}),this.events.on("canvas:background:clicked",()=>{this.clearSelection()})}}class ft extends be{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 e=new f.Graphics;e.fillStyle={color:"#424242",alpha:.5},e.rect(0,0,ft.Width,ft.Height),e.fill(),this.getContainer().addChild(e),this.background=e;const t=new f.Text;t.text="",t.style={fontFamily:"monospace",fontSize:14,fill:"#ffffff",wordWrap:!0,wordWrapWidth:ft.Width},this.getContainer().addChild(t),this.text=t}update(e,t){if(!this.text)return;const i=this.getMemoryInfo(),n=[`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=n.join(`
|
|
185
|
+
`)}draw(){}dispose(){this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null}getMemoryInfo(){const e={};return"memory"in performance&&(e.totalHeapSize=performance.memory.totalJSHeapSize,e.usedHeapSize=performance.memory.usedJSHeapSize,e.heapSizeLimit=performance.memory.jsHeapSizeLimit),e}bytesToMegabytes(e){return Math.round(e/1024/1024)}}class De{static CanvasSelector="[data-shotstack-studio]";static extensionsRegistered=!1;size;application;edit;inspector;container;background;timeline;minZoom=.1;maxZoom=4;currentZoom=.8;onTickBound;constructor(e,t){this.size=e,this.application=new f.Application,this.edit=t,this.inspector=new ft,this.onTickBound=this.onTick.bind(this)}async load(){const e=document.querySelector(De.CanvasSelector);if(!e)throw new Error(`Shotstack canvas root element '${De.CanvasSelector}' not found.`);this.registerExtensions(),this.container=new f.Container,this.background=new f.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(e),this.edit.getContainer().scale=this.currentZoom,e.appendChild(this.application.canvas)}setupTouchHandling(e){const t=this.edit.getContainer();e.addEventListener("wheel",i=>{if(i.preventDefault(),i.stopPropagation(),i.ctrlKey){const n=Math.exp(-i.deltaY/100),r=this.currentZoom*n,a=this.currentZoom;this.currentZoom=Math.min(Math.max(r,this.minZoom),this.maxZoom);const o={x:this.application.canvas.width/2,y:this.application.canvas.height/2},l={x:t.position.x-o.x,y:t.position.y-o.y},c=this.currentZoom/a;t.position.x=o.x+l.x*c,t.position.y=o.y+l.y*c,t.scale.x=this.currentZoom,t.scale.y=this.currentZoom}},{passive:!1,capture:!0})}centerEdit(){if(!this.edit)return;const e=this.edit.getContainer();e.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 e=this.application.canvas.width/this.edit.size.width,t=this.application.canvas.height/this.edit.size.height,i=Math.min(e,t);this.currentZoom=Math.min(Math.max(i,this.minZoom),this.maxZoom);const n=this.edit.getContainer();n.scale.x=this.currentZoom,n.scale.y=this.currentZoom,this.centerEdit()}setZoom(e){this.currentZoom=Math.min(Math.max(e,this.minZoom),this.maxZoom);const t=this.edit.getContainer();t.scale.x=this.currentZoom,t.scale.y=this.currentZoom}registerTimeline(e){this.timeline=e}registerExtensions(){De.extensionsRegistered||(f.extensions.add(new Tt),f.extensions.add(new Vt),De.extensionsRegistered=!0)}async configureApplication(){const e={background:"#000000",width:this.size.width,height:this.size.height,antialias:!0};await this.application.init(e),this.application.ticker.add(this.onTickBound),this.application.ticker.minFPS=60,this.application.ticker.maxFPS=60}onTick(e){this.edit.update(e.deltaTime,e.deltaMS),this.edit.draw(),this.inspector.fps=Math.ceil(e.FPS),this.inspector.playbackTime=this.edit.playbackTime,this.inspector.playbackDuration=this.edit.totalDuration,this.inspector.isPlaying=this.edit.isPlaying,this.inspector.update(e.deltaTime,e.deltaMS),this.inspector.draw(),this.timeline&&(this.timeline.update(e.deltaTime,e.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 f.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(e){e.target===this.background&&this.edit.events.emit("canvas:background:clicked",{})}pauseTicker(){this.application.ticker.remove(this.onTickBound)}resumeTicker(){this.application.ticker.add(this.onTickBound)}dispose(){const e=document.querySelector(De.CanvasSelector);e&&e.contains(this.application.canvas)&&e.removeChild(this.application.canvas),this.application.ticker.remove(this.onTickBound),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 Pr{edit;seekDistance=50;seekDistanceLarge=500;frameTime=16.67;constructor(e){this.edit=e}async load(){document.addEventListener("keydown",this.handleKeyDown),document.addEventListener("keyup",this.handleKeyUp)}dispose(){document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("keyup",this.handleKeyUp)}handleKeyDown=e=>{if(!(e.target instanceof HTMLInputElement||e.target instanceof HTMLTextAreaElement))switch(e.code){case"Space":{this.edit.isPlaying?this.edit.pause():this.edit.play();break}case"ArrowLeft":{if(e.metaKey)this.edit.seek(0);else{const t=e.shiftKey?this.seekDistanceLarge:this.seekDistance;this.edit.seek(this.edit.playbackTime-t)}break}case"ArrowRight":{if(e.metaKey)this.edit.seek(this.edit.getTotalDuration());else{const t=e.shiftKey?this.seekDistanceLarge:this.seekDistance;this.edit.seek(this.edit.playbackTime+t)}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":{(e.metaKey||e.ctrlKey)&&(e.preventDefault(),e.shiftKey?this.edit.redo():this.edit.undo());break}case"Delete":case"Backspace":{const t=this.edit.getSelectedClipInfo();t&&(e.preventDefault(),this.edit.deleteClip(t.trackIndex,t.clipIndex));break}}};handleKeyUp=e=>{if(!(e.target instanceof HTMLInputElement||e.target instanceof HTMLTextAreaElement))switch(e.code){case"KeyI":console.log(this.edit.getEdit());break}}}class Ar{name="export";clips=[];tracks=[];execute(e){this.clips=e.getClips(),this.tracks=e.getTracks()}getClips(){return this.clips}getTracks(){return this.tracks}}/*!
|
|
186
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
187
|
+
*
|
|
188
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
189
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
190
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
191
|
+
*/function x(s){if(!s)throw new Error("Assertion failed.")}const le=s=>s&&s[s.length-1],et=s=>s>=0&&s<2**32;class mt{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),t=this.bytes[e]??0,i=7-(this.pos&7),n=(t&1<<i)>>i;return this.pos++,n}readBits(e){if(e===1)return this.readBit();let t=0;for(let i=0;i<e;i++)t<<=1,t|=this.readBit();return t}writeBits(e,t){const i=this.pos+e;for(let n=this.pos;n<i;n++){const r=Math.floor(n/8);let a=this.bytes[r];const o=7-(n&7);a&=~(1<<o),a|=(t&1<<i-n-1)>>i-n-1<<o,this.bytes[r]=a}this.pos=i}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){const e=new mt(this.bytes);return e.pos=this.pos,e}}const T=s=>{let e=0;for(;s.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+s.readBits(e)},gt=s=>{const e=T(s);return e&1?e+1>>1:-(e>>1)},Ee=s=>s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength),ts=s=>s instanceof DataView?s:s instanceof ArrayBuffer?new DataView(s):new DataView(s.buffer,s.byteOffset,s.byteLength);new TextDecoder;const He=new TextEncoder,ui=s=>Object.fromEntries(Object.entries(s).map(([e,t])=>[t,e])),Nt={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12};ui(Nt);const Ut={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pg:16,hlg:18};ui(Ut);const Wt={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9};ui(Wt);const Or=s=>!!s&&!!s.primaries&&!!s.transfer&&!!s.matrix&&s.fullRange!==void 0,Gt=s=>s instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&s instanceof SharedArrayBuffer||ArrayBuffer.isView(s);class is{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e;const t=new Promise(n=>{e=n}),i=this.currentPromise;return this.currentPromise=t,await i,e}}const Mr=()=>{let s,e;return{promise:new Promise((i,n)=>{s=i,e=n}),resolve:s,reject:e}},Rr=s=>{throw new Error(`Unexpected value: ${s}`)},ss=(s,e,t,i)=>{t=t>>>0,t=t&16777215,i?(s.setUint8(e,t&255),s.setUint8(e+1,t>>>8&255),s.setUint8(e+2,t>>>16&255)):(s.setUint8(e,t>>>16&255),s.setUint8(e+1,t>>>8&255),s.setUint8(e+2,t&255))},Br=(s,e,t,i)=>{t=Q(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),ss(s,e,t,i)},Q=(s,e,t)=>Math.max(e,Math.min(t,s)),Lr="und",Fr=/^[a-z]{3}$/,zr=s=>Fr.test(s),Ie=1e6*(1+Number.EPSILON),Dr=(s,e)=>{const t=s<0?-1:1;s=Math.abs(s);let i=0,n=1,r=1,a=0,o=s;for(;;){const l=Math.floor(o),c=l*r+i,h=l*a+n;if(h>e)return{numerator:t*r,denominator:a};if(i=r,n=a,r=c,a=h,o=1/(o-l),!isFinite(o))break}return{numerator:t*r,denominator:a}};class ns{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}/*!
|
|
192
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
193
|
+
*
|
|
194
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
195
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
196
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
197
|
+
*/const Ve=["avc","hevc","vp9","av1","vp8"],he=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],rs=["aac","opus","mp3","vorbis","flac"],tt=[...rs,...he],$t=["webvtt"],as=[{maxMacroblocks:99,maxBitrate:64e3,level:10},{maxMacroblocks:396,maxBitrate:192e3,level:11},{maxMacroblocks:396,maxBitrate:384e3,level:12},{maxMacroblocks:396,maxBitrate:768e3,level:13},{maxMacroblocks:396,maxBitrate:2e6,level:20},{maxMacroblocks:792,maxBitrate:4e6,level:21},{maxMacroblocks:1620,maxBitrate:4e6,level:22},{maxMacroblocks:1620,maxBitrate:1e7,level:30},{maxMacroblocks:3600,maxBitrate:14e6,level:31},{maxMacroblocks:5120,maxBitrate:2e7,level:32},{maxMacroblocks:8192,maxBitrate:2e7,level:40},{maxMacroblocks:8192,maxBitrate:5e7,level:41},{maxMacroblocks:8704,maxBitrate:5e7,level:42},{maxMacroblocks:22080,maxBitrate:135e6,level:50},{maxMacroblocks:36864,maxBitrate:24e7,level:51},{maxMacroblocks:36864,maxBitrate:24e7,level:52},{maxMacroblocks:139264,maxBitrate:24e7,level:60},{maxMacroblocks:139264,maxBitrate:48e7,level:61},{maxMacroblocks:139264,maxBitrate:8e8,level:62}],os=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],cs=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],ls=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],Hr=(s,e,t,i)=>{if(s==="avc"){const r=Math.ceil(e/16)*Math.ceil(t/16),a=as.find(d=>r<=d.maxMacroblocks&&i<=d.maxBitrate)??le(as),o=a?a.level:0,l="64".padStart(2,"0"),c="00",h=o.toString(16).padStart(2,"0");return`avc1.${l}${c}${h}`}else if(s==="hevc"){const n="",a="6",o=e*t,l=os.find(h=>o<=h.maxPictureSize&&i<=h.maxBitrate)??le(os);return`hev1.${n}1.${a}.${l.tier}${l.level}.B0`}else{if(s==="vp8")return"vp8";if(s==="vp9"){const n="00",r=e*t,a=cs.find(l=>r<=l.maxPictureSize&&i<=l.maxBitrate)??le(cs);return`vp09.${n}.${a.level.toString().padStart(2,"0")}.08`}else if(s==="av1"){const r=e*t,a=ls.find(c=>r<=c.maxPictureSize&&i<=c.maxBitrate)??le(ls);return`av01.0.${a.level.toString().padStart(2,"0")}${a.tier}.08`}}throw new TypeError(`Unhandled codec '${s}'.`)},Vr=s=>{const e=s.split("."),n=(1<<7)+1,r=Number(e[1]),a=e[2],o=Number(a.slice(0,-1)),l=(r<<5)+o,c=a.slice(-1)==="H"?1:0,d=Number(e[3])===8?0:1,u=0,p=e[4]?Number(e[4]):0,g=e[5]?Number(e[5][0]):1,b=e[5]?Number(e[5][1]):1,_=e[5]?Number(e[5][2]):0,B=(c<<7)+(d<<6)+(u<<5)+(p<<4)+(g<<3)+(b<<2)+_;return[n,l,B,0]},Nr=(s,e,t)=>{if(s==="aac")return e>=2&&t<=24e3?"mp4a.40.29":t<=24e3?"mp4a.40.5":"mp4a.40.2";if(s==="mp3")return"mp3";if(s==="opus")return"opus";if(s==="vorbis")return"vorbis";if(s==="flac")return"flac";if(he.includes(s))return s;throw new TypeError(`Unhandled codec '${s}'.`)},hs=/^pcm-([usf])(\d+)+(be)?$/,it=s=>{if(x(he.includes(s)),s==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(s==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const e=hs.exec(s);x(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";const i=Number(e[2])/8,n=e[3]!=="be",r=s==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:i,littleEndian:n,silentValue:r}},ds=s=>s.startsWith("avc1")||s.startsWith("avc3")?"avc":s.startsWith("hev1")||s.startsWith("hvc1")?"hevc":s==="vp8"?"vp8":s.startsWith("vp09")?"vp9":s.startsWith("av01")?"av1":s.startsWith("mp4a.40")||s==="mp4a.67"?"aac":s==="mp3"||s==="mp4a.69"||s==="mp4a.6B"||s==="mp4a.6b"?"mp3":s==="opus"?"opus":s==="vorbis"?"vorbis":s==="flac"?"flac":s==="ulaw"?"ulaw":s==="alaw"?"alaw":hs.test(s)?s:s==="webvtt"?"webvtt":null,Ur=s=>s==="avc"?{avc:{format:"avc"}}:s==="hevc"?{hevc:{format:"hevc"}}:{},Wr=s=>s==="aac"?{aac:{format:"aac"}}:s==="opus"?{opus:{format:"opus"}}:{};class Zt{constructor(e){this._factor=e}_toVideoBitrate(e,t,i){const n=t*i,r={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},a=1920*1080,o=3e6,l=Math.pow(n/a,.95),d=o*l*r[e]*this._factor;return Math.ceil(d/1e3)*1e3}_toAudioBitrate(e){if(he.includes(e)||e==="flac")return;const i={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3}[e];if(!i)throw new Error(`Unhandled codec: ${e}`);let n=i*this._factor;return e==="aac"?n=[96e3,128e3,16e4,192e3].reduce((a,o)=>Math.abs(o-n)<Math.abs(a-n)?o:a):e==="opus"||e==="vorbis"?n=Math.max(6e3,n):e==="mp3"&&(n=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((a,o)=>Math.abs(o-n)<Math.abs(a-n)?o:a)),Math.round(n/1e3)*1e3}}const Gr=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],$r=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Zr=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Kr=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,jr=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Xr=s=>{if(!s)throw new TypeError("Video chunk metadata must be provided.");if(typeof s!="object")throw new TypeError("Video chunk metadata must be an object.");if(!s.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof s.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof s.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!Gr.some(e=>s.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(s.decoderConfig.codedWidth)||s.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(s.decoderConfig.codedHeight)||s.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(s.decoderConfig.description!==void 0&&!Gt(s.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(s.decoderConfig.colorSpace!==void 0){const{colorSpace:e}=s.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const t=Object.keys(Nt);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${t.join(", ")}.`);const i=Object.keys(Ut);if(e.transfer!=null&&!i.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${i.join(", ")}.`);const n=Object.keys(Wt);if(e.matrix!=null&&!n.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${n.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(s.decoderConfig.codec.startsWith("avc1")||s.decoderConfig.codec.startsWith("avc3")){if(!$r.test(s.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(s.decoderConfig.codec.startsWith("hev1")||s.decoderConfig.codec.startsWith("hvc1")){if(!Zr.test(s.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(s.decoderConfig.codec.startsWith("vp8")){if(s.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(s.decoderConfig.codec.startsWith("vp09")){if(!Kr.test(s.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(s.decoderConfig.codec.startsWith("av01")&&!jr.test(s.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')},Yr=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"],qr=s=>{if(!s)throw new TypeError("Audio chunk metadata must be provided.");if(typeof s!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!s.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof s.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof s.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!Yr.some(e=>s.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(s.decoderConfig.sampleRate)||s.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(s.decoderConfig.numberOfChannels)||s.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(s.decoderConfig.description!==void 0&&!Gt(s.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(s.decoderConfig.codec.startsWith("mp4a")&&s.decoderConfig.codec!=="mp4a.69"&&s.decoderConfig.codec!=="mp4a.6B"&&s.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(s.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.");if(!s.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for AAC must include a description, which is expected to be an AudioSpecificConfig as specified in ISO 14496-3.")}else if(s.decoderConfig.codec.startsWith("mp3")||s.decoderConfig.codec.startsWith("mp4a")){if(s.decoderConfig.codec!=="mp3"&&s.decoderConfig.codec!=="mp4a.69"&&s.decoderConfig.codec!=="mp4a.6B"&&s.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(s.decoderConfig.codec.startsWith("opus")){if(s.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(s.decoderConfig.description&&s.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(s.decoderConfig.codec.startsWith("vorbis")){if(s.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!s.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(s.decoderConfig.codec.startsWith("flac")){if(s.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!s.decoderConfig.description||s.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if((s.decoderConfig.codec.startsWith("pcm")||s.decoderConfig.codec.startsWith("ulaw")||s.decoderConfig.codec.startsWith("alaw"))&&!he.includes(s.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${he.join(", ")}).`)},Qr=s=>{if(!s)throw new TypeError("Subtitle metadata must be provided.");if(typeof s!="object")throw new TypeError("Subtitle metadata must be an object.");if(!s.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof s.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof s.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};/*!
|
|
198
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
199
|
+
*
|
|
200
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
201
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
202
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
203
|
+
*/class Jr{constructor(e){this.mutex=new is,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,t,i){t+=e.source._timestampOffset;let n=this.trackTimestampInfo.get(e);if(!n){if(!i)throw new Error("First frame must be a key frame.");n={maxTimestamp:t,maxTimestampBeforeLastKeyFrame:t},this.trackTimestampInfo.set(e,n)}if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);if(i&&(n.maxTimestampBeforeLastKeyFrame=n.maxTimestamp),t<n.maxTimestampBeforeLastKeyFrame)throw new Error(`Timestamps cannot be smaller than the highest timestamp of the previous run (a run begins with a key frame and ends right before the next key frame). Got ${t}s, but highest timestamp is ${n.maxTimestampBeforeLastKeyFrame}s.`);return n.maxTimestamp=Math.max(n.maxTimestamp,t),t}}/*!
|
|
204
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
205
|
+
*
|
|
206
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
207
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
208
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
209
|
+
*/const us=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,ea=s=>{const e=Math.floor(s/36e5),t=Math.floor(s%(60*60*1e3)/(60*1e3)),i=Math.floor(s%(60*1e3)/1e3),n=s%1e3;return e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+n.toString().padStart(3,"0")};/*!
|
|
210
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
211
|
+
*
|
|
212
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
213
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
214
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
215
|
+
*/const pi=s=>{const e=[];let t=0;for(;t<s.length;){let i=-1,n=0;for(let r=t;r<s.length-3;r++){if(s[r]===0&&s[r+1]===0&&s[r+2]===1){i=r,n=3;break}if(r<s.length-4&&s[r]===0&&s[r+1]===0&&s[r+2]===0&&s[r+3]===1){i=r,n=4;break}}if(i===-1)break;if(t>0&&i>t){const r=s.subarray(t,i);r.length>0&&e.push(r)}t=i+n}if(t<s.length){const i=s.subarray(t);i.length>0&&e.push(i)}return e},fi=s=>{const e=[],t=s.length;for(let i=0;i<t;i++)i+2<t&&s[i]===0&&s[i+1]===0&&s[i+2]===3?(e.push(0,0),i+=2):e.push(s[i]);return new Uint8Array(e)},ta=s=>{const t=pi(s);if(t.length===0)return null;let i=0;for(const o of t)i+=4+o.byteLength;const n=new Uint8Array(i),r=new DataView(n.buffer);let a=0;for(const o of t){const l=o.byteLength;r.setUint32(a,l,!1),a+=4,n.set(o,a),a+=o.byteLength}return n},mi=s=>s[0]&31,ia=s=>{try{const e=pi(s),t=e.filter(u=>mi(u)===7),i=e.filter(u=>mi(u)===8),n=e.filter(u=>mi(u)===13);if(t.length===0||i.length===0)return null;const r=t[0],a=new mt(fi(r));if(a.skipBits(1),a.skipBits(2),a.readBits(5)!==7)return console.error("Invalid SPS NAL unit type"),null;const l=a.readAlignedByte(),c=a.readAlignedByte(),h=a.readAlignedByte(),d={configurationVersion:1,avcProfileIndication:l,profileCompatibility:c,avcLevelIndication:h,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:i,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if(l===100||l===110||l===122||l===144){T(a);const u=T(a);u===3&&a.skipBits(1);const p=T(a),g=T(a);d.chromaFormat=u,d.bitDepthLumaMinus8=p,d.bitDepthChromaMinus8=g,d.sequenceParameterSetExt=n}return d}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},sa=s=>{const e=[];e.push(s.configurationVersion),e.push(s.avcProfileIndication),e.push(s.profileCompatibility),e.push(s.avcLevelIndication),e.push(252|s.lengthSizeMinusOne&3),e.push(224|s.sequenceParameterSets.length&31);for(const t of s.sequenceParameterSets){const i=t.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(t[n])}e.push(s.pictureParameterSets.length);for(const t of s.pictureParameterSets){const i=t.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(t[n])}if(s.avcProfileIndication===100||s.avcProfileIndication===110||s.avcProfileIndication===122||s.avcProfileIndication===144){x(s.chromaFormat!==null),x(s.bitDepthLumaMinus8!==null),x(s.bitDepthChromaMinus8!==null),x(s.sequenceParameterSetExt!==null),e.push(252|s.chromaFormat&3),e.push(248|s.bitDepthLumaMinus8&7),e.push(248|s.bitDepthChromaMinus8&7),e.push(s.sequenceParameterSetExt.length);for(const t of s.sequenceParameterSetExt){const i=t.byteLength;e.push(i>>8),e.push(i&255);for(let n=0;n<i;n++)e.push(t[n])}}return new Uint8Array(e)},ps=32,fs=33,ms=34,na=39,ra=40,st=s=>s[0]>>1&63,aa=s=>{try{const e=pi(s),t=e.filter(U=>st(U)===ps),i=e.filter(U=>st(U)===fs),n=e.filter(U=>st(U)===ms),r=e.filter(U=>st(U)===na||st(U)===ra);if(i.length===0||n.length===0)return null;const a=i[0],o=new mt(fi(a));o.skipBits(16),o.readBits(4);const l=o.readBits(3),c=o.readBits(1),{general_profile_space:h,general_tier_flag:d,general_profile_idc:u,general_profile_compatibility_flags:p,general_constraint_indicator_flags:g,general_level_idc:b}=oa(o,l);T(o);const _=T(o);_===3&&o.skipBits(1),T(o),T(o),o.readBits(1)&&(T(o),T(o),T(o),T(o));const B=T(o),N=T(o);T(o);const $=o.readBits(1)?0:l;for(let U=$;U<=l;U++)T(o),T(o),T(o);T(o),T(o),T(o),T(o),T(o),T(o),o.readBits(1)&&o.readBits(1)&&ca(o),o.skipBits(1),o.skipBits(1),o.readBits(1)&&(o.skipBits(4),o.skipBits(4),T(o),T(o),o.skipBits(1));const Z=T(o);if(la(o,Z),o.readBits(1)){const U=T(o);for(let z=0;z<U;z++)T(o),o.skipBits(1)}o.skipBits(1),o.skipBits(1);let fe=0;o.readBits(1)&&(fe=da(o,l));let se=0;if(n.length>0){const U=n[0],z=new mt(fi(U));z.skipBits(16),T(z),T(z),z.skipBits(1),z.skipBits(1),z.skipBits(3),z.skipBits(1),z.skipBits(1),T(z),T(z),gt(z),z.skipBits(1),z.skipBits(1),z.readBits(1)&&T(z),gt(z),gt(z),z.skipBits(1),z.skipBits(1),z.skipBits(1),z.skipBits(1);const Ge=z.readBits(1),vt=z.readBits(1);!Ge&&!vt?se=0:Ge&&!vt?se=2:!Ge&&vt?se=3:se=0}const me=[...t.length?[{arrayCompleteness:1,nalUnitType:ps,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:fs,nalUnits:i}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:ms,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:st(r[0]),nalUnits:r}]:[]];return{configurationVersion:1,generalProfileSpace:h,generalTierFlag:d,generalProfileIdc:u,generalProfileCompatibilityFlags:p,generalConstraintIndicatorFlags:g,generalLevelIdc:b,minSpatialSegmentationIdc:fe,parallelismType:se,chromaFormatIdc:_,bitDepthLumaMinus8:B,bitDepthChromaMinus8:N,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:l+1,temporalIdNested:c,lengthSizeMinusOne:3,arrays:me}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},oa=(s,e)=>{const t=s.readBits(2),i=s.readBits(1),n=s.readBits(5);let r=0;for(let h=0;h<32;h++)r=r<<1|s.readBits(1);const a=new Uint8Array(6);for(let h=0;h<6;h++)a[h]=s.readBits(8);const o=s.readBits(8),l=[],c=[];for(let h=0;h<e;h++)l.push(s.readBits(1)),c.push(s.readBits(1));if(e>0)for(let h=e;h<8;h++)s.skipBits(2);for(let h=0;h<e;h++)l[h]&&s.skipBits(88),c[h]&&s.skipBits(8);return{general_profile_space:t,general_tier_flag:i,general_profile_idc:n,general_profile_compatibility_flags:r,general_constraint_indicator_flags:a,general_level_idc:o}},ca=s=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!s.readBits(1))T(s);else{const n=Math.min(64,1<<4+(e<<1));e>1&>(s);for(let r=0;r<n;r++)gt(s)}},la=(s,e)=>{const t=[];for(let i=0;i<e;i++)t[i]=ha(s,i,e,t)},ha=(s,e,t,i)=>{let n=0,r=0,a=0;if(e!==0&&(r=s.readBits(1)),r){if(e===t){const l=T(s);a=e-(l+1)}else a=e-1;s.readBits(1),T(s);const o=i[a]??0;for(let l=0;l<=o;l++)s.readBits(1)||s.readBits(1);n=i[a]}else{const o=T(s),l=T(s);for(let c=0;c<o;c++)T(s),s.readBits(1);for(let c=0;c<l;c++)T(s),s.readBits(1);n=o+l}return n},da=(s,e)=>{if(s.readBits(1)&&s.readBits(8)===255&&(s.readBits(16),s.readBits(16)),s.readBits(1)&&s.readBits(1),s.readBits(1)&&(s.readBits(3),s.readBits(1),s.readBits(1)&&(s.readBits(8),s.readBits(8),s.readBits(8))),s.readBits(1)&&(T(s),T(s)),s.readBits(1),s.readBits(1),s.readBits(1),s.readBits(1)&&(T(s),T(s),T(s),T(s)),s.readBits(1)&&(s.readBits(32),s.readBits(32),s.readBits(1)&&T(s),s.readBits(1)&&ua(s,!0,e)),s.readBits(1)){s.readBits(1),s.readBits(1),s.readBits(1);const t=T(s);return T(s),T(s),T(s),T(s),t}return 0},ua=(s,e,t)=>{let i=!1,n=!1,r=!1;i=s.readBits(1)===1,n=s.readBits(1)===1,(i||n)&&(r=s.readBits(1)===1,r&&(s.readBits(8),s.readBits(5),s.readBits(1),s.readBits(5)),s.readBits(4),s.readBits(4),r&&s.readBits(4),s.readBits(5),s.readBits(5),s.readBits(5));for(let a=0;a<=t;a++){const o=s.readBits(1)===1;let l=!0;o||(l=s.readBits(1)===1);let c=!1;l?T(s):c=s.readBits(1)===1;let h=1;c||(h=T(s)+1),i&&gs(s,h,r),n&&gs(s,h,r)}},gs=(s,e,t)=>{for(let i=0;i<e;i++)T(s),T(s),t&&(T(s),T(s)),s.readBits(1)},pa=s=>{const e=[];e.push(s.configurationVersion),e.push((s.generalProfileSpace&3)<<6|(s.generalTierFlag&1)<<5|s.generalProfileIdc&31),e.push(s.generalProfileCompatibilityFlags>>>24&255),e.push(s.generalProfileCompatibilityFlags>>>16&255),e.push(s.generalProfileCompatibilityFlags>>>8&255),e.push(s.generalProfileCompatibilityFlags&255),e.push(...s.generalConstraintIndicatorFlags),e.push(s.generalLevelIdc&255),e.push(240|s.minSpatialSegmentationIdc>>8&15),e.push(s.minSpatialSegmentationIdc&255),e.push(252|s.parallelismType&3),e.push(252|s.chromaFormatIdc&3),e.push(248|s.bitDepthLumaMinus8&7),e.push(248|s.bitDepthChromaMinus8&7),e.push(s.avgFrameRate>>8&255),e.push(s.avgFrameRate&255),e.push((s.constantFrameRate&3)<<6|(s.numTemporalLayers&7)<<3|(s.temporalIdNested&1)<<2|s.lengthSizeMinusOne&3),e.push(s.arrays.length&255);for(const t of s.arrays){e.push((t.arrayCompleteness&1)<<7|0|t.nalUnitType&63),e.push(t.nalUnits.length>>8&255),e.push(t.nalUnits.length&255);for(const i of t.nalUnits){e.push(i.length>>8&255),e.push(i.length&255);for(let n=0;n<i.length;n++)e.push(i[n])}}return new Uint8Array(e)},fa=s=>{const e=ts(s),t=e.getUint8(9),i=e.getUint16(10,!0),n=e.getUint32(12,!0),r=e.getInt16(16,!0),a=e.getUint8(18);let o=null;return a&&(o=s.subarray(19,21+t)),{outputChannelCount:t,preSkip:i,inputSampleRate:n,outputGain:r,channelMappingFamily:a,channelMappingTable:o}};/*!
|
|
216
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
217
|
+
*
|
|
218
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
219
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
220
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
221
|
+
*/class ys{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8===7&&this.writer.write(this.helper);e.length%8!==0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{const t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(const r of e.children)r&&this.writeBox(r);const i=this.writer.getPos(),n=e.size??i-t;this.writer.seek(t),this.writeBoxHeader(e,n),this.writer.seek(i)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){const t=this.offsets.get(e);x(t!==void 0);const i=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(i)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(const i of e.children)i&&(t+=this.measureBox(i));return t}}}const M=new Uint8Array(8),de=new DataView(M.buffer),V=s=>[(s%256+256)%256],I=s=>(de.setUint16(0,s,!1),[M[0],M[1]]),ws=s=>(de.setInt16(0,s,!1),[M[0],M[1]]),Cs=s=>(de.setUint32(0,s,!1),[M[1],M[2],M[3]]),w=s=>(de.setUint32(0,s,!1),[M[0],M[1],M[2],M[3]]),Pe=s=>(de.setInt32(0,s,!1),[M[0],M[1],M[2],M[3]]),Ne=s=>(de.setUint32(0,Math.floor(s/2**32),!1),de.setUint32(4,s,!1),[M[0],M[1],M[2],M[3],M[4],M[5],M[6],M[7]]),xs=s=>(de.setInt16(0,2**8*s,!1),[M[0],M[1]]),ve=s=>(de.setInt32(0,2**16*s,!1),[M[0],M[1],M[2],M[3]]),gi=s=>(de.setInt32(0,2**30*s,!1),[M[0],M[1],M[2],M[3]]),yi=(s,e)=>{const t=[];let i=s;do{let n=i&127;i>>=7,t.length>0&&(n|=128),t.push(n)}while(i>0||e);return t.reverse()},Y=(s,e=!1)=>{const t=Array(s.length).fill(null).map((i,n)=>s.charCodeAt(n));return e&&t.push(0),t},wi=s=>{let e=null;for(const t of s)(!e||t.timestamp>e.timestamp)&&(e=t);return e},vs=s=>{const e=s*(Math.PI/180),t=Math.round(Math.cos(e)),i=Math.round(Math.sin(e));return[t,i,0,-i,t,0,0,0,1]},Ts=vs(0),bs=s=>[ve(s[0]),ve(s[1]),gi(s[2]),ve(s[3]),ve(s[4]),gi(s[5]),ve(s[6]),ve(s[7]),gi(s[8])],O=(s,e,t)=>({type:s,contents:e&&new Uint8Array(e.flat(10)),children:t}),F=(s,e,t,i,n)=>O(s,[V(e),Cs(t),i??[]],n),ma=s=>s.isQuickTime?O("ftyp",[Y("qt "),w(512),Y("qt ")]):s.fragmented?O("ftyp",[Y("iso5"),w(512),Y("iso5"),Y("iso6"),Y("mp41")]):O("ftyp",[Y("isom"),w(512),Y("isom"),s.holdsAvc?Y("avc1"):[],Y("mp41")]),Ci=s=>({type:"mdat",largeSize:s}),Kt=(s,e,t=!1)=>O("moov",void 0,[ga(e,s),...s.map(i=>ya(i,e)),t?Ya(s):null]),ga=(s,e)=>{const t=W(Math.max(0,...e.filter(a=>a.samples.length>0).map(a=>{const o=wi(a.samples);return o.timestamp+o.duration})),ki),i=Math.max(0,...e.map(a=>a.track.id))+1,n=!et(s)||!et(t),r=n?Ne:w;return F("mvhd",+n,0,[r(s),r(s),w(ki),r(t),ve(1),xs(1),Array(10).fill(0),bs(Ts),Array(24).fill(0),w(i)])},ya=(s,e)=>{const t=wo(s);return O("trak",void 0,[wa(s,e),Ca(s,e),t.name!==void 0?O("udta",void 0,[O("©nam",[...He.encode(t.name)])]):null])},wa=(s,e)=>{const t=wi(s.samples),i=W(t?t.timestamp+t.duration:0,ki),n=!et(e)||!et(i),r=n?Ne:w;let a;if(s.type==="video"){const o=s.track.metadata.rotation;a=vs(o??0)}else a=Ts;return F("tkhd",+n,3,[r(e),r(e),w(s.track.id),w(0),r(i),Array(8).fill(0),I(0),I(s.track.id),xs(s.type==="audio"?1:0),I(0),bs(a),ve(s.type==="video"?s.info.width:0),ve(s.type==="video"?s.info.height:0)])},Ca=(s,e)=>O("mdia",void 0,[xa(s,e),ba(!0,va[s.type],Ta[s.type]),ka(s)]),xa=(s,e)=>{const t=wi(s.samples),i=W(t?t.timestamp+t.duration:0,s.timescale),n=!et(e)||!et(i),r=n?Ne:w;let a=0;for(const o of s.track.metadata.languageCode??Lr)a<<=5,a+=o.charCodeAt(0)-96;return F("mdhd",+n,0,[r(e),r(e),w(s.timescale),r(i),I(a),I(0)])},va={video:"vide",audio:"soun",subtitle:"text"},Ta={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},ba=(s,e,t)=>F("hdlr",0,0,[Y("mhlr"),Y(e),w(0),w(0),w(0),Y(t,!0)]),ka=s=>O("minf",void 0,[Sa[s.type](),_a(),Pa(s)]),Sa={video:()=>F("vmhd",0,1,[I(0),I(0),I(0),I(0)]),audio:()=>F("smhd",0,0,[I(0),I(0)]),subtitle:()=>F("nmhd",0,0)},_a=()=>O("dinf",void 0,[Ea()]),Ea=()=>F("dref",0,0,[w(1)],[Ia()]),Ia=()=>F("url ",0,1),Pa=s=>{const e=s.compositionTimeOffsetTable.length>1||s.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return O("stbl",void 0,[Aa(s),Wa(s),e?ja(s):null,e?Xa(s):null,$a(s),Za(s),Ka(s),Ga(s)])},Aa=s=>{let e;if(s.type==="video")e=Oa(lo[s.track.source._codec],s);else if(s.type==="audio"){const t=Es(s.track.source._codec,s.muxer.isQuickTime);x(t),e=Fa(t,s)}else s.type==="subtitle"&&(e=Na(po[s.track.source._codec],s));return x(e),F("stsd",0,0,[w(1)],[e])},Oa=(s,e)=>O(s,[Array(6).fill(0),I(1),I(0),I(0),Array(12).fill(0),I(e.info.width),I(e.info.height),w(4718592),w(4718592),w(0),I(1),Array(32).fill(0),I(24),ws(65535)],[ho[e.track.source._codec](e),Or(e.info.decoderConfig.colorSpace)?Ma(e):null]),Ma=s=>O("colr",[Y("nclx"),I(Nt[s.info.decoderConfig.colorSpace.primaries]),I(Ut[s.info.decoderConfig.colorSpace.transfer]),I(Wt[s.info.decoderConfig.colorSpace.matrix]),V((s.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),Ra=s=>s.info.decoderConfig&&O("avcC",[...Ee(s.info.decoderConfig.description)]),Ba=s=>s.info.decoderConfig&&O("hvcC",[...Ee(s.info.decoderConfig.description)]),ks=s=>{if(!s.info.decoderConfig)return null;const e=s.info.decoderConfig,t=e.codec.split("."),i=Number(t[1]),n=Number(t[2]),r=Number(t[3]),a=t[4]?Number(t[4]):1,o=t[8]?Number(t[8]):Number(e.colorSpace?.fullRange??0),l=(r<<4)+(a<<1)+o,c=t[5]?Number(t[5]):e.colorSpace?.primaries?Nt[e.colorSpace.primaries]:2,h=t[6]?Number(t[6]):e.colorSpace?.transfer?Ut[e.colorSpace.transfer]:2,d=t[7]?Number(t[7]):e.colorSpace?.matrix?Wt[e.colorSpace.matrix]:2;return F("vpcC",1,0,[V(i),V(n),V(l),V(c),V(h),V(d),I(0)])},La=s=>O("av1C",Vr(s.info.decoderConfig.codec)),Fa=(s,e)=>{let t=0,i,n=16;if(he.includes(e.track.source._codec)){const r=e.track.source._codec,{sampleSize:a}=it(r);n=8*a,n>16&&(t=1)}return t===0?i=[Array(6).fill(0),I(1),I(t),I(0),w(0),I(e.info.numberOfChannels),I(n),I(0),I(0),I(e.info.sampleRate<2**16?e.info.sampleRate:0),I(0)]:i=[Array(6).fill(0),I(1),I(t),I(0),w(0),I(e.info.numberOfChannels),I(Math.min(n,16)),I(0),I(0),I(e.info.sampleRate<2**16?e.info.sampleRate:0),I(0),w(1),w(n/8),w(e.info.numberOfChannels*n/8),w(2)],O(s,i,[uo(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},xi=s=>{let e;switch(s.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${s.track.source._codec}`)}let t=[...V(e),...V(21),...Cs(0),...w(0),...w(0)];if(s.info.decoderConfig.description){const i=Ee(s.info.decoderConfig.description);t=[...t,...V(5),...yi(i.byteLength),...i]}return t=[...I(1),...V(0),...V(4),...yi(t.length),...t,...V(6),...V(1),...V(2)],t=[...V(3),...yi(t.length),...t],F("esds",0,0,t)},Ae=s=>O("wave",void 0,[za(s),Da(s),O("\0\0\0\0")]),za=s=>O("frma",[Y(Es(s.track.source._codec,s.muxer.isQuickTime))]),Da=s=>{const{littleEndian:e}=it(s.track.source._codec);return O("enda",[I(+e)])},Ha=s=>{let e=s.info.numberOfChannels,t=3840,i=s.info.sampleRate,n=0,r=0,a=new Uint8Array(0);const o=s.info.decoderConfig?.description;if(o){x(o.byteLength>=18);const l=Ee(o),c=fa(l);e=c.outputChannelCount,t=c.preSkip,i=c.inputSampleRate,n=c.outputGain,r=c.channelMappingFamily,c.channelMappingTable&&(a=c.channelMappingTable)}return O("dOps",[V(0),V(e),I(t),w(i),ws(n),V(r),...a])},Va=s=>{const e=s.info.decoderConfig?.description;x(e);const t=Ee(e);return F("dfLa",0,0,[...t.subarray(4)])},ue=s=>{const{littleEndian:e,sampleSize:t}=it(s.track.source._codec),i=+e;return F("pcmC",0,0,[V(i),V(8*t)])},Na=(s,e)=>O(s,[Array(6).fill(0),I(1)],[fo[e.track.source._codec](e)]),Ua=s=>O("vttC",[...He.encode(s.info.config.description)]),Wa=s=>F("stts",0,0,[w(s.timeToSampleTable.length),s.timeToSampleTable.map(e=>[w(e.sampleCount),w(e.sampleDelta)])]),Ga=s=>{if(s.samples.every(t=>t.type==="key"))return null;const e=[...s.samples.entries()].filter(([,t])=>t.type==="key");return F("stss",0,0,[w(e.length),e.map(([t])=>w(t+1))])},$a=s=>F("stsc",0,0,[w(s.compactlyCodedChunkTable.length),s.compactlyCodedChunkTable.map(e=>[w(e.firstChunk),w(e.samplesPerChunk),w(1)])]),Za=s=>{if(s.type==="audio"&&s.info.requiresPcmTransformation){const{sampleSize:e}=it(s.track.source._codec);return F("stsz",0,0,[w(e*s.info.numberOfChannels),w(s.samples.reduce((t,i)=>t+W(i.duration,s.timescale),0))])}return F("stsz",0,0,[w(0),w(s.samples.length),s.samples.map(e=>w(e.size))])},Ka=s=>s.finalizedChunks.length>0&&le(s.finalizedChunks).offset>=2**32?F("co64",0,0,[w(s.finalizedChunks.length),s.finalizedChunks.map(e=>Ne(e.offset))]):F("stco",0,0,[w(s.finalizedChunks.length),s.finalizedChunks.map(e=>w(e.offset))]),ja=s=>F("ctts",1,0,[w(s.compositionTimeOffsetTable.length),s.compositionTimeOffsetTable.map(e=>[w(e.sampleCount),Pe(e.sampleCompositionTimeOffset)])]),Xa=s=>{let e=1/0,t=-1/0,i=1/0,n=-1/0;x(s.compositionTimeOffsetTable.length>0),x(s.samples.length>0);for(let a=0;a<s.compositionTimeOffsetTable.length;a++){const o=s.compositionTimeOffsetTable[a];e=Math.min(e,o.sampleCompositionTimeOffset),t=Math.max(t,o.sampleCompositionTimeOffset)}for(let a=0;a<s.samples.length;a++){const o=s.samples[a];i=Math.min(i,W(o.timestamp,s.timescale)),n=Math.max(n,W(o.timestamp+o.duration,s.timescale))}const r=Math.max(-e,0);return n>=2**31?null:F("cslg",0,0,[Pe(r),Pe(e),Pe(t),Pe(i),Pe(n)])},Ya=s=>O("mvex",void 0,s.map(qa)),qa=s=>F("trex",0,0,[w(s.track.id),w(1),w(0),w(0),w(0)]),Ss=(s,e)=>O("moof",void 0,[Qa(s),...e.map(Ja)]),Qa=s=>F("mfhd",0,0,[w(s)]),_s=s=>{let e=0,t=0;const i=0,n=0,r=s.type==="delta";return t|=+r,r?e|=1:e|=2,e<<24|t<<16|i<<8|n},Ja=s=>O("traf",void 0,[eo(s),to(s),io(s)]),eo=s=>{x(s.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const t=s.currentChunk.samples[1]??s.currentChunk.samples[0],i={duration:t.timescaleUnitsToNextSample,size:t.size,flags:_s(t)};return F("tfhd",0,e,[w(s.track.id),w(i.duration),w(i.size),w(i.flags)])},to=s=>(x(s.currentChunk),F("tfdt",1,0,[Ne(W(s.currentChunk.startTimestamp,s.timescale))])),io=s=>{x(s.currentChunk);const e=s.currentChunk.samples.map(b=>b.timescaleUnitsToNextSample),t=s.currentChunk.samples.map(b=>b.size),i=s.currentChunk.samples.map(_s),n=s.currentChunk.samples.map(b=>W(b.timestamp-b.decodeTimestamp,s.timescale)),r=new Set(e),a=new Set(t),o=new Set(i),l=new Set(n),c=o.size===2&&i[0]!==i[1],h=r.size>1,d=a.size>1,u=!c&&o.size>1,p=l.size>1||[...l].some(b=>b!==0);let g=0;return g|=1,g|=4*+c,g|=256*+h,g|=512*+d,g|=1024*+u,g|=2048*+p,F("trun",1,g,[w(s.currentChunk.samples.length),w(s.currentChunk.offset-s.currentChunk.moofOffset||0),c?w(i[0]):[],s.currentChunk.samples.map((b,_)=>[h?w(e[_]):[],d?w(t[_]):[],u?w(i[_]):[],p?Pe(n[_]):[]])])},so=s=>O("mfra",void 0,[...s.map(no),ro()]),no=(s,e)=>F("tfra",1,0,[w(s.track.id),w(63),w(s.finalizedChunks.length),s.finalizedChunks.map(i=>[Ne(W(i.samples[0].timestamp,s.timescale)),Ne(i.moofOffset),w(e+1),w(1),w(1)])]),ro=()=>F("mfro",0,0,[w(0)]),ao=()=>O("vtte"),oo=(s,e,t,i,n)=>O("vttc",void 0,[n!==null?O("vsid",[Pe(n)]):null,t!==null?O("iden",[...He.encode(t)]):null,e!==null?O("ctim",[...He.encode(ea(e))]):null,i!==null?O("sttg",[...He.encode(i)]):null,O("payl",[...He.encode(s)])]),co=s=>O("vtta",[...He.encode(s)]),lo={avc:"avc1",hevc:"hvc1",vp8:"vp08",vp9:"vp09",av1:"av01"},ho={avc:Ra,hevc:Ba,vp8:ks,vp9:ks,av1:La},Es=(s,e)=>{switch(s){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt"}if(e)switch(s){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(s){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},uo=(s,e)=>{switch(s){case"aac":return xi;case"mp3":return xi;case"opus":return Ha;case"vorbis":return xi;case"flac":return Va}if(e)switch(s){case"pcm-s24":return Ae;case"pcm-s24be":return Ae;case"pcm-s32":return Ae;case"pcm-s32be":return Ae;case"pcm-f32":return Ae;case"pcm-f32be":return Ae;case"pcm-f64":return Ae;case"pcm-f64be":return Ae}else switch(s){case"pcm-s16":return ue;case"pcm-s16be":return ue;case"pcm-s24":return ue;case"pcm-s24be":return ue;case"pcm-s32":return ue;case"pcm-s32be":return ue;case"pcm-f32":return ue;case"pcm-f32be":return ue;case"pcm-f64":return ue;case"pcm-f64be":return ue}return null},po={webvtt:"wvtt"},fo={webvtt:Ua};/*!
|
|
222
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
223
|
+
*
|
|
224
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
225
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
226
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
227
|
+
*/class mo{constructor(){this.ensureMonotonicity=!1,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1}start(){}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}const i=t+e.byteLength-this.trackedStart;let n=this.trackedWrites.byteLength;for(;n<i;)n*=2;if(n!==this.trackedWrites.byteLength){const r=new Uint8Array(n);r.set(this.trackedWrites,0),this.trackedWrites=r}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");const t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}}const vi=2**16,Ti=2**32;class Is extends mo{constructor(e){if(super(),this.pos=0,this.maxPos=0,this.target=e,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(vi,{maxByteLength:Ti})}catch{this.buffer=new ArrayBuffer(vi),this.supportsResize=!1}else this.buffer=new ArrayBuffer(vi);this.bytes=new Uint8Array(this.buffer)}ensureSize(e){let t=this.buffer.byteLength;for(;t<e;)t*=2;if(t!==this.buffer.byteLength){if(t>Ti)throw new Error(`ArrayBuffer exceeded maximum size of ${Ti} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(t);else{const i=new ArrayBuffer(t),n=new Uint8Array(i);n.set(this.bytes,0),this.buffer=i,this.bytes=n}}}write(e){this.maybeTrackWrites(e),this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),this.pos+=e.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(e,t){return this.bytes.slice(e,t)}}/*!
|
|
228
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
229
|
+
*
|
|
230
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
231
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
232
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
233
|
+
*/class Ps{constructor(){this._output=null}}class As extends Ps{constructor(){super(...arguments),this.buffer=null}_createWriter(){return new Is(this)}}/*!
|
|
234
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
235
|
+
*
|
|
236
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
237
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
238
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
239
|
+
*/const go=s=>{let t=(s.hasVideo?"video/":s.hasAudio?"audio/":"application/")+(s.isQuickTime?"quicktime":"mp4");if(s.codecStrings.length>0){const i=[...new Set(s.codecStrings)];t+=`; codecs="${i.join(", ")}"`}return t};/*!
|
|
240
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
241
|
+
*
|
|
242
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
243
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
244
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
245
|
+
*/const bi=8,Os=16;/*!
|
|
246
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
247
|
+
*
|
|
248
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
249
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
250
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
251
|
+
*/const ki=1e3,yo=2082844800,wo=s=>{const e={},t=s.track;return t.metadata.name!==void 0&&(e.name=t.metadata.name),e},W=(s,e,t=!0)=>{const i=s*e;return t?Math.round(i):i};class Co extends Jr{constructor(e,t){super(e),this.auxTarget=new As,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new ys(this.auxWriter),this.mdat=null,this.trackDatas=[],this.allTracksKnown=Mr(),this.creationTime=Math.floor(Date.now()/1e3)+yo,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=t,this.writer=e._writer,this.boxWriter=new ys(this.writer),this.isQuickTime=t instanceof Fs;const i=this.writer instanceof Is?"in-memory":!1;this.fastStart=t._options.fastStart??i,this.isFragmented=this.fastStart==="fragmented",(this.fastStart==="in-memory"||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=t._options.minimumFragmentDuration??1}async start(){const e=await this.mutex.acquire(),t=this.output._tracks.some(i=>i.type==="video"&&i.source._codec==="avc");if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(ma({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented})),this.format._options.onFtyp){const{data:i,start:n}=this.writer.stopTrackingWrites();this.format._options.onFtyp(i,n)}this.fastStart==="in-memory"?this.mdat=Ci(!1):this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Ci(!0),this.boxWriter.writeBox(this.mdat)),await this.writer.flush(),e()}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(t=>t.type==="video"||t.type==="audio"?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source._codec]);return go({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,i){const n=this.trackDatas.find(c=>c.track===e);if(n)return n;Xr(i),x(i),x(i.decoderConfig);const r={...i.decoderConfig};x(r.codedWidth!==void 0),x(r.codedHeight!==void 0);let a=!1;if(e.source._codec==="avc"&&!r.description){const c=ia(t.data);if(!c)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");r.description=sa(c),a=!0}else if(e.source._codec==="hevc"&&!r.description){const c=aa(t.data);if(!c)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");r.description=pa(c),a=!0}const o=Dr(1/(e.metadata.frameRate??57600),1e6).denominator,l={muxer:this,track:e,type:"video",info:{width:r.codedWidth,height:r.codedHeight,decoderConfig:r,requiresAnnexBTransformation:a},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(l),this.trackDatas.sort((c,h)=>c.track.id-h.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),l}getAudioTrackData(e,t){const i=this.trackDatas.find(r=>r.track===e);if(i)return i;qr(t),x(t),x(t.decoderConfig);const n={muxer:this,track:e,type:"audio",info:{numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate,decoderConfig:t.decoderConfig,requiresPcmTransformation:!this.isFragmented&&he.includes(e.source._codec)},timescale:t.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(n),this.trackDatas.sort((r,a)=>r.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}getSubtitleTrackData(e,t){const i=this.trackDatas.find(r=>r.track===e);if(i)return i;Qr(t),x(t),x(t.config);const n={muxer:this,track:e,type:"subtitle",info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(n),this.trackDatas.sort((r,a)=>r.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}async addEncodedVideoPacket(e,t,i){const n=await this.mutex.acquire();try{const r=this.getVideoTrackData(e,t,i);let a=t.data;if(r.info.requiresAnnexBTransformation){const c=ta(a);if(!c)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");a=c}const o=this.validateAndNormalizeTimestamp(r.track,t.timestamp,t.type==="key"),l=this.createSampleForTrack(r,a,o,t.duration,t.type);await this.registerSample(r,l)}finally{n()}}async addEncodedAudioPacket(e,t,i){const n=await this.mutex.acquire();try{const r=this.getAudioTrackData(e,i),a=this.validateAndNormalizeTimestamp(r.track,t.timestamp,t.type==="key"),o=this.createSampleForTrack(r,t.data,a,t.duration,t.type);r.info.requiresPcmTransformation&&await this.maybePadWithSilence(r,a),await this.registerSample(r,o)}finally{n()}}async maybePadWithSilence(e,t){const i=le(e.samples),n=i?i.timestamp+i.duration:0,r=t-n,a=W(r,e.timescale);if(a>0){const{sampleSize:o,silentValue:l}=it(e.info.decoderConfig.codec),c=a*e.info.numberOfChannels,h=new Uint8Array(o*c).fill(l),d=this.createSampleForTrack(e,new Uint8Array(h.buffer),n,r,"key");await this.registerSample(e,d)}}async addSubtitleCue(e,t,i){const n=await this.mutex.acquire();try{const r=this.getSubtitleTrackData(e,i);this.validateAndNormalizeTimestamp(r.track,t.timestamp,!0),e.source._codec==="webvtt"&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{n()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){const i=new Set([]);for(const c of e.cueQueue)x(c.timestamp<=t),x(e.lastCueEndTimestamp<=c.timestamp+c.duration),i.add(Math.max(c.timestamp,e.lastCueEndTimestamp)),i.add(c.timestamp+c.duration);const n=[...i].sort((c,h)=>c-h),r=n[0],a=n[1]??r;if(t<a)break;if(e.lastCueEndTimestamp<r){this.auxWriter.seek(0);const c=ao();this.auxBoxWriter.writeBox(c);const h=this.auxWriter.getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,h,e.lastCueEndTimestamp,r-e.lastCueEndTimestamp,"key");await this.registerSample(e,d),e.lastCueEndTimestamp=r}this.auxWriter.seek(0);for(let c=0;c<e.cueQueue.length;c++){const h=e.cueQueue[c];if(h.timestamp>=a)break;us.lastIndex=0;const d=us.test(h.text),u=h.timestamp+h.duration;let p=e.cueToSourceId.get(h);if(p===void 0&&a<u&&(p=e.nextSourceId++,e.cueToSourceId.set(h,p)),h.notes){const b=co(h.notes);this.auxBoxWriter.writeBox(b)}const g=oo(h.text,d?r:null,h.identifier??null,h.settings??null,p??null);this.auxBoxWriter.writeBox(g),u===a&&e.cueQueue.splice(c--,1)}const o=this.auxWriter.getSlice(0,this.auxWriter.getPos()),l=this.createSampleForTrack(e,o,r,a-r,"key");await this.registerSample(e,l),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,i,n,r){return{timestamp:i,decodeTimestamp:i,duration:n,data:t,size:t.byteLength,type:r,timescaleUnitsToNextSample:W(n,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){let n=0;for(let r=0;r<e.timestampProcessingQueue.length;r++){const a=e.timestampProcessingQueue[r],o=W(a.duration,e.timescale);n+=o}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:n,sampleDelta:1});else{const r=le(e.timeToSampleTable);r.sampleCount+=n}e.timestampProcessingQueue.length=0;return}const i=e.timestampProcessingQueue.map(n=>n.timestamp).sort((n,r)=>n-r);for(let n=0;n<e.timestampProcessingQueue.length;n++){const r=e.timestampProcessingQueue[n];r.decodeTimestamp=i[n],!this.isFragmented&&e.lastTimescaleUnits===null&&(r.decodeTimestamp=0);const a=W(r.timestamp-r.decodeTimestamp,e.timescale),o=W(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){x(e.lastSample);const l=W(r.decodeTimestamp,e.timescale,!1),c=Math.round(l-e.lastTimescaleUnits);if(x(c>=0),e.lastTimescaleUnits+=c,e.lastSample.timescaleUnitsToNextSample=c,!this.isFragmented){let h=le(e.timeToSampleTable);if(x(h),h.sampleCount===1){h.sampleDelta=c;const u=e.timeToSampleTable[e.timeToSampleTable.length-2];u&&u.sampleDelta===c&&(u.sampleCount++,e.timeToSampleTable.pop(),h=u)}else h.sampleDelta!==c&&(h.sampleCount--,e.timeToSampleTable.push(h={sampleCount:1,sampleDelta:c}));h.sampleDelta===o?h.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});const d=le(e.compositionTimeOffsetTable);x(d),d.sampleCompositionTimeOffset===a?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=W(r.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=r}if(e.timestampProcessingQueue.length=0,x(e.lastSample),x(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){x(t.type==="key");const n=W(t.timestamp,e.timescale,!1),r=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=r}}async registerSample(e,t){t.type==="key"&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){this.isFragmented||e.samples.push(t);let i=!1;if(!e.currentChunk)i=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);const n=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const r=this.trackDatas.every(a=>{if(e===a)return t.type==="key";const o=a.sampleQueue[0];return o?o.type==="key":a.track.source._closed});n>=this.minimumFragmentDuration&&r&&t.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=n>=.5}i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),x(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(x(!this.isFragmented),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((i,n)=>i+W(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||le(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(const i of e.currentChunk.samples)x(i.data),this.writer.write(i.data),i.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(x(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let t=null,i=1/0;for(const r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!r.track.source._closed)break e;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<i&&(t=r,i=r.sampleQueue[0].timestamp)}if(!t)break;const n=t.sampleQueue.shift();await this.addSampleToTrack(t,n)}}async finalizeFragment(e=!0){x(this.isFragmented);const t=this.nextFragmentNumber++;if(t===1){this.format._options.onMoov&&this.writer.startTrackingWrites();const p=Kt(this.trackDatas,this.creationTime,!0);if(this.boxWriter.writeBox(p),this.format._options.onMoov){const{data:g,start:b}=this.writer.stopTrackingWrites();this.format._options.onMoov(g,b)}}const i=this.trackDatas.filter(p=>p.currentChunk),n=Ss(t,i),r=this.writer.getPos(),a=r+this.boxWriter.measureBox(n);let o=a+bi,l=1/0;for(const p of i){p.currentChunk.offset=o,p.currentChunk.moofOffset=r;for(const g of p.currentChunk.samples)o+=g.size;l=Math.min(l,p.currentChunk.startTimestamp)}const c=o-a,h=c>=2**32;if(h)for(const p of i)p.currentChunk.offset+=Os-bi;this.format._options.onMoof&&this.writer.startTrackingWrites();const d=Ss(t,i);if(this.boxWriter.writeBox(d),this.format._options.onMoof){const{data:p,start:g}=this.writer.stopTrackingWrites();this.format._options.onMoof(p,g,l)}x(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();const u=Ci(h);u.size=c,this.boxWriter.writeBox(u),this.writer.seek(a+(h?Os:bi));for(const p of i)for(const g of p.currentChunk.samples)this.writer.write(g.data),g.data=null;if(this.format._options.onMdat){const{data:p,start:g}=this.writer.stopTrackingWrites();this.format._options.onMdat(p,g)}for(const p of i)p.finalizedChunks.push(p.currentChunk),this.finalizedChunks.push(p.currentChunk),p.currentChunk=null;e&&await this.writer.flush()}async onTrackClose(e){const t=await this.mutex.acquire();if(e.type==="subtitle"&&e.source._codec==="webvtt"){const i=this.trackDatas.find(n=>n.track===e);i&&await this.processWebVTTCues(i,1/0)}this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const t of this.trackDatas)t.type==="subtitle"&&t.track.source._codec==="webvtt"&&await this.processWebVTTCues(t,1/0);if(this.isFragmented){await this.interleaveSamples(!0);for(const t of this.trackDatas)this.processTimestamps(t);await this.finalizeFragment(!1)}else for(const t of this.trackDatas)this.processTimestamps(t),await this.finalizeCurrentChunk(t);if(this.fastStart==="in-memory"){x(this.mdat);let t;for(let n=0;n<2;n++){const r=Kt(this.trackDatas,this.creationTime),a=this.boxWriter.measureBox(r);t=this.boxWriter.measureBox(this.mdat);let o=this.writer.getPos()+a+t;for(const l of this.finalizedChunks){l.offset=o;for(const{data:c}of l.samples)x(c),o+=c.byteLength,t+=c.byteLength}if(o<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const i=Kt(this.trackDatas,this.creationTime);if(this.boxWriter.writeBox(i),this.format._options.onMoov){const{data:n,start:r}=this.writer.stopTrackingWrites();this.format._options.onMoov(n,r)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(const n of this.finalizedChunks)for(const r of n.samples)x(r.data),this.writer.write(r.data),r.data=null;if(this.format._options.onMdat){const{data:n,start:r}=this.writer.stopTrackingWrites();this.format._options.onMdat(n,r)}}else if(this.isFragmented){const t=this.writer.getPos(),i=so(this.trackDatas);this.boxWriter.writeBox(i);const n=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{x(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);x(t!==void 0);const i=this.writer.getPos()-t;if(this.mdat.size=i,this.mdat.largeSize=i>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){const{data:r,start:a}=this.writer.stopTrackingWrites();this.format._options.onMdat(r,a)}this.format._options.onMoov&&this.writer.startTrackingWrites();const n=Kt(this.trackDatas,this.creationTime);if(this.boxWriter.writeBox(n),this.format._options.onMoov){const{data:r,start:a}=this.writer.stopTrackingWrites();this.format._options.onMoov(r,a)}}e()}}/*!
|
|
252
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
253
|
+
*
|
|
254
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
255
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
256
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
257
|
+
*/const xo=[],vo=[];/*!
|
|
258
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
259
|
+
*
|
|
260
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
261
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
262
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
263
|
+
*/const Ms=new Uint8Array(0);class Oe{constructor(e,t,i,n,r=-1,a){if(this.data=e,this.type=t,this.timestamp=i,this.duration=n,this.sequenceNumber=r,e===Ms&&a===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(n)||n<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(r))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(a)||a<0)throw new TypeError("byteLength must be a non-negative integer.");this.byteLength=a}get isMetadataOnly(){return this.data===Ms}get microsecondTimestamp(){return Math.trunc(Ie*this.timestamp)}get microsecondDuration(){return Math.trunc(Ie*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const t=new Uint8Array(e.byteLength);return e.copyTo(t),new Oe(t,e.type,e.timestamp/1e6,(e.duration??0)/1e6)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");return new Oe(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}}/*!
|
|
264
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
265
|
+
*
|
|
266
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
267
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
268
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
269
|
+
*/const To=s=>{let i=s,n=4096,r=0,a=12,o=0;for(i<0&&(i=-i,r=128),i+=33,i>8191&&(i=8191);(i&n)!==n&&a>=5;)n>>=1,a--;return o=i>>a-4&15,~(r|a-5<<4|o)&255},bo=s=>{let t=2048,i=0,n=11,r=0,a=s;for(a<0&&(a=-a,i=128),a>4095&&(a=4095);(a&t)!==t&&n>=5;)t>>=1,n--;return r=a>>(n===4?1:n-4)&15,(i|n-4<<4|r)^85};/*!
|
|
270
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
271
|
+
*
|
|
272
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
273
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
274
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
275
|
+
*/class Ue{get displayWidth(){return this.rotation%180===0?this.codedWidth:this.codedHeight}get displayHeight(){return this.rotation%180===0?this.codedHeight:this.codedWidth}get microsecondTimestamp(){return Math.trunc(Ie*this.timestamp)}get microsecondDuration(){return Math.trunc(Ie*this.duration)}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||ArrayBuffer.isView(e)){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(!("format"in t)||typeof t.format!="string")throw new TypeError("init.format must be a string.");if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=Ee(e).slice(),this.format=t.format,this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new VideoColorSpace(t.colorSpace)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(t?.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t?.timestamp!==void 0&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(t?.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=e,this.format=e.format,this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight,this.rotation=t?.rotation??0,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=e.colorSpace}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new Ue(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Ie),duration:Math.trunc((t.duration??0)*Ie)}),t);let i=0,n=0;if("naturalWidth"in e?(i=e.naturalWidth,n=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,n=e.videoHeight):"width"in e&&(i=Number(e.width),n=Number(e.height)),!i||!n)throw new TypeError("Could not determine dimensions.");const r=new OffscreenCanvas(i,n),a=r.getContext("2d",{alpha:!1,willReadFrequently:!0});x(a),a.drawImage(e,0,0),this._data=r,this.format="RGBX",this.codedWidth=i,this.codedHeight=n,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new VideoColorSpace({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.")}clone(){if(this._closed)throw new Error("VideoSample is closed.");return x(this._data!==null),yt(this._data)?new Ue(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?new Ue(this._data.slice(),{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation}):new Ue(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})}close(){this._closed||(yt(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(){if(this._closed)throw new Error("VideoSample is closed.");return x(this._data!==null),yt(this._data)?this._data.allocationSize():this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e){if(!Gt(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(this._closed)throw new Error("VideoSample is closed.");if(x(this._data!==null),yt(this._data))await this._data.copyTo(e);else if(this._data instanceof Uint8Array)Ee(e).set(this._data);else{const i=this._data.getContext("2d",{alpha:!1});x(i);const n=i.getImageData(0,0,this.codedWidth,this.codedHeight);Ee(e).set(n.data)}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return x(this._data!==null),yt(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}draw(e,t,i,n,r,a,o,l,c){let h=0,d=0,u=this.displayWidth,p=this.displayHeight,g=0,b=0,_=this.displayWidth,B=this.displayHeight;if(a!==void 0?(h=t,d=i,u=n,p=r,g=a,b=o,l!==void 0?(_=l,B=c):(_=u,B=p)):(g=t,b=i,n!==void 0&&(_=n,B=r)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(h))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(u)||u<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(p)||p<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(g))throw new TypeError("dx must be a number.");if(!Number.isFinite(b))throw new TypeError("dy must be a number.");if(!Number.isFinite(_)||_<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(B)||B<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");this.rotation===90?[h,d,u,p]=[d,this.codedHeight-h-u,p,u]:this.rotation===180?[h,d]=[this.codedWidth-h-u,this.codedHeight-d-p]:this.rotation===270&&([h,d,u,p]=[this.codedWidth-d-p,h,p,u]);const N=this.toCanvasImageSource();e.save();const J=g+_/2,$=b+B/2;e.translate(J,$),e.rotate(this.rotation*Math.PI/180);const Z=this.rotation%180===0?1:_/B;e.scale(1/Z,Z),e.drawImage(N,h,d,u,p,-_/2,-B/2,_,B),e.restore()}drawWithFit(e,t){const i=e.canvas.width,n=e.canvas.height,r=t.rotation??this.rotation;let a,o,l,c;if(t.fit==="fill")a=0,o=0,l=i,c=n;else{const[d,u]=r%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth],p=t.fit==="contain"?Math.min(i/d,n/u):Math.max(i/d,n/u);l=d*p,c=u*p,a=(i-l)/2,o=(n-c)/2}const h=r%180===0?1:l/c;e.translate(i/2,n/2),e.rotate(r*Math.PI/180),e.scale(1/h,h),e.translate(-i/2,-n/2),e.drawImage(this.toCanvasImageSource(),a,o,l,c)}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(x(this._data!==null),this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}}const yt=s=>typeof VideoFrame<"u"&&s instanceof VideoFrame,Si=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class We{get microsecondTimestamp(){return Math.trunc(Ie*this.timestamp)}get microsecondDuration(){return Math.trunc(Ie*this.duration)}constructor(e){if(this._closed=!1,Ct(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Si.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(wt(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let i;if(e.data instanceof ArrayBuffer)i=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))i=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");const n=this.numberOfFrames*this.numberOfChannels*wt(this.format);if(i.byteLength<n)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=i}}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!Si.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const t=e.format??this.format,i=e.frameOffset??0;if(i>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const n=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-i;if(n>this.numberOfFrames-i)throw new RangeError("frameCount out of range");const r=wt(t),a=jt(t);if(a&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!a&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(a?n:n*this.numberOfChannels)*r}copyTo(e,t){if(!Gt(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(t.format!==void 0&&!Si.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{planeIndex:i,format:n,frameCount:r,frameOffset:a}=t,o=n??this.format;if(!o)throw new Error("Destination format not determined");const l=this.numberOfFrames,c=this.numberOfChannels,h=a??0;if(h>=l)throw new RangeError("frameOffset out of range");const d=r!==void 0?r:l-h;if(d>l-h)throw new RangeError("frameCount out of range");const u=wt(o),p=jt(o);if(p&&i>=c)throw new RangeError("planeIndex out of range");if(!p&&i!==0)throw new RangeError("planeIndex out of range");const b=(p?d:d*c)*u;if(e.byteLength<b)throw new RangeError("Destination buffer is too small");const _=ts(e),B=So(o);if(Ct(this._data))if(p)if(o==="f32-planar")this._data.copyTo(e,{planeIndex:i,frameOffset:h,frameCount:d,format:"f32-planar"});else{const N=new ArrayBuffer(d*4),J=new Float32Array(N);this._data.copyTo(J,{planeIndex:i,frameOffset:h,frameCount:d,format:"f32-planar"});const $=new DataView(N);for(let Z=0;Z<d;Z++){const fe=Z*u,se=$.getFloat32(Z*4,!0);B(_,fe,se)}}else{const N=c,J=new Float32Array(d);for(let $=0;$<N;$++){this._data.copyTo(J,{planeIndex:$,frameOffset:h,frameCount:d,format:"f32-planar"});for(let Z=0;Z<d;Z++){const se=(Z*N+$)*u;B(_,se,J[Z])}}}else{const N=this._data,J=new DataView(N.buffer,N.byteOffset,N.byteLength),$=this.format,Z=ko($),fe=wt($),se=jt($);for(let me=0;me<d;me++)if(p){const Me=me*u;let U;se?U=(i*l+(me+h))*fe:U=((me+h)*c+i)*fe;const z=Z(J,U);B(_,Me,z)}else for(let Me=0;Me<c;Me++){const z=(me*c+Me)*u;let Ge;se?Ge=(Me*l+(me+h))*fe:Ge=((me+h)*c+Me)*fe;const vt=Z(J,Ge);B(_,z,vt)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(Ct(this._data)){const e=new We(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new We({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(Ct(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(Ct(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(jt(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(new Uint8Array(t,i*e,e),{planeIndex:i,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{const e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}else return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data})}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");const e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(t,{planeIndex:i,format:"f32-planar"}),e.copyToChannel(t,i);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,n=e.numberOfChannels,r=e.sampleRate,a=e.length,o=Math.floor(i/n);let l=0,c=a;for(;c>0;){const h=Math.min(o,c),d=new Float32Array(n*h);for(let u=0;u<n;u++)e.copyFromChannel(d.subarray(u*h,(u+1)*h),u,l);yield new We({format:"f32-planar",sampleRate:r,numberOfFrames:h,numberOfChannels:n,timestamp:t+l/r,data:d}),l+=h,c-=h}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,n=e.numberOfChannels,r=e.sampleRate,a=e.length,o=Math.floor(i/n);let l=0,c=a;const h=[];for(;c>0;){const d=Math.min(o,c),u=new Float32Array(n*d);for(let g=0;g<n;g++)e.copyFromChannel(u.subarray(g*d,(g+1)*d),g,l);const p=new We({format:"f32-planar",sampleRate:r,numberOfFrames:d,numberOfChannels:n,timestamp:t+l/r,data:u});h.push(p),l+=d,c-=d}return h}}const wt=s=>{switch(s){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},jt=s=>{switch(s){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},ko=s=>{switch(s){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},So=s=>{switch(s){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,Q((i+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,Q(Math.round(i*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,Q(Math.round(i*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Ct=s=>typeof AudioData<"u"&&s instanceof AudioData;/*!
|
|
276
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
277
|
+
*
|
|
278
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
279
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
280
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
281
|
+
*/class Rs{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>Ve.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>tt.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>$t.includes(e))}_codecUnsupportedHint(e){return""}}class Bs extends Rs{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","fragmented"].includes(e.fastStart))throw new TypeError('options.fastStart, when provided, must be false, "in-memory", or "fragmented".');if(e.minimumFragmentDuration!==void 0&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:2**32-1}}}get supportsVideoRotationMetadata(){return!0}_createMuxer(e){return new Co(e,this)}}class Ls extends Bs{get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Ve,...rs,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...$t]}_codecUnsupportedHint(e){return new Fs().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class Fs extends Bs{get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...Ve,...tt]}_codecUnsupportedHint(e){return new Ls().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}/*!
|
|
282
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
283
|
+
*
|
|
284
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
285
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
286
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
287
|
+
*/const _o=s=>{if(!s||typeof s!="object")throw new TypeError("Encoding config must be an object.");if(!Ve.includes(s.codec))throw new TypeError(`Invalid video codec '${s.codec}'. Must be one of: ${Ve.join(", ")}.`);if(!(s.bitrate instanceof Zt)&&(!Number.isInteger(s.bitrate)||s.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(s.keyFrameInterval!==void 0&&(!Number.isFinite(s.keyFrameInterval)||s.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(s.onEncodedPacket!==void 0&&typeof s.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(s.onEncoderConfig!==void 0&&typeof s.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");Eo(s.codec,s)},Eo=(s,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&ds(e.fullCodecString)!==s)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${s}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},Io=s=>{const e=s.bitrate instanceof Zt?s.bitrate._toVideoBitrate(s.codec,s.width,s.height):s.bitrate;return{codec:s.fullCodecString??Hr(s.codec,s.width,s.height,e),width:s.width,height:s.height,bitrate:e,bitrateMode:s.bitrateMode,framerate:s.framerate,latencyMode:s.latencyMode,hardwareAcceleration:s.hardwareAcceleration,scalabilityMode:s.scalabilityMode,contentHint:s.contentHint,...Ur(s.codec)}},Po=s=>{if(!s||typeof s!="object")throw new TypeError("Encoding config must be an object.");if(!tt.includes(s.codec))throw new TypeError(`Invalid audio codec '${s.codec}'. Must be one of: ${tt.join(", ")}.`);if(s.bitrate===void 0&&(!he.includes(s.codec)||s.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(s.bitrate!==void 0&&!(s.bitrate instanceof Zt)&&(!Number.isInteger(s.bitrate)||s.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(s.onEncodedPacket!==void 0&&typeof s.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(s.onEncoderConfig!==void 0&&typeof s.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");Ao(s.codec,s)},Ao=(s,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&ds(e.fullCodecString)!==s)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${s}).`)},Oo=s=>{const e=s.bitrate instanceof Zt?s.bitrate._toAudioBitrate(s.codec):s.bitrate;return{codec:s.fullCodecString??Nr(s.codec,s.numberOfChannels,s.sampleRate),numberOfChannels:s.numberOfChannels,sampleRate:s.sampleRate,bitrate:e,bitrateMode:s.bitrateMode,...Wr(s.codec)}};/*!
|
|
288
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
289
|
+
*
|
|
290
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
291
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
292
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
293
|
+
*/class _i{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._timestampOffset=0}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;const e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise?this._closingPromise:this._flushAndClose(e)}}class zs extends _i{constructor(e){if(super(),this._connectedTrack=null,!Ve.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${Ve.join(", ")}.`);this._codec=e}}class Mo{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.codedWidth=null,this.codedHeight=null,this.resizeCanvas=null,this.customEncoder=null,this.customEncoderCallSerializer=new ns,this.customEncoderQueueSize=0,this.encoderError=null}async add(e,t,i){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.codedWidth!==null&&this.codedHeight!==null){if(e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight){const o=this.encodingConfig.sizeChangeBehavior??"deny";if(o!=="passThrough"){if(o==="deny")throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'strict' in the encoding options.`);{let l=!1;this.resizeCanvas||(typeof document<"u"?(this.resizeCanvas=document.createElement("canvas"),this.resizeCanvas.width=this.codedWidth,this.resizeCanvas.height=this.codedHeight):this.resizeCanvas=new OffscreenCanvas(this.codedWidth,this.codedHeight),l=!0);const c=this.resizeCanvas.getContext("2d",{alpha:!1});x(c),l||c.clearRect(0,0,this.codedWidth,this.codedHeight),e.drawWithFit(c,{fit:o}),t&&e.close(),e=new Ue(this.resizeCanvas,{timestamp:e.timestamp,duration:e.duration,rotation:e.rotation}),t=!0}}}}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),x(this.encoderInitialized);const n=this.encodingConfig.keyFrameInterval??5,r=Math.floor(e.timestamp/n),a={...i,keyFrame:i?.keyFrame||n===0||r!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=r,this.customEncoder){this.customEncoderQueueSize++;const o=e.clone(),l=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(o,a)).then(()=>this.customEncoderQueueSize--).catch(c=>this.encoderError??=c).finally(()=>{o.close()});this.customEncoderQueueSize>=4&&await l}else{x(this.encoder);const o=e.toVideoFrame();this.encoder.encode(o,a),o.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(l=>this.encoder.addEventListener("dequeue",l,{once:!0}))}await this.muxer.mutex.currentPromise}finally{t&&e.close()}}async ensureEncoder(e){if(!this.encoder)return this.ensureEncoderPromise=(async()=>{const t=Io({width:e.codedWidth,height:e.codedHeight,...this.encodingConfig,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(t);const i=xo.find(n=>n.supports(this.encodingConfig.codec,t));if(i)this.customEncoder=new i,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=t,this.customEncoder.onPacket=(n,r)=>{if(!(n instanceof Oe))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(r!==void 0&&(!r||typeof r!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(n,r),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,n,r)},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(!(await VideoEncoder.isConfigSupported(t)).supported)throw new Error(`This specific encoder configuration (${t.codec}, ${t.bitrate} bps, ${t.width}x${t.height}, hardware acceleration: ${t.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);this.encoder=new VideoEncoder({output:(r,a)=>{const o=Oe.fromEncodedChunk(r);this.encodingConfig.onEncodedPacket?.(o,a),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,o,a)},error:r=>{r.stack=new Error().stack,this.encoderError??=r}}),this.encoder.configure(t)}x(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),this.encoder.close()),this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.encoderError)throw this.encoderError}}class Ro extends zs{constructor(e,t){if(!(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");_o(t),super(t.codec),this._encoder=new Mo(this,t),this._canvas=e}add(e,t=0,i){if(!Number.isFinite(e)||e<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(t)||t<0)throw new TypeError("duration must be a non-negative number.");const n=new Ue(this._canvas,{timestamp:e,duration:t});return this._encoder.add(n,!0,i)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Ds extends _i{constructor(e){if(super(),this._connectedTrack=null,!tt.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${tt.join(", ")}.`);this._codec=e}}class Bo{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new ns,this.customEncoderQueueSize=0,this.encoderError=null}async add(e,t){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),x(this.encoderInitialized),this.customEncoder){this.customEncoderQueueSize++;const i=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(i)).then(()=>this.customEncoderQueueSize--).catch(r=>this.encoderError??=r).finally(()=>{i.close()});this.customEncoderQueueSize>=4&&await n,await this.muxer.mutex.currentPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{x(this.encoder);const i=e.toAudioData();this.encoder.encode(i),i.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(n=>this.encoder.addEventListener("dequeue",n,{once:!0})),await this.muxer.mutex.currentPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){x(this.outputSampleSize),x(this.writeOutputValue);const{numberOfChannels:i,numberOfFrames:n,sampleRate:r,timestamp:a}=e,o=2048,l=[];for(let u=0;u<n;u+=o){const p=Math.min(o,e.numberOfFrames-u),g=p*i*this.outputSampleSize,b=new ArrayBuffer(g),_=new DataView(b);l.push({frameCount:p,view:_})}const c=e.allocationSize({planeIndex:0,format:"f32-planar"}),h=new Float32Array(c/Float32Array.BYTES_PER_ELEMENT);for(let u=0;u<i;u++){e.copyTo(h,{planeIndex:u,format:"f32-planar"});for(let p=0;p<l.length;p++){const{frameCount:g,view:b}=l[p];for(let _=0;_<g;_++)this.writeOutputValue(b,(_*i+u)*this.outputSampleSize,h[p*o+_])}}t&&e.close();const d={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:i,sampleRate:r}};for(let u=0;u<l.length;u++){const{frameCount:p,view:g}=l[u],b=g.buffer,_=u*o,B=new Oe(new Uint8Array(b),"key",a+_/r,p/r);this.encodingConfig.onEncodedPacket?.(B,d),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,B,d)}}ensureEncoder(e){if(!this.encoderInitialized)return this.ensureEncoderPromise=(async()=>{const{numberOfChannels:t,sampleRate:i}=e,n=Oo({numberOfChannels:t,sampleRate:i,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(n);const r=vo.find(a=>a.supports(this.encodingConfig.codec,n));if(r)this.customEncoder=new r,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=n,this.customEncoder.onPacket=(a,o)=>{if(!(a instanceof Oe))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(o!==void 0&&(!o||typeof o!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(a,o),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,a,o)},await this.customEncoder.init();else if(he.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(n)).supported)throw new Error(`This specific encoder configuration (${n.codec}, ${n.bitrate} bps, ${n.numberOfChannels} channels, ${n.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);this.encoder=new AudioEncoder({output:(o,l)=>{const c=Oe.fromEncodedChunk(o);this.encodingConfig.onEncodedPacket?.(c,l),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,c,l)},error:o=>{o.stack=new Error().stack,this.encoderError??=o}}),this.encoder.configure(n)}x(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;const e=this.encodingConfig.codec,{dataType:t,sampleSize:i,littleEndian:n}=it(e);switch(this.outputSampleSize=i,i){case 1:t==="unsigned"?this.writeOutputValue=(r,a,o)=>r.setUint8(a,Q((o+1)*127.5,0,255)):t==="signed"?this.writeOutputValue=(r,a,o)=>{r.setInt8(a,Q(Math.round(o*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(r,a,o)=>{const l=Q(Math.floor(o*32767),-32768,32767);r.setUint8(a,To(l))}:t==="alaw"?this.writeOutputValue=(r,a,o)=>{const l=Q(Math.floor(o*32767),-32768,32767);r.setUint8(a,bo(l))}:x(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(r,a,o)=>r.setUint16(a,Q((o+1)*32767.5,0,65535),n):t==="signed"?this.writeOutputValue=(r,a,o)=>r.setInt16(a,Q(Math.round(o*32767),-32768,32767),n):x(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(r,a,o)=>ss(r,a,Q((o+1)*83886075e-1,0,16777215),n):t==="signed"?this.writeOutputValue=(r,a,o)=>Br(r,a,Q(Math.round(o*8388607),-8388608,8388607),n):x(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(r,a,o)=>r.setUint32(a,Q((o+1)*21474836475e-1,0,4294967295),n):t==="signed"?this.writeOutputValue=(r,a,o)=>r.setInt32(a,Q(Math.round(o*2147483647),-2147483648,2147483647),n):t==="float"?this.writeOutputValue=(r,a,o)=>r.setFloat32(a,o,n):x(!1);break;case 8:t==="float"?this.writeOutputValue=(r,a,o)=>r.setFloat64(a,o,n):x(!1);break;default:Rr(i),x(!1)}}async flushAndClose(e){this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),this.encoder.close()),this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.encoderError)throw this.encoderError}}class Lo extends Ds{constructor(e){Po(e),super(e.codec),this._encoder=new Bo(this,e)}add(e){if(!(e instanceof We))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Fo extends _i{constructor(e){if(super(),this._connectedTrack=null,!$t.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${$t.join(", ")}.`);this._codec=e}}/*!
|
|
294
|
+
* Copyright (c) 2025-present, Vanilagy and contributors
|
|
295
|
+
*
|
|
296
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
297
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
298
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
299
|
+
*/const zo=["video","audio","subtitle"],Ei=s=>{if(!s||typeof s!="object")throw new TypeError("metadata must be an object.");if(s.languageCode!==void 0&&!zr(s.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(s.name!==void 0&&typeof s.name!="string")throw new TypeError("metadata.name, when provided, must be a string.")};class Do{constructor(e){if(this.state="pending",this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new is,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof Rs))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof Ps))throw new TypeError("options.target must be a Target.");if(e.target._output)throw new Error("Target is already used for another output.");e.target._output=this,this.format=e.format,this.target=e.target,this._writer=e.target._createWriter(),this._muxer=e.format._createMuxer(this)}addVideoTrack(e,t={}){if(!(e instanceof zs))throw new TypeError("source must be a VideoSource.");if(Ei(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);this._addTrack("video",e,t)}addAudioTrack(e,t={}){if(!(e instanceof Ds))throw new TypeError("source must be an AudioSource.");Ei(t),this._addTrack("audio",e,t)}addSubtitleTrack(e,t={}){if(!(e instanceof Fo))throw new TypeError("source must be a SubtitleSource.");Ei(t),this._addTrack("subtitle",e,t)}_addTrack(e,t,i){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(t._connectedTrack)throw new Error("Source is already used for a track.");const n=this.format.getSupportedTrackCounts(),r=this._tracks.reduce((c,h)=>c+(h.type===e?1:0),0),a=n[e].max;if(r===a)throw new Error(a===0?`${this.format._name} does not support ${e} tracks.`:`${this.format._name} does not support more than ${a} ${e} track${a===1?"":"s"}.`);const o=n.total.max;if(this._tracks.length===o)throw new Error(`${this.format._name} does not support more than ${o} tracks${o===1?"":"s"} in total.`);const l={id:this._tracks.length+1,output:this,type:e,source:t,metadata:i};if(l.type==="video"){const c=this.format.getSupportedVideoCodecs();if(c.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(l.source._codec));if(!c.includes(l.source._codec))throw new Error(`Codec '${l.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${c.map(h=>`'${h}'`).join(", ")}.`+this.format._codecUnsupportedHint(l.source._codec))}else if(l.type==="audio"){const c=this.format.getSupportedAudioCodecs();if(c.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(l.source._codec));if(!c.includes(l.source._codec))throw new Error(`Codec '${l.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${c.map(h=>`'${h}'`).join(", ")}.`+this.format._codecUnsupportedHint(l.source._codec))}else if(l.type==="subtitle"){const c=this.format.getSupportedSubtitleCodecs();if(c.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(l.source._codec));if(!c.includes(l.source._codec))throw new Error(`Codec '${l.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${c.map(h=>`'${h}'`).join(", ")}.`+this.format._codecUnsupportedHint(l.source._codec))}this._tracks.push(l),t._connectedTrack=l}async start(){const e=this.format.getSupportedTrackCounts();for(const i of zo){const n=this._tracks.reduce((a,o)=>a+(o.type===i?1:0),0),r=e[i].min;if(n<r)throw new Error(r===e[i].max?`${this.format._name} requires exactly ${r} ${i} track${r===1?"":"s"}.`:`${this.format._name} requires at least ${r} ${i} track${r===1?"":"s"}.`)}const t=e.total.min;if(this._tracks.length<t)throw new Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?"":"s"}.`:`${this.format._name} requires at least ${t} track${t===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(console.warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started",this._writer.start();const i=await this._mutex.acquire();await this._muxer.start();const n=this._tracks.map(r=>r.source._start());await Promise.all(n),i()})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return console.warn("Output has already been canceled."),this._cancelPromise;if(this.state==="finalizing"||this.state==="finalized"){console.warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";const e=await this._mutex.acquire(),t=this._tracks.map(i=>i.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await this._writer.close(),e()})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(console.warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";const e=await this._mutex.acquire(),t=this._tracks.map(i=>i.source._flushOrWaitForOngoingClose(!1));await Promise.all(t),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state="finalized",e()})()}}class Ho{audioTracks=[];async setupAudioTracks(e,t){const i=this.findAudioPlayers(e);if(!i.length)return null;this.audioTracks=[];for(const r of i){const a=await this.processAudioTrack(r);a&&this.audioTracks.push(a)}if(!this.audioTracks.length)return null;const n=new Lo({codec:"aac",bitrate:128e3});return t.addAudioTrack(n),n}async processAudioSamples(e){if(!this.audioTracks?.length)return;const t=new AudioContext;for(const i of this.audioTracks){const n=await t.decodeAudioData(i.data.slice(0)),{numberOfChannels:r,sampleRate:a,length:o}=n,l=Math.min(o,Math.floor(a*i.duration/1e3)),c=new Float32Array(l*r);for(let h=0;h<r;h+=1){const d=n.getChannelData(h);for(let u=0;u<l;u+=1)c[u*r+h]=d[u]*i.volume}await e.add(new We({data:c,format:"f32",numberOfChannels:r,sampleRate:a,timestamp:i.start/1e3}))}this.audioTracks=[]}findAudioPlayers(e){const t=[];for(const i of e)for(const n of i)this.isAudioPlayer(n)&&!t.includes(n)&&t.push(n);return t}async processAudioTrack(e){try{const t=e.clipConfiguration?.asset;if(!t?.src)return null;const i=await fetch(t.src);return i.ok?{data:await i.arrayBuffer(),start:e.getStart(),duration:e.getLength(),volume:e.getVolume()}:null}catch(t){return console.warn("Failed to process audio track:",t),null}}isAudioPlayer(e){if(e instanceof Ai)return!0;if(!e||typeof e!="object")return!1;const t=e,i=t.constructor?.name==="AudioPlayer",a=t.clipConfiguration?.asset?.type==="audio";return i||a}}class Vo{overlay=null;bar=null;percent=null;status=null;create(){this.overlay=Object.assign(document.createElement("div"),{style:"position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:9999;display:flex;justify-content:center;align-items:center;color:white;font-family:Arial"});const e=Object.assign(document.createElement("div"),{style:"background:#222;border-radius:8px;padding:20px;box-shadow:0 4px 8px rgba(0,0,0,0.2);width:300px;text-align:center"});e.innerHTML='<h3 style="margin:0 0 15px 0;font-weight:normal">Exporting Video</h3>',this.status=Object.assign(document.createElement("div"),{style:"font-size:12px;margin-bottom:10px;opacity:0.8"}),e.appendChild(this.status);const t=Object.assign(document.createElement("div"),{style:"width:100%;height:6px;background:#444;border-radius:3px;overflow:hidden;margin-bottom:10px"});this.bar=Object.assign(document.createElement("div"),{style:"width:0%;height:100%;background:#3498db;transition:width 0.3s"}),t.appendChild(this.bar),e.appendChild(t),this.percent=Object.assign(document.createElement("div"),{style:"font-size:12px",innerText:"0%"}),e.appendChild(this.percent),this.overlay.appendChild(e),document.body.appendChild(this.overlay)}update(e,t,i){if(!this.overlay)return;const n=Math.round(e/t*100);this.bar&&(this.bar.style.width=`${n}%`),this.percent&&(this.percent.innerText=`${n}%`),this.status&&i&&(this.status.innerText=i)}remove(){this.overlay?.remove(),this.overlay=null,this.bar=null,this.percent=null,this.status=null}}class Hs extends Map{constructor(e){super(),this.maxSize=e}get(e){const t=super.get(e);if(t!==void 0)return super.delete(e),super.set(e,t),t}set(e,t){if(super.delete(e),super.set(e,t),this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}}class Xt extends Error{constructor(e,t="unknown",i={},n){super(e),this.phase=t,this.context=i,this.name="ExportError",this.cause=n}}class No extends Xt{constructor(e,t){super(e,"initialization",{missingFeatures:t}),this.name="BrowserCompatibilityError"}}function Vs(s){if(!s||typeof s!="object")return!1;const e=s,t=e.constructor?.name==="VideoPlayer",n=e.texture?.source?.resource instanceof HTMLVideoElement;return t||n}class Uo{frameCache=new Hs(10);textureCache=new Hs(5);videoElements=new Map;extractionCanvas=null;extractionContext=null;async initialize(e){for(const t of e)if(Vs(t)){const i=t,n=i.texture?.source?.resource;n&&this.videoElements.set(this.getVideoKey(i),{element:n,player:i})}this.extractionCanvas=document.createElement("canvas"),this.extractionCanvas.width=3840,this.extractionCanvas.height=2160,this.extractionContext=this.extractionCanvas.getContext("2d",{willReadFrequently:!0,alpha:!0})}async extractFrame(e,t){const i=`${e}-${t}`,n=this.frameCache.get(i);if(n)return n;const r=this.videoElements.get(e);if(!r||!this.extractionContext||!this.extractionCanvas)return null;try{const{element:a,player:o}=r,l=(t-(o.getStart?.()||0))/1e3+(o.clipConfiguration?.asset?.trim||0);await this.seekToTime(a,l);const c=a.videoWidth||a.width||1920,h=a.videoHeight||a.height||1080;this.extractionContext.clearRect(0,0,c,h),this.extractionContext.drawImage(a,0,0,c,h);const d=this.extractionContext.getImageData(0,0,c,h);return this.frameCache.set(i,d),d}catch(a){return console.warn("Failed to extract frame:",a),null}}async replaceVideoTexture(e,t){const i=await this.extractFrame(this.getVideoKey(e),t);if(!i)return;const n=`${this.getVideoKey(e)}-${t}`;let r=this.textureCache.get(n);if(!r){const a=document.createElement("canvas");a.width=i.width,a.height=i.height;const o=a.getContext("2d");o&&(o.putImageData(i,0,0),r=f.Texture.from(a),this.textureCache.set(n,r))}r&&e.texture&&(e.originalTextureSource||(e.originalTextureSource=e.texture.source,e.texture.source?.resource instanceof HTMLVideoElement&&(e.originalVideoElement=e.texture.source.resource)),e.texture=r,e.sprite?.texture&&(e.sprite.texture=r),e.lastReplacedTimestamp=t)}disableVideoPlayback(e){const t=[];for(const i of e)if(Vs(i)){const n=i;t.push(n),n.texture?.source?.resource instanceof HTMLVideoElement&&n.texture.source.resource.pause(),n.skipVideoUpdate=!0}return t}getVideoKey(e){return e.clipConfiguration?.asset?.src||""}dispose(){this.frameCache.clear(),this.textureCache.clear(),this.videoElements.clear(),this.extractionCanvas=null,this.extractionContext=null}async seekToTime(e,t){return new Promise(i=>{if(Math.abs(e.currentTime-t)<.1){i();return}const n=()=>{e.removeEventListener("seeked",n),setTimeout(i,1)};e.addEventListener("seeked",n),e.currentTime=t})}}class Wo{edit;canvas;app;isExporting=!1;videoProcessor=new Uo;audioProcessor=new Ho;progressUI=new Vo;exportCommand=new Ar;constructor(e,t){this.edit=e,this.canvas=t,this.app=t.application,document.addEventListener("keydown",this.handleKeyDown)}async export(e="shotstack-export.mp4",t){if(typeof VideoEncoder>"u")throw new No("WebCodecs API not supported",["VideoEncoder"]);if(this.isExporting)throw new Xt("Export in progress","init");this.isExporting=!0;const i=this.saveEditState();this.edit.setExportMode(!0);try{this.progressUI.create(),this.canvas.pauseTicker();const n=this.prepareConfig(t??this.edit.getEdit().output?.fps??30);this.progressUI.update(0,100,"Preparing..."),this.edit.executeEditCommand(this.exportCommand),await this.videoProcessor.initialize(this.exportCommand.getClips()),this.progressUI.update(10,100,"Video ready");const r=new Do({format:new Ls,target:new As}),a=document.createElement("canvas");a.width=n.size.width,a.height=n.size.height;const o=a.getContext("2d");if(!o)throw new Error("No 2D context");const l=new Ro(a,{codec:"avc",bitrate:5e6});r.addVideoTrack(l),this.progressUI.update(15,100,"Audio...");const c=await this.audioProcessor.setupAudioTracks(this.exportCommand.getTracks(),r);await r.start(),c&&(this.progressUI.update(20,100,"Encoding audio..."),await this.audioProcessor.processAudioSamples(c)),this.progressUI.update(25,100,"Exporting..."),await this.processFrames(n,l,a,o),await r.finalize();const h=r.target.buffer;if(!h)throw new Error("No video data");const d=new Blob([h],{type:"video/mp4"}),u=URL.createObjectURL(d),p=document.createElement("a");p.href=u,p.download=e,p.click(),URL.revokeObjectURL(u),this.progressUI.update(100,100,"Complete!")}catch(n){throw n instanceof Xt?n:new Xt(`Export failed: ${n}`,"export")}finally{this.isExporting=!1,this.edit.setExportMode(!1),this.canvas.resumeTicker(),this.progressUI.remove(),this.restoreEditState(i)}}async processFrames(e,t,i,n){const r=this.edit.getContainer();this.edit.pause(),Object.assign(r.position,{x:0,y:0}),Object.assign(r.scale,{x:1,y:1}),r.visible=!0;const a=this.videoProcessor.disableVideoPlayback(this.exportCommand.getClips());for(let o=0;o<e.frames;o+=1){const l=o*e.frameDuration;this.edit.playbackTime=l;for(const d of this.exportCommand.getClips())d.update(0,0);for(const d of a){const u=d.getStart?.()||0,p=d.getEnd?.()||u+(d.getLength?.()||0);l>=u&&l<p&&await this.videoProcessor.replaceVideoTexture(d,l)}this.edit.draw(),this.app.renderer.render(this.app.stage);const c=this.app.renderer.extract.pixels({target:r,frame:new f.Rectangle(0,0,e.size.width,e.size.height)}),h=new ImageData(new Uint8ClampedArray(c.pixels),c.width,c.height);n.putImageData(h,0,0),await t.add(o/e.fps,1/e.fps),this.progressUI.update(25+Math.round((o+1)/e.frames*75),100,"Exporting...")}}handleKeyDown=e=>{e.target instanceof HTMLInputElement||e.target instanceof HTMLTextAreaElement||e.code==="KeyE"&&(e.metaKey||e.ctrlKey)&&!this.isExporting&&(e.preventDefault(),this.export("shotstack-export.mp4",this.edit.getEdit().output?.fps||30).catch(t=>console.error("Export failed:",t)))};dispose(){document.removeEventListener("keydown",this.handleKeyDown),this.videoProcessor.dispose(),this.progressUI.remove()}prepareConfig(e){const t=this.edit.getEdit().output?.size||{width:1920,height:1080},i=this.edit.totalDuration/1e3;return{fps:e,size:t,frames:Math.ceil(i*e),frameDuration:1e3/e}}saveEditState(){const e=this.edit.getContainer();return{wasPlaying:this.edit.isPlaying,time:this.edit.playbackTime,visible:e.visible,pos:{x:e.position.x,y:e.position.y},scale:{x:e.scale.x,y:e.scale.y}}}restoreEditState(e){const t=this.edit.getContainer();this.edit.setExportMode(!1);for(const i of this.exportCommand.getClips())if(this.isVideoPlayer(i)){const n=i;if(n.skipVideoUpdate=!1,n.originalVideoElement&&n.texture){const r=f.Texture.from(n.originalVideoElement);n.texture=r,n.sprite&&(n.sprite.texture=r),delete n.originalVideoElement,delete n.originalTextureSource,delete n.lastReplacedTimestamp}else n.originalTextureSource&&n.texture&&(n.texture.source=n.originalTextureSource,delete n.originalTextureSource,delete n.lastReplacedTimestamp)}Object.assign(t.position,e.pos),Object.assign(t.scale,e.scale),t.visible=e.visible,this.edit.seek(e.time),e.wasPlaying&&this.edit.play()}isVideoPlayer(e){if(!e||typeof e!="object")return!1;const t=e,i=t.constructor?.name==="VideoPlayer",r=t.texture?.source?.resource instanceof HTMLVideoElement;return i||r}}function Ns(s){const e=s.replace("#",""),t=parseInt(e,16);return Number.isNaN(t)?(console.warn(`Invalid hex color: ${s}, defaulting to black`),0):t}function Go(s){const e=t=>{if(typeof t=="string")return Ns(t);if(typeof t=="object"&&t!==null){const i=Array.isArray(t)?[]:{};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[n]=e(t[n]));return i}return t};return e(s)}function Us(s){if(typeof s=="string")return Ns(s);if(typeof s=="object"&&s!==null){const e=Array.isArray(s)?[]:{};for(const t in s)Object.prototype.hasOwnProperty.call(s,t)&&(e[t]=Us(s[t]));return e}return s}const Ws=Go({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 Gs{static resolveTheme(e){if(!e||!e.theme)return this.deepClone(Ws);const t=Us(e.theme),i=this.deepClone(Ws);return this.deepMerge(i,t)}static validateTheme(e){try{if(!e.timeline)return!1;const{timeline:t}=e;if(typeof t.background!="number"||typeof t.divider!="number"||typeof t.playhead!="number"||typeof t.snapGuide!="number"||typeof t.dropZone!="number"||typeof t.trackInsertion!="number"||!t.toolbar)return!1;const{toolbar:i}=t;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||!t.ruler)return!1;const{ruler:n}=t;if(typeof n.background!="number"||typeof n.text!="number"||typeof n.markers!="number"||typeof n.height!="number"||n.height<=0||!t.tracks)return!1;const{tracks:r}=t;if(typeof r.surface!="number"||typeof r.surfaceAlt!="number"||typeof r.border!="number"||typeof r.height!="number"||r.height<=0||!t.clips)return!1;const{clips:a}=t,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(t){return console.error("Theme validation error:",t),!1}}static deepClone(e){if(e===null||typeof e!="object")return e;if(e instanceof Array)return e.map(i=>this.deepClone(i));const t={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=this.deepClone(e[i]));return t}static deepMerge(e,t){const i={...e};for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const r=t[n],a=i[n];r!==void 0&&(typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof a=="object"&&a!==null&&!Array.isArray(a)?i[n]=this.deepMerge(a,r):i[n]=r)}return i}}class $o{timeline;constructor(e){this.timeline=e}getValidDropPosition(e,t,i,n){const r=this.timeline.getVisualTracks()[i];if(!r)return{validTime:e,wouldOverlap:!1};const a=this.getOtherClipBounds(r,n),o=e+t,l=a.find(p=>!(o<=p.start||e>=p.end));if(!l)return{validTime:e,wouldOverlap:!1};const c=l.start-t,h=l.end,d=Math.abs(e-c)<Math.abs(e-h)&&c>=0?c:h;return{validTime:this.getValidDropPosition(d,t,i,n).validTime,wouldOverlap:!0}}checkOverlap(e,t,i,n){const r=this.timeline.getVisualTracks()[i];if(!r)return!1;const a=this.getOtherClipBounds(r,n),o=e+t;return a.some(l=>!(o<=l.start||e>=l.end))}getOtherClipBounds(e,t){return e.getClips().map((i,n)=>({clip:i,index:n})).filter(({index:i})=>i!==t).map(({clip:i})=>{const n=i.getClipConfig();return n?{start:n.start||0,end:(n.start||0)+(n.length||0)}:null}).filter(i=>i!==null).sort((i,n)=>i.start-n.start)}findAvailableGaps(e,t){const i=this.timeline.getVisualTracks()[e];if(!i)return[];const n=this.getOtherClipBounds(i),r=[];n.length>0&&n[0].start>=t&&r.push({start:0,end:n[0].start});for(let a=0;a<n.length-1;a+=1)n[a+1].start-n[a].end>=t&&r.push({start:n[a].end,end:n[a+1].start});return r}}class $s{constructor(e,t,i,n){this.fromTrackIndex=e,this.fromClipIndex=t,this.toTrackIndex=i,this.newStart=n,this.originalTrackIndex=e,this.originalClipIndex=t}name="moveClip";player;originalTrackIndex;originalClipIndex;originalStart;execute(e){if(!e)return;const t=e.getTracks();if(this.fromTrackIndex<0||this.fromTrackIndex>=t.length){console.warn(`Invalid source track index: ${this.fromTrackIndex}`);return}const i=t[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>=t.length){console.warn(`Invalid destination track index: ${this.toTrackIndex}`);return}i.splice(this.fromClipIndex,1),this.player.layer=this.toTrackIndex+1;const n=t[this.toTrackIndex];let r=0;for(let a=0;a<n.length;a+=1){const o=n[a];if(o.clipConfiguration&&o.clipConfiguration.start!==void 0&&this.newStart<o.clipConfiguration.start)break;r+=1}n.splice(r,0,this.player),this.originalClipIndex=r}if(this.player.clipConfiguration.start=this.newStart,e.movePlayerToTrackContainer(this.player,this.fromTrackIndex,this.toTrackIndex),this.player.reconfigureAfterRestore(),this.player.draw(),e.updateDuration(),this.fromTrackIndex!==this.toTrackIndex){const n=t[this.fromTrackIndex],r=t[this.toTrackIndex];[...n,...r].forEach(a=>{a&&a!==this.player&&a.draw()})}e.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(e){if(!e||!this.player||this.originalStart===void 0)return;const t=e.getTracks();if(this.fromTrackIndex!==this.toTrackIndex){const i=t[this.toTrackIndex],n=i.indexOf(this.player);n!==-1&&i.splice(n,1),this.player.layer=this.fromTrackIndex+1,t[this.fromTrackIndex].splice(this.fromClipIndex,0,this.player)}this.player.clipConfiguration.start=this.originalStart,e.movePlayerToTrackContainer(this.player,this.toTrackIndex,this.fromTrackIndex),this.player.reconfigureAfterRestore(),this.player.draw(),e.updateDuration(),e.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 Zo{constructor(e,t,i,n){this.insertionIndex=e,this.fromTrackIndex=t,this.fromClipIndex=i,this.newStart=n,this.addTrackCommand=new es(e);const r=t>=e?t+1:t;this.moveClipCommand=new $s(r,i,e,n)}name="createTrackAndMoveClip";addTrackCommand;moveClipCommand;wasExecuted=!1;async execute(e){if(e)try{this.addTrackCommand.execute(e),this.moveClipCommand.execute(e),this.wasExecuted=!0}catch(t){if(this.wasExecuted)try{this.undo(e)}catch{}throw t}}undo(e){!e||!this.wasExecuted||(this.moveClipCommand.undo(e),this.addTrackCommand.undo(e),this.wasExecuted=!1,e.emitEvent("track:created:undone",{trackIndex:this.insertionIndex}))}}class Ko{timeline;thresholds;snapManager;collisionDetector;visualFeedback;dragInfo=null;currentDropZone=null;constructor(e,t,i,n,r){this.timeline=e,this.thresholds=t,this.snapManager=i,this.collisionDetector=n,this.visualFeedback=r}activate(){}deactivate(){this.endDrag()}canStartDrag(e,t){const i=Math.sqrt((t.x-e.x)**2+(t.y-e.y)**2),{trackHeight:n}=this.timeline.getLayout(),r=n<20?2:this.thresholds.drag.base;return i>r}startDrag(e,t){const i=this.timeline.getClipData(e.trackIndex,e.clipIndex);if(!i)return console.warn(`Clip data not found for track ${e.trackIndex}, clip ${e.clipIndex}`),!1;const n=this.timeline.getContainer().toLocal(t.global),r=this.timeline.getLayout(),a=r.getXAtTime(i.start||0),o=e.trackIndex*r.trackHeight;return this.dragInfo={trackIndex:e.trackIndex,clipIndex:e.clipIndex,startTime:i.start||0,offsetX:n.x-a,offsetY:n.y-o},this.timeline.getPixiApp().canvas.style.cursor="grabbing",this.timeline.getEdit().events.emit("drag:started",this.dragInfo),!0}updateDrag(e){if(!this.dragInfo)return;const t=this.calculateDragPosition(e),i=this.detectDropZone(t.y);i?this.handleDropZonePreview(i,t):this.handleNormalDragPreview(t),this.emitDragUpdate(t,i)}completeDrag(e){if(!this.dragInfo)return;const t={...this.dragInfo},i=this.calculateDragPosition(e),n=this.detectDropZone(i.y);this.endDrag(),n?this.executeDropZoneMove(n,t,i):this.executeNormalMove(t,i)}calculateDragPosition(e){if(!this.dragInfo)throw new Error("No drag info available");const t=this.timeline.getContainer().toLocal(e.global),i=this.timeline.getLayout(),n=Math.max(0,i.getTimeAtX(t.x-this.dragInfo.offsetX)),r=t.y-this.dragInfo.offsetY,a=r+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:t.x,y:t.y+i.viewportY,time:n,track:c,ghostY:r}}detectDropZone(e){const t=this.timeline.getLayout(),i=this.timeline.getVisualTracks(),n=t.trackHeight*this.thresholds.dropZone.ratio;for(let r=0;r<=i.length;r+=1){const a=t.tracksY+r*t.trackHeight;if(Math.abs(e-a)<n){let o;return r===0?o="above":r===i.length?o="below":o="between",{type:o,position:r}}}return null}handleDropZonePreview(e,t){(!this.currentDropZone||this.currentDropZone.type!==e.type||this.currentDropZone.position!==e.position)&&(this.currentDropZone=e,this.visualFeedback.showDropZone(e)),this.timeline.hideDragGhost(),this.visualFeedback.hideSnapGuidelines(),this.visualFeedback.hideTargetTrack()}handleNormalDragPreview(e){if(!this.dragInfo)return;this.currentDropZone&&(this.visualFeedback.hideDropZone(),this.currentDropZone=null);const t=this.timeline.getClipData(this.dragInfo.trackIndex,this.dragInfo.clipIndex);if(!t)return;const i=t.length||0,n=e.track===this.dragInfo.trackIndex?this.dragInfo.clipIndex:void 0,r=this.calculateFinalPosition(e.time,e.track,i,n),a=this.snapManager.findAlignedElements(r,i,e.track,n);a.length>0?this.visualFeedback.showSnapGuidelines(a):this.visualFeedback.hideSnapGuidelines(),this.visualFeedback.showTargetTrack(e.track),this.timeline.showDragGhost(e.track,r,e.ghostY)}calculateFinalPosition(e,t,i,n){const r=this.snapManager.calculateSnapPosition(e,t,i,n);return this.collisionDetector.getValidDropPosition(r.time,i,t,n).validTime}emitDragUpdate(e,t){if(!this.dragInfo)return;const i=this.timeline.getClipData(this.dragInfo.trackIndex,this.dragInfo.clipIndex);if(!i)return;const n=i.length||0,r=t?e.time:this.calculateFinalPosition(e.time,e.track,n,e.track===this.dragInfo.trackIndex?this.dragInfo.clipIndex:void 0);this.timeline.getEdit().events.emit("drag:moved",{...this.dragInfo,currentTime:r,currentTrack:t?-1:e.track})}executeDropZoneMove(e,t,i){const n=new Zo(e.position,t.trackIndex,t.clipIndex,i.time);this.timeline.getEdit().executeEditCommand(n)}executeNormalMove(e,t){const i=this.timeline.getClipData(e.trackIndex,e.clipIndex);if(!i)return;const n=i.length||0,r=t.track===e.trackIndex?e.clipIndex:void 0,a=this.calculateFinalPosition(t.time,t.track,n,r);if(t.track!==e.trackIndex||Math.abs(a-e.startTime)>.01){const l=new $s(e.trackIndex,e.clipIndex,t.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 jo{constructor(e,t,i){this.trackIndex=e,this.clipIndex=t,this.newLength=i}name="resizeClip";originalLength;player;execute(e){if(!e)return;const t=e.getTrack(this.trackIndex);if(!t){console.warn(`Invalid track index: ${this.trackIndex}`);return}if(this.clipIndex<0||this.clipIndex>=t.length){console.warn(`Invalid clip index: ${this.clipIndex} for track ${this.trackIndex}`);return}this.player=t[this.clipIndex],this.originalLength=this.player.clipConfiguration.length,this.player.clipConfiguration.length=this.newLength,this.player.reconfigureAfterRestore(),this.player.draw(),e.updateDuration(),e.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(e){!e||!this.player||this.originalLength===void 0||(this.player.clipConfiguration.length=this.originalLength,this.player.reconfigureAfterRestore(),this.player.draw(),e.updateDuration(),e.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 Xo{timeline;thresholds;resizeInfo=null;constructor(e,t){this.timeline=e,this.thresholds=t}activate(){}deactivate(){this.endResize()}isOnClipRightEdge(e,t){const i=this.timeline.getVisualTracks()[e.trackIndex];if(!i)return!1;const n=i.getClip(e.clipIndex);if(!n)return!1;const a=n.getContainer().getBounds(),o=a.x+a.width,l=Math.abs(t.global.x-o),c=this.getResizeThreshold();return l<=c}startResize(e,t){const i=this.timeline.getClipData(e.trackIndex,e.clipIndex);if(!i)return!1;this.resizeInfo={trackIndex:e.trackIndex,clipIndex:e.clipIndex,originalLength:i.length||0,startX:t.global.x},this.timeline.getPixiApp().canvas.style.cursor="ew-resize";const n=this.timeline.getVisualTracks()[e.trackIndex];if(n){const r=n.getClip(e.clipIndex);r&&r.setResizing(!0)}return this.timeline.getEdit().events.emit("resize:started",this.resizeInfo),!0}updateResize(e){if(!this.resizeInfo)return;const t=e.global.x-this.resizeInfo.startX,i=this.timeline.getOptions().pixelsPerSecond||50,n=t/i,r=Math.max(.1,this.resizeInfo.originalLength+n),a=this.timeline.getVisualTracks()[this.resizeInfo.trackIndex];if(a){const o=a.getClip(this.resizeInfo.clipIndex);if(o){const l=r*i;o.setPreviewWidth(l),this.timeline.getEdit().events.emit("resize:updated",{width:l})}}}completeResize(e){if(!this.resizeInfo)return;const t=e.global.x-this.resizeInfo.startX,i=this.timeline.getOptions().pixelsPerSecond||50,n=t/i,r=Math.max(.1,this.resizeInfo.originalLength+n),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(r-this.resizeInfo.originalLength)>.01){const o=new jo(this.resizeInfo.trackIndex,this.resizeInfo.clipIndex,r);this.timeline.getEdit().executeEditCommand(o),this.timeline.getEdit().events.emit("resize:ended",{newLength:r})}this.endResize()}getCursorForPosition(e,t){return e&&this.isOnClipRightEdge(e,t)?"ew-resize":""}getResizeThreshold(){const{trackHeight:e}=this.timeline.getLayout();return Math.max(this.thresholds.resize.min,Math.min(this.thresholds.resize.max,e*this.thresholds.resize.ratio))}endResize(){this.resizeInfo=null,this.timeline.getPixiApp().canvas.style.cursor="default"}getResizeInfo(){return this.resizeInfo}dispose(){this.endResize()}}class Yo{timeline;thresholds;constructor(e,t){this.timeline=e,this.thresholds=t}getAllSnapPoints(e,t){const i=[];this.timeline.getVisualTracks().forEach((a,o)=>{a.getClips().forEach((c,h)=>{if(o===e&&h===t)return;const d=c.getClipConfig();d&&(i.push({time:d.start||0,type:"clip-start",trackIndex:o,clipIndex:h}),i.push({time:(d.start||0)+(d.length||0),type:"clip-end",trackIndex:o,clipIndex:h}))})});const r=this.timeline.getPlayheadTime();return i.push({time:r,type:"playhead"}),i}getTrackSnapPoints(e,t){return this.getAllSnapPoints(e,t).filter(i=>i.trackIndex===void 0||i.trackIndex===e)}calculateSnapPosition(e,t,i,n){const r=this.timeline.getOptions().pixelsPerSecond||50,a=this.thresholds.snap.pixels/r,o=this.getTrackSnapPoints(t,n);let l=null;for(const c of o){const h=Math.abs(e-c.time);h<a&&(!l||h<l.distance)&&(l={time:c.time,type:c.type,distance:h});const d=Math.abs(e+i-c.time);d<a&&(!l||d<l.distance)&&(l={time:c.time-i,type:c.type,distance:d})}return l?{time:l.time,snapped:!0,snapType:l.type}:{time:e,snapped:!1}}findAlignedElements(e,t,i,n){const a=e+t,o=new Map;this.timeline.getVisualTracks().forEach((c,h)=>{c.getClips().forEach((d,u)=>{if(h===i&&u===n)return;const p=d.getClipConfig();if(!p)return;const g=p.start||0,b=g+(p.length||0);[{time:g,aligns:[e,a]},{time:b,aligns:[e,a]}].forEach(({time:_,aligns:B})=>{B.some(N=>Math.abs(N-_)<.1)&&(o.has(_)||o.set(_,{tracks:new Set,isPlayhead:!1}),o.get(_).tracks.add(h))})})});const l=this.timeline.getPlayheadTime();return(Math.abs(e-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 qo{timeline;graphics=new Map;constructor(e){this.timeline=e}showDropZone(e){this.hideDropZone();const t=new f.Graphics,i=this.timeline.getLayout(),n=this.timeline.getExtendedTimelineWidth(),r=e.position*i.trackHeight,o=this.timeline.getTheme().timeline.trackInsertion;t.setStrokeStyle({width:4,color:o,alpha:.8}),t.moveTo(0,r),t.lineTo(n,r),t.stroke(),t.setStrokeStyle({width:8,color:o,alpha:.3}),t.moveTo(0,r),t.lineTo(n,r),t.stroke(),this.timeline.getContainer().addChild(t),this.graphics.set("dropZone",t)}hideDropZone(){this.hideGraphics("dropZone")}showSnapGuidelines(e){this.hideSnapGuidelines();const t=new f.Graphics,i=this.timeline.getLayout(),n=this.timeline.getTheme();e.forEach(({time:r,tracks:a,isPlayhead:o})=>{const l=i.getXAtTime(r),c=Math.min(...a),h=Math.max(...a),d=c*i.trackHeight,u=(h+1)*i.trackHeight,p=o?n.timeline.playhead:n.timeline.snapGuide;t.setStrokeStyle({width:3,color:p,alpha:.3}),t.moveTo(l,d),t.lineTo(l,u),t.stroke(),t.setStrokeStyle({width:1,color:p,alpha:.8}),t.moveTo(l,d),t.lineTo(l,u),t.stroke()}),this.timeline.getContainer().addChild(t),this.graphics.set("snapGuidelines",t)}hideSnapGuidelines(){this.hideGraphics("snapGuidelines")}showTargetTrack(e){this.hideTargetTrack();const t=new f.Graphics,i=this.timeline.getLayout(),n=this.timeline.getExtendedTimelineWidth(),r=e*i.trackHeight,a=i.trackHeight,l=this.timeline.getTheme().timeline.dropZone;t.rect(0,r,n,a),t.fill({color:l,alpha:.1}),t.setStrokeStyle({width:1,color:l,alpha:.3}),t.rect(0,r,n,a),t.stroke(),this.timeline.getContainer().addChild(t),this.graphics.set("targetTrack",t)}hideTargetTrack(){this.hideGraphics("targetTrack")}hideAll(){this.graphics.forEach((e,t)=>this.hideGraphics(t))}hideGraphics(e){const t=this.graphics.get(e);t&&(t.clear(),t.parent&&t.parent.removeChild(t),t.destroy(),this.graphics.delete(e))}dispose(){this.hideAll(),this.graphics.clear()}}class Qo{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(e,t){if(this.timeline=e,t){const i=structuredClone(this.thresholds);t.drag&&Object.assign(i.drag,t.drag),t.resize&&Object.assign(i.resize,t.resize),t.dropZone&&Object.assign(i.dropZone,t.dropZone),t.snap&&Object.assign(i.snap,t.snap),this.thresholds=i}this.snapManager=new Yo(e,this.thresholds),this.collisionDetector=new $o(e),this.visualFeedback=new qo(e),this.dragHandler=new Ko(e,this.thresholds,this.snapManager,this.collisionDetector,this.visualFeedback),this.resizeHandler=new Xo(e,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 e=this.timeline.getPixiApp();e.stage.interactive=!0,e.stage.on("pointerdown",this.handlePointerDown.bind(this),{signal:this.abortController?.signal}),e.stage.on("pointermove",this.handlePointerMove.bind(this),{signal:this.abortController?.signal}),e.stage.on("pointerup",this.handlePointerUp.bind(this),{signal:this.abortController?.signal}),e.stage.on("pointerupoutside",this.handlePointerUp.bind(this),{signal:this.abortController?.signal})}handlePointerDown(e){const t=e.target;if(t.label){const i=this.parseClipLabel(t.label);if(i){if(this.resizeHandler.isOnClipRightEdge(i,e)){if(this.resizeHandler.startResize(i,e)){const n=this.resizeHandler.getResizeInfo();n&&(this.state={type:"resizing",resizeInfo:n})}return}this.state={type:"selecting",startPos:{x:e.global.x,y:e.global.y},clipInfo:i},this.timeline.getPixiApp().canvas.style.cursor="grab";return}}this.timeline.getEdit().clearSelection()}handlePointerMove(e){switch(this.state.type){case"selecting":this.handleSelectingMove(e);break;case"dragging":this.timeline.getPixiApp().canvas.style.cursor="grabbing",this.dragHandler.updateDrag(e);break;case"resizing":this.timeline.getPixiApp().canvas.style.cursor="ew-resize",this.resizeHandler.updateResize(e);break;case"idle":this.updateCursorForPosition(e);break}}handlePointerUp(e){switch(this.state.type){case"selecting":this.timeline.getEdit().selectClip(this.state.clipInfo.trackIndex,this.state.clipInfo.clipIndex);break;case"dragging":this.dragHandler.completeDrag(e);break;case"resizing":this.resizeHandler.completeResize(e);break}this.resetState()}handleSelectingMove(e){if(this.state.type!=="selecting")return;const t={x:e.global.x,y:e.global.y};if(this.dragHandler.canStartDrag(this.state.startPos,t)&&this.dragHandler.startDrag(this.state.clipInfo,e)){const i=this.dragHandler.getDragInfo();i&&(this.state={type:"dragging",dragInfo:i})}}updateCursorForPosition(e){const t=e.target;if(t.label){const i=this.parseClipLabel(t.label);if(i){const n=this.resizeHandler.getCursorForPosition(i,e);if(n){this.timeline.getPixiApp().canvas.style.cursor=n;return}this.timeline.getPixiApp().canvas.style.cursor="grab";return}}this.timeline.getPixiApp().canvas.style.cursor="default"}parseClipLabel(e){if(!e?.startsWith("clip-"))return null;const t=e.split("-");if(t.length!==3)return null;const i=parseInt(t[1],10),n=parseInt(t[2],10);return Number.isNaN(i)||Number.isNaN(n)?null:{trackIndex:i,clipIndex:n}}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 Jo{constructor(e,t,i,n,r){this.container=e,this.layout=t,this.getPixelsPerSecond=i,this.getTrackHeight=n,this.getVisualTracks=r}dragPreviewContainer=null;dragPreviewGraphics=null;draggedClipInfo=null;showDragPreview(e,t,i){if(!i)return;this.draggedClipInfo={trackIndex:e,clipIndex:t,clipConfig:i},this.dragPreviewContainer=new f.Container,this.dragPreviewGraphics=new f.Graphics,this.dragPreviewContainer.addChild(this.dragPreviewGraphics),this.container.addChild(this.dragPreviewContainer),this.getVisualTracks()[e]?.getClip(t)?.setDragging(!0),this.drawDragPreview(e,i.start||0)}drawDragPreview(e,t){if(!this.dragPreviewContainer||!this.dragPreviewGraphics||!this.draggedClipInfo)return;const{clipConfig:i}=this.draggedClipInfo,n=this.layout.getXAtTime(t),r=e*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(n,r)}drawDragPreviewAtPosition(e,t,i){if(!this.dragPreviewContainer||!this.dragPreviewGraphics||!this.draggedClipInfo)return;const{clipConfig:n}=this.draggedClipInfo,r=this.layout.getXAtTime(e),a=(n.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(t-l)<5?65280:16755200;this.dragPreviewGraphics.stroke({width:2,color:h}),this.dragPreviewContainer.position.set(r,t)}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(e,t,i){!this.dragPreviewContainer||!this.draggedClipInfo||(this.dragPreviewContainer.visible=!0,i!==void 0?this.drawDragPreviewAtPosition(t,i,e):this.drawDragPreview(e,t))}getDraggedClipInfo(){return this.draggedClipInfo}hasActivePreview(){return this.dragPreviewContainer!==null}dispose(){this.hideDragPreview()}}class ec{constructor(e,t,i,n,r){this.layout=e,this.trackLayer=t,this.overlayLayer=i,this.entityContainer=n,this.onRender=r}scrollX=0;scrollY=0;zoomLevel=1;viewport;rulerViewport;playheadContainer;async setupViewport(){this.rulerViewport=new f.Container,this.rulerViewport.label="ruler-viewport",this.overlayLayer.addChild(this.rulerViewport),this.playheadContainer=new f.Container,this.playheadContainer.label="playhead-container",this.overlayLayer.addChild(this.playheadContainer),this.viewport=new f.Container,this.viewport.label="viewport",this.trackLayer.addChild(this.viewport),this.viewport.addChild(this.entityContainer)}updateViewportTransform(){const e=this.layout.calculateViewportPosition(this.scrollX,this.scrollY);this.viewport.position.set(e.x,e.y),this.viewport.scale.set(this.zoomLevel,this.zoomLevel),this.rulerViewport.position.x=e.x,this.rulerViewport.scale.x=this.zoomLevel,this.playheadContainer.position.x=e.x,this.playheadContainer.scale.x=this.zoomLevel}setScroll(e,t){this.scrollX=e,this.scrollY=t,this.updateViewportTransform(),this.onRender()}setZoom(e){this.zoomLevel=Math.max(.1,Math.min(10,e)),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 te={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},xt={PADDING:2,LABEL_PADDING:8,DEFAULT_OPACITY:.8,BORDER_WIDTH:1},ne={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 Yt(s){const e=s.split("/");return e[e.length-1]||s}function tc(s){switch(s.type){case"video":return s.src?Yt(s.src):"Video";case"audio":return s.src?Yt(s.src):"Audio";case"image":return s.src?Yt(s.src):"Image";case"text":return s.text||"Text";case"shape":return s.shape||"Shape";case"html":return"HTML";case"luma":return s.src?Yt(s.src):"Luma";default:return"Unknown Asset"}}class ic extends be{clipConfig;options;graphics;background;text;selectionRenderer;lastGlobalX=-1;lastGlobalY=-1;visualState={mode:"normal"};CLIP_PADDING=te.PADDING;BORDER_WIDTH=te.BORDER_WIDTH;get CORNER_RADIUS(){return this.options.theme.timeline.clips.radius||te.CORNER_RADIUS}constructor(e,t){super(),this.clipConfig=e,this.options=t,this.selectionRenderer=t.selectionRenderer,this.graphics=new f.Graphics,this.background=new f.Graphics,this.text=new f.Text,this.setupContainer()}async load(){this.setupGraphics(),this.updateVisualState()}setupContainer(){const e=this.getContainer();e.label=`clip-${this.options.trackIndex}-${this.options.clipIndex}`,e.interactive=!0,e.cursor="pointer",e.addChild(this.background),e.addChild(this.graphics),e.addChild(this.text)}setupGraphics(){this.text.style=new f.TextStyle({fontSize:te.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(e){this.clipConfig=e,this.updateVisualState()}updateVisualState(){this.updatePosition(),this.updateAppearance(),this.updateSize(),this.updateText()}setVisualState(e){this.visualState={...this.visualState,...e},this.updateVisualState()}updatePosition(){const e=this.getContainer(),t=this.clipConfig.start||0;e.x=t*this.options.pixelsPerSecond,e.y=0}updateSize(){const e=this.getEffectiveWidth(),t=this.options.trackHeight;this.drawClipBackground(e,t),this.drawClipBorder(e,t)}getEffectiveWidth(){if(this.visualState.previewWidth!==void 0)return this.visualState.previewWidth;const t=(this.clipConfig.length||0)*this.options.pixelsPerSecond;return Math.max(te.MIN_WIDTH,t)}drawClipBackground(e,t){const i=this.getClipColor(),n=this.getStateStyles();this.background.clear(),this.background.roundRect(0,0,e,t,this.CORNER_RADIUS),this.background.fill({color:i,alpha:n.alpha})}drawClipBorder(e,t){const i=this.getStateStyles(),n=this.BORDER_WIDTH;this.graphics.clear(),this.graphics.roundRect(0,0,e,t,this.CORNER_RADIUS),this.graphics.stroke({width:n,color:i.borderColor}),this.updateSelectionState(e,t)}updateSelectionState(e,t){if(!this.selectionRenderer)return;const i=this.visualState.mode==="selected",n=this.getClipId();if(!i){this.selectionRenderer.clearSelection(n);return}const a=this.getContainer().toGlobal(new f.Point(0,0)),l=this.selectionRenderer.getOverlay().toLocal(a);this.selectionRenderer.renderSelection(n,{x:l.x,y:l.y,width:e,height:t,cornerRadius:this.CORNER_RADIUS,borderWidth:this.BORDER_WIDTH},i)}getClipColor(){const e=this.clipConfig.asset?.type,t=this.options.theme.timeline.clips;switch(e){case"video":return t.video;case"audio":return t.audio;case"image":return t.image;case"text":return t.text;case"shape":return t.shape;case"html":return t.html;case"luma":return t.luma;default:return t.default}}updateAppearance(){const e=this.getContainer();e.alpha=this.visualState.mode==="dragging"?te.DRAG_OPACITY:te.DEFAULT_ALPHA}updateText(){const e=this.clipConfig.asset?tc(this.clipConfig.asset):"Clip";this.text.text=e;const i=(this.clipConfig.length||0)*this.options.pixelsPerSecond-this.CLIP_PADDING*2;if(this.text.width>i){const n=i/this.text.width,r=Math.floor(e.length*n)-te.TEXT_TRUNCATE_SUFFIX_LENGTH;this.text.text=`${e.substring(0,Math.max(1,r))}...`}}getStateStyles(){const{theme:e}=this.options;switch(this.visualState.mode){case"dragging":return{alpha:te.DRAG_OPACITY,borderColor:e.timeline.tracks.border};case"resizing":return{alpha:te.RESIZE_OPACITY,borderColor:e.timeline.dropZone};case"selected":return{alpha:te.DEFAULT_ALPHA,borderColor:e.timeline.clips.selected};default:return{alpha:te.DEFAULT_ALPHA,borderColor:e.timeline.tracks.border}}}setSelected(e){this.setVisualState({mode:e?"selected":"normal"})}setDragging(e){this.setVisualState({mode:e?"dragging":"normal"})}setResizing(e){this.setVisualState({mode:e?"resizing":"normal",...e?{}:{previewWidth:void 0}})}setPreviewWidth(e){this.setVisualState({previewWidth:e||void 0})}setPixelsPerSecond(e){if(this.updateOptions({pixelsPerSecond:e}),this.visualState.mode==="selected"){const t=this.getEffectiveWidth(),i=this.options.trackHeight;this.updateSelectionState(t,i)}}updateOptions(e){this.options={...this.options,...e},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 e=this.getEffectiveWidth();return(this.clipConfig.start||0)*this.options.pixelsPerSecond+e}update(e,t){if(this.visualState.mode==="selected"&&this.selectionRenderer){const n=this.getContainer().toGlobal(new f.Point(0,0));if(n.x!==this.lastGlobalX||n.y!==this.lastGlobalY){this.lastGlobalX=n.x,this.lastGlobalY=n.y;const r=this.getEffectiveWidth(),a=this.options.trackHeight;this.updateSelectionState(r,a)}}}draw(){}dispose(){this.selectionRenderer&&this.selectionRenderer.clearSelection(this.getClipId()),this.background.destroy(),this.graphics.destroy(),this.text.destroy()}}class sc extends be{clips=[];options;background;TRACK_PADDING=xt.PADDING;LABEL_PADDING=xt.LABEL_PADDING;constructor(e){super(),this.options=e,this.background=new f.Graphics,this.setupContainer()}async load(){this.updateTrackAppearance()}setupContainer(){const e=this.getContainer();e.label=`track-${this.options.trackIndex}`,e.addChild(this.background),e.y=this.options.trackIndex*this.options.trackHeight}updateTrackAppearance(){const{width:e}=this.options,t=this.options.trackHeight,{theme:i}=this.options;this.background.clear();const n=this.options.trackIndex%2===0?i.timeline.tracks.surface:i.timeline.tracks.surfaceAlt;this.background.rect(0,0,e,t),this.background.fill({color:n,alpha:xt.DEFAULT_OPACITY}),this.background.rect(0,0,e,t),this.background.stroke({width:xt.BORDER_WIDTH,color:i.timeline.tracks.border}),this.background.moveTo(0,t-1),this.background.lineTo(e,t-1),this.background.stroke({width:xt.BORDER_WIDTH,color:i.timeline.divider})}rebuildFromTrackData(e,t){this.options={...this.options,pixelsPerSecond:t},this.clearAllClips(),e.clips&&e.clips.forEach((i,n)=>{const r={pixelsPerSecond:this.options.pixelsPerSecond,trackHeight:this.options.trackHeight,trackIndex:this.options.trackIndex,clipIndex:n,theme:this.options.theme,selectionRenderer:this.options.selectionRenderer},a=new ic(i,r);this.addClip(a)}),this.updateTrackAppearance()}async addClip(e){this.clips.push(e),await e.load(),this.getContainer().addChild(e.getContainer())}clearAllClips(){const e=this.getContainer();for(const t of this.clips)e.removeChild(t.getContainer()),t.dispose();this.clips=[]}removeClip(e){if(e>=0&&e<this.clips.length){const t=this.clips[e];this.getContainer().removeChild(t.getContainer()),t.dispose(),this.clips.splice(e,1)}}updateClip(e,t){e>=0&&e<this.clips.length&&this.clips[e].updateFromConfig(t)}setPixelsPerSecond(e){this.options={...this.options,pixelsPerSecond:e},this.clips.forEach(t=>{t.setPixelsPerSecond(e)})}setWidth(e){this.options={...this.options,width:e},this.updateTrackAppearance()}setTrackIndex(e){this.options={...this.options,trackIndex:e};const t=this.getContainer();t.y=e*this.options.trackHeight,this.clips.forEach((i,n)=>{i.updateOptions({trackIndex:e})})}selectClip(e){this.clearAllSelections(),e>=0&&e<this.clips.length&&this.clips[e].setSelected(!0)}clearAllSelections(){this.clips.forEach(e=>{e.setSelected(!1)})}getSelectedClip(){return this.clips.find(e=>e.getSelected())||null}getSelectedClipIndex(){return this.clips.findIndex(e=>e.getSelected())}getClips(){return[...this.clips]}getClip(e){return this.clips[e]||null}getClipCount(){return this.clips.length}getTrackIndex(){return this.options.trackIndex}getTrackHeight(){return this.options.trackHeight}getOptions(){return{...this.options}}findClipAtPosition(e,t){if(t<0||t>this.options.trackHeight)return null;const i=e/this.options.pixelsPerSecond;for(let n=0;n<this.clips.length;n+=1){const r=this.clips[n],a=r.getClipConfig(),o=a.start||0,l=o+(a.length||0);if(i>=o&&i<=l)return{clip:r,clipIndex:n}}return null}update(e,t){this.clips.forEach(i=>{i.update(e,t)})}draw(){this.clips.forEach(e=>{e.draw()})}dispose(){this.clearAllClips(),this.background.destroy()}}class nc{constructor(e,t){this.overlay=e,this.theme=t}selectionGraphics=new Map;renderSelection(e,t,i){if(!i){this.clearSelection(e);return}let n=this.selectionGraphics.get(e);n||(n=new f.Graphics,n.label=`selection-border-${e}`,this.selectionGraphics.set(e,n),this.overlay.addChild(n)),n.position.set(t.x,t.y),n.clear(),n.setStrokeStyle({width:t.borderWidth*te.SELECTED_BORDER_MULTIPLIER,color:this.theme.timeline.clips.selected}),n.roundRect(0,0,t.width,t.height,t.cornerRadius),n.stroke()}clearSelection(e){const t=this.selectionGraphics.get(e);t&&(this.overlay.removeChild(t),t.destroy(),this.selectionGraphics.delete(e))}clearAllSelections(){this.selectionGraphics.forEach((e,t)=>{this.clearSelection(t)})}updateTheme(e){this.theme=e,this.selectionGraphics.forEach(t=>{t.clear()})}getOverlay(){return this.overlay}dispose(){this.clearAllSelections()}}class rc{constructor(e,t,i,n,r){this.container=e,this.layout=t,this.theme=i,this.getPixelsPerSecond=n,this.getExtendedTimelineWidth=r,this.selectionOverlay=new f.Container,this.selectionOverlay.label="selectionOverlay",this.container.addChild(this.selectionOverlay),this.selectionRenderer=new nc(this.selectionOverlay,this.theme)}visualTracks=[];selectionOverlay;selectionRenderer;async rebuildFromEdit(e,t){if(e?.timeline?.tracks){this.clearAllVisualState();for(let i=0;i<e.timeline.tracks.length;i+=1){const n=e.timeline.tracks[i],r={pixelsPerSecond:t,trackHeight:this.layout.trackHeight,trackIndex:i,width:this.getExtendedTimelineWidth(),theme:this.theme,selectionRenderer:this.selectionRenderer},a=new sc(r);await a.load(),a.rebuildFromTrackData(n,t),this.container.addChild(a.getContainer()),this.visualTracks.push(a)}this.container.setChildIndex(this.selectionOverlay,this.container.children.length-1)}}clearAllVisualState(){this.visualTracks.forEach(e=>{this.container.removeChild(e.getContainer()),e.dispose()}),this.visualTracks=[],this.selectionRenderer.clearAllSelections()}updateVisualSelection(e,t){this.clearVisualSelection();const i=this.visualTracks[e];if(i){const n=i.getClip(t);n&&n.setSelected(!0)}}clearVisualSelection(){this.visualTracks.forEach(e=>{e.getClips().forEach(i=>{i.setSelected(!1)})})}findClipAtPosition(e,t){const i=Math.floor(t/this.layout.trackHeight);if(i<0||i>=this.visualTracks.length)return null;const n=this.visualTracks[i],r=t-i*this.layout.trackHeight,a=n.findClipAtPosition(e,r);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(e){this.visualTracks.forEach(t=>{t.setWidth(e)})}getVisualTracks(){return this.visualTracks}updatePixelsPerSecond(e){this.visualTracks.forEach(t=>{t.setPixelsPerSecond(e)})}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 ac{constructor(e,t){this.edit=e,this.callbacks=t}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(e){await this.callbacks.onEditChange(e.current)}async handleClipUpdated(){await this.callbacks.onEditChange()}handleClipSelected(e){this.callbacks.onClipSelected(e.trackIndex,e.clipIndex)}handleSelectionCleared(){this.callbacks.onSelectionCleared()}handleDragStarted(e){this.callbacks.onDragStarted(e.trackIndex,e.clipIndex)}handleDragEnded(){this.callbacks.onDragEnded()}async handleTrackCreated(){await this.callbacks.onEditChange()}handleSeek(e){this.callbacks.onSeek(e.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 oc{constructor(e,t){this.options=e,this.onUpdate=t}app;trackLayer;overlayLayer;animationFrameId=null;async initializePixiApp(){this.app=new f.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 e=document.querySelector("[data-shotstack-timeline]");if(!e)throw new Error("Timeline container element [data-shotstack-timeline] not found");e.appendChild(this.app.canvas)}async setupRenderLayers(){this.trackLayer=new f.Container,this.overlayLayer=new f.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 e=performance.now();const t=i=>{const n=i-e;e=i;const r=n/16.667;this.onUpdate(r,n),this.draw(),this.animationFrameId=requestAnimationFrame(t)};this.animationFrameId=requestAnimationFrame(t)}draw(){this.app.render()}render(){this.app.render()}updateBackgroundColor(e){this.app&&(this.app.renderer.background.color=e)}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 nt={RULER:{DEFAULT_HEIGHT:40,LABEL_FONT_SIZE:10,LABEL_PADDING_X:2},PLAYHEAD:{LINE_WIDTH:2},SCROLL:{HORIZONTAL_SPEED:2,VERTICAL_SPEED:.5}};class Zs extends be{events;rulerContainer;rulerBackground;timeMarkers;timeLabels;pixelsPerSecond;timelineDuration;rulerHeight;theme;constructor(e){super(),this.events=new pt,this.pixelsPerSecond=e.pixelsPerSecond,this.timelineDuration=e.timelineDuration,this.rulerHeight=e.rulerHeight??nt.RULER.DEFAULT_HEIGHT,this.theme=e.theme,this.rulerContainer=new f.Container,this.rulerBackground=new f.Graphics,this.timeMarkers=new f.Graphics,this.timeLabels=new f.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 e=this.calculateRulerWidth(),t=this.theme?.timeline.ruler.background||4210752,i=this.theme?.timeline.tracks.border||6316128;this.rulerBackground.rect(0,0,e,this.rulerHeight),this.rulerBackground.fill(t),this.rulerBackground.rect(0,this.rulerHeight-1,e,1),this.rulerBackground.fill(i)}drawTimeMarkers(){this.timeMarkers.clear();const e=this.getTimeInterval(),t=this.getVisibleDuration(),i=this.theme?.timeline.ruler.markers||6710886,n=this.rulerHeight*.5;let r=4;e===10?r=9:(e===30||e===60)&&(r=5);const a=e/(r+1);for(let o=0;o<=t;o+=e)for(let l=1;l<=r;l+=1){const c=o+l*a;if(c<=t){const h=c*this.pixelsPerSecond;this.timeMarkers.circle(h,n,1.5),this.timeMarkers.fill(i)}}}drawTimeLabels(){this.timeLabels.removeChildren();const e=this.getTimeInterval(),t=this.getVisibleDuration(),i=this.theme?.timeline.ruler.text||16777215,n={fontSize:nt.RULER.LABEL_FONT_SIZE,fill:i,fontFamily:"Arial"};for(let r=0;r<=t;r+=e){const a=new f.Text({text:this.formatTime(r),style:n}),o=r*this.pixelsPerSecond;r===0?(a.anchor.set(0,.5),a.x=o+nt.RULER.LABEL_PADDING_X):(a.anchor.set(.5,.5),a.x=o),a.y=this.rulerHeight*.5,this.timeLabels.addChild(a)}}onRulerPointerDown(e){const t=this.rulerContainer.toLocal(e.global),i=Math.max(0,t.x/this.pixelsPerSecond);this.events.emit("ruler:seeked",{time:i})}updateRuler(e,t){this.pixelsPerSecond=e,this.timelineDuration=t,this.draw()}update(e,t){}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 e=this.timelineDuration*this.pixelsPerSecond;return Math.max(e,this.getViewportWidth())}getVisibleDuration(){return Math.max(this.timelineDuration,this.getViewportWidth()/this.pixelsPerSecond)}getTimeInterval(){const e=[1,5,10,30,60,120,300,600],t=80;for(const i of e)if(i*this.pixelsPerSecond>=t)return i;return Math.ceil(this.getVisibleDuration()/10)}formatTime(e){if(e===0)return"0s";const t=Math.floor(e/60),i=e%60;if(e<60)return`${e}s`;if(i===0)return`${t}m`;const n=i.toString().padStart(2,"0");return`${t}:${n}`}}class Ks extends be{constructor(e){super(),this.options=e,this.graphics=new f.Graphics}events=new pt;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 e=this.currentTime*this.options.pixelsPerSecond,t=this.options.theme?.timeline.playhead??16729156,i=nt.PLAYHEAD.LINE_WIDTH,n=e+i/2;this.graphics.clear(),this.graphics.fill(t),this.graphics.rect(e,0,i,this.options.timelineHeight);const r=8;this.graphics.moveTo(n,10),this.graphics.lineTo(n-r,0),this.graphics.lineTo(n+r,0),this.graphics.closePath(),this.graphics.fill()}onPointerDown(e){this.isDragging=!0,this.graphics.cursor="grabbing",this.updateTimeFromPointer(e)}onPointerMove(e){this.isDragging&&this.updateTimeFromPointer(e)}onPointerUp(){this.isDragging=!1,this.graphics.cursor="pointer"}updateTimeFromPointer(e){const t=this.graphics.parent.toLocal(e.global),i=Math.max(0,t.x/this.options.pixelsPerSecond);this.setTime(i),this.events.emit("playhead:seeked",{time:i})}setTime(e){this.currentTime=e,this.draw(),this.events.emit("playhead:timeChanged",{time:e})}getTime(){return this.currentTime}updatePlayhead(e,t){this.options.pixelsPerSecond=e,this.options.timelineHeight=t,this.draw()}update(){}draw(){this.drawPlayhead()}dispose(){this.graphics.removeAllListeners(),this.events.clear("*")}}class cc{events;timeline;abortController;scrollX=0;scrollY=0;constructor(e){this.events=new pt,this.timeline=e.timeline}async initialize(){this.setupEventListeners()}setupEventListeners(){this.abortController=new AbortController;const{canvas:e}=this.timeline.getPixiApp();e.addEventListener("wheel",this.handleWheel.bind(this),{passive:!1,signal:this.abortController.signal})}handleWheel(e){if(e.preventDefault(),e.ctrlKey||e.metaKey){this.handleZoom(e);return}this.handleScroll(e)}handleZoom(e){const t=e.deltaY>0?"out":"in",i=this.timeline.getPlayheadTime(),n=this.timeline.getActualEditDuration();t==="in"?this.timeline.zoomIn():this.timeline.zoomOut();const r=this.timeline.getOptions().pixelsPerSecond||50,a=i*r,o=this.timeline.getOptions().width||800,c=this.timeline.timeRange.endTime*r,h=n*r,d=this.calculateZoomScrollPosition({playheadXAfterZoom:a,viewportWidth:o,contentWidth:c,maxPlayheadX:h,actualEditDuration:n,playheadTime:i});this.scrollX=d,this.timeline.setScroll(this.scrollX,this.scrollY);const u=a-d;this.events.emit("zoom",{pixelsPerSecond:r,focusX:u,focusTime:i})}handleScroll(e){let{deltaX:t}=e,{deltaY:i}=e;e.shiftKey&&(t=i,i=0);const n=nt.SCROLL.HORIZONTAL_SPEED,r=nt.SCROLL.VERTICAL_SPEED;this.scrollX+=t*n,this.scrollY+=i*r,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(e,t){this.scrollX=this.clampScrollX(e),this.scrollY=this.clampScrollY(t),this.timeline.setScroll(this.scrollX,this.scrollY),this.events.emit("scroll",{x:this.scrollX,y:this.scrollY})}clampScrollX(e){const t=this.timeline.getExtendedTimelineWidth(),i=this.timeline.getOptions().width||0,n=Math.max(0,t-i);return Math.max(0,Math.min(e,n))}clampScrollY(e){const t=this.timeline.getLayout(),i=this.timeline.getVisualTracks().length,n=this.timeline.getOptions().height||0,r=Math.max(0,i*t.trackHeight-(n-t.rulerHeight));return Math.max(0,Math.min(e,r))}getScroll(){return{x:this.scrollX,y:this.scrollY}}calculateZoomScrollPosition(e){const{playheadXAfterZoom:t,viewportWidth:i,contentWidth:n,maxPlayheadX:r,actualEditDuration:a,playheadTime:o}=e,l=t-i/2,c=Math.max(0,n-i);let h;const d=l+i,u=Math.max(0,r-i);n<=i||l<0?h=0:d>r&&o<=a?h=Math.min(u,c):l>c?h=c:h=l;const p=t-h;return(p<0||p>i)&&(t>n-i?h=Math.max(0,t-i+50):h=Math.max(0,t-50),h=Math.max(0,Math.min(h,c))),h}dispose(){this.abortController&&(this.abortController.abort(),this.abortController=void 0),this.events.clear("*")}}const D={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 qt{static createIcon(e,t,i){const n=i?i/D.BUTTON_SIZE:1;switch(e){case"play":return this.createPlayIcon(t,n);case"pause":return this.createPauseIcon(t,n);case"frame-back":return this.createFrameBackIcon(t,n);case"frame-forward":return this.createFrameForwardIcon(t,n);default:throw new Error(`Unknown icon type: ${e}`)}}static createPlayIcon(e,t=1){const i=new f.Graphics,{PLAY:n}=D.ICON;return i.fill({color:e.timeline.toolbar.icon}),i.moveTo(n.LEFT*t,n.TOP*t),i.lineTo(n.RIGHT*t,n.MIDDLE*t),i.lineTo(n.LEFT*t,n.BOTTOM*t),i.closePath(),i.fill(),i}static createPauseIcon(e,t=1){const i=new f.Graphics,{PAUSE:n}=D.ICON;return i.fill({color:e.timeline.toolbar.icon}),i.rect(n.RECT1_X*t,n.TOP*t,n.WIDTH*t,n.HEIGHT*t),i.rect(n.RECT2_X*t,n.TOP*t,n.WIDTH*t,n.HEIGHT*t),i.fill(),i}static createFrameBackIcon(e,t=1){const i=new f.Graphics,{FRAME_STEP:n}=D.ICON;return i.fill({color:e.timeline.toolbar.icon}),i.moveTo(n.TRIANGLE1.BACK.LEFT*t,n.TOP*t),i.lineTo(n.TRIANGLE1.BACK.RIGHT*t,n.TRIANGLE1.BACK.MIDDLE*t),i.lineTo(n.TRIANGLE1.BACK.LEFT*t,n.BOTTOM*t),i.closePath(),i.moveTo(n.TRIANGLE2.BACK.LEFT*t,n.TOP*t),i.lineTo(n.TRIANGLE2.BACK.RIGHT*t,n.TRIANGLE2.BACK.MIDDLE*t),i.lineTo(n.TRIANGLE2.BACK.LEFT*t,n.BOTTOM*t),i.closePath(),i.fill(),i}static createFrameForwardIcon(e,t=1){const i=new f.Graphics,{FRAME_STEP:n}=D.ICON;return i.fill({color:e.timeline.toolbar.icon}),i.moveTo(n.TRIANGLE1.FORWARD.LEFT*t,n.TOP*t),i.lineTo(n.TRIANGLE1.FORWARD.RIGHT*t,n.TRIANGLE1.FORWARD.MIDDLE*t),i.lineTo(n.TRIANGLE1.FORWARD.LEFT*t,n.BOTTOM*t),i.closePath(),i.moveTo(n.TRIANGLE2.FORWARD.LEFT*t,n.TOP*t),i.lineTo(n.TRIANGLE2.FORWARD.RIGHT*t,n.TRIANGLE2.FORWARD.MIDDLE*t),i.lineTo(n.TRIANGLE2.FORWARD.LEFT*t,n.BOTTOM*t),i.closePath(),i.fill(),i}static updateIconColor(e,t){const i=e.getBounds();e.clear(),e.position.set(i.x,i.y)}}class js extends f.Container{background;hoverBackground;icon;alternateIcon;state={isHovering:!1,isPressed:!1,isActive:!1};size;theme;onClick;constructor(e){super(),this.size=e.size||D.BUTTON_SIZE,this.theme=e.theme,this.onClick=e.onClick,this.eventMode="static",this.cursor="pointer",this.background=new f.Graphics,this.addChild(this.background),this.hoverBackground=new f.Graphics,this.addChild(this.hoverBackground);const i=this.size*.6,n=(this.size-i)/2;e.iconType&&(this.icon=qt.createIcon(e.iconType,this.theme,i),this.icon.position.set(n,n),this.addChild(this.icon)),e.alternateIconType&&(this.alternateIcon=qt.createIcon(e.alternateIconType,this.theme,i),this.alternateIcon.position.set(n,n),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 e=D.BUTTON_HOVER_PADDING,t=this.size/2;this.background.clear(),this.background.circle(t,t,t),this.background.fill({color:this.theme.timeline.toolbar.surface,alpha:.8}),this.hoverBackground.clear(),this.hoverBackground.circle(t,t,t+e),this.state.isPressed?this.hoverBackground.fill({color:this.theme.timeline.toolbar.active,alpha:D.ACTIVE_ANIMATION_ALPHA}):this.state.isHovering?this.hoverBackground.fill({color:this.theme.timeline.toolbar.hover,alpha:D.HOVER_ANIMATION_ALPHA}):this.hoverBackground.fill({color:this.theme.timeline.toolbar.hover,alpha:0})}setActive(e){this.state.isActive=e,this.icon&&this.alternateIcon&&(this.icon.visible=!e,this.alternateIcon.visible=e)}updateTheme(e){this.theme=e;const i=this.size*.6,n=(this.size-i)/2;if(this.icon){const r=this.getIconType(this.icon);r&&(this.removeChild(this.icon),this.icon=qt.createIcon(r,e,i),this.icon.position.set(n,n),this.addChild(this.icon))}if(this.alternateIcon){const r=this.getIconType(this.alternateIcon);r&&(this.removeChild(this.alternateIcon),this.alternateIcon=qt.createIcon(r,e,i),this.alternateIcon.position.set(n,n),this.alternateIcon.visible=this.state.isActive,this.addChild(this.alternateIcon))}this.updateVisuals()}getIconType(e){return null}destroy(){this.removeAllListeners(),super.destroy()}}class lc extends f.Container{edit;theme;toolbarHeight;frameBackButton;playPauseButton;frameForwardButton;constructor(e,t,i){super(),this.edit=e,this.theme=t,this.toolbarHeight=i||36,this.createButtons(),this.subscribeToEditEvents(),this.updatePlayPauseState()}createButtons(){const e=this.calculateButtonSizes(),t=(e.playButton-e.regularButton)/2,i=(n,r,a,o)=>new js({iconType:n,onClick:r,tooltip:a,theme:this.theme,size:o});this.frameBackButton=i("frame-back",()=>this.handleFrameBack(),"Previous frame",e.regularButton),this.frameBackButton.position.set(0,t),this.playPauseButton=new js({iconType:"play",alternateIconType:"pause",onClick:()=>this.handlePlayPause(),tooltip:"Play/Pause",theme:this.theme,size:e.playButton}),this.playPauseButton.position.set(e.regularButton+e.spacing,0),this.frameForwardButton=i("frame-forward",()=>this.handleFrameForward(),"Next frame",e.regularButton),this.frameForwardButton.position.set(e.regularButton+e.spacing+e.playButton+e.spacing,t),this.addChild(this.frameBackButton,this.playPauseButton,this.frameForwardButton)}calculateButtonSizes(){const e=Math.round(this.toolbarHeight*.5);return{regularButton:e,playButton:Math.round(e*1.5),spacing:Math.round(this.toolbarHeight*.15)}}handleFrameBack(){this.edit.seek(this.edit.playbackTime-D.FRAME_TIME_MS)}handlePlayPause(){this.edit.isPlaying?this.edit.pause():this.edit.play()}handleFrameForward(){this.edit.seek(this.edit.playbackTime+D.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(e){}updateTheme(e){this.theme=e,this.frameBackButton.updateTheme(e),this.playPauseButton.updateTheme(e),this.frameForwardButton.updateTheme(e)}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 e=this.calculateButtonSizes();return e.regularButton*2+e.playButton+e.spacing*2}}class hc extends f.Container{edit;theme;timeText;formatOptions;constructor(e,t,i={}){super(),this.edit=e,this.theme=t,this.formatOptions={showMilliseconds:!1,showHours:!1,...i},this.createDisplay(),this.subscribeToEditEvents(),this.updateTimeDisplay()}createDisplay(){const e=new f.TextStyle({fontFamily:D.TIME_DISPLAY.FONT_FAMILY,fontSize:D.TIME_DISPLAY.FONT_SIZE,fill:this.theme.timeline.toolbar.text});this.timeText=new f.Text("0:00 / 0:00",e),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 e=this.formatTime(this.edit.playbackTime/1e3),t=this.formatTime(this.edit.getTotalDuration()/1e3);this.timeText.text=`${e} / ${t}`};formatTime(e){const t=Math.floor(e/3600),i=Math.floor(e%3600/60),n=Math.floor(e%60),r=Math.floor(e%1*10);let a="";return this.formatOptions.showHours||t>0?a+=`${t}:${i.toString().padStart(2,"0")}`:a+=`${i}`,a+=`:${n.toString().padStart(2,"0")}`,this.formatOptions.showMilliseconds?a+=`.${r}`:a+=`.${r}`,a}update(){this.updateTimeDisplay()}resize(e){}updateTheme(e){this.theme=e,this.timeText.style.fill=e.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 dc extends f.Container{edit;theme;cutButton;cutButtonBackground;cutButtonText;constructor(e,t){super(),this.edit=e,this.theme=t,this.createCutButton()}createCutButton(){this.cutButton=new f.Container,this.cutButton.eventMode="static",this.cutButton.cursor="pointer";const{WIDTH:e,HEIGHT:t,FONT_SIZE:i}=D.CUT_BUTTON;this.cutButtonBackground=new f.Graphics,this.cutButtonBackground.roundRect(0,0,e,t,D.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 n=new f.TextStyle({fontFamily:"Arial",fontSize:i,fill:this.theme.timeline.toolbar.text||16777215});this.cutButtonText=new f.Text("SPLIT",n),this.cutButtonText.anchor.set(.5),this.cutButtonText.position.set(e/2,t/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=e=>{e.stopPropagation(),this.performCutClip()};handlePointerDown=e=>{e.stopPropagation(),this.updateButtonVisual(!0,!1)};handlePointerOver=()=>{this.updateButtonVisual(!1,!0)};handlePointerOut=()=>{this.updateButtonVisual(!1,!1)};updateButtonVisual(e,t){this.cutButtonBackground.clear(),this.cutButtonBackground.roundRect(0,0,D.CUT_BUTTON.WIDTH,D.CUT_BUTTON.HEIGHT,D.BORDER_RADIUS);let i=this.theme.timeline.toolbar.surface||4473924;const n=1;e?i=this.theme.timeline.toolbar.active||3355443:t&&(i=this.theme.timeline.toolbar.hover||5592405),this.cutButtonBackground.fill({color:i,alpha:n}),this.cutButtonBackground.stroke({color:this.theme.timeline.tracks.border||6710886,width:1})}performCutClip(){const e=this.edit.getSelectedClipInfo();if(!e)return;const{trackIndex:t,clipIndex:i}=e,n=this.edit.playbackTime/1e3;this.edit.splitClip(t,i,n)}update(){const e=this.edit.getSelectedClipInfo()!==null;this.cutButton.alpha=e?1:.5,this.cutButton.eventMode=e?"static":"none",this.cutButton.cursor=e?"pointer":"default"}resize(e){}updateTheme(e){this.theme=e,this.updateButtonVisual(!1,!1),this.cutButtonText.style.fill=e.timeline.toolbar.text||16777215}destroy(){this.cutButton.removeAllListeners(),super.destroy()}getWidth(){return D.CUT_BUTTON.WIDTH}}class uc{config;constructor(e,t){this.config={width:e,height:t,buttonSize:Math.round(t*.5),buttonSpacing:Math.round(t*.15),edgeMargin:D.EDGE_MARGIN}}getPlaybackControlsPosition(){const e=this.calculatePlaybackControlsWidth(),t=(this.config.width-e)/2,i=(this.config.height-this.getMaxButtonHeight())/2;return{x:t,y:i}}getMaxButtonHeight(){const e=this.config.buttonSize;return Math.round(e*1.5)}getTimeDisplayPosition(e){const i=(this.config.width-e)/2+e+D.TEXT_SPACING,n=this.config.height/2;return{x:i,y:n}}getEditControlsPosition(){const e=this.config.width-D.CUT_BUTTON.WIDTH-this.config.edgeMargin,t=(this.config.height-D.CUT_BUTTON.HEIGHT)/2;return{x:e,y:t}}calculatePlaybackControlsWidth(){const e=this.config.buttonSize,t=Math.round(e*1.5);return e*2+t+this.config.buttonSpacing*2}updateWidth(e){this.config.width=e}getConfig(){return{...this.config}}}class pc extends f.Container{constructor(e,t,i,n){super(),this.edit=e,this.theme=t,this.layout=i,this.toolbarWidth=n,this.toolbarHeight=i.toolbarHeight,this.position.set(0,i.toolbarY),this.toolbarLayout=new uc(n,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 f.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:D.DIVIDER_ALPHA}),this.background.moveTo(0,this.toolbarHeight-.5),this.background.lineTo(this.toolbarWidth,this.toolbarHeight-.5),this.background.stroke()}createComponents(){this.playbackControls=new lc(this.edit,this.theme,this.toolbarHeight),this.addChild(this.playbackControls),this.timeDisplay=new hc(this.edit,this.theme),this.addChild(this.timeDisplay),this.editControls=new dc(this.edit,this.theme),this.addChild(this.editControls)}positionComponents(){const e=this.toolbarLayout.getPlaybackControlsPosition();this.playbackControls.position.set(e.x,e.y);const t=this.toolbarLayout.getTimeDisplayPosition(this.playbackControls.getWidth());this.timeDisplay.position.set(t.x,t.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(e){this.toolbarWidth=e,this.toolbarLayout.updateWidth(e),this.drawBackground(),this.positionComponents(),this.playbackControls.resize(e),this.timeDisplay.resize(e),this.editControls.resize(e)}updateTheme(e){this.theme=e,this.drawBackground(),this.playbackControls.updateTheme(e),this.timeDisplay.updateTheme(e),this.editControls.updateTheme(e)}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 fc{constructor(e,t,i,n,r,a){this.edit=e,this.layout=t,this.renderer=i,this.viewportManager=n,this.eventHandler=r,this.getTimelineContext=a}toolbar;ruler;playhead;scroll;async setupTimelineFeatures(e,t,i,n,r){this.toolbar=new pc(this.edit,e,this.layout,i),this.renderer.getStage().addChild(this.toolbar);const a={pixelsPerSecond:t,timelineDuration:r,rulerHeight:this.layout.rulerHeight,theme:e};this.ruler=new Zs(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:t,timelineHeight:n,theme:e};this.playhead=new Ks(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 cc(l),await this.scroll.initialize(),this.viewportManager.updateViewportTransform()}recreateTimelineFeatures(e,t,i,n){if(this.ruler){this.ruler.dispose();const{rulerHeight:r}=this.layout,a={pixelsPerSecond:t,timelineDuration:n,rulerHeight:r,theme:e};this.ruler=new Zs(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 r={pixelsPerSecond:t,timelineHeight:i,theme:e};this.playhead=new Ks(r),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(e,t){this.ruler.updateRuler(e,t)}updatePlayhead(e,t){this.playhead&&this.playhead.updatePlayhead(e,t)}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 Te{constructor(e,t){this.options=e,this.theme=t,this.config=this.calculateLayout()}static TOOLBAR_HEIGHT_RATIO=ne.TOOLBAR_HEIGHT_RATIO;static RULER_HEIGHT_RATIO=ne.RULER_HEIGHT_RATIO;static TOOLBAR_HEIGHT_DEFAULT=ne.TOOLBAR_HEIGHT_DEFAULT;static RULER_HEIGHT_DEFAULT=ne.RULER_HEIGHT_DEFAULT;static TRACK_HEIGHT_DEFAULT=ne.TRACK_HEIGHT_DEFAULT;static CLIP_PADDING=ne.CLIP_PADDING;static BORDER_WIDTH=ne.BORDER_WIDTH;static CORNER_RADIUS=ne.CORNER_RADIUS;static LABEL_PADDING=ne.LABEL_PADDING;static TRACK_PADDING=ne.TRACK_PADDING;config;calculateLayout(){const e=this.options.height;let t=this.theme?.timeline.toolbar.height||Math.round(e*Te.TOOLBAR_HEIGHT_RATIO),i=this.theme?.timeline.ruler.height||Math.round(e*Te.RULER_HEIGHT_RATIO);t=Math.max(t,Te.TOOLBAR_HEIGHT_DEFAULT),i=Math.max(i,Te.RULER_HEIGHT_DEFAULT);const{trackHeight:n}=this.options;return{toolbarHeight:t,rulerHeight:i,trackHeight:n,toolbarY:0,rulerY:t,tracksY:t+i,gridY:t+i,playheadY:t,viewportY:t+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(e){return e*this.trackHeight}positionClip(e){return e*this.options.pixelsPerSecond}calculateClipWidth(e){return Math.max(ne.MIN_CLIP_WIDTH,e*this.options.pixelsPerSecond)}calculateDropPosition(e,t){const i=t-this.tracksY,n=Math.floor(i/this.trackHeight),r=Math.max(0,e/this.options.pixelsPerSecond);return{track:Math.max(0,n),time:r,x:e,y:i}}getTrackAtY(e){const t=e-this.tracksY;return Math.floor(t/this.trackHeight)}getTimeAtX(e){return e/this.options.pixelsPerSecond}getXAtTime(e){return e*this.options.pixelsPerSecond}getYAtTrack(e){return this.tracksY+e*this.trackHeight}getGridHeight(){return this.options.height-this.toolbarHeight-this.rulerHeight}getRulerWidth(){return this.options.width}getGridWidth(){return this.options.width}calculateViewportPosition(e,t){return{x:-e,y:this.viewportY-t}}updateOptions(e,t){this.options=e,this.theme=t,this.config=this.calculateLayout()}isPointInToolbar(e,t){return t>=this.toolbarY&&t<=this.toolbarY+this.toolbarHeight}isPointInRuler(e,t){return t>=this.rulerY&&t<=this.rulerY+this.rulerHeight}isPointInTracks(e,t){return t>=this.tracksY&&t<=this.options.height}getVisibleTrackRange(e,t){const i=e,n=Math.floor(i/this.trackHeight),r=Math.ceil((i+t)/this.trackHeight);return{start:Math.max(0,n),end:Math.max(0,r)}}}class pe{constructor(e,t,i,n){this.layout=i,this.onResize=n,this.width=e.width,this.height=e.height,this.pixelsPerSecond=50;const r=t.timeline.tracks.height||Te.TRACK_HEIGHT_DEFAULT;this.trackHeight=Math.max(40,r),this.backgroundColor=t.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(e){e.width!==void 0&&(this.width=e.width,this.onResize&&this.onResize(this.width)),e.height!==void 0&&(this.height=e.height),e.pixelsPerSecond!==void 0&&(this.pixelsPerSecond=e.pixelsPerSecond),e.trackHeight!==void 0&&(this.trackHeight=e.trackHeight),e.backgroundColor!==void 0&&(this.backgroundColor=e.backgroundColor),e.antialias!==void 0&&(this.antialias=e.antialias),e.resolution!==void 0&&(this.resolution=e.resolution),this.layout.updateOptions(this.getOptions())}updateFromTheme(e){this.backgroundColor=e.timeline.background;const t=e.timeline.tracks.height||Te.TRACK_HEIGHT_DEFAULT;this.trackHeight=Math.max(40,t),this.layout.updateOptions(this.getOptions(),e)}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 e=Math.min(this.pixelsPerSecond*pe.ZOOM_FACTOR,pe.MAX_PIXELS_PER_SECOND);this.setPixelsPerSecond(e)}zoomOut(){const e=Math.max(this.pixelsPerSecond/pe.ZOOM_FACTOR,pe.MIN_PIXELS_PER_SECOND);this.setPixelsPerSecond(e)}setPixelsPerSecond(e){this.pixelsPerSecond=Math.max(pe.MIN_PIXELS_PER_SECOND,Math.min(pe.MAX_PIXELS_PER_SECOND,e)),this.layout.updateOptions(this.getOptions())}canZoomIn(){return this.pixelsPerSecond<pe.MAX_PIXELS_PER_SECOND}canZoomOut(){return this.pixelsPerSecond>pe.MIN_PIXELS_PER_SECOND}}class Ii extends be{constructor(e,t,i){super(),this.edit=e,this.theme=Gs.resolveTheme(i),this.layout=new Te({width:t.width,height:t.height,pixelsPerSecond:50,trackHeight:Math.max(40,this.theme.timeline.tracks.height||Te.TRACK_HEIGHT_DEFAULT),backgroundColor:this.theme.timeline.background,antialias:!0,resolution:window.devicePixelRatio||1},this.theme),this.optionsManager=new pe(t,this.theme,this.layout,n=>this.featureManager?.getToolbar()?.resize(n)),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 e=this.optionsManager.getOptions();this.renderer=new oc({width:e.width||800,height:e.height||600,backgroundColor:e.backgroundColor||0,antialias:e.antialias??!0,resolution:e.resolution||window.devicePixelRatio||1},(t,i)=>this.update(t,i)),this.eventHandler=new ac(this.edit,{onEditChange:this.handleEditChange.bind(this),onSeek:t=>this.edit.seek(t),onClipSelected:(t,i)=>this.visualTrackManager.updateVisualSelection(t,i),onSelectionCleared:()=>this.visualTrackManager.clearVisualSelection(),onDragStarted:(t,i)=>{const n=this.getClipData(t,i);n&&this.dragPreviewManager.showDragPreview(t,i,n)},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 e=this.edit.getEdit();e&&(this.currentEditType=e,await this.rebuildFromEdit(e))}catch{}this.renderer.startAnimationLoop()}async setupViewport(){this.viewportManager=new ec(this.layout,this.renderer.getTrackLayer(),this.renderer.getOverlayLayer(),this.getContainer(),()=>this.renderer.render()),await this.viewportManager.setupViewport(),this.visualTrackManager=new rc(this.getContainer(),this.layout,this.theme,()=>this.optionsManager.getPixelsPerSecond(),()=>this.getExtendedTimelineWidth()),this.dragPreviewManager=new Jo(this.getContainer(),this.layout,()=>this.optionsManager.getPixelsPerSecond(),()=>this.optionsManager.getTrackHeight(),()=>this.visualTrackManager.getVisualTracks()),this.featureManager=new fc(this.edit,this.layout,this.renderer,this.viewportManager,this.eventHandler,()=>this)}async setupTimelineFeatures(){const e=this.getExtendedTimelineDuration();await this.featureManager.setupTimelineFeatures(this.theme,this.optionsManager.getPixelsPerSecond(),this.optionsManager.getWidth(),this.optionsManager.getHeight(),e)}recreateTimelineFeatures(){const e=this.getExtendedTimelineDuration();this.featureManager.recreateTimelineFeatures(this.theme,this.optionsManager.getPixelsPerSecond(),this.optionsManager.getHeight(),e)}setScroll(e,t){this.viewportManager.setScroll(e,t)}setZoom(e){this.viewportManager.setZoom(e)}getViewport(){return this.viewportManager.getViewport()}getPixiApp(){return this.renderer.getApp()}getTrackLayer(){return this.renderer.getTrackLayer()}getOverlayLayer(){return this.renderer.getOverlayLayer()}getClipData(e,t){return this.currentEditType?.timeline?.tracks&&this.currentEditType.timeline.tracks[e]?.clips?.[t]||null}getLayout(){return this.layout}getVisualTracks(){return this.visualTrackManager.getVisualTracks()}getEdit(){return this.edit}getExtendedTimelineWidth(){const e=this.getExtendedTimelineDuration()*this.optionsManager.getPixelsPerSecond(),t=this.optionsManager.getWidth();return Math.max(e,t)}hideDragGhost(){this.dragPreviewManager.hideDragGhost()}showDragGhost(e,t,i){this.dragPreviewManager.showDragGhost(e,t,i)}setPlayheadTime(e){this.featureManager.getPlayhead().setTime(e)}getPlayheadTime(){return this.featureManager.getPlayhead().getTime()}getActualEditDuration(){return this.edit.totalDuration/1e3||60}setupInteraction(){this.interaction=new Qo(this)}async handleEditChange(e){this.dragPreviewManager.hideDragPreview();const t=e||this.edit.getEdit();t&&(this.currentEditType=t,this.updateRulerDuration(),this.clearAllVisualState(),await this.rebuildFromEdit(t))}getExtendedTimelineDuration(){const e=this.edit.totalDuration/1e3||60;return Math.max(60,e*Ii.TIMELINE_BUFFER_MULTIPLIER)}updateRulerDuration(){const e=this.getExtendedTimelineDuration(),t=this.getExtendedTimelineWidth();this.featureManager.updateRuler(this.optionsManager.getPixelsPerSecond(),e),this.visualTrackManager.updateTrackWidths(t)}clearAllVisualState(){this.dragPreviewManager.hideDragPreview(),this.visualTrackManager.clearAllVisualState()}async rebuildFromEdit(e){await this.visualTrackManager.rebuildFromEdit(e,this.optionsManager.getPixelsPerSecond()),this.renderer.render()}findClipAtPosition(e,t){return this.currentEditType?this.visualTrackManager.findClipAtPosition(e,t):null}setTheme(e){this.theme=Gs.resolveTheme(e),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(e){this.optionsManager.setOptions(e)}update(e,t){(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(e,t){this.setPlayheadTime(e),t&&this.edit.seek(e*1e3)}get timeRange(){return{startTime:0,endTime:this.getExtendedTimelineDuration()}}get viewportHeight(){return this.optionsManager.getHeight()}get zoomLevelIndex(){const e=this.viewportManager.getViewport();return Math.round(Math.log2(e.zoom)+5)}zoomIn(){this.optionsManager.zoomIn(),this.onZoomChanged()}zoomOut(){this.optionsManager.zoomOut(),this.onZoomChanged()}onZoomChanged(){const e=this.optionsManager.getPixelsPerSecond();this.visualTrackManager.updatePixelsPerSecond(e);const t=this.getExtendedTimelineWidth();this.visualTrackManager.updateTrackWidths(t),this.featureManager.updateRuler(e,this.getExtendedTimelineDuration()),this.featureManager.updatePlayhead(e,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()}}ee.Canvas=De,ee.Controls=Pr,ee.Edit=Je,ee.Timeline=Ii,ee.VideoExporter=Wo,Object.defineProperty(ee,Symbol.toStringTag,{value:"Module"})});
|