diff --git "a/assets/index-C22NwL-p.js" "b/assets/index-C22NwL-p.js" new file mode 100644--- /dev/null +++ "b/assets/index-C22NwL-p.js" @@ -0,0 +1,4054 @@ +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const a of r)if(a.type==="childList")for(const c of a.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&i(c)}).observe(document,{childList:!0,subtree:!0});function n(r){const a={};return r.integrity&&(a.integrity=r.integrity),r.referrerPolicy&&(a.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?a.credentials="include":r.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function i(r){if(r.ep)return;r.ep=!0;const a=n(r);fetch(r.href,a)}})();var VB=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function fT(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Em={exports:{}},su={};var Q_;function tC(){if(Q_)return su;Q_=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(i,r,a){var c=null;if(a!==void 0&&(c=""+a),r.key!==void 0&&(c=""+r.key),"key"in r){a={};for(var u in r)u!=="key"&&(a[u]=r[u])}else a=r;return r=a.ref,{$$typeof:t,type:i,key:c,ref:r!==void 0?r:null,props:a}}return su.Fragment=e,su.jsx=n,su.jsxs=n,su}var eb;function nC(){return eb||(eb=1,Em.exports=tC()),Em.exports}var p=nC(),wm={exports:{}},en={};var tb;function iC(){if(tb)return en;tb=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),a=Symbol.for("react.consumer"),c=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),g=Symbol.for("react.lazy"),v=Symbol.for("react.activity"),y=Symbol.iterator;function S($){return $===null||typeof $!="object"?null:($=y&&$[y]||$["@@iterator"],typeof $=="function"?$:null)}var T={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},A=Object.assign,E={};function w($,ce,Xe){this.props=$,this.context=ce,this.refs=E,this.updater=Xe||T}w.prototype.isReactComponent={},w.prototype.setState=function($,ce){if(typeof $!="object"&&typeof $!="function"&&$!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,$,ce,"setState")},w.prototype.forceUpdate=function($){this.updater.enqueueForceUpdate(this,$,"forceUpdate")};function I(){}I.prototype=w.prototype;function L($,ce,Xe){this.props=$,this.context=ce,this.refs=E,this.updater=Xe||T}var D=L.prototype=new I;D.constructor=L,A(D,w.prototype),D.isPureReactComponent=!0;var W=Array.isArray;function V(){}var H={H:null,A:null,T:null,S:null},Q=Object.prototype.hasOwnProperty;function k($,ce,Xe){var oe=Xe.ref;return{$$typeof:t,type:$,key:ce,ref:oe!==void 0?oe:null,props:Xe}}function P($,ce){return k($.type,ce,$.props)}function J($){return typeof $=="object"&&$!==null&&$.$$typeof===t}function ve($){var ce={"=":"=0",":":"=2"};return"$"+$.replace(/[=:]/g,function(Xe){return ce[Xe]})}var fe=/\/+/g;function Ee($,ce){return typeof $=="object"&&$!==null&&$.key!=null?ve(""+$.key):ce.toString(36)}function je($){switch($.status){case"fulfilled":return $.value;case"rejected":throw $.reason;default:switch(typeof $.status=="string"?$.then(V,V):($.status="pending",$.then(function(ce){$.status==="pending"&&($.status="fulfilled",$.value=ce)},function(ce){$.status==="pending"&&($.status="rejected",$.reason=ce)})),$.status){case"fulfilled":return $.value;case"rejected":throw $.reason}}throw $}function X($,ce,Xe,oe,Ie){var nt=typeof $;(nt==="undefined"||nt==="boolean")&&($=null);var Se=!1;if($===null)Se=!0;else switch(nt){case"bigint":case"string":case"number":Se=!0;break;case"object":switch($.$$typeof){case t:case e:Se=!0;break;case g:return Se=$._init,X(Se($._payload),ce,Xe,oe,Ie)}}if(Se)return Ie=Ie($),Se=oe===""?"."+Ee($,0):oe,W(Ie)?(Xe="",Se!=null&&(Xe=Se.replace(fe,"$&/")+"/"),X(Ie,ce,Xe,"",function(xe){return xe})):Ie!=null&&(J(Ie)&&(Ie=P(Ie,Xe+(Ie.key==null||$&&$.key===Ie.key?"":(""+Ie.key).replace(fe,"$&/")+"/")+Se)),ce.push(Ie)),1;Se=0;var N=oe===""?".":oe+":";if(W($))for(var ye=0;ye<$.length;ye++)oe=$[ye],nt=N+Ee(oe,ye),Se+=X(oe,ce,Xe,nt,Ie);else if(ye=S($),typeof ye=="function")for($=ye.call($),ye=0;!(oe=$.next()).done;)oe=oe.value,nt=N+Ee(oe,ye++),Se+=X(oe,ce,Xe,nt,Ie);else if(nt==="object"){if(typeof $.then=="function")return X(je($),ce,Xe,oe,Ie);throw ce=String($),Error("Objects are not valid as a React child (found: "+(ce==="[object Object]"?"object with keys {"+Object.keys($).join(", ")+"}":ce)+"). If you meant to render a collection of children, use an array instead.")}return Se}function _e($,ce,Xe){if($==null)return $;var oe=[],Ie=0;return X($,oe,"","",function(nt){return ce.call(Xe,nt,Ie++)}),oe}function ne($){if($._status===-1){var ce=$._result;ce=ce(),ce.then(function(Xe){($._status===0||$._status===-1)&&($._status=1,$._result=Xe)},function(Xe){($._status===0||$._status===-1)&&($._status=2,$._result=Xe)}),$._status===-1&&($._status=0,$._result=ce)}if($._status===1)return $._result.default;throw $._result}var tt=typeof reportError=="function"?reportError:function($){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var ce=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof $=="object"&&$!==null&&typeof $.message=="string"?String($.message):String($),error:$});if(!window.dispatchEvent(ce))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",$);return}console.error($)},Ce={map:_e,forEach:function($,ce,Xe){_e($,function(){ce.apply(this,arguments)},Xe)},count:function($){var ce=0;return _e($,function(){ce++}),ce},toArray:function($){return _e($,function(ce){return ce})||[]},only:function($){if(!J($))throw Error("React.Children.only expected to receive a single React element child.");return $}};return en.Activity=v,en.Children=Ce,en.Component=w,en.Fragment=n,en.Profiler=r,en.PureComponent=L,en.StrictMode=i,en.Suspense=h,en.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=H,en.__COMPILER_RUNTIME={__proto__:null,c:function($){return H.H.useMemoCache($)}},en.cache=function($){return function(){return $.apply(null,arguments)}},en.cacheSignal=function(){return null},en.cloneElement=function($,ce,Xe){if($==null)throw Error("The argument must be a React element, but you passed "+$+".");var oe=A({},$.props),Ie=$.key;if(ce!=null)for(nt in ce.key!==void 0&&(Ie=""+ce.key),ce)!Q.call(ce,nt)||nt==="key"||nt==="__self"||nt==="__source"||nt==="ref"&&ce.ref===void 0||(oe[nt]=ce[nt]);var nt=arguments.length-2;if(nt===1)oe.children=Xe;else if(1>>1,Ce=X[tt];if(0>>1;tt<$;){var ce=2*(tt+1)-1,Xe=X[ce],oe=ce+1,Ie=X[oe];if(0>r(Xe,ne))oer(Ie,Xe)?(X[tt]=Ie,X[oe]=ne,tt=oe):(X[tt]=Xe,X[ce]=ne,tt=ce);else if(oer(Ie,ne))X[tt]=Ie,X[oe]=ne,tt=oe;else break e}}return _e}function r(X,_e){var ne=X.sortIndex-_e.sortIndex;return ne!==0?ne:X.id-_e.id}if(t.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var a=performance;t.unstable_now=function(){return a.now()}}else{var c=Date,u=c.now();t.unstable_now=function(){return c.now()-u}}var h=[],d=[],g=1,v=null,y=3,S=!1,T=!1,A=!1,E=!1,w=typeof setTimeout=="function"?setTimeout:null,I=typeof clearTimeout=="function"?clearTimeout:null,L=typeof setImmediate<"u"?setImmediate:null;function D(X){for(var _e=n(d);_e!==null;){if(_e.callback===null)i(d);else if(_e.startTime<=X)i(d),_e.sortIndex=_e.expirationTime,e(h,_e);else break;_e=n(d)}}function W(X){if(A=!1,D(X),!T)if(n(h)!==null)T=!0,V||(V=!0,ve());else{var _e=n(d);_e!==null&&je(W,_e.startTime-X)}}var V=!1,H=-1,Q=5,k=-1;function P(){return E?!0:!(t.unstable_now()-kX&&P());){var tt=v.callback;if(typeof tt=="function"){v.callback=null,y=v.priorityLevel;var Ce=tt(v.expirationTime<=X);if(X=t.unstable_now(),typeof Ce=="function"){v.callback=Ce,D(X),_e=!0;break t}v===n(h)&&i(h),D(X)}else i(h);v=n(h)}if(v!==null)_e=!0;else{var $=n(d);$!==null&&je(W,$.startTime-X),_e=!1}}break e}finally{v=null,y=ne,S=!1}_e=void 0}}finally{_e?ve():V=!1}}}var ve;if(typeof L=="function")ve=function(){L(J)};else if(typeof MessageChannel<"u"){var fe=new MessageChannel,Ee=fe.port2;fe.port1.onmessage=J,ve=function(){Ee.postMessage(null)}}else ve=function(){w(J,0)};function je(X,_e){H=w(function(){X(t.unstable_now())},_e)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(X){X.callback=null},t.unstable_forceFrameRate=function(X){0>X||125tt?(X.sortIndex=ne,e(d,X),n(h)===null&&X===n(d)&&(A?(I(H),H=-1):A=!0,je(W,ne-tt))):(X.sortIndex=Ce,e(h,X),T||S||(T=!0,V||(V=!0,ve()))),X},t.unstable_shouldYield=P,t.unstable_wrapCallback=function(X){var _e=y;return function(){var ne=y;y=_e;try{return X.apply(this,arguments)}finally{y=ne}}}})(Am)),Am}var ob;function sC(){return ob||(ob=1,Cm.exports=oC()),Cm.exports}var Rm={exports:{}},po={};var sb;function rC(){if(sb)return po;sb=1;var t=Fg();function e(h){var d="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(e){console.error(e)}}return t(),Rm.exports=rC(),Rm.exports}var ab;function lC(){if(ab)return ru;ab=1;var t=sC(),e=Fg(),n=aC();function i(o){var s="https://react.dev/errors/"+o;if(1Ce||(o.current=tt[Ce],tt[Ce]=null,Ce--)}function Xe(o,s){Ce++,tt[Ce]=o.current,o.current=s}var oe=$(null),Ie=$(null),nt=$(null),Se=$(null);function N(o,s){switch(Xe(nt,s),Xe(Ie,o),Xe(oe,null),s.nodeType){case 9:case 11:o=(o=s.documentElement)&&(o=o.namespaceURI)?S_(o):0;break;default:if(o=s.tagName,s=s.namespaceURI)s=S_(s),o=T_(s,o);else switch(o){case"svg":o=1;break;case"math":o=2;break;default:o=0}}ce(oe),Xe(oe,o)}function ye(){ce(oe),ce(Ie),ce(nt)}function xe(o){o.memoizedState!==null&&Xe(Se,o);var s=oe.current,l=T_(s,o.type);s!==l&&(Xe(Ie,o),Xe(oe,l))}function Oe(o){Ie.current===o&&(ce(oe),ce(Ie)),Se.current===o&&(ce(Se),tu._currentValue=ne)}var at,Ze;function U(o){if(at===void 0)try{throw Error()}catch(l){var s=l.stack.trim().match(/\n( *(at )?)/);at=s&&s[1]||"",Ze=-1)":-1_||ie[f]!==ze[_]){var ot=` +`+ie[f].replace(" at new "," at ");return o.displayName&&ot.includes("")&&(ot=ot.replace("",o.displayName)),ot}while(1<=f&&0<=_);break}}}finally{Me=!1,Error.prepareStackTrace=l}return(l=o?o.displayName||o.name:"")?U(l):""}function rt(o,s){switch(o.tag){case 26:case 27:case 5:return U(o.type);case 16:return U("Lazy");case 13:return o.child!==s&&s!==null?U("Suspense Fallback"):U("Suspense");case 19:return U("SuspenseList");case 0:case 15:return Pe(o.type,!1);case 11:return Pe(o.type.render,!1);case 1:return Pe(o.type,!0);case 31:return U("Activity");default:return""}}function We(o){try{var s="",l=null;do s+=rt(o,l),l=o,o=o.return;while(o);return s}catch(f){return` +Error generating stack: `+f.message+` +`+f.stack}}var gt=Object.prototype.hasOwnProperty,qe=t.unstable_scheduleCallback,q=t.unstable_cancelCallback,C=t.unstable_shouldYield,te=t.unstable_requestPaint,ae=t.unstable_now,Re=t.unstable_getCurrentPriorityLevel,De=t.unstable_ImmediatePriority,st=t.unstable_UserBlockingPriority,it=t.unstable_NormalPriority,F=t.unstable_LowPriority,le=t.unstable_IdlePriority,z=t.log,j=t.unstable_setDisableYieldValue,B=null,re=null;function Y(o){if(typeof z=="function"&&j(o),re&&typeof re.setStrictMode=="function")try{re.setStrictMode(B,o)}catch{}}var me=Math.clz32?Math.clz32:M,ee=Math.log,$e=Math.LN2;function M(o){return o>>>=0,o===0?32:31-(ee(o)/$e|0)|0}var K=256,de=262144,ue=4194304;function Ue(o){var s=o&42;if(s!==0)return s;switch(o&-o){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return o&261888;case 262144:case 524288:case 1048576:case 2097152:return o&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return o&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return o}}function Je(o,s,l){var f=o.pendingLanes;if(f===0)return 0;var _=0,b=o.suspendedLanes,R=o.pingedLanes;o=o.warmLanes;var O=f&134217727;return O!==0?(f=O&~b,f!==0?_=Ue(f):(R&=O,R!==0?_=Ue(R):l||(l=O&~o,l!==0&&(_=Ue(l))))):(O=f&~b,O!==0?_=Ue(O):R!==0?_=Ue(R):l||(l=f&~o,l!==0&&(_=Ue(l)))),_===0?0:s!==0&&s!==_&&(s&b)===0&&(b=_&-_,l=s&-s,b>=l||b===32&&(l&4194048)!==0)?s:_}function ht(o,s){return(o.pendingLanes&~(o.suspendedLanes&~o.pingedLanes)&s)===0}function et(o,s){switch(o){case 1:case 2:case 4:case 8:case 64:return s+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return s+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Te(){var o=ue;return ue<<=1,(ue&62914560)===0&&(ue=4194304),o}function Ke(o){for(var s=[],l=0;31>l;l++)s.push(o);return s}function Be(o,s){o.pendingLanes|=s,s!==268435456&&(o.suspendedLanes=0,o.pingedLanes=0,o.warmLanes=0)}function _t(o,s,l,f,_,b){var R=o.pendingLanes;o.pendingLanes=l,o.suspendedLanes=0,o.pingedLanes=0,o.warmLanes=0,o.expiredLanes&=l,o.entangledLanes&=l,o.errorRecoveryDisabledLanes&=l,o.shellSuspendCounter=0;var O=o.entanglements,ie=o.expirationTimes,ze=o.hiddenUpdates;for(l=R&~l;0"u")return null;try{return o.activeElement||o.body}catch{return o.body}}var Di=/[\n"\\]/g;function hi(o){return o.replace(Di,function(s){return"\\"+s.charCodeAt(0).toString(16)+" "})}function Rn(o,s,l,f,_,b,R,O){o.name="",R!=null&&typeof R!="function"&&typeof R!="symbol"&&typeof R!="boolean"?o.type=R:o.removeAttribute("type"),s!=null?R==="number"?(s===0&&o.value===""||o.value!=s)&&(o.value=""+Wt(s)):o.value!==""+Wt(s)&&(o.value=""+Wt(s)):R!=="submit"&&R!=="reset"||o.removeAttribute("value"),s!=null?qi(o,R,Wt(s)):l!=null?qi(o,R,Wt(l)):f!=null&&o.removeAttribute("value"),_==null&&b!=null&&(o.defaultChecked=!!b),_!=null&&(o.checked=_&&typeof _!="function"&&typeof _!="symbol"),O!=null&&typeof O!="function"&&typeof O!="symbol"&&typeof O!="boolean"?o.name=""+Wt(O):o.removeAttribute("name")}function io(o,s,l,f,_,b,R,O){if(b!=null&&typeof b!="function"&&typeof b!="symbol"&&typeof b!="boolean"&&(o.type=b),s!=null||l!=null){if(!(b!=="submit"&&b!=="reset"||s!=null)){vn(o);return}l=l!=null?""+Wt(l):"",s=s!=null?""+Wt(s):l,O||s===o.value||(o.value=s),o.defaultValue=s}f=f??_,f=typeof f!="function"&&typeof f!="symbol"&&!!f,o.checked=O?o.checked:!!f,o.defaultChecked=!!f,R!=null&&typeof R!="function"&&typeof R!="symbol"&&typeof R!="boolean"&&(o.name=R),vn(o)}function qi(o,s,l){s==="number"&&xo(o.ownerDocument)===o||o.defaultValue===""+l||(o.defaultValue=""+l)}function pi(o,s,l,f){if(o=o.options,s){s={};for(var _=0;_"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Mt=!1;if(se)try{var Ft={};Object.defineProperty(Ft,"passive",{get:function(){Mt=!0}}),window.addEventListener("test",Ft,Ft),window.removeEventListener("test",Ft,Ft)}catch{Mt=!1}var vt=null,on=null,Lt=null;function un(){if(Lt)return Lt;var o,s=on,l=s.length,f,_="value"in vt?vt.value:vt.textContent,b=_.length;for(o=0;o=Sc),Rv=" ",Nv=!1;function Iv(o,s){switch(o){case"keyup":return Tw.indexOf(s.keyCode)!==-1;case"keydown":return s.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Dv(o){return o=o.detail,typeof o=="object"&&"data"in o?o.data:null}var Qa=!1;function ww(o,s){switch(o){case"compositionend":return Dv(s);case"keypress":return s.which!==32?null:(Nv=!0,Rv);case"textInput":return o=s.data,o===Rv&&Nv?null:o;default:return null}}function Mw(o,s){if(Qa)return o==="compositionend"||!Nh&&Iv(o,s)?(o=un(),Lt=on=vt=null,Qa=!1,o):null;switch(o){case"paste":return null;case"keypress":if(!(s.ctrlKey||s.altKey||s.metaKey)||s.ctrlKey&&s.altKey){if(s.char&&1=s)return{node:l,offset:s-o};o=f}e:{for(;l;){if(l.nextSibling){l=l.nextSibling;break e}l=l.parentNode}l=void 0}l=Bv(l)}}function Hv(o,s){return o&&s?o===s?!0:o&&o.nodeType===3?!1:s&&s.nodeType===3?Hv(o,s.parentNode):"contains"in o?o.contains(s):o.compareDocumentPosition?!!(o.compareDocumentPosition(s)&16):!1:!1}function Gv(o){o=o!=null&&o.ownerDocument!=null&&o.ownerDocument.defaultView!=null?o.ownerDocument.defaultView:window;for(var s=xo(o.document);s instanceof o.HTMLIFrameElement;){try{var l=typeof s.contentWindow.location.href=="string"}catch{l=!1}if(l)o=s.contentWindow;else break;s=xo(o.document)}return s}function Lh(o){var s=o&&o.nodeName&&o.nodeName.toLowerCase();return s&&(s==="input"&&(o.type==="text"||o.type==="search"||o.type==="tel"||o.type==="url"||o.type==="password")||s==="textarea"||o.contentEditable==="true")}var Uw=se&&"documentMode"in document&&11>=document.documentMode,el=null,Uh=null,Mc=null,kh=!1;function jv(o,s,l){var f=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;kh||el==null||el!==xo(f)||(f=el,"selectionStart"in f&&Lh(f)?f={start:f.selectionStart,end:f.selectionEnd}:(f=(f.ownerDocument&&f.ownerDocument.defaultView||window).getSelection(),f={anchorNode:f.anchorNode,anchorOffset:f.anchorOffset,focusNode:f.focusNode,focusOffset:f.focusOffset}),Mc&&wc(Mc,f)||(Mc=f,f=Ld(Uh,"onSelect"),0>=R,_-=R,Ds=1<<32-me(s)+_|l<<_|f,Ls=b+o}else Ds=1<rn?(yn=Ut,Ut=null):yn=Ut.sibling;var Ln=Ge(we,Ut,ke[rn],ct);if(Ln===null){Ut===null&&(Ut=yn);break}o&&Ut&&Ln.alternate===null&&s(we,Ut),he=b(Ln,he,rn),Dn===null?Ot=Ln:Dn.sibling=Ln,Dn=Ln,Ut=yn}if(rn===ke.length)return l(we,Ut),Sn&&$s(we,rn),Ot;if(Ut===null){for(;rnrn?(yn=Ut,Ut=null):yn=Ut.sibling;var jr=Ge(we,Ut,Ln.value,ct);if(jr===null){Ut===null&&(Ut=yn);break}o&&Ut&&jr.alternate===null&&s(we,Ut),he=b(jr,he,rn),Dn===null?Ot=jr:Dn.sibling=jr,Dn=jr,Ut=yn}if(Ln.done)return l(we,Ut),Sn&&$s(we,rn),Ot;if(Ut===null){for(;!Ln.done;rn++,Ln=ke.next())Ln=ut(we,Ln.value,ct),Ln!==null&&(he=b(Ln,he,rn),Dn===null?Ot=Ln:Dn.sibling=Ln,Dn=Ln);return Sn&&$s(we,rn),Ot}for(Ut=f(Ut);!Ln.done;rn++,Ln=ke.next())Ln=Qe(Ut,we,rn,Ln.value,ct),Ln!==null&&(o&&Ln.alternate!==null&&Ut.delete(Ln.key===null?rn:Ln.key),he=b(Ln,he,rn),Dn===null?Ot=Ln:Dn.sibling=Ln,Dn=Ln);return o&&Ut.forEach(function(eC){return s(we,eC)}),Sn&&$s(we,rn),Ot}function Zn(we,he,ke,ct){if(typeof ke=="object"&&ke!==null&&ke.type===A&&ke.key===null&&(ke=ke.props.children),typeof ke=="object"&&ke!==null){switch(ke.$$typeof){case S:e:{for(var Ot=ke.key;he!==null;){if(he.key===Ot){if(Ot=ke.type,Ot===A){if(he.tag===7){l(we,he.sibling),ct=_(he,ke.props.children),ct.return=we,we=ct;break e}}else if(he.elementType===Ot||typeof Ot=="object"&&Ot!==null&&Ot.$$typeof===Q&&ga(Ot)===he.type){l(we,he.sibling),ct=_(he,ke.props),Dc(ct,ke),ct.return=we,we=ct;break e}l(we,he);break}else s(we,he);he=he.sibling}ke.type===A?(ct=da(ke.props.children,we.mode,ct,ke.key),ct.return=we,we=ct):(ct=Ju(ke.type,ke.key,ke.props,null,we.mode,ct),Dc(ct,ke),ct.return=we,we=ct)}return R(we);case T:e:{for(Ot=ke.key;he!==null;){if(he.key===Ot)if(he.tag===4&&he.stateNode.containerInfo===ke.containerInfo&&he.stateNode.implementation===ke.implementation){l(we,he.sibling),ct=_(he,ke.children||[]),ct.return=we,we=ct;break e}else{l(we,he);break}else s(we,he);he=he.sibling}ct=Hh(ke,we.mode,ct),ct.return=we,we=ct}return R(we);case Q:return ke=ga(ke),Zn(we,he,ke,ct)}if(je(ke))return Nt(we,he,ke,ct);if(ve(ke)){if(Ot=ve(ke),typeof Ot!="function")throw Error(i(150));return ke=Ot.call(ke),Gt(we,he,ke,ct)}if(typeof ke.then=="function")return Zn(we,he,id(ke),ct);if(ke.$$typeof===L)return Zn(we,he,Qu(we,ke),ct);od(we,ke)}return typeof ke=="string"&&ke!==""||typeof ke=="number"||typeof ke=="bigint"?(ke=""+ke,he!==null&&he.tag===6?(l(we,he.sibling),ct=_(he,ke),ct.return=we,we=ct):(l(we,he),ct=Vh(ke,we.mode,ct),ct.return=we,we=ct),R(we)):l(we,he)}return function(we,he,ke,ct){try{Ic=0;var Ot=Zn(we,he,ke,ct);return dl=null,Ot}catch(Ut){if(Ut===ul||Ut===td)throw Ut;var Dn=zo(29,Ut,null,we.mode);return Dn.lanes=ct,Dn.return=we,Dn}}}var xa=hx(!0),px=hx(!1),Cr=!1;function ep(o){o.updateQueue={baseState:o.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function tp(o,s){o=o.updateQueue,s.updateQueue===o&&(s.updateQueue={baseState:o.baseState,firstBaseUpdate:o.firstBaseUpdate,lastBaseUpdate:o.lastBaseUpdate,shared:o.shared,callbacks:null})}function Ar(o){return{lane:o,tag:0,payload:null,callback:null,next:null}}function Rr(o,s,l){var f=o.updateQueue;if(f===null)return null;if(f=f.shared,(Fn&2)!==0){var _=f.pending;return _===null?s.next=s:(s.next=_.next,_.next=s),f.pending=s,s=Yu(o),Kv(o,null,l),s}return Xu(o,f,s,l),Yu(o)}function Lc(o,s,l){if(s=s.updateQueue,s!==null&&(s=s.shared,(l&4194048)!==0)){var f=s.lanes;f&=o.pendingLanes,l|=f,s.lanes=l,Dt(o,l)}}function np(o,s){var l=o.updateQueue,f=o.alternate;if(f!==null&&(f=f.updateQueue,l===f)){var _=null,b=null;if(l=l.firstBaseUpdate,l!==null){do{var R={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};b===null?_=b=R:b=b.next=R,l=l.next}while(l!==null);b===null?_=b=s:b=b.next=s}else _=b=s;l={baseState:f.baseState,firstBaseUpdate:_,lastBaseUpdate:b,shared:f.shared,callbacks:f.callbacks},o.updateQueue=l;return}o=l.lastBaseUpdate,o===null?l.firstBaseUpdate=s:o.next=s,l.lastBaseUpdate=s}var ip=!1;function Uc(){if(ip){var o=cl;if(o!==null)throw o}}function kc(o,s,l,f){ip=!1;var _=o.updateQueue;Cr=!1;var b=_.firstBaseUpdate,R=_.lastBaseUpdate,O=_.shared.pending;if(O!==null){_.shared.pending=null;var ie=O,ze=ie.next;ie.next=null,R===null?b=ze:R.next=ze,R=ie;var ot=o.alternate;ot!==null&&(ot=ot.updateQueue,O=ot.lastBaseUpdate,O!==R&&(O===null?ot.firstBaseUpdate=ze:O.next=ze,ot.lastBaseUpdate=ie))}if(b!==null){var ut=_.baseState;R=0,ot=ze=ie=null,O=b;do{var Ge=O.lane&-536870913,Qe=Ge!==O.lane;if(Qe?(xn&Ge)===Ge:(f&Ge)===Ge){Ge!==0&&Ge===ll&&(ip=!0),ot!==null&&(ot=ot.next={lane:0,tag:O.tag,payload:O.payload,callback:null,next:null});e:{var Nt=o,Gt=O;Ge=s;var Zn=l;switch(Gt.tag){case 1:if(Nt=Gt.payload,typeof Nt=="function"){ut=Nt.call(Zn,ut,Ge);break e}ut=Nt;break e;case 3:Nt.flags=Nt.flags&-65537|128;case 0:if(Nt=Gt.payload,Ge=typeof Nt=="function"?Nt.call(Zn,ut,Ge):Nt,Ge==null)break e;ut=v({},ut,Ge);break e;case 2:Cr=!0}}Ge=O.callback,Ge!==null&&(o.flags|=64,Qe&&(o.flags|=8192),Qe=_.callbacks,Qe===null?_.callbacks=[Ge]:Qe.push(Ge))}else Qe={lane:Ge,tag:O.tag,payload:O.payload,callback:O.callback,next:null},ot===null?(ze=ot=Qe,ie=ut):ot=ot.next=Qe,R|=Ge;if(O=O.next,O===null){if(O=_.shared.pending,O===null)break;Qe=O,O=Qe.next,Qe.next=null,_.lastBaseUpdate=Qe,_.shared.pending=null}}while(!0);ot===null&&(ie=ut),_.baseState=ie,_.firstBaseUpdate=ze,_.lastBaseUpdate=ot,b===null&&(_.shared.lanes=0),Ur|=R,o.lanes=R,o.memoizedState=ut}}function mx(o,s){if(typeof o!="function")throw Error(i(191,o));o.call(s)}function gx(o,s){var l=o.callbacks;if(l!==null)for(o.callbacks=null,o=0;ob?b:8;var R=X.T,O={};X.T=O,Sp(o,!1,s,l);try{var ie=_(),ze=X.S;if(ze!==null&&ze(O,ie),ie!==null&&typeof ie=="object"&&typeof ie.then=="function"){var ot=Gw(ie,f);Fc(o,s,ot,Vo(o))}else Fc(o,s,f,Vo(o))}catch(ut){Fc(o,s,{then:function(){},status:"rejected",reason:ut},Vo())}finally{_e.p=b,R!==null&&O.types!==null&&(R.types=O.types),X.T=R}}function Yw(){}function _p(o,s,l,f){if(o.tag!==5)throw Error(i(476));var _=Xx(o).queue;$x(o,_,s,ne,l===null?Yw:function(){return Yx(o),l(f)})}function Xx(o){var s=o.memoizedState;if(s!==null)return s;s={memoizedState:ne,baseState:ne,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ks,lastRenderedState:ne},next:null};var l={};return s.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ks,lastRenderedState:l},next:null},o.memoizedState=s,o=o.alternate,o!==null&&(o.memoizedState=s),s}function Yx(o){var s=Xx(o);s.next===null&&(s=o.alternate.memoizedState),Fc(o,s.next.queue,{},Vo())}function bp(){return so(tu)}function Jx(){return Ri().memoizedState}function Kx(){return Ri().memoizedState}function Jw(o){for(var s=o.return;s!==null;){switch(s.tag){case 24:case 3:var l=Vo();o=Ar(l);var f=Rr(s,o,l);f!==null&&(Ro(f,s,l),Lc(f,s,l)),s={cache:Jh()},o.payload=s;return}s=s.return}}function Kw(o,s,l){var f=Vo();l={lane:f,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},pd(o)?Qx(s,l):(l=Oh(o,s,l,f),l!==null&&(Ro(l,o,f),ey(l,s,f)))}function Zx(o,s,l){var f=Vo();Fc(o,s,l,f)}function Fc(o,s,l,f){var _={lane:f,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(pd(o))Qx(s,_);else{var b=o.alternate;if(o.lanes===0&&(b===null||b.lanes===0)&&(b=s.lastRenderedReducer,b!==null))try{var R=s.lastRenderedState,O=b(R,l);if(_.hasEagerState=!0,_.eagerState=O,ko(O,R))return Xu(o,s,_,0),ei===null&&$u(),!1}catch{}if(l=Oh(o,s,_,f),l!==null)return Ro(l,o,f),ey(l,s,f),!0}return!1}function Sp(o,s,l,f){if(f={lane:2,revertLane:em(),gesture:null,action:f,hasEagerState:!1,eagerState:null,next:null},pd(o)){if(s)throw Error(i(479))}else s=Oh(o,l,f,2),s!==null&&Ro(s,o,2)}function pd(o){var s=o.alternate;return o===nn||s!==null&&s===nn}function Qx(o,s){hl=ad=!0;var l=o.pending;l===null?s.next=s:(s.next=l.next,l.next=s),o.pending=s}function ey(o,s,l){if((l&4194048)!==0){var f=s.lanes;f&=o.pendingLanes,l|=f,s.lanes=l,Dt(o,l)}}var Oc={readContext:so,use:ud,useCallback:Ti,useContext:Ti,useEffect:Ti,useImperativeHandle:Ti,useLayoutEffect:Ti,useInsertionEffect:Ti,useMemo:Ti,useReducer:Ti,useRef:Ti,useState:Ti,useDebugValue:Ti,useDeferredValue:Ti,useTransition:Ti,useSyncExternalStore:Ti,useId:Ti,useHostTransitionStatus:Ti,useFormState:Ti,useActionState:Ti,useOptimistic:Ti,useMemoCache:Ti,useCacheRefresh:Ti};Oc.useEffectEvent=Ti;var ty={readContext:so,use:ud,useCallback:function(o,s){return _o().memoizedState=[o,s===void 0?null:s],o},useContext:so,useEffect:Fx,useImperativeHandle:function(o,s,l){l=l!=null?l.concat([o]):null,fd(4194308,4,Hx.bind(null,s,o),l)},useLayoutEffect:function(o,s){return fd(4194308,4,o,s)},useInsertionEffect:function(o,s){fd(4,2,o,s)},useMemo:function(o,s){var l=_o();s=s===void 0?null:s;var f=o();if(ya){Y(!0);try{o()}finally{Y(!1)}}return l.memoizedState=[f,s],f},useReducer:function(o,s,l){var f=_o();if(l!==void 0){var _=l(s);if(ya){Y(!0);try{l(s)}finally{Y(!1)}}}else _=s;return f.memoizedState=f.baseState=_,o={pending:null,lanes:0,dispatch:null,lastRenderedReducer:o,lastRenderedState:_},f.queue=o,o=o.dispatch=Kw.bind(null,nn,o),[f.memoizedState,o]},useRef:function(o){var s=_o();return o={current:o},s.memoizedState=o},useState:function(o){o=mp(o);var s=o.queue,l=Zx.bind(null,nn,s);return s.dispatch=l,[o.memoizedState,l]},useDebugValue:xp,useDeferredValue:function(o,s){var l=_o();return yp(l,o,s)},useTransition:function(){var o=mp(!1);return o=$x.bind(null,nn,o.queue,!0,!1),_o().memoizedState=o,[!1,o]},useSyncExternalStore:function(o,s,l){var f=nn,_=_o();if(Sn){if(l===void 0)throw Error(i(407));l=l()}else{if(l=s(),ei===null)throw Error(i(349));(xn&127)!==0||Sx(f,s,l)}_.memoizedState=l;var b={value:l,getSnapshot:s};return _.queue=b,Fx(Ex.bind(null,f,b,o),[o]),f.flags|=2048,ml(9,{destroy:void 0},Tx.bind(null,f,b,l,s),null),l},useId:function(){var o=_o(),s=ei.identifierPrefix;if(Sn){var l=Ls,f=Ds;l=(f&~(1<<32-me(f)-1)).toString(32)+l,s="_"+s+"R_"+l,l=ld++,0<\/script>",b=b.removeChild(b.firstChild);break;case"select":b=typeof f.is=="string"?R.createElement("select",{is:f.is}):R.createElement("select"),f.multiple?b.multiple=!0:f.size&&(b.size=f.size);break;default:b=typeof f.is=="string"?R.createElement(_,{is:f.is}):R.createElement(_)}}b[fn]=s,b[fi]=f;e:for(R=s.child;R!==null;){if(R.tag===5||R.tag===6)b.appendChild(R.stateNode);else if(R.tag!==4&&R.tag!==27&&R.child!==null){R.child.return=R,R=R.child;continue}if(R===s)break e;for(;R.sibling===null;){if(R.return===null||R.return===s)break e;R=R.return}R.sibling.return=R.return,R=R.sibling}s.stateNode=b;e:switch(ao(b,_,f),_){case"button":case"input":case"select":case"textarea":f=!!f.autoFocus;break e;case"img":f=!0;break e;default:f=!1}f&&Qs(s)}}return ai(s),zp(s,s.type,o===null?null:o.memoizedProps,s.pendingProps,l),null;case 6:if(o&&s.stateNode!=null)o.memoizedProps!==f&&Qs(s);else{if(typeof f!="string"&&s.stateNode===null)throw Error(i(166));if(o=nt.current,rl(s)){if(o=s.stateNode,l=s.memoizedProps,f=null,_=oo,_!==null)switch(_.tag){case 27:case 5:f=_.memoizedProps}o[fn]=s,o=!!(o.nodeValue===l||f!==null&&f.suppressHydrationWarning===!0||__(o.nodeValue,l)),o||wr(s,!0)}else o=Ud(o).createTextNode(f),o[fn]=s,s.stateNode=o}return ai(s),null;case 31:if(l=s.memoizedState,o===null||o.memoizedState!==null){if(f=rl(s),l!==null){if(o===null){if(!f)throw Error(i(318));if(o=s.memoizedState,o=o!==null?o.dehydrated:null,!o)throw Error(i(557));o[fn]=s}else fa(),(s.flags&128)===0&&(s.memoizedState=null),s.flags|=4;ai(s),o=!1}else l=Wh(),o!==null&&o.memoizedState!==null&&(o.memoizedState.hydrationErrors=l),o=!0;if(!o)return s.flags&256?(Fo(s),s):(Fo(s),null);if((s.flags&128)!==0)throw Error(i(558))}return ai(s),null;case 13:if(f=s.memoizedState,o===null||o.memoizedState!==null&&o.memoizedState.dehydrated!==null){if(_=rl(s),f!==null&&f.dehydrated!==null){if(o===null){if(!_)throw Error(i(318));if(_=s.memoizedState,_=_!==null?_.dehydrated:null,!_)throw Error(i(317));_[fn]=s}else fa(),(s.flags&128)===0&&(s.memoizedState=null),s.flags|=4;ai(s),_=!1}else _=Wh(),o!==null&&o.memoizedState!==null&&(o.memoizedState.hydrationErrors=_),_=!0;if(!_)return s.flags&256?(Fo(s),s):(Fo(s),null)}return Fo(s),(s.flags&128)!==0?(s.lanes=l,s):(l=f!==null,o=o!==null&&o.memoizedState!==null,l&&(f=s.child,_=null,f.alternate!==null&&f.alternate.memoizedState!==null&&f.alternate.memoizedState.cachePool!==null&&(_=f.alternate.memoizedState.cachePool.pool),b=null,f.memoizedState!==null&&f.memoizedState.cachePool!==null&&(b=f.memoizedState.cachePool.pool),b!==_&&(f.flags|=2048)),l!==o&&l&&(s.child.flags|=8192),yd(s,s.updateQueue),ai(s),null);case 4:return ye(),o===null&&om(s.stateNode.containerInfo),ai(s),null;case 10:return Ys(s.type),ai(s),null;case 19:if(ce(Ai),f=s.memoizedState,f===null)return ai(s),null;if(_=(s.flags&128)!==0,b=f.rendering,b===null)if(_)Vc(f,!1);else{if(Ei!==0||o!==null&&(o.flags&128)!==0)for(o=s.child;o!==null;){if(b=rd(o),b!==null){for(s.flags|=128,Vc(f,!1),o=b.updateQueue,s.updateQueue=o,yd(s,o),s.subtreeFlags=0,o=l,l=s.child;l!==null;)Zv(l,o),l=l.sibling;return Xe(Ai,Ai.current&1|2),Sn&&$s(s,f.treeForkCount),s.child}o=o.sibling}f.tail!==null&&ae()>Ed&&(s.flags|=128,_=!0,Vc(f,!1),s.lanes=4194304)}else{if(!_)if(o=rd(b),o!==null){if(s.flags|=128,_=!0,o=o.updateQueue,s.updateQueue=o,yd(s,o),Vc(f,!0),f.tail===null&&f.tailMode==="hidden"&&!b.alternate&&!Sn)return ai(s),null}else 2*ae()-f.renderingStartTime>Ed&&l!==536870912&&(s.flags|=128,_=!0,Vc(f,!1),s.lanes=4194304);f.isBackwards?(b.sibling=s.child,s.child=b):(o=f.last,o!==null?o.sibling=b:s.child=b,f.last=b)}return f.tail!==null?(o=f.tail,f.rendering=o,f.tail=o.sibling,f.renderingStartTime=ae(),o.sibling=null,l=Ai.current,Xe(Ai,_?l&1|2:l&1),Sn&&$s(s,f.treeForkCount),o):(ai(s),null);case 22:case 23:return Fo(s),sp(),f=s.memoizedState!==null,o!==null?o.memoizedState!==null!==f&&(s.flags|=8192):f&&(s.flags|=8192),f?(l&536870912)!==0&&(s.flags&128)===0&&(ai(s),s.subtreeFlags&6&&(s.flags|=8192)):ai(s),l=s.updateQueue,l!==null&&yd(s,l.retryQueue),l=null,o!==null&&o.memoizedState!==null&&o.memoizedState.cachePool!==null&&(l=o.memoizedState.cachePool.pool),f=null,s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(f=s.memoizedState.cachePool.pool),f!==l&&(s.flags|=2048),o!==null&&ce(ma),null;case 24:return l=null,o!==null&&(l=o.memoizedState.cache),s.memoizedState.cache!==l&&(s.flags|=2048),Ys(zi),ai(s),null;case 25:return null;case 30:return null}throw Error(i(156,s.tag))}function nM(o,s){switch(jh(s),s.tag){case 1:return o=s.flags,o&65536?(s.flags=o&-65537|128,s):null;case 3:return Ys(zi),ye(),o=s.flags,(o&65536)!==0&&(o&128)===0?(s.flags=o&-65537|128,s):null;case 26:case 27:case 5:return Oe(s),null;case 31:if(s.memoizedState!==null){if(Fo(s),s.alternate===null)throw Error(i(340));fa()}return o=s.flags,o&65536?(s.flags=o&-65537|128,s):null;case 13:if(Fo(s),o=s.memoizedState,o!==null&&o.dehydrated!==null){if(s.alternate===null)throw Error(i(340));fa()}return o=s.flags,o&65536?(s.flags=o&-65537|128,s):null;case 19:return ce(Ai),null;case 4:return ye(),null;case 10:return Ys(s.type),null;case 22:case 23:return Fo(s),sp(),o!==null&&ce(ma),o=s.flags,o&65536?(s.flags=o&-65537|128,s):null;case 24:return Ys(zi),null;case 25:return null;default:return null}}function wy(o,s){switch(jh(s),s.tag){case 3:Ys(zi),ye();break;case 26:case 27:case 5:Oe(s);break;case 4:ye();break;case 31:s.memoizedState!==null&&Fo(s);break;case 13:Fo(s);break;case 19:ce(Ai);break;case 10:Ys(s.type);break;case 22:case 23:Fo(s),sp(),o!==null&&ce(ma);break;case 24:Ys(zi)}}function Hc(o,s){try{var l=s.updateQueue,f=l!==null?l.lastEffect:null;if(f!==null){var _=f.next;l=_;do{if((l.tag&o)===o){f=void 0;var b=l.create,R=l.inst;f=b(),R.destroy=f}l=l.next}while(l!==_)}}catch(O){Wn(s,s.return,O)}}function Dr(o,s,l){try{var f=s.updateQueue,_=f!==null?f.lastEffect:null;if(_!==null){var b=_.next;f=b;do{if((f.tag&o)===o){var R=f.inst,O=R.destroy;if(O!==void 0){R.destroy=void 0,_=s;var ie=l,ze=O;try{ze()}catch(ot){Wn(_,ie,ot)}}}f=f.next}while(f!==b)}}catch(ot){Wn(s,s.return,ot)}}function My(o){var s=o.updateQueue;if(s!==null){var l=o.stateNode;try{gx(s,l)}catch(f){Wn(o,o.return,f)}}}function Cy(o,s,l){l.props=_a(o.type,o.memoizedProps),l.state=o.memoizedState;try{l.componentWillUnmount()}catch(f){Wn(o,s,f)}}function Gc(o,s){try{var l=o.ref;if(l!==null){switch(o.tag){case 26:case 27:case 5:var f=o.stateNode;break;case 30:f=o.stateNode;break;default:f=o.stateNode}typeof l=="function"?o.refCleanup=l(f):l.current=f}}catch(_){Wn(o,s,_)}}function Us(o,s){var l=o.ref,f=o.refCleanup;if(l!==null)if(typeof f=="function")try{f()}catch(_){Wn(o,s,_)}finally{o.refCleanup=null,o=o.alternate,o!=null&&(o.refCleanup=null)}else if(typeof l=="function")try{l(null)}catch(_){Wn(o,s,_)}else l.current=null}function Ay(o){var s=o.type,l=o.memoizedProps,f=o.stateNode;try{e:switch(s){case"button":case"input":case"select":case"textarea":l.autoFocus&&f.focus();break e;case"img":l.src?f.src=l.src:l.srcSet&&(f.srcset=l.srcSet)}}catch(_){Wn(o,o.return,_)}}function Pp(o,s,l){try{var f=o.stateNode;EM(f,o.type,l,s),f[fi]=s}catch(_){Wn(o,o.return,_)}}function Ry(o){return o.tag===5||o.tag===3||o.tag===26||o.tag===27&&Or(o.type)||o.tag===4}function Fp(o){e:for(;;){for(;o.sibling===null;){if(o.return===null||Ry(o.return))return null;o=o.return}for(o.sibling.return=o.return,o=o.sibling;o.tag!==5&&o.tag!==6&&o.tag!==18;){if(o.tag===27&&Or(o.type)||o.flags&2||o.child===null||o.tag===4)continue e;o.child.return=o,o=o.child}if(!(o.flags&2))return o.stateNode}}function Op(o,s,l){var f=o.tag;if(f===5||f===6)o=o.stateNode,s?(l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l).insertBefore(o,s):(s=l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l,s.appendChild(o),l=l._reactRootContainer,l!=null||s.onclick!==null||(s.onclick=wt));else if(f!==4&&(f===27&&Or(o.type)&&(l=o.stateNode,s=null),o=o.child,o!==null))for(Op(o,s,l),o=o.sibling;o!==null;)Op(o,s,l),o=o.sibling}function _d(o,s,l){var f=o.tag;if(f===5||f===6)o=o.stateNode,s?l.insertBefore(o,s):l.appendChild(o);else if(f!==4&&(f===27&&Or(o.type)&&(l=o.stateNode),o=o.child,o!==null))for(_d(o,s,l),o=o.sibling;o!==null;)_d(o,s,l),o=o.sibling}function Ny(o){var s=o.stateNode,l=o.memoizedProps;try{for(var f=o.type,_=s.attributes;_.length;)s.removeAttributeNode(_[0]);ao(s,f,l),s[fn]=o,s[fi]=l}catch(b){Wn(o,o.return,b)}}var er=!1,Oi=!1,Bp=!1,Iy=typeof WeakSet=="function"?WeakSet:Set,Zi=null;function iM(o,s){if(o=o.containerInfo,am=Vd,o=Gv(o),Lh(o)){if("selectionStart"in o)var l={start:o.selectionStart,end:o.selectionEnd};else e:{l=(l=o.ownerDocument)&&l.defaultView||window;var f=l.getSelection&&l.getSelection();if(f&&f.rangeCount!==0){l=f.anchorNode;var _=f.anchorOffset,b=f.focusNode;f=f.focusOffset;try{l.nodeType,b.nodeType}catch{l=null;break e}var R=0,O=-1,ie=-1,ze=0,ot=0,ut=o,Ge=null;t:for(;;){for(var Qe;ut!==l||_!==0&&ut.nodeType!==3||(O=R+_),ut!==b||f!==0&&ut.nodeType!==3||(ie=R+f),ut.nodeType===3&&(R+=ut.nodeValue.length),(Qe=ut.firstChild)!==null;)Ge=ut,ut=Qe;for(;;){if(ut===o)break t;if(Ge===l&&++ze===_&&(O=R),Ge===b&&++ot===f&&(ie=R),(Qe=ut.nextSibling)!==null)break;ut=Ge,Ge=ut.parentNode}ut=Qe}l=O===-1||ie===-1?null:{start:O,end:ie}}else l=null}l=l||{start:0,end:0}}else l=null;for(lm={focusedElem:o,selectionRange:l},Vd=!1,Zi=s;Zi!==null;)if(s=Zi,o=s.child,(s.subtreeFlags&1028)!==0&&o!==null)o.return=s,Zi=o;else for(;Zi!==null;){switch(s=Zi,b=s.alternate,o=s.flags,s.tag){case 0:if((o&4)!==0&&(o=s.updateQueue,o=o!==null?o.events:null,o!==null))for(l=0;l title"))),ao(b,f,l),b[fn]=o,ge(b),f=b;break e;case"link":var R=P_("link","href",_).get(f+(l.href||""));if(R){for(var O=0;OZn&&(R=Zn,Zn=Gt,Gt=R);var we=Vv(O,Gt),he=Vv(O,Zn);if(we&&he&&(Qe.rangeCount!==1||Qe.anchorNode!==we.node||Qe.anchorOffset!==we.offset||Qe.focusNode!==he.node||Qe.focusOffset!==he.offset)){var ke=ut.createRange();ke.setStart(we.node,we.offset),Qe.removeAllRanges(),Gt>Zn?(Qe.addRange(ke),Qe.extend(he.node,he.offset)):(ke.setEnd(he.node,he.offset),Qe.addRange(ke))}}}}for(ut=[],Qe=O;Qe=Qe.parentNode;)Qe.nodeType===1&&ut.push({element:Qe,left:Qe.scrollLeft,top:Qe.scrollTop});for(typeof O.focus=="function"&&O.focus(),O=0;Ol?32:l,X.T=null,l=$p,$p=null;var b=zr,R=sr;if(Wi=0,_l=zr=null,sr=0,(Fn&6)!==0)throw Error(i(331));var O=Fn;if(Fn|=4,Hy(b.current),Oy(b,b.current,R,l),Fn=O,Yc(0,!1),re&&typeof re.onPostCommitFiberRoot=="function")try{re.onPostCommitFiberRoot(B,b)}catch{}return!0}finally{_e.p=_,X.T=f,r_(o,s)}}function l_(o,s,l){s=es(l,s),s=Mp(o.stateNode,s,2),o=Rr(o,s,2),o!==null&&(Be(o,2),ks(o))}function Wn(o,s,l){if(o.tag===3)l_(o,o,l);else for(;s!==null;){if(s.tag===3){l_(s,o,l);break}else if(s.tag===1){var f=s.stateNode;if(typeof s.type.getDerivedStateFromError=="function"||typeof f.componentDidCatch=="function"&&(kr===null||!kr.has(f))){o=es(l,o),l=cy(2),f=Rr(s,l,2),f!==null&&(uy(l,f,s,o),Be(f,2),ks(f));break}}s=s.return}}function Kp(o,s,l){var f=o.pingCache;if(f===null){f=o.pingCache=new rM;var _=new Set;f.set(s,_)}else _=f.get(s),_===void 0&&(_=new Set,f.set(s,_));_.has(l)||(Gp=!0,_.add(l),o=dM.bind(null,o,s,l),s.then(o,o))}function dM(o,s,l){var f=o.pingCache;f!==null&&f.delete(s),o.pingedLanes|=o.suspendedLanes&l,o.warmLanes&=~l,ei===o&&(xn&l)===l&&(Ei===4||Ei===3&&(xn&62914560)===xn&&300>ae()-Td?(Fn&2)===0&&bl(o,0):jp|=l,yl===xn&&(yl=0)),ks(o)}function c_(o,s){s===0&&(s=Te()),o=ua(o,s),o!==null&&(Be(o,s),ks(o))}function fM(o){var s=o.memoizedState,l=0;s!==null&&(l=s.retryLane),c_(o,l)}function hM(o,s){var l=0;switch(o.tag){case 31:case 13:var f=o.stateNode,_=o.memoizedState;_!==null&&(l=_.retryLane);break;case 19:f=o.stateNode;break;case 22:f=o.stateNode._retryCache;break;default:throw Error(i(314))}f!==null&&f.delete(s),c_(o,l)}function pM(o,s){return qe(o,s)}var Nd=null,Tl=null,Zp=!1,Id=!1,Qp=!1,Fr=0;function ks(o){o!==Tl&&o.next===null&&(Tl===null?Nd=Tl=o:Tl=Tl.next=o),Id=!0,Zp||(Zp=!0,gM())}function Yc(o,s){if(!Qp&&Id){Qp=!0;do for(var l=!1,f=Nd;f!==null;){if(o!==0){var _=f.pendingLanes;if(_===0)var b=0;else{var R=f.suspendedLanes,O=f.pingedLanes;b=(1<<31-me(42|o)+1)-1,b&=_&~(R&~O),b=b&201326741?b&201326741|1:b?b|2:0}b!==0&&(l=!0,h_(f,b))}else b=xn,b=Je(f,f===ei?b:0,f.cancelPendingCommit!==null||f.timeoutHandle!==-1),(b&3)===0||ht(f,b)||(l=!0,h_(f,b));f=f.next}while(l);Qp=!1}}function mM(){u_()}function u_(){Id=Zp=!1;var o=0;Fr!==0&&MM()&&(o=Fr);for(var s=ae(),l=null,f=Nd;f!==null;){var _=f.next,b=d_(f,s);b===0?(f.next=null,l===null?Nd=_:l.next=_,_===null&&(Tl=l)):(l=f,(o!==0||(b&3)!==0)&&(Id=!0)),f=_}Wi!==0&&Wi!==5||Yc(o),Fr!==0&&(Fr=0)}function d_(o,s){for(var l=o.suspendedLanes,f=o.pingedLanes,_=o.expirationTimes,b=o.pendingLanes&-62914561;0O)break;var ot=ie.transferSize,ut=ie.initiatorType;ot&&b_(ut)&&(ie=ie.responseEnd,R+=ot*(ie"u"?null:document;function L_(o,s,l){var f=El;if(f&&typeof s=="string"&&s){var _=hi(s);_='link[rel="'+o+'"][href="'+_+'"]',typeof l=="string"&&(_+='[crossorigin="'+l+'"]'),D_.has(_)||(D_.add(_),o={rel:o,crossOrigin:l,href:s},f.querySelector(_)===null&&(s=f.createElement("link"),ao(s,"link",o),ge(s),f.head.appendChild(s)))}}function kM(o){rr.D(o),L_("dns-prefetch",o,null)}function zM(o,s){rr.C(o,s),L_("preconnect",o,s)}function PM(o,s,l){rr.L(o,s,l);var f=El;if(f&&o&&s){var _='link[rel="preload"][as="'+hi(s)+'"]';s==="image"&&l&&l.imageSrcSet?(_+='[imagesrcset="'+hi(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(_+='[imagesizes="'+hi(l.imageSizes)+'"]')):_+='[href="'+hi(o)+'"]';var b=_;switch(s){case"style":b=wl(o);break;case"script":b=Ml(o)}rs.has(b)||(o=v({rel:"preload",href:s==="image"&&l&&l.imageSrcSet?void 0:o,as:s},l),rs.set(b,o),f.querySelector(_)!==null||s==="style"&&f.querySelector(Qc(b))||s==="script"&&f.querySelector(eu(b))||(s=f.createElement("link"),ao(s,"link",o),ge(s),f.head.appendChild(s)))}}function FM(o,s){rr.m(o,s);var l=El;if(l&&o){var f=s&&typeof s.as=="string"?s.as:"script",_='link[rel="modulepreload"][as="'+hi(f)+'"][href="'+hi(o)+'"]',b=_;switch(f){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":b=Ml(o)}if(!rs.has(b)&&(o=v({rel:"modulepreload",href:o},s),rs.set(b,o),l.querySelector(_)===null)){switch(f){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(eu(b)))return}f=l.createElement("link"),ao(f,"link",o),ge(f),l.head.appendChild(f)}}}function OM(o,s,l){rr.S(o,s,l);var f=El;if(f&&o){var _=Ve(f).hoistableStyles,b=wl(o);s=s||"default";var R=_.get(b);if(!R){var O={loading:0,preload:null};if(R=f.querySelector(Qc(b)))O.loading=5;else{o=v({rel:"stylesheet",href:o,"data-precedence":s},l),(l=rs.get(b))&&mm(o,l);var ie=R=f.createElement("link");ge(ie),ao(ie,"link",o),ie._p=new Promise(function(ze,ot){ie.onload=ze,ie.onerror=ot}),ie.addEventListener("load",function(){O.loading|=1}),ie.addEventListener("error",function(){O.loading|=2}),O.loading|=4,zd(R,s,f)}R={type:"stylesheet",instance:R,count:1,state:O},_.set(b,R)}}}function BM(o,s){rr.X(o,s);var l=El;if(l&&o){var f=Ve(l).hoistableScripts,_=Ml(o),b=f.get(_);b||(b=l.querySelector(eu(_)),b||(o=v({src:o,async:!0},s),(s=rs.get(_))&&gm(o,s),b=l.createElement("script"),ge(b),ao(b,"link",o),l.head.appendChild(b)),b={type:"script",instance:b,count:1,state:null},f.set(_,b))}}function VM(o,s){rr.M(o,s);var l=El;if(l&&o){var f=Ve(l).hoistableScripts,_=Ml(o),b=f.get(_);b||(b=l.querySelector(eu(_)),b||(o=v({src:o,async:!0,type:"module"},s),(s=rs.get(_))&&gm(o,s),b=l.createElement("script"),ge(b),ao(b,"link",o),l.head.appendChild(b)),b={type:"script",instance:b,count:1,state:null},f.set(_,b))}}function U_(o,s,l,f){var _=(_=nt.current)?kd(_):null;if(!_)throw Error(i(446));switch(o){case"meta":case"title":return null;case"style":return typeof l.precedence=="string"&&typeof l.href=="string"?(s=wl(l.href),l=Ve(_).hoistableStyles,f=l.get(s),f||(f={type:"style",instance:null,count:0,state:null},l.set(s,f)),f):{type:"void",instance:null,count:0,state:null};case"link":if(l.rel==="stylesheet"&&typeof l.href=="string"&&typeof l.precedence=="string"){o=wl(l.href);var b=Ve(_).hoistableStyles,R=b.get(o);if(R||(_=_.ownerDocument||_,R={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},b.set(o,R),(b=_.querySelector(Qc(o)))&&!b._p&&(R.instance=b,R.state.loading=5),rs.has(o)||(l={rel:"preload",as:"style",href:l.href,crossOrigin:l.crossOrigin,integrity:l.integrity,media:l.media,hrefLang:l.hrefLang,referrerPolicy:l.referrerPolicy},rs.set(o,l),b||HM(_,o,l,R.state))),s&&f===null)throw Error(i(528,""));return R}if(s&&f!==null)throw Error(i(529,""));return null;case"script":return s=l.async,l=l.src,typeof l=="string"&&s&&typeof s!="function"&&typeof s!="symbol"?(s=Ml(l),l=Ve(_).hoistableScripts,f=l.get(s),f||(f={type:"script",instance:null,count:0,state:null},l.set(s,f)),f):{type:"void",instance:null,count:0,state:null};default:throw Error(i(444,o))}}function wl(o){return'href="'+hi(o)+'"'}function Qc(o){return'link[rel="stylesheet"]['+o+"]"}function k_(o){return v({},o,{"data-precedence":o.precedence,precedence:null})}function HM(o,s,l,f){o.querySelector('link[rel="preload"][as="style"]['+s+"]")?f.loading=1:(s=o.createElement("link"),f.preload=s,s.addEventListener("load",function(){return f.loading|=1}),s.addEventListener("error",function(){return f.loading|=2}),ao(s,"link",l),ge(s),o.head.appendChild(s))}function Ml(o){return'[src="'+hi(o)+'"]'}function eu(o){return"script[async]"+o}function z_(o,s,l){if(s.count++,s.instance===null)switch(s.type){case"style":var f=o.querySelector('style[data-href~="'+hi(l.href)+'"]');if(f)return s.instance=f,ge(f),f;var _=v({},l,{"data-href":l.href,"data-precedence":l.precedence,href:null,precedence:null});return f=(o.ownerDocument||o).createElement("style"),ge(f),ao(f,"style",_),zd(f,l.precedence,o),s.instance=f;case"stylesheet":_=wl(l.href);var b=o.querySelector(Qc(_));if(b)return s.state.loading|=4,s.instance=b,ge(b),b;f=k_(l),(_=rs.get(_))&&mm(f,_),b=(o.ownerDocument||o).createElement("link"),ge(b);var R=b;return R._p=new Promise(function(O,ie){R.onload=O,R.onerror=ie}),ao(b,"link",f),s.state.loading|=4,zd(b,l.precedence,o),s.instance=b;case"script":return b=Ml(l.src),(_=o.querySelector(eu(b)))?(s.instance=_,ge(_),_):(f=l,(_=rs.get(b))&&(f=v({},l),gm(f,_)),o=o.ownerDocument||o,_=o.createElement("script"),ge(_),ao(_,"link",f),o.head.appendChild(_),s.instance=_);case"void":return null;default:throw Error(i(443,s.type))}else s.type==="stylesheet"&&(s.state.loading&4)===0&&(f=s.instance,s.state.loading|=4,zd(f,l.precedence,o));return s.instance}function zd(o,s,l){for(var f=l.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),_=f.length?f[f.length-1]:null,b=_,R=0;R title"):null)}function GM(o,s,l){if(l===1||s.itemProp!=null)return!1;switch(o){case"meta":case"title":return!0;case"style":if(typeof s.precedence!="string"||typeof s.href!="string"||s.href==="")break;return!0;case"link":if(typeof s.rel!="string"||typeof s.href!="string"||s.href===""||s.onLoad||s.onError)break;return s.rel==="stylesheet"?(o=s.disabled,typeof s.precedence=="string"&&o==null):!0;case"script":if(s.async&&typeof s.async!="function"&&typeof s.async!="symbol"&&!s.onLoad&&!s.onError&&s.src&&typeof s.src=="string")return!0}return!1}function O_(o){return!(o.type==="stylesheet"&&(o.state.loading&3)===0)}function jM(o,s,l,f){if(l.type==="stylesheet"&&(typeof f.media!="string"||matchMedia(f.media).matches!==!1)&&(l.state.loading&4)===0){if(l.instance===null){var _=wl(f.href),b=s.querySelector(Qc(_));if(b){s=b._p,s!==null&&typeof s=="object"&&typeof s.then=="function"&&(o.count++,o=Fd.bind(o),s.then(o,o)),l.state.loading|=4,l.instance=b,ge(b);return}b=s.ownerDocument||s,f=k_(f),(_=rs.get(_))&&mm(f,_),b=b.createElement("link"),ge(b);var R=b;R._p=new Promise(function(O,ie){R.onload=O,R.onerror=ie}),ao(b,"link",f),l.instance=b}o.stylesheets===null&&(o.stylesheets=new Map),o.stylesheets.set(l,s),(s=l.state.preload)&&(l.state.loading&3)===0&&(o.count++,l=Fd.bind(o),s.addEventListener("load",l),s.addEventListener("error",l))}}var vm=0;function qM(o,s){return o.stylesheets&&o.count===0&&Bd(o,o.stylesheets),0vm?50:800)+s);return o.unsuspend=l,function(){o.unsuspend=null,clearTimeout(f),clearTimeout(_)}}:null}function Fd(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Bd(this,this.stylesheets);else if(this.unsuspend){var o=this.unsuspend;this.unsuspend=null,o()}}}var Od=null;function Bd(o,s){o.stylesheets=null,o.unsuspend!==null&&(o.count++,Od=new Map,s.forEach(WM,o),Od=null,Fd.call(o))}function WM(o,s){if(!(s.state.loading&4)){var l=Od.get(o);if(l)var f=l.get(null);else{l=new Map,Od.set(o,l);for(var _=o.querySelectorAll("link[data-precedence],style[data-precedence]"),b=0;b<_.length;b++){var R=_[b];(R.nodeName==="LINK"||R.getAttribute("media")!=="not all")&&(l.set(R.dataset.precedence,R),f=R)}f&&l.set(null,f)}_=s.instance,R=_.getAttribute("data-precedence"),b=l.get(R)||f,b===f&&l.set(null,_),l.set(R,_),this.count++,f=Fd.bind(this),_.addEventListener("load",f),_.addEventListener("error",f),b?b.parentNode.insertBefore(_,b.nextSibling):(o=o.nodeType===9?o.head:o,o.insertBefore(_,o.firstChild)),s.state.loading|=4}}var tu={$$typeof:L,Provider:null,Consumer:null,_currentValue:ne,_currentValue2:ne,_threadCount:0};function $M(o,s,l,f,_,b,R,O,ie){this.tag=1,this.containerInfo=o,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=Ke(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ke(0),this.hiddenUpdates=Ke(null),this.identifierPrefix=f,this.onUncaughtError=_,this.onCaughtError=b,this.onRecoverableError=R,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=ie,this.incompleteTransitions=new Map}function B_(o,s,l,f,_,b,R,O,ie,ze,ot,ut){return o=new $M(o,s,l,R,ie,ze,ot,ut,O),s=1,b===!0&&(s|=24),b=zo(3,null,null,s),o.current=b,b.stateNode=o,s=Jh(),s.refCount++,o.pooledCache=s,s.refCount++,b.memoizedState={element:f,isDehydrated:l,cache:s},ep(b),o}function V_(o){return o?(o=il,o):il}function H_(o,s,l,f,_,b){_=V_(_),f.context===null?f.context=_:f.pendingContext=_,f=Ar(s),f.payload={element:l},b=b===void 0?null:b,b!==null&&(f.callback=b),l=Rr(o,f,s),l!==null&&(Ro(l,o,s),Lc(l,o,s))}function G_(o,s){if(o=o.memoizedState,o!==null&&o.dehydrated!==null){var l=o.retryLane;o.retryLane=l!==0&&l"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(e){console.error(e)}}return t(),Mm.exports=lC(),Mm.exports}var uC=cC();const dC=fT(uC),fC="modulepreload",hC=function(t){return"/"+t},cb={},v0=function(e,n,i){let r=Promise.resolve();if(n&&n.length>0){let h=function(d){return Promise.all(d.map(g=>Promise.resolve(g).then(v=>({status:"fulfilled",value:v}),v=>({status:"rejected",reason:v}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),u=c?.nonce||c?.getAttribute("nonce");r=h(n.map(d=>{if(d=hC(d),d in cb)return;cb[d]=!0;const g=d.endsWith(".css"),v=g?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${v}`))return;const y=document.createElement("link");if(y.rel=g?"stylesheet":fC,g||(y.as="script"),y.crossOrigin="",y.href=d,u&&y.setAttribute("nonce",u),document.head.appendChild(y),g)return new Promise((S,T)=>{y.addEventListener("load",S),y.addEventListener("error",()=>T(new Error(`Unable to preload CSS for ${d}`)))})}))}function a(c){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=c,window.dispatchEvent(u),!u.defaultPrevented)throw c}return r.then(c=>{for(const u of c||[])u.status==="rejected"&&a(u.reason);return e().catch(a)})};const pC=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),mC=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,i)=>i?i.toUpperCase():n.toLowerCase()),ub=t=>{const e=mC(t);return e.charAt(0).toUpperCase()+e.slice(1)},hT=(...t)=>t.filter((e,n,i)=>!!e&&e.trim()!==""&&i.indexOf(e)===n).join(" ").trim(),gC=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0};var vC={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const xC=Ae.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:i,className:r="",children:a,iconNode:c,...u},h)=>Ae.createElement("svg",{ref:h,...vC,width:e,height:e,stroke:t,strokeWidth:i?Number(n)*24/Number(e):n,className:hT("lucide",r),...!a&&!gC(u)&&{"aria-hidden":"true"},...u},[...c.map(([d,g])=>Ae.createElement(d,g)),...Array.isArray(a)?a:[a]]));const It=(t,e)=>{const n=Ae.forwardRef(({className:i,...r},a)=>Ae.createElement(xC,{ref:a,iconNode:e,className:hT(`lucide-${pC(ub(t))}`,`lucide-${t}`,i),...r}));return n.displayName=ub(t),n};const yC=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],_C=It("activity",yC);const bC=[["rect",{width:"14",height:"6",x:"5",y:"16",rx:"2",key:"1i8z2d"}],["rect",{width:"10",height:"6",x:"7",y:"2",rx:"2",key:"ypihtt"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],db=It("align-vertical-justify-center",bC);const SC=[["rect",{width:"14",height:"6",x:"5",y:"12",rx:"2",key:"4l4tp2"}],["rect",{width:"10",height:"6",x:"7",y:"2",rx:"2",key:"ypihtt"}],["path",{d:"M2 22h20",key:"272qi7"}]],TC=It("align-vertical-justify-end",SC);const EC=[["rect",{width:"14",height:"6",x:"5",y:"16",rx:"2",key:"1i8z2d"}],["rect",{width:"10",height:"6",x:"7",y:"6",rx:"2",key:"13squh"}],["path",{d:"M2 2h20",key:"1ennik"}]],wC=It("align-vertical-justify-start",EC);const MC=[["path",{d:"M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8",key:"mg9rjx"}]],Nm=It("bold",MC);const CC=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],pT=It("check",CC);const AC=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],zu=It("chevron-down",AC);const RC=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],x0=It("chevron-up",RC);const NC=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],IC=It("circle-alert",NC);const DC=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}]],LC=It("clipboard",DC);const UC=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],kC=It("copy",UC);const zC=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],PC=It("disc",zC);const FC=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],fb=It("download",FC);const OC=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],yu=It("eye-off",OC);const BC=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],_u=It("eye",BC);const VC=[["path",{d:"M12 6a2 2 0 0 1 3.414-1.414l6 6a2 2 0 0 1 0 2.828l-6 6A2 2 0 0 1 12 18z",key:"b19h5q"}],["path",{d:"M2 6a2 2 0 0 1 3.414-1.414l6 6a2 2 0 0 1 0 2.828l-6 6A2 2 0 0 1 2 18z",key:"h7h5ge"}]],HC=It("fast-forward",VC);const GC=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]],jC=It("file-down",GC);const qC=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Xf=It("file-text",qC);const WC=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M3 7.5h4",key:"zfgn84"}],["path",{d:"M3 12h18",key:"1i2n21"}],["path",{d:"M3 16.5h4",key:"1230mu"}],["path",{d:"M17 3v18",key:"in4fa5"}],["path",{d:"M17 7.5h4",key:"myr1c1"}],["path",{d:"M17 16.5h4",key:"go4c1d"}]],mT=It("film",WC);const $C=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],XC=It("folder",$C);const YC=[["circle",{cx:"12",cy:"9",r:"1",key:"124mty"}],["circle",{cx:"19",cy:"9",r:"1",key:"1ruzo2"}],["circle",{cx:"5",cy:"9",r:"1",key:"1a8b28"}],["circle",{cx:"12",cy:"15",r:"1",key:"1e56xg"}],["circle",{cx:"19",cy:"15",r:"1",key:"1a92ep"}],["circle",{cx:"5",cy:"15",r:"1",key:"5r1jwy"}]],Xd=It("grip-horizontal",YC);const JC=[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]],KC=It("grip-vertical",JC);const ZC=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],hb=It("image",ZC);const QC=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],eA=It("info",QC);const tA=[["line",{x1:"19",x2:"10",y1:"4",y2:"4",key:"15jd3p"}],["line",{x1:"14",x2:"5",y1:"20",y2:"20",key:"bu0au3"}],["line",{x1:"15",x2:"9",y1:"4",y2:"20",key:"uljnxc"}]],Im=It("italic",tA);const nA=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],iA=It("key",nA);const oA=[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]],Yf=It("keyboard",oA);const sA=[["path",{d:"M16 5H3",key:"m91uny"}],["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M11 19H3",key:"zflm78"}],["path",{d:"M21 16V5",key:"yxg4q8"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]],Jf=It("list-music",sA);const rA=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],pb=It("loader-circle",rA);const aA=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]],Au=It("maximize",aA);const lA=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]],mb=It("minimize",lA);const cA=[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]],$l=It("music",cA);const uA=[["path",{d:"M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z",key:"e79jfc"}],["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}]],dA=It("palette",uA);const fA=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M9 21V9",key:"1oto5p"}]],hA=It("panels-top-left",fA);const pA=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]],gT=It("pause",pA);const mA=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],y0=It("play",mA);const gA=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],vT=It("plus",gA);const vA=[["path",{d:"m15 14 5-5-5-5",key:"12vg1m"}],["path",{d:"M20 9H9.5A5.5 5.5 0 0 0 4 14.5A5.5 5.5 0 0 0 9.5 20H13",key:"6uklza"}]],xA=It("redo-2",vA);const yA=[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}],["path",{d:"M11 10h1v4",key:"70cz1p"}]],_A=It("repeat-1",yA);const bA=[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]],gb=It("repeat",bA);const SA=[["path",{d:"M12 6a2 2 0 0 0-3.414-1.414l-6 6a2 2 0 0 0 0 2.828l6 6A2 2 0 0 0 12 18z",key:"2a1g8i"}],["path",{d:"M22 6a2 2 0 0 0-3.414-1.414l-6 6a2 2 0 0 0 0 2.828l6 6A2 2 0 0 0 22 18z",key:"rg3s36"}]],TA=It("rewind",SA);const EA=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],Kf=It("rotate-ccw",EA);const wA=[["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M8.12 8.12 12 12",key:"1alkpv"}],["path",{d:"M20 4 8.12 15.88",key:"xgtan2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M14.8 14.8 20 20",key:"ptml3r"}]],MA=It("scissors",wA);const CA=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],AA=It("search",CA);const RA=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Gl=It("settings",RA);const NA=[["path",{d:"m18 14 4 4-4 4",key:"10pe0f"}],["path",{d:"m18 2 4 4-4 4",key:"pucp1d"}],["path",{d:"M2 18h1.973a4 4 0 0 0 3.3-1.7l5.454-8.6a4 4 0 0 1 3.3-1.7H22",key:"1ailkh"}],["path",{d:"M2 6h1.972a4 4 0 0 1 3.6 2.2",key:"km57vx"}],["path",{d:"M22 18h-6.041a4 4 0 0 1-3.3-1.8l-.359-.45",key:"os18l9"}]],IA=It("shuffle",NA);const DA=[["path",{d:"M17.971 4.285A2 2 0 0 1 21 6v12a2 2 0 0 1-3.029 1.715l-9.997-5.998a2 2 0 0 1-.003-3.432z",key:"15892j"}],["path",{d:"M3 20V4",key:"1ptbpl"}]],LA=It("skip-back",DA);const UA=[["path",{d:"M21 4v16",key:"7j8fe9"}],["path",{d:"M6.029 4.285A2 2 0 0 0 3 6v12a2 2 0 0 0 3.029 1.715l9.997-5.998a2 2 0 0 0 .003-3.432z",key:"zs4d6"}]],kA=It("skip-forward",UA);const zA=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],_0=It("sparkles",zA);const PA=[["path",{d:"M16 3h5v5",key:"1806ms"}],["path",{d:"M8 3H3v5",key:"15dfkv"}],["path",{d:"M12 22v-8.3a4 4 0 0 0-1.172-2.872L3 3",key:"1qrqzj"}],["path",{d:"m15 9 6-6",key:"ko1vev"}]],FA=It("split",PA);const OA=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],b0=It("square",OA);const BA=[["path",{d:"M16 4H9a3 3 0 0 0-2.83 4",key:"43sutm"}],["path",{d:"M14 12a4 4 0 0 1 0 8H6",key:"nlfj13"}],["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}]],VA=It("strikethrough",BA);const HA=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Ql=It("trash-2",HA);const GA=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],jA=It("triangle-alert",GA);const qA=[["path",{d:"M12 4v16",key:"1654pz"}],["path",{d:"M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2",key:"e0r10z"}],["path",{d:"M9 20h6",key:"s66wpe"}]],Qr=It("type",qA);const WA=[["path",{d:"M6 4v6a6 6 0 0 0 12 0V4",key:"9kb039"}],["line",{x1:"4",x2:"20",y1:"20",y2:"20",key:"nun2al"}]],$A=It("underline",WA);const XA=[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]],YA=It("undo-2",XA);const JA=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],cs=It("upload",JA);const KA=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],ZA=It("user",KA);const QA=[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]],Ru=It("video",QA);const eR=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]],Zr=It("volume-2",eR);const tR=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]],jl=It("volume-x",tR);const nR=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Wo=It("x",nR);const iR=[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]],oR=It("zoom-in",iR);const sR=[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]],rR=It("zoom-out",sR);var lo=(t=>(t.PLAYER="PLAYER",t.EDITOR="EDITOR",t))(lo||{});const Bg=t=>{const e=/([\u4E00-\u9FFF\u3040-\u309F\u30A0-\u30FF\uFF00-\uFFEF])\s+([\u4E00-\u9FFF\u3040-\u309F\u30A0-\u30FF\uFF00-\uFFEF])/g;return t.replace(e,"$1$2")},bu=t=>{if(!t)return 0;const n=t.replace(",",".").trim().split(":");let i=0;return n.length===3?(i+=parseInt(n[0],10)*3600,i+=parseInt(n[1],10)*60,i+=parseFloat(n[2])):n.length===2?(i+=parseInt(n[0],10)*60,i+=parseFloat(n[1])):n.length===1&&(i+=parseFloat(n[0])),isNaN(i)?0:i},Ps=t=>{const e=Math.floor(t/60),n=Math.floor(t%60);return`${e}:${n.toString().padStart(2,"0")}`},ea=t=>{const e=t.split(` +`),n=[],i=/\[(\d{2}):(\d{2})(\.(\d{2,3}))?\]/g,r=/<(\d{2}):(\d{2})(\.(\d{2,3}))?>/g;return e.forEach(a=>{const c=[...a.matchAll(i)];if(c.length>0){let u=a.replace(i,"").trim();u=u.replace(/\\n/g,` +`);const h=[...u.matchAll(r)];let d,g=u.replace(r,"").replace(/ +/g," ").trim();if(h.length>0){d=[];for(let v=0;v{W&&d.push({text:W,startTime:E,endTime:0}),V{const y=parseInt(v[1],10),S=parseInt(v[2],10),T=v[4];let A=y*60+S;T&&(T.length===2?A+=parseInt(T,10)/100:(T.length,A+=parseInt(T,10)/1e3)),n.push({time:A,text:g,words:d})})}}),n.sort((a,c)=>a.time-c.time)},ta=t=>{const n=t.replace(/\r\n/g,` +`).replace(/\r/g,` +`).split(` + +`),i=[],r=/(\d{2}):(\d{2}):(\d{2}),(\d{3})/,a=c=>{const u=c.match(r);if(u){const h=parseInt(u[1],10),d=parseInt(u[2],10),g=parseInt(u[3],10),v=parseInt(u[4],10);return h*3600+d*60+g+v/1e3}return null};return n.forEach(c=>{const u=c.split(` +`);if(u.length>=3){const h=u[1],g=u.slice(2).join(" ").trim(),v=Bg(g),y=h.split(" --> ");if(y.length>=2){const S=a(y[0]),T=a(y[1]);S!==null&&v&&i.push({time:S,text:v,endTime:T!==null?T:void 0})}}}),i},Pa=t=>{const e=[];try{const i=new DOMParser().parseFromString(t,"text/xml"),a=Array.from(i.getElementsByTagName("*")).filter(h=>h.localName==="p"),c=h=>{if(!h)return;const d=h.trim();return d.endsWith("ms")?parseFloat(d.slice(0,-2))/1e3:d.endsWith("s")?parseFloat(d.slice(0,-1)):bu(d)},u=(h,d)=>{if(h.hasAttribute(d))return h.getAttribute(d);for(let g=0;gI.localName==="span");for(let I=0;I0){const H=c(D),Q=c(W);H!==void 0&&Q!==void 0&&A.push({text:V,startTime:H,endTime:Q})}}S!==void 0&&e.push({time:S,text:y,endTime:T,words:A.length>0?A:void 0})}}}catch(n){console.error("Failed to parse TTML",n)}return e.sort((n,i)=>n.time-i.time)},aR=t=>{try{const e=JSON.parse(t);if(Array.isArray(e)&&e.every(i=>typeof i=="object"&&i!==null&&typeof i.time=="number"&&typeof i.text=="string"))return e}catch(e){console.warn("Failed to parse JSON lyrics",e)}return[]},Fa=t=>{const n=t.replace(/\r\n/g,` +`).replace(/\r/g,` +`).split(` +`),i=[],r=/(\d{2}:)?(\d{2}):(\d{2})\.(\d{3})/,a=u=>{const h=u.match(r);if(h){const d=h[1]?parseInt(h[1].replace(":",""),10):0,g=parseInt(h[2],10),v=parseInt(h[3],10),y=parseInt(h[4],10);return d*3600+g*60+v+y/1e3}return null};let c=0;for(n[0]&&n[0].startsWith("WEBVTT")&&(c=1);c")){const h=u.split("-->");if(h.length>=2){const d=h[0].trim(),g=h[1].trim().split(" ")[0],v=a(d),y=a(g);if(v!==null){c++;let S=[];for(;c"))break;S.push(n[c]),c++}if(c"),S.length>0){const T=S.join(" ").trim(),A=/<(\d{2}:)?(\d{2}):(\d{2})\.(\d{3})>/g;let E;const w=[...T.matchAll(A)];if(w.length>0){E=[],w.forEach((D,W)=>{const V=D[1]?parseInt(D[1].replace(":",""),10):0,H=parseInt(D[2],10),Q=parseInt(D[3],10),k=parseInt(D[4],10),P=V*3600+H*60+Q+k/1e3,J=(D.index||0)+D[0].length;let ve=T.length;W+10){const Ee=T.substring(0,D.index);Ee.trim()&&E.push({text:Ee.trim(),startTime:v,endTime:P})}fe&&E.push({text:fe,startTime:P,endTime:0})});for(let D=0;D/g,"").replace(/\s+/g," ").trim(),L=Bg(I);i.push({time:v,text:L,endTime:y!==null?y:void 0,words:E&&E.length>0?E:void 0})}continue}}}c++}return i},lR=({toast:t,onRemove:e})=>{const[n,i]=Ae.useState(!1);Ae.useEffect(()=>{const u=setTimeout(()=>{r()},t.duration||500);return()=>clearTimeout(u)},[]);const r=()=>{i(!0),setTimeout(e,300)},a=()=>{switch(t.type){case"success":return p.jsx(pT,{size:18,className:"text-green-400"});case"error":return p.jsx(IC,{size:18,className:"text-red-400"});default:return p.jsx(eA,{size:18,className:"text-blue-400"})}},c=()=>{switch(t.type){case"success":return"border-green-500/30";case"error":return"border-red-500/30";default:return"border-blue-500/30"}};return p.jsxs("div",{className:` + flex items-center gap-3 bg-zinc-900/60 backdrop-blur-xl border ${c()} + text-zinc-100 px-4 py-3 rounded-xl shadow-2xl min-w-[300px] max-w-md + transition-all duration-300 transform + ${n?"opacity-0 translate-x-full":"opacity-100 translate-x-0"} + animate-in slide-in-from-right fade-in + `,role:"alert",children:[p.jsx("div",{className:"shrink-0",children:a()}),p.jsx("p",{className:"text-sm font-medium flex-1",children:t.message}),p.jsx("button",{onClick:r,className:"text-zinc-500 hover:text-white transition-colors",children:p.jsx(Wo,{size:16})})]})},cR=({toasts:t,removeToast:e})=>p.jsx("div",{className:"fixed top-4 right-4 z-[9999] flex flex-col gap-3 pointer-events-none",children:t.map(n=>p.jsx("div",{className:"pointer-events-auto",children:p.jsx(lR,{toast:n,onRemove:()=>e(n.id)})},n.id))}),uR=({isOpen:t,message:e,onConfirm:n,onCancel:i,title:r="Confirm Action"})=>{const[a,c]=Ae.useState(!1);return Ae.useEffect(()=>{t?c(!0):setTimeout(()=>c(!1),300)},[t]),Ae.useEffect(()=>{const u=h=>{t&&(h.key==="Enter"?(h.preventDefault(),n()):h.key==="Escape"&&(h.preventDefault(),i()))};return t&&window.addEventListener("keydown",u),()=>{window.removeEventListener("keydown",u)}},[t,n,i]),!t&&!a?null:p.jsxs("div",{className:`fixed inset-0 z-[9999] flex items-center justify-center p-4 transition-all duration-300 ${t?"opacity-100":"opacity-0"}`,children:[p.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm transition-opacity",onClick:i}),p.jsxs("div",{className:` + relative bg-zinc-900 border border-white/10 rounded-2xl shadow-2xl w-full max-w-md overflow-hidden transform transition-all duration-300 + ${t?"scale-100 translate-y-0":"scale-95 translate-y-4"} + `,children:[p.jsx("div",{className:"p-6",children:p.jsxs("div",{className:"flex items-start gap-4",children:[p.jsx("div",{className:"p-3 bg-orange-500/10 rounded-full shrink-0",children:p.jsx(jA,{className:"text-orange-500",size:24})}),p.jsxs("div",{className:"flex-1",children:[p.jsx("h3",{className:"text-lg font-bold text-white mb-2",children:r}),p.jsx("p",{className:"text-zinc-400 text-sm leading-relaxed",children:e})]}),p.jsx("button",{onClick:i,className:"text-zinc-500 hover:text-white transition-colors",children:p.jsx(Wo,{size:20})})]})}),p.jsxs("div",{className:"flex items-center justify-end gap-3 p-4 bg-zinc-950/50 border-t border-white/5",children:[p.jsx("button",{onClick:i,className:"px-4 py-2 text-sm font-medium text-zinc-400 hover:text-white hover:bg-white/5 rounded-lg transition-colors",children:"Cancel"}),p.jsx("button",{onClick:n,className:"px-4 py-2 text-sm font-medium text-white bg-purple-600 hover:bg-purple-500 rounded-lg shadow-lg hover:shadow-purple-500/20 transition-all",children:"Confirm"})]})]})]})},xT=Ae.createContext(void 0),Ou=()=>{const t=Ae.useContext(xT);if(!t)throw new Error("useUI must be used within a UIProvider");return t},dR=({children:t})=>{const[e,n]=Ae.useState([]),i=Ae.useCallback((v,y,S)=>{let T,A;typeof S=="number"?T=S:typeof S=="object"&&(T=S.duration,A=S.id);const E=A||Math.random().toString(36).substr(2,9);n(w=>[...w.filter(L=>L.id!==E),{id:E,type:v,message:y,duration:T}])},[]),r=Ae.useCallback(v=>{n(y=>y.filter(S=>S.id!==v))},[]),a={success:(v,y)=>i("success",v,y),error:(v,y)=>i("error",v,y),info:(v,y)=>i("info",v,y)},[c,u]=Ae.useState({isOpen:!1,message:"",title:"",resolve:null}),h=Ae.useCallback((v,y="Confirm Action")=>new Promise(S=>{u({isOpen:!0,message:v,title:y,resolve:S})}),[]),d=Ae.useCallback(()=>{c.resolve&&c.resolve(!0),u(v=>({...v,isOpen:!1,resolve:null}))},[c]),g=Ae.useCallback(()=>{c.resolve&&c.resolve(!1),u(v=>({...v,isOpen:!1,resolve:null}))},[c]);return p.jsxs(xT.Provider,{value:{toast:a,confirm:h},children:[t,p.jsx(cR,{toasts:e,removeToast:r}),p.jsx(uR,{isOpen:c.isOpen,message:c.message,title:c.title,onConfirm:d,onCancel:g})]})},Yd=t=>t>=150?.5:t>=100?1:t>=60?2:t>=40?5:t>=25?10:15,fR=(t,e)=>{const n=Math.floor(t/60),i=t%60;return e<1?`${n}:${i.toFixed(1).padStart(4,"0")}`:`${n}:${Math.floor(i).toString().padStart(2,"0")}`},vb=10,hR=50,Hn={VISUAL_L2_TOP:32,VISUAL_L2_HEIGHT:48,VISUAL_L1_TOP:84,VISUAL_L1_HEIGHT:48,LYRICS_TOP:136,LYRICS_HEIGHT:32,AUDIO_L1_TOP:172,AUDIO_L1_HEIGHT:32,AUDIO_L2_TOP:208,AUDIO_L2_HEIGHT:32},pR=t=>new Promise(e=>{const n=URL.createObjectURL(t),i=document.createElement(t.type.startsWith("audio/")?"audio":"video");i.preload="metadata",i.onloadedmetadata=()=>{e(i.duration),URL.revokeObjectURL(n)},i.onerror=()=>{URL.revokeObjectURL(n),e(0)},i.src=n}),mR=({value:t,onChange:e})=>{const[n,i]=Ae.useState(t.toString());Ae.useEffect(()=>{const c=parseFloat(n);!isNaN(c)&&Math.abs(c-t)<.001||i(t.toString())},[t]);const r=()=>{const c=parseFloat(n);n===""||isNaN(c)||c<=0?i(t.toString()):e(c)},a=c=>{const u=parseFloat(n),h=isNaN(u)?t:u,d=Math.round((h+c)*100)/100;d<.05||(e(d),i(d.toString()))};return p.jsxs("div",{className:"flex items-center bg-zinc-900 rounded border border-zinc-700 h-[18px]",children:[p.jsx("button",{onClick:()=>a(-.05),className:"px-0.5 hover:bg-zinc-700 text-zinc-400 hover:text-white transition-colors h-full flex items-center justify-center border-r border-zinc-700",children:p.jsx(zu,{size:10})}),p.jsx("input",{type:"text",name:"speed-input","aria-label":"Speed Input",className:"bg-transparent text-[10px] text-zinc-300 focus:outline-none w-10 text-center",value:n,onChange:c=>{/^\d*\.?\d*$/.test(c.target.value)&&i(c.target.value)},onBlur:r,onKeyDown:c=>{c.stopPropagation(),c.key==="ArrowUp"&&(c.preventDefault(),a(.05)),c.key==="ArrowDown"&&(c.preventDefault(),a(-.05)),c.key==="Enter"&&c.currentTarget.blur()}}),p.jsx("button",{onClick:()=>a(.05),className:"px-0.5 hover:bg-zinc-700 text-zinc-400 hover:text-white transition-colors h-full flex items-center justify-center border-l border-zinc-700",children:p.jsx(x0,{size:10})})]})},gR=({slides:t,setSlides:e,currentTime:n,duration:i,lyrics:r,onSeek:a,onClose:c,renderConfig:u,setRenderConfig:h})=>{const{confirm:d,toast:g}=Ou(),v=Ae.useRef(null),y=Ae.useRef(null),S=Ae.useRef(null),[T,A]=Ae.useState(40),[E,w]=Ae.useState([]),[I,L]=Ae.useState(null),[D,W]=Ae.useState([]),[V,H]=Ae.useState(null),[Q,k]=Ae.useState(!1),[P,J]=Ae.useState(null),[ve,fe]=Ae.useState([{slides:t,selection:[]}]),[Ee,je]=Ae.useState(0),X=Ae.useRef(!1),[_e,ne]=Ae.useState([]);Ae.useEffect(()=>{if(X.current){X.current=!1;return}if(V||Q)return;const F=ve[Ee],le={slides:t,selection:E};if(JSON.stringify(F)!==JSON.stringify(le)){const z=ve.slice(0,Ee+1);z.push(le),z.length>hR?(z.shift(),fe(z)):(fe(z),je(Ee+1))}},[t,E,ve,Ee,V,Q]);const tt=Ee>0,Ce=Ee{if(Ee>0){const F=Ee-1;je(F),X.current=!0,e(ve[F].slides),w(ve[F].selection)}},[e,w,ve,Ee]),ce=Ae.useCallback(()=>{if(EeF.endTime)),oe=Math.max(i,60,Xe),Ie=oe*T,nt=Ae.useCallback(()=>{if(E.length===0)return;const F=t.filter(le=>E.includes(le.id));W(F),g.success(`Copied ${F.length} items`)},[E,t,g]),Se=Ae.useCallback(()=>{if(E.length===0)return;const F=t.filter(le=>E.includes(le.id));W(F),e(le=>le.filter(z=>!E.includes(z.id))),w([]),g.success(`Cut ${F.length} items`)},[E,t,e,g]),N=Ae.useRef(t),ye=Ae.useRef(T);Ae.useEffect(()=>{N.current=t,ye.current=T},[t,T]);const xe=Ae.useCallback(()=>{if(D.length===0)return;const F=Math.min(...D.map(j=>j.startTime)),le=n-F,z=D.map(j=>({...j,id:Math.random().toString(36).substr(2,9),startTime:j.startTime+le,endTime:j.endTime+le}));e(j=>[...j,...z].sort((B,re)=>B.startTime-re.startTime)),w(z.map(j=>j.id)),g.success(`Pasted ${z.length} items`)},[D,n,e,g]),Oe=Ae.useCallback(()=>{const F=t.filter(B=>E.includes(B.id)&&n>B.startTime&&n{const re=n,Y={...B,id:Math.random().toString(36).substr(2,9),endTime:re},me=re-B.startTime,ee={...B,id:Math.random().toString(36).substr(2,9),startTime:re,mediaStartOffset:(B.mediaStartOffset||0)+me};z.push(B.id),le.push(Y,ee),j.push(ee.id)}),e(B=>[...B.filter(Y=>!z.includes(Y.id)),...le].sort((Y,me)=>Y.startTime-me.startTime)),w(j),g.success(`Split ${F.length} items`)},[t,E,n,e,g]),at=async F=>{if(F.target.files&&F.target.files.length>0){const le=Array.from(F.target.files),z=le.every(B=>B.type.startsWith("image/")),j=[];if(z){const B=le.length,re=n,me=Math.max(0,i-re)/B,ee=Math.max(3,me);le.forEach(($e,M)=>{const K=URL.createObjectURL($e),de=re+M*ee,ue=de+ee;j.push({id:Math.random().toString(36).substr(2,9),url:K,type:"image",startTime:de,endTime:ue,name:$e.name,layer:0})})}else{let B=n;for(const re of le){const Y=re.type.startsWith("image/")?"image":re.type.startsWith("video/")?"video":"audio";let me=5;if(Y!=="image"){const $e=await pR(re);$e>0&&(me=$e)}const ee=URL.createObjectURL(re);j.push({id:Math.random().toString(36).substr(2,9),url:ee,type:Y,startTime:B,endTime:B+me,mediaDuration:Y!=="image"?me:void 0,name:re.name,isMuted:Y==="video",volume:Y==="video"||Y==="audio"?1:void 0,layer:0}),B+=me}}e(B=>[...B,...j].sort((re,Y)=>re.startTime-Y.startTime)),F.target.value=""}},Ze=F=>{e(le=>le.filter(z=>z.id!==F))},U=async F=>{F.stopPropagation(),t.length!==0&&await d("Are you sure you want to remove all visual slides?","Remove All Slides")&&e([])},Me=(F,le,z)=>{if(F.stopPropagation(),F.preventDefault(),v.current?.focus(),F.shiftKey&&I){const ee=t.findIndex(M=>M.id===I),$e=t.findIndex(M=>M.id===le);if(ee!==-1&&$e!==-1){const M=Math.min(ee,$e),K=Math.max(ee,$e),de=t.slice(M,K+1).map(ue=>ue.id);w(ue=>{const Ue=new Set([...ue,...de]);return Array.from(Ue)})}}else F.ctrlKey||F.metaKey?(w(ee=>ee.includes(le)?ee.filter($e=>$e!==le):[...ee,le]),L(le)):(E.includes(le)||w([le]),L(le));const j=t.find(ee=>ee.id===le);if(!j)return;const B=E.includes(le),re=F.ctrlKey||F.metaKey||F.shiftKey;let Y=[];if(!re&&!B)Y=[le];else if(re){if(Y=[le],(F.ctrlKey||F.metaKey)&&!B)Y=[...E,le];else if((F.ctrlKey||F.metaKey)&&B){Y=E.filter(ee=>ee!==le);return}}else Y=E;const me={};t.forEach(ee=>{Y.includes(ee.id)&&(me[ee.id]={start:ee.startTime,end:ee.endTime})}),me[le]||(me[le]={start:j.startTime,end:j.endTime}),H({id:le,type:z,startX:F.clientX,initialStart:j.startTime,initialEnd:j.endTime,initialMap:me}),window.addEventListener("mousemove",te),window.addEventListener("mouseup",ae)},Pe=F=>{F.button===0&&(F.stopPropagation(),v.current?.focus(),w([]),k(!0),We(F.clientX),window.addEventListener("mousemove",gt),window.addEventListener("mouseup",qe))},rt=F=>{if(F.button!==0)return;v.current?.focus();const le=F.clientX,z=F.clientY,j=S.current?.getBoundingClientRect();if(!j)return;const B=le-j.left,re=z-j.top;let Y=!1;const me=$e=>{const M=Math.sqrt(Math.pow($e.clientX-le,2)+Math.pow($e.clientY-z,2));if(!Y&&M>5&&(Y=!0,J({x:B,y:re,w:0,h:0})),Y&&S.current){const K=S.current.getBoundingClientRect(),de=$e.clientX-K.left,ue=$e.clientY-K.top;J(Dt=>{if(!Dt)return null;const Yt=de-B,Zt=ue-re;return{x:Yt>0?B:de,y:Zt>0?re:ue,w:Math.abs(Yt),h:Math.abs(Zt)}});const Ue=[],Je=N.current,ht=ye.current,et=Math.min(B,de),Te=Math.min(re,ue),Ke=Math.abs(de-B),Be=Math.abs(ue-re),_t=et+Ke,Jt=Te+Be;Je.forEach(Dt=>{const Yt=Dt.startTime*ht+96,Zt=Dt.endTime*ht+96;let ti=0,Gi=0;const Si=Dt.layer||0;Dt.type==="audio"?Si===0?(ti=Hn.AUDIO_L1_TOP,Gi=Hn.AUDIO_L1_TOP+Hn.AUDIO_L1_HEIGHT):(ti=Hn.AUDIO_L2_TOP,Gi=Hn.AUDIO_L2_TOP+Hn.AUDIO_L2_HEIGHT):Si===0?(ti=Hn.VISUAL_L1_TOP,Gi=Hn.VISUAL_L1_TOP+Hn.VISUAL_L1_HEIGHT):(ti=Hn.VISUAL_L2_TOP,Gi=Hn.VISUAL_L2_TOP+Hn.VISUAL_L2_HEIGHT);const ji=etYt,fn=Teti;ji&&fn&&Ue.push(Dt.id)}),w(Ue)}},ee=$e=>{Y||(w([]),We($e.clientX)),J(null),window.removeEventListener("mousemove",me),window.removeEventListener("mouseup",ee)};window.addEventListener("mousemove",me),window.addEventListener("mouseup",ee)},We=F=>{if(!S.current)return;const le=S.current.getBoundingClientRect(),z=F-le.left-96;let j=Math.max(0,Math.min(z/T,oe));j=C(j),a(j)},gt=F=>{We(F.clientX)},qe=()=>{k(!1),window.removeEventListener("mousemove",gt),window.removeEventListener("mouseup",qe)},q=F=>{const le=F.target;if(!(le.tagName==="INPUT"||le.tagName==="TEXTAREA"||le.isContentEditable)){if((F.ctrlKey||F.metaKey)&&F.key==="z"&&!F.shiftKey){F.preventDefault(),$();return}if((F.ctrlKey||F.metaKey)&&(F.key==="y"||F.key==="z"&&F.shiftKey)){F.preventDefault(),ce();return}if((F.ctrlKey||F.metaKey)&&F.key==="c"){F.preventDefault(),nt();return}if((F.ctrlKey||F.metaKey)&&F.key==="x"){F.preventDefault(),Se();return}if((F.ctrlKey||F.metaKey)&&F.key==="v"){F.preventDefault(),xe();return}if(F.key.toLowerCase()==="x"&&!F.ctrlKey&&!F.metaKey||(F.ctrlKey||F.metaKey)&&F.key==="k"){F.preventDefault(),F.stopPropagation(),Oe();return}if((F.key==="Delete"||F.key==="Backspace")&&E.length>0&&(F.preventDefault(),e(z=>z.filter(j=>!E.includes(j.id))),w([])),E.length>0&&(F.key==="ArrowLeft"||F.key==="ArrowRight")){F.preventDefault(),F.stopPropagation();const z=F.key==="ArrowRight"?.01:-.01,j=t.find(B=>B.id===E[0]);if(j){const B=Math.max(0,j.startTime+z);a(B)}e(B=>B.map(Y=>{if(E.includes(Y.id)){const me=Y.endTime-Y.startTime;let ee=Y.startTime+z;return ee=Math.max(0,ee),{...Y,startTime:ee,endTime:ee+me}}return Y}).sort((Y,me)=>Y.startTime-me.startTime))}}},C=(F,le=[])=>{const z=vb/T,j=[0,i,n],B=Yd(T),re=Math.round(F/B)*B;j.push(re),t.forEach(ee=>{le.includes(ee.id)||(j.push(ee.startTime),j.push(ee.endTime))}),r.forEach(ee=>{j.push(ee.time)});let Y=F,me=z;for(const ee of j){const $e=Math.abs(ee-F);$e{H(le=>{if(!le)return null;const j=(F.clientX-le.startX)/T;let B=[];return e(re=>{if(le.type==="move"){const Y=Object.keys(le.initialMap),me=Object.values(le.initialMap),ee=Math.min(...me.map(Be=>Be.start)),$e=Math.max(...me.map(Be=>Be.end)),M=le.initialMap[le.id],K=[{type:"drag-start",initVal:M.start,ref:"start"},{type:"drag-end",initVal:M.end,ref:"end"},{type:"group-start",initVal:ee,ref:"start"},{type:"group-end",initVal:$e,ref:"end"}],de=vb/T,ue=[0,i,n],Ue=Yd(T);t.forEach(Be=>{Y.includes(Be.id)||(ue.push(Be.startTime),ue.push(Be.endTime))}),r.forEach(Be=>{ue.push(Be.time)});let Je=j,ht=de,et=!1,Te=-1;K.forEach(Be=>{const _t=Be.initVal+j;for(const Yt of ue){const Zt=Math.abs(Yt-_t);Zt{const _t=le.initialMap[Be.id];if(_t){const Jt=_t.end-_t.start;let Dt=Be.layer||0;const Yt=S.current?.getBoundingClientRect();if(Yt){const Zt=F.clientY-Yt.top,ti=(Gi,Si,ji)=>Gi>=Si-10&&Gi<=Si+ji+10;Be.type==="audio"?ti(Zt,Hn.AUDIO_L1_TOP,Hn.AUDIO_L1_HEIGHT)?Dt=0:ti(Zt,Hn.AUDIO_L2_TOP,Hn.AUDIO_L2_HEIGHT)&&(Dt=1):ti(Zt,Hn.VISUAL_L1_TOP,Hn.VISUAL_L1_HEIGHT)?Dt=0:ti(Zt,Hn.VISUAL_L2_TOP,Hn.VISUAL_L2_HEIGHT)&&(Dt=1)}return{...Be,startTime:_t.start+Ke,endTime:_t.start+Ke+Jt,layer:Dt}}return Be})}else if(le.type==="resize-start"){let Y=le.initialStart+j;const me=C(Y,[le.id]);Math.abs(me-Y)>1e-4&&(B=[me]),Y=me;const ee=.5,$e=le.initialEnd;return Y=Math.max(0,Math.min(Y,$e-ee)),Y===0&&(B=[0]),re.map(M=>M.id!==le.id?M:{...M,startTime:Y})}else{let Y=le.initialEnd+j;const me=C(Y,[le.id]);Math.abs(me-Y)>1e-4&&(B=[me]),Y=me;const ee=.5,$e=le.initialStart;return Y=Math.max($e+ee,Y),re.map(M=>M.id!==le.id?M:{...M,endTime:Y})}}),ne(B),le})},ae=F=>{V&&V.type==="move"&&Math.abs(F.clientX-V.startX)<5&&!F.ctrlKey&&!F.metaKey&&!F.shiftKey&&w([V.id]),H(null),ne([]),window.removeEventListener("mousemove",te),window.removeEventListener("mouseup",ae),e(le=>[...le].sort((z,j)=>z.startTime-j.startTime))},Re=()=>A(F=>Math.min(200,F+10)),De=()=>A(F=>Math.max(10,F-10)),st=(F,le)=>{h(z=>{const j=z.layerVisibility?.[F]||{},B={...j,[le]:j[le]===!1};return{...z,layerVisibility:{...z.layerVisibility,[F]:B,...F==="visual"?{audio:z.layerVisibility?.audio||{}}:{visual:z.layerVisibility?.visual||{}}}}})},it=(F,le)=>u.layerVisibility?.[F]?.[le]!==!1;return p.jsxs("div",{ref:v,className:"w-full max-w-[100vw] h-64 flex flex-col bg-zinc-900/95 backdrop-blur-md border-t border-white/10 z-20 shadow-xl outline-none overflow-hidden",tabIndex:0,onMouseDown:F=>F.currentTarget.focus(),onKeyDown:q,children:[p.jsxs("div",{className:"p-2 border-b border-white/10 flex items-center justify-between bg-zinc-900 z-30 shrink-0 h-12",children:[p.jsxs("div",{className:"flex items-center gap-4 shrink-0",children:[p.jsxs("h2",{className:"text-sm font-bold flex items-center gap-2 text-zinc-300 whitespace-nowrap",children:[p.jsx(mT,{size:16,className:"text-purple-400"}),"Timeline"]}),p.jsx("div",{className:"w-px h-4 bg-zinc-700"}),p.jsxs("label",{className:"flex items-center gap-2 px-3 py-1 bg-purple-600 hover:bg-purple-500 rounded text-xs font-medium cursor-pointer transition-colors text-white whitespace-nowrap",children:[p.jsx(vT,{size:14})," Import Media",p.jsx("input",{type:"file",name:"import-media",id:"import-media",className:"hidden",accept:"image/*,video/*,audio/*",multiple:!0,onChange:at})]}),p.jsx("div",{className:"w-px h-4 bg-zinc-700"}),p.jsxs("div",{className:"flex items-center gap-1",children:[p.jsx("button",{onClick:De,className:"p-1 hover:bg-zinc-700 rounded text-zinc-400 hover:text-white",title:"Zoom Out",children:p.jsx(rR,{size:14})}),p.jsxs("div",{className:"text-[10px] text-zinc-500 font-mono min-w-[50px] text-center",children:[T,"px/s"]}),p.jsx("button",{onClick:Re,className:"p-1 hover:bg-zinc-700 rounded text-zinc-400 hover:text-white",title:"Zoom In",children:p.jsx(oR,{size:14})})]}),p.jsx("div",{className:"w-px h-4 bg-zinc-700"}),p.jsxs("div",{className:"flex items-center gap-1",children:[p.jsx("button",{onClick:$,disabled:!tt,className:"p-1 hover:bg-zinc-700 rounded text-zinc-400 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed",title:"Undo (Ctrl+Z)",children:p.jsx(YA,{size:14})}),p.jsx("button",{onClick:ce,disabled:!Ce,className:"p-1 hover:bg-zinc-700 rounded text-zinc-400 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed",title:"Redo (Ctrl+Y)",children:p.jsx(xA,{size:14})})]}),p.jsx("div",{className:"w-px h-4 bg-zinc-700"}),p.jsxs("div",{className:"flex items-center gap-1",children:[p.jsx("button",{onClick:nt,disabled:E.length===0,className:"p-1 hover:bg-zinc-700 rounded text-zinc-400 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed",title:"Copy (Ctrl+C)",children:p.jsx(kC,{size:14})}),p.jsx("button",{onClick:Se,disabled:E.length===0,className:"p-1 hover:bg-zinc-700 rounded text-zinc-400 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed",title:"Cut (Ctrl+X)",children:p.jsx(MA,{size:14})}),p.jsx("button",{onClick:xe,disabled:D.length===0,className:"p-1 hover:bg-zinc-700 rounded text-zinc-400 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed",title:"Paste (Ctrl+V)",children:p.jsx(LC,{size:14})})]}),p.jsx("div",{className:"w-px h-4 bg-zinc-700"}),p.jsx("div",{className:"flex items-center gap-1",children:p.jsx("button",{onClick:Oe,disabled:E.length===0,className:"p-1 hover:bg-zinc-700 rounded text-zinc-400 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed",title:"Split Content (X)",children:p.jsx(FA,{size:14})})}),p.jsx("div",{className:"w-px h-4 bg-zinc-700"}),p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx("button",{onClick:()=>{t.length>0&&E.length===t.length?w([]):w(t.map(F=>F.id))},className:"px-2 py-0.5 text-[10px] bg-zinc-800 hover:bg-zinc-700 border border-zinc-700 rounded text-zinc-300 transition-colors",children:"Select All"}),E.length===1&&p.jsxs("div",{className:"flex items-center gap-1 bg-zinc-800 rounded px-1 border border-zinc-700",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 px-1",children:"Dur:"}),p.jsx("input",{type:"text",name:"duration-input","aria-label":"Slide Duration",className:"w-12 bg-transparent text-[10px] text-white font-mono focus:outline-none py-0.5 text-center",placeholder:"MM:SS",defaultValue:(()=>{const F=t.find(le=>le.id===E[0]);return F?Ps(F.endTime-F.startTime):"00:00"})(),onBlur:F=>{const z=F.target.value.split(":");if(z.length===2){const B=parseInt(z[0])||0,re=parseInt(z[1])||0,Y=B*60+re;Y>0&&e(me=>me.map(ee=>ee.id===E[0]?{...ee,endTime:ee.startTime+Y}:ee))}const j=t.find(B=>B.id===E[0]);j&&(F.target.value=Ps(j.endTime-j.startTime))},onKeyDown:F=>{F.key==="Enter"&&F.currentTarget.blur()}},E[0])]}),E.length===1&&(()=>{const F=t.find(le=>le.id===E[0]);return F&&(F.type==="video"||F.type==="audio")?p.jsxs(p.Fragment,{children:[p.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800 rounded px-2 border border-zinc-700 h-[22px]",children:[p.jsx("span",{className:"text-[10px] text-zinc-500",children:"Vol:"}),p.jsxs("div",{className:"flex items-center gap-1 w-20",children:[p.jsx("button",{onClick:()=>{e(le=>le.map(z=>z.id===F.id?{...z,isMuted:!z.isMuted}:z))},className:"p-0.5 hover:bg-zinc-700 rounded cursor-pointer text-zinc-400 hover:text-white",title:F.isMuted!==!1?"Unmute":"Mute",children:F.isMuted!==!1?p.jsx(jl,{size:10}):p.jsx(Zr,{size:10})}),p.jsx("input",{type:"range",min:"0",max:"1",step:"0.05",name:"volume-input","aria-label":"Volume Level",className:"w-full h-1 bg-zinc-600 rounded-lg appearance-none cursor-pointer",value:F.volume!==void 0?F.volume:1,onChange:le=>{const z=parseFloat(le.target.value);e(j=>j.map(B=>B.id===F.id?{...B,volume:z,isMuted:z===0}:B))}})]}),p.jsxs("span",{className:"text-[9px] text-zinc-400 w-6 text-right",children:[Math.round((F.volume||1)*100),"%"]})]}),p.jsxs("div",{className:"flex items-center gap-1",children:[p.jsx("span",{className:"text-[10px] text-zinc-500",children:"Spd:"}),p.jsx(mR,{value:F.playbackRate||1,onChange:le=>{e(z=>z.map(j=>{if(j.id===F.id){const B=j.playbackRate||1,Y=(j.endTime-j.startTime)*(B/le);return{...j,playbackRate:le,endTime:j.startTime+Y}}return j}))}})]})]}):null})()]})]}),p.jsxs("div",{className:"flex gap-2 shrink-0",children:[p.jsx("button",{onClick:U,className:"p-1 hover:bg-red-900/50 text-zinc-500 hover:text-red-200 rounded transition-colors",title:"Clear All Slides",children:p.jsx(Ql,{size:14})}),p.jsx("div",{className:"w-px h-4 bg-zinc-700 mx-1 self-center"}),p.jsx("button",{onClick:c,className:"p-1 hover:bg-zinc-700 text-zinc-400 hover:text-white rounded transition-colors",title:"Close Timeline",children:p.jsx(Wo,{size:14})})]})]}),p.jsx("div",{ref:y,onWheel:F=>{y.current&&F.shiftKey&&(F.preventDefault(),y.current.scrollLeft+=F.deltaY)},className:"flex-1 overflow-x-auto overflow-y-auto relative bg-zinc-950 scroll-smooth custom-scrollbar cursor-default",children:p.jsxs("div",{ref:S,className:"relative",style:{width:`${Ie+96}px`,minWidth:"100%",height:"max(100%, 280px)"},onMouseDown:rt,children:[P&&p.jsx("div",{className:"absolute border border-purple-500 bg-purple-500/20 z-50 pointer-events-none",style:{left:P.x,top:P.y,width:P.w,height:P.h}}),_e.map((F,le)=>p.jsx("div",{className:"absolute top-0 bottom-0 border-l border-yellow-400 z-[60] shadow-[0_0_8px_rgba(250,204,21,0.6)]",style:{left:F*T}},`snap-${le}`)),p.jsxs("div",{className:"absolute top-0 bottom-0 left-[96px] right-0 pointer-events-none z-0",children:[(()=>{const F=Yd(T);return Array.from({length:Math.ceil(Ie/(T*F))}).map((le,z)=>p.jsx("div",{className:"absolute top-0 bottom-0 border-l border-white/5",style:{left:z*F*T}},z))})(),i>0&&p.jsx("div",{className:"absolute top-0 bottom-0 border-l-2 border-red-900/50 flex flex-col justify-end z-0",style:{left:i*T},children:p.jsx("span",{className:"text-[9px] text-red-900/50 bg-black/50 px-1 whitespace-nowrap",children:"End"})})]}),p.jsxs("div",{className:"sticky top-0 left-0 right-0 h-6 border-b border-white/10 bg-zinc-900/90 backdrop-blur-sm select-none cursor-pointer z-[60] flex",onMouseDown:Pe,children:[p.jsx("div",{className:"w-[96px] shrink-0 border-r border-white/10 flex items-center justify-center text-[10px] text-zinc-500 bg-zinc-900/90",children:"Time"}),p.jsx("div",{className:"relative flex-1",children:(()=>{const F=Yd(T);return Array.from({length:Math.ceil(Ie/(T*F))}).map((le,z)=>{const j=z*F;return j>oe?null:p.jsx("div",{className:"absolute bottom-0 border-l border-white/20 text-[9px] text-zinc-500 font-mono pl-1 pb-0.5 pointer-events-none",style:{left:j*T,width:F*T},children:fR(j,F)},z)})})()})]}),p.jsx("div",{className:"absolute top-6 bottom-0 w-px bg-red-500 z-50 pointer-events-none",style:{left:"96px",transform:`translateX(${n*T}px)`,willChange:"transform"},children:p.jsx("div",{className:"absolute -top-1.5 -left-1.5 w-3 h-3 bg-red-500 rotate-45 transform origin-center shadow-sm"})}),p.jsxs("div",{className:"absolute left-0 right-0 border-b border-white/5 bg-zinc-900/20",style:{top:Hn.VISUAL_L1_TOP,height:Hn.VISUAL_L1_HEIGHT},children:[p.jsxs("div",{className:"sticky left-0 w-[96px] h-full bg-zinc-900/90 border-r border-white/10 z-30 flex items-center justify-between px-2 text-[10px] text-zinc-400 backdrop-blur-sm",children:[p.jsx("span",{children:"Visual 1"}),p.jsx("button",{onClick:F=>{F.stopPropagation(),st("visual",0)},className:"p-1 hover:text-white hover:bg-zinc-700 rounded transition-colors",children:it("visual",0)?p.jsx(_u,{size:12}):p.jsx(yu,{size:12,className:"text-zinc-600"})})]}),p.jsx("div",{className:`absolute top-0 bottom-0 left-[96px] right-0 ${it("visual",0)?"":"opacity-30 grayscale pointer-events-none"}`,children:t.filter(F=>F.type!=="audio"&&(F.layer===0||F.layer===void 0)).map(F=>p.jsxs("div",{style:{left:F.startTime*T,width:Math.max(10,(F.endTime-F.startTime)*T)},className:`absolute top-1 bottom-1 rounded-md overflow-hidden group bg-zinc-800 border shadow-sm select-none cursor-move + ${V?.id===F.id||E.includes(F.id)?"border-purple-400 z-30 shadow-xl opacity-90":"border-zinc-600 hover:border-zinc-400 z-10 hover:z-20"} + ${E.includes(F.id)?"ring-2 ring-blue-500/70 ring-offset-1 ring-offset-zinc-950":""} + `,onMouseDown:le=>Me(le,F.id,"move"),children:[F.type==="video"?p.jsx("video",{src:F.url,className:"w-full h-full object-cover opacity-60 pointer-events-none",muted:!0}):p.jsx("img",{src:F.url,className:"w-full h-full object-cover opacity-60 pointer-events-none",draggable:!1,alt:F.name}),p.jsx("div",{className:"absolute inset-0 p-1 pointer-events-none flex flex-col justify-end",children:p.jsx("span",{className:"text-[10px] font-bold drop-shadow-md truncate text-zinc-200 bg-black/30 px-1 rounded w-max max-w-full",children:F.name})}),(V?.id===F.id||E.includes(F.id))&&p.jsx("div",{className:"absolute top-0 left-0 bg-black/80 text-white text-[9px] px-1.5 py-0.5 rounded-br font-mono z-50 pointer-events-none",children:Ps(F.startTime)}),F.type==="video"&&F.mediaDuration&&(Math.abs(F.endTime-F.startTime-F.mediaDuration)>.1||F.playbackRate!==void 0&&Math.abs(F.playbackRate-1)>.01)&&p.jsx("button",{onClick:le=>{le.stopPropagation(),e(z=>z.map(j=>j.id===F.id&&j.mediaDuration?{...j,endTime:j.startTime+j.mediaDuration,playbackRate:1}:j))},className:"absolute top-1 left-12 p-0.5 bg-black/60 hover:bg-zinc-600 rounded text-white opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer z-40",title:"Reset to Original Duration",children:p.jsx(Kf,{size:10})}),F.type==="video"&&p.jsx("button",{onClick:le=>{le.stopPropagation(),e(z=>z.map(j=>j.id===F.id?{...j,isMuted:!j.isMuted}:j))},className:"absolute top-1 right-10 p-0.5 bg-black/60 hover:bg-zinc-600 rounded text-white opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer z-40",title:F.isMuted!==!1?"Unmute":"Mute",children:F.isMuted!==!1?p.jsx(jl,{size:10}):p.jsx(Zr,{size:10})}),p.jsx("button",{onClick:le=>{le.stopPropagation(),Ze(F.id)},className:"absolute top-1 right-4 p-0.5 bg-black/60 hover:bg-red-500 rounded text-white opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer z-30",children:p.jsx(Wo,{size:10})}),p.jsx("div",{className:"absolute top-0 bottom-0 left-0 w-3 cursor-w-resize flex items-center justify-center bg-black/20 hover:bg-purple-500/80 transition-colors z-20",onMouseDown:le=>Me(le,F.id,"resize-start"),children:p.jsx(Xd,{size:10,className:"text-white/70 rotate-90"})}),p.jsx("div",{className:"absolute top-0 bottom-0 right-0 w-3 cursor-e-resize flex items-center justify-center bg-black/20 hover:bg-purple-500/80 transition-colors z-20",onMouseDown:le=>Me(le,F.id,"resize-end"),children:p.jsx(Xd,{size:10,className:"text-white/70 rotate-90"})})]},F.id))})]}),p.jsxs("div",{className:"absolute left-0 right-0 border-b border-white/5 bg-zinc-900/20",style:{top:Hn.VISUAL_L2_TOP,height:Hn.VISUAL_L2_HEIGHT},children:[p.jsxs("div",{className:"sticky left-0 w-[96px] h-full bg-zinc-900/90 border-r border-white/10 z-30 flex items-center justify-between px-2 text-[10px] text-zinc-400 backdrop-blur-sm",children:[p.jsx("span",{children:"Visual 2"}),p.jsx("button",{onClick:F=>{F.stopPropagation(),st("visual",1)},className:"p-1 hover:text-white hover:bg-zinc-700 rounded transition-colors",children:it("visual",1)?p.jsx(_u,{size:12}):p.jsx(yu,{size:12,className:"text-zinc-600"})})]}),p.jsx("div",{className:`absolute top-0 bottom-0 left-[96px] right-0 ${it("visual",1)?"":"opacity-30 grayscale pointer-events-none"}`,children:t.filter(F=>F.type!=="audio"&&F.layer===1).map(F=>p.jsxs("div",{style:{left:F.startTime*T,width:Math.max(10,(F.endTime-F.startTime)*T)},className:`absolute top-1 bottom-1 rounded-md overflow-hidden group bg-zinc-800 border shadow-sm select-none cursor-move + ${V?.id===F.id||E.includes(F.id)?"border-purple-400 z-30 shadow-xl opacity-90":"border-zinc-600 hover:border-zinc-400 z-10 hover:z-20"} + ${E.includes(F.id)?"ring-2 ring-blue-500/70 ring-offset-1 ring-offset-zinc-950":""} + `,onMouseDown:le=>Me(le,F.id,"move"),children:[F.type==="video"?p.jsx("video",{src:F.url,className:"w-full h-full object-cover opacity-60 pointer-events-none",muted:!0}):p.jsx("img",{src:F.url,className:"w-full h-full object-cover opacity-60 pointer-events-none",draggable:!1,alt:F.name}),p.jsx("div",{className:"absolute inset-0 p-1 pointer-events-none flex flex-col justify-end",children:p.jsx("span",{className:"text-[10px] font-bold drop-shadow-md truncate text-zinc-200 bg-black/30 px-1 rounded w-max max-w-full",children:F.name})}),(V?.id===F.id||E.includes(F.id))&&p.jsx("div",{className:"absolute top-0 left-0 bg-black/80 text-white text-[9px] px-1.5 py-0.5 rounded-br font-mono z-50 pointer-events-none",children:Ps(F.startTime)}),F.type==="video"&&F.mediaDuration&&(Math.abs(F.endTime-F.startTime-F.mediaDuration)>.1||F.playbackRate!==void 0&&Math.abs(F.playbackRate-1)>.01)&&p.jsx("button",{onClick:le=>{le.stopPropagation(),e(z=>z.map(j=>j.id===F.id&&j.mediaDuration?{...j,endTime:j.startTime+j.mediaDuration,playbackRate:1}:j))},className:"absolute top-1 left-12 p-0.5 bg-black/60 hover:bg-zinc-600 rounded text-white opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer z-40",title:"Reset to Original Duration",children:p.jsx(Kf,{size:10})}),F.type==="video"&&p.jsx("button",{onClick:le=>{le.stopPropagation(),e(z=>z.map(j=>j.id===F.id?{...j,isMuted:!j.isMuted}:j))},className:"absolute top-1 right-10 p-0.5 bg-black/60 hover:bg-zinc-600 rounded text-white opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer z-40",children:F.isMuted!==!1?p.jsx(jl,{size:10}):p.jsx(Zr,{size:10})}),p.jsx("button",{onClick:le=>{le.stopPropagation(),Ze(F.id)},className:"absolute top-1 right-4 p-0.5 bg-black/60 hover:bg-red-500 rounded text-white opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer z-30",children:p.jsx(Wo,{size:10})}),p.jsx("div",{className:"absolute top-0 bottom-0 left-0 w-3 cursor-w-resize flex items-center justify-center bg-black/20 hover:bg-purple-500/80 transition-colors z-20",onMouseDown:le=>Me(le,F.id,"resize-start"),children:p.jsx(Xd,{size:10,className:"text-white/70 rotate-90"})}),p.jsx("div",{className:"absolute top-0 bottom-0 right-0 w-3 cursor-e-resize flex items-center justify-center bg-black/20 hover:bg-purple-500/80 transition-colors z-20",onMouseDown:le=>Me(le,F.id,"resize-end"),children:p.jsx(Xd,{size:10,className:"text-white/70 rotate-90"})})]},F.id))})]}),p.jsxs("div",{className:"absolute left-0 right-0 overflow-hidden",style:{top:Hn.LYRICS_TOP,height:Hn.LYRICS_HEIGHT},children:[p.jsx("div",{className:"sticky left-0 w-[96px] h-full bg-zinc-900/90 border-r border-white/10 z-30 flex items-center px-2 text-[10px] text-zinc-400 backdrop-blur-sm select-none",children:p.jsx("span",{children:"Lyrics"})}),p.jsx("div",{className:"absolute top-0 bottom-0 left-[96px] right-0 pointer-events-none",children:r.map((F,le)=>p.jsxs("div",{className:"absolute top-1 bottom-1 text-[10px] text-zinc-400 truncate hover:text-white transition-colors hover:bg-zinc-800/50 rounded px-2 cursor-pointer border-l border-zinc-700 flex items-center whitespace-nowrap pointer-events-auto",style:{left:F.time*T},title:`${Ps(F.time)} - ${F.text}`,onClick:z=>{z.stopPropagation(),a(F.time)},children:[p.jsx("span",{className:"mr-1 text-zinc-600 font-mono text-[9px]",children:Ps(F.time)}),F.text]},le))})]}),p.jsxs("div",{className:"absolute left-0 right-0 border-t border-white/5 bg-zinc-900/40",style:{top:Hn.AUDIO_L1_TOP,height:Hn.AUDIO_L1_HEIGHT},children:[p.jsxs("div",{className:"sticky left-0 w-[96px] h-full bg-zinc-900/90 border-r border-white/10 z-30 flex items-center justify-between px-2 text-[10px] text-zinc-400 backdrop-blur-sm",children:[p.jsx("span",{children:"Audio 1"}),p.jsx("button",{onClick:F=>{F.stopPropagation(),st("audio",0)},className:"p-1 hover:text-white hover:bg-zinc-700 rounded transition-colors",children:it("audio",0)?p.jsx(_u,{size:12}):p.jsx(yu,{size:12,className:"text-zinc-600"})})]}),p.jsx("div",{className:`absolute top-0 bottom-0 left-[96px] right-0 ${it("audio",0)?"":"opacity-30 grayscale pointer-events-none"}`,children:t.filter(F=>F.type==="audio"&&(F.layer===0||F.layer===void 0)).map(F=>p.jsxs("div",{style:{left:F.startTime*T,width:Math.max(10,(F.endTime-F.startTime)*T)},className:`absolute top-1 bottom-1 rounded-md overflow-hidden group bg-emerald-900/50 border shadow-sm select-none cursor-move + ${V?.id===F.id||E.includes(F.id)?"border-emerald-400 z-30 shadow-xl opacity-90":"border-emerald-700/50 hover:border-emerald-500 z-10 hover:z-20"} + ${E.includes(F.id)?"ring-2 ring-blue-500/70 ring-offset-1 ring-offset-zinc-950":""} + `,onMouseDown:le=>Me(le,F.id,"move"),children:[p.jsx("div",{className:"absolute inset-0 flex items-center justify-center opacity-30",children:p.jsx(Zr,{size:16,className:"text-emerald-200"})}),p.jsx("div",{className:"absolute inset-0 p-1 pointer-events-none flex flex-col justify-center",children:p.jsx("span",{className:"text-[9px] font-bold drop-shadow-md truncate text-emerald-100 px-1",children:F.name})}),(V?.id===F.id||E.includes(F.id))&&p.jsx("div",{className:"absolute top-0 left-0 bg-black/80 text-white text-[9px] px-1.5 py-0.5 rounded-br font-mono z-50 pointer-events-none",children:Ps(F.startTime)}),p.jsx("button",{onClick:le=>{le.stopPropagation(),e(z=>z.map(j=>j.id===F.id?{...j,isMuted:!j.isMuted}:j))},className:"absolute top-1 right-10 p-0.5 bg-black/60 hover:bg-emerald-600 rounded text-white opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer z-40",title:F.isMuted===!0?"Unmute":"Mute",children:F.isMuted===!0?p.jsx(jl,{size:10}):p.jsx(Zr,{size:10})}),p.jsx("button",{onClick:le=>{le.stopPropagation(),Ze(F.id)},className:"absolute top-1 right-3 p-0.5 bg-black/60 hover:bg-red-500 rounded text-white opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer z-40",children:p.jsx(Wo,{size:10})}),p.jsx("div",{className:"absolute top-0 bottom-0 left-0 w-2 cursor-w-resize flex items-center justify-center hover:bg-emerald-500/50 transition-colors z-20",onMouseDown:le=>Me(le,F.id,"resize-start")}),p.jsx("div",{className:"absolute top-0 bottom-0 right-0 w-2 cursor-e-resize flex items-center justify-center hover:bg-emerald-500/50 transition-colors z-20",onMouseDown:le=>Me(le,F.id,"resize-end")})]},F.id))})]}),p.jsxs("div",{className:"absolute left-0 right-0 border-t border-white/5 bg-zinc-900/40",style:{top:Hn.AUDIO_L2_TOP,height:Hn.AUDIO_L2_HEIGHT},children:[p.jsxs("div",{className:"sticky left-0 w-[96px] h-full bg-zinc-900/90 border-r border-white/10 z-30 flex items-center justify-between px-2 text-[10px] text-zinc-400 backdrop-blur-sm",children:[p.jsx("span",{children:"Audio 2"}),p.jsx("button",{onClick:F=>{F.stopPropagation(),st("audio",1)},className:"p-1 hover:text-white hover:bg-zinc-700 rounded transition-colors",children:it("audio",1)?p.jsx(_u,{size:12}):p.jsx(yu,{size:12,className:"text-zinc-600"})})]}),p.jsx("div",{className:`absolute top-0 bottom-0 left-[96px] right-0 ${it("audio",1)?"":"opacity-30 grayscale pointer-events-none"}`,children:t.filter(F=>F.type==="audio"&&F.layer===1).map(F=>p.jsxs("div",{style:{left:F.startTime*T,width:Math.max(10,(F.endTime-F.startTime)*T)},className:`absolute top-1 bottom-1 rounded-md overflow-hidden group bg-emerald-900/50 border shadow-sm select-none cursor-move + ${V?.id===F.id||E.includes(F.id)?"border-emerald-400 z-30 shadow-xl opacity-90":"border-emerald-700/50 hover:border-emerald-500 z-10 hover:z-20"} + ${E.includes(F.id)?"ring-2 ring-blue-500/70 ring-offset-1 ring-offset-zinc-950":""} + `,onMouseDown:le=>Me(le,F.id,"move"),children:[p.jsx("div",{className:"absolute inset-0 flex items-center justify-center opacity-30",children:p.jsx(Zr,{size:16,className:"text-emerald-200"})}),p.jsx("div",{className:"absolute inset-0 p-1 pointer-events-none flex flex-col justify-center",children:p.jsx("span",{className:"text-[9px] font-bold drop-shadow-md truncate text-emerald-100 px-1",children:F.name})}),(V?.id===F.id||E.includes(F.id))&&p.jsx("div",{className:"absolute top-0 left-0 bg-black/80 text-white text-[9px] px-1.5 py-0.5 rounded-br font-mono z-50 pointer-events-none",children:Ps(F.startTime)}),p.jsx("button",{onClick:le=>{le.stopPropagation(),e(z=>z.map(j=>j.id===F.id?{...j,isMuted:!j.isMuted}:j))},className:"absolute top-1 right-10 p-0.5 bg-black/60 hover:bg-emerald-600 rounded text-white opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer z-40",title:F.isMuted===!0?"Unmute":"Mute",children:F.isMuted===!0?p.jsx(jl,{size:10}):p.jsx(Zr,{size:10})}),p.jsx("button",{onClick:le=>{le.stopPropagation(),Ze(F.id)},className:"absolute top-1 right-3 p-0.5 bg-black/60 hover:bg-red-500 rounded text-white opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer z-40",children:p.jsx(Wo,{size:10})}),p.jsx("div",{className:"absolute top-0 bottom-0 left-0 w-2 cursor-w-resize flex items-center justify-center hover:bg-emerald-500/50 transition-colors z-20",onMouseDown:le=>Me(le,F.id,"resize-start")}),p.jsx("div",{className:"absolute top-0 bottom-0 right-0 w-2 cursor-e-resize flex items-center justify-center hover:bg-emerald-500/50 transition-colors z-20",onMouseDown:le=>Me(le,F.id,"resize-end")})]},F.id))})]})]})})]})};var vR={};let xR,yR;function _R(){return{geminiUrl:xR,vertexUrl:yR}}function bR(t,e,n,i){var r,a;if(!t?.baseUrl){const c=_R();return e?(r=c.vertexUrl)!==null&&r!==void 0?r:n:(a=c.geminiUrl)!==null&&a!==void 0?a:i}return t.baseUrl}class br{}function Et(t,e){const n=/\{([^}]+)\}/g;return t.replace(n,(i,r)=>{if(Object.prototype.hasOwnProperty.call(e,r)){const a=e[r];return a!=null?String(a):""}else throw new Error(`Key '${r}' not found in valueMap.`)})}function x(t,e,n){for(let a=0;a({}));else throw new Error(`Value must be a list given an array path ${c}`);if(Array.isArray(t[u])){const h=t[u];if(Array.isArray(n))for(let d=0;dm(u,e.slice(i+1),n)):n}else return n}else t=t[r]}return t}catch(i){if(i instanceof TypeError)return n;throw i}}function SR(t,e){for(const[n,i]of Object.entries(e)){const r=n.split("."),a=i.split("."),c=new Set;let u=-1;for(let h=0;hu)for(let h=u;h=e.length||typeof t!="object"||t===null)return;const a=e[i];if(a.endsWith("[]")){const c=a.slice(0,-2),u=t;if(c in u&&Array.isArray(u[c]))for(const h of u[c])S0(h,e,n,i+1,r)}else if(a==="*"){if(typeof t=="object"&&t!==null&&!Array.isArray(t)){const c=t,u=Object.keys(c).filter(d=>!d.startsWith("_")&&!r.has(d)),h={};for(const d of u)h[d]=c[d];for(const[d,g]of Object.entries(h)){const v=[];for(const y of n.slice(i))y==="*"?v.push(d):v.push(y);x(c,v,g)}for(const d of u)delete c[d]}}else{const c=t;a in c&&S0(c[a],e,n,i+1,r)}}function Vg(t){if(typeof t!="string")throw new Error("fromImageBytes must be a string");return t}function TR(t){const e={},n=m(t,["operationName"]);n!=null&&x(e,["operationName"],n);const i=m(t,["resourceName"]);return i!=null&&x(e,["_url","resourceName"],i),e}function ER(t){const e={},n=m(t,["name"]);n!=null&&x(e,["name"],n);const i=m(t,["metadata"]);i!=null&&x(e,["metadata"],i);const r=m(t,["done"]);r!=null&&x(e,["done"],r);const a=m(t,["error"]);a!=null&&x(e,["error"],a);const c=m(t,["response","generateVideoResponse"]);return c!=null&&x(e,["response"],MR(c)),e}function wR(t){const e={},n=m(t,["name"]);n!=null&&x(e,["name"],n);const i=m(t,["metadata"]);i!=null&&x(e,["metadata"],i);const r=m(t,["done"]);r!=null&&x(e,["done"],r);const a=m(t,["error"]);a!=null&&x(e,["error"],a);const c=m(t,["response"]);return c!=null&&x(e,["response"],CR(c)),e}function MR(t){const e={},n=m(t,["generatedSamples"]);if(n!=null){let a=n;Array.isArray(a)&&(a=a.map(c=>AR(c))),x(e,["generatedVideos"],a)}const i=m(t,["raiMediaFilteredCount"]);i!=null&&x(e,["raiMediaFilteredCount"],i);const r=m(t,["raiMediaFilteredReasons"]);return r!=null&&x(e,["raiMediaFilteredReasons"],r),e}function CR(t){const e={},n=m(t,["videos"]);if(n!=null){let a=n;Array.isArray(a)&&(a=a.map(c=>RR(c))),x(e,["generatedVideos"],a)}const i=m(t,["raiMediaFilteredCount"]);i!=null&&x(e,["raiMediaFilteredCount"],i);const r=m(t,["raiMediaFilteredReasons"]);return r!=null&&x(e,["raiMediaFilteredReasons"],r),e}function AR(t){const e={},n=m(t,["video"]);return n!=null&&x(e,["video"],kR(n)),e}function RR(t){const e={},n=m(t,["_self"]);return n!=null&&x(e,["video"],zR(n)),e}function NR(t){const e={},n=m(t,["operationName"]);return n!=null&&x(e,["_url","operationName"],n),e}function IR(t){const e={},n=m(t,["operationName"]);return n!=null&&x(e,["_url","operationName"],n),e}function DR(t){const e={},n=m(t,["name"]);n!=null&&x(e,["name"],n);const i=m(t,["metadata"]);i!=null&&x(e,["metadata"],i);const r=m(t,["done"]);r!=null&&x(e,["done"],r);const a=m(t,["error"]);a!=null&&x(e,["error"],a);const c=m(t,["response"]);return c!=null&&x(e,["response"],LR(c)),e}function LR(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["parent"]);i!=null&&x(e,["parent"],i);const r=m(t,["documentName"]);return r!=null&&x(e,["documentName"],r),e}function yT(t){const e={},n=m(t,["name"]);n!=null&&x(e,["name"],n);const i=m(t,["metadata"]);i!=null&&x(e,["metadata"],i);const r=m(t,["done"]);r!=null&&x(e,["done"],r);const a=m(t,["error"]);a!=null&&x(e,["error"],a);const c=m(t,["response"]);return c!=null&&x(e,["response"],UR(c)),e}function UR(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["parent"]);i!=null&&x(e,["parent"],i);const r=m(t,["documentName"]);return r!=null&&x(e,["documentName"],r),e}function kR(t){const e={},n=m(t,["uri"]);n!=null&&x(e,["uri"],n);const i=m(t,["encodedVideo"]);i!=null&&x(e,["videoBytes"],Vg(i));const r=m(t,["encoding"]);return r!=null&&x(e,["mimeType"],r),e}function zR(t){const e={},n=m(t,["gcsUri"]);n!=null&&x(e,["uri"],n);const i=m(t,["bytesBase64Encoded"]);i!=null&&x(e,["videoBytes"],Vg(i));const r=m(t,["mimeType"]);return r!=null&&x(e,["mimeType"],r),e}var xb;(function(t){t.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",t.OUTCOME_OK="OUTCOME_OK",t.OUTCOME_FAILED="OUTCOME_FAILED",t.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(xb||(xb={}));var yb;(function(t){t.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",t.PYTHON="PYTHON"})(yb||(yb={}));var _b;(function(t){t.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",t.SILENT="SILENT",t.WHEN_IDLE="WHEN_IDLE",t.INTERRUPT="INTERRUPT"})(_b||(_b={}));var ci;(function(t){t.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",t.STRING="STRING",t.NUMBER="NUMBER",t.INTEGER="INTEGER",t.BOOLEAN="BOOLEAN",t.ARRAY="ARRAY",t.OBJECT="OBJECT",t.NULL="NULL"})(ci||(ci={}));var bb;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(bb||(bb={}));var Sb;(function(t){t.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",t.SIMPLE_SEARCH="SIMPLE_SEARCH",t.ELASTIC_SEARCH="ELASTIC_SEARCH"})(Sb||(Sb={}));var Tb;(function(t){t.AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",t.NO_AUTH="NO_AUTH",t.API_KEY_AUTH="API_KEY_AUTH",t.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",t.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",t.OAUTH="OAUTH",t.OIDC_AUTH="OIDC_AUTH"})(Tb||(Tb={}));var Eb;(function(t){t.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",t.HTTP_IN_QUERY="HTTP_IN_QUERY",t.HTTP_IN_HEADER="HTTP_IN_HEADER",t.HTTP_IN_PATH="HTTP_IN_PATH",t.HTTP_IN_BODY="HTTP_IN_BODY",t.HTTP_IN_COOKIE="HTTP_IN_COOKIE"})(Eb||(Eb={}));var wb;(function(t){t.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",t.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",t.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",t.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"})(wb||(wb={}));var Mb;(function(t){t.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH",t.MINIMAL="MINIMAL"})(Mb||(Mb={}));var Cb;(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",t.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",t.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",t.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",t.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",t.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK"})(Cb||(Cb={}));var Ab;(function(t){t.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",t.SEVERITY="SEVERITY",t.PROBABILITY="PROBABILITY"})(Ab||(Ab={}));var Rb;(function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE",t.OFF="OFF"})(Rb||(Rb={}));var Nb;(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.OTHER="OTHER",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.SPII="SPII",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.IMAGE_SAFETY="IMAGE_SAFETY",t.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",t.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",t.NO_IMAGE="NO_IMAGE",t.IMAGE_RECITATION="IMAGE_RECITATION",t.IMAGE_OTHER="IMAGE_OTHER"})(Nb||(Nb={}));var Ib;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(Ib||(Ib={}));var Db;(function(t){t.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",t.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",t.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",t.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",t.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"})(Db||(Db={}));var Lb;(function(t){t.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",t.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",t.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",t.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",t.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"})(Lb||(Lb={}));var Ub;(function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.IMAGE_SAFETY="IMAGE_SAFETY",t.MODEL_ARMOR="MODEL_ARMOR",t.JAILBREAK="JAILBREAK"})(Ub||(Ub={}));var kb;(function(t){t.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",t.ON_DEMAND="ON_DEMAND",t.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(kb||(kb={}));var Zf;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.AUDIO="AUDIO"})(Zf||(Zf={}));var zb;(function(t){t.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",t.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",t.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",t.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(zb||(zb={}));var Pb;(function(t){t.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",t.TUNING_MODE_FULL="TUNING_MODE_FULL",t.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"})(Pb||(Pb={}));var Fb;(function(t){t.ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",t.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",t.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",t.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",t.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",t.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",t.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO"})(Fb||(Fb={}));var T0;(function(t){t.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",t.JOB_STATE_QUEUED="JOB_STATE_QUEUED",t.JOB_STATE_PENDING="JOB_STATE_PENDING",t.JOB_STATE_RUNNING="JOB_STATE_RUNNING",t.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",t.JOB_STATE_FAILED="JOB_STATE_FAILED",t.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",t.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",t.JOB_STATE_PAUSED="JOB_STATE_PAUSED",t.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",t.JOB_STATE_UPDATING="JOB_STATE_UPDATING",t.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"})(T0||(T0={}));var Ob;(function(t){t.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",t.TUNING_TASK_I2V="TUNING_TASK_I2V",t.TUNING_TASK_T2V="TUNING_TASK_T2V",t.TUNING_TASK_R2V="TUNING_TASK_R2V"})(Ob||(Ob={}));var Bb;(function(t){t.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",t.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",t.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",t.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",t.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH"})(Bb||(Bb={}));var Vb;(function(t){t.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",t.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",t.BALANCED="BALANCED",t.PRIORITIZE_COST="PRIORITIZE_COST"})(Vb||(Vb={}));var Hb;(function(t){t.UNSPECIFIED="UNSPECIFIED",t.BLOCKING="BLOCKING",t.NON_BLOCKING="NON_BLOCKING"})(Hb||(Hb={}));var Gb;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(Gb||(Gb={}));var jb;(function(t){t.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",t.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER"})(jb||(jb={}));var qb;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE",t.VALIDATED="VALIDATED"})(qb||(qb={}));var Wb;(function(t){t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"})(Wb||(Wb={}));var $b;(function(t){t.DONT_ALLOW="DONT_ALLOW",t.ALLOW_ADULT="ALLOW_ADULT",t.ALLOW_ALL="ALLOW_ALL"})($b||($b={}));var Xb;(function(t){t.auto="auto",t.en="en",t.ja="ja",t.ko="ko",t.hi="hi",t.zh="zh",t.pt="pt",t.es="es"})(Xb||(Xb={}));var Yb;(function(t){t.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",t.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",t.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",t.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",t.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"})(Yb||(Yb={}));var Jb;(function(t){t.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",t.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",t.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",t.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"})(Jb||(Jb={}));var Kb;(function(t){t.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",t.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",t.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",t.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"})(Kb||(Kb={}));var Zb;(function(t){t.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",t.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",t.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",t.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",t.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",t.EDIT_MODE_STYLE="EDIT_MODE_STYLE",t.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",t.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"})(Zb||(Zb={}));var Qb;(function(t){t.FOREGROUND="FOREGROUND",t.BACKGROUND="BACKGROUND",t.PROMPT="PROMPT",t.SEMANTIC="SEMANTIC",t.INTERACTIVE="INTERACTIVE"})(Qb||(Qb={}));var eS;(function(t){t.ASSET="ASSET",t.STYLE="STYLE"})(eS||(eS={}));var tS;(function(t){t.INSERT="INSERT",t.REMOVE="REMOVE",t.REMOVE_STATIC="REMOVE_STATIC",t.OUTPAINT="OUTPAINT"})(tS||(tS={}));var nS;(function(t){t.OPTIMIZED="OPTIMIZED",t.LOSSLESS="LOSSLESS"})(nS||(nS={}));var iS;(function(t){t.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",t.PREFERENCE_TUNING="PREFERENCE_TUNING"})(iS||(iS={}));var oS;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.STATE_PENDING="STATE_PENDING",t.STATE_ACTIVE="STATE_ACTIVE",t.STATE_FAILED="STATE_FAILED"})(oS||(oS={}));var sS;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.PROCESSING="PROCESSING",t.ACTIVE="ACTIVE",t.FAILED="FAILED"})(sS||(sS={}));var rS;(function(t){t.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",t.UPLOADED="UPLOADED",t.GENERATED="GENERATED"})(rS||(rS={}));var aS;(function(t){t.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.RESPONSE_REJECTED="RESPONSE_REJECTED",t.NEED_MORE_INPUT="NEED_MORE_INPUT"})(aS||(aS={}));var lS;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.VIDEO="VIDEO",t.AUDIO="AUDIO",t.DOCUMENT="DOCUMENT"})(lS||(lS={}));var cS;(function(t){t.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",t.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",t.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"})(cS||(cS={}));var uS;(function(t){t.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",t.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",t.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(uS||(uS={}));var dS;(function(t){t.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",t.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",t.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(dS||(dS={}));var fS;(function(t){t.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",t.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",t.NO_INTERRUPTION="NO_INTERRUPTION"})(fS||(fS={}));var hS;(function(t){t.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",t.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",t.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT"})(hS||(hS={}));var pS;(function(t){t.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",t.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",t.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",t.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",t.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",t.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",t.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",t.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",t.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",t.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",t.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",t.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",t.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"})(pS||(pS={}));var mS;(function(t){t.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",t.QUALITY="QUALITY",t.DIVERSITY="DIVERSITY",t.VOCALIZATION="VOCALIZATION"})(mS||(mS={}));var Xl;(function(t){t.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",t.PLAY="PLAY",t.PAUSE="PAUSE",t.STOP="STOP",t.RESET_CONTEXT="RESET_CONTEXT"})(Xl||(Xl={}));class E0{constructor(e){const n={};for(const i of e.headers.entries())n[i[0]]=i[1];this.headers=n,this.responseInternal=e}json(){return this.responseInternal.json()}}class au{get text(){var e,n,i,r,a,c,u,h;if(((r=(i=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||i===void 0?void 0:i.parts)===null||r===void 0?void 0:r.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning text from the first one.");let d="",g=!1;const v=[];for(const y of(h=(u=(c=(a=this.candidates)===null||a===void 0?void 0:a[0])===null||c===void 0?void 0:c.content)===null||u===void 0?void 0:u.parts)!==null&&h!==void 0?h:[]){for(const[S,T]of Object.entries(y))S!=="text"&&S!=="thought"&&S!=="thoughtSignature"&&(T!==null||T!==void 0)&&v.push(S);if(typeof y.text=="string"){if(typeof y.thought=="boolean"&&y.thought)continue;g=!0,d+=y.text}}return v.length>0&&console.warn(`there are non-text parts ${v} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),g?d:void 0}get data(){var e,n,i,r,a,c,u,h;if(((r=(i=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||i===void 0?void 0:i.parts)===null||r===void 0?void 0:r.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning data from the first one.");let d="";const g=[];for(const v of(h=(u=(c=(a=this.candidates)===null||a===void 0?void 0:a[0])===null||c===void 0?void 0:c.content)===null||u===void 0?void 0:u.parts)!==null&&h!==void 0?h:[]){for(const[y,S]of Object.entries(v))y!=="inlineData"&&(S!==null||S!==void 0)&&g.push(y);v.inlineData&&typeof v.inlineData.data=="string"&&(d+=atob(v.inlineData.data))}return g.length>0&&console.warn(`there are non-data parts ${g} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),d.length>0?btoa(d):void 0}get functionCalls(){var e,n,i,r,a,c,u,h;if(((r=(i=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||i===void 0?void 0:i.parts)===null||r===void 0?void 0:r.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");const d=(h=(u=(c=(a=this.candidates)===null||a===void 0?void 0:a[0])===null||c===void 0?void 0:c.content)===null||u===void 0?void 0:u.parts)===null||h===void 0?void 0:h.filter(g=>g.functionCall).map(g=>g.functionCall).filter(g=>g!==void 0);if(d?.length!==0)return d}get executableCode(){var e,n,i,r,a,c,u,h,d;if(((r=(i=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||i===void 0?void 0:i.parts)===null||r===void 0?void 0:r.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning executable code from the first one.");const g=(h=(u=(c=(a=this.candidates)===null||a===void 0?void 0:a[0])===null||c===void 0?void 0:c.content)===null||u===void 0?void 0:u.parts)===null||h===void 0?void 0:h.filter(v=>v.executableCode).map(v=>v.executableCode).filter(v=>v!==void 0);if(g?.length!==0)return(d=g?.[0])===null||d===void 0?void 0:d.code}get codeExecutionResult(){var e,n,i,r,a,c,u,h,d;if(((r=(i=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||i===void 0?void 0:i.parts)===null||r===void 0?void 0:r.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning code execution result from the first one.");const g=(h=(u=(c=(a=this.candidates)===null||a===void 0?void 0:a[0])===null||c===void 0?void 0:c.content)===null||u===void 0?void 0:u.parts)===null||h===void 0?void 0:h.filter(v=>v.codeExecutionResult).map(v=>v.codeExecutionResult).filter(v=>v!==void 0);if(g?.length!==0)return(d=g?.[0])===null||d===void 0?void 0:d.output}}class gS{}class vS{}class PR{}class FR{}class OR{}class BR{}class xS{}class yS{}class _S{}class VR{}class Qf{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){const i=new Qf;let r;const a=e;return n?r=wR(a):r=ER(a),Object.assign(i,r),i}}class bS{}class SS{}class TS{}class ES{}class HR{}class GR{}class jR{}class Hg{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){const i=new Hg,a=DR(e);return Object.assign(i,a),i}}class qR{}class WR{}class $R{}class wS{}class XR{get text(){var e,n,i;let r="",a=!1;const c=[];for(const u of(i=(n=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||n===void 0?void 0:n.parts)!==null&&i!==void 0?i:[]){for(const[h,d]of Object.entries(u))h!=="text"&&h!=="thought"&&d!==null&&c.push(h);if(typeof u.text=="string"){if(typeof u.thought=="boolean"&&u.thought)continue;a=!0,r+=u.text}}return c.length>0&&console.warn(`there are non-text parts ${c} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),a?r:void 0}get data(){var e,n,i;let r="";const a=[];for(const c of(i=(n=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||n===void 0?void 0:n.parts)!==null&&i!==void 0?i:[]){for(const[u,h]of Object.entries(c))u!=="inlineData"&&h!==null&&a.push(u);c.inlineData&&typeof c.inlineData.data=="string"&&(r+=atob(c.inlineData.data))}return a.length>0&&console.warn(`there are non-data parts ${a} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),r.length>0?btoa(r):void 0}}class YR{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}}class Gg{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){const i=new Gg,a=yT(e);return Object.assign(i,a),i}}function zn(t,e){if(!e||typeof e!="string")throw new Error("model is required and must be a string");if(e.includes("..")||e.includes("?")||e.includes("&"))throw new Error("invalid model parameter");if(t.isVertexAI()){if(e.startsWith("publishers/")||e.startsWith("projects/")||e.startsWith("models/"))return e;if(e.indexOf("/")>=0){const n=e.split("/",2);return`publishers/${n[0]}/models/${n[1]}`}else return`publishers/google/models/${e}`}else return e.startsWith("models/")||e.startsWith("tunedModels/")?e:`models/${e}`}function _T(t,e){const n=zn(t,e);return n?n.startsWith("publishers/")&&t.isVertexAI()?`projects/${t.getProject()}/locations/${t.getLocation()}/${n}`:n.startsWith("models/")&&t.isVertexAI()?`projects/${t.getProject()}/locations/${t.getLocation()}/publishers/google/${n}`:n:""}function bT(t){return Array.isArray(t)?t.map(e=>eh(e)):[eh(t)]}function eh(t){if(typeof t=="object"&&t!==null)return t;throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof t}`)}function ST(t){const e=eh(t);if(e.mimeType&&e.mimeType.startsWith("image/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function TT(t){const e=eh(t);if(e.mimeType&&e.mimeType.startsWith("audio/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function MS(t){if(t==null)throw new Error("PartUnion is required");if(typeof t=="object")return t;if(typeof t=="string")return{text:t};throw new Error(`Unsupported part type: ${typeof t}`)}function ET(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("PartListUnion is required");return Array.isArray(t)?t.map(e=>MS(e)):[MS(t)]}function w0(t){return t!=null&&typeof t=="object"&&"parts"in t&&Array.isArray(t.parts)}function CS(t){return t!=null&&typeof t=="object"&&"functionCall"in t}function AS(t){return t!=null&&typeof t=="object"&&"functionResponse"in t}function vo(t){if(t==null)throw new Error("ContentUnion is required");return w0(t)?t:{role:"user",parts:ET(t)}}function jg(t,e){if(!e)return[];if(t.isVertexAI()&&Array.isArray(e))return e.flatMap(n=>{const i=vo(n);return i.parts&&i.parts.length>0&&i.parts[0].text!==void 0?[i.parts[0].text]:[]});if(t.isVertexAI()){const n=vo(e);return n.parts&&n.parts.length>0&&n.parts[0].text!==void 0?[n.parts[0].text]:[]}return Array.isArray(e)?e.map(n=>vo(n)):[vo(e)]}function hs(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("contents are required");if(!Array.isArray(t)){if(CS(t)||AS(t))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[vo(t)]}const e=[],n=[],i=w0(t[0]);for(const r of t){const a=w0(r);if(a!=i)throw new Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");if(a)e.push(r);else{if(CS(r)||AS(r))throw new Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");n.push(r)}}return i||e.push({role:"user",parts:ET(n)}),e}function JR(t,e){t.includes("null")&&(e.nullable=!0);const n=t.filter(i=>i!=="null");if(n.length===1)e.type=Object.values(ci).includes(n[0].toUpperCase())?n[0].toUpperCase():ci.TYPE_UNSPECIFIED;else{e.anyOf=[];for(const i of n)e.anyOf.push({type:Object.values(ci).includes(i.toUpperCase())?i.toUpperCase():ci.TYPE_UNSPECIFIED})}}function ec(t){const e={},n=["items"],i=["anyOf"],r=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");const a=t.anyOf;a!=null&&a.length==2&&(a[0].type==="null"?(e.nullable=!0,t=a[1]):a[1].type==="null"&&(e.nullable=!0,t=a[0])),t.type instanceof Array&&JR(t.type,e);for(const[c,u]of Object.entries(t))if(u!=null)if(c=="type"){if(u==="null")throw new Error("type: null can not be the only possible type for the field.");if(u instanceof Array)continue;e.type=Object.values(ci).includes(u.toUpperCase())?u.toUpperCase():ci.TYPE_UNSPECIFIED}else if(n.includes(c))e[c]=ec(u);else if(i.includes(c)){const h=[];for(const d of u){if(d.type=="null"){e.nullable=!0;continue}h.push(ec(d))}e[c]=h}else if(r.includes(c)){const h={};for(const[d,g]of Object.entries(u))h[d]=ec(g);e[c]=h}else{if(c==="additionalProperties")continue;e[c]=u}return e}function qg(t){return ec(t)}function Wg(t){if(typeof t=="object")return t;if(typeof t=="string")return{voiceConfig:{prebuiltVoiceConfig:{voiceName:t}}};throw new Error(`Unsupported speechConfig type: ${typeof t}`)}function $g(t){if("multiSpeakerVoiceConfig"in t)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return t}function mc(t){if(t.functionDeclarations)for(const e of t.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=ec(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=ec(e.response));return t}function gc(t){if(t==null)throw new Error("tools is required");if(!Array.isArray(t))throw new Error("tools is required and must be an array of Tools");const e=[];for(const n of t)e.push(n);return e}function KR(t,e,n,i=1){const r=!e.startsWith(`${n}/`)&&e.split("/").length===i;return t.isVertexAI()?e.startsWith("projects/")?e:e.startsWith("locations/")?`projects/${t.getProject()}/${e}`:e.startsWith(`${n}/`)?`projects/${t.getProject()}/locations/${t.getLocation()}/${e}`:r?`projects/${t.getProject()}/locations/${t.getLocation()}/${n}/${e}`:e:r?`${n}/${e}`:e}function Sr(t,e){if(typeof e!="string")throw new Error("name must be a string");return KR(t,e,"cachedContents")}function wT(t){switch(t){case"STATE_UNSPECIFIED":return"JOB_STATE_UNSPECIFIED";case"CREATING":return"JOB_STATE_RUNNING";case"ACTIVE":return"JOB_STATE_SUCCEEDED";case"FAILED":return"JOB_STATE_FAILED";default:return t}}function aa(t){return Vg(t)}function ZR(t){return t!=null&&typeof t=="object"&&"name"in t}function QR(t){return t!=null&&typeof t=="object"&&"video"in t}function eN(t){return t!=null&&typeof t=="object"&&"uri"in t}function MT(t){var e;let n;if(ZR(t)&&(n=t.name),!(eN(t)&&(n=t.uri,n===void 0))&&!(QR(t)&&(n=(e=t.video)===null||e===void 0?void 0:e.uri,n===void 0))){if(typeof t=="string"&&(n=t),n===void 0)throw new Error("Could not extract file name from the provided input.");if(n.startsWith("https://")){const r=n.split("files/")[1].match(/[a-z0-9]+/);if(r===null)throw new Error(`Could not extract file name from URI ${n}`);n=r[0]}else n.startsWith("files/")&&(n=n.split("files/")[1]);return n}}function CT(t,e){let n;return t.isVertexAI()?n=e?"publishers/google/models":"models":n=e?"models":"tunedModels",n}function AT(t){for(const e of["models","tunedModels","publisherModels"])if(tN(t,e))return t[e];return[]}function tN(t,e){return t!==null&&typeof t=="object"&&e in t}function nN(t,e={}){const n=t,i={name:n.name,description:n.description,parametersJsonSchema:n.inputSchema};return n.outputSchema&&(i.responseJsonSchema=n.outputSchema),e.behavior&&(i.behavior=e.behavior),{functionDeclarations:[i]}}function iN(t,e={}){const n=[],i=new Set;for(const r of t){const a=r.name;if(i.has(a))throw new Error(`Duplicate function name ${a} found in MCP tools. Please ensure function names are unique.`);i.add(a);const c=nN(r,e);c.functionDeclarations&&n.push(...c.functionDeclarations)}return{functionDeclarations:n}}function RT(t,e){let n;if(typeof e=="string")if(t.isVertexAI())if(e.startsWith("gs://"))n={format:"jsonl",gcsUri:[e]};else if(e.startsWith("bq://"))n={format:"bigquery",bigqueryUri:e};else throw new Error(`Unsupported string source for Vertex AI: ${e}`);else if(e.startsWith("files/"))n={fileName:e};else throw new Error(`Unsupported string source for Gemini API: ${e}`);else if(Array.isArray(e)){if(t.isVertexAI())throw new Error("InlinedRequest[] is not supported in Vertex AI.");n={inlinedRequests:e}}else n=e;const i=[n.gcsUri,n.bigqueryUri].filter(Boolean).length,r=[n.inlinedRequests,n.fileName].filter(Boolean).length;if(t.isVertexAI()){if(r>0||i!==1)throw new Error("Exactly one of `gcsUri` or `bigqueryUri` must be set for Vertex AI.")}else if(i>0||r!==1)throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return n}function oN(t){if(typeof t!="string")return t;const e=t;if(e.startsWith("gs://"))return{format:"jsonl",gcsUri:e};if(e.startsWith("bq://"))return{format:"bigquery",bigqueryUri:e};throw new Error(`Unsupported destination: ${e}`)}function NT(t){if(typeof t!="object"||t===null)return{};const e=t,n=e.inlinedResponses;if(typeof n!="object"||n===null)return t;const r=n.inlinedResponses;if(!Array.isArray(r)||r.length===0)return t;let a=!1;for(const c of r){if(typeof c!="object"||c===null)continue;const h=c.response;if(typeof h!="object"||h===null)continue;if(h.embedding!==void 0){a=!0;break}}return a&&(e.inlinedEmbedContentResponses=e.inlinedResponses,delete e.inlinedResponses),t}function vc(t,e){const n=e;if(!t.isVertexAI()){if(/batches\/[^/]+$/.test(n))return n.split("/").pop();throw new Error(`Invalid batch job name: ${n}.`)}if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(n))return n.split("/").pop();if(/^\d+$/.test(n))return n;throw new Error(`Invalid batch job name: ${n}.`)}function IT(t){const e=t;return e==="BATCH_STATE_UNSPECIFIED"?"JOB_STATE_UNSPECIFIED":e==="BATCH_STATE_PENDING"?"JOB_STATE_PENDING":e==="BATCH_STATE_RUNNING"?"JOB_STATE_RUNNING":e==="BATCH_STATE_SUCCEEDED"?"JOB_STATE_SUCCEEDED":e==="BATCH_STATE_FAILED"?"JOB_STATE_FAILED":e==="BATCH_STATE_CANCELLED"?"JOB_STATE_CANCELLED":e==="BATCH_STATE_EXPIRED"?"JOB_STATE_EXPIRED":e}function sN(t){const e={},n=m(t,["responsesFile"]);n!=null&&x(e,["fileName"],n);const i=m(t,["inlinedResponses","inlinedResponses"]);if(i!=null){let a=i;Array.isArray(a)&&(a=a.map(c=>ON(c))),x(e,["inlinedResponses"],a)}const r=m(t,["inlinedEmbedContentResponses","inlinedResponses"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(c=>c)),x(e,["inlinedEmbedContentResponses"],a)}return e}function rN(t){const e={},n=m(t,["predictionsFormat"]);n!=null&&x(e,["format"],n);const i=m(t,["gcsDestination","outputUriPrefix"]);i!=null&&x(e,["gcsUri"],i);const r=m(t,["bigqueryDestination","outputUri"]);return r!=null&&x(e,["bigqueryUri"],r),e}function aN(t){const e={},n=m(t,["format"]);n!=null&&x(e,["predictionsFormat"],n);const i=m(t,["gcsUri"]);i!=null&&x(e,["gcsDestination","outputUriPrefix"],i);const r=m(t,["bigqueryUri"]);if(r!=null&&x(e,["bigqueryDestination","outputUri"],r),m(t,["fileName"])!==void 0)throw new Error("fileName parameter is not supported in Vertex AI.");if(m(t,["inlinedResponses"])!==void 0)throw new Error("inlinedResponses parameter is not supported in Vertex AI.");if(m(t,["inlinedEmbedContentResponses"])!==void 0)throw new Error("inlinedEmbedContentResponses parameter is not supported in Vertex AI.");return e}function Df(t){const e={},n=m(t,["name"]);n!=null&&x(e,["name"],n);const i=m(t,["metadata","displayName"]);i!=null&&x(e,["displayName"],i);const r=m(t,["metadata","state"]);r!=null&&x(e,["state"],IT(r));const a=m(t,["metadata","createTime"]);a!=null&&x(e,["createTime"],a);const c=m(t,["metadata","endTime"]);c!=null&&x(e,["endTime"],c);const u=m(t,["metadata","updateTime"]);u!=null&&x(e,["updateTime"],u);const h=m(t,["metadata","model"]);h!=null&&x(e,["model"],h);const d=m(t,["metadata","output"]);return d!=null&&x(e,["dest"],sN(NT(d))),e}function M0(t){const e={},n=m(t,["name"]);n!=null&&x(e,["name"],n);const i=m(t,["displayName"]);i!=null&&x(e,["displayName"],i);const r=m(t,["state"]);r!=null&&x(e,["state"],IT(r));const a=m(t,["error"]);a!=null&&x(e,["error"],a);const c=m(t,["createTime"]);c!=null&&x(e,["createTime"],c);const u=m(t,["startTime"]);u!=null&&x(e,["startTime"],u);const h=m(t,["endTime"]);h!=null&&x(e,["endTime"],h);const d=m(t,["updateTime"]);d!=null&&x(e,["updateTime"],d);const g=m(t,["model"]);g!=null&&x(e,["model"],g);const v=m(t,["inputConfig"]);v!=null&&x(e,["src"],lN(v));const y=m(t,["outputConfig"]);y!=null&&x(e,["dest"],rN(NT(y)));const S=m(t,["completionStats"]);return S!=null&&x(e,["completionStats"],S),e}function lN(t){const e={},n=m(t,["instancesFormat"]);n!=null&&x(e,["format"],n);const i=m(t,["gcsSource","uris"]);i!=null&&x(e,["gcsUri"],i);const r=m(t,["bigquerySource","inputUri"]);return r!=null&&x(e,["bigqueryUri"],r),e}function cN(t,e){const n={};if(m(e,["format"])!==void 0)throw new Error("format parameter is not supported in Gemini API.");if(m(e,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");if(m(e,["bigqueryUri"])!==void 0)throw new Error("bigqueryUri parameter is not supported in Gemini API.");const i=m(e,["fileName"]);i!=null&&x(n,["fileName"],i);const r=m(e,["inlinedRequests"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(c=>FN(t,c))),x(n,["requests","requests"],a)}return n}function uN(t){const e={},n=m(t,["format"]);n!=null&&x(e,["instancesFormat"],n);const i=m(t,["gcsUri"]);i!=null&&x(e,["gcsSource","uris"],i);const r=m(t,["bigqueryUri"]);if(r!=null&&x(e,["bigquerySource","inputUri"],r),m(t,["fileName"])!==void 0)throw new Error("fileName parameter is not supported in Vertex AI.");if(m(t,["inlinedRequests"])!==void 0)throw new Error("inlinedRequests parameter is not supported in Vertex AI.");return e}function dN(t){const e={},n=m(t,["data"]);if(n!=null&&x(e,["data"],n),m(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const i=m(t,["mimeType"]);return i!=null&&x(e,["mimeType"],i),e}function fN(t,e){const n={},i=m(e,["name"]);return i!=null&&x(n,["_url","name"],vc(t,i)),n}function hN(t,e){const n={},i=m(e,["name"]);return i!=null&&x(n,["_url","name"],vc(t,i)),n}function pN(t){const e={},n=m(t,["content"]);n!=null&&x(e,["content"],n);const i=m(t,["citationMetadata"]);i!=null&&x(e,["citationMetadata"],mN(i));const r=m(t,["tokenCount"]);r!=null&&x(e,["tokenCount"],r);const a=m(t,["finishReason"]);a!=null&&x(e,["finishReason"],a);const c=m(t,["avgLogprobs"]);c!=null&&x(e,["avgLogprobs"],c);const u=m(t,["groundingMetadata"]);u!=null&&x(e,["groundingMetadata"],u);const h=m(t,["index"]);h!=null&&x(e,["index"],h);const d=m(t,["logprobsResult"]);d!=null&&x(e,["logprobsResult"],d);const g=m(t,["safetyRatings"]);if(g!=null){let y=g;Array.isArray(y)&&(y=y.map(S=>S)),x(e,["safetyRatings"],y)}const v=m(t,["urlContextMetadata"]);return v!=null&&x(e,["urlContextMetadata"],v),e}function mN(t){const e={},n=m(t,["citationSources"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(r=>r)),x(e,["citations"],i)}return e}function DT(t){const e={},n=m(t,["parts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(a=>WN(a))),x(e,["parts"],r)}const i=m(t,["role"]);return i!=null&&x(e,["role"],i),e}function gN(t,e){const n={},i=m(t,["displayName"]);if(e!==void 0&&i!=null&&x(e,["batch","displayName"],i),m(t,["dest"])!==void 0)throw new Error("dest parameter is not supported in Gemini API.");return n}function vN(t,e){const n={},i=m(t,["displayName"]);e!==void 0&&i!=null&&x(e,["displayName"],i);const r=m(t,["dest"]);return e!==void 0&&r!=null&&x(e,["outputConfig"],aN(oN(r))),n}function RS(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["_url","model"],zn(t,i));const r=m(e,["src"]);r!=null&&x(n,["batch","inputConfig"],cN(t,RT(t,r)));const a=m(e,["config"]);return a!=null&&gN(a,n),n}function xN(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["model"],zn(t,i));const r=m(e,["src"]);r!=null&&x(n,["inputConfig"],uN(RT(t,r)));const a=m(e,["config"]);return a!=null&&vN(a,n),n}function yN(t,e){const n={},i=m(t,["displayName"]);return e!==void 0&&i!=null&&x(e,["batch","displayName"],i),n}function _N(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["_url","model"],zn(t,i));const r=m(e,["src"]);r!=null&&x(n,["batch","inputConfig"],CN(t,r));const a=m(e,["config"]);return a!=null&&yN(a,n),n}function bN(t,e){const n={},i=m(e,["name"]);return i!=null&&x(n,["_url","name"],vc(t,i)),n}function SN(t,e){const n={},i=m(e,["name"]);return i!=null&&x(n,["_url","name"],vc(t,i)),n}function TN(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["name"]);i!=null&&x(e,["name"],i);const r=m(t,["done"]);r!=null&&x(e,["done"],r);const a=m(t,["error"]);return a!=null&&x(e,["error"],a),e}function EN(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["name"]);i!=null&&x(e,["name"],i);const r=m(t,["done"]);r!=null&&x(e,["done"],r);const a=m(t,["error"]);return a!=null&&x(e,["error"],a),e}function wN(t,e){const n={},i=m(e,["contents"]);if(i!=null){let a=jg(t,i);Array.isArray(a)&&(a=a.map(c=>c)),x(n,["requests[]","request","content"],a)}const r=m(e,["config"]);return r!=null&&(x(n,["_self"],MN(r,n)),SR(n,{"requests[].*":"requests[].request.*"})),n}function MN(t,e){const n={},i=m(t,["taskType"]);e!==void 0&&i!=null&&x(e,["requests[]","taskType"],i);const r=m(t,["title"]);e!==void 0&&r!=null&&x(e,["requests[]","title"],r);const a=m(t,["outputDimensionality"]);if(e!==void 0&&a!=null&&x(e,["requests[]","outputDimensionality"],a),m(t,["mimeType"])!==void 0)throw new Error("mimeType parameter is not supported in Gemini API.");if(m(t,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is not supported in Gemini API.");return n}function CN(t,e){const n={},i=m(e,["fileName"]);i!=null&&x(n,["file_name"],i);const r=m(e,["inlinedRequests"]);return r!=null&&x(n,["requests"],wN(t,r)),n}function AN(t){const e={};if(m(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const n=m(t,["fileUri"]);n!=null&&x(e,["fileUri"],n);const i=m(t,["mimeType"]);return i!=null&&x(e,["mimeType"],i),e}function RN(t){const e={},n=m(t,["id"]);n!=null&&x(e,["id"],n);const i=m(t,["args"]);i!=null&&x(e,["args"],i);const r=m(t,["name"]);if(r!=null&&x(e,["name"],r),m(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(m(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}function NN(t){const e={},n=m(t,["mode"]);n!=null&&x(e,["mode"],n);const i=m(t,["allowedFunctionNames"]);if(i!=null&&x(e,["allowedFunctionNames"],i),m(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}function IN(t,e,n){const i={},r=m(e,["systemInstruction"]);n!==void 0&&r!=null&&x(n,["systemInstruction"],DT(vo(r)));const a=m(e,["temperature"]);a!=null&&x(i,["temperature"],a);const c=m(e,["topP"]);c!=null&&x(i,["topP"],c);const u=m(e,["topK"]);u!=null&&x(i,["topK"],u);const h=m(e,["candidateCount"]);h!=null&&x(i,["candidateCount"],h);const d=m(e,["maxOutputTokens"]);d!=null&&x(i,["maxOutputTokens"],d);const g=m(e,["stopSequences"]);g!=null&&x(i,["stopSequences"],g);const v=m(e,["responseLogprobs"]);v!=null&&x(i,["responseLogprobs"],v);const y=m(e,["logprobs"]);y!=null&&x(i,["logprobs"],y);const S=m(e,["presencePenalty"]);S!=null&&x(i,["presencePenalty"],S);const T=m(e,["frequencyPenalty"]);T!=null&&x(i,["frequencyPenalty"],T);const A=m(e,["seed"]);A!=null&&x(i,["seed"],A);const E=m(e,["responseMimeType"]);E!=null&&x(i,["responseMimeType"],E);const w=m(e,["responseSchema"]);w!=null&&x(i,["responseSchema"],qg(w));const I=m(e,["responseJsonSchema"]);if(I!=null&&x(i,["responseJsonSchema"],I),m(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is not supported in Gemini API.");if(m(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");const L=m(e,["safetySettings"]);if(n!==void 0&&L!=null){let fe=L;Array.isArray(fe)&&(fe=fe.map(Ee=>$N(Ee))),x(n,["safetySettings"],fe)}const D=m(e,["tools"]);if(n!==void 0&&D!=null){let fe=gc(D);Array.isArray(fe)&&(fe=fe.map(Ee=>YN(mc(Ee)))),x(n,["tools"],fe)}const W=m(e,["toolConfig"]);if(n!==void 0&&W!=null&&x(n,["toolConfig"],XN(W)),m(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");const V=m(e,["cachedContent"]);n!==void 0&&V!=null&&x(n,["cachedContent"],Sr(t,V));const H=m(e,["responseModalities"]);H!=null&&x(i,["responseModalities"],H);const Q=m(e,["mediaResolution"]);Q!=null&&x(i,["mediaResolution"],Q);const k=m(e,["speechConfig"]);if(k!=null&&x(i,["speechConfig"],Wg(k)),m(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");const P=m(e,["thinkingConfig"]);P!=null&&x(i,["thinkingConfig"],P);const J=m(e,["imageConfig"]);J!=null&&x(i,["imageConfig"],PN(J));const ve=m(e,["enableEnhancedCivicAnswers"]);return ve!=null&&x(i,["enableEnhancedCivicAnswers"],ve),i}function DN(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["candidates"]);if(i!=null){let h=i;Array.isArray(h)&&(h=h.map(d=>pN(d))),x(e,["candidates"],h)}const r=m(t,["modelVersion"]);r!=null&&x(e,["modelVersion"],r);const a=m(t,["promptFeedback"]);a!=null&&x(e,["promptFeedback"],a);const c=m(t,["responseId"]);c!=null&&x(e,["responseId"],c);const u=m(t,["usageMetadata"]);return u!=null&&x(e,["usageMetadata"],u),e}function LN(t,e){const n={},i=m(e,["name"]);return i!=null&&x(n,["_url","name"],vc(t,i)),n}function UN(t,e){const n={},i=m(e,["name"]);return i!=null&&x(n,["_url","name"],vc(t,i)),n}function kN(t){const e={};if(m(t,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");const n=m(t,["enableWidget"]);return n!=null&&x(e,["enableWidget"],n),e}function zN(t){const e={};if(m(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(m(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");const n=m(t,["timeRangeFilter"]);return n!=null&&x(e,["timeRangeFilter"],n),e}function PN(t){const e={},n=m(t,["aspectRatio"]);n!=null&&x(e,["aspectRatio"],n);const i=m(t,["imageSize"]);if(i!=null&&x(e,["imageSize"],i),m(t,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is not supported in Gemini API.");if(m(t,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");return e}function FN(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["request","model"],zn(t,i));const r=m(e,["contents"]);if(r!=null){let u=hs(r);Array.isArray(u)&&(u=u.map(h=>DT(h))),x(n,["request","contents"],u)}const a=m(e,["metadata"]);a!=null&&x(n,["metadata"],a);const c=m(e,["config"]);return c!=null&&x(n,["request","generationConfig"],IN(t,c,m(n,["request"],{}))),n}function ON(t){const e={},n=m(t,["response"]);n!=null&&x(e,["response"],DN(n));const i=m(t,["error"]);return i!=null&&x(e,["error"],i),e}function BN(t,e){const n={},i=m(t,["pageSize"]);e!==void 0&&i!=null&&x(e,["_query","pageSize"],i);const r=m(t,["pageToken"]);if(e!==void 0&&r!=null&&x(e,["_query","pageToken"],r),m(t,["filter"])!==void 0)throw new Error("filter parameter is not supported in Gemini API.");return n}function VN(t,e){const n={},i=m(t,["pageSize"]);e!==void 0&&i!=null&&x(e,["_query","pageSize"],i);const r=m(t,["pageToken"]);e!==void 0&&r!=null&&x(e,["_query","pageToken"],r);const a=m(t,["filter"]);return e!==void 0&&a!=null&&x(e,["_query","filter"],a),n}function HN(t){const e={},n=m(t,["config"]);return n!=null&&BN(n,e),e}function GN(t){const e={},n=m(t,["config"]);return n!=null&&VN(n,e),e}function jN(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["nextPageToken"]);i!=null&&x(e,["nextPageToken"],i);const r=m(t,["operations"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(c=>Df(c))),x(e,["batchJobs"],a)}return e}function qN(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["nextPageToken"]);i!=null&&x(e,["nextPageToken"],i);const r=m(t,["batchPredictionJobs"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(c=>M0(c))),x(e,["batchJobs"],a)}return e}function WN(t){const e={},n=m(t,["mediaResolution"]);n!=null&&x(e,["mediaResolution"],n);const i=m(t,["codeExecutionResult"]);i!=null&&x(e,["codeExecutionResult"],i);const r=m(t,["executableCode"]);r!=null&&x(e,["executableCode"],r);const a=m(t,["fileData"]);a!=null&&x(e,["fileData"],AN(a));const c=m(t,["functionCall"]);c!=null&&x(e,["functionCall"],RN(c));const u=m(t,["functionResponse"]);u!=null&&x(e,["functionResponse"],u);const h=m(t,["inlineData"]);h!=null&&x(e,["inlineData"],dN(h));const d=m(t,["text"]);d!=null&&x(e,["text"],d);const g=m(t,["thought"]);g!=null&&x(e,["thought"],g);const v=m(t,["thoughtSignature"]);v!=null&&x(e,["thoughtSignature"],v);const y=m(t,["videoMetadata"]);return y!=null&&x(e,["videoMetadata"],y),e}function $N(t){const e={},n=m(t,["category"]);if(n!=null&&x(e,["category"],n),m(t,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");const i=m(t,["threshold"]);return i!=null&&x(e,["threshold"],i),e}function XN(t){const e={},n=m(t,["functionCallingConfig"]);n!=null&&x(e,["functionCallingConfig"],NN(n));const i=m(t,["retrievalConfig"]);return i!=null&&x(e,["retrievalConfig"],i),e}function YN(t){const e={},n=m(t,["functionDeclarations"]);if(n!=null){let g=n;Array.isArray(g)&&(g=g.map(v=>v)),x(e,["functionDeclarations"],g)}if(m(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");const i=m(t,["googleSearchRetrieval"]);i!=null&&x(e,["googleSearchRetrieval"],i);const r=m(t,["computerUse"]);r!=null&&x(e,["computerUse"],r);const a=m(t,["fileSearch"]);a!=null&&x(e,["fileSearch"],a);const c=m(t,["codeExecution"]);if(c!=null&&x(e,["codeExecution"],c),m(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const u=m(t,["googleMaps"]);u!=null&&x(e,["googleMaps"],kN(u));const h=m(t,["googleSearch"]);h!=null&&x(e,["googleSearch"],zN(h));const d=m(t,["urlContext"]);return d!=null&&x(e,["urlContext"],d),e}var xr;(function(t){t.PAGED_ITEM_BATCH_JOBS="batchJobs",t.PAGED_ITEM_MODELS="models",t.PAGED_ITEM_TUNING_JOBS="tuningJobs",t.PAGED_ITEM_FILES="files",t.PAGED_ITEM_CACHED_CONTENTS="cachedContents",t.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",t.PAGED_ITEM_DOCUMENTS="documents"})(xr||(xr={}));class Xa{constructor(e,n,i,r){this.pageInternal=[],this.paramsInternal={},this.requestInternal=n,this.init(e,i,r)}init(e,n,i){var r,a;this.nameInternal=e,this.pageInternal=n[this.nameInternal]||[],this.sdkHttpResponseInternal=n?.sdkHttpResponse,this.idxInternal=0;let c={config:{}};!i||Object.keys(i).length===0?c={config:{}}:typeof i=="object"?c=Object.assign({},i):c=i,c.config&&(c.config.pageToken=n.nextPageToken),this.paramsInternal=c,this.pageInternalSize=(a=(r=c.config)===null||r===void 0?void 0:r.pageSize)!==null&&a!==void 0?a:this.pageInternal.length}initNextPage(e){this.init(this.nameInternal,e,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(e){return this.pageInternal[e]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(this.hasNextPage())await this.nextPage();else return{value:void 0,done:!0};const e=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:e,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw new Error("No more pages to fetch.");const e=await this.requestInternal(this.params);return this.initNextPage(e),this.page}hasNextPage(){var e;return((e=this.params.config)===null||e===void 0?void 0:e.pageToken)!==void 0}}class JN extends br{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new Xa(xr.PAGED_ITEM_BATCH_JOBS,i=>this.listInternal(i),await this.listInternal(n),n),this.create=async n=>(this.apiClient.isVertexAI()&&(n.config=this.formatDestination(n.src,n.config)),this.createInternal(n)),this.createEmbeddings=async n=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw new Error("Vertex AI does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(n)}}createInlinedGenerateContentRequest(e){const n=RS(this.apiClient,e),i=n._url,r=Et("{model}:batchGenerateContent",i),u=n.batch.inputConfig.requests,h=u.requests,d=[];for(const g of h){const v=Object.assign({},g);if(v.systemInstruction){const y=v.systemInstruction;delete v.systemInstruction;const S=v.request;S.systemInstruction=y,v.request=S}d.push(v)}return u.requests=d,delete n.config,delete n._url,delete n._query,{path:r,body:n}}getGcsUri(e){if(typeof e=="string")return e.startsWith("gs://")?e:void 0;if(!Array.isArray(e)&&e.gcsUri&&e.gcsUri.length>0)return e.gcsUri[0]}getBigqueryUri(e){if(typeof e=="string")return e.startsWith("bq://")?e:void 0;if(!Array.isArray(e))return e.bigqueryUri}formatDestination(e,n){const i=n?Object.assign({},n):{},r=Date.now().toString();if(i.displayName||(i.displayName=`genaiBatchJob_${r}`),i.dest===void 0){const a=this.getGcsUri(e),c=this.getBigqueryUri(e);if(a)a.endsWith(".jsonl")?i.dest=`${a.slice(0,-6)}/dest`:i.dest=`${a}_dest_${r}`;else if(c)i.dest=`${c}_dest_${r}`;else throw new Error("Unsupported source for Vertex AI: No GCS or BigQuery URI found.")}return i}async createInternal(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=xN(this.apiClient,e);return u=Et("batchPredictionJobs",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json()),c.then(g=>M0(g))}else{const d=RS(this.apiClient,e);return u=Et("{model}:batchGenerateContent",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json()),c.then(g=>Df(g))}}async createEmbeddingsInternal(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=_N(this.apiClient,e);return a=Et("{model}:asyncBatchEmbedContent",u._url),c=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(h=>h.json()),r.then(h=>Df(h))}}async get(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=UN(this.apiClient,e);return u=Et("batchPredictionJobs/{name}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json()),c.then(g=>M0(g))}else{const d=LN(this.apiClient,e);return u=Et("batches/{name}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json()),c.then(g=>Df(g))}}async cancel(e){var n,i,r,a;let c="",u={};if(this.apiClient.isVertexAI()){const h=hN(this.apiClient,e);c=Et("batchPredictionJobs/{name}:cancel",h._url),u=h._query,delete h._url,delete h._query,await this.apiClient.request({path:c,queryParams:u,body:JSON.stringify(h),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal})}else{const h=fN(this.apiClient,e);c=Et("batches/{name}:cancel",h._url),u=h._query,delete h._url,delete h._query,await this.apiClient.request({path:c,queryParams:u,body:JSON.stringify(h),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal})}}async listInternal(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=GN(e);return u=Et("batchPredictionJobs",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=qN(g),y=new wS;return Object.assign(y,v),y})}else{const d=HN(e);return u=Et("batches",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=jN(g),y=new wS;return Object.assign(y,v),y})}}async delete(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=SN(this.apiClient,e);return u=Et("batchPredictionJobs/{name}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>EN(g))}else{const d=bN(this.apiClient,e);return u=Et("batches/{name}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>TN(g))}}}function KN(t){const e={},n=m(t,["data"]);if(n!=null&&x(e,["data"],n),m(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const i=m(t,["mimeType"]);return i!=null&&x(e,["mimeType"],i),e}function NS(t){const e={},n=m(t,["parts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(a=>_2(a))),x(e,["parts"],r)}const i=m(t,["role"]);return i!=null&&x(e,["role"],i),e}function ZN(t,e){const n={},i=m(t,["ttl"]);e!==void 0&&i!=null&&x(e,["ttl"],i);const r=m(t,["expireTime"]);e!==void 0&&r!=null&&x(e,["expireTime"],r);const a=m(t,["displayName"]);e!==void 0&&a!=null&&x(e,["displayName"],a);const c=m(t,["contents"]);if(e!==void 0&&c!=null){let g=hs(c);Array.isArray(g)&&(g=g.map(v=>NS(v))),x(e,["contents"],g)}const u=m(t,["systemInstruction"]);e!==void 0&&u!=null&&x(e,["systemInstruction"],NS(vo(u)));const h=m(t,["tools"]);if(e!==void 0&&h!=null){let g=h;Array.isArray(g)&&(g=g.map(v=>S2(v))),x(e,["tools"],g)}const d=m(t,["toolConfig"]);if(e!==void 0&&d!=null&&x(e,["toolConfig"],b2(d)),m(t,["kmsKeyName"])!==void 0)throw new Error("kmsKeyName parameter is not supported in Gemini API.");return n}function QN(t,e){const n={},i=m(t,["ttl"]);e!==void 0&&i!=null&&x(e,["ttl"],i);const r=m(t,["expireTime"]);e!==void 0&&r!=null&&x(e,["expireTime"],r);const a=m(t,["displayName"]);e!==void 0&&a!=null&&x(e,["displayName"],a);const c=m(t,["contents"]);if(e!==void 0&&c!=null){let v=hs(c);Array.isArray(v)&&(v=v.map(y=>y)),x(e,["contents"],v)}const u=m(t,["systemInstruction"]);e!==void 0&&u!=null&&x(e,["systemInstruction"],vo(u));const h=m(t,["tools"]);if(e!==void 0&&h!=null){let v=h;Array.isArray(v)&&(v=v.map(y=>T2(y))),x(e,["tools"],v)}const d=m(t,["toolConfig"]);e!==void 0&&d!=null&&x(e,["toolConfig"],d);const g=m(t,["kmsKeyName"]);return e!==void 0&&g!=null&&x(e,["encryption_spec","kmsKeyName"],g),n}function e2(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["model"],_T(t,i));const r=m(e,["config"]);return r!=null&&ZN(r,n),n}function t2(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["model"],_T(t,i));const r=m(e,["config"]);return r!=null&&QN(r,n),n}function n2(t,e){const n={},i=m(e,["name"]);return i!=null&&x(n,["_url","name"],Sr(t,i)),n}function i2(t,e){const n={},i=m(e,["name"]);return i!=null&&x(n,["_url","name"],Sr(t,i)),n}function o2(t){const e={},n=m(t,["sdkHttpResponse"]);return n!=null&&x(e,["sdkHttpResponse"],n),e}function s2(t){const e={},n=m(t,["sdkHttpResponse"]);return n!=null&&x(e,["sdkHttpResponse"],n),e}function r2(t){const e={};if(m(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const n=m(t,["fileUri"]);n!=null&&x(e,["fileUri"],n);const i=m(t,["mimeType"]);return i!=null&&x(e,["mimeType"],i),e}function a2(t){const e={},n=m(t,["id"]);n!=null&&x(e,["id"],n);const i=m(t,["args"]);i!=null&&x(e,["args"],i);const r=m(t,["name"]);if(r!=null&&x(e,["name"],r),m(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(m(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}function l2(t){const e={},n=m(t,["mode"]);n!=null&&x(e,["mode"],n);const i=m(t,["allowedFunctionNames"]);if(i!=null&&x(e,["allowedFunctionNames"],i),m(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}function c2(t){const e={};if(m(t,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Vertex AI.");const n=m(t,["description"]);n!=null&&x(e,["description"],n);const i=m(t,["name"]);i!=null&&x(e,["name"],i);const r=m(t,["parameters"]);r!=null&&x(e,["parameters"],r);const a=m(t,["parametersJsonSchema"]);a!=null&&x(e,["parametersJsonSchema"],a);const c=m(t,["response"]);c!=null&&x(e,["response"],c);const u=m(t,["responseJsonSchema"]);return u!=null&&x(e,["responseJsonSchema"],u),e}function u2(t,e){const n={},i=m(e,["name"]);return i!=null&&x(n,["_url","name"],Sr(t,i)),n}function d2(t,e){const n={},i=m(e,["name"]);return i!=null&&x(n,["_url","name"],Sr(t,i)),n}function f2(t){const e={};if(m(t,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");const n=m(t,["enableWidget"]);return n!=null&&x(e,["enableWidget"],n),e}function h2(t){const e={};if(m(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(m(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");const n=m(t,["timeRangeFilter"]);return n!=null&&x(e,["timeRangeFilter"],n),e}function p2(t,e){const n={},i=m(t,["pageSize"]);e!==void 0&&i!=null&&x(e,["_query","pageSize"],i);const r=m(t,["pageToken"]);return e!==void 0&&r!=null&&x(e,["_query","pageToken"],r),n}function m2(t,e){const n={},i=m(t,["pageSize"]);e!==void 0&&i!=null&&x(e,["_query","pageSize"],i);const r=m(t,["pageToken"]);return e!==void 0&&r!=null&&x(e,["_query","pageToken"],r),n}function g2(t){const e={},n=m(t,["config"]);return n!=null&&p2(n,e),e}function v2(t){const e={},n=m(t,["config"]);return n!=null&&m2(n,e),e}function x2(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["nextPageToken"]);i!=null&&x(e,["nextPageToken"],i);const r=m(t,["cachedContents"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(c=>c)),x(e,["cachedContents"],a)}return e}function y2(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["nextPageToken"]);i!=null&&x(e,["nextPageToken"],i);const r=m(t,["cachedContents"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(c=>c)),x(e,["cachedContents"],a)}return e}function _2(t){const e={},n=m(t,["mediaResolution"]);n!=null&&x(e,["mediaResolution"],n);const i=m(t,["codeExecutionResult"]);i!=null&&x(e,["codeExecutionResult"],i);const r=m(t,["executableCode"]);r!=null&&x(e,["executableCode"],r);const a=m(t,["fileData"]);a!=null&&x(e,["fileData"],r2(a));const c=m(t,["functionCall"]);c!=null&&x(e,["functionCall"],a2(c));const u=m(t,["functionResponse"]);u!=null&&x(e,["functionResponse"],u);const h=m(t,["inlineData"]);h!=null&&x(e,["inlineData"],KN(h));const d=m(t,["text"]);d!=null&&x(e,["text"],d);const g=m(t,["thought"]);g!=null&&x(e,["thought"],g);const v=m(t,["thoughtSignature"]);v!=null&&x(e,["thoughtSignature"],v);const y=m(t,["videoMetadata"]);return y!=null&&x(e,["videoMetadata"],y),e}function b2(t){const e={},n=m(t,["functionCallingConfig"]);n!=null&&x(e,["functionCallingConfig"],l2(n));const i=m(t,["retrievalConfig"]);return i!=null&&x(e,["retrievalConfig"],i),e}function S2(t){const e={},n=m(t,["functionDeclarations"]);if(n!=null){let g=n;Array.isArray(g)&&(g=g.map(v=>v)),x(e,["functionDeclarations"],g)}if(m(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");const i=m(t,["googleSearchRetrieval"]);i!=null&&x(e,["googleSearchRetrieval"],i);const r=m(t,["computerUse"]);r!=null&&x(e,["computerUse"],r);const a=m(t,["fileSearch"]);a!=null&&x(e,["fileSearch"],a);const c=m(t,["codeExecution"]);if(c!=null&&x(e,["codeExecution"],c),m(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const u=m(t,["googleMaps"]);u!=null&&x(e,["googleMaps"],f2(u));const h=m(t,["googleSearch"]);h!=null&&x(e,["googleSearch"],h2(h));const d=m(t,["urlContext"]);return d!=null&&x(e,["urlContext"],d),e}function T2(t){const e={},n=m(t,["functionDeclarations"]);if(n!=null){let v=n;Array.isArray(v)&&(v=v.map(y=>c2(y))),x(e,["functionDeclarations"],v)}const i=m(t,["retrieval"]);i!=null&&x(e,["retrieval"],i);const r=m(t,["googleSearchRetrieval"]);r!=null&&x(e,["googleSearchRetrieval"],r);const a=m(t,["computerUse"]);if(a!=null&&x(e,["computerUse"],a),m(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Vertex AI.");const c=m(t,["codeExecution"]);c!=null&&x(e,["codeExecution"],c);const u=m(t,["enterpriseWebSearch"]);u!=null&&x(e,["enterpriseWebSearch"],u);const h=m(t,["googleMaps"]);h!=null&&x(e,["googleMaps"],h);const d=m(t,["googleSearch"]);d!=null&&x(e,["googleSearch"],d);const g=m(t,["urlContext"]);return g!=null&&x(e,["urlContext"],g),e}function E2(t,e){const n={},i=m(t,["ttl"]);e!==void 0&&i!=null&&x(e,["ttl"],i);const r=m(t,["expireTime"]);return e!==void 0&&r!=null&&x(e,["expireTime"],r),n}function w2(t,e){const n={},i=m(t,["ttl"]);e!==void 0&&i!=null&&x(e,["ttl"],i);const r=m(t,["expireTime"]);return e!==void 0&&r!=null&&x(e,["expireTime"],r),n}function M2(t,e){const n={},i=m(e,["name"]);i!=null&&x(n,["_url","name"],Sr(t,i));const r=m(e,["config"]);return r!=null&&E2(r,n),n}function C2(t,e){const n={},i=m(e,["name"]);i!=null&&x(n,["_url","name"],Sr(t,i));const r=m(e,["config"]);return r!=null&&w2(r,n),n}class A2 extends br{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new Xa(xr.PAGED_ITEM_CACHED_CONTENTS,i=>this.listInternal(i),await this.listInternal(n),n)}async create(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=t2(this.apiClient,e);return u=Et("cachedContents",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json()),c.then(g=>g)}else{const d=e2(this.apiClient,e);return u=Et("cachedContents",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json()),c.then(g=>g)}}async get(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=d2(this.apiClient,e);return u=Et("{name}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json()),c.then(g=>g)}else{const d=u2(this.apiClient,e);return u=Et("{name}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json()),c.then(g=>g)}}async delete(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=i2(this.apiClient,e);return u=Et("{name}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=s2(g),y=new TS;return Object.assign(y,v),y})}else{const d=n2(this.apiClient,e);return u=Et("{name}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=o2(g),y=new TS;return Object.assign(y,v),y})}}async update(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=C2(this.apiClient,e);return u=Et("{name}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json()),c.then(g=>g)}else{const d=M2(this.apiClient,e);return u=Et("{name}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json()),c.then(g=>g)}}async listInternal(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=v2(e);return u=Et("cachedContents",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=y2(g),y=new ES;return Object.assign(y,v),y})}else{const d=g2(e);return u=Et("cachedContents",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=x2(g),y=new ES;return Object.assign(y,v),y})}}}function th(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(t);r=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Kt(t){return this instanceof Kt?(this.v=t,this):new Kt(t)}function Ms(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(t,e||[]),r,a=[];return r=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),u("next"),u("throw"),u("return",c),r[Symbol.asyncIterator]=function(){return this},r;function c(S){return function(T){return Promise.resolve(T).then(S,v)}}function u(S,T){i[S]&&(r[S]=function(A){return new Promise(function(E,w){a.push([S,A,E,w])>1||h(S,A)})},T&&(r[S]=T(r[S])))}function h(S,T){try{d(i[S](T))}catch(A){y(a[0][3],A)}}function d(S){S.value instanceof Kt?Promise.resolve(S.value.v).then(g,v):y(a[0][2],S)}function g(S){h("next",S)}function v(S){h("throw",S)}function y(S,T){S(T),a.shift(),a.length&&h(a[0][0],a[0][1])}}function Cs(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof IS=="function"?IS(t):t[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(a){n[a]=t[a]&&function(c){return new Promise(function(u,h){c=t[a](c),r(u,h,c.done,c.value)})}}function r(a,c,u,h){Promise.resolve(h).then(function(d){a({value:d,done:u})},c)}}function R2(t){var e;if(t.candidates==null||t.candidates.length===0)return!1;const n=(e=t.candidates[0])===null||e===void 0?void 0:e.content;return n===void 0?!1:LT(n)}function LT(t){if(t.parts===void 0||t.parts.length===0)return!1;for(const e of t.parts)if(e===void 0||Object.keys(e).length===0)return!1;return!0}function N2(t){if(t.length!==0){for(const e of t)if(e.role!=="user"&&e.role!=="model")throw new Error(`Role must be user or model, but got ${e.role}.`)}}function DS(t){if(t===void 0||t.length===0)return[];const e=[],n=t.length;let i=0;for(;i{var a,c,u;const h=await r,d=(c=(a=h.candidates)===null||a===void 0?void 0:a[0])===null||c===void 0?void 0:c.content,g=h.automaticFunctionCallingHistory,v=this.getHistory(!0).length;let y=[];g!=null&&(y=(u=g.slice(v))!==null&&u!==void 0?u:[]);const S=d?[d]:[];this.recordHistory(i,S,y)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),r}async sendMessageStream(e){var n;await this.sendPromise;const i=vo(e.message),r=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(i),config:(n=e.config)!==null&&n!==void 0?n:this.config});this.sendPromise=r.then(()=>{}).catch(()=>{});const a=await r;return this.processStreamResponse(a,i)}getHistory(e=!1){const n=e?DS(this.history):this.history;return structuredClone(n)}processStreamResponse(e,n){return Ms(this,arguments,function*(){var r,a,c,u,h,d;const g=[];try{for(var v=!0,y=Cs(e),S;S=yield Kt(y.next()),r=S.done,!r;v=!0){u=S.value,v=!1;const T=u;if(R2(T)){const A=(d=(h=T.candidates)===null||h===void 0?void 0:h[0])===null||d===void 0?void 0:d.content;A!==void 0&&g.push(A)}yield yield Kt(T)}}catch(T){a={error:T}}finally{try{!v&&!r&&(c=y.return)&&(yield Kt(c.call(y)))}finally{if(a)throw a.error}}this.recordHistory(n,g)})}recordHistory(e,n,i){let r=[];n.length>0&&n.every(a=>a.role!==void 0)?r=n:r.push({role:"model",parts:[]}),i&&i.length>0?this.history.push(...DS(i)):this.history.push(e),this.history.push(...r)}}class yh extends Error{constructor(e){super(e.message),this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,yh.prototype)}}function L2(t){const e={},n=m(t,["file"]);return n!=null&&x(e,["file"],n),e}function U2(t){const e={},n=m(t,["sdkHttpResponse"]);return n!=null&&x(e,["sdkHttpResponse"],n),e}function k2(t){const e={},n=m(t,["name"]);return n!=null&&x(e,["_url","file"],MT(n)),e}function z2(t){const e={},n=m(t,["sdkHttpResponse"]);return n!=null&&x(e,["sdkHttpResponse"],n),e}function P2(t){const e={},n=m(t,["name"]);return n!=null&&x(e,["_url","file"],MT(n)),e}function F2(t,e){const n={},i=m(t,["pageSize"]);e!==void 0&&i!=null&&x(e,["_query","pageSize"],i);const r=m(t,["pageToken"]);return e!==void 0&&r!=null&&x(e,["_query","pageToken"],r),n}function O2(t){const e={},n=m(t,["config"]);return n!=null&&F2(n,e),e}function B2(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["nextPageToken"]);i!=null&&x(e,["nextPageToken"],i);const r=m(t,["files"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(c=>c)),x(e,["files"],a)}return e}class V2 extends br{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new Xa(xr.PAGED_ITEM_FILES,i=>this.listInternal(i),await this.listInternal(n),n)}async upload(e){if(this.apiClient.isVertexAI())throw new Error("Vertex AI does not support uploading files. You can share files through a GCS bucket.");return this.apiClient.uploadFile(e.file,e.config).then(n=>n)}async download(e){await this.apiClient.downloadFile(e)}async listInternal(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=O2(e);return a=Et("files",u._url),c=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(h=>h.json().then(d=>{const g=d;return g.sdkHttpResponse={headers:h.headers},g})),r.then(h=>{const d=B2(h),g=new qR;return Object.assign(g,d),g})}}async createInternal(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=L2(e);return a=Et("upload/v1beta/files",u._url),c=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(h=>h.json()),r.then(h=>{const d=U2(h),g=new WR;return Object.assign(g,d),g})}}async get(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=P2(e);return a=Et("files/{file}",u._url),c=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(h=>h.json()),r.then(h=>h)}}async delete(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=k2(e);return a=Et("files/{file}",u._url),c=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(h=>h.json().then(d=>{const g=d;return g.sdkHttpResponse={headers:h.headers},g})),r.then(h=>{const d=z2(h),g=new $R;return Object.assign(g,d),g})}}}function Lf(t){const e={},n=m(t,["data"]);if(n!=null&&x(e,["data"],n),m(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const i=m(t,["mimeType"]);return i!=null&&x(e,["mimeType"],i),e}function H2(t){const e={},n=m(t,["parts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(a=>oI(a))),x(e,["parts"],r)}const i=m(t,["role"]);return i!=null&&x(e,["role"],i),e}function G2(t){const e={};if(m(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const n=m(t,["fileUri"]);n!=null&&x(e,["fileUri"],n);const i=m(t,["mimeType"]);return i!=null&&x(e,["mimeType"],i),e}function j2(t){const e={},n=m(t,["id"]);n!=null&&x(e,["id"],n);const i=m(t,["args"]);i!=null&&x(e,["args"],i);const r=m(t,["name"]);if(r!=null&&x(e,["name"],r),m(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(m(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}function q2(t){const e={};if(m(t,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Vertex AI.");const n=m(t,["description"]);n!=null&&x(e,["description"],n);const i=m(t,["name"]);i!=null&&x(e,["name"],i);const r=m(t,["parameters"]);r!=null&&x(e,["parameters"],r);const a=m(t,["parametersJsonSchema"]);a!=null&&x(e,["parametersJsonSchema"],a);const c=m(t,["response"]);c!=null&&x(e,["response"],c);const u=m(t,["responseJsonSchema"]);return u!=null&&x(e,["responseJsonSchema"],u),e}function W2(t){const e={},n=m(t,["modelSelectionConfig"]);n!=null&&x(e,["modelConfig"],n);const i=m(t,["responseJsonSchema"]);i!=null&&x(e,["responseJsonSchema"],i);const r=m(t,["audioTimestamp"]);r!=null&&x(e,["audioTimestamp"],r);const a=m(t,["candidateCount"]);a!=null&&x(e,["candidateCount"],a);const c=m(t,["enableAffectiveDialog"]);c!=null&&x(e,["enableAffectiveDialog"],c);const u=m(t,["frequencyPenalty"]);u!=null&&x(e,["frequencyPenalty"],u);const h=m(t,["logprobs"]);h!=null&&x(e,["logprobs"],h);const d=m(t,["maxOutputTokens"]);d!=null&&x(e,["maxOutputTokens"],d);const g=m(t,["mediaResolution"]);g!=null&&x(e,["mediaResolution"],g);const v=m(t,["presencePenalty"]);v!=null&&x(e,["presencePenalty"],v);const y=m(t,["responseLogprobs"]);y!=null&&x(e,["responseLogprobs"],y);const S=m(t,["responseMimeType"]);S!=null&&x(e,["responseMimeType"],S);const T=m(t,["responseModalities"]);T!=null&&x(e,["responseModalities"],T);const A=m(t,["responseSchema"]);A!=null&&x(e,["responseSchema"],A);const E=m(t,["routingConfig"]);E!=null&&x(e,["routingConfig"],E);const w=m(t,["seed"]);w!=null&&x(e,["seed"],w);const I=m(t,["speechConfig"]);I!=null&&x(e,["speechConfig"],I);const L=m(t,["stopSequences"]);L!=null&&x(e,["stopSequences"],L);const D=m(t,["temperature"]);D!=null&&x(e,["temperature"],D);const W=m(t,["thinkingConfig"]);W!=null&&x(e,["thinkingConfig"],W);const V=m(t,["topK"]);V!=null&&x(e,["topK"],V);const H=m(t,["topP"]);if(H!=null&&x(e,["topP"],H),m(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return e}function $2(t){const e={};if(m(t,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");const n=m(t,["enableWidget"]);return n!=null&&x(e,["enableWidget"],n),e}function X2(t){const e={};if(m(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(m(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");const n=m(t,["timeRangeFilter"]);return n!=null&&x(e,["timeRangeFilter"],n),e}function Y2(t,e){const n={},i=m(t,["generationConfig"]);e!==void 0&&i!=null&&x(e,["setup","generationConfig"],i);const r=m(t,["responseModalities"]);e!==void 0&&r!=null&&x(e,["setup","generationConfig","responseModalities"],r);const a=m(t,["temperature"]);e!==void 0&&a!=null&&x(e,["setup","generationConfig","temperature"],a);const c=m(t,["topP"]);e!==void 0&&c!=null&&x(e,["setup","generationConfig","topP"],c);const u=m(t,["topK"]);e!==void 0&&u!=null&&x(e,["setup","generationConfig","topK"],u);const h=m(t,["maxOutputTokens"]);e!==void 0&&h!=null&&x(e,["setup","generationConfig","maxOutputTokens"],h);const d=m(t,["mediaResolution"]);e!==void 0&&d!=null&&x(e,["setup","generationConfig","mediaResolution"],d);const g=m(t,["seed"]);e!==void 0&&g!=null&&x(e,["setup","generationConfig","seed"],g);const v=m(t,["speechConfig"]);e!==void 0&&v!=null&&x(e,["setup","generationConfig","speechConfig"],$g(v));const y=m(t,["thinkingConfig"]);e!==void 0&&y!=null&&x(e,["setup","generationConfig","thinkingConfig"],y);const S=m(t,["enableAffectiveDialog"]);e!==void 0&&S!=null&&x(e,["setup","generationConfig","enableAffectiveDialog"],S);const T=m(t,["systemInstruction"]);e!==void 0&&T!=null&&x(e,["setup","systemInstruction"],H2(vo(T)));const A=m(t,["tools"]);if(e!==void 0&&A!=null){let V=gc(A);Array.isArray(V)&&(V=V.map(H=>rI(mc(H)))),x(e,["setup","tools"],V)}const E=m(t,["sessionResumption"]);e!==void 0&&E!=null&&x(e,["setup","sessionResumption"],sI(E));const w=m(t,["inputAudioTranscription"]);e!==void 0&&w!=null&&x(e,["setup","inputAudioTranscription"],w);const I=m(t,["outputAudioTranscription"]);e!==void 0&&I!=null&&x(e,["setup","outputAudioTranscription"],I);const L=m(t,["realtimeInputConfig"]);e!==void 0&&L!=null&&x(e,["setup","realtimeInputConfig"],L);const D=m(t,["contextWindowCompression"]);e!==void 0&&D!=null&&x(e,["setup","contextWindowCompression"],D);const W=m(t,["proactivity"]);if(e!==void 0&&W!=null&&x(e,["setup","proactivity"],W),m(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");return n}function J2(t,e){const n={},i=m(t,["generationConfig"]);e!==void 0&&i!=null&&x(e,["setup","generationConfig"],W2(i));const r=m(t,["responseModalities"]);e!==void 0&&r!=null&&x(e,["setup","generationConfig","responseModalities"],r);const a=m(t,["temperature"]);e!==void 0&&a!=null&&x(e,["setup","generationConfig","temperature"],a);const c=m(t,["topP"]);e!==void 0&&c!=null&&x(e,["setup","generationConfig","topP"],c);const u=m(t,["topK"]);e!==void 0&&u!=null&&x(e,["setup","generationConfig","topK"],u);const h=m(t,["maxOutputTokens"]);e!==void 0&&h!=null&&x(e,["setup","generationConfig","maxOutputTokens"],h);const d=m(t,["mediaResolution"]);e!==void 0&&d!=null&&x(e,["setup","generationConfig","mediaResolution"],d);const g=m(t,["seed"]);e!==void 0&&g!=null&&x(e,["setup","generationConfig","seed"],g);const v=m(t,["speechConfig"]);e!==void 0&&v!=null&&x(e,["setup","generationConfig","speechConfig"],$g(v));const y=m(t,["thinkingConfig"]);e!==void 0&&y!=null&&x(e,["setup","generationConfig","thinkingConfig"],y);const S=m(t,["enableAffectiveDialog"]);e!==void 0&&S!=null&&x(e,["setup","generationConfig","enableAffectiveDialog"],S);const T=m(t,["systemInstruction"]);e!==void 0&&T!=null&&x(e,["setup","systemInstruction"],vo(T));const A=m(t,["tools"]);if(e!==void 0&&A!=null){let H=gc(A);Array.isArray(H)&&(H=H.map(Q=>aI(mc(Q)))),x(e,["setup","tools"],H)}const E=m(t,["sessionResumption"]);e!==void 0&&E!=null&&x(e,["setup","sessionResumption"],E);const w=m(t,["inputAudioTranscription"]);e!==void 0&&w!=null&&x(e,["setup","inputAudioTranscription"],w);const I=m(t,["outputAudioTranscription"]);e!==void 0&&I!=null&&x(e,["setup","outputAudioTranscription"],I);const L=m(t,["realtimeInputConfig"]);e!==void 0&&L!=null&&x(e,["setup","realtimeInputConfig"],L);const D=m(t,["contextWindowCompression"]);e!==void 0&&D!=null&&x(e,["setup","contextWindowCompression"],D);const W=m(t,["proactivity"]);e!==void 0&&W!=null&&x(e,["setup","proactivity"],W);const V=m(t,["explicitVadSignal"]);return e!==void 0&&V!=null&&x(e,["setup","explicitVadSignal"],V),n}function K2(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["setup","model"],zn(t,i));const r=m(e,["config"]);return r!=null&&x(n,["config"],Y2(r,n)),n}function Z2(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["setup","model"],zn(t,i));const r=m(e,["config"]);return r!=null&&x(n,["config"],J2(r,n)),n}function Q2(t){const e={},n=m(t,["musicGenerationConfig"]);return n!=null&&x(e,["musicGenerationConfig"],n),e}function eI(t){const e={},n=m(t,["weightedPrompts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(r=>r)),x(e,["weightedPrompts"],i)}return e}function tI(t){const e={},n=m(t,["media"]);if(n!=null){let d=bT(n);Array.isArray(d)&&(d=d.map(g=>Lf(g))),x(e,["mediaChunks"],d)}const i=m(t,["audio"]);i!=null&&x(e,["audio"],Lf(TT(i)));const r=m(t,["audioStreamEnd"]);r!=null&&x(e,["audioStreamEnd"],r);const a=m(t,["video"]);a!=null&&x(e,["video"],Lf(ST(a)));const c=m(t,["text"]);c!=null&&x(e,["text"],c);const u=m(t,["activityStart"]);u!=null&&x(e,["activityStart"],u);const h=m(t,["activityEnd"]);return h!=null&&x(e,["activityEnd"],h),e}function nI(t){const e={},n=m(t,["media"]);if(n!=null){let d=bT(n);Array.isArray(d)&&(d=d.map(g=>g)),x(e,["mediaChunks"],d)}const i=m(t,["audio"]);i!=null&&x(e,["audio"],TT(i));const r=m(t,["audioStreamEnd"]);r!=null&&x(e,["audioStreamEnd"],r);const a=m(t,["video"]);a!=null&&x(e,["video"],ST(a));const c=m(t,["text"]);c!=null&&x(e,["text"],c);const u=m(t,["activityStart"]);u!=null&&x(e,["activityStart"],u);const h=m(t,["activityEnd"]);return h!=null&&x(e,["activityEnd"],h),e}function iI(t){const e={},n=m(t,["setupComplete"]);n!=null&&x(e,["setupComplete"],n);const i=m(t,["serverContent"]);i!=null&&x(e,["serverContent"],i);const r=m(t,["toolCall"]);r!=null&&x(e,["toolCall"],r);const a=m(t,["toolCallCancellation"]);a!=null&&x(e,["toolCallCancellation"],a);const c=m(t,["usageMetadata"]);c!=null&&x(e,["usageMetadata"],lI(c));const u=m(t,["goAway"]);u!=null&&x(e,["goAway"],u);const h=m(t,["sessionResumptionUpdate"]);h!=null&&x(e,["sessionResumptionUpdate"],h);const d=m(t,["voiceActivityDetectionSignal"]);return d!=null&&x(e,["voiceActivityDetectionSignal"],d),e}function oI(t){const e={},n=m(t,["mediaResolution"]);n!=null&&x(e,["mediaResolution"],n);const i=m(t,["codeExecutionResult"]);i!=null&&x(e,["codeExecutionResult"],i);const r=m(t,["executableCode"]);r!=null&&x(e,["executableCode"],r);const a=m(t,["fileData"]);a!=null&&x(e,["fileData"],G2(a));const c=m(t,["functionCall"]);c!=null&&x(e,["functionCall"],j2(c));const u=m(t,["functionResponse"]);u!=null&&x(e,["functionResponse"],u);const h=m(t,["inlineData"]);h!=null&&x(e,["inlineData"],Lf(h));const d=m(t,["text"]);d!=null&&x(e,["text"],d);const g=m(t,["thought"]);g!=null&&x(e,["thought"],g);const v=m(t,["thoughtSignature"]);v!=null&&x(e,["thoughtSignature"],v);const y=m(t,["videoMetadata"]);return y!=null&&x(e,["videoMetadata"],y),e}function sI(t){const e={},n=m(t,["handle"]);if(n!=null&&x(e,["handle"],n),m(t,["transparent"])!==void 0)throw new Error("transparent parameter is not supported in Gemini API.");return e}function rI(t){const e={},n=m(t,["functionDeclarations"]);if(n!=null){let g=n;Array.isArray(g)&&(g=g.map(v=>v)),x(e,["functionDeclarations"],g)}if(m(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");const i=m(t,["googleSearchRetrieval"]);i!=null&&x(e,["googleSearchRetrieval"],i);const r=m(t,["computerUse"]);r!=null&&x(e,["computerUse"],r);const a=m(t,["fileSearch"]);a!=null&&x(e,["fileSearch"],a);const c=m(t,["codeExecution"]);if(c!=null&&x(e,["codeExecution"],c),m(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const u=m(t,["googleMaps"]);u!=null&&x(e,["googleMaps"],$2(u));const h=m(t,["googleSearch"]);h!=null&&x(e,["googleSearch"],X2(h));const d=m(t,["urlContext"]);return d!=null&&x(e,["urlContext"],d),e}function aI(t){const e={},n=m(t,["functionDeclarations"]);if(n!=null){let v=n;Array.isArray(v)&&(v=v.map(y=>q2(y))),x(e,["functionDeclarations"],v)}const i=m(t,["retrieval"]);i!=null&&x(e,["retrieval"],i);const r=m(t,["googleSearchRetrieval"]);r!=null&&x(e,["googleSearchRetrieval"],r);const a=m(t,["computerUse"]);if(a!=null&&x(e,["computerUse"],a),m(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Vertex AI.");const c=m(t,["codeExecution"]);c!=null&&x(e,["codeExecution"],c);const u=m(t,["enterpriseWebSearch"]);u!=null&&x(e,["enterpriseWebSearch"],u);const h=m(t,["googleMaps"]);h!=null&&x(e,["googleMaps"],h);const d=m(t,["googleSearch"]);d!=null&&x(e,["googleSearch"],d);const g=m(t,["urlContext"]);return g!=null&&x(e,["urlContext"],g),e}function lI(t){const e={},n=m(t,["promptTokenCount"]);n!=null&&x(e,["promptTokenCount"],n);const i=m(t,["cachedContentTokenCount"]);i!=null&&x(e,["cachedContentTokenCount"],i);const r=m(t,["candidatesTokenCount"]);r!=null&&x(e,["responseTokenCount"],r);const a=m(t,["toolUsePromptTokenCount"]);a!=null&&x(e,["toolUsePromptTokenCount"],a);const c=m(t,["thoughtsTokenCount"]);c!=null&&x(e,["thoughtsTokenCount"],c);const u=m(t,["totalTokenCount"]);u!=null&&x(e,["totalTokenCount"],u);const h=m(t,["promptTokensDetails"]);if(h!=null){let S=h;Array.isArray(S)&&(S=S.map(T=>T)),x(e,["promptTokensDetails"],S)}const d=m(t,["cacheTokensDetails"]);if(d!=null){let S=d;Array.isArray(S)&&(S=S.map(T=>T)),x(e,["cacheTokensDetails"],S)}const g=m(t,["candidatesTokensDetails"]);if(g!=null){let S=g;Array.isArray(S)&&(S=S.map(T=>T)),x(e,["responseTokensDetails"],S)}const v=m(t,["toolUsePromptTokensDetails"]);if(v!=null){let S=v;Array.isArray(S)&&(S=S.map(T=>T)),x(e,["toolUsePromptTokensDetails"],S)}const y=m(t,["trafficType"]);return y!=null&&x(e,["trafficType"],y),e}function cI(t){const e={},n=m(t,["data"]);if(n!=null&&x(e,["data"],n),m(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const i=m(t,["mimeType"]);return i!=null&&x(e,["mimeType"],i),e}function uI(t){const e={},n=m(t,["content"]);n!=null&&x(e,["content"],n);const i=m(t,["citationMetadata"]);i!=null&&x(e,["citationMetadata"],dI(i));const r=m(t,["tokenCount"]);r!=null&&x(e,["tokenCount"],r);const a=m(t,["finishReason"]);a!=null&&x(e,["finishReason"],a);const c=m(t,["avgLogprobs"]);c!=null&&x(e,["avgLogprobs"],c);const u=m(t,["groundingMetadata"]);u!=null&&x(e,["groundingMetadata"],u);const h=m(t,["index"]);h!=null&&x(e,["index"],h);const d=m(t,["logprobsResult"]);d!=null&&x(e,["logprobsResult"],d);const g=m(t,["safetyRatings"]);if(g!=null){let y=g;Array.isArray(y)&&(y=y.map(S=>S)),x(e,["safetyRatings"],y)}const v=m(t,["urlContextMetadata"]);return v!=null&&x(e,["urlContextMetadata"],v),e}function dI(t){const e={},n=m(t,["citationSources"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(r=>r)),x(e,["citations"],i)}return e}function fI(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["_url","model"],zn(t,i));const r=m(e,["contents"]);if(r!=null){let a=hs(r);Array.isArray(a)&&(a=a.map(c=>c)),x(n,["contents"],a)}return n}function hI(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["tokensInfo"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>a)),x(e,["tokensInfo"],r)}return e}function pI(t){const e={},n=m(t,["values"]);n!=null&&x(e,["values"],n);const i=m(t,["statistics"]);return i!=null&&x(e,["statistics"],mI(i)),e}function mI(t){const e={},n=m(t,["truncated"]);n!=null&&x(e,["truncated"],n);const i=m(t,["token_count"]);return i!=null&&x(e,["tokenCount"],i),e}function _h(t){const e={},n=m(t,["parts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(a=>ED(a))),x(e,["parts"],r)}const i=m(t,["role"]);return i!=null&&x(e,["role"],i),e}function gI(t){const e={},n=m(t,["controlType"]);n!=null&&x(e,["controlType"],n);const i=m(t,["enableControlImageComputation"]);return i!=null&&x(e,["computeControl"],i),e}function vI(t){const e={};if(m(t,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is not supported in Gemini API.");if(m(t,["tools"])!==void 0)throw new Error("tools parameter is not supported in Gemini API.");if(m(t,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is not supported in Gemini API.");return e}function xI(t,e){const n={},i=m(t,["systemInstruction"]);e!==void 0&&i!=null&&x(e,["systemInstruction"],vo(i));const r=m(t,["tools"]);if(e!==void 0&&r!=null){let c=r;Array.isArray(c)&&(c=c.map(u=>PT(u))),x(e,["tools"],c)}const a=m(t,["generationConfig"]);return e!==void 0&&a!=null&&x(e,["generationConfig"],cD(a)),n}function yI(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["_url","model"],zn(t,i));const r=m(e,["contents"]);if(r!=null){let c=hs(r);Array.isArray(c)&&(c=c.map(u=>_h(u))),x(n,["contents"],c)}const a=m(e,["config"]);return a!=null&&vI(a),n}function _I(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["_url","model"],zn(t,i));const r=m(e,["contents"]);if(r!=null){let c=hs(r);Array.isArray(c)&&(c=c.map(u=>u)),x(n,["contents"],c)}const a=m(e,["config"]);return a!=null&&xI(a,n),n}function bI(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["totalTokens"]);i!=null&&x(e,["totalTokens"],i);const r=m(t,["cachedContentTokenCount"]);return r!=null&&x(e,["cachedContentTokenCount"],r),e}function SI(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["totalTokens"]);return i!=null&&x(e,["totalTokens"],i),e}function TI(t,e){const n={},i=m(e,["model"]);return i!=null&&x(n,["_url","name"],zn(t,i)),n}function EI(t,e){const n={},i=m(e,["model"]);return i!=null&&x(n,["_url","name"],zn(t,i)),n}function wI(t){const e={},n=m(t,["sdkHttpResponse"]);return n!=null&&x(e,["sdkHttpResponse"],n),e}function MI(t){const e={},n=m(t,["sdkHttpResponse"]);return n!=null&&x(e,["sdkHttpResponse"],n),e}function CI(t,e){const n={},i=m(t,["outputGcsUri"]);e!==void 0&&i!=null&&x(e,["parameters","storageUri"],i);const r=m(t,["negativePrompt"]);e!==void 0&&r!=null&&x(e,["parameters","negativePrompt"],r);const a=m(t,["numberOfImages"]);e!==void 0&&a!=null&&x(e,["parameters","sampleCount"],a);const c=m(t,["aspectRatio"]);e!==void 0&&c!=null&&x(e,["parameters","aspectRatio"],c);const u=m(t,["guidanceScale"]);e!==void 0&&u!=null&&x(e,["parameters","guidanceScale"],u);const h=m(t,["seed"]);e!==void 0&&h!=null&&x(e,["parameters","seed"],h);const d=m(t,["safetyFilterLevel"]);e!==void 0&&d!=null&&x(e,["parameters","safetySetting"],d);const g=m(t,["personGeneration"]);e!==void 0&&g!=null&&x(e,["parameters","personGeneration"],g);const v=m(t,["includeSafetyAttributes"]);e!==void 0&&v!=null&&x(e,["parameters","includeSafetyAttributes"],v);const y=m(t,["includeRaiReason"]);e!==void 0&&y!=null&&x(e,["parameters","includeRaiReason"],y);const S=m(t,["language"]);e!==void 0&&S!=null&&x(e,["parameters","language"],S);const T=m(t,["outputMimeType"]);e!==void 0&&T!=null&&x(e,["parameters","outputOptions","mimeType"],T);const A=m(t,["outputCompressionQuality"]);e!==void 0&&A!=null&&x(e,["parameters","outputOptions","compressionQuality"],A);const E=m(t,["addWatermark"]);e!==void 0&&E!=null&&x(e,["parameters","addWatermark"],E);const w=m(t,["labels"]);e!==void 0&&w!=null&&x(e,["labels"],w);const I=m(t,["editMode"]);e!==void 0&&I!=null&&x(e,["parameters","editMode"],I);const L=m(t,["baseSteps"]);return e!==void 0&&L!=null&&x(e,["parameters","editConfig","baseSteps"],L),n}function AI(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["_url","model"],zn(t,i));const r=m(e,["prompt"]);r!=null&&x(n,["instances[0]","prompt"],r);const a=m(e,["referenceImages"]);if(a!=null){let u=a;Array.isArray(u)&&(u=u.map(h=>ND(h))),x(n,["instances[0]","referenceImages"],u)}const c=m(e,["config"]);return c!=null&&CI(c,n),n}function RI(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["predictions"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>bh(a))),x(e,["generatedImages"],r)}return e}function NI(t,e){const n={},i=m(t,["taskType"]);e!==void 0&&i!=null&&x(e,["requests[]","taskType"],i);const r=m(t,["title"]);e!==void 0&&r!=null&&x(e,["requests[]","title"],r);const a=m(t,["outputDimensionality"]);if(e!==void 0&&a!=null&&x(e,["requests[]","outputDimensionality"],a),m(t,["mimeType"])!==void 0)throw new Error("mimeType parameter is not supported in Gemini API.");if(m(t,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is not supported in Gemini API.");return n}function II(t,e){const n={},i=m(t,["taskType"]);e!==void 0&&i!=null&&x(e,["instances[]","task_type"],i);const r=m(t,["title"]);e!==void 0&&r!=null&&x(e,["instances[]","title"],r);const a=m(t,["outputDimensionality"]);e!==void 0&&a!=null&&x(e,["parameters","outputDimensionality"],a);const c=m(t,["mimeType"]);e!==void 0&&c!=null&&x(e,["instances[]","mimeType"],c);const u=m(t,["autoTruncate"]);return e!==void 0&&u!=null&&x(e,["parameters","autoTruncate"],u),n}function DI(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["_url","model"],zn(t,i));const r=m(e,["contents"]);if(r!=null){let u=jg(t,r);Array.isArray(u)&&(u=u.map(h=>h)),x(n,["requests[]","content"],u)}const a=m(e,["config"]);a!=null&&NI(a,n);const c=m(e,["model"]);return c!==void 0&&x(n,["requests[]","model"],zn(t,c)),n}function LI(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["_url","model"],zn(t,i));const r=m(e,["contents"]);if(r!=null){let c=jg(t,r);Array.isArray(c)&&(c=c.map(u=>u)),x(n,["instances[]","content"],c)}const a=m(e,["config"]);return a!=null&&II(a,n),n}function UI(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["embeddings"]);if(i!=null){let a=i;Array.isArray(a)&&(a=a.map(c=>c)),x(e,["embeddings"],a)}const r=m(t,["metadata"]);return r!=null&&x(e,["metadata"],r),e}function kI(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["predictions[]","embeddings"]);if(i!=null){let a=i;Array.isArray(a)&&(a=a.map(c=>pI(c))),x(e,["embeddings"],a)}const r=m(t,["metadata"]);return r!=null&&x(e,["metadata"],r),e}function zI(t){const e={},n=m(t,["endpoint"]);n!=null&&x(e,["name"],n);const i=m(t,["deployedModelId"]);return i!=null&&x(e,["deployedModelId"],i),e}function PI(t){const e={};if(m(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const n=m(t,["fileUri"]);n!=null&&x(e,["fileUri"],n);const i=m(t,["mimeType"]);return i!=null&&x(e,["mimeType"],i),e}function FI(t){const e={},n=m(t,["id"]);n!=null&&x(e,["id"],n);const i=m(t,["args"]);i!=null&&x(e,["args"],i);const r=m(t,["name"]);if(r!=null&&x(e,["name"],r),m(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(m(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}function OI(t){const e={},n=m(t,["mode"]);n!=null&&x(e,["mode"],n);const i=m(t,["allowedFunctionNames"]);if(i!=null&&x(e,["allowedFunctionNames"],i),m(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}function BI(t){const e={};if(m(t,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Vertex AI.");const n=m(t,["description"]);n!=null&&x(e,["description"],n);const i=m(t,["name"]);i!=null&&x(e,["name"],i);const r=m(t,["parameters"]);r!=null&&x(e,["parameters"],r);const a=m(t,["parametersJsonSchema"]);a!=null&&x(e,["parametersJsonSchema"],a);const c=m(t,["response"]);c!=null&&x(e,["response"],c);const u=m(t,["responseJsonSchema"]);return u!=null&&x(e,["responseJsonSchema"],u),e}function VI(t,e,n){const i={},r=m(e,["systemInstruction"]);n!==void 0&&r!=null&&x(n,["systemInstruction"],_h(vo(r)));const a=m(e,["temperature"]);a!=null&&x(i,["temperature"],a);const c=m(e,["topP"]);c!=null&&x(i,["topP"],c);const u=m(e,["topK"]);u!=null&&x(i,["topK"],u);const h=m(e,["candidateCount"]);h!=null&&x(i,["candidateCount"],h);const d=m(e,["maxOutputTokens"]);d!=null&&x(i,["maxOutputTokens"],d);const g=m(e,["stopSequences"]);g!=null&&x(i,["stopSequences"],g);const v=m(e,["responseLogprobs"]);v!=null&&x(i,["responseLogprobs"],v);const y=m(e,["logprobs"]);y!=null&&x(i,["logprobs"],y);const S=m(e,["presencePenalty"]);S!=null&&x(i,["presencePenalty"],S);const T=m(e,["frequencyPenalty"]);T!=null&&x(i,["frequencyPenalty"],T);const A=m(e,["seed"]);A!=null&&x(i,["seed"],A);const E=m(e,["responseMimeType"]);E!=null&&x(i,["responseMimeType"],E);const w=m(e,["responseSchema"]);w!=null&&x(i,["responseSchema"],qg(w));const I=m(e,["responseJsonSchema"]);if(I!=null&&x(i,["responseJsonSchema"],I),m(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is not supported in Gemini API.");if(m(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");const L=m(e,["safetySettings"]);if(n!==void 0&&L!=null){let fe=L;Array.isArray(fe)&&(fe=fe.map(Ee=>ID(Ee))),x(n,["safetySettings"],fe)}const D=m(e,["tools"]);if(n!==void 0&&D!=null){let fe=gc(D);Array.isArray(fe)&&(fe=fe.map(Ee=>FD(mc(Ee)))),x(n,["tools"],fe)}const W=m(e,["toolConfig"]);if(n!==void 0&&W!=null&&x(n,["toolConfig"],PD(W)),m(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");const V=m(e,["cachedContent"]);n!==void 0&&V!=null&&x(n,["cachedContent"],Sr(t,V));const H=m(e,["responseModalities"]);H!=null&&x(i,["responseModalities"],H);const Q=m(e,["mediaResolution"]);Q!=null&&x(i,["mediaResolution"],Q);const k=m(e,["speechConfig"]);if(k!=null&&x(i,["speechConfig"],Wg(k)),m(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");const P=m(e,["thinkingConfig"]);P!=null&&x(i,["thinkingConfig"],P);const J=m(e,["imageConfig"]);J!=null&&x(i,["imageConfig"],pD(J));const ve=m(e,["enableEnhancedCivicAnswers"]);return ve!=null&&x(i,["enableEnhancedCivicAnswers"],ve),i}function HI(t,e,n){const i={},r=m(e,["systemInstruction"]);n!==void 0&&r!=null&&x(n,["systemInstruction"],vo(r));const a=m(e,["temperature"]);a!=null&&x(i,["temperature"],a);const c=m(e,["topP"]);c!=null&&x(i,["topP"],c);const u=m(e,["topK"]);u!=null&&x(i,["topK"],u);const h=m(e,["candidateCount"]);h!=null&&x(i,["candidateCount"],h);const d=m(e,["maxOutputTokens"]);d!=null&&x(i,["maxOutputTokens"],d);const g=m(e,["stopSequences"]);g!=null&&x(i,["stopSequences"],g);const v=m(e,["responseLogprobs"]);v!=null&&x(i,["responseLogprobs"],v);const y=m(e,["logprobs"]);y!=null&&x(i,["logprobs"],y);const S=m(e,["presencePenalty"]);S!=null&&x(i,["presencePenalty"],S);const T=m(e,["frequencyPenalty"]);T!=null&&x(i,["frequencyPenalty"],T);const A=m(e,["seed"]);A!=null&&x(i,["seed"],A);const E=m(e,["responseMimeType"]);E!=null&&x(i,["responseMimeType"],E);const w=m(e,["responseSchema"]);w!=null&&x(i,["responseSchema"],qg(w));const I=m(e,["responseJsonSchema"]);I!=null&&x(i,["responseJsonSchema"],I);const L=m(e,["routingConfig"]);L!=null&&x(i,["routingConfig"],L);const D=m(e,["modelSelectionConfig"]);D!=null&&x(i,["modelConfig"],D);const W=m(e,["safetySettings"]);if(n!==void 0&&W!=null){let X=W;Array.isArray(X)&&(X=X.map(_e=>_e)),x(n,["safetySettings"],X)}const V=m(e,["tools"]);if(n!==void 0&&V!=null){let X=gc(V);Array.isArray(X)&&(X=X.map(_e=>PT(mc(_e)))),x(n,["tools"],X)}const H=m(e,["toolConfig"]);n!==void 0&&H!=null&&x(n,["toolConfig"],H);const Q=m(e,["labels"]);n!==void 0&&Q!=null&&x(n,["labels"],Q);const k=m(e,["cachedContent"]);n!==void 0&&k!=null&&x(n,["cachedContent"],Sr(t,k));const P=m(e,["responseModalities"]);P!=null&&x(i,["responseModalities"],P);const J=m(e,["mediaResolution"]);J!=null&&x(i,["mediaResolution"],J);const ve=m(e,["speechConfig"]);ve!=null&&x(i,["speechConfig"],Wg(ve));const fe=m(e,["audioTimestamp"]);fe!=null&&x(i,["audioTimestamp"],fe);const Ee=m(e,["thinkingConfig"]);Ee!=null&&x(i,["thinkingConfig"],Ee);const je=m(e,["imageConfig"]);if(je!=null&&x(i,["imageConfig"],mD(je)),m(e,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return i}function LS(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["_url","model"],zn(t,i));const r=m(e,["contents"]);if(r!=null){let c=hs(r);Array.isArray(c)&&(c=c.map(u=>_h(u))),x(n,["contents"],c)}const a=m(e,["config"]);return a!=null&&x(n,["generationConfig"],VI(t,a,n)),n}function US(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["_url","model"],zn(t,i));const r=m(e,["contents"]);if(r!=null){let c=hs(r);Array.isArray(c)&&(c=c.map(u=>u)),x(n,["contents"],c)}const a=m(e,["config"]);return a!=null&&x(n,["generationConfig"],HI(t,a,n)),n}function kS(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["candidates"]);if(i!=null){let h=i;Array.isArray(h)&&(h=h.map(d=>uI(d))),x(e,["candidates"],h)}const r=m(t,["modelVersion"]);r!=null&&x(e,["modelVersion"],r);const a=m(t,["promptFeedback"]);a!=null&&x(e,["promptFeedback"],a);const c=m(t,["responseId"]);c!=null&&x(e,["responseId"],c);const u=m(t,["usageMetadata"]);return u!=null&&x(e,["usageMetadata"],u),e}function zS(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["candidates"]);if(i!=null){let d=i;Array.isArray(d)&&(d=d.map(g=>g)),x(e,["candidates"],d)}const r=m(t,["createTime"]);r!=null&&x(e,["createTime"],r);const a=m(t,["modelVersion"]);a!=null&&x(e,["modelVersion"],a);const c=m(t,["promptFeedback"]);c!=null&&x(e,["promptFeedback"],c);const u=m(t,["responseId"]);u!=null&&x(e,["responseId"],u);const h=m(t,["usageMetadata"]);return h!=null&&x(e,["usageMetadata"],h),e}function GI(t,e){const n={};if(m(t,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is not supported in Gemini API.");if(m(t,["negativePrompt"])!==void 0)throw new Error("negativePrompt parameter is not supported in Gemini API.");const i=m(t,["numberOfImages"]);e!==void 0&&i!=null&&x(e,["parameters","sampleCount"],i);const r=m(t,["aspectRatio"]);e!==void 0&&r!=null&&x(e,["parameters","aspectRatio"],r);const a=m(t,["guidanceScale"]);if(e!==void 0&&a!=null&&x(e,["parameters","guidanceScale"],a),m(t,["seed"])!==void 0)throw new Error("seed parameter is not supported in Gemini API.");const c=m(t,["safetyFilterLevel"]);e!==void 0&&c!=null&&x(e,["parameters","safetySetting"],c);const u=m(t,["personGeneration"]);e!==void 0&&u!=null&&x(e,["parameters","personGeneration"],u);const h=m(t,["includeSafetyAttributes"]);e!==void 0&&h!=null&&x(e,["parameters","includeSafetyAttributes"],h);const d=m(t,["includeRaiReason"]);e!==void 0&&d!=null&&x(e,["parameters","includeRaiReason"],d);const g=m(t,["language"]);e!==void 0&&g!=null&&x(e,["parameters","language"],g);const v=m(t,["outputMimeType"]);e!==void 0&&v!=null&&x(e,["parameters","outputOptions","mimeType"],v);const y=m(t,["outputCompressionQuality"]);if(e!==void 0&&y!=null&&x(e,["parameters","outputOptions","compressionQuality"],y),m(t,["addWatermark"])!==void 0)throw new Error("addWatermark parameter is not supported in Gemini API.");if(m(t,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");const S=m(t,["imageSize"]);if(e!==void 0&&S!=null&&x(e,["parameters","sampleImageSize"],S),m(t,["enhancePrompt"])!==void 0)throw new Error("enhancePrompt parameter is not supported in Gemini API.");return n}function jI(t,e){const n={},i=m(t,["outputGcsUri"]);e!==void 0&&i!=null&&x(e,["parameters","storageUri"],i);const r=m(t,["negativePrompt"]);e!==void 0&&r!=null&&x(e,["parameters","negativePrompt"],r);const a=m(t,["numberOfImages"]);e!==void 0&&a!=null&&x(e,["parameters","sampleCount"],a);const c=m(t,["aspectRatio"]);e!==void 0&&c!=null&&x(e,["parameters","aspectRatio"],c);const u=m(t,["guidanceScale"]);e!==void 0&&u!=null&&x(e,["parameters","guidanceScale"],u);const h=m(t,["seed"]);e!==void 0&&h!=null&&x(e,["parameters","seed"],h);const d=m(t,["safetyFilterLevel"]);e!==void 0&&d!=null&&x(e,["parameters","safetySetting"],d);const g=m(t,["personGeneration"]);e!==void 0&&g!=null&&x(e,["parameters","personGeneration"],g);const v=m(t,["includeSafetyAttributes"]);e!==void 0&&v!=null&&x(e,["parameters","includeSafetyAttributes"],v);const y=m(t,["includeRaiReason"]);e!==void 0&&y!=null&&x(e,["parameters","includeRaiReason"],y);const S=m(t,["language"]);e!==void 0&&S!=null&&x(e,["parameters","language"],S);const T=m(t,["outputMimeType"]);e!==void 0&&T!=null&&x(e,["parameters","outputOptions","mimeType"],T);const A=m(t,["outputCompressionQuality"]);e!==void 0&&A!=null&&x(e,["parameters","outputOptions","compressionQuality"],A);const E=m(t,["addWatermark"]);e!==void 0&&E!=null&&x(e,["parameters","addWatermark"],E);const w=m(t,["labels"]);e!==void 0&&w!=null&&x(e,["labels"],w);const I=m(t,["imageSize"]);e!==void 0&&I!=null&&x(e,["parameters","sampleImageSize"],I);const L=m(t,["enhancePrompt"]);return e!==void 0&&L!=null&&x(e,["parameters","enhancePrompt"],L),n}function qI(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["_url","model"],zn(t,i));const r=m(e,["prompt"]);r!=null&&x(n,["instances[0]","prompt"],r);const a=m(e,["config"]);return a!=null&&GI(a,n),n}function WI(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["_url","model"],zn(t,i));const r=m(e,["prompt"]);r!=null&&x(n,["instances[0]","prompt"],r);const a=m(e,["config"]);return a!=null&&jI(a,n),n}function $I(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["predictions"]);if(i!=null){let a=i;Array.isArray(a)&&(a=a.map(c=>sD(c))),x(e,["generatedImages"],a)}const r=m(t,["positivePromptSafetyAttributes"]);return r!=null&&x(e,["positivePromptSafetyAttributes"],kT(r)),e}function XI(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["predictions"]);if(i!=null){let a=i;Array.isArray(a)&&(a=a.map(c=>bh(c))),x(e,["generatedImages"],a)}const r=m(t,["positivePromptSafetyAttributes"]);return r!=null&&x(e,["positivePromptSafetyAttributes"],zT(r)),e}function YI(t,e){const n={},i=m(t,["numberOfVideos"]);if(e!==void 0&&i!=null&&x(e,["parameters","sampleCount"],i),m(t,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is not supported in Gemini API.");if(m(t,["fps"])!==void 0)throw new Error("fps parameter is not supported in Gemini API.");const r=m(t,["durationSeconds"]);if(e!==void 0&&r!=null&&x(e,["parameters","durationSeconds"],r),m(t,["seed"])!==void 0)throw new Error("seed parameter is not supported in Gemini API.");const a=m(t,["aspectRatio"]);e!==void 0&&a!=null&&x(e,["parameters","aspectRatio"],a);const c=m(t,["resolution"]);e!==void 0&&c!=null&&x(e,["parameters","resolution"],c);const u=m(t,["personGeneration"]);if(e!==void 0&&u!=null&&x(e,["parameters","personGeneration"],u),m(t,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is not supported in Gemini API.");const h=m(t,["negativePrompt"]);e!==void 0&&h!=null&&x(e,["parameters","negativePrompt"],h);const d=m(t,["enhancePrompt"]);if(e!==void 0&&d!=null&&x(e,["parameters","enhancePrompt"],d),m(t,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is not supported in Gemini API.");const g=m(t,["lastFrame"]);e!==void 0&&g!=null&&x(e,["instances[0]","lastFrame"],Sh(g));const v=m(t,["referenceImages"]);if(e!==void 0&&v!=null){let y=v;Array.isArray(y)&&(y=y.map(S=>KD(S))),x(e,["instances[0]","referenceImages"],y)}if(m(t,["mask"])!==void 0)throw new Error("mask parameter is not supported in Gemini API.");if(m(t,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is not supported in Gemini API.");return n}function JI(t,e){const n={},i=m(t,["numberOfVideos"]);e!==void 0&&i!=null&&x(e,["parameters","sampleCount"],i);const r=m(t,["outputGcsUri"]);e!==void 0&&r!=null&&x(e,["parameters","storageUri"],r);const a=m(t,["fps"]);e!==void 0&&a!=null&&x(e,["parameters","fps"],a);const c=m(t,["durationSeconds"]);e!==void 0&&c!=null&&x(e,["parameters","durationSeconds"],c);const u=m(t,["seed"]);e!==void 0&&u!=null&&x(e,["parameters","seed"],u);const h=m(t,["aspectRatio"]);e!==void 0&&h!=null&&x(e,["parameters","aspectRatio"],h);const d=m(t,["resolution"]);e!==void 0&&d!=null&&x(e,["parameters","resolution"],d);const g=m(t,["personGeneration"]);e!==void 0&&g!=null&&x(e,["parameters","personGeneration"],g);const v=m(t,["pubsubTopic"]);e!==void 0&&v!=null&&x(e,["parameters","pubsubTopic"],v);const y=m(t,["negativePrompt"]);e!==void 0&&y!=null&&x(e,["parameters","negativePrompt"],y);const S=m(t,["enhancePrompt"]);e!==void 0&&S!=null&&x(e,["parameters","enhancePrompt"],S);const T=m(t,["generateAudio"]);e!==void 0&&T!=null&&x(e,["parameters","generateAudio"],T);const A=m(t,["lastFrame"]);e!==void 0&&A!=null&&x(e,["instances[0]","lastFrame"],As(A));const E=m(t,["referenceImages"]);if(e!==void 0&&E!=null){let L=E;Array.isArray(L)&&(L=L.map(D=>ZD(D))),x(e,["instances[0]","referenceImages"],L)}const w=m(t,["mask"]);e!==void 0&&w!=null&&x(e,["instances[0]","mask"],JD(w));const I=m(t,["compressionQuality"]);return e!==void 0&&I!=null&&x(e,["parameters","compressionQuality"],I),n}function KI(t){const e={},n=m(t,["name"]);n!=null&&x(e,["name"],n);const i=m(t,["metadata"]);i!=null&&x(e,["metadata"],i);const r=m(t,["done"]);r!=null&&x(e,["done"],r);const a=m(t,["error"]);a!=null&&x(e,["error"],a);const c=m(t,["response","generateVideoResponse"]);return c!=null&&x(e,["response"],tD(c)),e}function ZI(t){const e={},n=m(t,["name"]);n!=null&&x(e,["name"],n);const i=m(t,["metadata"]);i!=null&&x(e,["metadata"],i);const r=m(t,["done"]);r!=null&&x(e,["done"],r);const a=m(t,["error"]);a!=null&&x(e,["error"],a);const c=m(t,["response"]);return c!=null&&x(e,["response"],nD(c)),e}function QI(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["_url","model"],zn(t,i));const r=m(e,["prompt"]);r!=null&&x(n,["instances[0]","prompt"],r);const a=m(e,["image"]);a!=null&&x(n,["instances[0]","image"],Sh(a));const c=m(e,["video"]);c!=null&&x(n,["instances[0]","video"],FT(c));const u=m(e,["source"]);u!=null&&iD(u,n);const h=m(e,["config"]);return h!=null&&YI(h,n),n}function eD(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["_url","model"],zn(t,i));const r=m(e,["prompt"]);r!=null&&x(n,["instances[0]","prompt"],r);const a=m(e,["image"]);a!=null&&x(n,["instances[0]","image"],As(a));const c=m(e,["video"]);c!=null&&x(n,["instances[0]","video"],OT(c));const u=m(e,["source"]);u!=null&&oD(u,n);const h=m(e,["config"]);return h!=null&&JI(h,n),n}function tD(t){const e={},n=m(t,["generatedSamples"]);if(n!=null){let a=n;Array.isArray(a)&&(a=a.map(c=>aD(c))),x(e,["generatedVideos"],a)}const i=m(t,["raiMediaFilteredCount"]);i!=null&&x(e,["raiMediaFilteredCount"],i);const r=m(t,["raiMediaFilteredReasons"]);return r!=null&&x(e,["raiMediaFilteredReasons"],r),e}function nD(t){const e={},n=m(t,["videos"]);if(n!=null){let a=n;Array.isArray(a)&&(a=a.map(c=>lD(c))),x(e,["generatedVideos"],a)}const i=m(t,["raiMediaFilteredCount"]);i!=null&&x(e,["raiMediaFilteredCount"],i);const r=m(t,["raiMediaFilteredReasons"]);return r!=null&&x(e,["raiMediaFilteredReasons"],r),e}function iD(t,e){const n={},i=m(t,["prompt"]);e!==void 0&&i!=null&&x(e,["instances[0]","prompt"],i);const r=m(t,["image"]);e!==void 0&&r!=null&&x(e,["instances[0]","image"],Sh(r));const a=m(t,["video"]);return e!==void 0&&a!=null&&x(e,["instances[0]","video"],FT(a)),n}function oD(t,e){const n={},i=m(t,["prompt"]);e!==void 0&&i!=null&&x(e,["instances[0]","prompt"],i);const r=m(t,["image"]);e!==void 0&&r!=null&&x(e,["instances[0]","image"],As(r));const a=m(t,["video"]);return e!==void 0&&a!=null&&x(e,["instances[0]","video"],OT(a)),n}function sD(t){const e={},n=m(t,["_self"]);n!=null&&x(e,["image"],gD(n));const i=m(t,["raiFilteredReason"]);i!=null&&x(e,["raiFilteredReason"],i);const r=m(t,["_self"]);return r!=null&&x(e,["safetyAttributes"],kT(r)),e}function bh(t){const e={},n=m(t,["_self"]);n!=null&&x(e,["image"],UT(n));const i=m(t,["raiFilteredReason"]);i!=null&&x(e,["raiFilteredReason"],i);const r=m(t,["_self"]);r!=null&&x(e,["safetyAttributes"],zT(r));const a=m(t,["prompt"]);return a!=null&&x(e,["enhancedPrompt"],a),e}function rD(t){const e={},n=m(t,["_self"]);n!=null&&x(e,["mask"],UT(n));const i=m(t,["labels"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>a)),x(e,["labels"],r)}return e}function aD(t){const e={},n=m(t,["video"]);return n!=null&&x(e,["video"],XD(n)),e}function lD(t){const e={},n=m(t,["_self"]);return n!=null&&x(e,["video"],YD(n)),e}function cD(t){const e={},n=m(t,["modelSelectionConfig"]);n!=null&&x(e,["modelConfig"],n);const i=m(t,["responseJsonSchema"]);i!=null&&x(e,["responseJsonSchema"],i);const r=m(t,["audioTimestamp"]);r!=null&&x(e,["audioTimestamp"],r);const a=m(t,["candidateCount"]);a!=null&&x(e,["candidateCount"],a);const c=m(t,["enableAffectiveDialog"]);c!=null&&x(e,["enableAffectiveDialog"],c);const u=m(t,["frequencyPenalty"]);u!=null&&x(e,["frequencyPenalty"],u);const h=m(t,["logprobs"]);h!=null&&x(e,["logprobs"],h);const d=m(t,["maxOutputTokens"]);d!=null&&x(e,["maxOutputTokens"],d);const g=m(t,["mediaResolution"]);g!=null&&x(e,["mediaResolution"],g);const v=m(t,["presencePenalty"]);v!=null&&x(e,["presencePenalty"],v);const y=m(t,["responseLogprobs"]);y!=null&&x(e,["responseLogprobs"],y);const S=m(t,["responseMimeType"]);S!=null&&x(e,["responseMimeType"],S);const T=m(t,["responseModalities"]);T!=null&&x(e,["responseModalities"],T);const A=m(t,["responseSchema"]);A!=null&&x(e,["responseSchema"],A);const E=m(t,["routingConfig"]);E!=null&&x(e,["routingConfig"],E);const w=m(t,["seed"]);w!=null&&x(e,["seed"],w);const I=m(t,["speechConfig"]);I!=null&&x(e,["speechConfig"],I);const L=m(t,["stopSequences"]);L!=null&&x(e,["stopSequences"],L);const D=m(t,["temperature"]);D!=null&&x(e,["temperature"],D);const W=m(t,["thinkingConfig"]);W!=null&&x(e,["thinkingConfig"],W);const V=m(t,["topK"]);V!=null&&x(e,["topK"],V);const H=m(t,["topP"]);if(H!=null&&x(e,["topP"],H),m(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return e}function uD(t,e){const n={},i=m(e,["model"]);return i!=null&&x(n,["_url","name"],zn(t,i)),n}function dD(t,e){const n={},i=m(e,["model"]);return i!=null&&x(n,["_url","name"],zn(t,i)),n}function fD(t){const e={};if(m(t,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");const n=m(t,["enableWidget"]);return n!=null&&x(e,["enableWidget"],n),e}function hD(t){const e={};if(m(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(m(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");const n=m(t,["timeRangeFilter"]);return n!=null&&x(e,["timeRangeFilter"],n),e}function pD(t){const e={},n=m(t,["aspectRatio"]);n!=null&&x(e,["aspectRatio"],n);const i=m(t,["imageSize"]);if(i!=null&&x(e,["imageSize"],i),m(t,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is not supported in Gemini API.");if(m(t,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");return e}function mD(t){const e={},n=m(t,["aspectRatio"]);n!=null&&x(e,["aspectRatio"],n);const i=m(t,["imageSize"]);i!=null&&x(e,["imageSize"],i);const r=m(t,["outputMimeType"]);r!=null&&x(e,["imageOutputOptions","mimeType"],r);const a=m(t,["outputCompressionQuality"]);return a!=null&&x(e,["imageOutputOptions","compressionQuality"],a),e}function gD(t){const e={},n=m(t,["bytesBase64Encoded"]);n!=null&&x(e,["imageBytes"],aa(n));const i=m(t,["mimeType"]);return i!=null&&x(e,["mimeType"],i),e}function UT(t){const e={},n=m(t,["gcsUri"]);n!=null&&x(e,["gcsUri"],n);const i=m(t,["bytesBase64Encoded"]);i!=null&&x(e,["imageBytes"],aa(i));const r=m(t,["mimeType"]);return r!=null&&x(e,["mimeType"],r),e}function Sh(t){const e={};if(m(t,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");const n=m(t,["imageBytes"]);n!=null&&x(e,["bytesBase64Encoded"],aa(n));const i=m(t,["mimeType"]);return i!=null&&x(e,["mimeType"],i),e}function As(t){const e={},n=m(t,["gcsUri"]);n!=null&&x(e,["gcsUri"],n);const i=m(t,["imageBytes"]);i!=null&&x(e,["bytesBase64Encoded"],aa(i));const r=m(t,["mimeType"]);return r!=null&&x(e,["mimeType"],r),e}function vD(t,e,n){const i={},r=m(e,["pageSize"]);n!==void 0&&r!=null&&x(n,["_query","pageSize"],r);const a=m(e,["pageToken"]);n!==void 0&&a!=null&&x(n,["_query","pageToken"],a);const c=m(e,["filter"]);n!==void 0&&c!=null&&x(n,["_query","filter"],c);const u=m(e,["queryBase"]);return n!==void 0&&u!=null&&x(n,["_url","models_url"],CT(t,u)),i}function xD(t,e,n){const i={},r=m(e,["pageSize"]);n!==void 0&&r!=null&&x(n,["_query","pageSize"],r);const a=m(e,["pageToken"]);n!==void 0&&a!=null&&x(n,["_query","pageToken"],a);const c=m(e,["filter"]);n!==void 0&&c!=null&&x(n,["_query","filter"],c);const u=m(e,["queryBase"]);return n!==void 0&&u!=null&&x(n,["_url","models_url"],CT(t,u)),i}function yD(t,e){const n={},i=m(e,["config"]);return i!=null&&vD(t,i,n),n}function _D(t,e){const n={},i=m(e,["config"]);return i!=null&&xD(t,i,n),n}function bD(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["nextPageToken"]);i!=null&&x(e,["nextPageToken"],i);const r=m(t,["_self"]);if(r!=null){let a=AT(r);Array.isArray(a)&&(a=a.map(c=>C0(c))),x(e,["models"],a)}return e}function SD(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["nextPageToken"]);i!=null&&x(e,["nextPageToken"],i);const r=m(t,["_self"]);if(r!=null){let a=AT(r);Array.isArray(a)&&(a=a.map(c=>A0(c))),x(e,["models"],a)}return e}function TD(t){const e={},n=m(t,["maskMode"]);n!=null&&x(e,["maskMode"],n);const i=m(t,["segmentationClasses"]);i!=null&&x(e,["maskClasses"],i);const r=m(t,["maskDilation"]);return r!=null&&x(e,["dilation"],r),e}function C0(t){const e={},n=m(t,["name"]);n!=null&&x(e,["name"],n);const i=m(t,["displayName"]);i!=null&&x(e,["displayName"],i);const r=m(t,["description"]);r!=null&&x(e,["description"],r);const a=m(t,["version"]);a!=null&&x(e,["version"],a);const c=m(t,["_self"]);c!=null&&x(e,["tunedModelInfo"],OD(c));const u=m(t,["inputTokenLimit"]);u!=null&&x(e,["inputTokenLimit"],u);const h=m(t,["outputTokenLimit"]);h!=null&&x(e,["outputTokenLimit"],h);const d=m(t,["supportedGenerationMethods"]);d!=null&&x(e,["supportedActions"],d);const g=m(t,["temperature"]);g!=null&&x(e,["temperature"],g);const v=m(t,["maxTemperature"]);v!=null&&x(e,["maxTemperature"],v);const y=m(t,["topP"]);y!=null&&x(e,["topP"],y);const S=m(t,["topK"]);S!=null&&x(e,["topK"],S);const T=m(t,["thinking"]);return T!=null&&x(e,["thinking"],T),e}function A0(t){const e={},n=m(t,["name"]);n!=null&&x(e,["name"],n);const i=m(t,["displayName"]);i!=null&&x(e,["displayName"],i);const r=m(t,["description"]);r!=null&&x(e,["description"],r);const a=m(t,["versionId"]);a!=null&&x(e,["version"],a);const c=m(t,["deployedModels"]);if(c!=null){let v=c;Array.isArray(v)&&(v=v.map(y=>zI(y))),x(e,["endpoints"],v)}const u=m(t,["labels"]);u!=null&&x(e,["labels"],u);const h=m(t,["_self"]);h!=null&&x(e,["tunedModelInfo"],BD(h));const d=m(t,["defaultCheckpointId"]);d!=null&&x(e,["defaultCheckpointId"],d);const g=m(t,["checkpoints"]);if(g!=null){let v=g;Array.isArray(v)&&(v=v.map(y=>y)),x(e,["checkpoints"],v)}return e}function ED(t){const e={},n=m(t,["mediaResolution"]);n!=null&&x(e,["mediaResolution"],n);const i=m(t,["codeExecutionResult"]);i!=null&&x(e,["codeExecutionResult"],i);const r=m(t,["executableCode"]);r!=null&&x(e,["executableCode"],r);const a=m(t,["fileData"]);a!=null&&x(e,["fileData"],PI(a));const c=m(t,["functionCall"]);c!=null&&x(e,["functionCall"],FI(c));const u=m(t,["functionResponse"]);u!=null&&x(e,["functionResponse"],u);const h=m(t,["inlineData"]);h!=null&&x(e,["inlineData"],cI(h));const d=m(t,["text"]);d!=null&&x(e,["text"],d);const g=m(t,["thought"]);g!=null&&x(e,["thought"],g);const v=m(t,["thoughtSignature"]);v!=null&&x(e,["thoughtSignature"],v);const y=m(t,["videoMetadata"]);return y!=null&&x(e,["videoMetadata"],y),e}function wD(t){const e={},n=m(t,["productImage"]);return n!=null&&x(e,["image"],As(n)),e}function MD(t,e){const n={},i=m(t,["numberOfImages"]);e!==void 0&&i!=null&&x(e,["parameters","sampleCount"],i);const r=m(t,["baseSteps"]);e!==void 0&&r!=null&&x(e,["parameters","baseSteps"],r);const a=m(t,["outputGcsUri"]);e!==void 0&&a!=null&&x(e,["parameters","storageUri"],a);const c=m(t,["seed"]);e!==void 0&&c!=null&&x(e,["parameters","seed"],c);const u=m(t,["safetyFilterLevel"]);e!==void 0&&u!=null&&x(e,["parameters","safetySetting"],u);const h=m(t,["personGeneration"]);e!==void 0&&h!=null&&x(e,["parameters","personGeneration"],h);const d=m(t,["addWatermark"]);e!==void 0&&d!=null&&x(e,["parameters","addWatermark"],d);const g=m(t,["outputMimeType"]);e!==void 0&&g!=null&&x(e,["parameters","outputOptions","mimeType"],g);const v=m(t,["outputCompressionQuality"]);e!==void 0&&v!=null&&x(e,["parameters","outputOptions","compressionQuality"],v);const y=m(t,["enhancePrompt"]);e!==void 0&&y!=null&&x(e,["parameters","enhancePrompt"],y);const S=m(t,["labels"]);return e!==void 0&&S!=null&&x(e,["labels"],S),n}function CD(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["_url","model"],zn(t,i));const r=m(e,["source"]);r!=null&&RD(r,n);const a=m(e,["config"]);return a!=null&&MD(a,n),n}function AD(t){const e={},n=m(t,["predictions"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(r=>bh(r))),x(e,["generatedImages"],i)}return e}function RD(t,e){const n={},i=m(t,["prompt"]);e!==void 0&&i!=null&&x(e,["instances[0]","prompt"],i);const r=m(t,["personImage"]);e!==void 0&&r!=null&&x(e,["instances[0]","personImage","image"],As(r));const a=m(t,["productImages"]);if(e!==void 0&&a!=null){let c=a;Array.isArray(c)&&(c=c.map(u=>wD(u))),x(e,["instances[0]","productImages"],c)}return n}function ND(t){const e={},n=m(t,["referenceImage"]);n!=null&&x(e,["referenceImage"],As(n));const i=m(t,["referenceId"]);i!=null&&x(e,["referenceId"],i);const r=m(t,["referenceType"]);r!=null&&x(e,["referenceType"],r);const a=m(t,["maskImageConfig"]);a!=null&&x(e,["maskImageConfig"],TD(a));const c=m(t,["controlImageConfig"]);c!=null&&x(e,["controlImageConfig"],gI(c));const u=m(t,["styleImageConfig"]);u!=null&&x(e,["styleImageConfig"],u);const h=m(t,["subjectImageConfig"]);return h!=null&&x(e,["subjectImageConfig"],h),e}function kT(t){const e={},n=m(t,["safetyAttributes","categories"]);n!=null&&x(e,["categories"],n);const i=m(t,["safetyAttributes","scores"]);i!=null&&x(e,["scores"],i);const r=m(t,["contentType"]);return r!=null&&x(e,["contentType"],r),e}function zT(t){const e={},n=m(t,["safetyAttributes","categories"]);n!=null&&x(e,["categories"],n);const i=m(t,["safetyAttributes","scores"]);i!=null&&x(e,["scores"],i);const r=m(t,["contentType"]);return r!=null&&x(e,["contentType"],r),e}function ID(t){const e={},n=m(t,["category"]);if(n!=null&&x(e,["category"],n),m(t,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");const i=m(t,["threshold"]);return i!=null&&x(e,["threshold"],i),e}function DD(t){const e={},n=m(t,["image"]);return n!=null&&x(e,["image"],As(n)),e}function LD(t,e){const n={},i=m(t,["mode"]);e!==void 0&&i!=null&&x(e,["parameters","mode"],i);const r=m(t,["maxPredictions"]);e!==void 0&&r!=null&&x(e,["parameters","maxPredictions"],r);const a=m(t,["confidenceThreshold"]);e!==void 0&&a!=null&&x(e,["parameters","confidenceThreshold"],a);const c=m(t,["maskDilation"]);e!==void 0&&c!=null&&x(e,["parameters","maskDilation"],c);const u=m(t,["binaryColorThreshold"]);e!==void 0&&u!=null&&x(e,["parameters","binaryColorThreshold"],u);const h=m(t,["labels"]);return e!==void 0&&h!=null&&x(e,["labels"],h),n}function UD(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["_url","model"],zn(t,i));const r=m(e,["source"]);r!=null&&zD(r,n);const a=m(e,["config"]);return a!=null&&LD(a,n),n}function kD(t){const e={},n=m(t,["predictions"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(r=>rD(r))),x(e,["generatedMasks"],i)}return e}function zD(t,e){const n={},i=m(t,["prompt"]);e!==void 0&&i!=null&&x(e,["instances[0]","prompt"],i);const r=m(t,["image"]);e!==void 0&&r!=null&&x(e,["instances[0]","image"],As(r));const a=m(t,["scribbleImage"]);return e!==void 0&&a!=null&&x(e,["instances[0]","scribble"],DD(a)),n}function PD(t){const e={},n=m(t,["functionCallingConfig"]);n!=null&&x(e,["functionCallingConfig"],OI(n));const i=m(t,["retrievalConfig"]);return i!=null&&x(e,["retrievalConfig"],i),e}function FD(t){const e={},n=m(t,["functionDeclarations"]);if(n!=null){let g=n;Array.isArray(g)&&(g=g.map(v=>v)),x(e,["functionDeclarations"],g)}if(m(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");const i=m(t,["googleSearchRetrieval"]);i!=null&&x(e,["googleSearchRetrieval"],i);const r=m(t,["computerUse"]);r!=null&&x(e,["computerUse"],r);const a=m(t,["fileSearch"]);a!=null&&x(e,["fileSearch"],a);const c=m(t,["codeExecution"]);if(c!=null&&x(e,["codeExecution"],c),m(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const u=m(t,["googleMaps"]);u!=null&&x(e,["googleMaps"],fD(u));const h=m(t,["googleSearch"]);h!=null&&x(e,["googleSearch"],hD(h));const d=m(t,["urlContext"]);return d!=null&&x(e,["urlContext"],d),e}function PT(t){const e={},n=m(t,["functionDeclarations"]);if(n!=null){let v=n;Array.isArray(v)&&(v=v.map(y=>BI(y))),x(e,["functionDeclarations"],v)}const i=m(t,["retrieval"]);i!=null&&x(e,["retrieval"],i);const r=m(t,["googleSearchRetrieval"]);r!=null&&x(e,["googleSearchRetrieval"],r);const a=m(t,["computerUse"]);if(a!=null&&x(e,["computerUse"],a),m(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Vertex AI.");const c=m(t,["codeExecution"]);c!=null&&x(e,["codeExecution"],c);const u=m(t,["enterpriseWebSearch"]);u!=null&&x(e,["enterpriseWebSearch"],u);const h=m(t,["googleMaps"]);h!=null&&x(e,["googleMaps"],h);const d=m(t,["googleSearch"]);d!=null&&x(e,["googleSearch"],d);const g=m(t,["urlContext"]);return g!=null&&x(e,["urlContext"],g),e}function OD(t){const e={},n=m(t,["baseModel"]);n!=null&&x(e,["baseModel"],n);const i=m(t,["createTime"]);i!=null&&x(e,["createTime"],i);const r=m(t,["updateTime"]);return r!=null&&x(e,["updateTime"],r),e}function BD(t){const e={},n=m(t,["labels","google-vertex-llm-tuning-base-model-id"]);n!=null&&x(e,["baseModel"],n);const i=m(t,["createTime"]);i!=null&&x(e,["createTime"],i);const r=m(t,["updateTime"]);return r!=null&&x(e,["updateTime"],r),e}function VD(t,e){const n={},i=m(t,["displayName"]);e!==void 0&&i!=null&&x(e,["displayName"],i);const r=m(t,["description"]);e!==void 0&&r!=null&&x(e,["description"],r);const a=m(t,["defaultCheckpointId"]);return e!==void 0&&a!=null&&x(e,["defaultCheckpointId"],a),n}function HD(t,e){const n={},i=m(t,["displayName"]);e!==void 0&&i!=null&&x(e,["displayName"],i);const r=m(t,["description"]);e!==void 0&&r!=null&&x(e,["description"],r);const a=m(t,["defaultCheckpointId"]);return e!==void 0&&a!=null&&x(e,["defaultCheckpointId"],a),n}function GD(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["_url","name"],zn(t,i));const r=m(e,["config"]);return r!=null&&VD(r,n),n}function jD(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["_url","model"],zn(t,i));const r=m(e,["config"]);return r!=null&&HD(r,n),n}function qD(t,e){const n={},i=m(t,["outputGcsUri"]);e!==void 0&&i!=null&&x(e,["parameters","storageUri"],i);const r=m(t,["safetyFilterLevel"]);e!==void 0&&r!=null&&x(e,["parameters","safetySetting"],r);const a=m(t,["personGeneration"]);e!==void 0&&a!=null&&x(e,["parameters","personGeneration"],a);const c=m(t,["includeRaiReason"]);e!==void 0&&c!=null&&x(e,["parameters","includeRaiReason"],c);const u=m(t,["outputMimeType"]);e!==void 0&&u!=null&&x(e,["parameters","outputOptions","mimeType"],u);const h=m(t,["outputCompressionQuality"]);e!==void 0&&h!=null&&x(e,["parameters","outputOptions","compressionQuality"],h);const d=m(t,["enhanceInputImage"]);e!==void 0&&d!=null&&x(e,["parameters","upscaleConfig","enhanceInputImage"],d);const g=m(t,["imagePreservationFactor"]);e!==void 0&&g!=null&&x(e,["parameters","upscaleConfig","imagePreservationFactor"],g);const v=m(t,["labels"]);e!==void 0&&v!=null&&x(e,["labels"],v);const y=m(t,["numberOfImages"]);e!==void 0&&y!=null&&x(e,["parameters","sampleCount"],y);const S=m(t,["mode"]);return e!==void 0&&S!=null&&x(e,["parameters","mode"],S),n}function WD(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["_url","model"],zn(t,i));const r=m(e,["image"]);r!=null&&x(n,["instances[0]","image"],As(r));const a=m(e,["upscaleFactor"]);a!=null&&x(n,["parameters","upscaleConfig","upscaleFactor"],a);const c=m(e,["config"]);return c!=null&&qD(c,n),n}function $D(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["predictions"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>bh(a))),x(e,["generatedImages"],r)}return e}function XD(t){const e={},n=m(t,["uri"]);n!=null&&x(e,["uri"],n);const i=m(t,["encodedVideo"]);i!=null&&x(e,["videoBytes"],aa(i));const r=m(t,["encoding"]);return r!=null&&x(e,["mimeType"],r),e}function YD(t){const e={},n=m(t,["gcsUri"]);n!=null&&x(e,["uri"],n);const i=m(t,["bytesBase64Encoded"]);i!=null&&x(e,["videoBytes"],aa(i));const r=m(t,["mimeType"]);return r!=null&&x(e,["mimeType"],r),e}function JD(t){const e={},n=m(t,["image"]);n!=null&&x(e,["_self"],As(n));const i=m(t,["maskMode"]);return i!=null&&x(e,["maskMode"],i),e}function KD(t){const e={},n=m(t,["image"]);n!=null&&x(e,["image"],Sh(n));const i=m(t,["referenceType"]);return i!=null&&x(e,["referenceType"],i),e}function ZD(t){const e={},n=m(t,["image"]);n!=null&&x(e,["image"],As(n));const i=m(t,["referenceType"]);return i!=null&&x(e,["referenceType"],i),e}function FT(t){const e={},n=m(t,["uri"]);n!=null&&x(e,["uri"],n);const i=m(t,["videoBytes"]);i!=null&&x(e,["encodedVideo"],aa(i));const r=m(t,["mimeType"]);return r!=null&&x(e,["encoding"],r),e}function OT(t){const e={},n=m(t,["uri"]);n!=null&&x(e,["gcsUri"],n);const i=m(t,["videoBytes"]);i!=null&&x(e,["bytesBase64Encoded"],aa(i));const r=m(t,["mimeType"]);return r!=null&&x(e,["mimeType"],r),e}function QD(t,e){const n={},i=m(t,["displayName"]);return e!==void 0&&i!=null&&x(e,["displayName"],i),n}function e3(t){const e={},n=m(t,["config"]);return n!=null&&QD(n,e),e}function t3(t,e){const n={},i=m(t,["force"]);return e!==void 0&&i!=null&&x(e,["_query","force"],i),n}function n3(t){const e={},n=m(t,["name"]);n!=null&&x(e,["_url","name"],n);const i=m(t,["config"]);return i!=null&&t3(i,e),e}function i3(t){const e={},n=m(t,["name"]);return n!=null&&x(e,["_url","name"],n),e}function o3(t,e){const n={},i=m(t,["customMetadata"]);if(e!==void 0&&i!=null){let a=i;Array.isArray(a)&&(a=a.map(c=>c)),x(e,["customMetadata"],a)}const r=m(t,["chunkingConfig"]);return e!==void 0&&r!=null&&x(e,["chunkingConfig"],r),n}function s3(t){const e={},n=m(t,["name"]);n!=null&&x(e,["name"],n);const i=m(t,["metadata"]);i!=null&&x(e,["metadata"],i);const r=m(t,["done"]);r!=null&&x(e,["done"],r);const a=m(t,["error"]);a!=null&&x(e,["error"],a);const c=m(t,["response"]);return c!=null&&x(e,["response"],a3(c)),e}function r3(t){const e={},n=m(t,["fileSearchStoreName"]);n!=null&&x(e,["_url","file_search_store_name"],n);const i=m(t,["fileName"]);i!=null&&x(e,["fileName"],i);const r=m(t,["config"]);return r!=null&&o3(r,e),e}function a3(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["parent"]);i!=null&&x(e,["parent"],i);const r=m(t,["documentName"]);return r!=null&&x(e,["documentName"],r),e}function l3(t,e){const n={},i=m(t,["pageSize"]);e!==void 0&&i!=null&&x(e,["_query","pageSize"],i);const r=m(t,["pageToken"]);return e!==void 0&&r!=null&&x(e,["_query","pageToken"],r),n}function c3(t){const e={},n=m(t,["config"]);return n!=null&&l3(n,e),e}function u3(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["nextPageToken"]);i!=null&&x(e,["nextPageToken"],i);const r=m(t,["fileSearchStores"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(c=>c)),x(e,["fileSearchStores"],a)}return e}function BT(t,e){const n={},i=m(t,["mimeType"]);e!==void 0&&i!=null&&x(e,["mimeType"],i);const r=m(t,["displayName"]);e!==void 0&&r!=null&&x(e,["displayName"],r);const a=m(t,["customMetadata"]);if(e!==void 0&&a!=null){let u=a;Array.isArray(u)&&(u=u.map(h=>h)),x(e,["customMetadata"],u)}const c=m(t,["chunkingConfig"]);return e!==void 0&&c!=null&&x(e,["chunkingConfig"],c),n}function d3(t){const e={},n=m(t,["fileSearchStoreName"]);n!=null&&x(e,["_url","file_search_store_name"],n);const i=m(t,["config"]);return i!=null&&BT(i,e),e}function f3(t){const e={},n=m(t,["sdkHttpResponse"]);return n!=null&&x(e,["sdkHttpResponse"],n),e}const h3="Content-Type",p3="X-Server-Timeout",m3="User-Agent",R0="x-goog-api-client",g3="1.34.0",v3=`google-genai-sdk/${g3}`,x3="v1beta1",y3="v1beta";class _3{constructor(e){var n,i;this.clientOptions=Object.assign(Object.assign({},e),{project:e.project,location:e.location,apiKey:e.apiKey,vertexai:e.vertexai});const r={};this.clientOptions.vertexai?(r.apiVersion=(n=this.clientOptions.apiVersion)!==null&&n!==void 0?n:x3,r.baseUrl=this.baseUrlFromProjectLocation(),this.normalizeAuthParameters()):(r.apiVersion=(i=this.clientOptions.apiVersion)!==null&&i!==void 0?i:y3,r.baseUrl="https://generativelanguage.googleapis.com/"),r.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=r,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(r,e.httpOptions))}baseUrlFromProjectLocation(){return this.clientOptions.project&&this.clientOptions.location&&this.clientOptions.location!=="global"?`https://${this.clientOptions.location}-aiplatform.googleapis.com/`:"https://aiplatform.googleapis.com/"}normalizeAuthParameters(){if(this.clientOptions.project&&this.clientOptions.location){this.clientOptions.apiKey=void 0;return}this.clientOptions.project=void 0,this.clientOptions.location=void 0}isVertexAI(){var e;return(e=this.clientOptions.vertexai)!==null&&e!==void 0?e:!1}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}async getAuthHeaders(){const e=new Headers;return await this.clientOptions.auth.addAuthHeaders(e),e}getApiVersion(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.apiVersion!==void 0)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw new Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.headers!==void 0)return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getRequestUrlInternal(e){if(!e||e.baseUrl===void 0||e.apiVersion===void 0)throw new Error("HTTP options are not correctly set.");const i=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];return e.apiVersion&&e.apiVersion!==""&&i.push(e.apiVersion),i.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){const e=this.getBaseUrl(),n=new URL(e);return n.protocol=n.protocol=="http:"?"ws":"wss",n.toString()}setBaseUrl(e){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=e;else throw new Error("HTTP options are not correctly set.")}constructUrl(e,n,i){const r=[this.getRequestUrlInternal(n)];return i&&r.push(this.getBaseResourcePath()),e!==""&&r.push(e),new URL(`${r.join("/")}`)}shouldPrependVertexProjectPath(e){return!(this.clientOptions.apiKey||!this.clientOptions.vertexai||e.path.startsWith("projects/")||e.httpMethod==="GET"&&e.path.startsWith("publishers/google/models"))}async request(e){let n=this.clientOptions.httpOptions;e.httpOptions&&(n=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));const i=this.shouldPrependVertexProjectPath(e),r=this.constructUrl(e.path,n,i);if(e.queryParams)for(const[c,u]of Object.entries(e.queryParams))r.searchParams.append(c,String(u));let a={};if(e.httpMethod==="GET"){if(e.body&&e.body!=="{}")throw new Error("Request body should be empty for GET request, but got non empty request body")}else a.body=e.body;return a=await this.includeExtraHttpOptionsToRequestInit(a,n,r.toString(),e.abortSignal),this.unaryApiCall(r,a,e.httpMethod)}patchHttpOptions(e,n){const i=JSON.parse(JSON.stringify(e));for(const[r,a]of Object.entries(n))typeof a=="object"?i[r]=Object.assign(Object.assign({},i[r]),a):a!==void 0&&(i[r]=a);return i}async requestStream(e){let n=this.clientOptions.httpOptions;e.httpOptions&&(n=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));const i=this.shouldPrependVertexProjectPath(e),r=this.constructUrl(e.path,n,i);(!r.searchParams.has("alt")||r.searchParams.get("alt")!=="sse")&&r.searchParams.set("alt","sse");let a={};return a.body=e.body,a=await this.includeExtraHttpOptionsToRequestInit(a,n,r.toString(),e.abortSignal),this.streamApiCall(r,a,e.httpMethod)}async includeExtraHttpOptionsToRequestInit(e,n,i,r){if(n&&n.timeout||r){const a=new AbortController,c=a.signal;if(n.timeout&&n?.timeout>0){const u=setTimeout(()=>a.abort(),n.timeout);u&&typeof u.unref=="function"&&u.unref()}r&&r.addEventListener("abort",()=>{a.abort()}),e.signal=c}return n&&n.extraBody!==null&&b3(e,n.extraBody),e.headers=await this.getHeadersInternal(n,i),e}async unaryApiCall(e,n,i){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:i})).then(async r=>(await PS(r),new E0(r))).catch(r=>{throw r instanceof Error?r:new Error(JSON.stringify(r))})}async streamApiCall(e,n,i){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:i})).then(async r=>(await PS(r),this.processStreamResponse(r))).catch(r=>{throw r instanceof Error?r:new Error(JSON.stringify(r))})}processStreamResponse(e){return Ms(this,arguments,function*(){var i;const r=(i=e?.body)===null||i===void 0?void 0:i.getReader(),a=new TextDecoder("utf-8");if(!r)throw new Error("Response body is empty");try{let c="";const u="data:",h=[` + +`,"\r\r",`\r +\r +`];for(;;){const{done:d,value:g}=yield Kt(r.read());if(d){if(c.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}const v=a.decode(g,{stream:!0});try{const T=JSON.parse(v);if("error"in T){const A=JSON.parse(JSON.stringify(T.error)),E=A.status,w=A.code,I=`got status: ${E}. ${JSON.stringify(T)}`;if(w>=400&&w<600)throw new yh({message:I,status:w})}}catch(T){if(T.name==="ApiError")throw T}c+=v;let y=-1,S=0;for(;;){y=-1,S=0;for(const E of h){const w=c.indexOf(E);w!==-1&&(y===-1||w{throw new Error(`exception ${i} sending request`)})}getDefaultHeaders(){const e={},n=v3+" "+this.clientOptions.userAgentExtra;return e[m3]=n,e[R0]=n,e[h3]="application/json",e}async getHeadersInternal(e,n){const i=new Headers;if(e&&e.headers){for(const[r,a]of Object.entries(e.headers))i.append(r,a);e.timeout&&e.timeout>0&&i.append(p3,String(Math.ceil(e.timeout/1e3)))}return await this.clientOptions.auth.addAuthHeaders(i,n),i}getFileName(e){var n;let i="";return typeof e=="string"&&(i=e.replace(/[/\\]+$/,""),i=(n=i.split(/[/\\]/).pop())!==null&&n!==void 0?n:""),i}async uploadFile(e,n){var i;const r={};n!=null&&(r.mimeType=n.mimeType,r.name=n.name,r.displayName=n.displayName),r.name&&!r.name.startsWith("files/")&&(r.name=`files/${r.name}`);const a=this.clientOptions.uploader,c=await a.stat(e);r.sizeBytes=String(c.size);const u=(i=n?.mimeType)!==null&&i!==void 0?i:c.type;if(u===void 0||u==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");r.mimeType=u;const h={file:r},d=this.getFileName(e),g=Et("upload/v1beta/files",h._url),v=await this.fetchUploadUrl(g,r.sizeBytes,r.mimeType,d,h,n?.httpOptions);return a.upload(e,v,this)}async uploadFileToFileSearchStore(e,n,i){var r;const a=this.clientOptions.uploader,c=await a.stat(n),u=String(c.size),h=(r=i?.mimeType)!==null&&r!==void 0?r:c.type;if(h===void 0||h==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");const d=`upload/v1beta/${e}:uploadToFileSearchStore`,g=this.getFileName(n),v={};i!=null&&BT(i,v);const y=await this.fetchUploadUrl(d,u,h,g,v,i?.httpOptions);return a.uploadToFileSearchStore(n,y,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,n,i,r,a,c){var u;let h={};c?h=c:h={apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${n}`,"X-Goog-Upload-Header-Content-Type":`${i}`},r?{"X-Goog-Upload-File-Name":r}:{})};const d=await this.request({path:e,body:JSON.stringify(a),httpMethod:"POST",httpOptions:h});if(!d||!d?.headers)throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");const g=(u=d?.headers)===null||u===void 0?void 0:u["x-goog-upload-url"];if(g===void 0)throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return g}}async function PS(t){var e;if(t===void 0)throw new Error("response is undefined");if(!t.ok){const n=t.status;let i;!((e=t.headers.get("content-type"))===null||e===void 0)&&e.includes("application/json")?i=await t.json():i={error:{message:await t.text(),code:t.status,status:t.statusText}};const r=JSON.stringify(i);throw n>=400&&n<600?new yh({message:r,status:n}):new Error(r)}}function b3(t,e){if(!e||Object.keys(e).length===0)return;if(t.body instanceof Blob){console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");return}let n={};if(typeof t.body=="string"&&t.body.length>0)try{const a=JSON.parse(t.body);if(typeof a=="object"&&a!==null&&!Array.isArray(a))n=a;else{console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");return}}catch{console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}function i(a,c){const u=Object.assign({},a);for(const h in c)if(Object.prototype.hasOwnProperty.call(c,h)){const d=c[h],g=u[h];d&&typeof d=="object"&&!Array.isArray(d)&&g&&typeof g=="object"&&!Array.isArray(g)?u[h]=i(g,d):(g&&d&&typeof g!=typeof d&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${h}". Original type: ${typeof g}, New type: ${typeof d}. Overwriting.`),u[h]=d)}return u}const r=i(n,e);t.body=JSON.stringify(r)}const S3="mcp_used/unknown";let T3=!1;function VT(t){for(const e of t)if(E3(e)||typeof e=="object"&&"inputSchema"in e)return!0;return T3}function HT(t){var e;const n=(e=t[R0])!==null&&e!==void 0?e:"";t[R0]=(n+` ${S3}`).trimStart()}function E3(t){return t!==null&&typeof t=="object"&&t instanceof Xg}function w3(t){return Ms(this,arguments,function*(n,i=100){let r,a=0;for(;a0)return;const a={},c=[];for(const g of this.mcpClients)try{for(var u=!0,h=(n=void 0,Cs(w3(g))),d;d=await h.next(),e=d.done,!e;u=!0){r=d.value,u=!1;const v=r;c.push(v);const y=v.name;if(a[y])throw new Error(`Duplicate function name ${y} found in MCP tools. Please ensure function names are unique.`);a[y]=g}}catch(v){n={error:v}}finally{try{!u&&!e&&(i=h.return)&&await i.call(h)}finally{if(n)throw n.error}}this.mcpTools=c,this.functionNameToMcpClient=a}async tool(){return await this.initialize(),iN(this.mcpTools,this.config)}async callTool(e){await this.initialize();const n=[];for(const i of e)if(i.name in this.functionNameToMcpClient){const r=this.functionNameToMcpClient[i.name];let a;this.config.timeout&&(a={timeout:this.config.timeout});const c=await r.callTool({name:i.name,arguments:i.args},void 0,a);n.push({functionResponse:{name:i.name,response:c.isError?{error:c}:c}})}return n}}async function M3(t,e,n){const i=new YR;let r;n.data instanceof Blob?r=JSON.parse(await n.data.text()):r=JSON.parse(n.data),Object.assign(i,r),e(i)}class C3{constructor(e,n,i){this.apiClient=e,this.auth=n,this.webSocketFactory=i}async connect(e){var n,i;if(this.apiClient.isVertexAI())throw new Error("Live music is not supported for Vertex AI.");console.warn("Live music generation is experimental and may change in future versions.");const r=this.apiClient.getWebsocketBaseUrl(),a=this.apiClient.getApiVersion(),c=N3(this.apiClient.getDefaultHeaders()),u=this.apiClient.getApiKey(),h=`${r}/ws/google.ai.generativelanguage.${a}.GenerativeService.BidiGenerateMusic?key=${u}`;let d=()=>{};const g=new Promise(L=>{d=L}),v=e.callbacks,y=function(){d({})},S=this.apiClient,T={onopen:y,onmessage:L=>{M3(S,v.onmessage,L)},onerror:(n=v?.onerror)!==null&&n!==void 0?n:function(L){},onclose:(i=v?.onclose)!==null&&i!==void 0?i:function(L){}},A=this.webSocketFactory.create(h,R3(c),T);A.connect(),await g;const I={setup:{model:zn(this.apiClient,e.model)}};return A.send(JSON.stringify(I)),new A3(A,this.apiClient)}}class A3{constructor(e,n){this.conn=e,this.apiClient=n}async setWeightedPrompts(e){if(!e.weightedPrompts||Object.keys(e.weightedPrompts).length===0)throw new Error("Weighted prompts must be set and contain at least one entry.");const n=eI(e);this.conn.send(JSON.stringify({clientContent:n}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});const n=Q2(e);this.conn.send(JSON.stringify(n))}sendPlaybackControl(e){const n={playbackControl:e};this.conn.send(JSON.stringify(n))}play(){this.sendPlaybackControl(Xl.PLAY)}pause(){this.sendPlaybackControl(Xl.PAUSE)}stop(){this.sendPlaybackControl(Xl.STOP)}resetContext(){this.sendPlaybackControl(Xl.RESET_CONTEXT)}close(){this.conn.close()}}function R3(t){const e={};return t.forEach((n,i)=>{e[i]=n}),e}function N3(t){const e=new Headers;for(const[n,i]of Object.entries(t))e.append(n,i);return e}const I3="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function D3(t,e,n){const i=new XR;let r;n.data instanceof Blob?r=await n.data.text():n.data instanceof ArrayBuffer?r=new TextDecoder().decode(n.data):r=n.data;const a=JSON.parse(r);if(t.isVertexAI()){const c=iI(a);Object.assign(i,c)}else Object.assign(i,a);e(i)}class L3{constructor(e,n,i){this.apiClient=e,this.auth=n,this.webSocketFactory=i,this.music=new C3(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var n,i,r,a,c,u;if(e.config&&e.config.httpOptions)throw new Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");const h=this.apiClient.getWebsocketBaseUrl(),d=this.apiClient.getApiVersion();let g;const v=this.apiClient.getHeaders();e.config&&e.config.tools&&VT(e.config.tools)&&HT(v);const y=P3(v);if(this.apiClient.isVertexAI())g=`${h}/ws/google.cloud.aiplatform.${d}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(y,g);else{const k=this.apiClient.getApiKey();let P="BidiGenerateContent",J="key";k?.startsWith("auth_tokens/")&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),d!=="v1alpha"&&console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."),P="BidiGenerateContentConstrained",J="access_token"),g=`${h}/ws/google.ai.generativelanguage.${d}.GenerativeService.${P}?${J}=${k}`}let S=()=>{};const T=new Promise(k=>{S=k}),A=e.callbacks,E=function(){var k;(k=A?.onopen)===null||k===void 0||k.call(A),S({})},w=this.apiClient,I={onopen:E,onmessage:k=>{D3(w,A.onmessage,k)},onerror:(n=A?.onerror)!==null&&n!==void 0?n:function(k){},onclose:(i=A?.onclose)!==null&&i!==void 0?i:function(k){}},L=this.webSocketFactory.create(g,z3(y),I);L.connect(),await T;let D=zn(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&D.startsWith("publishers/")){const k=this.apiClient.getProject(),P=this.apiClient.getLocation();D=`projects/${k}/locations/${P}/`+D}let W={};this.apiClient.isVertexAI()&&((r=e.config)===null||r===void 0?void 0:r.responseModalities)===void 0&&(e.config===void 0?e.config={responseModalities:[Zf.AUDIO]}:e.config.responseModalities=[Zf.AUDIO]),!((a=e.config)===null||a===void 0)&&a.generationConfig&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).");const V=(u=(c=e.config)===null||c===void 0?void 0:c.tools)!==null&&u!==void 0?u:[],H=[];for(const k of V)if(this.isCallableTool(k)){const P=k;H.push(await P.tool())}else H.push(k);H.length>0&&(e.config.tools=H);const Q={model:D,config:e.config,callbacks:e.callbacks};return this.apiClient.isVertexAI()?W=Z2(this.apiClient,Q):W=K2(this.apiClient,Q),delete W.config,L.send(JSON.stringify(W)),new k3(L,this.apiClient)}isCallableTool(e){return"callTool"in e&&typeof e.callTool=="function"}}const U3={turnComplete:!0};class k3{constructor(e,n){this.conn=e,this.apiClient=n}tLiveClientContent(e,n){if(n.turns!==null&&n.turns!==void 0){let i=[];try{i=hs(n.turns),e.isVertexAI()||(i=i.map(r=>_h(r)))}catch{throw new Error(`Failed to parse client content "turns", type: '${typeof n.turns}'`)}return{clientContent:{turns:i,turnComplete:n.turnComplete}}}return{clientContent:{turnComplete:n.turnComplete}}}tLiveClienttToolResponse(e,n){let i=[];if(n.functionResponses==null)throw new Error("functionResponses is required.");if(Array.isArray(n.functionResponses)?i=n.functionResponses:i=[n.functionResponses],i.length===0)throw new Error("functionResponses is required.");for(const a of i){if(typeof a!="object"||a===null||!("name"in a)||!("response"in a))throw new Error(`Could not parse function response, type '${typeof a}'.`);if(!e.isVertexAI()&&!("id"in a))throw new Error(I3)}return{toolResponse:{functionResponses:i}}}sendClientContent(e){e=Object.assign(Object.assign({},U3),e);const n=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(n))}sendRealtimeInput(e){let n={};this.apiClient.isVertexAI()?n={realtimeInput:nI(e)}:n={realtimeInput:tI(e)},this.conn.send(JSON.stringify(n))}sendToolResponse(e){if(e.functionResponses==null)throw new Error("Tool response parameters are required.");const n=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(n))}close(){this.conn.close()}}function z3(t){const e={};return t.forEach((n,i)=>{e[i]=n}),e}function P3(t){const e=new Headers;for(const[n,i]of Object.entries(t))e.append(n,i);return e}const FS=10;function OS(t){var e,n,i;if(!((e=t?.automaticFunctionCalling)===null||e===void 0)&&e.disable)return!0;let r=!1;for(const c of(n=t?.tools)!==null&&n!==void 0?n:[])if(tc(c)){r=!0;break}if(!r)return!0;const a=(i=t?.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls;return a&&(a<0||!Number.isInteger(a))||a==0?(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",a),!0):!1}function tc(t){return"callTool"in t&&typeof t.callTool=="function"}function F3(t){var e,n,i;return(i=(n=(e=t.config)===null||e===void 0?void 0:e.tools)===null||n===void 0?void 0:n.some(r=>tc(r)))!==null&&i!==void 0?i:!1}function BS(t){var e;const n=[];return!((e=t?.config)===null||e===void 0)&&e.tools&&t.config.tools.forEach((i,r)=>{if(tc(i))return;const a=i;a.functionDeclarations&&a.functionDeclarations.length>0&&n.push(r)}),n}function VS(t){var e;return!(!((e=t?.automaticFunctionCalling)===null||e===void 0)&&e.ignoreCallHistory)}class O3 extends br{constructor(e){super(),this.apiClient=e,this.generateContent=async n=>{var i,r,a,c,u;const h=await this.processParamsMaybeAddMcpUsage(n);if(this.maybeMoveToResponseJsonSchem(n),!F3(n)||OS(n.config))return await this.generateContentInternal(h);const d=BS(n);if(d.length>0){const A=d.map(E=>`tools[${E}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${A}.`)}let g,v;const y=hs(h.contents),S=(a=(r=(i=h.config)===null||i===void 0?void 0:i.automaticFunctionCalling)===null||r===void 0?void 0:r.maximumRemoteCalls)!==null&&a!==void 0?a:FS;let T=0;for(;T{var i,r,a,c,u;if(this.maybeMoveToResponseJsonSchem(n),OS(n.config)){const v=await this.processParamsMaybeAddMcpUsage(n);return await this.generateContentStreamInternal(v)}const h=BS(n);if(h.length>0){const v=h.map(y=>`tools[${y}]`).join(", ");throw new Error(`Incompatible tools found at ${v}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}const d=(a=(r=(i=n?.config)===null||i===void 0?void 0:i.toolConfig)===null||r===void 0?void 0:r.functionCallingConfig)===null||a===void 0?void 0:a.streamFunctionCallArguments,g=(u=(c=n?.config)===null||c===void 0?void 0:c.automaticFunctionCalling)===null||u===void 0?void 0:u.disable;if(d&&!g)throw new Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(n)},this.generateImages=async n=>await this.generateImagesInternal(n).then(i=>{var r;let a;const c=[];if(i?.generatedImages)for(const h of i.generatedImages)h&&h?.safetyAttributes&&((r=h?.safetyAttributes)===null||r===void 0?void 0:r.contentType)==="Positive Prompt"?a=h?.safetyAttributes:c.push(h);let u;return a?u={generatedImages:c,positivePromptSafetyAttributes:a,sdkHttpResponse:i.sdkHttpResponse}:u={generatedImages:c,sdkHttpResponse:i.sdkHttpResponse},u}),this.list=async n=>{var i;const c={config:Object.assign(Object.assign({},{queryBase:!0}),n?.config)};if(this.apiClient.isVertexAI()&&!c.config.queryBase){if(!((i=c.config)===null||i===void 0)&&i.filter)throw new Error("Filtering tuned models list for Vertex AI is not currently supported");c.config.filter="labels.tune-type:*"}return new Xa(xr.PAGED_ITEM_MODELS,u=>this.listInternal(u),await this.listInternal(c),c)},this.editImage=async n=>{const i={model:n.model,prompt:n.prompt,referenceImages:[],config:n.config};return n.referenceImages&&n.referenceImages&&(i.referenceImages=n.referenceImages.map(r=>r.toReferenceImageAPI())),await this.editImageInternal(i)},this.upscaleImage=async n=>{let i={numberOfImages:1,mode:"upscale"};n.config&&(i=Object.assign(Object.assign({},i),n.config));const r={model:n.model,image:n.image,upscaleFactor:n.upscaleFactor,config:i};return await this.upscaleImageInternal(r)},this.generateVideos=async n=>{var i,r,a,c,u,h;if((n.prompt||n.image||n.video)&&n.source)throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return this.apiClient.isVertexAI()||(!((i=n.video)===null||i===void 0)&&i.uri&&(!((r=n.video)===null||r===void 0)&&r.videoBytes)?n.video={uri:n.video.uri,mimeType:n.video.mimeType}:!((c=(a=n.source)===null||a===void 0?void 0:a.video)===null||c===void 0)&&c.uri&&(!((h=(u=n.source)===null||u===void 0?void 0:u.video)===null||h===void 0)&&h.videoBytes)&&(n.source.video={uri:n.source.video.uri,mimeType:n.source.video.mimeType})),await this.generateVideosInternal(n)}}maybeMoveToResponseJsonSchem(e){e.config&&e.config.responseSchema&&(e.config.responseJsonSchema||Object.keys(e.config.responseSchema).includes("$schema")&&(e.config.responseJsonSchema=e.config.responseSchema,delete e.config.responseSchema))}async processParamsMaybeAddMcpUsage(e){var n,i,r;const a=(n=e.config)===null||n===void 0?void 0:n.tools;if(!a)return e;const c=await Promise.all(a.map(async h=>tc(h)?await h.tool():h)),u={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:c})};if(u.config.tools=c,e.config&&e.config.tools&&VT(e.config.tools)){const h=(r=(i=e.config.httpOptions)===null||i===void 0?void 0:i.headers)!==null&&r!==void 0?r:{};let d=Object.assign({},h);Object.keys(d).length===0&&(d=this.apiClient.getDefaultHeaders()),HT(d),u.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:d})}return u}async initAfcToolsMap(e){var n,i,r;const a=new Map;for(const c of(i=(n=e.config)===null||n===void 0?void 0:n.tools)!==null&&i!==void 0?i:[])if(tc(c)){const u=c,h=await u.tool();for(const d of(r=h.functionDeclarations)!==null&&r!==void 0?r:[]){if(!d.name)throw new Error("Function declaration name is required.");if(a.has(d.name))throw new Error(`Duplicate tool declaration name: ${d.name}`);a.set(d.name,u)}}return a}async processAfcStream(e){var n,i,r;const a=(r=(i=(n=e.config)===null||n===void 0?void 0:n.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls)!==null&&r!==void 0?r:FS;let c=!1,u=0;const h=await this.initAfcToolsMap(e);return(function(d,g,v){return Ms(this,arguments,function*(){for(var y,S,T,A,E,w;u0){c=!0;const k=new au;k.candidates=[{content:{role:"user",parts:H}}],yield yield Kt(k);const P=[];P.push(...Q),P.push({role:"user",parts:H});const J=hs(v.contents).concat(P);v.contents=J}else break}})})(this,h,e)}async generateContentInternal(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=US(this.apiClient,e);return u=Et("{model}:generateContent",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=zS(g),y=new au;return Object.assign(y,v),y})}else{const d=LS(this.apiClient,e);return u=Et("{model}:generateContent",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=kS(g),y=new au;return Object.assign(y,v),y})}}async generateContentStreamInternal(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=US(this.apiClient,e);return u=Et("{model}:streamGenerateContent?alt=sse",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.requestStream({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}),c.then(function(v){return Ms(this,arguments,function*(){var y,S,T,A;try{for(var E=!0,w=Cs(v),I;I=yield Kt(w.next()),y=I.done,!y;E=!0){A=I.value,E=!1;const L=A,D=zS(yield Kt(L.json()));D.sdkHttpResponse={headers:L.headers};const W=new au;Object.assign(W,D),yield yield Kt(W)}}catch(L){S={error:L}}finally{try{!E&&!y&&(T=w.return)&&(yield Kt(T.call(w)))}finally{if(S)throw S.error}}})})}else{const d=LS(this.apiClient,e);return u=Et("{model}:streamGenerateContent?alt=sse",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.requestStream({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}),c.then(function(v){return Ms(this,arguments,function*(){var y,S,T,A;try{for(var E=!0,w=Cs(v),I;I=yield Kt(w.next()),y=I.done,!y;E=!0){A=I.value,E=!1;const L=A,D=kS(yield Kt(L.json()));D.sdkHttpResponse={headers:L.headers};const W=new au;Object.assign(W,D),yield yield Kt(W)}}catch(L){S={error:L}}finally{try{!E&&!y&&(T=w.return)&&(yield Kt(T.call(w)))}finally{if(S)throw S.error}}})})}}async embedContent(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=LI(this.apiClient,e);return u=Et("{model}:predict",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=kI(g),y=new gS;return Object.assign(y,v),y})}else{const d=DI(this.apiClient,e);return u=Et("{model}:batchEmbedContents",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=UI(g),y=new gS;return Object.assign(y,v),y})}}async generateImagesInternal(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=WI(this.apiClient,e);return u=Et("{model}:predict",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=XI(g),y=new vS;return Object.assign(y,v),y})}else{const d=qI(this.apiClient,e);return u=Et("{model}:predict",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=$I(g),y=new vS;return Object.assign(y,v),y})}}async editImageInternal(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI()){const u=AI(this.apiClient,e);return a=Et("{model}:predict",u._url),c=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(h=>h.json().then(d=>{const g=d;return g.sdkHttpResponse={headers:h.headers},g})),r.then(h=>{const d=RI(h),g=new PR;return Object.assign(g,d),g})}else throw new Error("This method is only supported by the Vertex AI.")}async upscaleImageInternal(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI()){const u=WD(this.apiClient,e);return a=Et("{model}:predict",u._url),c=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(h=>h.json().then(d=>{const g=d;return g.sdkHttpResponse={headers:h.headers},g})),r.then(h=>{const d=$D(h),g=new FR;return Object.assign(g,d),g})}else throw new Error("This method is only supported by the Vertex AI.")}async recontextImage(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI()){const u=CD(this.apiClient,e);return a=Et("{model}:predict",u._url),c=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(h=>h.json()),r.then(h=>{const d=AD(h),g=new OR;return Object.assign(g,d),g})}else throw new Error("This method is only supported by the Vertex AI.")}async segmentImage(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI()){const u=UD(this.apiClient,e);return a=Et("{model}:predict",u._url),c=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(h=>h.json()),r.then(h=>{const d=kD(h),g=new BR;return Object.assign(g,d),g})}else throw new Error("This method is only supported by the Vertex AI.")}async get(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=dD(this.apiClient,e);return u=Et("{name}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json()),c.then(g=>A0(g))}else{const d=uD(this.apiClient,e);return u=Et("{name}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json()),c.then(g=>C0(g))}}async listInternal(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=_D(this.apiClient,e);return u=Et("{models_url}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=SD(g),y=new xS;return Object.assign(y,v),y})}else{const d=yD(this.apiClient,e);return u=Et("{models_url}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=bD(g),y=new xS;return Object.assign(y,v),y})}}async update(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=jD(this.apiClient,e);return u=Et("{model}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json()),c.then(g=>A0(g))}else{const d=GD(this.apiClient,e);return u=Et("{name}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json()),c.then(g=>C0(g))}}async delete(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=EI(this.apiClient,e);return u=Et("{name}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=MI(g),y=new yS;return Object.assign(y,v),y})}else{const d=TI(this.apiClient,e);return u=Et("{name}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=wI(g),y=new yS;return Object.assign(y,v),y})}}async countTokens(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=_I(this.apiClient,e);return u=Et("{model}:countTokens",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=SI(g),y=new _S;return Object.assign(y,v),y})}else{const d=yI(this.apiClient,e);return u=Et("{model}:countTokens",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=bI(g),y=new _S;return Object.assign(y,v),y})}}async computeTokens(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI()){const u=fI(this.apiClient,e);return a=Et("{model}:computeTokens",u._url),c=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(h=>h.json().then(d=>{const g=d;return g.sdkHttpResponse={headers:h.headers},g})),r.then(h=>{const d=hI(h),g=new VR;return Object.assign(g,d),g})}else throw new Error("This method is only supported by the Vertex AI.")}async generateVideosInternal(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=eD(this.apiClient,e);return u=Et("{model}:predictLongRunning",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json()),c.then(g=>{const v=ZI(g),y=new Qf;return Object.assign(y,v),y})}else{const d=QI(this.apiClient,e);return u=Et("{model}:predictLongRunning",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json()),c.then(g=>{const v=KI(g),y=new Qf;return Object.assign(y,v),y})}}}class B3 extends br{constructor(e){super(),this.apiClient=e}async getVideosOperation(e){const n=e.operation,i=e.config;if(n.name===void 0||n.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){const r=n.name.split("/operations/")[0];let a;i&&"httpOptions"in i&&(a=i.httpOptions);const c=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:r,config:{httpOptions:a}});return n._fromAPIResponse({apiResponse:c,_isVertexAI:!0})}else{const r=await this.getVideosOperationInternal({operationName:n.name,config:i});return n._fromAPIResponse({apiResponse:r,_isVertexAI:!1})}}async get(e){const n=e.operation,i=e.config;if(n.name===void 0||n.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){const r=n.name.split("/operations/")[0];let a;i&&"httpOptions"in i&&(a=i.httpOptions);const c=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:r,config:{httpOptions:a}});return n._fromAPIResponse({apiResponse:c,_isVertexAI:!0})}else{const r=await this.getVideosOperationInternal({operationName:n.name,config:i});return n._fromAPIResponse({apiResponse:r,_isVertexAI:!1})}}async getVideosOperationInternal(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=IR(e);return u=Et("{operationName}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json()),c}else{const d=NR(e);return u=Et("{operationName}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json()),c}}async fetchPredictVideosOperationInternal(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI()){const u=TR(e);return a=Et("{resourceName}:fetchPredictOperation",u._url),c=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(h=>h.json()),r}else throw new Error("This method is only supported by the Vertex AI.")}}function V3(t){const e={},n=m(t,["data"]);if(n!=null&&x(e,["data"],n),m(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const i=m(t,["mimeType"]);return i!=null&&x(e,["mimeType"],i),e}function H3(t){const e={},n=m(t,["parts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(a=>K3(a))),x(e,["parts"],r)}const i=m(t,["role"]);return i!=null&&x(e,["role"],i),e}function G3(t,e,n){const i={},r=m(e,["expireTime"]);n!==void 0&&r!=null&&x(n,["expireTime"],r);const a=m(e,["newSessionExpireTime"]);n!==void 0&&a!=null&&x(n,["newSessionExpireTime"],a);const c=m(e,["uses"]);n!==void 0&&c!=null&&x(n,["uses"],c);const u=m(e,["liveConnectConstraints"]);n!==void 0&&u!=null&&x(n,["bidiGenerateContentSetup"],J3(t,u));const h=m(e,["lockAdditionalFields"]);return n!==void 0&&h!=null&&x(n,["fieldMask"],h),i}function j3(t,e){const n={},i=m(e,["config"]);return i!=null&&x(n,["config"],G3(t,i,n)),n}function q3(t){const e={};if(m(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const n=m(t,["fileUri"]);n!=null&&x(e,["fileUri"],n);const i=m(t,["mimeType"]);return i!=null&&x(e,["mimeType"],i),e}function W3(t){const e={},n=m(t,["id"]);n!=null&&x(e,["id"],n);const i=m(t,["args"]);i!=null&&x(e,["args"],i);const r=m(t,["name"]);if(r!=null&&x(e,["name"],r),m(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(m(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}function $3(t){const e={};if(m(t,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");const n=m(t,["enableWidget"]);return n!=null&&x(e,["enableWidget"],n),e}function X3(t){const e={};if(m(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(m(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");const n=m(t,["timeRangeFilter"]);return n!=null&&x(e,["timeRangeFilter"],n),e}function Y3(t,e){const n={},i=m(t,["generationConfig"]);e!==void 0&&i!=null&&x(e,["setup","generationConfig"],i);const r=m(t,["responseModalities"]);e!==void 0&&r!=null&&x(e,["setup","generationConfig","responseModalities"],r);const a=m(t,["temperature"]);e!==void 0&&a!=null&&x(e,["setup","generationConfig","temperature"],a);const c=m(t,["topP"]);e!==void 0&&c!=null&&x(e,["setup","generationConfig","topP"],c);const u=m(t,["topK"]);e!==void 0&&u!=null&&x(e,["setup","generationConfig","topK"],u);const h=m(t,["maxOutputTokens"]);e!==void 0&&h!=null&&x(e,["setup","generationConfig","maxOutputTokens"],h);const d=m(t,["mediaResolution"]);e!==void 0&&d!=null&&x(e,["setup","generationConfig","mediaResolution"],d);const g=m(t,["seed"]);e!==void 0&&g!=null&&x(e,["setup","generationConfig","seed"],g);const v=m(t,["speechConfig"]);e!==void 0&&v!=null&&x(e,["setup","generationConfig","speechConfig"],$g(v));const y=m(t,["thinkingConfig"]);e!==void 0&&y!=null&&x(e,["setup","generationConfig","thinkingConfig"],y);const S=m(t,["enableAffectiveDialog"]);e!==void 0&&S!=null&&x(e,["setup","generationConfig","enableAffectiveDialog"],S);const T=m(t,["systemInstruction"]);e!==void 0&&T!=null&&x(e,["setup","systemInstruction"],H3(vo(T)));const A=m(t,["tools"]);if(e!==void 0&&A!=null){let V=gc(A);Array.isArray(V)&&(V=V.map(H=>Q3(mc(H)))),x(e,["setup","tools"],V)}const E=m(t,["sessionResumption"]);e!==void 0&&E!=null&&x(e,["setup","sessionResumption"],Z3(E));const w=m(t,["inputAudioTranscription"]);e!==void 0&&w!=null&&x(e,["setup","inputAudioTranscription"],w);const I=m(t,["outputAudioTranscription"]);e!==void 0&&I!=null&&x(e,["setup","outputAudioTranscription"],I);const L=m(t,["realtimeInputConfig"]);e!==void 0&&L!=null&&x(e,["setup","realtimeInputConfig"],L);const D=m(t,["contextWindowCompression"]);e!==void 0&&D!=null&&x(e,["setup","contextWindowCompression"],D);const W=m(t,["proactivity"]);if(e!==void 0&&W!=null&&x(e,["setup","proactivity"],W),m(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");return n}function J3(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["setup","model"],zn(t,i));const r=m(e,["config"]);return r!=null&&x(n,["config"],Y3(r,n)),n}function K3(t){const e={},n=m(t,["mediaResolution"]);n!=null&&x(e,["mediaResolution"],n);const i=m(t,["codeExecutionResult"]);i!=null&&x(e,["codeExecutionResult"],i);const r=m(t,["executableCode"]);r!=null&&x(e,["executableCode"],r);const a=m(t,["fileData"]);a!=null&&x(e,["fileData"],q3(a));const c=m(t,["functionCall"]);c!=null&&x(e,["functionCall"],W3(c));const u=m(t,["functionResponse"]);u!=null&&x(e,["functionResponse"],u);const h=m(t,["inlineData"]);h!=null&&x(e,["inlineData"],V3(h));const d=m(t,["text"]);d!=null&&x(e,["text"],d);const g=m(t,["thought"]);g!=null&&x(e,["thought"],g);const v=m(t,["thoughtSignature"]);v!=null&&x(e,["thoughtSignature"],v);const y=m(t,["videoMetadata"]);return y!=null&&x(e,["videoMetadata"],y),e}function Z3(t){const e={},n=m(t,["handle"]);if(n!=null&&x(e,["handle"],n),m(t,["transparent"])!==void 0)throw new Error("transparent parameter is not supported in Gemini API.");return e}function Q3(t){const e={},n=m(t,["functionDeclarations"]);if(n!=null){let g=n;Array.isArray(g)&&(g=g.map(v=>v)),x(e,["functionDeclarations"],g)}if(m(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");const i=m(t,["googleSearchRetrieval"]);i!=null&&x(e,["googleSearchRetrieval"],i);const r=m(t,["computerUse"]);r!=null&&x(e,["computerUse"],r);const a=m(t,["fileSearch"]);a!=null&&x(e,["fileSearch"],a);const c=m(t,["codeExecution"]);if(c!=null&&x(e,["codeExecution"],c),m(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const u=m(t,["googleMaps"]);u!=null&&x(e,["googleMaps"],$3(u));const h=m(t,["googleSearch"]);h!=null&&x(e,["googleSearch"],X3(h));const d=m(t,["urlContext"]);return d!=null&&x(e,["urlContext"],d),e}function eL(t){const e=[];for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const i=t[n];if(typeof i=="object"&&i!=null&&Object.keys(i).length>0){const r=Object.keys(i).map(a=>`${n}.${a}`);e.push(...r)}else e.push(n)}return e.join(",")}function tL(t,e){let n=null;const i=t.bidiGenerateContentSetup;if(typeof i=="object"&&i!==null&&"setup"in i){const a=i.setup;typeof a=="object"&&a!==null?(t.bidiGenerateContentSetup=a,n=a):delete t.bidiGenerateContentSetup}else i!==void 0&&delete t.bidiGenerateContentSetup;const r=t.fieldMask;if(n){const a=eL(n);if(Array.isArray(e?.lockAdditionalFields)&&e?.lockAdditionalFields.length===0)a?t.fieldMask=a:delete t.fieldMask;else if(e?.lockAdditionalFields&&e.lockAdditionalFields.length>0&&r!==null&&Array.isArray(r)&&r.length>0){const c=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"];let u=[];r.length>0&&(u=r.map(d=>c.includes(d)?`generationConfig.${d}`:d));const h=[];a&&h.push(a),u.length>0&&h.push(...u),h.length>0?t.fieldMask=h.join(","):delete t.fieldMask}else delete t.fieldMask}else r!==null&&Array.isArray(r)&&r.length>0?t.fieldMask=r.join(","):delete t.fieldMask;return t}class nL extends br{constructor(e){super(),this.apiClient=e}async create(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{const u=j3(this.apiClient,e);a=Et("auth_tokens",u._url),c=u._query,delete u.config,delete u._url,delete u._query;const h=tL(u,e.config);return r=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(h),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(d=>d.json()),r.then(d=>d)}}}function iL(t,e){const n={},i=m(t,["force"]);return e!==void 0&&i!=null&&x(e,["_query","force"],i),n}function oL(t){const e={},n=m(t,["name"]);n!=null&&x(e,["_url","name"],n);const i=m(t,["config"]);return i!=null&&iL(i,e),e}function sL(t){const e={},n=m(t,["name"]);return n!=null&&x(e,["_url","name"],n),e}function rL(t,e){const n={},i=m(t,["pageSize"]);e!==void 0&&i!=null&&x(e,["_query","pageSize"],i);const r=m(t,["pageToken"]);return e!==void 0&&r!=null&&x(e,["_query","pageToken"],r),n}function aL(t){const e={},n=m(t,["parent"]);n!=null&&x(e,["_url","parent"],n);const i=m(t,["config"]);return i!=null&&rL(i,e),e}function lL(t){const e={},n=m(t,["sdkHttpResponse"]);n!=null&&x(e,["sdkHttpResponse"],n);const i=m(t,["nextPageToken"]);i!=null&&x(e,["nextPageToken"],i);const r=m(t,["documents"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(c=>c)),x(e,["documents"],a)}return e}class cL extends br{constructor(e){super(),this.apiClient=e,this.list=async n=>new Xa(xr.PAGED_ITEM_DOCUMENTS,i=>this.listInternal({parent:n.parent,config:i.config}),await this.listInternal(n),n)}async get(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=sL(e);return a=Et("{name}",u._url),c=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(h=>h.json()),r.then(h=>h)}}async delete(e){var n,i;let r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const c=oL(e);r=Et("{name}",c._url),a=c._query,delete c._url,delete c._query,await this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal})}}async listInternal(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=aL(e);return a=Et("{parent}/documents",u._url),c=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(h=>h.json()),r.then(h=>{const d=lL(h),g=new HR;return Object.assign(g,d),g})}}}class uL extends br{constructor(e,n=new cL(e)){super(),this.apiClient=e,this.documents=n,this.list=async(i={})=>new Xa(xr.PAGED_ITEM_FILE_SEARCH_STORES,r=>this.listInternal(r),await this.listInternal(i),i)}async uploadToFileSearchStore(e){if(this.apiClient.isVertexAI())throw new Error("Vertex AI does not support uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(e.fileSearchStoreName,e.file,e.config)}async create(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=e3(e);return a=Et("fileSearchStores",u._url),c=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(h=>h.json()),r.then(h=>h)}}async get(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=i3(e);return a=Et("{name}",u._url),c=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(h=>h.json()),r.then(h=>h)}}async delete(e){var n,i;let r="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const c=n3(e);r=Et("{name}",c._url),a=c._query,delete c._url,delete c._query,await this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(c),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal})}}async listInternal(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=c3(e);return a=Et("fileSearchStores",u._url),c=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(h=>h.json()),r.then(h=>{const d=u3(h),g=new GR;return Object.assign(g,d),g})}}async uploadToFileSearchStoreInternal(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=d3(e);return a=Et("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",u._url),c=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(h=>h.json()),r.then(h=>{const d=f3(h),g=new jR;return Object.assign(g,d),g})}}async importFile(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=r3(e);return a=Et("{file_search_store_name}:importFile",u._url),c=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(h=>h.json()),r.then(h=>{const d=s3(h),g=new Hg;return Object.assign(g,d),g})}}}let GT=function(){const{crypto:t}=globalThis;if(t?.randomUUID)return GT=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,i=>(+i^n()&15>>+i/4).toString(16))};const dL=()=>GT();function N0(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const I0=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class ps extends Error{}class Eo extends ps{constructor(e,n,i,r){super(`${Eo.makeMessage(e,n,i)}`),this.status=e,this.headers=r,this.error=n}static makeMessage(e,n,i){const r=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):i;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,n,i,r){if(!e||!r)return new Th({message:i,cause:I0(n)});const a=n;return e===400?new qT(e,a,i,r):e===401?new WT(e,a,i,r):e===403?new $T(e,a,i,r):e===404?new XT(e,a,i,r):e===409?new YT(e,a,i,r):e===422?new JT(e,a,i,r):e===429?new KT(e,a,i,r):e>=500?new ZT(e,a,i,r):new Eo(e,a,i,r)}}class D0 extends Eo{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Th extends Eo{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}}class jT extends Th{constructor({message:e}={}){super({message:e??"Request timed out."})}}class qT extends Eo{}class WT extends Eo{}class $T extends Eo{}class XT extends Eo{}class YT extends Eo{}class JT extends Eo{}class KT extends Eo{}class ZT extends Eo{}const fL=/^[a-z][a-z0-9+.-]*:/i,hL=t=>fL.test(t);let L0=t=>(L0=Array.isArray,L0(t));const pL=L0;let mL=pL;const HS=mL;function gL(t){if(!t)return!0;for(const e in t)return!1;return!0}function vL(t,e){return Object.prototype.hasOwnProperty.call(t,e)}const xL=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new ps(`${t} must be an integer`);if(e<0)throw new ps(`${t} must be a positive integer`);return e},yL=t=>{try{return JSON.parse(t)}catch{return}};const _L=t=>new Promise(e=>setTimeout(e,t));const ql="0.0.1";function bL(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const SL=()=>{var t,e,n,i,r;const a=bL();if(a==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ql,"X-Stainless-OS":jS(Deno.build.os),"X-Stainless-Arch":GS(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:(e=(t=Deno.version)===null||t===void 0?void 0:t.deno)!==null&&e!==void 0?e:"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ql,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(a==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ql,"X-Stainless-OS":jS((n=globalThis.process.platform)!==null&&n!==void 0?n:"unknown"),"X-Stainless-Arch":GS((i=globalThis.process.arch)!==null&&i!==void 0?i:"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":(r=globalThis.process.version)!==null&&r!==void 0?r:"unknown"};const c=TL();return c?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ql,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${c.browser}`,"X-Stainless-Runtime-Version":c.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ql,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function TL(){if(typeof navigator>"u"||!navigator)return null;const t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:n}of t){const i=n.exec(navigator.userAgent);if(i){const r=i[1]||0,a=i[2]||0,c=i[3]||0;return{browser:e,version:`${r}.${a}.${c}`}}}return null}const GS=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",jS=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown");let Jd;const EL=()=>Jd??(Jd=SL());function wL(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function QT(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function ML(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return QT({start(){},async pull(n){const{done:i,value:r}=await e.next();i?n.close():n.enqueue(r)},async cancel(){var n;await((n=e.return)===null||n===void 0?void 0:n.call(e))}})}function eE(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){const n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function CL(t){var e,n;if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await((n=(e=t[Symbol.asyncIterator]()).return)===null||n===void 0?void 0:n.call(e));return}const i=t.getReader(),r=i.cancel();i.releaseLock(),await r}const AL=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});const tE=()=>{var t;if(typeof File>"u"){const{process:e}=globalThis,n=typeof((t=e?.versions)===null||t===void 0?void 0:t.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(n?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Dm(t,e,n){return tE(),new File(t,e??"unknown_file",n)}function RL(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}const NL=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function";const nE=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",IL=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&nE(t),DL=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function LL(t,e,n){if(tE(),t=await t,IL(t))return t instanceof File?t:Dm([await t.arrayBuffer()],t.name);if(DL(t)){const r=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Dm(await U0(r),e,n)}const i=await U0(t);if(e||(e=RL(t)),!n?.type){const r=i.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof r=="string"&&(n=Object.assign(Object.assign({},n),{type:r}))}return Dm(i,e,n)}async function U0(t){var e,n,i,r,a;let c=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)c.push(t);else if(nE(t))c.push(t instanceof Blob?t:await t.arrayBuffer());else if(NL(t))try{for(var u=!0,h=Cs(t),d;d=await h.next(),e=d.done,!e;u=!0){r=d.value,u=!1;const g=r;c.push(...await U0(g))}}catch(g){n={error:g}}finally{try{!u&&!e&&(i=h.return)&&await i.call(h)}finally{if(n)throw n.error}}else{const g=(a=t?.constructor)===null||a===void 0?void 0:a.name;throw new Error(`Unexpected data type: ${typeof t}${g?`; constructor: ${g}`:""}${UL(t)}`)}return c}function UL(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}class iE{constructor(e){this._client=e}}iE._key=[];function oE(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const qS=Object.freeze(Object.create(null)),kL=(t=oE)=>(function(n,...i){if(n.length===1)return n[0];let r=!1;const a=[],c=n.reduce((g,v,y)=>{var S,T,A;/[?#]/.test(v)&&(r=!0);const E=i[y];let w=(r?encodeURIComponent:t)(""+E);return y!==i.length&&(E==null||typeof E=="object"&&E.toString===((A=Object.getPrototypeOf((T=Object.getPrototypeOf((S=E.hasOwnProperty)!==null&&S!==void 0?S:qS))!==null&&T!==void 0?T:qS))===null||A===void 0?void 0:A.toString))&&(w=E+"",a.push({start:g.length+v.length,length:w.length,error:`Value of type ${Object.prototype.toString.call(E).slice(8,-1)} is not a valid path parameter`})),g+v+(y===i.length?"":w)},""),u=c.split(/[?#]/,1)[0],h=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let d;for(;(d=h.exec(u))!==null;)a.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(a.sort((g,v)=>g.start-v.start),a.length>0){let g=0;const v=a.reduce((y,S)=>{const T=" ".repeat(S.start-g),A="^".repeat(S.length);return g=S.start+S.length,y+T+A},"");throw new ps(`Path parameters result in path with invalid segments: +${a.map(y=>y.error).join(` +`)} +${c} +${v}`)}return c}),Kd=kL(oE);class sE extends iE{create(e,n){var i;const{api_version:r=this._client.apiVersion}=e,a=th(e,["api_version"]);if("model"in a&&"agent_config"in a)throw new ps("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.");if("agent"in a&&"generation_config"in a)throw new ps("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.");return this._client.post(Kd`/${r}/interactions`,Object.assign(Object.assign({body:a},n),{stream:(i=e.stream)!==null&&i!==void 0?i:!1}))}delete(e,n={},i){const{api_version:r=this._client.apiVersion}=n??{};return this._client.delete(Kd`/${r}/interactions/${e}`,i)}cancel(e,n={},i){const{api_version:r=this._client.apiVersion}=n??{};return this._client.post(Kd`/${r}/interactions/${e}/cancel`,i)}get(e,n={},i){var r;const a=n??{},{api_version:c=this._client.apiVersion}=a,u=th(a,["api_version"]);return this._client.get(Kd`/${c}/interactions/${e}`,Object.assign(Object.assign({query:u},i),{stream:(r=n?.stream)!==null&&r!==void 0?r:!1}))}}sE._key=Object.freeze(["interactions"]);class rE extends sE{}function zL(t){let e=0;for(const r of t)e+=r.length;const n=new Uint8Array(e);let i=0;for(const r of t)n.set(r,i),i+=r.length;return n}let Zd;function Yg(t){let e;return(Zd??(e=new globalThis.TextEncoder,Zd=e.encode.bind(e)))(t)}let Qd;function WS(t){let e;return(Qd??(e=new globalThis.TextDecoder,Qd=e.decode.bind(e)))(t)}class Eh{constructor(){this.buffer=new Uint8Array,this.carriageReturnIndex=null}decode(e){if(e==null)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Yg(e):e;this.buffer=zL([this.buffer,n]);const i=[];let r;for(;(r=PL(this.buffer,this.carriageReturnIndex))!=null;){if(r.carriage&&this.carriageReturnIndex==null){this.carriageReturnIndex=r.index;continue}if(this.carriageReturnIndex!=null&&(r.index!==this.carriageReturnIndex+1||r.carriage)){i.push(WS(this.buffer.subarray(0,this.carriageReturnIndex-1))),this.buffer=this.buffer.subarray(this.carriageReturnIndex),this.carriageReturnIndex=null;continue}const a=this.carriageReturnIndex!==null?r.preceding-1:r.preceding,c=WS(this.buffer.subarray(0,a));i.push(c),this.buffer=this.buffer.subarray(r.index),this.carriageReturnIndex=null}return i}flush(){return this.buffer.length?this.decode(` +`):[]}}Eh.NEWLINE_CHARS=new Set([` +`,"\r"]);Eh.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function PL(t,e){for(let r=e??0;r{if(t){if(vL(nh,t))return t;So(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(nh))}`)}};function Su(){}function ef(t,e,n){return!e||nh[t]>nh[n]?Su:e[t].bind(e)}const OL={error:Su,warn:Su,info:Su,debug:Su};let XS=new WeakMap;function So(t){var e;const n=t.logger,i=(e=t.logLevel)!==null&&e!==void 0?e:"off";if(!n)return OL;const r=XS.get(n);if(r&&r[0]===i)return r[1];const a={error:ef("error",n,i),warn:ef("warn",n,i),info:ef("info",n,i),debug:ef("debug",n,i)};return XS.set(n,[i,a]),a}const Ra=t=>(t.options&&(t.options=Object.assign({},t.options),delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="x-goog-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);class Yl{constructor(e,n,i){this.iterator=e,this.controller=n,this.client=i}static fromSSEResponse(e,n,i){let r=!1;const a=i?So(i):console;function c(){return Ms(this,arguments,function*(){var h,d,g,v;if(r)throw new ps("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let y=!1;try{try{for(var S=!0,T=Cs(BL(e,n)),A;A=yield Kt(T.next()),h=A.done,!h;S=!0){v=A.value,S=!1;const E=v;if(!y)if(E.data.startsWith("[DONE]")){y=!0;continue}else try{yield yield Kt(JSON.parse(E.data))}catch(w){throw a.error("Could not parse message into JSON:",E.data),a.error("From chunk:",E.raw),w}}}catch(E){d={error:E}}finally{try{!S&&!h&&(g=T.return)&&(yield Kt(g.call(T)))}finally{if(d)throw d.error}}y=!0}catch(E){if(N0(E))return yield Kt(void 0);throw E}finally{y||n.abort()}})}return new Yl(c,n,i)}static fromReadableStream(e,n,i){let r=!1;function a(){return Ms(this,arguments,function*(){var h,d,g,v;const y=new Eh,S=eE(e);try{for(var T=!0,A=Cs(S),E;E=yield Kt(A.next()),h=E.done,!h;T=!0){v=E.value,T=!1;const w=v;for(const I of y.decode(w))yield yield Kt(I)}}catch(w){d={error:w}}finally{try{!T&&!h&&(g=A.return)&&(yield Kt(g.call(A)))}finally{if(d)throw d.error}}for(const w of y.flush())yield yield Kt(w)})}function c(){return Ms(this,arguments,function*(){var h,d,g,v;if(r)throw new ps("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let y=!1;try{try{for(var S=!0,T=Cs(a()),A;A=yield Kt(T.next()),h=A.done,!h;S=!0){v=A.value,S=!1;const E=v;y||E&&(yield yield Kt(JSON.parse(E)))}}catch(E){d={error:E}}finally{try{!S&&!h&&(g=T.return)&&(yield Kt(g.call(T)))}finally{if(d)throw d.error}}y=!0}catch(E){if(N0(E))return yield Kt(void 0);throw E}finally{y||n.abort()}})}return new Yl(c,n,i)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],n=[],i=this.iterator(),r=a=>({next:()=>{if(a.length===0){const c=i.next();e.push(c),n.push(c)}return a.shift()}});return[new Yl(()=>r(e),this.controller,this.client),new Yl(()=>r(n),this.controller,this.client)]}toReadableStream(){const e=this;let n;return QT({async start(){n=e[Symbol.asyncIterator]()},async pull(i){try{const{value:r,done:a}=await n.next();if(a)return i.close();const c=Yg(JSON.stringify(r)+` +`);i.enqueue(c)}catch(r){i.error(r)}},async cancel(){var i;await((i=n.return)===null||i===void 0?void 0:i.call(n))}})}}function BL(t,e){return Ms(this,arguments,function*(){var i,r,a,c;if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ps("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new ps("Attempted to iterate over a response with no body");const u=new HL,h=new Eh,d=eE(t.body);try{for(var g=!0,v=Cs(VL(d)),y;y=yield Kt(v.next()),i=y.done,!i;g=!0){c=y.value,g=!1;const S=c;for(const T of h.decode(S)){const A=u.decode(T);A&&(yield yield Kt(A))}}}catch(S){r={error:S}}finally{try{!g&&!i&&(a=v.return)&&(yield Kt(a.call(v)))}finally{if(r)throw r.error}}for(const S of h.flush()){const T=u.decode(S);T&&(yield yield Kt(T))}})}function VL(t){return Ms(this,arguments,function*(){var n,i,r,a;let c=new Uint8Array;try{for(var u=!0,h=Cs(t),d;d=yield Kt(h.next()),n=d.done,!n;u=!0){a=d.value,u=!1;const g=a;if(g==null)continue;const v=g instanceof ArrayBuffer?new Uint8Array(g):typeof g=="string"?Yg(g):g;let y=new Uint8Array(c.length+v.length);y.set(c),y.set(v,c.length),c=y;let S;for(;(S=FL(c))!==-1;)yield yield Kt(c.slice(0,S)),c=c.slice(S)}}catch(g){i={error:g}}finally{try{!u&&!n&&(r=h.return)&&(yield Kt(r.call(h)))}finally{if(i)throw i.error}}c.length>0&&(yield yield Kt(c))})}class HL{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const a={event:this.event,data:this.data.join(` +`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,i,r]=GL(e,":");return r.startsWith(" ")&&(r=r.substring(1)),n==="event"?this.event=r:n==="data"&&this.data.push(r),null}}function GL(t,e){const n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}async function jL(t,e){const{response:n,requestLogID:i,retryOfRequestLogID:r,startTime:a}=e,c=await(async()=>{var u;if(e.options.stream)return So(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller,t):Yl.fromSSEResponse(n,e.controller,t);if(n.status===204)return null;if(e.options.__binaryResponse)return n;const h=n.headers.get("content-type"),d=(u=h?.split(";")[0])===null||u===void 0?void 0:u.trim();return d?.includes("application/json")||d?.endsWith("+json")?await n.json():await n.text()})();return So(t).debug(`[${i}] response parsed`,Ra({retryOfRequestLogID:r,url:n.url,status:n.status,body:c,durationMs:Date.now()-a})),c}class Jg extends Promise{constructor(e,n,i=jL){super(r=>{r(null)}),this.responsePromise=n,this.parseResponse=i,this.client=e}_thenUnwrap(e){return new Jg(this.client,this.responsePromise,async(n,i)=>e(await this.parseResponse(n,i),i))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(this.client,e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}const aE=Symbol("brand.privateNullableHeaders");function*qL(t){if(!t)return;if(aE in t){const{values:i,nulls:r}=t;yield*i.entries();for(const a of r)yield[a,null];return}let e=!1,n;t instanceof Headers?n=t.entries():HS(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let i of n){const r=i[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const a=HS(i[1])?i[1]:[i[1]];let c=!1;for(const u of a)u!==void 0&&(e&&!c&&(c=!0,yield[r,null]),yield[r,u])}}const lu=t=>{const e=new Headers,n=new Set;for(const i of t){const r=new Set;for(const[a,c]of qL(i)){const u=a.toLowerCase();r.has(u)||(e.delete(a),r.add(u)),c===null?(e.delete(a),n.add(u)):(e.append(a,c),n.delete(u))}}return{[aE]:!0,values:e,nulls:n}};const Lm=t=>{var e,n,i,r,a,c;if(typeof globalThis.process<"u")return(i=(n=(e=vR)===null||e===void 0?void 0:e[t])===null||n===void 0?void 0:n.trim())!==null&&i!==void 0?i:void 0;if(typeof globalThis.Deno<"u")return(c=(a=(r=globalThis.Deno.env)===null||r===void 0?void 0:r.get)===null||a===void 0?void 0:a.call(r,t))===null||c===void 0?void 0:c.trim()};var lE;class wh{constructor(e){var n,i,r,a,c,u,h,{baseURL:d=Lm("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:g=(n=Lm("GEMINI_API_KEY"))!==null&&n!==void 0?n:null,apiVersion:v="v1beta"}=e,y=th(e,["baseURL","apiKey","apiVersion"]);const S=Object.assign(Object.assign({apiKey:g,apiVersion:v},y),{baseURL:d||"https://generativelanguage.googleapis.com"});this.baseURL=S.baseURL,this.timeout=(i=S.timeout)!==null&&i!==void 0?i:wh.DEFAULT_TIMEOUT,this.logger=(r=S.logger)!==null&&r!==void 0?r:console;const T="warn";this.logLevel=T,this.logLevel=(c=(a=$S(S.logLevel,"ClientOptions.logLevel",this))!==null&&a!==void 0?a:$S(Lm("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))!==null&&c!==void 0?c:T,this.fetchOptions=S.fetchOptions,this.maxRetries=(u=S.maxRetries)!==null&&u!==void 0?u:2,this.fetch=(h=S.fetch)!==null&&h!==void 0?h:wL(),this.encoder=AL,this._options=S,this.apiKey=g,this.apiVersion=v,this.clientAdapter=S.clientAdapter}withOptions(e){return new this.constructor(Object.assign(Object.assign(Object.assign({},this._options),{baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,apiVersion:this.apiVersion}),e))}baseURLOverridden(){return this.baseURL!=="https://generativelanguage.googleapis.com"}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(!(e.has("authorization")||e.has("x-goog-api-key"))&&!(this.apiKey&&e.get("x-goog-api-key"))&&!n.has("x-goog-api-key"))throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted')}async authHeaders(e){const n=lu([e.headers]);if(!(n.values.has("authorization")||n.values.has("x-goog-api-key"))){if(this.apiKey)return lu([{"x-goog-api-key":this.apiKey}]);if(this.clientAdapter.isVertexAI())return lu([await this.clientAdapter.getAuthHeaders()])}}stringifyQuery(e){return Object.entries(e).filter(([n,i])=>typeof i<"u").map(([n,i])=>{if(typeof i=="string"||typeof i=="number"||typeof i=="boolean")return`${encodeURIComponent(n)}=${encodeURIComponent(i)}`;if(i===null)return`${encodeURIComponent(n)}=`;throw new ps(`Cannot stringify type ${typeof i}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${ql}`}defaultIdempotencyKey(){return`stainless-node-retry-${dL()}`}makeStatusError(e,n,i,r){return Eo.generate(e,n,i,r)}buildURL(e,n,i){const r=!this.baseURLOverridden()&&i||this.baseURL,a=hL(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),c=this.defaultQuery();return gL(c)||(n=Object.assign(Object.assign({},c),n)),typeof n=="object"&&n&&!Array.isArray(n)&&(a.search=this.stringifyQuery(n)),a.toString()}async prepareOptions(e){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!e.path.startsWith(`/${this.apiVersion}/projects/`)){const n=e.path.slice(this.apiVersion.length+1);e.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${n}`}}async prepareRequest(e,{url:n,options:i}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,i){return this.request(Promise.resolve(i).then(r=>Object.assign({method:e,path:n},r)))}request(e,n=null){return new Jg(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,i){var r,a,c;const u=await e,h=(r=u.maxRetries)!==null&&r!==void 0?r:this.maxRetries;n==null&&(n=h),await this.prepareOptions(u);const{req:d,url:g,timeout:v}=await this.buildRequest(u,{retryCount:h-n});await this.prepareRequest(d,{url:g,options:u});const y="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),S=i===void 0?"":`, retryOf: ${i}`,T=Date.now();if(So(this).debug(`[${y}] sending request`,Ra({retryOfRequestLogID:i,method:u.method,url:g,options:u,headers:d.headers})),!((a=u.signal)===null||a===void 0)&&a.aborted)throw new D0;const A=new AbortController,E=await this.fetchWithTimeout(g,d,v,A).catch(I0),w=Date.now();if(E instanceof globalThis.Error){const L=`retrying, ${n} attempts remaining`;if(!((c=u.signal)===null||c===void 0)&&c.aborted)throw new D0;const D=N0(E)||/timed? ?out/i.test(String(E)+("cause"in E?String(E.cause):""));if(n)return So(this).info(`[${y}] connection ${D?"timed out":"failed"} - ${L}`),So(this).debug(`[${y}] connection ${D?"timed out":"failed"} (${L})`,Ra({retryOfRequestLogID:i,url:g,durationMs:w-T,message:E.message})),this.retryRequest(u,n,i??y);throw So(this).info(`[${y}] connection ${D?"timed out":"failed"} - error; no more retries left`),So(this).debug(`[${y}] connection ${D?"timed out":"failed"} (error; no more retries left)`,Ra({retryOfRequestLogID:i,url:g,durationMs:w-T,message:E.message})),D?new jT:new Th({cause:E})}const I=`[${y}${S}] ${d.method} ${g} ${E.ok?"succeeded":"failed"} with status ${E.status} in ${w-T}ms`;if(!E.ok){const L=await this.shouldRetry(E);if(n&&L){const k=`retrying, ${n} attempts remaining`;return await CL(E.body),So(this).info(`${I} - ${k}`),So(this).debug(`[${y}] response error (${k})`,Ra({retryOfRequestLogID:i,url:E.url,status:E.status,headers:E.headers,durationMs:w-T})),this.retryRequest(u,n,i??y,E.headers)}const D=L?"error; no more retries left":"error; not retryable";So(this).info(`${I} - ${D}`);const W=await E.text().catch(k=>I0(k).message),V=yL(W),H=V?void 0:W;throw So(this).debug(`[${y}] response error (${D})`,Ra({retryOfRequestLogID:i,url:E.url,status:E.status,headers:E.headers,message:H,durationMs:Date.now()-T})),this.makeStatusError(E.status,V,H,E.headers)}return So(this).info(I),So(this).debug(`[${y}] response start`,Ra({retryOfRequestLogID:i,url:E.url,status:E.status,headers:E.headers,durationMs:w-T})),{response:E,options:u,controller:A,requestLogID:y,retryOfRequestLogID:i,startTime:T}}async fetchWithTimeout(e,n,i,r){const a=n||{},{signal:c,method:u}=a,h=th(a,["signal","method"]);c&&c.addEventListener("abort",()=>r.abort());const d=setTimeout(()=>r.abort(),i),g=globalThis.ReadableStream&&h.body instanceof globalThis.ReadableStream||typeof h.body=="object"&&h.body!==null&&Symbol.asyncIterator in h.body,v=Object.assign(Object.assign(Object.assign({signal:r.signal},g?{duplex:"half"}:{}),{method:"GET"}),h);u&&(v.method=u.toUpperCase());try{return await this.fetch.call(void 0,e,v)}finally{clearTimeout(d)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,i,r){var a;let c;const u=r?.get("retry-after-ms");if(u){const d=parseFloat(u);Number.isNaN(d)||(c=d)}const h=r?.get("retry-after");if(h&&!c){const d=parseFloat(h);Number.isNaN(d)?c=Date.parse(h)-Date.now():c=d*1e3}if(!(c&&0<=c&&c<60*1e3)){const d=(a=e.maxRetries)!==null&&a!==void 0?a:this.maxRetries;c=this.calculateDefaultRetryTimeoutMillis(n,d)}return await _L(c),this.makeRequest(e,n-1,i)}calculateDefaultRetryTimeoutMillis(e,n){const a=n-e,c=Math.min(.5*Math.pow(2,a),8),u=1-Math.random()*.25;return c*u*1e3}async buildRequest(e,{retryCount:n=0}={}){var i,r,a;const c=Object.assign({},e),{method:u,path:h,query:d,defaultBaseURL:g}=c,v=this.buildURL(h,d,g);"timeout"in c&&xL("timeout",c.timeout),c.timeout=(i=c.timeout)!==null&&i!==void 0?i:this.timeout;const{bodyHeaders:y,body:S}=this.buildBody({options:c}),T=await this.buildHeaders({options:e,method:u,bodyHeaders:y,retryCount:n});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:u,headers:T},c.signal&&{signal:c.signal}),globalThis.ReadableStream&&S instanceof globalThis.ReadableStream&&{duplex:"half"}),S&&{body:S}),(r=this.fetchOptions)!==null&&r!==void 0?r:{}),(a=c.fetchOptions)!==null&&a!==void 0?a:{}),url:v,timeout:c.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:i,retryCount:r}){let a={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);const c=await this.authHeaders(e);let u=lu([a,Object.assign(Object.assign({Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r)},e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{}),EL()),this._options.defaultHeaders,i,e.headers,c]);return this.validateHeaders(u),u.values}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};const i=lu([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&i.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:ML(e)}:this.encoder({body:e,headers:i})}}wh.DEFAULT_TIMEOUT=6e4;class no extends wh{constructor(){super(...arguments),this.interactions=new rE(this)}}lE=no;no.GeminiNextGenAPIClient=lE;no.GeminiNextGenAPIClientError=ps;no.APIError=Eo;no.APIConnectionError=Th;no.APIConnectionTimeoutError=jT;no.APIUserAbortError=D0;no.NotFoundError=XT;no.ConflictError=YT;no.RateLimitError=KT;no.BadRequestError=qT;no.AuthenticationError=WT;no.InternalServerError=ZT;no.PermissionDeniedError=$T;no.UnprocessableEntityError=JT;no.toFile=LL;no.Interactions=rE;function WL(t,e){const n={},i=m(t,["name"]);return i!=null&&x(n,["_url","name"],i),n}function $L(t,e){const n={},i=m(t,["name"]);return i!=null&&x(n,["_url","name"],i),n}function XL(t,e){const n={},i=m(t,["sdkHttpResponse"]);return i!=null&&x(n,["sdkHttpResponse"],i),n}function YL(t,e){const n={},i=m(t,["sdkHttpResponse"]);return i!=null&&x(n,["sdkHttpResponse"],i),n}function JL(t,e,n){const i={};if(m(t,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is not supported in Gemini API.");const r=m(t,["tunedModelDisplayName"]);if(e!==void 0&&r!=null&&x(e,["displayName"],r),m(t,["description"])!==void 0)throw new Error("description parameter is not supported in Gemini API.");const a=m(t,["epochCount"]);e!==void 0&&a!=null&&x(e,["tuningTask","hyperparameters","epochCount"],a);const c=m(t,["learningRateMultiplier"]);if(c!=null&&x(i,["tuningTask","hyperparameters","learningRateMultiplier"],c),m(t,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is not supported in Gemini API.");if(m(t,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is not supported in Gemini API.");if(m(t,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is not supported in Gemini API.");const u=m(t,["batchSize"]);e!==void 0&&u!=null&&x(e,["tuningTask","hyperparameters","batchSize"],u);const h=m(t,["learningRate"]);if(e!==void 0&&h!=null&&x(e,["tuningTask","hyperparameters","learningRate"],h),m(t,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");if(m(t,["beta"])!==void 0)throw new Error("beta parameter is not supported in Gemini API.");return i}function KL(t,e,n){const i={};let r=m(n,["config","method"]);if(r===void 0&&(r="SUPERVISED_FINE_TUNING"),r==="SUPERVISED_FINE_TUNING"){const S=m(t,["validationDataset"]);e!==void 0&&S!=null&&x(e,["supervisedTuningSpec"],YS(S))}else if(r==="PREFERENCE_TUNING"){const S=m(t,["validationDataset"]);e!==void 0&&S!=null&&x(e,["preferenceOptimizationSpec"],YS(S))}const a=m(t,["tunedModelDisplayName"]);e!==void 0&&a!=null&&x(e,["tunedModelDisplayName"],a);const c=m(t,["description"]);e!==void 0&&c!=null&&x(e,["description"],c);let u=m(n,["config","method"]);if(u===void 0&&(u="SUPERVISED_FINE_TUNING"),u==="SUPERVISED_FINE_TUNING"){const S=m(t,["epochCount"]);e!==void 0&&S!=null&&x(e,["supervisedTuningSpec","hyperParameters","epochCount"],S)}else if(u==="PREFERENCE_TUNING"){const S=m(t,["epochCount"]);e!==void 0&&S!=null&&x(e,["preferenceOptimizationSpec","hyperParameters","epochCount"],S)}let h=m(n,["config","method"]);if(h===void 0&&(h="SUPERVISED_FINE_TUNING"),h==="SUPERVISED_FINE_TUNING"){const S=m(t,["learningRateMultiplier"]);e!==void 0&&S!=null&&x(e,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],S)}else if(h==="PREFERENCE_TUNING"){const S=m(t,["learningRateMultiplier"]);e!==void 0&&S!=null&&x(e,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],S)}let d=m(n,["config","method"]);if(d===void 0&&(d="SUPERVISED_FINE_TUNING"),d==="SUPERVISED_FINE_TUNING"){const S=m(t,["exportLastCheckpointOnly"]);e!==void 0&&S!=null&&x(e,["supervisedTuningSpec","exportLastCheckpointOnly"],S)}else if(d==="PREFERENCE_TUNING"){const S=m(t,["exportLastCheckpointOnly"]);e!==void 0&&S!=null&&x(e,["preferenceOptimizationSpec","exportLastCheckpointOnly"],S)}let g=m(n,["config","method"]);if(g===void 0&&(g="SUPERVISED_FINE_TUNING"),g==="SUPERVISED_FINE_TUNING"){const S=m(t,["adapterSize"]);e!==void 0&&S!=null&&x(e,["supervisedTuningSpec","hyperParameters","adapterSize"],S)}else if(g==="PREFERENCE_TUNING"){const S=m(t,["adapterSize"]);e!==void 0&&S!=null&&x(e,["preferenceOptimizationSpec","hyperParameters","adapterSize"],S)}if(m(t,["batchSize"])!==void 0)throw new Error("batchSize parameter is not supported in Vertex AI.");if(m(t,["learningRate"])!==void 0)throw new Error("learningRate parameter is not supported in Vertex AI.");const v=m(t,["labels"]);e!==void 0&&v!=null&&x(e,["labels"],v);const y=m(t,["beta"]);return e!==void 0&&y!=null&&x(e,["preferenceOptimizationSpec","hyperParameters","beta"],y),i}function ZL(t,e){const n={},i=m(t,["baseModel"]);i!=null&&x(n,["baseModel"],i);const r=m(t,["preTunedModel"]);r!=null&&x(n,["preTunedModel"],r);const a=m(t,["trainingDataset"]);a!=null&&cU(a);const c=m(t,["config"]);return c!=null&&JL(c,n),n}function QL(t,e){const n={},i=m(t,["baseModel"]);i!=null&&x(n,["baseModel"],i);const r=m(t,["preTunedModel"]);r!=null&&x(n,["preTunedModel"],r);const a=m(t,["trainingDataset"]);a!=null&&uU(a,n,e);const c=m(t,["config"]);return c!=null&&KL(c,n,e),n}function eU(t,e){const n={},i=m(t,["name"]);return i!=null&&x(n,["_url","name"],i),n}function tU(t,e){const n={},i=m(t,["name"]);return i!=null&&x(n,["_url","name"],i),n}function nU(t,e,n){const i={},r=m(t,["pageSize"]);e!==void 0&&r!=null&&x(e,["_query","pageSize"],r);const a=m(t,["pageToken"]);e!==void 0&&a!=null&&x(e,["_query","pageToken"],a);const c=m(t,["filter"]);return e!==void 0&&c!=null&&x(e,["_query","filter"],c),i}function iU(t,e,n){const i={},r=m(t,["pageSize"]);e!==void 0&&r!=null&&x(e,["_query","pageSize"],r);const a=m(t,["pageToken"]);e!==void 0&&a!=null&&x(e,["_query","pageToken"],a);const c=m(t,["filter"]);return e!==void 0&&c!=null&&x(e,["_query","filter"],c),i}function oU(t,e){const n={},i=m(t,["config"]);return i!=null&&nU(i,n),n}function sU(t,e){const n={},i=m(t,["config"]);return i!=null&&iU(i,n),n}function rU(t,e){const n={},i=m(t,["sdkHttpResponse"]);i!=null&&x(n,["sdkHttpResponse"],i);const r=m(t,["nextPageToken"]);r!=null&&x(n,["nextPageToken"],r);const a=m(t,["tunedModels"]);if(a!=null){let c=a;Array.isArray(c)&&(c=c.map(u=>cE(u))),x(n,["tuningJobs"],c)}return n}function aU(t,e){const n={},i=m(t,["sdkHttpResponse"]);i!=null&&x(n,["sdkHttpResponse"],i);const r=m(t,["nextPageToken"]);r!=null&&x(n,["nextPageToken"],r);const a=m(t,["tuningJobs"]);if(a!=null){let c=a;Array.isArray(c)&&(c=c.map(u=>k0(u))),x(n,["tuningJobs"],c)}return n}function lU(t,e){const n={},i=m(t,["name"]);i!=null&&x(n,["model"],i);const r=m(t,["name"]);return r!=null&&x(n,["endpoint"],r),n}function cU(t,e){const n={};if(m(t,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");if(m(t,["vertexDatasetResource"])!==void 0)throw new Error("vertexDatasetResource parameter is not supported in Gemini API.");const i=m(t,["examples"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>a)),x(n,["examples","examples"],r)}return n}function uU(t,e,n){const i={};let r=m(n,["config","method"]);if(r===void 0&&(r="SUPERVISED_FINE_TUNING"),r==="SUPERVISED_FINE_TUNING"){const c=m(t,["gcsUri"]);e!==void 0&&c!=null&&x(e,["supervisedTuningSpec","trainingDatasetUri"],c)}else if(r==="PREFERENCE_TUNING"){const c=m(t,["gcsUri"]);e!==void 0&&c!=null&&x(e,["preferenceOptimizationSpec","trainingDatasetUri"],c)}let a=m(n,["config","method"]);if(a===void 0&&(a="SUPERVISED_FINE_TUNING"),a==="SUPERVISED_FINE_TUNING"){const c=m(t,["vertexDatasetResource"]);e!==void 0&&c!=null&&x(e,["supervisedTuningSpec","trainingDatasetUri"],c)}else if(a==="PREFERENCE_TUNING"){const c=m(t,["vertexDatasetResource"]);e!==void 0&&c!=null&&x(e,["preferenceOptimizationSpec","trainingDatasetUri"],c)}if(m(t,["examples"])!==void 0)throw new Error("examples parameter is not supported in Vertex AI.");return i}function cE(t,e){const n={},i=m(t,["sdkHttpResponse"]);i!=null&&x(n,["sdkHttpResponse"],i);const r=m(t,["name"]);r!=null&&x(n,["name"],r);const a=m(t,["state"]);a!=null&&x(n,["state"],wT(a));const c=m(t,["createTime"]);c!=null&&x(n,["createTime"],c);const u=m(t,["tuningTask","startTime"]);u!=null&&x(n,["startTime"],u);const h=m(t,["tuningTask","completeTime"]);h!=null&&x(n,["endTime"],h);const d=m(t,["updateTime"]);d!=null&&x(n,["updateTime"],d);const g=m(t,["description"]);g!=null&&x(n,["description"],g);const v=m(t,["baseModel"]);v!=null&&x(n,["baseModel"],v);const y=m(t,["_self"]);return y!=null&&x(n,["tunedModel"],lU(y)),n}function k0(t,e){const n={},i=m(t,["sdkHttpResponse"]);i!=null&&x(n,["sdkHttpResponse"],i);const r=m(t,["name"]);r!=null&&x(n,["name"],r);const a=m(t,["state"]);a!=null&&x(n,["state"],wT(a));const c=m(t,["createTime"]);c!=null&&x(n,["createTime"],c);const u=m(t,["startTime"]);u!=null&&x(n,["startTime"],u);const h=m(t,["endTime"]);h!=null&&x(n,["endTime"],h);const d=m(t,["updateTime"]);d!=null&&x(n,["updateTime"],d);const g=m(t,["error"]);g!=null&&x(n,["error"],g);const v=m(t,["description"]);v!=null&&x(n,["description"],v);const y=m(t,["baseModel"]);y!=null&&x(n,["baseModel"],y);const S=m(t,["tunedModel"]);S!=null&&x(n,["tunedModel"],S);const T=m(t,["preTunedModel"]);T!=null&&x(n,["preTunedModel"],T);const A=m(t,["supervisedTuningSpec"]);A!=null&&x(n,["supervisedTuningSpec"],A);const E=m(t,["preferenceOptimizationSpec"]);E!=null&&x(n,["preferenceOptimizationSpec"],E);const w=m(t,["tuningDataStats"]);w!=null&&x(n,["tuningDataStats"],w);const I=m(t,["encryptionSpec"]);I!=null&&x(n,["encryptionSpec"],I);const L=m(t,["partnerModelTuningSpec"]);L!=null&&x(n,["partnerModelTuningSpec"],L);const D=m(t,["customBaseModel"]);D!=null&&x(n,["customBaseModel"],D);const W=m(t,["experiment"]);W!=null&&x(n,["experiment"],W);const V=m(t,["labels"]);V!=null&&x(n,["labels"],V);const H=m(t,["outputUri"]);H!=null&&x(n,["outputUri"],H);const Q=m(t,["pipelineJob"]);Q!=null&&x(n,["pipelineJob"],Q);const k=m(t,["serviceAccount"]);k!=null&&x(n,["serviceAccount"],k);const P=m(t,["tunedModelDisplayName"]);P!=null&&x(n,["tunedModelDisplayName"],P);const J=m(t,["veoTuningSpec"]);return J!=null&&x(n,["veoTuningSpec"],J),n}function dU(t,e){const n={},i=m(t,["sdkHttpResponse"]);i!=null&&x(n,["sdkHttpResponse"],i);const r=m(t,["name"]);r!=null&&x(n,["name"],r);const a=m(t,["metadata"]);a!=null&&x(n,["metadata"],a);const c=m(t,["done"]);c!=null&&x(n,["done"],c);const u=m(t,["error"]);return u!=null&&x(n,["error"],u),n}function YS(t,e){const n={},i=m(t,["gcsUri"]);i!=null&&x(n,["validationDatasetUri"],i);const r=m(t,["vertexDatasetResource"]);return r!=null&&x(n,["validationDatasetUri"],r),n}class fU extends br{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new Xa(xr.PAGED_ITEM_TUNING_JOBS,i=>this.listInternal(i),await this.listInternal(n),n),this.get=async n=>await this.getInternal(n),this.tune=async n=>{var i;if(this.apiClient.isVertexAI())if(n.baseModel.startsWith("projects/")){const r={tunedModelName:n.baseModel};!((i=n.config)===null||i===void 0)&&i.preTunedModelCheckpointId&&(r.checkpointId=n.config.preTunedModelCheckpointId);const a=Object.assign(Object.assign({},n),{preTunedModel:r});return a.baseModel=void 0,await this.tuneInternal(a)}else{const r=Object.assign({},n);return await this.tuneInternal(r)}else{const r=Object.assign({},n),a=await this.tuneMldevInternal(r);let c="";return a.metadata!==void 0&&a.metadata.tunedModel!==void 0?c=a.metadata.tunedModel:a.name!==void 0&&a.name.includes("/operations/")&&(c=a.name.split("/operations/")[0]),{name:c,state:T0.JOB_STATE_QUEUED}}}}async getInternal(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=tU(e);return u=Et("{name}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>k0(g))}else{const d=eU(e);return u=Et("{name}",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>cE(g))}}async listInternal(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=sU(e);return u=Et("tuningJobs",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=aU(g),y=new bS;return Object.assign(y,v),y})}else{const d=oU(e);return u=Et("tunedModels",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=rU(g),y=new bS;return Object.assign(y,v),y})}}async cancel(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=$L(e);return u=Et("{name}:cancel",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=YL(g),y=new SS;return Object.assign(y,v),y})}else{const d=WL(e);return u=Et("{name}:cancel",d._url),h=d._query,delete d._url,delete d._query,c=this.apiClient.request({path:u,queryParams:h,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(a=e.config)===null||a===void 0?void 0:a.abortSignal}).then(g=>g.json().then(v=>{const y=v;return y.sdkHttpResponse={headers:g.headers},y})),c.then(g=>{const v=XL(g),y=new SS;return Object.assign(y,v),y})}}async tuneInternal(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI()){const u=QL(e,e);return a=Et("tuningJobs",u._url),c=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(h=>h.json().then(d=>{const g=d;return g.sdkHttpResponse={headers:h.headers},g})),r.then(h=>k0(h))}else throw new Error("This method is only supported by the Vertex AI.")}async tuneMldevInternal(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=ZL(e);return a=Et("tunedModels",u._url),c=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:a,queryParams:c,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(i=e.config)===null||i===void 0?void 0:i.abortSignal}).then(h=>h.json().then(d=>{const g=d;return g.sdkHttpResponse={headers:h.headers},g})),r.then(h=>dU(h))}}}class hU{async download(e,n){throw new Error("Download to file is not supported in the browser, please use a browser compliant download like an tag.")}}const pU=1024*1024*8,mU=3,gU=1e3,vU=2,ih="x-goog-upload-status";async function xU(t,e,n){var i;const r=await uE(t,e,n),a=await r?.json();if(((i=r?.headers)===null||i===void 0?void 0:i[ih])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return a.file}async function yU(t,e,n){var i;const r=await uE(t,e,n),a=await r?.json();if(((i=r?.headers)===null||i===void 0?void 0:i[ih])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");const c=yT(a),u=new Gg;return Object.assign(u,c),u}async function uE(t,e,n){var i,r;let a=0,c=0,u=new E0(new Response),h="upload";for(a=t.size;c=a&&(h+=", finalize");let v=0,y=gU;for(;vsetTimeout(e,t))}class SU{async upload(e,n,i){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await xU(e,n,i)}async uploadToFileSearchStore(e,n,i){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await yU(e,n,i)}async stat(e){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await _U(e)}}class TU{create(e,n,i){return new EU(e,n,i)}}class EU{constructor(e,n,i){this.url=e,this.headers=n,this.callbacks=i}connect(){this.ws=new WebSocket(this.url),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(e){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.send(e)}close(){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.close()}}const JS="x-goog-api-key";class wU{constructor(e){this.apiKey=e}async addAuthHeaders(e,n){if(e.get(JS)===null){if(this.apiKey.startsWith("auth_tokens/"))throw new Error("Ephemeral tokens are only supported by the live API.");if(!this.apiKey)throw new Error("API key is missing. Please provide a valid API key.");e.append(JS,this.apiKey)}}}const MU="gl-node/";class CU{get interactions(){if(this._interactions!==void 0)return this._interactions;console.warn("GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions.");const e=this.httpOptions;e?.extraBody&&console.warn("GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored.");const n=new no({baseURL:this.apiClient.getBaseUrl(),apiKey:this.apiKey,apiVersion:this.apiClient.getApiVersion(),clientAdapter:this.apiClient,defaultHeaders:this.apiClient.getDefaultHeaders(),timeout:e?.timeout});return this._interactions=n.interactions,this._interactions}constructor(e){var n;if(e.apiKey==null)throw new Error("An API Key must be set when running in a browser");if(e.project||e.location)throw new Error("Vertex AI project based authentication is not supported on browser runtimes. Please do not provide a project or location.");this.vertexai=(n=e.vertexai)!==null&&n!==void 0?n:!1,this.apiKey=e.apiKey;const i=bR(e.httpOptions,e.vertexai,void 0,void 0);i&&(e.httpOptions?e.httpOptions.baseUrl=i:e.httpOptions={baseUrl:i}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;const r=new wU(this.apiKey);this.apiClient=new _3({auth:r,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:MU+"web",uploader:new SU,downloader:new hU}),this.models=new O3(this.apiClient),this.live=new L3(this.apiClient,r,new TU),this.batches=new JN(this.apiClient),this.chats=new I2(this.models,this.apiClient),this.caches=new A2(this.apiClient),this.files=new V2(this.apiClient),this.operations=new B3(this.apiClient),this.authTokens=new nL(this.apiClient),this.tunings=new fU(this.apiClient),this.fileSearchStores=new uL(this.apiClient)}}const AU=t=>new CU({apiKey:t}),RU={type:ci.OBJECT,properties:{segments:{type:ci.ARRAY,items:{type:ci.OBJECT,properties:{startTime:{type:ci.STRING,description:"Absolute timestamp in MM:SS.mmm format (e.g. '01:05.300'). Cumulative from start."},endTime:{type:ci.STRING,description:"Absolute timestamp in MM:SS.mmm format."},text:{type:ci.STRING,description:"Transcribed text. Exact words spoken. No hallucinations. Must include every single word."}},required:["startTime","endTime","text"]}}},required:["segments"]},NU={type:ci.OBJECT,properties:{segments:{type:ci.ARRAY,items:{type:ci.OBJECT,properties:{startTime:{type:ci.STRING},endTime:{type:ci.STRING},text:{type:ci.STRING},words:{type:ci.ARRAY,items:{type:ci.OBJECT,properties:{text:{type:ci.STRING,description:"The single word, or character (for Chinese), or linguistic unit."},startTime:{type:ci.STRING,description:"Start time of the word"},endTime:{type:ci.STRING,description:"End time of the word"}},required:["text","startTime","endTime"]}}},required:["startTime","endTime","text","words"]}}},required:["segments"]};function tf(t){if(!t)return"00:00.000";let e=t.trim().replace(/[^\d:.]/g,""),n=0;if(!e.includes(":")&&/^[\d.]+$/.test(e))n=parseFloat(e);else{const c=e.split(":");if(c.length===3){const u=parseInt(c[0],10)||0,h=parseInt(c[1],10)||0,d=c[2].split("."),g=parseInt(d[0],10)||0;let v=0;d[1]&&(v=parseFloat("0."+d[1])),n=u*3600+h*60+g+v}else if(c.length===2){const u=parseInt(c[0],10)||0,h=c[1].split("."),d=parseInt(h[0],10)||0;let g=0;h[1]&&(g=parseFloat("0."+h[1])),n=u*60+d+g}}if(isNaN(n)||n<0)return"00:00.000";const i=Math.floor(n/60),r=Math.floor(n%60),a=Math.round(n%1*1e3);return`${String(i).padStart(2,"0")}:${String(r).padStart(2,"0")}.${String(a).padStart(3,"0")}`}function IU(t){const e=t.trim();try{const c=JSON.parse(e);if(c.segments&&Array.isArray(c.segments))return c;if(Array.isArray(c))return{segments:c}}catch{}const n=e.lastIndexOf("}");if(n!==-1){const c=["]}","}","]}"];for(const h of c)try{const d=e+h,g=JSON.parse(d);if(g.segments)return g}catch{}const u=e.substring(0,n+1)+"]}";try{const h=JSON.parse(u);if(h.segments&&Array.isArray(h.segments))return h}catch{}}if(e.includes('"words"'))throw new Error("Complex nested JSON (word-level) could not be parsed. PLease try again.");const i=[],r=/\{\s*"startTime"\s*:\s*"?([^",]+)"?\s*,\s*"endTime"\s*:\s*"?([^",]+)"?\s*,\s*"text"\s*:\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)')/g;let a;for(;(a=r.exec(e))!==null;){const c=a[3]!==void 0?a[3]:a[4];let u=c;try{u=JSON.parse(`"${c.replace(/"/g,'\\"')}"`)}catch{u=c.replace(/\\"/g,'"').replace(/\\'/g,"'").replace(/\\\\/g,"\\")}i.push({startTime:a[1],endTime:a[2],text:u})}if(i.length>0)return{segments:i};throw new Error("Response structure invalid and could not be repaired.")}async function DU(t,e,n,i,r,a="line"){try{const c=AU(i),u=t.includes("gemini-3"),h=` + TIMING RULES: + 1. FORMAT: strictly **MM:SS.mmm** (e.g., 01:23.450). + 2. CONTINUITY: Timestamps must be strictly chronological. + 3. ACCURACY: Sync text exactly to the audio. + 4. PRECISION: For fast speech/rap, ensure word-level timestamps are millisecond-accurate. + `;let d="";a==="word"?d=` + SEGMENTATION: HIERARCHICAL WORD-LEVEL (TTML/KARAOKE/Enhanced LRC) + --------------------------------------------------- + CRITICAL: You are generating data for rich TTML or Karaoke display. + + 1. STRUCTURE: Group words into short, natural lines/phrases (this is the parent object). + 2. LINE LENGTH: **CRITICAL** Keep lines SHORT (approx 3-8 words). Split long sentences into multiple lines. + - Example: "I will love you forever and ever" -> Line 1: "I will love you", Line 2: "forever and ever". + 3. REPEATED WORDS & STUTTERS: **EXTREMELY IMPORTANT** + - Treat every spoken utterance as a distinct word which must be timestamped. + - Example: "No no no wait" -> 4 distinct word objects. + - Example: "I I I didn't mean it" -> 3 distinct "I" objects followed by "didn't", "mean", "it". + - NEVER merge repeated words into a single event. + 4. DETAILS: Inside each line object, you MUST provide a "words" array. + 5. WORDS: The "words" array must contain EVERY single word from that line with its own precise start/end time. + 6. CJK HANDLING: For Chinese, Japanese, or Korean scripts, treat each character (or logical block of characters) as a separate "word" for the purposes of karaoke timing. + 7. FAST SPEECH / RAP / CONVERSATION HANDLING: + - Anticipate RAPID speech delivery (high words-per-minute). + - Ensure NO DRIFT: Align every word's start/end exactly to its pronunciation. + - For rapid-fire lyrics or conversation, word segments should be distinct and tightly packed. + `:d=` + SEGMENTATION: LINE-LEVEL (SUBTITLE/LRC MODE) + --------------------------------------------------- + CRITICAL: You are generating subtitles for a movie/music video. + + 1. PHRASES: Group words into complete sentences or musical phrases. + 2. CLARITY: Do not break a sentence in the middle unless there is a pause. + 3. REPETITIONS: Separate repetitive vocalizations (e.g. "Oh oh oh") from the main lyrics into their own lines. + 4. LENGTH: Keep segments between 2 and 6 seconds for readability. + 5. WORDS ARRAY: You may omit the "words" array in this mode to save tokens. + `;const g=` + You are an expert Audio Transcription AI specialized in generating precise timed lyrics and subtitled conversations. + + TASK: Transcribe the audio file into JSON segments. + MODE: ${a.toUpperCase()} LEVEL. + + ${h} + + ${d} + + LANGUAGE HANDLING (CRITICAL): + 1. RAPID CODE-SWITCHING: Audio often contains multiple languages mixed within the SAME sentence. + 2. MULTI-LINGUAL EQUALITY: The languages might NOT include English (e.g. Indonesian mixed with Japanese, Chinese mixed with Japanese). Treat all detected languages as equally probable. + 3. WORD-LEVEL DETECTION: Detect the language of every individual word. + 4. NATIVE SCRIPT STRICTNESS: Write EACH word in its native script. + - Example: "Aku cinta kamu" (Indonesian) -> Latin. + - Example: "愛してる" (Japanese) -> Kanji/Kana. + 5. MIXED SCRIPT PRESERVATION (IMPORTANT): + - If specific English/Latin words are spoken amidst Japanese/Chinese/etc., KEEP them in LATIN script. + - DO NOT transliterate English words into Katakana (e.g. if audio says "I love you", write "I love you", NOT "アイラブユー"). + - Maintain mixed text (Kanji/Kana + Latin) exactly as spoken. + 6. PROHIBITIONS: + - DO NOT translate. + - DO NOT romanize (unless explicitly spelled out). + - DO NOT force English if it is not spoken. + + GENERAL RULES: + - Verbatim: Transcribe exactly what is heard. Include fillers (um, ah) if sung. + - Completeness: Transcribe from 00:00 to the very end. Do not summarize. + - JSON Only: Output pure JSON. No markdown fences. + `,v={responseMimeType:"application/json",responseSchema:a==="word"?NU:RU,temperature:.1};u&&(v.thinkingConfig={thinkingBudget:1024});const y=new Promise((w,I)=>{r?.aborted&&I(new DOMException("Aborted","AbortError")),r?.addEventListener("abort",()=>I(new DOMException("Aborted","AbortError")))});let T=(await Promise.race([c.models.generateContent({model:t,contents:[{parts:[{inlineData:{data:e,mimeType:n}},{text:g}]}],config:v}),y])).text;if(!T)throw new Error("Empty response from model");return T=T.trim(),T.startsWith("```json")?T=T.replace(/^```json\s*/,"").replace(/\s*```$/,""):T.startsWith("```")&&(T=T.replace(/^```\s*/,"").replace(/\s*```$/,"")),(IU(T).segments||[]).map(w=>({startTime:tf(String(w.startTime)),endTime:tf(String(w.endTime)),text:String(w.text),words:w.words?w.words.map(I=>({text:String(I.text),startTime:tf(String(I.startTime)),endTime:tf(String(I.endTime))})):void 0}))}catch(c){throw c.name==="AbortError"?c:(console.error(`Error with ${t}:`,c),new Error(c.message||"Transcription failed"))}}const LU=({playlist:t,setPlaylist:e,currentTrackIndex:n,setCurrentTrackIndex:i,onPlayTrack:r,isPlaying:a,onTogglePlay:c,onSeek:u,onClearPlaylist:h,onRemoveTrack:d,currentTime:g,onClose:v})=>{const{confirm:y}=Ou(),S=Ae.useRef(null),T=Ae.useRef(new Map),A=z=>{const j=Math.floor(z/60).toString().padStart(2,"0"),B=(z%60).toFixed(2).padStart(5,"0");return`[${j}:${B}]`},[E,w]=Ae.useState(null),[I,L]=Ae.useState({key:null,direction:"asc"}),[D,W]=Ae.useState(new Set),[V,H]=Ae.useState(new Set),[Q,k]=Ae.useState(localStorage.getItem("gemini_api_key")||""),[P,J]=Ae.useState("gemini-2.5-flash"),[ve,fe]=Ae.useState("line"),[Ee,je]=Ae.useState(!1),X=Ae.useRef(null),[_e,ne]=Ae.useState(null);Ae.useEffect(()=>{Q&&localStorage.setItem("gemini_api_key",Q)},[Q]);const tt=n>=0?t[n]:null,Ce=tt?.parsedLyrics||[],$=Ae.useMemo(()=>tt?Ce.findIndex((z,j)=>{if(z.endTime!==void 0)return g>=z.time&&g=z.time&&(!B||g{if($!==-1){const z=document.getElementById(`lyric-active-${n}`);z&&z.scrollIntoView({behavior:"smooth",inline:"nearest",block:"nearest"})}},[$,n]);const ce=z=>{if(t.length===0)return;const j=n>=0?t[n]:null,B=[...t];let re="asc";if(z==="random"){L({key:"random",direction:"asc"});for(let Y=B.length-1;Y>0;Y--){const me=Math.floor(Math.random()*(Y+1));[B[Y],B[me]]=[B[me],B[Y]]}}else{I.key===z&&I.direction==="asc"&&(re="desc"),L({key:z,direction:re});const Y=re==="asc"?1:-1;z==="filename"?B.sort((me,ee)=>Y*me.audioFile.name.localeCompare(ee.audioFile.name)):z==="artist"?B.sort((me,ee)=>Y*(me.metadata.artist||"").localeCompare(ee.metadata.artist||"")):z==="title"?B.sort((me,ee)=>Y*(me.metadata.title||"").localeCompare(ee.metadata.title||"")):z==="album"&&B.sort((me,ee)=>Y*(me.metadata.album||"").localeCompare(ee.metadata.album||""))}if(e(B),j){const Y=B.findIndex(me=>me.id===j.id);Y!==-1&&i(Y)}},Xe=Ae.useCallback(z=>{E!==null&&z.key==="Delete"?(z.preventDefault(),z.stopPropagation(),d?d(E):e(j=>{const B=[...j];return B.splice(E,1),B}),E>=t.length-1&&w(t.length>1?t.length-2:null)):z.key==="ArrowDown"&&t.length>0?(z.preventDefault(),z.stopPropagation(),w(j=>j===null?0:Math.min(j+1,t.length-1))):z.key==="ArrowUp"&&t.length>0?(z.preventDefault(),z.stopPropagation(),w(j=>j===null?0:Math.max(j-1,0))):z.key==="Enter"&&E!==null?(z.preventDefault(),z.stopPropagation(),r(E)):z.key==="Escape"&&w(null)},[E,t.length,e,r]);Ae.useEffect(()=>{const z=S.current;if(z)return z.addEventListener("keydown",Xe),()=>z.removeEventListener("keydown",Xe)},[Xe]),Ae.useEffect(()=>{E!==null&&E>=t.length&&w(t.length>0?t.length-1:null)},[t.length,E]);const oe=async z=>{const j=new Map;z.forEach(me=>{const ee=me.name.split(".").pop()?.toLowerCase(),M=(me.webkitRelativePath||me.name).replace(/\.[^/.]+$/,"");j.has(M)||j.set(M,{});const K=j.get(M);["mp3","wav","ogg","flac","m4a","mp4","webm","ogg","mkv","mov","avi","m4v"].includes(ee||"")?K.audio=me:["lrc","srt","ttml","xml","json","vtt"].includes(ee||"")&&(K.lyric=me)});const B=[],re=async(me,ee)=>new Promise($e=>{if(me.type.startsWith("video/")){$e({title:ee,artist:"Unknown Artist",coverUrl:URL.createObjectURL(me),backgroundType:"video"});return}v0(()=>import("./jsmediatags.min-C5sB4g8Y.js").then(M=>M.j),[]).then(M=>{M.read(me,{onSuccess:K=>{const{title:de,artist:ue,album:Ue,picture:Je}=K.tags;let ht=null;if(Je){const{data:et,format:Te}=Je;let Ke="";for(let Be=0;Be{$e({title:ee,artist:"Unknown Artist",coverUrl:null})}})}).catch(()=>{$e({title:ee,artist:"Unknown Artist",coverUrl:null})})}),Y=async me=>{try{const ee=await me.text(),$e=me.name.split(".").pop()?.toLowerCase();if($e==="lrc")return ea(ee);if($e==="srt")return ta(ee);if($e==="ttml"||$e==="xml")return Pa(ee);if($e==="vtt")return Fa(ee);if($e==="json")return aR(ee)}catch(ee){console.error("Failed to parse lyrics",ee)}return[]};for(const[me,ee]of j.entries())if(ee.audio){const $e=await re(ee.audio,me),M=Math.random().toString(36).substr(2,9);let K=[];ee.lyric&&(K=await Y(ee.lyric)),B.push({id:M,audioFile:ee.audio,lyricFile:ee.lyric,parsedLyrics:K,metadata:$e,duration:0})}if(B.length>0){const me=[...t,...B];e(me),r(0,!1,me)}},Ie=async z=>{if(z.target.files&&z.target.files.length>0){const j=Array.from(z.target.files);await oe(j),z.target.value=""}},[nt,Se]=Ae.useState(!1),[N,ye]=Ae.useState(null),[xe,Oe]=Ae.useState(null),[at,Ze]=Ae.useState(null),U=(z,j)=>{ye(j),z.dataTransfer.effectAllowed="move"},Me=(z,j)=>{if(z.preventDefault(),z.stopPropagation(),N===null||N===j)return;const B=z.currentTarget.getBoundingClientRect(),re=B.top+B.height/2,Y=z.clientY{if(z.preventDefault(),z.stopPropagation(),N===null)return;const B=[...t],[re]=B.splice(N,1);let Y=j;at==="after"&&Y++,N=n?i(n-1):N>n&&Y<=n&&i(n+1),rt()},rt=()=>{ye(null),Oe(null),Ze(null)},We=z=>{z.preventDefault(),z.stopPropagation(),N===null&&Se(!0)},gt=z=>{z.preventDefault(),z.stopPropagation(),Se(!1)},qe=async z=>{if(z.preventDefault(),z.stopPropagation(),Se(!1),z.dataTransfer.files&&z.dataTransfer.files.length>0){const j=Array.from(z.dataTransfer.files);await oe(j)}},q=z=>{d?d(z):e(j=>{const B=[...j];return B.splice(z,1),B})},C=z=>new Promise((j,B)=>{const re=new FileReader;re.readAsDataURL(z),re.onload=()=>{const Y=re.result.split(",")[1];j(Y)},re.onerror=Y=>B(Y)}),te=async z=>{if(!navigator.onLine){alert("Unable to transcribe: No internet connection.");return}if(D.has(z.id)){const Y=T.current.get(z.id);Y&&Y.abort();return}const j=Q||"PLACEHOLDER_API_KEY";if(j.trim().length<39){alert(`Invalid API Key length (${j.trim().length}). It must be at least 39 characters.`),je(!0);return}W(Y=>new Set(Y).add(z.id));const B=new AbortController;T.current.set(z.id,B);const re=19.5*1024*1024;if(z.audioFile.size>re){alert(`File is too large (${(z.audioFile.size/1024/1024).toFixed(1)}MB). Gemini inline audio limit is ~20MB. + +Please convert to MP3/M4A or use a smaller file.`),W(Y=>{const me=new Set(Y);return me.delete(z.id),me}),T.current.delete(z.id);return}try{const Y=await C(z.audioFile);let me=z.duration||0;if(me===0)try{me=await new Promise(M=>{const K=new Audio(URL.createObjectURL(z.audioFile));K.onloadedmetadata=()=>{M(K.duration),URL.revokeObjectURL(K.src)},K.onerror=()=>{URL.revokeObjectURL(K.src),M(0)}})}catch(M){console.warn("Could not determine duration for AI validation",M)}let $e=(await DU(P,Y,z.audioFile.type,j,B.signal,ve)).map(M=>({time:bu(M.startTime),text:M.text,endTime:bu(M.endTime),words:M.words?M.words.map(K=>({text:K.text,startTime:bu(K.startTime),endTime:bu(K.endTime)})):void 0}));me>0&&($e=$e.filter(M=>M.time=0)),e(M=>M.map(K=>K.id===z.id?{...K,parsedLyrics:$e.sort((de,ue)=>de.time-ue.time),duration:me>0?me:K.duration}:K))}catch(Y){if(Y.name==="AbortError")console.log("Transcription aborted via user action.");else{console.error("Transcription failed:",Y);let me="Transcription failed. Please check your API key or file format.";if(!navigator.onLine)me="Connection lost. Please check your internet connection.";else if(Y.message){const ee=Y.message.toLowerCase();ee.includes("fetch")||ee.includes("network")||ee.includes("failed to connect")?me="Network error. Please check your connection.":(ee.includes("api key")||Y.message.includes("400")||Y.message.includes("401")||Y.message.includes("403"))&&(me="API Key Error: Please check if your key is valid and has credits.")}alert(me)}}finally{T.current.delete(z.id),W(Y=>{const me=new Set(Y);return me.delete(z.id),me})}},ae=async z=>{if(!navigator.onLine){alert("No internet connection.");return}H(j=>new Set(j).add(z.id));try{const j=await v0(()=>import("./index.min-BpoufnPa.js").then($e=>$e.i),[]);let B;const re=j.default||j;console.log("SyncLyrics Module:",j);const Y=["musixmatch","lrclib","netease"];if(typeof re=="function"&&re.prototype&&re.prototype.getLyrics){console.log("Detected Class usage");const $e=new re({sources:Y});B=M=>$e.getLyrics(M)}else if(re.getLyrics&&typeof re.getLyrics=="function")console.log("Detected Instance usage"),B=$e=>re.getLyrics($e);else if(re.SyncLyrics){console.log("Detected Mod.SyncLyrics export");const $e=re.SyncLyrics;if(typeof $e=="function"&&$e.prototype&&$e.prototype.getLyrics){console.log("Using SyncLyrics as Class");const M=new $e({sources:Y});B=K=>M.getLyrics(K)}else if(typeof $e=="function")console.log("Using SyncLyrics as Function"),B=$e;else throw new Error("Mod.SyncLyrics found but is not a function or class.")}else if(typeof re=="function")console.log("Detected Function usage"),B=re;else throw new Error(`Could not find suitable search function. Mod type: ${typeof re}. Keys: ${typeof re=="object"?JSON.stringify(Object.keys(re)):"N/A"}`);const me={track:z.metadata.title,artist:z.metadata.artist,album:z.metadata.album,sources:Y};console.log("Searching lyrics with options:",me);const ee=await B(me);if(ee&&typeof ee=="string")Re(ee,z);else{console.warn("npm package returned no result. Attempting fallback to LrcLib.net API directly...");let $e=z.duration||0;if($e===0)try{$e=await new Promise(ue=>{const Ue=new Audio(URL.createObjectURL(z.audioFile));Ue.onloadedmetadata=()=>{const Je=Ue.duration;URL.revokeObjectURL(Ue.src),ue(Je)},Ue.onerror=()=>ue(0)})}catch(ue){console.warn("Could not determine duration for search",ue)}const M=new URLSearchParams({artist_name:z.metadata.artist,track_name:z.metadata.title,album_name:z.metadata.album||"",duration:$e.toString()}),K=await fetch(`https://lrclib.net/api/get?${M.toString()}`);if(!K.ok){const ue=await fetch(`https://lrclib.net/api/search?q=${encodeURIComponent(z.metadata.title+" "+z.metadata.artist)}`);if(ue.ok){const Ue=await ue.json();if(Array.isArray(Ue)&&Ue.length>0){const Je=Ue.find(ht=>ht.syncedLyrics);if(Je){Re(Je.syncedLyrics,z);return}else if(Ue[0].plainLyrics){Re(Ue[0].plainLyrics,z);return}}}throw new Error("No lyrics found in fallback source.")}const de=await K.json();de.syncedLyrics?Re(de.syncedLyrics,z):de.plainLyrics?Re(de.plainLyrics,z):alert("No lyrics found.")}}catch(j){console.error("Search failed:",j),j.message?.includes("CORS")||j.message?.includes("etwork")||j.message?.includes("Failed to fetch")?alert(`Network Error: Could not connect to lyric services. +(Possible CORS blocking in browser).`):alert("Search failed: "+j.message)}finally{H(j=>{const B=new Set(j);return B.delete(z.id),B})}},Re=(z,j)=>{let B=ea(z);if(B.length===0&&(B=ta(z)),B.length>0){const re=B.some(Y=>Y.words&&Y.words.length>0);console.log(re?"Word-level (enhanced) lyrics found!":"Line-level lyrics found."),e(Y=>Y.map(me=>me.id===j.id?{...me,parsedLyrics:B,lyricFile:new File([z],`synched-lyrics${re?".lrc-enhanced":".lrc"}`,{type:"text/plain"})}:me))}else alert("Lyrics found but could not be parsed.")},De=(z,j,B)=>{const re=new Blob([z],{type:"application/octet-stream"}),Y=URL.createObjectURL(re),me=document.createElement("a");me.href=Y,me.download=j,document.body.appendChild(me),me.click(),document.body.removeChild(me),URL.revokeObjectURL(Y)},st=async(z,j)=>{const B=z.parsedLyrics||[];if(B.length===0)return;let re="";const Y=j==="lrc-enhanced"?"lrc":j,me=`${z.metadata.title||"lyrics"}.${Y}`;let ee=z.duration||0;if(ee===0)try{ee=await new Promise(M=>{const K=new Audio(URL.createObjectURL(z.audioFile));K.onloadedmetadata=()=>{M(K.duration),URL.revokeObjectURL(K.src)},K.onerror=()=>M(0)})}catch(M){console.warn("Could not determine duration for export check",M)}const $e=B.map(M=>({...M,words:M.words?M.words.filter(K=>K.text.trim().length>0).map(K=>({...K})):void 0}));for(let M=0;M<$e.length;M++){const K=$e[M],de=$e[M+1];if(K.endTime===void 0&&(de?K.endTime=de.time:K.endTime=ee>0?ee:K.time+5),K.words&&K.words.length>0)for(let ue=0;ueM.text).join(` +`);else if(j==="json")re=JSON.stringify($e,null,2);else if(j==="srt"){const M=K=>{const de=Math.floor(K/3600).toString().padStart(2,"0"),ue=Math.floor(K%3600/60).toString().padStart(2,"0"),Ue=Math.floor(K%60).toString().padStart(2,"0"),Je=Math.floor(K%1*1e3).toString().padStart(3,"0");return`${de}:${ue}:${Ue},${Je}`};re=$e.map((K,de)=>{const ue=M(K.time),Ue=K.endTime!==void 0&&K.endTime>K.time?K.endTime:K.time+2,Je=M(Ue);return`${de+1} +${ue} --> ${Je} +${K.text} +`}).join(` +`)}else if(j==="lrc"){const M=[],K=de=>{const ue=Math.floor(de/60).toString().padStart(2,"0"),Ue=(de%60).toFixed(2).padStart(5,"0");return`[${ue}:${Ue}]`};for(let de=0;de0)||ht<=ee)&&(Ue?Ue.time>ht&&M.push(`${K(ht)}`):M.push(`${K(ht)}`))}re=M.join(` +`)}else if(j==="lrc-enhanced"){const M=[],K=ue=>{const Ue=Math.floor(ue/60).toString().padStart(2,"0"),Je=(ue%60).toFixed(2).padStart(5,"0");return`[${Ue}:${Je}]`},de=ue=>{const Ue=Math.floor(ue/60).toString().padStart(2,"0"),Je=(ue%60).toFixed(2).padStart(5,"0");return`<${Ue}:${Je}>`};for(let ue=0;ue0?Ue.words.forEach((Be,_t)=>{const Jt=Be.text.replace(/[ \t]+/g," ").trim().replace(/\n/g,"\\n");ht+=`${de(Be.startTime)}${Jt}`,_t0)||Te<=ee)&&(Je?Je.time>Te&&M.push(`${K(Te)}`):M.push(`${K(Te)}`))}re=M.join(` +`)}else if(j==="ttml"){const M=K=>{const de=Math.floor(K/3600).toString().padStart(2,"0"),ue=Math.floor(K%3600/60).toString().padStart(2,"0"),Ue=Math.floor(K%60).toString().padStart(2,"0"),Je=Math.floor(K%1*1e3).toString().padStart(3,"0");return`${de}:${ue}:${Ue}.${Je}`};re=` + + +
`,$e.forEach(K=>{const de=M(K.time),ue=K.endTime!==void 0&&K.endTime>K.time?K.endTime:K.time+3,Ue=M(ue);re+=` +

`,K.words&&K.words.length>0?K.words.forEach(Je=>{if(!Je.text.trim())return;const ht=M(Je.startTime);let et=Je.endTime;(et===void 0||et<=Je.startTime)&&(et=Je.startTime+.5);const Te=M(et);let Ke=Je.text.replace(/[ \t]+/g," ").trim();Ke.endsWith("-")||(Ke+=" "),re+=` + ${Ke}`}):re+=` + ${K.text.replace(/-\s+/g,"-").replace(/[ \t]+/g," ").trim()}`,re+=` +

`}),re+=` +
+ +
`}else if(j==="vtt"){const M=K=>{const de=Math.floor(K/3600).toString().padStart(2,"0"),ue=Math.floor(K%3600/60).toString().padStart(2,"0"),Ue=Math.floor(K%60).toString().padStart(2,"0"),Je=Math.floor(K%1*1e3).toString().padStart(3,"0");return`${de}:${ue}:${Ue}.${Je}`};re=`WEBVTT + +`,$e.forEach(K=>{const de=M(K.time),ue=K.endTime!==void 0&&K.endTime>K.time?K.endTime:K.time+2,Ue=M(ue);let Je=K.text.trim();if(K.words&&K.words.length>0){const ht=K.words.map(et=>`<${M(et.startTime)}>${et.text.trim()}`).join(" ");ht.length>0&&(Je=ht)}re+=`${de} --> ${Ue} +${Je} + +`})}De(re,me)},it=async()=>{if(t.length===0)return;const z=async B=>new Promise(re=>{const Y=new Audio(URL.createObjectURL(B));Y.onloadedmetadata=()=>{re(Y.duration),URL.revokeObjectURL(Y.src)},Y.onerror=()=>{re(0),URL.revokeObjectURL(Y.src)}});let j=`#EXTM3U +`;for(const B of t){let re=B.duration||0;if(re===0)try{re=await z(B.audioFile)}catch(M){console.error("Failed to get duration for export",M)}const Y=Math.round(re),me=(B.metadata.artist||"Unknown Artist").replace(/[\r\n]/g,""),ee=(B.metadata.title||"Unknown Title").replace(/[\r\n]/g,"");j+=`#EXTINF:${Y},${me} - ${ee} +`;const $e=B.audioFile.webkitRelativePath||B.audioFile.name;j+=`${$e} +`}De(j,"playlist.m3u8")},F=async z=>{await y("Are you sure you want to clear the lyric timeline?","Clear Lyrics")&&e(j=>j.map(B=>B.id===z.id?{...B,parsedLyrics:[],lyricFile:void 0}:B))},le=async z=>{const j=z.target.files?.[0];if(!(!j||!_e)){try{const B=await j.text(),re=j.name.split(".").pop()?.toLowerCase();let Y=[];re==="lrc"?Y=ea(B):re==="srt"?Y=ta(B):re==="ttml"||re==="xml"?Y=Pa(B):re==="vtt"&&(Y=Fa(B)),Y.length>0?e(me=>me.map(ee=>ee.id===_e?{...ee,lyricFile:j,parsedLyrics:Y}:ee)):alert("Could not parse lyrics. Ensure file is .lrc, .srt, or .vtt")}catch(B){console.error("Failed to load lyrics",B),alert("Failed to load lyrics file.")}ne(null),z.target.value=""}};return p.jsxs("div",{className:`w-full max-w-[100vw] h-64 flex flex-col bg-zinc-900/95 backdrop-blur-md border-t border-white/10 z-20 shadow-xl overflow-hidden outline-none relative transition-colors ${nt?"bg-zinc-800 border-orange-500":""}`,onDragOver:We,onDragLeave:gt,onDrop:qe,children:[nt&&p.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-zinc-900/90 backdrop-blur-sm pointer-events-none",children:p.jsxs("div",{className:"flex flex-col items-center gap-4 text-orange-500 animate-pulse",children:[p.jsx(cs,{size:48}),p.jsx("h3",{className:"text-xl font-bold",children:"Drop Audio & Lyrics Here"}),p.jsx("p",{className:"text-sm text-zinc-400",children:"Supported formats: MP3, WAV, FLAC, Video (MP4/WebM), LRC, SRT, VTT"})]})}),p.jsx("input",{type:"file",name:"manual-lyric-upload",id:"manual-lyric-upload",ref:X,className:"hidden",accept:".lrc,.srt,.ttml,.xml,.vtt",onChange:le}),p.jsxs("div",{className:"p-2 border-b border-white/10 flex items-center justify-between bg-zinc-900 z-30 shrink-0 h-12",children:[p.jsxs("div",{className:"flex items-center gap-4 shrink-0",children:[p.jsxs("h2",{className:"text-sm font-bold flex items-center gap-2 text-zinc-300 whitespace-nowrap",children:[p.jsx(Jf,{size:16,className:"text-orange-400"}),"Playlist"]}),p.jsx("div",{className:"w-px h-4 bg-zinc-700"}),p.jsxs("div",{className:"flex bg-orange-600 rounded overflow-hidden",children:[p.jsxs("label",{className:"flex items-center gap-2 px-3 py-1 hover:bg-orange-500 cursor-pointer transition-colors text-white text-xs font-medium whitespace-nowrap border-r border-orange-700",children:[p.jsx(vT,{size:14})," Add Files",p.jsx("input",{type:"file",name:"add-files",id:"add-files",className:"hidden",accept:"audio/*,video/*,.lrc,.srt,.ttml,.xml,.vtt",multiple:!0,onChange:Ie})]}),p.jsxs("label",{className:"flex items-center gap-2 px-2 py-1 hover:bg-orange-500 cursor-pointer transition-colors text-white text-xs whitespace-nowrap",title:"Add Folder",children:[p.jsx(XC,{size:14}),p.jsx("input",{type:"file",name:"add-folder",id:"add-folder",className:"hidden",multiple:!0,webkitdirectory:"",onChange:Ie})]})]}),p.jsx("div",{className:"w-px h-4 bg-zinc-700"}),p.jsxs("div",{className:"flex items-center gap-1",children:[p.jsx("button",{onClick:()=>ce("filename"),className:`p-1 rounded transition-colors ${I.key==="filename"?"bg-zinc-700 text-white":"hover:bg-zinc-700 text-zinc-400 hover:text-white"}`,title:`Sort by Filename ${I.key==="filename"?I.direction==="asc"?"(A-Z)":"(Z-A)":""}`,children:p.jsx(Xf,{size:14,className:I.key==="filename"&&I.direction==="desc"?"rotate-180 transition-transform":"transition-transform"})}),p.jsx("button",{onClick:()=>ce("artist"),className:`p-1 rounded transition-colors ${I.key==="artist"?"bg-zinc-700 text-white":"hover:bg-zinc-700 text-zinc-400 hover:text-white"}`,title:`Sort by Artist ${I.key==="artist"?I.direction==="asc"?"(A-Z)":"(Z-A)":""}`,children:p.jsx(ZA,{size:14,className:I.key==="artist"&&I.direction==="desc"?"rotate-180 transition-transform":"transition-transform"})}),p.jsx("button",{onClick:()=>ce("title"),className:`p-1 rounded transition-colors ${I.key==="title"?"bg-zinc-700 text-white":"hover:bg-zinc-700 text-zinc-400 hover:text-white"}`,title:`Sort by Title ${I.key==="title"?I.direction==="asc"?"(A-Z)":"(Z-A)":""}`,children:p.jsx($l,{size:14,className:I.key==="title"&&I.direction==="desc"?"rotate-180 transition-transform":"transition-transform"})}),p.jsx("button",{onClick:()=>ce("album"),className:`p-1 rounded transition-colors ${I.key==="album"?"bg-zinc-700 text-white":"hover:bg-zinc-700 text-zinc-400 hover:text-white"}`,title:`Sort by Album ${I.key==="album"?I.direction==="asc"?"(A-Z)":"(Z-A)":""}`,children:p.jsx(PC,{size:14,className:I.key==="album"&&I.direction==="desc"?"rotate-180 transition-transform":"transition-transform"})}),p.jsx("button",{onClick:()=>ce("random"),className:`p-1 rounded transition-colors ${I.key==="random"?"bg-zinc-700 text-white":"hover:bg-zinc-700 text-zinc-400 hover:text-white"}`,title:"Shuffle",children:p.jsx(IA,{size:14})})]})]}),p.jsxs("div",{className:"flex gap-2 shrink-0 items-center",children:[p.jsxs("div",{className:"flex items-center gap-1 bg-zinc-800/50 rounded px-1",children:[p.jsx("button",{onClick:()=>je(!Ee),className:`p-1 rounded transition-colors ${Ee?"text-orange-400":"text-zinc-500 hover:text-zinc-300"}`,title:"Gemini API Key",children:p.jsx(iA,{size:14})}),Ee&&p.jsx("input",{type:Q?"password":"text",name:"api-key","aria-label":"Gemini API Key",value:Q,onChange:z=>k(z.target.value),placeholder:"Paste API Key here",className:"bg-transparent border-none outline-none text-xs text-zinc-200 w-32 placeholder:text-zinc-600",autoFocus:!0,autoComplete:"off",spellCheck:!1})]}),p.jsx("div",{className:"relative group",children:p.jsxs("select",{value:P,onChange:z=>J(z.target.value),className:"bg-zinc-800 text-[10px] text-zinc-300 border border-zinc-700 rounded px-1 py-1 focus:outline-none focus:border-orange-500 appearance-none cursor-pointer hover:bg-zinc-700",title:"Select Gemini Model",name:"gemini-model",id:"gemini-model","aria-label":"Gemini Model",children:[p.jsx("option",{value:"gemini-2.5-flash",children:"Gemini 2.5 Flash"}),p.jsx("option",{value:"gemini-3-flash-preview",children:"Gemini 3.0 Flash Preview"})]})}),p.jsx("div",{className:"relative group",children:p.jsxs("select",{value:ve,onChange:z=>fe(z.target.value),className:"bg-zinc-800 text-[10px] text-zinc-300 border border-zinc-700 rounded px-1 py-1 focus:outline-none focus:border-orange-500 appearance-none cursor-pointer hover:bg-zinc-700 w-[60px]",title:"Transcription Mode (Line or Word Level)",name:"transcription-mode",id:"transcription-mode","aria-label":"Transcription Mode",children:[p.jsx("option",{value:"line",children:"Line"}),p.jsx("option",{value:"word",children:"Word"})]})}),p.jsx("button",{onClick:it,className:"p-1 hover:bg-zinc-700 text-zinc-500 hover:text-white rounded transition-colors",title:"Export Playlist (.m3u8)",children:p.jsx(jC,{size:14})}),p.jsx("button",{onClick:async()=>{t.length>0&&await y("Clear entire playlist?","Clear Playlist")&&(h(),e([]))},className:"p-1 hover:bg-red-900/50 text-zinc-500 hover:text-red-200 rounded transition-colors",title:"Clear Playlist",children:p.jsx(Ql,{size:14})}),p.jsx("div",{className:"w-px h-4 bg-zinc-700 mx-1 self-center"}),p.jsx("button",{onClick:v,className:"p-1 hover:bg-zinc-700 text-zinc-400 hover:text-white rounded transition-colors",title:"Close Playlist",children:p.jsx(Wo,{size:14})})]})]}),p.jsx("div",{ref:S,tabIndex:0,onMouseEnter:()=>S.current?.focus(),className:"flex-1 overflow-y-auto overflow-x-hidden custom-scrollbar bg-zinc-950 p-1 space-y-1 focus:outline-none",children:t.length===0?p.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-zinc-500 text-xs",children:[p.jsx(Jf,{size:32,className:"mb-2 opacity-50"}),p.jsx("p",{children:"Playlist is empty"}),p.jsx("p",{className:"opacity-50",children:"Add audio files (matches .lrc/.srt/.ttml by name)"})]}):t.map((z,j)=>{const B=j===n,re=j===E,Y=z.parsedLyrics||[],me=B?Y.findIndex((ee,$e)=>{if(ee.endTime!==void 0)return g>=ee.time&&g=ee.time&&(!M||gU(ee,j),onDragEnd:rt,onDragOver:ee=>Me(ee,j),onDrop:ee=>Pe(ee,j),onClick:()=>w(j),className:`group relative flex gap-2 p-1.5 rounded-md border transition-all cursor-pointer + ${B?"bg-zinc-800 border-orange-500/50 shadow-lg":"bg-zinc-900/50 border-zinc-800 hover:bg-zinc-800 hover:border-zinc-700"} + ${re?"ring-2 ring-blue-500/70 ring-offset-1 ring-offset-zinc-950":""} + ${N===j?"opacity-50 border-dashed border-zinc-500":""} + ${xe===j&&at==="before"?"border-t-2 border-t-orange-500":""} + ${xe===j&&at==="after"?"border-b-2 border-b-orange-500":""} + `,children:[p.jsx("div",{className:"flex items-center justify-center px-1 cursor-grab active:cursor-grabbing text-zinc-600 hover:text-zinc-400 self-stretch",onMouseDown:ee=>ee.stopPropagation(),children:p.jsx(KC,{size:12})}),p.jsxs("div",{className:"flex flex-col gap-1 shrink-0 w-48",children:[p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx("button",{onClick:ee=>{ee.stopPropagation(),B?c():r(j)},className:`p-1.5 rounded-full transition-colors flex-shrink-0 + ${B?"bg-orange-500 text-white":"bg-zinc-800 text-zinc-400 hover:bg-zinc-700 hover:text-white"} + `,children:B?a?p.jsx(gT,{size:14}):p.jsx(y0,{size:14}):p.jsx(y0,{size:14})}),p.jsxs("div",{className:"flex-1 min-w-0",children:[p.jsx("div",{className:`text-xs font-medium truncate ${B?"text-orange-100":"text-zinc-300"}`,title:z.audioFile.name,children:z.metadata.title}),p.jsx("div",{className:"text-[9px] text-zinc-500 truncate",title:z.metadata.artist,children:z.metadata.artist})]})]}),p.jsxs("div",{className:"ml-8 flex items-center gap-2",children:[p.jsxs("span",{className:"text-[8px] text-zinc-600",children:[(z.audioFile.size/1024/1024).toFixed(1),"MB"]}),z.lyricFile?p.jsxs("div",{className:"flex items-center gap-0.5 text-[8px] px-1 rounded bg-blue-900/30 text-blue-300/80",title:z.lyricFile.name,children:[p.jsx(Xf,{size:7}),p.jsx("span",{className:"truncate max-w-[80px]",children:z.lyricFile.name})]}):p.jsx("span",{className:"text-[8px] text-zinc-700 italic",children:"No Lyrics"})]})]}),p.jsx("div",{className:"flex-1 min-w-0 h-12 bg-zinc-950/50 rounded border border-zinc-800/50 overflow-x-auto overflow-y-hidden custom-scrollbar",children:Y.length>0?p.jsx("div",{className:"relative h-full min-w-max flex items-center px-1",children:Y.map((ee,$e)=>{const M=$e===me;return p.jsxs("div",{id:M?`lyric-active-${j}`:void 0,className:`flex items-center gap-1 px-1.5 py-0.5 mx-0.5 rounded text-[9px] transition-colors whitespace-nowrap cursor-pointer + ${M?"bg-orange-600 text-white border border-orange-400 shadow-[0_0_10px_rgba(234,88,12,0.3)]":"bg-zinc-800/50 hover:bg-blue-900/50 border border-zinc-700/30 hover:border-blue-500/50 text-zinc-400"} + `,title:`${A(ee.time)} - ${ee.text}`,onClick:K=>{K.stopPropagation(),j!==n?(r(j),setTimeout(()=>u(ee.time),150)):u(ee.time)},children:[p.jsx("span",{className:`font-mono text-[8px] ${M?"text-orange-200":"text-zinc-500"}`,children:A(ee.time)}),p.jsx("span",{className:`truncate max-w-[120px] ${M?"text-white font-medium":"text-zinc-400"}`,children:ee.text||"♪"})]},$e)})}):p.jsx("div",{className:"h-full flex items-center justify-center text-zinc-700 text-[9px] italic",children:"No lyric timeline"})}),p.jsxs("div",{className:"flex items-center gap-1 shrink-0 px-1",children:[p.jsx("button",{onClick:ee=>{ee.stopPropagation(),ne(z.id),X.current&&(X.current.value=""),X.current?.click()},className:"p-1.5 rounded bg-blue-900/30 border border-blue-500/30 text-blue-400 hover:bg-blue-800/50 transition-colors",title:"Load Lyrics Manually",children:p.jsx(cs,{size:14})}),p.jsx("button",{onClick:ee=>{ee.stopPropagation(),ae(z)},className:`group/btn relative p-1.5 rounded bg-cyan-900/30 border border-cyan-500/30 text-cyan-400 hover:bg-cyan-800/50 transition-colors ${V.has(z.id)?"animate-pulse":""}`,title:"Search Lyrics (Online)",disabled:V.has(z.id),children:V.has(z.id)?p.jsx(pb,{size:14,className:"animate-spin"}):p.jsx(AA,{size:14})}),p.jsx("button",{onClick:ee=>{ee.stopPropagation(),te(z)},className:`group/btn relative p-1.5 rounded bg-purple-900/30 border border-purple-500/30 text-purple-400 hover:bg-purple-800/50 transition-colors ${D.has(z.id)?"text-red-400 border-red-500/50 hover:bg-red-900/30":""}`,title:D.has(z.id)?"Stop Transcription":"AI Sync Transcribe",children:D.has(z.id)?p.jsxs(p.Fragment,{children:[p.jsx(pb,{size:14,className:"animate-spin group-hover/btn:hidden"}),p.jsx(b0,{size:14,className:"hidden group-hover/btn:block fill-current"})]}):p.jsx(_0,{size:14})}),Y.length>0&&p.jsxs("div",{className:"flex items-center gap-0.5 bg-zinc-800/50 rounded p-0.5 border border-zinc-700/50",children:[p.jsx("button",{onClick:ee=>{ee.stopPropagation(),st(z,"txt")},className:"p-1 hover:bg-white/10 rounded text-[8px] text-zinc-400 font-bold",title:"Download TXT",children:"TXT"}),p.jsx("button",{onClick:ee=>{ee.stopPropagation(),st(z,"lrc")},className:"p-1 hover:bg-white/10 rounded text-[8px] text-zinc-400 font-bold",title:"Download LRC",children:"LRC"}),p.jsx("button",{onClick:ee=>{ee.stopPropagation(),st(z,"lrc-enhanced")},className:"p-1 hover:bg-white/10 rounded text-[8px] text-zinc-400 font-bold",title:"Download Enhanced LRC (Word Level)",children:"eLRC"}),p.jsx("button",{onClick:ee=>{ee.stopPropagation(),st(z,"srt")},className:"p-1 hover:bg-white/10 rounded text-[8px] text-zinc-400 font-bold",title:"Download SRT",children:"SRT"}),p.jsx("button",{onClick:ee=>{ee.stopPropagation(),st(z,"vtt")},className:"p-1 hover:bg-white/10 rounded text-[8px] text-zinc-400 font-bold",title:"Download VTT",children:"VTT"}),p.jsx("button",{onClick:ee=>{ee.stopPropagation(),st(z,"ttml")},className:"p-1 hover:bg-white/10 rounded text-[8px] text-zinc-400 font-bold",title:"Download TTML",children:"TTML"}),p.jsx("button",{onClick:ee=>{ee.stopPropagation(),st(z,"json")},className:"p-1 hover:bg-white/10 rounded text-[8px] text-zinc-400 font-bold",title:"Download JSON",children:"JSON"}),p.jsx("div",{className:"w-px h-3 bg-zinc-700 mx-0.5"}),p.jsx("button",{onClick:ee=>{ee.stopPropagation(),F(z)},className:"p-1 hover:bg-red-900/50 rounded text-[8px] text-red-500 hover:text-red-300 font-bold",title:"Clear Lyrics",children:"CLR"})]})]}),p.jsx("button",{onClick:ee=>{ee.stopPropagation(),q(j)},className:"p-1 text-zinc-600 hover:text-red-400 hover:bg-red-900/20 rounded self-start",title:"Remove Track",children:p.jsx(Ql,{size:12})})]},z.id)})})]})},Kg=[{label:"Modern & Clean",options:[{label:"System Sans Serif",value:"ui-sans-serif, system-ui, sans-serif"},{label:"Inter",value:"'Inter', sans-serif"},{label:"Roboto",value:"'Roboto', sans-serif"},{label:"Poppins",value:"'Poppins', sans-serif"},{label:"Montserrat",value:"'Montserrat', sans-serif"},{label:"Open Sans",value:"'Open Sans', sans-serif"},{label:"Lato",value:"'Lato', sans-serif"},{label:"Raleway",value:"'Raleway', sans-serif"},{label:"Outfit",value:"'Outfit', sans-serif"},{label:"Nunito",value:"'Nunito', sans-serif"}]},{label:"Classic & Elegant",options:[{label:"System Serif",value:"ui-serif, Georgia, serif"},{label:"Playfair Display",value:"'Playfair Display', serif"},{label:"Merriweather",value:"'Merriweather', serif"},{label:"Lora",value:"'Lora', serif"},{label:"Crimson Text",value:"'Crimson Text', serif"},{label:"EB Garamond",value:"'EB Garamond', serif"},{label:"Libre Baskerville",value:"'Libre Baskerville', serif"}]},{label:"Display & Bold",options:[{label:"Bebas Neue",value:"'Bebas Neue', sans-serif"},{label:"Anton",value:"'Anton', sans-serif"},{label:"Oswald",value:"'Oswald', sans-serif"},{label:"Archivo Black",value:"'Archivo Black', sans-serif"},{label:"Staatliches",value:"'Staatliches', cursive"},{label:"Righteous",value:"'Righteous', cursive"},{label:"Bungee",value:"'Bungee', cursive"}]},{label:"Handwritten & Script",options:[{label:"Dancing Script",value:"'Dancing Script', cursive"},{label:"Pacifico",value:"'Pacifico', cursive"},{label:"Great Vibes",value:"'Great Vibes', cursive"},{label:"Satisfy",value:"'Satisfy', cursive"},{label:"Shadows Into Light",value:"'Shadows Into Light', cursive"},{label:"Caveat",value:"'Caveat', cursive"},{label:"Indie Flower",value:"'Indie Flower', cursive"},{label:"Kalam",value:"'Kalam', cursive"},{label:"Sacramento",value:"'Sacramento', cursive"}]},{label:"Fun & Playful",options:[{label:"Fredoka One",value:"'Fredoka One', cursive"},{label:"Bangers",value:"'Bangers', cursive"},{label:"Luckiest Guy",value:"'Luckiest Guy', cursive"},{label:"Chewy",value:"'Chewy', cursive"},{label:"Bubblegum Sans",value:"'Bubblegum Sans', cursive"},{label:"Cherry Cream Soda",value:"'Cherry Cream Soda', cursive"},{label:"Patrick Hand",value:"'Patrick Hand', cursive"}]},{label:"Tech & Futuristic",options:[{label:"System Monospace",value:"ui-monospace, monospace"},{label:"Orbitron",value:"'Orbitron', sans-serif"},{label:"Audiowide",value:"'Audiowide', cursive"},{label:"Share Tech Mono",value:"'Share Tech Mono', monospace"},{label:"VT323",value:"'VT323', monospace"},{label:"Press Start 2P",value:"'Press Start 2P', cursive"},{label:"Fira Code",value:"'Fira Code', monospace"},{label:"JetBrains Mono",value:"'JetBrains Mono', monospace"}]},{label:"Decorative & Themed",options:[{label:"Metal Mania",value:"'Metal Mania', cursive"},{label:"UnifrakturMaguntia",value:"'UnifrakturMaguntia', cursive"},{label:"Cinzel",value:"'Cinzel', serif"},{label:"Creepster",value:"'Creepster', cursive"},{label:"Pirata One",value:"'Pirata One', cursive"},{label:"Rubik Moonrocks",value:"'Rubik Moonrocks', cursive"},{label:"Nabla",value:"'Nabla', cursive"}]},{label:"International & Multilingual",options:[{label:"Noto Sans SC (Chinese)",value:"'Noto Sans SC', sans-serif"},{label:"Noto Sans JP (Japanese)",value:"'Noto Sans JP', sans-serif"},{label:"Noto Sans KR (Korean)",value:"'Noto Sans KR', sans-serif"},{label:"Noto Sans Arabic (Arabic)",value:"'Noto Sans Arabic', sans-serif"},{label:"Noto Sans Devanagari (Hindi)",value:"'Noto Sans Devanagari', sans-serif"}]}],dE=["Metal Mania","Bebas Neue","Anton","Staatliches","Righteous","Bungee","Dancing Script","Pacifico","Great Vibes","Satisfy","Shadows Into Light","Caveat","Indie Flower","Kalam","Sacramento","Fredoka One","Bangers","Luckiest Guy","Chewy","Bubblegum Sans","Cherry Cream Soda","Patrick Hand","Orbitron","Audiowide","Share Tech Mono","VT323","Press Start 2P","Fira Code","JetBrains Mono","UnifrakturMaguntia","Creepster","Pirata One","Rubik Moonrocks","Nabla"],UU=()=>{if(!document.getElementById("google-fonts-preconnect")){const t=document.createElement("link");t.id="google-fonts-preconnect",t.rel="preconnect",t.href="https://fonts.googleapis.com",t.crossOrigin="anonymous",document.head.appendChild(t);const e=document.createElement("link");e.rel="preconnect",e.href="https://fonts.gstatic.com",e.crossOrigin="anonymous",document.head.appendChild(e)}Kg.forEach((t,e)=>{const n=new Set;if(t.options.forEach(h=>{const d=h.value.split(",")[0].trim().replace(/['"]/g,"");!d.startsWith("ui-")&&d!=="system-ui"&&d!=="sans-serif"&&d!=="serif"&&d!=="monospace"&&n.add(d)}),n.size===0)return;const a=`https://fonts.googleapis.com/css2?${Array.from(n).map(h=>{const d=h.replace(/['"]/g,"");return dE.includes(d)?`family=${h.replace(/ /g,"+")}`:`family=${h.replace(/ /g,"+")}:wght@400;700`}).join("&")}&display=swap`,c=`google-fonts-group-${e}`;if(document.getElementById(c))return;const u=document.createElement("link");u.id=c,u.rel="stylesheet",u.crossOrigin="anonymous",u.href=a,document.head.appendChild(u)})},kU=t=>{const e=`google-font-${t.replace(/\s+/g,"-").toLowerCase()}`;if(document.getElementById(e))return;const n=t.replace(/['"]/g,"");let i=`family=${t.replace(/\s+/g,"+")}:wght@400;700`;dE.includes(n)&&(i=`family=${t.replace(/\s+/g,"+")}`);const r=document.createElement("link");r.id=e,r.rel="stylesheet",r.crossOrigin="anonymous",r.href=`https://fonts.googleapis.com/css2?${i}&display=swap`,document.head.appendChild(r)},Zg=[{label:"Basic",options:[{label:"Default",value:"default"},{label:"Custom",value:"custom"}]},{label:"Typography",options:[{label:"Large Text",value:"large"},{label:"Large Uppercase",value:"large_upper"},{label:"Big Center",value:"big_center"},{label:"Classic Serif",value:"classic"},{label:"Monospace",value:"monospace"}]},{label:"Thematic",options:[{label:"Heavy Metal",value:"metal"},{label:"Kids Fun",value:"kids"},{label:"Melancholy",value:"sad"},{label:"Romantic",value:"romantic"},{label:"Tech / Sci-Fi",value:"tech"},{label:"Gothic",value:"gothic"}]},{label:"Layout & Minimal",options:[{label:"Slideshow (Small)",value:"slideshow"},{label:"Subtitle Mode",value:"subtitle"},{label:"Video Only",value:"just_video"}]},{label:"Debug",options:[{label:"Testing",value:"testing"},{label:"Testing Up",value:"testing_up"}]}],oh={default:{fontSizeScale:1,fontFamily:"ui-sans-serif, system-ui, sans-serif",textCase:"none",textAlign:"center",fontColor:"#ffffff"},large:{fontSizeScale:1.8,fontFamily:"ui-sans-serif, system-ui, sans-serif",fontColor:"#ffffff",fontWeight:"bold"},classic:{fontSizeScale:1,fontFamily:'ui-serif, Georgia, Cambria, "Times New Roman", Times, serif',fontColor:"#fef3c7",fontStyle:"italic",fontWeight:"bold"},large_upper:{fontSizeScale:1.6,fontFamily:"ui-sans-serif, system-ui, sans-serif",textCase:"upper",fontColor:"#ffffff",fontWeight:"bold"},monospace:{fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',fontColor:"#ffffff",fontWeight:"bold"},big_center:{fontSizeScale:1.6,fontFamily:"ui-sans-serif, system-ui, sans-serif",textCase:"upper",textAlign:"center",contentPosition:"center",fontColor:"#ffffff",fontWeight:"bold"},metal:{fontFamily:'"Metal Mania", cursive',fontSizeScale:1.6,textCase:"upper",fontColor:"#ffffff"},kids:{fontFamily:'"Fredoka One", cursive',fontSizeScale:1.6,textCase:"upper",fontColor:"#ffffff"},sad:{fontFamily:'"Shadows Into Light", cursive',fontSizeScale:1.2,fontColor:"#e4e4e7"},romantic:{fontFamily:'"Dancing Script", cursive',fontSizeScale:1.2,fontColor:"#fce7f3",fontStyle:"italic"},tech:{fontFamily:'"Orbitron", sans-serif',fontSizeScale:1.6,textCase:"upper",fontColor:"#ecfeff",fontWeight:"bold"},gothic:{fontFamily:'"UnifrakturMaguntia", cursive',fontSizeScale:1.2,fontColor:"#d4d4d8"},slideshow:{fontSizeScale:.6,fontColor:"#ffffff"},just_video:{},subtitle:{fontSizeScale:.6,contentPosition:"bottom",fontColor:"#ffffff"},testing:{fontSizeScale:1.6},testing_up:{fontSizeScale:1.6,textCase:"upper"}},Um=Zg.flatMap(t=>t.options.map(e=>e.value)),km=({onApply:t,placeholder:e="Google Font Name"})=>{const{toast:n}=Ou(),[i,r]=Ae.useState(""),a=()=>{if(!i.trim())return;const c=i.trim().replace(/['"]/g,"").replace(/\s+/g," ");kU(c),t(c),n.success(`Loaded & Applied: ${c}`),r("")};return p.jsxs("div",{className:"flex gap-2 mt-2 items-center",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase whitespace-nowrap",children:"Google Font:"}),p.jsx("input",{type:"text",name:"google-font-name","aria-label":"Google Font Name",value:i,onChange:c=>r(c.target.value),placeholder:e,className:"flex-1 min-w-0 bg-zinc-900 border border-white/10 rounded-md px-2 py-1 text-[10px] text-zinc-200 focus:outline-none focus:ring-1 focus:ring-purple-500",onKeyDown:c=>{c.key==="Enter"&&a()}}),p.jsx("button",{onClick:a,disabled:!i.trim(),className:"bg-zinc-700 hover:bg-zinc-600 text-white text-[10px] px-2 py-1 rounded-md font-medium disabled:opacity-50 transition-colors",title:"Load and apply",children:"Load"})]})},KS={backgroundSource:"custom",backgroundColor:"#581c87",backgroundGradient:"linear-gradient(to bottom right, #312e81, #581c87, #000000)",renderMode:"current",textAlign:"center",contentPosition:"center",fontFamily:"ui-sans-serif, system-ui, sans-serif",fontSizeScale:1,lyricLineHeight:1.3,fontColor:"#ffffff",textEffect:"preset",textAnimation:"none",transitionEffect:"none",lyricDisplayMode:"all",fontWeight:"bold",fontStyle:"normal",lyricStyleTarget:"active-only",textDecoration:"none",showTitle:!0,showArtist:!0,showCover:!0,showIntro:!0,showLyrics:!0,infoPosition:"top-left",infoStyle:"classic",infoMarginScale:1,infoSizeScale:1,infoFontFamily:"ui-sans-serif, system-ui, sans-serif",infoFontWeight:"bold",infoFontStyle:"normal",infoFontColor:"#ffffff",backgroundBlurStrength:0,introMode:"auto",introText:"",textCase:"none",highlightEffect:"karaoke",highlightColor:"#fb923c",highlightBackground:"#fb923c",showChannelInfo:!1,channelInfoText:"Music Channel",channelInfoPosition:"bottom-right",channelInfoStyle:"classic",channelInfoSizeScale:1,channelInfoMarginScale:1,channelInfoFontFamily:"ui-sans-serif, system-ui, sans-serif",channelInfoFontWeight:"bold",channelInfoFontStyle:"normal",channelInfoFontColor:"#ffffff",channelInfoImage:void 0,useCustomHighlightColors:!1,backgroundImage:void 0,visualTransitionType:"none",visualTransitionDuration:1,enableGradientOverlay:!1,useRealColorMedia:!1,marginTopScale:1,marginBottomScale:1,showVisualization:!1,visualizationType:"bars",visualizationColorMode:"gradient",visualizationColor1:"#a855f7",visualizationColor2:"#6366f1",visualizationOpacity:.6,visualizationPosition:"bottom",visualizationSensitivity:1.5,visualizationBarCount:48},ZS=[{label:"Basic",options:[{label:"Use Preset Default",value:"preset"},{label:"None",value:"none"},{label:"Drop Shadow",value:"shadow"},{label:"Outline",value:"outline"}]},{label:"Glow Effects",options:[{label:"Soft Glow",value:"glow"},{label:"Neon Glow",value:"neon"},{label:"Multi-Color Neon",value:"neon-multi"}]},{label:"3D & Pop",options:[{label:"3D Pop",value:"3d"},{label:"Embossed",value:"emboss"},{label:"Chrome Metallic",value:"chrome"},{label:"Gold Foil",value:"gold"}]},{label:"Artistic",options:[{label:"Glassmorphism",value:"glass"},{label:"Gradient Fill",value:"gradient"},{label:"Fire",value:"fire"},{label:"Frozen Ice",value:"frozen"},{label:"Rainbow",value:"rainbow"},{label:"Reflection",value:"mirror"}]},{label:"Retro & Stylized",options:[{label:"VHS Glitch",value:"vhs"},{label:"Retro 80s",value:"retro"},{label:"Cyberpunk",value:"cyberpunk"},{label:"Hologram",value:"hologram"},{label:"Comic Book",value:"comic"},{label:"Digital Glitch",value:"glitch-text"}]}],QS=[{label:"Static",options:[{label:"None (Static)",value:"none"}]},{label:"Subtle",options:[{label:"Pulse",value:"pulse"},{label:"Breathe",value:"breathe"},{label:"Float",value:"float"},{label:"Sway",value:"sway"},{label:"Flicker",value:"flicker"}]},{label:"Energetic",options:[{label:"Bounce",value:"bounce"},{label:"Shake",value:"shake"},{label:"Wave",value:"wave"},{label:"Wobble",value:"wobble"},{label:"Jello",value:"jello"},{label:"Rubber Band",value:"rubberband"}]},{label:"Attention",options:[{label:"Heartbeat",value:"heartbeat"},{label:"Flash",value:"flash"},{label:"Tada!",value:"tada"},{label:"Swing",value:"swing"}]},{label:"Rotation",options:[{label:"Gentle Rotate",value:"rotate"},{label:"Spin",value:"spin"}]},{label:"Special",options:[{label:"Glitch",value:"glitch"},{label:"Typewriter",value:"typewriter"}]}],e1=[{label:"Basic",options:[{label:"Instant",value:"none"},{label:"Smooth Fade",value:"fade"}]},{label:"Slide & Move",options:[{label:"Slide In",value:"slide"},{label:"Float Up",value:"float"},{label:"Drop In",value:"drop"},{label:"Lightspeed",value:"lightspeed"},{label:"Roll In",value:"roll"}]},{label:"Scale & Transform",options:[{label:"Zoom In",value:"zoom"},{label:"Bounce In",value:"bounce"},{label:"Elastic Pop",value:"elastic"},{label:"Scale + Rotate",value:"scale-rotate"}]},{label:"Rotation",options:[{label:"Flip In",value:"flip"},{label:"Rotate In",value:"rotate-in"},{label:"Spiral In",value:"spiral"},{label:"Swing In",value:"swing"}]},{label:"Special",options:[{label:"Motion Blur",value:"blur"},{label:"Shatter In",value:"shatter"},{label:"Typewriter",value:"typewriter"}]}],t1=[{label:"Visual Transition",options:[{label:"None (Cut)",value:"none"},{label:"Crossfade",value:"crossfade"},{label:"Fade Through Black",value:"fade-to-black"}]}],z0=[{label:"Basic",options:[{label:"None",value:"none"},{label:"Simple Color",value:"color"},{label:"Scale Up",value:"scale"},{label:"Intense Glow",value:"glow"},{label:"Background Box",value:"background"}]},{label:"Karaoke Standard",options:[{label:"Default (Line/Fill)",value:"karaoke"},{label:"Smooth Transition",value:"karaoke-smooth"},{label:"Smooth Transition White",value:"karaoke-smooth-white"},{label:"Smooth Transition Plus",value:"karaoke-smooth-plus"},{label:"Fill Background",value:"karaoke-fill"},{label:"Outline Only",value:"karaoke-outline"},{label:"Underline",value:"karaoke-underline"},{label:"Shadow",value:"karaoke-shadow"},{label:"Gradient",value:"karaoke-gradient"}]},{label:"Animations",options:[{label:"Bounce",value:"karaoke-bounce"},{label:"Wave",value:"karaoke-wave"},{label:"Zoom In",value:"karaoke-scale"}]},{label:"Neon & Glow",options:[{label:"Neon White",value:"karaoke-neon"},{label:"Glow Blue",value:"karaoke-glow-blue"},{label:"Glow Pink",value:"karaoke-glow-pink"},{label:"Multi-Color Neon",value:"karaoke-neon-multi"},{label:"Soft Glow",value:"karaoke-soft-glow"}]},{label:"3D & Artistic",options:[{label:"3D Pop",value:"karaoke-3d"},{label:"Embossed",value:"karaoke-emboss"},{label:"Chrome Metallic",value:"karaoke-chrome"},{label:"Gold Foil",value:"karaoke-gold"},{label:"Glassmorphism",value:"karaoke-glass"},{label:"Gradient Fill",value:"karaoke-gradient-fill"},{label:"Fire",value:"karaoke-fire"},{label:"Frozen Ice",value:"karaoke-frozen"},{label:"Rainbow",value:"karaoke-rainbow"},{label:"Reflection",value:"karaoke-mirror"}]},{label:"Retro & Stylized",options:[{label:"VHS Glitch",value:"karaoke-vhs"},{label:"Retro 80s",value:"karaoke-retro"},{label:"Cyberpunk",value:"karaoke-cyberpunk"},{label:"Hologram",value:"karaoke-hologram"},{label:"Comic Book",value:"karaoke-comic"},{label:"Digital Glitch",value:"karaoke-glitch-text"}]},{label:"Detailed Animations",options:[{label:"Pulse",value:"karaoke-pulse"},{label:"Breathe",value:"karaoke-breathe"},{label:"Float",value:"karaoke-float"},{label:"Sway",value:"karaoke-sway"},{label:"Flicker",value:"karaoke-flicker"},{label:"Shake",value:"karaoke-shake"},{label:"Wobble",value:"karaoke-wobble"},{label:"Jello",value:"karaoke-jello"},{label:"Rubber Band",value:"karaoke-rubberband"},{label:"Heartbeat",value:"karaoke-heartbeat"},{label:"Flash",value:"karaoke-flash"},{label:"Tada!",value:"karaoke-tada"},{label:"Swing",value:"karaoke-swing"},{label:"Gentle Rotate",value:"karaoke-rotate"},{label:"Spin",value:"karaoke-spin"},{label:"Glitch Anim",value:"karaoke-glitch"},{label:"Typewriter",value:"karaoke-typewriter"}]},{label:"Motion & Transitions",options:[{label:"Smooth Fade",value:"karaoke-fade"},{label:"Slide In",value:"karaoke-slide"},{label:"Drop In",value:"karaoke-drop"},{label:"Lightspeed",value:"karaoke-lightspeed"},{label:"Roll In",value:"karaoke-roll"},{label:"Zoom In",value:"karaoke-zoom"},{label:"Elastic Pop",value:"karaoke-elastic"},{label:"Scale + Rotate",value:"karaoke-scale-rotate"},{label:"Flip In",value:"karaoke-flip"},{label:"Rotate In",value:"karaoke-rotate-in"},{label:"Spiral In",value:"karaoke-spiral"},{label:"Motion Blur",value:"karaoke-blur"},{label:"Shatter",value:"karaoke-shatter"}]},{label:"Solid Colors",options:[{label:"Blue",value:"karaoke-blue"},{label:"Purple",value:"karaoke-purple"},{label:"Green",value:"karaoke-green"},{label:"Pink",value:"karaoke-pink"},{label:"Cyan",value:"karaoke-cyan"}]},{label:"Shapes",options:[{label:"Pill Shape",value:"karaoke-pill"},{label:"Square Box",value:"karaoke-box"},{label:"Rounded Box",value:"karaoke-rounded"}]}],Uf=t=>{let e="",n="";return t.includes("blue")||t.includes("cyan")?(e=t.includes("cyan")?"#06b6d4":"#3b82f6",n=e):t.includes("purple")?(e="#a855f7",n=e):t.includes("green")?(e="#22c55e",n=e):t.includes("pink")?(e="#ec4899",n=e):(t==="karaoke-pill"||t==="karaoke-box"||t==="karaoke-rounded")&&(e="#fb923c",n="#fb923c"),e?{color:e,bg:n}:null},n1=[{label:"Source",options:[{label:"From Timeline",value:"timeline"},{label:"Metadata / Default",value:"custom"},{label:"Smart Gradient",value:"smart-gradient"},{label:"Gradient (Manual)",value:"gradient"},{label:"Solid Color",value:"color"},{label:"Custom Image",value:"image"},{label:"Custom Video (Loops)",value:"video"},{label:"Three.js 3D Background",value:"threejs"}]}],zU=[{label:"Classic",options:[{label:"✦ Stars",value:"stars"},{label:"◇ Rotating Cubes",value:"cubes"},{label:"≈ Wireframe Waves",value:"waves"},{label:"● Particle Flow",value:"particles"}]},{label:"Cosmic",options:[{label:"🌀 Spiral Galaxy",value:"galaxy"},{label:"☁ Cosmic Nebula",value:"nebula"},{label:"🌌 Aurora Borealis",value:"aurora"},{label:"🚀 Warp Speed",value:"warp"},{label:"🌪 Particle Vortex",value:"vortex"}]},{label:"Sci-Fi",options:[{label:"🧬 DNA Helix",value:"dna"},{label:"▓ Matrix Rain",value:"matrix"},{label:"◎ Saturn Rings",value:"rings"},{label:"🚇 Infinity Tunnel",value:"tunnel"},{label:"🌐 Cyber Grid",value:"cybergrid"},{label:"💎 Geometric Crystals",value:"crystals"}]}],P0=[{label:"Display Modes",options:[{label:"Show All (Default)",value:"all"},{label:"Prev & Next (Centered)",value:"previous-next"},{label:"Current & Next",value:"next-only"},{label:"Current Line Only",value:"active-only"}]}],fE=["none","upper","lower","title","sentence","invert"],i1=[{label:"Layout Styles",options:[{label:"Classic (Detailed)",value:"classic"},{label:"Modern + Cover",value:"modern_art"},{label:"Circle Cover",value:"circle_art"},{label:"Modern (Text Only)",value:"modern"},{label:"Boxed Cover",value:"box"},{label:"Minimal (Text Only)",value:"minimal"}]}],o1=[{label:"Layout Styles",options:[{label:"Classic (Row)",value:"classic"},{label:"Modern (Col)",value:"modern"},{label:"Minimal (Text Only)",value:"minimal"},{label:"Circle (Avatar)",value:"circle"},{label:"Logo Only",value:"logo"},{label:"Boxed",value:"box"}]}],PU=[{label:"Frame Rate",options:[{label:"24 FPS (Cinematic)",value:"24"},{label:"30 FPS (Standard)",value:"30"},{label:"60 FPS (Smooth)",value:"60"}]}],No=({value:t,onChange:e,groups:n})=>{const[i,r]=Ae.useState(!1),[a,c]=Ae.useState(t);Ae.useEffect(()=>{i||c(t)},[t,i]);const u=v=>{for(const y of n){const S=y.options.find(T=>T.value===v);if(S)return S.label}return v},h=v=>{e(v)},d=()=>{i&&e(a),r(!1)},g=v=>{e(v),c(v),r(!1)};return p.jsxs("div",{className:"space-y-2 relative",onMouseLeave:d,children:[p.jsxs("button",{onClick:()=>r(!i),className:"w-full bg-zinc-800 border border-white/10 rounded-lg px-3 py-2 text-sm text-zinc-200 flex items-center justify-between focus:outline-none focus:ring-1 focus:ring-purple-500 hover:bg-zinc-700/50 transition-colors",title:i?"Close List":"Expand List",children:[p.jsx("span",{className:"truncate",children:u(t)}),p.jsx(zu,{size:14,className:`transition-transform duration-200 ${i?"rotate-180":""}`})]}),i&&p.jsx("div",{className:"bg-zinc-900/50 border border-white/10 rounded-lg overflow-hidden transition-all animate-in fade-in slide-in-from-top-2 z-10",children:n.map(v=>p.jsxs("div",{className:"px-2 py-1.5 border-b border-white/5 last:border-0",children:[p.jsx("div",{className:"text-[10px] text-zinc-500 font-bold uppercase mb-1 px-2",children:v.label}),p.jsx("div",{className:"grid grid-cols-1 gap-0.5",children:v.options.map(y=>p.jsx("button",{onMouseEnter:()=>h(y.value),onClick:()=>g(y.value),className:`w-full text-left px-3 py-1.5 rounded-md text-sm transition-colors ${t===y.value?"bg-purple-600/50 text-white":"text-zinc-300 hover:bg-white/10"}`,children:y.label},y.value))})]},v.label))})]})},FU=(t,e,n)=>{if(t==="CustomFont"&&n)return n;for(const i of e){const r=i.options.find(a=>a.value===t);if(r)return r.label}return"Select Font"},zm=({value:t,onChange:e,customFontName:n,groups:i=Kg})=>{const[r,a]=Ae.useState(!1),[c,u]=Ae.useState(t);Ae.useEffect(()=>{r||u(t)},[t,r]);const h=v=>{e(v)},d=()=>{r&&e(c)},g=v=>{e(v),u(v),a(!1)};return p.jsxs("div",{className:"space-y-2",onMouseLeave:d,children:[p.jsxs("button",{onClick:()=>a(!r),className:"w-full bg-zinc-800 border border-white/10 rounded-lg px-3 py-2 text-sm text-zinc-200 flex items-center justify-between focus:outline-none focus:ring-1 focus:ring-purple-500 hover:bg-zinc-700/50 transition-colors",title:r?"Close Font List":"Expand Font List",children:[p.jsx("span",{className:"truncate",style:{fontFamily:t},children:FU(t,i,n)}),p.jsx(zu,{size:14,className:`transition-transform duration-200 ${r?"rotate-180":""}`})]}),r&&p.jsxs("div",{className:"bg-zinc-900/50 border border-white/10 rounded-lg overflow-hidden transition-all animate-in fade-in slide-in-from-top-2",children:[n&&p.jsxs("div",{className:"px-2 py-1.5 border-b border-white/5",children:[p.jsx("div",{className:"text-[10px] text-zinc-500 font-bold uppercase mb-1 px-2",children:"Custom"}),p.jsx("button",{onMouseEnter:()=>h("CustomFont"),onClick:()=>g("CustomFont"),className:`w-full text-left px-3 py-2 rounded-md text-sm transition-colors ${t==="CustomFont"?"bg-purple-600 text-white":"text-zinc-300 hover:bg-white/10"}`,children:p.jsxs("span",{style:{fontFamily:"CustomFont"},children:["✨ ",n]})})]}),i.map(v=>p.jsxs("div",{className:"px-2 py-1.5 border-b border-white/5 last:border-0",children:[p.jsx("div",{className:"text-[10px] text-zinc-500 font-bold uppercase mb-1 px-2",children:v.label}),p.jsx("div",{className:"grid grid-cols-1 gap-0.5",children:v.options.map(y=>p.jsx("button",{onMouseEnter:()=>h(y.value),onClick:()=>g(y.value),className:`w-full text-left px-3 py-1.5 rounded-md text-sm transition-colors ${t===y.value?"bg-purple-600/50 text-white":"text-zinc-300 hover:bg-white/10"}`,title:y.label,children:p.jsx("span",{style:{fontFamily:y.value},children:y.label})},y.value))})]},v.label))]})]})},OU=Object.values(oh).filter(t=>t.fontFamily).reduce((t,e)=>{if(!t.find(n=>n.value===e.fontFamily)){let n=e.fontFamily.split(",")[0].replace(/['"]/g,"");n.includes("ui-serif")?n="Classic Serif":n.includes("ui-monospace")?n="Monospace":n==="sans-serif"&&(n="Default Sans"),t.push({label:`${n} (Preset)`,value:e.fontFamily})}return t},[]),BU=[{label:"Visual Presets",options:OU},...Kg],VU=({config:t,setConfig:e,preset:n,setPreset:i,onClose:r,isPlaylistMode:a,hasPlaylist:c,onRender:u,customFontName:h,onFontUpload:d,onClearCustomFont:g,resolution:v,setResolution:y,aspectRatio:S,setAspectRatio:T,renderCodec:A,setRenderCodec:E,supportedCodecs:w,renderQuality:I,setRenderQuality:L,renderFps:D,setRenderFps:W,renderEngine:V,setRenderEngine:H,ffmpegCodec:Q,setFfmpegCodec:k,customChannelFontName:P,onChannelFontUpload:J,onClearChannelCustomFont:ve,customInfoFontName:fe,onInfoFontUpload:Ee,onClearInfoCustomFont:je})=>{const{toast:X,confirm:_e}=Ou(),[ne,tt]=Ae.useState([]),Ce=(C,te)=>{ne.includes(C)||tt(Re=>[C,...Re]);const ae=C.includes(" ")?`'${C}'`:C;U(te,ae)},$=Og.useMemo(()=>{const C=[],te=t.fontFamily?t.fontFamily.split(",")[0].replace(/['"]/g,""):"";return te&&C.push({label:"Matched",options:[{label:`Use Lyric Font (${te})`,value:t.fontFamily}]}),ne.length>0&&C.push({label:"Loaded Google Fonts",options:ne.map(ae=>({label:ae,value:ae.includes(" ")?`'${ae}'`:ae}))}),[...C,...BU]},[ne,t.fontFamily]),ce=Ae.useRef(null),Xe=Ae.useRef(null),oe=Ae.useRef(null),Ie=Ae.useRef(null),nt=Ae.useRef(null),Se=Ae.useRef(null),N=Ae.useRef(null),ye=Ae.useRef(null),[xe,Oe]=Ae.useState(!1),[at,Ze]=Ae.useState(null),U=(C,te)=>{let ae={...t,[C]:te};if(C==="highlightEffect"){const De=Uf(te);ae.useCustomHighlightColors=!1,De?(ae.highlightColor=De.color,ae.highlightBackground=De.bg):(ae.highlightColor="#fb923c",ae.highlightBackground="#fb923c")}else if(C==="useCustomHighlightColors"&&te===!1){const Re=t.highlightEffect,De=Uf(Re);De?(ae.highlightColor=De.color,ae.highlightBackground=De.bg):(ae.highlightColor="#fb923c",ae.highlightBackground="#fb923c")}e(ae)},Me=C=>{i(C);const te=oh[C];te&&e({...t,...{fontFamily:"sans-serif",fontSizeScale:1,fontColor:"#ffffff",fontWeight:"bold",fontStyle:"normal",textCase:"none",textAlign:"center",contentPosition:"center",textDecoration:"none",textEffect:"preset",textAnimation:"none",highlightEffect:"karaoke",highlightColor:"#fb923c",highlightBackground:"#fb923c",useCustomHighlightColors:!1,lyricStyleTarget:"active-only",transitionEffect:"none"},...te})},Pe=C=>{const te=C.target.files?.[0];if(te){const ae=new FileReader;ae.onload=Re=>{Re.target?.result&&U("channelInfoImage",Re.target.result)},ae.readAsDataURL(te)}C.target.value=""},rt=C=>{const te=C.target.files?.[0];if(te){const ae=new FileReader;ae.onload=Re=>{Re.target?.result&&U("backgroundImage",Re.target.result)},ae.readAsDataURL(te)}C.target.value=""},We=C=>{const te=C.target.files?.[0];if(te){if(!te.type.startsWith("video/")){X.error("Please upload a valid video file.");return}const ae=new FileReader;ae.onload=Re=>{Re.target?.result&&U("backgroundVideo",Re.target.result)},ae.readAsDataURL(te)}C.target.value=""},gt=async()=>{await _e(`This will reset ALL settings to factory defaults: + +• Visual preset → Default +• Background, fonts & colors +• Text effects, animations & transitions +• Song info, watermark & visualization +• Output: 1080p, 30fps, MediaRecorder + +This cannot be undone.`,"Reset All Settings to Default")&&(e(KS),i("default"),y("1080p"),T("16:9"),E("auto"),W(30),L("med"),H("mediarecorder"),k("h264"),nt.current&&(nt.current.value=""),Se.current&&(Se.current.value=""),N.current&&(N.current.value=""),ye.current&&(ye.current.value=""),g(),ve&&ve(),je&&je(),Xe.current&&(Xe.current.value=""),oe.current&&(oe.current.value=""),Ie.current&&(Ie.current.value=""),Ze(null),X.success("All settings have been reset to default."))},qe=()=>{const C=new Date,te=C.toISOString().replace(/[:.]/g,"-").slice(0,19),ae=(z,j=6)=>typeof z=="number"?Number(z.toFixed(j)):z,Re=(z,j,B,re)=>{if(z===B&&j)return{slot:re,cssValue:B,realName:j,source:"uploaded-file",warning:`Re-upload font file "${j}" after importing this config.`};if(z&&ne.some(Y=>z.includes(Y))){const Y=z.replace(/['"]/g,"").trim();return{slot:re,cssValue:z,realName:Y,source:"google-font",warning:`Google Font "${Y}" – internet connection required on target machine.`}}return{slot:re,cssValue:z??"sans-serif",realName:z??"sans-serif",source:"built-in",warning:""}},De=Re(t.fontFamily,h,"CustomFont","lyrics"),st=Re(t.channelInfoFontFamily,P,"ChannelFont","channel-watermark"),it=Re(t.infoFontFamily,fe,"InfoFont","song-info"),F=[De,st,it].filter(z=>z.source!=="built-in"),le={_meta:{exportedAt:C.toISOString(),appVersion:"1.0",schema:"render-settings-v1",_fontNotes:F.length>0?F:"all fonts are built-in system fonts"},...t,fontSizeScale:ae(t.fontSizeScale),infoSizeScale:ae(t.infoSizeScale),infoMarginScale:ae(t.infoMarginScale),channelInfoSizeScale:ae(t.channelInfoSizeScale),channelInfoMarginScale:ae(t.channelInfoMarginScale),marginTopScale:ae(t.marginTopScale),marginBottomScale:ae(t.marginBottomScale),visualizationOpacity:ae(t.visualizationOpacity,4),visualizationSensitivity:ae(t.visualizationSensitivity,4),fontFamily:t.fontFamily,...De.source!=="built-in"&&{__note_fontFamily:`Real name: "${De.realName}" [${De.source}]`+(De.source==="uploaded-file"?" – re-upload required after import":"")},channelInfoFontFamily:t.channelInfoFontFamily,...st.source!=="built-in"&&t.channelInfoFontFamily&&{__note_channelInfoFontFamily:`Real name: "${st.realName}" [${st.source}]`+(st.source==="uploaded-file"?" – re-upload required after import":"")},infoFontFamily:t.infoFontFamily,...it.source!=="built-in"&&t.infoFontFamily&&{__note_infoFontFamily:`Real name: "${it.realName}" [${it.source}]`+(it.source==="uploaded-file"?" – re-upload required after import":"")},preset:n,resolution:v,aspectRatio:S,renderCodec:A,renderFps:D,renderQuality:I,renderEngine:V,ffmpegCodec:Q,customFontName:h,customChannelFontName:P,customInfoFontName:fe,channelInfoFontWeight:t.channelInfoFontWeight,channelInfoFontStyle:t.channelInfoFontStyle,infoFontWeight:t.infoFontWeight,infoFontStyle:t.infoFontStyle};le.backgroundSource!=="image"&&delete le.backgroundImage,le.backgroundSource!=="video"&&delete le.backgroundVideo,le.showChannelInfo||delete le.channelInfoImage;try{const z=JSON.stringify(le,null,2),j=new Blob([z],{type:"application/json"}),B=URL.createObjectURL(j),re=document.createElement("a");re.href=B,re.download=`render_settings_${te}.json`,document.body.appendChild(re),re.click(),re.remove(),URL.revokeObjectURL(B),X.success(`Settings exported as render_settings_${te}.json`)}catch(z){console.error("Export failed:",z),X.error("Failed to export settings.")}},q=C=>{const te=C.target.files?.[0];if(!te)return;Ze(te.name);const ae=new FileReader;ae.onload=Re=>{try{const De=JSON.parse(Re.target?.result);if(De&&typeof De=="object"){const{_meta:st,__note_fontFamily:it,__note_channelInfoFontFamily:F,__note_infoFontFamily:le,resolution:z,aspectRatio:j,renderCodec:B,renderFps:re,renderQuality:Y,renderEngine:me,ffmpegCodec:ee,preset:$e,customFontName:M,customChannelFontName:K,customInfoFontName:de,channelInfoFontWeight:ue,channelInfoFontStyle:Ue,infoFontWeight:Je,infoFontStyle:ht,...et}=De,Te={...KS,...et};if(ue&&(Te.channelInfoFontWeight=ue),Ue&&(Te.channelInfoFontStyle=Ue),Je&&(Te.infoFontWeight=Je),ht&&(Te.infoFontStyle=ht),["backgroundBlurStrength","fontSizeScale","infoMarginScale","infoSizeScale","channelInfoSizeScale","channelInfoMarginScale","visualTransitionDuration","lyricLineHeight","marginTopScale","marginBottomScale","visualizationOpacity","visualizationSensitivity","visualizationBarCount"].forEach(Zt=>{Te[Zt]!==void 0&&(Te[Zt]=Number(Te[Zt]))}),Te.useCustomHighlightColors!==void 0&&(Te.useCustomHighlightColors=!!Te.useCustomHighlightColors),Te.useRealColorMedia!==void 0&&(Te.useRealColorMedia=!!Te.useRealColorMedia),Te.showChannelInfo!==void 0&&(Te.showChannelInfo=!!Te.showChannelInfo),Te.showIntro!==void 0&&(Te.showIntro=!!Te.showIntro),Te.showTitle!==void 0&&(Te.showTitle=!!Te.showTitle),Te.showArtist!==void 0&&(Te.showArtist=!!Te.showArtist),Te.showCover!==void 0&&(Te.showCover=!!Te.showCover),Te.showLyrics!==void 0&&(Te.showLyrics=!!Te.showLyrics),Te.showVisualization!==void 0&&(Te.showVisualization=!!Te.showVisualization),Te.enableGradientOverlay!==void 0&&(Te.enableGradientOverlay=!!Te.enableGradientOverlay),Te.threejsCameraMovement!==void 0&&(Te.threejsCameraMovement=!!Te.threejsCameraMovement),Te.highlightEffect&&(!Te.highlightColor||!Te.highlightBackground)){const Zt=Uf(Te.highlightEffect);Zt&&(Te.highlightColor||(Te.highlightColor=Zt.color),Te.highlightBackground||(Te.highlightBackground=Zt.bg))}const Be=(Zt,ti)=>ti.some(Gi=>Gi.options.some(Si=>Si.value===Zt));Te.textEffect&&!Be(Te.textEffect,ZS)&&(Te.textEffect="shadow"),Te.textAnimation&&!Be(Te.textAnimation,QS)&&(Te.textAnimation="none"),Te.transitionEffect&&!Be(Te.transitionEffect,e1)&&(Te.transitionEffect="none"),Te.visualTransitionType&&!Be(Te.visualTransitionType,t1)&&(Te.visualTransitionType="none"),Te.highlightEffect&&!Be(Te.highlightEffect,z0)&&(Te.highlightEffect="karaoke"),Te.backgroundSource&&!Be(Te.backgroundSource,n1)&&(Te.backgroundSource="custom"),["current","playlist"].includes(Te.renderMode)||(Te.renderMode="current"),["left","center","right"].includes(Te.textAlign)||(Te.textAlign="center"),["top","center","bottom"].includes(Te.contentPosition)||(Te.contentPosition="center"),Te.marginTopScale===void 0||isNaN(Te.marginTopScale)?Te.marginTopScale=1:Te.marginTopScale=Math.max(0,Math.min(5,Te.marginTopScale)),Te.marginBottomScale===void 0||isNaN(Te.marginBottomScale)?Te.marginBottomScale=1:Te.marginBottomScale=Math.max(0,Math.min(5,Te.marginBottomScale)),Te.lyricDisplayMode&&!Be(Te.lyricDisplayMode,P0)&&(Te.lyricDisplayMode="all"),["normal","bold"].includes(Te.fontWeight)||(Te.fontWeight="bold"),["normal","italic"].includes(Te.fontStyle)||(Te.fontStyle="normal"),["none","underline","line-through"].includes(Te.textDecoration)||(Te.textDecoration="none"),fE.includes(Te.textCase)||(Te.textCase="none"),["auto","manual"].includes(Te.introMode)||(Te.introMode="auto"),Te.lyricStyleTarget&&!["active-only","all"].includes(Te.lyricStyleTarget)&&(Te.lyricStyleTarget="active-only");const _t=["top-left","top-right","bottom-left","bottom-right","top-center","bottom-center"];Te.infoPosition&&!_t.includes(Te.infoPosition)&&(Te.infoPosition="top-left"),Te.infoStyle&&!Be(Te.infoStyle,i1)&&(Te.infoStyle="classic"),Te.channelInfoPosition&&!_t.includes(Te.channelInfoPosition)&&(Te.channelInfoPosition="bottom-right"),Te.channelInfoStyle&&!Be(Te.channelInfoStyle,o1)&&(Te.channelInfoStyle="classic");const Jt=["bars","wave","circular","particles","pulse-ring"];Te.visualizationType&&!Jt.includes(Te.visualizationType)&&(Te.visualizationType="bars");const Dt=["accent","gradient","custom","rainbow"];Te.visualizationColorMode&&!Dt.includes(Te.visualizationColorMode)&&(Te.visualizationColorMode="gradient");const Yt=["bottom","top","full","center"];Te.visualizationPosition&&!Yt.includes(Te.visualizationPosition)&&(Te.visualizationPosition="bottom"),Te.visualizationOpacity!==void 0&&(Te.visualizationOpacity=Math.max(0,Math.min(1,Te.visualizationOpacity))),Te.visualizationSensitivity!==void 0&&(Te.visualizationSensitivity=Math.max(.5,Math.min(3,Te.visualizationSensitivity))),Te.visualizationBarCount!==void 0&&(Te.visualizationBarCount=Math.max(16,Math.min(128,Math.round(Te.visualizationBarCount)))),e(Te),z&&y(z),j&&T(j),B&&E(B),re&&W(Number(re)),Y&&L(Y),me&&H(me),ee&&k(ee),i($e||"custom"),M&&M!==h?X.success(`Settings loaded. Note: Config used font "${M}".`):K||de?X.success(`Settings loaded. Custom fonts referenced: ${[K,de].filter(Boolean).join(", ")}`):X.success("Settings loaded successfully!")}}catch(De){console.error(De),X.error("Failed to parse settings file. Please ensure it is a valid JSON file.")}},ae.readAsText(te),C.target.value=""};return Ae.useEffect(()=>{const C=te=>{ce.current&&!ce.current.contains(te.target)&&r()};return document.addEventListener("mousedown",C),()=>{document.removeEventListener("mousedown",C)}},[r]),p.jsxs("div",{ref:ce,onMouseDown:C=>C.stopPropagation(),className:"no-minimal-mode-toggle absolute right-0 top-0 bottom-0 w-full sm:w-80 bg-zinc-900/95 backdrop-blur-xl border-l border-white/10 z-50 flex flex-col shadow-2xl animate-in slide-in-from-right duration-300",children:[p.jsxs("div",{className:"h-14 border-b border-white/10 flex items-center justify-between px-3 md:px-4 bg-zinc-900/50 overflow-hidden",children:[p.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[p.jsx(Gl,{size:18,className:"text-purple-400 shrink-0"}),p.jsx("h2",{className:"font-bold text-zinc-200 truncate",children:"Render Settings"})]}),p.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-2",children:[p.jsx("input",{ref:ye,type:"file",name:"import-settings",id:"import-settings","aria-label":"Import Settings JSON",accept:".json",className:"hidden",onChange:q}),p.jsx("button",{onClick:()=>ye.current?.click(),className:"p-1.5 rounded-lg text-zinc-400 hover:text-emerald-300 hover:bg-emerald-500/10 transition-all",title:"Import settings (.json)",children:p.jsx(cs,{size:15})}),p.jsx("button",{onClick:qe,className:"p-1.5 rounded-lg text-zinc-400 hover:text-blue-300 hover:bg-blue-500/10 transition-all",title:"Export settings (.json)",children:p.jsx(fb,{size:15})}),p.jsx("button",{onClick:gt,className:"p-1.5 rounded-lg text-zinc-500 hover:text-red-400 hover:bg-red-500/10 transition-all",title:"Reset all settings to defaults",children:p.jsx(Kf,{size:15})}),p.jsx("div",{className:"w-px h-4 bg-white/10 mx-0.5"}),p.jsx("button",{onClick:r,className:"p-1.5 hover:bg-white/10 rounded-lg text-zinc-400 hover:text-white transition-colors",title:"Close",children:p.jsx(Wo,{size:18})})]})]}),p.jsxs("div",{className:"flex-1 overflow-y-auto p-3 md:p-4 space-y-6 custom-scrollbar",children:[p.jsxs("section",{className:"space-y-2",children:[p.jsxs("h3",{className:"text-xs font-bold text-zinc-500 uppercase tracking-wider flex items-center gap-2",children:[p.jsx(Gl,{size:14})," Settings Management"]}),p.jsxs("div",{className:"rounded-xl border border-white/10 bg-zinc-800/40 overflow-hidden",children:[p.jsxs("div",{className:"flex items-center gap-3 px-3 py-2.5 border-b border-white/5",children:[p.jsxs("div",{className:"flex-1 min-w-0",children:[p.jsx("p",{className:"text-xs font-semibold text-zinc-200",children:"Import Settings"}),p.jsx("p",{className:"text-[10px] text-zinc-500 truncate",children:at?p.jsxs("span",{className:"text-emerald-400 font-mono",children:["✓ ",at]}):"Load a previously exported .json file"})]}),p.jsxs("button",{onClick:()=>ye.current?.click(),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-emerald-600/20 hover:bg-emerald-600/40 border border-emerald-500/30 text-emerald-300 hover:text-emerald-100 text-xs font-semibold transition-all active:scale-95 shrink-0",title:"Import settings from a .json file",children:[p.jsx(cs,{size:13})," Import"]})]}),p.jsxs("div",{className:"flex items-center gap-3 px-3 py-2.5 border-b border-white/5",children:[p.jsxs("div",{className:"flex-1 min-w-0",children:[p.jsx("p",{className:"text-xs font-semibold text-zinc-200",children:"Export Settings"}),p.jsx("p",{className:"text-[10px] text-zinc-500",children:"Save current config as a .json file"})]}),p.jsxs("button",{onClick:qe,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-blue-600/20 hover:bg-blue-600/40 border border-blue-500/30 text-blue-300 hover:text-blue-100 text-xs font-semibold transition-all active:scale-95 shrink-0",title:"Export current settings as a .json file",children:[p.jsx(fb,{size:13})," Export"]})]}),p.jsxs("div",{className:"flex items-center gap-3 px-3 py-2.5",children:[p.jsxs("div",{className:"flex-1 min-w-0",children:[p.jsx("p",{className:"text-xs font-semibold text-zinc-200",children:"Reset to Default"}),p.jsx("p",{className:"text-[10px] text-zinc-500",children:"Restore all settings to factory defaults"})]}),p.jsxs("button",{onClick:gt,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-red-600/10 hover:bg-red-600/30 border border-red-500/20 hover:border-red-500/50 text-red-400 hover:text-red-200 text-xs font-semibold transition-all active:scale-95 shrink-0",title:"Reset all settings to factory defaults",children:[p.jsx(Kf,{size:13})," Reset"]})]})]})]}),p.jsxs("section",{className:"space-y-3",children:[p.jsxs("h3",{className:"text-xs font-bold text-zinc-500 uppercase tracking-wider flex items-center gap-2",children:[p.jsx(_0,{size:14})," Visual Preset"]}),p.jsx(No,{value:n,onChange:C=>Me(C),groups:Zg})]}),p.jsxs("section",{className:"space-y-3",children:[p.jsxs("h3",{className:"text-xs font-bold text-zinc-500 uppercase tracking-wider flex items-center gap-2",children:[p.jsx(Ru,{size:14})," Render Scope"]}),p.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[p.jsx("button",{onClick:()=>U("renderMode","current"),className:`px-3 py-2 rounded-lg text-xs font-medium border transition-all ${t.renderMode==="current"?"bg-purple-600 border-purple-500 text-white shadow-[0_0_10px_rgba(147,51,234,0.3)]":"bg-zinc-800/50 border-white/5 text-zinc-400 hover:border-white/20"}`,children:"Current Song"}),p.jsx("button",{onClick:()=>U("renderMode","playlist"),disabled:!c,className:`px-3 py-2 rounded-lg text-xs font-medium border transition-all ${t.renderMode==="playlist"?"bg-purple-600 border-purple-500 text-white shadow-[0_0_10px_rgba(147,51,234,0.3)]":"bg-zinc-800/50 border-white/5 text-zinc-400 hover:border-white/20 disabled:opacity-30 disabled:cursor-not-allowed"}`,children:"All Playlist"})]})]}),p.jsxs("section",{className:"space-y-3",children:[p.jsxs("h3",{className:"text-xs font-bold text-zinc-500 uppercase tracking-wider flex items-center gap-2",children:[p.jsx(hb,{size:14})," Background Source"]}),p.jsx(No,{value:t.backgroundSource,onChange:C=>{C==="gradient"&&!t.backgroundGradient?(i("custom"),e({...t,backgroundSource:"gradient",backgroundGradient:"linear-gradient(to bottom right, #312e81, #581c87, #000000)"})):C==="smart-gradient"&&(!t.backgroundColor||t.backgroundColor==="#000000")?(i("custom"),e({...t,backgroundSource:"smart-gradient",backgroundColor:"#581c87"})):C==="color"&&!t.backgroundColor?(i("custom"),e({...t,backgroundSource:"color",backgroundColor:"#000000"})):U("backgroundSource",C)},groups:n1}),t.backgroundSource==="smart-gradient"&&p.jsxs("div",{className:"flex items-center gap-3 bg-zinc-800/30 p-2 rounded-lg border border-white/5",children:[p.jsx("input",{type:"color",name:"smart-bg-color","aria-label":"Smart Gradient Base Color",value:t.backgroundColor,onChange:C=>U("backgroundColor",C.target.value),className:"w-10 h-10 rounded cursor-pointer bg-transparent border-none shrink-0"}),p.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[p.jsx("span",{className:"text-xs text-zinc-300 font-medium",children:"Pick Base Color"}),p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx("span",{className:"text-[10px] text-zinc-500",children:"Hex:"}),p.jsx("input",{type:"text",name:"smart-bg-hex","aria-label":"Smart Gradient Base Color Hex",value:t.backgroundColor,onChange:C=>U("backgroundColor",C.target.value),className:"bg-transparent border-b border-zinc-700 focus:border-purple-500 text-[10px] text-zinc-300 font-mono focus:outline-none p-0 w-20 uppercase"})]})]})]}),t.backgroundSource==="color"&&p.jsxs("div",{className:"flex items-center gap-3 bg-zinc-800/30 p-2 rounded-lg border border-white/5",children:[p.jsx("input",{id:"solid-bg-color",type:"color",name:"solid-bg-color","aria-label":"Background Color",value:t.backgroundColor,onChange:C=>U("backgroundColor",C.target.value),className:"w-8 h-8 rounded cursor-pointer bg-transparent border-none shrink-0"}),p.jsx("input",{id:"solid-bg-hex",type:"text",name:"solid-bg-hex","aria-label":"Background Color Hex",value:t.backgroundColor,onChange:C=>U("backgroundColor",C.target.value),className:"bg-transparent border-b border-zinc-700 text-xs text-zinc-300 font-mono flex-1 focus:outline-none focus:border-purple-500 uppercase py-1"})]}),t.backgroundSource==="gradient"&&p.jsx("input",{type:"text",name:"custom-gradient","aria-label":"Custom CSS Gradient",value:t.backgroundGradient,onChange:C=>U("backgroundGradient",C.target.value),placeholder:"linear-gradient(to bottom right, #312e81, #581c87, #000000)",className:"w-full bg-zinc-800 border border-white/10 rounded-lg px-3 py-2 text-xs font-mono text-zinc-300 focus:outline-none focus:ring-1 focus:ring-purple-500"}),t.backgroundSource==="image"&&p.jsx("div",{className:"space-y-3 animate-in slide-in-from-top-1 fade-in duration-200",children:p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("label",{htmlFor:"bg-image-upload",className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Custom Background Image"}),p.jsx("input",{ref:Se,type:"file",name:"bg-image-upload",id:"bg-image-upload",accept:"image/*",onChange:rt,className:"hidden"}),t.backgroundImage?p.jsxs("div",{className:"flex items-center gap-3 bg-zinc-800 p-2 rounded-lg border border-white/10",children:[p.jsx("div",{className:"w-10 h-10 rounded bg-zinc-700/50 flex items-center justify-center overflow-hidden border border-white/5",children:p.jsx("img",{src:t.backgroundImage,alt:"Background",className:"w-full h-full object-cover"})}),p.jsxs("div",{className:"flex-1 min-w-0",children:[p.jsx("p",{className:"text-xs text-zinc-300 truncate",children:"Image Loaded"}),p.jsx("button",{onClick:()=>U("backgroundImage",void 0),className:"text-[10px] text-red-400 hover:text-red-300",children:"Remove"})]}),p.jsx("button",{onClick:()=>Se.current?.click(),className:"p-1.5 hover:bg-white/10 rounded-md text-zinc-400 hover:text-white",children:p.jsx(Gl,{size:14})})]}):p.jsxs("button",{onClick:()=>Se.current?.click(),className:"w-full flex items-center justify-center gap-2 bg-zinc-800/50 border border-dashed border-white/10 hover:border-purple-500/50 rounded-lg px-3 py-3 text-zinc-400 hover:text-purple-300 transition-colors",children:[p.jsx(cs,{size:14}),p.jsx("span",{className:"text-xs",children:"Upload Background"})]})]})}),t.backgroundSource==="video"&&p.jsx("div",{className:"space-y-3 animate-in slide-in-from-top-1 fade-in duration-200",children:p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("label",{htmlFor:"bg-video-upload",className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Custom Background Video"}),p.jsx("input",{ref:N,type:"file",name:"bg-video-upload",id:"bg-video-upload",accept:"video/*",onChange:We,className:"hidden"}),t.backgroundVideo?p.jsxs("div",{className:"flex items-center gap-3 bg-zinc-800 p-2 rounded-lg border border-white/10",children:[p.jsx("div",{className:"w-10 h-10 rounded bg-zinc-700/50 flex items-center justify-center overflow-hidden border border-white/5",children:p.jsx("video",{src:t.backgroundVideo,className:"w-full h-full object-cover",muted:!0,autoPlay:!0,loop:!0})}),p.jsxs("div",{className:"flex-1 min-w-0",children:[p.jsx("p",{className:"text-xs text-zinc-300 truncate",children:"Video Loaded"}),p.jsx("button",{onClick:()=>U("backgroundVideo",void 0),className:"text-[10px] text-red-400 hover:text-red-300",children:"Remove"})]}),p.jsx("button",{onClick:()=>N.current?.click(),className:"p-1.5 hover:bg-white/10 rounded-md text-zinc-400 hover:text-white",children:p.jsx(Gl,{size:14})})]}):p.jsxs("button",{onClick:()=>N.current?.click(),className:"w-full flex items-center justify-center gap-2 bg-zinc-800/50 border border-dashed border-white/10 hover:border-purple-500/50 rounded-lg px-3 py-3 text-zinc-400 hover:text-purple-300 transition-colors",children:[p.jsx(cs,{size:14}),p.jsx("span",{className:"text-xs",children:"Upload Video Loop"})]})]})}),t.backgroundSource==="threejs"&&p.jsxs("div",{className:"space-y-3 animate-in slide-in-from-top-1 fade-in duration-200",children:[p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Three.js Scene Effect"}),p.jsx(No,{value:t.threejsScene||"stars",onChange:C=>U("threejsScene",C),groups:zU})]}),p.jsxs("div",{className:"space-y-1.5 flex flex-col gap-1",children:[p.jsxs("label",{htmlFor:"threejs-speed",className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:["Speed: ",t.threejsSpeed||1,"x"]}),p.jsx("input",{id:"threejs-speed",type:"range",min:"0.1",max:"5",step:"0.1",value:t.threejsSpeed||1,onChange:C=>U("threejsSpeed",parseFloat(C.target.value)),className:"w-full accent-purple-500"})]}),p.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("label",{htmlFor:"threejs-color",className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Theme Color"}),p.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800 border border-white/10 rounded-lg px-2 py-1.5 h-9",children:[p.jsx("input",{id:"threejs-color",name:"threejs-color",type:"color",value:t.threejsColor||"#a855f7",onChange:C=>U("threejsColor",C.target.value),className:"w-6 h-6 bg-transparent cursor-pointer border-none shrink-0"}),p.jsx("input",{id:"threejs-color-hex",name:"threejs-color-hex",type:"text","aria-label":"Theme Color Hex",value:t.threejsColor||"#a855f7",onChange:C=>U("threejsColor",C.target.value),className:"w-full bg-transparent border-none text-xs items-center flex text-zinc-200 focus:outline-none font-mono"})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("label",{htmlFor:"threejs-bg-color",className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",title:"Leave empty for transparent (uses app background)",children:"Bg Color"}),p.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800 border border-white/10 rounded-lg px-2 py-1.5 h-9",children:[p.jsx("input",{id:"threejs-bg-color",name:"threejs-bg-color",type:"color",value:t.threejsBgColor||"#000000",onChange:C=>U("threejsBgColor",C.target.value),className:"w-6 h-6 bg-transparent cursor-pointer border-none shrink-0"}),p.jsx("input",{id:"threejs-bg-color-hex",name:"threejs-bg-color-hex",type:"text",placeholder:"None","aria-label":"Background Color Hex",value:t.threejsBgColor||"",onChange:C=>U("threejsBgColor",C.target.value),className:"w-full bg-transparent border-none text-xs items-center flex text-zinc-200 focus:outline-none placeholder:text-zinc-600 font-mono"})]})]})]}),p.jsx("div",{className:"pt-1",children:p.jsxs("label",{htmlFor:"threejs-camera-movement",className:"flex items-center gap-2 cursor-pointer group",children:[p.jsxs("div",{className:"relative flex items-center justify-center",children:[p.jsx("input",{id:"threejs-camera-movement",name:"threejs-camera-movement",type:"checkbox",checked:t.threejsCameraMovement||!1,onChange:C=>U("threejsCameraMovement",C.target.checked),className:"peer sr-only"}),p.jsx("div",{className:"w-5 h-5 bg-zinc-800 border border-white/20 rounded-md peer-checked:bg-purple-500 peer-checked:border-purple-500 transition-colors"}),p.jsx(pT,{size:12,className:"absolute text-white opacity-0 peer-checked:opacity-100 transition-opacity"})]}),p.jsx("span",{className:"text-xs text-zinc-300 font-medium group-hover:text-purple-300 transition-colors",children:"Auto Camera Movement"})]})})]})]}),p.jsxs("section",{className:"space-y-3",children:[p.jsxs("h3",{className:"text-xs font-bold text-zinc-500 uppercase tracking-wider flex items-center gap-2",children:[p.jsx(dA,{size:14})," Background Effects"]}),p.jsxs("div",{className:"space-y-3",children:[p.jsxs("div",{className:"flex bg-zinc-800 p-1 rounded-lg border border-white/5",children:[p.jsx("button",{onClick:()=>U("backgroundBlurStrength",0),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-all ${t.backgroundBlurStrength===0?"bg-zinc-600 text-white shadow-sm":"text-zinc-400 hover:text-zinc-200 hover:bg-white/5"}`,children:"Sharp"}),p.jsx("button",{onClick:()=>U("backgroundBlurStrength",12),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-all ${t.backgroundBlurStrength>0?"bg-purple-600 text-white shadow-sm":"text-zinc-400 hover:text-zinc-200 hover:bg-white/5"}`,children:"Blur"})]}),t.backgroundBlurStrength>0&&p.jsxs("div",{className:"space-y-1.5 animate-in slide-in-from-top-2 fade-in duration-200",children:[p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Blur Intensity"}),p.jsxs("span",{className:"text-[10px] text-zinc-400 font-mono",children:[t.backgroundBlurStrength,"px"]})]}),p.jsx("div",{className:"flex items-center gap-2 bg-zinc-800 border border-white/10 rounded-lg px-2 py-1.5",children:p.jsx("input",{type:"range",name:"blur-strength","aria-label":"Blur Intensity",min:"1",max:"64",step:"1",value:t.backgroundBlurStrength,onChange:C=>U("backgroundBlurStrength",parseInt(C.target.value)),className:"w-full h-1 bg-zinc-600 rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:rounded-full hover:[&::-webkit-slider-thumb]:bg-purple-400 transition-all"})})]})]}),p.jsxs("div",{className:"bg-zinc-800/30 border border-white/5 rounded-lg p-2.5 flex items-center justify-between cursor-pointer hover:bg-zinc-800/50 transition-colors",children:[p.jsxs("div",{className:"flex flex-col",children:[p.jsx("label",{htmlFor:"real-color-media",className:"text-xs text-zinc-300 font-medium cursor-pointer",children:"Real Color Media Source"}),p.jsx("span",{className:"text-[10px] text-zinc-500",children:"Disable dark dimming effect on background"})]}),p.jsxs("div",{className:"relative inline-flex items-center cursor-pointer",children:[p.jsx("input",{type:"checkbox",id:"real-color-media",name:"real-color-media","aria-label":"Real Color Media",checked:t.useRealColorMedia??!1,onChange:C=>U("useRealColorMedia",C.target.checked),className:"sr-only peer"}),p.jsx("label",{htmlFor:"real-color-media",className:"w-8 h-4 bg-zinc-700 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-3 after:w-3 after:transition-all peer-checked:bg-purple-600 block cursor-pointer"})]})]}),p.jsxs("div",{className:"bg-zinc-800/30 border border-white/5 rounded-lg p-2.5 flex items-center justify-between cursor-pointer hover:bg-zinc-800/50 transition-colors",children:[p.jsxs("div",{className:"flex flex-col",children:[p.jsx("label",{htmlFor:"gradient-overlay",className:"text-xs text-zinc-300 font-medium cursor-pointer",children:"Black Gradient Overlay"}),p.jsx("span",{className:"text-[10px] text-zinc-500",children:"Fade bottom to top (readability)"})]}),p.jsxs("div",{className:"relative inline-flex items-center cursor-pointer",children:[p.jsx("input",{type:"checkbox",id:"gradient-overlay",name:"gradient-overlay","aria-label":"Gradient Overlay",checked:t.enableGradientOverlay??!1,onChange:C=>U("enableGradientOverlay",C.target.checked),className:"sr-only peer"}),p.jsx("label",{htmlFor:"gradient-overlay",className:"w-8 h-4 bg-zinc-700 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-3 after:w-3 after:transition-all peer-checked:bg-purple-600 block cursor-pointer"})]})]})]}),p.jsxs("section",{className:"space-y-3",children:[p.jsx("div",{className:"flex items-center justify-between",children:p.jsxs("h3",{className:"text-xs font-bold text-zinc-500 uppercase tracking-wider flex items-center gap-2",children:[p.jsx(_C,{size:14})," Audio Visualizer"]})}),p.jsxs("div",{className:"bg-zinc-800/30 border border-white/5 rounded-lg p-2.5 flex items-center justify-between cursor-pointer hover:bg-zinc-800/50 transition-colors",children:[p.jsxs("div",{className:"flex flex-col",children:[p.jsx("label",{htmlFor:"show-visualization",className:"text-xs text-zinc-300 font-medium cursor-pointer",children:"Show Visualization"}),p.jsx("span",{className:"text-[10px] text-zinc-500",children:"Real-time audio reactive visuals"})]}),p.jsxs("div",{className:"relative inline-flex items-center cursor-pointer",children:[p.jsx("input",{type:"checkbox",id:"show-visualization",name:"show-visualization","aria-label":"Show Visualization",checked:t.showVisualization??!1,onChange:C=>U("showVisualization",C.target.checked),className:"sr-only peer"}),p.jsx("label",{htmlFor:"show-visualization",className:"w-8 h-4 bg-zinc-700 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-3 after:w-3 after:transition-all peer-checked:bg-purple-600 block cursor-pointer"})]})]}),t.showVisualization&&p.jsxs("div",{className:"space-y-3 animate-in slide-in-from-top-2 fade-in duration-200",children:[p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Visualization Type"}),p.jsx(No,{value:t.visualizationType||"bars",onChange:C=>U("visualizationType",C),groups:[{label:"Minimalist",options:[{label:"Bars",value:"bars"},{label:"Waveform",value:"wave"}]},{label:"Dynamic",options:[{label:"Circular",value:"circular"},{label:"Particles",value:"particles"},{label:"Pulse Ring",value:"pulse-ring"}]}]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Color Mode"}),p.jsx("div",{className:"grid grid-cols-4 gap-1",children:["accent","gradient","rainbow","custom"].map(C=>p.jsx("button",{onClick:()=>U("visualizationColorMode",C),className:`px-2 py-1.5 rounded-md text-[10px] font-medium border transition-all capitalize ${t.visualizationColorMode===C?"bg-purple-600/40 border-purple-500/50 text-purple-200":"bg-zinc-800/50 border-white/5 text-zinc-400 hover:border-white/20"}`,children:C},C))})]}),t.visualizationColorMode==="custom"&&p.jsxs("div",{className:"grid grid-cols-2 gap-2 animate-in slide-in-from-top-2 fade-in duration-200",children:[p.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800/30 p-2 rounded-lg border border-white/5",children:[p.jsx("input",{id:"viz-color-1",type:"color",name:"viz-color-1","aria-label":"Visualization Color 1",value:t.visualizationColor1||"#a855f7",onChange:C=>U("visualizationColor1",C.target.value),className:"w-8 h-8 rounded cursor-pointer bg-transparent border-none shrink-0"}),p.jsx("span",{className:"text-[10px] text-zinc-400",children:"Color 1"})]}),p.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800/30 p-2 rounded-lg border border-white/5",children:[p.jsx("input",{id:"viz-color-2",type:"color",name:"viz-color-2","aria-label":"Visualization Color 2",value:t.visualizationColor2||"#6366f1",onChange:C=>U("visualizationColor2",C.target.value),className:"w-8 h-8 rounded cursor-pointer bg-transparent border-none shrink-0"}),p.jsx("span",{className:"text-[10px] text-zinc-400",children:"Color 2"})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Position"}),p.jsx("div",{className:"grid grid-cols-4 gap-1",children:[{label:"Bottom",value:"bottom"},{label:"Top",value:"top"},{label:"Center",value:"center"},{label:"Full",value:"full"}].map(C=>p.jsx("button",{onClick:()=>U("visualizationPosition",C.value),className:`px-2 py-1.5 rounded-md text-[10px] font-medium border transition-all ${(t.visualizationPosition||"bottom")===C.value?"bg-purple-600/40 border-purple-500/50 text-purple-200":"bg-zinc-800/50 border-white/5 text-zinc-400 hover:border-white/20"}`,children:C.label},C.value))})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Opacity"}),p.jsxs("span",{className:"text-[10px] text-zinc-400 font-mono",children:[((t.visualizationOpacity??.6)*100).toFixed(0),"%"]})]}),p.jsx("div",{className:"flex items-center gap-2 bg-zinc-800 border border-white/10 rounded-lg px-2 py-1.5",children:p.jsx("input",{type:"range",name:"viz-opacity","aria-label":"Visualization Opacity",min:"0.1",max:"1.0",step:"0.05",value:t.visualizationOpacity??.6,onChange:C=>U("visualizationOpacity",parseFloat(C.target.value)),className:"w-full h-1 bg-zinc-600 rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:rounded-full hover:[&::-webkit-slider-thumb]:bg-purple-400 transition-all"})})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Sensitivity"}),p.jsxs("span",{className:"text-[10px] text-zinc-400 font-mono",children:[(t.visualizationSensitivity??1.5).toFixed(1),"x"]})]}),p.jsx("div",{className:"flex items-center gap-2 bg-zinc-800 border border-white/10 rounded-lg px-2 py-1.5",children:p.jsx("input",{type:"range",name:"viz-sensitivity","aria-label":"Visualization Sensitivity",min:"0.5",max:"3.0",step:"0.1",value:t.visualizationSensitivity??1.5,onChange:C=>U("visualizationSensitivity",parseFloat(C.target.value)),className:"w-full h-1 bg-zinc-600 rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:rounded-full hover:[&::-webkit-slider-thumb]:bg-purple-400 transition-all"})})]}),["bars","circular","pulse-ring"].includes(t.visualizationType||"bars")&&p.jsxs("div",{className:"space-y-1.5",children:[p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:["circular","pulse-ring"].includes(t.visualizationType||"bars")?"Segments":"Bar Count"}),p.jsx("span",{className:"text-[10px] text-zinc-400 font-mono",children:t.visualizationBarCount??48})]}),p.jsx("div",{className:"flex items-center gap-2 bg-zinc-800 border border-white/10 rounded-lg px-2 py-1.5",children:p.jsx("input",{type:"range",name:"viz-bar-count","aria-label":"Visualization Bar Count",min:"16",max:"128",step:"4",value:t.visualizationBarCount??48,onChange:C=>U("visualizationBarCount",parseInt(C.target.value)),className:"w-full h-1 bg-zinc-600 rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:rounded-full hover:[&::-webkit-slider-thumb]:bg-purple-400 transition-all"})})]})]})]}),p.jsxs("section",{className:"space-y-3",children:[p.jsxs("h3",{className:"text-xs font-bold text-zinc-500 uppercase tracking-wider flex items-center gap-2",children:[p.jsx(Xf,{size:14})," Lyric Display Mode"]}),p.jsx(No,{value:t.lyricDisplayMode,onChange:C=>U("lyricDisplayMode",C),groups:P0})]}),p.jsxs("section",{className:"space-y-3",children:[p.jsxs("h3",{className:"text-xs font-bold text-zinc-500 uppercase tracking-wider flex items-center gap-2",children:[p.jsx(_0,{size:14})," Highlight Effect"]}),p.jsx(No,{value:t.highlightEffect||"none",onChange:C=>{U("highlightEffect",C)},groups:z0}),t.highlightEffect&&t.highlightEffect!=="none"&&p.jsxs("div",{className:"mt-2 space-y-2 animate-in slide-in-from-top-2",children:[p.jsxs("button",{onClick:()=>U("useCustomHighlightColors",!t.useCustomHighlightColors),className:`w-full flex items-center justify-between p-2 rounded-lg border text-xs font-medium transition-all ${t.useCustomHighlightColors?"bg-purple-900/30 border-purple-500/50 text-purple-200":"bg-zinc-800 border-white/5 text-zinc-400 hover:bg-zinc-700"}`,children:[p.jsx("span",{children:"Custom Colors"}),p.jsx("div",{className:`w-8 h-4 rounded-full p-0.5 transition-colors ${t.useCustomHighlightColors?"bg-purple-500":"bg-zinc-600"}`,children:p.jsx("div",{className:`w-3 h-3 bg-white rounded-full shadow-sm transition-transform ${t.useCustomHighlightColors?"translate-x-4":"translate-x-0"}`})})]}),t.useCustomHighlightColors&&p.jsxs("div",{className:"grid grid-cols-2 gap-3 animate-in fade-in duration-200",children:[p.jsxs("div",{className:"space-y-1",children:[p.jsx("span",{className:"text-[10px] text-zinc-400 font-bold uppercase",children:"Text/Glow Color"}),p.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800 p-1.5 rounded-lg border border-white/5",children:[p.jsx("input",{id:"highlight-color",type:"color",name:"highlight-color","aria-label":"Highlight Text Color",value:t.highlightColor||"#fb923c",onChange:C=>U("highlightColor",C.target.value),className:"w-8 h-6 rounded cursor-pointer bg-transparent border-none shrink-0"}),p.jsx("input",{id:"highlight-color-hex",type:"text",name:"highlight-color-hex","aria-label":"Highlight Text Color Hex",value:t.highlightColor||"#fb923c",onChange:C=>U("highlightColor",C.target.value),className:"bg-transparent border-none text-[10px] text-zinc-300 font-mono w-full focus:outline-none uppercase"})]})]}),p.jsxs("div",{className:"space-y-1",children:[p.jsx("span",{className:"text-[10px] text-zinc-400 font-bold uppercase",children:"Back/Shape Color"}),p.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800 p-1.5 rounded-lg border border-white/5",children:[p.jsx("input",{id:"highlight-bg-color",type:"color",name:"highlight-bg-color","aria-label":"Highlight Background Color",value:t.highlightBackground||"#fb923c",onChange:C=>U("highlightBackground",C.target.value),className:"w-8 h-6 rounded cursor-pointer bg-transparent border-none shrink-0"}),p.jsx("input",{id:"highlight-bg-hex",type:"text",name:"highlight-bg-hex","aria-label":"Highlight Background Color Hex",value:t.highlightBackground||"#fb923c",onChange:C=>U("highlightBackground",C.target.value),className:"bg-transparent border-none text-[10px] text-zinc-300 font-mono w-full focus:outline-none uppercase"})]})]})]})]})]}),p.jsxs("section",{className:"space-y-3",children:[p.jsxs("h3",{className:"text-xs font-bold text-zinc-500 uppercase tracking-wider flex items-center gap-2",children:[p.jsx(hA,{size:14})," Visible Elements"]}),p.jsx("div",{className:"space-y-2",children:[{label:"Lyrics / Subtitles",key:"showLyrics"},{label:"Song Title",key:"showTitle"},{label:"Artist Name",key:"showArtist"},{label:"Cover Art",key:"showCover"},{label:"Intro Info",key:"showIntro"}].map(C=>p.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg bg-zinc-800/30 border border-white/5 hover:bg-zinc-800/50 cursor-pointer transition-colors",children:[p.jsx("label",{htmlFor:C.key,className:"text-xs text-zinc-300 cursor-pointer w-full",children:C.label}),p.jsxs("div",{className:"relative inline-flex items-center cursor-pointer",children:[p.jsx("input",{type:"checkbox",id:C.key,name:C.key,"aria-label":C.label,checked:t[C.key],onChange:te=>U(C.key,te.target.checked),className:"sr-only peer"}),p.jsx("label",{htmlFor:C.key,className:"w-8 h-4 bg-zinc-700 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-3 after:w-3 after:transition-all peer-checked:bg-purple-600 block cursor-pointer"})]})]},C.key))})]}),p.jsxs("section",{className:"space-y-3",children:[p.jsxs("h3",{className:"text-xs font-bold text-zinc-500 uppercase tracking-wider flex items-center gap-2",children:[p.jsx(Qr,{size:14})," Intro Settings"]}),p.jsxs("div",{className:"bg-zinc-800/30 border border-white/5 rounded-lg p-3 space-y-3",children:[p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsx("span",{className:"text-xs text-zinc-300 font-medium",children:"Intro Text"}),p.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800 rounded-md p-1 border border-white/5",children:[p.jsx("button",{onClick:()=>U("introMode","auto"),className:`px-2 py-1 text-[10px] font-medium rounded transition-all ${t.introMode==="auto"?"bg-zinc-600 text-white shadow-sm":"text-zinc-400 hover:text-zinc-200"}`,children:"Auto"}),p.jsx("button",{onClick:()=>U("introMode","manual"),className:`px-2 py-1 text-[10px] font-medium rounded transition-all ${t.introMode==="manual"?"bg-purple-600 text-white shadow-sm":"text-zinc-400 hover:text-zinc-200"}`,children:"Manual"})]})]}),t.introMode==="manual"&&p.jsxs("div",{className:"space-y-1 animate-in slide-in-from-top-1 fade-in duration-200",children:[p.jsx("label",{htmlFor:"intro-text",className:"text-[10px] text-zinc-500 uppercase font-bold",children:"Custom Intro Content"}),p.jsx("textarea",{id:"intro-text",name:"intro-text","aria-label":"Intro Text",value:t.introText,onChange:C=>U("introText",C.target.value),placeholder:"Enter intro text...",className:"w-full bg-zinc-900 border border-white/10 rounded-md px-3 py-2 text-xs text-zinc-200 focus:outline-none focus:ring-1 focus:ring-purple-500 min-h-[60px]"})]})]})]}),p.jsxs("section",{className:"space-y-3",children:[p.jsxs("h3",{className:"text-xs font-bold text-zinc-500 uppercase tracking-wider flex items-center gap-2",children:[p.jsx(hb,{size:14})," Channel Info / Watermark"]}),p.jsxs("div",{className:"bg-zinc-800/30 border border-white/5 rounded-lg p-3 space-y-3",children:[p.jsxs("div",{className:"flex items-center justify-between cursor-pointer",children:[p.jsx("label",{htmlFor:"show-channel-info",className:"text-xs text-zinc-300 font-medium cursor-pointer",children:"Show Channel Info"}),p.jsxs("div",{className:"relative inline-flex items-center cursor-pointer",children:[p.jsx("input",{type:"checkbox",id:"show-channel-info",name:"show-channel-info","aria-label":"Show Channel Info",checked:t.showChannelInfo??!1,onChange:C=>U("showChannelInfo",C.target.checked),className:"sr-only peer"}),p.jsx("label",{htmlFor:"show-channel-info",className:"w-8 h-4 bg-zinc-700 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-3 after:w-3 after:transition-all peer-checked:bg-purple-600 block cursor-pointer"})]})]}),t.showChannelInfo&&p.jsxs("div",{className:"space-y-3 animate-in slide-in-from-top-1 fade-in duration-200 pt-2 border-t border-white/5",children:[p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("label",{htmlFor:"channel-image-upload",className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Channel Logo / Image"}),p.jsx("input",{ref:nt,type:"file",name:"channel-image-upload",id:"channel-image-upload",accept:"image/*",onChange:Pe,className:"hidden"}),t.channelInfoImage?p.jsxs("div",{className:"flex items-center gap-3 bg-zinc-800 p-2 rounded-lg border border-white/10",children:[p.jsx("div",{className:"w-10 h-10 rounded bg-zinc-700/50 flex items-center justify-center overflow-hidden border border-white/5",children:p.jsx("img",{src:t.channelInfoImage,alt:"Channel",className:"w-full h-full object-cover"})}),p.jsxs("div",{className:"flex-1 min-w-0",children:[p.jsx("p",{className:"text-xs text-zinc-300 truncate",children:"Image Loaded"}),p.jsx("button",{onClick:()=>U("channelInfoImage",void 0),className:"text-[10px] text-red-400 hover:text-red-300",children:"Remove"})]}),p.jsx("button",{onClick:()=>nt.current?.click(),className:"p-1.5 hover:bg-white/10 rounded-md text-zinc-400 hover:text-white",children:p.jsx(Gl,{size:14})})]}):p.jsxs("button",{onClick:()=>nt.current?.click(),className:"w-full flex items-center justify-center gap-2 bg-zinc-800/50 border border-dashed border-white/10 hover:border-purple-500/50 rounded-lg px-3 py-3 text-zinc-400 hover:text-purple-300 transition-colors",children:[p.jsx(cs,{size:14}),p.jsx("span",{className:"text-xs",children:"Upload Image"})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("label",{htmlFor:"channel-info-text",className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Channel Name / SVG Code"}),p.jsx("textarea",{id:"channel-info-text",name:"channel-info-text","aria-label":"Channel Info Text",value:t.channelInfoText??"",onChange:C=>U("channelInfoText",C.target.value),placeholder:"Display Name or ...",className:"w-full bg-zinc-900 border border-white/10 rounded-md px-3 py-2 text-xs text-zinc-200 focus:outline-none focus:ring-1 focus:ring-purple-500 min-h-[40px] resize-y font-mono",rows:2})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Position"}),p.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[p.jsx("button",{onClick:()=>U("channelInfoPosition","top-left"),className:`h-8 rounded-md border flex items-start justify-start p-1 transition-all ${t.channelInfoPosition==="top-left"?"bg-purple-600 border-purple-500 text-white":"bg-zinc-800 border-white/5 text-zinc-500 hover:border-white/20"}`,title:"Top Left",children:p.jsx("div",{className:"w-2 h-2 bg-current rounded-sm"})}),p.jsx("button",{onClick:()=>U("channelInfoPosition","top-center"),className:`h-8 rounded-md border flex items-start justify-center p-1 transition-all ${t.channelInfoPosition==="top-center"?"bg-purple-600 border-purple-500 text-white":"bg-zinc-800 border-white/5 text-zinc-500 hover:border-white/20"}`,title:"Top Center",children:p.jsx("div",{className:"w-2 h-2 bg-current rounded-sm"})}),p.jsx("button",{onClick:()=>U("channelInfoPosition","top-right"),className:`h-8 rounded-md border flex items-start justify-end p-1 transition-all ${t.channelInfoPosition==="top-right"?"bg-purple-600 border-purple-500 text-white":"bg-zinc-800 border-white/5 text-zinc-500 hover:border-white/20"}`,title:"Top Right",children:p.jsx("div",{className:"w-2 h-2 bg-current rounded-sm"})}),p.jsx("button",{onClick:()=>U("channelInfoPosition","bottom-left"),className:`h-8 rounded-md border flex items-end justify-start p-1 transition-all ${t.channelInfoPosition==="bottom-left"?"bg-purple-600 border-purple-500 text-white":"bg-zinc-800 border-white/5 text-zinc-500 hover:border-white/20"}`,title:"Bottom Left",children:p.jsx("div",{className:"w-2 h-2 bg-current rounded-sm"})}),p.jsx("button",{onClick:()=>U("channelInfoPosition","bottom-center"),className:`h-8 rounded-md border flex items-end justify-center p-1 transition-all ${t.channelInfoPosition==="bottom-center"?"bg-purple-600 border-purple-500 text-white":"bg-zinc-800 border-white/5 text-zinc-500 hover:border-white/20"}`,title:"Bottom Center",children:p.jsx("div",{className:"w-2 h-2 bg-current rounded-sm"})}),p.jsx("button",{onClick:()=>U("channelInfoPosition","bottom-right"),className:`h-8 rounded-md border flex items-end justify-end p-1 transition-all ${t.channelInfoPosition==="bottom-right"?"bg-purple-600 border-purple-500 text-white":"bg-zinc-800 border-white/5 text-zinc-500 hover:border-white/20"}`,title:"Bottom Right",children:p.jsx("div",{className:"w-2 h-2 bg-current rounded-sm"})})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Style"}),p.jsx(No,{value:t.channelInfoStyle||"classic",onChange:C=>U("channelInfoStyle",C),groups:o1})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Edge Margin"}),p.jsxs("span",{className:"text-[10px] text-zinc-400 font-mono",children:[(t.channelInfoMarginScale??1).toFixed(1),"x"]})]}),p.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800 border border-white/10 rounded-lg px-2 py-1.5",children:[p.jsx("span",{className:"text-zinc-500",children:p.jsx(Au,{size:12})}),p.jsx("input",{type:"range",name:"channel-margin","aria-label":"Channel Info Margin",min:"0.0",max:"5.0",step:"0.1",value:t.channelInfoMarginScale??1,onChange:C=>U("channelInfoMarginScale",parseFloat(C.target.value)),className:"w-full h-1 bg-zinc-600 rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:rounded-full hover:[&::-webkit-slider-thumb]:bg-purple-400 transition-all"})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Size"}),p.jsxs("span",{className:"text-[10px] text-zinc-400 font-mono",children:[(t.channelInfoSizeScale??1).toFixed(1),"x"]})]}),p.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800 border border-white/10 rounded-lg px-2 py-1.5",children:[p.jsx("span",{className:"text-zinc-500",children:p.jsx(Au,{size:12})}),p.jsx("input",{type:"range",name:"channel-size","aria-label":"Channel Info Size",min:"0.5",max:"3.0",step:"0.1",value:t.channelInfoSizeScale??1,onChange:C=>U("channelInfoSizeScale",parseFloat(C.target.value)),className:"w-full h-1 bg-zinc-600 rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:rounded-full hover:[&::-webkit-slider-thumb]:bg-purple-400 transition-all"})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Font Family"}),p.jsx(zm,{value:t.channelInfoFontFamily||"sans-serif",onChange:C=>U("channelInfoFontFamily",C),customFontName:P||null,groups:$}),p.jsx(km,{onApply:C=>Ce(C,"channelInfoFontFamily"),placeholder:"Channel Font (e.g. Oswald)"}),p.jsx("input",{"aria-label":"Upload Channel Font",ref:oe,type:"file",name:"channel-font-upload",id:"channel-font-upload",accept:".ttf,.otf,.woff,.woff2",onChange:J,className:"hidden"}),P?p.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800/50 border border-purple-500/30 rounded-lg px-2 py-1.5 mt-1",children:[p.jsx("span",{className:"text-[10px] text-purple-300 font-medium truncate flex-1",children:P}),p.jsx("button",{onClick:()=>U("channelInfoFontFamily","ChannelFont"),className:`text-[10px] px-2 py-0.5 rounded transition-colors ${t.channelInfoFontFamily==="ChannelFont"?"bg-purple-600 text-white":"bg-zinc-700 text-zinc-300 hover:bg-zinc-600"}`,children:"Use"}),p.jsx("button",{onClick:ve,className:"text-zinc-500 hover:text-red-400",children:p.jsx(Ql,{size:12})})]}):p.jsxs("button",{onClick:()=>oe.current?.click(),className:"w-full flex items-center justify-center gap-2 bg-zinc-800/30 border border-dashed border-white/10 hover:border-purple-500/50 rounded-lg px-2 py-1.5 text-zinc-500 hover:text-purple-300 transition-colors mt-1",children:[p.jsx(cs,{size:10}),p.jsx("span",{className:"text-[10px]",children:"Upload Font"})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Font Style"}),p.jsxs("div",{className:"flex bg-zinc-800 rounded-lg p-1 gap-1",children:[p.jsx("button",{onClick:()=>U("channelInfoFontWeight",t.channelInfoFontWeight==="bold"?"normal":"bold"),className:`flex-1 py-1.5 rounded-md flex items-center justify-center transition-all ${t.channelInfoFontWeight==="bold"?"bg-zinc-600 text-white shadow-sm":"text-zinc-500 hover:text-zinc-300"}`,title:"Bold",children:p.jsx(Nm,{size:14})}),p.jsx("button",{onClick:()=>U("channelInfoFontStyle",t.channelInfoFontStyle==="italic"?"normal":"italic"),className:`flex-1 py-1.5 rounded-md flex items-center justify-center transition-all ${t.channelInfoFontStyle==="italic"?"bg-zinc-600 text-white shadow-sm":"text-zinc-500 hover:text-zinc-300"}`,title:"Italic",children:p.jsx(Im,{size:14})})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Text Color"}),p.jsxs("div",{className:"flex items-center gap-3 bg-zinc-800/30 p-2 rounded-lg border border-white/5",children:[p.jsx("input",{id:"channel-font-color",type:"color",name:"channel-font-color","aria-label":"Channel Font Color",value:t.channelInfoFontColor||"#ffffff",onChange:C=>U("channelInfoFontColor",C.target.value),className:"w-6 h-6 rounded cursor-pointer bg-transparent border-none shrink-0"}),p.jsx("span",{className:"text-[10px] text-zinc-400 font-mono uppercase",children:t.channelInfoFontColor||"#ffffff"})]})]})]})]})]}),p.jsxs("section",{className:"space-y-3",children:[p.jsxs("h3",{className:"text-xs font-bold text-zinc-500 uppercase tracking-wider flex items-center gap-2",children:[p.jsx($l,{size:14})," Song Info Design"]}),p.jsxs("div",{className:"space-y-3",children:[p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Position"}),p.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[p.jsx("button",{onClick:()=>U("infoPosition","top-left"),className:`h-8 rounded-md border flex items-start justify-start p-1 transition-all ${t.infoPosition==="top-left"?"bg-purple-600 border-purple-500 text-white":"bg-zinc-800 border-white/5 text-zinc-500 hover:border-white/20"}`,children:p.jsx("div",{className:"w-2 h-2 bg-current rounded-sm"})}),p.jsx("button",{onClick:()=>U("infoPosition","top-center"),className:`h-8 rounded-md border flex items-start justify-center p-1 transition-all ${t.infoPosition==="top-center"?"bg-purple-600 border-purple-500 text-white":"bg-zinc-800 border-white/5 text-zinc-500 hover:border-white/20"}`,children:p.jsx("div",{className:"w-2 h-2 bg-current rounded-sm"})}),p.jsx("button",{onClick:()=>U("infoPosition","top-right"),className:`h-8 rounded-md border flex items-start justify-end p-1 transition-all ${t.infoPosition==="top-right"?"bg-purple-600 border-purple-500 text-white":"bg-zinc-800 border-white/5 text-zinc-500 hover:border-white/20"}`,children:p.jsx("div",{className:"w-2 h-2 bg-current rounded-sm"})}),p.jsx("button",{onClick:()=>U("infoPosition","bottom-left"),className:`h-8 rounded-md border flex items-end justify-start p-1 transition-all ${t.infoPosition==="bottom-left"?"bg-purple-600 border-purple-500 text-white":"bg-zinc-800 border-white/5 text-zinc-500 hover:border-white/20"}`,children:p.jsx("div",{className:"w-2 h-2 bg-current rounded-sm"})}),p.jsx("button",{onClick:()=>U("infoPosition","bottom-center"),className:`h-8 rounded-md border flex items-end justify-center p-1 transition-all ${t.infoPosition==="bottom-center"?"bg-purple-600 border-purple-500 text-white":"bg-zinc-800 border-white/5 text-zinc-500 hover:border-white/20"}`,children:p.jsx("div",{className:"w-2 h-2 bg-current rounded-sm"})}),p.jsx("button",{onClick:()=>U("infoPosition","bottom-right"),className:`h-8 rounded-md border flex items-end justify-end p-1 transition-all ${t.infoPosition==="bottom-right"?"bg-purple-600 border-purple-500 text-white":"bg-zinc-800 border-white/5 text-zinc-500 hover:border-white/20"}`,children:p.jsx("div",{className:"w-2 h-2 bg-current rounded-sm"})})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Style"}),p.jsx(No,{value:t.infoStyle||"classic",onChange:C=>U("infoStyle",C),groups:i1})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Edge Margin"}),p.jsxs("span",{className:"text-[10px] text-zinc-400 font-mono",children:[(t.infoMarginScale??1).toFixed(1),"x"]})]}),p.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800 border border-white/10 rounded-lg px-2 py-1.5",children:[p.jsx("span",{className:"text-zinc-500",children:p.jsx(Au,{size:12})}),p.jsx("input",{type:"range",name:"info-margin","aria-label":"Song Info Margin",min:"0.0",max:"5.0",step:"0.1",value:t.infoMarginScale??1,onChange:C=>U("infoMarginScale",parseFloat(C.target.value)),className:"w-full h-1 bg-zinc-600 rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:rounded-full hover:[&::-webkit-slider-thumb]:bg-purple-400 transition-all"})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Info Size"}),p.jsxs("span",{className:"text-[10px] text-zinc-400 font-mono",children:[(t.infoSizeScale??1).toFixed(1),"x"]})]}),p.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800 border border-white/10 rounded-lg px-2 py-1.5",children:[p.jsx("span",{className:"text-zinc-500",children:p.jsx(Qr,{size:12})}),p.jsx("input",{type:"range",name:"info-size","aria-label":"Song Info Size",min:"0.5",max:"3.0",step:"0.1",value:t.infoSizeScale??1,onChange:C=>U("infoSizeScale",parseFloat(C.target.value)),className:"w-full h-1 bg-zinc-600 rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:rounded-full hover:[&::-webkit-slider-thumb]:bg-purple-400 transition-all"})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Font Family"}),p.jsx(zm,{value:t.infoFontFamily||"sans-serif",onChange:C=>U("infoFontFamily",C),customFontName:fe||null,groups:$}),p.jsx(km,{onApply:C=>Ce(C,"infoFontFamily"),placeholder:"Info Font (e.g. Roboto)"}),p.jsx("input",{"aria-label":"Upload Info Font",ref:Ie,type:"file",name:"info-font-upload",id:"info-font-upload",accept:".ttf,.otf,.woff,.woff2",onChange:Ee,className:"hidden"}),fe?p.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800/50 border border-purple-500/30 rounded-lg px-2 py-1.5 mt-1",children:[p.jsx("span",{className:"text-[10px] text-purple-300 font-medium truncate flex-1",children:fe}),p.jsx("button",{onClick:()=>U("infoFontFamily","InfoFont"),className:`text-[10px] px-2 py-0.5 rounded transition-colors ${t.infoFontFamily==="InfoFont"?"bg-purple-600 text-white":"bg-zinc-700 text-zinc-300 hover:bg-zinc-600"}`,children:"Use"}),p.jsx("button",{onClick:je,className:"text-zinc-500 hover:text-red-400",children:p.jsx(Ql,{size:12})})]}):p.jsxs("button",{onClick:()=>Ie.current?.click(),className:"w-full flex items-center justify-center gap-2 bg-zinc-800/30 border border-dashed border-white/10 hover:border-purple-500/50 rounded-lg px-2 py-1.5 text-zinc-500 hover:text-purple-300 transition-colors mt-1",children:[p.jsx(cs,{size:10}),p.jsx("span",{className:"text-[10px]",children:"Upload Font"})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Font Style"}),p.jsxs("div",{className:"flex bg-zinc-800 rounded-lg p-1 gap-1",children:[p.jsx("button",{onClick:()=>U("infoFontWeight",t.infoFontWeight==="bold"?"normal":"bold"),className:`flex-1 py-1.5 rounded-md flex items-center justify-center transition-all ${t.infoFontWeight==="bold"?"bg-zinc-600 text-white shadow-sm":"text-zinc-500 hover:text-zinc-300"}`,title:"Bold",children:p.jsx(Nm,{size:14})}),p.jsx("button",{onClick:()=>U("infoFontStyle",t.infoFontStyle==="italic"?"normal":"italic"),className:`flex-1 py-1.5 rounded-md flex items-center justify-center transition-all ${t.infoFontStyle==="italic"?"bg-zinc-600 text-white shadow-sm":"text-zinc-500 hover:text-zinc-300"}`,title:"Italic",children:p.jsx(Im,{size:14})})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Text Color"}),p.jsxs("div",{className:"flex items-center gap-3 bg-zinc-800/30 p-2 rounded-lg border border-white/5",children:[p.jsx("input",{id:"info-font-color",type:"color",name:"info-font-color","aria-label":"Song Info Text Color",value:t.infoFontColor||"#ffffff",onChange:C=>U("infoFontColor",C.target.value),className:"w-6 h-6 rounded cursor-pointer bg-transparent border-none shrink-0"}),p.jsx("span",{className:"text-[10px] text-zinc-400 font-mono uppercase",children:t.infoFontColor||"#ffffff"})]})]})]})]}),p.jsxs("section",{className:"space-y-3",children:[p.jsxs("h3",{className:"text-xs font-bold text-zinc-500 uppercase tracking-wider flex items-center gap-2",children:[p.jsx(Qr,{size:14})," Typography & Style"]}),p.jsxs("div",{className:"space-y-4 pt-1",children:[p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Alignment"}),p.jsx("div",{className:"flex bg-zinc-800 rounded-lg p-1",children:["left","center","right"].map(C=>p.jsx("button",{onClick:()=>U("textAlign",C),className:`flex-1 py-1.5 rounded-md text-[10px] font-bold uppercase transition-all ${t.textAlign===C?"bg-zinc-600 text-white shadow-sm":"text-zinc-500 hover:text-zinc-300"}`,children:C},C))})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Vertical Position"}),p.jsxs("div",{className:"flex bg-zinc-800 rounded-lg p-1 gap-1",children:[p.jsx("button",{onClick:()=>U("contentPosition","top"),className:`flex-1 py-1.5 rounded-md flex items-center justify-center transition-all ${t.contentPosition==="top"?"bg-zinc-600 text-white shadow-sm":"text-zinc-500 hover:text-zinc-300"}`,title:"Top",children:p.jsx(wC,{size:14})}),p.jsx("button",{onClick:()=>U("contentPosition","center"),className:`flex-1 py-1.5 rounded-md flex items-center justify-center transition-all ${t.contentPosition==="center"?"bg-zinc-600 text-white shadow-sm":"text-zinc-500 hover:text-zinc-300"}`,title:"Center",children:p.jsx(db,{size:14})}),p.jsx("button",{onClick:()=>U("contentPosition","bottom"),className:`flex-1 py-1.5 rounded-md flex items-center justify-center transition-all ${t.contentPosition==="bottom"?"bg-zinc-600 text-white shadow-sm":"text-zinc-500 hover:text-zinc-300"}`,title:"Bottom",children:p.jsx(TC,{size:14})})]}),p.jsxs("div",{className:"grid grid-cols-2 gap-3 mt-2",children:[p.jsxs("div",{className:"space-y-1.5",children:[p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Top Margin"}),p.jsxs("span",{className:"text-[10px] text-zinc-400 font-mono",children:[(t.marginTopScale??1).toFixed(1),"x"]})]}),p.jsx("div",{className:"flex items-center gap-2 bg-zinc-800 border border-white/10 rounded-lg px-2 py-1.5",children:p.jsx("input",{type:"range",name:"margin-top","aria-label":"Lyrics Top Margin",min:"0.0",max:"5.0",step:"0.1",value:t.marginTopScale??1,onChange:C=>U("marginTopScale",parseFloat(C.target.value)),className:"w-full h-1 bg-zinc-600 rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:rounded-full hover:[&::-webkit-slider-thumb]:bg-purple-400 transition-all"})})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Bottom Margin"}),p.jsxs("span",{className:"text-[10px] text-zinc-400 font-mono",children:[(t.marginBottomScale??1).toFixed(1),"x"]})]}),p.jsx("div",{className:"flex items-center gap-2 bg-zinc-800 border border-white/10 rounded-lg px-2 py-1.5",children:p.jsx("input",{type:"range",name:"margin-bottom","aria-label":"Lyrics Bottom Margin",min:"0.0",max:"5.0",step:"0.1",value:t.marginBottomScale??1,onChange:C=>U("marginBottomScale",parseFloat(C.target.value)),className:"w-full h-1 bg-zinc-600 rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:rounded-full hover:[&::-webkit-slider-thumb]:bg-purple-400 transition-all"})})]})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Style"}),p.jsxs("div",{className:"flex bg-zinc-800 rounded-lg p-1 gap-1",children:[p.jsx("button",{onClick:()=>U("fontWeight",t.fontWeight==="bold"?"normal":"bold"),className:`flex-1 py-1.5 rounded-md flex items-center justify-center transition-all ${t.fontWeight==="bold"?"bg-zinc-600 text-white shadow-sm":"text-zinc-500 hover:text-zinc-300"}`,title:"Bold",children:p.jsx(Nm,{size:14})}),p.jsx("button",{onClick:()=>U("fontStyle",t.fontStyle==="italic"?"normal":"italic"),className:`flex-1 py-1.5 rounded-md flex items-center justify-center transition-all ${t.fontStyle==="italic"?"bg-zinc-600 text-white shadow-sm":"text-zinc-500 hover:text-zinc-300"}`,title:"Italic",children:p.jsx(Im,{size:14})}),p.jsx("button",{onClick:()=>U("textDecoration",t.textDecoration==="underline"?"none":"underline"),className:`flex-1 py-1.5 rounded-md flex items-center justify-center transition-all ${t.textDecoration==="underline"?"bg-zinc-600 text-white shadow-sm":"text-zinc-500 hover:text-zinc-300"}`,title:"Underline",children:p.jsx($A,{size:14})}),p.jsx("button",{onClick:()=>U("textDecoration",t.textDecoration==="line-through"?"none":"line-through"),className:`flex-1 py-1.5 rounded-md flex items-center justify-center transition-all ${t.textDecoration==="line-through"?"bg-zinc-600 text-white shadow-sm":"text-zinc-500 hover:text-zinc-300"}`,title:"Strikethrough",children:p.jsx(VA,{size:14})})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Apply Style To"}),p.jsxs("div",{className:"flex bg-zinc-800 rounded-lg p-1 gap-1",children:[p.jsx("button",{onClick:()=>U("lyricStyleTarget","active-only"),className:`flex-1 py-1.5 rounded-md text-[10px] transition-all ${t.lyricStyleTarget==="active-only"||!t.lyricStyleTarget?"bg-zinc-600 text-white shadow-sm font-bold":"text-zinc-500 hover:text-zinc-300"}`,title:"Apply style to current line only (others normal)",children:"Current Only"}),p.jsx("button",{onClick:()=>U("lyricStyleTarget","all"),className:`flex-1 py-1.5 rounded-md text-[10px] transition-all ${t.lyricStyleTarget==="all"?"bg-zinc-600 text-white shadow-sm font-bold":"text-zinc-500 hover:text-zinc-300"}`,title:"Apply style to all lines (previous, current, next)",children:"All Lines"})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Text Case"}),p.jsxs("div",{className:"grid grid-cols-3 gap-1 bg-zinc-800 rounded-lg p-1",children:[p.jsx("button",{onClick:()=>U("textCase","none"),className:`py-1.5 rounded-md text-[10px] transition-all ${t.textCase==="none"?"bg-zinc-600 text-white shadow-sm font-bold":"text-zinc-500 hover:text-zinc-300"}`,children:"Normal"}),p.jsx("button",{onClick:()=>U("textCase","upper"),className:`py-1.5 rounded-md text-[10px] uppercase transition-all ${t.textCase==="upper"?"bg-zinc-600 text-white shadow-sm font-bold":"text-zinc-500 hover:text-zinc-300"}`,children:"Upper"}),p.jsx("button",{onClick:()=>U("textCase","lower"),className:`py-1.5 rounded-md text-[10px] lowercase transition-all ${t.textCase==="lower"?"bg-zinc-600 text-white shadow-sm font-bold":"text-zinc-500 hover:text-zinc-300"}`,children:"Lower"}),p.jsx("button",{onClick:()=>U("textCase","title"),className:`py-1.5 rounded-md text-[10px] capitalize transition-all ${t.textCase==="title"?"bg-zinc-600 text-white shadow-sm font-bold":"text-zinc-500 hover:text-zinc-300"}`,children:"Title Case"}),p.jsx("button",{onClick:()=>U("textCase","sentence"),className:`py-1.5 rounded-md text-[10px] transition-all ${t.textCase==="sentence"?"bg-zinc-600 text-white shadow-sm font-bold":"text-zinc-500 hover:text-zinc-300"}`,children:"Sentence case"}),p.jsx("button",{onClick:()=>U("textCase","invert"),className:`py-1.5 rounded-md text-[10px] transition-all ${t.textCase==="invert"?"bg-zinc-600 text-white shadow-sm font-bold":"text-zinc-500 hover:text-zinc-300"}`,children:"Invert Case"})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Font Family"}),p.jsx(zm,{value:t.fontFamily,onChange:C=>U("fontFamily",C),customFontName:h,groups:$}),p.jsx(km,{onApply:C=>Ce(C,"fontFamily"),placeholder:"Lyrics Font (e.g. Pacifico)"})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("label",{htmlFor:"main-font-upload",className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Custom Font File"}),p.jsx("input",{ref:Xe,type:"file",name:"main-font-upload",id:"main-font-upload",accept:".ttf,.otf,.woff,.woff2",onChange:d,className:"hidden"}),h?p.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800/50 border border-purple-500/30 rounded-lg px-3 py-2",children:[p.jsx(Qr,{size:14,className:"text-purple-400 shrink-0"}),p.jsx("span",{className:"text-xs text-purple-300 font-medium truncate flex-1",children:h}),p.jsx("button",{onClick:()=>{U("fontFamily","CustomFont")},className:`text-[10px] px-2 py-1 rounded transition-colors ${t.fontFamily==="CustomFont"?"bg-purple-600 text-white":"bg-zinc-700 text-zinc-300 hover:bg-zinc-600"}`,children:t.fontFamily==="CustomFont"?"Active":"Use"}),p.jsx("button",{onClick:g,className:"p-1 text-zinc-500 hover:text-red-400 transition-colors",title:"Remove custom font",children:p.jsx(Ql,{size:14})})]}):p.jsxs("button",{onClick:()=>Xe.current?.click(),className:"w-full flex items-center justify-center gap-2 bg-zinc-800/50 border border-dashed border-white/10 hover:border-purple-500/50 rounded-lg px-3 py-2.5 text-zinc-400 hover:text-purple-300 transition-colors",children:[p.jsx(cs,{size:14}),p.jsx("span",{className:"text-xs",children:"Upload Custom Font (.ttf, .otf, .woff2)"})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Font Size"}),p.jsxs("span",{className:"text-[10px] text-zinc-400 font-mono",children:[(t.fontSizeScale*100).toFixed(0),"%"]})]}),p.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800 border border-white/10 rounded-lg px-2 py-1.5",children:[p.jsx("span",{className:"text-zinc-500",children:p.jsx(Qr,{size:12})}),p.jsx("input",{type:"range",name:"font-size","aria-label":"Font Size",min:"0.1",max:"3.0",step:"0.1",value:t.fontSizeScale,onChange:C=>U("fontSizeScale",parseFloat(C.target.value)),className:"w-full h-1 bg-zinc-600 rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:rounded-full hover:[&::-webkit-slider-thumb]:bg-purple-400 transition-all"}),p.jsx("span",{className:"text-zinc-300",children:p.jsx(Qr,{size:16})})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Current Line Height"}),p.jsxs("span",{className:"text-[10px] text-zinc-400 font-mono",children:[(t.lyricLineHeight||1.3).toFixed(1),"x"]})]}),p.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800 border border-white/10 rounded-lg px-2 py-1.5",children:[p.jsx("span",{className:"text-zinc-500",children:p.jsx(db,{size:12})}),p.jsx("input",{type:"range",name:"line-height","aria-label":"Line Height",min:"1.0",max:"3.0",step:"0.1",value:t.lyricLineHeight||1.3,onChange:C=>U("lyricLineHeight",parseFloat(C.target.value)),className:"w-full h-1 bg-zinc-600 rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:rounded-full hover:[&::-webkit-slider-thumb]:bg-purple-400 transition-all"})]})]}),t.fontFamily!=="sans-serif"&&t.fontFamily!=="CustomFont"&&p.jsx("div",{className:"text-[10px] text-zinc-500 bg-zinc-800/30 p-2 rounded border border-white/5",children:"Some presets like Gothic, Metal, or Tech use specific fonts. Changing Font Family here might override that look."}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Color"}),p.jsxs("div",{className:"flex items-center gap-3 bg-zinc-800/30 p-2 rounded-lg border border-white/5",children:[p.jsx("input",{id:"main-font-color",type:"color",name:"main-font-color","aria-label":"Main Font Color",value:t.fontColor,onChange:C=>U("fontColor",C.target.value),className:"w-8 h-8 rounded cursor-pointer bg-transparent border-none shrink-0"}),p.jsx("input",{id:"main-font-hex",type:"text",name:"main-font-hex","aria-label":"Main Font Color Hex",value:t.fontColor,onChange:C=>U("fontColor",C.target.value),className:"bg-transparent border-b border-zinc-700 text-xs text-zinc-300 font-mono flex-1 focus:outline-none focus:border-purple-500 uppercase py-1"})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Text Effect"}),p.jsx(No,{value:t.textEffect,onChange:C=>U("textEffect",C),groups:ZS})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Text Animation"}),p.jsx(No,{value:t.textAnimation,onChange:C=>U("textAnimation",C),groups:QS})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Transition"}),p.jsx(No,{value:t.transitionEffect,onChange:C=>U("transitionEffect",C),groups:e1})]}),p.jsxs("div",{className:"space-y-1.5 pt-2 border-t border-white/5",children:[p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Visual Transition (Images/Video)"}),t.visualTransitionDuration&&p.jsxs("span",{className:"text-[10px] text-zinc-400 font-mono",children:[t.visualTransitionDuration.toFixed(1),"s"]})]}),p.jsxs("div",{className:"flex gap-2",children:[p.jsx("div",{className:"flex-1",children:p.jsx(No,{value:t.visualTransitionType||"none",onChange:C=>U("visualTransitionType",C),groups:t1})}),t.visualTransitionType&&t.visualTransitionType!=="none"&&p.jsx("div",{className:"w-1/3 flex items-center bg-zinc-800 border border-white/10 rounded-lg px-2",children:p.jsx("input",{type:"range",name:"transition-duration","aria-label":"Transition Duration",min:"0.1",max:"5.0",step:"0.1",value:t.visualTransitionDuration||1,onChange:C=>U("visualTransitionDuration",parseFloat(C.target.value)),className:"w-full h-1 bg-zinc-600 rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:rounded-full hover:[&::-webkit-slider-thumb]:bg-purple-400 transition-all"})})]})]}),p.jsxs("div",{className:"pt-2 border-t border-white/5 space-y-3",children:[p.jsxs("h3",{className:"text-xs font-bold text-zinc-500 uppercase tracking-wider flex items-center gap-2",children:[p.jsx(Ru,{size:14})," Output Settings"]}),p.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Resolution"}),p.jsxs("div",{className:"flex bg-zinc-800 rounded-lg p-1",children:[p.jsx("button",{onClick:()=>y("720p"),className:`flex-1 py-1 px-2 rounded-md text-[10px] font-bold transition-all ${v==="720p"?"bg-zinc-600 text-white shadow-sm":"text-zinc-500 hover:text-zinc-300"}`,children:"720p"}),p.jsx("button",{onClick:()=>y("1080p"),className:`flex-1 py-1 px-2 rounded-md text-[10px] font-bold transition-all ${v==="1080p"?"bg-purple-600 text-white shadow-sm":"text-zinc-500 hover:text-zinc-300"}`,children:"1080p"})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"FPS"}),p.jsx(No,{value:String(D),onChange:C=>W(parseInt(C)),groups:PU})]})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Aspect Ratio"}),p.jsx("div",{className:"grid grid-cols-4 gap-1",children:["16:9","9:16","1:1","4:5","3:4","4:3","2:3","3:2","1:2","2:1","20:9","21:9"].map(C=>p.jsx("button",{onClick:()=>T(C),className:`py-1.5 rounded-md text-[10px] font-mono transition-all border ${S===C?"bg-purple-600 border-purple-500 text-white":"bg-zinc-800 border-white/5 text-zinc-500 hover:bg-zinc-700 hover:text-zinc-300"}`,children:C},C))})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Render Engine"}),p.jsxs("div",{className:"flex bg-zinc-800 rounded-lg p-1 gap-1",children:[p.jsx("button",{onClick:()=>H("mediarecorder"),className:`flex-1 py-2 rounded-md text-[10px] font-bold uppercase transition-all ${V==="mediarecorder"?"bg-purple-600 text-white":"text-zinc-500 hover:text-zinc-300"}`,title:"Uses browser's MediaRecorder API. Renders in realtime while playing audio.",children:"Realtime"}),p.jsx("button",{onClick:()=>H("webcodecs"),className:`flex-1 py-2 rounded-md text-[10px] font-bold uppercase transition-all ${V==="webcodecs"?"bg-blue-600 text-white":"text-zinc-500 hover:text-zinc-300"}`,title:"Uses WebCodecs API. Hardware accelerated rendering. Fastest option.",children:"WebCodecs 🚀"}),p.jsx("button",{onClick:()=>H("ffmpeg"),className:`flex-1 py-2 rounded-md text-[10px] font-bold uppercase transition-all ${V==="ffmpeg"?"bg-orange-500 text-white":"text-zinc-500 hover:text-zinc-300"}`,title:"Uses FFmpeg WASM. Frame-by-frame rendering with professional codecs.",children:"FFmpeg ⚡"})]}),p.jsx("p",{className:"text-[9px] text-zinc-600 ml-1 leading-tight",children:V==="mediarecorder"?"Realtime recording. Fast but quality depends on browser.":V==="webcodecs"?"Hardware accelerated (GPU). Very fast export with simple MP4.":"Software rendering. High compatiblity but slower."})]}),V==="mediarecorder"&&p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Video Codec"}),p.jsx(No,{value:A,onChange:C=>E(C),groups:[{label:"Format",options:[{label:"Auto Select (Best)",value:"auto"},...w]}]})]}),V==="ffmpeg"&&p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"FFmpeg Codec"}),p.jsx("div",{className:"grid grid-cols-2 gap-1",children:[{label:"H.264",value:"h264",desc:"Best Compatibility"},{label:"H.265",value:"h265",desc:"Higher Quality"}].map(C=>p.jsxs("button",{onClick:()=>k(C.value),className:`py-2 px-2 rounded-md text-[10px] font-medium transition-all border text-left ${Q===C.value?"bg-orange-500 border-orange-400 text-white":"bg-zinc-800 border-white/5 text-zinc-400 hover:bg-zinc-700 hover:text-zinc-200"}`,title:C.desc,children:[p.jsx("div",{className:"font-bold",children:C.label}),p.jsx("div",{className:"text-[8px] opacity-75",children:C.desc})]},C.value))})]}),V==="webcodecs"&&p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Video Codec"}),p.jsx("div",{className:"p-2 bg-zinc-800/50 rounded border border-white/5 text-[10px] text-zinc-400",children:"H.264 / AAC (Hardware Accelerated)"})]}),p.jsxs("div",{className:"space-y-1.5",children:[p.jsx("span",{className:"text-[10px] text-zinc-500 font-bold uppercase ml-1",children:"Render Quality (Bitrate)"}),p.jsxs("div",{className:"flex bg-zinc-800 rounded-lg p-1",children:[p.jsx("button",{onClick:()=>L("low"),className:`flex-1 py-1.5 rounded-md text-[10px] font-bold uppercase transition-all ${I==="low"?"bg-zinc-600 text-white":"text-zinc-500 hover:text-zinc-300"}`,children:"Low"}),p.jsx("button",{onClick:()=>L("med"),className:`flex-1 py-1.5 rounded-md text-[10px] font-bold uppercase transition-all ${I==="med"?"bg-zinc-600 text-white":"text-zinc-500 hover:text-zinc-300"}`,children:"Medium"}),p.jsx("button",{onClick:()=>L("high"),className:`flex-1 py-1.5 rounded-md text-[10px] font-bold uppercase transition-all ${I==="high"?"bg-purple-600 text-white":"text-zinc-500 hover:text-zinc-300"}`,children:"High"})]})]})]}),p.jsxs("div",{className:"pt-2 border-t border-white/5 space-y-2",children:[p.jsxs("p",{className:"text-[10px] text-zinc-500 italic leading-relaxed",children:[p.jsx("span",{className:"text-purple-400 font-bold",children:"*Tip:"})," You can backup your current configuration using the ",p.jsx("span",{className:"text-zinc-300",children:"Export"})," button above."]}),p.jsxs("button",{onClick:()=>Oe(!0),className:"w-full flex items-center justify-center gap-2 bg-zinc-800/30 border border-white/5 hover:bg-zinc-800 hover:border-white/20 text-xs text-zinc-400 hover:text-white py-2 rounded-lg transition-all",children:[p.jsx(Yf,{size:14})," View Keyboard Shortcuts"]})]})]}),xe&&p.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/60 backdrop-blur-sm animate-in fade-in cursor-default",onClick:()=>Oe(!1),children:p.jsxs("div",{className:"no-minimal-mode-toggle bg-zinc-900 border border-white/10 rounded-xl shadow-2xl w-[480px] max-w-[90vw] overflow-hidden flex flex-col max-h-[85vh] animate-in slide-in-from-bottom-5",onClick:C=>C.stopPropagation(),children:[p.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-white/10 bg-zinc-800/50",children:[p.jsxs("h3",{className:"font-bold text-white flex items-center gap-2",children:[p.jsx(Yf,{size:18,className:"text-purple-400"}),"Keyboard Shortcuts"]}),p.jsx("button",{onClick:()=>Oe(!1),className:"p-1.5 hover:bg-white/10 rounded-full text-zinc-400 hover:text-white transition-colors",children:p.jsx(Wo,{size:18})})]}),p.jsxs("div",{className:"p-4 overflow-y-auto space-y-6 custom-scrollbar",children:[p.jsxs("div",{className:"space-y-3",children:[p.jsx("h4",{className:"text-xs font-bold text-zinc-500 uppercase tracking-wider",children:"Media Controls"}),p.jsxs("div",{className:"grid grid-cols-2 gap-2 text-sm",children:[p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Play / Pause"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"Space"})]}),p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Stop"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"S"})]}),p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Next Song"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"N"})]}),p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Prev Song"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"B"})]}),p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Repeat Mode"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"R"})]}),p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Mute / Unmute"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"M"})]})]})]}),p.jsxs("div",{className:"space-y-3",children:[p.jsx("h4",{className:"text-xs font-bold text-zinc-500 uppercase tracking-wider",children:"View & Appearance"}),p.jsxs("div",{className:"grid grid-cols-2 gap-2 text-sm",children:[p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Fullscreen"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"F"})]}),p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Playlist Mode"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"L"})]}),p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Timeline / Edit"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"T"})]}),p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Toggle Info"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"I"})]}),p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Toggle Player"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"P"})]}),p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Auto-Hide HUD"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"H"})]}),p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Minimal Mode"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"O"})]}),p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Lyric Display Mode"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"G"})]}),p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Text Case"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"C"})]}),p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Render Settings"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"D"})]})]})]}),p.jsxs("div",{className:"space-y-3",children:[p.jsx("h4",{className:"text-xs font-bold text-zinc-500 uppercase tracking-wider",children:"Visual Effects"}),p.jsxs("div",{className:"grid grid-cols-2 gap-2 text-sm",children:[p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Toggle Highlight On/Off"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"X"})]}),p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Cycle Next Highlight Effect"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"Z"})]})]})]}),p.jsxs("div",{className:"space-y-3",children:[p.jsx("h4",{className:"text-xs font-bold text-zinc-500 uppercase tracking-wider",children:"Adjustment & Export"}),p.jsxs("div",{className:"grid grid-cols-2 gap-2 text-sm",children:[p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Cycle Presets"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"J"})]}),p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Font Size"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"+ / -"})]}),p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Seek +/- 5s"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"Arrows"})]}),p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-zinc-300",children:"Scroll Lyrics"})," ",p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-400 font-mono text-[10px] border border-white/10",children:"Up/Down"})]}),p.jsxs("div",{className:"flex justify-between col-span-2 items-center bg-purple-900/20 p-2 rounded-lg border border-purple-500/20",children:[p.jsx("span",{className:"text-purple-300 font-medium",children:"Quick Export"}),p.jsxs("div",{className:"flex gap-1 items-center",children:[p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-300 font-mono text-[10px] border border-white/10",children:"Ctrl"}),p.jsx("span",{className:"text-zinc-500 text-[10px]",children:"+"}),p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-300 font-mono text-[10px] border border-white/10",children:"Shift"}),p.jsx("span",{className:"text-zinc-500 text-[10px]",children:"+"}),p.jsx("kbd",{className:"bg-zinc-800 px-1.5 py-0.5 rounded text-zinc-300 font-mono text-[10px] border border-white/10",children:"E"})]})]})]})]})]}),p.jsx("div",{className:"p-4 border-t border-white/10 bg-zinc-900/50 text-center",children:p.jsxs("p",{className:"text-[10px] text-zinc-500",children:["Press ",p.jsx("kbd",{className:"font-mono text-zinc-400",children:"Esc"})," to close"]})})]})})]}),p.jsxs("div",{className:"p-4 border-t border-white/10 bg-zinc-900/50 space-y-3",children:[p.jsxs("button",{onClick:u,className:"w-full py-2.5 rounded-lg bg-purple-600 hover:bg-purple-500 text-white font-bold text-sm shadow-lg shadow-purple-500/20 active:scale-95 transition-all flex items-center justify-center gap-2",children:[p.jsx(Ru,{size:16})," Start Render"]}),p.jsx("p",{className:"text-[10px] text-zinc-500 text-center leading-relaxed italic",children:"These settings will be applied to the final video. Ensure all sources are loaded correctly."})]})]})};function s1(t){const e=t.replace("#","");return[parseInt(e.substring(0,2),16)||0,parseInt(e.substring(2,4),16)||0,parseInt(e.substring(4,6),16)||0]}function HU(t,e,n,i,r,a,c,u){const h=e>1?t/(e-1):0;switch(i){case"rainbow":return`hsla(${(h*360+u*.05)%360}, 80%, ${55+n*15}%, ${c})`;case"accent":return`hsla(270, 80%, ${50+n*20}%, ${c})`;case"custom":{const[d,g,v]=s1(r),[y,S,T]=s1(a),A=Math.round(d+(y-d)*h),E=Math.round(g+(S-g)*h),w=Math.round(v+(T-v)*h);return`rgba(${A}, ${E}, ${w}, ${c})`}default:{const d=260+h*60,g=50+n*15;return`hsla(${d}, 75%, ${g}%, ${c})`}}}function hE(t){return{type:t.visualizationType||"bars",colorMode:t.visualizationColorMode||"gradient",color1:t.visualizationColor1||"#a855f7",color2:t.visualizationColor2||"#6366f1",opacity:t.visualizationOpacity??.6,position:t.visualizationPosition||"bottom",sensitivity:t.visualizationSensitivity??1.5,barCount:t.visualizationBarCount??48}}function pE(t,e,n,i,r,a,c){const{type:u,sensitivity:h,barCount:d}=a,v=GU(e)/255;t.save();const y=jU(a.position,i,r);switch(t.beginPath(),t.rect(y.x,y.y,y.w,y.h),t.clip(),u){case"bars":qU(t,e,y,a,c);break;case"wave":WU(t,n||e,y,a,c);break;case"circular":$U(t,e,y,a,c,v);break;case"particles":XU(t,e,y,a,c);break;case"pulse-ring":YU(t,e,n,y,a,c,v);break}t.restore()}function GU(t){let e=0;for(let n=0;n{const L=Math.sin(I*127.1+I*311.7)*43758.5453;return L-Math.floor(L)},A=Math.min(80,Math.floor(d*40+10));for(let I=0;In.x+n.w||Een.y+n.h)continue;const je=(1+H*3)*(1-k*.6),X=(1-k)*H*i.opacity*.6;X<.03||(t.globalAlpha=X,t.fillStyle=Es(i,V/e.length,1,H,r),t.beginPath(),t.arc(fe,Ee,je,0,Math.PI*2),t.fill())}const w=Math.min(15,Math.floor(v*8+3));for(let I=0;In.x+n.w||kn.y+n.h)continue;const P=1+Math.sin(c*3+W*10)*.3*v,J=(3+W*5)*P,ve=.08+v*.15;t.globalAlpha=ve*i.opacity;const fe=t.createRadialGradient(Q,k,0,Q,k,J),Ee=Es(i,L,1,.7,r);fe.addColorStop(0,Ee),fe.addColorStop(.5,Ee.replace(/[\d.]+\)$/,`${.3})`)),fe.addColorStop(1,Ee.replace(/[\d.]+\)$/,"0)")),t.fillStyle=fe,t.beginPath(),t.arc(Q,k,J,0,Math.PI*2),t.fill()}if(d>.5){const I=c*.8%1,L=I*Math.min(n.w,n.h)*.45,D=(1-I)*(d-.5)*i.opacity*.5;if(D>.03){const W=n.x+n.w/2,V=n.y+n.h/2;t.globalAlpha=D,t.beginPath(),t.arc(W,V,L,0,Math.PI*2),t.strokeStyle=Es(i,0,1,d,r),t.lineWidth=2+(1-I)*3,t.stroke()}}t.globalAlpha=1}function YU(t,e,n,i,r,a,c){const u=i.x+i.w/2,h=i.y+i.h/2,d=Math.min(i.w,i.h)*.4,g=3,v=a*.001;for(let y=0;y=0&&v=0&&v((!nf||nf.state==="closed")&&(nf=new(window.AudioContext||window.webkitAudioContext)),nf),kf=(t,e=sh())=>{if(Pm.has(t))return Pm.get(t);const n=e.createMediaElementSource(t);return Pm.set(t,n),n};let jo=null,Jl=null,zf=null,Tu=null,Eu=null;function JU(){try{Jl&&Jl.disconnect(),jo&&(jo.disconnect(),jo=null),zf=null,Tu=null,Eu=null}catch(t){console.warn("AudioVisualizer: disconnect failed",t)}}const KU=({audioElement:t,config:e,isPlaying:n})=>{const i=Ae.useRef(null),r=Ae.useRef(0),a=Ae.useRef(0);return Ae.useEffect(()=>{if(!t)return;const c=sh();if(!(zf===t&&jo)){try{jo=c.createAnalyser(),jo.fftSize=512,jo.smoothingTimeConstant=.8,zf!==t&&(Jl=kf(t,c)),Jl&&(Jl.disconnect(),Jl.connect(jo),jo.connect(c.destination));const u=jo.frequencyBinCount;Tu=new Uint8Array(u),Eu=new Uint8Array(u),zf=t}catch(u){console.warn("AudioVisualizer: Failed to connect audio context",u)}return()=>{}}},[t]),Ae.useEffect(()=>{const c=sh();n&&c&&c.state==="suspended"&&c.resume()},[n]),Ae.useEffect(()=>{if(!e.showVisualization)return;const c=i.current;if(!c)return;const u=c.getContext("2d",{alpha:!0});if(!u)return;let h=!0;const d=g=>{if(!h||(r.current=requestAnimationFrame(d),g-a.current<33))return;a.current=g;const v=c.getBoundingClientRect(),y=Math.min(window.devicePixelRatio||1,2),S=Math.round(v.width*y),T=Math.round(v.height*y);(c.width!==S||c.height!==T)&&(c.width=S,c.height=T);const A=v.width,E=v.height;if(u.setTransform(y,0,0,y,0,0),u.clearRect(0,0,A,E),!jo||!Tu||!Eu)return;jo.getByteFrequencyData(Tu);const w=hE(e),I=w.type==="wave"||w.type==="pulse-ring";I&&jo.getByteTimeDomainData(Eu),pE(u,Tu,I?Eu:null,A,E,w,g)};return r.current=requestAnimationFrame(d),()=>{h=!1,cancelAnimationFrame(r.current)}},[e.showVisualization,e.visualizationType,e.visualizationColorMode,e.visualizationColor1,e.visualizationColor2,e.visualizationOpacity,e.visualizationPosition,e.visualizationSensitivity,e.visualizationBarCount]),e.showVisualization?p.jsx("canvas",{ref:i,className:"absolute inset-0 w-full h-full pointer-events-none z-[5]"}):null};const ev="174",ZU=0,r1=1,QU=2,mE=1,ek=2,fr=3,sa=0,Do=1,$o=2,ia=0,nc=1,a1=2,l1=3,c1=4,tk=5,Oa=100,nk=101,ik=102,ok=103,sk=104,rk=200,ak=201,lk=202,ck=203,F0=204,O0=205,uk=206,dk=207,fk=208,hk=209,pk=210,mk=211,gk=212,vk=213,xk=214,B0=0,V0=1,H0=2,rc=3,G0=4,j0=5,q0=6,W0=7,gE=0,yk=1,_k=2,oa=0,bk=1,Sk=2,Tk=3,Ek=4,wk=5,Mk=6,Ck=7,vE=300,ac=301,lc=302,$0=303,X0=304,Mh=306,Y0=1e3,Va=1001,J0=1002,Jo=1003,Ak=1004,of=1005,Bs=1006,Fm=1007,Ha=1008,yr=1009,xE=1010,yE=1011,Pu=1012,tv=1013,qa=1014,Vs=1015,Bu=1016,nv=1017,iv=1018,cc=1020,_E=35902,bE=1021,SE=1022,ws=1023,TE=1024,EE=1025,ic=1026,uc=1027,ov=1028,sv=1029,wE=1030,rv=1031,av=1033,Pf=33776,Ff=33777,Of=33778,Bf=33779,K0=35840,Z0=35841,Q0=35842,eg=35843,tg=36196,ng=37492,ig=37496,og=37808,sg=37809,rg=37810,ag=37811,lg=37812,cg=37813,ug=37814,dg=37815,fg=37816,hg=37817,pg=37818,mg=37819,gg=37820,vg=37821,Vf=36492,xg=36494,yg=36495,ME=36283,_g=36284,bg=36285,Sg=36286,Rk=3200,Nk=3201,Ik=0,Dk=1,na="",ds="srgb",dc="srgb-linear",rh="linear",Qn="srgb",Al=7680,u1=519,Lk=512,Uk=513,kk=514,CE=515,zk=516,Pk=517,Fk=518,Ok=519,d1=35044,f1="300 es",mr=2e3,ah=2001;class xc{addEventListener(e,n){this._listeners===void 0&&(this._listeners={});const i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(n)===-1&&i[e].push(n)}hasEventListener(e,n){const i=this._listeners;return i===void 0?!1:i[e]!==void 0&&i[e].indexOf(n)!==-1}removeEventListener(e,n){const i=this._listeners;if(i===void 0)return;const r=i[e];if(r!==void 0){const a=r.indexOf(n);a!==-1&&r.splice(a,1)}}dispatchEvent(e){const n=this._listeners;if(n===void 0)return;const i=n[e.type];if(i!==void 0){e.target=this;const r=i.slice(0);for(let a=0,c=r.length;a>8&255]+mo[t>>16&255]+mo[t>>24&255]+"-"+mo[e&255]+mo[e>>8&255]+"-"+mo[e>>16&15|64]+mo[e>>24&255]+"-"+mo[n&63|128]+mo[n>>8&255]+"-"+mo[n>>16&255]+mo[n>>24&255]+mo[i&255]+mo[i>>8&255]+mo[i>>16&255]+mo[i>>24&255]).toLowerCase()}function Tn(t,e,n){return Math.max(e,Math.min(n,t))}function Bk(t,e){return(t%e+e)%e}function Bm(t,e,n){return(1-n)*t+n*e}function cu(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function Io(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(t*4294967295);case Uint16Array:return Math.round(t*65535);case Uint8Array:return Math.round(t*255);case Int32Array:return Math.round(t*2147483647);case Int16Array:return Math.round(t*32767);case Int8Array:return Math.round(t*127);default:throw new Error("Invalid component type.")}}class Bn{constructor(e=0,n=0){Bn.prototype.isVector2=!0,this.x=e,this.y=n}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,n){return this.x=e,this.y=n,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const n=this.x,i=this.y,r=e.elements;return this.x=r[0]*n+r[3]*i+r[6],this.y=r[1]*n+r[4]*i+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,n){return this.x=Tn(this.x,e.x,n.x),this.y=Tn(this.y,e.y,n.y),this}clampScalar(e,n){return this.x=Tn(this.x,e,n),this.y=Tn(this.y,e,n),this}clampLength(e,n){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Tn(i,e,n))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const n=Math.sqrt(this.lengthSq()*e.lengthSq());if(n===0)return Math.PI/2;const i=this.dot(e)/n;return Math.acos(Tn(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,i=this.y-e.y;return n*n+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this}lerpVectors(e,n,i){return this.x=e.x+(n.x-e.x)*i,this.y=e.y+(n.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this}rotateAround(e,n){const i=Math.cos(n),r=Math.sin(n),a=this.x-e.x,c=this.y-e.y;return this.x=a*i-c*r+e.x,this.y=a*r+c*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class an{constructor(e,n,i,r,a,c,u,h,d){an.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,n,i,r,a,c,u,h,d)}set(e,n,i,r,a,c,u,h,d){const g=this.elements;return g[0]=e,g[1]=r,g[2]=u,g[3]=n,g[4]=a,g[5]=h,g[6]=i,g[7]=c,g[8]=d,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const n=this.elements,i=e.elements;return n[0]=i[0],n[1]=i[1],n[2]=i[2],n[3]=i[3],n[4]=i[4],n[5]=i[5],n[6]=i[6],n[7]=i[7],n[8]=i[8],this}extractBasis(e,n,i){return e.setFromMatrix3Column(this,0),n.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const n=e.elements;return this.set(n[0],n[4],n[8],n[1],n[5],n[9],n[2],n[6],n[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,n){const i=e.elements,r=n.elements,a=this.elements,c=i[0],u=i[3],h=i[6],d=i[1],g=i[4],v=i[7],y=i[2],S=i[5],T=i[8],A=r[0],E=r[3],w=r[6],I=r[1],L=r[4],D=r[7],W=r[2],V=r[5],H=r[8];return a[0]=c*A+u*I+h*W,a[3]=c*E+u*L+h*V,a[6]=c*w+u*D+h*H,a[1]=d*A+g*I+v*W,a[4]=d*E+g*L+v*V,a[7]=d*w+g*D+v*H,a[2]=y*A+S*I+T*W,a[5]=y*E+S*L+T*V,a[8]=y*w+S*D+T*H,this}multiplyScalar(e){const n=this.elements;return n[0]*=e,n[3]*=e,n[6]*=e,n[1]*=e,n[4]*=e,n[7]*=e,n[2]*=e,n[5]*=e,n[8]*=e,this}determinant(){const e=this.elements,n=e[0],i=e[1],r=e[2],a=e[3],c=e[4],u=e[5],h=e[6],d=e[7],g=e[8];return n*c*g-n*u*d-i*a*g+i*u*h+r*a*d-r*c*h}invert(){const e=this.elements,n=e[0],i=e[1],r=e[2],a=e[3],c=e[4],u=e[5],h=e[6],d=e[7],g=e[8],v=g*c-u*d,y=u*h-g*a,S=d*a-c*h,T=n*v+i*y+r*S;if(T===0)return this.set(0,0,0,0,0,0,0,0,0);const A=1/T;return e[0]=v*A,e[1]=(r*d-g*i)*A,e[2]=(u*i-r*c)*A,e[3]=y*A,e[4]=(g*n-r*h)*A,e[5]=(r*a-u*n)*A,e[6]=S*A,e[7]=(i*h-d*n)*A,e[8]=(c*n-i*a)*A,this}transpose(){let e;const n=this.elements;return e=n[1],n[1]=n[3],n[3]=e,e=n[2],n[2]=n[6],n[6]=e,e=n[5],n[5]=n[7],n[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const n=this.elements;return e[0]=n[0],e[1]=n[3],e[2]=n[6],e[3]=n[1],e[4]=n[4],e[5]=n[7],e[6]=n[2],e[7]=n[5],e[8]=n[8],this}setUvTransform(e,n,i,r,a,c,u){const h=Math.cos(a),d=Math.sin(a);return this.set(i*h,i*d,-i*(h*c+d*u)+c+e,-r*d,r*h,-r*(-d*c+h*u)+u+n,0,0,1),this}scale(e,n){return this.premultiply(Vm.makeScale(e,n)),this}rotate(e){return this.premultiply(Vm.makeRotation(-e)),this}translate(e,n){return this.premultiply(Vm.makeTranslation(e,n)),this}makeTranslation(e,n){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,n,0,0,1),this}makeRotation(e){const n=Math.cos(e),i=Math.sin(e);return this.set(n,-i,0,i,n,0,0,0,1),this}makeScale(e,n){return this.set(e,0,0,0,n,0,0,0,1),this}equals(e){const n=this.elements,i=e.elements;for(let r=0;r<9;r++)if(n[r]!==i[r])return!1;return!0}fromArray(e,n=0){for(let i=0;i<9;i++)this.elements[i]=e[i+n];return this}toArray(e=[],n=0){const i=this.elements;return e[n]=i[0],e[n+1]=i[1],e[n+2]=i[2],e[n+3]=i[3],e[n+4]=i[4],e[n+5]=i[5],e[n+6]=i[6],e[n+7]=i[7],e[n+8]=i[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const Vm=new an;function AE(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}function lh(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function Vk(){const t=lh("canvas");return t.style.display="block",t}const h1={};function Na(t){t in h1||(h1[t]=!0,console.warn(t))}function Hk(t,e,n){return new Promise(function(i,r){function a(){switch(t.clientWaitSync(e,t.SYNC_FLUSH_COMMANDS_BIT,0)){case t.WAIT_FAILED:r();break;case t.TIMEOUT_EXPIRED:setTimeout(a,n);break;default:i()}}setTimeout(a,n)})}function Gk(t){const e=t.elements;e[2]=.5*e[2]+.5*e[3],e[6]=.5*e[6]+.5*e[7],e[10]=.5*e[10]+.5*e[11],e[14]=.5*e[14]+.5*e[15]}function jk(t){const e=t.elements;e[11]===-1?(e[10]=-e[10]-1,e[14]=-e[14]):(e[10]=-e[10],e[14]=-e[14]+1)}const p1=new an().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),m1=new an().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function qk(){const t={enabled:!0,workingColorSpace:dc,spaces:{},convert:function(r,a,c){return this.enabled===!1||a===c||!a||!c||(this.spaces[a].transfer===Qn&&(r.r=gr(r.r),r.g=gr(r.g),r.b=gr(r.b)),this.spaces[a].primaries!==this.spaces[c].primaries&&(r.applyMatrix3(this.spaces[a].toXYZ),r.applyMatrix3(this.spaces[c].fromXYZ)),this.spaces[c].transfer===Qn&&(r.r=oc(r.r),r.g=oc(r.g),r.b=oc(r.b))),r},fromWorkingColorSpace:function(r,a){return this.convert(r,this.workingColorSpace,a)},toWorkingColorSpace:function(r,a){return this.convert(r,a,this.workingColorSpace)},getPrimaries:function(r){return this.spaces[r].primaries},getTransfer:function(r){return r===na?rh:this.spaces[r].transfer},getLuminanceCoefficients:function(r,a=this.workingColorSpace){return r.fromArray(this.spaces[a].luminanceCoefficients)},define:function(r){Object.assign(this.spaces,r)},_getMatrix:function(r,a,c){return r.copy(this.spaces[a].toXYZ).multiply(this.spaces[c].fromXYZ)},_getDrawingBufferColorSpace:function(r){return this.spaces[r].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(r=this.workingColorSpace){return this.spaces[r].workingColorSpaceConfig.unpackColorSpace}},e=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],i=[.3127,.329];return t.define({[dc]:{primaries:e,whitePoint:i,transfer:rh,toXYZ:p1,fromXYZ:m1,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:ds},outputColorSpaceConfig:{drawingBufferColorSpace:ds}},[ds]:{primaries:e,whitePoint:i,transfer:Qn,toXYZ:p1,fromXYZ:m1,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:ds}}}),t}const kn=qk();function gr(t){return t<.04045?t*.0773993808:Math.pow(t*.9478672986+.0521327014,2.4)}function oc(t){return t<.0031308?t*12.92:1.055*Math.pow(t,.41666)-.055}let Rl;class Wk{static getDataURL(e){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{Rl===void 0&&(Rl=lh("canvas")),Rl.width=e.width,Rl.height=e.height;const i=Rl.getContext("2d");e instanceof ImageData?i.putImageData(e,0,0):i.drawImage(e,0,0,e.width,e.height),n=Rl}return n.toDataURL("image/png")}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const n=lh("canvas");n.width=e.width,n.height=e.height;const i=n.getContext("2d");i.drawImage(e,0,0,e.width,e.height);const r=i.getImageData(0,0,e.width,e.height),a=r.data;for(let c=0;c0&&(i.userData=this.userData),n||(e.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==vE)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Y0:e.x=e.x-Math.floor(e.x);break;case Va:e.x=e.x<0?0:1;break;case J0:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Y0:e.y=e.y-Math.floor(e.y);break;case Va:e.y=e.y<0?0:1;break;case J0:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}To.DEFAULT_IMAGE=null;To.DEFAULT_MAPPING=vE;To.DEFAULT_ANISOTROPY=1;class Ii{constructor(e=0,n=0,i=0,r=1){Ii.prototype.isVector4=!0,this.x=e,this.y=n,this.z=i,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,n,i,r){return this.x=e,this.y=n,this.z=i,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;case 2:this.z=n;break;case 3:this.w=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this.z=e.z+n.z,this.w=e.w+n.w,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this.z+=e.z*n,this.w+=e.w*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this.z=e.z-n.z,this.w=e.w-n.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const n=this.x,i=this.y,r=this.z,a=this.w,c=e.elements;return this.x=c[0]*n+c[4]*i+c[8]*r+c[12]*a,this.y=c[1]*n+c[5]*i+c[9]*r+c[13]*a,this.z=c[2]*n+c[6]*i+c[10]*r+c[14]*a,this.w=c[3]*n+c[7]*i+c[11]*r+c[15]*a,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const n=Math.sqrt(1-e.w*e.w);return n<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/n,this.y=e.y/n,this.z=e.z/n),this}setAxisAngleFromRotationMatrix(e){let n,i,r,a;const h=e.elements,d=h[0],g=h[4],v=h[8],y=h[1],S=h[5],T=h[9],A=h[2],E=h[6],w=h[10];if(Math.abs(g-y)<.01&&Math.abs(v-A)<.01&&Math.abs(T-E)<.01){if(Math.abs(g+y)<.1&&Math.abs(v+A)<.1&&Math.abs(T+E)<.1&&Math.abs(d+S+w-3)<.1)return this.set(1,0,0,0),this;n=Math.PI;const L=(d+1)/2,D=(S+1)/2,W=(w+1)/2,V=(g+y)/4,H=(v+A)/4,Q=(T+E)/4;return L>D&&L>W?L<.01?(i=0,r=.707106781,a=.707106781):(i=Math.sqrt(L),r=V/i,a=H/i):D>W?D<.01?(i=.707106781,r=0,a=.707106781):(r=Math.sqrt(D),i=V/r,a=Q/r):W<.01?(i=.707106781,r=.707106781,a=0):(a=Math.sqrt(W),i=H/a,r=Q/a),this.set(i,r,a,n),this}let I=Math.sqrt((E-T)*(E-T)+(v-A)*(v-A)+(y-g)*(y-g));return Math.abs(I)<.001&&(I=1),this.x=(E-T)/I,this.y=(v-A)/I,this.z=(y-g)/I,this.w=Math.acos((d+S+w-1)/2),this}setFromMatrixPosition(e){const n=e.elements;return this.x=n[12],this.y=n[13],this.z=n[14],this.w=n[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,n){return this.x=Tn(this.x,e.x,n.x),this.y=Tn(this.y,e.y,n.y),this.z=Tn(this.z,e.z,n.z),this.w=Tn(this.w,e.w,n.w),this}clampScalar(e,n){return this.x=Tn(this.x,e,n),this.y=Tn(this.y,e,n),this.z=Tn(this.z,e,n),this.w=Tn(this.w,e,n),this}clampLength(e,n){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Tn(i,e,n))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this.z+=(e.z-this.z)*n,this.w+=(e.w-this.w)*n,this}lerpVectors(e,n,i){return this.x=e.x+(n.x-e.x)*i,this.y=e.y+(n.y-e.y)*i,this.z=e.z+(n.z-e.z)*i,this.w=e.w+(n.w-e.w)*i,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this.z=e[n+2],this.w=e[n+3],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e[n+2]=this.z,e[n+3]=this.w,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this.z=e.getZ(n),this.w=e.getW(n),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class Yk extends xc{constructor(e=1,n=1,i={}){super(),this.isRenderTarget=!0,this.width=e,this.height=n,this.depth=1,this.scissor=new Ii(0,0,e,n),this.scissorTest=!1,this.viewport=new Ii(0,0,e,n);const r={width:e,height:n,depth:1};i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Bs,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1},i);const a=new To(r,i.mapping,i.wrapS,i.wrapT,i.magFilter,i.minFilter,i.format,i.type,i.anisotropy,i.colorSpace);a.flipY=!1,a.generateMipmaps=i.generateMipmaps,a.internalFormat=i.internalFormat,this.textures=[];const c=i.count;for(let u=0;u=0?1:-1,L=1-w*w;if(L>Number.EPSILON){const W=Math.sqrt(L),V=Math.atan2(W,w*I);E=Math.sin(E*V)/W,u=Math.sin(u*V)/W}const D=u*I;if(h=h*E+y*D,d=d*E+S*D,g=g*E+T*D,v=v*E+A*D,E===1-u){const W=1/Math.sqrt(h*h+d*d+g*g+v*v);h*=W,d*=W,g*=W,v*=W}}e[n]=h,e[n+1]=d,e[n+2]=g,e[n+3]=v}static multiplyQuaternionsFlat(e,n,i,r,a,c){const u=i[r],h=i[r+1],d=i[r+2],g=i[r+3],v=a[c],y=a[c+1],S=a[c+2],T=a[c+3];return e[n]=u*T+g*v+h*S-d*y,e[n+1]=h*T+g*y+d*v-u*S,e[n+2]=d*T+g*S+u*y-h*v,e[n+3]=g*T-u*v-h*y-d*S,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,n,i,r){return this._x=e,this._y=n,this._z=i,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,n=!0){const i=e._x,r=e._y,a=e._z,c=e._order,u=Math.cos,h=Math.sin,d=u(i/2),g=u(r/2),v=u(a/2),y=h(i/2),S=h(r/2),T=h(a/2);switch(c){case"XYZ":this._x=y*g*v+d*S*T,this._y=d*S*v-y*g*T,this._z=d*g*T+y*S*v,this._w=d*g*v-y*S*T;break;case"YXZ":this._x=y*g*v+d*S*T,this._y=d*S*v-y*g*T,this._z=d*g*T-y*S*v,this._w=d*g*v+y*S*T;break;case"ZXY":this._x=y*g*v-d*S*T,this._y=d*S*v+y*g*T,this._z=d*g*T+y*S*v,this._w=d*g*v-y*S*T;break;case"ZYX":this._x=y*g*v-d*S*T,this._y=d*S*v+y*g*T,this._z=d*g*T-y*S*v,this._w=d*g*v+y*S*T;break;case"YZX":this._x=y*g*v+d*S*T,this._y=d*S*v+y*g*T,this._z=d*g*T-y*S*v,this._w=d*g*v-y*S*T;break;case"XZY":this._x=y*g*v-d*S*T,this._y=d*S*v-y*g*T,this._z=d*g*T+y*S*v,this._w=d*g*v+y*S*T;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+c)}return n===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,n){const i=n/2,r=Math.sin(i);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){const n=e.elements,i=n[0],r=n[4],a=n[8],c=n[1],u=n[5],h=n[9],d=n[2],g=n[6],v=n[10],y=i+u+v;if(y>0){const S=.5/Math.sqrt(y+1);this._w=.25/S,this._x=(g-h)*S,this._y=(a-d)*S,this._z=(c-r)*S}else if(i>u&&i>v){const S=2*Math.sqrt(1+i-u-v);this._w=(g-h)/S,this._x=.25*S,this._y=(r+c)/S,this._z=(a+d)/S}else if(u>v){const S=2*Math.sqrt(1+u-i-v);this._w=(a-d)/S,this._x=(r+c)/S,this._y=.25*S,this._z=(h+g)/S}else{const S=2*Math.sqrt(1+v-i-u);this._w=(c-r)/S,this._x=(a+d)/S,this._y=(h+g)/S,this._z=.25*S}return this._onChangeCallback(),this}setFromUnitVectors(e,n){let i=e.dot(n)+1;return iMath.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=i):(this._x=0,this._y=-e.z,this._z=e.y,this._w=i)):(this._x=e.y*n.z-e.z*n.y,this._y=e.z*n.x-e.x*n.z,this._z=e.x*n.y-e.y*n.x,this._w=i),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Tn(this.dot(e),-1,1)))}rotateTowards(e,n){const i=this.angleTo(e);if(i===0)return this;const r=Math.min(1,n/i);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,n){const i=e._x,r=e._y,a=e._z,c=e._w,u=n._x,h=n._y,d=n._z,g=n._w;return this._x=i*g+c*u+r*d-a*h,this._y=r*g+c*h+a*u-i*d,this._z=a*g+c*d+i*h-r*u,this._w=c*g-i*u-r*h-a*d,this._onChangeCallback(),this}slerp(e,n){if(n===0)return this;if(n===1)return this.copy(e);const i=this._x,r=this._y,a=this._z,c=this._w;let u=c*e._w+i*e._x+r*e._y+a*e._z;if(u<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,u=-u):this.copy(e),u>=1)return this._w=c,this._x=i,this._y=r,this._z=a,this;const h=1-u*u;if(h<=Number.EPSILON){const S=1-n;return this._w=S*c+n*this._w,this._x=S*i+n*this._x,this._y=S*r+n*this._y,this._z=S*a+n*this._z,this.normalize(),this}const d=Math.sqrt(h),g=Math.atan2(d,u),v=Math.sin((1-n)*g)/d,y=Math.sin(n*g)/d;return this._w=c*v+this._w*y,this._x=i*v+this._x*y,this._y=r*v+this._y*y,this._z=a*v+this._z*y,this._onChangeCallback(),this}slerpQuaternions(e,n,i){return this.copy(e).slerp(n,i)}random(){const e=2*Math.PI*Math.random(),n=2*Math.PI*Math.random(),i=Math.random(),r=Math.sqrt(1-i),a=Math.sqrt(i);return this.set(r*Math.sin(e),r*Math.cos(e),a*Math.sin(n),a*Math.cos(n))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,n=0){return this._x=e[n],this._y=e[n+1],this._z=e[n+2],this._w=e[n+3],this._onChangeCallback(),this}toArray(e=[],n=0){return e[n]=this._x,e[n+1]=this._y,e[n+2]=this._z,e[n+3]=this._w,e}fromBufferAttribute(e,n){return this._x=e.getX(n),this._y=e.getY(n),this._z=e.getZ(n),this._w=e.getW(n),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class Le{constructor(e=0,n=0,i=0){Le.prototype.isVector3=!0,this.x=e,this.y=n,this.z=i}set(e,n,i){return i===void 0&&(i=this.z),this.x=e,this.y=n,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;case 2:this.z=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this.z=e.z+n.z,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this.z+=e.z*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this.z=e.z-n.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,n){return this.x=e.x*n.x,this.y=e.y*n.y,this.z=e.z*n.z,this}applyEuler(e){return this.applyQuaternion(g1.setFromEuler(e))}applyAxisAngle(e,n){return this.applyQuaternion(g1.setFromAxisAngle(e,n))}applyMatrix3(e){const n=this.x,i=this.y,r=this.z,a=e.elements;return this.x=a[0]*n+a[3]*i+a[6]*r,this.y=a[1]*n+a[4]*i+a[7]*r,this.z=a[2]*n+a[5]*i+a[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const n=this.x,i=this.y,r=this.z,a=e.elements,c=1/(a[3]*n+a[7]*i+a[11]*r+a[15]);return this.x=(a[0]*n+a[4]*i+a[8]*r+a[12])*c,this.y=(a[1]*n+a[5]*i+a[9]*r+a[13])*c,this.z=(a[2]*n+a[6]*i+a[10]*r+a[14])*c,this}applyQuaternion(e){const n=this.x,i=this.y,r=this.z,a=e.x,c=e.y,u=e.z,h=e.w,d=2*(c*r-u*i),g=2*(u*n-a*r),v=2*(a*i-c*n);return this.x=n+h*d+c*v-u*g,this.y=i+h*g+u*d-a*v,this.z=r+h*v+a*g-c*d,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const n=this.x,i=this.y,r=this.z,a=e.elements;return this.x=a[0]*n+a[4]*i+a[8]*r,this.y=a[1]*n+a[5]*i+a[9]*r,this.z=a[2]*n+a[6]*i+a[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,n){return this.x=Tn(this.x,e.x,n.x),this.y=Tn(this.y,e.y,n.y),this.z=Tn(this.z,e.z,n.z),this}clampScalar(e,n){return this.x=Tn(this.x,e,n),this.y=Tn(this.y,e,n),this.z=Tn(this.z,e,n),this}clampLength(e,n){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Tn(i,e,n))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this.z+=(e.z-this.z)*n,this}lerpVectors(e,n,i){return this.x=e.x+(n.x-e.x)*i,this.y=e.y+(n.y-e.y)*i,this.z=e.z+(n.z-e.z)*i,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,n){const i=e.x,r=e.y,a=e.z,c=n.x,u=n.y,h=n.z;return this.x=r*h-a*u,this.y=a*c-i*h,this.z=i*u-r*c,this}projectOnVector(e){const n=e.lengthSq();if(n===0)return this.set(0,0,0);const i=e.dot(this)/n;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return Gm.copy(this).projectOnVector(e),this.sub(Gm)}reflect(e){return this.sub(Gm.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const n=Math.sqrt(this.lengthSq()*e.lengthSq());if(n===0)return Math.PI/2;const i=this.dot(e)/n;return Math.acos(Tn(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,i=this.y-e.y,r=this.z-e.z;return n*n+i*i+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,n,i){const r=Math.sin(n)*e;return this.x=r*Math.sin(i),this.y=Math.cos(n)*e,this.z=r*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,n,i){return this.x=e*Math.sin(n),this.y=i,this.z=e*Math.cos(n),this}setFromMatrixPosition(e){const n=e.elements;return this.x=n[12],this.y=n[13],this.z=n[14],this}setFromMatrixScale(e){const n=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=n,this.y=i,this.z=r,this}setFromMatrixColumn(e,n){return this.fromArray(e.elements,n*4)}setFromMatrix3Column(e,n){return this.fromArray(e.elements,n*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this.z=e[n+2],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e[n+2]=this.z,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this.z=e.getZ(n),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,n=Math.random()*2-1,i=Math.sqrt(1-n*n);return this.x=i*Math.cos(e),this.y=n,this.z=i*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Gm=new Le,g1=new Hu;class Ya{constructor(e=new Le(1/0,1/0,1/0),n=new Le(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=n}set(e,n){return this.min.copy(e),this.max.copy(n),this}setFromArray(e){this.makeEmpty();for(let n=0,i=e.length;n=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,n){return n.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,ys),ys.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let n,i;return e.normal.x>0?(n=e.normal.x*this.min.x,i=e.normal.x*this.max.x):(n=e.normal.x*this.max.x,i=e.normal.x*this.min.x),e.normal.y>0?(n+=e.normal.y*this.min.y,i+=e.normal.y*this.max.y):(n+=e.normal.y*this.max.y,i+=e.normal.y*this.min.y),e.normal.z>0?(n+=e.normal.z*this.min.z,i+=e.normal.z*this.max.z):(n+=e.normal.z*this.max.z,i+=e.normal.z*this.min.z),n<=-e.constant&&i>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(uu),rf.subVectors(this.max,uu),Nl.subVectors(e.a,uu),Il.subVectors(e.b,uu),Dl.subVectors(e.c,uu),qr.subVectors(Il,Nl),Wr.subVectors(Dl,Il),Ta.subVectors(Nl,Dl);let n=[0,-qr.z,qr.y,0,-Wr.z,Wr.y,0,-Ta.z,Ta.y,qr.z,0,-qr.x,Wr.z,0,-Wr.x,Ta.z,0,-Ta.x,-qr.y,qr.x,0,-Wr.y,Wr.x,0,-Ta.y,Ta.x,0];return!jm(n,Nl,Il,Dl,rf)||(n=[1,0,0,0,1,0,0,0,1],!jm(n,Nl,Il,Dl,rf))?!1:(af.crossVectors(qr,Wr),n=[af.x,af.y,af.z],jm(n,Nl,Il,Dl,rf))}clampPoint(e,n){return n.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,ys).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(ys).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(ar[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),ar[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),ar[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),ar[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),ar[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),ar[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),ar[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),ar[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(ar),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const ar=[new Le,new Le,new Le,new Le,new Le,new Le,new Le,new Le],ys=new Le,sf=new Ya,Nl=new Le,Il=new Le,Dl=new Le,qr=new Le,Wr=new Le,Ta=new Le,uu=new Le,rf=new Le,af=new Le,Ea=new Le;function jm(t,e,n,i,r){for(let a=0,c=t.length-3;a<=c;a+=3){Ea.fromArray(t,a);const u=r.x*Math.abs(Ea.x)+r.y*Math.abs(Ea.y)+r.z*Math.abs(Ea.z),h=e.dot(Ea),d=n.dot(Ea),g=i.dot(Ea);if(Math.max(-Math.max(h,d,g),Math.min(h,d,g))>u)return!1}return!0}const Kk=new Ya,du=new Le,qm=new Le;class Ja{constructor(e=new Le,n=-1){this.isSphere=!0,this.center=e,this.radius=n}set(e,n){return this.center.copy(e),this.radius=n,this}setFromPoints(e,n){const i=this.center;n!==void 0?i.copy(n):Kk.setFromPoints(e).getCenter(i);let r=0;for(let a=0,c=e.length;athis.radius*this.radius&&(n.sub(this.center).normalize(),n.multiplyScalar(this.radius).add(this.center)),n}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;du.subVectors(e,this.center);const n=du.lengthSq();if(n>this.radius*this.radius){const i=Math.sqrt(n),r=(i-this.radius)*.5;this.center.addScaledVector(du,r/i),this.radius+=r}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(qm.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(du.copy(e.center).add(qm)),this.expandByPoint(du.copy(e.center).sub(qm))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}}const lr=new Le,Wm=new Le,lf=new Le,$r=new Le,$m=new Le,cf=new Le,Xm=new Le;class cv{constructor(e=new Le,n=new Le(0,0,-1)){this.origin=e,this.direction=n}set(e,n){return this.origin.copy(e),this.direction.copy(n),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,n){return n.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,lr)),this}closestPointToPoint(e,n){n.subVectors(e,this.origin);const i=n.dot(this.direction);return i<0?n.copy(this.origin):n.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const n=lr.subVectors(e,this.origin).dot(this.direction);return n<0?this.origin.distanceToSquared(e):(lr.copy(this.origin).addScaledVector(this.direction,n),lr.distanceToSquared(e))}distanceSqToSegment(e,n,i,r){Wm.copy(e).add(n).multiplyScalar(.5),lf.copy(n).sub(e).normalize(),$r.copy(this.origin).sub(Wm);const a=e.distanceTo(n)*.5,c=-this.direction.dot(lf),u=$r.dot(this.direction),h=-$r.dot(lf),d=$r.lengthSq(),g=Math.abs(1-c*c);let v,y,S,T;if(g>0)if(v=c*h-u,y=c*u-h,T=a*g,v>=0)if(y>=-T)if(y<=T){const A=1/g;v*=A,y*=A,S=v*(v+c*y+2*u)+y*(c*v+y+2*h)+d}else y=a,v=Math.max(0,-(c*y+u)),S=-v*v+y*(y+2*h)+d;else y=-a,v=Math.max(0,-(c*y+u)),S=-v*v+y*(y+2*h)+d;else y<=-T?(v=Math.max(0,-(-c*a+u)),y=v>0?-a:Math.min(Math.max(-a,-h),a),S=-v*v+y*(y+2*h)+d):y<=T?(v=0,y=Math.min(Math.max(-a,-h),a),S=y*(y+2*h)+d):(v=Math.max(0,-(c*a+u)),y=v>0?a:Math.min(Math.max(-a,-h),a),S=-v*v+y*(y+2*h)+d);else y=c>0?-a:a,v=Math.max(0,-(c*y+u)),S=-v*v+y*(y+2*h)+d;return i&&i.copy(this.origin).addScaledVector(this.direction,v),r&&r.copy(Wm).addScaledVector(lf,y),S}intersectSphere(e,n){lr.subVectors(e.center,this.origin);const i=lr.dot(this.direction),r=lr.dot(lr)-i*i,a=e.radius*e.radius;if(r>a)return null;const c=Math.sqrt(a-r),u=i-c,h=i+c;return h<0?null:u<0?this.at(h,n):this.at(u,n)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const n=e.normal.dot(this.direction);if(n===0)return e.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(e.normal)+e.constant)/n;return i>=0?i:null}intersectPlane(e,n){const i=this.distanceToPlane(e);return i===null?null:this.at(i,n)}intersectsPlane(e){const n=e.distanceToPoint(this.origin);return n===0||e.normal.dot(this.direction)*n<0}intersectBox(e,n){let i,r,a,c,u,h;const d=1/this.direction.x,g=1/this.direction.y,v=1/this.direction.z,y=this.origin;return d>=0?(i=(e.min.x-y.x)*d,r=(e.max.x-y.x)*d):(i=(e.max.x-y.x)*d,r=(e.min.x-y.x)*d),g>=0?(a=(e.min.y-y.y)*g,c=(e.max.y-y.y)*g):(a=(e.max.y-y.y)*g,c=(e.min.y-y.y)*g),i>c||a>r||((a>i||isNaN(i))&&(i=a),(c=0?(u=(e.min.z-y.z)*v,h=(e.max.z-y.z)*v):(u=(e.max.z-y.z)*v,h=(e.min.z-y.z)*v),i>h||u>r)||((u>i||i!==i)&&(i=u),(h=0?i:r,n)}intersectsBox(e){return this.intersectBox(e,lr)!==null}intersectTriangle(e,n,i,r,a){$m.subVectors(n,e),cf.subVectors(i,e),Xm.crossVectors($m,cf);let c=this.direction.dot(Xm),u;if(c>0){if(r)return null;u=1}else if(c<0)u=-1,c=-c;else return null;$r.subVectors(this.origin,e);const h=u*this.direction.dot(cf.crossVectors($r,cf));if(h<0)return null;const d=u*this.direction.dot($m.cross($r));if(d<0||h+d>c)return null;const g=-u*$r.dot(Xm);return g<0?null:this.at(g/c,a)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class ui{constructor(e,n,i,r,a,c,u,h,d,g,v,y,S,T,A,E){ui.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,n,i,r,a,c,u,h,d,g,v,y,S,T,A,E)}set(e,n,i,r,a,c,u,h,d,g,v,y,S,T,A,E){const w=this.elements;return w[0]=e,w[4]=n,w[8]=i,w[12]=r,w[1]=a,w[5]=c,w[9]=u,w[13]=h,w[2]=d,w[6]=g,w[10]=v,w[14]=y,w[3]=S,w[7]=T,w[11]=A,w[15]=E,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new ui().fromArray(this.elements)}copy(e){const n=this.elements,i=e.elements;return n[0]=i[0],n[1]=i[1],n[2]=i[2],n[3]=i[3],n[4]=i[4],n[5]=i[5],n[6]=i[6],n[7]=i[7],n[8]=i[8],n[9]=i[9],n[10]=i[10],n[11]=i[11],n[12]=i[12],n[13]=i[13],n[14]=i[14],n[15]=i[15],this}copyPosition(e){const n=this.elements,i=e.elements;return n[12]=i[12],n[13]=i[13],n[14]=i[14],this}setFromMatrix3(e){const n=e.elements;return this.set(n[0],n[3],n[6],0,n[1],n[4],n[7],0,n[2],n[5],n[8],0,0,0,0,1),this}extractBasis(e,n,i){return e.setFromMatrixColumn(this,0),n.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(e,n,i){return this.set(e.x,n.x,i.x,0,e.y,n.y,i.y,0,e.z,n.z,i.z,0,0,0,0,1),this}extractRotation(e){const n=this.elements,i=e.elements,r=1/Ll.setFromMatrixColumn(e,0).length(),a=1/Ll.setFromMatrixColumn(e,1).length(),c=1/Ll.setFromMatrixColumn(e,2).length();return n[0]=i[0]*r,n[1]=i[1]*r,n[2]=i[2]*r,n[3]=0,n[4]=i[4]*a,n[5]=i[5]*a,n[6]=i[6]*a,n[7]=0,n[8]=i[8]*c,n[9]=i[9]*c,n[10]=i[10]*c,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this}makeRotationFromEuler(e){const n=this.elements,i=e.x,r=e.y,a=e.z,c=Math.cos(i),u=Math.sin(i),h=Math.cos(r),d=Math.sin(r),g=Math.cos(a),v=Math.sin(a);if(e.order==="XYZ"){const y=c*g,S=c*v,T=u*g,A=u*v;n[0]=h*g,n[4]=-h*v,n[8]=d,n[1]=S+T*d,n[5]=y-A*d,n[9]=-u*h,n[2]=A-y*d,n[6]=T+S*d,n[10]=c*h}else if(e.order==="YXZ"){const y=h*g,S=h*v,T=d*g,A=d*v;n[0]=y+A*u,n[4]=T*u-S,n[8]=c*d,n[1]=c*v,n[5]=c*g,n[9]=-u,n[2]=S*u-T,n[6]=A+y*u,n[10]=c*h}else if(e.order==="ZXY"){const y=h*g,S=h*v,T=d*g,A=d*v;n[0]=y-A*u,n[4]=-c*v,n[8]=T+S*u,n[1]=S+T*u,n[5]=c*g,n[9]=A-y*u,n[2]=-c*d,n[6]=u,n[10]=c*h}else if(e.order==="ZYX"){const y=c*g,S=c*v,T=u*g,A=u*v;n[0]=h*g,n[4]=T*d-S,n[8]=y*d+A,n[1]=h*v,n[5]=A*d+y,n[9]=S*d-T,n[2]=-d,n[6]=u*h,n[10]=c*h}else if(e.order==="YZX"){const y=c*h,S=c*d,T=u*h,A=u*d;n[0]=h*g,n[4]=A-y*v,n[8]=T*v+S,n[1]=v,n[5]=c*g,n[9]=-u*g,n[2]=-d*g,n[6]=S*v+T,n[10]=y-A*v}else if(e.order==="XZY"){const y=c*h,S=c*d,T=u*h,A=u*d;n[0]=h*g,n[4]=-v,n[8]=d*g,n[1]=y*v+A,n[5]=c*g,n[9]=S*v-T,n[2]=T*v-S,n[6]=u*g,n[10]=A*v+y}return n[3]=0,n[7]=0,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Zk,e,Qk)}lookAt(e,n,i){const r=this.elements;return Ho.subVectors(e,n),Ho.lengthSq()===0&&(Ho.z=1),Ho.normalize(),Xr.crossVectors(i,Ho),Xr.lengthSq()===0&&(Math.abs(i.z)===1?Ho.x+=1e-4:Ho.z+=1e-4,Ho.normalize(),Xr.crossVectors(i,Ho)),Xr.normalize(),uf.crossVectors(Ho,Xr),r[0]=Xr.x,r[4]=uf.x,r[8]=Ho.x,r[1]=Xr.y,r[5]=uf.y,r[9]=Ho.y,r[2]=Xr.z,r[6]=uf.z,r[10]=Ho.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,n){const i=e.elements,r=n.elements,a=this.elements,c=i[0],u=i[4],h=i[8],d=i[12],g=i[1],v=i[5],y=i[9],S=i[13],T=i[2],A=i[6],E=i[10],w=i[14],I=i[3],L=i[7],D=i[11],W=i[15],V=r[0],H=r[4],Q=r[8],k=r[12],P=r[1],J=r[5],ve=r[9],fe=r[13],Ee=r[2],je=r[6],X=r[10],_e=r[14],ne=r[3],tt=r[7],Ce=r[11],$=r[15];return a[0]=c*V+u*P+h*Ee+d*ne,a[4]=c*H+u*J+h*je+d*tt,a[8]=c*Q+u*ve+h*X+d*Ce,a[12]=c*k+u*fe+h*_e+d*$,a[1]=g*V+v*P+y*Ee+S*ne,a[5]=g*H+v*J+y*je+S*tt,a[9]=g*Q+v*ve+y*X+S*Ce,a[13]=g*k+v*fe+y*_e+S*$,a[2]=T*V+A*P+E*Ee+w*ne,a[6]=T*H+A*J+E*je+w*tt,a[10]=T*Q+A*ve+E*X+w*Ce,a[14]=T*k+A*fe+E*_e+w*$,a[3]=I*V+L*P+D*Ee+W*ne,a[7]=I*H+L*J+D*je+W*tt,a[11]=I*Q+L*ve+D*X+W*Ce,a[15]=I*k+L*fe+D*_e+W*$,this}multiplyScalar(e){const n=this.elements;return n[0]*=e,n[4]*=e,n[8]*=e,n[12]*=e,n[1]*=e,n[5]*=e,n[9]*=e,n[13]*=e,n[2]*=e,n[6]*=e,n[10]*=e,n[14]*=e,n[3]*=e,n[7]*=e,n[11]*=e,n[15]*=e,this}determinant(){const e=this.elements,n=e[0],i=e[4],r=e[8],a=e[12],c=e[1],u=e[5],h=e[9],d=e[13],g=e[2],v=e[6],y=e[10],S=e[14],T=e[3],A=e[7],E=e[11],w=e[15];return T*(+a*h*v-r*d*v-a*u*y+i*d*y+r*u*S-i*h*S)+A*(+n*h*S-n*d*y+a*c*y-r*c*S+r*d*g-a*h*g)+E*(+n*d*v-n*u*S-a*c*v+i*c*S+a*u*g-i*d*g)+w*(-r*u*g-n*h*v+n*u*y+r*c*v-i*c*y+i*h*g)}transpose(){const e=this.elements;let n;return n=e[1],e[1]=e[4],e[4]=n,n=e[2],e[2]=e[8],e[8]=n,n=e[6],e[6]=e[9],e[9]=n,n=e[3],e[3]=e[12],e[12]=n,n=e[7],e[7]=e[13],e[13]=n,n=e[11],e[11]=e[14],e[14]=n,this}setPosition(e,n,i){const r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=n,r[14]=i),this}invert(){const e=this.elements,n=e[0],i=e[1],r=e[2],a=e[3],c=e[4],u=e[5],h=e[6],d=e[7],g=e[8],v=e[9],y=e[10],S=e[11],T=e[12],A=e[13],E=e[14],w=e[15],I=v*E*d-A*y*d+A*h*S-u*E*S-v*h*w+u*y*w,L=T*y*d-g*E*d-T*h*S+c*E*S+g*h*w-c*y*w,D=g*A*d-T*v*d+T*u*S-c*A*S-g*u*w+c*v*w,W=T*v*h-g*A*h-T*u*y+c*A*y+g*u*E-c*v*E,V=n*I+i*L+r*D+a*W;if(V===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const H=1/V;return e[0]=I*H,e[1]=(A*y*a-v*E*a-A*r*S+i*E*S+v*r*w-i*y*w)*H,e[2]=(u*E*a-A*h*a+A*r*d-i*E*d-u*r*w+i*h*w)*H,e[3]=(v*h*a-u*y*a-v*r*d+i*y*d+u*r*S-i*h*S)*H,e[4]=L*H,e[5]=(g*E*a-T*y*a+T*r*S-n*E*S-g*r*w+n*y*w)*H,e[6]=(T*h*a-c*E*a-T*r*d+n*E*d+c*r*w-n*h*w)*H,e[7]=(c*y*a-g*h*a+g*r*d-n*y*d-c*r*S+n*h*S)*H,e[8]=D*H,e[9]=(T*v*a-g*A*a-T*i*S+n*A*S+g*i*w-n*v*w)*H,e[10]=(c*A*a-T*u*a+T*i*d-n*A*d-c*i*w+n*u*w)*H,e[11]=(g*u*a-c*v*a-g*i*d+n*v*d+c*i*S-n*u*S)*H,e[12]=W*H,e[13]=(g*A*r-T*v*r+T*i*y-n*A*y-g*i*E+n*v*E)*H,e[14]=(T*u*r-c*A*r-T*i*h+n*A*h+c*i*E-n*u*E)*H,e[15]=(c*v*r-g*u*r+g*i*h-n*v*h-c*i*y+n*u*y)*H,this}scale(e){const n=this.elements,i=e.x,r=e.y,a=e.z;return n[0]*=i,n[4]*=r,n[8]*=a,n[1]*=i,n[5]*=r,n[9]*=a,n[2]*=i,n[6]*=r,n[10]*=a,n[3]*=i,n[7]*=r,n[11]*=a,this}getMaxScaleOnAxis(){const e=this.elements,n=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(n,i,r))}makeTranslation(e,n,i){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,n,0,0,1,i,0,0,0,1),this}makeRotationX(e){const n=Math.cos(e),i=Math.sin(e);return this.set(1,0,0,0,0,n,-i,0,0,i,n,0,0,0,0,1),this}makeRotationY(e){const n=Math.cos(e),i=Math.sin(e);return this.set(n,0,i,0,0,1,0,0,-i,0,n,0,0,0,0,1),this}makeRotationZ(e){const n=Math.cos(e),i=Math.sin(e);return this.set(n,-i,0,0,i,n,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,n){const i=Math.cos(n),r=Math.sin(n),a=1-i,c=e.x,u=e.y,h=e.z,d=a*c,g=a*u;return this.set(d*c+i,d*u-r*h,d*h+r*u,0,d*u+r*h,g*u+i,g*h-r*c,0,d*h-r*u,g*h+r*c,a*h*h+i,0,0,0,0,1),this}makeScale(e,n,i){return this.set(e,0,0,0,0,n,0,0,0,0,i,0,0,0,0,1),this}makeShear(e,n,i,r,a,c){return this.set(1,i,a,0,e,1,c,0,n,r,1,0,0,0,0,1),this}compose(e,n,i){const r=this.elements,a=n._x,c=n._y,u=n._z,h=n._w,d=a+a,g=c+c,v=u+u,y=a*d,S=a*g,T=a*v,A=c*g,E=c*v,w=u*v,I=h*d,L=h*g,D=h*v,W=i.x,V=i.y,H=i.z;return r[0]=(1-(A+w))*W,r[1]=(S+D)*W,r[2]=(T-L)*W,r[3]=0,r[4]=(S-D)*V,r[5]=(1-(y+w))*V,r[6]=(E+I)*V,r[7]=0,r[8]=(T+L)*H,r[9]=(E-I)*H,r[10]=(1-(y+A))*H,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,n,i){const r=this.elements;let a=Ll.set(r[0],r[1],r[2]).length();const c=Ll.set(r[4],r[5],r[6]).length(),u=Ll.set(r[8],r[9],r[10]).length();this.determinant()<0&&(a=-a),e.x=r[12],e.y=r[13],e.z=r[14],_s.copy(this);const d=1/a,g=1/c,v=1/u;return _s.elements[0]*=d,_s.elements[1]*=d,_s.elements[2]*=d,_s.elements[4]*=g,_s.elements[5]*=g,_s.elements[6]*=g,_s.elements[8]*=v,_s.elements[9]*=v,_s.elements[10]*=v,n.setFromRotationMatrix(_s),i.x=a,i.y=c,i.z=u,this}makePerspective(e,n,i,r,a,c,u=mr){const h=this.elements,d=2*a/(n-e),g=2*a/(i-r),v=(n+e)/(n-e),y=(i+r)/(i-r);let S,T;if(u===mr)S=-(c+a)/(c-a),T=-2*c*a/(c-a);else if(u===ah)S=-c/(c-a),T=-c*a/(c-a);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+u);return h[0]=d,h[4]=0,h[8]=v,h[12]=0,h[1]=0,h[5]=g,h[9]=y,h[13]=0,h[2]=0,h[6]=0,h[10]=S,h[14]=T,h[3]=0,h[7]=0,h[11]=-1,h[15]=0,this}makeOrthographic(e,n,i,r,a,c,u=mr){const h=this.elements,d=1/(n-e),g=1/(i-r),v=1/(c-a),y=(n+e)*d,S=(i+r)*g;let T,A;if(u===mr)T=(c+a)*v,A=-2*v;else if(u===ah)T=a*v,A=-1*v;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+u);return h[0]=2*d,h[4]=0,h[8]=0,h[12]=-y,h[1]=0,h[5]=2*g,h[9]=0,h[13]=-S,h[2]=0,h[6]=0,h[10]=A,h[14]=-T,h[3]=0,h[7]=0,h[11]=0,h[15]=1,this}equals(e){const n=this.elements,i=e.elements;for(let r=0;r<16;r++)if(n[r]!==i[r])return!1;return!0}fromArray(e,n=0){for(let i=0;i<16;i++)this.elements[i]=e[i+n];return this}toArray(e=[],n=0){const i=this.elements;return e[n]=i[0],e[n+1]=i[1],e[n+2]=i[2],e[n+3]=i[3],e[n+4]=i[4],e[n+5]=i[5],e[n+6]=i[6],e[n+7]=i[7],e[n+8]=i[8],e[n+9]=i[9],e[n+10]=i[10],e[n+11]=i[11],e[n+12]=i[12],e[n+13]=i[13],e[n+14]=i[14],e[n+15]=i[15],e}}const Ll=new Le,_s=new ui,Zk=new Le(0,0,0),Qk=new Le(1,1,1),Xr=new Le,uf=new Le,Ho=new Le,v1=new ui,x1=new Hu;class _r{constructor(e=0,n=0,i=0,r=_r.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=n,this._z=i,this._order=r}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,n,i,r=this._order){return this._x=e,this._y=n,this._z=i,this._order=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,n=this._order,i=!0){const r=e.elements,a=r[0],c=r[4],u=r[8],h=r[1],d=r[5],g=r[9],v=r[2],y=r[6],S=r[10];switch(n){case"XYZ":this._y=Math.asin(Tn(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(-g,S),this._z=Math.atan2(-c,a)):(this._x=Math.atan2(y,d),this._z=0);break;case"YXZ":this._x=Math.asin(-Tn(g,-1,1)),Math.abs(g)<.9999999?(this._y=Math.atan2(u,S),this._z=Math.atan2(h,d)):(this._y=Math.atan2(-v,a),this._z=0);break;case"ZXY":this._x=Math.asin(Tn(y,-1,1)),Math.abs(y)<.9999999?(this._y=Math.atan2(-v,S),this._z=Math.atan2(-c,d)):(this._y=0,this._z=Math.atan2(h,a));break;case"ZYX":this._y=Math.asin(-Tn(v,-1,1)),Math.abs(v)<.9999999?(this._x=Math.atan2(y,S),this._z=Math.atan2(h,a)):(this._x=0,this._z=Math.atan2(-c,d));break;case"YZX":this._z=Math.asin(Tn(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(-g,d),this._y=Math.atan2(-v,a)):(this._x=0,this._y=Math.atan2(u,S));break;case"XZY":this._z=Math.asin(-Tn(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(y,d),this._y=Math.atan2(u,a)):(this._x=Math.atan2(-g,S),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+n)}return this._order=n,i===!0&&this._onChangeCallback(),this}setFromQuaternion(e,n,i){return v1.makeRotationFromQuaternion(e),this.setFromRotationMatrix(v1,n,i)}setFromVector3(e,n=this._order){return this.set(e.x,e.y,e.z,n)}reorder(e){return x1.setFromEuler(this),this.setFromQuaternion(x1,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],n=0){return e[n]=this._x,e[n+1]=this._y,e[n+2]=this._z,e[n+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}_r.DEFAULT_ORDER="XYZ";class NE{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let n=0;n1){for(let i=0;i0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(r.matrixAutoUpdate=!1),this.isInstancedMesh&&(r.type="InstancedMesh",r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type="BatchedMesh",r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.visibility=this._visibility,r.active=this._active,r.bounds=this._bounds.map(u=>({boxInitialized:u.boxInitialized,boxMin:u.box.min.toArray(),boxMax:u.box.max.toArray(),sphereInitialized:u.sphereInitialized,sphereRadius:u.sphere.radius,sphereCenter:u.sphere.center.toArray()})),r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.geometryCount=this._geometryCount,r.matricesTexture=this._matricesTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere={center:r.boundingSphere.center.toArray(),radius:r.boundingSphere.radius}),this.boundingBox!==null&&(r.boundingBox={min:r.boundingBox.min.toArray(),max:r.boundingBox.max.toArray()}));function a(u,h){return u[h.uuid]===void 0&&(u[h.uuid]=h.toJSON(e)),h.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=a(e.geometries,this.geometry);const u=this.geometry.parameters;if(u!==void 0&&u.shapes!==void 0){const h=u.shapes;if(Array.isArray(h))for(let d=0,g=h.length;d0){r.children=[];for(let u=0;u0){r.animations=[];for(let u=0;u0&&(i.geometries=u),h.length>0&&(i.materials=h),d.length>0&&(i.textures=d),g.length>0&&(i.images=g),v.length>0&&(i.shapes=v),y.length>0&&(i.skeletons=y),S.length>0&&(i.animations=S),T.length>0&&(i.nodes=T)}return i.object=r,i;function c(u){const h=[];for(const d in u){const g=u[d];delete g.metadata,h.push(g)}return h}}clone(e){return new this.constructor().copy(this,e)}copy(e,n=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),n===!0)for(let i=0;i0?r.multiplyScalar(1/Math.sqrt(a)):r.set(0,0,0)}static getBarycoord(e,n,i,r,a){bs.subVectors(r,n),ur.subVectors(i,n),Jm.subVectors(e,n);const c=bs.dot(bs),u=bs.dot(ur),h=bs.dot(Jm),d=ur.dot(ur),g=ur.dot(Jm),v=c*d-u*u;if(v===0)return a.set(0,0,0),null;const y=1/v,S=(d*h-u*g)*y,T=(c*g-u*h)*y;return a.set(1-S-T,T,S)}static containsPoint(e,n,i,r){return this.getBarycoord(e,n,i,r,dr)===null?!1:dr.x>=0&&dr.y>=0&&dr.x+dr.y<=1}static getInterpolation(e,n,i,r,a,c,u,h){return this.getBarycoord(e,n,i,r,dr)===null?(h.x=0,h.y=0,"z"in h&&(h.z=0),"w"in h&&(h.w=0),null):(h.setScalar(0),h.addScaledVector(a,dr.x),h.addScaledVector(c,dr.y),h.addScaledVector(u,dr.z),h)}static getInterpolatedAttribute(e,n,i,r,a,c){return e0.setScalar(0),t0.setScalar(0),n0.setScalar(0),e0.fromBufferAttribute(e,n),t0.fromBufferAttribute(e,i),n0.fromBufferAttribute(e,r),c.setScalar(0),c.addScaledVector(e0,a.x),c.addScaledVector(t0,a.y),c.addScaledVector(n0,a.z),c}static isFrontFacing(e,n,i,r){return bs.subVectors(i,n),ur.subVectors(e,n),bs.cross(ur).dot(r)<0}set(e,n,i){return this.a.copy(e),this.b.copy(n),this.c.copy(i),this}setFromPointsAndIndices(e,n,i,r){return this.a.copy(e[n]),this.b.copy(e[i]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,n,i,r){return this.a.fromBufferAttribute(e,n),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return bs.subVectors(this.c,this.b),ur.subVectors(this.a,this.b),bs.cross(ur).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Ts.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,n){return Ts.getBarycoord(e,this.a,this.b,this.c,n)}getInterpolation(e,n,i,r,a){return Ts.getInterpolation(e,this.a,this.b,this.c,n,i,r,a)}containsPoint(e){return Ts.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Ts.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,n){const i=this.a,r=this.b,a=this.c;let c,u;zl.subVectors(r,i),Pl.subVectors(a,i),Km.subVectors(e,i);const h=zl.dot(Km),d=Pl.dot(Km);if(h<=0&&d<=0)return n.copy(i);Zm.subVectors(e,r);const g=zl.dot(Zm),v=Pl.dot(Zm);if(g>=0&&v<=g)return n.copy(r);const y=h*v-g*d;if(y<=0&&h>=0&&g<=0)return c=h/(h-g),n.copy(i).addScaledVector(zl,c);Qm.subVectors(e,a);const S=zl.dot(Qm),T=Pl.dot(Qm);if(T>=0&&S<=T)return n.copy(a);const A=S*d-h*T;if(A<=0&&d>=0&&T<=0)return u=d/(d-T),n.copy(i).addScaledVector(Pl,u);const E=g*T-S*v;if(E<=0&&v-g>=0&&S-T>=0)return E1.subVectors(a,r),u=(v-g)/(v-g+(S-T)),n.copy(r).addScaledVector(E1,u);const w=1/(E+A+y);return c=A*w,u=y*w,n.copy(i).addScaledVector(zl,c).addScaledVector(Pl,u)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const IE={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Yr={h:0,s:0,l:0},ff={h:0,s:0,l:0};function i0(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+(e-t)*6*n:n<1/2?e:n<2/3?t+(e-t)*6*(2/3-n):t}class An{constructor(e,n,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,n,i)}set(e,n,i){if(n===void 0&&i===void 0){const r=e;r&&r.isColor?this.copy(r):typeof r=="number"?this.setHex(r):typeof r=="string"&&this.setStyle(r)}else this.setRGB(e,n,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,n=ds){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,kn.toWorkingColorSpace(this,n),this}setRGB(e,n,i,r=kn.workingColorSpace){return this.r=e,this.g=n,this.b=i,kn.toWorkingColorSpace(this,r),this}setHSL(e,n,i,r=kn.workingColorSpace){if(e=Bk(e,1),n=Tn(n,0,1),i=Tn(i,0,1),n===0)this.r=this.g=this.b=i;else{const a=i<=.5?i*(1+n):i+n-i*n,c=2*i-a;this.r=i0(c,a,e+1/3),this.g=i0(c,a,e),this.b=i0(c,a,e-1/3)}return kn.toWorkingColorSpace(this,r),this}setStyle(e,n=ds){function i(a){a!==void 0&&parseFloat(a)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let a;const c=r[1],u=r[2];switch(c){case"rgb":case"rgba":if(a=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(u))return i(a[4]),this.setRGB(Math.min(255,parseInt(a[1],10))/255,Math.min(255,parseInt(a[2],10))/255,Math.min(255,parseInt(a[3],10))/255,n);if(a=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(u))return i(a[4]),this.setRGB(Math.min(100,parseInt(a[1],10))/100,Math.min(100,parseInt(a[2],10))/100,Math.min(100,parseInt(a[3],10))/100,n);break;case"hsl":case"hsla":if(a=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(u))return i(a[4]),this.setHSL(parseFloat(a[1])/360,parseFloat(a[2])/100,parseFloat(a[3])/100,n);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){const a=r[1],c=a.length;if(c===3)return this.setRGB(parseInt(a.charAt(0),16)/15,parseInt(a.charAt(1),16)/15,parseInt(a.charAt(2),16)/15,n);if(c===6)return this.setHex(parseInt(a,16),n);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,n);return this}setColorName(e,n=ds){const i=IE[e.toLowerCase()];return i!==void 0?this.setHex(i,n):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=gr(e.r),this.g=gr(e.g),this.b=gr(e.b),this}copyLinearToSRGB(e){return this.r=oc(e.r),this.g=oc(e.g),this.b=oc(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=ds){return kn.fromWorkingColorSpace(go.copy(this),e),Math.round(Tn(go.r*255,0,255))*65536+Math.round(Tn(go.g*255,0,255))*256+Math.round(Tn(go.b*255,0,255))}getHexString(e=ds){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,n=kn.workingColorSpace){kn.fromWorkingColorSpace(go.copy(this),n);const i=go.r,r=go.g,a=go.b,c=Math.max(i,r,a),u=Math.min(i,r,a);let h,d;const g=(u+c)/2;if(u===c)h=0,d=0;else{const v=c-u;switch(d=g<=.5?v/(c+u):v/(2-c-u),c){case i:h=(r-a)/v+(r0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const n in e){const i=e[n];if(i===void 0){console.warn(`THREE.Material: parameter '${n}' has value of undefined.`);continue}const r=this[n];if(r===void 0){console.warn(`THREE.Material: '${n}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(i):r&&r.isVector3&&i&&i.isVector3?r.copy(i):this[n]=i}}toJSON(e){const n=e===void 0||typeof e=="string";n&&(e={textures:{},images:{}});const i={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(e).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(e).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(e).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(e).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(e).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==nc&&(i.blending=this.blending),this.side!==sa&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==F0&&(i.blendSrc=this.blendSrc),this.blendDst!==O0&&(i.blendDst=this.blendDst),this.blendEquation!==Oa&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==rc&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==u1&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Al&&(i.stencilFail=this.stencilFail),this.stencilZFail!==Al&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==Al&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function r(a){const c=[];for(const u in a){const h=a[u];delete h.metadata,c.push(h)}return c}if(n){const a=r(e.textures),c=r(e.images);a.length>0&&(i.textures=a),c.length>0&&(i.images=c)}return i}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const n=e.clippingPlanes;let i=null;if(n!==null){const r=n.length;i=new Array(r);for(let a=0;a!==r;++a)i[a]=n[a].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}}class ls extends yc{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new An(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new _r,this.combine=gE,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const Bi=new Le,hf=new Bn;let sz=0;class Vi{constructor(e,n,i=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:sz++}),this.name="",this.array=e,this.itemSize=n,this.count=e!==void 0?e.length/n:0,this.normalized=i,this.usage=d1,this.updateRanges=[],this.gpuType=Vs,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,n){this.updateRanges.push({start:e,count:n})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,n,i){e*=this.itemSize,i*=n.itemSize;for(let r=0,a=this.itemSize;rn.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),n.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Ya);const e=this.attributes.position,n=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new Le(-1/0,-1/0,-1/0),new Le(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),n)for(let i=0,r=n.length;i0&&(e.userData=this.userData),this.parameters!==void 0){const h=this.parameters;for(const d in h)h[d]!==void 0&&(e[d]=h[d]);return e}e.data={attributes:{}};const n=this.index;n!==null&&(e.data.index={type:n.array.constructor.name,array:Array.prototype.slice.call(n.array)});const i=this.attributes;for(const h in i){const d=i[h];e.data.attributes[h]=d.toJSON(e.data)}const r={};let a=!1;for(const h in this.morphAttributes){const d=this.morphAttributes[h],g=[];for(let v=0,y=d.length;v0&&(r[h]=g,a=!0)}a&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);const c=this.groups;c.length>0&&(e.data.groups=JSON.parse(JSON.stringify(c)));const u=this.boundingSphere;return u!==null&&(e.data.boundingSphere={center:u.center.toArray(),radius:u.radius}),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const n={};this.name=e.name;const i=e.index;i!==null&&this.setIndex(i.clone(n));const r=e.attributes;for(const d in r){const g=r[d];this.setAttribute(d,g.clone(n))}const a=e.morphAttributes;for(const d in a){const g=[],v=a[d];for(let y=0,S=v.length;y0){const r=n[i[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,c=r.length;a(e.far-e.near)**2))&&(w1.copy(a).invert(),wa.copy(e.ray).applyMatrix4(w1),!(i.boundingBox!==null&&wa.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,n,wa)))}_computeIntersections(e,n,i){let r;const a=this.geometry,c=this.material,u=a.index,h=a.attributes.position,d=a.attributes.uv,g=a.attributes.uv1,v=a.attributes.normal,y=a.groups,S=a.drawRange;if(u!==null)if(Array.isArray(c))for(let T=0,A=y.length;Tn.far?null:{distance:d,point:yf.clone(),object:t}}function _f(t,e,n,i,r,a,c,u,h,d){t.getVertexPosition(u,mf),t.getVertexPosition(h,gf),t.getVertexPosition(d,vf);const g=az(t,e,n,i,mf,gf,vf,C1);if(g){const v=new Le;Ts.getBarycoord(C1,mf,gf,vf,v),r&&(g.uv=Ts.getInterpolatedAttribute(r,u,h,d,v,new Bn)),a&&(g.uv1=Ts.getInterpolatedAttribute(a,u,h,d,v,new Bn)),c&&(g.normal=Ts.getInterpolatedAttribute(c,u,h,d,v,new Le),g.normal.dot(i.direction)>0&&g.normal.multiplyScalar(-1));const y={a:u,b:h,c:d,normal:new Le,materialIndex:0};Ts.getNormal(mf,gf,vf,y.normal),g.face=y,g.barycoord=v}return g}class _c extends xi{constructor(e=1,n=1,i=1,r=1,a=1,c=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:n,depth:i,widthSegments:r,heightSegments:a,depthSegments:c};const u=this;r=Math.floor(r),a=Math.floor(a),c=Math.floor(c);const h=[],d=[],g=[],v=[];let y=0,S=0;T("z","y","x",-1,-1,i,n,e,c,a,0),T("z","y","x",1,-1,i,n,-e,c,a,1),T("x","z","y",1,1,e,i,n,r,c,2),T("x","z","y",1,-1,e,i,-n,r,c,3),T("x","y","z",1,-1,e,n,i,r,a,4),T("x","y","z",-1,-1,e,n,-i,r,a,5),this.setIndex(h),this.setAttribute("position",new wi(d,3)),this.setAttribute("normal",new wi(g,3)),this.setAttribute("uv",new wi(v,2));function T(A,E,w,I,L,D,W,V,H,Q,k){const P=D/H,J=W/Q,ve=D/2,fe=W/2,Ee=V/2,je=H+1,X=Q+1;let _e=0,ne=0;const tt=new Le;for(let Ce=0;Ce0?1:-1,g.push(tt.x,tt.y,tt.z),v.push(ce/H),v.push(1-Ce/Q),_e+=1}}for(let Ce=0;Ce0&&(n.defines=this.defines),n.vertexShader=this.vertexShader,n.fragmentShader=this.fragmentShader,n.lights=this.lights,n.clipping=this.clipping;const i={};for(const r in this.extensions)this.extensions[r]===!0&&(i[r]=!0);return Object.keys(i).length>0&&(n.extensions=i),n}}class kE extends uo{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new ui,this.projectionMatrix=new ui,this.projectionMatrixInverse=new ui,this.coordinateSystem=mr}copy(e,n){return super.copy(e,n),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,n){super.updateWorldMatrix(e,n),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const Jr=new Le,A1=new Bn,R1=new Bn;class fs extends kE{constructor(e=50,n=1,i=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=i,this.far=r,this.focus=10,this.aspect=n,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,n){return super.copy(e,n),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const n=.5*this.getFilmHeight()/e;this.fov=Tg*2*Math.atan(n),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(Om*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Tg*2*Math.atan(Math.tan(Om*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,n,i){Jr.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Jr.x,Jr.y).multiplyScalar(-e/Jr.z),Jr.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(Jr.x,Jr.y).multiplyScalar(-e/Jr.z)}getViewSize(e,n){return this.getViewBounds(e,A1,R1),n.subVectors(R1,A1)}setViewOffset(e,n,i,r,a,c){this.aspect=e/n,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=n,this.view.offsetX=i,this.view.offsetY=r,this.view.width=a,this.view.height=c,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let n=e*Math.tan(Om*.5*this.fov)/this.zoom,i=2*n,r=this.aspect*i,a=-.5*r;const c=this.view;if(this.view!==null&&this.view.enabled){const h=c.fullWidth,d=c.fullHeight;a+=c.offsetX*r/h,n-=c.offsetY*i/d,r*=c.width/h,i*=c.height/d}const u=this.filmOffset;u!==0&&(a+=e*u/this.getFilmWidth()),this.projectionMatrix.makePerspective(a,a+r,n,n-i,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const n=super.toJSON(e);return n.object.fov=this.fov,n.object.zoom=this.zoom,n.object.near=this.near,n.object.far=this.far,n.object.focus=this.focus,n.object.aspect=this.aspect,this.view!==null&&(n.object.view=Object.assign({},this.view)),n.object.filmGauge=this.filmGauge,n.object.filmOffset=this.filmOffset,n}}const Ol=-90,Bl=1;class fz extends uo{constructor(e,n,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const r=new fs(Ol,Bl,e,n);r.layers=this.layers,this.add(r);const a=new fs(Ol,Bl,e,n);a.layers=this.layers,this.add(a);const c=new fs(Ol,Bl,e,n);c.layers=this.layers,this.add(c);const u=new fs(Ol,Bl,e,n);u.layers=this.layers,this.add(u);const h=new fs(Ol,Bl,e,n);h.layers=this.layers,this.add(h);const d=new fs(Ol,Bl,e,n);d.layers=this.layers,this.add(d)}updateCoordinateSystem(){const e=this.coordinateSystem,n=this.children.concat(),[i,r,a,c,u,h]=n;for(const d of n)this.remove(d);if(e===mr)i.up.set(0,1,0),i.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),a.up.set(0,0,-1),a.lookAt(0,1,0),c.up.set(0,0,1),c.lookAt(0,-1,0),u.up.set(0,1,0),u.lookAt(0,0,1),h.up.set(0,1,0),h.lookAt(0,0,-1);else if(e===ah)i.up.set(0,-1,0),i.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),a.up.set(0,0,1),a.lookAt(0,1,0),c.up.set(0,0,-1),c.lookAt(0,-1,0),u.up.set(0,-1,0),u.lookAt(0,0,1),h.up.set(0,-1,0),h.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const d of n)this.add(d),d.updateMatrixWorld()}update(e,n){this.parent===null&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[a,c,u,h,d,g]=this.children,v=e.getRenderTarget(),y=e.getActiveCubeFace(),S=e.getActiveMipmapLevel(),T=e.xr.enabled;e.xr.enabled=!1;const A=i.texture.generateMipmaps;i.texture.generateMipmaps=!1,e.setRenderTarget(i,0,r),e.render(n,a),e.setRenderTarget(i,1,r),e.render(n,c),e.setRenderTarget(i,2,r),e.render(n,u),e.setRenderTarget(i,3,r),e.render(n,h),e.setRenderTarget(i,4,r),e.render(n,d),i.texture.generateMipmaps=A,e.setRenderTarget(i,5,r),e.render(n,g),e.setRenderTarget(v,y,S),e.xr.enabled=T,i.texture.needsPMREMUpdate=!0}}class zE extends To{constructor(e,n,i,r,a,c,u,h,d,g){e=e!==void 0?e:[],n=n!==void 0?n:ac,super(e,n,i,r,a,c,u,h,d,g),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class hz extends Wa{constructor(e=1,n={}){super(e,e,n),this.isWebGLCubeRenderTarget=!0;const i={width:e,height:e,depth:1},r=[i,i,i,i,i,i];this.texture=new zE(r,n.mapping,n.wrapS,n.wrapT,n.magFilter,n.minFilter,n.format,n.type,n.anisotropy,n.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=n.generateMipmaps!==void 0?n.generateMipmaps:!1,this.texture.minFilter=n.minFilter!==void 0?n.minFilter:Bs}fromEquirectangularTexture(e,n){this.texture.type=n.type,this.texture.colorSpace=n.colorSpace,this.texture.generateMipmaps=n.generateMipmaps,this.texture.minFilter=n.minFilter,this.texture.magFilter=n.magFilter;const i={uniforms:{tEquirect:{value:null}},vertexShader:` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `,fragmentShader:` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + `},r=new _c(5,5,5),a=new ra({name:"CubemapFromEquirect",uniforms:fc(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:Do,blending:ia});a.uniforms.tEquirect.value=n;const c=new Ni(r,a),u=n.minFilter;return n.minFilter===Ha&&(n.minFilter=Bs),new fz(1,10,this).update(e,c),n.minFilter=u,c.geometry.dispose(),c.material.dispose(),this}clear(e,n,i,r){const a=e.getRenderTarget();for(let c=0;c<6;c++)e.setRenderTarget(this,c),e.clear(n,i,r);e.setRenderTarget(a)}}class Ss extends uo{constructor(){super(),this.isGroup=!0,this.type="Group"}}const pz={type:"move"};class r0{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Ss,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Ss,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new Le,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Le),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Ss,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new Le,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Le),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const n=this._hand;if(n)for(const i of e.hand.values())this._getHandJoint(n,i)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,n,i){let r=null,a=null,c=null;const u=this._targetRay,h=this._grip,d=this._hand;if(e&&n.session.visibilityState!=="visible-blurred"){if(d&&e.hand){c=!0;for(const A of e.hand.values()){const E=n.getJointPose(A,i),w=this._getHandJoint(d,A);E!==null&&(w.matrix.fromArray(E.transform.matrix),w.matrix.decompose(w.position,w.rotation,w.scale),w.matrixWorldNeedsUpdate=!0,w.jointRadius=E.radius),w.visible=E!==null}const g=d.joints["index-finger-tip"],v=d.joints["thumb-tip"],y=g.position.distanceTo(v.position),S=.02,T=.005;d.inputState.pinching&&y>S+T?(d.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!d.inputState.pinching&&y<=S-T&&(d.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else h!==null&&e.gripSpace&&(a=n.getPose(e.gripSpace,i),a!==null&&(h.matrix.fromArray(a.transform.matrix),h.matrix.decompose(h.position,h.rotation,h.scale),h.matrixWorldNeedsUpdate=!0,a.linearVelocity?(h.hasLinearVelocity=!0,h.linearVelocity.copy(a.linearVelocity)):h.hasLinearVelocity=!1,a.angularVelocity?(h.hasAngularVelocity=!0,h.angularVelocity.copy(a.angularVelocity)):h.hasAngularVelocity=!1));u!==null&&(r=n.getPose(e.targetRaySpace,i),r===null&&a!==null&&(r=a),r!==null&&(u.matrix.fromArray(r.transform.matrix),u.matrix.decompose(u.position,u.rotation,u.scale),u.matrixWorldNeedsUpdate=!0,r.linearVelocity?(u.hasLinearVelocity=!0,u.linearVelocity.copy(r.linearVelocity)):u.hasLinearVelocity=!1,r.angularVelocity?(u.hasAngularVelocity=!0,u.angularVelocity.copy(r.angularVelocity)):u.hasAngularVelocity=!1,this.dispatchEvent(pz)))}return u!==null&&(u.visible=r!==null),h!==null&&(h.visible=a!==null),d!==null&&(d.visible=c!==null),this}_getHandJoint(e,n){if(e.joints[n.jointName]===void 0){const i=new Ss;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[n.jointName]=i,e.add(i)}return e.joints[n.jointName]}}class mz extends uo{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new _r,this.environmentIntensity=1,this.environmentRotation=new _r,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,n){return super.copy(e,n),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const n=super.toJSON(e);return this.fog!==null&&(n.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(n.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(n.object.backgroundIntensity=this.backgroundIntensity),n.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(n.object.environmentIntensity=this.environmentIntensity),n.object.environmentRotation=this.environmentRotation.toArray(),n}}class gz extends To{constructor(e=null,n=1,i=1,r,a,c,u,h,d=Jo,g=Jo,v,y){super(null,c,u,h,d,g,r,a,v,y),this.isDataTexture=!0,this.image={data:e,width:n,height:i},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class N1 extends Vi{constructor(e,n,i,r=1){super(e,n,i),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=r}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){const e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}}const Vl=new ui,I1=new ui,bf=[],D1=new Ya,vz=new ui,pu=new Ni,mu=new Ja;class xz extends Ni{constructor(e,n,i){super(e,n),this.isInstancedMesh=!0,this.instanceMatrix=new N1(new Float32Array(i*16),16),this.instanceColor=null,this.morphTexture=null,this.count=i,this.boundingBox=null,this.boundingSphere=null;for(let r=0;r1?null:n.copy(e.start).addScaledVector(i,a)}intersectsLine(e){const n=this.distanceToPoint(e.start),i=this.distanceToPoint(e.end);return n<0&&i>0||i<0&&n>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,n){const i=n||_z.getNormalMatrix(e),r=this.coplanarPoint(a0).applyMatrix4(e),a=this.normal.applyMatrix3(i).normalize();return this.constant=-r.dot(a),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Ma=new Ja,Sf=new Le;class PE{constructor(e=new Ia,n=new Ia,i=new Ia,r=new Ia,a=new Ia,c=new Ia){this.planes=[e,n,i,r,a,c]}set(e,n,i,r,a,c){const u=this.planes;return u[0].copy(e),u[1].copy(n),u[2].copy(i),u[3].copy(r),u[4].copy(a),u[5].copy(c),this}copy(e){const n=this.planes;for(let i=0;i<6;i++)n[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,n=mr){const i=this.planes,r=e.elements,a=r[0],c=r[1],u=r[2],h=r[3],d=r[4],g=r[5],v=r[6],y=r[7],S=r[8],T=r[9],A=r[10],E=r[11],w=r[12],I=r[13],L=r[14],D=r[15];if(i[0].setComponents(h-a,y-d,E-S,D-w).normalize(),i[1].setComponents(h+a,y+d,E+S,D+w).normalize(),i[2].setComponents(h+c,y+g,E+T,D+I).normalize(),i[3].setComponents(h-c,y-g,E-T,D-I).normalize(),i[4].setComponents(h-u,y-v,E-A,D-L).normalize(),n===mr)i[5].setComponents(h+u,y+v,E+A,D+L).normalize();else if(n===ah)i[5].setComponents(u,v,A,L).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+n);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Ma.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const n=e.geometry;n.boundingSphere===null&&n.computeBoundingSphere(),Ma.copy(n.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Ma)}intersectsSprite(e){return Ma.center.set(0,0,0),Ma.radius=.7071067811865476,Ma.applyMatrix4(e.matrixWorld),this.intersectsSphere(Ma)}intersectsSphere(e){const n=this.planes,i=e.center,r=-e.radius;for(let a=0;a<6;a++)if(n[a].distanceToPoint(i)0?e.max.x:e.min.x,Sf.y=r.normal.y>0?e.max.y:e.min.y,Sf.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(Sf)<0)return!1}return!0}containsPoint(e){const n=this.planes;for(let i=0;i<6;i++)if(n[i].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class Nu extends yc{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new An(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}const ch=new Le,uh=new Le,L1=new ui,gu=new cv,Tf=new Ja,l0=new Le,U1=new Le;class Eg extends uo{constructor(e=new xi,n=new Nu){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=n,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,n){return super.copy(e,n),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(e.index===null){const n=e.attributes.position,i=[0];for(let r=1,a=n.count;r0){const r=n[i[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,c=r.length;ai)return;l0.applyMatrix4(t.matrixWorld);const d=e.ray.origin.distanceTo(l0);if(!(de.far))return{distance:d,point:U1.clone().applyMatrix4(t.matrixWorld),index:c,face:null,faceIndex:null,barycoord:null,object:t}}const k1=new Le,z1=new Le;class FE extends Eg{constructor(e,n){super(e,n),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const n=e.attributes.position,i=[];for(let r=0,a=n.count;r0){const r=n[i[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let a=0,c=r.length;ar.far)return;a.push({distance:d,distanceToRay:Math.sqrt(u),point:h,index:e,face:null,faceIndex:null,barycoord:null,object:c})}}class OE extends To{constructor(e,n,i,r,a,c,u,h,d,g=ic){if(g!==ic&&g!==uc)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");i===void 0&&g===ic&&(i=qa),i===void 0&&g===uc&&(i=cc),super(null,r,a,c,u,h,g,i,d),this.isDepthTexture=!0,this.image={width:e,height:n},this.magFilter=u!==void 0?u:Jo,this.minFilter=h!==void 0?h:Jo,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new lv(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const n=super.toJSON(e);return this.compareFunction!==null&&(n.compareFunction=this.compareFunction),n}}class Gu extends xi{constructor(e=[],n=[],i=1,r=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:n,radius:i,detail:r};const a=[],c=[];u(r),d(i),g(),this.setAttribute("position",new wi(a,3)),this.setAttribute("normal",new wi(a.slice(),3)),this.setAttribute("uv",new wi(c,2)),r===0?this.computeVertexNormals():this.normalizeNormals();function u(I){const L=new Le,D=new Le,W=new Le;for(let V=0;V.9&&H<.1&&(L<.2&&(c[I+0]+=1),D<.2&&(c[I+2]+=1),W<.2&&(c[I+4]+=1))}}function y(I){a.push(I.x,I.y,I.z)}function S(I,L){const D=I*3;L.x=e[D+0],L.y=e[D+1],L.z=e[D+2]}function T(){const I=new Le,L=new Le,D=new Le,W=new Le,V=new Bn,H=new Bn,Q=new Bn;for(let k=0,P=0;k0)&&S.push(L,D,V),(w!==i-1||hS.start-T.start);let y=0;for(let S=1;S 0 + vec4 plane; + #ifdef ALPHA_TO_COVERAGE + float distanceToPlane, distanceGradient; + float clipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + if ( clipOpacity == 0.0 ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + float unionClipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + } + #pragma unroll_loop_end + clipOpacity *= 1.0 - unionClipOpacity; + #endif + diffuseColor.a *= clipOpacity; + if ( diffuseColor.a == 0.0 ) discard; + #else + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + bool clipped = true; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; + } + #pragma unroll_loop_end + if ( clipped ) discard; + #endif + #endif +#endif`,jz=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`,qz=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`,Wz=`#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`,$z=`#if defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#elif defined( USE_COLOR ) + diffuseColor.rgb *= vColor; +#endif`,Xz=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) + varying vec3 vColor; +#endif`,Yz=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + varying vec3 vColor; +#endif`,Jz=`#if defined( USE_COLOR_ALPHA ) + vColor = vec4( 1.0 ); +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + vColor = vec3( 1.0 ); +#endif +#ifdef USE_COLOR + vColor *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.xyz *= instanceColor.xyz; +#endif +#ifdef USE_BATCHING_COLOR + vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); + vColor.xyz *= batchingColor.xyz; +#endif`,Kz=`#define PI 3.141592653589793 +#define PI2 6.283185307179586 +#define PI_HALF 1.5707963267948966 +#define RECIPROCAL_PI 0.3183098861837907 +#define RECIPROCAL_PI2 0.15915494309189535 +#define EPSILON 1e-6 +#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +#define whiteComplement( a ) ( 1.0 - saturate( a ) ) +float pow2( const in float x ) { return x*x; } +vec3 pow2( const in vec3 x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } +float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract( sin( sn ) * c ); +} +#ifdef HIGH_PRECISION + float precisionSafeLength( vec3 v ) { return length( v ); } +#else + float precisionSafeLength( vec3 v ) { + float maxComponent = max3( abs( v ) ); + return length( v / maxComponent ) * maxComponent; + } +#endif +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; +#ifdef USE_ALPHAHASH + varying vec3 vPosition; +#endif +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); +} +vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); +} +mat3 transposeMat3( const in mat3 m ) { + mat3 tmp; + tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); + tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); + tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); + return tmp; +} +bool isPerspectiveMatrix( mat4 m ) { + return m[ 2 ][ 3 ] == - 1.0; +} +vec2 equirectUv( in vec3 dir ) { + float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; + float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; + return vec2( u, v ); +} +vec3 BRDF_Lambert( const in vec3 diffuseColor ) { + return RECIPROCAL_PI * diffuseColor; +} +vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} +float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} // validated`,Zz=`#ifdef ENVMAP_TYPE_CUBE_UV + #define cubeUV_minMipLevel 4.0 + #define cubeUV_minTileSize 16.0 + float getFace( vec3 direction ) { + vec3 absDirection = abs( direction ); + float face = - 1.0; + if ( absDirection.x > absDirection.z ) { + if ( absDirection.x > absDirection.y ) + face = direction.x > 0.0 ? 0.0 : 3.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } else { + if ( absDirection.z > absDirection.y ) + face = direction.z > 0.0 ? 2.0 : 5.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } + return face; + } + vec2 getUV( vec3 direction, float face ) { + vec2 uv; + if ( face == 0.0 ) { + uv = vec2( direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 1.0 ) { + uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); + } else if ( face == 2.0 ) { + uv = vec2( - direction.x, direction.y ) / abs( direction.z ); + } else if ( face == 3.0 ) { + uv = vec2( - direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 4.0 ) { + uv = vec2( - direction.x, direction.z ) / abs( direction.y ); + } else { + uv = vec2( direction.x, direction.y ) / abs( direction.z ); + } + return 0.5 * ( uv + 1.0 ); + } + vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { + float face = getFace( direction ); + float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); + mipInt = max( mipInt, cubeUV_minMipLevel ); + float faceSize = exp2( mipInt ); + highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; + if ( face > 2.0 ) { + uv.y += faceSize; + face -= 3.0; + } + uv.x += face * faceSize; + uv.x += filterInt * 3.0 * cubeUV_minTileSize; + uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); + uv.x *= CUBEUV_TEXEL_WIDTH; + uv.y *= CUBEUV_TEXEL_HEIGHT; + #ifdef texture2DGradEXT + return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; + #else + return texture2D( envMap, uv ).rgb; + #endif + } + #define cubeUV_r0 1.0 + #define cubeUV_m0 - 2.0 + #define cubeUV_r1 0.8 + #define cubeUV_m1 - 1.0 + #define cubeUV_r4 0.4 + #define cubeUV_m4 2.0 + #define cubeUV_r5 0.305 + #define cubeUV_m5 3.0 + #define cubeUV_r6 0.21 + #define cubeUV_m6 4.0 + float roughnessToMip( float roughness ) { + float mip = 0.0; + if ( roughness >= cubeUV_r1 ) { + mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; + } else if ( roughness >= cubeUV_r4 ) { + mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; + } else if ( roughness >= cubeUV_r5 ) { + mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; + } else if ( roughness >= cubeUV_r6 ) { + mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; + } else { + mip = - 2.0 * log2( 1.16 * roughness ); } + return mip; + } + vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { + float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); + float mipF = fract( mip ); + float mipInt = floor( mip ); + vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); + if ( mipF == 0.0 ) { + return vec4( color0, 1.0 ); + } else { + vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); + return vec4( mix( color0, color1, mipF ), 1.0 ); + } + } +#endif`,Qz=`vec3 transformedNormal = objectNormal; +#ifdef USE_TANGENT + vec3 transformedTangent = objectTangent; +#endif +#ifdef USE_BATCHING + mat3 bm = mat3( batchingMatrix ); + transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); + transformedNormal = bm * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = bm * transformedTangent; + #endif +#endif +#ifdef USE_INSTANCING + mat3 im = mat3( instanceMatrix ); + transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); + transformedNormal = im * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = im * transformedTangent; + #endif +#endif +transformedNormal = normalMatrix * transformedNormal; +#ifdef FLIP_SIDED + transformedNormal = - transformedNormal; +#endif +#ifdef USE_TANGENT + transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; + #ifdef FLIP_SIDED + transformedTangent = - transformedTangent; + #endif +#endif`,eP=`#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`,tP=`#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); +#endif`,nP=`#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); + #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE + emissiveColor = sRGBTransferEOTF( emissiveColor ); + #endif + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`,iP=`#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`,oP="gl_FragColor = linearToOutputTexel( gl_FragColor );",sP=`vec4 LinearTransferOETF( in vec4 value ) { + return value; +} +vec4 sRGBTransferEOTF( in vec4 value ) { + return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); +} +vec4 sRGBTransferOETF( in vec4 value ) { + return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); +}`,rP=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vec3 cameraToFrag; + if ( isOrthographic ) { + cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToFrag = normalize( vWorldPosition - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vec3 reflectVec = reflect( cameraToFrag, worldNormal ); + #else + vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); + #endif + #else + vec3 reflectVec = vReflect; + #endif + #ifdef ENVMAP_TYPE_CUBE + vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); + #else + vec4 envColor = vec4( 0.0 ); + #endif + #ifdef ENVMAP_BLENDING_MULTIPLY + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_MIX ) + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_ADD ) + outgoingLight += envColor.xyz * specularStrength * reflectivity; + #endif +#endif`,aP=`#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform float flipEnvMap; + uniform mat3 envMapRotation; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif + +#endif`,lP=`#ifdef USE_ENVMAP + uniform float reflectivity; + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + varying vec3 vWorldPosition; + uniform float refractionRatio; + #else + varying vec3 vReflect; + #endif +#endif`,cP=`#ifdef USE_ENVMAP + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + + varying vec3 vWorldPosition; + #else + varying vec3 vReflect; + uniform float refractionRatio; + #endif +#endif`,uP=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vWorldPosition = worldPosition.xyz; + #else + vec3 cameraToVertex; + if ( isOrthographic ) { + cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vReflect = reflect( cameraToVertex, worldNormal ); + #else + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + #endif + #endif +#endif`,dP=`#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`,fP=`#ifdef USE_FOG + varying float vFogDepth; +#endif`,hP=`#ifdef USE_FOG + #ifdef FOG_EXP2 + float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); + #else + float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); + #endif + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); +#endif`,pP=`#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`,mP=`#ifdef USE_GRADIENTMAP + uniform sampler2D gradientMap; +#endif +vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { + float dotNL = dot( normal, lightDirection ); + vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); + #ifdef USE_GRADIENTMAP + return vec3( texture2D( gradientMap, coord ).r ); + #else + vec2 fw = fwidth( coord ) * 0.5; + return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); + #endif +}`,gP=`#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`,vP=`LambertMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularStrength = specularStrength;`,xP=`varying vec3 vViewPosition; +struct LambertMaterial { + vec3 diffuseColor; + float specularStrength; +}; +void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Lambert +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,yP=`uniform bool receiveShadow; +uniform vec3 ambientLightColor; +#if defined( USE_LIGHT_PROBES ) + uniform vec3 lightProbe[ 9 ]; +#endif +vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { + float x = normal.x, y = normal.y, z = normal.z; + vec3 result = shCoefficients[ 0 ] * 0.886227; + result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; + result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; + result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; + result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; + result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; + result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); + result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; + result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); + return result; +} +vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); + return irradiance; +} +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + vec3 irradiance = ambientLightColor; + return irradiance; +} +float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; +} +float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { + return smoothstep( coneCosine, penumbraCosine, angleCosine ); +} +#if NUM_DIR_LIGHTS > 0 + struct DirectionalLight { + vec3 direction; + vec3 color; + }; + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { + light.color = directionalLight.color; + light.direction = directionalLight.direction; + light.visible = true; + } +#endif +#if NUM_POINT_LIGHTS > 0 + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + }; + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = pointLight.position - geometryPosition; + light.direction = normalize( lVector ); + float lightDistance = length( lVector ); + light.color = pointLight.color; + light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } +#endif +#if NUM_SPOT_LIGHTS > 0 + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + }; + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = spotLight.position - geometryPosition; + light.direction = normalize( lVector ); + float angleCos = dot( light.direction, spotLight.direction ); + float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + if ( spotAttenuation > 0.0 ) { + float lightDistance = length( lVector ); + light.color = spotLight.color * spotAttenuation; + light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } else { + light.color = vec3( 0.0 ); + light.visible = false; + } + } +#endif +#if NUM_RECT_AREA_LIGHTS > 0 + struct RectAreaLight { + vec3 color; + vec3 position; + vec3 halfWidth; + vec3 halfHeight; + }; + uniform sampler2D ltc_1; uniform sampler2D ltc_2; + uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; +#endif +#if NUM_HEMI_LIGHTS > 0 + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { + float dotNL = dot( normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + return irradiance; + } +#endif`,_P=`#ifdef USE_ENVMAP + vec3 getIBLIrradiance( const in vec3 normal ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); + return PI * envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 reflectVec = reflect( - viewDir, normal ); + reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + #ifdef USE_ANISOTROPY + vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 bentNormal = cross( bitangent, viewDir ); + bentNormal = normalize( cross( bentNormal, bitangent ) ); + bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); + return getIBLRadiance( viewDir, bentNormal, roughness ); + #else + return vec3( 0.0 ); + #endif + } + #endif +#endif`,bP=`ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`,SP=`varying vec3 vViewPosition; +struct ToonMaterial { + vec3 diffuseColor; +}; +void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Toon +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,TP=`BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`,EP=`varying vec3 vViewPosition; +struct BlinnPhongMaterial { + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; +}; +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; +} +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,wP=`PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); +float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); +material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; +material.roughness = min( material.roughness, 1.0 ); +#ifdef IOR + material.ior = ior; + #ifdef USE_SPECULAR + float specularIntensityFactor = specularIntensity; + vec3 specularColorFactor = specularColor; + #ifdef USE_SPECULAR_COLORMAP + specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; + #endif + material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); + #else + float specularIntensityFactor = 1.0; + vec3 specularColorFactor = vec3( 1.0 ); + material.specularF90 = 1.0; + #endif + material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); + material.specularF90 = 1.0; +#endif +#ifdef USE_CLEARCOAT + material.clearcoat = clearcoat; + material.clearcoatRoughness = clearcoatRoughness; + material.clearcoatF0 = vec3( 0.04 ); + material.clearcoatF90 = 1.0; + #ifdef USE_CLEARCOATMAP + material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; + #endif + #ifdef USE_CLEARCOAT_ROUGHNESSMAP + material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; + #endif + material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); + material.clearcoatRoughness += geometryRoughness; + material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); +#endif +#ifdef USE_DISPERSION + material.dispersion = dispersion; +#endif +#ifdef USE_IRIDESCENCE + material.iridescence = iridescence; + material.iridescenceIOR = iridescenceIOR; + #ifdef USE_IRIDESCENCEMAP + material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; + #endif + #ifdef USE_IRIDESCENCE_THICKNESSMAP + material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; + #else + material.iridescenceThickness = iridescenceThicknessMaximum; + #endif +#endif +#ifdef USE_SHEEN + material.sheenColor = sheenColor; + #ifdef USE_SHEEN_COLORMAP + material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; + #endif + material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); + #ifdef USE_SHEEN_ROUGHNESSMAP + material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; + #endif +#endif +#ifdef USE_ANISOTROPY + #ifdef USE_ANISOTROPYMAP + mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); + vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; + vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; + #else + vec2 anisotropyV = anisotropyVector; + #endif + material.anisotropy = length( anisotropyV ); + if( material.anisotropy == 0.0 ) { + anisotropyV = vec2( 1.0, 0.0 ); + } else { + anisotropyV /= material.anisotropy; + material.anisotropy = saturate( material.anisotropy ); + } + material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); + material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; + material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; +#endif`,MP=`struct PhysicalMaterial { + vec3 diffuseColor; + float roughness; + vec3 specularColor; + float specularF90; + float dispersion; + #ifdef USE_CLEARCOAT + float clearcoat; + float clearcoatRoughness; + vec3 clearcoatF0; + float clearcoatF90; + #endif + #ifdef USE_IRIDESCENCE + float iridescence; + float iridescenceIOR; + float iridescenceThickness; + vec3 iridescenceFresnel; + vec3 iridescenceF0; + #endif + #ifdef USE_SHEEN + vec3 sheenColor; + float sheenRoughness; + #endif + #ifdef IOR + float ior; + #endif + #ifdef USE_TRANSMISSION + float transmission; + float transmissionAlpha; + float thickness; + float attenuationDistance; + vec3 attenuationColor; + #endif + #ifdef USE_ANISOTROPY + float anisotropy; + float alphaT; + vec3 anisotropyT; + vec3 anisotropyB; + #endif +}; +vec3 clearcoatSpecularDirect = vec3( 0.0 ); +vec3 clearcoatSpecularIndirect = vec3( 0.0 ); +vec3 sheenSpecularDirect = vec3( 0.0 ); +vec3 sheenSpecularIndirect = vec3(0.0 ); +vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { + float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); + float x2 = x * x; + float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); + return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); +} +float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { + float a2 = pow2( alpha ); + float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); + float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); + return 0.5 / max( gv + gl, EPSILON ); +} +float D_GGX( const in float alpha, const in float dotNH ) { + float a2 = pow2( alpha ); + float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; + return RECIPROCAL_PI * a2 / pow2( denom ); +} +#ifdef USE_ANISOTROPY + float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { + float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); + float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); + float v = 0.5 / ( gv + gl ); + return saturate(v); + } + float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { + float a2 = alphaT * alphaB; + highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); + highp float v2 = dot( v, v ); + float w2 = a2 / v2; + return RECIPROCAL_PI * a2 * pow2 ( w2 ); + } +#endif +#ifdef USE_CLEARCOAT + vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { + vec3 f0 = material.clearcoatF0; + float f90 = material.clearcoatF90; + float roughness = material.clearcoatRoughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + return F * ( V * D ); + } +#endif +vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 f0 = material.specularColor; + float f90 = material.specularF90; + float roughness = material.roughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + #ifdef USE_IRIDESCENCE + F = mix( F, material.iridescenceFresnel, material.iridescence ); + #endif + #ifdef USE_ANISOTROPY + float dotTL = dot( material.anisotropyT, lightDir ); + float dotTV = dot( material.anisotropyT, viewDir ); + float dotTH = dot( material.anisotropyT, halfDir ); + float dotBL = dot( material.anisotropyB, lightDir ); + float dotBV = dot( material.anisotropyB, viewDir ); + float dotBH = dot( material.anisotropyB, halfDir ); + float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); + float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); + #else + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + #endif + return F * ( V * D ); +} +vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { + const float LUT_SIZE = 64.0; + const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; + const float LUT_BIAS = 0.5 / LUT_SIZE; + float dotNV = saturate( dot( N, V ) ); + vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); + uv = uv * LUT_SCALE + LUT_BIAS; + return uv; +} +float LTC_ClippedSphereFormFactor( const in vec3 f ) { + float l = length( f ); + return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); +} +vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { + float x = dot( v1, v2 ); + float y = abs( x ); + float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; + float b = 3.4175940 + ( 4.1616724 + y ) * y; + float v = a / b; + float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; + return cross( v1, v2 ) * theta_sintheta; +} +vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { + vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; + vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; + vec3 lightNormal = cross( v1, v2 ); + if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); + vec3 T1, T2; + T1 = normalize( V - N * dot( V, N ) ); + T2 = - cross( N, T1 ); + mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); + vec3 coords[ 4 ]; + coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); + coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); + coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); + coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); + coords[ 0 ] = normalize( coords[ 0 ] ); + coords[ 1 ] = normalize( coords[ 1 ] ); + coords[ 2 ] = normalize( coords[ 2 ] ); + coords[ 3 ] = normalize( coords[ 3 ] ); + vec3 vectorFormFactor = vec3( 0.0 ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); + float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); + return vec3( result ); +} +#if defined( USE_SHEEN ) +float D_Charlie( float roughness, float dotNH ) { + float alpha = pow2( roughness ); + float invAlpha = 1.0 / alpha; + float cos2h = dotNH * dotNH; + float sin2h = max( 1.0 - cos2h, 0.0078125 ); + return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); +} +float V_Neubelt( float dotNV, float dotNL ) { + return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); +} +vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float D = D_Charlie( sheenRoughness, dotNH ); + float V = V_Neubelt( dotNV, dotNL ); + return sheenColor * ( D * V ); +} +#endif +float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + float r2 = roughness * roughness; + float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; + float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; + float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); + return saturate( DG * RECIPROCAL_PI ); +} +vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); + const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); + vec4 r = roughness * c0 + c1; + float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; + vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; + return fab; +} +vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { + vec2 fab = DFGApprox( normal, viewDir, roughness ); + return specularColor * fab.x + specularF90 * fab.y; +} +#ifdef USE_IRIDESCENCE +void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#else +void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#endif + vec2 fab = DFGApprox( normal, viewDir, roughness ); + #ifdef USE_IRIDESCENCE + vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); + #else + vec3 Fr = specularColor; + #endif + vec3 FssEss = Fr * fab.x + specularF90 * fab.y; + float Ess = fab.x + fab.y; + float Ems = 1.0 - Ess; + vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); + singleScatter += FssEss; + multiScatter += Fms * Ems; +} +#if NUM_RECT_AREA_LIGHTS > 0 + void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 normal = geometryNormal; + vec3 viewDir = geometryViewDir; + vec3 position = geometryPosition; + vec3 lightPos = rectAreaLight.position; + vec3 halfWidth = rectAreaLight.halfWidth; + vec3 halfHeight = rectAreaLight.halfHeight; + vec3 lightColor = rectAreaLight.color; + float roughness = material.roughness; + vec3 rectCoords[ 4 ]; + rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; + rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; + rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; + vec2 uv = LTC_Uv( normal, viewDir, roughness ); + vec4 t1 = texture2D( ltc_1, uv ); + vec4 t2 = texture2D( ltc_2, uv ); + mat3 mInv = mat3( + vec3( t1.x, 0, t1.y ), + vec3( 0, 1, 0 ), + vec3( t1.z, 0, t1.w ) + ); + vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); + reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); + reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); + } +#endif +void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + #ifdef USE_CLEARCOAT + float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); + vec3 ccIrradiance = dotNLcc * directLight.color; + clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); + #endif + #ifdef USE_SHEEN + sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); + #endif + reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { + #ifdef USE_CLEARCOAT + clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + #endif + vec3 singleScattering = vec3( 0.0 ); + vec3 multiScattering = vec3( 0.0 ); + vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; + #ifdef USE_IRIDESCENCE + computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); + #else + computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); + #endif + vec3 totalScattering = singleScattering + multiScattering; + vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); + reflectedLight.indirectSpecular += radiance * singleScattering; + reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; + reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; +} +#define RE_Direct RE_Direct_Physical +#define RE_Direct_RectArea RE_Direct_RectArea_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); +}`,CP=` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); +vec3 geometryClearcoatNormal = vec3( 0.0 ); +#ifdef USE_CLEARCOAT + geometryClearcoatNormal = clearcoatNormal; +#endif +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); + } +#endif +IncidentLight directLight; +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + pointLight = pointLights[ i ]; + getPointLightInfo( pointLight, geometryPosition, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + spotLight = spotLights[ i ]; + getSpotLightInfo( spotLight, geometryPosition, directLight ); + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + RectAreaLight rectAreaLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if defined( RE_IndirectDiffuse ) + vec3 iblIrradiance = vec3( 0.0 ); + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + #if defined( USE_LIGHT_PROBES ) + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + #endif + #if ( NUM_HEMI_LIGHTS > 0 ) + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + } + #pragma unroll_loop_end + #endif +#endif +#if defined( RE_IndirectSpecular ) + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); +#endif`,AP=`#if defined( RE_IndirectDiffuse ) + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + irradiance += lightMapIrradiance; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) + iblIrradiance += getIBLIrradiance( geometryNormal ); + #endif +#endif +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + #ifdef USE_ANISOTROPY + radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); + #else + radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); + #endif + #ifdef USE_CLEARCOAT + clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); + #endif +#endif`,RP=`#if defined( RE_IndirectDiffuse ) + RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif +#if defined( RE_IndirectSpecular ) + RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif`,NP=`#if defined( USE_LOGDEPTHBUF ) + gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`,IP=`#if defined( USE_LOGDEPTHBUF ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`,DP=`#ifdef USE_LOGDEPTHBUF + varying float vFragDepth; + varying float vIsPerspective; +#endif`,LP=`#ifdef USE_LOGDEPTHBUF + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); +#endif`,UP=`#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vMapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); + #endif + diffuseColor *= sampledDiffuseColor; +#endif`,kP=`#ifdef USE_MAP + uniform sampler2D map; +#endif`,zP=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + #if defined( USE_POINTS_UV ) + vec2 uv = vUv; + #else + vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; + #endif +#endif +#ifdef USE_MAP + diffuseColor *= texture2D( map, uv ); +#endif +#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, uv ).g; +#endif`,PP=`#if defined( USE_POINTS_UV ) + varying vec2 vUv; +#else + #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + uniform mat3 uvTransform; + #endif +#endif +#ifdef USE_MAP + uniform sampler2D map; +#endif +#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`,FP=`float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); + metalnessFactor *= texelMetalness.b; +#endif`,OP=`#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`,BP=`#ifdef USE_INSTANCING_MORPH + float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; + } +#endif`,VP=`#if defined( USE_MORPHCOLORS ) + vColor *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + #if defined( USE_COLOR_ALPHA ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; + #elif defined( USE_COLOR ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; + #endif + } +#endif`,HP=`#ifdef USE_MORPHNORMALS + objectNormal *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,GP=`#ifdef USE_MORPHTARGETS + #ifndef USE_INSTANCING_MORPH + uniform float morphTargetBaseInfluence; + uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + #endif + uniform sampler2DArray morphTargetsTexture; + uniform ivec2 morphTargetsTextureSize; + vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { + int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; + int y = texelIndex / morphTargetsTextureSize.x; + int x = texelIndex - y * morphTargetsTextureSize.x; + ivec3 morphUV = ivec3( x, y, morphTargetIndex ); + return texelFetch( morphTargetsTexture, morphUV, 0 ); + } +#endif`,jP=`#ifdef USE_MORPHTARGETS + transformed *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,qP=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#ifdef FLAT_SHADED + vec3 fdx = dFdx( vViewPosition ); + vec3 fdy = dFdy( vViewPosition ); + vec3 normal = normalize( cross( fdx, fdy ) ); +#else + vec3 normal = normalize( vNormal ); + #ifdef DOUBLE_SIDED + normal *= faceDirection; + #endif +#endif +#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) + #ifdef USE_TANGENT + mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn = getTangentFrame( - vViewPosition, normal, + #if defined( USE_NORMALMAP ) + vNormalMapUv + #elif defined( USE_CLEARCOAT_NORMALMAP ) + vClearcoatNormalMapUv + #else + vUv + #endif + ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn[0] *= faceDirection; + tbn[1] *= faceDirection; + #endif +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + #ifdef USE_TANGENT + mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn2[0] *= faceDirection; + tbn2[1] *= faceDirection; + #endif +#endif +vec3 nonPerturbedNormal = normal;`,WP=`#ifdef USE_NORMALMAP_OBJECTSPACE + normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + #ifdef FLIP_SIDED + normal = - normal; + #endif + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + normal = normalize( normalMatrix * normal ); +#elif defined( USE_NORMALMAP_TANGENTSPACE ) + vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + mapN.xy *= normalScale; + normal = normalize( tbn * mapN ); +#elif defined( USE_BUMPMAP ) + normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); +#endif`,$P=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,XP=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,YP=`#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`,JP=`#ifdef USE_NORMALMAP + uniform sampler2D normalMap; + uniform vec2 normalScale; +#endif +#ifdef USE_NORMALMAP_OBJECTSPACE + uniform mat3 normalMatrix; +#endif +#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) + mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { + vec3 q0 = dFdx( eye_pos.xyz ); + vec3 q1 = dFdy( eye_pos.xyz ); + vec2 st0 = dFdx( uv.st ); + vec2 st1 = dFdy( uv.st ); + vec3 N = surf_norm; + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); + return mat3( T * scale, B * scale, N ); + } +#endif`,KP=`#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = nonPerturbedNormal; +#endif`,ZP=`#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + clearcoatNormal = normalize( tbn2 * clearcoatMapN ); +#endif`,QP=`#ifdef USE_CLEARCOATMAP + uniform sampler2D clearcoatMap; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform sampler2D clearcoatNormalMap; + uniform vec2 clearcoatNormalScale; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform sampler2D clearcoatRoughnessMap; +#endif`,e5=`#ifdef USE_IRIDESCENCEMAP + uniform sampler2D iridescenceMap; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform sampler2D iridescenceThicknessMap; +#endif`,t5=`#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= material.transmissionAlpha; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,n5=`vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 2.0 * rgb.xyz - 1.0; +} +const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; +const float Inv255 = 1. / 255.; +const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); +const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); +const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); +const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); +vec4 packDepthToRGBA( const in float v ) { + if( v <= 0.0 ) + return vec4( 0., 0., 0., 0. ); + if( v >= 1.0 ) + return vec4( 1., 1., 1., 1. ); + float vuf; + float af = modf( v * PackFactors.a, vuf ); + float bf = modf( vuf * ShiftRight8, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); +} +vec3 packDepthToRGB( const in float v ) { + if( v <= 0.0 ) + return vec3( 0., 0., 0. ); + if( v >= 1.0 ) + return vec3( 1., 1., 1. ); + float vuf; + float bf = modf( v * PackFactors.b, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec3( vuf * Inv255, gf * PackUpscale, bf ); +} +vec2 packDepthToRG( const in float v ) { + if( v <= 0.0 ) + return vec2( 0., 0. ); + if( v >= 1.0 ) + return vec2( 1., 1. ); + float vuf; + float gf = modf( v * 256., vuf ); + return vec2( vuf * Inv255, gf ); +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors4 ); +} +float unpackRGBToDepth( const in vec3 v ) { + return dot( v, UnpackFactors3 ); +} +float unpackRGToDepth( const in vec2 v ) { + return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; +} +vec4 pack2HalfToRGBA( const in vec2 v ) { + vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); + return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); +} +vec2 unpackRGBATo2Half( const in vec4 v ) { + return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); +} +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { + return depth * ( near - far ) - near; +} +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { + return ( near * far ) / ( ( far - near ) * depth - far ); +}`,i5=`#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`,o5=`vec4 mvPosition = vec4( transformed, 1.0 ); +#ifdef USE_BATCHING + mvPosition = batchingMatrix * mvPosition; +#endif +#ifdef USE_INSTANCING + mvPosition = instanceMatrix * mvPosition; +#endif +mvPosition = modelViewMatrix * mvPosition; +gl_Position = projectionMatrix * mvPosition;`,s5=`#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`,r5=`#ifdef DITHERING + vec3 dithering( vec3 color ) { + float grid_position = rand( gl_FragCoord.xy ); + vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); + dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); + return color + dither_shift_RGB; + } +#endif`,a5=`float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); + roughnessFactor *= texelRoughness.g; +#endif`,l5=`#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`,c5=`#if NUM_SPOT_LIGHT_COORDS > 0 + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#if NUM_SPOT_LIGHT_MAPS > 0 + uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { + return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); + } + vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { + return unpackRGBATo2Half( texture2D( shadow, uv ) ); + } + float VSMShadow (sampler2D shadow, vec2 uv, float compare ){ + float occlusion = 1.0; + vec2 distribution = texture2DDistribution( shadow, uv ); + float hard_shadow = step( compare , distribution.x ); + if (hard_shadow != 1.0 ) { + float distance = compare - distribution.x ; + float variance = max( 0.00000, distribution.y * distribution.y ); + float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); + } + return occlusion; + } + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + #if defined( SHADOWMAP_TYPE_PCF ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx0 = - texelSize.x * shadowRadius; + float dy0 = - texelSize.y * shadowRadius; + float dx1 = + texelSize.x * shadowRadius; + float dy1 = + texelSize.y * shadowRadius; + float dx2 = dx0 / 2.0; + float dy2 = dy0 / 2.0; + float dx3 = dx1 / 2.0; + float dy3 = dy1 / 2.0; + shadow = ( + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) + ) * ( 1.0 / 17.0 ); + #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx = texelSize.x; + float dy = texelSize.y; + vec2 uv = shadowCoord.xy; + vec2 f = fract( uv * shadowMapSize + 0.5 ); + uv -= f * texelSize; + shadow = ( + texture2DCompare( shadowMap, uv, shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), + f.x ), + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), + f.x ), + f.y ) + ) * ( 1.0 / 9.0 ); + #elif defined( SHADOWMAP_TYPE_VSM ) + shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); + #else + shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } + vec2 cubeToUV( vec3 v, float texelSizeY ) { + vec3 absV = abs( v ); + float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); + absV *= scaleToCube; + v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); + vec2 planar = v.xy; + float almostATexel = 1.5 * texelSizeY; + float almostOne = 1.0 - almostATexel; + if ( absV.z >= almostOne ) { + if ( v.z > 0.0 ) + planar.x = 4.0 - v.x; + } else if ( absV.x >= almostOne ) { + float signX = sign( v.x ); + planar.x = v.z * signX + 2.0 * signX; + } else if ( absV.y >= almostOne ) { + float signY = sign( v.y ); + planar.x = v.x + 2.0 * signY + 2.0; + planar.y = v.z * signY - 2.0; + } + return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); + } + float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + + float lightToPositionLength = length( lightToPosition ); + if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { + float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; + vec3 bd3D = normalize( lightToPosition ); + vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); + #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) + vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; + shadow = ( + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) + ) * ( 1.0 / 9.0 ); + #else + shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } +#endif`,u5=`#if NUM_SPOT_LIGHT_COORDS > 0 + uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif +#endif`,d5=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) + vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + vec4 shadowWorldPosition; +#endif +#if defined( USE_SHADOWMAP ) + #if NUM_DIR_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif +#endif +#if NUM_SPOT_LIGHT_COORDS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { + shadowWorldPosition = worldPosition; + #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; + #endif + vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end +#endif`,f5=`float getShadowMask() { + float shadow = 1.0; + #ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + directionalLight = directionalLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + spotLight = spotLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + pointLight = pointLightShadows[ i ]; + shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`,h5=`#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`,p5=`#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif`,m5=`#ifdef USE_SKINNING + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif`,g5=`#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + #ifdef USE_TANGENT + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #endif +#endif`,v5=`float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`,x5=`#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`,y5=`#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`,_5=`#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +uniform float toneMappingExposure; +vec3 LinearToneMapping( vec3 color ) { + return saturate( toneMappingExposure * color ); +} +vec3 ReinhardToneMapping( vec3 color ) { + color *= toneMappingExposure; + return saturate( color / ( vec3( 1.0 ) + color ) ); +} +vec3 CineonToneMapping( vec3 color ) { + color *= toneMappingExposure; + color = max( vec3( 0.0 ), color - 0.004 ); + return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); +} +vec3 RRTAndODTFit( vec3 v ) { + vec3 a = v * ( v + 0.0245786 ) - 0.000090537; + vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; + return a / b; +} +vec3 ACESFilmicToneMapping( vec3 color ) { + const mat3 ACESInputMat = mat3( + vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), + vec3( 0.04823, 0.01566, 0.83777 ) + ); + const mat3 ACESOutputMat = mat3( + vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), + vec3( -0.07367, -0.00605, 1.07602 ) + ); + color *= toneMappingExposure / 0.6; + color = ACESInputMat * color; + color = RRTAndODTFit( color ); + color = ACESOutputMat * color; + return saturate( color ); +} +const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( + vec3( 1.6605, - 0.1246, - 0.0182 ), + vec3( - 0.5876, 1.1329, - 0.1006 ), + vec3( - 0.0728, - 0.0083, 1.1187 ) +); +const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( + vec3( 0.6274, 0.0691, 0.0164 ), + vec3( 0.3293, 0.9195, 0.0880 ), + vec3( 0.0433, 0.0113, 0.8956 ) +); +vec3 agxDefaultContrastApprox( vec3 x ) { + vec3 x2 = x * x; + vec3 x4 = x2 * x2; + return + 15.5 * x4 * x2 + - 40.14 * x4 * x + + 31.96 * x4 + - 6.868 * x2 * x + + 0.4298 * x2 + + 0.1191 * x + - 0.00232; +} +vec3 AgXToneMapping( vec3 color ) { + const mat3 AgXInsetMatrix = mat3( + vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), + vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), + vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) + ); + const mat3 AgXOutsetMatrix = mat3( + vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), + vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), + vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) + ); + const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; + color *= toneMappingExposure; + color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; + color = AgXInsetMatrix * color; + color = max( color, 1e-10 ); color = log2( color ); + color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); + color = clamp( color, 0.0, 1.0 ); + color = agxDefaultContrastApprox( color ); + color = AgXOutsetMatrix * color; + color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); + color = LINEAR_REC2020_TO_LINEAR_SRGB * color; + color = clamp( color, 0.0, 1.0 ); + return color; +} +vec3 NeutralToneMapping( vec3 color ) { + const float StartCompression = 0.8 - 0.04; + const float Desaturation = 0.15; + color *= toneMappingExposure; + float x = min( color.r, min( color.g, color.b ) ); + float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; + color -= offset; + float peak = max( color.r, max( color.g, color.b ) ); + if ( peak < StartCompression ) return color; + float d = 1. - StartCompression; + float newPeak = 1. - d * d / ( peak + d - StartCompression ); + color *= newPeak / peak; + float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); + return mix( color, vec3( newPeak ), g ); +} +vec3 CustomToneMapping( vec3 color ) { return color; }`,b5=`#ifdef USE_TRANSMISSION + material.transmission = transmission; + material.transmissionAlpha = 1.0; + material.thickness = thickness; + material.attenuationDistance = attenuationDistance; + material.attenuationColor = attenuationColor; + #ifdef USE_TRANSMISSIONMAP + material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; + #endif + #ifdef USE_THICKNESSMAP + material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; + #endif + vec3 pos = vWorldPosition; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = inverseTransformDirection( normal, viewMatrix ); + vec4 transmitted = getIBLVolumeRefraction( + n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, + material.attenuationColor, material.attenuationDistance ); + material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); + totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); +#endif`,S5=`#ifdef USE_TRANSMISSION + uniform float transmission; + uniform float thickness; + uniform float attenuationDistance; + uniform vec3 attenuationColor; + #ifdef USE_TRANSMISSIONMAP + uniform sampler2D transmissionMap; + #endif + #ifdef USE_THICKNESSMAP + uniform sampler2D thicknessMap; + #endif + uniform vec2 transmissionSamplerSize; + uniform sampler2D transmissionSamplerMap; + uniform mat4 modelMatrix; + uniform mat4 projectionMatrix; + varying vec3 vWorldPosition; + float w0( float a ) { + return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); + } + float w1( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); + } + float w2( float a ){ + return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); + } + float w3( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * a ); + } + float g0( float a ) { + return w0( a ) + w1( a ); + } + float g1( float a ) { + return w2( a ) + w3( a ); + } + float h0( float a ) { + return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); + } + float h1( float a ) { + return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); + } + vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { + uv = uv * texelSize.zw + 0.5; + vec2 iuv = floor( uv ); + vec2 fuv = fract( uv ); + float g0x = g0( fuv.x ); + float g1x = g1( fuv.x ); + float h0x = h0( fuv.x ); + float h1x = h1( fuv.x ); + float h0y = h0( fuv.y ); + float h1y = h1( fuv.y ); + vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); + } + vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { + vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); + vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); + vec2 fLodSizeInv = 1.0 / fLodSize; + vec2 cLodSizeInv = 1.0 / cLodSize; + vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); + vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); + return mix( fSample, cSample, fract( lod ) ); + } + vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { + vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); + vec3 modelScale; + modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); + modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); + modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); + return normalize( refractionVector ) * thickness * modelScale; + } + float applyIorToRoughness( const in float roughness, const in float ior ) { + return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); + } + vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { + float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); + return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); + } + vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { + if ( isinf( attenuationDistance ) ) { + return vec3( 1.0 ); + } else { + vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; + vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; + } + } + vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, + const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, + const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, + const in vec3 attenuationColor, const in float attenuationDistance ) { + vec4 transmittedLight; + vec3 transmittance; + #ifdef USE_DISPERSION + float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; + vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); + for ( int i = 0; i < 3; i ++ ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); + transmittedLight[ i ] = transmissionSample[ i ]; + transmittedLight.a += transmissionSample.a; + transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; + } + transmittedLight.a /= 3.0; + #else + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); + #endif + vec3 attenuatedColor = transmittance * transmittedLight.rgb; + vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); + float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; + return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); + } +#endif`,T5=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + varying vec2 vNormalMapUv; +#endif +#ifdef USE_EMISSIVEMAP + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_SPECULARMAP + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,E5=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + uniform mat3 mapTransform; + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + uniform mat3 alphaMapTransform; + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + uniform mat3 lightMapTransform; + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + uniform mat3 aoMapTransform; + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + uniform mat3 bumpMapTransform; + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + uniform mat3 normalMapTransform; + varying vec2 vNormalMapUv; +#endif +#ifdef USE_DISPLACEMENTMAP + uniform mat3 displacementMapTransform; + varying vec2 vDisplacementMapUv; +#endif +#ifdef USE_EMISSIVEMAP + uniform mat3 emissiveMapTransform; + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + uniform mat3 metalnessMapTransform; + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + uniform mat3 roughnessMapTransform; + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + uniform mat3 anisotropyMapTransform; + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + uniform mat3 clearcoatMapTransform; + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform mat3 clearcoatNormalMapTransform; + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform mat3 clearcoatRoughnessMapTransform; + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + uniform mat3 sheenColorMapTransform; + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + uniform mat3 sheenRoughnessMapTransform; + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + uniform mat3 iridescenceMapTransform; + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform mat3 iridescenceThicknessMapTransform; + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SPECULARMAP + uniform mat3 specularMapTransform; + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + uniform mat3 specularColorMapTransform; + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + uniform mat3 specularIntensityMapTransform; + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,w5=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + vUv = vec3( uv, 1 ).xy; +#endif +#ifdef USE_MAP + vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ALPHAMAP + vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_LIGHTMAP + vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_AOMAP + vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_BUMPMAP + vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_NORMALMAP + vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_DISPLACEMENTMAP + vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_EMISSIVEMAP + vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_METALNESSMAP + vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ROUGHNESSMAP + vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ANISOTROPYMAP + vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOATMAP + vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCEMAP + vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_COLORMAP + vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULARMAP + vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_COLORMAP + vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_TRANSMISSIONMAP + vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_THICKNESSMAP + vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; +#endif`,M5=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 + vec4 worldPosition = vec4( transformed, 1.0 ); + #ifdef USE_BATCHING + worldPosition = batchingMatrix * worldPosition; + #endif + #ifdef USE_INSTANCING + worldPosition = instanceMatrix * worldPosition; + #endif + worldPosition = modelMatrix * worldPosition; +#endif`;const C5=`varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`,A5=`uniform sampler2D t2D; +uniform float backgroundIntensity; +varying vec2 vUv; +void main() { + vec4 texColor = texture2D( t2D, vUv ); + #ifdef DECODE_VIDEO_TEXTURE + texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,R5=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,N5=`#ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; +#elif defined( ENVMAP_TYPE_CUBE_UV ) + uniform sampler2D envMap; +#endif +uniform float flipEnvMap; +uniform float backgroundBlurriness; +uniform float backgroundIntensity; +uniform mat3 backgroundRotation; +varying vec3 vWorldDirection; +#include +void main() { + #ifdef ENVMAP_TYPE_CUBE + vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); + #elif defined( ENVMAP_TYPE_CUBE_UV ) + vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); + #else + vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,I5=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,D5=`uniform samplerCube tCube; +uniform float tFlip; +uniform float opacity; +varying vec3 vWorldDirection; +void main() { + vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); + gl_FragColor = texColor; + gl_FragColor.a *= opacity; + #include + #include +}`,L5=`#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`,U5=`#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + vec4 diffuseColor = vec4( 1.0 ); + #include + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + #include + float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5; + #if DEPTH_PACKING == 3200 + gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); + #elif DEPTH_PACKING == 3201 + gl_FragColor = packDepthToRGBA( fragCoordZ ); + #elif DEPTH_PACKING == 3202 + gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); + #elif DEPTH_PACKING == 3203 + gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); + #endif +}`,k5=`#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`,z5=`#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +#include +void main () { + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = packDepthToRGBA( dist ); +}`,P5=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`,F5=`uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`,O5=`uniform float scale; +attribute float lineDistance; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vLineDistance = scale * lineDistance; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,B5=`uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,V5=`#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) + #include + #include + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,H5=`uniform vec3 diffuse; +uniform float opacity; +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; + #else + reflectedLight.indirectDiffuse += vec3( 1.0 ); + #endif + #include + reflectedLight.indirectDiffuse *= diffuseColor.rgb; + vec3 outgoingLight = reflectedLight.indirectDiffuse; + #include + #include + #include + #include + #include + #include + #include +}`,G5=`#define LAMBERT +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,j5=`#define LAMBERT +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,q5=`#define MATCAP +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; +}`,W5=`#define MATCAP +uniform vec3 diffuse; +uniform float opacity; +uniform sampler2D matcap; +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 viewDir = normalize( vViewPosition ); + vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); + vec3 y = cross( viewDir, x ); + vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; + #ifdef USE_MATCAP + vec4 matcapColor = texture2D( matcap, uv ); + #else + vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); + #endif + vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; + #include + #include + #include + #include + #include + #include +}`,$5=`#define NORMAL +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + vViewPosition = - mvPosition.xyz; +#endif +}`,X5=`#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); + #include + #include + #include + #include + gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); + #ifdef OPAQUE + gl_FragColor.a = 1.0; + #endif +}`,Y5=`#define PHONG +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,J5=`#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,K5=`#define STANDARD +varying vec3 vViewPosition; +#ifdef USE_TRANSMISSION + varying vec3 vWorldPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`,Z5=`#define STANDARD +#ifdef PHYSICAL + #define IOR + #define USE_SPECULAR +#endif +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; +#ifdef IOR + uniform float ior; +#endif +#ifdef USE_SPECULAR + uniform float specularIntensity; + uniform vec3 specularColor; + #ifdef USE_SPECULAR_COLORMAP + uniform sampler2D specularColorMap; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + uniform sampler2D specularIntensityMap; + #endif +#endif +#ifdef USE_CLEARCOAT + uniform float clearcoat; + uniform float clearcoatRoughness; +#endif +#ifdef USE_DISPERSION + uniform float dispersion; +#endif +#ifdef USE_IRIDESCENCE + uniform float iridescence; + uniform float iridescenceIOR; + uniform float iridescenceThicknessMinimum; + uniform float iridescenceThicknessMaximum; +#endif +#ifdef USE_SHEEN + uniform vec3 sheenColor; + uniform float sheenRoughness; + #ifdef USE_SHEEN_COLORMAP + uniform sampler2D sheenColorMap; + #endif + #ifdef USE_SHEEN_ROUGHNESSMAP + uniform sampler2D sheenRoughnessMap; + #endif +#endif +#ifdef USE_ANISOTROPY + uniform vec2 anisotropyVector; + #ifdef USE_ANISOTROPYMAP + uniform sampler2D anisotropyMap; + #endif +#endif +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; + #ifdef USE_SHEEN + float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); + outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; + #endif + #ifdef USE_CLEARCOAT + float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); + vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); + outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; + #endif + #include + #include + #include + #include + #include + #include +}`,Q5=`#define TOON +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`,eF=`#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`,tF=`uniform float size; +uniform float scale; +#include +#include +#include +#include +#include +#include +#ifdef USE_POINTS_UV + varying vec2 vUv; + uniform mat3 uvTransform; +#endif +void main() { + #ifdef USE_POINTS_UV + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + #endif + #include + #include + #include + #include + #include + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`,nF=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,iF=`#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,oF=`uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include +}`,sF=`uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + vec4 mvPosition = modelViewMatrix[ 3 ]; + vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); + #ifndef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) scale *= - mvPosition.z; + #endif + vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; + vec2 rotatedPosition; + rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; + rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; + mvPosition.xy += rotatedPosition; + gl_Position = projectionMatrix * mvPosition; + #include + #include + #include +}`,rF=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`,ln={alphahash_fragment:Az,alphahash_pars_fragment:Rz,alphamap_fragment:Nz,alphamap_pars_fragment:Iz,alphatest_fragment:Dz,alphatest_pars_fragment:Lz,aomap_fragment:Uz,aomap_pars_fragment:kz,batching_pars_vertex:zz,batching_vertex:Pz,begin_vertex:Fz,beginnormal_vertex:Oz,bsdfs:Bz,iridescence_fragment:Vz,bumpmap_pars_fragment:Hz,clipping_planes_fragment:Gz,clipping_planes_pars_fragment:jz,clipping_planes_pars_vertex:qz,clipping_planes_vertex:Wz,color_fragment:$z,color_pars_fragment:Xz,color_pars_vertex:Yz,color_vertex:Jz,common:Kz,cube_uv_reflection_fragment:Zz,defaultnormal_vertex:Qz,displacementmap_pars_vertex:eP,displacementmap_vertex:tP,emissivemap_fragment:nP,emissivemap_pars_fragment:iP,colorspace_fragment:oP,colorspace_pars_fragment:sP,envmap_fragment:rP,envmap_common_pars_fragment:aP,envmap_pars_fragment:lP,envmap_pars_vertex:cP,envmap_physical_pars_fragment:_P,envmap_vertex:uP,fog_vertex:dP,fog_pars_vertex:fP,fog_fragment:hP,fog_pars_fragment:pP,gradientmap_pars_fragment:mP,lightmap_pars_fragment:gP,lights_lambert_fragment:vP,lights_lambert_pars_fragment:xP,lights_pars_begin:yP,lights_toon_fragment:bP,lights_toon_pars_fragment:SP,lights_phong_fragment:TP,lights_phong_pars_fragment:EP,lights_physical_fragment:wP,lights_physical_pars_fragment:MP,lights_fragment_begin:CP,lights_fragment_maps:AP,lights_fragment_end:RP,logdepthbuf_fragment:NP,logdepthbuf_pars_fragment:IP,logdepthbuf_pars_vertex:DP,logdepthbuf_vertex:LP,map_fragment:UP,map_pars_fragment:kP,map_particle_fragment:zP,map_particle_pars_fragment:PP,metalnessmap_fragment:FP,metalnessmap_pars_fragment:OP,morphinstance_vertex:BP,morphcolor_vertex:VP,morphnormal_vertex:HP,morphtarget_pars_vertex:GP,morphtarget_vertex:jP,normal_fragment_begin:qP,normal_fragment_maps:WP,normal_pars_fragment:$P,normal_pars_vertex:XP,normal_vertex:YP,normalmap_pars_fragment:JP,clearcoat_normal_fragment_begin:KP,clearcoat_normal_fragment_maps:ZP,clearcoat_pars_fragment:QP,iridescence_pars_fragment:e5,opaque_fragment:t5,packing:n5,premultiplied_alpha_fragment:i5,project_vertex:o5,dithering_fragment:s5,dithering_pars_fragment:r5,roughnessmap_fragment:a5,roughnessmap_pars_fragment:l5,shadowmap_pars_fragment:c5,shadowmap_pars_vertex:u5,shadowmap_vertex:d5,shadowmask_pars_fragment:f5,skinbase_vertex:h5,skinning_pars_vertex:p5,skinning_vertex:m5,skinnormal_vertex:g5,specularmap_fragment:v5,specularmap_pars_fragment:x5,tonemapping_fragment:y5,tonemapping_pars_fragment:_5,transmission_fragment:b5,transmission_pars_fragment:S5,uv_pars_fragment:T5,uv_pars_vertex:E5,uv_vertex:w5,worldpos_vertex:M5,background_vert:C5,background_frag:A5,backgroundCube_vert:R5,backgroundCube_frag:N5,cube_vert:I5,cube_frag:D5,depth_vert:L5,depth_frag:U5,distanceRGBA_vert:k5,distanceRGBA_frag:z5,equirect_vert:P5,equirect_frag:F5,linedashed_vert:O5,linedashed_frag:B5,meshbasic_vert:V5,meshbasic_frag:H5,meshlambert_vert:G5,meshlambert_frag:j5,meshmatcap_vert:q5,meshmatcap_frag:W5,meshnormal_vert:$5,meshnormal_frag:X5,meshphong_vert:Y5,meshphong_frag:J5,meshphysical_vert:K5,meshphysical_frag:Z5,meshtoon_vert:Q5,meshtoon_frag:eF,points_vert:tF,points_frag:nF,shadow_vert:iF,shadow_frag:oF,sprite_vert:sF,sprite_frag:rF},St={common:{diffuse:{value:new An(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new an},alphaMap:{value:null},alphaMapTransform:{value:new an},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new an}},envmap:{envMap:{value:null},envMapRotation:{value:new an},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new an}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new an}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new an},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new an},normalScale:{value:new Bn(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new an},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new an}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new an}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new an}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new An(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new An(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new an},alphaTest:{value:0},uvTransform:{value:new an}},sprite:{diffuse:{value:new An(16777215)},opacity:{value:1},center:{value:new Bn(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new an},alphaMap:{value:null},alphaMapTransform:{value:new an},alphaTest:{value:0}}},Fs={basic:{uniforms:bo([St.common,St.specularmap,St.envmap,St.aomap,St.lightmap,St.fog]),vertexShader:ln.meshbasic_vert,fragmentShader:ln.meshbasic_frag},lambert:{uniforms:bo([St.common,St.specularmap,St.envmap,St.aomap,St.lightmap,St.emissivemap,St.bumpmap,St.normalmap,St.displacementmap,St.fog,St.lights,{emissive:{value:new An(0)}}]),vertexShader:ln.meshlambert_vert,fragmentShader:ln.meshlambert_frag},phong:{uniforms:bo([St.common,St.specularmap,St.envmap,St.aomap,St.lightmap,St.emissivemap,St.bumpmap,St.normalmap,St.displacementmap,St.fog,St.lights,{emissive:{value:new An(0)},specular:{value:new An(1118481)},shininess:{value:30}}]),vertexShader:ln.meshphong_vert,fragmentShader:ln.meshphong_frag},standard:{uniforms:bo([St.common,St.envmap,St.aomap,St.lightmap,St.emissivemap,St.bumpmap,St.normalmap,St.displacementmap,St.roughnessmap,St.metalnessmap,St.fog,St.lights,{emissive:{value:new An(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:ln.meshphysical_vert,fragmentShader:ln.meshphysical_frag},toon:{uniforms:bo([St.common,St.aomap,St.lightmap,St.emissivemap,St.bumpmap,St.normalmap,St.displacementmap,St.gradientmap,St.fog,St.lights,{emissive:{value:new An(0)}}]),vertexShader:ln.meshtoon_vert,fragmentShader:ln.meshtoon_frag},matcap:{uniforms:bo([St.common,St.bumpmap,St.normalmap,St.displacementmap,St.fog,{matcap:{value:null}}]),vertexShader:ln.meshmatcap_vert,fragmentShader:ln.meshmatcap_frag},points:{uniforms:bo([St.points,St.fog]),vertexShader:ln.points_vert,fragmentShader:ln.points_frag},dashed:{uniforms:bo([St.common,St.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ln.linedashed_vert,fragmentShader:ln.linedashed_frag},depth:{uniforms:bo([St.common,St.displacementmap]),vertexShader:ln.depth_vert,fragmentShader:ln.depth_frag},normal:{uniforms:bo([St.common,St.bumpmap,St.normalmap,St.displacementmap,{opacity:{value:1}}]),vertexShader:ln.meshnormal_vert,fragmentShader:ln.meshnormal_frag},sprite:{uniforms:bo([St.sprite,St.fog]),vertexShader:ln.sprite_vert,fragmentShader:ln.sprite_frag},background:{uniforms:{uvTransform:{value:new an},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:ln.background_vert,fragmentShader:ln.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new an}},vertexShader:ln.backgroundCube_vert,fragmentShader:ln.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:ln.cube_vert,fragmentShader:ln.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ln.equirect_vert,fragmentShader:ln.equirect_frag},distanceRGBA:{uniforms:bo([St.common,St.displacementmap,{referencePosition:{value:new Le},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:ln.distanceRGBA_vert,fragmentShader:ln.distanceRGBA_frag},shadow:{uniforms:bo([St.lights,St.fog,{color:{value:new An(0)},opacity:{value:1}}]),vertexShader:ln.shadow_vert,fragmentShader:ln.shadow_frag}};Fs.physical={uniforms:bo([Fs.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new an},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new an},clearcoatNormalScale:{value:new Bn(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new an},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new an},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new an},sheen:{value:0},sheenColor:{value:new An(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new an},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new an},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new an},transmissionSamplerSize:{value:new Bn},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new an},attenuationDistance:{value:0},attenuationColor:{value:new An(0)},specularColor:{value:new An(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new an},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new an},anisotropyVector:{value:new Bn},anisotropyMap:{value:null},anisotropyMapTransform:{value:new an}}]),vertexShader:ln.meshphysical_vert,fragmentShader:ln.meshphysical_frag};const Cf={r:0,b:0,g:0},Ca=new _r,aF=new ui;function lF(t,e,n,i,r,a,c){const u=new An(0);let h=a===!0?0:1,d,g,v=null,y=0,S=null;function T(L){let D=L.isScene===!0?L.background:null;return D&&D.isTexture&&(D=(L.backgroundBlurriness>0?n:e).get(D)),D}function A(L){let D=!1;const W=T(L);W===null?w(u,h):W&&W.isColor&&(w(W,1),D=!0);const V=t.xr.getEnvironmentBlendMode();V==="additive"?i.buffers.color.setClear(0,0,0,1,c):V==="alpha-blend"&&i.buffers.color.setClear(0,0,0,0,c),(t.autoClear||D)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil))}function E(L,D){const W=T(D);W&&(W.isCubeTexture||W.mapping===Mh)?(g===void 0&&(g=new Ni(new _c(1,1,1),new ra({name:"BackgroundCubeMaterial",uniforms:fc(Fs.backgroundCube.uniforms),vertexShader:Fs.backgroundCube.vertexShader,fragmentShader:Fs.backgroundCube.fragmentShader,side:Do,depthTest:!1,depthWrite:!1,fog:!1})),g.geometry.deleteAttribute("normal"),g.geometry.deleteAttribute("uv"),g.onBeforeRender=function(V,H,Q){this.matrixWorld.copyPosition(Q.matrixWorld)},Object.defineProperty(g.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(g)),Ca.copy(D.backgroundRotation),Ca.x*=-1,Ca.y*=-1,Ca.z*=-1,W.isCubeTexture&&W.isRenderTargetTexture===!1&&(Ca.y*=-1,Ca.z*=-1),g.material.uniforms.envMap.value=W,g.material.uniforms.flipEnvMap.value=W.isCubeTexture&&W.isRenderTargetTexture===!1?-1:1,g.material.uniforms.backgroundBlurriness.value=D.backgroundBlurriness,g.material.uniforms.backgroundIntensity.value=D.backgroundIntensity,g.material.uniforms.backgroundRotation.value.setFromMatrix4(aF.makeRotationFromEuler(Ca)),g.material.toneMapped=kn.getTransfer(W.colorSpace)!==Qn,(v!==W||y!==W.version||S!==t.toneMapping)&&(g.material.needsUpdate=!0,v=W,y=W.version,S=t.toneMapping),g.layers.enableAll(),L.unshift(g,g.geometry,g.material,0,0,null)):W&&W.isTexture&&(d===void 0&&(d=new Ni(new Ga(2,2),new ra({name:"BackgroundMaterial",uniforms:fc(Fs.background.uniforms),vertexShader:Fs.background.vertexShader,fragmentShader:Fs.background.fragmentShader,side:sa,depthTest:!1,depthWrite:!1,fog:!1})),d.geometry.deleteAttribute("normal"),Object.defineProperty(d.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(d)),d.material.uniforms.t2D.value=W,d.material.uniforms.backgroundIntensity.value=D.backgroundIntensity,d.material.toneMapped=kn.getTransfer(W.colorSpace)!==Qn,W.matrixAutoUpdate===!0&&W.updateMatrix(),d.material.uniforms.uvTransform.value.copy(W.matrix),(v!==W||y!==W.version||S!==t.toneMapping)&&(d.material.needsUpdate=!0,v=W,y=W.version,S=t.toneMapping),d.layers.enableAll(),L.unshift(d,d.geometry,d.material,0,0,null))}function w(L,D){L.getRGB(Cf,UE(t)),i.buffers.color.setClear(Cf.r,Cf.g,Cf.b,D,c)}function I(){g!==void 0&&(g.geometry.dispose(),g.material.dispose(),g=void 0),d!==void 0&&(d.geometry.dispose(),d.material.dispose(),d=void 0)}return{getClearColor:function(){return u},setClearColor:function(L,D=1){u.set(L),h=D,w(u,h)},getClearAlpha:function(){return h},setClearAlpha:function(L){h=L,w(u,h)},render:A,addToRenderList:E,dispose:I}}function cF(t,e){const n=t.getParameter(t.MAX_VERTEX_ATTRIBS),i={},r=y(null);let a=r,c=!1;function u(P,J,ve,fe,Ee){let je=!1;const X=v(fe,ve,J);a!==X&&(a=X,d(a.object)),je=S(P,fe,ve,Ee),je&&T(P,fe,ve,Ee),Ee!==null&&e.update(Ee,t.ELEMENT_ARRAY_BUFFER),(je||c)&&(c=!1,D(P,J,ve,fe),Ee!==null&&t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,e.get(Ee).buffer))}function h(){return t.createVertexArray()}function d(P){return t.bindVertexArray(P)}function g(P){return t.deleteVertexArray(P)}function v(P,J,ve){const fe=ve.wireframe===!0;let Ee=i[P.id];Ee===void 0&&(Ee={},i[P.id]=Ee);let je=Ee[J.id];je===void 0&&(je={},Ee[J.id]=je);let X=je[fe];return X===void 0&&(X=y(h()),je[fe]=X),X}function y(P){const J=[],ve=[],fe=[];for(let Ee=0;Ee=0){const Ce=Ee[ne];let $=je[ne];if($===void 0&&(ne==="instanceMatrix"&&P.instanceMatrix&&($=P.instanceMatrix),ne==="instanceColor"&&P.instanceColor&&($=P.instanceColor)),Ce===void 0||Ce.attribute!==$||$&&Ce.data!==$.data)return!0;X++}return a.attributesNum!==X||a.index!==fe}function T(P,J,ve,fe){const Ee={},je=J.attributes;let X=0;const _e=ve.getAttributes();for(const ne in _e)if(_e[ne].location>=0){let Ce=je[ne];Ce===void 0&&(ne==="instanceMatrix"&&P.instanceMatrix&&(Ce=P.instanceMatrix),ne==="instanceColor"&&P.instanceColor&&(Ce=P.instanceColor));const $={};$.attribute=Ce,Ce&&Ce.data&&($.data=Ce.data),Ee[ne]=$,X++}a.attributes=Ee,a.attributesNum=X,a.index=fe}function A(){const P=a.newAttributes;for(let J=0,ve=P.length;J=0){let tt=Ee[_e];if(tt===void 0&&(_e==="instanceMatrix"&&P.instanceMatrix&&(tt=P.instanceMatrix),_e==="instanceColor"&&P.instanceColor&&(tt=P.instanceColor)),tt!==void 0){const Ce=tt.normalized,$=tt.itemSize,ce=e.get(tt);if(ce===void 0)continue;const Xe=ce.buffer,oe=ce.type,Ie=ce.bytesPerElement,nt=oe===t.INT||oe===t.UNSIGNED_INT||tt.gpuType===tv;if(tt.isInterleavedBufferAttribute){const Se=tt.data,N=Se.stride,ye=tt.offset;if(Se.isInstancedInterleavedBuffer){for(let xe=0;xe0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";H="mediump"}return H==="mediump"&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let d=n.precision!==void 0?n.precision:"highp";const g=h(d);g!==d&&(console.warn("THREE.WebGLRenderer:",d,"not supported, using",g,"instead."),d=g);const v=n.logarithmicDepthBuffer===!0,y=n.reverseDepthBuffer===!0&&e.has("EXT_clip_control"),S=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),T=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),A=t.getParameter(t.MAX_TEXTURE_SIZE),E=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),w=t.getParameter(t.MAX_VERTEX_ATTRIBS),I=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),L=t.getParameter(t.MAX_VARYING_VECTORS),D=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),W=T>0,V=t.getParameter(t.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:h,textureFormatReadable:c,textureTypeReadable:u,precision:d,logarithmicDepthBuffer:v,reverseDepthBuffer:y,maxTextures:S,maxVertexTextures:T,maxTextureSize:A,maxCubemapSize:E,maxAttributes:w,maxVertexUniforms:I,maxVaryings:L,maxFragmentUniforms:D,vertexTextures:W,maxSamples:V}}function fF(t){const e=this;let n=null,i=0,r=!1,a=!1;const c=new Ia,u=new an,h={value:null,needsUpdate:!1};this.uniform=h,this.numPlanes=0,this.numIntersection=0,this.init=function(v,y){const S=v.length!==0||y||i!==0||r;return r=y,i=v.length,S},this.beginShadows=function(){a=!0,g(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(v,y){n=g(v,y,0)},this.setState=function(v,y,S){const T=v.clippingPlanes,A=v.clipIntersection,E=v.clipShadows,w=t.get(v);if(!r||T===null||T.length===0||a&&!E)a?g(null):d();else{const I=a?0:i,L=I*4;let D=w.clippingState||null;h.value=D,D=g(T,y,L,S);for(let W=0;W!==L;++W)D[W]=n[W];w.clippingState=D,this.numIntersection=A?this.numPlanes:0,this.numPlanes+=I}};function d(){h.value!==n&&(h.value=n,h.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function g(v,y,S,T){const A=v!==null?v.length:0;let E=null;if(A!==0){if(E=h.value,T!==!0||E===null){const w=S+A*4,I=y.matrixWorldInverse;u.getNormalMatrix(I),(E===null||E.length0){const d=new hz(h.height);return d.fromEquirectangularTexture(t,c),e.set(c,d),c.addEventListener("dispose",r),n(d.texture,c.mapping)}else return null}}return c}function r(c){const u=c.target;u.removeEventListener("dispose",r);const h=e.get(u);h!==void 0&&(e.delete(u),h.dispose())}function a(){e=new WeakMap}return{get:i,dispose:a}}const Kl=4,B1=[.125,.215,.35,.446,.526,.582],Ba=20,c0=new Tz,V1=new An;let u0=null,d0=0,f0=0,h0=!1;const Da=(1+Math.sqrt(5))/2,Hl=1/Da,H1=[new Le(-Da,Hl,0),new Le(Da,Hl,0),new Le(-Hl,0,Da),new Le(Hl,0,Da),new Le(0,Da,-Hl),new Le(0,Da,Hl),new Le(-1,1,-1),new Le(1,1,-1),new Le(-1,1,1),new Le(1,1,1)],pF=new Le;class G1{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,n=0,i=.1,r=100,a={}){const{size:c=256,position:u=pF}=a;u0=this._renderer.getRenderTarget(),d0=this._renderer.getActiveCubeFace(),f0=this._renderer.getActiveMipmapLevel(),h0=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(c);const h=this._allocateTargets();return h.depthBuffer=!0,this._sceneToCubeUV(e,i,r,h,u),n>0&&this._blur(h,0,0,n),this._applyPMREM(h),this._cleanup(h),h}fromEquirectangular(e,n=null){return this._fromTexture(e,n)}fromCubemap(e,n=null){return this._fromTexture(e,n)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=W1(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=q1(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?D:0,D,D),v.setRenderTarget(r),E&&v.render(A,h),v.render(e,h)}A.geometry.dispose(),A.material.dispose(),v.toneMapping=S,v.autoClear=y,e.background=w}_textureToCubeUV(e,n){const i=this._renderer,r=e.mapping===ac||e.mapping===lc;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=W1()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=q1());const a=r?this._cubemapMaterial:this._equirectMaterial,c=new Ni(this._lodPlanes[0],a),u=a.uniforms;u.envMap.value=e;const h=this._cubeSize;Af(n,0,0,3*h,2*h),i.setRenderTarget(n),i.render(c,c0)}_applyPMREM(e){const n=this._renderer,i=n.autoClear;n.autoClear=!1;const r=this._lodPlanes.length;for(let a=1;aBa&&console.warn(`sigmaRadians, ${a}, is too large and will clip, as it requested ${E} samples when the maximum is set to ${Ba}`);const w=[];let I=0;for(let H=0;HL-Kl?r-L+Kl:0),V=4*(this._cubeSize-D);Af(n,W,V,3*D,2*D),h.setRenderTarget(n),h.render(v,c0)}}function mF(t){const e=[],n=[],i=[];let r=t;const a=t-Kl+1+B1.length;for(let c=0;ct-Kl?h=B1[c-t+Kl-1]:c===0&&(h=0),i.push(h);const d=1/(u-2),g=-d,v=1+d,y=[g,g,v,g,v,v,g,g,v,v,g,v],S=6,T=6,A=3,E=2,w=1,I=new Float32Array(A*T*S),L=new Float32Array(E*T*S),D=new Float32Array(w*T*S);for(let V=0;V2?0:-1,k=[H,Q,0,H+2/3,Q,0,H+2/3,Q+1,0,H,Q,0,H+2/3,Q+1,0,H,Q+1,0];I.set(k,A*T*V),L.set(y,E*T*V);const P=[V,V,V,V,V,V];D.set(P,w*T*V)}const W=new xi;W.setAttribute("position",new Vi(I,A)),W.setAttribute("uv",new Vi(L,E)),W.setAttribute("faceIndex",new Vi(D,w)),e.push(W),r>Kl&&r--}return{lodPlanes:e,sizeLods:n,sigmas:i}}function j1(t,e,n){const i=new Wa(t,e,n);return i.texture.mapping=Mh,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function Af(t,e,n,i,r){t.viewport.set(e,n,i,r),t.scissor.set(e,n,i,r)}function gF(t,e,n){const i=new Float32Array(Ba),r=new Le(0,1,0);return new ra({name:"SphericalGaussianBlur",defines:{n:Ba,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:hv(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `,blending:ia,depthTest:!1,depthWrite:!1})}function q1(){return new ra({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:hv(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `,blending:ia,depthTest:!1,depthWrite:!1})}function W1(){return new ra({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:hv(),fragmentShader:` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `,blending:ia,depthTest:!1,depthWrite:!1})}function hv(){return` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `}function vF(t){let e=new WeakMap,n=null;function i(u){if(u&&u.isTexture){const h=u.mapping,d=h===$0||h===X0,g=h===ac||h===lc;if(d||g){let v=e.get(u);const y=v!==void 0?v.texture.pmremVersion:0;if(u.isRenderTargetTexture&&u.pmremVersion!==y)return n===null&&(n=new G1(t)),v=d?n.fromEquirectangular(u,v):n.fromCubemap(u,v),v.texture.pmremVersion=u.pmremVersion,e.set(u,v),v.texture;if(v!==void 0)return v.texture;{const S=u.image;return d&&S&&S.height>0||g&&S&&r(S)?(n===null&&(n=new G1(t)),v=d?n.fromEquirectangular(u):n.fromCubemap(u),v.texture.pmremVersion=u.pmremVersion,e.set(u,v),u.addEventListener("dispose",a),v.texture):null}}}return u}function r(u){let h=0;const d=6;for(let g=0;ge.maxTextureSize&&(W=Math.ceil(D/e.maxTextureSize),D=e.maxTextureSize);const V=new Float32Array(D*W*4*v),H=new RE(V,D,W,v);H.type=Vs,H.needsUpdate=!0;const Q=L*4;for(let P=0;P0)return t;const r=e*n;let a=X1[r];if(a===void 0&&(a=new Float32Array(r),X1[r]=a),e!==0){i.toArray(a,0);for(let c=1,u=0;c!==e;++c)u+=n,t[c].toArray(a,u)}return a}function Xi(t,e){if(t.length!==e.length)return!1;for(let n=0,i=t.length;n":" "} ${u}: ${n[c]}`)}return i.join(` +`)}const tT=new an;function v4(t){kn._getMatrix(tT,kn.workingColorSpace,t);const e=`mat3( ${tT.elements.map(n=>n.toFixed(4))} )`;switch(kn.getTransfer(t)){case rh:return[e,"LinearTransferOETF"];case Qn:return[e,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",t),[e,"LinearTransferOETF"]}}function nT(t,e,n){const i=t.getShaderParameter(e,t.COMPILE_STATUS),r=t.getShaderInfoLog(e).trim();if(i&&r==="")return"";const a=/ERROR: 0:(\d+)/.exec(r);if(a){const c=parseInt(a[1]);return n.toUpperCase()+` + +`+r+` + +`+g4(t.getShaderSource(e),c)}else return r}function x4(t,e){const n=v4(e);return[`vec4 ${t}( vec4 value ) {`,` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join(` +`)}function y4(t,e){let n;switch(e){case bk:n="Linear";break;case Sk:n="Reinhard";break;case Tk:n="Cineon";break;case Ek:n="ACESFilmic";break;case Mk:n="AgX";break;case Ck:n="Neutral";break;case wk:n="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),n="Linear"}return"vec3 "+t+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}const Rf=new Le;function _4(){kn.getLuminanceCoefficients(Rf);const t=Rf.x.toFixed(4),e=Rf.y.toFixed(4),n=Rf.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${t}, ${e}, ${n} );`," return dot( weights, rgb );","}"].join(` +`)}function b4(t){return[t.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",t.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(wu).join(` +`)}function S4(t){const e=[];for(const n in t){const i=t[n];i!==!1&&e.push("#define "+n+" "+i)}return e.join(` +`)}function T4(t,e){const n={},i=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let r=0;r/gm;function Mg(t){return t.replace(E4,M4)}const w4=new Map;function M4(t,e){let n=ln[e];if(n===void 0){const i=w4.get(e);if(i!==void 0)n=ln[i],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,i);else throw new Error("Can not resolve #include <"+e+">")}return Mg(n)}const C4=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function sT(t){return t.replace(C4,A4)}function A4(t,e,n,i){let r="";for(let a=parseInt(e);a0&&(E+=` +`),w=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,T].filter(wu).join(` +`),w.length>0&&(w+=` +`)):(E=[rT(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,T,n.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",n.batching?"#define USE_BATCHING":"",n.batchingColor?"#define USE_BATCHING_COLOR":"",n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.instancingMorph?"#define USE_INSTANCING_MORPH":"",n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+g:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.displacementMap?"#define USE_DISPLACEMENTMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.mapUv?"#define MAP_UV "+n.mapUv:"",n.alphaMapUv?"#define ALPHAMAP_UV "+n.alphaMapUv:"",n.lightMapUv?"#define LIGHTMAP_UV "+n.lightMapUv:"",n.aoMapUv?"#define AOMAP_UV "+n.aoMapUv:"",n.emissiveMapUv?"#define EMISSIVEMAP_UV "+n.emissiveMapUv:"",n.bumpMapUv?"#define BUMPMAP_UV "+n.bumpMapUv:"",n.normalMapUv?"#define NORMALMAP_UV "+n.normalMapUv:"",n.displacementMapUv?"#define DISPLACEMENTMAP_UV "+n.displacementMapUv:"",n.metalnessMapUv?"#define METALNESSMAP_UV "+n.metalnessMapUv:"",n.roughnessMapUv?"#define ROUGHNESSMAP_UV "+n.roughnessMapUv:"",n.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+n.anisotropyMapUv:"",n.clearcoatMapUv?"#define CLEARCOATMAP_UV "+n.clearcoatMapUv:"",n.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+n.clearcoatNormalMapUv:"",n.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+n.clearcoatRoughnessMapUv:"",n.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+n.iridescenceMapUv:"",n.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+n.iridescenceThicknessMapUv:"",n.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+n.sheenColorMapUv:"",n.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+n.sheenRoughnessMapUv:"",n.specularMapUv?"#define SPECULARMAP_UV "+n.specularMapUv:"",n.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+n.specularColorMapUv:"",n.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+n.specularIntensityMapUv:"",n.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+n.transmissionMapUv:"",n.thicknessMapUv?"#define THICKNESSMAP_UV "+n.thicknessMapUv:"",n.vertexTangents&&n.flatShading===!1?"#define USE_TANGENT":"",n.vertexColors?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.flatShading?"#define FLAT_SHADED":"",n.skinning?"#define USE_SKINNING":"",n.morphTargets?"#define USE_MORPHTARGETS":"",n.morphNormals&&n.flatShading===!1?"#define USE_MORPHNORMALS":"",n.morphColors?"#define USE_MORPHCOLORS":"",n.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+n.morphTextureStride:"",n.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+h:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` +`].filter(wu).join(` +`),w=[rT(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,T,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+d:"",n.envMap?"#define "+g:"",n.envMap?"#define "+v:"",y?"#define CUBEUV_TEXEL_WIDTH "+y.texelWidth:"",y?"#define CUBEUV_TEXEL_HEIGHT "+y.texelHeight:"",y?"#define CUBEUV_MAX_MIP "+y.maxMip+".0":"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoat?"#define USE_CLEARCOAT":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.dispersion?"#define USE_DISPERSION":"",n.iridescence?"#define USE_IRIDESCENCE":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.vertexTangents&&n.flatShading===!1?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor||n.batchingColor?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.gradientMap?"#define USE_GRADIENTMAP":"",n.flatShading?"#define FLAT_SHADED":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+h:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",n.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",n.toneMapping!==oa?"#define TONE_MAPPING":"",n.toneMapping!==oa?ln.tonemapping_pars_fragment:"",n.toneMapping!==oa?y4("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",ln.colorspace_pars_fragment,x4("linearToOutputTexel",n.outputColorSpace),_4(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"",` +`].filter(wu).join(` +`)),c=Mg(c),c=iT(c,n),c=oT(c,n),u=Mg(u),u=iT(u,n),u=oT(u,n),c=sT(c),u=sT(u),n.isRawShaderMaterial!==!0&&(I=`#version 300 es +`,E=[S,"#define attribute in","#define varying out","#define texture2D texture"].join(` +`)+` +`+E,w=["#define varying in",n.glslVersion===f1?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===f1?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` +`)+` +`+w);const L=I+E+c,D=I+w+u,W=eT(r,r.VERTEX_SHADER,L),V=eT(r,r.FRAGMENT_SHADER,D);r.attachShader(A,W),r.attachShader(A,V),n.index0AttributeName!==void 0?r.bindAttribLocation(A,0,n.index0AttributeName):n.morphTargets===!0&&r.bindAttribLocation(A,0,"position"),r.linkProgram(A);function H(J){if(t.debug.checkShaderErrors){const ve=r.getProgramInfoLog(A).trim(),fe=r.getShaderInfoLog(W).trim(),Ee=r.getShaderInfoLog(V).trim();let je=!0,X=!0;if(r.getProgramParameter(A,r.LINK_STATUS)===!1)if(je=!1,typeof t.debug.onShaderError=="function")t.debug.onShaderError(r,A,W,V);else{const _e=nT(r,W,"vertex"),ne=nT(r,V,"fragment");console.error("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(A,r.VALIDATE_STATUS)+` + +Material Name: `+J.name+` +Material Type: `+J.type+` + +Program Info Log: `+ve+` +`+_e+` +`+ne)}else ve!==""?console.warn("THREE.WebGLProgram: Program Info Log:",ve):(fe===""||Ee==="")&&(X=!1);X&&(J.diagnostics={runnable:je,programLog:ve,vertexShader:{log:fe,prefix:E},fragmentShader:{log:Ee,prefix:w}})}r.deleteShader(W),r.deleteShader(V),Q=new Hf(r,A),k=T4(r,A)}let Q;this.getUniforms=function(){return Q===void 0&&H(this),Q};let k;this.getAttributes=function(){return k===void 0&&H(this),k};let P=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return P===!1&&(P=r.getProgramParameter(A,p4)),P},this.destroy=function(){i.releaseStatesOfProgram(this),r.deleteProgram(A),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=m4++,this.cacheKey=e,this.usedTimes=1,this.program=A,this.vertexShader=W,this.fragmentShader=V,this}let k4=0;class z4{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const n=e.vertexShader,i=e.fragmentShader,r=this._getShaderStage(n),a=this._getShaderStage(i),c=this._getShaderCacheForMaterial(e);return c.has(r)===!1&&(c.add(r),r.usedTimes++),c.has(a)===!1&&(c.add(a),a.usedTimes++),this}remove(e){const n=this.materialCache.get(e);for(const i of n)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const n=this.materialCache;let i=n.get(e);return i===void 0&&(i=new Set,n.set(e,i)),i}_getShaderStage(e){const n=this.shaderCache;let i=n.get(e);return i===void 0&&(i=new P4(e),n.set(e,i)),i}}class P4{constructor(e){this.id=k4++,this.code=e,this.usedTimes=0}}function F4(t,e,n,i,r,a,c){const u=new NE,h=new z4,d=new Set,g=[],v=r.logarithmicDepthBuffer,y=r.vertexTextures;let S=r.precision;const T={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function A(k){return d.add(k),k===0?"uv":`uv${k}`}function E(k,P,J,ve,fe){const Ee=ve.fog,je=fe.geometry,X=k.isMeshStandardMaterial?ve.environment:null,_e=(k.isMeshStandardMaterial?n:e).get(k.envMap||X),ne=_e&&_e.mapping===Mh?_e.image.height:null,tt=T[k.type];k.precision!==null&&(S=r.getMaxPrecision(k.precision),S!==k.precision&&console.warn("THREE.WebGLProgram.getParameters:",k.precision,"not supported, using",S,"instead."));const Ce=je.morphAttributes.position||je.morphAttributes.normal||je.morphAttributes.color,$=Ce!==void 0?Ce.length:0;let ce=0;je.morphAttributes.position!==void 0&&(ce=1),je.morphAttributes.normal!==void 0&&(ce=2),je.morphAttributes.color!==void 0&&(ce=3);let Xe,oe,Ie,nt;if(tt){const Ke=Fs[tt];Xe=Ke.vertexShader,oe=Ke.fragmentShader}else Xe=k.vertexShader,oe=k.fragmentShader,h.update(k),Ie=h.getVertexShaderID(k),nt=h.getFragmentShaderID(k);const Se=t.getRenderTarget(),N=t.state.buffers.depth.getReversed(),ye=fe.isInstancedMesh===!0,xe=fe.isBatchedMesh===!0,Oe=!!k.map,at=!!k.matcap,Ze=!!_e,U=!!k.aoMap,Me=!!k.lightMap,Pe=!!k.bumpMap,rt=!!k.normalMap,We=!!k.displacementMap,gt=!!k.emissiveMap,qe=!!k.metalnessMap,q=!!k.roughnessMap,C=k.anisotropy>0,te=k.clearcoat>0,ae=k.dispersion>0,Re=k.iridescence>0,De=k.sheen>0,st=k.transmission>0,it=C&&!!k.anisotropyMap,F=te&&!!k.clearcoatMap,le=te&&!!k.clearcoatNormalMap,z=te&&!!k.clearcoatRoughnessMap,j=Re&&!!k.iridescenceMap,B=Re&&!!k.iridescenceThicknessMap,re=De&&!!k.sheenColorMap,Y=De&&!!k.sheenRoughnessMap,me=!!k.specularMap,ee=!!k.specularColorMap,$e=!!k.specularIntensityMap,M=st&&!!k.transmissionMap,K=st&&!!k.thicknessMap,de=!!k.gradientMap,ue=!!k.alphaMap,Ue=k.alphaTest>0,Je=!!k.alphaHash,ht=!!k.extensions;let et=oa;k.toneMapped&&(Se===null||Se.isXRRenderTarget===!0)&&(et=t.toneMapping);const Te={shaderID:tt,shaderType:k.type,shaderName:k.name,vertexShader:Xe,fragmentShader:oe,defines:k.defines,customVertexShaderID:Ie,customFragmentShaderID:nt,isRawShaderMaterial:k.isRawShaderMaterial===!0,glslVersion:k.glslVersion,precision:S,batching:xe,batchingColor:xe&&fe._colorsTexture!==null,instancing:ye,instancingColor:ye&&fe.instanceColor!==null,instancingMorph:ye&&fe.morphTexture!==null,supportsVertexTextures:y,outputColorSpace:Se===null?t.outputColorSpace:Se.isXRRenderTarget===!0?Se.texture.colorSpace:dc,alphaToCoverage:!!k.alphaToCoverage,map:Oe,matcap:at,envMap:Ze,envMapMode:Ze&&_e.mapping,envMapCubeUVHeight:ne,aoMap:U,lightMap:Me,bumpMap:Pe,normalMap:rt,displacementMap:y&&We,emissiveMap:gt,normalMapObjectSpace:rt&&k.normalMapType===Dk,normalMapTangentSpace:rt&&k.normalMapType===Ik,metalnessMap:qe,roughnessMap:q,anisotropy:C,anisotropyMap:it,clearcoat:te,clearcoatMap:F,clearcoatNormalMap:le,clearcoatRoughnessMap:z,dispersion:ae,iridescence:Re,iridescenceMap:j,iridescenceThicknessMap:B,sheen:De,sheenColorMap:re,sheenRoughnessMap:Y,specularMap:me,specularColorMap:ee,specularIntensityMap:$e,transmission:st,transmissionMap:M,thicknessMap:K,gradientMap:de,opaque:k.transparent===!1&&k.blending===nc&&k.alphaToCoverage===!1,alphaMap:ue,alphaTest:Ue,alphaHash:Je,combine:k.combine,mapUv:Oe&&A(k.map.channel),aoMapUv:U&&A(k.aoMap.channel),lightMapUv:Me&&A(k.lightMap.channel),bumpMapUv:Pe&&A(k.bumpMap.channel),normalMapUv:rt&&A(k.normalMap.channel),displacementMapUv:We&&A(k.displacementMap.channel),emissiveMapUv:gt&&A(k.emissiveMap.channel),metalnessMapUv:qe&&A(k.metalnessMap.channel),roughnessMapUv:q&&A(k.roughnessMap.channel),anisotropyMapUv:it&&A(k.anisotropyMap.channel),clearcoatMapUv:F&&A(k.clearcoatMap.channel),clearcoatNormalMapUv:le&&A(k.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:z&&A(k.clearcoatRoughnessMap.channel),iridescenceMapUv:j&&A(k.iridescenceMap.channel),iridescenceThicknessMapUv:B&&A(k.iridescenceThicknessMap.channel),sheenColorMapUv:re&&A(k.sheenColorMap.channel),sheenRoughnessMapUv:Y&&A(k.sheenRoughnessMap.channel),specularMapUv:me&&A(k.specularMap.channel),specularColorMapUv:ee&&A(k.specularColorMap.channel),specularIntensityMapUv:$e&&A(k.specularIntensityMap.channel),transmissionMapUv:M&&A(k.transmissionMap.channel),thicknessMapUv:K&&A(k.thicknessMap.channel),alphaMapUv:ue&&A(k.alphaMap.channel),vertexTangents:!!je.attributes.tangent&&(rt||C),vertexColors:k.vertexColors,vertexAlphas:k.vertexColors===!0&&!!je.attributes.color&&je.attributes.color.itemSize===4,pointsUvs:fe.isPoints===!0&&!!je.attributes.uv&&(Oe||ue),fog:!!Ee,useFog:k.fog===!0,fogExp2:!!Ee&&Ee.isFogExp2,flatShading:k.flatShading===!0,sizeAttenuation:k.sizeAttenuation===!0,logarithmicDepthBuffer:v,reverseDepthBuffer:N,skinning:fe.isSkinnedMesh===!0,morphTargets:je.morphAttributes.position!==void 0,morphNormals:je.morphAttributes.normal!==void 0,morphColors:je.morphAttributes.color!==void 0,morphTargetsCount:$,morphTextureStride:ce,numDirLights:P.directional.length,numPointLights:P.point.length,numSpotLights:P.spot.length,numSpotLightMaps:P.spotLightMap.length,numRectAreaLights:P.rectArea.length,numHemiLights:P.hemi.length,numDirLightShadows:P.directionalShadowMap.length,numPointLightShadows:P.pointShadowMap.length,numSpotLightShadows:P.spotShadowMap.length,numSpotLightShadowsWithMaps:P.numSpotLightShadowsWithMaps,numLightProbes:P.numLightProbes,numClippingPlanes:c.numPlanes,numClipIntersection:c.numIntersection,dithering:k.dithering,shadowMapEnabled:t.shadowMap.enabled&&J.length>0,shadowMapType:t.shadowMap.type,toneMapping:et,decodeVideoTexture:Oe&&k.map.isVideoTexture===!0&&kn.getTransfer(k.map.colorSpace)===Qn,decodeVideoTextureEmissive:gt&&k.emissiveMap.isVideoTexture===!0&&kn.getTransfer(k.emissiveMap.colorSpace)===Qn,premultipliedAlpha:k.premultipliedAlpha,doubleSided:k.side===$o,flipSided:k.side===Do,useDepthPacking:k.depthPacking>=0,depthPacking:k.depthPacking||0,index0AttributeName:k.index0AttributeName,extensionClipCullDistance:ht&&k.extensions.clipCullDistance===!0&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(ht&&k.extensions.multiDraw===!0||xe)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:k.customProgramCacheKey()};return Te.vertexUv1s=d.has(1),Te.vertexUv2s=d.has(2),Te.vertexUv3s=d.has(3),d.clear(),Te}function w(k){const P=[];if(k.shaderID?P.push(k.shaderID):(P.push(k.customVertexShaderID),P.push(k.customFragmentShaderID)),k.defines!==void 0)for(const J in k.defines)P.push(J),P.push(k.defines[J]);return k.isRawShaderMaterial===!1&&(I(P,k),L(P,k),P.push(t.outputColorSpace)),P.push(k.customProgramCacheKey),P.join()}function I(k,P){k.push(P.precision),k.push(P.outputColorSpace),k.push(P.envMapMode),k.push(P.envMapCubeUVHeight),k.push(P.mapUv),k.push(P.alphaMapUv),k.push(P.lightMapUv),k.push(P.aoMapUv),k.push(P.bumpMapUv),k.push(P.normalMapUv),k.push(P.displacementMapUv),k.push(P.emissiveMapUv),k.push(P.metalnessMapUv),k.push(P.roughnessMapUv),k.push(P.anisotropyMapUv),k.push(P.clearcoatMapUv),k.push(P.clearcoatNormalMapUv),k.push(P.clearcoatRoughnessMapUv),k.push(P.iridescenceMapUv),k.push(P.iridescenceThicknessMapUv),k.push(P.sheenColorMapUv),k.push(P.sheenRoughnessMapUv),k.push(P.specularMapUv),k.push(P.specularColorMapUv),k.push(P.specularIntensityMapUv),k.push(P.transmissionMapUv),k.push(P.thicknessMapUv),k.push(P.combine),k.push(P.fogExp2),k.push(P.sizeAttenuation),k.push(P.morphTargetsCount),k.push(P.morphAttributeCount),k.push(P.numDirLights),k.push(P.numPointLights),k.push(P.numSpotLights),k.push(P.numSpotLightMaps),k.push(P.numHemiLights),k.push(P.numRectAreaLights),k.push(P.numDirLightShadows),k.push(P.numPointLightShadows),k.push(P.numSpotLightShadows),k.push(P.numSpotLightShadowsWithMaps),k.push(P.numLightProbes),k.push(P.shadowMapType),k.push(P.toneMapping),k.push(P.numClippingPlanes),k.push(P.numClipIntersection),k.push(P.depthPacking)}function L(k,P){u.disableAll(),P.supportsVertexTextures&&u.enable(0),P.instancing&&u.enable(1),P.instancingColor&&u.enable(2),P.instancingMorph&&u.enable(3),P.matcap&&u.enable(4),P.envMap&&u.enable(5),P.normalMapObjectSpace&&u.enable(6),P.normalMapTangentSpace&&u.enable(7),P.clearcoat&&u.enable(8),P.iridescence&&u.enable(9),P.alphaTest&&u.enable(10),P.vertexColors&&u.enable(11),P.vertexAlphas&&u.enable(12),P.vertexUv1s&&u.enable(13),P.vertexUv2s&&u.enable(14),P.vertexUv3s&&u.enable(15),P.vertexTangents&&u.enable(16),P.anisotropy&&u.enable(17),P.alphaHash&&u.enable(18),P.batching&&u.enable(19),P.dispersion&&u.enable(20),P.batchingColor&&u.enable(21),k.push(u.mask),u.disableAll(),P.fog&&u.enable(0),P.useFog&&u.enable(1),P.flatShading&&u.enable(2),P.logarithmicDepthBuffer&&u.enable(3),P.reverseDepthBuffer&&u.enable(4),P.skinning&&u.enable(5),P.morphTargets&&u.enable(6),P.morphNormals&&u.enable(7),P.morphColors&&u.enable(8),P.premultipliedAlpha&&u.enable(9),P.shadowMapEnabled&&u.enable(10),P.doubleSided&&u.enable(11),P.flipSided&&u.enable(12),P.useDepthPacking&&u.enable(13),P.dithering&&u.enable(14),P.transmission&&u.enable(15),P.sheen&&u.enable(16),P.opaque&&u.enable(17),P.pointsUvs&&u.enable(18),P.decodeVideoTexture&&u.enable(19),P.decodeVideoTextureEmissive&&u.enable(20),P.alphaToCoverage&&u.enable(21),k.push(u.mask)}function D(k){const P=T[k.type];let J;if(P){const ve=Fs[P];J=cz.clone(ve.uniforms)}else J=k.uniforms;return J}function W(k,P){let J;for(let ve=0,fe=g.length;ve0?i.push(w):S.transparent===!0?r.push(w):n.push(w)}function h(v,y,S,T,A,E){const w=c(v,y,S,T,A,E);S.transmission>0?i.unshift(w):S.transparent===!0?r.unshift(w):n.unshift(w)}function d(v,y){n.length>1&&n.sort(v||B4),i.length>1&&i.sort(y||aT),r.length>1&&r.sort(y||aT)}function g(){for(let v=e,y=t.length;v=a.length?(c=new lT,a.push(c)):c=a[r],c}function n(){t=new WeakMap}return{get:e,dispose:n}}function H4(){const t={};return{get:function(e){if(t[e.id]!==void 0)return t[e.id];let n;switch(e.type){case"DirectionalLight":n={direction:new Le,color:new An};break;case"SpotLight":n={position:new Le,direction:new Le,color:new An,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new Le,color:new An,distance:0,decay:0};break;case"HemisphereLight":n={direction:new Le,skyColor:new An,groundColor:new An};break;case"RectAreaLight":n={color:new An,position:new Le,halfWidth:new Le,halfHeight:new Le};break}return t[e.id]=n,n}}}function G4(){const t={};return{get:function(e){if(t[e.id]!==void 0)return t[e.id];let n;switch(e.type){case"DirectionalLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Bn};break;case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Bn};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Bn,shadowCameraNear:1,shadowCameraFar:1e3};break}return t[e.id]=n,n}}}let j4=0;function q4(t,e){return(e.castShadow?2:0)-(t.castShadow?2:0)+(e.map?1:0)-(t.map?1:0)}function W4(t){const e=new H4,n=G4(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let d=0;d<9;d++)i.probe.push(new Le);const r=new Le,a=new ui,c=new ui;function u(d){let g=0,v=0,y=0;for(let k=0;k<9;k++)i.probe[k].set(0,0,0);let S=0,T=0,A=0,E=0,w=0,I=0,L=0,D=0,W=0,V=0,H=0;d.sort(q4);for(let k=0,P=d.length;k0&&(t.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=St.LTC_FLOAT_1,i.rectAreaLTC2=St.LTC_FLOAT_2):(i.rectAreaLTC1=St.LTC_HALF_1,i.rectAreaLTC2=St.LTC_HALF_2)),i.ambient[0]=g,i.ambient[1]=v,i.ambient[2]=y;const Q=i.hash;(Q.directionalLength!==S||Q.pointLength!==T||Q.spotLength!==A||Q.rectAreaLength!==E||Q.hemiLength!==w||Q.numDirectionalShadows!==I||Q.numPointShadows!==L||Q.numSpotShadows!==D||Q.numSpotMaps!==W||Q.numLightProbes!==H)&&(i.directional.length=S,i.spot.length=A,i.rectArea.length=E,i.point.length=T,i.hemi.length=w,i.directionalShadow.length=I,i.directionalShadowMap.length=I,i.pointShadow.length=L,i.pointShadowMap.length=L,i.spotShadow.length=D,i.spotShadowMap.length=D,i.directionalShadowMatrix.length=I,i.pointShadowMatrix.length=L,i.spotLightMatrix.length=D+W-V,i.spotLightMap.length=W,i.numSpotLightShadowsWithMaps=V,i.numLightProbes=H,Q.directionalLength=S,Q.pointLength=T,Q.spotLength=A,Q.rectAreaLength=E,Q.hemiLength=w,Q.numDirectionalShadows=I,Q.numPointShadows=L,Q.numSpotShadows=D,Q.numSpotMaps=W,Q.numLightProbes=H,i.version=j4++)}function h(d,g){let v=0,y=0,S=0,T=0,A=0;const E=g.matrixWorldInverse;for(let w=0,I=d.length;w=c.length?(u=new cT(t),c.push(u)):u=c[a],u}function i(){e=new WeakMap}return{get:n,dispose:i}}const X4=`void main() { + gl_Position = vec4( position, 1.0 ); +}`,Y4=`uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +#include +void main() { + const float samples = float( VSM_SAMPLES ); + float mean = 0.0; + float squared_mean = 0.0; + float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); + float uvStart = samples <= 1.0 ? 0.0 : - 1.0; + for ( float i = 0.0; i < samples; i ++ ) { + float uvOffset = uvStart + i * uvStride; + #ifdef HORIZONTAL_PASS + vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); + mean += distribution.x; + squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; + #else + float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); + mean += depth; + squared_mean += depth * depth; + #endif + } + mean = mean / samples; + squared_mean = squared_mean / samples; + float std_dev = sqrt( squared_mean - mean * mean ); + gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); +}`;function J4(t,e,n){let i=new PE;const r=new Bn,a=new Bn,c=new Ii,u=new bz({depthPacking:Nk}),h=new Sz,d={},g=n.maxTextureSize,v={[sa]:Do,[Do]:sa,[$o]:$o},y=new ra({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Bn},radius:{value:4}},vertexShader:X4,fragmentShader:Y4}),S=y.clone();S.defines.HORIZONTAL_PASS=1;const T=new xi;T.setAttribute("position",new Vi(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const A=new Ni(T,y),E=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=mE;let w=this.type;this.render=function(V,H,Q){if(E.enabled===!1||E.autoUpdate===!1&&E.needsUpdate===!1||V.length===0)return;const k=t.getRenderTarget(),P=t.getActiveCubeFace(),J=t.getActiveMipmapLevel(),ve=t.state;ve.setBlending(ia),ve.buffers.color.setClear(1,1,1,1),ve.buffers.depth.setTest(!0),ve.setScissorTest(!1);const fe=w!==fr&&this.type===fr,Ee=w===fr&&this.type!==fr;for(let je=0,X=V.length;jeg||r.y>g)&&(r.x>g&&(a.x=Math.floor(g/tt.x),r.x=a.x*tt.x,ne.mapSize.x=a.x),r.y>g&&(a.y=Math.floor(g/tt.y),r.y=a.y*tt.y,ne.mapSize.y=a.y)),ne.map===null||fe===!0||Ee===!0){const $=this.type!==fr?{minFilter:Jo,magFilter:Jo}:{};ne.map!==null&&ne.map.dispose(),ne.map=new Wa(r.x,r.y,$),ne.map.texture.name=_e.name+".shadowMap",ne.camera.updateProjectionMatrix()}t.setRenderTarget(ne.map),t.clear();const Ce=ne.getViewportCount();for(let $=0;$0||H.map&&H.alphaTest>0){const ve=P.uuid,fe=H.uuid;let Ee=d[ve];Ee===void 0&&(Ee={},d[ve]=Ee);let je=Ee[fe];je===void 0&&(je=P.clone(),Ee[fe]=je,H.addEventListener("dispose",W)),P=je}if(P.visible=H.visible,P.wireframe=H.wireframe,k===fr?P.side=H.shadowSide!==null?H.shadowSide:H.side:P.side=H.shadowSide!==null?H.shadowSide:v[H.side],P.alphaMap=H.alphaMap,P.alphaTest=H.alphaTest,P.map=H.map,P.clipShadows=H.clipShadows,P.clippingPlanes=H.clippingPlanes,P.clipIntersection=H.clipIntersection,P.displacementMap=H.displacementMap,P.displacementScale=H.displacementScale,P.displacementBias=H.displacementBias,P.wireframeLinewidth=H.wireframeLinewidth,P.linewidth=H.linewidth,Q.isPointLight===!0&&P.isMeshDistanceMaterial===!0){const ve=t.properties.get(P);ve.light=Q}return P}function D(V,H,Q,k,P){if(V.visible===!1)return;if(V.layers.test(H.layers)&&(V.isMesh||V.isLine||V.isPoints)&&(V.castShadow||V.receiveShadow&&P===fr)&&(!V.frustumCulled||i.intersectsObject(V))){V.modelViewMatrix.multiplyMatrices(Q.matrixWorldInverse,V.matrixWorld);const fe=e.update(V),Ee=V.material;if(Array.isArray(Ee)){const je=fe.groups;for(let X=0,_e=je.length;X<_e;X++){const ne=je[X],tt=Ee[ne.materialIndex];if(tt&&tt.visible){const Ce=L(V,tt,k,P);V.onBeforeShadow(t,V,H,Q,fe,Ce,ne),t.renderBufferDirect(Q,null,fe,Ce,V,ne),V.onAfterShadow(t,V,H,Q,fe,Ce,ne)}}}else if(Ee.visible){const je=L(V,Ee,k,P);V.onBeforeShadow(t,V,H,Q,fe,je,null),t.renderBufferDirect(Q,null,fe,je,V,null),V.onAfterShadow(t,V,H,Q,fe,je,null)}}const ve=V.children;for(let fe=0,Ee=ve.length;fe=1):ne.indexOf("OpenGL ES")!==-1&&(_e=parseFloat(/^OpenGL ES (\d)/.exec(ne)[1]),X=_e>=2);let tt=null,Ce={};const $=t.getParameter(t.SCISSOR_BOX),ce=t.getParameter(t.VIEWPORT),Xe=new Ii().fromArray($),oe=new Ii().fromArray(ce);function Ie(M,K,de,ue){const Ue=new Uint8Array(4),Je=t.createTexture();t.bindTexture(M,Je),t.texParameteri(M,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(M,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let ht=0;ht"u"?!1:/OculusBrowser/g.test(navigator.userAgent),d=new Bn,g=new WeakMap;let v;const y=new WeakMap;let S=!1;try{S=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function T(q,C){return S?new OffscreenCanvas(q,C):lh("canvas")}function A(q,C,te){let ae=1;const Re=qe(q);if((Re.width>te||Re.height>te)&&(ae=te/Math.max(Re.width,Re.height)),ae<1)if(typeof HTMLImageElement<"u"&&q instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&q instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&q instanceof ImageBitmap||typeof VideoFrame<"u"&&q instanceof VideoFrame){const De=Math.floor(ae*Re.width),st=Math.floor(ae*Re.height);v===void 0&&(v=T(De,st));const it=C?T(De,st):v;return it.width=De,it.height=st,it.getContext("2d").drawImage(q,0,0,De,st),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+Re.width+"x"+Re.height+") to ("+De+"x"+st+")."),it}else return"data"in q&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+Re.width+"x"+Re.height+")."),q;return q}function E(q){return q.generateMipmaps}function w(q){t.generateMipmap(q)}function I(q){return q.isWebGLCubeRenderTarget?t.TEXTURE_CUBE_MAP:q.isWebGL3DRenderTarget?t.TEXTURE_3D:q.isWebGLArrayRenderTarget||q.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:t.TEXTURE_2D}function L(q,C,te,ae,Re=!1){if(q!==null){if(t[q]!==void 0)return t[q];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+q+"'")}let De=C;if(C===t.RED&&(te===t.FLOAT&&(De=t.R32F),te===t.HALF_FLOAT&&(De=t.R16F),te===t.UNSIGNED_BYTE&&(De=t.R8)),C===t.RED_INTEGER&&(te===t.UNSIGNED_BYTE&&(De=t.R8UI),te===t.UNSIGNED_SHORT&&(De=t.R16UI),te===t.UNSIGNED_INT&&(De=t.R32UI),te===t.BYTE&&(De=t.R8I),te===t.SHORT&&(De=t.R16I),te===t.INT&&(De=t.R32I)),C===t.RG&&(te===t.FLOAT&&(De=t.RG32F),te===t.HALF_FLOAT&&(De=t.RG16F),te===t.UNSIGNED_BYTE&&(De=t.RG8)),C===t.RG_INTEGER&&(te===t.UNSIGNED_BYTE&&(De=t.RG8UI),te===t.UNSIGNED_SHORT&&(De=t.RG16UI),te===t.UNSIGNED_INT&&(De=t.RG32UI),te===t.BYTE&&(De=t.RG8I),te===t.SHORT&&(De=t.RG16I),te===t.INT&&(De=t.RG32I)),C===t.RGB_INTEGER&&(te===t.UNSIGNED_BYTE&&(De=t.RGB8UI),te===t.UNSIGNED_SHORT&&(De=t.RGB16UI),te===t.UNSIGNED_INT&&(De=t.RGB32UI),te===t.BYTE&&(De=t.RGB8I),te===t.SHORT&&(De=t.RGB16I),te===t.INT&&(De=t.RGB32I)),C===t.RGBA_INTEGER&&(te===t.UNSIGNED_BYTE&&(De=t.RGBA8UI),te===t.UNSIGNED_SHORT&&(De=t.RGBA16UI),te===t.UNSIGNED_INT&&(De=t.RGBA32UI),te===t.BYTE&&(De=t.RGBA8I),te===t.SHORT&&(De=t.RGBA16I),te===t.INT&&(De=t.RGBA32I)),C===t.RGB&&te===t.UNSIGNED_INT_5_9_9_9_REV&&(De=t.RGB9_E5),C===t.RGBA){const st=Re?rh:kn.getTransfer(ae);te===t.FLOAT&&(De=t.RGBA32F),te===t.HALF_FLOAT&&(De=t.RGBA16F),te===t.UNSIGNED_BYTE&&(De=st===Qn?t.SRGB8_ALPHA8:t.RGBA8),te===t.UNSIGNED_SHORT_4_4_4_4&&(De=t.RGBA4),te===t.UNSIGNED_SHORT_5_5_5_1&&(De=t.RGB5_A1)}return(De===t.R16F||De===t.R32F||De===t.RG16F||De===t.RG32F||De===t.RGBA16F||De===t.RGBA32F)&&e.get("EXT_color_buffer_float"),De}function D(q,C){let te;return q?C===null||C===qa||C===cc?te=t.DEPTH24_STENCIL8:C===Vs?te=t.DEPTH32F_STENCIL8:C===Pu&&(te=t.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):C===null||C===qa||C===cc?te=t.DEPTH_COMPONENT24:C===Vs?te=t.DEPTH_COMPONENT32F:C===Pu&&(te=t.DEPTH_COMPONENT16),te}function W(q,C){return E(q)===!0||q.isFramebufferTexture&&q.minFilter!==Jo&&q.minFilter!==Bs?Math.log2(Math.max(C.width,C.height))+1:q.mipmaps!==void 0&&q.mipmaps.length>0?q.mipmaps.length:q.isCompressedTexture&&Array.isArray(q.image)?C.mipmaps.length:1}function V(q){const C=q.target;C.removeEventListener("dispose",V),Q(C),C.isVideoTexture&&g.delete(C)}function H(q){const C=q.target;C.removeEventListener("dispose",H),P(C)}function Q(q){const C=i.get(q);if(C.__webglInit===void 0)return;const te=q.source,ae=y.get(te);if(ae){const Re=ae[C.__cacheKey];Re.usedTimes--,Re.usedTimes===0&&k(q),Object.keys(ae).length===0&&y.delete(te)}i.remove(q)}function k(q){const C=i.get(q);t.deleteTexture(C.__webglTexture);const te=q.source,ae=y.get(te);delete ae[C.__cacheKey],c.memory.textures--}function P(q){const C=i.get(q);if(q.depthTexture&&(q.depthTexture.dispose(),i.remove(q.depthTexture)),q.isWebGLCubeRenderTarget)for(let ae=0;ae<6;ae++){if(Array.isArray(C.__webglFramebuffer[ae]))for(let Re=0;Re=r.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+q+" texture units while this GPU supports only "+r.maxTextures),J+=1,q}function Ee(q){const C=[];return C.push(q.wrapS),C.push(q.wrapT),C.push(q.wrapR||0),C.push(q.magFilter),C.push(q.minFilter),C.push(q.anisotropy),C.push(q.internalFormat),C.push(q.format),C.push(q.type),C.push(q.generateMipmaps),C.push(q.premultiplyAlpha),C.push(q.flipY),C.push(q.unpackAlignment),C.push(q.colorSpace),C.join()}function je(q,C){const te=i.get(q);if(q.isVideoTexture&&We(q),q.isRenderTargetTexture===!1&&q.version>0&&te.__version!==q.version){const ae=q.image;if(ae===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(ae.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{oe(te,q,C);return}}n.bindTexture(t.TEXTURE_2D,te.__webglTexture,t.TEXTURE0+C)}function X(q,C){const te=i.get(q);if(q.version>0&&te.__version!==q.version){oe(te,q,C);return}n.bindTexture(t.TEXTURE_2D_ARRAY,te.__webglTexture,t.TEXTURE0+C)}function _e(q,C){const te=i.get(q);if(q.version>0&&te.__version!==q.version){oe(te,q,C);return}n.bindTexture(t.TEXTURE_3D,te.__webglTexture,t.TEXTURE0+C)}function ne(q,C){const te=i.get(q);if(q.version>0&&te.__version!==q.version){Ie(te,q,C);return}n.bindTexture(t.TEXTURE_CUBE_MAP,te.__webglTexture,t.TEXTURE0+C)}const tt={[Y0]:t.REPEAT,[Va]:t.CLAMP_TO_EDGE,[J0]:t.MIRRORED_REPEAT},Ce={[Jo]:t.NEAREST,[Ak]:t.NEAREST_MIPMAP_NEAREST,[of]:t.NEAREST_MIPMAP_LINEAR,[Bs]:t.LINEAR,[Fm]:t.LINEAR_MIPMAP_NEAREST,[Ha]:t.LINEAR_MIPMAP_LINEAR},$={[Lk]:t.NEVER,[Ok]:t.ALWAYS,[Uk]:t.LESS,[CE]:t.LEQUAL,[kk]:t.EQUAL,[Fk]:t.GEQUAL,[zk]:t.GREATER,[Pk]:t.NOTEQUAL};function ce(q,C){if(C.type===Vs&&e.has("OES_texture_float_linear")===!1&&(C.magFilter===Bs||C.magFilter===Fm||C.magFilter===of||C.magFilter===Ha||C.minFilter===Bs||C.minFilter===Fm||C.minFilter===of||C.minFilter===Ha)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),t.texParameteri(q,t.TEXTURE_WRAP_S,tt[C.wrapS]),t.texParameteri(q,t.TEXTURE_WRAP_T,tt[C.wrapT]),(q===t.TEXTURE_3D||q===t.TEXTURE_2D_ARRAY)&&t.texParameteri(q,t.TEXTURE_WRAP_R,tt[C.wrapR]),t.texParameteri(q,t.TEXTURE_MAG_FILTER,Ce[C.magFilter]),t.texParameteri(q,t.TEXTURE_MIN_FILTER,Ce[C.minFilter]),C.compareFunction&&(t.texParameteri(q,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(q,t.TEXTURE_COMPARE_FUNC,$[C.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(C.magFilter===Jo||C.minFilter!==of&&C.minFilter!==Ha||C.type===Vs&&e.has("OES_texture_float_linear")===!1)return;if(C.anisotropy>1||i.get(C).__currentAnisotropy){const te=e.get("EXT_texture_filter_anisotropic");t.texParameterf(q,te.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(C.anisotropy,r.getMaxAnisotropy())),i.get(C).__currentAnisotropy=C.anisotropy}}}function Xe(q,C){let te=!1;q.__webglInit===void 0&&(q.__webglInit=!0,C.addEventListener("dispose",V));const ae=C.source;let Re=y.get(ae);Re===void 0&&(Re={},y.set(ae,Re));const De=Ee(C);if(De!==q.__cacheKey){Re[De]===void 0&&(Re[De]={texture:t.createTexture(),usedTimes:0},c.memory.textures++,te=!0),Re[De].usedTimes++;const st=Re[q.__cacheKey];st!==void 0&&(Re[q.__cacheKey].usedTimes--,st.usedTimes===0&&k(C)),q.__cacheKey=De,q.__webglTexture=Re[De].texture}return te}function oe(q,C,te){let ae=t.TEXTURE_2D;(C.isDataArrayTexture||C.isCompressedArrayTexture)&&(ae=t.TEXTURE_2D_ARRAY),C.isData3DTexture&&(ae=t.TEXTURE_3D);const Re=Xe(q,C),De=C.source;n.bindTexture(ae,q.__webglTexture,t.TEXTURE0+te);const st=i.get(De);if(De.version!==st.__version||Re===!0){n.activeTexture(t.TEXTURE0+te);const it=kn.getPrimaries(kn.workingColorSpace),F=C.colorSpace===na?null:kn.getPrimaries(C.colorSpace),le=C.colorSpace===na||it===F?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,C.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,C.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,C.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,le);let z=A(C.image,!1,r.maxTextureSize);z=gt(C,z);const j=a.convert(C.format,C.colorSpace),B=a.convert(C.type);let re=L(C.internalFormat,j,B,C.colorSpace,C.isVideoTexture);ce(ae,C);let Y;const me=C.mipmaps,ee=C.isVideoTexture!==!0,$e=st.__version===void 0||Re===!0,M=De.dataReady,K=W(C,z);if(C.isDepthTexture)re=D(C.format===uc,C.type),$e&&(ee?n.texStorage2D(t.TEXTURE_2D,1,re,z.width,z.height):n.texImage2D(t.TEXTURE_2D,0,re,z.width,z.height,0,j,B,null));else if(C.isDataTexture)if(me.length>0){ee&&$e&&n.texStorage2D(t.TEXTURE_2D,K,re,me[0].width,me[0].height);for(let de=0,ue=me.length;de0){const Ue=O1(Y.width,Y.height,C.format,C.type);for(const Je of C.layerUpdates){const ht=Y.data.subarray(Je*Ue/Y.data.BYTES_PER_ELEMENT,(Je+1)*Ue/Y.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,de,0,0,Je,Y.width,Y.height,1,j,ht)}C.clearLayerUpdates()}else n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,de,0,0,0,Y.width,Y.height,z.depth,j,Y.data)}else n.compressedTexImage3D(t.TEXTURE_2D_ARRAY,de,re,Y.width,Y.height,z.depth,0,Y.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else ee?M&&n.texSubImage3D(t.TEXTURE_2D_ARRAY,de,0,0,0,Y.width,Y.height,z.depth,j,B,Y.data):n.texImage3D(t.TEXTURE_2D_ARRAY,de,re,Y.width,Y.height,z.depth,0,j,B,Y.data)}else{ee&&$e&&n.texStorage2D(t.TEXTURE_2D,K,re,me[0].width,me[0].height);for(let de=0,ue=me.length;de0){const de=O1(z.width,z.height,C.format,C.type);for(const ue of C.layerUpdates){const Ue=z.data.subarray(ue*de/z.data.BYTES_PER_ELEMENT,(ue+1)*de/z.data.BYTES_PER_ELEMENT);n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,ue,z.width,z.height,1,j,B,Ue)}C.clearLayerUpdates()}else n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,0,z.width,z.height,z.depth,j,B,z.data)}else n.texImage3D(t.TEXTURE_2D_ARRAY,0,re,z.width,z.height,z.depth,0,j,B,z.data);else if(C.isData3DTexture)ee?($e&&n.texStorage3D(t.TEXTURE_3D,K,re,z.width,z.height,z.depth),M&&n.texSubImage3D(t.TEXTURE_3D,0,0,0,0,z.width,z.height,z.depth,j,B,z.data)):n.texImage3D(t.TEXTURE_3D,0,re,z.width,z.height,z.depth,0,j,B,z.data);else if(C.isFramebufferTexture){if($e)if(ee)n.texStorage2D(t.TEXTURE_2D,K,re,z.width,z.height);else{let de=z.width,ue=z.height;for(let Ue=0;Ue>=1,ue>>=1}}else if(me.length>0){if(ee&&$e){const de=qe(me[0]);n.texStorage2D(t.TEXTURE_2D,K,re,de.width,de.height)}for(let de=0,ue=me.length;de0&&K++;const ue=qe(j[0]);n.texStorage2D(t.TEXTURE_CUBE_MAP,K,me,ue.width,ue.height)}for(let ue=0;ue<6;ue++)if(z){ee?M&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ue,0,0,0,j[ue].width,j[ue].height,re,Y,j[ue].data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ue,0,me,j[ue].width,j[ue].height,0,re,Y,j[ue].data);for(let Ue=0;Ue>De),B=Math.max(1,C.height>>De);Re===t.TEXTURE_3D||Re===t.TEXTURE_2D_ARRAY?n.texImage3D(Re,De,F,j,B,C.depth,0,st,it,null):n.texImage2D(Re,De,F,j,B,0,st,it,null)}n.bindFramebuffer(t.FRAMEBUFFER,q),rt(C)?u.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,ae,Re,z.__webglTexture,0,Pe(C)):(Re===t.TEXTURE_2D||Re>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&Re<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,ae,Re,z.__webglTexture,De),n.bindFramebuffer(t.FRAMEBUFFER,null)}function Se(q,C,te){if(t.bindRenderbuffer(t.RENDERBUFFER,q),C.depthBuffer){const ae=C.depthTexture,Re=ae&&ae.isDepthTexture?ae.type:null,De=D(C.stencilBuffer,Re),st=C.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,it=Pe(C);rt(C)?u.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,it,De,C.width,C.height):te?t.renderbufferStorageMultisample(t.RENDERBUFFER,it,De,C.width,C.height):t.renderbufferStorage(t.RENDERBUFFER,De,C.width,C.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,st,t.RENDERBUFFER,q)}else{const ae=C.textures;for(let Re=0;Re{delete C.__boundDepthTexture,delete C.__depthDisposeCallback,ae.removeEventListener("dispose",Re)};ae.addEventListener("dispose",Re),C.__depthDisposeCallback=Re}C.__boundDepthTexture=ae}if(q.depthTexture&&!C.__autoAllocateDepthBuffer){if(te)throw new Error("target.depthTexture not supported in Cube render targets");N(C.__webglFramebuffer,q)}else if(te){C.__webglDepthbuffer=[];for(let ae=0;ae<6;ae++)if(n.bindFramebuffer(t.FRAMEBUFFER,C.__webglFramebuffer[ae]),C.__webglDepthbuffer[ae]===void 0)C.__webglDepthbuffer[ae]=t.createRenderbuffer(),Se(C.__webglDepthbuffer[ae],q,!1);else{const Re=q.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,De=C.__webglDepthbuffer[ae];t.bindRenderbuffer(t.RENDERBUFFER,De),t.framebufferRenderbuffer(t.FRAMEBUFFER,Re,t.RENDERBUFFER,De)}}else if(n.bindFramebuffer(t.FRAMEBUFFER,C.__webglFramebuffer),C.__webglDepthbuffer===void 0)C.__webglDepthbuffer=t.createRenderbuffer(),Se(C.__webglDepthbuffer,q,!1);else{const ae=q.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,Re=C.__webglDepthbuffer;t.bindRenderbuffer(t.RENDERBUFFER,Re),t.framebufferRenderbuffer(t.FRAMEBUFFER,ae,t.RENDERBUFFER,Re)}n.bindFramebuffer(t.FRAMEBUFFER,null)}function xe(q,C,te){const ae=i.get(q);C!==void 0&&nt(ae.__webglFramebuffer,q,q.texture,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,0),te!==void 0&&ye(q)}function Oe(q){const C=q.texture,te=i.get(q),ae=i.get(C);q.addEventListener("dispose",H);const Re=q.textures,De=q.isWebGLCubeRenderTarget===!0,st=Re.length>1;if(st||(ae.__webglTexture===void 0&&(ae.__webglTexture=t.createTexture()),ae.__version=C.version,c.memory.textures++),De){te.__webglFramebuffer=[];for(let it=0;it<6;it++)if(C.mipmaps&&C.mipmaps.length>0){te.__webglFramebuffer[it]=[];for(let F=0;F0){te.__webglFramebuffer=[];for(let it=0;it0&&rt(q)===!1){te.__webglMultisampledFramebuffer=t.createFramebuffer(),te.__webglColorRenderbuffer=[],n.bindFramebuffer(t.FRAMEBUFFER,te.__webglMultisampledFramebuffer);for(let it=0;it0)for(let F=0;F0)for(let F=0;F0){if(rt(q)===!1){const C=q.textures,te=q.width,ae=q.height;let Re=t.COLOR_BUFFER_BIT;const De=q.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,st=i.get(q),it=C.length>1;if(it)for(let F=0;F0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&C.__useRenderToTexture!==!1}function We(q){const C=c.render.frame;g.get(q)!==C&&(g.set(q,C),q.update())}function gt(q,C){const te=q.colorSpace,ae=q.format,Re=q.type;return q.isCompressedTexture===!0||q.isVideoTexture===!0||te!==dc&&te!==na&&(kn.getTransfer(te)===Qn?(ae!==ws||Re!==yr)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",te)),C}function qe(q){return typeof HTMLImageElement<"u"&&q instanceof HTMLImageElement?(d.width=q.naturalWidth||q.width,d.height=q.naturalHeight||q.height):typeof VideoFrame<"u"&&q instanceof VideoFrame?(d.width=q.displayWidth,d.height=q.displayHeight):(d.width=q.width,d.height=q.height),d}this.allocateTextureUnit=fe,this.resetTextureUnits=ve,this.setTexture2D=je,this.setTexture2DArray=X,this.setTexture3D=_e,this.setTextureCube=ne,this.rebindTextures=xe,this.setupRenderTarget=Oe,this.updateRenderTargetMipmap=at,this.updateMultisampleRenderTarget=Me,this.setupDepthRenderbuffer=ye,this.setupFrameBufferTexture=nt,this.useMultisampledRTT=rt}function eO(t,e){function n(i,r=na){let a;const c=kn.getTransfer(r);if(i===yr)return t.UNSIGNED_BYTE;if(i===nv)return t.UNSIGNED_SHORT_4_4_4_4;if(i===iv)return t.UNSIGNED_SHORT_5_5_5_1;if(i===_E)return t.UNSIGNED_INT_5_9_9_9_REV;if(i===xE)return t.BYTE;if(i===yE)return t.SHORT;if(i===Pu)return t.UNSIGNED_SHORT;if(i===tv)return t.INT;if(i===qa)return t.UNSIGNED_INT;if(i===Vs)return t.FLOAT;if(i===Bu)return t.HALF_FLOAT;if(i===bE)return t.ALPHA;if(i===SE)return t.RGB;if(i===ws)return t.RGBA;if(i===TE)return t.LUMINANCE;if(i===EE)return t.LUMINANCE_ALPHA;if(i===ic)return t.DEPTH_COMPONENT;if(i===uc)return t.DEPTH_STENCIL;if(i===ov)return t.RED;if(i===sv)return t.RED_INTEGER;if(i===wE)return t.RG;if(i===rv)return t.RG_INTEGER;if(i===av)return t.RGBA_INTEGER;if(i===Pf||i===Ff||i===Of||i===Bf)if(c===Qn)if(a=e.get("WEBGL_compressed_texture_s3tc_srgb"),a!==null){if(i===Pf)return a.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===Ff)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===Of)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===Bf)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(a=e.get("WEBGL_compressed_texture_s3tc"),a!==null){if(i===Pf)return a.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===Ff)return a.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===Of)return a.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===Bf)return a.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===K0||i===Z0||i===Q0||i===eg)if(a=e.get("WEBGL_compressed_texture_pvrtc"),a!==null){if(i===K0)return a.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===Z0)return a.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===Q0)return a.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===eg)return a.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===tg||i===ng||i===ig)if(a=e.get("WEBGL_compressed_texture_etc"),a!==null){if(i===tg||i===ng)return c===Qn?a.COMPRESSED_SRGB8_ETC2:a.COMPRESSED_RGB8_ETC2;if(i===ig)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:a.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(i===og||i===sg||i===rg||i===ag||i===lg||i===cg||i===ug||i===dg||i===fg||i===hg||i===pg||i===mg||i===gg||i===vg)if(a=e.get("WEBGL_compressed_texture_astc"),a!==null){if(i===og)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:a.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===sg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:a.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===rg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:a.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===ag)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:a.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===lg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:a.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===cg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:a.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===ug)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:a.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===dg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:a.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===fg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:a.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===hg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:a.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===pg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:a.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===mg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:a.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===gg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:a.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===vg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:a.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===Vf||i===xg||i===yg)if(a=e.get("EXT_texture_compression_bptc"),a!==null){if(i===Vf)return c===Qn?a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:a.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===xg)return a.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===yg)return a.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===ME||i===_g||i===bg||i===Sg)if(a=e.get("EXT_texture_compression_rgtc"),a!==null){if(i===Vf)return a.COMPRESSED_RED_RGTC1_EXT;if(i===_g)return a.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===bg)return a.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===Sg)return a.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===cc?t.UNSIGNED_INT_24_8:t[i]!==void 0?t[i]:null}return{convert:n}}const tO=` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`,nO=` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`;class iO{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,n,i){if(this.texture===null){const r=new To,a=e.properties.get(r);a.__webglTexture=n.texture,(n.depthNear!==i.depthNear||n.depthFar!==i.depthFar)&&(this.depthNear=n.depthNear,this.depthFar=n.depthFar),this.texture=r}}getMesh(e){if(this.texture!==null&&this.mesh===null){const n=e.cameras[0].viewport,i=new ra({vertexShader:tO,fragmentShader:nO,uniforms:{depthColor:{value:this.texture},depthWidth:{value:n.z},depthHeight:{value:n.w}}});this.mesh=new Ni(new Ga(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class oO extends xc{constructor(e,n){super();const i=this;let r=null,a=1,c=null,u="local-floor",h=1,d=null,g=null,v=null,y=null,S=null,T=null;const A=new iO,E=n.getContextAttributes();let w=null,I=null;const L=[],D=[],W=new Bn;let V=null;const H=new fs;H.viewport=new Ii;const Q=new fs;Q.viewport=new Ii;const k=[H,Q],P=new Ez;let J=null,ve=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(oe){let Ie=L[oe];return Ie===void 0&&(Ie=new r0,L[oe]=Ie),Ie.getTargetRaySpace()},this.getControllerGrip=function(oe){let Ie=L[oe];return Ie===void 0&&(Ie=new r0,L[oe]=Ie),Ie.getGripSpace()},this.getHand=function(oe){let Ie=L[oe];return Ie===void 0&&(Ie=new r0,L[oe]=Ie),Ie.getHandSpace()};function fe(oe){const Ie=D.indexOf(oe.inputSource);if(Ie===-1)return;const nt=L[Ie];nt!==void 0&&(nt.update(oe.inputSource,oe.frame,d||c),nt.dispatchEvent({type:oe.type,data:oe.inputSource}))}function Ee(){r.removeEventListener("select",fe),r.removeEventListener("selectstart",fe),r.removeEventListener("selectend",fe),r.removeEventListener("squeeze",fe),r.removeEventListener("squeezestart",fe),r.removeEventListener("squeezeend",fe),r.removeEventListener("end",Ee),r.removeEventListener("inputsourceschange",je);for(let oe=0;oe=0&&(D[Se]=null,L[Se].disconnect(nt))}for(let Ie=0;Ie=D.length){D.push(nt),Se=ye;break}else if(D[ye]===null){D[ye]=nt,Se=ye;break}if(Se===-1)break}const N=L[Se];N&&N.connect(nt)}}const X=new Le,_e=new Le;function ne(oe,Ie,nt){X.setFromMatrixPosition(Ie.matrixWorld),_e.setFromMatrixPosition(nt.matrixWorld);const Se=X.distanceTo(_e),N=Ie.projectionMatrix.elements,ye=nt.projectionMatrix.elements,xe=N[14]/(N[10]-1),Oe=N[14]/(N[10]+1),at=(N[9]+1)/N[5],Ze=(N[9]-1)/N[5],U=(N[8]-1)/N[0],Me=(ye[8]+1)/ye[0],Pe=xe*U,rt=xe*Me,We=Se/(-U+Me),gt=We*-U;if(Ie.matrixWorld.decompose(oe.position,oe.quaternion,oe.scale),oe.translateX(gt),oe.translateZ(We),oe.matrixWorld.compose(oe.position,oe.quaternion,oe.scale),oe.matrixWorldInverse.copy(oe.matrixWorld).invert(),N[10]===-1)oe.projectionMatrix.copy(Ie.projectionMatrix),oe.projectionMatrixInverse.copy(Ie.projectionMatrixInverse);else{const qe=xe+We,q=Oe+We,C=Pe-gt,te=rt+(Se-gt),ae=at*Oe/q*qe,Re=Ze*Oe/q*qe;oe.projectionMatrix.makePerspective(C,te,ae,Re,qe,q),oe.projectionMatrixInverse.copy(oe.projectionMatrix).invert()}}function tt(oe,Ie){Ie===null?oe.matrixWorld.copy(oe.matrix):oe.matrixWorld.multiplyMatrices(Ie.matrixWorld,oe.matrix),oe.matrixWorldInverse.copy(oe.matrixWorld).invert()}this.updateCamera=function(oe){if(r===null)return;let Ie=oe.near,nt=oe.far;A.texture!==null&&(A.depthNear>0&&(Ie=A.depthNear),A.depthFar>0&&(nt=A.depthFar)),P.near=Q.near=H.near=Ie,P.far=Q.far=H.far=nt,(J!==P.near||ve!==P.far)&&(r.updateRenderState({depthNear:P.near,depthFar:P.far}),J=P.near,ve=P.far),H.layers.mask=oe.layers.mask|2,Q.layers.mask=oe.layers.mask|4,P.layers.mask=H.layers.mask|Q.layers.mask;const Se=oe.parent,N=P.cameras;tt(P,Se);for(let ye=0;ye0&&(E.alphaTest.value=w.alphaTest);const I=e.get(w),L=I.envMap,D=I.envMapRotation;L&&(E.envMap.value=L,Aa.copy(D),Aa.x*=-1,Aa.y*=-1,Aa.z*=-1,L.isCubeTexture&&L.isRenderTargetTexture===!1&&(Aa.y*=-1,Aa.z*=-1),E.envMapRotation.value.setFromMatrix4(sO.makeRotationFromEuler(Aa)),E.flipEnvMap.value=L.isCubeTexture&&L.isRenderTargetTexture===!1?-1:1,E.reflectivity.value=w.reflectivity,E.ior.value=w.ior,E.refractionRatio.value=w.refractionRatio),w.lightMap&&(E.lightMap.value=w.lightMap,E.lightMapIntensity.value=w.lightMapIntensity,n(w.lightMap,E.lightMapTransform)),w.aoMap&&(E.aoMap.value=w.aoMap,E.aoMapIntensity.value=w.aoMapIntensity,n(w.aoMap,E.aoMapTransform))}function c(E,w){E.diffuse.value.copy(w.color),E.opacity.value=w.opacity,w.map&&(E.map.value=w.map,n(w.map,E.mapTransform))}function u(E,w){E.dashSize.value=w.dashSize,E.totalSize.value=w.dashSize+w.gapSize,E.scale.value=w.scale}function h(E,w,I,L){E.diffuse.value.copy(w.color),E.opacity.value=w.opacity,E.size.value=w.size*I,E.scale.value=L*.5,w.map&&(E.map.value=w.map,n(w.map,E.uvTransform)),w.alphaMap&&(E.alphaMap.value=w.alphaMap,n(w.alphaMap,E.alphaMapTransform)),w.alphaTest>0&&(E.alphaTest.value=w.alphaTest)}function d(E,w){E.diffuse.value.copy(w.color),E.opacity.value=w.opacity,E.rotation.value=w.rotation,w.map&&(E.map.value=w.map,n(w.map,E.mapTransform)),w.alphaMap&&(E.alphaMap.value=w.alphaMap,n(w.alphaMap,E.alphaMapTransform)),w.alphaTest>0&&(E.alphaTest.value=w.alphaTest)}function g(E,w){E.specular.value.copy(w.specular),E.shininess.value=Math.max(w.shininess,1e-4)}function v(E,w){w.gradientMap&&(E.gradientMap.value=w.gradientMap)}function y(E,w){E.metalness.value=w.metalness,w.metalnessMap&&(E.metalnessMap.value=w.metalnessMap,n(w.metalnessMap,E.metalnessMapTransform)),E.roughness.value=w.roughness,w.roughnessMap&&(E.roughnessMap.value=w.roughnessMap,n(w.roughnessMap,E.roughnessMapTransform)),w.envMap&&(E.envMapIntensity.value=w.envMapIntensity)}function S(E,w,I){E.ior.value=w.ior,w.sheen>0&&(E.sheenColor.value.copy(w.sheenColor).multiplyScalar(w.sheen),E.sheenRoughness.value=w.sheenRoughness,w.sheenColorMap&&(E.sheenColorMap.value=w.sheenColorMap,n(w.sheenColorMap,E.sheenColorMapTransform)),w.sheenRoughnessMap&&(E.sheenRoughnessMap.value=w.sheenRoughnessMap,n(w.sheenRoughnessMap,E.sheenRoughnessMapTransform))),w.clearcoat>0&&(E.clearcoat.value=w.clearcoat,E.clearcoatRoughness.value=w.clearcoatRoughness,w.clearcoatMap&&(E.clearcoatMap.value=w.clearcoatMap,n(w.clearcoatMap,E.clearcoatMapTransform)),w.clearcoatRoughnessMap&&(E.clearcoatRoughnessMap.value=w.clearcoatRoughnessMap,n(w.clearcoatRoughnessMap,E.clearcoatRoughnessMapTransform)),w.clearcoatNormalMap&&(E.clearcoatNormalMap.value=w.clearcoatNormalMap,n(w.clearcoatNormalMap,E.clearcoatNormalMapTransform),E.clearcoatNormalScale.value.copy(w.clearcoatNormalScale),w.side===Do&&E.clearcoatNormalScale.value.negate())),w.dispersion>0&&(E.dispersion.value=w.dispersion),w.iridescence>0&&(E.iridescence.value=w.iridescence,E.iridescenceIOR.value=w.iridescenceIOR,E.iridescenceThicknessMinimum.value=w.iridescenceThicknessRange[0],E.iridescenceThicknessMaximum.value=w.iridescenceThicknessRange[1],w.iridescenceMap&&(E.iridescenceMap.value=w.iridescenceMap,n(w.iridescenceMap,E.iridescenceMapTransform)),w.iridescenceThicknessMap&&(E.iridescenceThicknessMap.value=w.iridescenceThicknessMap,n(w.iridescenceThicknessMap,E.iridescenceThicknessMapTransform))),w.transmission>0&&(E.transmission.value=w.transmission,E.transmissionSamplerMap.value=I.texture,E.transmissionSamplerSize.value.set(I.width,I.height),w.transmissionMap&&(E.transmissionMap.value=w.transmissionMap,n(w.transmissionMap,E.transmissionMapTransform)),E.thickness.value=w.thickness,w.thicknessMap&&(E.thicknessMap.value=w.thicknessMap,n(w.thicknessMap,E.thicknessMapTransform)),E.attenuationDistance.value=w.attenuationDistance,E.attenuationColor.value.copy(w.attenuationColor)),w.anisotropy>0&&(E.anisotropyVector.value.set(w.anisotropy*Math.cos(w.anisotropyRotation),w.anisotropy*Math.sin(w.anisotropyRotation)),w.anisotropyMap&&(E.anisotropyMap.value=w.anisotropyMap,n(w.anisotropyMap,E.anisotropyMapTransform))),E.specularIntensity.value=w.specularIntensity,E.specularColor.value.copy(w.specularColor),w.specularColorMap&&(E.specularColorMap.value=w.specularColorMap,n(w.specularColorMap,E.specularColorMapTransform)),w.specularIntensityMap&&(E.specularIntensityMap.value=w.specularIntensityMap,n(w.specularIntensityMap,E.specularIntensityMapTransform))}function T(E,w){w.matcap&&(E.matcap.value=w.matcap)}function A(E,w){const I=e.get(w).light;E.referencePosition.value.setFromMatrixPosition(I.matrixWorld),E.nearDistance.value=I.shadow.camera.near,E.farDistance.value=I.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:r}}function aO(t,e,n,i){let r={},a={},c=[];const u=t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS);function h(I,L){const D=L.program;i.uniformBlockBinding(I,D)}function d(I,L){let D=r[I.id];D===void 0&&(T(I),D=g(I),r[I.id]=D,I.addEventListener("dispose",E));const W=L.program;i.updateUBOMapping(I,W);const V=e.render.frame;a[I.id]!==V&&(y(I),a[I.id]=V)}function g(I){const L=v();I.__bindingPointIndex=L;const D=t.createBuffer(),W=I.__size,V=I.usage;return t.bindBuffer(t.UNIFORM_BUFFER,D),t.bufferData(t.UNIFORM_BUFFER,W,V),t.bindBuffer(t.UNIFORM_BUFFER,null),t.bindBufferBase(t.UNIFORM_BUFFER,L,D),D}function v(){for(let I=0;I0&&(D+=W-V),I.__size=D,I.__cache={},this}function A(I){const L={boundary:0,storage:0};return typeof I=="number"||typeof I=="boolean"?(L.boundary=4,L.storage=4):I.isVector2?(L.boundary=8,L.storage=8):I.isVector3||I.isColor?(L.boundary=16,L.storage=12):I.isVector4?(L.boundary=16,L.storage=16):I.isMatrix3?(L.boundary=48,L.storage=48):I.isMatrix4?(L.boundary=64,L.storage=64):I.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",I),L}function E(I){const L=I.target;L.removeEventListener("dispose",E);const D=c.indexOf(L.__bindingPointIndex);c.splice(D,1),t.deleteBuffer(r[L.id]),delete r[L.id],delete a[L.id]}function w(){for(const I in r)t.deleteBuffer(r[I]);c=[],r={},a={}}return{bind:h,update:d,dispose:w}}class lO{constructor(e={}){const{canvas:n=Vk(),context:i=null,depth:r=!0,stencil:a=!1,alpha:c=!1,antialias:u=!1,premultipliedAlpha:h=!0,preserveDrawingBuffer:d=!1,powerPreference:g="default",failIfMajorPerformanceCaveat:v=!1,reverseDepthBuffer:y=!1}=e;this.isWebGLRenderer=!0;let S;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");S=i.getContextAttributes().alpha}else S=c;const T=new Uint32Array(4),A=new Int32Array(4);let E=null,w=null;const I=[],L=[];this.domElement=n,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=ds,this.toneMapping=oa,this.toneMappingExposure=1;const D=this;let W=!1,V=0,H=0,Q=null,k=-1,P=null;const J=new Ii,ve=new Ii;let fe=null;const Ee=new An(0);let je=0,X=n.width,_e=n.height,ne=1,tt=null,Ce=null;const $=new Ii(0,0,X,_e),ce=new Ii(0,0,X,_e);let Xe=!1;const oe=new PE;let Ie=!1,nt=!1;this.transmissionResolutionScale=1;const Se=new ui,N=new ui,ye=new Le,xe=new Ii,Oe={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let at=!1;function Ze(){return Q===null?ne:1}let U=i;function Me(G,be){return n.getContext(G,be)}try{const G={alpha:!0,depth:r,stencil:a,antialias:u,premultipliedAlpha:h,preserveDrawingBuffer:d,powerPreference:g,failIfMajorPerformanceCaveat:v};if("setAttribute"in n&&n.setAttribute("data-engine",`three.js r${ev}`),n.addEventListener("webglcontextlost",ue,!1),n.addEventListener("webglcontextrestored",Ue,!1),n.addEventListener("webglcontextcreationerror",Je,!1),U===null){const be="webgl2";if(U=Me(be,G),U===null)throw Me(be)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(G){throw console.error("THREE.WebGLRenderer: "+G.message),G}let Pe,rt,We,gt,qe,q,C,te,ae,Re,De,st,it,F,le,z,j,B,re,Y,me,ee,$e,M;function K(){Pe=new xF(U),Pe.init(),ee=new eO(U,Pe),rt=new dF(U,Pe,e,ee),We=new Z4(U,Pe),rt.reverseDepthBuffer&&y&&We.buffers.depth.setReversed(!0),gt=new bF(U),qe=new O4,q=new Q4(U,Pe,We,qe,rt,ee,gt),C=new hF(D),te=new vF(D),ae=new Cz(U),$e=new cF(U,ae),Re=new yF(U,ae,gt,$e),De=new TF(U,Re,ae,gt),re=new SF(U,rt,q),z=new fF(qe),st=new F4(D,C,te,Pe,rt,$e,z),it=new rO(D,qe),F=new V4,le=new $4(Pe),B=new lF(D,C,te,We,De,S,h),j=new J4(D,De,rt),M=new aO(U,gt,rt,We),Y=new uF(U,Pe,gt),me=new _F(U,Pe,gt),gt.programs=st.programs,D.capabilities=rt,D.extensions=Pe,D.properties=qe,D.renderLists=F,D.shadowMap=j,D.state=We,D.info=gt}K();const de=new oO(D,U);this.xr=de,this.getContext=function(){return U},this.getContextAttributes=function(){return U.getContextAttributes()},this.forceContextLoss=function(){const G=Pe.get("WEBGL_lose_context");G&&G.loseContext()},this.forceContextRestore=function(){const G=Pe.get("WEBGL_lose_context");G&&G.restoreContext()},this.getPixelRatio=function(){return ne},this.setPixelRatio=function(G){G!==void 0&&(ne=G,this.setSize(X,_e,!1))},this.getSize=function(G){return G.set(X,_e)},this.setSize=function(G,be,He=!0){if(de.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}X=G,_e=be,n.width=Math.floor(G*ne),n.height=Math.floor(be*ne),He===!0&&(n.style.width=G+"px",n.style.height=be+"px"),this.setViewport(0,0,G,be)},this.getDrawingBufferSize=function(G){return G.set(X*ne,_e*ne).floor()},this.setDrawingBufferSize=function(G,be,He){X=G,_e=be,ne=He,n.width=Math.floor(G*He),n.height=Math.floor(be*He),this.setViewport(0,0,G,be)},this.getCurrentViewport=function(G){return G.copy(J)},this.getViewport=function(G){return G.copy($)},this.setViewport=function(G,be,He,Ve){G.isVector4?$.set(G.x,G.y,G.z,G.w):$.set(G,be,He,Ve),We.viewport(J.copy($).multiplyScalar(ne).round())},this.getScissor=function(G){return G.copy(ce)},this.setScissor=function(G,be,He,Ve){G.isVector4?ce.set(G.x,G.y,G.z,G.w):ce.set(G,be,He,Ve),We.scissor(ve.copy(ce).multiplyScalar(ne).round())},this.getScissorTest=function(){return Xe},this.setScissorTest=function(G){We.setScissorTest(Xe=G)},this.setOpaqueSort=function(G){tt=G},this.setTransparentSort=function(G){Ce=G},this.getClearColor=function(G){return G.copy(B.getClearColor())},this.setClearColor=function(){B.setClearColor(...arguments)},this.getClearAlpha=function(){return B.getClearAlpha()},this.setClearAlpha=function(){B.setClearAlpha(...arguments)},this.clear=function(G=!0,be=!0,He=!0){let Ve=0;if(G){let ge=!1;if(Q!==null){const pt=Q.texture.format;ge=pt===av||pt===rv||pt===sv}if(ge){const pt=Q.texture.type,yt=pt===yr||pt===qa||pt===Pu||pt===cc||pt===nv||pt===iv,xt=B.getClearColor(),Tt=B.getClearAlpha(),jt=xt.r,qt=xt.g,kt=xt.b;yt?(T[0]=jt,T[1]=qt,T[2]=kt,T[3]=Tt,U.clearBufferuiv(U.COLOR,0,T)):(A[0]=jt,A[1]=qt,A[2]=kt,A[3]=Tt,U.clearBufferiv(U.COLOR,0,A))}else Ve|=U.COLOR_BUFFER_BIT}be&&(Ve|=U.DEPTH_BUFFER_BIT),He&&(Ve|=U.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),U.clear(Ve)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){n.removeEventListener("webglcontextlost",ue,!1),n.removeEventListener("webglcontextrestored",Ue,!1),n.removeEventListener("webglcontextcreationerror",Je,!1),B.dispose(),F.dispose(),le.dispose(),qe.dispose(),C.dispose(),te.dispose(),De.dispose(),$e.dispose(),M.dispose(),st.dispose(),de.dispose(),de.removeEventListener("sessionstart",Jt),de.removeEventListener("sessionend",Dt),Yt.stop()};function ue(G){G.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),W=!0}function Ue(){console.log("THREE.WebGLRenderer: Context Restored."),W=!1;const G=gt.autoReset,be=j.enabled,He=j.autoUpdate,Ve=j.needsUpdate,ge=j.type;K(),gt.autoReset=G,j.enabled=be,j.autoUpdate=He,j.needsUpdate=Ve,j.type=ge}function Je(G){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",G.statusMessage)}function ht(G){const be=G.target;be.removeEventListener("dispose",ht),et(be)}function et(G){Te(G),qe.remove(G)}function Te(G){const be=qe.get(G).programs;be!==void 0&&(be.forEach(function(He){st.releaseProgram(He)}),G.isShaderMaterial&&st.releaseShaderCache(G))}this.renderBufferDirect=function(G,be,He,Ve,ge,pt){be===null&&(be=Oe);const yt=ge.isMesh&&ge.matrixWorld.determinant()<0,xt=tn(G,be,He,Ve,ge);We.setMaterial(Ve,yt);let Tt=He.index,jt=1;if(Ve.wireframe===!0){if(Tt=Re.getWireframeAttribute(He),Tt===void 0)return;jt=2}const qt=He.drawRange,kt=He.attributes.position;let hn=qt.start*jt,pn=(qt.start+qt.count)*jt;pt!==null&&(hn=Math.max(hn,pt.start*jt),pn=Math.min(pn,(pt.start+pt.count)*jt)),Tt!==null?(hn=Math.max(hn,0),pn=Math.min(pn,Tt.count)):kt!=null&&(hn=Math.max(hn,0),pn=Math.min(pn,kt.count));const Xn=pn-hn;if(Xn<0||Xn===1/0)return;$e.setup(ge,Ve,xt,He,Tt);let wn,Wt=Y;if(Tt!==null&&(wn=ae.get(Tt),Wt=me,Wt.setIndex(wn)),ge.isMesh)Ve.wireframe===!0?(We.setLineWidth(Ve.wireframeLinewidth*Ze()),Wt.setMode(U.LINES)):Wt.setMode(U.TRIANGLES);else if(ge.isLine){let zt=Ve.linewidth;zt===void 0&&(zt=1),We.setLineWidth(zt*Ze()),ge.isLineSegments?Wt.setMode(U.LINES):ge.isLineLoop?Wt.setMode(U.LINE_LOOP):Wt.setMode(U.LINE_STRIP)}else ge.isPoints?Wt.setMode(U.POINTS):ge.isSprite&&Wt.setMode(U.TRIANGLES);if(ge.isBatchedMesh)if(ge._multiDrawInstances!==null)Na("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),Wt.renderMultiDrawInstances(ge._multiDrawStarts,ge._multiDrawCounts,ge._multiDrawCount,ge._multiDrawInstances);else if(Pe.get("WEBGL_multi_draw"))Wt.renderMultiDraw(ge._multiDrawStarts,ge._multiDrawCounts,ge._multiDrawCount);else{const zt=ge._multiDrawStarts,Ci=ge._multiDrawCounts,vn=ge._multiDrawCount,Ji=Tt?ae.get(Tt).bytesPerElement:1,xo=qe.get(Ve).currentProgram.getUniforms();for(let Di=0;Di{function pt(){if(Ve.forEach(function(yt){qe.get(yt).currentProgram.isReady()&&Ve.delete(yt)}),Ve.size===0){ge(G);return}setTimeout(pt,10)}Pe.get("KHR_parallel_shader_compile")!==null?pt():setTimeout(pt,10)})};let Be=null;function _t(G){Be&&Be(G)}function Jt(){Yt.stop()}function Dt(){Yt.start()}const Yt=new BE;Yt.setAnimationLoop(_t),typeof self<"u"&&Yt.setContext(self),this.setAnimationLoop=function(G){Be=G,de.setAnimationLoop(G),G===null?Yt.stop():Yt.start()},de.addEventListener("sessionstart",Jt),de.addEventListener("sessionend",Dt),this.render=function(G,be){if(be!==void 0&&be.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(W===!0)return;if(G.matrixWorldAutoUpdate===!0&&G.updateMatrixWorld(),be.parent===null&&be.matrixWorldAutoUpdate===!0&&be.updateMatrixWorld(),de.enabled===!0&&de.isPresenting===!0&&(de.cameraAutoUpdate===!0&&de.updateCamera(be),be=de.getCamera()),G.isScene===!0&&G.onBeforeRender(D,G,be,Q),w=le.get(G,L.length),w.init(be),L.push(w),N.multiplyMatrices(be.projectionMatrix,be.matrixWorldInverse),oe.setFromProjectionMatrix(N),nt=this.localClippingEnabled,Ie=z.init(this.clippingPlanes,nt),E=F.get(G,I.length),E.init(),I.push(E),de.enabled===!0&&de.isPresenting===!0){const pt=D.xr.getDepthSensingMesh();pt!==null&&Zt(pt,be,-1/0,D.sortObjects)}Zt(G,be,0,D.sortObjects),E.finish(),D.sortObjects===!0&&E.sort(tt,Ce),at=de.enabled===!1||de.isPresenting===!1||de.hasDepthSensing()===!1,at&&B.addToRenderList(E,G),this.info.render.frame++,Ie===!0&&z.beginShadows();const He=w.state.shadowsArray;j.render(He,G,be),Ie===!0&&z.endShadows(),this.info.autoReset===!0&&this.info.reset();const Ve=E.opaque,ge=E.transmissive;if(w.setupLights(),be.isArrayCamera){const pt=be.cameras;if(ge.length>0)for(let yt=0,xt=pt.length;yt0&&Gi(Ve,ge,G,be),at&&B.render(G),ti(E,G,be);Q!==null&&H===0&&(q.updateMultisampleRenderTarget(Q),q.updateRenderTargetMipmap(Q)),G.isScene===!0&&G.onAfterRender(D,G,be),$e.resetDefaultState(),k=-1,P=null,L.pop(),L.length>0?(w=L[L.length-1],Ie===!0&&z.setGlobalState(D.clippingPlanes,w.state.camera)):w=null,I.pop(),I.length>0?E=I[I.length-1]:E=null};function Zt(G,be,He,Ve){if(G.visible===!1)return;if(G.layers.test(be.layers)){if(G.isGroup)He=G.renderOrder;else if(G.isLOD)G.autoUpdate===!0&&G.update(be);else if(G.isLight)w.pushLight(G),G.castShadow&&w.pushShadow(G);else if(G.isSprite){if(!G.frustumCulled||oe.intersectsSprite(G)){Ve&&xe.setFromMatrixPosition(G.matrixWorld).applyMatrix4(N);const yt=De.update(G),xt=G.material;xt.visible&&E.push(G,yt,xt,He,xe.z,null)}}else if((G.isMesh||G.isLine||G.isPoints)&&(!G.frustumCulled||oe.intersectsObject(G))){const yt=De.update(G),xt=G.material;if(Ve&&(G.boundingSphere!==void 0?(G.boundingSphere===null&&G.computeBoundingSphere(),xe.copy(G.boundingSphere.center)):(yt.boundingSphere===null&&yt.computeBoundingSphere(),xe.copy(yt.boundingSphere.center)),xe.applyMatrix4(G.matrixWorld).applyMatrix4(N)),Array.isArray(xt)){const Tt=yt.groups;for(let jt=0,qt=Tt.length;jt0&&Si(ge,be,He),pt.length>0&&Si(pt,be,He),yt.length>0&&Si(yt,be,He),We.buffers.depth.setTest(!0),We.buffers.depth.setMask(!0),We.buffers.color.setMask(!0),We.setPolygonOffset(!1)}function Gi(G,be,He,Ve){if((He.isScene===!0?He.overrideMaterial:null)!==null)return;w.state.transmissionRenderTarget[Ve.id]===void 0&&(w.state.transmissionRenderTarget[Ve.id]=new Wa(1,1,{generateMipmaps:!0,type:Pe.has("EXT_color_buffer_half_float")||Pe.has("EXT_color_buffer_float")?Bu:yr,minFilter:Ha,samples:4,stencilBuffer:a,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:kn.workingColorSpace}));const pt=w.state.transmissionRenderTarget[Ve.id],yt=Ve.viewport||J;pt.setSize(yt.z*D.transmissionResolutionScale,yt.w*D.transmissionResolutionScale);const xt=D.getRenderTarget();D.setRenderTarget(pt),D.getClearColor(Ee),je=D.getClearAlpha(),je<1&&D.setClearColor(16777215,.5),D.clear(),at&&B.render(He);const Tt=D.toneMapping;D.toneMapping=oa;const jt=Ve.viewport;if(Ve.viewport!==void 0&&(Ve.viewport=void 0),w.setupLightsView(Ve),Ie===!0&&z.setGlobalState(D.clippingPlanes,Ve),Si(G,He,Ve),q.updateMultisampleRenderTarget(pt),q.updateRenderTargetMipmap(pt),Pe.has("WEBGL_multisampled_render_to_texture")===!1){let qt=!1;for(let kt=0,hn=be.length;kt0),kt=!!He.morphAttributes.position,hn=!!He.morphAttributes.normal,pn=!!He.morphAttributes.color;let Xn=oa;Ve.toneMapped&&(Q===null||Q.isXRRenderTarget===!0)&&(Xn=D.toneMapping);const wn=He.morphAttributes.position||He.morphAttributes.normal||He.morphAttributes.color,Wt=wn!==void 0?wn.length:0,zt=qe.get(Ve),Ci=w.state.lights;if(Ie===!0&&(nt===!0||G!==P)){const pi=G===P&&Ve.id===k;z.setState(Ve,G,pi)}let vn=!1;Ve.version===zt.__version?(zt.needsLights&&zt.lightsStateVersion!==Ci.state.version||zt.outputColorSpace!==xt||ge.isBatchedMesh&&zt.batching===!1||!ge.isBatchedMesh&&zt.batching===!0||ge.isBatchedMesh&&zt.batchingColor===!0&&ge.colorTexture===null||ge.isBatchedMesh&&zt.batchingColor===!1&&ge.colorTexture!==null||ge.isInstancedMesh&&zt.instancing===!1||!ge.isInstancedMesh&&zt.instancing===!0||ge.isSkinnedMesh&&zt.skinning===!1||!ge.isSkinnedMesh&&zt.skinning===!0||ge.isInstancedMesh&&zt.instancingColor===!0&&ge.instanceColor===null||ge.isInstancedMesh&&zt.instancingColor===!1&&ge.instanceColor!==null||ge.isInstancedMesh&&zt.instancingMorph===!0&&ge.morphTexture===null||ge.isInstancedMesh&&zt.instancingMorph===!1&&ge.morphTexture!==null||zt.envMap!==Tt||Ve.fog===!0&&zt.fog!==pt||zt.numClippingPlanes!==void 0&&(zt.numClippingPlanes!==z.numPlanes||zt.numIntersection!==z.numIntersection)||zt.vertexAlphas!==jt||zt.vertexTangents!==qt||zt.morphTargets!==kt||zt.morphNormals!==hn||zt.morphColors!==pn||zt.toneMapping!==Xn||zt.morphTargetsCount!==Wt)&&(vn=!0):(vn=!0,zt.__version=Ve.version);let Ji=zt.currentProgram;vn===!0&&(Ji=fn(Ve,be,ge));let xo=!1,Di=!1,hi=!1;const Rn=Ji.getUniforms(),io=zt.uniforms;if(We.useProgram(Ji.program)&&(xo=!0,Di=!0,hi=!0),Ve.id!==k&&(k=Ve.id,Di=!0),xo||P!==G){We.buffers.depth.getReversed()?(Se.copy(G.projectionMatrix),Gk(Se),jk(Se),Rn.setValue(U,"projectionMatrix",Se)):Rn.setValue(U,"projectionMatrix",G.projectionMatrix),Rn.setValue(U,"viewMatrix",G.matrixWorldInverse);const yi=Rn.map.cameraPosition;yi!==void 0&&yi.setValue(U,ye.setFromMatrixPosition(G.matrixWorld)),rt.logarithmicDepthBuffer&&Rn.setValue(U,"logDepthBufFC",2/(Math.log(G.far+1)/Math.LN2)),(Ve.isMeshPhongMaterial||Ve.isMeshToonMaterial||Ve.isMeshLambertMaterial||Ve.isMeshBasicMaterial||Ve.isMeshStandardMaterial||Ve.isShaderMaterial)&&Rn.setValue(U,"isOrthographic",G.isOrthographicCamera===!0),P!==G&&(P=G,Di=!0,hi=!0)}if(ge.isSkinnedMesh){Rn.setOptional(U,ge,"bindMatrix"),Rn.setOptional(U,ge,"bindMatrixInverse");const pi=ge.skeleton;pi&&(pi.boneTexture===null&&pi.computeBoneTexture(),Rn.setValue(U,"boneTexture",pi.boneTexture,q))}ge.isBatchedMesh&&(Rn.setOptional(U,ge,"batchingTexture"),Rn.setValue(U,"batchingTexture",ge._matricesTexture,q),Rn.setOptional(U,ge,"batchingIdTexture"),Rn.setValue(U,"batchingIdTexture",ge._indirectTexture,q),Rn.setOptional(U,ge,"batchingColorTexture"),ge._colorsTexture!==null&&Rn.setValue(U,"batchingColorTexture",ge._colorsTexture,q));const qi=He.morphAttributes;if((qi.position!==void 0||qi.normal!==void 0||qi.color!==void 0)&&re.update(ge,He,Ji),(Di||zt.receiveShadow!==ge.receiveShadow)&&(zt.receiveShadow=ge.receiveShadow,Rn.setValue(U,"receiveShadow",ge.receiveShadow)),Ve.isMeshGouraudMaterial&&Ve.envMap!==null&&(io.envMap.value=Tt,io.flipEnvMap.value=Tt.isCubeTexture&&Tt.isRenderTargetTexture===!1?-1:1),Ve.isMeshStandardMaterial&&Ve.envMap===null&&be.environment!==null&&(io.envMapIntensity.value=be.environmentIntensity),Di&&(Rn.setValue(U,"toneMappingExposure",D.toneMappingExposure),zt.needsLights&&En(io,hi),pt&&Ve.fog===!0&&it.refreshFogUniforms(io,pt),it.refreshMaterialUniforms(io,Ve,ne,_e,w.state.transmissionRenderTarget[G.id]),Hf.upload(U,fi(zt),io,q)),Ve.isShaderMaterial&&Ve.uniformsNeedUpdate===!0&&(Hf.upload(U,fi(zt),io,q),Ve.uniformsNeedUpdate=!1),Ve.isSpriteMaterial&&Rn.setValue(U,"center",ge.center),Rn.setValue(U,"modelViewMatrix",ge.modelViewMatrix),Rn.setValue(U,"normalMatrix",ge.normalMatrix),Rn.setValue(U,"modelMatrix",ge.matrixWorld),Ve.isShaderMaterial||Ve.isRawShaderMaterial){const pi=Ve.uniformsGroups;for(let yi=0,Lo=pi.length;yi0&&q.useMultisampledRTT(G)===!1?ge=qe.get(G).__webglMultisampledFramebuffer:Array.isArray(qt)?ge=qt[He]:ge=qt,J.copy(G.viewport),ve.copy(G.scissor),fe=G.scissorTest}else J.copy($).multiplyScalar(ne).floor(),ve.copy(ce).multiplyScalar(ne).floor(),fe=Xe;if(He!==0&&(ge=bn),We.bindFramebuffer(U.FRAMEBUFFER,ge)&&Ve&&We.drawBuffers(G,ge),We.viewport(J),We.scissor(ve),We.setScissorTest(fe),pt){const Tt=qe.get(G.texture);U.framebufferTexture2D(U.FRAMEBUFFER,U.COLOR_ATTACHMENT0,U.TEXTURE_CUBE_MAP_POSITIVE_X+be,Tt.__webglTexture,He)}else if(yt){const Tt=qe.get(G.texture),jt=be;U.framebufferTextureLayer(U.FRAMEBUFFER,U.COLOR_ATTACHMENT0,Tt.__webglTexture,He,jt)}else if(G!==null&&He!==0){const Tt=qe.get(G.texture);U.framebufferTexture2D(U.FRAMEBUFFER,U.COLOR_ATTACHMENT0,U.TEXTURE_2D,Tt.__webglTexture,He)}k=-1},this.readRenderTargetPixels=function(G,be,He,Ve,ge,pt,yt){if(!(G&&G.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let xt=qe.get(G).__webglFramebuffer;if(G.isWebGLCubeRenderTarget&&yt!==void 0&&(xt=xt[yt]),xt){We.bindFramebuffer(U.FRAMEBUFFER,xt);try{const Tt=G.texture,jt=Tt.format,qt=Tt.type;if(!rt.textureFormatReadable(jt)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!rt.textureTypeReadable(qt)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}be>=0&&be<=G.width-Ve&&He>=0&&He<=G.height-ge&&U.readPixels(be,He,Ve,ge,ee.convert(jt),ee.convert(qt),pt)}finally{const Tt=Q!==null?qe.get(Q).__webglFramebuffer:null;We.bindFramebuffer(U.FRAMEBUFFER,Tt)}}},this.readRenderTargetPixelsAsync=async function(G,be,He,Ve,ge,pt,yt){if(!(G&&G.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let xt=qe.get(G).__webglFramebuffer;if(G.isWebGLCubeRenderTarget&&yt!==void 0&&(xt=xt[yt]),xt){const Tt=G.texture,jt=Tt.format,qt=Tt.type;if(!rt.textureFormatReadable(jt))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!rt.textureTypeReadable(qt))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");if(be>=0&&be<=G.width-Ve&&He>=0&&He<=G.height-ge){We.bindFramebuffer(U.FRAMEBUFFER,xt);const kt=U.createBuffer();U.bindBuffer(U.PIXEL_PACK_BUFFER,kt),U.bufferData(U.PIXEL_PACK_BUFFER,pt.byteLength,U.STREAM_READ),U.readPixels(be,He,Ve,ge,ee.convert(jt),ee.convert(qt),0);const hn=Q!==null?qe.get(Q).__webglFramebuffer:null;We.bindFramebuffer(U.FRAMEBUFFER,hn);const pn=U.fenceSync(U.SYNC_GPU_COMMANDS_COMPLETE,0);return U.flush(),await Hk(U,pn,4),U.bindBuffer(U.PIXEL_PACK_BUFFER,kt),U.getBufferSubData(U.PIXEL_PACK_BUFFER,0,pt),U.deleteBuffer(kt),U.deleteSync(pn),pt}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(G,be=null,He=0){G.isTexture!==!0&&(Na("WebGLRenderer: copyFramebufferToTexture function signature has changed."),be=arguments[0]||null,G=arguments[1]);const Ve=Math.pow(2,-He),ge=Math.floor(G.image.width*Ve),pt=Math.floor(G.image.height*Ve),yt=be!==null?be.x:0,xt=be!==null?be.y:0;q.setTexture2D(G,0),U.copyTexSubImage2D(U.TEXTURE_2D,He,0,0,yt,xt,ge,pt),We.unbindTexture()};const ii=U.createFramebuffer(),Rs=U.createFramebuffer();this.copyTextureToTexture=function(G,be,He=null,Ve=null,ge=0,pt=null){G.isTexture!==!0&&(Na("WebGLRenderer: copyTextureToTexture function signature has changed."),Ve=arguments[0]||null,G=arguments[1],be=arguments[2],pt=arguments[3]||0,He=null),pt===null&&(ge!==0?(Na("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),pt=ge,ge=0):pt=0);let yt,xt,Tt,jt,qt,kt,hn,pn,Xn;const wn=G.isCompressedTexture?G.mipmaps[pt]:G.image;if(He!==null)yt=He.max.x-He.min.x,xt=He.max.y-He.min.y,Tt=He.isBox3?He.max.z-He.min.z:1,jt=He.min.x,qt=He.min.y,kt=He.isBox3?He.min.z:0;else{const qi=Math.pow(2,-ge);yt=Math.floor(wn.width*qi),xt=Math.floor(wn.height*qi),G.isDataArrayTexture?Tt=wn.depth:G.isData3DTexture?Tt=Math.floor(wn.depth*qi):Tt=1,jt=0,qt=0,kt=0}Ve!==null?(hn=Ve.x,pn=Ve.y,Xn=Ve.z):(hn=0,pn=0,Xn=0);const Wt=ee.convert(be.format),zt=ee.convert(be.type);let Ci;be.isData3DTexture?(q.setTexture3D(be,0),Ci=U.TEXTURE_3D):be.isDataArrayTexture||be.isCompressedArrayTexture?(q.setTexture2DArray(be,0),Ci=U.TEXTURE_2D_ARRAY):(q.setTexture2D(be,0),Ci=U.TEXTURE_2D),U.pixelStorei(U.UNPACK_FLIP_Y_WEBGL,be.flipY),U.pixelStorei(U.UNPACK_PREMULTIPLY_ALPHA_WEBGL,be.premultiplyAlpha),U.pixelStorei(U.UNPACK_ALIGNMENT,be.unpackAlignment);const vn=U.getParameter(U.UNPACK_ROW_LENGTH),Ji=U.getParameter(U.UNPACK_IMAGE_HEIGHT),xo=U.getParameter(U.UNPACK_SKIP_PIXELS),Di=U.getParameter(U.UNPACK_SKIP_ROWS),hi=U.getParameter(U.UNPACK_SKIP_IMAGES);U.pixelStorei(U.UNPACK_ROW_LENGTH,wn.width),U.pixelStorei(U.UNPACK_IMAGE_HEIGHT,wn.height),U.pixelStorei(U.UNPACK_SKIP_PIXELS,jt),U.pixelStorei(U.UNPACK_SKIP_ROWS,qt),U.pixelStorei(U.UNPACK_SKIP_IMAGES,kt);const Rn=G.isDataArrayTexture||G.isData3DTexture,io=be.isDataArrayTexture||be.isData3DTexture;if(G.isDepthTexture){const qi=qe.get(G),pi=qe.get(be),yi=qe.get(qi.__renderTarget),Lo=qe.get(pi.__renderTarget);We.bindFramebuffer(U.READ_FRAMEBUFFER,yi.__webglFramebuffer),We.bindFramebuffer(U.DRAW_FRAMEBUFFER,Lo.__webglFramebuffer);for(let Ki=0;Ki{const n=e;if(n.geometry&&n.geometry.dispose(),n.material){const i=n.material;Array.isArray(i)?i.forEach(r=>r.dispose()):i.dispose()}})}function qE(){dn.forEach(t=>{cO(t),li&&li.remove(t)}),dn=[]}const uO=(t,e,n)=>{if(Xo||(Xo=new lO({alpha:!0,antialias:!0,preserveDrawingBuffer:!0}),Xo.setPixelRatio(Math.min(devicePixelRatio,2)),Xo.setClearColor(0,0)),Xo.setSize(t,e),!li||Cg!==n.threejsScene){li&&qE(),li=new mz,Un=new fs(75,t/e,.1,1e3),Un.position.set(0,0,5),Cg=n.threejsScene;const i=n.threejsScene??"stars";switch(vi.set(n.threejsColor??"#a855f7"),i){case"cubes":{const r=new _c;for(let a=0;a<20;a++){const c=new ls({color:vi,wireframe:!0}),u=new Ni(r,c);u.position.set((Math.random()-.5)*10,(Math.random()-.5)*10,(Math.random()-.5)*10),li.add(u),dn.push(u)}break}case"waves":{const r=new Ga(20,20,32,32),a=Float32Array.from(r.attributes.position.array);r.userData.origPos=a;const c=new ls({color:vi,wireframe:!0}),u=new Ni(r,c);u.rotation.x=-Math.PI/2,li.add(u),dn.push(u);break}case"particles":{const a=new Float32Array(15e3);for(let d=0;d<5e3*3;d++)a[d]=(Math.random()-.5)*20;const c=new xi;c.setAttribute("position",new Vi(a,3));const u=new hr({size:.05,color:vi}),h=new Kr(c,u);li.add(h),dn.push(h);break}case"galaxy":{const a=new Float32Array(24e3),c=4;for(let A=0;A<8e3;A++){const E=Math.random()*8,w=A%c/c*Math.PI*2,I=E*1.5,L=(1-E/8)*.5+.1;a[A*3]=Math.cos(w+I)*E+(Math.random()-.5)*L*2,a[A*3+1]=(Math.random()-.5)*L*.5,a[A*3+2]=Math.sin(w+I)*E+(Math.random()-.5)*L*2}const u=new xi;u.setAttribute("position",new Vi(a,3));const h=new hr({size:.04,color:vi,transparent:!0,opacity:.8}),d=new Kr(u,h);li.add(d),dn.push(d);const g=500,v=new Float32Array(g*3);for(let A=0;Aw%3===1));y.userData.origY=S;const T=new ls({color:vi,transparent:!0,opacity:.15+v*.05,side:$o}),A=new Ni(y,T);A.position.set(0,2+v*.6,-3-v*.5),A.rotation.x=-.3,r.add(A)}li.add(r),dn.push(r);const c=1e3,u=new Float32Array(c*3);for(let v=0;v{if(uO(e,n,i),!Xo||!li||!Un)return null;const r=i.threejsSpeed??1,a=t*r,c=i.threejsScene??"stars";switch(vi.set(i.threejsColor??"#a855f7"),dn.forEach(u=>{u.userData.keepColor||u.traverse(h=>{if(h.userData.keepColor)return;const d=h;if(!d.material)return;(Array.isArray(d.material)?d.material:[d.material]).forEach(v=>{v.color&&v.color.copy(vi)})})}),c){case"cubes":dn.forEach((u,h)=>{u.rotation.x=a*.5+h,u.rotation.y=a*.5+h});break;case"waves":{const u=dn[0],h=u.geometry.attributes.position,d=h.array,g=u.geometry.userData.origPos,v=h.count;for(let y=0;y{if(!(h instanceof Ni))return;const g=h.geometry.attributes.position,v=g.array,y=h.geometry.userData.origY,S=d*.7,T=g.count;for(let E=0;E{h.rotation.y=a*(.03+d*.015),h.rotation.x=Math.sin(a*.1+d)*.1});break}case"rings":{const u=dn[0];u.children[0]&&(u.children[0].rotation.y=a*.3,u.children[0].rotation.x=a*.1);for(let h=1;h{const y=(a*h+v*1.5)%d;g.position.z=5-y;const S=Math.max(0,(1-y/(d*.9))*.8);g.material.opacity=S});break}case"warp":{const u=dn[0],h=u.geometry.attributes.position,d=h.array,{TAIL:g}=u.userData,v=h.count/2,y=3*r;for(let S=0;S5&&(T-=100),d[S*6+2]=T,d[S*6+5]=T+g}h.needsUpdate=!0;break}case"cybergrid":{const u=dn[0],h=a*5%100;u.children.forEach(d=>{const g=d.userData.tileIndex;d.position.z=-g*100+h});break}case"vortex":{const u=dn[0],h=u.geometry.attributes.position,d=h.array,{angles:g,radii:v,heights:y}=u.userData,S=10/5*.01*r,T=.05*r,A=h.count;for(let E=0;E10&&(y[E]-=20),d[E*3]=Math.cos(g[E])*v[E],d[E*3+1]=y[E],d[E*3+2]=Math.sin(g[E])*v[E];h.needsUpdate=!0;break}case"crystals":{dn[0].children.forEach(h=>{const{rotSpeed:d}=h.userData;h.rotation.x+=d.x*r,h.rotation.y+=d.y*r,h.rotation.z+=d.z*r,h.position.y+=Math.sin(a+h.position.x)*.005});break}default:{const u=dn[0];u&&(u.rotation.x=a*.05,u.rotation.y=a*.05,u.rotation.z=a*.01);break}}return i.threejsBgColor?Xo.setClearColor(new An(i.threejsBgColor),1):Xo.setClearColor(0,0),i.threejsCameraMovement?fO(Un,c,a):dO(Un,c),Xo.render(li,Un),Xo.domElement},hO=()=>{qE(),Xo&&(Xo.dispose(),Xo=null),li=null,Un=null,Cg=void 0},pO=({isPlaying:t,currentTime:e,config:n})=>{const i=Ae.useRef(null),r=Ae.useRef(null),a=Ae.useRef(t),c=Ae.useRef(e),u=Ae.useRef(n);return Ae.useEffect(()=>{a.current=t},[t]),Ae.useEffect(()=>{c.current=e},[e]),Ae.useEffect(()=>{u.current=n},[n]),Ae.useEffect(()=>{let h,d=performance.now(),g=c.current;const v=y=>{const S=(y-d)/1e3;d=y,a.current?g+=S:g=c.current;const T=i.current,A=T&&T.clientWidth||1280,E=T&&T.clientHeight||720,w=WE(g,A,E,u.current);w&&T&&r.current!==w&&(T.innerHTML="",T.appendChild(w),r.current=w,w.style.width="100%",w.style.height="100%",w.style.objectFit="cover",w.style.display="block"),h=requestAnimationFrame(v)};return h=requestAnimationFrame(v),()=>{cancelAnimationFrame(h),hO(),r.current=null}},[]),p.jsx("div",{ref:i,className:"absolute inset-0 pointer-events-none"})},Ah=(t,e,n,i,r,a,c,u,h,d,g,v,y,S,T,A=!0,E=!0,w,I)=>{const L=N=>{const ye=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(N);return ye?{r:parseInt(ye[1],16),g:parseInt(ye[2],16),b:parseInt(ye[3],16)}:{r:255,g:255,b:255}},D=N=>{let ye=0,xe=0;if(N instanceof ImageBitmap?(ye=N.width,xe=N.height):N instanceof HTMLVideoElement?(ye=N.videoWidth,xe=N.videoHeight):(ye=N.width,xe=N.height),ye&&xe){const Oe=Math.max(e/ye,n/xe),at=e/2-ye/2*Oe,Ze=n/2-xe/2*Oe;t.drawImage(N,at,Ze,ye*Oe,xe*Oe)}},W=(N,ye,xe)=>{if(ye.includes(` +`))return ye.split(` +`).flatMap(Me=>W(N,Me,xe));const Oe=ye.split(" ");let at=[],Ze=Oe[0]||"";for(let Me=1;Me{if(at==="vhs"&&N instanceof CanvasRenderingContext2D)N.save(),N.globalCompositeOperation="screen",N.fillStyle="#ff0000",N.fillText(ye,xe-2,Oe),N.fillStyle="#00ff00",N.fillText(ye,xe,Oe),N.fillStyle="#0000ff",N.fillText(ye,xe+2,Oe),N.restore();else if(at==="3d"){const U=N.fillStyle;N.fillStyle="rgba(0,0,0,0.5)";for(let Me=1;Me<=4;Me++)N.fillText(ye,xe+Me,Oe+Me);N.fillStyle=U,N.fillText(ye,xe,Oe)}else if(at==="neon"){const U=N.fillStyle;N.shadowColor=U,N.shadowBlur=20,N.fillText(ye,xe,Oe),N.shadowBlur=40,N.fillText(ye,xe,Oe)}else if(at==="outline")N.strokeText(ye,xe,Oe),N.fillText(ye,xe,Oe);else if(at==="gradient"){const U=N.createLinearGradient(xe,Oe-20,xe,Oe+20);U.addColorStop(0,N.fillStyle),U.addColorStop(1,"#ffffff"),N.fillStyle=U,N.fillText(ye,xe,Oe)}else if(at==="fire")N.save(),N.shadowBlur=5,N.shadowColor="#ff0000",N.fillStyle="#ff4500",N.fillText(ye,xe,Oe),N.shadowBlur=2,N.shadowColor="#ffff00",N.fillStyle="#ffcc00",N.fillText(ye,xe+1,Oe-1),N.restore();else if(at==="emboss")N.fillStyle="rgba(255,255,255,0.7)",N.fillText(ye,xe-1,Oe-1),N.fillStyle="rgba(0,0,0,0.7)",N.fillText(ye,xe+1,Oe+1),N.fillStyle="rgba(128,128,128,0.5)",N.fillText(ye,xe,Oe);else if(at==="mirror")N.fillText(ye,xe,Oe),N.save(),N.translate(xe,Oe),N.scale(1,-1),N.translate(-xe,-Oe),N.globalAlpha*=.2,N.fillText(ye,xe,Oe-40),N.restore();else if(at==="neon-multi")N.fillStyle,N.shadowBlur=10,N.shadowColor="#fff",N.fillText(ye,xe,Oe),N.shadowBlur=20,N.shadowColor="#ff00de",N.fillText(ye,xe,Oe),N.shadowBlur=35,N.shadowColor="#00ffff",N.fillText(ye,xe,Oe);else if(at==="gold"){const U=N.createLinearGradient(xe,Oe-20,xe,Oe+20);U.addColorStop(0,"#d4af37"),U.addColorStop(1,"#C5A028"),N.fillStyle=U,N.fillText(ye,xe,Oe)}else if(at==="chrome"){const U=N.createLinearGradient(xe,Oe-20,xe,Oe+20);U.addColorStop(0,"#ebebeb"),U.addColorStop(.5,"#616161"),U.addColorStop(.51,"#ebebeb"),U.addColorStop(1,"#ebebeb"),N.fillStyle=U,N.fillText(ye,xe,Oe)}else if(at==="frozen")N.shadowColor="#03A9F4",N.shadowBlur=20,N.fillStyle="#ffffff",N.fillText(ye,xe,Oe);else if(at==="rainbow"){const U=N.createLinearGradient(xe-100,Oe,xe+100,Oe);U.addColorStop(0,"violet"),U.addColorStop(.16,"indigo"),U.addColorStop(.32,"blue"),U.addColorStop(.48,"green"),U.addColorStop(.64,"yellow"),U.addColorStop(.8,"orange"),U.addColorStop(1,"red"),N.fillStyle=U,N.fillText(ye,xe,Oe)}else if(at==="retro")N.fillStyle="#ff00ff",N.shadowColor="#00ffff",N.shadowBlur=0,N.shadowOffsetX=4,N.shadowOffsetY=4,N.fillText(ye,xe,Oe);else if(at==="cyberpunk")N.save(),N.fillStyle="#05d9e8",N.fillText(ye,xe-1,Oe-1),N.restore(),N.save(),N.fillStyle="#000000",N.fillText(ye,xe+2,Oe+2),N.restore(),N.save(),N.fillStyle="#fcee0a",N.fillText(ye,xe,Oe),N.restore();else if(at==="glitch-text"){const U=(Math.random()-.5)*5,Me=(Math.random()-.5)*2;N.save(),N.fillStyle="red",N.fillText(ye,xe+U,Oe+Me),N.restore(),N.save(),N.fillStyle="cyan",N.fillText(ye,xe-U,Oe-Me),N.restore(),N.fillStyle="#ffffff",N.fillText(ye,xe,Oe)}else at==="hologram"?(N.fillStyle="rgba(0, 255, 255, 0.7)",N.shadowColor="rgba(0,255,255,0.5)",N.shadowBlur=10,N.fillText(ye,xe,Oe)):(at==="comic"&&(N.lineWidth=3,N.strokeStyle="#000000",N.strokeText(ye,xe,Oe),N.fillStyle="#ffcc00"),N.fillText(ye,xe,Oe));if(Ze&&Ze!=="none"){const Me=N.measureText(ye).width;let Pe=xe;if(N.textAlign==="center"?Pe=xe-Me/2:N.textAlign==="right"&&(Pe=xe-Me),N.save(),N.beginPath(),N.lineWidth=Math.max(2,4*Ce),N.strokeStyle=N.fillStyle,Ze.includes("line-through")&&(N.moveTo(Pe,Oe),N.lineTo(Pe+Me,Oe)),Ze.includes("underline")){const rt=N.font.match(/(\d+(\.\d+)?)px/),We=rt?parseFloat(rt[1]):50,gt=Oe+We*.4;N.moveTo(Pe,gt),N.lineTo(Pe+Me,gt)}N.stroke(),N.restore()}},H=(N,ye,xe,Oe,at,Ze,U,Me,Pe,rt,We,gt,qe)=>{const q=Me?.textCase||"none",C=(Y,me)=>{if(!Y)return Y;if(q==="upper")return Y.toUpperCase();if(q==="lower")return Y.toLowerCase();if(q==="title")return Y.replace(/\w\S*/g,ee=>ee.charAt(0).toUpperCase()+ee.substr(1).toLowerCase());if(q==="sentence"){const ee=Y.toLowerCase();return me?ee.charAt(0).toUpperCase()+ee.slice(1):ee}return q==="invert"?Y.replace(/\w\S*/g,ee=>ee.charAt(0).toLowerCase()+ee.slice(1).toUpperCase()):Y};let te=ye.words||[];if(te.length===0){const Y=ye.text.split(` +`);te=[],Y.forEach((me,ee)=>{const $e=me.split(" ").map(M=>({text:M,startTime:ye.time,endTime:ye.endTime||ye.time+3}));te.push(...$e),eeY.text===` +`||Y.text.trim().length>0).map((Y,me)=>({...Y,text:Y.text===` +`?` +`:C(Y.text,me===0).trim()}));(Me?.highlightEffect?.includes("cyberpunk")||Me?.textEffect==="cyberpunk")&&(Pe="'Orbitron', sans-serif"),N.font=`${gt} ${We} ${rt}px ${Pe}`;const Re=[];let De=[],st=0,it=.3;["default","custom"].includes(d)?it=.25:d==="monospace"&&(it=.5);const F=N.measureText("M").width*it;ae.forEach((Y,me)=>{if(Y.text===` +`){De.length>0&&Re.push(De),De=[],st=0;return}const ee=N.measureText(Y.text).width;let M=!Y.text.endsWith(" ");const K=/[-‐‑‒–—―]$/,de=/^[-‐‑‒–—―]/;K.test(Y.text.trim())&&(M=!1);const ue=ae[me+1];ue&&(de.test(ue.text.trim())||ue.text===` +`)&&(M=!1);const Ue=M?F:0;st+ee>at&&De.length>0&&(Re.push(De),De=[],st=0),De.push(Y),st+=ee+Ue}),De.length>0&&Re.push(De);const le=Oe-(Re.length-1)*Ze/2;let z=Me.highlightColor||"#fb923c",j=Me.highlightBackground||"#ffffff";const B=Me.highlightEffect||"none";Me.useCustomHighlightColors||(B.includes("blue")||B.includes("cyan")?(z="#3b82f6",j="#3b82f6"):B.includes("purple")?(z="#a855f7",j="#a855f7"):B.includes("green")?(z="#22c55e",j="#22c55e"):B.includes("pink")?(z="#ec4899",j="#ec4899"):B.includes("neon")?(z="#ffffff",j="#ffffff"):B.includes("gold")?(z="#FFD700",j="#B8860B"):B.includes("chrome")?(z="#E0E0E0",j="#757575"):B.includes("fire")?(z="#FF4500",j="#FF0000"):B.includes("glass")?(z="#ffffff",j="rgba(255,255,255,0.1)"):B==="karaoke"&&(z="#fb923c",j="#fb923c"));let re=Me.fontColor||"#ffffff";Me.highlightEffect==="karaoke-smooth-white"&&(re="#ffffff"),Re.forEach((Y,me)=>{const ee=le+me*Ze;let $e=0;Y.forEach((K,de)=>{if($e+=N.measureText(K.text).width,de{const ue=N.measureText(K.text).width,Ue=U>=K.startTime,Je=U>=K.startTime&&U.3&&En<.45)&&(Jt=1.15,Dt=1.15)}else if(B.includes("flash"))Yt=.5+Math.sin(U*10)*.5;else if(B.includes("tada")){const En=U*2%1;En<.1?(_t=-.05,Jt=.9):En<.2&&(_t=.05,Jt=1.1)}else B.includes("swing")?_t=Math.sin(U*4)*.15:B.includes("glitch")&&Math.sin(U*15)>.8&&(Be+=(Math.random()-.5)*10,Ke+=(Math.random()-.5)*10);const tn=.3;if(Rt1-Math.pow(1-ii,3))(En);if(B.includes("fade"))Yt=En;else if(B.includes("slide"))Ke+=(1-bn)*30*qe,Yt=bn;else if(B.includes("drop"))Ke-=(1-bn)*50*qe,Yt=bn;else if(B.includes("zoom")||B.includes("scale")){const ii=.5+.5*bn;Jt*=ii,Dt*=ii}else if(B.includes("elastic")){const ii=En===0?0:En===1?1:Math.pow(2,-10*En)*Math.sin((En*10-.75)*(2*Math.PI)/3)+1;Jt*=ii,Dt*=ii}else if(B.includes("flip"))Dt*=bn;else if(B.includes("rotate-in"))_t+=(1-bn)*-1,Yt=bn;else if(B.includes("roll"))Be-=(1-bn)*50*qe,_t-=(1-bn)*Math.PI,Yt=bn;else if(B.includes("lightspeed"))Be+=(1-bn)*100*qe,Yt=bn;else if(B.includes("blur"))Zt=(1-bn)*10,Yt=bn;else if(B.includes("shatter")){const ii=1+(1-bn)*2;Jt*=ii,Dt*=ii,Zt=(1-bn)*10,Yt=bn}else B.includes("spiral")&&(Jt*=bn,Dt*=bn,_t+=(1-bn)*Math.PI*2)}else B.includes("scale")&&(Jt*=1.3,Dt*=1.3)}if(N.save(),Yt<1&&(N.globalAlpha*=Yt),Zt>0&&(N.filter=`blur(${Zt}px)`),_t!==0||Jt!==1||Dt!==1){const Rt=Be+ue/2,tn=Ke;N.translate(Rt,tn),N.rotate(_t),N.scale(Jt,Dt),N.translate(-Rt,-tn)}if(Te){if(B==="karaoke-smooth-plus"){const Rt=Me.textEffect||"none";if(Je){const tn=K.endTime-K.startTime,En=U-K.startTime,Mi=Math.max(0,Math.min(1,En/tn)),bn=Be+ue*Mi,ii=Me?.textDecoration||"none",Rs=G=>{if(ii!=="none"){N.lineWidth=Math.max(2,3*qe),N.strokeStyle=G,N.beginPath();const be=Ke+rt*.45;ii.includes("underline")&&(N.moveTo(Be,be),N.lineTo(Be+ue,be)),ii.includes("line-through")&&(N.moveTo(Be,Ke),N.lineTo(Be+ue,Ke)),N.stroke()}};N.save(),N.beginPath(),N.rect(Be-50,Ke-Ze,bn-(Be-50),Ze*2),N.clip(),N.fillStyle=z,V(N,K.text,Be,Ke,Rt),Rs(z),N.restore(),N.save(),N.beginPath(),N.rect(bn,Ke-Ze,Be+ue+50-bn,Ze*2),N.clip(),N.fillStyle=re,N.fillText(K.text,Be,Ke),Rs(re),N.restore(),ht="rgba(0,0,0,0)"}else N.fillStyle=z,V(N,K.text,Be,Ke,Rt),ht=z}else if(B.includes("gradient")||B.includes("chrome")||B.includes("gold")){const Rt=N.createLinearGradient(Be,Ke-Ze/2,Be,Ke+Ze/2);B.includes("gold")?(Rt.addColorStop(0,"#d4af37"),Rt.addColorStop(1,"#C5A028")):B.includes("chrome")?(Rt.addColorStop(0,"#ebebeb"),Rt.addColorStop(.5,"#616161"),Rt.addColorStop(.51,"#ebebeb"),Rt.addColorStop(1,"#ebebeb")):(Rt.addColorStop(0,z),Rt.addColorStop(1,j)),N.fillStyle=Rt}if(B.includes("shadow")&&(N.save(),N.fillStyle="#000000",N.fillText(K.text,Be+2*qe,Ke+2*qe),N.restore()),B.includes("3d")){const Rt=N.fillStyle;N.fillStyle="rgba(0,0,0,0.5)";for(let tn=1;tn<=3;tn++)N.fillText(K.text,Be+tn*qe,Ke+tn*qe);N.fillStyle=Rt}if(B.includes("neon-multi"))N.shadowBlur=10,N.shadowColor="#fff",N.fillText(K.text,Be,Ke),N.shadowBlur=20,N.shadowColor="#ff00de",N.fillText(K.text,Be,Ke),N.shadowBlur=35,N.shadowColor="#00ffff",N.fillText(K.text,Be,Ke);else if(B.includes("cyberpunk"))N.save(),N.fillStyle="#05d9e8",N.fillText(K.text,Be-1,Ke-1),N.restore(),N.save(),N.fillStyle="#000000",N.fillText(K.text,Be+2,Ke+2),N.restore(),N.fillStyle="#fcee0a",N.fillText(K.text,Be,Ke);else if(B.includes("glitch-text")){const Rt=(Math.random()-.5)*5,tn=(Math.random()-.5)*2;N.save(),N.fillStyle="red",N.fillText(K.text,Be+Rt,Ke+tn),N.restore(),N.save(),N.fillStyle="cyan",N.fillText(K.text,Be-Rt,Ke-tn),N.restore(),N.fillStyle="#ffffff",N.fillText(K.text,Be,Ke)}else if(B.includes("retro")||B.includes("vhs")){const Rt=Math.sin(U*5)*2*qe,tn=Math.random()>.95?(Math.random()-.5)*5:0;N.globalCompositeOperation="screen",N.fillStyle="#ff0000",N.fillText(K.text,Be-3*qe+Rt,Ke+tn),N.fillStyle="#00ff00",N.fillText(K.text,Be+tn,Ke-Rt),N.fillStyle="#0000ff",N.fillText(K.text,Be+3*qe-Rt,Ke+tn)}else if(B.includes("fire")){const Rt=Math.abs(Math.sin(U*15))*5,tn=Math.sin(U*20)*1*qe;N.shadowBlur=5+Rt,N.shadowColor="#ff0000",N.fillStyle="#ff4500",N.fillText(K.text,Be,Ke+tn),N.shadowBlur=2,N.shadowColor="#ffff00",N.fillStyle="#ffcc00",N.fillText(K.text,Be+Math.sin(U*25)*1*qe,Ke-1*qe+tn)}else if(B.includes("typewriter")){const Rt=U-K.startTime,tn=K.endTime-K.startTime,En=Math.min(1,Math.max(0,Rt/tn)),Mi=Math.floor(K.text.length*En),bn=K.text.substring(0,Mi);B.includes("outline")?(N.strokeStyle=z,N.strokeText(bn,Be,Ke)):N.fillText(bn,Be,Ke)}else!B.includes("neon-multi")&&!B.includes("retro")&&!B.includes("vhs")&&!B.includes("fire")&&(B.includes("outline")?(N.strokeStyle=z,N.lineWidth=2*qe,N.strokeText(K.text,Be,Ke)):N.fillText(K.text,Be,Ke))}else N.fillText(K.text,Be,Ke);const ti=Me?.textDecoration||"none";if(ti!=="none"){if(N.lineWidth=Math.max(2,3*qe),N.strokeStyle=ht,N.beginPath(),ti.includes("underline")&&!B.includes("underline")){const Rt=Ke+rt*.45;N.moveTo(Be,Rt),N.lineTo(Be+ue,Rt)}ti.includes("line-through")&&(N.moveTo(Be,Ke),N.lineTo(Be+ue,Ke)),N.stroke()}N.restore(),N.restore();let Si=!K.text.endsWith(" ");const ji=/[-‐‑‒–—―]$/,fn=/^[-‐‑‒–—―]/;ji.test(K.text.trim())&&(Si=!1);const fi=Y[de+1];fi&&fn.test(fi.text.trim())&&(Si=!1),M+=ue+(Si?F:0)}),N.restore()})},Q=(N,ye,xe,Oe,at,Ze,U,Me)=>{const Pe=W(N,ye,at),rt=Oe-(Pe.length-1)*Ze/2;Pe.forEach((We,gt)=>{const qe=rt+gt*Ze;if(U==="glass"){const q=N.measureText(We).width;N.save(),N.fillStyle="rgba(255, 255, 255, 0.1)",N.beginPath(),N.roundRect?N.roundRect(xe-(N.textAlign==="center"?q/2:N.textAlign==="right"?q:0)-10,qe-Ze/2,q+20,Ze,8):N.rect(xe-(N.textAlign==="center"?q/2:N.textAlign==="right"?q:0)-10,qe-Ze/2,q+20,Ze),N.fill(),N.strokeStyle="rgba(255, 255, 255, 0.2)",N.stroke(),N.restore()}V(N,We,xe,qe,U,Me)})},k='ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',P='ui-serif, Georgia, Cambria, "Times New Roman", Times, serif',J='ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',ve='"Metal Mania", cursive',fe='"Fredoka One", cursive',Ee='"Shadows Into Light", cursive',je='"Dancing Script", cursive',X='"Orbitron", sans-serif',_e='"UnifrakturMaguntia", cursive';let ne=k;d==="classic"?ne=P:d==="monospace"?ne=J:d==="metal"?ne=ve:d==="kids"?ne=fe:d==="sad"?ne=Ee:d==="romantic"?ne=je:d==="tech"?ne=X:d==="gothic"?ne=_e:d==="custom"&&(ne=T?.fontFamily||k),g&&(ne="CustomFont, sans-serif"),T&&T.fontFamily!=="sans-serif"&&(ne=T.fontFamily);const tt=e<=n,Ce=Math.min(e,n)/1080;if(T&&(T.backgroundSource==="color"||T.backgroundSource==="smart-gradient")?t.fillStyle=T.backgroundColor||"#000000":T&&T.backgroundSource==="threejs"?t.fillStyle=T.threejsBgColor||"#000000":t.fillStyle="#000000",t.fillRect(0,0,e,n),T?.backgroundSource==="gradient"&&T.backgroundGradient)t.fillStyle=T.backgroundGradient,t.fillRect(0,0,e,n);else if(T?.backgroundSource==="smart-gradient"){const N=T.backgroundColor||"#312e81",ye=L(N),xe=t.createLinearGradient(0,0,e,n);xe.addColorStop(0,N),xe.addColorStop(.5,`rgb(${Math.floor(ye.r*.6)}, ${Math.floor(ye.g*.6)}, ${Math.floor(ye.b*.6)})`),xe.addColorStop(1,"#000000"),t.fillStyle=xe,t.fillRect(0,0,e,n)}else if(T?.backgroundSource==="image"&&T.backgroundImage){const N=u.get("__custom_bg__");N&&D(N)}else if(T?.backgroundSource==="video"&&T.backgroundVideo){const N=h.get("__custom_bg_video__");N&&D(N)}else if(T?.backgroundSource==="threejs"){const N=WE(i,e,n,T);N&&t.drawImage(N,0,0,e,n)}if(T&&T.backgroundBlurStrength>0?t.filter=`blur(${T.backgroundBlurStrength}px)`:y&&(t.filter="blur(12px)"),!T||T.backgroundSource==="timeline"||T.backgroundSource==="custom"){const N=T?T.backgroundSource==="timeline":!1;let ye=!1;if(N){const at=T?.visualTransitionType||"none",Ze=T?.visualTransitionDuration||1,U=c.filter(Me=>Me.type==="audio"?!1:i>=Me.startTime&&i=Me.endTime&&i{const rt=(Me.layer||0)-(Pe.layer||0);return rt!==0?rt:Me.startTime-Pe.startTime}),U.length>0&&(U.forEach(Me=>{const Pe=Me.layer||0;if(T&&T.layerVisibility?.visual?.[Pe]===!1)return;const rt=Me.type==="video"?h.get(Me.id):null,We=Me.type!=="video"?u.get(Me.id):null;let gt=1;if(at!=="none"){if(i=Me.endTime){let qe=!1;if(at==="crossfade"&&(qe=c.some(q=>q.id!==Me.id&&(q.layer||0)===(Me.layer||0)&&q.startTime>=Me.endTime-.1&&q.startTimeMe.endTime-Ze){const qe=(Me.endTime-i)/Ze;gt=Math.min(gt,Math.max(0,Math.min(1,qe)))}}gt>0&&(t.save(),t.globalAlpha=gt,rt?D(rt):We&&D(We),t.restore())}),ye=!0)}const xe=T?.backgroundSource||"custom",Oe=xe==="custom"||xe==="timeline"&&c.length===0;if(!ye&&a.coverUrl&&Oe){const at=a.backgroundType==="video"?h.get("background"):null,Ze=u.get("cover");at?D(at):Ze&&D(Ze)}}if((T&&T.backgroundBlurStrength>0||y)&&(t.filter="none"),!["just_video","none"].includes(d)&&!T?.useRealColorMedia&&(t.fillStyle=T&&(T.backgroundSource==="color"||T.backgroundSource==="gradient")?"rgba(0, 0, 0, 0.2)":"rgba(0, 0, 0, 0.5)",t.fillRect(0,0,e,n)),T?.enableGradientOverlay){const N=t.createLinearGradient(0,n,0,0);N.addColorStop(0,"rgba(0, 0, 0, 0.95)"),N.addColorStop(.35,"rgba(0, 0, 0, 0.6)"),N.addColorStop(.7,"rgba(0, 0, 0, 0)"),t.fillStyle=N,t.fillRect(0,0,e,n)}if(T?.showVisualization&&w&&w.length>0){t.save();const N=hE(T);pE(t,w,I||null,e,n,N,i*1e3),t.restore()}if(d==="just_video"||d==="none")return;const $=r.findIndex((N,ye)=>{if(N.endTime!==void 0)return i>=N.time&&i=N.time&&(!xe||i0)if(iye.time>i);ce=N!==-1?N:r.length-1}const Xe=T?.introMode==="manual"&&T.introText?T.introText:`${a.title} +${a.artist}`;let oe=$===-1&&i<5&&(T?.showIntro??!0)&&(T?.introMode!=="manual"||E)&&(r.length===0||i0)){let N=n/2;T?.contentPosition==="top"?N=n*(.15*(T.marginTopScale??1)):T?.contentPosition==="bottom"&&(N=n*(1-.1*(T.marginBottomScale??1)));let ye=0;const xe=["large","large_upper","big_center","metal","kids","sad","romantic","tech","gothic","testing","testing_up","one_line","one_line_up","custom"].includes(d);if(xe||d==="slideshow"||d==="subtitle"){const Me=oe?{text:Xe}:r[$]||r[ce];if(Me){t.font=`900 ${Ie}px ${ne}`;const Pe=["large_upper","big_center","metal","tech","testing_up","one_line_up"].includes(d)?Me.text.toUpperCase():Me.text,rt=W(t,Pe,e*.9);rt.length>1&&(ye=(rt.length-1)*(Ie*1.2)/2)}}let Oe=xe?-1:-2,at=xe?1:2;T?.lyricDisplayMode==="active-only"?(Oe=0,at=0):T?.lyricDisplayMode==="next-only"?(Oe=0,at=1):T?.lyricDisplayMode==="previous-next"?(Oe=-1,at=1):T?.lyricDisplayMode==="all"&&(Oe=-r.length,at=r.length);const Ze=new Map,U=new Map;{const Me=Math.max((tt?30:40)*Ce,Se-Ie);for(let Pe=Oe;Pe<=at;Pe++){let rt=0,We=!1;if(oe&&Pe===0){const gt=Ie*1.2,qe=nt*1.2,C=Xe.split(` +`).length>1;rt=gt+(C?qe:0),We=!0}else{const gt=ce+Pe;if(gt>=0&>st.charAt(0).toUpperCase()+st.substr(1).toLowerCase()):Re==="sentence"?ae=ae.charAt(0).toUpperCase()+ae.slice(1).toLowerCase():Re==="invert"&&(ae=ae.replace(/\w\S*/g,st=>st.charAt(0).toLowerCase()+st.slice(1).toUpperCase())),rt=W(t,ae,e*.9).length*(q*1.2)}}U.set(Pe,rt)}Ze.set(0,N);for(let Pe=1;Pe<=at;Pe++){const rt=Ze.get(Pe-1)??N,We=U.get(Pe-1)??0,gt=U.get(Pe)??0;Ze.set(Pe,rt+We/2+Me+gt/2)}for(let Pe=-1;Pe>=Oe;Pe--){const rt=Ze.get(Pe+1)??N,We=U.get(Pe+1)??0,gt=U.get(Pe)??0;Ze.set(Pe,rt-We/2-Me-gt/2)}}for(let Me=Oe;Me<=at;Me++){let Pe=null,rt=!1;if(oe)Me===0&&(Pe={time:0,text:Xe},rt=!0);else{const We=ce+Me;We>=0&&We1+2.70158*Math.pow(Dt-1,3)+1.70158*Math.pow(Dt-1,2),Jt=Dt=>{const Yt=2*Math.PI/3;return Dt===0?0:Dt===1?1:Math.pow(2,-10*Dt)*Math.sin((Dt*10-.75)*Yt)+1};if(te==="slide")Re=(1-Be)*(et0&&(t.filter=`blur(${F}px)`);const z=rt&&T?.textAnimation||"none";let j=Pe.text,B=T?.textCase||"none";B==="none"&&rt&&["large_upper","big_center","metal","tech","testing_up","one_line_up"].includes(d)&&(B="upper"),B==="upper"?j=j.toUpperCase():B==="lower"?j=j.toLowerCase():B==="title"?j=j.replace(/\w\S*/g,et=>et.charAt(0).toUpperCase()+et.substr(1).toLowerCase()):B==="sentence"?j=j.charAt(0).toUpperCase()+j.slice(1).toLowerCase():B==="invert"&&(j=j.replace(/\w\S*/g,et=>et.charAt(0).toLowerCase()+et.slice(1).toUpperCase()));let re=0,Y=0,me=1,ee=1,$e=0;if(rt&&z!=="none")if(z==="bounce")Y=Math.sin(i*6)*15*Ce;else if(z==="pulse"){const et=1+Math.sin(i*4)*.08;me=et,ee=et}else if(z==="wave")Y=Math.sin(i*4)*20*Ce,$e=Math.sin(i*4)*.05;else if(z==="glitch")Math.sin(i*10)>.8&&(re=(Math.random()-.5)*15*Ce,Y=(Math.random()-.5)*15*Ce);else if(z==="shake")re=(Math.random()-.5)*5*Ce,Y=(Math.random()-.5)*5*Ce;else if(z==="typewriter"){const Te=Math.floor((i-Pe.time)*30);j=j.substring(0,Math.max(0,Te))}else if(z==="wobble"){$e=Math.sin(i*5)*.05;const et=1+Math.sin(i*3)*.05;me=et,ee=et}else if(z==="breathe"){const et=1+Math.sin(i*2)*.03;me=et,ee=et}else if(z==="rotate")$e=Math.sin(i*2)*.05;else if(z==="sway")$e=Math.sin(i*2)*.08;else if(z==="flicker")t.globalAlpha=ae*(.8+Math.random()*.2);else if(z==="jello")me=1+Math.sin(i*6)*.1,ee=1-Math.sin(i*6)*.1;else if(z==="spin")$e=i%2*Math.PI;else if(z==="heartbeat"){const et=i*1.5%1;(et<.1||et>.3&&et<.4)&&(me=1.1,ee=1.1)}else if(z==="tada"){const et=i*1.5%1;et<.1?(me=.9,ee=.9,$e=-.05):et<.2?(me=1.1,ee=1.1,$e=.05):(me=1,ee=1,$e=0)}else z==="swing"&&($e=Math.sin(i*3)*.1);let M=0;Ze.has(Me)?M=Ze.get(Me)+(Me===0?Re:0):(M=d==="subtitle"&&Me===0&&T?.lyricDisplayMode!=="all"?n-140*Ce:N+Me*Se+(Me===0?Re:0),d!=="custom"&&(Me<0?M-=ye:Me>0&&(M+=ye))),M+=Y;let K=e/2;t.textAlign==="left"?K=60*Ce:t.textAlign==="right"&&(K=e-60*Ce),K+=De+re;const de=st*me,ue=it*ee,Ue=le+$e;(de!==1||ue!==1||Ue!==0)&&(t.translate(K,M),t.rotate(Ue),t.scale(de,ue),t.translate(-K,-M));const Je=rt?T?.textEffect||"preset":"none";if(oe&&Me===0&&T?.introMode!=="manual"){const et=j.split(` +`),Te=et[0],Ke=et.slice(1).join(` +`),Be=Ie*1.2,_t=nt*1.2,Jt=20*Ce;let Dt=M;Ke&&(Dt=M-_t/2-Jt/2);const Yt=M+Be/2+Jt/2;if(t.font=`${q} ${qe} ${Ie}px ${ne}`,Q(t,Te,K,Dt,e*.9,Be,Je,C),Ke){const Zt=d==="custom"&&T?.fontWeight?T.fontWeight:"400";t.font=`${q} ${Zt} ${nt}px ${ne}`,Q(t,Ke,K,Yt,e*.9,_t,Je,C)}}else{const et=rt?Ie:nt;T&&T.highlightEffect&&T.highlightEffect,rt&&Pe?H(t,Pe,K,M,e*.9,et*(T?.lyricLineHeight||1.2),i,T,ne,et,qe,q,Ce):Q(t,j,K,M,e*.9,et*(T?.lyricLineHeight||1.2),Je,C)}t.restore()}}}if(!["subtitle","just_video","none"].includes(d)){const N=T?T.showTitle||T.showArtist:!0,ye=T?T.showCover:!0;if(N||ye)if(d==="custom"||d==="default"){const xe=T?.infoPosition||"top-left",Oe=T?.infoStyle||"classic",at=Oe==="box",Ze=at?16*Ce:12*Ce,U=40*Ce*(T?.infoMarginScale??1);let Me="left",Pe="top";xe.includes("left")?Me="left":xe.includes("right")?Me="right":Me="center",xe.includes("top")?Pe="top":Pe="bottom";const rt=T?.infoSizeScale??1,We=(Oe==="minimal"||Oe==="modern"?0:100*Ce)*rt,gt=ye&&We>0&&a.coverUrl!==null,qe=gt?a.backgroundType==="video"?h.get("background"):u.get("cover"):null,q=(Oe==="minimal"?20:Oe==="modern"||Oe==="modern_art"?40:28)*Ce,C=(Oe==="minimal"?14:Oe==="modern"||Oe==="modern_art"?24:18)*Ce,te=q*rt,ae=C*rt,Re=T?.infoFontFamily||ne,De=T?.infoFontWeight||"bold",st=T?.infoFontStyle||"normal",it=`${st} ${De} ${te}px ${Re}`,F=`${st} ${De} ${ae}px ${Re}`,le=20*Ce,z=at?24*Ce:0,j=T?.infoFontColor||"#ffffff",B=Oe==="modern"||Oe==="modern_art"?j:T?.infoFontColor||"#d4d4d8";t.font=it;const re=t.measureText(a.title),Y=T?.showTitle?re.width:0;t.font=F;const me=t.measureText(a.artist),ee=T?.showArtist?me.width:0;let $e=0,M=0;if(Me==="center"){$e=Math.max(gt&&qe?We:0,Y,ee)+z*2;let Be=0;gt&&qe&&(Be+=We),(T?.showTitle??!0)&&(Be+=(gt&&qe?le:0)+te),(T?.showArtist??!0)&&(Be+=(gt&&qe||(T?.showTitle??!0)?5*Ce:0)+ae),M=Be+z*2}else{const Ke=Math.max(Y,ee);$e=(gt&&qe?We+le:0)+Ke+z*2;const _t=(T?.showTitle?te:0)+(T?.showArtist?ae+5*Ce:0);M=Math.max(_t,gt&&qe?We:0)+z*2}let K=0,de=0;Me==="left"?K=U:Me==="right"?K=e-U:K=e/2,Pe==="top"?de=U:de=n-U;let ue=0,Ue=0;Me==="left"?ue=K:Me==="right"?ue=K-$e:ue=K-$e/2,Pe==="top"?Ue=de:Ue=de-M,at&&(t.save(),t.fillStyle="rgba(0, 0, 0, 0.6)",t.shadowColor="rgba(0,0,0,0.5)",t.shadowBlur=20,t.beginPath(),t.roundRect(ue,Ue,$e,M,Ze),t.fill(),t.restore());const Je=ue+z,ht=Ue+z,et=$e-z*2,Te=M-z*2;if(Me==="center"){let Ke=ht;const Be=Je+et/2;if(t.textAlign="center",Pe==="top"){if(gt&&qe){t.save(),t.beginPath();const _t=Be-We/2;Oe==="circle_art"?t.arc(Be,Ke+We/2,We/2,0,Math.PI*2):t.roundRect(_t,Ke,We,We,Ze/2),t.clip(),t.drawImage(qe,_t,Ke,We,We),t.restore(),Ke+=We+le}(T?.showTitle??!0)&&(t.fillStyle=j,t.font=it,t.textBaseline="top",t.fillText(a.title,Be,Ke),Ke+=te+5*Ce),(T?.showArtist??!0)&&(t.fillStyle=B,t.font=F,t.textBaseline="top",t.fillText(a.artist,Be,Ke))}else{if(gt&&qe){t.save(),t.beginPath();const _t=Be-We/2;Oe==="circle_art"?t.arc(Be,Ke+We/2,We/2,0,Math.PI*2):t.roundRect(_t,Ke,We,We,Ze/2),t.clip(),t.drawImage(qe,_t,Ke,We,We),t.restore(),Ke+=We+le}(T?.showTitle??!0)&&(t.fillStyle=j,t.font=it,t.textBaseline="top",t.fillText(a.title,Be,Ke),Ke+=te+5*Ce),(T?.showArtist??!0)&&(t.fillStyle=B,t.font=F,t.textBaseline="top",t.fillText(a.artist,Be,Ke))}}else{const Ke=Me==="right",Be=ht+Te/2;let _t=Je;if(Ke&&(_t=Je+et),gt&&qe){const Yt=Be-We/2,Zt=Ke?_t-We:_t;t.save(),t.beginPath(),Oe==="circle_art"?t.arc(Zt+We/2,Yt+We/2,We/2,0,Math.PI*2):t.roundRect(Zt,Yt,We,We,Ze/2),t.clip(),t.drawImage(qe,Zt,Yt,We,We),t.restore(),Ke?_t-=We+le:_t+=We+le}const Jt=(T?.showTitle?te:0)+(T?.showArtist?ae+5*Ce:0);let Dt=Be-Jt/2;t.textAlign=Ke?"right":"left",t.textBaseline="top",(T?.showTitle??!0)&&(t.fillStyle=j,t.font=it,t.fillText(a.title,_t,Dt),Dt+=te+5*Ce),(T?.showArtist??!0)&&(t.fillStyle=B,t.font=F,t.fillText(a.artist,_t,Dt))}}else if(["big_center","metal","kids","sad","romantic","tech","gothic","testing","testing_up","one_line","one_line_up","slideshow","subtitle"].includes(d)){if(N){t.textAlign="center",t.textBaseline="middle";let xe=80*Ce;["testing","testing_up","one_line","one_line_up"].includes(d)&&(xe=120*Ce),(T?.showTitle??!0)&&(t.font=`bold ${20*Ce}px ${ne}`,t.fillStyle="#ffffff",t.fillText(d==="tech"?a.title.toUpperCase():a.title,e/2,n-xe-30*Ce)),(T?.showArtist??!0)&&(t.font=`${16*Ce}px ${ne}`,t.fillStyle="#d4d4d8",t.fillText(a.artist,e/2,n-xe))}}else{const xe=40*Ce*(T?.infoMarginScale??1),Oe=e===n,at=(tt?Oe?110:150:100)*Ce,Ze=a.coverUrl?u.get("cover"):null,U=12*Ce;if(tt){const Me=xe*(Oe?1.5:3),Pe=e/2,rt=Pe-at/2,We=Me;if(ye&&(t.save(),t.beginPath(),t.roundRect(rt,We,at,at,U),t.clip(),Ze?t.drawImage(Ze,rt,We,at,at):(t.fillStyle="#27272a",t.fillRect(rt,We,at,at)),t.restore()),N){t.textAlign="center",t.textBaseline="top";const gt=We+(ye?at+25*Ce:0),qe=T?.infoFontFamily||ne,q=T?.infoFontColor||"#ffffff",C=T?.infoFontColor||"#d4d4d8",te=T?.infoFontWeight||"bold",ae=T?.infoFontStyle||"normal";(T?.showTitle??!0)&&(t.font=`${ae} ${te} ${(Oe?26:36)*Ce}px ${qe}`,t.fillStyle=q,t.fillText(a.title,Pe,gt)),(T?.showArtist??!0)&&(t.font=`${ae} ${te} ${(Oe?18:24)*Ce}px ${qe}`,t.fillStyle=C,t.fillText(a.artist,Pe,gt+(T?.showTitle??!0?(Oe?30:40)*Ce:0)))}}else{const Me=xe,Pe=xe;if(ye&&(t.save(),t.beginPath(),t.roundRect(Me,Pe,at,at,U),t.clip(),Ze?t.drawImage(Ze,Me,Pe,at,at):(t.fillStyle="#27272a",t.fillRect(Me,Pe,at,at)),t.restore()),N){t.textAlign="left",t.textBaseline="top";const rt=T?.infoFontFamily||ne,We=T?.infoFontColor||"#ffffff",gt=T?.infoFontColor||"#d4d4d8",qe=T?.infoFontWeight||"bold",q=T?.infoFontStyle||"normal",C=Me+(ye?at+25*Ce:0),te=28*Ce,ae=Pe+at/2-te;(T?.showTitle??!0)&&(t.font=`${q} ${qe} ${te}px ${rt}`,t.fillStyle=We,t.fillText(a.title,C,ae)),(T?.showArtist??!0)&&(t.font=`${q} ${qe} ${18*Ce}px ${rt}`,t.fillStyle=gt,t.fillText(a.artist,C,ae+(T?.showTitle??!0?te+5*Ce:0)))}}}}if(T?.showChannelInfo&&!["subtitle","just_video","none"].includes(d)){const N=T.channelInfoPosition||"bottom-right",ye=T.channelInfoStyle||"classic",xe=T.channelInfoSizeScale??1,Oe=T.channelInfoMarginScale??1,at=u.get("__channel_info__"),Ze=T.channelInfoText;if(!(!at&&!Ze)){if(!(ye==="logo"&&!at)){if(!(ye==="minimal"&&!Ze)){t.save();const U=40*Ce*Oe,Me=80*Ce*xe,Pe=ye==="modern"||ye==="logo"?Me*1.2:Me,rt=20*Ce*xe,We=u.get("__channel_info_text_svg__"),gt=!!We;let qe=0,q=rt;if(gt&&We){q=rt*1.5;const j=We.width/We.height;qe=q*j}else{const j=T.channelInfoFontWeight||"bold",B=T.channelInfoFontStyle||"normal";t.font=`${B} ${j} ${rt}px ${T.channelInfoFontFamily||"sans-serif"}`,Ze&&ye!=="logo"&&(qe=t.measureText(Ze).width)}const C=12*Ce*xe,te=12*Ce*xe,ae=8*Ce*xe;let Re=0,De=0;const st=!!at&&ye!=="minimal",it=!!Ze&&ye!=="logo";ye==="modern"?(Re=Math.max(st?Pe:0,it?qe+te*2:0),De=(st?Pe:0)+(st&&it?C:0)+(it?q+ae*2:0)):ye==="box"?(Re=(st?Pe:0)+(st&&it?C:0)+(it?qe:0)+te*2,De=Math.max(st?Pe:0,it?q:0)+ae*2):ye==="minimal"?(Re=it?qe+te*2:0,De=it?q+ae*2:0):ye==="logo"?(Re=Pe,De=Pe):(Re=(st?Pe:0)+(st&&it?C:0)+(it?qe+te*2:0),De=Math.max(st?Pe:0,it?q+ae*2:0));let F=0,le=0;N.includes("left")?F=U:N.includes("right")?F=e-U-Re:N.includes("center")&&(F=(e-Re)/2),N.includes("top")?le=U:N.includes("bottom")&&(le=n-U-De),ye==="box"&&(t.fillStyle="rgba(0, 0, 0, 0.4)",t.shadowColor="rgba(0,0,0,0.5)",t.shadowBlur=10,t.roundRect?(t.beginPath(),t.roundRect(F,le,Re,De,12*Ce*xe),t.fill()):t.fillRect(F,le,Re,De),t.shadowColor="transparent",t.shadowBlur=0);const z=(j,B,re,Y,me)=>{if(ye!=="box"&&ye!=="minimal"&&(t.fillStyle="rgba(0, 0, 0, 0.2)",t.roundRect?(t.beginPath(),t.roundRect(j,B,re,Y,8*Ce*xe),t.fill()):t.fillRect(j,B,re,Y)),gt&&We){const ee=j+(re-qe)/2,$e=B+(Y-q)/2;t.drawImage(We,ee,$e,qe,q)}else{t.fillStyle=T.channelInfoFontColor||"#ffffff",t.textAlign="left",t.textBaseline="top",t.shadowColor="rgba(0,0,0,0.5)",t.shadowBlur=4;const ee=j+(re-qe)/2,$e=B+(Y-q)/2+q*.1;t.fillText(me,ee,$e),t.shadowColor="transparent"}};if(ye==="modern"){let j=le;if(st){const B=F+(Re-Pe)/2;t.drawImage(at,B,j,Pe,Pe),j+=Pe+C}if(it){const B=qe+te*2,re=q+ae*2,Y=F+(Re-B)/2;z(Y,j,B,re,Ze)}}else{const j=N.includes("right");let B=F+(ye==="box"?te:0);const re=le+De/2;if(j&&(ye==="classic"||ye==="circle")){if(it){const Y=qe+te*2,me=q+ae*2;z(B,re-me/2,Y,me,Ze),B+=Y+C}st&&(ye==="circle"?(t.save(),t.beginPath(),t.arc(B+Pe/2,re,Pe/2,0,Math.PI*2),t.closePath(),t.clip(),t.drawImage(at,B,re-Pe/2,Pe,Pe),t.restore()):t.drawImage(at,B,re-Pe/2,Pe,Pe))}else if(st&&(ye==="circle"?(t.save(),t.beginPath(),t.arc(B+Pe/2,re,Pe/2,0,Math.PI*2),t.closePath(),t.clip(),t.drawImage(at,B,re-Pe/2,Pe,Pe),t.restore()):t.drawImage(at,B,re-Pe/2,Pe,Pe),B+=Pe+C),it){const Y=qe+(ye==="box"?0:te*2),me=q+(ye==="box"?0:ae*2);ye==="box"?gt&&We?(t.shadowColor="rgba(0,0,0,0.5)",t.shadowBlur=4,t.drawImage(We,B,re-q/2,qe,q),t.shadowColor="transparent"):(t.fillStyle=T.channelInfoFontColor||"#ffffff",t.textAlign="left",t.textBaseline="middle",t.shadowColor="rgba(0,0,0,0.5)",t.shadowBlur=4,t.fillText(Ze,B,re+q*.1),t.shadowColor="transparent"):z(B,re-me/2,Y,me,Ze)}}t.restore()}}}}};var $n;(function(t){t.LOAD="LOAD",t.EXEC="EXEC",t.FFPROBE="FFPROBE",t.WRITE_FILE="WRITE_FILE",t.READ_FILE="READ_FILE",t.DELETE_FILE="DELETE_FILE",t.RENAME="RENAME",t.CREATE_DIR="CREATE_DIR",t.LIST_DIR="LIST_DIR",t.DELETE_DIR="DELETE_DIR",t.ERROR="ERROR",t.DOWNLOAD="DOWNLOAD",t.PROGRESS="PROGRESS",t.LOG="LOG",t.MOUNT="MOUNT",t.UNMOUNT="UNMOUNT"})($n||($n={}));const mO=(()=>{let t=0;return()=>t++})(),gO=new Error("ffmpeg is not loaded, call `await ffmpeg.load()` first"),vO=new Error("called FFmpeg.terminate()");class xO{#t=null;#i={};#n={};#o=[];#s=[];loaded=!1;#r=()=>{this.#t&&(this.#t.onmessage=({data:{id:e,type:n,data:i}})=>{switch(n){case $n.LOAD:this.loaded=!0,this.#i[e](i);break;case $n.MOUNT:case $n.UNMOUNT:case $n.EXEC:case $n.FFPROBE:case $n.WRITE_FILE:case $n.READ_FILE:case $n.DELETE_FILE:case $n.RENAME:case $n.CREATE_DIR:case $n.LIST_DIR:case $n.DELETE_DIR:this.#i[e](i);break;case $n.LOG:this.#o.forEach(r=>r(i));break;case $n.PROGRESS:this.#s.forEach(r=>r(i));break;case $n.ERROR:this.#n[e](i);break}delete this.#i[e],delete this.#n[e]})};#e=({type:e,data:n},i=[],r)=>this.#t?new Promise((a,c)=>{const u=mO();this.#t&&this.#t.postMessage({id:u,type:e,data:n},i),this.#i[u]=a,this.#n[u]=c,r?.addEventListener("abort",()=>{c(new DOMException(`Message # ${u} was aborted`,"AbortError"))},{once:!0})}):Promise.reject(gO);on(e,n){e==="log"?this.#o.push(n):e==="progress"&&this.#s.push(n)}off(e,n){e==="log"?this.#o=this.#o.filter(i=>i!==n):e==="progress"&&(this.#s=this.#s.filter(i=>i!==n))}load=({classWorkerURL:e,...n}={},{signal:i}={})=>(this.#t||(this.#t=e?new Worker(new URL(e,import.meta.url),{type:"module"}):new Worker(new URL("/assets/worker-BAOIWoxA.js",import.meta.url),{type:"module"}),this.#r()),this.#e({type:$n.LOAD,data:n},void 0,i));exec=(e,n=-1,{signal:i}={})=>this.#e({type:$n.EXEC,data:{args:e,timeout:n}},void 0,i);ffprobe=(e,n=-1,{signal:i}={})=>this.#e({type:$n.FFPROBE,data:{args:e,timeout:n}},void 0,i);terminate=()=>{const e=Object.keys(this.#n);for(const n of e)this.#n[n](vO),delete this.#n[n],delete this.#i[n];this.#t&&(this.#t.terminate(),this.#t=null,this.loaded=!1)};writeFile=(e,n,{signal:i}={})=>{const r=[];return n instanceof Uint8Array&&r.push(n.buffer),this.#e({type:$n.WRITE_FILE,data:{path:e,data:n}},r,i)};mount=(e,n,i)=>{const r=[];return this.#e({type:$n.MOUNT,data:{fsType:e,options:n,mountPoint:i}},r)};unmount=e=>{const n=[];return this.#e({type:$n.UNMOUNT,data:{mountPoint:e}},n)};readFile=(e,n="binary",{signal:i}={})=>this.#e({type:$n.READ_FILE,data:{path:e,encoding:n}},void 0,i);deleteFile=(e,{signal:n}={})=>this.#e({type:$n.DELETE_FILE,data:{path:e}},void 0,n);rename=(e,n,{signal:i}={})=>this.#e({type:$n.RENAME,data:{oldPath:e,newPath:n}},void 0,i);createDir=(e,{signal:n}={})=>this.#e({type:$n.CREATE_DIR,data:{path:e}},void 0,n);listDir=(e,{signal:n}={})=>this.#e({type:$n.LIST_DIR,data:{path:e}},void 0,n);deleteDir=(e,{signal:n}={})=>this.#e({type:$n.DELETE_DIR,data:{path:e}},void 0,n)}var uT;(function(t){t.MEMFS="MEMFS",t.NODEFS="NODEFS",t.NODERAWFS="NODERAWFS",t.IDBFS="IDBFS",t.WORKERFS="WORKERFS",t.PROXYFS="PROXYFS"})(uT||(uT={}));const yO=new Error("failed to get response body reader"),_O=new Error("failed to complete download"),bO="Content-Length",SO=async(t,e)=>{const n=await fetch(t);let i;try{const r=parseInt(n.headers.get(bO)||"-1"),a=n.body?.getReader();if(!a)throw yO;const c=[];let u=0;for(;;){const{done:g,value:v}=await a.read(),y=v?v.length:0;if(g){if(r!=-1&&r!==u)throw _O;e&&e({url:t,total:r,received:u,delta:y,done:g});break}c.push(v),u+=y,e&&e({url:t,total:r,received:u,delta:y,done:g})}const h=new Uint8Array(u);let d=0;for(const g of c)h.set(g,d),d+=g.length;i=h.buffer}catch(r){console.log("failed to send download progress event: ",r),i=await n.arrayBuffer()}return i},vu=async(t,e,n=!1,i)=>{const r=n?await SO(t,i):await(await fetch(t)).arrayBuffer(),a=new Blob([r],{type:e});return URL.createObjectURL(a)};let xu=null,m0=!1,Nf=!1;async function $E(t){if(xu&&m0)return xu;if(Nf){for(;Nf;)await new Promise(e=>setTimeout(e,100));if(xu&&m0)return xu}Nf=!0;try{const e=new xO;if(e.on("log",({message:i})=>{t?.(`[FFmpeg] ${i}`),console.log("[FFmpeg]",i)}),e.on("progress",({progress:i,time:r})=>{t?.(`[FFmpeg Progress] ${(i*100).toFixed(1)}% (${r}s)`)}),typeof window<"u"&&window.crossOriginIsolated){t?.("[FFmpeg] Cross-Origin Isolated: YES. Using Multi-Threaded Core 🚀");const i="https://unpkg.com/@ffmpeg/core-mt@0.12.10/dist/esm";let r,a,c;const u=async(g,v,y)=>{const T=`${g.endsWith("/")?g:`${g}/`}${v}`;try{const A=await fetch(T,{cache:"no-cache",mode:"same-origin"});if(!A.ok)throw new Error(`HTTP ${A.status}`);const E=A.headers.get("Content-Type")||"",w=await A.arrayBuffer(),I=new Uint8Array(w);if(I[0]===60||E.includes("text/html")){const L=new TextDecoder().decode(I.slice(0,100));throw t?.(`[FFmpeg] Error: Path ${T} returned HTML instead of binary. Check if file exists in public/ffmpeg.`),console.debug(`[FFmpeg] Received HTML: ${L}...`),new Error(`Server returned HTML (SPA Redirect) at ${T}`)}if(v.endsWith(".wasm")&&(I[0]!==0||I[1]!==97||I[2]!==115||I[3]!==109))throw new Error("File version mismatch or invalid WASM binary (Check for partial downloads)");return URL.createObjectURL(new Blob([w],{type:y}))}catch(A){throw new Error(`[${v}] ${A.message}`)}},h=window.location.origin,d="/";try{t?.(`[FFmpeg] Initializing (Offline Support: ${navigator.onLine?"OFF":"ACTIVE"})...`);const g=[d.endsWith("/")?`${d}ffmpeg`:`${d}/ffmpeg`,"/ffmpeg","./ffmpeg","ffmpeg",h+"/ffmpeg"].filter((y,S,T)=>T.indexOf(y)===S);let v=!1;for(const y of g)try{t?.(`[FFmpeg] Probing ${y}...`);const S=await u(y,"ffmpeg-core.js","text/javascript"),[T,A]=await Promise.all([u(y,"ffmpeg-core.wasm","application/wasm"),u(y,"ffmpeg-core.worker.js","text/javascript")]);r=S,a=T,c=A,t?.(`[FFmpeg] Success! Core verified at ${y} 🚀`),v=!0;break}catch(S){console.debug(`[FFmpeg] Path ${y} skipped:`,S.message)}if(!v)throw new Error("Could not find valid local binaries")}catch(g){t?.(`[FFmpeg] Local load failed: ${g.message}. Falling back to CDN.`),console.warn("[FFmpeg] Falling back to remote CDN:",g),[r,a,c]=await Promise.all([vu(`${i}/ffmpeg-core.js`,"text/javascript"),vu(`${i}/ffmpeg-core.wasm`,"application/wasm"),vu(`${i}/ffmpeg-core.worker.js`,"text/javascript")])}await e.load({coreURL:r,wasmURL:a,workerURL:c})}else{t?.("[FFmpeg] Cross-Origin Isolated: NO. Using Single-Threaded Core 🐢");const i="https://unpkg.com/@ffmpeg/core@0.12.10/dist/esm";let r,a;const c=async(u,h,d)=>{const v=`${u.endsWith("/")?u:`${u}/`}${h}?v=${Date.now()}`;try{const y=await fetch(v);if(!y.ok||y.headers.get("Content-Type")?.includes("text/html"))throw new Error("404");const S=await y.blob();if((await S.slice(0,10).text()).trim().startsWith("<"))throw new Error("HTML Content");return URL.createObjectURL(new Blob([S],{type:d}))}catch(y){throw y}};try{t?.("[FFmpeg] Searching for local ST core files...");let u=!1;const d=["/ffmpeg","./ffmpeg","ffmpeg",window.location.pathname.replace(/\/[^\/]*$/,"")+"/ffmpeg"];for(const g of d)try{r=await c(g,"ffmpeg-core.js","text/javascript"),a=await c(g,"ffmpeg-core.wasm","application/wasm"),t?.(`[FFmpeg] Success! ST core verified at local ${g} 🐢`),u=!0;break}catch{}if(!u)throw new Error("NotFound")}catch{t?.("[FFmpeg] Local ST core failure. Using CDN."),r=await vu(`${i}/ffmpeg-core.js`,"text/javascript"),a=await vu(`${i}/ffmpeg-core.wasm`,"application/wasm")}await e.load({coreURL:r,wasmURL:a})}return xu=e,m0=!0,t?.("[FFmpeg] Loaded successfully"),e}finally{Nf=!1}}function TO(t,e,n){const i=n==="1080p",a={low:i?28:30,med:i?23:25,high:i?18:20}[e];switch(t){case"h265":return{vcodec:"libx265",args:["-crf",a.toString(),"-preset","medium","-tag:v","hvc1"],format:"mp4",ext:"mp4"};case"vp9":return{vcodec:"libvpx-vp9",args:["-crf",a.toString(),"-b:v","0","-deadline","good","-cpu-used","2"],format:"webm",ext:"webm"};case"av1":return{vcodec:"libaom-av1",args:["-crf",(a+10).toString(),"-b:v","0","-cpu-used","4","-strict","experimental"],format:"mp4",ext:"mp4"};default:return{vcodec:"libx264",args:["-crf",a.toString(),"-preset","medium","-profile:v","high","-level","4.2"],format:"mp4",ext:"mp4"}}}async function XE(t){const{canvas:e,audioFile:n,lyrics:i,metadata:r,visualSlides:a,imageMap:c,videoMap:u,preset:h,customFontName:d,renderConfig:g,fps:v,quality:y,codec:S,aspectRatio:T,onProgress:A,onLog:E,abortSignal:w,isFirstSong:I=!0,isLastSong:L=!0,startTimeOffset:D=0}=t;A(0,"Loading FFmpeg...");const W=await $E(E),V=()=>w?.aborted===!0||w?.current===!0;if(V())throw new Error("Render aborted");if(r.coverUrl&&(r.backgroundType==="video"?(E?.("[FFmpeg] Loading video background from metadata..."),await AO("background",r.coverUrl,u)):(E?.("[FFmpeg] Loading cover art from metadata..."),await CO("cover",r.coverUrl,c))),E?.(`[FFmpeg] VideoMap keys: ${Array.from(u.keys()).join(", ")}`),E?.(`[FFmpeg] RenderConfig Source: ${g.backgroundSource}`),u.has("__custom_bg_video__")){const $=u.get("__custom_bg_video__");E?.(`[FFmpeg] Custom Video: ReadyState=${$?.readyState}, Size=${$?.videoWidth}x${$?.videoHeight}, Duration=${$?.duration}`),$&&($.muted=!0)}else g.backgroundSource==="video"&&E?.("[FFmpeg] WARNING: backgroundSource is 'video' but '__custom_bg_video__' is missing from map!");A(5,"Preparing audio...");const H=URL.createObjectURL(n),Q=await wO(H);URL.revokeObjectURL(H);const k=Math.ceil(Q*v),P=e.getContext("2d");if(!P)throw new Error("Failed to get canvas context");A(10,"Rendering frames...");const J=await n.arrayBuffer();await W.writeFile("audio_src",new Uint8Array(J));let ve=null,fe=44100;if(g.showVisualization)try{E?.("[FFmpeg] Decoding audio for visualization analysis...");const $=new(window.AudioContext||window.webkitAudioContext),ce=await $.decodeAudioData(J.slice(0));ve=ce.getChannelData(0),fe=ce.sampleRate,$.close(),E?.(`[FFmpeg] Audio decoded: ${ce.duration.toFixed(1)}s @ ${fe}Hz`)}catch($){E?.(`[FFmpeg] Warning: Could not decode audio for visualization: ${$.message}`)}const Ee=Math.max(6,k.toString().length);for(let $=0;$0,Q,g,L,I,oe,Ie);const Se=await(await new Promise((xe,Oe)=>{e.toBlob(at=>at?xe(at):Oe(new Error("Failed to create blob")),"image/jpeg",y==="high"?.98:y==="med"?.92:.85)})).arrayBuffer(),N=`frame_${$.toString().padStart(Ee,"0")}.jpg`;await W.writeFile(N,new Uint8Array(Se));const ye=10+$/k*70;A(ye,`Rendering frame ${$+1}/${k}`)}if(V())throw await If(W,k,Ee),new Error("Render aborted");A(80,"Encoding video...");const je=TO(S,y,t.resolution),X=`output.${je.ext}`,_e=["-framerate",v.toString(),"-i",`frame_%0${Ee}d.jpg`,"-i","audio_src","-c:v",je.vcodec,...je.args,"-c:a","aac","-b:a","192k","-ar","44100","-ac","2","-pix_fmt","yuv420p","-movflags","+faststart","-shortest","-y",X];E?.(`[FFmpeg] Running: ffmpeg ${_e.join(" ")}`);try{await W.exec(_e)}catch($){throw console.error("FFmpeg encoding failed:",$),await If(W,k,Ee),new Error(`FFmpeg encoding failed: ${$}`)}A(95,"Finalizing...");const ne=await W.readFile(X),tt=ne instanceof Uint8Array?new Uint8Array(ne):new TextEncoder().encode(ne),Ce=new Blob([tt],{type:je.format==="webm"?"video/webm":"video/mp4"});await If(W,k,Ee);try{await W.deleteFile("audio_src"),await W.deleteFile(X)}catch{}return A(100,"Complete!"),{blob:Ce,duration:Q,format:je.ext}}async function EO(t,e,n){const i=await $E(e.onLog),r=[];let a=0;for(let y=0;y{n(y,t.length,D,W)},startTimeOffset:a}),I=`segment_${y}.${w.format}`,L=await w.blob.arrayBuffer();await i.writeFile(I,new Uint8Array(L)),r.push(I),a+=w.duration}if(t.length===1){const y=await i.readFile(r[0]),S=r[0].split(".").pop()||"mp4";await i.deleteFile(r[0]);const T=y instanceof Uint8Array?new Uint8Array(y):new TextEncoder().encode(y);return{blob:new Blob([T],{type:S==="webm"?"video/webm":"video/mp4"}),duration:a,format:S}}n(t.length,t.length,0,"Concatenating tracks...");const c=r.map(y=>`file '${y}'`).join(` +`);await i.writeFile("concat.txt",new TextEncoder().encode(c));const u=r[0].split(".").pop()||"mp4",h=`final_output.${u}`;await i.exec(["-f","concat","-safe","0","-i","concat.txt","-c","copy","-y",h]);const d=await i.readFile(h),g=d instanceof Uint8Array?new Uint8Array(d):new TextEncoder().encode(d),v=new Blob([g],{type:u==="webm"?"video/webm":"video/mp4"});for(const y of r)try{await i.deleteFile(y)}catch{}try{await i.deleteFile("concat.txt"),await i.deleteFile(h)}catch{}return n(t.length,t.length,100,"Complete!"),{blob:v,duration:a,format:u}}async function wO(t){return new Promise((e,n)=>{const i=document.createElement("audio");i.preload="metadata",i.onloadedmetadata=()=>{e(i.duration),URL.revokeObjectURL(t)},i.onerror=()=>{n(new Error("Failed to load audio metadata")),URL.revokeObjectURL(t)},i.src=t})}async function MO(t,e,n,i){const r=[];t.forEach((a,c)=>{let u=-1;if(c==="__custom_bg_video__"){const h=a.duration||1;h>0&&(u=i%h)}else if(c==="background"){const h=a.duration||1;h>0&&(u=n%h)}else{const h=e.find(d=>d.id===c);if(h&&h.type==="video"&&n>=h.startTime&&n0&&g>=v&&(g=g%v),u=g}}if(u>=0){if(a.readyState===0)return;Math.abs(a.currentTime-u)>.05&&r.push(new Promise(h=>{let d=!1;const g=()=>{d||(d=!0,a.removeEventListener("seeked",g),h())};a.addEventListener("seeked",g),a.currentTime=u,setTimeout(()=>{d||(d=!0,a.removeEventListener("seeked",g),h())},500)}))}}),r.length>0&&await Promise.all(r)}async function CO(t,e,n){if(!(n.has(t)&&n.get(t)?.src===e))return new Promise(i=>{const r=new Image;r.crossOrigin="anonymous",r.onload=()=>{n.set(t,r),i()},r.onerror=()=>{console.warn("Failed to load background image:",e),i()},r.src=e})}async function AO(t,e,n){if(!(n.has(t)&&n.get(t)?.src===e))return new Promise(i=>{const r=document.createElement("video");r.crossOrigin="anonymous",r.muted=!0,r.playsInline=!0,r.preload="auto";let a=!1;const c=()=>{a||(a=!0,n.set(t,r),i())};r.oncanplay=()=>{a||(r.currentTime=.001)},r.onseeked=()=>c(),r.onerror=()=>{console.warn("Failed to load background video:",e),c()},setTimeout(()=>c(),1e4),r.src=e,r.load()})}async function If(t,e,n){for(let i=0;i{if(!e.has(t))throw TypeError("Cannot "+n)},pe=(t,e,n)=>(pv(t,e,"read from private field"),n?n.call(t):e.get(t)),cn=(t,e,n)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,n)},to=(t,e,n,i)=>(pv(t,e,"write to private field"),e.set(t,n),n),RO=(t,e,n,i)=>({set _(r){to(t,e,r)},get _(){return pe(t,e,i)}}),_n=(t,e,n)=>(pv(t,e,"access private method"),n),Cn=new Uint8Array(8),Gs=new DataView(Cn.buffer),$i=t=>[(t%256+256)%256],On=t=>(Gs.setUint16(0,t,!1),[Cn[0],Cn[1]]),NO=t=>(Gs.setInt16(0,t,!1),[Cn[0],Cn[1]]),YE=t=>(Gs.setUint32(0,t,!1),[Cn[1],Cn[2],Cn[3]]),Ct=t=>(Gs.setUint32(0,t,!1),[Cn[0],Cn[1],Cn[2],Cn[3]]),IO=t=>(Gs.setInt32(0,t,!1),[Cn[0],Cn[1],Cn[2],Cn[3]]),$a=t=>(Gs.setUint32(0,Math.floor(t/2**32),!1),Gs.setUint32(4,t,!1),[Cn[0],Cn[1],Cn[2],Cn[3],Cn[4],Cn[5],Cn[6],Cn[7]]),mv=t=>(Gs.setInt16(0,2**8*t,!1),[Cn[0],Cn[1]]),Os=t=>(Gs.setInt32(0,2**16*t,!1),[Cn[0],Cn[1],Cn[2],Cn[3]]),g0=t=>(Gs.setInt32(0,2**30*t,!1),[Cn[0],Cn[1],Cn[2],Cn[3]]),us=(t,e=!1)=>{let n=Array(t.length).fill(null).map((i,r)=>t.charCodeAt(r));return e&&n.push(0),n},hh=t=>t&&t[t.length-1],gv=t=>{let e;for(let n of t)(!e||n.presentationTimestamp>e.presentationTimestamp)&&(e=n);return e},Hs=(t,e,n=!0)=>{let i=t*e;return n?Math.round(i):i},JE=t=>{let e=t*(Math.PI/180),n=Math.cos(e),i=Math.sin(e);return[n,i,0,-i,n,0,0,0,1]},KE=JE(0),ZE=t=>[Os(t[0]),Os(t[1]),g0(t[2]),Os(t[3]),Os(t[4]),g0(t[5]),Os(t[6]),Os(t[7]),g0(t[8])],Iu=t=>!t||typeof t!="object"?t:Array.isArray(t)?t.map(Iu):Object.fromEntries(Object.entries(t).map(([e,n])=>[e,Iu(n)])),hc=t=>t>=0&&t<2**32,Hi=(t,e,n)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:n}),di=(t,e,n,i,r)=>Hi(t,[$i(e),YE(n),i??[]],r),DO=t=>{let e=512;return t.fragmented?Hi("ftyp",[us("iso5"),Ct(e),us("iso5"),us("iso6"),us("mp41")]):Hi("ftyp",[us("isom"),Ct(e),us("isom"),t.holdsAvc?us("avc1"):[],us("mp41")])},Ag=t=>({type:"mdat",largeSize:t}),LO=t=>({type:"free",size:t}),Gf=(t,e,n=!1)=>Hi("moov",null,[UO(e,t),...t.map(i=>kO(i,e)),n?fB(t):null]),UO=(t,e)=>{let n=Hs(Math.max(0,...e.filter(c=>c.samples.length>0).map(c=>{const u=gv(c.samples);return u.presentationTimestamp+u.duration})),Ig),i=Math.max(...e.map(c=>c.id))+1,r=!hc(t)||!hc(n),a=r?$a:Ct;return di("mvhd",+r,0,[a(t),a(t),Ct(Ig),a(n),Os(1),mv(1),Array(10).fill(0),ZE(KE),Array(24).fill(0),Ct(i)])},kO=(t,e)=>Hi("trak",null,[zO(t,e),PO(t,e)]),zO=(t,e)=>{let n=gv(t.samples),i=Hs(n?n.presentationTimestamp+n.duration:0,Ig),r=!hc(e)||!hc(i),a=r?$a:Ct,c;return t.info.type==="video"?c=typeof t.info.rotation=="number"?JE(t.info.rotation):t.info.rotation:c=KE,di("tkhd",+r,3,[a(e),a(e),Ct(t.id),Ct(0),a(i),Array(8).fill(0),On(0),On(0),mv(t.info.type==="audio"?1:0),On(0),ZE(c),Os(t.info.type==="video"?t.info.width:0),Os(t.info.type==="video"?t.info.height:0)])},PO=(t,e)=>Hi("mdia",null,[FO(t,e),OO(t.info.type==="video"?"vide":"soun"),BO(t)]),FO=(t,e)=>{let n=gv(t.samples),i=Hs(n?n.presentationTimestamp+n.duration:0,t.timescale),r=!hc(e)||!hc(i),a=r?$a:Ct;return di("mdhd",+r,0,[a(e),a(e),Ct(t.timescale),a(i),On(21956),On(0)])},OO=t=>di("hdlr",0,0,[us("mhlr"),us(t),Ct(0),Ct(0),Ct(0),us("mp4-muxer-hdlr",!0)]),BO=t=>Hi("minf",null,[t.info.type==="video"?VO():HO(),GO(),WO(t)]),VO=()=>di("vmhd",0,1,[On(0),On(0),On(0),On(0)]),HO=()=>di("smhd",0,0,[On(0),On(0)]),GO=()=>Hi("dinf",null,[jO()]),jO=()=>di("dref",0,0,[Ct(1)],[qO()]),qO=()=>di("url ",0,1),WO=t=>{const e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(n=>n.sampleCompositionTimeOffset!==0);return Hi("stbl",null,[$O(t),rB(t),aB(t),lB(t),cB(t),uB(t),e?dB(t):null])},$O=t=>di("stsd",0,0,[Ct(1)],[t.info.type==="video"?XO(SB[t.info.codec],t):iB(EB[t.info.codec],t)]),XO=(t,e)=>Hi(t,[Array(6).fill(0),On(1),On(0),On(0),Array(12).fill(0),On(e.info.width),On(e.info.height),Ct(4718592),Ct(4718592),Ct(0),On(1),Array(32).fill(0),On(24),NO(65535)],[TB[e.info.codec](e),e.info.decoderConfig.colorSpace?ZO(e):null]),YO={bt709:1,bt470bg:5,smpte170m:6},JO={bt709:1,smpte170m:6,"iec61966-2-1":13},KO={rgb:0,bt709:1,bt470bg:5,smpte170m:6},ZO=t=>Hi("colr",[us("nclx"),On(YO[t.info.decoderConfig.colorSpace.primaries]),On(JO[t.info.decoderConfig.colorSpace.transfer]),On(KO[t.info.decoderConfig.colorSpace.matrix]),$i((t.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),QO=t=>t.info.decoderConfig&&Hi("avcC",[...new Uint8Array(t.info.decoderConfig.description)]),eB=t=>t.info.decoderConfig&&Hi("hvcC",[...new Uint8Array(t.info.decoderConfig.description)]),tB=t=>{if(!t.info.decoderConfig)return null;let e=t.info.decoderConfig;if(!e.colorSpace)throw new Error("'colorSpace' is required in the decoder config for VP9.");let n=e.codec.split("."),i=Number(n[1]),r=Number(n[2]),u=(Number(n[3])<<4)+(0<<1)+Number(e.colorSpace.fullRange);return di("vpcC",1,0,[$i(i),$i(r),$i(u),$i(2),$i(2),$i(2),On(0)])},nB=()=>{let n=(1<<7)+1;return Hi("av1C",[n,0,0,0])},iB=(t,e)=>Hi(t,[Array(6).fill(0),On(1),On(0),On(0),Ct(0),On(e.info.numberOfChannels),On(16),On(0),On(0),Os(e.info.sampleRate)],[wB[e.info.codec](e)]),oB=t=>{let e=new Uint8Array(t.info.decoderConfig.description);return di("esds",0,0,[Ct(58753152),$i(32+e.byteLength),On(1),$i(0),Ct(75530368),$i(18+e.byteLength),$i(64),$i(21),YE(0),Ct(130071),Ct(130071),Ct(92307584),$i(e.byteLength),...e,Ct(109084800),$i(1),$i(2)])},sB=t=>{let e=3840,n=0;const i=t.info.decoderConfig?.description;if(i){if(i.byteLength<18)throw new TypeError("Invalid decoder description provided for Opus; must be at least 18 bytes long.");const r=ArrayBuffer.isView(i)?new DataView(i.buffer,i.byteOffset,i.byteLength):new DataView(i);e=r.getUint16(10,!0),n=r.getInt16(14,!0)}return Hi("dOps",[$i(0),$i(t.info.numberOfChannels),On(e),Ct(t.info.sampleRate),mv(n),$i(0)])},rB=t=>di("stts",0,0,[Ct(t.timeToSampleTable.length),t.timeToSampleTable.map(e=>[Ct(e.sampleCount),Ct(e.sampleDelta)])]),aB=t=>{if(t.samples.every(n=>n.type==="key"))return null;let e=[...t.samples.entries()].filter(([,n])=>n.type==="key");return di("stss",0,0,[Ct(e.length),e.map(([n])=>Ct(n+1))])},lB=t=>di("stsc",0,0,[Ct(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(e=>[Ct(e.firstChunk),Ct(e.samplesPerChunk),Ct(1)])]),cB=t=>di("stsz",0,0,[Ct(0),Ct(t.samples.length),t.samples.map(e=>Ct(e.size))]),uB=t=>t.finalizedChunks.length>0&&hh(t.finalizedChunks).offset>=2**32?di("co64",0,0,[Ct(t.finalizedChunks.length),t.finalizedChunks.map(e=>$a(e.offset))]):di("stco",0,0,[Ct(t.finalizedChunks.length),t.finalizedChunks.map(e=>Ct(e.offset))]),dB=t=>di("ctts",0,0,[Ct(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(e=>[Ct(e.sampleCount),Ct(e.sampleCompositionTimeOffset)])]),fB=t=>Hi("mvex",null,t.map(hB)),hB=t=>di("trex",0,0,[Ct(t.id),Ct(1),Ct(0),Ct(0),Ct(0)]),dT=(t,e)=>Hi("moof",null,[pB(t),...e.map(mB)]),pB=t=>di("mfhd",0,0,[Ct(t)]),QE=t=>{let e=0,n=0,i=0,r=0,a=t.type==="delta";return n|=+a,a?e|=1:e|=2,e<<24|n<<16|i<<8|r},mB=t=>Hi("traf",null,[gB(t),vB(t),xB(t)]),gB=t=>{let e=0;e|=8,e|=16,e|=32,e|=131072;let n=t.currentChunk.samples[1]??t.currentChunk.samples[0],i={duration:n.timescaleUnitsToNextSample,size:n.size,flags:QE(n)};return di("tfhd",0,e,[Ct(t.id),Ct(i.duration),Ct(i.size),Ct(i.flags)])},vB=t=>di("tfdt",1,0,[$a(Hs(t.currentChunk.startTimestamp,t.timescale))]),xB=t=>{let e=t.currentChunk.samples.map(A=>A.timescaleUnitsToNextSample),n=t.currentChunk.samples.map(A=>A.size),i=t.currentChunk.samples.map(QE),r=t.currentChunk.samples.map(A=>Hs(A.presentationTimestamp-A.decodeTimestamp,t.timescale)),a=new Set(e),c=new Set(n),u=new Set(i),h=new Set(r),d=u.size===2&&i[0]!==i[1],g=a.size>1,v=c.size>1,y=!d&&u.size>1,S=h.size>1||[...h].some(A=>A!==0),T=0;return T|=1,T|=4*+d,T|=256*+g,T|=512*+v,T|=1024*+y,T|=2048*+S,di("trun",1,T,[Ct(t.currentChunk.samples.length),Ct(t.currentChunk.offset-t.currentChunk.moofOffset||0),d?Ct(i[0]):[],t.currentChunk.samples.map((A,E)=>[g?Ct(e[E]):[],v?Ct(n[E]):[],y?Ct(i[E]):[],S?IO(r[E]):[]])])},yB=t=>Hi("mfra",null,[...t.map(_B),bB()]),_B=(t,e)=>di("tfra",1,0,[Ct(t.id),Ct(63),Ct(t.finalizedChunks.length),t.finalizedChunks.map(i=>[$a(Hs(i.startTimestamp,t.timescale)),$a(i.moofOffset),Ct(e+1),Ct(1),Ct(1)])]),bB=()=>di("mfro",0,0,[Ct(0)]),SB={avc:"avc1",hevc:"hvc1",vp9:"vp09",av1:"av01"},TB={avc:QO,hevc:eB,vp9:tB,av1:nB},EB={aac:"mp4a",opus:"Opus"},wB={aac:oB,opus:sB},Rh=class{},vv=class extends Rh{constructor(){super(...arguments),this.buffer=null}},ew=class extends Rh{constructor(t){if(super(),this.options=t,typeof t!="object")throw new TypeError("StreamTarget requires an options object to be passed to its constructor.");if(t.onData){if(typeof t.onData!="function")throw new TypeError("options.onData, when provided, must be a function.");if(t.onData.length<2)throw new TypeError("options.onData, when provided, must be a function that takes in at least two arguments (data and position). Ignoring the position argument, which specifies the byte offset at which the data is to be written, can lead to broken outputs.")}if(t.chunked!==void 0&&typeof t.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(t.chunkSize!==void 0&&(!Number.isInteger(t.chunkSize)||t.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.")}},MB=class extends Rh{constructor(t,e){if(super(),this.stream=t,this.options=e,!(t instanceof FileSystemWritableFileStream))throw new TypeError("FileSystemWritableFileStreamTarget requires a FileSystemWritableFileStream instance.");if(e!==void 0&&typeof e!="object")throw new TypeError("FileSystemWritableFileStreamTarget's options, when provided, must be an object.");if(e&&e.chunkSize!==void 0&&(!Number.isInteger(e.chunkSize)||e.chunkSize<=0))throw new TypeError("options.chunkSize, when provided, must be a positive integer")}},La,Wl,tw=class{constructor(){this.pos=0,cn(this,La,new Uint8Array(8)),cn(this,Wl,new DataView(pe(this,La).buffer)),this.offsets=new WeakMap}seek(t){this.pos=t}writeU32(t){pe(this,Wl).setUint32(0,t,!1),this.write(pe(this,La).subarray(0,4))}writeU64(t){pe(this,Wl).setUint32(0,Math.floor(t/2**32),!1),pe(this,Wl).setUint32(4,t,!1),this.write(pe(this,La).subarray(0,8))}writeAscii(t){for(let e=0;en.start-i.start);t.push({start:e[0].start,size:e[0].data.byteLength});for(let n=1;nu.start<=e&&eRB){for(let u=0;u=t.written[r+1].start;)t.written[r].end=Math.max(t.written[r].end,t.written[r+1].end),t.written.splice(r+1,1)};yv=new WeakSet;iw=function(t){let n={start:Math.floor(t/pe(this,vr))*pe(this,vr),data:new Uint8Array(pe(this,vr)),written:[],shouldFlush:!1};return pe(this,Yo).push(n),pe(this,Yo).sort((i,r)=>i.start-r.start),pe(this,Yo).indexOf(n)};Lu=new WeakSet;mh=function(t=!1){for(let e=0;et.stream.write({type:"write",data:e,position:n}),chunked:!0,chunkSize:t.options?.chunkSize}))}},Ig=1e3,IB=["avc","hevc","vp9","av1"],DB=["aac","opus"],LB=2082844800,UB=["strict","offset","cross-track-offset"],Bt,Xt,gh,qo,co,eo,Zl,sc,bv,ka,za,Uu,Dg,ow,Lg,sw,Sv,rw,Ug,aw,Tv,lw,Wf,kg,zs,pr,Ev,cw,ku,vh,xh,wv,pc,ju,$f,zg,uw=class{constructor(t){if(cn(this,Dg),cn(this,Lg),cn(this,Sv),cn(this,Ug),cn(this,Tv),cn(this,Wf),cn(this,zs),cn(this,Ev),cn(this,ku),cn(this,xh),cn(this,pc),cn(this,$f),cn(this,Bt,void 0),cn(this,Xt,void 0),cn(this,gh,void 0),cn(this,qo,void 0),cn(this,co,null),cn(this,eo,null),cn(this,Zl,Math.floor(Date.now()/1e3)+LB),cn(this,sc,[]),cn(this,bv,1),cn(this,ka,[]),cn(this,za,[]),cn(this,Uu,!1),_n(this,Dg,ow).call(this,t),t.video=Iu(t.video),t.audio=Iu(t.audio),t.fastStart=Iu(t.fastStart),this.target=t.target,to(this,Bt,{firstTimestampBehavior:"strict",...t}),t.target instanceof vv)to(this,Xt,new CB(t.target));else if(t.target instanceof ew)to(this,Xt,new _v(t.target));else if(t.target instanceof MB)to(this,Xt,new NB(t.target));else throw new Error(`Invalid target: ${t.target}`);_n(this,Ug,aw).call(this),_n(this,Lg,sw).call(this)}addVideoChunk(t,e,n,i){if(!(t instanceof EncodedVideoChunk))throw new TypeError("addVideoChunk's first argument (sample) must be of type EncodedVideoChunk.");if(e&&typeof e!="object")throw new TypeError("addVideoChunk's second argument (meta), when provided, must be an object.");if(n!==void 0&&(!Number.isFinite(n)||n<0))throw new TypeError("addVideoChunk's third argument (timestamp), when provided, must be a non-negative real number.");if(i!==void 0&&!Number.isFinite(i))throw new TypeError("addVideoChunk's fourth argument (compositionTimeOffset), when provided, must be a real number.");let r=new Uint8Array(t.byteLength);t.copyTo(r),this.addVideoChunkRaw(r,t.type,n??t.timestamp,t.duration,e,i)}addVideoChunkRaw(t,e,n,i,r,a){if(!(t instanceof Uint8Array))throw new TypeError("addVideoChunkRaw's first argument (data) must be an instance of Uint8Array.");if(e!=="key"&&e!=="delta")throw new TypeError("addVideoChunkRaw's second argument (type) must be either 'key' or 'delta'.");if(!Number.isFinite(n)||n<0)throw new TypeError("addVideoChunkRaw's third argument (timestamp) must be a non-negative real number.");if(!Number.isFinite(i)||i<0)throw new TypeError("addVideoChunkRaw's fourth argument (duration) must be a non-negative real number.");if(r&&typeof r!="object")throw new TypeError("addVideoChunkRaw's fifth argument (meta), when provided, must be an object.");if(a!==void 0&&!Number.isFinite(a))throw new TypeError("addVideoChunkRaw's sixth argument (compositionTimeOffset), when provided, must be a real number.");if(_n(this,$f,zg).call(this),!pe(this,Bt).video)throw new Error("No video track declared.");if(typeof pe(this,Bt).fastStart=="object"&&pe(this,co).samples.length===pe(this,Bt).fastStart.expectedVideoChunks)throw new Error(`Cannot add more video chunks than specified in 'fastStart' (${pe(this,Bt).fastStart.expectedVideoChunks}).`);let c=_n(this,Wf,kg).call(this,pe(this,co),t,e,n,i,r,a);if(pe(this,Bt).fastStart==="fragmented"&&pe(this,eo)){for(;pe(this,za).length>0&&pe(this,za)[0].decodeTimestamp<=c.decodeTimestamp;){let u=pe(this,za).shift();_n(this,zs,pr).call(this,pe(this,eo),u)}c.decodeTimestamp<=pe(this,eo).lastDecodeTimestamp?_n(this,zs,pr).call(this,pe(this,co),c):pe(this,ka).push(c)}else _n(this,zs,pr).call(this,pe(this,co),c)}addAudioChunk(t,e,n){if(!(t instanceof EncodedAudioChunk))throw new TypeError("addAudioChunk's first argument (sample) must be of type EncodedAudioChunk.");if(e&&typeof e!="object")throw new TypeError("addAudioChunk's second argument (meta), when provided, must be an object.");if(n!==void 0&&(!Number.isFinite(n)||n<0))throw new TypeError("addAudioChunk's third argument (timestamp), when provided, must be a non-negative real number.");let i=new Uint8Array(t.byteLength);t.copyTo(i),this.addAudioChunkRaw(i,t.type,n??t.timestamp,t.duration,e)}addAudioChunkRaw(t,e,n,i,r){if(!(t instanceof Uint8Array))throw new TypeError("addAudioChunkRaw's first argument (data) must be an instance of Uint8Array.");if(e!=="key"&&e!=="delta")throw new TypeError("addAudioChunkRaw's second argument (type) must be either 'key' or 'delta'.");if(!Number.isFinite(n)||n<0)throw new TypeError("addAudioChunkRaw's third argument (timestamp) must be a non-negative real number.");if(!Number.isFinite(i)||i<0)throw new TypeError("addAudioChunkRaw's fourth argument (duration) must be a non-negative real number.");if(r&&typeof r!="object")throw new TypeError("addAudioChunkRaw's fifth argument (meta), when provided, must be an object.");if(_n(this,$f,zg).call(this),!pe(this,Bt).audio)throw new Error("No audio track declared.");if(typeof pe(this,Bt).fastStart=="object"&&pe(this,eo).samples.length===pe(this,Bt).fastStart.expectedAudioChunks)throw new Error(`Cannot add more audio chunks than specified in 'fastStart' (${pe(this,Bt).fastStart.expectedAudioChunks}).`);let a=_n(this,Wf,kg).call(this,pe(this,eo),t,e,n,i,r);if(pe(this,Bt).fastStart==="fragmented"&&pe(this,co)){for(;pe(this,ka).length>0&&pe(this,ka)[0].decodeTimestamp<=a.decodeTimestamp;){let c=pe(this,ka).shift();_n(this,zs,pr).call(this,pe(this,co),c)}a.decodeTimestamp<=pe(this,co).lastDecodeTimestamp?_n(this,zs,pr).call(this,pe(this,eo),a):pe(this,za).push(a)}else _n(this,zs,pr).call(this,pe(this,eo),a)}finalize(){if(pe(this,Uu))throw new Error("Cannot finalize a muxer more than once.");if(pe(this,Bt).fastStart==="fragmented"){for(let e of pe(this,ka))_n(this,zs,pr).call(this,pe(this,co),e);for(let e of pe(this,za))_n(this,zs,pr).call(this,pe(this,eo),e);_n(this,xh,wv).call(this,!1)}else pe(this,co)&&_n(this,ku,vh).call(this,pe(this,co)),pe(this,eo)&&_n(this,ku,vh).call(this,pe(this,eo));let t=[pe(this,co),pe(this,eo)].filter(Boolean);if(pe(this,Bt).fastStart==="in-memory"){let e;for(let i=0;i<2;i++){let r=Gf(t,pe(this,Zl)),a=pe(this,Xt).measureBox(r);e=pe(this,Xt).measureBox(pe(this,qo));let c=pe(this,Xt).pos+a+e;for(let u of pe(this,sc)){u.offset=c;for(let{data:h}of u.samples)c+=h.byteLength,e+=h.byteLength}if(c<2**32)break;e>=2**32&&(pe(this,qo).largeSize=!0)}let n=Gf(t,pe(this,Zl));pe(this,Xt).writeBox(n),pe(this,qo).size=e,pe(this,Xt).writeBox(pe(this,qo));for(let i of pe(this,sc))for(let r of i.samples)pe(this,Xt).write(r.data),r.data=null}else if(pe(this,Bt).fastStart==="fragmented"){let e=pe(this,Xt).pos,n=yB(t);pe(this,Xt).writeBox(n);let i=pe(this,Xt).pos-e;pe(this,Xt).seek(pe(this,Xt).pos-4),pe(this,Xt).writeU32(i)}else{let e=pe(this,Xt).offsets.get(pe(this,qo)),n=pe(this,Xt).pos-e;pe(this,qo).size=n,pe(this,qo).largeSize=n>=2**32,pe(this,Xt).patchBox(pe(this,qo));let i=Gf(t,pe(this,Zl));if(typeof pe(this,Bt).fastStart=="object"){pe(this,Xt).seek(pe(this,gh)),pe(this,Xt).writeBox(i);let r=e-pe(this,Xt).pos;pe(this,Xt).writeBox(LO(r))}else pe(this,Xt).writeBox(i)}_n(this,pc,ju).call(this),pe(this,Xt).finalize(),to(this,Uu,!0)}};Bt=new WeakMap;Xt=new WeakMap;gh=new WeakMap;qo=new WeakMap;co=new WeakMap;eo=new WeakMap;Zl=new WeakMap;sc=new WeakMap;bv=new WeakMap;ka=new WeakMap;za=new WeakMap;Uu=new WeakMap;Dg=new WeakSet;ow=function(t){if(typeof t!="object")throw new TypeError("The muxer requires an options object to be passed to its constructor.");if(!(t.target instanceof Rh))throw new TypeError("The target must be provided and an instance of Target.");if(t.video){if(!IB.includes(t.video.codec))throw new TypeError(`Unsupported video codec: ${t.video.codec}`);if(!Number.isInteger(t.video.width)||t.video.width<=0)throw new TypeError(`Invalid video width: ${t.video.width}. Must be a positive integer.`);if(!Number.isInteger(t.video.height)||t.video.height<=0)throw new TypeError(`Invalid video height: ${t.video.height}. Must be a positive integer.`);const e=t.video.rotation;if(typeof e=="number"&&![0,90,180,270].includes(e))throw new TypeError(`Invalid video rotation: ${e}. Has to be 0, 90, 180 or 270.`);if(Array.isArray(e)&&(e.length!==9||e.some(n=>typeof n!="number")))throw new TypeError(`Invalid video transformation matrix: ${e.join()}`);if(t.video.frameRate!==void 0&&(!Number.isInteger(t.video.frameRate)||t.video.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.video.frameRate}. Must be a positive integer.`)}if(t.audio){if(!DB.includes(t.audio.codec))throw new TypeError(`Unsupported audio codec: ${t.audio.codec}`);if(!Number.isInteger(t.audio.numberOfChannels)||t.audio.numberOfChannels<=0)throw new TypeError(`Invalid number of audio channels: ${t.audio.numberOfChannels}. Must be a positive integer.`);if(!Number.isInteger(t.audio.sampleRate)||t.audio.sampleRate<=0)throw new TypeError(`Invalid audio sample rate: ${t.audio.sampleRate}. Must be a positive integer.`)}if(t.firstTimestampBehavior&&!UB.includes(t.firstTimestampBehavior))throw new TypeError(`Invalid first timestamp behavior: ${t.firstTimestampBehavior}`);if(typeof t.fastStart=="object"){if(t.video){if(t.fastStart.expectedVideoChunks===void 0)throw new TypeError("'fastStart' is an object but is missing property 'expectedVideoChunks'.");if(!Number.isInteger(t.fastStart.expectedVideoChunks)||t.fastStart.expectedVideoChunks<0)throw new TypeError("'expectedVideoChunks' must be a non-negative integer.")}if(t.audio){if(t.fastStart.expectedAudioChunks===void 0)throw new TypeError("'fastStart' is an object but is missing property 'expectedAudioChunks'.");if(!Number.isInteger(t.fastStart.expectedAudioChunks)||t.fastStart.expectedAudioChunks<0)throw new TypeError("'expectedAudioChunks' must be a non-negative integer.")}}else if(![!1,"in-memory","fragmented"].includes(t.fastStart))throw new TypeError("'fastStart' option must be false, 'in-memory', 'fragmented' or an object.");if(t.minFragmentDuration!==void 0&&(!Number.isFinite(t.minFragmentDuration)||t.minFragmentDuration<0))throw new TypeError("'minFragmentDuration' must be a non-negative number.")};Lg=new WeakSet;sw=function(){if(pe(this,Xt).writeBox(DO({holdsAvc:pe(this,Bt).video?.codec==="avc",fragmented:pe(this,Bt).fastStart==="fragmented"})),to(this,gh,pe(this,Xt).pos),pe(this,Bt).fastStart==="in-memory")to(this,qo,Ag(!1));else if(pe(this,Bt).fastStart!=="fragmented"){if(typeof pe(this,Bt).fastStart=="object"){let t=_n(this,Sv,rw).call(this);pe(this,Xt).seek(pe(this,Xt).pos+t)}to(this,qo,Ag(!0)),pe(this,Xt).writeBox(pe(this,qo))}_n(this,pc,ju).call(this)};Sv=new WeakSet;rw=function(){if(typeof pe(this,Bt).fastStart!="object")return;let t=0,e=[pe(this,Bt).fastStart.expectedVideoChunks,pe(this,Bt).fastStart.expectedAudioChunks];for(let n of e)n&&(t+=8*Math.ceil(2/3*n),t+=4*n,t+=12*Math.ceil(2/3*n),t+=4*n,t+=8*n);return t+=4096,t};Ug=new WeakSet;aw=function(){if(pe(this,Bt).video&&to(this,co,{id:1,info:{type:"video",codec:pe(this,Bt).video.codec,width:pe(this,Bt).video.width,height:pe(this,Bt).video.height,rotation:pe(this,Bt).video.rotation??0,decoderConfig:null},timescale:pe(this,Bt).video.frameRate??57600,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),pe(this,Bt).audio&&(to(this,eo,{id:pe(this,Bt).video?2:1,info:{type:"audio",codec:pe(this,Bt).audio.codec,numberOfChannels:pe(this,Bt).audio.numberOfChannels,sampleRate:pe(this,Bt).audio.sampleRate,decoderConfig:null},timescale:pe(this,Bt).audio.sampleRate,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),pe(this,Bt).audio.codec==="aac")){let t=_n(this,Tv,lw).call(this,2,pe(this,Bt).audio.sampleRate,pe(this,Bt).audio.numberOfChannels);pe(this,eo).info.decoderConfig={codec:pe(this,Bt).audio.codec,description:t,numberOfChannels:pe(this,Bt).audio.numberOfChannels,sampleRate:pe(this,Bt).audio.sampleRate}}};Tv=new WeakSet;lw=function(t,e,n){let r=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350].indexOf(e),a=n,c="";c+=t.toString(2).padStart(5,"0"),c+=r.toString(2).padStart(4,"0"),r===15&&(c+=e.toString(2).padStart(24,"0")),c+=a.toString(2).padStart(4,"0");let u=Math.ceil(c.length/8)*8;c=c.padEnd(u,"0");let h=new Uint8Array(c.length/8);for(let d=0;d=c&&(i=!0,_n(this,xh,wv).call(this))}else i=r>=.5}i&&(t.currentChunk&&_n(this,ku,vh).call(this,t),t.currentChunk={startTimestamp:e.presentationTimestamp,samples:[]}),t.currentChunk.samples.push(e)};Ev=new WeakSet;cw=function(t,e,n){const i=pe(this,Bt).firstTimestampBehavior==="strict",r=n.lastDecodeTimestamp===-1;if(i&&r&&e!==0)throw new Error(`The first chunk for your media track must have a timestamp of 0 (received DTS=${e}).Non-zero first timestamps are often caused by directly piping frames or audio data from a MediaStreamTrack into the encoder. Their timestamps are typically relative to the age of thedocument, which is probably what you want. + +If you want to offset all timestamps of a track such that the first one is zero, set firstTimestampBehavior: 'offset' in the options. +`);if(pe(this,Bt).firstTimestampBehavior==="offset"||pe(this,Bt).firstTimestampBehavior==="cross-track-offset"){n.firstDecodeTimestamp===void 0&&(n.firstDecodeTimestamp=e);let c;pe(this,Bt).firstTimestampBehavior==="offset"?c=n.firstDecodeTimestamp:c=Math.min(pe(this,co)?.firstDecodeTimestamp??1/0,pe(this,eo)?.firstDecodeTimestamp??1/0),e-=c,t-=c}if(eu&&u.currentChunk);if(e.length===0)return;let n=RO(this,bv)._++;if(n===1){let u=Gf(e,pe(this,Zl),!0);pe(this,Xt).writeBox(u)}let i=pe(this,Xt).pos,r=dT(n,e);pe(this,Xt).writeBox(r);{let u=Ag(!1),h=0;for(let g of e)for(let v of g.currentChunk.samples)h+=v.size;let d=pe(this,Xt).measureBox(u)+h;d>=2**32&&(u.largeSize=!0,d=pe(this,Xt).measureBox(u)+h),u.size=d,pe(this,Xt).writeBox(u)}for(let u of e){u.currentChunk.offset=pe(this,Xt).pos,u.currentChunk.moofOffset=i;for(let h of u.currentChunk.samples)pe(this,Xt).write(h.data),h.data=null}let a=pe(this,Xt).pos;pe(this,Xt).seek(pe(this,Xt).offsets.get(r));let c=dT(n,e);pe(this,Xt).writeBox(c),pe(this,Xt).seek(a);for(let u of e)u.finalizedChunks.push(u.currentChunk),pe(this,sc).push(u.currentChunk),u.currentChunk=null;t&&_n(this,pc,ju).call(this)};pc=new WeakSet;ju=function(){pe(this,Xt)instanceof _v&&pe(this,Xt).flush()};$f=new WeakSet;zg=function(){if(pe(this,Uu))throw new Error("Cannot add new video or audio chunks after the file has been finalized.")};function Mv(){return typeof window<"u"&&"VideoEncoder"in window&&"AudioEncoder"in window}async function Pg(t){const e=await t.arrayBuffer(),n=new(window.AudioContext||window.webkitAudioContext),i=await n.decodeAudioData(e);return n.close(),i}async function dw(t,e,n,i){const r=[];t.forEach((a,c)=>{let u=-1;if(c==="__custom_bg_video__"){const h=a.duration||1;h>0&&(u=(i!==void 0?i:n)%h)}else if(c==="background"){const h=a.duration||1;h>0&&(u=n%h)}else{const h=e.find(d=>d.id===c);if(h&&h.type==="video"&&n>=h.startTime&&n0&&g>=v&&(g=g%v),u=g}}if(u>=0){if(a.readyState===0)return;Math.abs(a.currentTime-u)>.05&&r.push(new Promise(h=>{let d=!1;const g=()=>{d||(d=!0,a.removeEventListener("seeked",g),h())};a.addEventListener("seeked",g),a.currentTime=u,setTimeout(()=>{d||(d=!0,a.removeEventListener("seeked",g),h())},500)}))}}),r.length>0&&await Promise.all(r)}async function kB(t,e,n){if(!(n.has(t)&&n.get(t)?.src===e))return new Promise(i=>{const r=new Image;r.crossOrigin="anonymous",r.onload=()=>{n.set(t,r),i()},r.onerror=()=>{console.warn("Failed to load background image:",e),i()},r.src=e})}async function zB(t,e,n){if(!(n.has(t)&&n.get(t)?.src===e))return new Promise(i=>{const r=document.createElement("video");r.crossOrigin="anonymous",r.muted=!0,r.playsInline=!0,r.preload="auto";let a=!1;const c=()=>{a||(a=!0,n.set(t,r),i())};r.oncanplay=()=>{a||(r.currentTime=.001)},r.onseeked=()=>c(),r.onerror=()=>{console.warn("Failed to load background video:",e),c()},setTimeout(()=>c(),1e4),r.src=e,r.load()})}async function PB(t){const{canvas:e,audioFile:n,lyrics:i,metadata:r,visualSlides:a,imageMap:c,videoMap:u,preset:h,customFontName:d,renderConfig:g,fps:v,quality:y,onProgress:S,onLog:T,abortSignal:A,isFirstSong:E=!0,isLastSong:w=!0,startTimeOffset:I=0}=t;if(!Mv())throw new Error("WebCodecs API is not supported in this browser.");const L=()=>A?.aborted===!0||A?.current===!0;S(0,"Initializing WebCodecs..."),T?.("Decoding audio...");const D=await Pg(n),W=D.duration,V=Math.ceil(W*v),H=new uw({target:new vv,video:{codec:"avc",width:e.width,height:e.height},audio:{codec:"aac",sampleRate:D.sampleRate,numberOfChannels:D.numberOfChannels},fastStart:"in-memory"}),P=(t.resolution==="1080p"?8e6:4e6)*(y==="high"?1.5:y==="low"?.5:1),J=new VideoEncoder({output:(ce,Xe)=>H.addVideoChunk(ce,Xe),error:ce=>{console.error("VideoEncoder error:",ce),T?.(`VideoEncoder error: ${ce.message}`)}});J.configure({codec:"avc1.4d002a",width:e.width,height:e.height,bitrate:P,framerate:v});const ve=new AudioEncoder({output:(ce,Xe)=>H.addAudioChunk(ce,Xe),error:ce=>{console.error("AudioEncoder error:",ce),T?.(`AudioEncoder error: ${ce.message}`)}});ve.configure({codec:"mp4a.40.2",sampleRate:D.sampleRate,numberOfChannels:D.numberOfChannels,bitrate:128e3}),S(5,"Encoding Audio...");const fe=D.numberOfChannels,Ee=D.sampleRate,je=Ee,X=D.length;for(let ce=0;ce10;)await new Promise(Se=>setTimeout(Se,10))}await ve.flush(),S(10,"Rendering Frames...");const _e=e.getContext("2d",{desynchronized:!1});if(!_e)throw new Error("No canvas context");const ne=1/v*1e6,tt=g.showVisualization?D.getChannelData(0):null,Ce=D.sampleRate;for(let ce=0;ce0,W,g,w,E,Ie,nt);const Se=Math.round(ce*ne),N=new VideoFrame(e,{timestamp:Se,duration:Math.round(ne)});J.encode(N,{keyFrame:ce%(v*2)===0}),N.close();const ye=10+ce/V*89;S(ye,`Rendering frame ${ce}/${V}`),J.encodeQueueSize>5&&await new Promise(xe=>{const Oe=()=>J.encodeQueueSize<=2?xe(null):setTimeout(Oe,10);Oe()}),ce%2===0&&await new Promise(xe=>setTimeout(xe,0))}S(99,"Finalizing frames..."),await J.flush(),H.finalize();const{buffer:$}=H.target;return S(100,"Done!"),{blob:new Blob([$],{type:"video/mp4"}),duration:W,format:"mp4"}}async function FB(t,e){const{canvas:n,visualSlides:i,imageMap:r,videoMap:a,preset:c,customFontName:u,renderConfig:h,fps:d,quality:g,onProgress:v,onLog:y,abortSignal:S}=e;if(!Mv())throw new Error("WebCodecs API is not supported in this browser.");const T=()=>S?.aborted===!0||S?.current===!0;v(0,"Decoding first track...");const A=await Pg(t[0].audioFile),E=A.sampleRate,w=A.numberOfChannels;v(2,"Initializing WebCodecs Playlist Render...");const I=new uw({target:new vv,video:{codec:"avc",width:n.width,height:n.height},audio:{codec:"aac",sampleRate:E,numberOfChannels:w},fastStart:"in-memory"}),W=(e.resolution==="1080p"?8e6:4e6)*(g==="high"?1.5:g==="low"?.5:1),V=new VideoEncoder({output:(J,ve)=>I.addVideoChunk(J,ve),error:J=>{console.error("VideoEncoder error:",J),y?.(`VideoEncoder error: ${J.message}`)}});V.configure({codec:"avc1.4d002a",width:n.width,height:n.height,bitrate:W,framerate:d});const H=new AudioEncoder({output:(J,ve)=>I.addAudioChunk(J,ve),error:J=>{console.error("AudioEncoder error:",J),y?.(`AudioEncoder error: ${J.message}`)}});H.configure({codec:"mp4a.40.2",sampleRate:E,numberOfChannels:w,bitrate:128e3});let Q=0,k=0;for(let J=0;J10&&await new Promise(ye=>setTimeout(ye,10))}const $=Math.ceil(X*d),ce=1/d*1e6,Xe=n.getContext("2d");if(!Xe)throw new Error("No canvas context");for(let oe=0;oe<$;oe++){if(T())throw new Error("Render aborted");if(V.state==="closed")throw new Error("VideoEncoder closed unexpectedly.");const Ie=oe/d,nt=k-X+Ie;await dw(a,i,Ie,nt);let Se=null,N=null;if(h.showVisualization){const Ze=je.getChannelData(0),U=Qg(Ze,tt,Ie,512);Se=U.frequencyData,N=U.waveformData}Ah(Xe,n.width,n.height,Ie,ve.lyrics,ve.metadata,i,r,a,c,u,h.fontSizeScale,h.backgroundBlurStrength>0,X,h,Ee,fe,Se,N);const ye=Q+Math.round(oe*ce),xe=new VideoFrame(n,{timestamp:ye,duration:Math.round(ce)});V.encode(xe,{keyFrame:oe%(d*2)===0}),xe.close();const Oe=oe/$,at=(J+Oe)/t.length*100;v(at,`Song ${J+1}/${t.length}: Rendering frame ${oe}/${$}`),V.encodeQueueSize>5&&await new Promise(Ze=>{const U=()=>V.encodeQueueSize<=2?Ze(null):setTimeout(U,10);U()}),oe%5===0&&await new Promise(Ze=>setTimeout(Ze,0))}Q+=Math.round(X*1e6)}v(99,"Flushing encoders..."),H.state!=="closed"&&await H.flush(),V.state!=="closed"&&await V.flush(),I.finalize();const{buffer:P}=I.target;return v(100,"Done!"),{blob:new Blob([P],{type:"video/mp4"}),duration:k,format:"mp4"}}function OB(){const{toast:t,confirm:e}=Ou(),n=Ae.useRef(null),i=Ae.useRef(null),r=Ae.useRef(null),a=Ae.useRef(null),c=Ae.useRef(null),u=Ae.useRef({aborted:!1}),h=Ae.useRef(()=>{});Ae.useEffect(()=>{UU()},[]);const[d,g]=Ae.useState(null),[v,y]=Ae.useState(0),[S,T]=Ae.useState({title:"No Audio Loaded",artist:"Select a file",coverUrl:null}),[A,E]=Ae.useState([]),[w,I]=Ae.useState([]),[L,D]=Ae.useState(0),[W,V]=Ae.useState(!1),[H,Q]=Ae.useState("off"),[k,P]=Ae.useState(0),[J,ve]=Ae.useState(0),[fe,Ee]=Ae.useState(1),[je,X]=Ae.useState(!1),[_e,ne]=Ae.useState(lo.PLAYER),[tt,Ce]=Ae.useState(!1),[$,ce]=Ae.useState(!1),[Xe,oe]=Ae.useState(!1),[Ie,nt]=Ae.useState(!1),[Se,N]=Ae.useState(!1),[ye,xe]=Ae.useState(0),[Oe,at]=Ae.useState("16:9"),[Ze,U]=Ae.useState("1080p"),[Me,Pe]=Ae.useState("default"),[rt,We]=Ae.useState(null),[gt,qe]=Ae.useState(null),[q,C]=Ae.useState(null),[te,ae]=Ae.useState("auto"),[Re,De]=Ae.useState(30),[st,it]=Ae.useState("med"),[F,le]=Ae.useState("mediarecorder"),[z,j]=Ae.useState("h264"),[B,re]=Ae.useState(""),[Y,me]=Ae.useState(!1),[ee,$e]=Ae.useState(!1),[M,K]=Ae.useState({backgroundSource:"custom",backgroundColor:"#581c87",backgroundGradient:"linear-gradient(to bottom right, #312e81, #581c87, #000000)",renderMode:"current",textAlign:"center",contentPosition:"center",fontFamily:"ui-sans-serif, system-ui, sans-serif",fontSizeScale:1,fontColor:"#ffffff",textEffect:"preset",textAnimation:"none",transitionEffect:"none",lyricDisplayMode:"all",fontWeight:"bold",fontStyle:"normal",lyricStyleTarget:"active-only",textDecoration:"none",showTitle:!0,showArtist:!0,showCover:!0,showIntro:!0,showLyrics:!0,infoPosition:"top-left",infoStyle:"classic",infoMarginScale:1,backgroundBlurStrength:0,introMode:"auto",introText:"",textCase:"none",highlightEffect:"karaoke",lyricLineHeight:1.3,useRealColorMedia:!1,channelInfoFontWeight:"bold",channelInfoFontStyle:"normal",infoFontWeight:"bold",infoFontStyle:"normal"}),de=Ae.useRef(M);Ae.useEffect(()=>{de.current=M},[M]);const ue=Ae.useRef(null),Ue=Ae.useRef(null),Je=M.backgroundBlurStrength>0,ht=Ae.useMemo(()=>[{label:"VP9 (WebM)",value:"video/webm; codecs=vp9,opus"},{label:"H.264 (MP4)",value:'video/mp4; codecs="avc1.4D401E, mp4a.40.2"'},{label:"AV1 (MP4)",value:'video/mp4; codecs="av01.0.05M.08"'},{label:"AV1 (WebM)",value:"video/webm; codecs=av1"},{label:"H.264 High (MP4)",value:'video/mp4; codecs="avc1.64001E, mp4a.40.2"'}].filter(Ne=>MediaRecorder.isTypeSupported(Ne.value)),[]),[et,Te]=Ae.useState([]),[Ke,Be]=Ae.useState(-1),[_t,Jt]=Ae.useState(!1),Dt=()=>{const Z=Ze==="1080p";switch(Oe){case"9:16":return Z?{w:1080,h:1920}:{w:720,h:1280};case"3:4":return Z?{w:1080,h:1440}:{w:720,h:960};case"4:3":return Z?{w:1440,h:1080}:{w:960,h:720};case"1:1":return Z?{w:1080,h:1080}:{w:720,h:720};case"1:2":return Z?{w:1080,h:2160}:{w:720,h:1440};case"2:1":return Z?{w:2160,h:1080}:{w:1440,h:720};case"2:3":return Z?{w:1080,h:1620}:{w:720,h:1080};case"3:2":return Z?{w:1620,h:1080}:{w:1080,h:720};case"4:5":return Z?{w:1080,h:1350}:{w:720,h:900};case"20:9":return Z?{w:2400,h:1080}:{w:1600,h:720};case"21:9":return Z?{w:2560,h:1080}:{w:1720,h:720};default:return Z?{w:1920,h:1080}:{w:1280,h:720}}},{w:Yt,h:Zt}=Dt(),[ti,Gi]=Ae.useState(!0),[Si,ji]=Ae.useState(!0),[fn,fi]=Ae.useState(!1),Rt=Ae.useMemo(()=>{const Z=M.visualTransitionType||"none",Ne=M.visualTransitionDuration||1;return w.filter(Fe=>Fe.type==="audio"?!1:k>=Fe.startTime&&k=Fe.endTime&&k{const mt=(Fe.layer||0)-(lt.layer||0);return mt!==0?mt:Fe.startTime-lt.startTime})},[w,k,M.visualTransitionType,M.visualTransitionDuration]),tn=w.filter(Z=>Z.type==="audio"&&k>=Z.startTime&&kL===0?A:A.map(Z=>({...Z,time:Z.time+L,endTime:Z.endTime!==void 0?Z.endTime+L:void 0})),[A,L]),Mi=En.findIndex((Z,Ne)=>{if(Z.endTime!==void 0)return k>=Z.time&&k=Z.time&&(!dt||k{const Ne=Z.target.files?.[0];if(Ne){const dt=URL.createObjectURL(Ne);g(dt);const Fe={title:Ne.name.replace(/\.[^/.]+$/,""),artist:"Unknown Artist",coverUrl:null};T(Fe),Ne.type.startsWith("audio/")?v0(()=>import("./jsmediatags.min-C5sB4g8Y.js").then(lt=>lt.j),[]).then(lt=>{lt.read(Ne,{onSuccess:mt=>{const{title:wt,artist:Ht,picture:Pt}=mt.tags;let oi=null;if(Pt){const{data:Nn,format:ft}=Pt;let $t="";for(let In=0;In{console.log("Error reading tags:",mt)}})}):Ne.type.startsWith("video/")&&(nt(!1),T({...Fe,coverUrl:dt,backgroundType:"video"})),D(0),V(!1),P(0),Be(-1),r.current&&(r.current.scrollTop=0),n.current&&n.current.load()}Z.target.value=""},ii=Z=>{const Ne=Z.target.files?.[0];if(Ne){const dt=URL.createObjectURL(Ne),Fe=Ne.type.startsWith("video/");Fe&&nt(!1),T(lt=>({...lt,coverUrl:dt,backgroundType:Fe?"video":"image"}))}Z.target.value=""},Rs=async Z=>{const Ne=Z.target.files?.[0];if(Ne)try{const dt=await Ne.text(),Fe=Ne.name.split(".").pop()?.toLowerCase();let lt=[];Fe==="lrc"?lt=ea(dt):Fe==="srt"?lt=ta(dt):Fe==="ttml"||Fe==="xml"?lt=Pa(dt):Fe==="vtt"&&(lt=Fa(dt)),lt.some(mt=>mt.words&&mt.words.length>0)&&(K(mt=>({...mt,highlightEffect:"karaoke"})),t.success(`${Fe?.toUpperCase()} loaded with word-level timing! Karaoke mode enabled.`)),E(lt)}catch(dt){console.error("Failed to parse lyrics:",dt),t.error("Failed to parse lyric file.")}Z.target.value=""};Ae.useEffect(()=>{if(Ke!==-1&&et[Ke]){const Z=et[Ke];E(Z.parsedLyrics||[])}},[et,Ke]);const G=async Z=>{const Ne=Z.target.files?.[0];if(Ne){if(!window.FontFace||!document.fonts){t.error("Custom fonts are not supported in this browser.");return}try{const dt=URL.createObjectURL(Ne),Fe=Ne.name.replace(/\.[^/.]+$/,""),lt="CustomFont",mt=new FontFace(lt,`url(${dt})`);await mt.load(),document.fonts.add(mt),We(Fe),K(wt=>({...wt,fontFamily:lt})),t.success(`Loaded font: ${Fe}`)}catch(dt){console.error("Failed to load font:",dt),t.error("Failed to load font file.")}}Z.target.value=""},be=async Z=>{const Ne=Z.target.files?.[0];if(Ne){if(!window.FontFace||!document.fonts){t.error("Custom fonts are not supported in this browser.");return}try{const dt=URL.createObjectURL(Ne),Fe=Ne.name.replace(/\.[^/.]+$/,""),lt="ChannelFont",mt=new FontFace(lt,`url(${dt})`);await mt.load(),document.fonts.add(mt),qe(Fe),K(wt=>({...wt,channelInfoFontFamily:lt})),t.success(`Loaded Channel font: ${Fe}`)}catch(dt){console.error("Failed to load font:",dt),t.error("Failed to load channel font file.")}}Z.target.value=""},He=async Z=>{const Ne=Z.target.files?.[0];if(Ne){if(!window.FontFace||!document.fonts){t.error("Custom fonts are not supported in this browser.");return}try{const dt=URL.createObjectURL(Ne),Fe=Ne.name.replace(/\.[^/.]+$/,""),lt="InfoFont",mt=new FontFace(lt,`url(${dt})`);await mt.load(),document.fonts.add(mt),C(Fe),K(wt=>({...wt,infoFontFamily:lt})),t.success(`Loaded Info font: ${Fe}`)}catch(dt){console.error("Failed to load font:",dt),t.error("Failed to load info font file.")}}Z.target.value=""},Ve=Ae.useCallback(async(Z,Ne=!0,dt)=>{const Fe=dt||et;if(Z<0||Z>=Fe.length)return;const lt=Fe[Z],mt=URL.createObjectURL(lt.audioFile);if(g(mt),T({title:lt.metadata.title,artist:lt.metadata.artist,coverUrl:lt.metadata.coverUrl||null,backgroundType:lt.metadata.backgroundType||"image"}),E([]),lt.parsedLyrics&<.parsedLyrics.length>0)E(lt.parsedLyrics);else if(lt.lyricFile)try{const wt=await lt.lyricFile.text(),Ht=lt.lyricFile.name.split(".").pop()?.toLowerCase();let Pt=[];Ht==="lrc"?Pt=ea(wt):Ht==="srt"?Pt=ta(wt):Ht==="ttml"||Ht==="xml"?Pt=Pa(wt):Ht==="vtt"&&(Pt=Fa(wt)),E(Pt)}catch(wt){console.error("Failed to load lyrics",wt)}D(0),Be(Z),r.current&&(r.current.scrollTop=0),Ne?setTimeout(()=>{n.current&&(n.current.play().catch(wt=>console.log("Autoplay failed",wt)),V(!0))},100):(V(!1),n.current&&(n.current.pause(),n.current.currentTime=0))},[et]),ge=Ae.useCallback(()=>{if(et.length===0)return;const Z=(Ke+1)%et.length;Ve(Z)},[et,Ke,Ve]),pt=Ae.useCallback(()=>{if(et.length===0)return;const Z=(Ke-1+et.length)%et.length;Ve(Z)},[et,Ke,Ve]),yt=()=>{n.current&&(W?(n.current.pause(),V(!1)):!d&&et.length>0?Ve(0):(n.current.play().catch(console.error),V(!0)))},xt=Ae.useCallback(()=>{n.current&&(n.current.pause(),n.current.currentTime=0,V(!1),P(0))},[]),Tt=()=>{Q(Z=>Z==="off"?"one":Z==="one"?"all":Z==="all"?"all_repeat":"off")},jt=()=>{document.fullscreenElement?(document.exitFullscreen(),Ce(!1)):(i.current?.requestFullscreen(),Ce(!0))},qt=Z=>{if(Se||Z&&Z.target.closest(".no-minimal-mode-toggle"))return;const Ne=!fn;fi(Ne),Ne&&oe(!0),t.success(`Minimal Mode: ${Ne?"On":"Off"}`,{id:"minimal-mode"})},kt=()=>{n.current&&(P(n.current.currentTime),Se&&xe(n.current.currentTime/J*100))},hn=()=>{n.current&&ve(n.current.duration)},pn=Z=>{const Ne=parseFloat(Z.target.value);n.current&&(n.current.currentTime=Ne,P(Ne))},Xn=Z=>{if(!ue.current||Se||!J)return;const Ne=ue.current.getBoundingClientRect(),lt=Math.max(0,Math.min(Z-Ne.left,Ne.width))/Ne.width*J;n.current&&(n.current.currentTime=lt,P(lt))},wn=Z=>{const Ne=parseFloat(Z.target.value);Ee(Ne),n.current&&(n.current.volume=Ne),X(Ne===0)},Wt=Z=>{if(!Ue.current)return;const Ne=Ue.current.getBoundingClientRect(),Fe=Math.max(0,Math.min(Z-Ne.left,Ne.width))/Ne.width;Ee(Fe),n.current&&(n.current.volume=Fe),X(Fe===0)},zt=async()=>{if(!n.current||!a.current)return;const Z=M.renderMode==="playlist"&&et.length>0;console.log(`[Render] Starting Export. Mode: ${M.renderMode}, Playlist Items: ${et.length}, IsPlaylistRender: ${Z}`),Z?t.success(`Starting Playlist Render (${et.length} songs)...`):t.success("Starting Single Track Render...");const Ne=[];if(Z)for(const At of et){let Vt=[];if(At.parsedLyrics&&At.parsedLyrics.length>0)Vt=At.parsedLyrics;else if(At.lyricFile)try{const bt=await At.lyricFile.text(),Yn=At.lyricFile.name.split(".").pop()?.toLowerCase();Yn==="lrc"?Vt=ea(bt):Yn==="srt"?Vt=ta(bt):Yn==="ttml"||Yn==="xml"?Vt=Pa(bt):Yn==="vtt"&&(Vt=Fa(bt))}catch(bt){console.error("Failed to parse lyrics for playlist item",bt)}const Mn=URL.createObjectURL(At.audioFile);Ne.push({audioSrc:Mn,lyrics:Vt,metadata:At.metadata,isFileSource:!0})}else{if(!d)return;Ne.push({audioSrc:d,lyrics:En,metadata:S,isFileSource:!1})}if(Ne.length===0)return;const dt=Z?`Start rendering ALL ${Ne.length} songs from the playlist? This will result in one continuous video.`:`Start rendering ${Oe} (${Ze}) video? This will play the song from start to finish.`;if(!await e(`${dt} Please do not switch tabs during rendering.`,"Start Rendering?")){Z&&Ne.forEach(At=>At.isFileSource&&URL.revokeObjectURL(At.audioSrc));return}me(!1),N(!0),xe(0);const lt={aborted:!1};u.current=lt,xt(),Q("off"),hi.current&&clearTimeout(hi.current),ce(!1),oe(!0),Li.current&&Li.current.pause();const mt=n.current,wt=Me,Ht=new Map,Pt=new Map,oi=new Map,Nn=[],ft=(At,Vt)=>new Promise(Mn=>{const bt=new Image;bt.crossOrigin="anonymous",bt.onload=()=>{Ht.set(At,bt),Mn()},bt.onerror=()=>Mn(),bt.src=Vt}),$t=(At,Vt)=>new Promise(Mn=>{const bt=document.createElement("video");bt.crossOrigin="anonymous",bt.muted=!0,bt.playsInline=!0,bt.preload="auto";let Yn=!1;const Pn=()=>{Yn||(Yn=!0,Pt.set(At,bt),Mn())};bt.oncanplay=()=>{Yn||(bt.currentTime=.001)},bt.onseeked=()=>Pn(),bt.onerror=()=>{console.warn("Failed to load video:",Vt),Pn()},setTimeout(()=>Pn(),5e3),bt.src=Vt,bt.load()}),In=(At,Vt)=>new Promise(Mn=>{const bt=document.createElement("audio");bt.crossOrigin="anonymous",bt.onloadedmetadata=()=>{oi.set(At,bt),Mn()},bt.onerror=()=>Mn(),bt.src=Vt});if(w.forEach(At=>{At.type==="video"?Nn.push($t(At.id,At.url)):At.type==="audio"?Nn.push(In(At.id,At.url)):Nn.push(ft(At.id,At.url))}),M.showChannelInfo&&(M.channelInfoImage&&Nn.push(ft("__channel_info__",M.channelInfoImage)),M.channelInfoText)){const At=M.channelInfoText.trim();if(//i.test(At))try{const Vt=document.createElement("div");Vt.style.position="absolute",Vt.style.visibility="hidden",Vt.style.whiteSpace="nowrap",Vt.style.fontFamily="sans-serif",Vt.style.fontWeight="bold",Vt.style.fontSize="100px",Vt.style.display="inline-flex",Vt.style.alignItems="center",Vt.style.gap="0.25em",Vt.innerHTML=At;const Mn=Vt.getElementsByTagName("svg");for(let ho=0;ho + +
+ + ${At} +
+
+ + `,Zo=`data:image/svg+xml;base64,${window.btoa(encodeURIComponent(Pn).replace(/%([0-9A-F]{2})/g,function(Is,Za){return String.fromCharCode(parseInt(Za,16))}))}`;Nn.push(ft("__channel_info_text_svg__",Zo))}catch(Vt){console.warn("Failed to process SVG channel info",Vt)}}if(M.backgroundSource==="image"&&M.backgroundImage&&Nn.push(ft("__custom_bg__",M.backgroundImage)),M.backgroundSource==="video"&&M.backgroundVideo&&Nn.push($t("__custom_bg_video__",M.backgroundVideo)),await Promise.all(Nn),lt.aborted){N(!1),Z&&Ne.forEach(At=>At.isFileSource&&URL.revokeObjectURL(At.audioSrc));return}const ni=a.current,se=ni.getContext("2d"),Mt=ni.captureStream(Re);let Ft=null;try{if(mt.captureStream)Ft=mt.captureStream();else if(mt.mozCaptureStream)Ft=mt.mozCaptureStream();else throw new Error("Audio capture not supported")}catch{t.error("Your browser does not support audio capture for recording."),N(!1);return}JU();const vt=sh();vt.state==="suspended"&&await vt.resume();const on=vt.createMediaStreamDestination(),Lt=kf(mt,vt);Lt.disconnect(),Lt.connect(on);let un=null,Vn=null,jn=null;M.showVisualization&&(un=vt.createAnalyser(),un.fftSize=512,un.smoothingTimeConstant=.8,Lt.connect(un),Vn=new Uint8Array(un.frequencyBinCount),jn=new Uint8Array(un.frequencyBinCount)),Pt.forEach(At=>{At.muted=!0;const Vt=kf(At,vt);Vt.disconnect(),Vt.connect(on)}),oi.forEach(At=>{At.muted=!0;const Vt=kf(At,vt);Vt.disconnect(),Vt.connect(on)}),on.stream.getAudioTracks().length>0?Mt.addTrack(on.stream.getAudioTracks()[0]):Ft&&Mt.addTrack(Ft.getAudioTracks()[0]);const _i=(()=>{if(te!=="auto"&&MediaRecorder.isTypeSupported(te))return te;const At=["video/webm; codecs=vp9,opus","video/webm; codecs=vp9","video/webm; codecs=av1",'video/mp4; codecs="av01.0.05M.08"','video/mp4; codecs="avc1.4D401E, mp4a.40.2"','video/mp4; codecs="avc1.64001E, mp4a.40.2"',"video/mp4","video/webm"];for(const Vt of At)if(MediaRecorder.isTypeSupported(Vt))return Vt;return"video/webm"})(),yo=Ze==="1080p"?8e6:4e6,fo=Re>30?1.5:1,Uo=st==="high"?2:st==="low"?.5:1,Ye=yo*fo*Uo,si=new MediaRecorder(Mt,{mimeType:_i,videoBitsPerSecond:Ye});c.current=si;const Qt=[];si.ondataavailable=At=>{At.data.size>0&&Qt.push(At.data)},si.onstop=()=>{if(lt.aborted)console.log("Render aborted");else{const At=new Blob(Qt,{type:_i}),Vt=Mn=>{const bt=URL.createObjectURL(Mn),Yn=document.createElement("a");Yn.href=bt;const Pn=_i.includes("mp4")?"mp4":"webm",ki=Z?`Playlist_${Ne.length}_Songs_${Oe.replace(":","-")}.${Pn}`:`${Ne[0].metadata.title||"video"}_${Oe.replace(":","-")}.${Pn}`;Yn.download=ki,document.body.appendChild(Yn),Yn.click(),document.body.removeChild(Yn),URL.revokeObjectURL(bt)};_i.includes("webm"),Vt(At)}vt.close(),N(!1),y(At=>At+1),Z&&Ne.forEach(At=>At.isFileSource&&URL.revokeObjectURL(At.audioSrc))};let bi=0,ms=[],Ns=S,Ko=0,qs=0;const sn=1e3/Re,Ui=At=>{if(lt.aborted)return;(si.state==="recording"||si.state==="paused")&&requestAnimationFrame(Ui);const Vt=At-qs;if(Vt0){const bt=Mn/Ko;if(Z){const Yn=(bi+bt)/Ne.length*100;xe(Yn)}else xe(bt*100)}Pt.forEach((bt,Yn)=>{if(Yn==="background"||Yn==="__custom_bg_video__"){const Pn=bt.duration||1,ki=Mn%Pn;let Zo=Math.abs(bt.currentTime-ki);(kiPn/2||Zo>.5)&&(bt.currentTime=ki),bt.paused&&bt.play().catch(()=>{})}else{const Pn=w.find(ki=>ki.id===Yn);if(Pn)if(Mn>=Pn.startTime&&Mn0&&Zo>=ho&&(Zo=Zo%ho),Math.abs(bt.playbackRate-ki)>.01&&(bt.playbackRate=ki),Math.abs(bt.currentTime-Zo)>.5&&(bt.currentTime=Zo);const Is=Pn.isMuted!==!1;bt.muted!==Is&&(bt.muted=Is),bt.paused&&bt.play().catch(()=>{})}else bt.paused||bt.pause(),bt.muted||(bt.muted=!0)}}),oi.forEach((bt,Yn)=>{const Pn=w.find(ki=>ki.id===Yn);if(Pn){const ki=Pn.layer||0;if(M.layerVisibility?.audio?.[ki]!==!1&&Mn>=Pn.startTime&&Mn.01&&(bt.playbackRate=ho),Math.abs(bt.currentTime-Is)>.5&&(bt.currentTime=Is);const Za=Pn.isMuted===!0;bt.muted!==Za&&(bt.muted=Za),bt.paused&&bt.play().catch(()=>{})}else bt.paused||bt.pause(),bt.muted||(bt.muted=!0)}}),se&&(un&&Vn&&jn&&(un.getByteFrequencyData(Vn),un.getByteTimeDomainData(jn)),Ah(se,ni.width,ni.height,Mn,ms,Ns,w,Ht,Pt,wt,rt,M.fontSizeScale,M.backgroundBlurStrength>0,Ko,M,M.renderMode==="current"||bi===Ne.length-1,M.renderMode==="current"||bi===0,Vn,jn))},Ka=async()=>{if(lt.aborted){si.stop();return}if(bi>=Ne.length){await new Promise(Vt=>setTimeout(Vt,500)),si.stop();return}const At=Ne[bi];si.state==="recording"&&si.pause(),ms=At.lyrics,Ns=At.metadata,Ko=0,Z&&Be(bi),At.metadata.coverUrl&&(At.metadata.backgroundType==="video"?await $t("background",At.metadata.coverUrl):await ft("cover",At.metadata.coverUrl)),mt.pause(),mt.src=At.audioSrc,mt.load(),await new Promise(Vt=>{const Mn=()=>{mt.removeEventListener("canplay",Mn),Vt()};mt.addEventListener("canplay",Mn),mt.readyState>=3&&Mn()}),Ko=mt.duration,si.state==="inactive"?(vt.state==="suspended"&&await vt.resume(),si.start(),requestAnimationFrame(Ui)):si.state==="paused"&&si.resume(),await mt.play(),await new Promise(Vt=>{const Mn=()=>{mt.removeEventListener("ended",Mn),Vt()};mt.addEventListener("ended",Mn)}),bi++,await Ka()};if(console.log(`[Render] Queue prepared with ${Ne.length} items.`),Ne.length===0){t.error("Render queue is empty!"),N(!1);return}bi=0,await Ka()},Ci=async()=>{if(!a.current)return;const Z=M.renderMode==="playlist"&&et.length>0;console.log(`[FFmpeg Render] Mode: ${M.renderMode}, Playlist: ${et.length}, IsPlaylist: ${Z}`);let Ne=null,dt=En,Fe=S;if(Z&&et.length>0)Ne=et[0].audioFile,dt=et[0].parsedLyrics||[],Fe=et[0].metadata;else if(et.length>0&&Ke>=0)Ne=et[Ke].audioFile;else if(d)try{Ne=await(await fetch(d)).blob()}catch(se){console.error("FFmpeg: Failed to fetch audio blob",se),t.error("Failed to load audio source for rendering.");return}else{t.error("Please load an audio file first.");return}if(!Ne){t.error("No audio file available for FFmpeg export.");return}const lt=`Start FFmpeg rendering at ${Ze} (${Oe})? This uses frame-by-frame capture for higher quality. Rendering may take several minutes.`;if(!await e(lt,"Start FFmpeg Rendering?"))return;me(!1),N(!0),xe(0),re("Initializing...");const wt={aborted:!1};u.current=wt,xt();const Ht=a.current,{w:Pt,h:oi}=Dt();Ht.width=Pt,Ht.height=oi;const Nn=new Map,ft=new Map,$t=[],In=(se,Mt)=>new Promise(Ft=>{const vt=new Image;vt.crossOrigin="anonymous",vt.onload=()=>{Nn.set(se,vt),Ft()},vt.onerror=()=>Ft(),vt.src=Mt}),ni=(se,Mt)=>new Promise(Ft=>{const vt=document.createElement("video");vt.crossOrigin="anonymous",vt.muted=!0,vt.playsInline=!0,vt.preload="auto";let on=!1;const Lt=()=>{on||(on=!0,ft.set(se,vt),Ft())};vt.oncanplay=()=>{on||(vt.currentTime=.001)},vt.onseeked=()=>Lt(),vt.onerror=()=>{console.warn("Failed to load video:",Mt),Lt()},setTimeout(()=>Lt(),5e3),vt.src=Mt,vt.load()});if(w.forEach(se=>{se.type==="video"?$t.push(ni(se.id,se.url)):se.type!=="audio"&&$t.push(In(se.id,se.url))}),Fe.coverUrl&&(Fe.backgroundType==="video"?$t.push(ni("background",Fe.coverUrl)):$t.push(In("cover",Fe.coverUrl))),M.backgroundSource==="image"&&M.backgroundImage&&$t.push(In("__custom_bg__",M.backgroundImage)),M.backgroundSource==="video"&&M.backgroundVideo&&(Li.current&&Li.current.currentSrc&&!Li.current.error?(ft.set("__custom_bg_video__",Li.current),console.log("WebCodecs: Re-using existing background video element")):$t.push(ni("__custom_bg_video__",M.backgroundVideo))),M.backgroundSource==="video"&&M.backgroundVideo&&(Li.current&&Li.current.currentSrc&&!Li.current.error?(ft.set("__custom_bg_video__",Li.current),console.log("FFmpeg: Re-using existing background video element")):$t.push(ni("__custom_bg_video__",M.backgroundVideo))),M.showChannelInfo&&M.channelInfoImage&&$t.push(In("__channel_info__",M.channelInfoImage)),await Promise.all($t),wt.aborted){N(!1);return}try{if(Z){const se=[];for(const Lt of et){let un=[];if(Lt.parsedLyrics&&Lt.parsedLyrics.length>0)un=Lt.parsedLyrics;else if(Lt.lyricFile)try{const Vn=await Lt.lyricFile.text(),jn=Lt.lyricFile.name.split(".").pop()?.toLowerCase();jn==="lrc"?un=ea(Vn):jn==="srt"?un=ta(Vn):jn==="ttml"||jn==="xml"?un=Pa(Vn):jn==="vtt"&&(un=Fa(Vn))}catch(Vn){console.error("FFmpeg: Failed to parse lyrics for playlist item",Vn)}se.push({audioFile:Lt.audioFile,lyrics:un,metadata:Lt.metadata})}const Mt=await EO(se,{canvas:Ht,visualSlides:w,imageMap:Nn,videoMap:ft,preset:Me,customFontName:rt,renderConfig:M,resolution:Ze,aspectRatio:Oe,fps:Re,quality:st,codec:z,onProgress:(Lt,un)=>{},onLog:Lt=>console.log(Lt),abortSignal:wt},(Lt,un,Vn,jn)=>{const js=(Lt+Vn/100)/un*100;xe(js),re(`Song ${Lt+1}/${un}: ${jn}`)}),Ft=`Playlist_${se.length}_Songs_${Oe.replace(":","-")}_ffmpeg.${Mt.format}`,vt=URL.createObjectURL(Mt.blob),on=document.createElement("a");on.href=vt,on.download=Ft,document.body.appendChild(on),on.click(),document.body.removeChild(on),URL.revokeObjectURL(vt),t.success(`Playlist exported successfully! (${Mt.format.toUpperCase()}, ${Math.round(Mt.duration)}s)`)}else{const se=await XE({canvas:Ht,audioFile:Ne,lyrics:dt,metadata:Fe,visualSlides:w,imageMap:Nn,videoMap:ft,preset:Me,customFontName:rt,renderConfig:M,resolution:Ze,aspectRatio:Oe,fps:Re,quality:st,codec:z,onProgress:(on,Lt)=>{xe(on),re(Lt)},onLog:on=>console.log(on),abortSignal:wt,isFirstSong:!0,isLastSong:!0}),Mt=`${Fe.title||"video"}_${Oe.replace(":","-")}_ffmpeg.${se.format}`,Ft=URL.createObjectURL(se.blob),vt=document.createElement("a");vt.href=Ft,vt.download=Mt,document.body.appendChild(vt),vt.click(),document.body.removeChild(vt),URL.revokeObjectURL(Ft),t.success(`Video exported successfully! (${se.format.toUpperCase()}, ${Math.round(se.duration)}s)`)}}catch(se){se.message!=="Render aborted"&&(console.error("FFmpeg render failed:",se),t.error(`FFmpeg render failed: ${se.message}`))}finally{N(!1),re("")}},vn=async()=>{if(!a.current)return;const Z=M.renderMode==="playlist"&&et.length>0;let Ne=null,dt=En,Fe=S;if(Z&&et.length>0)Ne=et[0].audioFile,dt=et[0].parsedLyrics||[],Fe=et[0].metadata;else if(et.length>0&&Ke>=0)Ne=et[Ke].audioFile;else if(d)try{Ne=await(await fetch(d)).blob()}catch(se){console.error("WebCodecs: Failed to fetch audio blob",se),t.error("Failed to load audio source for rendering.");return}else{t.error("Please load an audio file first.");return}if(!Ne){t.error("No audio file available for export.");return}if(!Mv()){t.error("WebCodecs is not supported in this browser.");return}const{w:lt,h:mt}=Dt(),wt=`Start WebCodecs rendering at ${Ze} @ ${Re}fps? +Resolution: ${lt}x${mt} + +This uses hardware acceleration and is very fast.`;if(!await e(wt,"Start WebCodecs Rendering?"))return;me(!1),N(!0),xe(0),re("Initializing WebCodecs...");const Pt={aborted:!1};u.current=Pt,xt();const oi=a.current;oi.width=lt,oi.height=mt;const Nn=new Map,ft=new Map,$t=[],In=(se,Mt)=>new Promise(Ft=>{const vt=new Image;vt.crossOrigin="anonymous",vt.onload=()=>{Nn.set(se,vt),Ft()},vt.onerror=()=>Ft(),vt.src=Mt}),ni=(se,Mt)=>new Promise(Ft=>{const vt=document.createElement("video");vt.crossOrigin="anonymous",vt.muted=!0,vt.playsInline=!0,vt.preload="auto";let on=!1;const Lt=()=>{on||(on=!0,ft.set(se,vt),Ft())};vt.oncanplay=()=>{on||(vt.currentTime=.001)},vt.onseeked=()=>Lt(),vt.onerror=()=>{console.warn("Failed to load video:",Mt),Lt()},setTimeout(()=>Lt(),5e3),vt.src=Mt,vt.load()});if(w.forEach(se=>{se.type==="video"?$t.push(ni(se.id,se.url)):se.type!=="audio"&&$t.push(In(se.id,se.url))}),Fe.coverUrl&&(Fe.backgroundType==="video"?$t.push(ni("background",Fe.coverUrl)):$t.push(In("cover",Fe.coverUrl))),M.backgroundSource==="image"&&M.backgroundImage&&$t.push(In("__custom_bg__",M.backgroundImage)),M.backgroundSource==="video"&&M.backgroundVideo&&(Li.current&&Li.current.currentSrc&&!Li.current.error?(ft.set("__custom_bg_video__",Li.current),console.log("WebCodecs: Re-using existing background video element")):$t.push(ni("__custom_bg_video__",M.backgroundVideo))),M.showChannelInfo&&M.channelInfoImage&&$t.push(In("__channel_info__",M.channelInfoImage)),await Promise.all($t),Pt.aborted){N(!1);return}try{if(Z){const se=[];for(const Lt of et){let un=[];if(Lt.parsedLyrics&&Lt.parsedLyrics.length>0)un=Lt.parsedLyrics;else if(Lt.lyricFile)try{const Vn=await Lt.lyricFile.text(),jn=Lt.lyricFile.name.split(".").pop()?.toLowerCase();jn==="lrc"?un=ea(Vn):jn==="srt"?un=ta(Vn):jn==="ttml"||jn==="xml"?un=Pa(Vn):jn==="vtt"&&(un=Fa(Vn))}catch(Vn){console.error("WebCodecs: Failed to parse lyrics for playlist item",Vn)}se.push({audioFile:Lt.audioFile,lyrics:un,metadata:Lt.metadata})}const Mt=await FB(se,{canvas:oi,visualSlides:w,imageMap:Nn,videoMap:ft,preset:Me,customFontName:rt,renderConfig:M,resolution:Ze,aspectRatio:Oe,fps:Re,quality:st,onProgress:(Lt,un)=>{xe(Lt),re(un)},onLog:Lt=>console.log(Lt),abortSignal:Pt}),Ft=`Playlist_${se.length}_Songs_${Oe.replace(":","-")}_webcodecs.${Mt.format}`,vt=URL.createObjectURL(Mt.blob),on=document.createElement("a");on.href=vt,on.download=Ft,document.body.appendChild(on),on.click(),document.body.removeChild(on),URL.revokeObjectURL(vt),t.success(`Playlist exported successfully! (${Mt.format.toUpperCase()}, ${Math.round(Mt.duration)}s)`)}else{const se=await PB({canvas:oi,audioFile:Ne,lyrics:dt,metadata:Fe,visualSlides:w,imageMap:Nn,videoMap:ft,preset:Me,customFontName:rt,renderConfig:M,resolution:Ze,aspectRatio:Oe,fps:Re,quality:st,onProgress:(on,Lt)=>{xe(on),re(Lt)},abortSignal:Pt,isFirstSong:!0,isLastSong:!0}),Mt=`${Fe.title||"video"}_${Oe.replace(":","-")}_webcodecs.${se.format}`,Ft=URL.createObjectURL(se.blob),vt=document.createElement("a");vt.href=Ft,vt.download=Mt,document.body.appendChild(vt),vt.click(),document.body.removeChild(vt),URL.revokeObjectURL(Ft),t.success(`Video exported successfully! (${Math.round(se.duration)}s)`)}}catch(se){se.message!=="Render aborted"&&(console.error("WebCodecs render failed:",se),t.error(`Render failed: ${se.message}`))}finally{N(!1),re("")}},Ji=async()=>{F==="ffmpeg"?await Ci():F==="webcodecs"?await vn():await zt()};Ae.useEffect(()=>{h.current=Ji});const xo=Ae.useCallback(()=>{u.current&&(u.current.aborted=!0),c.current&&c.current.state==="recording"?c.current.stop():N(!1),xt()},[xt]),Di=Ae.useCallback(()=>{if(r.current){const Z=n.current?.currentTime||0;if(Mi===-1&&Z<2){r.current.scrollTo({top:0,behavior:"smooth"});return}if(Mi!==-1){const Ne=r.current.querySelector('[data-lyric-active="true"]');if(Ne){const dt=r.current;if(Ne.offsetHeight===0)return;const Fe=Ne.offsetTop,lt=Ne.offsetHeight,mt=dt.clientHeight;let wt=.5;M.contentPosition==="top"&&(wt=.25),M.contentPosition==="bottom"&&(wt=.75);const Ht=Fe-mt*wt+lt/2;dt.scrollTo({top:Ht,behavior:"smooth"})}}}},[Mi,Me,M.contentPosition,M.marginTopScale,M.marginBottomScale]);Ae.useEffect(()=>{Di()},[Di]),Ae.useEffect(()=>{const Z=setTimeout(()=>{Di()},550);return()=>clearTimeout(Z)},[$,Xe,ti,Si,_e,_t,Di]);const hi=Ae.useRef(null),Rn=Ae.useCallback(()=>{if(ce(!1),hi.current&&clearTimeout(hi.current),!Se){const Z=window.setTimeout(()=>{ce(!0)},3e3);hi.current=Z}},[Se]),io=()=>{Rn()},qi=Ae.useRef(0),pi=Z=>{Rn();const Ne=Date.now();if(Ne-qi.current<300){if(Z.target.closest(".no-minimal-mode-toggle"))return;qt(Z)}qi.current=Ne};Ae.useEffect(()=>{const Z=Ne=>{const dt=Ne.key.toLowerCase();if([" ","k","s","t","l","r","f","h","g","m","j","d","e","c","x","z","arrowleft","arrowright","arrowup","arrowdown","meta","control","shift","alt","printscreen","fn","+","-","="].includes(dt)||Rn(),!(Ne.target instanceof HTMLInputElement||Ne.target instanceof HTMLTextAreaElement)){if(Se){dt==="escape"&&xo();return}switch(Ne.key.toLowerCase()){case" ":case"k":Ne.preventDefault(),yt(),t.success(W?"Paused":"Playing",{id:"play-pause"});break;case"s":Ne.preventDefault(),xt(),t.success("Stopped",{id:"stop"});break;case"n":Ne.preventDefault(),ge(),t.success("Next Song",{id:"next-song"});break;case"o":Ne.preventDefault();const lt=!fn;fi(lt),lt&&oe(!0),t.success(`Minimal Mode: ${lt?"On":"Off"}`,{id:"minimal-mode"});break;case"b":Ne.preventDefault(),pt(),t.success("Previous Song",{id:"prev-song"});break;case"r":Ne.preventDefault(),Tt();const mt=H==="off"?"one":H==="one"?"all":H==="all"?"all_repeat":"off",wt={off:"Repeat Off",one:"Loop One",all:"Play All (Stop)",all_repeat:"Loop Playlist"};t.success(`Repeat: ${wt[mt]}`,{id:"repeat"});break;case"l":Ne.preventDefault();const Ht=!_t;Jt(Ht),Ht&&ne(lo.PLAYER);break;case"h":Ne.preventDefault();const Pt=!Xe;oe(Pt),t.success(Pt?"HUD: Always Visible":"HUD: Auto-Hide",{id:"hud-mode"});break;case"y":Ne.preventDefault(),$e(sn=>!sn);break;case"g":Ne.preventDefault();const oi=P0.flatMap(sn=>sn.options.map(Ui=>Ui.value)),Nn=de.current.lyricDisplayMode,$t=(oi.indexOf(Nn)+1)%oi.length,In=oi[$t];K(sn=>({...sn,lyricDisplayMode:In})),t.success(`Lyric Mode: ${In.replace("-"," ")}`,{id:"lyric-mode"});break;case"c":Ne.preventDefault();const ni=fE,se=de.current.textCase,Ft=(ni.indexOf(se)+1)%ni.length,vt=ni[Ft];K(sn=>({...sn,textCase:vt})),t.success(`Text Case: ${vt}`,{id:"text-case"});break;case"f":jt();break;case"i":Gi(sn=>!sn);break;case"p":ji(sn=>!sn);break;case"d":Ne.preventDefault(),me(sn=>!sn);break;case"t":_t?(Jt(!1),ne(lo.EDITOR)):ne(sn=>sn===lo.PLAYER?lo.EDITOR:lo.PLAYER);break;case"m":Ne.preventDefault();const on=!je;X(on),t.success(on?"Muted":"Unmuted",{id:"mute"});break;case"x":Ne.preventDefault();const Lt=de.current.highlightEffect==="none";K(sn=>({...sn,highlightEffect:sn.highlightEffect==="none"?"karaoke":"none"})),t.success(`Highlight: ${Lt?"On (Karaoke)":"Off"}`,{id:"highlight-toggle"});break;case"z":Ne.preventDefault();const un=z0.flatMap(sn=>sn.options.map(Ui=>Ui.value)),Vn=de.current.highlightEffect||"none",jn=un.indexOf(Vn),_i=((jn===-1?0:jn)+1)%un.length,yo=un[_i],fo=Uf(yo);K(sn=>{const Ui={...sn,highlightEffect:yo};return Ui.useCustomHighlightColors=!1,fo&&(Ui.highlightColor=fo.color,Ui.highlightBackground=fo.bg),Ui}),t.success(`Effect: ${yo.replace(/-/g," ")}`,{id:"highlight-effect"});break;case"j":Ne.preventDefault();const Ye=(Um.indexOf(Me)+1)%Um.length,si=Um[Ye];Pe(si);const Qt=oh[si];if(Qt){const sn={fontFamily:"ui-sans-serif, system-ui, sans-serif",fontSizeScale:1,fontColor:"#ffffff",fontWeight:"bold",fontStyle:"normal",textCase:"none",textAlign:"center",contentPosition:"center",textDecoration:"none",textEffect:"preset",textAnimation:"none",highlightEffect:"karaoke",highlightColor:"#fb923c",highlightBackground:"#fb923c",useCustomHighlightColors:!1,lyricStyleTarget:"active-only",transitionEffect:"none"};K(Ui=>({...Ui,...sn,...Qt}))}let bi=si;for(const sn of Zg){const Ui=sn.options.find(Ka=>Ka.value===si);if(Ui){bi=Ui.label;break}}t.success(`Preset: ${bi}`,{id:"preset"});break;case"arrowleft":if(Ne.preventDefault(),n.current){const sn=Math.max(0,n.current.currentTime-5);n.current.currentTime=sn,P(sn)}break;case"arrowright":if(Ne.preventDefault(),n.current){const sn=Math.min(J,n.current.currentTime+5);n.current.currentTime=sn,P(sn)}break;case"arrowup":Ne.preventDefault(),r.current&&r.current.scrollBy({top:-100,behavior:"smooth"});break;case"arrowdown":Ne.preventDefault(),r.current&&r.current.scrollBy({top:100,behavior:"smooth"});break;case"+":case"=":Ne.preventDefault();const ms=de.current.fontSizeScale,Ns=Math.min(ms+.1,3);K(sn=>({...sn,fontSizeScale:Ns})),t.success(`Font Size: ${(Ns*100).toFixed(0)}%`,{id:"font-size"});break;case"-":Ne.preventDefault();const Ko=de.current.fontSizeScale,qs=Math.max(Ko-.1,.1);K(sn=>({...sn,fontSizeScale:qs})),t.success(`Font Size: ${(qs*100).toFixed(0)}%`,{id:"font-size"});break;case"e":(Ne.ctrlKey||Ne.metaKey)&&Ne.shiftKey&&(Ne.preventDefault(),h.current());break}}};return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[W,H,_e,Se,Rn,xo,_t,ge,pt,t,fn,Me,Xe,je]),Ae.useEffect(()=>{let Z,Ne=0;const dt=1e3/30,Fe=lt=>{if(n.current&&!n.current.paused&&W){Z=requestAnimationFrame(Fe);const mt=lt-Ne;mt>dt&&(Ne=lt-mt%dt,P(n.current.currentTime))}};return W&&!Se&&(Z=requestAnimationFrame(Fe)),()=>{Z&&cancelAnimationFrame(Z)}},[W,Se]);const yi=ti&&(!$||Xe)&&!Se,Lo=Si&&(!$||Xe)&&!Se&&!fn,Ki=Rt.length>0?Rt[0]:null;Ki?`${Ki.url}`:S.coverUrl&&`${S.coverUrl}`;const Li=Ae.useRef(null);return Ae.useEffect(()=>{if(Rt.forEach(Z=>{const Ne=Z.layer||0;if(M.layerVisibility?.visual?.[Ne]!==!1&&Z.type==="video"){const dt=document.getElementById(`video-preview-${Z.id}`);if(dt)if(Se)dt.paused||dt.pause();else{const Fe=Z.playbackRate||1;let lt=(k-Z.startTime)*Fe+(Z.mediaStartOffset||0);const mt=Z.mediaDuration||dt.duration;mt&&mt>0&<>=mt&&(lt=lt%mt),Math.abs(dt.playbackRate-Fe)>.01&&(dt.playbackRate=Fe),Math.abs(dt.currentTime-lt)>.2&&(dt.currentTime=lt);const wt=Z.isMuted!==!1;dt.muted!==wt&&(dt.muted=wt);const Ht=Z.volume!==void 0?Z.volume:1;Math.abs(dt.volume-Ht)>.01&&(dt.volume=Ht),W&&dt.paused?dt.play().catch(()=>{}):!W&&!dt.paused&&dt.pause()}}}),(S.backgroundType==="video"||M.backgroundSource==="video")&&Li.current){const Z=Li.current;if(Se)Z.paused||Z.pause();else{const Ne=Z.duration||1,dt=k%Ne;Math.abs(Z.currentTime-dt)>.1&&(Z.currentTime=dt),W&&Z.paused?Z.play().catch(()=>{}):!W&&!Z.paused&&Z.pause()}}tn.forEach(Z=>{const Ne=document.getElementById(`audio-preview-${Z.id}`);if(Ne){const dt=Z.playbackRate||1,Fe=(k-Z.startTime)*dt+(Z.mediaStartOffset||0);Math.abs(Ne.playbackRate-dt)>.01&&(Ne.playbackRate=dt),Math.abs(Ne.currentTime-Fe)>.2&&(Ne.currentTime=Fe);const lt=Z.isMuted===!0;Ne.muted!==lt&&(Ne.muted=lt);const mt=Z.volume!==void 0?Z.volume:1;Math.abs(Ne.volume-mt)>.01&&(Ne.volume=mt),W&&Ne.paused?Ne.play().catch(()=>{}):!W&&!Ne.paused&&Ne.pause()}})},[k,W,Rt,S,tn,M.layerVisibility]),p.jsxs("div",{ref:i,onMouseMove:io,onTouchStart:pi,onDoubleClick:qt,className:`relative w-full h-[100dvh] bg-black overflow-hidden flex font-sans select-none ${$&&!Xe?"cursor-none":""}`,children:[p.jsx("audio",{ref:n,src:d||void 0,loop:H==="one",muted:je,onTimeUpdate:kt,onLoadedMetadata:hn,onEnded:()=>{if(Se)return;const Z=et.length>0;H==="one"||(H==="all_repeat"?Z?ge():n.current?.play():H==="all"&&Z&&Kep.jsx("audio",{id:`audio-preview-${Z.id}`,src:Z.url,className:"hidden",playsInline:!0},Z.id)),p.jsx("canvas",{ref:a,width:Yt,height:Zt,className:"absolute top-0 left-0 hidden pointer-events-none opacity-0"}),p.jsxs("div",{className:"absolute inset-0 bg-black overflow-hidden pointer-events-none",children:[(M.backgroundSource==="color"||M.backgroundSource==="threejs")&&p.jsx("div",{className:"absolute inset-0",style:{backgroundColor:M.backgroundSource==="threejs"?M.threejsBgColor||"#000000":M.backgroundColor}}),M.backgroundSource==="gradient"&&p.jsx("div",{className:"absolute inset-0",style:{background:M.backgroundGradient}}),M.backgroundSource==="image"&&M.backgroundImage&&p.jsx("div",{className:"absolute inset-0 bg-cover bg-center",style:{backgroundImage:`url(${M.backgroundImage})`}}),M.backgroundSource==="video"&&M.backgroundVideo&&p.jsx("video",{ref:Li,src:M.backgroundVideo,className:"absolute inset-0 w-full h-full object-cover",muted:!0,loop:!0,playsInline:!0}),M.backgroundSource==="smart-gradient"&&p.jsx("div",{className:"absolute inset-0",style:{background:(()=>{const Z=M.backgroundColor||"#312e81",Ne=parseInt(Z.slice(1,3),16),dt=parseInt(Z.slice(3,5),16),Fe=parseInt(Z.slice(5,7),16),lt=`${Ne},${dt},${Fe}`,mt=`${Math.floor(Ne*.6)},${Math.floor(dt*.6)},${Math.floor(Fe*.6)}`;return`linear-gradient(to bottom right, rgb(${lt}), rgb(${mt}) 50%, #000000)`})()}}),(M.backgroundSource==="timeline"&&w.length===0||M.backgroundSource==="custom")&&S.coverUrl&&(S.backgroundType==="video"?p.jsx("video",{ref:Li,src:S.coverUrl,className:`absolute inset-0 w-full h-full object-cover transition-opacity duration-300 ${Ie?"opacity-60":"opacity-0"}`,muted:!0,loop:!Se,playsInline:!0,preload:"auto",onLoadedData:()=>nt(!0)}):p.jsx("div",{className:`absolute inset-0 bg-cover bg-center transition-all duration-700 ease-in-out ${M.backgroundSource==="custom"||Rt.length===0?"opacity-60":"opacity-0"}`,style:{backgroundImage:`url(${S.coverUrl})`}})),(M.backgroundSource==="color"||M.backgroundSource==="threejs")&&p.jsx("div",{className:"absolute inset-0 transition-all duration-500",style:{backgroundColor:M.backgroundSource==="threejs"?M.threejsBgColor||"#000000":M.backgroundColor}}),M.backgroundSource==="gradient"&&p.jsx("div",{className:"absolute inset-0 transition-all duration-500",style:{background:M.backgroundGradient}}),M.backgroundSource==="smart-gradient"&&p.jsx("div",{className:"absolute inset-0 transition-all duration-500",style:{background:(()=>{const Z=M.backgroundColor||"#312e81",Ne=parseInt(Z.slice(1,3),16),dt=parseInt(Z.slice(3,5),16),Fe=parseInt(Z.slice(5,7),16),lt=`${Ne},${dt},${Fe}`,mt=`${Math.floor(Ne*.6)},${Math.floor(dt*.6)},${Math.floor(Fe*.6)}`;return`linear-gradient(to bottom right, rgb(${lt}), rgb(${mt}) 50%, #000000)`})()}}),!S.coverUrl&&(M.backgroundSource==="timeline"&&w.length===0||M.backgroundSource==="custom")&&p.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-indigo-900 via-purple-900 to-black opacity-80"}),M.backgroundSource==="threejs"&&!Se&&p.jsx(pO,{isPlaying:W,currentTime:k,config:M}),p.jsx("div",{className:`absolute inset-0 pointer-events-none ${M.backgroundSource==="timeline"?"opacity-100":"opacity-0"}`,children:M.backgroundSource==="timeline"&&Rt.map(Z=>{const Ne=Z.layer||0;if(M.layerVisibility?.visual?.[Ne]===!1)return null;const dt=M.visualTransitionType||"none",Fe=M.visualTransitionDuration||1;let lt=1;if(dt!=="none"){if(k=Z.endTime){let mt=!1;if(dt==="crossfade"&&(mt=w.some(wt=>wt.id!==Z.id&&(wt.layer||0)===(Z.layer||0)&&wt.startTime>=Z.endTime-.1&&wt.startTimeZ.endTime-Fe){const mt=(Z.endTime-k)/Fe;lt=Math.min(lt,Math.max(0,Math.min(1,mt)))}}return p.jsx("div",{className:"absolute inset-0 flex items-center justify-center overflow-hidden",style:{opacity:lt},children:Z.type==="video"?p.jsx("video",{id:`video-preview-${Z.id}`,src:Z.url,className:"w-full h-full object-cover",muted:Z.isMuted!==!1,playsInline:!0}):p.jsx("div",{className:"w-full h-full bg-cover bg-center",style:{backgroundImage:`url(${Z.url})`}})},Z.id)})}),p.jsx("div",{className:"absolute inset-0 bg-black/30 transition-all duration-700",style:{backdropFilter:M.backgroundBlurStrength>0?`blur(${M.backgroundBlurStrength}px)`:Je?"blur(12px)":"none",backgroundColor:M.useRealColorMedia?"transparent":M.backgroundBlurStrength>0||Je?"rgba(0,0,0,0.4)":void 0}}),M.enableGradientOverlay&&p.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/95 via-black/60 to-transparent pointer-events-none z-0"}),!Se&&p.jsx(KU,{audioElement:n.current,config:M,isPlaying:W})]}),p.jsxs("div",{className:"relative z-10 flex-1 flex flex-col transition-all duration-500",children:[M.showChannelInfo&&fn&&p.jsxs("div",{className:`absolute z-[60] flex gap-2 p-6 pointer-events-none transition-all duration-500 + ${M.channelInfoStyle==="modern"?"flex-col items-center":"flex-row items-center"} + ${M.channelInfoStyle==="box"?"bg-black/40 backdrop-blur-md rounded-xl border border-white/10":""} + ${M.channelInfoPosition==="top-left"?"top-0 left-0 items-start text-left":M.channelInfoPosition==="top-right"?"top-0 right-0 items-end text-right":M.channelInfoPosition==="top-center"?"top-0 left-1/2 items-center text-center":M.channelInfoPosition==="bottom-left"?"bottom-0 left-0 items-start text-left":M.channelInfoPosition==="bottom-center"?"bottom-0 left-1/2 items-center text-center":"bottom-0 right-0 items-end text-right"} + `,style:{transform:`${M.channelInfoPosition?.includes("center")?"translateX(-50%)":""} scale(${M.channelInfoSizeScale??1})`,transformOrigin:M.channelInfoPosition?.includes("top")?M.channelInfoPosition?.includes("center")?"top center":M.channelInfoPosition?.includes("left")?"top left":"top right":M.channelInfoPosition?.includes("center")?"bottom center":M.channelInfoPosition?.includes("left")?"bottom left":"bottom right",...M.channelInfoPosition?.includes("center")?M.channelInfoPosition?.includes("top")?{marginTop:`${(M.channelInfoMarginScale??1)*1.5}rem`}:{marginBottom:`${(M.channelInfoMarginScale??1)*1.5}rem`}:{margin:`${(M.channelInfoMarginScale??1)*1.5}rem`}},children:[M.channelInfoImage&&M.channelInfoStyle!=="minimal"&&p.jsx("img",{src:M.channelInfoImage,alt:"Channel",className:`w-20 h-20 object-contain drop-shadow-lg ${M.channelInfoStyle==="circle"?"rounded-full":""}`}),M.channelInfoText&&M.channelInfoStyle!=="logo"&&(()=>{const Z=M.channelInfoText.trim();return//i.test(Z)?p.jsx("div",{className:`font-bold drop-shadow-md text-lg inline-flex items-center gap-1 + ${M.channelInfoStyle==="minimal"||M.channelInfoStyle==="box"?"":"px-2 py-1 bg-black/20 rounded-lg backdrop-blur-sm"} + [&>svg]:w-auto [&>svg]:h-[1.5em]`,style:{fontFamily:M.channelInfoFontFamily,color:M.channelInfoFontColor||"white",fontWeight:M.channelInfoFontWeight||"bold",fontStyle:M.channelInfoFontStyle||"normal"},dangerouslySetInnerHTML:{__html:Z}}):p.jsx("p",{className:`font-bold drop-shadow-md text-lg + ${M.channelInfoStyle==="minimal"||M.channelInfoStyle==="box"?"":"px-2 py-1 bg-black/20 rounded-lg backdrop-blur-sm"}`,style:{fontFamily:M.channelInfoFontFamily,color:M.channelInfoFontColor||"white",fontWeight:M.channelInfoFontWeight||"bold",fontStyle:M.channelInfoFontStyle||"normal"},children:M.channelInfoText})})()]}),fn&&p.jsx("div",{className:`absolute z-20 flex flex-col gap-2 p-6 transition-all duration-500 pointer-events-none + ${yi?"opacity-100":"opacity-0"} + ${M.infoPosition==="top-left"?"top-0 left-0 items-start text-left":M.infoPosition==="top-right"?"top-0 right-0 items-end text-right":M.infoPosition==="top-center"?"top-0 left-1/2 items-center text-center":M.infoPosition==="bottom-left"?"bottom-0 left-0 items-start text-left":M.infoPosition==="bottom-right"?"bottom-0 right-0 items-end text-right":M.infoPosition==="bottom-center"?"bottom-0 left-1/2 items-center text-center":"top-0 left-0 items-start text-left"} + `,style:{transform:`${M.infoPosition?.includes("center")?"translateX(-50%)":""} scale(${M.infoSizeScale??1})`,transformOrigin:M.infoPosition?.includes("top")?M.infoPosition?.includes("center")?"top center":M.infoPosition?.includes("right")?"top right":"top left":M.infoPosition?.includes("center")?"bottom center":M.infoPosition?.includes("right")?"bottom right":"bottom left",...M.infoPosition?.includes("center")?M.infoPosition?.includes("top")?{marginTop:`${(M.infoMarginScale??1)*1.5}rem`}:{marginBottom:`${(M.infoMarginScale??1)*1.5}rem`}:{margin:`${(M.infoMarginScale??1)*1.5}rem`}},children:p.jsxs("div",{className:` + flex items-center gap-4 pointer-events-auto + ${M.infoPosition?.includes("center")?"flex-col justify-center":""} + ${M.infoPosition?.includes("right")?"flex-row-reverse":"flex-row"} + ${M.infoStyle==="box"?"bg-black/40 backdrop-blur-md p-4 rounded-xl border border-white/10":""} + ${M.infoStyle==="modern"||M.infoStyle==="minimal",""} + `,children:[p.jsxs("div",{className:`relative group shrink-0 transition-opacity duration-300 + ${!M.showCover||M.infoStyle==="minimal"||M.infoStyle==="modern"?"hidden":"block"} + ${M.infoStyle==="circle_art"?"rounded-full":"rounded-md"} + overflow-hidden bg-zinc-800 shadow-lg border border-white/10 + w-12 h-12 md:w-16 md:h-16 + `,children:[S.coverUrl?S.backgroundType==="video"?p.jsx("video",{src:S.coverUrl,className:"w-full h-full object-cover",muted:!0,loop:!0,onMouseOver:Z=>Z.currentTarget.play(),onMouseOut:Z=>Z.currentTarget.pause()}):p.jsx("img",{src:S.coverUrl,alt:"Cover",className:"w-full h-full object-cover"}):p.jsx("div",{className:"w-full h-full flex items-center justify-center text-zinc-500",children:p.jsx($l,{size:24})}),p.jsxs("label",{className:"absolute inset-0 bg-black/50 flex items-center justify-center opacity-0 group-hover:opacity-100 cursor-pointer transition-opacity",children:[p.jsx(cs,{size:20,className:"text-white"}),p.jsx("input",{type:"file",accept:"image/*,video/*",className:"hidden",onChange:ii})]})]}),p.jsxs("div",{className:`flex flex-col justify-center ${M.infoPosition?.includes("right")?"items-end":M.infoPosition?.includes("center")?"items-center":"items-start"}`,children:[p.jsx("h1",{className:`font-bold drop-shadow-md line-clamp-1 transition-opacity duration-300 + ${M.showTitle?"opacity-100":"opacity-0 h-0 w-0"} + ${M.infoStyle==="minimal"?"text-sm":M.infoStyle==="modern"||M.infoStyle==="modern_art"?"text-xl":"text-lg"} + `,style:{fontFamily:M.infoFontFamily,color:M.infoFontColor||"white",fontWeight:M.infoFontWeight||"bold",fontStyle:M.infoFontStyle||"normal"},children:S.title}),p.jsx("div",{className:`flex items-center gap-2 transition-opacity duration-300 + ${M.showArtist?"opacity-100":"opacity-0 h-0 w-0"} + `,children:p.jsx("p",{className:`drop-shadow-md + ${M.infoStyle==="minimal"?"text-[10px]":M.infoStyle==="modern"||M.infoStyle==="modern_art"?"text-sm font-medium":"text-xs"} + `,style:{fontFamily:M.infoFontFamily,color:M.infoFontColor||(M.infoStyle==="minimal"?"#a1a1aa":"#d4d4d8"),fontWeight:M.infoFontWeight||"bold",fontStyle:M.infoFontStyle||"normal"},children:S.artist})})]})]})}),p.jsx("div",{className:`transition-all duration-500 ease-in-out overflow-hidden ${yi&&!fn?"max-h-80 md:max-h-40 opacity-100":"max-h-0 opacity-0"}`,children:p.jsxs("div",{className:"p-4 md:p-6 flex flex-col md:flex-row justify-between items-start gap-4 md:gap-0",children:[p.jsx("div",{className:"flex gap-4",children:p.jsxs("div",{className:"flex gap-4 items-center",children:[p.jsxs("div",{className:`relative group w-16 h-16 rounded-md overflow-hidden bg-zinc-800 shadow-lg border border-white/10 shrink-0 transition-opacity duration-300 ${M.showCover?"opacity-100 scale-100":"opacity-0 scale-75 pointer-events-none w-0 h-0 -ml-4"}`,children:[S.coverUrl?S.backgroundType==="video"?p.jsx("video",{src:S.coverUrl,className:"w-full h-full object-cover",muted:!0,loop:!0,onMouseOver:Z=>Z.currentTarget.play(),onMouseOut:Z=>Z.currentTarget.pause()}):p.jsx("img",{src:S.coverUrl,alt:"Cover",className:"w-full h-full object-cover"}):p.jsx("div",{className:"w-full h-full flex items-center justify-center text-zinc-500",children:p.jsx($l,{size:24})}),p.jsxs("label",{className:"absolute inset-0 bg-black/50 flex items-center justify-center opacity-0 group-hover:opacity-100 cursor-pointer transition-opacity",children:[p.jsx(cs,{size:20,className:"text-white"}),p.jsx("input",{type:"file",accept:"image/*,video/*",className:"hidden",onChange:ii})]})]}),p.jsxs("div",{children:[p.jsx("h1",{className:`text-xl font-bold text-white drop-shadow-md line-clamp-1 transition-opacity duration-300 ${M.showTitle?"opacity-100":"opacity-0"}`,children:S.title}),p.jsx("div",{className:`flex items-center gap-2 transition-opacity duration-300 ${M.showArtist?"opacity-100":"opacity-0"}`,children:p.jsx("p",{className:"text-zinc-300 text-sm drop-shadow-md",children:S.artist})})]})]})}),p.jsxs("div",{className:`flex gap-2 flex-wrap ${fn?"hidden":""}`,children:[p.jsx("a",{href:"https://github.com/dotslashgabut/immersive-audio-player-lyric-video-maker",target:"_blank",rel:"noopener noreferrer",title:"Immersive Audio Player & Lyric Video Maker | GitHub",className:"px-3 py-2 rounded-full transition-colors bg-black/30 text-zinc-300 hover:bg-white/10 text-xs font-bold flex items-center",children:p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",fill:"#eee",className:"bi bi-github",viewBox:"0 0 16 16",children:p.jsx("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8"})})}),p.jsx("a",{href:"https://ai.studio/apps/drive/11YaG-jtLXb8BnXM3aMfj7wmKIw-S3mt3?fullscreenApplet=true",target:"_blank",rel:"noopener noreferrer",title:"LyricalEditorPlus - Universal Lyrics/Subtitle Editor",className:"px-3 py-2 rounded-full transition-colors bg-black/30 text-zinc-300 hover:bg-white/10 text-xs font-bold flex items-center",children:"LyricalEditorPlus"}),p.jsx("a",{href:"https://ai.studio/apps/drive/1M1VfxdBlNB_eOPQqQiHspvVwizaEs0aI?fullscreenApplet=true",target:"_blank",rel:"noopener noreferrer",title:"LyricFlow - Turn Audio into Subtitles",className:"px-3 py-2 rounded-full transition-colors bg-black/30 text-zinc-300 hover:bg-white/10 text-xs font-bold flex items-center",children:"LyricFlow"}),p.jsx("a",{href:"https://ai.studio/apps/drive/1WKA-bCxzIKD-DcI_pq0HzxN3m1_oNEkg?fullscreenApplet=true",target:"_blank",rel:"noopener noreferrer",title:"LyricalVision - Visualize lyrics with Gemini AI",className:"px-3 py-2 rounded-full transition-colors bg-black/30 text-zinc-300 hover:bg-white/10 text-xs font-bold flex items-center",children:"LyricalVision"}),p.jsx("button",{onClick:()=>oe(!Xe),className:`p-2 rounded-full transition-colors ${Xe?"bg-purple-600/50 text-white":"bg-black/30 text-zinc-300 hover:bg-white/10"}`,title:"Bypass Auto-hide (H)",children:Xe?p.jsx(_u,{size:20}):p.jsx(yu,{size:20})}),p.jsx("button",{onClick:()=>fi(!fn),className:`p-2 rounded-full transition-colors ${fn?"bg-purple-600 text-white":"bg-black/30 text-zinc-300 hover:bg-white/10"}`,title:"Minimal Mode (O)",children:fn?p.jsx(Au,{size:20}):p.jsx(mb,{size:20})}),p.jsx("button",{onClick:()=>{const Z=!_t;Jt(Z),Z&&ne(lo.PLAYER)},className:`p-2 rounded-full transition-colors ${_t?"bg-orange-600 text-white":"bg-black/30 text-zinc-300 hover:bg-white/10"}`,title:"Toggle Playlist (L)",children:p.jsx(Jf,{size:20})}),p.jsx("button",{onClick:()=>{_t&&Jt(!1),ne(_e===lo.PLAYER?lo.EDITOR:lo.PLAYER)},className:`p-2 rounded-full transition-colors ${_e===lo.EDITOR&&!_t?"bg-purple-600 text-white":"bg-black/30 text-zinc-300 hover:bg-white/10"}`,title:"Toggle Timeline (T)",children:p.jsx(mT,{size:20})}),p.jsx("button",{onMouseDown:Z=>{Z.stopPropagation(),me(!Y)},className:`p-2 rounded-full transition-colors ${Y?"bg-purple-600 text-white":"bg-black/30 text-zinc-300 hover:bg-white/10"}`,title:"Render Settings (D)",children:p.jsx(Gl,{size:20})}),p.jsx("button",{onMouseDown:Z=>{Z.stopPropagation(),$e(!ee)},className:`p-2 rounded-full transition-colors ${ee?"bg-purple-600 text-white":"bg-black/30 text-zinc-300 hover:bg-white/10"}`,title:"Keyboard Shortcuts (Y)",children:p.jsx(Yf,{size:20})}),p.jsx("button",{onClick:jt,className:"p-2 rounded-full bg-black/30 text-zinc-300 hover:bg-white/10 transition-colors",title:"Fullscreen (F)",children:tt?p.jsx(mb,{size:20}):p.jsx(Au,{size:20})})]})]})}),p.jsx("div",{className:`flex-1 flex justify-center overflow-hidden relative ${M.contentPosition==="top"?"items-start":M.contentPosition==="bottom"?"items-end":"items-center"}`,style:{paddingTop:M.contentPosition==="top"?`${(M.marginTopScale??1)*10}vh`:void 0,paddingBottom:M.contentPosition==="bottom"?`${(M.marginBottomScale??1)*10}vh`:void 0},children:A.length>0?p.jsxs("div",{ref:r,className:`w-full max-w-5xl max-h-full overflow-y-auto no-scrollbar px-4 md:px-6 space-y-4 md:space-y-6 transition-all duration-500 lyrics-root ${M.textAlign==="left"?"text-left":M.textAlign==="right"?"text-right":"text-center"} ${M.showLyrics?"opacity-100":"opacity-0 pointer-events-none"}`,style:{maskImage:(yi||Lo)&&Me!=="subtitle"?"linear-gradient(to bottom, transparent, black 10%, black 90%, transparent)":"none"},children:[p.jsx("style",{children:` + .lyrics-root .text-lg { font-size: calc(1.125rem * ${M.fontSizeScale}); line-height: calc(1.75rem * ${M.fontSizeScale} * ${M.lyricLineHeight||1.2}); } + .lyrics-root .text-xl { font-size: calc(1.25rem * ${M.fontSizeScale}); line-height: calc(1.75rem * ${M.fontSizeScale} * ${M.lyricLineHeight||1.2}); } + .lyrics-root .text-2xl { font-size: calc(1.5rem * ${M.fontSizeScale}); line-height: calc(2rem * ${M.fontSizeScale} * ${M.lyricLineHeight||1.2}); } + .lyrics-root .text-3xl { font-size: calc(1.875rem * ${M.fontSizeScale}); line-height: calc(2.25rem * ${M.fontSizeScale} * ${M.lyricLineHeight||1.2}); } + .lyrics-root .text-4xl { font-size: calc(2.25rem * ${M.fontSizeScale}); line-height: calc(2.5rem * ${M.fontSizeScale} * ${M.lyricLineHeight||1.2}); } + .lyrics-root .text-5xl { font-size: calc(3rem * ${M.fontSizeScale}); line-height: calc(1 * ${M.lyricLineHeight||1.2}); } + .lyrics-root .text-6xl { font-size: calc(3.75rem * ${M.fontSizeScale}); line-height: calc(1 * ${M.lyricLineHeight||1.2}); } + .lyrics-root .text-7xl { font-size: calc(4.5rem * ${M.fontSizeScale}); line-height: calc(1 * ${M.lyricLineHeight||1.2}); } + .lyrics-root .text-8xl { font-size: calc(6rem * ${M.fontSizeScale}); line-height: calc(1 * ${M.lyricLineHeight||1.2}); } + `}),p.jsx("div",{className:`transition-all duration-500 ${M.contentPosition==="center"?_e===lo.EDITOR||_t?"h-[25vh]":!yi&&!Lo?"h-[50vh]":"h-[40vh]":"h-0"}`}),En.map((Z,Ne)=>{const dt=Ne===Mi,Fe=_e===lo.EDITOR||_t,lt=["9:16","3:4","1:1","1:2","2:3"].includes(Oe);if(M.lyricDisplayMode!=="all"){if(M.lyricDisplayMode==="active-only"&&Ne!==Mi)return p.jsx("p",{className:"hidden"},Ne);if(M.lyricDisplayMode==="next-only"&&(NeMi+1))return p.jsx("p",{className:"hidden"},Ne);if(M.lyricDisplayMode==="previous-next"&&Math.abs(Ne-Mi)>1)return p.jsx("p",{className:"hidden"},Ne)}else if(Me==="none"||Me==="just_video")return p.jsx("p",{className:"hidden"},Ne);let mt="",wt="";const Ht=M.transitionEffect;let Pt="transition-[color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,text-shadow] duration-500 cursor-pointer whitespace-pre-wrap break-words ";if(dt?Ht==="slide"?Pt+="translate-y-0 opacity-100 ":Ht==="zoom"?Pt+="scale-100 opacity-100 ":Ht==="float"?Pt+="translate-y-0 opacity-100 ":Ht==="blur"?Pt+="blur-0 opacity-100 ":Ht==="fade"?Pt+="opacity-100 ":Ht==="drop"?Pt+="trans-drop-enter opacity-100 ":Ht==="lightspeed"?Pt+="trans-lightspeed-enter opacity-100 ":Ht==="roll"?Pt+="trans-roll-enter opacity-100 ":Ht==="elastic"?Pt+="trans-elastic-enter opacity-100 ":Ht==="flip"?Pt+="trans-flip-enter opacity-100 ":Ht==="rotate-in"?Pt+="trans-rotate-in-enter opacity-100 ":Ht==="spiral"?Pt+="trans-spiral-enter opacity-100 ":Ht==="shatter"?Pt+="trans-shatter-enter opacity-100 ":Pt+="opacity-100 ":(Ht==="slide"?Pt+="translate-y-4 opacity-0 ":Ht==="zoom"?Pt+="scale-75 opacity-0 ":Ht==="float"?Pt+="translate-y-8 opacity-0 ":Ht==="blur"?Pt+="blur-md opacity-0 ":Ht==="fade"?Pt+="opacity-50 ":Ht==="drop"?Pt+="trans-drop-exit opacity-0 ":Ht==="roll"?Pt+="trans-roll-exit opacity-0 ":Pt+="opacity-0 ",Ht==="none"&&(Pt=Pt.replace("opacity-0","opacity-50"))),Me==="large"||Me==="large_upper"){const Ft=lt?Fe?"text-4xl":"text-6xl":Fe?"text-6xl":"text-8xl",vt=lt?Fe?"text-xl":"text-2xl":Fe?"text-2xl":"text-3xl";mt=`${Ft} font-black text-white ${Me==="large_upper"?"uppercase":""} tracking-tight text-left pl-4`,wt=`${vt} text-zinc-600/40 hover:text-zinc-400 text-left pl-4`}else if(Me==="big_center"){const se=lt?Fe?"text-4xl":"text-5xl":Fe?"text-6xl":"text-8xl",Mt=lt?Fe?"text-xl":"text-2xl":Fe?"text-2xl":"text-3xl";mt=`${se} font-black text-white uppercase tracking-tight text-center`,wt=`${Mt} text-zinc-600/40 hover:text-zinc-400 text-center`}else if(Me==="testing_up"){const se=lt?Fe?"text-4xl":"text-5xl":Fe?"text-6xl":"text-8xl",Mt=lt?Fe?"text-xl":"text-2xl":Fe?"text-2xl":"text-3xl";mt=`${se} text-white uppercase tracking-tight text-center`,wt=`${Mt} text-zinc-600/40 hover:text-zinc-400 text-center`}else if(Me==="testing"){const se=lt?Fe?"text-4xl":"text-5xl":Fe?"text-6xl":"text-8xl",Mt=lt?Fe?"text-xl":"text-2xl":Fe?"text-2xl":"text-3xl";mt=`${se} text-white tracking-tight text-center`,wt=`${Mt} text-zinc-600/40 hover:text-zinc-400 text-center`}else if(Me==="one_line_up"){const se=lt?Fe?"text-4xl":"text-5xl":Fe?"text-6xl":"text-8xl",Mt=lt?Fe?"text-xl":"text-2xl":Fe?"text-2xl":"text-3xl";mt=`${se} text-white uppercase tracking-tight text-center`,wt=`${Mt} text-zinc-600/40 hover:text-zinc-400 text-center`}else if(Me==="one_line"){const se=lt?Fe?"text-4xl":"text-5xl":Fe?"text-6xl":"text-8xl",Mt=lt?Fe?"text-xl":"text-2xl":Fe?"text-2xl":"text-3xl";mt=`${se} text-white tracking-tight text-center`,wt=`${Mt} text-zinc-600/40 hover:text-zinc-400 text-center`}else if(Me==="metal"){const se=lt?Fe?"text-4xl":"text-5xl":Fe?"text-6xl":"text-8xl",Mt=lt?Fe?"text-xl":"text-2xl":Fe?"text-2xl":"text-3xl";mt=`${se} text-white uppercase tracking-wide text-center drop-shadow-[0_4px_6px_rgba(255,0,0,0.5)]`,wt=`${Mt} text-zinc-600/60 hover:text-zinc-400 text-center`}else if(Me==="kids"){const se=lt?Fe?"text-4xl":"text-5xl":Fe?"text-6xl":"text-8xl",Mt=lt?Fe?"text-xl":"text-2xl":Fe?"text-2xl":"text-3xl";mt=`${se} text-white tracking-wide text-center drop-shadow-[3px_3px_0px_rgba(0,0,0,0.5)]`,wt=`${Mt} text-zinc-600/60 hover:text-zinc-400 text-center`}else if(Me==="sad"){const se=lt?Fe?"text-4xl":"text-5xl":Fe?"text-6xl":"text-7xl",Mt=lt?Fe?"text-lg":"text-xl":Fe?"text-xl":"text-2xl";mt=`${se} text-zinc-200 tracking-wider text-center drop-shadow-md`,wt=`${Mt} text-zinc-600/60 hover:text-zinc-400 text-center`}else if(Me==="romantic"){const se=lt?Fe?"text-4xl":"text-5xl":Fe?"text-6xl":"text-7xl",Mt=lt?Fe?"text-lg":"text-xl":Fe?"text-xl":"text-2xl";mt=`${se} text-pink-100 italic tracking-wide text-center drop-shadow-[0_0_10px_rgba(236,72,153,0.5)]`,wt=`${Mt} text-zinc-600/60 hover:text-zinc-400 text-center italic`}else if(Me==="tech"){const se=lt?Fe?"text-4xl":"text-5xl":Fe?"text-6xl":"text-8xl",Mt=lt?Fe?"text-xl":"text-2xl":Fe?"text-2xl":"text-3xl";mt=`${se} text-cyan-50 font-bold uppercase tracking-widest text-center drop-shadow-[0_0_10px_rgba(34,211,238,0.8)]`,wt=`${Mt} text-cyan-900/40 hover:text-cyan-800 text-center uppercase`}else if(Me==="gothic"){const se=lt?Fe?"text-4xl":"text-5xl":Fe?"text-6xl":"text-7xl",Mt=lt?Fe?"text-xl":"text-2xl":Fe?"text-2xl":"text-3xl";mt=`${se} text-zinc-300 tracking-normal text-center drop-shadow-[0_4px_10px_rgba(0,0,0,0.9)]`,wt=`${Mt} text-zinc-700/60 hover:text-zinc-500 text-center`}else if(Me==="monospace"){const se=lt?Fe?"text-2xl":"text-3xl":Fe?"text-3xl":"text-5xl",Mt=lt?Fe?"text-lg":"text-xl":Fe?"text-xl":"text-2xl";mt=`${se} font-mono font-bold text-white scale-105 drop-shadow-[0_2px_4px_rgba(0,0,0,0.8)]`,wt=`${Mt} font-mono text-zinc-500/60 hover:text-zinc-300 drop-shadow-sm`}else if(Me==="classic"){const se=lt?Fe?"text-2xl":"text-3xl":Fe?"text-3xl":"text-6xl",Mt=lt?Fe?"text-lg":"text-xl":Fe?"text-xl":"text-2xl";mt=`${se} font-serif italic font-bold text-amber-100 drop-shadow-[0_4px_8px_rgba(0,0,0,0.9)]`,wt=`${Mt} font-serif text-zinc-500/60 hover:text-zinc-300 italic`}else if(Me==="slideshow"||Me==="just_video")mt=`${lt?Fe?"text-2xl":"text-3xl":Fe?"text-3xl":"text-4xl"} text-white tracking-wide text-center`,wt="hidden";else if(Me==="subtitle"){mt=`${lt?Fe?"text-2xl":"text-3xl":Fe?"text-3xl":"text-4xl"} text-white tracking-wide text-center whitespace-pre-wrap`,wt="hidden";let Mt="bottom-16";Fe&&Lo?Mt="bottom-[560px]":Fe?Mt="bottom-[360px]":Lo&&(Mt="bottom-[280px]"),Pt=Pt.replace("absolute","").replace("transform",""),Pt+=`fixed ${Mt} left-1/2 -translate-x-1/2 w-full px-8 z-[100] pointer-events-none `}else if(Me==="custom"){const se=lt?Fe?"text-4xl":"text-5xl":Fe?"text-6xl":"text-8xl",Mt=lt?Fe?"text-xl":"text-2xl":Fe?"text-2xl":"text-3xl",Ft=M.textAlign==="center"?"text-center":M.textAlign==="right"?"text-right":"text-left";mt=`${se} tracking-tight ${Ft}`,wt=`${Mt} opacity-40 hover:opacity-100 ${Ft}`}else{const se=lt?Fe?"text-2xl":"text-3xl":Fe?"text-3xl":"text-5xl",Mt=lt?Fe?"text-lg":"text-xl":Fe?"text-xl":"text-2xl";mt=`${se} font-bold text-white scale-105 drop-shadow-[0_2px_4px_rgba(0,0,0,0.8)]`,wt=`${Mt} text-zinc-500/60 hover:text-zinc-300 drop-shadow-sm`}const Nn=(M.lyricStyleTarget||"active-only")==="all"||dt;let ft={color:M.fontColor,fontWeight:Nn?M.fontWeight:void 0,fontStyle:Nn?M.fontStyle:void 0,textDecoration:Nn?M.textDecoration:void 0,fontFamily:M.fontFamily==="CustomFont"?"CustomFont, sans-serif":M.fontFamily};if((Me==="custom"||Me==="default")&&dt&&M.textEffect!=="none"){const se=M.textEffect;se==="glow"?ft.textShadow=`0 0 10px ${M.fontColor}, 0 0 20px ${M.fontColor}`:se==="neon"?ft.textShadow=`0 0 5px #fff, 0 0 10px #fff, 0 0 20px ${M.fontColor}, 0 0 40px ${M.fontColor}, 0 0 80px ${M.fontColor}`:se==="neon-multi"?ft.textShadow="0 0 5px #fff, 0 0 10px #fff, 0 0 20px #ff00de, 0 0 35px #00ffff, 0 0 40px #ff00de, 0 0 50px #00ffff":se==="shadow"?ft.textShadow="3px 3px 6px rgba(0,0,0,0.7)":se==="outline"?ft.textShadow="-1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000":se==="3d"?ft.textShadow="1px 1px 0px #ccc, 2px 2px 0px #bbb, 3px 3px 0px #aaa, 4px 4px 0px rgba(0,0,0,0.5)":se==="emboss"?(ft.color="#ebebeb",ft.textShadow="1px 2px 3px rgba(255,255,255,0.8), -1px -2px 3px rgba(0,0,0,0.8)"):se==="gold"?(ft.background="linear-gradient(to bottom, #d4af37, #C5A028)",ft.WebkitBackgroundClip="text",ft.color="transparent"):se==="chrome"?(ft.background="linear-gradient(to bottom, #ebebeb 50%, #616161 50%, #ebebeb)",ft.WebkitBackgroundClip="text",ft.color="transparent"):se==="fire"?(ft.color="#fff",ft.textShadow="0 -5px 4px #FFC107, 2px -10px 6px #FF9800, -2px -15px 11px #FF5722, 2px -25px 18px #795548"):se==="frozen"?(ft.color="#fff",ft.textShadow="0 0 5px rgba(255,255,255,0.8), 0 0 10px rgba(255,255,255,0.5), 0 0 20px #03A9F4, 0 0 30px #03A9F4, 0 0 40px #03A9F4"):se==="vhs"?ft.textShadow="2px 0 0 rgba(255,0,0,0.7), -2px 0 0 rgba(0,0,255,0.7)":se==="gradient"?(ft.background=`linear-gradient(to right, ${M.fontColor}, #ffffff)`,ft.WebkitBackgroundClip="text",ft.color="transparent"):se==="rainbow"?(ft.background="linear-gradient(to left, violet, indigo, blue, green, yellow, orange, red)",ft.WebkitBackgroundClip="text",ft.color="transparent"):se==="glass"?(ft.backgroundColor="rgba(255, 255, 255, 0.1)",ft.backdropFilter="blur(8px)",ft.padding="0.5rem 1rem",ft.borderRadius="0.75rem",ft.border="1px solid rgba(255, 255, 255, 0.2)",ft.display="inline-block"):se==="mirror"?(ft.transform="scaleY(1.3) perspective(500px) rotateX(-10deg)",ft.textShadow="0 15px 5px rgba(0,0,0,0.1), 0 -1px 3px rgba(0,0,0,0.3)"):se==="retro"?(ft.fontFamily="'Press Start 2P', cursive",ft.color="#ff00ff",ft.textShadow="4px 4px 0px #00ffff"):se==="cyberpunk"?(ft.color="#fcee0a",ft.textShadow="2px 2px 0px #000, -1px -1px 0 #05d9e8",ft.fontFamily="'Orbitron', sans-serif",ft.letterSpacing="1px"):se==="glitch-text"?(ft.animation="anim-glitch 0.4s infinite linear",ft.position="relative"):se==="hologram"?(ft.color="rgba(0, 255, 255, 0.7)",ft.textShadow="0 0 5px rgba(0,255,255,0.5), 0 0 10px rgba(0,255,255,0.5)",ft.backgroundImage="repeating-linear-gradient(0deg, transparent, transparent 2px, #00ffff 3px)",ft.WebkitBackgroundClip="text"):se==="comic"&&(ft.fontFamily="'Bangers', cursive",ft.color="#ffcc00",ft.textShadow="2px 2px 0px #000, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000",ft.letterSpacing="1px")}let $t=Z.text;const In=M.textCase;In==="upper"?$t=$t.toUpperCase():In==="lower"?$t=$t.toLowerCase():In==="title"?$t=$t.replace(/\w\S*/g,se=>se.charAt(0).toUpperCase()+se.substr(1).toLowerCase()):In==="sentence"?$t=$t.charAt(0).toUpperCase()+$t.slice(1).toLowerCase():In==="invert"&&($t=$t.replace(/\w\S*/g,se=>se.charAt(0).toLowerCase()+se.slice(1).toUpperCase())),$t=$t.replace(/\s*([-‐‑‒–—―])\s*/g,"$1"),dt&&M.textAnimation==="typewriter"&&($t=$t.substring(0,Math.max(0,Math.floor((k-Z.time)*35))));let ni=$t;if(dt&&M.highlightEffect!=="none"){const se=M.highlightEffect,Mt=Z.words&&Z.words.length>0;if((se==="karaoke"||se?.startsWith("karaoke-"))&&Mt)ni=Z.words.filter(Ft=>Ft.text===` +`||Ft.text.trim().length>0).map((Ft,vt,on)=>{if(Ft.text===` +`)return p.jsx("br",{},vt);let Lt=Ft.text.trim();if(In==="upper")Lt=Lt.toUpperCase();else if(In==="lower")Lt=Lt.toLowerCase();else if(In==="title")Lt=Lt.replace(/\w\S*/g,Qt=>Qt.charAt(0).toUpperCase()+Qt.substr(1).toLowerCase());else if(In==="sentence"){const Qt=Lt.toLowerCase();Lt=vt===0?Qt.charAt(0).toUpperCase()+Qt.slice(1):Qt}else In==="invert"&&(Lt=Lt.replace(/\w\S*/g,Qt=>Qt.charAt(0).toLowerCase()+Qt.slice(1).toUpperCase()));const un=Ft.startTime+L,Vn=Ft.endTime+L,jn=k>=un&&k=Vn,_i=/[-‐‑‒–—―]$/,yo=/^[-‐‑‒–—―]/;let fo=!Lt.endsWith(" ");_i.test(Lt.trim())&&(fo=!1);const Uo=on[vt+1];Uo&&yo.test(Uo.text.trim())&&(fo=!1),Uo&&Uo.text===` +`&&(fo=!1),vt===on.length-1&&(fo=!1);let Ye={display:"inline-block",transition:"all 0.1s ease"};if(M.textDecoration&&M.textDecoration!=="none"&&(Ye.textDecoration=M.textDecoration),!jn&&!js)se==="karaoke-smooth-white"?(Ye.opacity=1,Ye.color="#ffffff"):Ye.opacity=.5,Ye.transform="scale(1)";else if(js)if(se==="karaoke-fill"){const Qt=M.highlightBackground||"#fb923c";Ye.backgroundColor=Qt,Ye.color="#000",Ye.padding="2px 6px",Ye.borderRadius="4px",Ye.opacity=1}else se==="karaoke-smooth"||se==="karaoke-smooth-white"?(Ye.color=M.highlightColor||"#fb923c",Ye.opacity=1):(Me==="custom"&&(Ye.color=M.fontColor),Ye.opacity=1);if(jn){const Qt=M.highlightColor||"#fb923c",bi=M.highlightBackground||"#fb923c";if(se==="karaoke-smooth"||se==="karaoke-smooth-white"){const ms=Ft.endTime-Ft.startTime,Ns=k-un,Ko=Math.min(100,Math.max(0,Ns/ms*100)),qs=se==="karaoke-smooth-white"?"#ffffff":M.fontColor||"#ffffff";Ye.backgroundImage=`linear-gradient(90deg, ${Qt} ${Ko}%, ${qs} ${Ko}%)`,Ye.backgroundClip="text",Ye.WebkitBackgroundClip="text",Ye.color="transparent",Ye.WebkitTextFillColor="transparent",Ye.textShadow="none"}else se==="karaoke"||se==="color"?(Ye.color=Qt,Ye.textShadow=`0 0 10px ${Qt}`):se==="karaoke-neon"?(Ye.color="#fff",Ye.textShadow=`0 0 5px #fff, 0 0 10px #fff, 0 0 20px ${Qt}, 0 0 35px ${Qt}`):se==="karaoke-scale"?(Ye.color=Qt,Ye.transform="scale(1.3)"):se==="karaoke-underline"?(Ye.color=Qt,Ye.textDecoration=(Ye.textDecoration||"")+" underline",Ye.textDecorationColor=Qt,Ye.textUnderlineOffset="4px"):se==="karaoke-bounce"?(Ye.color=Qt,Ye.transform="translateY(-10px)"):se==="karaoke-fill"?(Ye.backgroundColor=bi,Ye.color="#000",Ye.padding="2px 6px",Ye.borderRadius="4px"):se==="karaoke-outline"?(Ye.color="transparent",Ye.WebkitTextStroke=`2px ${Qt}`):se==="karaoke-shadow"?(Ye.color=Qt,Ye.textShadow="3px 3px 0 #000, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000"):se==="karaoke-gradient"?(Ye.background=`linear-gradient(90deg, ${Qt}, ${bi})`,Ye.WebkitBackgroundClip="text",Ye.WebkitTextFillColor="transparent"):se==="karaoke-wave"?(Ye.color=Qt,Ye.animation="bounce 0.3s ease infinite"):se==="karaoke-pill"?(Ye.backgroundColor=bi,Ye.color="#000",Ye.padding="4px 16px",Ye.borderRadius="9999px"):se==="karaoke-box"?(Ye.backgroundColor=bi,Ye.color="#000",Ye.padding="4px 8px",Ye.borderRadius="0"):se==="karaoke-rounded"?(Ye.backgroundColor=bi,Ye.color="#000",Ye.padding="4px 12px",Ye.padding="4px 12px",Ye.borderRadius="12px"):se==="karaoke-glass"?(Ye.backgroundColor="rgba(255, 255, 255, 0.1)",Ye.color="#fff",Ye.padding="4px 12px",Ye.borderRadius="8px",Ye.backdropFilter="blur(4px)",Ye.border="1px solid rgba(255, 255, 255, 0.3)",Ye.boxShadow="0 4px 6px rgba(0, 0, 0, 0.1)"):se==="karaoke-neon-multi"?(Ye.color="#fff",Ye.textShadow="0 0 5px #fff, 0 0 10px #fff, 0 0 20px #ff00de, 0 0 35px #00ffff, 0 0 40px #ff00de"):se==="karaoke-soft-glow"?(Ye.color=Qt,Ye.textShadow=`0 0 5px ${Qt}, 0 0 15px ${Qt}, 0 0 30px ${Qt}`):se==="karaoke-3d"?Ye.textShadow="1px 1px 0px #ccc, 2px 2px 0px #bbb, 3px 3px 0px #aaa, 4px 4px 0px rgba(0,0,0,0.5)":se==="karaoke-emboss"?(Ye.color="#ebebeb",Ye.textShadow="1px 2px 3px rgba(255,255,255,0.8), -1px -2px 3px rgba(0,0,0,0.8)"):se==="karaoke-chrome"?(Ye.background="linear-gradient(to bottom, #ebebeb 50%, #616161 50%, #ebebeb)",Ye.WebkitBackgroundClip="text",Ye.color="transparent"):se==="karaoke-gold"?(Ye.background="linear-gradient(to bottom, #d4af37, #C5A028)",Ye.WebkitBackgroundClip="text",Ye.color="transparent"):se==="karaoke-fire"?(Ye.color="#fff",Ye.textShadow="0 -5px 4px #FFC107, 2px -10px 6px #FF9800, -2px -15px 11px #FF5722, 2px -25px 18px #795548"):se==="karaoke-frozen"?(Ye.color="#fff",Ye.textShadow="0 0 5px rgba(255,255,255,0.8), 0 0 10px rgba(255,255,255,0.5), 0 0 20px #03A9F4, 0 0 30px #03A9F4"):se==="karaoke-rainbow"?(Ye.background="linear-gradient(to left, violet, indigo, blue, green, yellow, orange, red)",Ye.WebkitBackgroundClip="text",Ye.color="transparent"):se==="karaoke-mirror"?(Ye.transform="scaleY(1.3) perspective(500px) rotateX(-10deg)",Ye.textShadow="0 15px 5px rgba(0,0,0,0.1), 0 -1px 3px rgba(0,0,0,0.3)"):se==="karaoke-vhs"?Ye.textShadow="2px 0 0 rgba(255,0,0,0.7), -2px 0 0 rgba(0,0,255,0.7)":se==="karaoke-retro"?(Ye.fontFamily="'Press Start 2P', cursive",Ye.color="#ff00ff",Ye.textShadow="4px 4px 0px #00ffff"):se==="karaoke-cyberpunk"?(Ye.color="#fcee0a",Ye.textShadow="2px 2px 0px #000, -1px -1px 0 #05d9e8",Ye.fontFamily="'Orbitron', sans-serif"):se==="karaoke-hologram"?(Ye.color="rgba(0, 255, 255, 0.7)",Ye.textShadow="0 0 5px rgba(0,255,255,0.5)"):se==="karaoke-comic"?(Ye.fontFamily="'Bangers', cursive",Ye.color="#ffcc00",Ye.textShadow="2px 2px 0px #000, -1px -1px 0 #000"):se==="karaoke-glitch-text"?Ye.animation="anim-glitch 0.4s infinite linear":se==="karaoke-pulse"?Ye.animation="anim-pulse 1s infinite ease-in-out":se==="karaoke-breathe"?Ye.animation="anim-breathe 2s infinite ease-in-out":se==="karaoke-float"?Ye.animation="anim-float 2s infinite ease-in-out":se==="karaoke-sway"?Ye.animation="anim-sway 2s infinite ease-in-out":se==="karaoke-flicker"?Ye.animation="anim-flicker 2s infinite linear":se==="karaoke-shake"?Ye.animation="anim-shake 0.2s infinite linear":se==="karaoke-wobble"?Ye.animation="anim-wobble 1s infinite ease-in-out":se==="karaoke-jello"?Ye.animation="anim-jello 1s infinite":se==="karaoke-rubberband"?Ye.animation="anim-rubberband 1s infinite":se==="karaoke-heartbeat"?Ye.animation="anim-heartbeat 1.3s infinite ease-in-out":se==="karaoke-flash"?Ye.animation="anim-flash 1s infinite":se==="karaoke-tada"?Ye.animation="anim-tada 1s infinite":se==="karaoke-swing"?Ye.animation="anim-swing 2s infinite":se==="karaoke-rotate"?Ye.animation="anim-rotate 4s infinite linear":se==="karaoke-spin"?Ye.animation="anim-rotate 1s infinite linear":se==="karaoke-glitch"?Ye.animation="anim-glitch 0.3s infinite linear":se==="karaoke-typewriter"?(Ye.animation="typewriter-reveal 0.5s steps(10, end) forwards",Ye.whiteSpace="nowrap",Ye.overflow="hidden",Ye.display="inline-block",Ye.verticalAlign="bottom"):se==="karaoke-fade"?Ye.animation="trans-fade-in 0.4s cubic-bezier(0.4, 0, 0.2, 1) forwards":se==="karaoke-slide"?Ye.animation="trans-slide-in 0.4s cubic-bezier(0.16, 1, 0.3, 1) forwards":se==="karaoke-drop"?Ye.animation="trans-drop-in 0.5s cubic-bezier(0.34, 1.56, 0.64, 1) forwards":se==="karaoke-lightspeed"?Ye.animation="trans-lightspeed-in 0.5s ease-out forwards":se==="karaoke-roll"?Ye.animation="trans-roll-in 0.5s ease-out forwards":se==="karaoke-zoom"?Ye.animation="trans-zoom-in 0.4s cubic-bezier(0.34, 1.56, 0.64, 1) forwards":se==="karaoke-elastic"?Ye.animation="trans-elastic-in 0.7s ease-out forwards":se==="karaoke-scale-rotate"?Ye.animation="trans-scale-rotate-in 0.5s ease-out forwards":se==="karaoke-flip"?Ye.animation="trans-flip-in 0.5s ease-out forwards":se==="karaoke-rotate-in"?Ye.animation="trans-rotate-in 0.5s ease-out forwards":se==="karaoke-spiral"?Ye.animation="trans-spiral-in 0.6s ease-out forwards":se==="karaoke-blur"?Ye.animation="trans-blur-in 0.4s ease-out forwards":se==="karaoke-shatter"?Ye.animation="trans-shatter-in 0.5s ease-out forwards":["karaoke-blue","karaoke-purple","karaoke-green","karaoke-pink","karaoke-cyan","karaoke-glow-blue","karaoke-glow-pink"].includes(se||"")&&(Ye.color=Qt,Ye.textShadow=`0 0 10px ${Qt}`,se?.includes("glow")&&(Ye.textShadow=`0 0 5px ${Qt}, 0 0 15px ${Qt}, 0 0 30px ${Qt}`))}const si=p.jsx("span",{className:"inline-block",style:Ye,children:Lt},vt);return fo?p.jsxs(Og.Fragment,{children:[si," "]},vt):si});else if(se==="karaoke"||se?.startsWith("karaoke-")){const Ft=M.highlightColor||"#fb923c",vt=M.highlightBackground||"#fb923c";ft.color=Ft,se==="karaoke-neon"&&(ft.textShadow=`0 0 10px ${Ft}, 0 0 20px ${Ft}`),se==="karaoke-scale"&&(ft.transform=(ft.transform||"")+" scale(1.1)"),se==="karaoke-underline"&&(ft.textDecoration="underline"),se==="karaoke-bounce"&&(ft.transform=(ft.transform||"")+" translateY(-5px)"),se==="karaoke-fill"&&(ft.backgroundColor=vt,ft.color="#000",ft.padding="4px 12px",ft.borderRadius="6px"),se==="karaoke-outline"&&(ft.color="transparent",ft.WebkitTextStroke=`2px ${Ft}`),se==="karaoke-shadow"&&(ft.textShadow="3px 3px 0 #000, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000"),se==="karaoke-gradient"&&(ft.background=`linear-gradient(90deg, ${Ft}, ${vt})`,ft.WebkitBackgroundClip="text",ft.WebkitTextFillColor="transparent"),["karaoke-pill","karaoke-box","karaoke-rounded"].includes(se)&&(ft.backgroundColor=vt,ft.color="#000",ft.padding="4px 16px",ft.borderRadius=se==="karaoke-pill"?"9999px":se==="karaoke-rounded"?"12px":"0"),se?.includes("glow")&&(ft.textShadow=`0 0 10px ${Ft}, 0 0 20px ${Ft}`)}else se==="scale"?ft.color=M.highlightColor||"#fb923c":M.highlightEffect==="background"&&(ft.backgroundColor=(M.highlightBackground||"#fb923c")+"4D",ft.padding="0 10px",ft.borderRadius="8px")}return p.jsx("p",{"data-lyric-active":dt?"true":"false",className:`${Pt} ${dt?mt:wt}`,onClick:()=>{dt&&(navigator.clipboard.writeText(Z.text),t.success("Lyric copied to clipboard",1500)),n.current&&!Se&&(n.current.currentTime=Z.time,P(Z.time))},children:p.jsx("span",{className:`inline-block ${dt&&M.textAnimation!=="none"&&M.textAnimation!=="typewriter"?`text-anim-${M.textAnimation}`:""}`,children:p.jsx("span",{style:ft,className:"inline-block",children:ni})})},Ne)}),p.jsx("div",{className:`transition-all duration-500 ${M.contentPosition==="center"?_e===lo.EDITOR||_t?"h-[25vh]":!yi&&!Lo?"h-[50vh]":"h-[40vh]":"h-0"}`})]}):p.jsx("div",{className:"text-center text-zinc-400/50 select-none pointer-events-none",children:!Ki&&!d&&et.length===0&&Me!=="none"&&p.jsxs("div",{className:"flex flex-col items-center gap-4 animate-pulse",children:[p.jsx($l,{size:64,className:"opacity-20"}),p.jsx("p",{children:"Load audio & lyrics to start"}),p.jsx("p",{className:"text-xs opacity-50",children:"Shortcuts: Space (Play), S (Stop), R (Repeat), H (Hold UI)"})]})})}),p.jsx("div",{className:`no-minimal-mode-toggle transition-all duration-500 ease-in-out overflow-hidden ${Lo?"max-h-60 opacity-100 translate-y-0":"max-h-0 opacity-0 translate-y-4"}`,children:p.jsx("div",{className:"bg-gradient-to-t from-black/60 via-black/30 to-transparent p-4 pb-6 lg:p-6 lg:pb-8",children:p.jsxs("div",{className:"max-w-7xl mx-auto space-y-4",children:[p.jsxs("div",{className:"flex items-center gap-3 group",children:[p.jsx("span",{className:"text-xs text-zinc-400 font-mono w-10 text-right",children:Ps(k)}),p.jsxs("div",{ref:ue,className:"flex-1 h-1 bg-zinc-700/50 rounded-full relative cursor-pointer group-hover:h-2 transition-all touch-none",onPointerDown:Z=>{Z.currentTarget.setPointerCapture(Z.pointerId),Xn(Z.clientX)},onPointerMove:Z=>{Z.buttons===1&&Xn(Z.clientX)},children:[p.jsx("div",{className:"absolute top-0 left-0 h-full bg-purple-500 rounded-full pointer-events-none",style:{width:`${k/J*100}%`}}),p.jsx("input",{type:"range",name:"progress",id:"progress-bar","aria-label":"Seek Progress",min:"0",max:J||0,value:k,onChange:pn,disabled:Se,className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer disabled:cursor-wait pointer-events-none"})]}),p.jsx("span",{className:"text-xs text-zinc-400 font-mono w-10",children:Ps(J)}),p.jsxs("div",{className:"flex items-center gap-2 pl-4",children:[p.jsx("button",{onClick:()=>X(!je),className:"text-zinc-400 hover:text-white",children:je||fe===0?p.jsx(jl,{size:16}):p.jsx(Zr,{size:16})}),p.jsxs("div",{ref:Ue,className:"w-16 h-1 bg-zinc-700/50 rounded-full relative overflow-hidden group/vol cursor-pointer touch-none",onPointerDown:Z=>{Z.currentTarget.setPointerCapture(Z.pointerId),Wt(Z.clientX)},onPointerMove:Z=>{Z.buttons===1&&Wt(Z.clientX)},children:[p.jsx("div",{className:"absolute top-0 left-0 h-full bg-zinc-300 group-hover/vol:bg-purple-400 transition-colors pointer-events-none",style:{width:`${je?0:fe*100}%`}}),p.jsx("input",{type:"range",name:"volume",id:"volume-control","aria-label":"Volume Control",min:"0",max:"1",step:"0.05",value:je?0:fe,onChange:wn,className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer pointer-events-none"})]})]})]}),p.jsxs("div",{className:"flex flex-wrap lg:grid lg:grid-cols-[1fr_auto_1fr] items-center justify-center gap-4",children:[p.jsxs("div",{className:"flex gap-1 justify-center lg:justify-start flex-wrap order-2 lg:order-none w-auto lg:w-full",children:[p.jsxs("label",{className:"p-2 rounded-lg hover:bg-white/10 text-zinc-400 hover:text-white cursor-pointer transition-colors",title:"Load Audio or video",children:[p.jsx($l,{size:18}),p.jsx("input",{type:"file",name:"audio-file",id:"audio-file",accept:"audio/*,video/*",className:"hidden",onChange:bn,disabled:Se})]}),p.jsxs("div",{className:"flex items-center gap-1",children:[p.jsxs("label",{className:`p-2 rounded-lg hover:bg-white/10 cursor-pointer transition-colors ${A.length>0?"text-purple-400":"text-zinc-400 hover:text-white"}`,title:"Load Lyrics (.lrc, .srt, .vtt, .ttml)",children:[p.jsx(Xf,{size:18}),p.jsx("input",{type:"file",name:"lyrics-file",id:"lyrics-file",accept:".lrc,.srt,.ttml,.xml,.vtt",className:"hidden",onChange:Rs,disabled:Se})]}),A.length>0&&p.jsx("button",{onClick:()=>E([]),className:"p-1 rounded-full text-zinc-500 hover:text-red-400 hover:bg-white/5 transition-colors",title:"Clear Lyrics",disabled:Se,children:p.jsx(Wo,{size:14})})]}),p.jsxs("div",{className:"flex items-center gap-1 bg-zinc-800/50 rounded-lg px-2 py-1 h-9",children:[p.jsxs("span",{className:"text-xs text-zinc-300 w-12 text-center font-mono select-none border-r border-white/10 pr-2 mr-1",children:[L>0?"+":"",L.toFixed(1),"s"]}),p.jsxs("div",{className:"flex flex-col -my-1 h-full justify-center",children:[p.jsx("button",{onClick:()=>D(Z=>parseFloat((Z+.1).toFixed(1))),className:"text-zinc-400 hover:text-white flex items-center justify-center h-3.5 w-4 hover:bg-white/10 rounded-sm transition-colors",title:"Increase Lyric Offset (+0.1s)",disabled:Se,children:p.jsx(x0,{size:12})}),p.jsx("button",{onClick:()=>D(Z=>parseFloat((Z-.1).toFixed(1))),className:"text-zinc-400 hover:text-white flex items-center justify-center h-3.5 w-4 hover:bg-white/10 rounded-sm transition-colors",title:"Decrease Lyric Offset (-0.1s)",disabled:Se,children:p.jsx(zu,{size:12})})]})]}),p.jsxs("div",{className:"flex items-center gap-1",children:[p.jsxs("label",{className:`p-2 rounded-lg hover:bg-white/10 cursor-pointer transition-colors ${rt?"text-purple-400":"text-zinc-400 hover:text-white"}`,title:rt?`Custom Font: ${rt}`:"Load Custom Font (.ttf, .otf, .woff)",children:[p.jsx(Qr,{size:18}),p.jsx("input",{type:"file",name:"font-file",id:"font-file",accept:".ttf,.otf,.woff,.woff2",className:"hidden",onChange:G,disabled:Se})]}),rt&&p.jsx("button",{onClick:()=>We(null),className:"p-1 rounded-full text-zinc-500 hover:text-red-400 hover:bg-white/5 transition-colors",title:"Reset Default Font",disabled:Se,children:p.jsx(Wo,{size:14})})]}),p.jsxs("div",{className:"flex items-center gap-1 bg-zinc-800/50 rounded-lg px-2 py-1 h-9",children:[p.jsxs("span",{className:"text-xs text-zinc-300 w-10 text-center font-mono select-none border-r border-white/10 pr-2 mr-1",children:[Math.round(M.fontSizeScale*100),"%"]}),p.jsxs("div",{className:"flex flex-col -my-1 h-full justify-center",children:[p.jsx("button",{onClick:()=>K(Z=>({...Z,fontSizeScale:Math.min(Z.fontSizeScale+.1,3)})),className:"text-zinc-400 hover:text-white flex items-center justify-center h-3.5 w-4 hover:bg-white/10 rounded-sm transition-colors",title:"Increase Font Size",disabled:Se,children:p.jsx(x0,{size:12})}),p.jsx("button",{onClick:()=>K(Z=>({...Z,fontSizeScale:Math.max(Z.fontSizeScale-.1,.1)})),className:"text-zinc-400 hover:text-white flex items-center justify-center h-3.5 w-4 hover:bg-white/10 rounded-sm transition-colors",title:"Decrease Font Size",disabled:Se,children:p.jsx(zu,{size:12})})]})]}),p.jsxs("div",{className:"relative group",children:[p.jsxs("select",{value:Me,onChange:Z=>{const Ne=Z.target.value;Pe(Ne);const dt=oh[Ne];if(dt){const Fe={fontFamily:"sans-serif",fontSizeScale:1,fontColor:"#ffffff",fontWeight:"bold",fontStyle:"normal",textCase:"none",textAlign:"center",contentPosition:"center",textDecoration:"none",textEffect:"preset",textAnimation:"none",highlightEffect:"karaoke",highlightColor:"#fb923c",highlightBackground:"#fb923c",useCustomHighlightColors:!1,lyricStyleTarget:"active-only",transitionEffect:"none"};K(lt=>({...lt,...Fe,...dt}))}},className:"appearance-none bg-zinc-800/50 border border-white/5 text-zinc-300 text-xs rounded-lg px-3 pr-8 h-9 w-24 focus:outline-none focus:border-purple-500 cursor-pointer",disabled:Se,title:"Select Visual Preset",name:"preset",id:"preset-select","aria-label":"Visual Preset",children:[p.jsx("option",{value:"custom",className:"bg-zinc-900 font-bold text-purple-400",children:"Custom ✨"}),p.jsx("option",{value:"default",className:"bg-zinc-900",children:"Default"}),p.jsx("option",{value:"large",className:"bg-zinc-900",children:"Big Text"}),p.jsx("option",{value:"large_upper",className:"bg-zinc-900",children:"Big Text (UP)"}),p.jsx("option",{value:"big_center",className:"bg-zinc-900",children:"Big Center"}),p.jsx("option",{value:"metal",className:"bg-zinc-900",children:"Metal"}),p.jsx("option",{value:"kids",className:"bg-zinc-900",children:"Kids"}),p.jsx("option",{value:"sad",className:"bg-zinc-900",children:"Sad"}),p.jsx("option",{value:"romantic",className:"bg-zinc-900",children:"Romantic"}),p.jsx("option",{value:"tech",className:"bg-zinc-900",children:"Tech"}),p.jsx("option",{value:"gothic",className:"bg-zinc-900",children:"Gothic"}),p.jsx("option",{value:"classic",className:"bg-zinc-900",children:"Classic Serif"}),p.jsx("option",{value:"monospace",className:"bg-zinc-900",children:"Monospace"}),p.jsx("option",{value:"testing_up",className:"bg-zinc-900",children:"Testing (UP)"}),p.jsx("option",{value:"testing",className:"bg-zinc-900",children:"Testing"}),p.jsx("option",{value:"one_line_up",className:"bg-zinc-900",children:"One Line (UP)"}),p.jsx("option",{value:"one_line",className:"bg-zinc-900",children:"One Line"}),p.jsx("option",{value:"slideshow",className:"bg-zinc-900",children:"Slideshow"}),p.jsx("option",{value:"just_video",className:"bg-zinc-900",children:"Just Video"}),p.jsx("option",{value:"subtitle",className:"bg-zinc-900",children:"Subtitle"}),p.jsx("option",{value:"none",className:"bg-zinc-900",children:"None"})]}),p.jsx("div",{className:"pointer-events-none absolute inset-y-0 right-0 flex items-center px-1 text-zinc-500",children:p.jsx("svg",{className:"fill-current h-3 w-3",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",children:p.jsx("path",{d:"M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z"})})})]})]}),p.jsxs("div",{className:"flex items-center gap-4 lg:gap-6 justify-center order-1 lg:order-none w-full lg:w-auto mb-2 lg:mb-0",children:[p.jsx("button",{className:"text-zinc-400 hover:text-white transition-colors disabled:opacity-50",onClick:xt,title:"Stop (S)",disabled:Se,children:p.jsx(b0,{size:20,fill:"currentColor"})}),p.jsx("button",{className:"text-zinc-400 hover:text-white transition-colors disabled:opacity-50",disabled:Se||et.length===0,onClick:pt,title:"Previous Song",children:p.jsx(LA,{size:24})}),p.jsx("button",{className:"text-zinc-400 hover:text-white transition-colors disabled:opacity-50",disabled:Se,onClick:()=>n.current&&(n.current.currentTime-=5),title:"Rewind 5s",children:p.jsx(TA,{size:20})}),p.jsx("button",{onClick:yt,disabled:Se,className:"w-14 h-14 flex items-center justify-center bg-white text-black rounded-full hover:scale-105 transition-transform shadow-lg shadow-purple-500/20 disabled:opacity-50 disabled:hover:scale-100",children:W?p.jsx(gT,{size:28,fill:"currentColor"}):p.jsx(y0,{size:28,fill:"currentColor",className:"ml-1"})}),p.jsx("button",{className:"text-zinc-400 hover:text-white transition-colors disabled:opacity-50",disabled:Se,onClick:()=>n.current&&(n.current.currentTime+=5),title:"Fast Forward 5s",children:p.jsx(HC,{size:20})}),p.jsx("button",{className:"text-zinc-400 hover:text-white transition-colors disabled:opacity-50",disabled:Se||et.length===0,onClick:ge,title:"Next Song",children:p.jsx(kA,{size:24})}),p.jsxs("button",{className:`transition-colors disabled:opacity-50 ${H!=="off"?"text-green-400 hover:text-green-300":"text-zinc-400 hover:text-white"}`,onClick:Tt,title:`Repeat: ${H==="off"?"Off":H==="one"?"One":H==="all"?"Play All (No Repeat)":"Loop All"} (R)`,disabled:Se,children:[H==="one"&&p.jsx(_A,{size:20}),H==="all_repeat"&&p.jsx(gb,{size:20}),H==="all"&&p.jsx(Jf,{size:20}),H==="off"&&p.jsx(gb,{size:20,className:"opacity-50"})]})]}),p.jsxs("div",{className:"flex items-center gap-1 justify-center lg:justify-end group flex-wrap order-3 lg:order-none w-auto lg:w-full",children:[p.jsxs("div",{className:"flex items-center gap-1",children:[p.jsx("button",{onClick:()=>K(Z=>({...Z,backgroundBlurStrength:Z.backgroundBlurStrength>0?0:12})),className:`bg-zinc-800/50 border border-white/5 text-[10px] font-mono rounded-lg px-2 h-9 transition-colors disabled:opacity-30 ${Je?"text-purple-400 border-purple-500/50":"text-zinc-300 hover:text-white"}`,title:`Background Blur: ${Je?"On":"Off"}`,disabled:Se,children:Je?"BLUR":"SHARP"}),p.jsx("button",{onClick:()=>K(Z=>({...Z,highlightEffect:Z.highlightEffect==="none"?"karaoke":"none"})),className:`p-2 rounded-full transition-all ${M.highlightEffect!=="none"?"bg-orange-500 text-white shadow-[0_0_15px_rgba(249,115,22,0.5)]":"hover:bg-zinc-800 text-zinc-400"}`,title:"Toggle Lyric Highlight",children:p.jsx(Qr,{size:20})}),p.jsx("button",{onClick:()=>U(Z=>Z==="1080p"?"720p":"1080p"),className:"bg-zinc-800/50 border border-white/5 text-[10px] font-mono text-zinc-300 hover:text-white rounded-lg px-2 h-9 transition-colors disabled:opacity-30",title:"Toggle Resolution (720p / 1080p)",disabled:Se,children:Ze}),p.jsx("button",{onClick:()=>at(Z=>Z==="16:9"?"9:16":Z==="9:16"?"3:4":Z==="3:4"?"1:1":Z==="1:1"?"1:2":Z==="1:2"?"2:1":Z==="2:1"?"2:3":Z==="2:3"?"3:2":"16:9"),className:"bg-zinc-800/50 border border-white/5 text-[10px] font-mono text-zinc-300 hover:text-white rounded-lg px-2 h-9 transition-colors disabled:opacity-30",title:"Toggle Aspect Ratio (16:9 / 9:16 / 3:4 / 1:1 / 1:2 / 2:1 / 2:3 / 3:2)",disabled:Se,children:Oe})]}),p.jsxs("div",{className:"relative group",children:[p.jsxs("select",{value:F,onChange:Z=>le(Z.target.value),className:"appearance-none bg-zinc-800/50 border border-white/5 text-zinc-300 text-xs rounded-lg px-3 pr-8 w-26 h-9 focus:outline-none focus:border-purple-500 cursor-pointer text-ellipsis overflow-hidden",disabled:Se,title:"Select Render Engine",name:"engine",id:"engine-select","aria-label":"Render Engine",children:[p.jsx("option",{value:"mediarecorder",className:"bg-zinc-900",children:"Realtime"}),p.jsx("option",{value:"webcodecs",className:"bg-zinc-900",children:"WebCodecs"}),p.jsx("option",{value:"ffmpeg",className:"bg-zinc-900",children:"FFMPEG"})]}),p.jsx("div",{className:"pointer-events-none absolute inset-y-0 right-0 flex items-center px-1 text-zinc-500",children:p.jsx("svg",{className:"fill-current h-3 w-3",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",children:p.jsx("path",{d:"M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z"})})})]}),p.jsxs("div",{className:"relative group",children:[p.jsxs("select",{value:st,onChange:Z=>it(Z.target.value),className:"appearance-none bg-zinc-800/50 border border-white/5 text-zinc-300 text-xs rounded-lg px-3 pr-8 w-18 h-9 focus:outline-none focus:border-purple-500 cursor-pointer",disabled:Se,title:"Select Quality (Bitrate)",name:"quality",id:"quality-select","aria-label":"Render Quality",children:[p.jsx("option",{value:"low",className:"bg-zinc-900",children:"Low"}),p.jsx("option",{value:"med",className:"bg-zinc-900",children:"Med"}),p.jsx("option",{value:"high",className:"bg-zinc-900",children:"High"})]}),p.jsx("div",{className:"pointer-events-none absolute inset-y-0 right-0 flex items-center px-1 text-zinc-500",children:p.jsx("svg",{className:"fill-current h-3 w-3",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",children:p.jsx("path",{d:"M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z"})})})]}),p.jsx("button",{onClick:Ji,disabled:Se||!d,className:"p-2 rounded-lg hover:bg-white/10 text-zinc-400 hover:text-white cursor-pointer transition-colors",title:`Export as Video (${F==="ffmpeg"?"FFmpeg":"MediaRecorder"})`,children:p.jsx(Ru,{size:18})})]})]})]})})}),_t?p.jsx("div",{className:"no-minimal-mode-toggle animate-slide-up border-t border-white/10 z-30 shrink-0 w-full max-w-[100vw] overflow-hidden",children:p.jsx(LU,{playlist:et,setPlaylist:Te,currentTrackIndex:Ke,setCurrentTrackIndex:Be,onPlayTrack:Ve,isPlaying:W,onTogglePlay:yt,currentTime:k,onSeek:Z=>{n.current&&!Se&&(n.current.currentTime=Z,P(Z))},onClearPlaylist:()=>{xt(),g(null),E([]),Be(-1),T({title:"No Audio Loaded",artist:"Select a file",coverUrl:null,backgroundType:"image"})},onRemoveTrack:Z=>{Z===Ke?(xt(),g(null),E([]),Be(-1),T({title:"No Audio Loaded",artist:"Select a file",coverUrl:null,backgroundType:"image"})):ZNe-1),Te(Ne=>{const dt=[...Ne];return dt.splice(Z,1),dt})},onClose:()=>Jt(!1)})}):_e===lo.EDITOR&&p.jsx("div",{className:"no-minimal-mode-toggle animate-slide-up border-t border-white/10 z-30 shrink-0 w-full max-w-[100vw] overflow-hidden",children:p.jsx(gR,{slides:w,setSlides:I,currentTime:k,duration:J||60,lyrics:A,onSeek:Z=>{n.current&&!Se&&(n.current.currentTime=Z,P(Z))},onClose:()=>ne(lo.PLAYER),renderConfig:M,setRenderConfig:K})})]}),Se&&p.jsxs("div",{className:"absolute inset-0 z-50 bg-black/90 flex flex-col items-center justify-center p-8 text-center space-y-6",children:[p.jsx("div",{className:F==="ffmpeg"?"animate-pulse":"animate-bounce",children:p.jsx(Ru,{size:48,className:F==="ffmpeg"?"text-orange-500":"text-purple-500"})}),p.jsxs("h2",{className:"text-2xl font-bold text-white",children:[F==="ffmpeg"?"FFmpeg Rendering":"Rendering Video"," (",Oe," ",Ze,")"]}),p.jsx("p",{className:"text-zinc-400 max-w-md",children:F==="ffmpeg"?p.jsxs(p.Fragment,{children:["Frame-by-frame capture using FFmpeg WASM.",p.jsx("br",{}),p.jsx("span",{className:"text-orange-400 font-medium",children:B||"Initializing..."}),p.jsx("br",{}),"This is faster than realtime - no audio playback needed."]}):p.jsxs(p.Fragment,{children:["Rendering in real-time using Canvas 2D engine.",p.jsx("br",{}),"The audio will play during capture.",p.jsx("br",{}),"Please keep this tab active for best performance."]})}),p.jsx("div",{className:"w-full max-w-md h-2 bg-zinc-800 rounded-full overflow-hidden",children:p.jsx("div",{className:`h-full transition-all duration-300 ease-linear ${F==="ffmpeg"?"bg-orange-500":"bg-purple-500"}`,style:{width:`${ye}%`}})}),p.jsxs("p",{className:"text-sm font-mono text-zinc-500",children:[Math.round(ye),"%"]}),p.jsxs("button",{onClick:xo,className:"mt-4 px-6 py-2 bg-red-500/20 text-red-400 hover:bg-red-500/30 hover:text-red-300 rounded-full transition-colors flex items-center gap-2 border border-red-500/50",children:[p.jsx(b0,{size:16,fill:"currentColor"}),"Abort Rendering"]})]}),Y&&p.jsx(VU,{config:M,setConfig:K,preset:Me,setPreset:Pe,onClose:()=>me(!1),isPlaylistMode:_t,hasPlaylist:et.length>0,onRender:Ji,customFontName:rt,onFontUpload:G,onClearCustomFont:()=>{We(null),K(Z=>({...Z,fontFamily:"ui-sans-serif, system-ui, sans-serif"}))},customChannelFontName:gt,onChannelFontUpload:be,onClearChannelCustomFont:()=>{qe(null),K(Z=>({...Z,channelInfoFontFamily:void 0}))},customInfoFontName:q,onInfoFontUpload:He,onClearInfoCustomFont:()=>{C(null),K(Z=>({...Z,infoFontFamily:void 0}))},resolution:Ze,setResolution:U,aspectRatio:Oe,setAspectRatio:at,renderCodec:te,setRenderCodec:ae,supportedCodecs:ht,renderQuality:st,setRenderQuality:it,renderFps:Re,setRenderFps:De,renderEngine:F,setRenderEngine:le,ffmpegCodec:z,setFfmpegCodec:j}),ee&&p.jsx("div",{className:"fixed inset-0 z-50 bg-black/80 backdrop-blur-sm flex items-center justify-center p-4 animate-in fade-in duration-200",onClick:()=>$e(!1),children:p.jsxs("div",{className:"no-minimal-mode-toggle bg-zinc-900 border border-white/10 rounded-2xl p-6 max-w-2xl w-full max-h-[80vh] overflow-y-auto shadow-2xl relative",onClick:Z=>Z.stopPropagation(),children:[p.jsx("button",{onClick:()=>$e(!1),className:"absolute top-4 right-4 p-2 rounded-full hover:bg-white/10 text-zinc-400 hover:text-white transition-colors",children:p.jsx(Wo,{size:20})}),p.jsxs("h2",{className:"text-2xl font-bold text-white mb-6 flex items-center gap-2",children:[p.jsx(Yf,{className:"text-purple-500"}),"Keyboard Shortcuts"]}),p.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-x-12 gap-y-6",children:[p.jsxs("div",{className:"space-y-4",children:[p.jsx("h3",{className:"text-sm font-bold text-zinc-500 uppercase tracking-wider",children:"Playback"}),p.jsxs("div",{className:"space-y-2",children:[p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Play / Pause"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"Space"})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Stop"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"S"})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Rewind 5s"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"←"})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Forward 5s"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"→"})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Repeat Mode"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"R"})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Mute"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"M"})]})]}),p.jsx("h3",{className:"text-sm font-bold text-zinc-500 uppercase tracking-wider mt-6",children:"Interface"}),p.jsxs("div",{className:"space-y-2",children:[p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Fullscreen"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"F"})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Minimal Mode"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"O"})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Hold UI (No Auto-Hide)"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"H"})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Toggle Header Info"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"I"})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Toggle Shortcut Info"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"Y"})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Toggle Player"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"P"})]})]})]}),p.jsxs("div",{className:"space-y-4",children:[p.jsx("h3",{className:"text-sm font-bold text-zinc-500 uppercase tracking-wider",children:"Editor & Styles"}),p.jsxs("div",{className:"space-y-2",children:[p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Toggle Timeline"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"T"})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Toggle Playlist"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"L"})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Render Settings"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"D"})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Export Video"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"Ctrl+Shift+E"})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Font Size"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"+ / -"})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Cycle Visual Preset"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"J"})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Cycle Highight Effect"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"Z"})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Toggle Highlight"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"X"})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Cycle Text Case"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"C"})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Cycle Lyric Mode"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"G"})]})]}),p.jsx("h3",{className:"text-sm font-bold text-zinc-500 uppercase tracking-wider mt-6",children:"Mouse & Touch"}),p.jsxs("div",{className:"space-y-2",children:[p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Toggle Minimal Mode"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"Double Click / Tap"})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Seek to Lyric"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"Click Line"})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{className:"text-zinc-300",children:"Copy Active Lyric"})," ",p.jsx("span",{className:"font-mono text-purple-400 bg-white/5 px-2 py-0.5 rounded",children:"Click Active Line"})]})]})]})]}),p.jsx("div",{className:"mt-8 pt-6 border-t border-white/5 text-center",children:p.jsx("p",{className:"text-zinc-500 text-sm",children:"Shortcuts are disabled during video rendering."})})]})})]})}const fw=document.getElementById("root");if(!fw)throw new Error("Could not find root element to mount to");const BB=dC.createRoot(fw);BB.render(p.jsx(Og.StrictMode,{children:p.jsx(dR,{children:p.jsx(OB,{})})}));export{VB as c,fT as g};