diff --git "a/assets/index-DRoVJsBw.js" "b/assets/index-DRoVJsBw.js" deleted file mode 100644--- "a/assets/index-DRoVJsBw.js" +++ /dev/null @@ -1,4044 +0,0 @@ -(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 GB=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function pT(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var wm={exports:{}},su={};var tb;function iC(){if(tb)return su;tb=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 nb;function oC(){return nb||(nb=1,wm.exports=iC()),wm.exports}var p=oC(),Mm={exports:{}},en={};var ib;function sC(){if(ib)return en;ib=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($,be,Fe){this.props=$,this.context=be,this.refs=E,this.updater=Fe||T}w.prototype.isReactComponent={},w.prototype.setState=function($,be){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,$,be,"setState")},w.prototype.forceUpdate=function($){this.updater.enqueueForceUpdate(this,$,"forceUpdate")};function I(){}I.prototype=w.prototype;function L($,be,Fe){this.props=$,this.context=be,this.refs=E,this.updater=Fe||T}var D=L.prototype=new I;D.constructor=L,A(D,w.prototype),D.isPureReactComponent=!0;var W=Array.isArray;function H(){}var V={H:null,A:null,T:null,S:null},Z=Object.prototype.hasOwnProperty;function k($,be,Fe){var oe=Fe.ref;return{$$typeof:t,type:$,key:be,ref:oe!==void 0?oe:null,props:Fe}}function P($,be){return k($.type,be,$.props)}function Q($){return typeof $=="object"&&$!==null&&$.$$typeof===t}function ue($){var be={"=":"=0",":":"=2"};return"$"+$.replace(/[=:]/g,function(Fe){return be[Fe]})}var se=/\/+/g;function Te($,be){return typeof $=="object"&&$!==null&&$.key!=null?ue(""+$.key):be.toString(36)}function $e($){switch($.status){case"fulfilled":return $.value;case"rejected":throw $.reason;default:switch(typeof $.status=="string"?$.then(H,H):($.status="pending",$.then(function(be){$.status==="pending"&&($.status="fulfilled",$.value=be)},function(be){$.status==="pending"&&($.status="rejected",$.reason=be)})),$.status){case"fulfilled":return $.value;case"rejected":throw $.reason}}throw $}function X($,be,Fe,oe,Ae){var Qe=typeof $;(Qe==="undefined"||Qe==="boolean")&&($=null);var we=!1;if($===null)we=!0;else switch(Qe){case"bigint":case"string":case"number":we=!0;break;case"object":switch($.$$typeof){case t:case e:we=!0;break;case g:return we=$._init,X(we($._payload),be,Fe,oe,Ae)}}if(we)return Ae=Ae($),we=oe===""?"."+Te($,0):oe,W(Ae)?(Fe="",we!=null&&(Fe=we.replace(se,"$&/")+"/"),X(Ae,be,Fe,"",function(xe){return xe})):Ae!=null&&(Q(Ae)&&(Ae=P(Ae,Fe+(Ae.key==null||$&&$.key===Ae.key?"":(""+Ae.key).replace(se,"$&/")+"/")+we)),be.push(Ae)),1;we=0;var N=oe===""?".":oe+":";if(W($))for(var ye=0;ye<$.length;ye++)oe=$[ye],Qe=N+Te(oe,ye),we+=X(oe,be,Fe,Qe,Ae);else if(ye=S($),typeof ye=="function")for($=ye.call($),ye=0;!(oe=$.next()).done;)oe=oe.value,Qe=N+Te(oe,ye++),we+=X(oe,be,Fe,Qe,Ae);else if(Qe==="object"){if(typeof $.then=="function")return X($e($),be,Fe,oe,Ae);throw be=String($),Error("Objects are not valid as a React child (found: "+(be==="[object Object]"?"object with keys {"+Object.keys($).join(", ")+"}":be)+"). If you meant to render a collection of children, use an array instead.")}return we}function ve($,be,Fe){if($==null)return $;var oe=[],Ae=0;return X($,oe,"","",function(Qe){return be.call(Fe,Qe,Ae++)}),oe}function ie($){if($._status===-1){var be=$._result;be=be(),be.then(function(Fe){($._status===0||$._status===-1)&&($._status=1,$._result=Fe)},function(Fe){($._status===0||$._status===-1)&&($._status=2,$._result=Fe)}),$._status===-1&&($._status=0,$._result=be)}if($._status===1)return $._result.default;throw $._result}var nt=typeof reportError=="function"?reportError:function($){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var be=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof $=="object"&&$!==null&&typeof $.message=="string"?String($.message):String($),error:$});if(!window.dispatchEvent(be))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",$);return}console.error($)},Ce={map:ve,forEach:function($,be,Fe){ve($,function(){be.apply(this,arguments)},Fe)},count:function($){var be=0;return ve($,function(){be++}),be},toArray:function($){return ve($,function(be){return be})||[]},only:function($){if(!Q($))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=V,en.__COMPILER_RUNTIME={__proto__:null,c:function($){return V.H.useMemoCache($)}},en.cache=function($){return function(){return $.apply(null,arguments)}},en.cacheSignal=function(){return null},en.cloneElement=function($,be,Fe){if($==null)throw Error("The argument must be a React element, but you passed "+$+".");var oe=A({},$.props),Ae=$.key;if(be!=null)for(Qe in be.key!==void 0&&(Ae=""+be.key),be)!Z.call(be,Qe)||Qe==="key"||Qe==="__self"||Qe==="__source"||Qe==="ref"&&be.ref===void 0||(oe[Qe]=be[Qe]);var Qe=arguments.length-2;if(Qe===1)oe.children=Fe;else if(1>>1,Ce=X[nt];if(0>>1;nt<$;){var be=2*(nt+1)-1,Fe=X[be],oe=be+1,Ae=X[oe];if(0>r(Fe,ie))oer(Ae,Fe)?(X[nt]=Ae,X[oe]=ie,nt=oe):(X[nt]=Fe,X[be]=ie,nt=be);else if(oer(Ae,ie))X[nt]=Ae,X[oe]=ie,nt=oe;else break e}}return ve}function r(X,ve){var ie=X.sortIndex-ve.sortIndex;return ie!==0?ie:X.id-ve.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 ve=n(d);ve!==null;){if(ve.callback===null)i(d);else if(ve.startTime<=X)i(d),ve.sortIndex=ve.expirationTime,e(h,ve);else break;ve=n(d)}}function W(X){if(A=!1,D(X),!T)if(n(h)!==null)T=!0,H||(H=!0,ue());else{var ve=n(d);ve!==null&&$e(W,ve.startTime-X)}}var H=!1,V=-1,Z=5,k=-1;function P(){return E?!0:!(t.unstable_now()-kX&&P());){var nt=v.callback;if(typeof nt=="function"){v.callback=null,y=v.priorityLevel;var Ce=nt(v.expirationTime<=X);if(X=t.unstable_now(),typeof Ce=="function"){v.callback=Ce,D(X),ve=!0;break t}v===n(h)&&i(h),D(X)}else i(h);v=n(h)}if(v!==null)ve=!0;else{var $=n(d);$!==null&&$e(W,$.startTime-X),ve=!1}}break e}finally{v=null,y=ie,S=!1}ve=void 0}}finally{ve?ue():H=!1}}}var ue;if(typeof L=="function")ue=function(){L(Q)};else if(typeof MessageChannel<"u"){var se=new MessageChannel,Te=se.port2;se.port1.onmessage=Q,ue=function(){Te.postMessage(null)}}else ue=function(){w(Q,0)};function $e(X,ve){V=w(function(){X(t.unstable_now())},ve)}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||125nt?(X.sortIndex=ie,e(d,X),n(h)===null&&X===n(d)&&(A?(I(V),V=-1):A=!0,$e(W,ie-nt))):(X.sortIndex=Ce,e(h,X),T||S||(T=!0,H||(H=!0,ue()))),X},t.unstable_shouldYield=P,t.unstable_wrapCallback=function(X){var ve=y;return function(){var ie=y;y=ve;try{return X.apply(this,arguments)}finally{y=ie}}}})(Rm)),Rm}var rb;function aC(){return rb||(rb=1,Am.exports=rC()),Am.exports}var Nm={exports:{}},po={};var ab;function lC(){if(ab)return po;ab=1;var t=Bg();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(),Nm.exports=lC(),Nm.exports}var cb;function uC(){if(cb)return ru;cb=1;var t=aC(),e=Bg(),n=cC();function i(o){var s="https://react.dev/errors/"+o;if(1Ce||(o.current=nt[Ce],nt[Ce]=null,Ce--)}function Fe(o,s){Ce++,nt[Ce]=o.current,o.current=s}var oe=$(null),Ae=$(null),Qe=$(null),we=$(null);function N(o,s){switch(Fe(Qe,s),Fe(Ae,o),Fe(oe,null),s.nodeType){case 9:case 11:o=(o=s.documentElement)&&(o=o.namespaceURI)?E_(o):0;break;default:if(o=s.tagName,s=s.namespaceURI)s=E_(s),o=w_(s,o);else switch(o){case"svg":o=1;break;case"math":o=2;break;default:o=0}}be(oe),Fe(oe,o)}function ye(){be(oe),be(Ae),be(Qe)}function xe(o){o.memoizedState!==null&&Fe(we,o);var s=oe.current,l=w_(s,o.type);s!==l&&(Fe(Ae,o),Fe(oe,l))}function Le(o){Ae.current===o&&(be(oe),be(Ae)),we.current===o&&(be(we),tu._currentValue=ie)}var st,tt;function U(o){if(st===void 0)try{throw Error()}catch(l){var s=l.stack.trim().match(/\n( *(at )?)/);st=s&&s[1]||"",tt=-1)":-1_||ne[f]!==Pe[_]){var ot=` -`+ne[f].replace(" at new "," at ");return o.displayName&&ot.includes("")&&(ot=ot.replace("",o.displayName)),ot}while(1<=f&&0<=_);break}}}finally{Ee=!1,Error.prepareStackTrace=l}return(l=o?o.displayName||o.name:"")?U(l):""}function lt(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 Oe(o.type,!1);case 11:return Oe(o.type.render,!1);case 1:return Oe(o.type,!0);case 31:return U("Activity");default:return""}}function We(o){try{var s="",l=null;do s+=lt(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,le=t.unstable_now,Ne=t.unstable_getCurrentPriorityLevel,De=t.unstable_ImmediatePriority,rt=t.unstable_UserBlockingPriority,it=t.unstable_NormalPriority,F=t.unstable_LowPriority,ce=t.unstable_IdlePriority,z=t.log,j=t.unstable_setDisableYieldValue,B=null,ae=null;function Y(o){if(typeof z=="function"&&j(o),ae&&typeof ae.setStrictMode=="function")try{ae.setStrictMode(B,o)}catch{}}var me=Math.clz32?Math.clz32:M,ee=Math.log,Xe=Math.LN2;function M(o){return o>>>=0,o===0?32:31-(ee(o)/Xe|0)|0}var J=256,fe=262144,de=4194304;function ke(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?_=ke(f):(R&=O,R!==0?_=ke(R):l||(l=O&~o,l!==0&&(_=ke(l))))):(O=f&~b,O!==0?_=ke(O):R!==0?_=ke(R):l||(l=f&~o,l!==0&&(_=ke(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 Se(){var o=de;return de<<=1,(de&62914560)===0&&(de=4194304),o}function Ke(o){for(var s=[],l=0;31>l;l++)s.push(o);return s}function Ve(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,ne=o.expirationTimes,Pe=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(re)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),Iv=" ",Dv=!1;function Lv(o,s){switch(o){case"keyup":return ww.indexOf(s.keyCode)!==-1;case"keydown":return s.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Uv(o){return o=o.detail,typeof o=="object"&&"data"in o?o.data:null}var Qa=!1;function Cw(o,s){switch(o){case"compositionend":return Uv(s);case"keypress":return s.which!==32?null:(Dv=!0,Iv);case"textInput":return o=s.data,o===Iv&&Dv?null:o;default:return null}}function Aw(o,s){if(Qa)return o==="compositionend"||!Ih&&Lv(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=Hv(l)}}function jv(o,s){return o&&s?o===s?!0:o&&o.nodeType===3?!1:s&&s.nodeType===3?jv(o,s.parentNode):"contains"in o?o.contains(s):o.compareDocumentPosition?!!(o.compareDocumentPosition(s)&16):!1:!1}function qv(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 Uh(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 zw=re&&"documentMode"in document&&11>=document.documentMode,el=null,kh=null,Mc=null,zh=!1;function Wv(o,s,l){var f=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;zh||el==null||el!==xo(f)||(f=el,"selectionStart"in f&&Uh(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(kh,"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=je(Me,Ut,ze[rn],ct);if(Ln===null){Ut===null&&(Ut=yn);break}o&&Ut&&Ln.alternate===null&&s(Me,Ut),he=b(Ln,he,rn),Dn===null?Ot=Ln:Dn.sibling=Ln,Dn=Ln,Ut=yn}if(rn===ze.length)return l(Me,Ut),Sn&&$s(Me,rn),Ot;if(Ut===null){for(;rnrn?(yn=Ut,Ut=null):yn=Ut.sibling;var jr=je(Me,Ut,Ln.value,ct);if(jr===null){Ut===null&&(Ut=yn);break}o&&Ut&&jr.alternate===null&&s(Me,Ut),he=b(jr,he,rn),Dn===null?Ot=jr:Dn.sibling=jr,Dn=jr,Ut=yn}if(Ln.done)return l(Me,Ut),Sn&&$s(Me,rn),Ot;if(Ut===null){for(;!Ln.done;rn++,Ln=ze.next())Ln=ut(Me,Ln.value,ct),Ln!==null&&(he=b(Ln,he,rn),Dn===null?Ot=Ln:Dn.sibling=Ln,Dn=Ln);return Sn&&$s(Me,rn),Ot}for(Ut=f(Ut);!Ln.done;rn++,Ln=ze.next())Ln=Ze(Ut,Me,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(nC){return s(Me,nC)}),Sn&&$s(Me,rn),Ot}function Zn(Me,he,ze,ct){if(typeof ze=="object"&&ze!==null&&ze.type===A&&ze.key===null&&(ze=ze.props.children),typeof ze=="object"&&ze!==null){switch(ze.$$typeof){case S:e:{for(var Ot=ze.key;he!==null;){if(he.key===Ot){if(Ot=ze.type,Ot===A){if(he.tag===7){l(Me,he.sibling),ct=_(he,ze.props.children),ct.return=Me,Me=ct;break e}}else if(he.elementType===Ot||typeof Ot=="object"&&Ot!==null&&Ot.$$typeof===Z&&ga(Ot)===he.type){l(Me,he.sibling),ct=_(he,ze.props),Dc(ct,ze),ct.return=Me,Me=ct;break e}l(Me,he);break}else s(Me,he);he=he.sibling}ze.type===A?(ct=da(ze.props.children,Me.mode,ct,ze.key),ct.return=Me,Me=ct):(ct=Ju(ze.type,ze.key,ze.props,null,Me.mode,ct),Dc(ct,ze),ct.return=Me,Me=ct)}return R(Me);case T:e:{for(Ot=ze.key;he!==null;){if(he.key===Ot)if(he.tag===4&&he.stateNode.containerInfo===ze.containerInfo&&he.stateNode.implementation===ze.implementation){l(Me,he.sibling),ct=_(he,ze.children||[]),ct.return=Me,Me=ct;break e}else{l(Me,he);break}else s(Me,he);he=he.sibling}ct=Gh(ze,Me.mode,ct),ct.return=Me,Me=ct}return R(Me);case Z:return ze=ga(ze),Zn(Me,he,ze,ct)}if($e(ze))return Nt(Me,he,ze,ct);if(ue(ze)){if(Ot=ue(ze),typeof Ot!="function")throw Error(i(150));return ze=Ot.call(ze),Gt(Me,he,ze,ct)}if(typeof ze.then=="function")return Zn(Me,he,id(ze),ct);if(ze.$$typeof===L)return Zn(Me,he,Qu(Me,ze),ct);od(Me,ze)}return typeof ze=="string"&&ze!==""||typeof ze=="number"||typeof ze=="bigint"?(ze=""+ze,he!==null&&he.tag===6?(l(Me,he.sibling),ct=_(he,ze),ct.return=Me,Me=ct):(l(Me,he),ct=Hh(ze,Me.mode,ct),ct.return=Me,Me=ct),R(Me)):l(Me,he)}return function(Me,he,ze,ct){try{Ic=0;var Ot=Zn(Me,he,ze,ct);return dl=null,Ot}catch(Ut){if(Ut===ul||Ut===td)throw Ut;var Dn=zo(29,Ut,null,Me.mode);return Dn.lanes=ct,Dn.return=Me,Dn}}}var xa=mx(!0),gx=mx(!1),Cr=!1;function tp(o){o.updateQueue={baseState:o.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function np(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),Qv(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 ip(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 op=!1;function Uc(){if(op){var o=cl;if(o!==null)throw o}}function kc(o,s,l,f){op=!1;var _=o.updateQueue;Cr=!1;var b=_.firstBaseUpdate,R=_.lastBaseUpdate,O=_.shared.pending;if(O!==null){_.shared.pending=null;var ne=O,Pe=ne.next;ne.next=null,R===null?b=Pe:R.next=Pe,R=ne;var ot=o.alternate;ot!==null&&(ot=ot.updateQueue,O=ot.lastBaseUpdate,O!==R&&(O===null?ot.firstBaseUpdate=Pe:O.next=Pe,ot.lastBaseUpdate=ne))}if(b!==null){var ut=_.baseState;R=0,ot=Pe=ne=null,O=b;do{var je=O.lane&-536870913,Ze=je!==O.lane;if(Ze?(xn&je)===je:(f&je)===je){je!==0&&je===ll&&(op=!0),ot!==null&&(ot=ot.next={lane:0,tag:O.tag,payload:O.payload,callback:null,next:null});e:{var Nt=o,Gt=O;je=s;var Zn=l;switch(Gt.tag){case 1:if(Nt=Gt.payload,typeof Nt=="function"){ut=Nt.call(Zn,ut,je);break e}ut=Nt;break e;case 3:Nt.flags=Nt.flags&-65537|128;case 0:if(Nt=Gt.payload,je=typeof Nt=="function"?Nt.call(Zn,ut,je):Nt,je==null)break e;ut=v({},ut,je);break e;case 2:Cr=!0}}je=O.callback,je!==null&&(o.flags|=64,Ze&&(o.flags|=8192),Ze=_.callbacks,Ze===null?_.callbacks=[je]:Ze.push(je))}else Ze={lane:je,tag:O.tag,payload:O.payload,callback:O.callback,next:null},ot===null?(Pe=ot=Ze,ne=ut):ot=ot.next=Ze,R|=je;if(O=O.next,O===null){if(O=_.shared.pending,O===null)break;Ze=O,O=Ze.next,Ze.next=null,_.lastBaseUpdate=Ze,_.shared.pending=null}}while(!0);ot===null&&(ne=ut),_.baseState=ne,_.firstBaseUpdate=Pe,_.lastBaseUpdate=ot,b===null&&(_.shared.lanes=0),Ur|=R,o.lanes=R,o.memoizedState=ut}}function vx(o,s){if(typeof o!="function")throw Error(i(191,o));o.call(s)}function xx(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,Tp(o,!1,s,l);try{var ne=_(),Pe=X.S;if(Pe!==null&&Pe(O,ne),ne!==null&&typeof ne=="object"&&typeof ne.then=="function"){var ot=qw(ne,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{ve.p=b,R!==null&&O.types!==null&&(R.types=O.types),X.T=R}}function Kw(){}function bp(o,s,l,f){if(o.tag!==5)throw Error(i(476));var _=Jx(o).queue;Yx(o,_,s,ie,l===null?Kw:function(){return Kx(o),l(f)})}function Jx(o){var s=o.memoizedState;if(s!==null)return s;s={memoizedState:ie,baseState:ie,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ks,lastRenderedState:ie},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 Kx(o){var s=Jx(o);s.next===null&&(s=o.alternate.memoizedState),Fc(o,s.next.queue,{},Vo())}function Sp(){return so(tu)}function Zx(){return Ri().memoizedState}function Qx(){return Ri().memoizedState}function Zw(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:Kh()},o.payload=s;return}s=s.return}}function Qw(o,s,l){var f=Vo();l={lane:f,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},pd(o)?ty(s,l):(l=Bh(o,s,l,f),l!==null&&(Ro(l,o,f),ny(l,s,f)))}function ey(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))ty(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=Bh(o,s,_,f),l!==null)return Ro(l,o,f),ny(l,s,f),!0}return!1}function Tp(o,s,l,f){if(f={lane:2,revertLane:tm(),gesture:null,action:f,hasEagerState:!1,eagerState:null,next:null},pd(o)){if(s)throw Error(i(479))}else s=Bh(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 ty(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 ny(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 iy={readContext:so,use:ud,useCallback:function(o,s){return _o().memoizedState=[o,s===void 0?null:s],o},useContext:so,useEffect:Bx,useImperativeHandle:function(o,s,l){l=l!=null?l.concat([o]):null,fd(4194308,4,jx.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=Qw.bind(null,nn,o),[f.memoizedState,o]},useRef:function(o){var s=_o();return o={current:o},s.memoizedState=o},useState:function(o){o=gp(o);var s=o.queue,l=ey.bind(null,nn,s);return s.dispatch=l,[o.memoizedState,l]},useDebugValue:yp,useDeferredValue:function(o,s){var l=_o();return _p(l,o,s)},useTransition:function(){var o=gp(!1);return o=Yx.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||Ex(f,s,l)}_.memoizedState=l;var b={value:l,getSnapshot:s};return _.queue=b,Bx(Mx.bind(null,f,b,o),[o]),f.flags|=2048,ml(9,{destroy:void 0},wx.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),Pp(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=Qe.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||S_(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=$h(),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 _=$h(),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&&sm(s.stateNode.containerInfo),ai(s),null;case 10:return Ys(s.type),ai(s),null;case 19:if(be(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;)ex(l,o),l=l.sibling;return Fe(Ai,Ai.current&1|2),Sn&&$s(s,f.treeForkCount),s.child}o=o.sibling}f.tail!==null&&le()>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*le()-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=le(),o.sibling=null,l=Ai.current,Fe(Ai,_?l&1|2:l&1),Sn&&$s(s,f.treeForkCount),o):(ai(s),null);case 22:case 23:return Fo(s),rp(),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&&be(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 oM(o,s){switch(qh(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 Le(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 be(Ai),null;case 4:return ye(),null;case 10:return Ys(s.type),null;case 22:case 23:return Fo(s),rp(),o!==null&&be(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 Cy(o,s){switch(qh(s),s.tag){case 3:Ys(zi),ye();break;case 26:case 27:case 5:Le(s);break;case 4:ye();break;case 31:s.memoizedState!==null&&Fo(s);break;case 13:Fo(s);break;case 19:be(Ai);break;case 10:Ys(s.type);break;case 22:case 23:Fo(s),rp(),o!==null&&be(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 ne=l,Pe=O;try{Pe()}catch(ot){Wn(_,ne,ot)}}}f=f.next}while(f!==b)}}catch(ot){Wn(s,s.return,ot)}}function Ay(o){var s=o.updateQueue;if(s!==null){var l=o.stateNode;try{xx(s,l)}catch(f){Wn(o,o.return,f)}}}function Ry(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 Ny(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 Fp(o,s,l){try{var f=o.stateNode;MM(f,o.type,l,s),f[fi]=s}catch(_){Wn(o,o.return,_)}}function Iy(o){return o.tag===5||o.tag===3||o.tag===26||o.tag===27&&Or(o.type)||o.tag===4}function Op(o){e:for(;;){for(;o.sibling===null;){if(o.return===null||Iy(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 Bp(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(Bp(o,s,l),o=o.sibling;o!==null;)Bp(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 Dy(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,Vp=!1,Ly=typeof WeakSet=="function"?WeakSet:Set,Zi=null;function sM(o,s){if(o=o.containerInfo,lm=Vd,o=qv(o),Uh(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,ne=-1,Pe=0,ot=0,ut=o,je=null;t:for(;;){for(var Ze;ut!==l||_!==0&&ut.nodeType!==3||(O=R+_),ut!==b||f!==0&&ut.nodeType!==3||(ne=R+f),ut.nodeType===3&&(R+=ut.nodeValue.length),(Ze=ut.firstChild)!==null;)je=ut,ut=Ze;for(;;){if(ut===o)break t;if(je===l&&++Pe===_&&(O=R),je===b&&++ot===f&&(ne=R),(Ze=ut.nextSibling)!==null)break;ut=je,je=ut.parentNode}ut=Ze}l=O===-1||ne===-1?null:{start:O,end:ne}}else l=null}l=l||{start:0,end:0}}else l=null;for(cm={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=O_("link","href",_).get(f+(l.href||""));if(R){for(var O=0;OZn&&(R=Zn,Zn=Gt,Gt=R);var Me=Gv(O,Gt),he=Gv(O,Zn);if(Me&&he&&(Ze.rangeCount!==1||Ze.anchorNode!==Me.node||Ze.anchorOffset!==Me.offset||Ze.focusNode!==he.node||Ze.focusOffset!==he.offset)){var ze=ut.createRange();ze.setStart(Me.node,Me.offset),Ze.removeAllRanges(),Gt>Zn?(Ze.addRange(ze),Ze.extend(he.node,he.offset)):(ze.setEnd(he.node,he.offset),Ze.addRange(ze))}}}}for(ut=[],Ze=O;Ze=Ze.parentNode;)Ze.nodeType===1&&ut.push({element:Ze,left:Ze.scrollLeft,top:Ze.scrollTop});for(typeof O.focus=="function"&&O.focus(),O=0;Ol?32:l,X.T=null,l=Xp,Xp=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,jy(b.current),Vy(b,b.current,R,l),Fn=O,Yc(0,!1),ae&&typeof ae.onPostCommitFiberRoot=="function")try{ae.onPostCommitFiberRoot(B,b)}catch{}return!0}finally{ve.p=_,X.T=f,l_(o,s)}}function u_(o,s,l){s=es(l,s),s=Cp(o.stateNode,s,2),o=Rr(o,s,2),o!==null&&(Ve(o,2),ks(o))}function Wn(o,s,l){if(o.tag===3)u_(o,o,l);else for(;s!==null;){if(s.tag===3){u_(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=dy(2),f=Rr(s,l,2),f!==null&&(fy(l,f,s,o),Ve(f,2),ks(f));break}}s=s.return}}function Zp(o,s,l){var f=o.pingCache;if(f===null){f=o.pingCache=new lM;var _=new Set;f.set(s,_)}else _=f.get(s),_===void 0&&(_=new Set,f.set(s,_));_.has(l)||(jp=!0,_.add(l),o=hM.bind(null,o,s,l),s.then(o,o))}function hM(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>le()-Td?(Fn&2)===0&&bl(o,0):qp|=l,yl===xn&&(yl=0)),ks(o)}function d_(o,s){s===0&&(s=Se()),o=ua(o,s),o!==null&&(Ve(o,s),ks(o))}function pM(o){var s=o.memoizedState,l=0;s!==null&&(l=s.retryLane),d_(o,l)}function mM(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),d_(o,l)}function gM(o,s){return qe(o,s)}var Nd=null,Tl=null,Qp=!1,Id=!1,em=!1,Fr=0;function ks(o){o!==Tl&&o.next===null&&(Tl===null?Nd=Tl=o:Tl=Tl.next=o),Id=!0,Qp||(Qp=!0,xM())}function Yc(o,s){if(!em&&Id){em=!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,m_(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,m_(f,b));f=f.next}while(l);em=!1}}function vM(){f_()}function f_(){Id=Qp=!1;var o=0;Fr!==0&&AM()&&(o=Fr);for(var s=le(),l=null,f=Nd;f!==null;){var _=f.next,b=h_(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 h_(o,s){for(var l=o.suspendedLanes,f=o.pingedLanes,_=o.expirationTimes,b=o.pendingLanes&-62914561;0O)break;var ot=ne.transferSize,ut=ne.initiatorType;ot&&T_(ut)&&(ne=ne.responseEnd,R+=ot*(ne"u"?null:document;function k_(o,s,l){var f=El;if(f&&typeof s=="string"&&s){var _=hi(s);_='link[rel="'+o+'"][href="'+_+'"]',typeof l=="string"&&(_+='[crossorigin="'+l+'"]'),U_.has(_)||(U_.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 PM(o){rr.D(o),k_("dns-prefetch",o,null)}function FM(o,s){rr.C(o,s),k_("preconnect",o,s)}function OM(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 BM(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 VM(o,s,l){rr.S(o,s,l);var f=El;if(f&&o){var _=He(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))&&gm(o,l);var ne=R=f.createElement("link");ge(ne),ao(ne,"link",o),ne._p=new Promise(function(Pe,ot){ne.onload=Pe,ne.onerror=ot}),ne.addEventListener("load",function(){O.loading|=1}),ne.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 HM(o,s){rr.X(o,s);var l=El;if(l&&o){var f=He(l).hoistableScripts,_=Ml(o),b=f.get(_);b||(b=l.querySelector(eu(_)),b||(o=v({src:o,async:!0},s),(s=rs.get(_))&&vm(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 GM(o,s){rr.M(o,s);var l=El;if(l&&o){var f=He(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(_))&&vm(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 z_(o,s,l,f){var _=(_=Qe.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=He(_).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=He(_).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||jM(_,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=He(_).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 P_(o){return v({},o,{"data-precedence":o.precedence,precedence:null})}function jM(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 F_(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=P_(l),(_=rs.get(_))&&gm(f,_),b=(o.ownerDocument||o).createElement("link"),ge(b);var R=b;return R._p=new Promise(function(O,ne){R.onload=O,R.onerror=ne}),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),vm(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 qM(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 V_(o){return!(o.type==="stylesheet"&&(o.state.loading&3)===0)}function WM(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=P_(f),(_=rs.get(_))&&gm(f,_),b=b.createElement("link"),ge(b);var R=b;R._p=new Promise(function(O,ne){R.onload=O,R.onerror=ne}),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 xm=0;function $M(o,s){return o.stylesheets&&o.count===0&&Bd(o,o.stylesheets),0xm?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(XM,o),Od=null,Fd.call(o))}function XM(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:ie,_currentValue2:ie,_threadCount:0};function YM(o,s,l,f,_,b,R,O,ne){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=ne,this.incompleteTransitions=new Map}function H_(o,s,l,f,_,b,R,O,ne,Pe,ot,ut){return o=new YM(o,s,l,R,ne,Pe,ot,ut,O),s=1,b===!0&&(s|=24),b=zo(3,null,null,s),o.current=b,b.stateNode=o,s=Kh(),s.refCount++,o.pooledCache=s,s.refCount++,b.memoizedState={element:f,isDehydrated:l,cache:s},tp(b),o}function G_(o){return o?(o=il,o):il}function j_(o,s,l,f,_,b){_=G_(_),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 q_(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(),Cm.exports=uC(),Cm.exports}var fC=dC();const hC=pT(fC),pC="modulepreload",mC=function(t){return"/"+t},db={},x0=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=mC(d),d in db)return;db[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":pC,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 gC=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),vC=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,i)=>i?i.toUpperCase():n.toLowerCase()),fb=t=>{const e=vC(t);return e.charAt(0).toUpperCase()+e.slice(1)},mT=(...t)=>t.filter((e,n,i)=>!!e&&e.trim()!==""&&i.indexOf(e)===n).join(" ").trim(),xC=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0};var yC={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 _C=Re.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:i,className:r="",children:a,iconNode:c,...u},h)=>Re.createElement("svg",{ref:h,...yC,width:e,height:e,stroke:t,strokeWidth:i?Number(n)*24/Number(e):n,className:mT("lucide",r),...!a&&!xC(u)&&{"aria-hidden":"true"},...u},[...c.map(([d,g])=>Re.createElement(d,g)),...Array.isArray(a)?a:[a]]));const It=(t,e)=>{const n=Re.forwardRef(({className:i,...r},a)=>Re.createElement(_C,{ref:a,iconNode:e,className:mT(`lucide-${gC(fb(t))}`,`lucide-${t}`,i),...r}));return n.displayName=fb(t),n};const bC=[["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"}]],SC=It("activity",bC);const TC=[["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"}]],hb=It("align-vertical-justify-center",TC);const EC=[["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"}]],wC=It("align-vertical-justify-end",EC);const MC=[["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"}]],CC=It("align-vertical-justify-start",MC);const AC=[["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"}]],Im=It("bold",AC);const RC=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],gT=It("check",RC);const NC=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],zu=It("chevron-down",NC);const IC=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],y0=It("chevron-up",IC);const DC=[["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"}]],LC=It("circle-alert",DC);const UC=[["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"}]],kC=It("clipboard",UC);const zC=[["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"}]],PC=It("copy",zC);const FC=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],OC=It("disc",FC);const BC=[["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"}]],pb=It("download",BC);const VC=[["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",VC);const HC=[["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",HC);const GC=[["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"}]],jC=It("fast-forward",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:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]],WC=It("file-down",qC);const $C=[["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",$C);const XC=[["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"}]],vT=It("film",XC);const YC=[["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"}]],JC=It("folder",YC);const KC=[["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",KC);const ZC=[["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"}]],QC=It("grip-vertical",ZC);const eA=[["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"}]],mb=It("image",eA);const tA=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],nA=It("info",tA);const iA=[["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"}]],Dm=It("italic",iA);const oA=[["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"}]],sA=It("key",oA);const rA=[["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",rA);const aA=[["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",aA);const lA=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],gb=It("loader-circle",lA);const cA=[["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",cA);const uA=[["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"}]],vb=It("minimize",uA);const dA=[["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",dA);const fA=[["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"}]],hA=It("palette",fA);const pA=[["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"}]],mA=It("panels-top-left",pA);const gA=[["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"}]],xT=It("pause",gA);const vA=[["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"}]],_0=It("play",vA);const xA=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],yT=It("plus",xA);const yA=[["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"}]],_A=It("redo-2",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"}],["path",{d:"M11 10h1v4",key:"70cz1p"}]],SA=It("repeat-1",bA);const TA=[["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"}]],xb=It("repeat",TA);const EA=[["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"}]],wA=It("rewind",EA);const MA=[["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",MA);const CA=[["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"}]],AA=It("scissors",CA);const RA=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],NA=It("search",RA);const IA=[["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",IA);const DA=[["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"}]],LA=It("shuffle",DA);const UA=[["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"}]],kA=It("skip-back",UA);const zA=[["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"}]],PA=It("skip-forward",zA);const FA=[["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"}]],b0=It("sparkles",FA);const OA=[["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"}]],BA=It("split",OA);const VA=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],S0=It("square",VA);const HA=[["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"}]],GA=It("strikethrough",HA);const jA=[["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",jA);const qA=[["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"}]],WA=It("triangle-alert",qA);const $A=[["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",$A);const XA=[["path",{d:"M6 4v6a6 6 0 0 0 12 0V4",key:"9kb039"}],["line",{x1:"4",x2:"20",y1:"20",y2:"20",key:"nun2al"}]],YA=It("underline",XA);const JA=[["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"}]],KA=It("undo-2",JA);const ZA=[["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",ZA);const QA=[["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"}]],eR=It("user",QA);const tR=[["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",tR);const nR=[["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",nR);const iR=[["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",iR);const oR=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Wo=It("x",oR);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:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]],rR=It("zoom-in",sR);const aR=[["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"}]],lR=It("zoom-out",aR);var lo=(t=>(t.PLAYER="PLAYER",t.EDITOR="EDITOR",t))(lo||{});const Hg=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}),H{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=Hg(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 V=c(D),Z=c(W);V!==void 0&&Z!==void 0&&A.push({text:H,startTime:V,endTime:Z})}}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)},cR=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 H=D[1]?parseInt(D[1].replace(":",""),10):0,V=parseInt(D[2],10),Z=parseInt(D[3],10),k=parseInt(D[4],10),P=H*3600+V*60+Z+k/1e3,Q=(D.index||0)+D[0].length;let ue=T.length;W+10){const Te=T.substring(0,D.index);Te.trim()&&E.push({text:Te.trim(),startTime:v,endTime:P})}se&&E.push({text:se,startTime:P,endTime:0})});for(let D=0;D/g,"").replace(/\s+/g," ").trim(),L=Hg(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},uR=({toast:t,onRemove:e})=>{const[n,i]=Re.useState(!1);Re.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(gT,{size:18,className:"text-green-400"});case"error":return p.jsx(LC,{size:18,className:"text-red-400"});default:return p.jsx(nA,{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})})]})},dR=({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(uR,{toast:n,onRemove:()=>e(n.id)})},n.id))}),fR=({isOpen:t,message:e,onConfirm:n,onCancel:i,title:r="Confirm Action"})=>{const[a,c]=Re.useState(!1);return Re.useEffect(()=>{t?c(!0):setTimeout(()=>c(!1),300)},[t]),Re.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(WA,{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"})]})]})]})},_T=Re.createContext(void 0),Ou=()=>{const t=Re.useContext(_T);if(!t)throw new Error("useUI must be used within a UIProvider");return t},hR=({children:t})=>{const[e,n]=Re.useState([]),i=Re.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=Re.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]=Re.useState({isOpen:!1,message:"",title:"",resolve:null}),h=Re.useCallback((v,y="Confirm Action")=>new Promise(S=>{u({isOpen:!0,message:v,title:y,resolve:S})}),[]),d=Re.useCallback(()=>{c.resolve&&c.resolve(!0),u(v=>({...v,isOpen:!1,resolve:null}))},[c]),g=Re.useCallback(()=>{c.resolve&&c.resolve(!1),u(v=>({...v,isOpen:!1,resolve:null}))},[c]);return p.jsxs(_T.Provider,{value:{toast:a,confirm:h},children:[t,p.jsx(dR,{toasts:e,removeToast:r}),p.jsx(fR,{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,pR=(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")}`},yb=10,mR=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},gR=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}),vR=({value:t,onChange:e})=>{const[n,i]=Re.useState(t.toString());Re.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(y0,{size:10})})]})},xR=({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=Re.useRef(null),y=Re.useRef(null),S=Re.useRef(null),[T,A]=Re.useState(40),[E,w]=Re.useState([]),[I,L]=Re.useState(null),[D,W]=Re.useState([]),[H,V]=Re.useState(null),[Z,k]=Re.useState(!1),[P,Q]=Re.useState(null),[ue,se]=Re.useState([{slides:t,selection:[]}]),[Te,$e]=Re.useState(0),X=Re.useRef(!1),[ve,ie]=Re.useState([]);Re.useEffect(()=>{if(X.current){X.current=!1;return}if(H||Z)return;const F=ue[Te],ce={slides:t,selection:E};if(JSON.stringify(F)!==JSON.stringify(ce)){const z=ue.slice(0,Te+1);z.push(ce),z.length>mR?(z.shift(),se(z)):(se(z),$e(Te+1))}},[t,E,ue,Te,H,Z]);const nt=Te>0,Ce=Te{if(Te>0){const F=Te-1;$e(F),X.current=!0,e(ue[F].slides),w(ue[F].selection)}},[e,w,ue,Te]),be=Re.useCallback(()=>{if(TeF.endTime)),oe=Math.max(i,60,Fe),Ae=oe*T,Qe=Re.useCallback(()=>{if(E.length===0)return;const F=t.filter(ce=>E.includes(ce.id));W(F),g.success(`Copied ${F.length} items`)},[E,t,g]),we=Re.useCallback(()=>{if(E.length===0)return;const F=t.filter(ce=>E.includes(ce.id));W(F),e(ce=>ce.filter(z=>!E.includes(z.id))),w([]),g.success(`Cut ${F.length} items`)},[E,t,e,g]),N=Re.useRef(t),ye=Re.useRef(T);Re.useEffect(()=>{N.current=t,ye.current=T},[t,T]);const xe=Re.useCallback(()=>{if(D.length===0)return;const F=Math.min(...D.map(j=>j.startTime)),ce=n-F,z=D.map(j=>({...j,id:Math.random().toString(36).substr(2,9),startTime:j.startTime+ce,endTime:j.endTime+ce}));e(j=>[...j,...z].sort((B,ae)=>B.startTime-ae.startTime)),w(z.map(j=>j.id)),g.success(`Pasted ${z.length} items`)},[D,n,e,g]),Le=Re.useCallback(()=>{const F=t.filter(B=>E.includes(B.id)&&n>B.startTime&&n{const ae=n,Y={...B,id:Math.random().toString(36).substr(2,9),endTime:ae},me=ae-B.startTime,ee={...B,id:Math.random().toString(36).substr(2,9),startTime:ae,mediaStartOffset:(B.mediaStartOffset||0)+me};z.push(B.id),ce.push(Y,ee),j.push(ee.id)}),e(B=>[...B.filter(Y=>!z.includes(Y.id)),...ce].sort((Y,me)=>Y.startTime-me.startTime)),w(j),g.success(`Split ${F.length} items`)},[t,E,n,e,g]),st=async F=>{if(F.target.files&&F.target.files.length>0){const ce=Array.from(F.target.files),z=ce.every(B=>B.type.startsWith("image/")),j=[];if(z){const B=ce.length,ae=n,me=Math.max(0,i-ae)/B,ee=Math.max(3,me);ce.forEach((Xe,M)=>{const J=URL.createObjectURL(Xe),fe=ae+M*ee,de=fe+ee;j.push({id:Math.random().toString(36).substr(2,9),url:J,type:"image",startTime:fe,endTime:de,name:Xe.name,layer:0})})}else{let B=n;for(const ae of ce){const Y=ae.type.startsWith("image/")?"image":ae.type.startsWith("video/")?"video":"audio";let me=5;if(Y!=="image"){const Xe=await gR(ae);Xe>0&&(me=Xe)}const ee=URL.createObjectURL(ae);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:ae.name,isMuted:Y==="video",volume:Y==="video"||Y==="audio"?1:void 0,layer:0}),B+=me}}e(B=>[...B,...j].sort((ae,Y)=>ae.startTime-Y.startTime)),F.target.value=""}},tt=F=>{e(ce=>ce.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([])},Ee=(F,ce,z)=>{if(F.stopPropagation(),F.preventDefault(),v.current?.focus(),F.shiftKey&&I){const ee=t.findIndex(M=>M.id===I),Xe=t.findIndex(M=>M.id===ce);if(ee!==-1&&Xe!==-1){const M=Math.min(ee,Xe),J=Math.max(ee,Xe),fe=t.slice(M,J+1).map(de=>de.id);w(de=>{const ke=new Set([...de,...fe]);return Array.from(ke)})}}else F.ctrlKey||F.metaKey?(w(ee=>ee.includes(ce)?ee.filter(Xe=>Xe!==ce):[...ee,ce]),L(ce)):(E.includes(ce)||w([ce]),L(ce));const j=t.find(ee=>ee.id===ce);if(!j)return;const B=E.includes(ce),ae=F.ctrlKey||F.metaKey||F.shiftKey;let Y=[];if(!ae&&!B)Y=[ce];else if(ae){if(Y=[ce],(F.ctrlKey||F.metaKey)&&!B)Y=[...E,ce];else if((F.ctrlKey||F.metaKey)&&B){Y=E.filter(ee=>ee!==ce);return}}else Y=E;const me={};t.forEach(ee=>{Y.includes(ee.id)&&(me[ee.id]={start:ee.startTime,end:ee.endTime})}),me[ce]||(me[ce]={start:j.startTime,end:j.endTime}),V({id:ce,type:z,startX:F.clientX,initialStart:j.startTime,initialEnd:j.endTime,initialMap:me}),window.addEventListener("mousemove",te),window.addEventListener("mouseup",le)},Oe=F=>{F.button===0&&(F.stopPropagation(),v.current?.focus(),w([]),k(!0),We(F.clientX),window.addEventListener("mousemove",gt),window.addEventListener("mouseup",qe))},lt=F=>{if(F.button!==0)return;v.current?.focus();const ce=F.clientX,z=F.clientY,j=S.current?.getBoundingClientRect();if(!j)return;const B=ce-j.left,ae=z-j.top;let Y=!1;const me=Xe=>{const M=Math.sqrt(Math.pow(Xe.clientX-ce,2)+Math.pow(Xe.clientY-z,2));if(!Y&&M>5&&(Y=!0,Q({x:B,y:ae,w:0,h:0})),Y&&S.current){const J=S.current.getBoundingClientRect(),fe=Xe.clientX-J.left,de=Xe.clientY-J.top;Q(Dt=>{if(!Dt)return null;const Yt=fe-B,Zt=de-ae;return{x:Yt>0?B:fe,y:Zt>0?ae:de,w:Math.abs(Yt),h:Math.abs(Zt)}});const ke=[],Je=N.current,ht=ye.current,et=Math.min(B,fe),Se=Math.min(ae,de),Ke=Math.abs(fe-B),Ve=Math.abs(de-ae),_t=et+Ke,Jt=Se+Ve;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=Seti;ji&&fn&&ke.push(Dt.id)}),w(ke)}},ee=Xe=>{Y||(w([]),We(Xe.clientX)),Q(null),window.removeEventListener("mousemove",me),window.removeEventListener("mouseup",ee)};window.addEventListener("mousemove",me),window.addEventListener("mouseup",ee)},We=F=>{if(!S.current)return;const ce=S.current.getBoundingClientRect(),z=F-ce.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 ce=F.target;if(!(ce.tagName==="INPUT"||ce.tagName==="TEXTAREA"||ce.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(),be();return}if((F.ctrlKey||F.metaKey)&&F.key==="c"){F.preventDefault(),Qe();return}if((F.ctrlKey||F.metaKey)&&F.key==="x"){F.preventDefault(),we();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(),Le();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,ce=[])=>{const z=yb/T,j=[0,i,n],B=Yd(T),ae=Math.round(F/B)*B;j.push(ae),t.forEach(ee=>{ce.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 Xe=Math.abs(ee-F);Xe{V(ce=>{if(!ce)return null;const j=(F.clientX-ce.startX)/T;let B=[];return e(ae=>{if(ce.type==="move"){const Y=Object.keys(ce.initialMap),me=Object.values(ce.initialMap),ee=Math.min(...me.map(Ve=>Ve.start)),Xe=Math.max(...me.map(Ve=>Ve.end)),M=ce.initialMap[ce.id],J=[{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:Xe,ref:"end"}],fe=yb/T,de=[0,i,n],ke=Yd(T);t.forEach(Ve=>{Y.includes(Ve.id)||(de.push(Ve.startTime),de.push(Ve.endTime))}),r.forEach(Ve=>{de.push(Ve.time)});let Je=j,ht=fe,et=!1,Se=-1;J.forEach(Ve=>{const _t=Ve.initVal+j;for(const Yt of de){const Zt=Math.abs(Yt-_t);Zt{const _t=ce.initialMap[Ve.id];if(_t){const Jt=_t.end-_t.start;let Dt=Ve.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;Ve.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{...Ve,startTime:_t.start+Ke,endTime:_t.start+Ke+Jt,layer:Dt}}return Ve})}else if(ce.type==="resize-start"){let Y=ce.initialStart+j;const me=C(Y,[ce.id]);Math.abs(me-Y)>1e-4&&(B=[me]),Y=me;const ee=.5,Xe=ce.initialEnd;return Y=Math.max(0,Math.min(Y,Xe-ee)),Y===0&&(B=[0]),ae.map(M=>M.id!==ce.id?M:{...M,startTime:Y})}else{let Y=ce.initialEnd+j;const me=C(Y,[ce.id]);Math.abs(me-Y)>1e-4&&(B=[me]),Y=me;const ee=.5,Xe=ce.initialStart;return Y=Math.max(Xe+ee,Y),ae.map(M=>M.id!==ce.id?M:{...M,endTime:Y})}}),ie(B),ce})},le=F=>{H&&H.type==="move"&&Math.abs(F.clientX-H.startX)<5&&!F.ctrlKey&&!F.metaKey&&!F.shiftKey&&w([H.id]),V(null),ie([]),window.removeEventListener("mousemove",te),window.removeEventListener("mouseup",le),e(ce=>[...ce].sort((z,j)=>z.startTime-j.startTime))},Ne=()=>A(F=>Math.min(200,F+10)),De=()=>A(F=>Math.max(10,F-10)),rt=(F,ce)=>{h(z=>{const j=z.layerVisibility?.[F]||{},B={...j,[ce]:j[ce]===!1};return{...z,layerVisibility:{...z.layerVisibility,[F]:B,...F==="visual"?{audio:z.layerVisibility?.audio||{}}:{visual:z.layerVisibility?.visual||{}}}}})},it=(F,ce)=>u.layerVisibility?.[F]?.[ce]!==!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(vT,{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(yT,{size:14})," Import Media",p.jsx("input",{type:"file",name:"import-media",id:"import-media",className:"hidden",accept:"image/*,video/*,audio/*",multiple:!0,onChange:st})]}),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(lR,{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:Ne,className:"p-1 hover:bg-zinc-700 rounded text-zinc-400 hover:text-white",title:"Zoom In",children:p.jsx(rR,{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:!nt,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(KA,{size:14})}),p.jsx("button",{onClick:be,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(_A,{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:Qe,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(PC,{size:14})}),p.jsx("button",{onClick:we,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(AA,{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(kC,{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:Le,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(BA,{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(ce=>ce.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,ae=parseInt(z[1])||0,Y=B*60+ae;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(ce=>ce.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(ce=>ce.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:ce=>{const z=parseFloat(ce.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(vR,{value:F.playbackRate||1,onChange:ce=>{e(z=>z.map(j=>{if(j.id===F.id){const B=j.playbackRate||1,Y=(j.endTime-j.startTime)*(B/ce);return{...j,playbackRate:ce,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:`${Ae+96}px`,minWidth:"100%",height:"max(100%, 280px)"},onMouseDown:lt,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}}),ve.map((F,ce)=>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-${ce}`)),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(Ae/(T*F))}).map((ce,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:Oe,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(Ae/(T*F))}).map((ce,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:pR(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(),rt("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 - ${H?.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:ce=>Ee(ce,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})}),(H?.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:ce=>{ce.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:ce=>{ce.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:ce=>{ce.stopPropagation(),tt(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:ce=>Ee(ce,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:ce=>Ee(ce,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(),rt("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 - ${H?.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:ce=>Ee(ce,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})}),(H?.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:ce=>{ce.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:ce=>{ce.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:ce=>{ce.stopPropagation(),tt(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:ce=>Ee(ce,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:ce=>Ee(ce,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,ce)=>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]},ce))})]}),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(),rt("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 - ${H?.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:ce=>Ee(ce,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})}),(H?.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:ce=>{ce.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:ce=>{ce.stopPropagation(),tt(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:ce=>Ee(ce,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:ce=>Ee(ce,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(),rt("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 - ${H?.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:ce=>Ee(ce,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})}),(H?.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:ce=>{ce.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:ce=>{ce.stopPropagation(),tt(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:ce=>Ee(ce,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:ce=>Ee(ce,F.id,"resize-end")})]},F.id))})]})]})})]})};var yR={};let _R,bR;function SR(){return{geminiUrl:_R,vertexUrl:bR}}function TR(t,e,n,i){var r,a;if(!t?.baseUrl){const c=SR();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 ER(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])T0(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&&T0(c[a],e,n,i+1,r)}}function Gg(t){if(typeof t!="string")throw new Error("fromImageBytes must be a string");return t}function wR(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 MR(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"],AR(c)),e}function CR(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"],RR(c)),e}function AR(t){const e={},n=m(t,["generatedSamples"]);if(n!=null){let a=n;Array.isArray(a)&&(a=a.map(c=>NR(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 RR(t){const e={},n=m(t,["videos"]);if(n!=null){let a=n;Array.isArray(a)&&(a=a.map(c=>IR(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 NR(t){const e={},n=m(t,["video"]);return n!=null&&x(e,["video"],PR(n)),e}function IR(t){const e={},n=m(t,["_self"]);return n!=null&&x(e,["video"],FR(n)),e}function DR(t){const e={},n=m(t,["operationName"]);return n!=null&&x(e,["_url","operationName"],n),e}function LR(t){const e={},n=m(t,["operationName"]);return n!=null&&x(e,["_url","operationName"],n),e}function UR(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"],kR(c)),e}function kR(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 bT(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"],zR(c)),e}function zR(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 PR(t){const e={},n=m(t,["uri"]);n!=null&&x(e,["uri"],n);const i=m(t,["encodedVideo"]);i!=null&&x(e,["videoBytes"],Gg(i));const r=m(t,["encoding"]);return r!=null&&x(e,["mimeType"],r),e}function FR(t){const e={},n=m(t,["gcsUri"]);n!=null&&x(e,["uri"],n);const i=m(t,["bytesBase64Encoded"]);i!=null&&x(e,["videoBytes"],Gg(i));const r=m(t,["mimeType"]);return r!=null&&x(e,["mimeType"],r),e}var _b;(function(t){t.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",t.OUTCOME_OK="OUTCOME_OK",t.OUTCOME_FAILED="OUTCOME_FAILED",t.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(_b||(_b={}));var bb;(function(t){t.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",t.PYTHON="PYTHON"})(bb||(bb={}));var Sb;(function(t){t.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",t.SILENT="SILENT",t.WHEN_IDLE="WHEN_IDLE",t.INTERRUPT="INTERRUPT"})(Sb||(Sb={}));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 Tb;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(Tb||(Tb={}));var Eb;(function(t){t.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",t.SIMPLE_SEARCH="SIMPLE_SEARCH",t.ELASTIC_SEARCH="ELASTIC_SEARCH"})(Eb||(Eb={}));var wb;(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"})(wb||(wb={}));var Mb;(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"})(Mb||(Mb={}));var Cb;(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"})(Cb||(Cb={}));var Ab;(function(t){t.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH",t.MINIMAL="MINIMAL"})(Ab||(Ab={}));var Rb;(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"})(Rb||(Rb={}));var Nb;(function(t){t.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",t.SEVERITY="SEVERITY",t.PROBABILITY="PROBABILITY"})(Nb||(Nb={}));var Ib;(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"})(Ib||(Ib={}));var Db;(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"})(Db||(Db={}));var Lb;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(Lb||(Lb={}));var Ub;(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"})(Ub||(Ub={}));var kb;(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"})(kb||(kb={}));var zb;(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"})(zb||(zb={}));var Pb;(function(t){t.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",t.ON_DEMAND="ON_DEMAND",t.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(Pb||(Pb={}));var Zf;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.AUDIO="AUDIO"})(Zf||(Zf={}));var Fb;(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"})(Fb||(Fb={}));var Ob;(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"})(Ob||(Ob={}));var Bb;(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"})(Bb||(Bb={}));var E0;(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"})(E0||(E0={}));var Vb;(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"})(Vb||(Vb={}));var Hb;(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"})(Hb||(Hb={}));var Gb;(function(t){t.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",t.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",t.BALANCED="BALANCED",t.PRIORITIZE_COST="PRIORITIZE_COST"})(Gb||(Gb={}));var jb;(function(t){t.UNSPECIFIED="UNSPECIFIED",t.BLOCKING="BLOCKING",t.NON_BLOCKING="NON_BLOCKING"})(jb||(jb={}));var qb;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(qb||(qb={}));var Wb;(function(t){t.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",t.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER"})(Wb||(Wb={}));var $b;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE",t.VALIDATED="VALIDATED"})($b||($b={}));var Xb;(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"})(Xb||(Xb={}));var Yb;(function(t){t.DONT_ALLOW="DONT_ALLOW",t.ALLOW_ADULT="ALLOW_ADULT",t.ALLOW_ALL="ALLOW_ALL"})(Yb||(Yb={}));var Jb;(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"})(Jb||(Jb={}));var Kb;(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"})(Kb||(Kb={}));var Zb;(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"})(Zb||(Zb={}));var Qb;(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"})(Qb||(Qb={}));var eS;(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"})(eS||(eS={}));var tS;(function(t){t.FOREGROUND="FOREGROUND",t.BACKGROUND="BACKGROUND",t.PROMPT="PROMPT",t.SEMANTIC="SEMANTIC",t.INTERACTIVE="INTERACTIVE"})(tS||(tS={}));var nS;(function(t){t.ASSET="ASSET",t.STYLE="STYLE"})(nS||(nS={}));var iS;(function(t){t.INSERT="INSERT",t.REMOVE="REMOVE",t.REMOVE_STATIC="REMOVE_STATIC",t.OUTPAINT="OUTPAINT"})(iS||(iS={}));var oS;(function(t){t.OPTIMIZED="OPTIMIZED",t.LOSSLESS="LOSSLESS"})(oS||(oS={}));var sS;(function(t){t.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",t.PREFERENCE_TUNING="PREFERENCE_TUNING"})(sS||(sS={}));var rS;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.STATE_PENDING="STATE_PENDING",t.STATE_ACTIVE="STATE_ACTIVE",t.STATE_FAILED="STATE_FAILED"})(rS||(rS={}));var aS;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.PROCESSING="PROCESSING",t.ACTIVE="ACTIVE",t.FAILED="FAILED"})(aS||(aS={}));var lS;(function(t){t.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",t.UPLOADED="UPLOADED",t.GENERATED="GENERATED"})(lS||(lS={}));var cS;(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"})(cS||(cS={}));var uS;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.VIDEO="VIDEO",t.AUDIO="AUDIO",t.DOCUMENT="DOCUMENT"})(uS||(uS={}));var dS;(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"})(dS||(dS={}));var fS;(function(t){t.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",t.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",t.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(fS||(fS={}));var hS;(function(t){t.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",t.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",t.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(hS||(hS={}));var pS;(function(t){t.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",t.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",t.NO_INTERRUPTION="NO_INTERRUPTION"})(pS||(pS={}));var mS;(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"})(mS||(mS={}));var gS;(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"})(gS||(gS={}));var vS;(function(t){t.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",t.QUALITY="QUALITY",t.DIVERSITY="DIVERSITY",t.VOCALIZATION="VOCALIZATION"})(vS||(vS={}));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 w0{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 xS{}class yS{}class OR{}class BR{}class VR{}class HR{}class _S{}class bS{}class SS{}class GR{}class Qf{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){const i=new Qf;let r;const a=e;return n?r=CR(a):r=MR(a),Object.assign(i,r),i}}class TS{}class ES{}class wS{}class MS{}class jR{}class qR{}class WR{}class jg{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){const i=new jg,a=UR(e);return Object.assign(i,a),i}}class $R{}class XR{}class YR{}class CS{}class JR{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 KR{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}}class qg{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){const i=new qg,a=bT(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 ST(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 TT(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 ET(t){const e=eh(t);if(e.mimeType&&e.mimeType.startsWith("image/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function wT(t){const e=eh(t);if(e.mimeType&&e.mimeType.startsWith("audio/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function AS(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 MT(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("PartListUnion is required");return Array.isArray(t)?t.map(e=>AS(e)):[AS(t)]}function M0(t){return t!=null&&typeof t=="object"&&"parts"in t&&Array.isArray(t.parts)}function RS(t){return t!=null&&typeof t=="object"&&"functionCall"in t}function NS(t){return t!=null&&typeof t=="object"&&"functionResponse"in t}function vo(t){if(t==null)throw new Error("ContentUnion is required");return M0(t)?t:{role:"user",parts:MT(t)}}function Wg(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(RS(t)||NS(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=M0(t[0]);for(const r of t){const a=M0(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(RS(r)||NS(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:MT(n)}),e}function ZR(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&&ZR(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 $g(t){return ec(t)}function Xg(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 Yg(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 QR(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 QR(t,e,"cachedContents")}function CT(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 Gg(t)}function eN(t){return t!=null&&typeof t=="object"&&"name"in t}function tN(t){return t!=null&&typeof t=="object"&&"video"in t}function nN(t){return t!=null&&typeof t=="object"&&"uri"in t}function AT(t){var e;let n;if(eN(t)&&(n=t.name),!(nN(t)&&(n=t.uri,n===void 0))&&!(tN(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 RT(t,e){let n;return t.isVertexAI()?n=e?"publishers/google/models":"models":n=e?"models":"tunedModels",n}function NT(t){for(const e of["models","tunedModels","publisherModels"])if(iN(t,e))return t[e];return[]}function iN(t,e){return t!==null&&typeof t=="object"&&e in t}function oN(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 sN(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=oN(r,e);c.functionDeclarations&&n.push(...c.functionDeclarations)}return{functionDeclarations:n}}function IT(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 rN(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 DT(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 LT(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 aN(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=>VN(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 lN(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 cN(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"],LT(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"],aN(DT(d))),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,["state"]);r!=null&&x(e,["state"],LT(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"],uN(v));const y=m(t,["outputConfig"]);y!=null&&x(e,["dest"],lN(DT(y)));const S=m(t,["completionStats"]);return S!=null&&x(e,["completionStats"],S),e}function uN(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 dN(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=>BN(t,c))),x(n,["requests","requests"],a)}return n}function fN(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 hN(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 pN(t,e){const n={},i=m(e,["name"]);return i!=null&&x(n,["_url","name"],vc(t,i)),n}function mN(t,e){const n={},i=m(e,["name"]);return i!=null&&x(n,["_url","name"],vc(t,i)),n}function gN(t){const e={},n=m(t,["content"]);n!=null&&x(e,["content"],n);const i=m(t,["citationMetadata"]);i!=null&&x(e,["citationMetadata"],vN(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 vN(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 UT(t){const e={},n=m(t,["parts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(a=>XN(a))),x(e,["parts"],r)}const i=m(t,["role"]);return i!=null&&x(e,["role"],i),e}function xN(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 yN(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"],cN(rN(r))),n}function IS(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"],dN(t,IT(t,r)));const a=m(e,["config"]);return a!=null&&xN(a,n),n}function _N(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"],fN(IT(t,r)));const a=m(e,["config"]);return a!=null&&yN(a,n),n}function bN(t,e){const n={},i=m(t,["displayName"]);return e!==void 0&&i!=null&&x(e,["batch","displayName"],i),n}function SN(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"],RN(t,r));const a=m(e,["config"]);return a!=null&&bN(a,n),n}function TN(t,e){const n={},i=m(e,["name"]);return i!=null&&x(n,["_url","name"],vc(t,i)),n}function EN(t,e){const n={},i=m(e,["name"]);return i!=null&&x(n,["_url","name"],vc(t,i)),n}function wN(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 MN(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 CN(t,e){const n={},i=m(e,["contents"]);if(i!=null){let a=Wg(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"],AN(r,n)),ER(n,{"requests[].*":"requests[].request.*"})),n}function AN(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 RN(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"],CN(t,r)),n}function NN(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 IN(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 DN(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 LN(t,e,n){const i={},r=m(e,["systemInstruction"]);n!==void 0&&r!=null&&x(n,["systemInstruction"],UT(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"],$g(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 se=L;Array.isArray(se)&&(se=se.map(Te=>YN(Te))),x(n,["safetySettings"],se)}const D=m(e,["tools"]);if(n!==void 0&&D!=null){let se=gc(D);Array.isArray(se)&&(se=se.map(Te=>KN(mc(Te)))),x(n,["tools"],se)}const W=m(e,["toolConfig"]);if(n!==void 0&&W!=null&&x(n,["toolConfig"],JN(W)),m(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");const H=m(e,["cachedContent"]);n!==void 0&&H!=null&&x(n,["cachedContent"],Sr(t,H));const V=m(e,["responseModalities"]);V!=null&&x(i,["responseModalities"],V);const Z=m(e,["mediaResolution"]);Z!=null&&x(i,["mediaResolution"],Z);const k=m(e,["speechConfig"]);if(k!=null&&x(i,["speechConfig"],Xg(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 Q=m(e,["imageConfig"]);Q!=null&&x(i,["imageConfig"],ON(Q));const ue=m(e,["enableEnhancedCivicAnswers"]);return ue!=null&&x(i,["enableEnhancedCivicAnswers"],ue),i}function UN(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=>gN(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 kN(t,e){const n={},i=m(e,["name"]);return i!=null&&x(n,["_url","name"],vc(t,i)),n}function zN(t,e){const n={},i=m(e,["name"]);return i!=null&&x(n,["_url","name"],vc(t,i)),n}function PN(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 FN(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 ON(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 BN(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=>UT(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"],LN(t,c,m(n,["request"],{}))),n}function VN(t){const e={},n=m(t,["response"]);n!=null&&x(e,["response"],UN(n));const i=m(t,["error"]);return i!=null&&x(e,["error"],i),e}function HN(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 GN(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 jN(t){const e={},n=m(t,["config"]);return n!=null&&HN(n,e),e}function qN(t){const e={},n=m(t,["config"]);return n!=null&&GN(n,e),e}function WN(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 $N(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=>C0(c))),x(e,["batchJobs"],a)}return e}function XN(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"],NN(a));const c=m(t,["functionCall"]);c!=null&&x(e,["functionCall"],IN(c));const u=m(t,["functionResponse"]);u!=null&&x(e,["functionResponse"],u);const h=m(t,["inlineData"]);h!=null&&x(e,["inlineData"],hN(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 YN(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 JN(t){const e={},n=m(t,["functionCallingConfig"]);n!=null&&x(e,["functionCallingConfig"],DN(n));const i=m(t,["retrievalConfig"]);return i!=null&&x(e,["retrievalConfig"],i),e}function KN(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"],PN(u));const h=m(t,["googleSearch"]);h!=null&&x(e,["googleSearch"],FN(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 ZN 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=IS(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=_N(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=>C0(g))}else{const d=IS(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=SN(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=zN(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=>C0(g))}else{const d=kN(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=mN(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=pN(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=qN(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=$N(g),y=new CS;return Object.assign(y,v),y})}else{const d=jN(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=WN(g),y=new CS;return Object.assign(y,v),y})}}async delete(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=EN(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=>MN(g))}else{const d=TN(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=>wN(g))}}}function QN(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 DS(t){const e={},n=m(t,["parts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(a=>S2(a))),x(e,["parts"],r)}const i=m(t,["role"]);return i!=null&&x(e,["role"],i),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"]);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=>DS(v))),x(e,["contents"],g)}const u=m(t,["systemInstruction"]);e!==void 0&&u!=null&&x(e,["systemInstruction"],DS(vo(u)));const h=m(t,["tools"]);if(e!==void 0&&h!=null){let g=h;Array.isArray(g)&&(g=g.map(v=>E2(v))),x(e,["tools"],g)}const d=m(t,["toolConfig"]);if(e!==void 0&&d!=null&&x(e,["toolConfig"],T2(d)),m(t,["kmsKeyName"])!==void 0)throw new Error("kmsKeyName parameter is not supported in Gemini API.");return n}function t2(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=>w2(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 n2(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["model"],ST(t,i));const r=m(e,["config"]);return r!=null&&e2(r,n),n}function i2(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["model"],ST(t,i));const r=m(e,["config"]);return r!=null&&t2(r,n),n}function o2(t,e){const n={},i=m(e,["name"]);return i!=null&&x(n,["_url","name"],Sr(t,i)),n}function s2(t,e){const n={},i=m(e,["name"]);return i!=null&&x(n,["_url","name"],Sr(t,i)),n}function r2(t){const e={},n=m(t,["sdkHttpResponse"]);return n!=null&&x(e,["sdkHttpResponse"],n),e}function a2(t){const e={},n=m(t,["sdkHttpResponse"]);return n!=null&&x(e,["sdkHttpResponse"],n),e}function l2(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 c2(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 u2(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 d2(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 f2(t,e){const n={},i=m(e,["name"]);return i!=null&&x(n,["_url","name"],Sr(t,i)),n}function h2(t,e){const n={},i=m(e,["name"]);return i!=null&&x(n,["_url","name"],Sr(t,i)),n}function p2(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 m2(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 g2(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 v2(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 x2(t){const e={},n=m(t,["config"]);return n!=null&&g2(n,e),e}function y2(t){const e={},n=m(t,["config"]);return n!=null&&v2(n,e),e}function _2(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 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,["cachedContents"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(c=>c)),x(e,["cachedContents"],a)}return e}function S2(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"],l2(a));const c=m(t,["functionCall"]);c!=null&&x(e,["functionCall"],c2(c));const u=m(t,["functionResponse"]);u!=null&&x(e,["functionResponse"],u);const h=m(t,["inlineData"]);h!=null&&x(e,["inlineData"],QN(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 T2(t){const e={},n=m(t,["functionCallingConfig"]);n!=null&&x(e,["functionCallingConfig"],u2(n));const i=m(t,["retrievalConfig"]);return i!=null&&x(e,["retrievalConfig"],i),e}function E2(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"],p2(u));const h=m(t,["googleSearch"]);h!=null&&x(e,["googleSearch"],m2(h));const d=m(t,["urlContext"]);return d!=null&&x(e,["urlContext"],d),e}function w2(t){const e={},n=m(t,["functionDeclarations"]);if(n!=null){let v=n;Array.isArray(v)&&(v=v.map(y=>d2(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 M2(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 C2(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 A2(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&&M2(r,n),n}function R2(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&&C2(r,n),n}class N2 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=i2(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=n2(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=h2(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=f2(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=s2(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=a2(g),y=new wS;return Object.assign(y,v),y})}else{const d=o2(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=r2(g),y=new wS;return Object.assign(y,v),y})}}async update(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=R2(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=A2(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=y2(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=b2(g),y=new MS;return Object.assign(y,v),y})}else{const d=x2(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=_2(g),y=new MS;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 LS=="function"?LS(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 I2(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:kT(n)}function kT(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 D2(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 US(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?US(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(I2(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(...US(i)):this.history.push(e),this.history.push(...r)}}class _h extends Error{constructor(e){super(e.message),this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,_h.prototype)}}function k2(t){const e={},n=m(t,["file"]);return n!=null&&x(e,["file"],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"],AT(n)),e}function F2(t){const e={},n=m(t,["sdkHttpResponse"]);return n!=null&&x(e,["sdkHttpResponse"],n),e}function O2(t){const e={},n=m(t,["name"]);return n!=null&&x(e,["_url","file"],AT(n)),e}function B2(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 V2(t){const e={},n=m(t,["config"]);return n!=null&&B2(n,e),e}function H2(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 G2 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=V2(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=H2(h),g=new $R;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=k2(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=z2(h),g=new XR;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=O2(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=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:"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=F2(h),g=new YR;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 j2(t){const e={},n=m(t,["parts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(a=>rI(a))),x(e,["parts"],r)}const i=m(t,["role"]);return i!=null&&x(e,["role"],i),e}function q2(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 W2(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 $2(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 X2(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 H=m(t,["topK"]);H!=null&&x(e,["topK"],H);const V=m(t,["topP"]);if(V!=null&&x(e,["topP"],V),m(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return e}function Y2(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 J2(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 K2(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"],Yg(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"],j2(vo(T)));const A=m(t,["tools"]);if(e!==void 0&&A!=null){let H=gc(A);Array.isArray(H)&&(H=H.map(V=>lI(mc(V)))),x(e,["setup","tools"],H)}const E=m(t,["sessionResumption"]);e!==void 0&&E!=null&&x(e,["setup","sessionResumption"],aI(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 Z2(t,e){const n={},i=m(t,["generationConfig"]);e!==void 0&&i!=null&&x(e,["setup","generationConfig"],X2(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"],Yg(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 V=gc(A);Array.isArray(V)&&(V=V.map(Z=>cI(mc(Z)))),x(e,["setup","tools"],V)}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 H=m(t,["explicitVadSignal"]);return e!==void 0&&H!=null&&x(e,["setup","explicitVadSignal"],H),n}function Q2(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"],K2(r,n)),n}function eI(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"],Z2(r,n)),n}function tI(t){const e={},n=m(t,["musicGenerationConfig"]);return n!=null&&x(e,["musicGenerationConfig"],n),e}function nI(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 iI(t){const e={},n=m(t,["media"]);if(n!=null){let d=TT(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(wT(i)));const r=m(t,["audioStreamEnd"]);r!=null&&x(e,["audioStreamEnd"],r);const a=m(t,["video"]);a!=null&&x(e,["video"],Lf(ET(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 oI(t){const e={},n=m(t,["media"]);if(n!=null){let d=TT(n);Array.isArray(d)&&(d=d.map(g=>g)),x(e,["mediaChunks"],d)}const i=m(t,["audio"]);i!=null&&x(e,["audio"],wT(i));const r=m(t,["audioStreamEnd"]);r!=null&&x(e,["audioStreamEnd"],r);const a=m(t,["video"]);a!=null&&x(e,["video"],ET(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 sI(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"],uI(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 rI(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"],q2(a));const c=m(t,["functionCall"]);c!=null&&x(e,["functionCall"],W2(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 aI(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 lI(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"],Y2(u));const h=m(t,["googleSearch"]);h!=null&&x(e,["googleSearch"],J2(h));const d=m(t,["urlContext"]);return d!=null&&x(e,["urlContext"],d),e}function cI(t){const e={},n=m(t,["functionDeclarations"]);if(n!=null){let v=n;Array.isArray(v)&&(v=v.map(y=>$2(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 uI(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 dI(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 fI(t){const e={},n=m(t,["content"]);n!=null&&x(e,["content"],n);const i=m(t,["citationMetadata"]);i!=null&&x(e,["citationMetadata"],hI(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 hI(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 pI(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 mI(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 gI(t){const e={},n=m(t,["values"]);n!=null&&x(e,["values"],n);const i=m(t,["statistics"]);return i!=null&&x(e,["statistics"],vI(i)),e}function vI(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 bh(t){const e={},n=m(t,["parts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(a=>MD(a))),x(e,["parts"],r)}const i=m(t,["role"]);return i!=null&&x(e,["role"],i),e}function xI(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 yI(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 _I(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=>OT(u))),x(e,["tools"],c)}const a=m(t,["generationConfig"]);return e!==void 0&&a!=null&&x(e,["generationConfig"],dD(a)),n}function bI(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=>bh(u))),x(n,["contents"],c)}const a=m(e,["config"]);return a!=null&&yI(a),n}function SI(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&&_I(a,n),n}function TI(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 EI(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 wI(t,e){const n={},i=m(e,["model"]);return i!=null&&x(n,["_url","name"],zn(t,i)),n}function MI(t,e){const n={},i=m(e,["model"]);return i!=null&&x(n,["_url","name"],zn(t,i)),n}function CI(t){const e={},n=m(t,["sdkHttpResponse"]);return n!=null&&x(e,["sdkHttpResponse"],n),e}function AI(t){const e={},n=m(t,["sdkHttpResponse"]);return n!=null&&x(e,["sdkHttpResponse"],n),e}function RI(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 NI(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=>DD(h))),x(n,["instances[0]","referenceImages"],u)}const c=m(e,["config"]);return c!=null&&RI(c,n),n}function II(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=>Sh(a))),x(e,["generatedImages"],r)}return e}function DI(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 LI(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 UI(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=Wg(t,r);Array.isArray(u)&&(u=u.map(h=>h)),x(n,["requests[]","content"],u)}const a=m(e,["config"]);a!=null&&DI(a,n);const c=m(e,["model"]);return c!==void 0&&x(n,["requests[]","model"],zn(t,c)),n}function kI(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=Wg(t,r);Array.isArray(c)&&(c=c.map(u=>u)),x(n,["instances[]","content"],c)}const a=m(e,["config"]);return a!=null&&LI(a,n),n}function zI(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 PI(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=>gI(c))),x(e,["embeddings"],a)}const r=m(t,["metadata"]);return r!=null&&x(e,["metadata"],r),e}function FI(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 OI(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 BI(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 VI(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 HI(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 GI(t,e,n){const i={},r=m(e,["systemInstruction"]);n!==void 0&&r!=null&&x(n,["systemInstruction"],bh(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"],$g(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 se=L;Array.isArray(se)&&(se=se.map(Te=>LD(Te))),x(n,["safetySettings"],se)}const D=m(e,["tools"]);if(n!==void 0&&D!=null){let se=gc(D);Array.isArray(se)&&(se=se.map(Te=>BD(mc(Te)))),x(n,["tools"],se)}const W=m(e,["toolConfig"]);if(n!==void 0&&W!=null&&x(n,["toolConfig"],OD(W)),m(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");const H=m(e,["cachedContent"]);n!==void 0&&H!=null&&x(n,["cachedContent"],Sr(t,H));const V=m(e,["responseModalities"]);V!=null&&x(i,["responseModalities"],V);const Z=m(e,["mediaResolution"]);Z!=null&&x(i,["mediaResolution"],Z);const k=m(e,["speechConfig"]);if(k!=null&&x(i,["speechConfig"],Xg(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 Q=m(e,["imageConfig"]);Q!=null&&x(i,["imageConfig"],gD(Q));const ue=m(e,["enableEnhancedCivicAnswers"]);return ue!=null&&x(i,["enableEnhancedCivicAnswers"],ue),i}function jI(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"],$g(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(ve=>ve)),x(n,["safetySettings"],X)}const H=m(e,["tools"]);if(n!==void 0&&H!=null){let X=gc(H);Array.isArray(X)&&(X=X.map(ve=>OT(mc(ve)))),x(n,["tools"],X)}const V=m(e,["toolConfig"]);n!==void 0&&V!=null&&x(n,["toolConfig"],V);const Z=m(e,["labels"]);n!==void 0&&Z!=null&&x(n,["labels"],Z);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 Q=m(e,["mediaResolution"]);Q!=null&&x(i,["mediaResolution"],Q);const ue=m(e,["speechConfig"]);ue!=null&&x(i,["speechConfig"],Xg(ue));const se=m(e,["audioTimestamp"]);se!=null&&x(i,["audioTimestamp"],se);const Te=m(e,["thinkingConfig"]);Te!=null&&x(i,["thinkingConfig"],Te);const $e=m(e,["imageConfig"]);if($e!=null&&x(i,["imageConfig"],vD($e)),m(e,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return i}function kS(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=>bh(u))),x(n,["contents"],c)}const a=m(e,["config"]);return a!=null&&x(n,["generationConfig"],GI(t,a,n)),n}function zS(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"],jI(t,a,n)),n}function PS(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=>fI(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 FS(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 qI(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 WI(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 $I(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&&qI(a,n),n}function XI(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&&WI(a,n),n}function YI(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=>aD(c))),x(e,["generatedImages"],a)}const r=m(t,["positivePromptSafetyAttributes"]);return r!=null&&x(e,["positivePromptSafetyAttributes"],PT(r)),e}function JI(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=>Sh(c))),x(e,["generatedImages"],a)}const r=m(t,["positivePromptSafetyAttributes"]);return r!=null&&x(e,["positivePromptSafetyAttributes"],FT(r)),e}function KI(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"],Th(g));const v=m(t,["referenceImages"]);if(e!==void 0&&v!=null){let y=v;Array.isArray(y)&&(y=y.map(S=>QD(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 ZI(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=>e3(D))),x(e,["instances[0]","referenceImages"],L)}const w=m(t,["mask"]);e!==void 0&&w!=null&&x(e,["instances[0]","mask"],ZD(w));const I=m(t,["compressionQuality"]);return e!==void 0&&I!=null&&x(e,["parameters","compressionQuality"],I),n}function QI(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"],iD(c)),e}function eD(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"],oD(c)),e}function tD(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"],Th(a));const c=m(e,["video"]);c!=null&&x(n,["instances[0]","video"],BT(c));const u=m(e,["source"]);u!=null&&sD(u,n);const h=m(e,["config"]);return h!=null&&KI(h,n),n}function nD(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"],VT(c));const u=m(e,["source"]);u!=null&&rD(u,n);const h=m(e,["config"]);return h!=null&&ZI(h,n),n}function iD(t){const e={},n=m(t,["generatedSamples"]);if(n!=null){let a=n;Array.isArray(a)&&(a=a.map(c=>cD(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 oD(t){const e={},n=m(t,["videos"]);if(n!=null){let a=n;Array.isArray(a)&&(a=a.map(c=>uD(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 sD(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"],Th(r));const a=m(t,["video"]);return e!==void 0&&a!=null&&x(e,["instances[0]","video"],BT(a)),n}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,["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"],VT(a)),n}function aD(t){const e={},n=m(t,["_self"]);n!=null&&x(e,["image"],xD(n));const i=m(t,["raiFilteredReason"]);i!=null&&x(e,["raiFilteredReason"],i);const r=m(t,["_self"]);return r!=null&&x(e,["safetyAttributes"],PT(r)),e}function Sh(t){const e={},n=m(t,["_self"]);n!=null&&x(e,["image"],zT(n));const i=m(t,["raiFilteredReason"]);i!=null&&x(e,["raiFilteredReason"],i);const r=m(t,["_self"]);r!=null&&x(e,["safetyAttributes"],FT(r));const a=m(t,["prompt"]);return a!=null&&x(e,["enhancedPrompt"],a),e}function lD(t){const e={},n=m(t,["_self"]);n!=null&&x(e,["mask"],zT(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 cD(t){const e={},n=m(t,["video"]);return n!=null&&x(e,["video"],JD(n)),e}function uD(t){const e={},n=m(t,["_self"]);return n!=null&&x(e,["video"],KD(n)),e}function dD(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 H=m(t,["topK"]);H!=null&&x(e,["topK"],H);const V=m(t,["topP"]);if(V!=null&&x(e,["topP"],V),m(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return e}function fD(t,e){const n={},i=m(e,["model"]);return i!=null&&x(n,["_url","name"],zn(t,i)),n}function hD(t,e){const n={},i=m(e,["model"]);return i!=null&&x(n,["_url","name"],zn(t,i)),n}function pD(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 mD(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 gD(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 vD(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 xD(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 zT(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 Th(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 yD(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"],RT(t,u)),i}function _D(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"],RT(t,u)),i}function bD(t,e){const n={},i=m(e,["config"]);return i!=null&&yD(t,i,n),n}function SD(t,e){const n={},i=m(e,["config"]);return i!=null&&_D(t,i,n),n}function TD(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=NT(r);Array.isArray(a)&&(a=a.map(c=>A0(c))),x(e,["models"],a)}return e}function ED(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=NT(r);Array.isArray(a)&&(a=a.map(c=>R0(c))),x(e,["models"],a)}return e}function wD(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 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,["version"]);a!=null&&x(e,["version"],a);const c=m(t,["_self"]);c!=null&&x(e,["tunedModelInfo"],VD(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 R0(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=>FI(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"],HD(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 MD(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"],OI(a));const c=m(t,["functionCall"]);c!=null&&x(e,["functionCall"],BI(c));const u=m(t,["functionResponse"]);u!=null&&x(e,["functionResponse"],u);const h=m(t,["inlineData"]);h!=null&&x(e,["inlineData"],dI(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 CD(t){const e={},n=m(t,["productImage"]);return n!=null&&x(e,["image"],As(n)),e}function AD(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 RD(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["_url","model"],zn(t,i));const r=m(e,["source"]);r!=null&&ID(r,n);const a=m(e,["config"]);return a!=null&&AD(a,n),n}function ND(t){const e={},n=m(t,["predictions"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(r=>Sh(r))),x(e,["generatedImages"],i)}return 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,["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=>CD(u))),x(e,["instances[0]","productImages"],c)}return n}function DD(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"],wD(a));const c=m(t,["controlImageConfig"]);c!=null&&x(e,["controlImageConfig"],xI(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 PT(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 FT(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 LD(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 UD(t){const e={},n=m(t,["image"]);return n!=null&&x(e,["image"],As(n)),e}function kD(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 zD(t,e){const n={},i=m(e,["model"]);i!=null&&x(n,["_url","model"],zn(t,i));const r=m(e,["source"]);r!=null&&FD(r,n);const a=m(e,["config"]);return a!=null&&kD(a,n),n}function PD(t){const e={},n=m(t,["predictions"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(r=>lD(r))),x(e,["generatedMasks"],i)}return e}function FD(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"],UD(a)),n}function OD(t){const e={},n=m(t,["functionCallingConfig"]);n!=null&&x(e,["functionCallingConfig"],VI(n));const i=m(t,["retrievalConfig"]);return i!=null&&x(e,["retrievalConfig"],i),e}function BD(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"],pD(u));const h=m(t,["googleSearch"]);h!=null&&x(e,["googleSearch"],mD(h));const d=m(t,["urlContext"]);return d!=null&&x(e,["urlContext"],d),e}function OT(t){const e={},n=m(t,["functionDeclarations"]);if(n!=null){let v=n;Array.isArray(v)&&(v=v.map(y=>HI(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 VD(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 HD(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 GD(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 jD(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 qD(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&&GD(r,n),n}function WD(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&&jD(r,n),n}function $D(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 XD(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&&$D(c,n),n}function YD(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=>Sh(a))),x(e,["generatedImages"],r)}return e}function JD(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 KD(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 ZD(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 QD(t){const e={},n=m(t,["image"]);n!=null&&x(e,["image"],Th(n));const i=m(t,["referenceType"]);return i!=null&&x(e,["referenceType"],i),e}function e3(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 BT(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 VT(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 t3(t,e){const n={},i=m(t,["displayName"]);return e!==void 0&&i!=null&&x(e,["displayName"],i),n}function n3(t){const e={},n=m(t,["config"]);return n!=null&&t3(n,e),e}function i3(t,e){const n={},i=m(t,["force"]);return e!==void 0&&i!=null&&x(e,["_query","force"],i),n}function o3(t){const e={},n=m(t,["name"]);n!=null&&x(e,["_url","name"],n);const i=m(t,["config"]);return i!=null&&i3(i,e),e}function s3(t){const e={},n=m(t,["name"]);return n!=null&&x(e,["_url","name"],n),e}function r3(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 a3(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"],c3(c)),e}function l3(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&&r3(r,e),e}function c3(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 u3(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 d3(t){const e={},n=m(t,["config"]);return n!=null&&u3(n,e),e}function f3(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 HT(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 h3(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&&HT(i,e),e}function p3(t){const e={},n=m(t,["sdkHttpResponse"]);return n!=null&&x(e,["sdkHttpResponse"],n),e}const m3="Content-Type",g3="X-Server-Timeout",v3="User-Agent",N0="x-goog-api-client",x3="1.34.0",y3=`google-genai-sdk/${x3}`,_3="v1beta1",b3="v1beta";class S3{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:_3,r.baseUrl=this.baseUrlFromProjectLocation(),this.normalizeAuthParameters()):(r.apiVersion=(i=this.clientOptions.apiVersion)!==null&&i!==void 0?i:b3,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&&T3(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 OS(r),new w0(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 OS(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 _h({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=y3+" "+this.clientOptions.userAgentExtra;return e[v3]=n,e[N0]=n,e[m3]="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(g3,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&&HT(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 OS(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 _h({message:r,status:n}):new Error(r)}}function T3(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 E3="mcp_used/unknown";let w3=!1;function GT(t){for(const e of t)if(M3(e)||typeof e=="object"&&"inputSchema"in e)return!0;return w3}function jT(t){var e;const n=(e=t[N0])!==null&&e!==void 0?e:"";t[N0]=(n+` ${E3}`).trimStart()}function M3(t){return t!==null&&typeof t=="object"&&t instanceof Jg}function C3(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(C3(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(),sN(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 A3(t,e,n){const i=new KR;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 R3{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=D3(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=>{A3(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,I3(c),T);A.connect(),await g;const I={setup:{model:zn(this.apiClient,e.model)}};return A.send(JSON.stringify(I)),new N3(A,this.apiClient)}}class N3{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=nI(e);this.conn.send(JSON.stringify({clientContent:n}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});const n=tI(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 I3(t){const e={};return t.forEach((n,i)=>{e[i]=n}),e}function D3(t){const e=new Headers;for(const[n,i]of Object.entries(t))e.append(n,i);return e}const L3="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function U3(t,e,n){const i=new JR;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=sI(a);Object.assign(i,c)}else Object.assign(i,a);e(i)}class k3{constructor(e,n,i){this.apiClient=e,this.auth=n,this.webSocketFactory=i,this.music=new R3(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&>(e.config.tools)&&jT(v);const y=O3(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",Q="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",Q="access_token"),g=`${h}/ws/google.ai.generativelanguage.${d}.GenerativeService.${P}?${Q}=${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=>{U3(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,F3(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 H=(u=(c=e.config)===null||c===void 0?void 0:c.tools)!==null&&u!==void 0?u:[],V=[];for(const k of H)if(this.isCallableTool(k)){const P=k;V.push(await P.tool())}else V.push(k);V.length>0&&(e.config.tools=V);const Z={model:D,config:e.config,callbacks:e.callbacks};return this.apiClient.isVertexAI()?W=eI(this.apiClient,Z):W=Q2(this.apiClient,Z),delete W.config,L.send(JSON.stringify(W)),new P3(L,this.apiClient)}isCallableTool(e){return"callTool"in e&&typeof e.callTool=="function"}}const z3={turnComplete:!0};class P3{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=>bh(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(L3)}return{toolResponse:{functionResponses:i}}}sendClientContent(e){e=Object.assign(Object.assign({},z3),e);const n=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(n))}sendRealtimeInput(e){let n={};this.apiClient.isVertexAI()?n={realtimeInput:oI(e)}:n={realtimeInput:iI(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 F3(t){const e={};return t.forEach((n,i)=>{e[i]=n}),e}function O3(t){const e=new Headers;for(const[n,i]of Object.entries(t))e.append(n,i);return e}const BS=10;function VS(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 B3(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 HS(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 GS(t){var e;return!(!((e=t?.automaticFunctionCalling)===null||e===void 0)&&e.ignoreCallHistory)}class V3 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),!B3(n)||VS(n.config))return await this.generateContentInternal(h);const d=HS(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:BS;let T=0;for(;T{var i,r,a,c,u;if(this.maybeMoveToResponseJsonSchem(n),VS(n.config)){const v=await this.processParamsMaybeAddMcpUsage(n);return await this.generateContentStreamInternal(v)}const h=HS(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&>(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()),jT(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:BS;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:V}}],yield yield Kt(k);const P=[];P.push(...Z),P.push({role:"user",parts:V});const Q=hs(v.contents).concat(P);v.contents=Q}else break}})})(this,h,e)}async generateContentInternal(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=zS(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=FS(g),y=new au;return Object.assign(y,v),y})}else{const d=kS(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=PS(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=zS(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=FS(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=kS(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=PS(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=kI(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=PI(g),y=new xS;return Object.assign(y,v),y})}else{const d=UI(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=zI(g),y=new xS;return Object.assign(y,v),y})}}async generateImagesInternal(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=XI(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=JI(g),y=new yS;return Object.assign(y,v),y})}else{const d=$I(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=YI(g),y=new yS;return Object.assign(y,v),y})}}async editImageInternal(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI()){const u=NI(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=II(h),g=new OR;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=XD(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=YD(h),g=new BR;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=RD(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=ND(h),g=new VR;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=zD(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=PD(h),g=new HR;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=hD(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=>R0(g))}else{const d=fD(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=>A0(g))}}async listInternal(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=SD(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=ED(g),y=new _S;return Object.assign(y,v),y})}else{const d=bD(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=TD(g),y=new _S;return Object.assign(y,v),y})}}async update(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=WD(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=>R0(g))}else{const d=qD(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=>A0(g))}}async delete(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=MI(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=AI(g),y=new bS;return Object.assign(y,v),y})}else{const d=wI(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=CI(g),y=new bS;return Object.assign(y,v),y})}}async countTokens(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=SI(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=EI(g),y=new SS;return Object.assign(y,v),y})}else{const d=bI(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=TI(g),y=new SS;return Object.assign(y,v),y})}}async computeTokens(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI()){const u=pI(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=mI(h),g=new GR;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=nD(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=eD(g),y=new Qf;return Object.assign(y,v),y})}else{const d=tD(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=QI(g),y=new Qf;return Object.assign(y,v),y})}}}class H3 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=LR(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=DR(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=wR(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 G3(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 j3(t){const e={},n=m(t,["parts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(a=>Q3(a))),x(e,["parts"],r)}const i=m(t,["role"]);return i!=null&&x(e,["role"],i),e}function q3(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"],Z3(t,u));const h=m(e,["lockAdditionalFields"]);return n!==void 0&&h!=null&&x(n,["fieldMask"],h),i}function W3(t,e){const n={},i=m(e,["config"]);return i!=null&&x(n,["config"],q3(t,i,n)),n}function $3(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 X3(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 Y3(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 J3(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 K3(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"],Yg(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"],j3(vo(T)));const A=m(t,["tools"]);if(e!==void 0&&A!=null){let H=gc(A);Array.isArray(H)&&(H=H.map(V=>tL(mc(V)))),x(e,["setup","tools"],H)}const E=m(t,["sessionResumption"]);e!==void 0&&E!=null&&x(e,["setup","sessionResumption"],eL(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 Z3(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"],K3(r,n)),n}function Q3(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"],$3(a));const c=m(t,["functionCall"]);c!=null&&x(e,["functionCall"],X3(c));const u=m(t,["functionResponse"]);u!=null&&x(e,["functionResponse"],u);const h=m(t,["inlineData"]);h!=null&&x(e,["inlineData"],G3(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 eL(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 tL(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"],Y3(u));const h=m(t,["googleSearch"]);h!=null&&x(e,["googleSearch"],J3(h));const d=m(t,["urlContext"]);return d!=null&&x(e,["urlContext"],d),e}function nL(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 iL(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=nL(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 oL 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=W3(this.apiClient,e);a=Et("auth_tokens",u._url),c=u._query,delete u.config,delete u._url,delete u._query;const h=iL(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 sL(t,e){const n={},i=m(t,["force"]);return e!==void 0&&i!=null&&x(e,["_query","force"],i),n}function rL(t){const e={},n=m(t,["name"]);n!=null&&x(e,["_url","name"],n);const i=m(t,["config"]);return i!=null&&sL(i,e),e}function aL(t){const e={},n=m(t,["name"]);return n!=null&&x(e,["_url","name"],n),e}function lL(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 cL(t){const e={},n=m(t,["parent"]);n!=null&&x(e,["_url","parent"],n);const i=m(t,["config"]);return i!=null&&lL(i,e),e}function uL(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 dL 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=aL(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=rL(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=cL(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=uL(h),g=new jR;return Object.assign(g,d),g})}}}class fL extends br{constructor(e,n=new dL(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=n3(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=s3(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=o3(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=d3(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=f3(h),g=new qR;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=h3(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=p3(h),g=new WR;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=l3(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=a3(h),g=new jg;return Object.assign(g,d),g})}}}let qT=function(){const{crypto:t}=globalThis;if(t?.randomUUID)return qT=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 hL=()=>qT();function I0(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const D0=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 Eh({message:i,cause:D0(n)});const a=n;return e===400?new $T(e,a,i,r):e===401?new XT(e,a,i,r):e===403?new YT(e,a,i,r):e===404?new JT(e,a,i,r):e===409?new KT(e,a,i,r):e===422?new ZT(e,a,i,r):e===429?new QT(e,a,i,r):e>=500?new eE(e,a,i,r):new Eo(e,a,i,r)}}class L0 extends Eo{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Eh extends Eo{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}}class WT extends Eh{constructor({message:e}={}){super({message:e??"Request timed out."})}}class $T extends Eo{}class XT extends Eo{}class YT extends Eo{}class JT extends Eo{}class KT extends Eo{}class ZT extends Eo{}class QT extends Eo{}class eE extends Eo{}const pL=/^[a-z][a-z0-9+.-]*:/i,mL=t=>pL.test(t);let U0=t=>(U0=Array.isArray,U0(t));const gL=U0;let vL=gL;const jS=vL;function xL(t){if(!t)return!0;for(const e in t)return!1;return!0}function yL(t,e){return Object.prototype.hasOwnProperty.call(t,e)}const _L=(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},bL=t=>{try{return JSON.parse(t)}catch{return}};const SL=t=>new Promise(e=>setTimeout(e,t));const ql="0.0.1";function TL(){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 EL=()=>{var t,e,n,i,r;const a=TL();if(a==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ql,"X-Stainless-OS":WS(Deno.build.os),"X-Stainless-Arch":qS(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":WS((n=globalThis.process.platform)!==null&&n!==void 0?n:"unknown"),"X-Stainless-Arch":qS((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=wL();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 wL(){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 qS=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",WS=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 ML=()=>Jd??(Jd=EL());function CL(){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 tE(...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 AL(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return tE({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 nE(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 RL(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 NL=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});const iE=()=>{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 Lm(t,e,n){return iE(),new File(t,e??"unknown_file",n)}function IL(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 DL=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function";const oE=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",LL=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&oE(t),UL=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function kL(t,e,n){if(iE(),t=await t,LL(t))return t instanceof File?t:Lm([await t.arrayBuffer()],t.name);if(UL(t)){const r=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Lm(await k0(r),e,n)}const i=await k0(t);if(e||(e=IL(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 Lm(i,e,n)}async function k0(t){var e,n,i,r,a;let c=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)c.push(t);else if(oE(t))c.push(t instanceof Blob?t:await t.arrayBuffer());else if(DL(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 k0(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}`:""}${zL(t)}`)}return c}function zL(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}class sE{constructor(e){this._client=e}}sE._key=[];function rE(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const $S=Object.freeze(Object.create(null)),PL=(t=rE)=>(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:$S))!==null&&T!==void 0?T:$S))===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=PL(rE);class aE extends sE{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}))}}aE._key=Object.freeze(["interactions"]);class lE extends aE{}function FL(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 Kg(t){let e;return(Zd??(e=new globalThis.TextEncoder,Zd=e.encode.bind(e)))(t)}let Qd;function XS(t){let e;return(Qd??(e=new globalThis.TextDecoder,Qd=e.decode.bind(e)))(t)}class wh{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"?Kg(e):e;this.buffer=FL([this.buffer,n]);const i=[];let r;for(;(r=OL(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(XS(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=XS(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(` -`):[]}}wh.NEWLINE_CHARS=new Set([` -`,"\r"]);wh.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function OL(t,e){for(let r=e??0;r{if(t){if(yL(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 VL={error:Su,warn:Su,info:Su,debug:Su};let JS=new WeakMap;function So(t){var e;const n=t.logger,i=(e=t.logLevel)!==null&&e!==void 0?e:"off";if(!n)return VL;const r=JS.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 JS.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(HL(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(I0(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 wh,S=nE(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(I0(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 tE({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=Kg(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 HL(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 jL,h=new wh,d=nE(t.body);try{for(var g=!0,v=Cs(GL(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 GL(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"?Kg(g):g;let y=new Uint8Array(c.length+v.length);y.set(c),y.set(v,c.length),c=y;let S;for(;(S=BL(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 jL{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]=qL(e,":");return r.startsWith(" ")&&(r=r.substring(1)),n==="event"?this.event=r:n==="data"&&this.data.push(r),null}}function qL(t,e){const n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}async function WL(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 Zg extends Promise{constructor(e,n,i=WL){super(r=>{r(null)}),this.responsePromise=n,this.parseResponse=i,this.client=e}_thenUnwrap(e){return new Zg(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 cE=Symbol("brand.privateNullableHeaders");function*$L(t){if(!t)return;if(cE 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():jS(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=jS(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 $L(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{[cE]:!0,values:e,nulls:n}};const Um=t=>{var e,n,i,r,a,c;if(typeof globalThis.process<"u")return(i=(n=(e=yR)===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 uE;class Mh{constructor(e){var n,i,r,a,c,u,h,{baseURL:d=Um("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:g=(n=Um("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:Mh.DEFAULT_TIMEOUT,this.logger=(r=S.logger)!==null&&r!==void 0?r:console;const T="warn";this.logLevel=T,this.logLevel=(c=(a=YS(S.logLevel,"ClientOptions.logLevel",this))!==null&&a!==void 0?a:YS(Um("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:CL(),this.encoder=NL,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-${hL()}`}makeStatusError(e,n,i,r){return Eo.generate(e,n,i,r)}buildURL(e,n,i){const r=!this.baseURLOverridden()&&i||this.baseURL,a=mL(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),c=this.defaultQuery();return xL(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 Zg(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 L0;const A=new AbortController,E=await this.fetchWithTimeout(g,d,v,A).catch(D0),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 L0;const D=I0(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 WT:new Eh({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 RL(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=>D0(k).message),H=bL(W),V=H?void 0:W;throw So(this).debug(`[${y}] response error (${D})`,Ra({retryOfRequestLogID:i,url:E.url,status:E.status,headers:E.headers,message:V,durationMs:Date.now()-T})),this.makeStatusError(E.status,H,V,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 SL(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&&_L("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))}:{}),ML()),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:AL(e)}:this.encoder({body:e,headers:i})}}Mh.DEFAULT_TIMEOUT=6e4;class no extends Mh{constructor(){super(...arguments),this.interactions=new lE(this)}}uE=no;no.GeminiNextGenAPIClient=uE;no.GeminiNextGenAPIClientError=ps;no.APIError=Eo;no.APIConnectionError=Eh;no.APIConnectionTimeoutError=WT;no.APIUserAbortError=L0;no.NotFoundError=JT;no.ConflictError=KT;no.RateLimitError=QT;no.BadRequestError=$T;no.AuthenticationError=XT;no.InternalServerError=eE;no.PermissionDeniedError=YT;no.UnprocessableEntityError=ZT;no.toFile=kL;no.Interactions=lE;function XL(t,e){const n={},i=m(t,["name"]);return i!=null&&x(n,["_url","name"],i),n}function YL(t,e){const n={},i=m(t,["name"]);return i!=null&&x(n,["_url","name"],i),n}function JL(t,e){const n={},i=m(t,["sdkHttpResponse"]);return i!=null&&x(n,["sdkHttpResponse"],i),n}function KL(t,e){const n={},i=m(t,["sdkHttpResponse"]);return i!=null&&x(n,["sdkHttpResponse"],i),n}function ZL(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 QL(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"],KS(S))}else if(r==="PREFERENCE_TUNING"){const S=m(t,["validationDataset"]);e!==void 0&&S!=null&&x(e,["preferenceOptimizationSpec"],KS(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 eU(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&&dU(a);const c=m(t,["config"]);return c!=null&&ZL(c,n),n}function tU(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&&fU(a,n,e);const c=m(t,["config"]);return c!=null&&QL(c,n,e),n}function nU(t,e){const n={},i=m(t,["name"]);return i!=null&&x(n,["_url","name"],i),n}function iU(t,e){const n={},i=m(t,["name"]);return i!=null&&x(n,["_url","name"],i),n}function oU(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 sU(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 rU(t,e){const n={},i=m(t,["config"]);return i!=null&&oU(i,n),n}function aU(t,e){const n={},i=m(t,["config"]);return i!=null&&sU(i,n),n}function lU(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=>dE(u))),x(n,["tuningJobs"],c)}return n}function cU(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=>z0(u))),x(n,["tuningJobs"],c)}return n}function uU(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 dU(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 fU(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 dE(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"],CT(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"],uU(y)),n}function z0(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"],CT(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 H=m(t,["labels"]);H!=null&&x(n,["labels"],H);const V=m(t,["outputUri"]);V!=null&&x(n,["outputUri"],V);const Z=m(t,["pipelineJob"]);Z!=null&&x(n,["pipelineJob"],Z);const k=m(t,["serviceAccount"]);k!=null&&x(n,["serviceAccount"],k);const P=m(t,["tunedModelDisplayName"]);P!=null&&x(n,["tunedModelDisplayName"],P);const Q=m(t,["veoTuningSpec"]);return Q!=null&&x(n,["veoTuningSpec"],Q),n}function hU(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 KS(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 pU 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:E0.JOB_STATE_QUEUED}}}}async getInternal(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=iU(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=>z0(g))}else{const d=nU(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=>dE(g))}}async listInternal(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=aU(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=cU(g),y=new TS;return Object.assign(y,v),y})}else{const d=rU(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=lU(g),y=new TS;return Object.assign(y,v),y})}}async cancel(e){var n,i,r,a;let c,u="",h={};if(this.apiClient.isVertexAI()){const d=YL(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=KL(g),y=new ES;return Object.assign(y,v),y})}else{const d=XL(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=JL(g),y=new ES;return Object.assign(y,v),y})}}async tuneInternal(e){var n,i;let r,a="",c={};if(this.apiClient.isVertexAI()){const u=tU(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=>z0(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=eU(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=>hU(h))}}}class mU{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 gU=1024*1024*8,vU=3,xU=1e3,yU=2,ih="x-goog-upload-status";async function _U(t,e,n){var i;const r=await fE(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 bU(t,e,n){var i;const r=await fE(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=bT(a),u=new qg;return Object.assign(u,c),u}async function fE(t,e,n){var i,r;let a=0,c=0,u=new w0(new Response),h="upload";for(a=t.size;c=a&&(h+=", finalize");let v=0,y=xU;for(;vsetTimeout(e,t))}class EU{async upload(e,n,i){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await _U(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 bU(e,n,i)}async stat(e){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await SU(e)}}class wU{create(e,n,i){return new MU(e,n,i)}}class MU{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 ZS="x-goog-api-key";class CU{constructor(e){this.apiKey=e}async addAuthHeaders(e,n){if(e.get(ZS)===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(ZS,this.apiKey)}}}const AU="gl-node/";class RU{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=TR(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 CU(this.apiKey);this.apiClient=new S3({auth:r,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:AU+"web",uploader:new EU,downloader:new mU}),this.models=new V3(this.apiClient),this.live=new k3(this.apiClient,r,new wU),this.batches=new ZN(this.apiClient),this.chats=new L2(this.models,this.apiClient),this.caches=new N2(this.apiClient),this.files=new G2(this.apiClient),this.operations=new H3(this.apiClient),this.authTokens=new oL(this.apiClient),this.tunings=new pU(this.apiClient),this.fileSearchStores=new fL(this.apiClient)}}const NU=t=>new RU({apiKey:t}),IU={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"]},DU={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 LU(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 UU(t,e,n,i,r,a="line"){try{const c=NU(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"?DU:IU,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*```$/,"")),(LU(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 kU=({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=Re.useRef(null),T=Re.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]=Re.useState(null),[I,L]=Re.useState({key:null,direction:"asc"}),[D,W]=Re.useState(new Set),[H,V]=Re.useState(new Set),[Z,k]=Re.useState(localStorage.getItem("gemini_api_key")||""),[P,Q]=Re.useState("gemini-2.5-flash"),[ue,se]=Re.useState("line"),[Te,$e]=Re.useState(!1),X=Re.useRef(null),[ve,ie]=Re.useState(null);Re.useEffect(()=>{Z&&localStorage.setItem("gemini_api_key",Z)},[Z]);const nt=n>=0?t[n]:null,Ce=nt?.parsedLyrics||[],$=Re.useMemo(()=>nt?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 be=z=>{if(t.length===0)return;const j=n>=0?t[n]:null,B=[...t];let ae="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"&&(ae="desc"),L({key:z,direction:ae});const Y=ae==="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)}},Fe=Re.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]);Re.useEffect(()=>{const z=S.current;if(z)return z.addEventListener("keydown",Fe),()=>z.removeEventListener("keydown",Fe)},[Fe]),Re.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 J=j.get(M);["mp3","wav","ogg","flac","m4a","mp4","webm","ogg","mkv","mov","avi","m4v"].includes(ee||"")?J.audio=me:["lrc","srt","ttml","xml","json","vtt"].includes(ee||"")&&(J.lyric=me)});const B=[],ae=async(me,ee)=>new Promise(Xe=>{if(me.type.startsWith("video/")){Xe({title:ee,artist:"Unknown Artist",coverUrl:URL.createObjectURL(me),backgroundType:"video"});return}x0(()=>import("./jsmediatags.min-BZxB3j-v.js").then(M=>M.j),[]).then(M=>{M.read(me,{onSuccess:J=>{const{title:fe,artist:de,album:ke,picture:Je}=J.tags;let ht=null;if(Je){const{data:et,format:Se}=Je;let Ke="";for(let Ve=0;Ve{Xe({title:ee,artist:"Unknown Artist",coverUrl:null})}})}).catch(()=>{Xe({title:ee,artist:"Unknown Artist",coverUrl:null})})}),Y=async me=>{try{const ee=await me.text(),Xe=me.name.split(".").pop()?.toLowerCase();if(Xe==="lrc")return ea(ee);if(Xe==="srt")return ta(ee);if(Xe==="ttml"||Xe==="xml")return Pa(ee);if(Xe==="vtt")return Fa(ee);if(Xe==="json")return cR(ee)}catch(ee){console.error("Failed to parse lyrics",ee)}return[]};for(const[me,ee]of j.entries())if(ee.audio){const Xe=await ae(ee.audio,me),M=Math.random().toString(36).substr(2,9);let J=[];ee.lyric&&(J=await Y(ee.lyric)),B.push({id:M,audioFile:ee.audio,lyricFile:ee.lyric,parsedLyrics:J,metadata:Xe,duration:0})}if(B.length>0){const me=[...t,...B];e(me),r(0,!1,me)}},Ae=async z=>{if(z.target.files&&z.target.files.length>0){const j=Array.from(z.target.files);await oe(j),z.target.value=""}},[Qe,we]=Re.useState(!1),[N,ye]=Re.useState(null),[xe,Le]=Re.useState(null),[st,tt]=Re.useState(null),U=(z,j)=>{ye(j),z.dataTransfer.effectAllowed="move"},Ee=(z,j)=>{if(z.preventDefault(),z.stopPropagation(),N===null||N===j)return;const B=z.currentTarget.getBoundingClientRect(),ae=B.top+B.height/2,Y=z.clientY{if(z.preventDefault(),z.stopPropagation(),N===null)return;const B=[...t],[ae]=B.splice(N,1);let Y=j;st==="after"&&Y++,N=n?i(n-1):N>n&&Y<=n&&i(n+1),lt()},lt=()=>{ye(null),Le(null),tt(null)},We=z=>{z.preventDefault(),z.stopPropagation(),N===null&&we(!0)},gt=z=>{z.preventDefault(),z.stopPropagation(),we(!1)},qe=async z=>{if(z.preventDefault(),z.stopPropagation(),we(!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 ae=new FileReader;ae.readAsDataURL(z),ae.onload=()=>{const Y=ae.result.split(",")[1];j(Y)},ae.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=Z||"PLACEHOLDER_API_KEY";if(j.trim().length<39){alert(`Invalid API Key length (${j.trim().length}). It must be at least 39 characters.`),$e(!0);return}W(Y=>new Set(Y).add(z.id));const B=new AbortController;T.current.set(z.id,B);const ae=19.5*1024*1024;if(z.audioFile.size>ae){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 J=new Audio(URL.createObjectURL(z.audioFile));J.onloadedmetadata=()=>{M(J.duration),URL.revokeObjectURL(J.src)},J.onerror=()=>{URL.revokeObjectURL(J.src),M(0)}})}catch(M){console.warn("Could not determine duration for AI validation",M)}let Xe=(await UU(P,Y,z.audioFile.type,j,B.signal,ue)).map(M=>({time:bu(M.startTime),text:M.text,endTime:bu(M.endTime),words:M.words?M.words.map(J=>({text:J.text,startTime:bu(J.startTime),endTime:bu(J.endTime)})):void 0}));me>0&&(Xe=Xe.filter(M=>M.time=0)),e(M=>M.map(J=>J.id===z.id?{...J,parsedLyrics:Xe.sort((fe,de)=>fe.time-de.time),duration:me>0?me:J.duration}:J))}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})}},le=async z=>{if(!navigator.onLine){alert("No internet connection.");return}V(j=>new Set(j).add(z.id));try{const j=await x0(()=>import("./index.min-B27ELfOc.js").then(Xe=>Xe.i),[]);let B;const ae=j.default||j;console.log("SyncLyrics Module:",j);const Y=["musixmatch","lrclib","netease"];if(typeof ae=="function"&&ae.prototype&&ae.prototype.getLyrics){console.log("Detected Class usage");const Xe=new ae({sources:Y});B=M=>Xe.getLyrics(M)}else if(ae.getLyrics&&typeof ae.getLyrics=="function")console.log("Detected Instance usage"),B=Xe=>ae.getLyrics(Xe);else if(ae.SyncLyrics){console.log("Detected Mod.SyncLyrics export");const Xe=ae.SyncLyrics;if(typeof Xe=="function"&&Xe.prototype&&Xe.prototype.getLyrics){console.log("Using SyncLyrics as Class");const M=new Xe({sources:Y});B=J=>M.getLyrics(J)}else if(typeof Xe=="function")console.log("Using SyncLyrics as Function"),B=Xe;else throw new Error("Mod.SyncLyrics found but is not a function or class.")}else if(typeof ae=="function")console.log("Detected Function usage"),B=ae;else throw new Error(`Could not find suitable search function. Mod type: ${typeof ae}. Keys: ${typeof ae=="object"?JSON.stringify(Object.keys(ae)):"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")Ne(ee,z);else{console.warn("npm package returned no result. Attempting fallback to LrcLib.net API directly...");let Xe=z.duration||0;if(Xe===0)try{Xe=await new Promise(de=>{const ke=new Audio(URL.createObjectURL(z.audioFile));ke.onloadedmetadata=()=>{const Je=ke.duration;URL.revokeObjectURL(ke.src),de(Je)},ke.onerror=()=>de(0)})}catch(de){console.warn("Could not determine duration for search",de)}const M=new URLSearchParams({artist_name:z.metadata.artist,track_name:z.metadata.title,album_name:z.metadata.album||"",duration:Xe.toString()}),J=await fetch(`https://lrclib.net/api/get?${M.toString()}`);if(!J.ok){const de=await fetch(`https://lrclib.net/api/search?q=${encodeURIComponent(z.metadata.title+" "+z.metadata.artist)}`);if(de.ok){const ke=await de.json();if(Array.isArray(ke)&&ke.length>0){const Je=ke.find(ht=>ht.syncedLyrics);if(Je){Ne(Je.syncedLyrics,z);return}else if(ke[0].plainLyrics){Ne(ke[0].plainLyrics,z);return}}}throw new Error("No lyrics found in fallback source.")}const fe=await J.json();fe.syncedLyrics?Ne(fe.syncedLyrics,z):fe.plainLyrics?Ne(fe.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{V(j=>{const B=new Set(j);return B.delete(z.id),B})}},Ne=(z,j)=>{let B=ea(z);if(B.length===0&&(B=ta(z)),B.length>0){const ae=B.some(Y=>Y.words&&Y.words.length>0);console.log(ae?"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${ae?".lrc-enhanced":".lrc"}`,{type:"text/plain"})}:me))}else alert("Lyrics found but could not be parsed.")},De=(z,j,B)=>{const ae=new Blob([z],{type:"application/octet-stream"}),Y=URL.createObjectURL(ae),me=document.createElement("a");me.href=Y,me.download=j,document.body.appendChild(me),me.click(),document.body.removeChild(me),URL.revokeObjectURL(Y)},rt=async(z,j)=>{const B=z.parsedLyrics||[];if(B.length===0)return;let ae="";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 J=new Audio(URL.createObjectURL(z.audioFile));J.onloadedmetadata=()=>{M(J.duration),URL.revokeObjectURL(J.src)},J.onerror=()=>M(0)})}catch(M){console.warn("Could not determine duration for export check",M)}const Xe=B.map(M=>({...M,words:M.words?M.words.filter(J=>J.text.trim().length>0).map(J=>({...J})):void 0}));for(let M=0;M0?ee:J.time+5),J.words&&J.words.length>0)for(let de=0;deM.text).join(` -`);else if(j==="json")ae=JSON.stringify(Xe,null,2);else if(j==="srt"){const M=J=>{const fe=Math.floor(J/3600).toString().padStart(2,"0"),de=Math.floor(J%3600/60).toString().padStart(2,"0"),ke=Math.floor(J%60).toString().padStart(2,"0"),Je=Math.floor(J%1*1e3).toString().padStart(3,"0");return`${fe}:${de}:${ke},${Je}`};ae=Xe.map((J,fe)=>{const de=M(J.time),ke=J.endTime!==void 0&&J.endTime>J.time?J.endTime:J.time+2,Je=M(ke);return`${fe+1} -${de} --> ${Je} -${J.text} -`}).join(` -`)}else if(j==="lrc"){const M=[],J=fe=>{const de=Math.floor(fe/60).toString().padStart(2,"0"),ke=(fe%60).toFixed(2).padStart(5,"0");return`[${de}:${ke}]`};for(let fe=0;fe0)||ht<=ee)&&(ke?ke.time>ht&&M.push(`${J(ht)}`):M.push(`${J(ht)}`))}ae=M.join(` -`)}else if(j==="lrc-enhanced"){const M=[],J=de=>{const ke=Math.floor(de/60).toString().padStart(2,"0"),Je=(de%60).toFixed(2).padStart(5,"0");return`[${ke}:${Je}]`},fe=de=>{const ke=Math.floor(de/60).toString().padStart(2,"0"),Je=(de%60).toFixed(2).padStart(5,"0");return`<${ke}:${Je}>`};for(let de=0;de0?ke.words.forEach((Ve,_t)=>{const Jt=Ve.text.replace(/[ \t]+/g," ").trim().replace(/\n/g,"\\n");ht+=`${fe(Ve.startTime)}${Jt}`,_t0)||Se<=ee)&&(Je?Je.time>Se&&M.push(`${J(Se)}`):M.push(`${J(Se)}`))}ae=M.join(` -`)}else if(j==="ttml"){const M=J=>{const fe=Math.floor(J/3600).toString().padStart(2,"0"),de=Math.floor(J%3600/60).toString().padStart(2,"0"),ke=Math.floor(J%60).toString().padStart(2,"0"),Je=Math.floor(J%1*1e3).toString().padStart(3,"0");return`${fe}:${de}:${ke}.${Je}`};ae=` - - -
`,Xe.forEach(J=>{const fe=M(J.time),de=J.endTime!==void 0&&J.endTime>J.time?J.endTime:J.time+3,ke=M(de);ae+=` -

`,J.words&&J.words.length>0?J.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 Se=M(et);let Ke=Je.text.replace(/[ \t]+/g," ").trim();Ke.endsWith("-")||(Ke+=" "),ae+=` - ${Ke}`}):ae+=` - ${J.text.replace(/-\s+/g,"-").replace(/[ \t]+/g," ").trim()}`,ae+=` -

`}),ae+=` -
- -
`}else if(j==="vtt"){const M=J=>{const fe=Math.floor(J/3600).toString().padStart(2,"0"),de=Math.floor(J%3600/60).toString().padStart(2,"0"),ke=Math.floor(J%60).toString().padStart(2,"0"),Je=Math.floor(J%1*1e3).toString().padStart(3,"0");return`${fe}:${de}:${ke}.${Je}`};ae=`WEBVTT - -`,Xe.forEach(J=>{const fe=M(J.time),de=J.endTime!==void 0&&J.endTime>J.time?J.endTime:J.time+2,ke=M(de);let Je=J.text.trim();if(J.words&&J.words.length>0){const ht=J.words.map(et=>`<${M(et.startTime)}>${et.text.trim()}`).join(" ");ht.length>0&&(Je=ht)}ae+=`${fe} --> ${ke} -${Je} - -`})}De(ae,me)},it=async()=>{if(t.length===0)return;const z=async B=>new Promise(ae=>{const Y=new Audio(URL.createObjectURL(B));Y.onloadedmetadata=()=>{ae(Y.duration),URL.revokeObjectURL(Y.src)},Y.onerror=()=>{ae(0),URL.revokeObjectURL(Y.src)}});let j=`#EXTM3U -`;for(const B of t){let ae=B.duration||0;if(ae===0)try{ae=await z(B.audioFile)}catch(M){console.error("Failed to get duration for export",M)}const Y=Math.round(ae),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 Xe=B.audioFile.webkitRelativePath||B.audioFile.name;j+=`${Xe} -`}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))},ce=async z=>{const j=z.target.files?.[0];if(!(!j||!ve)){try{const B=await j.text(),ae=j.name.split(".").pop()?.toLowerCase();let Y=[];ae==="lrc"?Y=ea(B):ae==="srt"?Y=ta(B):ae==="ttml"||ae==="xml"?Y=Pa(B):ae==="vtt"&&(Y=Fa(B)),Y.length>0?e(me=>me.map(ee=>ee.id===ve?{...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.")}ie(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 ${Qe?"bg-zinc-800 border-orange-500":""}`,onDragOver:We,onDragLeave:gt,onDrop:qe,children:[Qe&&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:ce}),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(yT,{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:Ae})]}),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(JC,{size:14}),p.jsx("input",{type:"file",name:"add-folder",id:"add-folder",className:"hidden",multiple:!0,webkitdirectory:"",onChange:Ae})]})]}),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:()=>be("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:()=>be("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(eR,{size:14,className:I.key==="artist"&&I.direction==="desc"?"rotate-180 transition-transform":"transition-transform"})}),p.jsx("button",{onClick:()=>be("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:()=>be("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(OC,{size:14,className:I.key==="album"&&I.direction==="desc"?"rotate-180 transition-transform":"transition-transform"})}),p.jsx("button",{onClick:()=>be("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(LA,{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:()=>$e(!Te),className:`p-1 rounded transition-colors ${Te?"text-orange-400":"text-zinc-500 hover:text-zinc-300"}`,title:"Gemini API Key",children:p.jsx(sA,{size:14})}),Te&&p.jsx("input",{type:Z?"password":"text",name:"api-key","aria-label":"Gemini API Key",value:Z,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=>Q(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:ue,onChange:z=>se(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(WC,{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,ae=j===E,Y=z.parsedLyrics||[],me=B?Y.findIndex((ee,Xe)=>{if(ee.endTime!==void 0)return g>=ee.time&&g=ee.time&&(!M||gU(ee,j),onDragEnd:lt,onDragOver:ee=>Ee(ee,j),onDrop:ee=>Oe(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"} - ${ae?"ring-2 ring-blue-500/70 ring-offset-1 ring-offset-zinc-950":""} - ${N===j?"opacity-50 border-dashed border-zinc-500":""} - ${xe===j&&st==="before"?"border-t-2 border-t-orange-500":""} - ${xe===j&&st==="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(QC,{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(xT,{size:14}):p.jsx(_0,{size:14}):p.jsx(_0,{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,Xe)=>{const M=Xe===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:J=>{J.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||"♪"})]},Xe)})}):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(),ie(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(),le(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 ${H.has(z.id)?"animate-pulse":""}`,title:"Search Lyrics (Online)",disabled:H.has(z.id),children:H.has(z.id)?p.jsx(gb,{size:14,className:"animate-spin"}):p.jsx(NA,{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(gb,{size:14,className:"animate-spin group-hover/btn:hidden"}),p.jsx(S0,{size:14,className:"hidden group-hover/btn:block fill-current"})]}):p.jsx(b0,{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(),rt(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(),rt(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(),rt(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(),rt(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(),rt(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(),rt(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(),rt(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)})})]})},Qg=[{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"}]}],hE=["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"],zU=()=>{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)}Qg.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 hE.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)})},PU=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`;hE.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)},ev=[{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"}},km=ev.flatMap(t=>t.options.map(e=>e.value)),zm=({onApply:t,placeholder:e="Google Font Name"})=>{const{toast:n}=Ou(),[i,r]=Re.useState(""),a=()=>{if(!i.trim())return;const c=i.trim().replace(/['"]/g,"").replace(/\s+/g," ");PU(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"})]})},QS={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},e1=[{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"}]}],t1=[{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"}]}],n1=[{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"}]}],i1=[{label:"Visual Transition",options:[{label:"None (Cut)",value:"none"},{label:"Crossfade",value:"crossfade"},{label:"Fade Through Black",value:"fade-to-black"}]}],P0=[{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},o1=[{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"}]}],FU=[{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"}]}],F0=[{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"}]}],pE=["none","upper","lower","title","sentence","invert"],s1=[{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"}]}],r1=[{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"}]}],OU=[{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]=Re.useState(!1),[a,c]=Re.useState(t);Re.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))})]})},BU=(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"},Pm=({value:t,onChange:e,customFontName:n,groups:i=Qg})=>{const[r,a]=Re.useState(!1),[c,u]=Re.useState(t);Re.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:BU(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))]})]})},VU=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},[]),HU=[{label:"Visual Presets",options:VU},...Qg],GU=({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:H,setRenderEngine:V,ffmpegCodec:Z,setFfmpegCodec:k,customChannelFontName:P,onChannelFontUpload:Q,onClearChannelCustomFont:ue,customInfoFontName:se,onInfoFontUpload:Te,onClearInfoCustomFont:$e})=>{const{toast:X,confirm:ve}=Ou(),[ie,nt]=Re.useState([]),Ce=(C,te)=>{ie.includes(C)||nt(Ne=>[C,...Ne]);const le=C.includes(" ")?`'${C}'`:C;U(te,le)},$=Vg.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}]}),ie.length>0&&C.push({label:"Loaded Google Fonts",options:ie.map(le=>({label:le,value:le.includes(" ")?`'${le}'`:le}))}),[...C,...HU]},[ie,t.fontFamily]),be=Re.useRef(null),Fe=Re.useRef(null),oe=Re.useRef(null),Ae=Re.useRef(null),Qe=Re.useRef(null),we=Re.useRef(null),N=Re.useRef(null),ye=Re.useRef(null),[xe,Le]=Re.useState(!1),[st,tt]=Re.useState(null),U=(C,te)=>{let le={...t,[C]:te};if(C==="highlightEffect"){const De=Uf(te);le.useCustomHighlightColors=!1,De?(le.highlightColor=De.color,le.highlightBackground=De.bg):(le.highlightColor="#fb923c",le.highlightBackground="#fb923c")}else if(C==="useCustomHighlightColors"&&te===!1){const Ne=t.highlightEffect,De=Uf(Ne);De?(le.highlightColor=De.color,le.highlightBackground=De.bg):(le.highlightColor="#fb923c",le.highlightBackground="#fb923c")}e(le)},Ee=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})},Oe=C=>{const te=C.target.files?.[0];if(te){const le=new FileReader;le.onload=Ne=>{Ne.target?.result&&U("channelInfoImage",Ne.target.result)},le.readAsDataURL(te)}C.target.value=""},lt=C=>{const te=C.target.files?.[0];if(te){const le=new FileReader;le.onload=Ne=>{Ne.target?.result&&U("backgroundImage",Ne.target.result)},le.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 le=new FileReader;le.onload=Ne=>{Ne.target?.result&&U("backgroundVideo",Ne.target.result)},le.readAsDataURL(te)}C.target.value=""},gt=async()=>{await ve(`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(QS),i("default"),y("1080p"),T("16:9"),E("auto"),W(30),L("med"),V("mediarecorder"),k("h264"),Qe.current&&(Qe.current.value=""),we.current&&(we.current.value=""),N.current&&(N.current.value=""),ye.current&&(ye.current.value=""),g(),ue&&ue(),$e&&$e(),Fe.current&&(Fe.current.value=""),oe.current&&(oe.current.value=""),Ae.current&&(Ae.current.value=""),tt(null),X.success("All settings have been reset to default."))},qe=()=>{const C=new Date,te=C.toISOString().replace(/[:.]/g,"-").slice(0,19),le=(z,j=6)=>typeof z=="number"?Number(z.toFixed(j)):z,Ne=(z,j,B,ae)=>{if(z===B&&j)return{slot:ae,cssValue:B,realName:j,source:"uploaded-file",warning:`Re-upload font file "${j}" after importing this config.`};if(z&&ie.some(Y=>z.includes(Y))){const Y=z.replace(/['"]/g,"").trim();return{slot:ae,cssValue:z,realName:Y,source:"google-font",warning:`Google Font "${Y}" – internet connection required on target machine.`}}return{slot:ae,cssValue:z??"sans-serif",realName:z??"sans-serif",source:"built-in",warning:""}},De=Ne(t.fontFamily,h,"CustomFont","lyrics"),rt=Ne(t.channelInfoFontFamily,P,"ChannelFont","channel-watermark"),it=Ne(t.infoFontFamily,se,"InfoFont","song-info"),F=[De,rt,it].filter(z=>z.source!=="built-in"),ce={_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:le(t.fontSizeScale),infoSizeScale:le(t.infoSizeScale),infoMarginScale:le(t.infoMarginScale),channelInfoSizeScale:le(t.channelInfoSizeScale),channelInfoMarginScale:le(t.channelInfoMarginScale),marginTopScale:le(t.marginTopScale),marginBottomScale:le(t.marginBottomScale),visualizationOpacity:le(t.visualizationOpacity,4),visualizationSensitivity:le(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,...rt.source!=="built-in"&&t.channelInfoFontFamily&&{__note_channelInfoFontFamily:`Real name: "${rt.realName}" [${rt.source}]`+(rt.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:H,ffmpegCodec:Z,customFontName:h,customChannelFontName:P,customInfoFontName:se,channelInfoFontWeight:t.channelInfoFontWeight,channelInfoFontStyle:t.channelInfoFontStyle,infoFontWeight:t.infoFontWeight,infoFontStyle:t.infoFontStyle};ce.backgroundSource!=="image"&&delete ce.backgroundImage,ce.backgroundSource!=="video"&&delete ce.backgroundVideo,ce.showChannelInfo||delete ce.channelInfoImage;try{const z=JSON.stringify(ce,null,2),j=new Blob([z],{type:"application/json"}),B=URL.createObjectURL(j),ae=document.createElement("a");ae.href=B,ae.download=`render_settings_${te}.json`,document.body.appendChild(ae),ae.click(),ae.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;tt(te.name);const le=new FileReader;le.onload=Ne=>{try{const De=JSON.parse(Ne.target?.result);if(De&&typeof De=="object"){const{_meta:rt,__note_fontFamily:it,__note_channelInfoFontFamily:F,__note_infoFontFamily:ce,resolution:z,aspectRatio:j,renderCodec:B,renderFps:ae,renderQuality:Y,renderEngine:me,ffmpegCodec:ee,preset:Xe,customFontName:M,customChannelFontName:J,customInfoFontName:fe,channelInfoFontWeight:de,channelInfoFontStyle:ke,infoFontWeight:Je,infoFontStyle:ht,...et}=De,Se={...QS,...et};if(de&&(Se.channelInfoFontWeight=de),ke&&(Se.channelInfoFontStyle=ke),Je&&(Se.infoFontWeight=Je),ht&&(Se.infoFontStyle=ht),["backgroundBlurStrength","fontSizeScale","infoMarginScale","infoSizeScale","channelInfoSizeScale","channelInfoMarginScale","visualTransitionDuration","lyricLineHeight","marginTopScale","marginBottomScale","visualizationOpacity","visualizationSensitivity","visualizationBarCount"].forEach(Zt=>{Se[Zt]!==void 0&&(Se[Zt]=Number(Se[Zt]))}),Se.useCustomHighlightColors!==void 0&&(Se.useCustomHighlightColors=!!Se.useCustomHighlightColors),Se.useRealColorMedia!==void 0&&(Se.useRealColorMedia=!!Se.useRealColorMedia),Se.showChannelInfo!==void 0&&(Se.showChannelInfo=!!Se.showChannelInfo),Se.showIntro!==void 0&&(Se.showIntro=!!Se.showIntro),Se.showTitle!==void 0&&(Se.showTitle=!!Se.showTitle),Se.showArtist!==void 0&&(Se.showArtist=!!Se.showArtist),Se.showCover!==void 0&&(Se.showCover=!!Se.showCover),Se.showLyrics!==void 0&&(Se.showLyrics=!!Se.showLyrics),Se.showVisualization!==void 0&&(Se.showVisualization=!!Se.showVisualization),Se.enableGradientOverlay!==void 0&&(Se.enableGradientOverlay=!!Se.enableGradientOverlay),Se.threejsCameraMovement!==void 0&&(Se.threejsCameraMovement=!!Se.threejsCameraMovement),Se.highlightEffect&&(!Se.highlightColor||!Se.highlightBackground)){const Zt=Uf(Se.highlightEffect);Zt&&(Se.highlightColor||(Se.highlightColor=Zt.color),Se.highlightBackground||(Se.highlightBackground=Zt.bg))}const Ve=(Zt,ti)=>ti.some(Gi=>Gi.options.some(Si=>Si.value===Zt));Se.textEffect&&!Ve(Se.textEffect,e1)&&(Se.textEffect="shadow"),Se.textAnimation&&!Ve(Se.textAnimation,t1)&&(Se.textAnimation="none"),Se.transitionEffect&&!Ve(Se.transitionEffect,n1)&&(Se.transitionEffect="none"),Se.visualTransitionType&&!Ve(Se.visualTransitionType,i1)&&(Se.visualTransitionType="none"),Se.highlightEffect&&!Ve(Se.highlightEffect,P0)&&(Se.highlightEffect="karaoke"),Se.backgroundSource&&!Ve(Se.backgroundSource,o1)&&(Se.backgroundSource="custom"),["current","playlist"].includes(Se.renderMode)||(Se.renderMode="current"),["left","center","right"].includes(Se.textAlign)||(Se.textAlign="center"),["top","center","bottom"].includes(Se.contentPosition)||(Se.contentPosition="center"),Se.marginTopScale===void 0||isNaN(Se.marginTopScale)?Se.marginTopScale=1:Se.marginTopScale=Math.max(0,Math.min(5,Se.marginTopScale)),Se.marginBottomScale===void 0||isNaN(Se.marginBottomScale)?Se.marginBottomScale=1:Se.marginBottomScale=Math.max(0,Math.min(5,Se.marginBottomScale)),Se.lyricDisplayMode&&!Ve(Se.lyricDisplayMode,F0)&&(Se.lyricDisplayMode="all"),["normal","bold"].includes(Se.fontWeight)||(Se.fontWeight="bold"),["normal","italic"].includes(Se.fontStyle)||(Se.fontStyle="normal"),["none","underline","line-through"].includes(Se.textDecoration)||(Se.textDecoration="none"),pE.includes(Se.textCase)||(Se.textCase="none"),["auto","manual"].includes(Se.introMode)||(Se.introMode="auto"),Se.lyricStyleTarget&&!["active-only","all"].includes(Se.lyricStyleTarget)&&(Se.lyricStyleTarget="active-only");const _t=["top-left","top-right","bottom-left","bottom-right","top-center","bottom-center"];Se.infoPosition&&!_t.includes(Se.infoPosition)&&(Se.infoPosition="top-left"),Se.infoStyle&&!Ve(Se.infoStyle,s1)&&(Se.infoStyle="classic"),Se.channelInfoPosition&&!_t.includes(Se.channelInfoPosition)&&(Se.channelInfoPosition="bottom-right"),Se.channelInfoStyle&&!Ve(Se.channelInfoStyle,r1)&&(Se.channelInfoStyle="classic");const Jt=["bars","wave","circular","particles","pulse-ring"];Se.visualizationType&&!Jt.includes(Se.visualizationType)&&(Se.visualizationType="bars");const Dt=["accent","gradient","custom","rainbow"];Se.visualizationColorMode&&!Dt.includes(Se.visualizationColorMode)&&(Se.visualizationColorMode="gradient");const Yt=["bottom","top","full","center"];Se.visualizationPosition&&!Yt.includes(Se.visualizationPosition)&&(Se.visualizationPosition="bottom"),Se.visualizationOpacity!==void 0&&(Se.visualizationOpacity=Math.max(0,Math.min(1,Se.visualizationOpacity))),Se.visualizationSensitivity!==void 0&&(Se.visualizationSensitivity=Math.max(.5,Math.min(3,Se.visualizationSensitivity))),Se.visualizationBarCount!==void 0&&(Se.visualizationBarCount=Math.max(16,Math.min(128,Math.round(Se.visualizationBarCount)))),e(Se),z&&y(z),j&&T(j),B&&E(B),ae&&W(Number(ae)),Y&&L(Y),me&&V(me),ee&&k(ee),i(Xe||"custom"),M&&M!==h?X.success(`Settings loaded. Note: Config used font "${M}".`):J||fe?X.success(`Settings loaded. Custom fonts referenced: ${[J,fe].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.")}},le.readAsText(te),C.target.value=""};return Re.useEffect(()=>{const C=te=>{be.current&&!be.current.contains(te.target)&&r()};return document.addEventListener("mousedown",C),()=>{document.removeEventListener("mousedown",C)}},[r]),p.jsxs("div",{ref:be,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(pb,{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:st?p.jsxs("span",{className:"text-emerald-400 font-mono",children:["✓ ",st]}):"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(pb,{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(b0,{size:14})," Visual Preset"]}),p.jsx(No,{value:n,onChange:C=>Ee(C),groups:ev})]}),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(mb,{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:o1}),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:we,type:"file",name:"bg-image-upload",id:"bg-image-upload",accept:"image/*",onChange:lt,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:()=>we.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:()=>we.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:FU})]}),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(gT,{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(hA,{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(SC,{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:F0})]}),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(b0,{size:14})," Highlight Effect"]}),p.jsx(No,{value:t.highlightEffect||"none",onChange:C=>{U("highlightEffect",C)},groups:P0}),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(mA,{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(mb,{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:Qe,type:"file",name:"channel-image-upload",id:"channel-image-upload",accept:"image/*",onChange:Oe,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:()=>Qe.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:()=>Qe.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:r1})]}),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(Pm,{value:t.channelInfoFontFamily||"sans-serif",onChange:C=>U("channelInfoFontFamily",C),customFontName:P||null,groups:$}),p.jsx(zm,{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:Q,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:ue,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(Im,{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(Dm,{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:s1})]}),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(Pm,{value:t.infoFontFamily||"sans-serif",onChange:C=>U("infoFontFamily",C),customFontName:se||null,groups:$}),p.jsx(zm,{onApply:C=>Ce(C,"infoFontFamily"),placeholder:"Info Font (e.g. Roboto)"}),p.jsx("input",{"aria-label":"Upload Info Font",ref:Ae,type:"file",name:"info-font-upload",id:"info-font-upload",accept:".ttf,.otf,.woff,.woff2",onChange:Te,className:"hidden"}),se?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:se}),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:$e,className:"text-zinc-500 hover:text-red-400",children:p.jsx(Ql,{size:12})})]}):p.jsxs("button",{onClick:()=>Ae.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(Im,{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(Dm,{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(CC,{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(hb,{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(wC,{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(Im,{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(Dm,{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(YA,{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(GA,{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(Pm,{value:t.fontFamily,onChange:C=>U("fontFamily",C),customFontName:h,groups:$}),p.jsx(zm,{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:Fe,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:()=>Fe.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(hb,{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:e1})]}),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:t1})]})]}),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:n1})]}),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:i1})}),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:OU})]})]}),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:()=>V("mediarecorder"),className:`flex-1 py-2 rounded-md text-[10px] font-bold uppercase transition-all ${H==="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:()=>V("webcodecs"),className:`flex-1 py-2 rounded-md text-[10px] font-bold uppercase transition-all ${H==="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:()=>V("ffmpeg"),className:`flex-1 py-2 rounded-md text-[10px] font-bold uppercase transition-all ${H==="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:H==="mediarecorder"?"Realtime recording. Fast but quality depends on browser.":H==="webcodecs"?"Hardware accelerated (GPU). Very fast export with simple MP4.":"Software rendering. High compatiblity but slower."})]}),H==="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]}]})]}),H==="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 ${Z===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))})]}),H==="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:()=>Le(!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:()=>Le(!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:()=>Le(!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 a1(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 jU(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]=a1(r),[y,S,T]=a1(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 mE(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 gE(t,e,n,i,r,a,c){const{type:u,sensitivity:h,barCount:d}=a,v=qU(e)/255;t.save();const y=WU(a.position,i,r);switch(t.beginPath(),t.rect(y.x,y.y,y.w,y.h),t.clip(),u){case"bars":$U(t,e,y,a,c);break;case"wave":XU(t,n||e,y,a,c);break;case"circular":YU(t,e,y,a,c,v);break;case"particles":JU(t,e,y,a,c);break;case"pulse-ring":KU(t,e,n,y,a,c,v);break}t.restore()}function qU(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||Ten.y+n.h)continue;const $e=(1+V*3)*(1-k*.6),X=(1-k)*V*i.opacity*.6;X<.03||(t.globalAlpha=X,t.fillStyle=Es(i,H/e.length,1,V,r),t.beginPath(),t.arc(se,Te,$e,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,Q=(3+W*5)*P,ue=.08+v*.15;t.globalAlpha=ue*i.opacity;const se=t.createRadialGradient(Z,k,0,Z,k,Q),Te=Es(i,L,1,.7,r);se.addColorStop(0,Te),se.addColorStop(.5,Te.replace(/[\d.]+\)$/,`${.3})`)),se.addColorStop(1,Te.replace(/[\d.]+\)$/,"0)")),t.fillStyle=se,t.beginPath(),t.arc(Z,k,Q,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,H=n.y+n.h/2;t.globalAlpha=D,t.beginPath(),t.arc(W,H,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 KU(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(Fm.has(t))return Fm.get(t);const n=e.createMediaElementSource(t);return Fm.set(t,n),n};let jo=null,Jl=null,zf=null,Tu=null,Eu=null;function ZU(){try{Jl&&Jl.disconnect(),jo&&(jo.disconnect(),jo=null),zf=null,Tu=null,Eu=null}catch(t){console.warn("AudioVisualizer: disconnect failed",t)}}const QU=({audioElement:t,config:e,isPlaying:n})=>{const i=Re.useRef(null),r=Re.useRef(0),a=Re.useRef(0);return Re.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]),Re.useEffect(()=>{const c=sh();n&&c&&c.state==="suspended"&&c.resume()},[n]),Re.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=mE(e),I=w.type==="wave"||w.type==="pulse-ring";I&&jo.getByteTimeDomainData(Eu),gE(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 nv="174",ek=0,l1=1,tk=2,vE=1,nk=2,fr=3,sa=0,Do=1,$o=2,ia=0,nc=1,c1=2,u1=3,d1=4,ik=5,Oa=100,ok=101,sk=102,rk=103,ak=104,lk=200,ck=201,uk=202,dk=203,O0=204,B0=205,fk=206,hk=207,pk=208,mk=209,gk=210,vk=211,xk=212,yk=213,_k=214,V0=0,H0=1,G0=2,rc=3,j0=4,q0=5,W0=6,$0=7,xE=0,bk=1,Sk=2,oa=0,Tk=1,Ek=2,wk=3,Mk=4,Ck=5,Ak=6,Rk=7,yE=300,ac=301,lc=302,X0=303,Y0=304,Ch=306,J0=1e3,Va=1001,K0=1002,Jo=1003,Nk=1004,of=1005,Bs=1006,Om=1007,Ha=1008,yr=1009,_E=1010,bE=1011,Pu=1012,iv=1013,qa=1014,Vs=1015,Bu=1016,ov=1017,sv=1018,cc=1020,SE=35902,TE=1021,EE=1022,ws=1023,wE=1024,ME=1025,ic=1026,uc=1027,rv=1028,av=1029,CE=1030,lv=1031,cv=1033,Pf=33776,Ff=33777,Of=33778,Bf=33779,Z0=35840,Q0=35841,eg=35842,tg=35843,ng=36196,ig=37492,og=37496,sg=37808,rg=37809,ag=37810,lg=37811,cg=37812,ug=37813,dg=37814,fg=37815,hg=37816,pg=37817,mg=37818,gg=37819,vg=37820,xg=37821,Vf=36492,yg=36494,_g=36495,AE=36283,bg=36284,Sg=36285,Tg=36286,Ik=3200,Dk=3201,Lk=0,Uk=1,na="",ds="srgb",dc="srgb-linear",rh="linear",Qn="srgb",Al=7680,f1=519,kk=512,zk=513,Pk=514,RE=515,Fk=516,Ok=517,Bk=518,Vk=519,h1=35044,p1="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 Hk(t,e){return(t%e+e)%e}function Vm(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],H=r[5],V=r[8];return a[0]=c*A+u*I+h*W,a[3]=c*E+u*L+h*H,a[6]=c*w+u*D+h*V,a[1]=d*A+g*I+v*W,a[4]=d*E+g*L+v*H,a[7]=d*w+g*D+v*V,a[2]=y*A+S*I+T*W,a[5]=y*E+S*L+T*H,a[8]=y*w+S*D+T*V,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(Hm.makeScale(e,n)),this}rotate(e){return this.premultiply(Hm.makeRotation(-e)),this}translate(e,n){return this.premultiply(Hm.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 Hm=new an;function NE(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 Gk(){const t=lh("canvas");return t.style.display="block",t}const m1={};function Na(t){t in m1||(m1[t]=!0,console.warn(t))}function jk(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 qk(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 Wk(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 g1=new an().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),v1=new an().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function $k(){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:g1,fromXYZ:v1,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:ds},outputColorSpaceConfig:{drawingBufferColorSpace:ds}},[ds]:{primaries:e,whitePoint:i,transfer:Qn,toXYZ:g1,fromXYZ:v1,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:ds}}}),t}const kn=$k();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 Xk{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!==yE)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case J0:e.x=e.x-Math.floor(e.x);break;case Va:e.x=e.x<0?0:1;break;case K0: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 J0:e.y=e.y-Math.floor(e.y);break;case Va:e.y=e.y<0?0:1;break;case K0: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=yE;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,H=(g+y)/4,V=(v+A)/4,Z=(T+E)/4;return L>D&&L>W?L<.01?(i=0,r=.707106781,a=.707106781):(i=Math.sqrt(L),r=H/i,a=V/i):D>W?D<.01?(i=.707106781,r=0,a=.707106781):(r=Math.sqrt(D),i=H/r,a=Z/r):W<.01?(i=.707106781,r=.707106781,a=0):(a=Math.sqrt(W),i=V/a,r=Z/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 Kk 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),H=Math.atan2(W,w*I);E=Math.sin(E*H)/W,u=Math.sin(u*H)/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 Ue{constructor(e=0,n=0,i=0){Ue.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(x1.setFromEuler(e))}applyAxisAngle(e,n){return this.applyQuaternion(x1.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 jm.copy(this).projectOnVector(e),this.sub(jm)}reflect(e){return this.sub(jm.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 jm=new Ue,x1=new Hu;class Ya{constructor(e=new Ue(1/0,1/0,1/0),n=new Ue(-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!qm(n,Nl,Il,Dl,rf)||(n=[1,0,0,0,1,0,0,0,1],!qm(n,Nl,Il,Dl,rf))?!1:(af.crossVectors(qr,Wr),n=[af.x,af.y,af.z],qm(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 Ue,new Ue,new Ue,new Ue,new Ue,new Ue,new Ue,new Ue],ys=new Ue,sf=new Ya,Nl=new Ue,Il=new Ue,Dl=new Ue,qr=new Ue,Wr=new Ue,Ta=new Ue,uu=new Ue,rf=new Ue,af=new Ue,Ea=new Ue;function qm(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 Qk=new Ya,du=new Ue,Wm=new Ue;class Ja{constructor(e=new Ue,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):Qk.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):(Wm.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(du.copy(e.center).add(Wm)),this.expandByPoint(du.copy(e.center).sub(Wm))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}}const lr=new Ue,$m=new Ue,lf=new Ue,$r=new Ue,Xm=new Ue,cf=new Ue,Ym=new Ue;class dv{constructor(e=new Ue,n=new Ue(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){$m.copy(e).add(n).multiplyScalar(.5),lf.copy(n).sub(e).normalize(),$r.copy(this.origin).sub($m);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($m).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){Xm.subVectors(n,e),cf.subVectors(i,e),Ym.crossVectors(Xm,cf);let c=this.direction.dot(Ym),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(Xm.cross($r));if(d<0||h+d>c)return null;const g=-u*$r.dot(Ym);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(ez,e,tz)}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],H=r[0],V=r[4],Z=r[8],k=r[12],P=r[1],Q=r[5],ue=r[9],se=r[13],Te=r[2],$e=r[6],X=r[10],ve=r[14],ie=r[3],nt=r[7],Ce=r[11],$=r[15];return a[0]=c*H+u*P+h*Te+d*ie,a[4]=c*V+u*Q+h*$e+d*nt,a[8]=c*Z+u*ue+h*X+d*Ce,a[12]=c*k+u*se+h*ve+d*$,a[1]=g*H+v*P+y*Te+S*ie,a[5]=g*V+v*Q+y*$e+S*nt,a[9]=g*Z+v*ue+y*X+S*Ce,a[13]=g*k+v*se+y*ve+S*$,a[2]=T*H+A*P+E*Te+w*ie,a[6]=T*V+A*Q+E*$e+w*nt,a[10]=T*Z+A*ue+E*X+w*Ce,a[14]=T*k+A*se+E*ve+w*$,a[3]=I*H+L*P+D*Te+W*ie,a[7]=I*V+L*Q+D*$e+W*nt,a[11]=I*Z+L*ue+D*X+W*Ce,a[15]=I*k+L*se+D*ve+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,H=n*I+i*L+r*D+a*W;if(H===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const V=1/H;return e[0]=I*V,e[1]=(A*y*a-v*E*a-A*r*S+i*E*S+v*r*w-i*y*w)*V,e[2]=(u*E*a-A*h*a+A*r*d-i*E*d-u*r*w+i*h*w)*V,e[3]=(v*h*a-u*y*a-v*r*d+i*y*d+u*r*S-i*h*S)*V,e[4]=L*V,e[5]=(g*E*a-T*y*a+T*r*S-n*E*S-g*r*w+n*y*w)*V,e[6]=(T*h*a-c*E*a-T*r*d+n*E*d+c*r*w-n*h*w)*V,e[7]=(c*y*a-g*h*a+g*r*d-n*y*d-c*r*S+n*h*S)*V,e[8]=D*V,e[9]=(T*v*a-g*A*a-T*i*S+n*A*S+g*i*w-n*v*w)*V,e[10]=(c*A*a-T*u*a+T*i*d-n*A*d-c*i*w+n*u*w)*V,e[11]=(g*u*a-c*v*a-g*i*d+n*v*d+c*i*S-n*u*S)*V,e[12]=W*V,e[13]=(g*A*r-T*v*r+T*i*y-n*A*y-g*i*E+n*v*E)*V,e[14]=(T*u*r-c*A*r-T*i*h+n*A*h+c*i*E-n*u*E)*V,e[15]=(c*v*r-g*u*r+g*i*h-n*v*h-c*i*y+n*u*y)*V,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,H=i.y,V=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)*H,r[5]=(1-(y+w))*H,r[6]=(E+I)*H,r[7]=0,r[8]=(T+L)*V,r[9]=(E-I)*V,r[10]=(1-(y+A))*V,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 Ue,_s=new ui,ez=new Ue(0,0,0),tz=new Ue(1,1,1),Xr=new Ue,uf=new Ue,Ho=new Ue,y1=new ui,_1=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 y1.makeRotationFromQuaternion(e),this.setFromRotationMatrix(y1,n,i)}setFromVector3(e,n=this._order){return this.set(e.x,e.y,e.z,n)}reorder(e){return _1.setFromEuler(this),this.setFromQuaternion(_1,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 DE{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),Km.subVectors(e,n);const c=bs.dot(bs),u=bs.dot(ur),h=bs.dot(Km),d=ur.dot(ur),g=ur.dot(Km),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 t0.setScalar(0),n0.setScalar(0),i0.setScalar(0),t0.fromBufferAttribute(e,n),n0.fromBufferAttribute(e,i),i0.fromBufferAttribute(e,r),c.setScalar(0),c.addScaledVector(t0,a.x),c.addScaledVector(n0,a.y),c.addScaledVector(i0,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),Zm.subVectors(e,i);const h=zl.dot(Zm),d=Pl.dot(Zm);if(h<=0&&d<=0)return n.copy(i);Qm.subVectors(e,r);const g=zl.dot(Qm),v=Pl.dot(Qm);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);e0.subVectors(e,a);const S=zl.dot(e0),T=Pl.dot(e0);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 M1.subVectors(a,r),u=(v-g)/(v-g+(S-T)),n.copy(r).addScaledVector(M1,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 LE={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 o0(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=Hk(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=o0(c,a,e+1/3),this.g=o0(c,a,e),this.b=o0(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=LE[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!==O0&&(i.blendSrc=this.blendSrc),this.blendDst!==B0&&(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!==f1&&(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=xE,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 Ue,hf=new Bn;let az=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:az++}),this.name="",this.array=e,this.itemSize=n,this.count=e!==void 0?e.length/n:0,this.normalized=i,this.usage=h1,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 Ue(-1/0,-1/0,-1/0),new Ue(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))&&(C1.copy(a).invert(),wa.copy(e.ray).applyMatrix4(C1),!(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=cz(t,e,n,i,mf,gf,vf,R1);if(g){const v=new Ue;Ts.getBarycoord(R1,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 Ue),g.normal.dot(i.direction)>0&&g.normal.multiplyScalar(-1));const y={a:u,b:h,c:d,normal:new Ue,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,H,V,Z,k){const P=D/V,Q=W/Z,ue=D/2,se=W/2,Te=H/2,$e=V+1,X=Z+1;let ve=0,ie=0;const nt=new Ue;for(let Ce=0;Ce0?1:-1,g.push(nt.x,nt.y,nt.z),v.push(be/V),v.push(1-Ce/Z),ve+=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 PE 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 Ue,N1=new Bn,I1=new Bn;class fs extends PE{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=Eg*2*Math.atan(n),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(Bm*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Eg*2*Math.atan(Math.tan(Bm*.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,N1,I1),n.subVectors(I1,N1)}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(Bm*.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 pz 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 FE 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 mz 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 FE(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 pz(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 gz={type:"move"};class a0{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 Ue,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Ue),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 Ue,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Ue),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(gz)))}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 vz 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 xz 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 D1 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,L1=new ui,bf=[],U1=new Ya,yz=new ui,pu=new Ni,mu=new Ja;class _z extends Ni{constructor(e,n,i){super(e,n),this.isInstancedMesh=!0,this.instanceMatrix=new D1(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||Sz.getNormalMatrix(e),r=this.coplanarPoint(l0).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 Ue;class OE{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 Ue,uh=new Ue,k1=new ui,gu=new dv,Tf=new Ja,c0=new Ue,z1=new Ue;class wg 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;c0.applyMatrix4(t.matrixWorld);const d=e.ray.origin.distanceTo(c0);if(!(de.far))return{distance:d,point:z1.clone().applyMatrix4(t.matrixWorld),index:c,face:null,faceIndex:null,barycoord:null,object:t}}const P1=new Ue,F1=new Ue;class BE extends wg{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 VE 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 uv(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 Ue,D=new Ue,W=new Ue;for(let H=0;H.9&&V<.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 Ue,L=new Ue,D=new Ue,W=new Ue,H=new Bn,V=new Bn,Z=new Bn;for(let k=0,P=0;k0)&&S.push(L,D,H),(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`,Wz=`#if NUM_CLIPPING_PLANES > 0 - varying vec3 vClipPosition; - uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; -#endif`,$z=`#if NUM_CLIPPING_PLANES > 0 - varying vec3 vClipPosition; -#endif`,Xz=`#if NUM_CLIPPING_PLANES > 0 - vClipPosition = - mvPosition.xyz; -#endif`,Yz=`#if defined( USE_COLOR_ALPHA ) - diffuseColor *= vColor; -#elif defined( USE_COLOR ) - diffuseColor.rgb *= vColor; -#endif`,Jz=`#if defined( USE_COLOR_ALPHA ) - varying vec4 vColor; -#elif defined( USE_COLOR ) - varying vec3 vColor; -#endif`,Kz=`#if defined( USE_COLOR_ALPHA ) - varying vec4 vColor; -#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) - varying vec3 vColor; -#endif`,Zz=`#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`,Qz=`#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`,eP=`#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`,tP=`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`,nP=`#ifdef USE_DISPLACEMENTMAP - uniform sampler2D displacementMap; - uniform float displacementScale; - uniform float displacementBias; -#endif`,iP=`#ifdef USE_DISPLACEMENTMAP - transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); -#endif`,oP=`#ifdef USE_EMISSIVEMAP - vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); - #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE - emissiveColor = sRGBTransferEOTF( emissiveColor ); - #endif - totalEmissiveRadiance *= emissiveColor.rgb; -#endif`,sP=`#ifdef USE_EMISSIVEMAP - uniform sampler2D emissiveMap; -#endif`,rP="gl_FragColor = linearToOutputTexel( gl_FragColor );",aP=`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 ); -}`,lP=`#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`,cP=`#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`,uP=`#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`,dP=`#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`,fP=`#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`,hP=`#ifdef USE_FOG - vFogDepth = - mvPosition.z; -#endif`,pP=`#ifdef USE_FOG - varying float vFogDepth; -#endif`,mP=`#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`,gP=`#ifdef USE_FOG - uniform vec3 fogColor; - varying float vFogDepth; - #ifdef FOG_EXP2 - uniform float fogDensity; - #else - uniform float fogNear; - uniform float fogFar; - #endif -#endif`,vP=`#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 -}`,xP=`#ifdef USE_LIGHTMAP - uniform sampler2D lightMap; - uniform float lightMapIntensity; -#endif`,yP=`LambertMaterial material; -material.diffuseColor = diffuseColor.rgb; -material.specularStrength = specularStrength;`,_P=`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`,bP=`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`,SP=`#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`,TP=`ToonMaterial material; -material.diffuseColor = diffuseColor.rgb;`,EP=`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`,wP=`BlinnPhongMaterial material; -material.diffuseColor = diffuseColor.rgb; -material.specularColor = specular; -material.specularShininess = shininess; -material.specularStrength = specularStrength;`,MP=`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`,CP=`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`,AP=`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 ); -}`,RP=` -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`,NP=`#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`,IP=`#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`,DP=`#if defined( USE_LOGDEPTHBUF ) - gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; -#endif`,LP=`#if defined( USE_LOGDEPTHBUF ) - uniform float logDepthBufFC; - varying float vFragDepth; - varying float vIsPerspective; -#endif`,UP=`#ifdef USE_LOGDEPTHBUF - varying float vFragDepth; - varying float vIsPerspective; -#endif`,kP=`#ifdef USE_LOGDEPTHBUF - vFragDepth = 1.0 + gl_Position.w; - vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); -#endif`,zP=`#ifdef USE_MAP - vec4 sampledDiffuseColor = texture2D( map, vMapUv ); - #ifdef DECODE_VIDEO_TEXTURE - sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); - #endif - diffuseColor *= sampledDiffuseColor; -#endif`,PP=`#ifdef USE_MAP - uniform sampler2D map; -#endif`,FP=`#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`,OP=`#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`,BP=`float metalnessFactor = metalness; -#ifdef USE_METALNESSMAP - vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); - metalnessFactor *= texelMetalness.b; -#endif`,VP=`#ifdef USE_METALNESSMAP - uniform sampler2D metalnessMap; -#endif`,HP=`#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`,GP=`#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`,jP=`#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`,qP=`#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`,WP=`#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`,$P=`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;`,XP=`#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`,YP=`#ifndef FLAT_SHADED - varying vec3 vNormal; - #ifdef USE_TANGENT - varying vec3 vTangent; - varying vec3 vBitangent; - #endif -#endif`,JP=`#ifndef FLAT_SHADED - varying vec3 vNormal; - #ifdef USE_TANGENT - varying vec3 vTangent; - varying vec3 vBitangent; - #endif -#endif`,KP=`#ifndef FLAT_SHADED - vNormal = normalize( transformedNormal ); - #ifdef USE_TANGENT - vTangent = normalize( transformedTangent ); - vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); - #endif -#endif`,ZP=`#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`,QP=`#ifdef USE_CLEARCOAT - vec3 clearcoatNormal = nonPerturbedNormal; -#endif`,e5=`#ifdef USE_CLEARCOAT_NORMALMAP - vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; - clearcoatMapN.xy *= clearcoatNormalScale; - clearcoatNormal = normalize( tbn2 * clearcoatMapN ); -#endif`,t5=`#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`,n5=`#ifdef USE_IRIDESCENCEMAP - uniform sampler2D iridescenceMap; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - uniform sampler2D iridescenceThicknessMap; -#endif`,i5=`#ifdef OPAQUE -diffuseColor.a = 1.0; -#endif -#ifdef USE_TRANSMISSION -diffuseColor.a *= material.transmissionAlpha; -#endif -gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,o5=`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 ); -}`,s5=`#ifdef PREMULTIPLIED_ALPHA - gl_FragColor.rgb *= gl_FragColor.a; -#endif`,r5=`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;`,a5=`#ifdef DITHERING - gl_FragColor.rgb = dithering( gl_FragColor.rgb ); -#endif`,l5=`#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`,c5=`float roughnessFactor = roughness; -#ifdef USE_ROUGHNESSMAP - vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); - roughnessFactor *= texelRoughness.g; -#endif`,u5=`#ifdef USE_ROUGHNESSMAP - uniform sampler2D roughnessMap; -#endif`,d5=`#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`,f5=`#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`,h5=`#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`,p5=`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; -}`,m5=`#ifdef USE_SKINNING - mat4 boneMatX = getBoneMatrix( skinIndex.x ); - mat4 boneMatY = getBoneMatrix( skinIndex.y ); - mat4 boneMatZ = getBoneMatrix( skinIndex.z ); - mat4 boneMatW = getBoneMatrix( skinIndex.w ); -#endif`,g5=`#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`,v5=`#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`,x5=`#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`,y5=`float specularStrength; -#ifdef USE_SPECULARMAP - vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); - specularStrength = texelSpecular.r; -#else - specularStrength = 1.0; -#endif`,_5=`#ifdef USE_SPECULARMAP - uniform sampler2D specularMap; -#endif`,b5=`#if defined( TONE_MAPPING ) - gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); -#endif`,S5=`#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; }`,T5=`#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`,E5=`#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`,w5=`#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`,M5=`#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`,C5=`#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`,A5=`#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 R5=`varying vec2 vUv; -uniform mat3 uvTransform; -void main() { - vUv = ( uvTransform * vec3( uv, 1 ) ).xy; - gl_Position = vec4( position.xy, 1.0, 1.0 ); -}`,N5=`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 -}`,I5=`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include - gl_Position.z = gl_Position.w; -}`,D5=`#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 -}`,L5=`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include - gl_Position.z = gl_Position.w; -}`,U5=`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 -}`,k5=`#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; -}`,z5=`#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 -}`,P5=`#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; -}`,F5=`#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 ); -}`,O5=`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include -}`,B5=`uniform sampler2D tEquirect; -varying vec3 vWorldDirection; -#include -void main() { - vec3 direction = normalize( vWorldDirection ); - vec2 sampleUV = equirectUv( direction ); - gl_FragColor = texture2D( tEquirect, sampleUV ); - #include - #include -}`,V5=`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 -}`,H5=`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 -}`,G5=`#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 -}`,j5=`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 -}`,q5=`#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 -}`,W5=`#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 -}`,$5=`#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; -}`,X5=`#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 -}`,Y5=`#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 -}`,J5=`#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 -}`,K5=`#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 -}`,Z5=`#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 -}`,Q5=`#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 -}`,eF=`#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 -}`,tF=`#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 -}`,nF=`#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 -}`,iF=`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 -}`,oF=`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 -}`,sF=`#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -}`,rF=`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 -}`,aF=`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 -}`,lF=`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:Nz,alphahash_pars_fragment:Iz,alphamap_fragment:Dz,alphamap_pars_fragment:Lz,alphatest_fragment:Uz,alphatest_pars_fragment:kz,aomap_fragment:zz,aomap_pars_fragment:Pz,batching_pars_vertex:Fz,batching_vertex:Oz,begin_vertex:Bz,beginnormal_vertex:Vz,bsdfs:Hz,iridescence_fragment:Gz,bumpmap_pars_fragment:jz,clipping_planes_fragment:qz,clipping_planes_pars_fragment:Wz,clipping_planes_pars_vertex:$z,clipping_planes_vertex:Xz,color_fragment:Yz,color_pars_fragment:Jz,color_pars_vertex:Kz,color_vertex:Zz,common:Qz,cube_uv_reflection_fragment:eP,defaultnormal_vertex:tP,displacementmap_pars_vertex:nP,displacementmap_vertex:iP,emissivemap_fragment:oP,emissivemap_pars_fragment:sP,colorspace_fragment:rP,colorspace_pars_fragment:aP,envmap_fragment:lP,envmap_common_pars_fragment:cP,envmap_pars_fragment:uP,envmap_pars_vertex:dP,envmap_physical_pars_fragment:SP,envmap_vertex:fP,fog_vertex:hP,fog_pars_vertex:pP,fog_fragment:mP,fog_pars_fragment:gP,gradientmap_pars_fragment:vP,lightmap_pars_fragment:xP,lights_lambert_fragment:yP,lights_lambert_pars_fragment:_P,lights_pars_begin:bP,lights_toon_fragment:TP,lights_toon_pars_fragment:EP,lights_phong_fragment:wP,lights_phong_pars_fragment:MP,lights_physical_fragment:CP,lights_physical_pars_fragment:AP,lights_fragment_begin:RP,lights_fragment_maps:NP,lights_fragment_end:IP,logdepthbuf_fragment:DP,logdepthbuf_pars_fragment:LP,logdepthbuf_pars_vertex:UP,logdepthbuf_vertex:kP,map_fragment:zP,map_pars_fragment:PP,map_particle_fragment:FP,map_particle_pars_fragment:OP,metalnessmap_fragment:BP,metalnessmap_pars_fragment:VP,morphinstance_vertex:HP,morphcolor_vertex:GP,morphnormal_vertex:jP,morphtarget_pars_vertex:qP,morphtarget_vertex:WP,normal_fragment_begin:$P,normal_fragment_maps:XP,normal_pars_fragment:YP,normal_pars_vertex:JP,normal_vertex:KP,normalmap_pars_fragment:ZP,clearcoat_normal_fragment_begin:QP,clearcoat_normal_fragment_maps:e5,clearcoat_pars_fragment:t5,iridescence_pars_fragment:n5,opaque_fragment:i5,packing:o5,premultiplied_alpha_fragment:s5,project_vertex:r5,dithering_fragment:a5,dithering_pars_fragment:l5,roughnessmap_fragment:c5,roughnessmap_pars_fragment:u5,shadowmap_pars_fragment:d5,shadowmap_pars_vertex:f5,shadowmap_vertex:h5,shadowmask_pars_fragment:p5,skinbase_vertex:m5,skinning_pars_vertex:g5,skinning_vertex:v5,skinnormal_vertex:x5,specularmap_fragment:y5,specularmap_pars_fragment:_5,tonemapping_fragment:b5,tonemapping_pars_fragment:S5,transmission_fragment:T5,transmission_pars_fragment:E5,uv_pars_fragment:w5,uv_pars_vertex:M5,uv_vertex:C5,worldpos_vertex:A5,background_vert:R5,background_frag:N5,backgroundCube_vert:I5,backgroundCube_frag:D5,cube_vert:L5,cube_frag:U5,depth_vert:k5,depth_frag:z5,distanceRGBA_vert:P5,distanceRGBA_frag:F5,equirect_vert:O5,equirect_frag:B5,linedashed_vert:V5,linedashed_frag:H5,meshbasic_vert:G5,meshbasic_frag:j5,meshlambert_vert:q5,meshlambert_frag:W5,meshmatcap_vert:$5,meshmatcap_frag:X5,meshnormal_vert:Y5,meshnormal_frag:J5,meshphong_vert:K5,meshphong_frag:Z5,meshphysical_vert:Q5,meshphysical_frag:eF,meshtoon_vert:tF,meshtoon_frag:nF,points_vert:iF,points_frag:oF,shadow_vert:sF,shadow_frag:rF,sprite_vert:aF,sprite_frag:lF},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 Ue},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,cF=new ui;function uF(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 H=t.xr.getEnvironmentBlendMode();H==="additive"?i.buffers.color.setClear(0,0,0,1,c):H==="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===Ch)?(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(H,V,Z){this.matrixWorld.copyPosition(Z.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(cF.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,zE(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 dF(t,e){const n=t.getParameter(t.MAX_VERTEX_ATTRIBS),i={},r=y(null);let a=r,c=!1;function u(P,Q,ue,se,Te){let $e=!1;const X=v(se,ue,Q);a!==X&&(a=X,d(a.object)),$e=S(P,se,ue,Te),$e&&T(P,se,ue,Te),Te!==null&&e.update(Te,t.ELEMENT_ARRAY_BUFFER),($e||c)&&(c=!1,D(P,Q,ue,se),Te!==null&&t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,e.get(Te).buffer))}function h(){return t.createVertexArray()}function d(P){return t.bindVertexArray(P)}function g(P){return t.deleteVertexArray(P)}function v(P,Q,ue){const se=ue.wireframe===!0;let Te=i[P.id];Te===void 0&&(Te={},i[P.id]=Te);let $e=Te[Q.id];$e===void 0&&($e={},Te[Q.id]=$e);let X=$e[se];return X===void 0&&(X=y(h()),$e[se]=X),X}function y(P){const Q=[],ue=[],se=[];for(let Te=0;Te=0){const Ce=Te[ie];let $=$e[ie];if($===void 0&&(ie==="instanceMatrix"&&P.instanceMatrix&&($=P.instanceMatrix),ie==="instanceColor"&&P.instanceColor&&($=P.instanceColor)),Ce===void 0||Ce.attribute!==$||$&&Ce.data!==$.data)return!0;X++}return a.attributesNum!==X||a.index!==se}function T(P,Q,ue,se){const Te={},$e=Q.attributes;let X=0;const ve=ue.getAttributes();for(const ie in ve)if(ve[ie].location>=0){let Ce=$e[ie];Ce===void 0&&(ie==="instanceMatrix"&&P.instanceMatrix&&(Ce=P.instanceMatrix),ie==="instanceColor"&&P.instanceColor&&(Ce=P.instanceColor));const $={};$.attribute=Ce,Ce&&Ce.data&&($.data=Ce.data),Te[ie]=$,X++}a.attributes=Te,a.attributesNum=X,a.index=se}function A(){const P=a.newAttributes;for(let Q=0,ue=P.length;Q=0){let nt=Te[ve];if(nt===void 0&&(ve==="instanceMatrix"&&P.instanceMatrix&&(nt=P.instanceMatrix),ve==="instanceColor"&&P.instanceColor&&(nt=P.instanceColor)),nt!==void 0){const Ce=nt.normalized,$=nt.itemSize,be=e.get(nt);if(be===void 0)continue;const Fe=be.buffer,oe=be.type,Ae=be.bytesPerElement,Qe=oe===t.INT||oe===t.UNSIGNED_INT||nt.gpuType===iv;if(nt.isInterleavedBufferAttribute){const we=nt.data,N=we.stride,ye=nt.offset;if(we.isInstancedInterleavedBuffer){for(let xe=0;xe0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";V="mediump"}return V==="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,H=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:H}}function pF(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 mz(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,H1=[.125,.215,.35,.446,.526,.582],Ba=20,u0=new wz,G1=new An;let d0=null,f0=0,h0=0,p0=!1;const Da=(1+Math.sqrt(5))/2,Hl=1/Da,j1=[new Ue(-Da,Hl,0),new Ue(Da,Hl,0),new Ue(-Hl,0,Da),new Ue(Hl,0,Da),new Ue(0,Da,-Hl),new Ue(0,Da,Hl),new Ue(-1,1,-1),new Ue(1,1,-1),new Ue(-1,1,1),new Ue(1,1,1)],gF=new Ue;class q1{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=gF}=a;d0=this._renderer.getRenderTarget(),f0=this._renderer.getActiveCubeFace(),h0=this._renderer.getActiveMipmapLevel(),p0=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=X1(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=$1(),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=X1()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=$1());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,u0)}_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 V=0;VL-Kl?r-L+Kl:0),H=4*(this._cubeSize-D);Af(n,W,H,3*D,2*D),h.setRenderTarget(n),h.render(v,u0)}}function vF(t){const e=[],n=[],i=[];let r=t;const a=t-Kl+1+H1.length;for(let c=0;ct-Kl?h=H1[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 H=0;H2?0:-1,k=[V,Z,0,V+2/3,Z,0,V+2/3,Z+1,0,V,Z,0,V+2/3,Z+1,0,V,Z+1,0];I.set(k,A*T*H),L.set(y,E*T*H);const P=[H,H,H,H,H,H];D.set(P,w*T*H)}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 W1(t,e,n){const i=new Wa(t,e,n);return i.texture.mapping=Ch,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 xF(t,e,n){const i=new Float32Array(Ba),r=new Ue(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:mv(),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 $1(){return new ra({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:mv(),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 X1(){return new ra({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:mv(),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 mv(){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 yF(t){let e=new WeakMap,n=null;function i(u){if(u&&u.isTexture){const h=u.mapping,d=h===X0||h===Y0,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 q1(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 q1(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 H=new Float32Array(D*W*4*v),V=new IE(H,D,W,v);V.type=Vs,V.needsUpdate=!0;const Z=L*4;for(let P=0;P0)return t;const r=e*n;let a=J1[r];if(a===void 0&&(a=new Float32Array(r),J1[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 iT=new an;function y4(t){kn._getMatrix(iT,kn.workingColorSpace,t);const e=`mat3( ${iT.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 oT(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+` - -`+x4(t.getShaderSource(e),c)}else return r}function _4(t,e){const n=y4(e);return[`vec4 ${t}( vec4 value ) {`,` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join(` -`)}function b4(t,e){let n;switch(e){case Tk:n="Linear";break;case Ek:n="Reinhard";break;case wk:n="Cineon";break;case Mk:n="ACESFilmic";break;case Ak:n="AgX";break;case Rk:n="Neutral";break;case Ck: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 Ue;function S4(){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 T4(t){return[t.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",t.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(wu).join(` -`)}function E4(t){const e=[];for(const n in t){const i=t[n];i!==!1&&e.push("#define "+n+" "+i)}return e.join(` -`)}function w4(t,e){const n={},i=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let r=0;r/gm;function Cg(t){return t.replace(M4,A4)}const C4=new Map;function A4(t,e){let n=ln[e];if(n===void 0){const i=C4.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 Cg(n)}const R4=/#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 aT(t){return t.replace(R4,N4)}function N4(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=[lT(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=[lT(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?b4("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",ln.colorspace_pars_fragment,_4("linearToOutputTexel",n.outputColorSpace),S4(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"",` -`].filter(wu).join(` -`)),c=Cg(c),c=sT(c,n),c=rT(c,n),u=Cg(u),u=sT(u,n),u=rT(u,n),c=aT(c),u=aT(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===p1?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===p1?"":"#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=nT(r,r.VERTEX_SHADER,L),H=nT(r,r.FRAGMENT_SHADER,D);r.attachShader(A,W),r.attachShader(A,H),n.index0AttributeName!==void 0?r.bindAttribLocation(A,0,n.index0AttributeName):n.morphTargets===!0&&r.bindAttribLocation(A,0,"position"),r.linkProgram(A);function V(Q){if(t.debug.checkShaderErrors){const ue=r.getProgramInfoLog(A).trim(),se=r.getShaderInfoLog(W).trim(),Te=r.getShaderInfoLog(H).trim();let $e=!0,X=!0;if(r.getProgramParameter(A,r.LINK_STATUS)===!1)if($e=!1,typeof t.debug.onShaderError=="function")t.debug.onShaderError(r,A,W,H);else{const ve=oT(r,W,"vertex"),ie=oT(r,H,"fragment");console.error("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(A,r.VALIDATE_STATUS)+` - -Material Name: `+Q.name+` -Material Type: `+Q.type+` - -Program Info Log: `+ue+` -`+ve+` -`+ie)}else ue!==""?console.warn("THREE.WebGLProgram: Program Info Log:",ue):(se===""||Te==="")&&(X=!1);X&&(Q.diagnostics={runnable:$e,programLog:ue,vertexShader:{log:se,prefix:E},fragmentShader:{log:Te,prefix:w}})}r.deleteShader(W),r.deleteShader(H),Z=new Hf(r,A),k=w4(r,A)}let Z;this.getUniforms=function(){return Z===void 0&&V(this),Z};let k;this.getAttributes=function(){return k===void 0&&V(this),k};let P=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return P===!1&&(P=r.getProgramParameter(A,g4)),P},this.destroy=function(){i.releaseStatesOfProgram(this),r.deleteProgram(A),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=v4++,this.cacheKey=e,this.usedTimes=1,this.program=A,this.vertexShader=W,this.fragmentShader=H,this}let P4=0;class F4{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 O4(e),n.set(e,i)),i}}class O4{constructor(e){this.id=P4++,this.code=e,this.usedTimes=0}}function B4(t,e,n,i,r,a,c){const u=new DE,h=new F4,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,Q,ue,se){const Te=ue.fog,$e=se.geometry,X=k.isMeshStandardMaterial?ue.environment:null,ve=(k.isMeshStandardMaterial?n:e).get(k.envMap||X),ie=ve&&ve.mapping===Ch?ve.image.height:null,nt=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=$e.morphAttributes.position||$e.morphAttributes.normal||$e.morphAttributes.color,$=Ce!==void 0?Ce.length:0;let be=0;$e.morphAttributes.position!==void 0&&(be=1),$e.morphAttributes.normal!==void 0&&(be=2),$e.morphAttributes.color!==void 0&&(be=3);let Fe,oe,Ae,Qe;if(nt){const Ke=Fs[nt];Fe=Ke.vertexShader,oe=Ke.fragmentShader}else Fe=k.vertexShader,oe=k.fragmentShader,h.update(k),Ae=h.getVertexShaderID(k),Qe=h.getFragmentShaderID(k);const we=t.getRenderTarget(),N=t.state.buffers.depth.getReversed(),ye=se.isInstancedMesh===!0,xe=se.isBatchedMesh===!0,Le=!!k.map,st=!!k.matcap,tt=!!ve,U=!!k.aoMap,Ee=!!k.lightMap,Oe=!!k.bumpMap,lt=!!k.normalMap,We=!!k.displacementMap,gt=!!k.emissiveMap,qe=!!k.metalnessMap,q=!!k.roughnessMap,C=k.anisotropy>0,te=k.clearcoat>0,le=k.dispersion>0,Ne=k.iridescence>0,De=k.sheen>0,rt=k.transmission>0,it=C&&!!k.anisotropyMap,F=te&&!!k.clearcoatMap,ce=te&&!!k.clearcoatNormalMap,z=te&&!!k.clearcoatRoughnessMap,j=Ne&&!!k.iridescenceMap,B=Ne&&!!k.iridescenceThicknessMap,ae=De&&!!k.sheenColorMap,Y=De&&!!k.sheenRoughnessMap,me=!!k.specularMap,ee=!!k.specularColorMap,Xe=!!k.specularIntensityMap,M=rt&&!!k.transmissionMap,J=rt&&!!k.thicknessMap,fe=!!k.gradientMap,de=!!k.alphaMap,ke=k.alphaTest>0,Je=!!k.alphaHash,ht=!!k.extensions;let et=oa;k.toneMapped&&(we===null||we.isXRRenderTarget===!0)&&(et=t.toneMapping);const Se={shaderID:nt,shaderType:k.type,shaderName:k.name,vertexShader:Fe,fragmentShader:oe,defines:k.defines,customVertexShaderID:Ae,customFragmentShaderID:Qe,isRawShaderMaterial:k.isRawShaderMaterial===!0,glslVersion:k.glslVersion,precision:S,batching:xe,batchingColor:xe&&se._colorsTexture!==null,instancing:ye,instancingColor:ye&&se.instanceColor!==null,instancingMorph:ye&&se.morphTexture!==null,supportsVertexTextures:y,outputColorSpace:we===null?t.outputColorSpace:we.isXRRenderTarget===!0?we.texture.colorSpace:dc,alphaToCoverage:!!k.alphaToCoverage,map:Le,matcap:st,envMap:tt,envMapMode:tt&&ve.mapping,envMapCubeUVHeight:ie,aoMap:U,lightMap:Ee,bumpMap:Oe,normalMap:lt,displacementMap:y&&We,emissiveMap:gt,normalMapObjectSpace:lt&&k.normalMapType===Uk,normalMapTangentSpace:lt&&k.normalMapType===Lk,metalnessMap:qe,roughnessMap:q,anisotropy:C,anisotropyMap:it,clearcoat:te,clearcoatMap:F,clearcoatNormalMap:ce,clearcoatRoughnessMap:z,dispersion:le,iridescence:Ne,iridescenceMap:j,iridescenceThicknessMap:B,sheen:De,sheenColorMap:ae,sheenRoughnessMap:Y,specularMap:me,specularColorMap:ee,specularIntensityMap:Xe,transmission:rt,transmissionMap:M,thicknessMap:J,gradientMap:fe,opaque:k.transparent===!1&&k.blending===nc&&k.alphaToCoverage===!1,alphaMap:de,alphaTest:ke,alphaHash:Je,combine:k.combine,mapUv:Le&&A(k.map.channel),aoMapUv:U&&A(k.aoMap.channel),lightMapUv:Ee&&A(k.lightMap.channel),bumpMapUv:Oe&&A(k.bumpMap.channel),normalMapUv:lt&&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:ce&&A(k.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:z&&A(k.clearcoatRoughnessMap.channel),iridescenceMapUv:j&&A(k.iridescenceMap.channel),iridescenceThicknessMapUv:B&&A(k.iridescenceThicknessMap.channel),sheenColorMapUv:ae&&A(k.sheenColorMap.channel),sheenRoughnessMapUv:Y&&A(k.sheenRoughnessMap.channel),specularMapUv:me&&A(k.specularMap.channel),specularColorMapUv:ee&&A(k.specularColorMap.channel),specularIntensityMapUv:Xe&&A(k.specularIntensityMap.channel),transmissionMapUv:M&&A(k.transmissionMap.channel),thicknessMapUv:J&&A(k.thicknessMap.channel),alphaMapUv:de&&A(k.alphaMap.channel),vertexTangents:!!$e.attributes.tangent&&(lt||C),vertexColors:k.vertexColors,vertexAlphas:k.vertexColors===!0&&!!$e.attributes.color&&$e.attributes.color.itemSize===4,pointsUvs:se.isPoints===!0&&!!$e.attributes.uv&&(Le||de),fog:!!Te,useFog:k.fog===!0,fogExp2:!!Te&&Te.isFogExp2,flatShading:k.flatShading===!0,sizeAttenuation:k.sizeAttenuation===!0,logarithmicDepthBuffer:v,reverseDepthBuffer:N,skinning:se.isSkinnedMesh===!0,morphTargets:$e.morphAttributes.position!==void 0,morphNormals:$e.morphAttributes.normal!==void 0,morphColors:$e.morphAttributes.color!==void 0,morphTargetsCount:$,morphTextureStride:be,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&&Q.length>0,shadowMapType:t.shadowMap.type,toneMapping:et,decodeVideoTexture:Le&&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 Se.vertexUv1s=d.has(1),Se.vertexUv2s=d.has(2),Se.vertexUv3s=d.has(3),d.clear(),Se}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 Q in k.defines)P.push(Q),P.push(k.defines[Q]);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 Q;if(P){const ue=Fs[P];Q=dz.clone(ue.uniforms)}else Q=k.uniforms;return Q}function W(k,P){let Q;for(let ue=0,se=g.length;ue0?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||H4),i.length>1&&i.sort(y||cT),r.length>1&&r.sort(y||cT)}function g(){for(let v=e,y=t.length;v=a.length?(c=new uT,a.push(c)):c=a[r],c}function n(){t=new WeakMap}return{get:e,dispose:n}}function j4(){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 Ue,color:new An};break;case"SpotLight":n={position:new Ue,direction:new Ue,color:new An,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new Ue,color:new An,distance:0,decay:0};break;case"HemisphereLight":n={direction:new Ue,skyColor:new An,groundColor:new An};break;case"RectAreaLight":n={color:new An,position:new Ue,halfWidth:new Ue,halfHeight:new Ue};break}return t[e.id]=n,n}}}function q4(){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 W4=0;function $4(t,e){return(e.castShadow?2:0)-(t.castShadow?2:0)+(e.map?1:0)-(t.map?1:0)}function X4(t){const e=new j4,n=q4(),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 Ue);const r=new Ue,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,H=0,V=0;d.sort($4);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 Z=i.hash;(Z.directionalLength!==S||Z.pointLength!==T||Z.spotLength!==A||Z.rectAreaLength!==E||Z.hemiLength!==w||Z.numDirectionalShadows!==I||Z.numPointShadows!==L||Z.numSpotShadows!==D||Z.numSpotMaps!==W||Z.numLightProbes!==V)&&(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-H,i.spotLightMap.length=W,i.numSpotLightShadowsWithMaps=H,i.numLightProbes=V,Z.directionalLength=S,Z.pointLength=T,Z.spotLength=A,Z.rectAreaLength=E,Z.hemiLength=w,Z.numDirectionalShadows=I,Z.numPointShadows=L,Z.numSpotShadows=D,Z.numSpotMaps=W,Z.numLightProbes=V,i.version=W4++)}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 dT(t),c.push(u)):u=c[a],u}function i(){e=new WeakMap}return{get:n,dispose:i}}const J4=`void main() { - gl_Position = vec4( position, 1.0 ); -}`,K4=`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 Z4(t,e,n){let i=new OE;const r=new Bn,a=new Bn,c=new Ii,u=new Tz({depthPacking:Dk}),h=new Ez,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:J4,fragmentShader:K4}),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=vE;let w=this.type;this.render=function(H,V,Z){if(E.enabled===!1||E.autoUpdate===!1&&E.needsUpdate===!1||H.length===0)return;const k=t.getRenderTarget(),P=t.getActiveCubeFace(),Q=t.getActiveMipmapLevel(),ue=t.state;ue.setBlending(ia),ue.buffers.color.setClear(1,1,1,1),ue.buffers.depth.setTest(!0),ue.setScissorTest(!1);const se=w!==fr&&this.type===fr,Te=w===fr&&this.type!==fr;for(let $e=0,X=H.length;$eg||r.y>g)&&(r.x>g&&(a.x=Math.floor(g/nt.x),r.x=a.x*nt.x,ie.mapSize.x=a.x),r.y>g&&(a.y=Math.floor(g/nt.y),r.y=a.y*nt.y,ie.mapSize.y=a.y)),ie.map===null||se===!0||Te===!0){const $=this.type!==fr?{minFilter:Jo,magFilter:Jo}:{};ie.map!==null&&ie.map.dispose(),ie.map=new Wa(r.x,r.y,$),ie.map.texture.name=ve.name+".shadowMap",ie.camera.updateProjectionMatrix()}t.setRenderTarget(ie.map),t.clear();const Ce=ie.getViewportCount();for(let $=0;$0||V.map&&V.alphaTest>0){const ue=P.uuid,se=V.uuid;let Te=d[ue];Te===void 0&&(Te={},d[ue]=Te);let $e=Te[se];$e===void 0&&($e=P.clone(),Te[se]=$e,V.addEventListener("dispose",W)),P=$e}if(P.visible=V.visible,P.wireframe=V.wireframe,k===fr?P.side=V.shadowSide!==null?V.shadowSide:V.side:P.side=V.shadowSide!==null?V.shadowSide:v[V.side],P.alphaMap=V.alphaMap,P.alphaTest=V.alphaTest,P.map=V.map,P.clipShadows=V.clipShadows,P.clippingPlanes=V.clippingPlanes,P.clipIntersection=V.clipIntersection,P.displacementMap=V.displacementMap,P.displacementScale=V.displacementScale,P.displacementBias=V.displacementBias,P.wireframeLinewidth=V.wireframeLinewidth,P.linewidth=V.linewidth,Z.isPointLight===!0&&P.isMeshDistanceMaterial===!0){const ue=t.properties.get(P);ue.light=Z}return P}function D(H,V,Z,k,P){if(H.visible===!1)return;if(H.layers.test(V.layers)&&(H.isMesh||H.isLine||H.isPoints)&&(H.castShadow||H.receiveShadow&&P===fr)&&(!H.frustumCulled||i.intersectsObject(H))){H.modelViewMatrix.multiplyMatrices(Z.matrixWorldInverse,H.matrixWorld);const se=e.update(H),Te=H.material;if(Array.isArray(Te)){const $e=se.groups;for(let X=0,ve=$e.length;X=1):ie.indexOf("OpenGL ES")!==-1&&(ve=parseFloat(/^OpenGL ES (\d)/.exec(ie)[1]),X=ve>=2);let nt=null,Ce={};const $=t.getParameter(t.SCISSOR_BOX),be=t.getParameter(t.VIEWPORT),Fe=new Ii().fromArray($),oe=new Ii().fromArray(be);function Ae(M,J,fe,de){const ke=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 le=1;const Ne=qe(q);if((Ne.width>te||Ne.height>te)&&(le=te/Math.max(Ne.width,Ne.height)),le<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(le*Ne.width),rt=Math.floor(le*Ne.height);v===void 0&&(v=T(De,rt));const it=C?T(De,rt):v;return it.width=De,it.height=rt,it.getContext("2d").drawImage(q,0,0,De,rt),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+Ne.width+"x"+Ne.height+") to ("+De+"x"+rt+")."),it}else return"data"in q&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+Ne.width+"x"+Ne.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,le,Ne=!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 rt=Ne?rh:kn.getTransfer(le);te===t.FLOAT&&(De=t.RGBA32F),te===t.HALF_FLOAT&&(De=t.RGBA16F),te===t.UNSIGNED_BYTE&&(De=rt===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 H(q){const C=q.target;C.removeEventListener("dispose",H),Z(C),C.isVideoTexture&&g.delete(C)}function V(q){const C=q.target;C.removeEventListener("dispose",V),P(C)}function Z(q){const C=i.get(q);if(C.__webglInit===void 0)return;const te=q.source,le=y.get(te);if(le){const Ne=le[C.__cacheKey];Ne.usedTimes--,Ne.usedTimes===0&&k(q),Object.keys(le).length===0&&y.delete(te)}i.remove(q)}function k(q){const C=i.get(q);t.deleteTexture(C.__webglTexture);const te=q.source,le=y.get(te);delete le[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 le=0;le<6;le++){if(Array.isArray(C.__webglFramebuffer[le]))for(let Ne=0;Ne=r.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+q+" texture units while this GPU supports only "+r.maxTextures),Q+=1,q}function Te(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 $e(q,C){const te=i.get(q);if(q.isVideoTexture&&We(q),q.isRenderTargetTexture===!1&&q.version>0&&te.__version!==q.version){const le=q.image;if(le===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(le.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 ve(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 ie(q,C){const te=i.get(q);if(q.version>0&&te.__version!==q.version){Ae(te,q,C);return}n.bindTexture(t.TEXTURE_CUBE_MAP,te.__webglTexture,t.TEXTURE0+C)}const nt={[J0]:t.REPEAT,[Va]:t.CLAMP_TO_EDGE,[K0]:t.MIRRORED_REPEAT},Ce={[Jo]:t.NEAREST,[Nk]:t.NEAREST_MIPMAP_NEAREST,[of]:t.NEAREST_MIPMAP_LINEAR,[Bs]:t.LINEAR,[Om]:t.LINEAR_MIPMAP_NEAREST,[Ha]:t.LINEAR_MIPMAP_LINEAR},$={[kk]:t.NEVER,[Vk]:t.ALWAYS,[zk]:t.LESS,[RE]:t.LEQUAL,[Pk]:t.EQUAL,[Bk]:t.GEQUAL,[Fk]:t.GREATER,[Ok]:t.NOTEQUAL};function be(q,C){if(C.type===Vs&&e.has("OES_texture_float_linear")===!1&&(C.magFilter===Bs||C.magFilter===Om||C.magFilter===of||C.magFilter===Ha||C.minFilter===Bs||C.minFilter===Om||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,nt[C.wrapS]),t.texParameteri(q,t.TEXTURE_WRAP_T,nt[C.wrapT]),(q===t.TEXTURE_3D||q===t.TEXTURE_2D_ARRAY)&&t.texParameteri(q,t.TEXTURE_WRAP_R,nt[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 Fe(q,C){let te=!1;q.__webglInit===void 0&&(q.__webglInit=!0,C.addEventListener("dispose",H));const le=C.source;let Ne=y.get(le);Ne===void 0&&(Ne={},y.set(le,Ne));const De=Te(C);if(De!==q.__cacheKey){Ne[De]===void 0&&(Ne[De]={texture:t.createTexture(),usedTimes:0},c.memory.textures++,te=!0),Ne[De].usedTimes++;const rt=Ne[q.__cacheKey];rt!==void 0&&(Ne[q.__cacheKey].usedTimes--,rt.usedTimes===0&&k(C)),q.__cacheKey=De,q.__webglTexture=Ne[De].texture}return te}function oe(q,C,te){let le=t.TEXTURE_2D;(C.isDataArrayTexture||C.isCompressedArrayTexture)&&(le=t.TEXTURE_2D_ARRAY),C.isData3DTexture&&(le=t.TEXTURE_3D);const Ne=Fe(q,C),De=C.source;n.bindTexture(le,q.__webglTexture,t.TEXTURE0+te);const rt=i.get(De);if(De.version!==rt.__version||Ne===!0){n.activeTexture(t.TEXTURE0+te);const it=kn.getPrimaries(kn.workingColorSpace),F=C.colorSpace===na?null:kn.getPrimaries(C.colorSpace),ce=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,ce);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 ae=L(C.internalFormat,j,B,C.colorSpace,C.isVideoTexture);be(le,C);let Y;const me=C.mipmaps,ee=C.isVideoTexture!==!0,Xe=rt.__version===void 0||Ne===!0,M=De.dataReady,J=W(C,z);if(C.isDepthTexture)ae=D(C.format===uc,C.type),Xe&&(ee?n.texStorage2D(t.TEXTURE_2D,1,ae,z.width,z.height):n.texImage2D(t.TEXTURE_2D,0,ae,z.width,z.height,0,j,B,null));else if(C.isDataTexture)if(me.length>0){ee&&Xe&&n.texStorage2D(t.TEXTURE_2D,J,ae,me[0].width,me[0].height);for(let fe=0,de=me.length;fe0){const ke=V1(Y.width,Y.height,C.format,C.type);for(const Je of C.layerUpdates){const ht=Y.data.subarray(Je*ke/Y.data.BYTES_PER_ELEMENT,(Je+1)*ke/Y.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,fe,0,0,Je,Y.width,Y.height,1,j,ht)}C.clearLayerUpdates()}else n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,fe,0,0,0,Y.width,Y.height,z.depth,j,Y.data)}else n.compressedTexImage3D(t.TEXTURE_2D_ARRAY,fe,ae,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,fe,0,0,0,Y.width,Y.height,z.depth,j,B,Y.data):n.texImage3D(t.TEXTURE_2D_ARRAY,fe,ae,Y.width,Y.height,z.depth,0,j,B,Y.data)}else{ee&&Xe&&n.texStorage2D(t.TEXTURE_2D,J,ae,me[0].width,me[0].height);for(let fe=0,de=me.length;fe0){const fe=V1(z.width,z.height,C.format,C.type);for(const de of C.layerUpdates){const ke=z.data.subarray(de*fe/z.data.BYTES_PER_ELEMENT,(de+1)*fe/z.data.BYTES_PER_ELEMENT);n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,de,z.width,z.height,1,j,B,ke)}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,ae,z.width,z.height,z.depth,0,j,B,z.data);else if(C.isData3DTexture)ee?(Xe&&n.texStorage3D(t.TEXTURE_3D,J,ae,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,ae,z.width,z.height,z.depth,0,j,B,z.data);else if(C.isFramebufferTexture){if(Xe)if(ee)n.texStorage2D(t.TEXTURE_2D,J,ae,z.width,z.height);else{let fe=z.width,de=z.height;for(let ke=0;ke>=1,de>>=1}}else if(me.length>0){if(ee&&Xe){const fe=qe(me[0]);n.texStorage2D(t.TEXTURE_2D,J,ae,fe.width,fe.height)}for(let fe=0,de=me.length;fe0&&J++;const de=qe(j[0]);n.texStorage2D(t.TEXTURE_CUBE_MAP,J,me,de.width,de.height)}for(let de=0;de<6;de++)if(z){ee?M&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+de,0,0,0,j[de].width,j[de].height,ae,Y,j[de].data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+de,0,me,j[de].width,j[de].height,0,ae,Y,j[de].data);for(let ke=0;ke>De),B=Math.max(1,C.height>>De);Ne===t.TEXTURE_3D||Ne===t.TEXTURE_2D_ARRAY?n.texImage3D(Ne,De,F,j,B,C.depth,0,rt,it,null):n.texImage2D(Ne,De,F,j,B,0,rt,it,null)}n.bindFramebuffer(t.FRAMEBUFFER,q),lt(C)?u.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,le,Ne,z.__webglTexture,0,Oe(C)):(Ne===t.TEXTURE_2D||Ne>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&Ne<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,le,Ne,z.__webglTexture,De),n.bindFramebuffer(t.FRAMEBUFFER,null)}function we(q,C,te){if(t.bindRenderbuffer(t.RENDERBUFFER,q),C.depthBuffer){const le=C.depthTexture,Ne=le&&le.isDepthTexture?le.type:null,De=D(C.stencilBuffer,Ne),rt=C.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,it=Oe(C);lt(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,rt,t.RENDERBUFFER,q)}else{const le=C.textures;for(let Ne=0;Ne{delete C.__boundDepthTexture,delete C.__depthDisposeCallback,le.removeEventListener("dispose",Ne)};le.addEventListener("dispose",Ne),C.__depthDisposeCallback=Ne}C.__boundDepthTexture=le}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 le=0;le<6;le++)if(n.bindFramebuffer(t.FRAMEBUFFER,C.__webglFramebuffer[le]),C.__webglDepthbuffer[le]===void 0)C.__webglDepthbuffer[le]=t.createRenderbuffer(),we(C.__webglDepthbuffer[le],q,!1);else{const Ne=q.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,De=C.__webglDepthbuffer[le];t.bindRenderbuffer(t.RENDERBUFFER,De),t.framebufferRenderbuffer(t.FRAMEBUFFER,Ne,t.RENDERBUFFER,De)}}else if(n.bindFramebuffer(t.FRAMEBUFFER,C.__webglFramebuffer),C.__webglDepthbuffer===void 0)C.__webglDepthbuffer=t.createRenderbuffer(),we(C.__webglDepthbuffer,q,!1);else{const le=q.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,Ne=C.__webglDepthbuffer;t.bindRenderbuffer(t.RENDERBUFFER,Ne),t.framebufferRenderbuffer(t.FRAMEBUFFER,le,t.RENDERBUFFER,Ne)}n.bindFramebuffer(t.FRAMEBUFFER,null)}function xe(q,C,te){const le=i.get(q);C!==void 0&&Qe(le.__webglFramebuffer,q,q.texture,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,0),te!==void 0&&ye(q)}function Le(q){const C=q.texture,te=i.get(q),le=i.get(C);q.addEventListener("dispose",V);const Ne=q.textures,De=q.isWebGLCubeRenderTarget===!0,rt=Ne.length>1;if(rt||(le.__webglTexture===void 0&&(le.__webglTexture=t.createTexture()),le.__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&<(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(lt(q)===!1){const C=q.textures,te=q.width,le=q.height;let Ne=t.COLOR_BUFFER_BIT;const De=q.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,rt=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,le=q.format,Ne=q.type;return q.isCompressedTexture===!0||q.isVideoTexture===!0||te!==dc&&te!==na&&(kn.getTransfer(te)===Qn?(le!==ws||Ne!==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=se,this.resetTextureUnits=ue,this.setTexture2D=$e,this.setTexture2DArray=X,this.setTexture3D=ve,this.setTextureCube=ie,this.rebindTextures=xe,this.setupRenderTarget=Le,this.updateRenderTargetMipmap=st,this.updateMultisampleRenderTarget=Ee,this.setupDepthRenderbuffer=ye,this.setupFrameBufferTexture=Qe,this.useMultisampledRTT=lt}function nO(t,e){function n(i,r=na){let a;const c=kn.getTransfer(r);if(i===yr)return t.UNSIGNED_BYTE;if(i===ov)return t.UNSIGNED_SHORT_4_4_4_4;if(i===sv)return t.UNSIGNED_SHORT_5_5_5_1;if(i===SE)return t.UNSIGNED_INT_5_9_9_9_REV;if(i===_E)return t.BYTE;if(i===bE)return t.SHORT;if(i===Pu)return t.UNSIGNED_SHORT;if(i===iv)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===TE)return t.ALPHA;if(i===EE)return t.RGB;if(i===ws)return t.RGBA;if(i===wE)return t.LUMINANCE;if(i===ME)return t.LUMINANCE_ALPHA;if(i===ic)return t.DEPTH_COMPONENT;if(i===uc)return t.DEPTH_STENCIL;if(i===rv)return t.RED;if(i===av)return t.RED_INTEGER;if(i===CE)return t.RG;if(i===lv)return t.RG_INTEGER;if(i===cv)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===Z0||i===Q0||i===eg||i===tg)if(a=e.get("WEBGL_compressed_texture_pvrtc"),a!==null){if(i===Z0)return a.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===Q0)return a.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===eg)return a.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===tg)return a.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===ng||i===ig||i===og)if(a=e.get("WEBGL_compressed_texture_etc"),a!==null){if(i===ng||i===ig)return c===Qn?a.COMPRESSED_SRGB8_ETC2:a.COMPRESSED_RGB8_ETC2;if(i===og)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:a.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(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||i===xg)if(a=e.get("WEBGL_compressed_texture_astc"),a!==null){if(i===sg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:a.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===rg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:a.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===ag)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:a.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===lg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:a.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===cg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:a.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===ug)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:a.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===dg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:a.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===fg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:a.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===hg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:a.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===pg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:a.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===mg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:a.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===gg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:a.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===vg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:a.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===xg)return c===Qn?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:a.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===Vf||i===yg||i===_g)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===yg)return a.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===_g)return a.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===AE||i===bg||i===Sg||i===Tg)if(a=e.get("EXT_texture_compression_rgtc"),a!==null){if(i===Vf)return a.COMPRESSED_RED_RGTC1_EXT;if(i===bg)return a.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===Sg)return a.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===Tg)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 iO=` -void main() { - - gl_Position = vec4( position, 1.0 ); - -}`,oO=` -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 sO{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:iO,fragmentShader:oO,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 rO 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 sO,E=n.getContextAttributes();let w=null,I=null;const L=[],D=[],W=new Bn;let H=null;const V=new fs;V.viewport=new Ii;const Z=new fs;Z.viewport=new Ii;const k=[V,Z],P=new Mz;let Q=null,ue=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(oe){let Ae=L[oe];return Ae===void 0&&(Ae=new a0,L[oe]=Ae),Ae.getTargetRaySpace()},this.getControllerGrip=function(oe){let Ae=L[oe];return Ae===void 0&&(Ae=new a0,L[oe]=Ae),Ae.getGripSpace()},this.getHand=function(oe){let Ae=L[oe];return Ae===void 0&&(Ae=new a0,L[oe]=Ae),Ae.getHandSpace()};function se(oe){const Ae=D.indexOf(oe.inputSource);if(Ae===-1)return;const Qe=L[Ae];Qe!==void 0&&(Qe.update(oe.inputSource,oe.frame,d||c),Qe.dispatchEvent({type:oe.type,data:oe.inputSource}))}function Te(){r.removeEventListener("select",se),r.removeEventListener("selectstart",se),r.removeEventListener("selectend",se),r.removeEventListener("squeeze",se),r.removeEventListener("squeezestart",se),r.removeEventListener("squeezeend",se),r.removeEventListener("end",Te),r.removeEventListener("inputsourceschange",$e);for(let oe=0;oe=0&&(D[we]=null,L[we].disconnect(Qe))}for(let Ae=0;Ae=D.length){D.push(Qe),we=ye;break}else if(D[ye]===null){D[ye]=Qe,we=ye;break}if(we===-1)break}const N=L[we];N&&N.connect(Qe)}}const X=new Ue,ve=new Ue;function ie(oe,Ae,Qe){X.setFromMatrixPosition(Ae.matrixWorld),ve.setFromMatrixPosition(Qe.matrixWorld);const we=X.distanceTo(ve),N=Ae.projectionMatrix.elements,ye=Qe.projectionMatrix.elements,xe=N[14]/(N[10]-1),Le=N[14]/(N[10]+1),st=(N[9]+1)/N[5],tt=(N[9]-1)/N[5],U=(N[8]-1)/N[0],Ee=(ye[8]+1)/ye[0],Oe=xe*U,lt=xe*Ee,We=we/(-U+Ee),gt=We*-U;if(Ae.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(Ae.projectionMatrix),oe.projectionMatrixInverse.copy(Ae.projectionMatrixInverse);else{const qe=xe+We,q=Le+We,C=Oe-gt,te=lt+(we-gt),le=st*Le/q*qe,Ne=tt*Le/q*qe;oe.projectionMatrix.makePerspective(C,te,le,Ne,qe,q),oe.projectionMatrixInverse.copy(oe.projectionMatrix).invert()}}function nt(oe,Ae){Ae===null?oe.matrixWorld.copy(oe.matrix):oe.matrixWorld.multiplyMatrices(Ae.matrixWorld,oe.matrix),oe.matrixWorldInverse.copy(oe.matrixWorld).invert()}this.updateCamera=function(oe){if(r===null)return;let Ae=oe.near,Qe=oe.far;A.texture!==null&&(A.depthNear>0&&(Ae=A.depthNear),A.depthFar>0&&(Qe=A.depthFar)),P.near=Z.near=V.near=Ae,P.far=Z.far=V.far=Qe,(Q!==P.near||ue!==P.far)&&(r.updateRenderState({depthNear:P.near,depthFar:P.far}),Q=P.near,ue=P.far),V.layers.mask=oe.layers.mask|2,Z.layers.mask=oe.layers.mask|4,P.layers.mask=V.layers.mask|Z.layers.mask;const we=oe.parent,N=P.cameras;nt(P,we);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(aO.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 cO(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 H=e.render.frame;a[I.id]!==H&&(y(I),a[I.id]=H)}function g(I){const L=v();I.__bindingPointIndex=L;const D=t.createBuffer(),W=I.__size,H=I.usage;return t.bindBuffer(t.UNIFORM_BUFFER,D),t.bufferData(t.UNIFORM_BUFFER,W,H),t.bindBuffer(t.UNIFORM_BUFFER,null),t.bindBufferBase(t.UNIFORM_BUFFER,L,D),D}function v(){for(let I=0;I0&&(D+=W-H),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 uO{constructor(e={}){const{canvas:n=Gk(),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,H=0,V=0,Z=null,k=-1,P=null;const Q=new Ii,ue=new Ii;let se=null;const Te=new An(0);let $e=0,X=n.width,ve=n.height,ie=1,nt=null,Ce=null;const $=new Ii(0,0,X,ve),be=new Ii(0,0,X,ve);let Fe=!1;const oe=new OE;let Ae=!1,Qe=!1;this.transmissionResolutionScale=1;const we=new ui,N=new ui,ye=new Ue,xe=new Ii,Le={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let st=!1;function tt(){return Z===null?ie:1}let U=i;function Ee(G,_e){return n.getContext(G,_e)}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${nv}`),n.addEventListener("webglcontextlost",de,!1),n.addEventListener("webglcontextrestored",ke,!1),n.addEventListener("webglcontextcreationerror",Je,!1),U===null){const _e="webgl2";if(U=Ee(_e,G),U===null)throw Ee(_e)?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 Oe,lt,We,gt,qe,q,C,te,le,Ne,De,rt,it,F,ce,z,j,B,ae,Y,me,ee,Xe,M;function J(){Oe=new _F(U),Oe.init(),ee=new nO(U,Oe),lt=new hF(U,Oe,e,ee),We=new eO(U,Oe),lt.reverseDepthBuffer&&y&&We.buffers.depth.setReversed(!0),gt=new TF(U),qe=new V4,q=new tO(U,Oe,We,qe,lt,ee,gt),C=new mF(D),te=new yF(D),le=new Rz(U),Xe=new dF(U,le),Ne=new bF(U,le,gt,Xe),De=new wF(U,Ne,le,gt),ae=new EF(U,lt,q),z=new pF(qe),rt=new B4(D,C,te,Oe,lt,Xe,z),it=new lO(D,qe),F=new G4,ce=new Y4(Oe),B=new uF(D,C,te,We,De,S,h),j=new Z4(D,De,lt),M=new cO(U,gt,lt,We),Y=new fF(U,Oe,gt),me=new SF(U,Oe,gt),gt.programs=rt.programs,D.capabilities=lt,D.extensions=Oe,D.properties=qe,D.renderLists=F,D.shadowMap=j,D.state=We,D.info=gt}J();const fe=new rO(D,U);this.xr=fe,this.getContext=function(){return U},this.getContextAttributes=function(){return U.getContextAttributes()},this.forceContextLoss=function(){const G=Oe.get("WEBGL_lose_context");G&&G.loseContext()},this.forceContextRestore=function(){const G=Oe.get("WEBGL_lose_context");G&&G.restoreContext()},this.getPixelRatio=function(){return ie},this.setPixelRatio=function(G){G!==void 0&&(ie=G,this.setSize(X,ve,!1))},this.getSize=function(G){return G.set(X,ve)},this.setSize=function(G,_e,Ge=!0){if(fe.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}X=G,ve=_e,n.width=Math.floor(G*ie),n.height=Math.floor(_e*ie),Ge===!0&&(n.style.width=G+"px",n.style.height=_e+"px"),this.setViewport(0,0,G,_e)},this.getDrawingBufferSize=function(G){return G.set(X*ie,ve*ie).floor()},this.setDrawingBufferSize=function(G,_e,Ge){X=G,ve=_e,ie=Ge,n.width=Math.floor(G*Ge),n.height=Math.floor(_e*Ge),this.setViewport(0,0,G,_e)},this.getCurrentViewport=function(G){return G.copy(Q)},this.getViewport=function(G){return G.copy($)},this.setViewport=function(G,_e,Ge,He){G.isVector4?$.set(G.x,G.y,G.z,G.w):$.set(G,_e,Ge,He),We.viewport(Q.copy($).multiplyScalar(ie).round())},this.getScissor=function(G){return G.copy(be)},this.setScissor=function(G,_e,Ge,He){G.isVector4?be.set(G.x,G.y,G.z,G.w):be.set(G,_e,Ge,He),We.scissor(ue.copy(be).multiplyScalar(ie).round())},this.getScissorTest=function(){return Fe},this.setScissorTest=function(G){We.setScissorTest(Fe=G)},this.setOpaqueSort=function(G){nt=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,_e=!0,Ge=!0){let He=0;if(G){let ge=!1;if(Z!==null){const pt=Z.texture.format;ge=pt===cv||pt===lv||pt===av}if(ge){const pt=Z.texture.type,yt=pt===yr||pt===qa||pt===Pu||pt===cc||pt===ov||pt===sv,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 He|=U.COLOR_BUFFER_BIT}_e&&(He|=U.DEPTH_BUFFER_BIT),Ge&&(He|=U.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),U.clear(He)},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",de,!1),n.removeEventListener("webglcontextrestored",ke,!1),n.removeEventListener("webglcontextcreationerror",Je,!1),B.dispose(),F.dispose(),ce.dispose(),qe.dispose(),C.dispose(),te.dispose(),De.dispose(),Xe.dispose(),M.dispose(),rt.dispose(),fe.dispose(),fe.removeEventListener("sessionstart",Jt),fe.removeEventListener("sessionend",Dt),Yt.stop()};function de(G){G.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),W=!0}function ke(){console.log("THREE.WebGLRenderer: Context Restored."),W=!1;const G=gt.autoReset,_e=j.enabled,Ge=j.autoUpdate,He=j.needsUpdate,ge=j.type;J(),gt.autoReset=G,j.enabled=_e,j.autoUpdate=Ge,j.needsUpdate=He,j.type=ge}function Je(G){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",G.statusMessage)}function ht(G){const _e=G.target;_e.removeEventListener("dispose",ht),et(_e)}function et(G){Se(G),qe.remove(G)}function Se(G){const _e=qe.get(G).programs;_e!==void 0&&(_e.forEach(function(Ge){rt.releaseProgram(Ge)}),G.isShaderMaterial&&rt.releaseShaderCache(G))}this.renderBufferDirect=function(G,_e,Ge,He,ge,pt){_e===null&&(_e=Le);const yt=ge.isMesh&&ge.matrixWorld.determinant()<0,xt=tn(G,_e,Ge,He,ge);We.setMaterial(He,yt);let Tt=Ge.index,jt=1;if(He.wireframe===!0){if(Tt=Ne.getWireframeAttribute(Ge),Tt===void 0)return;jt=2}const qt=Ge.drawRange,kt=Ge.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;Xe.setup(ge,He,xt,Ge,Tt);let wn,Wt=Y;if(Tt!==null&&(wn=le.get(Tt),Wt=me,Wt.setIndex(wn)),ge.isMesh)He.wireframe===!0?(We.setLineWidth(He.wireframeLinewidth*tt()),Wt.setMode(U.LINES)):Wt.setMode(U.TRIANGLES);else if(ge.isLine){let zt=He.linewidth;zt===void 0&&(zt=1),We.setLineWidth(zt*tt()),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(Oe.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?le.get(Tt).bytesPerElement:1,xo=qe.get(He).currentProgram.getUniforms();for(let Di=0;Di{function pt(){if(He.forEach(function(yt){qe.get(yt).currentProgram.isReady()&&He.delete(yt)}),He.size===0){ge(G);return}setTimeout(pt,10)}Oe.get("KHR_parallel_shader_compile")!==null?pt():setTimeout(pt,10)})};let Ve=null;function _t(G){Ve&&Ve(G)}function Jt(){Yt.stop()}function Dt(){Yt.start()}const Yt=new HE;Yt.setAnimationLoop(_t),typeof self<"u"&&Yt.setContext(self),this.setAnimationLoop=function(G){Ve=G,fe.setAnimationLoop(G),G===null?Yt.stop():Yt.start()},fe.addEventListener("sessionstart",Jt),fe.addEventListener("sessionend",Dt),this.render=function(G,_e){if(_e!==void 0&&_e.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(),_e.parent===null&&_e.matrixWorldAutoUpdate===!0&&_e.updateMatrixWorld(),fe.enabled===!0&&fe.isPresenting===!0&&(fe.cameraAutoUpdate===!0&&fe.updateCamera(_e),_e=fe.getCamera()),G.isScene===!0&&G.onBeforeRender(D,G,_e,Z),w=ce.get(G,L.length),w.init(_e),L.push(w),N.multiplyMatrices(_e.projectionMatrix,_e.matrixWorldInverse),oe.setFromProjectionMatrix(N),Qe=this.localClippingEnabled,Ae=z.init(this.clippingPlanes,Qe),E=F.get(G,I.length),E.init(),I.push(E),fe.enabled===!0&&fe.isPresenting===!0){const pt=D.xr.getDepthSensingMesh();pt!==null&&Zt(pt,_e,-1/0,D.sortObjects)}Zt(G,_e,0,D.sortObjects),E.finish(),D.sortObjects===!0&&E.sort(nt,Ce),st=fe.enabled===!1||fe.isPresenting===!1||fe.hasDepthSensing()===!1,st&&B.addToRenderList(E,G),this.info.render.frame++,Ae===!0&&z.beginShadows();const Ge=w.state.shadowsArray;j.render(Ge,G,_e),Ae===!0&&z.endShadows(),this.info.autoReset===!0&&this.info.reset();const He=E.opaque,ge=E.transmissive;if(w.setupLights(),_e.isArrayCamera){const pt=_e.cameras;if(ge.length>0)for(let yt=0,xt=pt.length;yt0&&Gi(He,ge,G,_e),st&&B.render(G),ti(E,G,_e);Z!==null&&V===0&&(q.updateMultisampleRenderTarget(Z),q.updateRenderTargetMipmap(Z)),G.isScene===!0&&G.onAfterRender(D,G,_e),Xe.resetDefaultState(),k=-1,P=null,L.pop(),L.length>0?(w=L[L.length-1],Ae===!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,_e,Ge,He){if(G.visible===!1)return;if(G.layers.test(_e.layers)){if(G.isGroup)Ge=G.renderOrder;else if(G.isLOD)G.autoUpdate===!0&&G.update(_e);else if(G.isLight)w.pushLight(G),G.castShadow&&w.pushShadow(G);else if(G.isSprite){if(!G.frustumCulled||oe.intersectsSprite(G)){He&&xe.setFromMatrixPosition(G.matrixWorld).applyMatrix4(N);const yt=De.update(G),xt=G.material;xt.visible&&E.push(G,yt,xt,Ge,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(He&&(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,_e,Ge),pt.length>0&&Si(pt,_e,Ge),yt.length>0&&Si(yt,_e,Ge),We.buffers.depth.setTest(!0),We.buffers.depth.setMask(!0),We.buffers.color.setMask(!0),We.setPolygonOffset(!1)}function Gi(G,_e,Ge,He){if((Ge.isScene===!0?Ge.overrideMaterial:null)!==null)return;w.state.transmissionRenderTarget[He.id]===void 0&&(w.state.transmissionRenderTarget[He.id]=new Wa(1,1,{generateMipmaps:!0,type:Oe.has("EXT_color_buffer_half_float")||Oe.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[He.id],yt=He.viewport||Q;pt.setSize(yt.z*D.transmissionResolutionScale,yt.w*D.transmissionResolutionScale);const xt=D.getRenderTarget();D.setRenderTarget(pt),D.getClearColor(Te),$e=D.getClearAlpha(),$e<1&&D.setClearColor(16777215,.5),D.clear(),st&&B.render(Ge);const Tt=D.toneMapping;D.toneMapping=oa;const jt=He.viewport;if(He.viewport!==void 0&&(He.viewport=void 0),w.setupLightsView(He),Ae===!0&&z.setGlobalState(D.clippingPlanes,He),Si(G,Ge,He),q.updateMultisampleRenderTarget(pt),q.updateRenderTargetMipmap(pt),Oe.has("WEBGL_multisampled_render_to_texture")===!1){let qt=!1;for(let kt=0,hn=_e.length;kt0),kt=!!Ge.morphAttributes.position,hn=!!Ge.morphAttributes.normal,pn=!!Ge.morphAttributes.color;let Xn=oa;He.toneMapped&&(Z===null||Z.isXRRenderTarget===!0)&&(Xn=D.toneMapping);const wn=Ge.morphAttributes.position||Ge.morphAttributes.normal||Ge.morphAttributes.color,Wt=wn!==void 0?wn.length:0,zt=qe.get(He),Ci=w.state.lights;if(Ae===!0&&(Qe===!0||G!==P)){const pi=G===P&&He.id===k;z.setState(He,G,pi)}let vn=!1;He.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||He.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=He.version);let Ji=zt.currentProgram;vn===!0&&(Ji=fn(He,_e,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),He.id!==k&&(k=He.id,Di=!0),xo||P!==G){We.buffers.depth.getReversed()?(we.copy(G.projectionMatrix),qk(we),Wk(we),Rn.setValue(U,"projectionMatrix",we)):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)),lt.logarithmicDepthBuffer&&Rn.setValue(U,"logDepthBufFC",2/(Math.log(G.far+1)/Math.LN2)),(He.isMeshPhongMaterial||He.isMeshToonMaterial||He.isMeshLambertMaterial||He.isMeshBasicMaterial||He.isMeshStandardMaterial||He.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=Ge.morphAttributes;if((qi.position!==void 0||qi.normal!==void 0||qi.color!==void 0)&&ae.update(ge,Ge,Ji),(Di||zt.receiveShadow!==ge.receiveShadow)&&(zt.receiveShadow=ge.receiveShadow,Rn.setValue(U,"receiveShadow",ge.receiveShadow)),He.isMeshGouraudMaterial&&He.envMap!==null&&(io.envMap.value=Tt,io.flipEnvMap.value=Tt.isCubeTexture&&Tt.isRenderTargetTexture===!1?-1:1),He.isMeshStandardMaterial&&He.envMap===null&&_e.environment!==null&&(io.envMapIntensity.value=_e.environmentIntensity),Di&&(Rn.setValue(U,"toneMappingExposure",D.toneMappingExposure),zt.needsLights&&En(io,hi),pt&&He.fog===!0&&it.refreshFogUniforms(io,pt),it.refreshMaterialUniforms(io,He,ie,ve,w.state.transmissionRenderTarget[G.id]),Hf.upload(U,fi(zt),io,q)),He.isShaderMaterial&&He.uniformsNeedUpdate===!0&&(Hf.upload(U,fi(zt),io,q),He.uniformsNeedUpdate=!1),He.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),He.isShaderMaterial||He.isRawShaderMaterial){const pi=He.uniformsGroups;for(let yi=0,Lo=pi.length;yi0&&q.useMultisampledRTT(G)===!1?ge=qe.get(G).__webglMultisampledFramebuffer:Array.isArray(qt)?ge=qt[Ge]:ge=qt,Q.copy(G.viewport),ue.copy(G.scissor),se=G.scissorTest}else Q.copy($).multiplyScalar(ie).floor(),ue.copy(be).multiplyScalar(ie).floor(),se=Fe;if(Ge!==0&&(ge=bn),We.bindFramebuffer(U.FRAMEBUFFER,ge)&&He&&We.drawBuffers(G,ge),We.viewport(Q),We.scissor(ue),We.setScissorTest(se),pt){const Tt=qe.get(G.texture);U.framebufferTexture2D(U.FRAMEBUFFER,U.COLOR_ATTACHMENT0,U.TEXTURE_CUBE_MAP_POSITIVE_X+_e,Tt.__webglTexture,Ge)}else if(yt){const Tt=qe.get(G.texture),jt=_e;U.framebufferTextureLayer(U.FRAMEBUFFER,U.COLOR_ATTACHMENT0,Tt.__webglTexture,Ge,jt)}else if(G!==null&&Ge!==0){const Tt=qe.get(G.texture);U.framebufferTexture2D(U.FRAMEBUFFER,U.COLOR_ATTACHMENT0,U.TEXTURE_2D,Tt.__webglTexture,Ge)}k=-1},this.readRenderTargetPixels=function(G,_e,Ge,He,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(!lt.textureFormatReadable(jt)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!lt.textureTypeReadable(qt)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}_e>=0&&_e<=G.width-He&&Ge>=0&&Ge<=G.height-ge&&U.readPixels(_e,Ge,He,ge,ee.convert(jt),ee.convert(qt),pt)}finally{const Tt=Z!==null?qe.get(Z).__webglFramebuffer:null;We.bindFramebuffer(U.FRAMEBUFFER,Tt)}}},this.readRenderTargetPixelsAsync=async function(G,_e,Ge,He,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(!lt.textureFormatReadable(jt))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!lt.textureTypeReadable(qt))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");if(_e>=0&&_e<=G.width-He&&Ge>=0&&Ge<=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(_e,Ge,He,ge,ee.convert(jt),ee.convert(qt),0);const hn=Z!==null?qe.get(Z).__webglFramebuffer:null;We.bindFramebuffer(U.FRAMEBUFFER,hn);const pn=U.fenceSync(U.SYNC_GPU_COMMANDS_COMPLETE,0);return U.flush(),await jk(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,_e=null,Ge=0){G.isTexture!==!0&&(Na("WebGLRenderer: copyFramebufferToTexture function signature has changed."),_e=arguments[0]||null,G=arguments[1]);const He=Math.pow(2,-Ge),ge=Math.floor(G.image.width*He),pt=Math.floor(G.image.height*He),yt=_e!==null?_e.x:0,xt=_e!==null?_e.y:0;q.setTexture2D(G,0),U.copyTexSubImage2D(U.TEXTURE_2D,Ge,0,0,yt,xt,ge,pt),We.unbindTexture()};const ii=U.createFramebuffer(),Rs=U.createFramebuffer();this.copyTextureToTexture=function(G,_e,Ge=null,He=null,ge=0,pt=null){G.isTexture!==!0&&(Na("WebGLRenderer: copyTextureToTexture function signature has changed."),He=arguments[0]||null,G=arguments[1],_e=arguments[2],pt=arguments[3]||0,Ge=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(Ge!==null)yt=Ge.max.x-Ge.min.x,xt=Ge.max.y-Ge.min.y,Tt=Ge.isBox3?Ge.max.z-Ge.min.z:1,jt=Ge.min.x,qt=Ge.min.y,kt=Ge.isBox3?Ge.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}He!==null?(hn=He.x,pn=He.y,Xn=He.z):(hn=0,pn=0,Xn=0);const Wt=ee.convert(_e.format),zt=ee.convert(_e.type);let Ci;_e.isData3DTexture?(q.setTexture3D(_e,0),Ci=U.TEXTURE_3D):_e.isDataArrayTexture||_e.isCompressedArrayTexture?(q.setTexture2DArray(_e,0),Ci=U.TEXTURE_2D_ARRAY):(q.setTexture2D(_e,0),Ci=U.TEXTURE_2D),U.pixelStorei(U.UNPACK_FLIP_Y_WEBGL,_e.flipY),U.pixelStorei(U.UNPACK_PREMULTIPLY_ALPHA_WEBGL,_e.premultiplyAlpha),U.pixelStorei(U.UNPACK_ALIGNMENT,_e.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=_e.isDataArrayTexture||_e.isData3DTexture;if(G.isDepthTexture){const qi=qe.get(G),pi=qe.get(_e),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 $E(){dn.forEach(t=>{dO(t),li&&li.remove(t)}),dn=[]}const fO=(t,e,n)=>{if(Xo||(Xo=new uO({alpha:!0,antialias:!0,preserveDrawingBuffer:!0}),Xo.setPixelRatio(Math.min(devicePixelRatio,2)),Xo.setClearColor(0,0)),Xo.setSize(t,e),!li||Ag!==n.threejsScene){li&&$E(),li=new vz,Un=new fs(75,t/e,.1,1e3),Un.position.set(0,0,5),Ag=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(fO(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?pO(Un,c,a):hO(Un,c),Xo.render(li,Un),Xo.domElement},mO=()=>{$E(),Xo&&(Xo.dispose(),Xo=null),li=null,Un=null,Ag=void 0},gO=({isPlaying:t,currentTime:e,config:n})=>{const i=Re.useRef(null),r=Re.useRef(null),a=Re.useRef(t),c=Re.useRef(e),u=Re.useRef(n);return Re.useEffect(()=>{a.current=t},[t]),Re.useEffect(()=>{c.current=e},[e]),Re.useEffect(()=>{u.current=n},[n]),Re.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=XE(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),mO(),r.current=null}},[]),p.jsx("div",{ref:i,className:"absolute inset-0 pointer-events-none"})},Rh=(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 Le=Math.max(e/ye,n/xe),st=e/2-ye/2*Le,tt=n/2-xe/2*Le;t.drawImage(N,st,tt,ye*Le,xe*Le)}},W=(N,ye,xe)=>{if(ye.includes(` -`))return ye.split(` -`).flatMap(Ee=>W(N,Ee,xe));const Le=ye.split(" ");let st=[],tt=Le[0]||"";for(let Ee=1;Ee{if(st==="vhs"&&N instanceof CanvasRenderingContext2D)N.save(),N.globalCompositeOperation="screen",N.fillStyle="#ff0000",N.fillText(ye,xe-2,Le),N.fillStyle="#00ff00",N.fillText(ye,xe,Le),N.fillStyle="#0000ff",N.fillText(ye,xe+2,Le),N.restore();else if(st==="3d"){const U=N.fillStyle;N.fillStyle="rgba(0,0,0,0.5)";for(let Ee=1;Ee<=4;Ee++)N.fillText(ye,xe+Ee,Le+Ee);N.fillStyle=U,N.fillText(ye,xe,Le)}else if(st==="neon"){const U=N.fillStyle;N.shadowColor=U,N.shadowBlur=20,N.fillText(ye,xe,Le),N.shadowBlur=40,N.fillText(ye,xe,Le)}else if(st==="outline")N.strokeText(ye,xe,Le),N.fillText(ye,xe,Le);else if(st==="gradient"){const U=N.createLinearGradient(xe,Le-20,xe,Le+20);U.addColorStop(0,N.fillStyle),U.addColorStop(1,"#ffffff"),N.fillStyle=U,N.fillText(ye,xe,Le)}else if(st==="fire")N.save(),N.shadowBlur=5,N.shadowColor="#ff0000",N.fillStyle="#ff4500",N.fillText(ye,xe,Le),N.shadowBlur=2,N.shadowColor="#ffff00",N.fillStyle="#ffcc00",N.fillText(ye,xe+1,Le-1),N.restore();else if(st==="emboss")N.fillStyle="rgba(255,255,255,0.7)",N.fillText(ye,xe-1,Le-1),N.fillStyle="rgba(0,0,0,0.7)",N.fillText(ye,xe+1,Le+1),N.fillStyle="rgba(128,128,128,0.5)",N.fillText(ye,xe,Le);else if(st==="mirror")N.fillText(ye,xe,Le),N.save(),N.translate(xe,Le),N.scale(1,-1),N.translate(-xe,-Le),N.globalAlpha*=.2,N.fillText(ye,xe,Le-40),N.restore();else if(st==="neon-multi")N.fillStyle,N.shadowBlur=10,N.shadowColor="#fff",N.fillText(ye,xe,Le),N.shadowBlur=20,N.shadowColor="#ff00de",N.fillText(ye,xe,Le),N.shadowBlur=35,N.shadowColor="#00ffff",N.fillText(ye,xe,Le);else if(st==="gold"){const U=N.createLinearGradient(xe,Le-20,xe,Le+20);U.addColorStop(0,"#d4af37"),U.addColorStop(1,"#C5A028"),N.fillStyle=U,N.fillText(ye,xe,Le)}else if(st==="chrome"){const U=N.createLinearGradient(xe,Le-20,xe,Le+20);U.addColorStop(0,"#ebebeb"),U.addColorStop(.5,"#616161"),U.addColorStop(.51,"#ebebeb"),U.addColorStop(1,"#ebebeb"),N.fillStyle=U,N.fillText(ye,xe,Le)}else if(st==="frozen")N.shadowColor="#03A9F4",N.shadowBlur=20,N.fillStyle="#ffffff",N.fillText(ye,xe,Le);else if(st==="rainbow"){const U=N.createLinearGradient(xe-100,Le,xe+100,Le);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,Le)}else if(st==="retro")N.fillStyle="#ff00ff",N.shadowColor="#00ffff",N.shadowBlur=0,N.shadowOffsetX=4,N.shadowOffsetY=4,N.fillText(ye,xe,Le);else if(st==="cyberpunk")N.save(),N.fillStyle="#05d9e8",N.fillText(ye,xe-1,Le-1),N.restore(),N.save(),N.fillStyle="#000000",N.fillText(ye,xe+2,Le+2),N.restore(),N.save(),N.fillStyle="#fcee0a",N.fillText(ye,xe,Le),N.restore();else if(st==="glitch-text"){const U=(Math.random()-.5)*5,Ee=(Math.random()-.5)*2;N.save(),N.fillStyle="red",N.fillText(ye,xe+U,Le+Ee),N.restore(),N.save(),N.fillStyle="cyan",N.fillText(ye,xe-U,Le-Ee),N.restore(),N.fillStyle="#ffffff",N.fillText(ye,xe,Le)}else st==="hologram"?(N.fillStyle="rgba(0, 255, 255, 0.7)",N.shadowColor="rgba(0,255,255,0.5)",N.shadowBlur=10,N.fillText(ye,xe,Le)):(st==="comic"&&(N.lineWidth=3,N.strokeStyle="#000000",N.strokeText(ye,xe,Le),N.fillStyle="#ffcc00"),N.fillText(ye,xe,Le));if(tt&&tt!=="none"){const Ee=N.measureText(ye).width;let Oe=xe;if(N.textAlign==="center"?Oe=xe-Ee/2:N.textAlign==="right"&&(Oe=xe-Ee),N.save(),N.beginPath(),N.lineWidth=Math.max(2,4*Ce),N.strokeStyle=N.fillStyle,tt.includes("line-through")&&(N.moveTo(Oe,Le),N.lineTo(Oe+Ee,Le)),tt.includes("underline")){const lt=N.font.match(/(\d+(\.\d+)?)px/),We=lt?parseFloat(lt[1]):50,gt=Le+We*.4;N.moveTo(Oe,gt),N.lineTo(Oe+Ee,gt)}N.stroke(),N.restore()}},V=(N,ye,xe,Le,st,tt,U,Ee,Oe,lt,We,gt,qe)=>{const q=Ee?.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 Xe=me.split(" ").map(M=>({text:M,startTime:ye.time,endTime:ye.endTime||ye.time+3}));te.push(...Xe),eeY.text===` -`||Y.text.trim().length>0).map((Y,me)=>({...Y,text:Y.text===` -`?` -`:C(Y.text,me===0).trim()}));(Ee?.highlightEffect?.includes("cyberpunk")||Ee?.textEffect==="cyberpunk")&&(Oe="'Orbitron', sans-serif"),N.font=`${gt} ${We} ${lt}px ${Oe}`;const Ne=[];let De=[],rt=0,it=.3;["default","custom"].includes(d)?it=.25:d==="monospace"&&(it=.5);const F=N.measureText("M").width*it;le.forEach((Y,me)=>{if(Y.text===` -`){De.length>0&&Ne.push(De),De=[],rt=0;return}const ee=N.measureText(Y.text).width;let M=!Y.text.endsWith(" ");const J=/[-‐‑‒–—―]$/,fe=/^[-‐‑‒–—―]/;J.test(Y.text.trim())&&(M=!1);const de=le[me+1];de&&(fe.test(de.text.trim())||de.text===` -`)&&(M=!1);const ke=M?F:0;rt+ee>st&&De.length>0&&(Ne.push(De),De=[],rt=0),De.push(Y),rt+=ee+ke}),De.length>0&&Ne.push(De);const ce=Le-(Ne.length-1)*tt/2;let z=Ee.highlightColor||"#fb923c",j=Ee.highlightBackground||"#ffffff";const B=Ee.highlightEffect||"none";Ee.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 ae=Ee.fontColor||"#ffffff";Ee.highlightEffect==="karaoke-smooth-white"&&(ae="#ffffff"),Ne.forEach((Y,me)=>{const ee=ce+me*tt;let Xe=0;Y.forEach((J,fe)=>{if(Xe+=N.measureText(J.text).width,fe{const de=N.measureText(J.text).width,ke=U>=J.startTime,Je=U>=J.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&&(Ve+=(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"))Ve-=(1-bn)*50*qe,_t-=(1-bn)*Math.PI,Yt=bn;else if(B.includes("lightspeed"))Ve+=(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=Ve+de/2,tn=Ke;N.translate(Rt,tn),N.rotate(_t),N.scale(Jt,Dt),N.translate(-Rt,-tn)}if(Se){if(B==="karaoke-smooth-plus"){const Rt=Ee.textEffect||"none";if(Je){const tn=J.endTime-J.startTime,En=U-J.startTime,Mi=Math.max(0,Math.min(1,En/tn)),bn=Ve+de*Mi,ii=Ee?.textDecoration||"none",Rs=G=>{if(ii!=="none"){N.lineWidth=Math.max(2,3*qe),N.strokeStyle=G,N.beginPath();const _e=Ke+lt*.45;ii.includes("underline")&&(N.moveTo(Ve,_e),N.lineTo(Ve+de,_e)),ii.includes("line-through")&&(N.moveTo(Ve,Ke),N.lineTo(Ve+de,Ke)),N.stroke()}};N.save(),N.beginPath(),N.rect(Ve-50,Ke-tt,bn-(Ve-50),tt*2),N.clip(),N.fillStyle=z,H(N,J.text,Ve,Ke,Rt),Rs(z),N.restore(),N.save(),N.beginPath(),N.rect(bn,Ke-tt,Ve+de+50-bn,tt*2),N.clip(),N.fillStyle=ae,N.fillText(J.text,Ve,Ke),Rs(ae),N.restore(),ht="rgba(0,0,0,0)"}else N.fillStyle=z,H(N,J.text,Ve,Ke,Rt),ht=z}else if(B.includes("gradient")||B.includes("chrome")||B.includes("gold")){const Rt=N.createLinearGradient(Ve,Ke-tt/2,Ve,Ke+tt/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(J.text,Ve+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(J.text,Ve+tn*qe,Ke+tn*qe);N.fillStyle=Rt}if(B.includes("neon-multi"))N.shadowBlur=10,N.shadowColor="#fff",N.fillText(J.text,Ve,Ke),N.shadowBlur=20,N.shadowColor="#ff00de",N.fillText(J.text,Ve,Ke),N.shadowBlur=35,N.shadowColor="#00ffff",N.fillText(J.text,Ve,Ke);else if(B.includes("cyberpunk"))N.save(),N.fillStyle="#05d9e8",N.fillText(J.text,Ve-1,Ke-1),N.restore(),N.save(),N.fillStyle="#000000",N.fillText(J.text,Ve+2,Ke+2),N.restore(),N.fillStyle="#fcee0a",N.fillText(J.text,Ve,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(J.text,Ve+Rt,Ke+tn),N.restore(),N.save(),N.fillStyle="cyan",N.fillText(J.text,Ve-Rt,Ke-tn),N.restore(),N.fillStyle="#ffffff",N.fillText(J.text,Ve,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(J.text,Ve-3*qe+Rt,Ke+tn),N.fillStyle="#00ff00",N.fillText(J.text,Ve+tn,Ke-Rt),N.fillStyle="#0000ff",N.fillText(J.text,Ve+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(J.text,Ve,Ke+tn),N.shadowBlur=2,N.shadowColor="#ffff00",N.fillStyle="#ffcc00",N.fillText(J.text,Ve+Math.sin(U*25)*1*qe,Ke-1*qe+tn)}else if(B.includes("typewriter")){const Rt=U-J.startTime,tn=J.endTime-J.startTime,En=Math.min(1,Math.max(0,Rt/tn)),Mi=Math.floor(J.text.length*En),bn=J.text.substring(0,Mi);B.includes("outline")?(N.strokeStyle=z,N.strokeText(bn,Ve,Ke)):N.fillText(bn,Ve,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(J.text,Ve,Ke)):N.fillText(J.text,Ve,Ke))}else N.fillText(J.text,Ve,Ke);const ti=Ee?.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+lt*.45;N.moveTo(Ve,Rt),N.lineTo(Ve+de,Rt)}ti.includes("line-through")&&(N.moveTo(Ve,Ke),N.lineTo(Ve+de,Ke)),N.stroke()}N.restore(),N.restore();let Si=!J.text.endsWith(" ");const ji=/[-‐‑‒–—―]$/,fn=/^[-‐‑‒–—―]/;ji.test(J.text.trim())&&(Si=!1);const fi=Y[fe+1];fi&&fn.test(fi.text.trim())&&(Si=!1),M+=de+(Si?F:0)}),N.restore()})},Z=(N,ye,xe,Le,st,tt,U,Ee)=>{const Oe=W(N,ye,st),lt=Le-(Oe.length-1)*tt/2;Oe.forEach((We,gt)=>{const qe=lt+gt*tt;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-tt/2,q+20,tt,8):N.rect(xe-(N.textAlign==="center"?q/2:N.textAlign==="right"?q:0)-10,qe-tt/2,q+20,tt),N.fill(),N.strokeStyle="rgba(255, 255, 255, 0.2)",N.stroke(),N.restore()}H(N,We,xe,qe,U,Ee)})},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',Q='ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',ue='"Metal Mania", cursive',se='"Fredoka One", cursive',Te='"Shadows Into Light", cursive',$e='"Dancing Script", cursive',X='"Orbitron", sans-serif',ve='"UnifrakturMaguntia", cursive';let ie=k;d==="classic"?ie=P:d==="monospace"?ie=Q:d==="metal"?ie=ue:d==="kids"?ie=se:d==="sad"?ie=Te:d==="romantic"?ie=$e:d==="tech"?ie=X:d==="gothic"?ie=ve:d==="custom"&&(ie=T?.fontFamily||k),g&&(ie="CustomFont, sans-serif"),T&&T.fontFamily!=="sans-serif"&&(ie=T.fontFamily);const nt=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=XE(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 st=T?.visualTransitionType||"none",tt=T?.visualTransitionDuration||1,U=c.filter(Ee=>Ee.type==="audio"?!1:i>=Ee.startTime&&i=Ee.endTime&&i{const lt=(Ee.layer||0)-(Oe.layer||0);return lt!==0?lt:Ee.startTime-Oe.startTime}),U.length>0&&(U.forEach(Ee=>{const Oe=Ee.layer||0;if(T&&T.layerVisibility?.visual?.[Oe]===!1)return;const lt=Ee.type==="video"?h.get(Ee.id):null,We=Ee.type!=="video"?u.get(Ee.id):null;let gt=1;if(st!=="none"){if(i=Ee.endTime){let qe=!1;if(st==="crossfade"&&(qe=c.some(q=>q.id!==Ee.id&&(q.layer||0)===(Ee.layer||0)&&q.startTime>=Ee.endTime-.1&&q.startTimeEe.endTime-tt){const qe=(Ee.endTime-i)/tt;gt=Math.min(gt,Math.max(0,Math.min(1,qe)))}}gt>0&&(t.save(),t.globalAlpha=gt,lt?D(lt):We&&D(We),t.restore())}),ye=!0)}const xe=T?.backgroundSource||"custom",Le=xe==="custom"||xe==="timeline"&&c.length===0;if(!ye&&a.coverUrl&&Le){const st=a.backgroundType==="video"?h.get("background"):null,tt=u.get("cover");st?D(st):tt&&D(tt)}}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=mE(T);gE(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);be=N!==-1?N:r.length-1}const Fe=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 Ee=oe?{text:Fe}:r[$]||r[be];if(Ee){t.font=`900 ${Ae}px ${ie}`;const Oe=["large_upper","big_center","metal","tech","testing_up","one_line_up"].includes(d)?Ee.text.toUpperCase():Ee.text,lt=W(t,Oe,e*.9);lt.length>1&&(ye=(lt.length-1)*(Ae*1.2)/2)}}let Le=xe?-1:-2,st=xe?1:2;T?.lyricDisplayMode==="active-only"?(Le=0,st=0):T?.lyricDisplayMode==="next-only"?(Le=0,st=1):T?.lyricDisplayMode==="previous-next"?(Le=-1,st=1):T?.lyricDisplayMode==="all"&&(Le=-r.length,st=r.length);const tt=new Map,U=new Map;{const Ee=Math.max((nt?30:40)*Ce,we-Ae);for(let Oe=Le;Oe<=st;Oe++){let lt=0,We=!1;if(oe&&Oe===0){const gt=Ae*1.2,qe=Qe*1.2,C=Fe.split(` -`).length>1;lt=gt+(C?qe:0),We=!0}else{const gt=be+Oe;if(gt>=0&>rt.charAt(0).toUpperCase()+rt.substr(1).toLowerCase()):Ne==="sentence"?le=le.charAt(0).toUpperCase()+le.slice(1).toLowerCase():Ne==="invert"&&(le=le.replace(/\w\S*/g,rt=>rt.charAt(0).toLowerCase()+rt.slice(1).toUpperCase())),lt=W(t,le,e*.9).length*(q*1.2)}}U.set(Oe,lt)}tt.set(0,N);for(let Oe=1;Oe<=st;Oe++){const lt=tt.get(Oe-1)??N,We=U.get(Oe-1)??0,gt=U.get(Oe)??0;tt.set(Oe,lt+We/2+Ee+gt/2)}for(let Oe=-1;Oe>=Le;Oe--){const lt=tt.get(Oe+1)??N,We=U.get(Oe+1)??0,gt=U.get(Oe)??0;tt.set(Oe,lt-We/2-Ee-gt/2)}}for(let Ee=Le;Ee<=st;Ee++){let Oe=null,lt=!1;if(oe)Ee===0&&(Oe={time:0,text:Fe},lt=!0);else{const We=be+Ee;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")Ne=(1-Ve)*(et0&&(t.filter=`blur(${F}px)`);const z=lt&&T?.textAnimation||"none";let j=Oe.text,B=T?.textCase||"none";B==="none"&<&&["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 ae=0,Y=0,me=1,ee=1,Xe=0;if(lt&&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,Xe=Math.sin(i*4)*.05;else if(z==="glitch")Math.sin(i*10)>.8&&(ae=(Math.random()-.5)*15*Ce,Y=(Math.random()-.5)*15*Ce);else if(z==="shake")ae=(Math.random()-.5)*5*Ce,Y=(Math.random()-.5)*5*Ce;else if(z==="typewriter"){const Se=Math.floor((i-Oe.time)*30);j=j.substring(0,Math.max(0,Se))}else if(z==="wobble"){Xe=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")Xe=Math.sin(i*2)*.05;else if(z==="sway")Xe=Math.sin(i*2)*.08;else if(z==="flicker")t.globalAlpha=le*(.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")Xe=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,Xe=-.05):et<.2?(me=1.1,ee=1.1,Xe=.05):(me=1,ee=1,Xe=0)}else z==="swing"&&(Xe=Math.sin(i*3)*.1);let M=0;tt.has(Ee)?M=tt.get(Ee)+(Ee===0?Ne:0):(M=d==="subtitle"&&Ee===0&&T?.lyricDisplayMode!=="all"?n-140*Ce:N+Ee*we+(Ee===0?Ne:0),d!=="custom"&&(Ee<0?M-=ye:Ee>0&&(M+=ye))),M+=Y;let J=e/2;t.textAlign==="left"?J=60*Ce:t.textAlign==="right"&&(J=e-60*Ce),J+=De+ae;const fe=rt*me,de=it*ee,ke=ce+Xe;(fe!==1||de!==1||ke!==0)&&(t.translate(J,M),t.rotate(ke),t.scale(fe,de),t.translate(-J,-M));const Je=lt?T?.textEffect||"preset":"none";if(oe&&Ee===0&&T?.introMode!=="manual"){const et=j.split(` -`),Se=et[0],Ke=et.slice(1).join(` -`),Ve=Ae*1.2,_t=Qe*1.2,Jt=20*Ce;let Dt=M;Ke&&(Dt=M-_t/2-Jt/2);const Yt=M+Ve/2+Jt/2;if(t.font=`${q} ${qe} ${Ae}px ${ie}`,Z(t,Se,J,Dt,e*.9,Ve,Je,C),Ke){const Zt=d==="custom"&&T?.fontWeight?T.fontWeight:"400";t.font=`${q} ${Zt} ${Qe}px ${ie}`,Z(t,Ke,J,Yt,e*.9,_t,Je,C)}}else{const et=lt?Ae:Qe;T&&T.highlightEffect&&T.highlightEffect,lt&&Oe?V(t,Oe,J,M,e*.9,et*(T?.lyricLineHeight||1.2),i,T,ie,et,qe,q,Ce):Z(t,j,J,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",Le=T?.infoStyle||"classic",st=Le==="box",tt=st?16*Ce:12*Ce,U=40*Ce*(T?.infoMarginScale??1);let Ee="left",Oe="top";xe.includes("left")?Ee="left":xe.includes("right")?Ee="right":Ee="center",xe.includes("top")?Oe="top":Oe="bottom";const lt=T?.infoSizeScale??1,We=(Le==="minimal"||Le==="modern"?0:100*Ce)*lt,gt=ye&&We>0&&a.coverUrl!==null,qe=gt?a.backgroundType==="video"?h.get("background"):u.get("cover"):null,q=(Le==="minimal"?20:Le==="modern"||Le==="modern_art"?40:28)*Ce,C=(Le==="minimal"?14:Le==="modern"||Le==="modern_art"?24:18)*Ce,te=q*lt,le=C*lt,Ne=T?.infoFontFamily||ie,De=T?.infoFontWeight||"bold",rt=T?.infoFontStyle||"normal",it=`${rt} ${De} ${te}px ${Ne}`,F=`${rt} ${De} ${le}px ${Ne}`,ce=20*Ce,z=st?24*Ce:0,j=T?.infoFontColor||"#ffffff",B=Le==="modern"||Le==="modern_art"?j:T?.infoFontColor||"#d4d4d8";t.font=it;const ae=t.measureText(a.title),Y=T?.showTitle?ae.width:0;t.font=F;const me=t.measureText(a.artist),ee=T?.showArtist?me.width:0;let Xe=0,M=0;if(Ee==="center"){Xe=Math.max(gt&&qe?We:0,Y,ee)+z*2;let Ve=0;gt&&qe&&(Ve+=We),(T?.showTitle??!0)&&(Ve+=(gt&&qe?ce:0)+te),(T?.showArtist??!0)&&(Ve+=(gt&&qe||(T?.showTitle??!0)?5*Ce:0)+le),M=Ve+z*2}else{const Ke=Math.max(Y,ee);Xe=(gt&&qe?We+ce:0)+Ke+z*2;const _t=(T?.showTitle?te:0)+(T?.showArtist?le+5*Ce:0);M=Math.max(_t,gt&&qe?We:0)+z*2}let J=0,fe=0;Ee==="left"?J=U:Ee==="right"?J=e-U:J=e/2,Oe==="top"?fe=U:fe=n-U;let de=0,ke=0;Ee==="left"?de=J:Ee==="right"?de=J-Xe:de=J-Xe/2,Oe==="top"?ke=fe:ke=fe-M,st&&(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(de,ke,Xe,M,tt),t.fill(),t.restore());const Je=de+z,ht=ke+z,et=Xe-z*2,Se=M-z*2;if(Ee==="center"){let Ke=ht;const Ve=Je+et/2;if(t.textAlign="center",Oe==="top"){if(gt&&qe){t.save(),t.beginPath();const _t=Ve-We/2;Le==="circle_art"?t.arc(Ve,Ke+We/2,We/2,0,Math.PI*2):t.roundRect(_t,Ke,We,We,tt/2),t.clip(),t.drawImage(qe,_t,Ke,We,We),t.restore(),Ke+=We+ce}(T?.showTitle??!0)&&(t.fillStyle=j,t.font=it,t.textBaseline="top",t.fillText(a.title,Ve,Ke),Ke+=te+5*Ce),(T?.showArtist??!0)&&(t.fillStyle=B,t.font=F,t.textBaseline="top",t.fillText(a.artist,Ve,Ke))}else{if(gt&&qe){t.save(),t.beginPath();const _t=Ve-We/2;Le==="circle_art"?t.arc(Ve,Ke+We/2,We/2,0,Math.PI*2):t.roundRect(_t,Ke,We,We,tt/2),t.clip(),t.drawImage(qe,_t,Ke,We,We),t.restore(),Ke+=We+ce}(T?.showTitle??!0)&&(t.fillStyle=j,t.font=it,t.textBaseline="top",t.fillText(a.title,Ve,Ke),Ke+=te+5*Ce),(T?.showArtist??!0)&&(t.fillStyle=B,t.font=F,t.textBaseline="top",t.fillText(a.artist,Ve,Ke))}}else{const Ke=Ee==="right",Ve=ht+Se/2;let _t=Je;if(Ke&&(_t=Je+et),gt&&qe){const Yt=Ve-We/2,Zt=Ke?_t-We:_t;t.save(),t.beginPath(),Le==="circle_art"?t.arc(Zt+We/2,Yt+We/2,We/2,0,Math.PI*2):t.roundRect(Zt,Yt,We,We,tt/2),t.clip(),t.drawImage(qe,Zt,Yt,We,We),t.restore(),Ke?_t-=We+ce:_t+=We+ce}const Jt=(T?.showTitle?te:0)+(T?.showArtist?le+5*Ce:0);let Dt=Ve-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 ${ie}`,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 ${ie}`,t.fillStyle="#d4d4d8",t.fillText(a.artist,e/2,n-xe))}}else{const xe=40*Ce*(T?.infoMarginScale??1),Le=e===n,st=(nt?Le?110:150:100)*Ce,tt=a.coverUrl?u.get("cover"):null,U=12*Ce;if(nt){const Ee=xe*(Le?1.5:3),Oe=e/2,lt=Oe-st/2,We=Ee;if(ye&&(t.save(),t.beginPath(),t.roundRect(lt,We,st,st,U),t.clip(),tt?t.drawImage(tt,lt,We,st,st):(t.fillStyle="#27272a",t.fillRect(lt,We,st,st)),t.restore()),N){t.textAlign="center",t.textBaseline="top";const gt=We+(ye?st+25*Ce:0),qe=T?.infoFontFamily||ie,q=T?.infoFontColor||"#ffffff",C=T?.infoFontColor||"#d4d4d8",te=T?.infoFontWeight||"bold",le=T?.infoFontStyle||"normal";(T?.showTitle??!0)&&(t.font=`${le} ${te} ${(Le?26:36)*Ce}px ${qe}`,t.fillStyle=q,t.fillText(a.title,Oe,gt)),(T?.showArtist??!0)&&(t.font=`${le} ${te} ${(Le?18:24)*Ce}px ${qe}`,t.fillStyle=C,t.fillText(a.artist,Oe,gt+(T?.showTitle??!0?(Le?30:40)*Ce:0)))}}else{const Ee=xe,Oe=xe;if(ye&&(t.save(),t.beginPath(),t.roundRect(Ee,Oe,st,st,U),t.clip(),tt?t.drawImage(tt,Ee,Oe,st,st):(t.fillStyle="#27272a",t.fillRect(Ee,Oe,st,st)),t.restore()),N){t.textAlign="left",t.textBaseline="top";const lt=T?.infoFontFamily||ie,We=T?.infoFontColor||"#ffffff",gt=T?.infoFontColor||"#d4d4d8",qe=T?.infoFontWeight||"bold",q=T?.infoFontStyle||"normal",C=Ee+(ye?st+25*Ce:0),te=28*Ce,le=Oe+st/2-te;(T?.showTitle??!0)&&(t.font=`${q} ${qe} ${te}px ${lt}`,t.fillStyle=We,t.fillText(a.title,C,le)),(T?.showArtist??!0)&&(t.font=`${q} ${qe} ${18*Ce}px ${lt}`,t.fillStyle=gt,t.fillText(a.artist,C,le+(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,Le=T.channelInfoMarginScale??1,st=u.get("__channel_info__"),tt=T.channelInfoText;if(!(!st&&!tt)){if(!(ye==="logo"&&!st)){if(!(ye==="minimal"&&!tt)){t.save();const U=40*Ce*Le,Ee=80*Ce*xe,Oe=ye==="modern"||ye==="logo"?Ee*1.2:Ee,lt=20*Ce*xe,We=u.get("__channel_info_text_svg__"),gt=!!We;let qe=0,q=lt;if(gt&&We){q=lt*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} ${lt}px ${T.channelInfoFontFamily||"sans-serif"}`,tt&&ye!=="logo"&&(qe=t.measureText(tt).width)}const C=12*Ce*xe,te=12*Ce*xe,le=8*Ce*xe;let Ne=0,De=0;const rt=!!st&&ye!=="minimal",it=!!tt&&ye!=="logo";ye==="modern"?(Ne=Math.max(rt?Oe:0,it?qe+te*2:0),De=(rt?Oe:0)+(rt&&it?C:0)+(it?q+le*2:0)):ye==="box"?(Ne=(rt?Oe:0)+(rt&&it?C:0)+(it?qe:0)+te*2,De=Math.max(rt?Oe:0,it?q:0)+le*2):ye==="minimal"?(Ne=it?qe+te*2:0,De=it?q+le*2:0):ye==="logo"?(Ne=Oe,De=Oe):(Ne=(rt?Oe:0)+(rt&&it?C:0)+(it?qe+te*2:0),De=Math.max(rt?Oe:0,it?q+le*2:0));let F=0,ce=0;N.includes("left")?F=U:N.includes("right")?F=e-U-Ne:N.includes("center")&&(F=(e-Ne)/2),N.includes("top")?ce=U:N.includes("bottom")&&(ce=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,ce,Ne,De,12*Ce*xe),t.fill()):t.fillRect(F,ce,Ne,De),t.shadowColor="transparent",t.shadowBlur=0);const z=(j,B,ae,Y,me)=>{if(ye!=="box"&&ye!=="minimal"&&(t.fillStyle="rgba(0, 0, 0, 0.2)",t.roundRect?(t.beginPath(),t.roundRect(j,B,ae,Y,8*Ce*xe),t.fill()):t.fillRect(j,B,ae,Y)),gt&&We){const ee=j+(ae-qe)/2,Xe=B+(Y-q)/2;t.drawImage(We,ee,Xe,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+(ae-qe)/2,Xe=B+(Y-q)/2+q*.1;t.fillText(me,ee,Xe),t.shadowColor="transparent"}};if(ye==="modern"){let j=ce;if(rt){const B=F+(Ne-Oe)/2;t.drawImage(st,B,j,Oe,Oe),j+=Oe+C}if(it){const B=qe+te*2,ae=q+le*2,Y=F+(Ne-B)/2;z(Y,j,B,ae,tt)}}else{const j=N.includes("right");let B=F+(ye==="box"?te:0);const ae=ce+De/2;if(j&&(ye==="classic"||ye==="circle")){if(it){const Y=qe+te*2,me=q+le*2;z(B,ae-me/2,Y,me,tt),B+=Y+C}rt&&(ye==="circle"?(t.save(),t.beginPath(),t.arc(B+Oe/2,ae,Oe/2,0,Math.PI*2),t.closePath(),t.clip(),t.drawImage(st,B,ae-Oe/2,Oe,Oe),t.restore()):t.drawImage(st,B,ae-Oe/2,Oe,Oe))}else if(rt&&(ye==="circle"?(t.save(),t.beginPath(),t.arc(B+Oe/2,ae,Oe/2,0,Math.PI*2),t.closePath(),t.clip(),t.drawImage(st,B,ae-Oe/2,Oe,Oe),t.restore()):t.drawImage(st,B,ae-Oe/2,Oe,Oe),B+=Oe+C),it){const Y=qe+(ye==="box"?0:te*2),me=q+(ye==="box"?0:le*2);ye==="box"?gt&&We?(t.shadowColor="rgba(0,0,0,0.5)",t.shadowBlur=4,t.drawImage(We,B,ae-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(tt,B,ae+q*.1),t.shadowColor="transparent"):z(B,ae-me/2,Y,me,tt)}}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 vO=(()=>{let t=0;return()=>t++})(),xO=new Error("ffmpeg is not loaded, call `await ffmpeg.load()` first"),yO=new Error("called FFmpeg.terminate()");class _O{#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=vO();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(xO);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](yO),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 fT;(function(t){t.MEMFS="MEMFS",t.NODEFS="NODEFS",t.NODERAWFS="NODERAWFS",t.IDBFS="IDBFS",t.WORKERFS="WORKERFS",t.PROXYFS="PROXYFS"})(fT||(fT={}));const bO=new Error("failed to get response body reader"),SO=new Error("failed to complete download"),TO="Content-Length",EO=async(t,e)=>{const n=await fetch(t);let i;try{const r=parseInt(n.headers.get(TO)||"-1"),a=n.body?.getReader();if(!a)throw bO;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 SO;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 EO(t,i):await(await fetch(t)).arrayBuffer(),a=new Blob([r],{type:e});return URL.createObjectURL(a)};let xu=null,g0=!1,Nf=!1;async function YE(t){if(xu&&g0)return xu;if(Nf){for(;Nf;)await new Promise(e=>setTimeout(e,100));if(xu&&g0)return xu}Nf=!0;try{const e=new _O;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,g0=!0,t?.("[FFmpeg] Loaded successfully"),e}finally{Nf=!1}}function wO(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 JE(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 YE(E),H=()=>w?.aborted===!0||w?.current===!0;if(H())throw new Error("Render aborted");if(r.coverUrl&&(r.backgroundType==="video"?(E?.("[FFmpeg] Loading video background from metadata..."),await NO("background",r.coverUrl,u)):(E?.("[FFmpeg] Loading cover art from metadata..."),await RO("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 V=URL.createObjectURL(n),Z=await CO(V);URL.revokeObjectURL(V);const k=Math.ceil(Z*v),P=e.getContext("2d");if(!P)throw new Error("Failed to get canvas context");A(10,"Rendering frames...");const Q=await n.arrayBuffer();await W.writeFile("audio_src",new Uint8Array(Q));let ue=null,se=44100;if(g.showVisualization)try{E?.("[FFmpeg] Decoding audio for visualization analysis...");const $=new(window.AudioContext||window.webkitAudioContext),be=await $.decodeAudioData(Q.slice(0));ue=be.getChannelData(0),se=be.sampleRate,$.close(),E?.(`[FFmpeg] Audio decoded: ${be.duration.toFixed(1)}s @ ${se}Hz`)}catch($){E?.(`[FFmpeg] Warning: Could not decode audio for visualization: ${$.message}`)}const Te=Math.max(6,k.toString().length);for(let $=0;$0,Z,g,L,I,oe,Ae);const we=await(await new Promise((xe,Le)=>{e.toBlob(st=>st?xe(st):Le(new Error("Failed to create blob")),"image/jpeg",y==="high"?.98:y==="med"?.92:.85)})).arrayBuffer(),N=`frame_${$.toString().padStart(Te,"0")}.jpg`;await W.writeFile(N,new Uint8Array(we));const ye=10+$/k*70;A(ye,`Rendering frame ${$+1}/${k}`)}if(H())throw await If(W,k,Te),new Error("Render aborted");A(80,"Encoding video...");const $e=wO(S,y,t.resolution),X=`output.${$e.ext}`,ve=["-framerate",v.toString(),"-i",`frame_%0${Te}d.jpg`,"-i","audio_src","-c:v",$e.vcodec,...$e.args,"-c:a","aac","-b:a","192k","-ar","44100","-ac","2","-pix_fmt","yuv420p","-movflags","+faststart","-shortest","-y",X];E?.(`[FFmpeg] Running: ffmpeg ${ve.join(" ")}`);try{await W.exec(ve)}catch($){throw console.error("FFmpeg encoding failed:",$),await If(W,k,Te),new Error(`FFmpeg encoding failed: ${$}`)}A(95,"Finalizing...");const ie=await W.readFile(X),nt=ie instanceof Uint8Array?new Uint8Array(ie):new TextEncoder().encode(ie),Ce=new Blob([nt],{type:$e.format==="webm"?"video/webm":"video/mp4"});await If(W,k,Te);try{await W.deleteFile("audio_src"),await W.deleteFile(X)}catch{}return A(100,"Complete!"),{blob:Ce,duration:Z,format:$e.ext}}async function MO(t,e,n){const i=await YE(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 CO(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 AO(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 RO(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 NO(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)=>(gv(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)=>(gv(t,e,"write to private field"),e.set(t,n),n),IO=(t,e,n,i)=>({set _(r){to(t,e,r)},get _(){return pe(t,e,i)}}),_n=(t,e,n)=>(gv(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]]),DO=t=>(Gs.setInt16(0,t,!1),[Cn[0],Cn[1]]),KE=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]]),LO=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]]),vv=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]]),v0=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],xv=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},ZE=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]},QE=ZE(0),ew=t=>[Os(t[0]),Os(t[1]),v0(t[2]),Os(t[3]),Os(t[4]),v0(t[5]),Os(t[6]),Os(t[7]),v0(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),KE(n),i??[]],r),UO=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")])},Rg=t=>({type:"mdat",largeSize:t}),kO=t=>({type:"free",size:t}),Gf=(t,e,n=!1)=>Hi("moov",null,[zO(e,t),...t.map(i=>PO(i,e)),n?pB(t):null]),zO=(t,e)=>{let n=Hs(Math.max(0,...e.filter(c=>c.samples.length>0).map(c=>{const u=xv(c.samples);return u.presentationTimestamp+u.duration})),Dg),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(Dg),a(n),Os(1),vv(1),Array(10).fill(0),ew(QE),Array(24).fill(0),Ct(i)])},PO=(t,e)=>Hi("trak",null,[FO(t,e),OO(t,e)]),FO=(t,e)=>{let n=xv(t.samples),i=Hs(n?n.presentationTimestamp+n.duration:0,Dg),r=!hc(e)||!hc(i),a=r?$a:Ct,c;return t.info.type==="video"?c=typeof t.info.rotation=="number"?ZE(t.info.rotation):t.info.rotation:c=QE,di("tkhd",+r,3,[a(e),a(e),Ct(t.id),Ct(0),a(i),Array(8).fill(0),On(0),On(0),vv(t.info.type==="audio"?1:0),On(0),ew(c),Os(t.info.type==="video"?t.info.width:0),Os(t.info.type==="video"?t.info.height:0)])},OO=(t,e)=>Hi("mdia",null,[BO(t,e),VO(t.info.type==="video"?"vide":"soun"),HO(t)]),BO=(t,e)=>{let n=xv(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)])},VO=t=>di("hdlr",0,0,[us("mhlr"),us(t),Ct(0),Ct(0),Ct(0),us("mp4-muxer-hdlr",!0)]),HO=t=>Hi("minf",null,[t.info.type==="video"?GO():jO(),qO(),XO(t)]),GO=()=>di("vmhd",0,1,[On(0),On(0),On(0),On(0)]),jO=()=>di("smhd",0,0,[On(0),On(0)]),qO=()=>Hi("dinf",null,[WO()]),WO=()=>di("dref",0,0,[Ct(1)],[$O()]),$O=()=>di("url ",0,1),XO=t=>{const e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(n=>n.sampleCompositionTimeOffset!==0);return Hi("stbl",null,[YO(t),lB(t),cB(t),uB(t),dB(t),fB(t),e?hB(t):null])},YO=t=>di("stsd",0,0,[Ct(1)],[t.info.type==="video"?JO(EB[t.info.codec],t):sB(MB[t.info.codec],t)]),JO=(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),DO(65535)],[wB[e.info.codec](e),e.info.decoderConfig.colorSpace?eB(e):null]),KO={bt709:1,bt470bg:5,smpte170m:6},ZO={bt709:1,smpte170m:6,"iec61966-2-1":13},QO={rgb:0,bt709:1,bt470bg:5,smpte170m:6},eB=t=>Hi("colr",[us("nclx"),On(KO[t.info.decoderConfig.colorSpace.primaries]),On(ZO[t.info.decoderConfig.colorSpace.transfer]),On(QO[t.info.decoderConfig.colorSpace.matrix]),$i((t.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),tB=t=>t.info.decoderConfig&&Hi("avcC",[...new Uint8Array(t.info.decoderConfig.description)]),nB=t=>t.info.decoderConfig&&Hi("hvcC",[...new Uint8Array(t.info.decoderConfig.description)]),iB=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)])},oB=()=>{let n=(1<<7)+1;return Hi("av1C",[n,0,0,0])},sB=(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)],[CB[e.info.codec](e)]),rB=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),KE(0),Ct(130071),Ct(130071),Ct(92307584),$i(e.byteLength),...e,Ct(109084800),$i(1),$i(2)])},aB=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),vv(n),$i(0)])},lB=t=>di("stts",0,0,[Ct(t.timeToSampleTable.length),t.timeToSampleTable.map(e=>[Ct(e.sampleCount),Ct(e.sampleDelta)])]),cB=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))])},uB=t=>di("stsc",0,0,[Ct(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(e=>[Ct(e.firstChunk),Ct(e.samplesPerChunk),Ct(1)])]),dB=t=>di("stsz",0,0,[Ct(0),Ct(t.samples.length),t.samples.map(e=>Ct(e.size))]),fB=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))]),hB=t=>di("ctts",0,0,[Ct(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(e=>[Ct(e.sampleCount),Ct(e.sampleCompositionTimeOffset)])]),pB=t=>Hi("mvex",null,t.map(mB)),mB=t=>di("trex",0,0,[Ct(t.id),Ct(1),Ct(0),Ct(0),Ct(0)]),hT=(t,e)=>Hi("moof",null,[gB(t),...e.map(vB)]),gB=t=>di("mfhd",0,0,[Ct(t)]),tw=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},vB=t=>Hi("traf",null,[xB(t),yB(t),_B(t)]),xB=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:tw(n)};return di("tfhd",0,e,[Ct(t.id),Ct(i.duration),Ct(i.size),Ct(i.flags)])},yB=t=>di("tfdt",1,0,[$a(Hs(t.currentChunk.startTimestamp,t.timescale))]),_B=t=>{let e=t.currentChunk.samples.map(A=>A.timescaleUnitsToNextSample),n=t.currentChunk.samples.map(A=>A.size),i=t.currentChunk.samples.map(tw),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?LO(r[E]):[]])])},bB=t=>Hi("mfra",null,[...t.map(SB),TB()]),SB=(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)])]),TB=()=>di("mfro",0,0,[Ct(0)]),EB={avc:"avc1",hevc:"hvc1",vp9:"vp09",av1:"av01"},wB={avc:tB,hevc:nB,vp9:iB,av1:oB},MB={aac:"mp4a",opus:"Opus"},CB={aac:rB,opus:aB},Nh=class{},yv=class extends Nh{constructor(){super(...arguments),this.buffer=null}},nw=class extends Nh{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.")}},AB=class extends Nh{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,iw=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&&eIB){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)};bv=new WeakSet;sw=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}))}},Dg=1e3,LB=["avc","hevc","vp9","av1"],UB=["aac","opus"],kB=2082844800,zB=["strict","offset","cross-track-offset"],Bt,Xt,gh,qo,co,eo,Zl,sc,Tv,ka,za,Uu,Lg,rw,Ug,aw,Ev,lw,kg,cw,wv,uw,Wf,zg,zs,pr,Mv,dw,ku,vh,xh,Cv,pc,ju,$f,Pg,fw=class{constructor(t){if(cn(this,Lg),cn(this,Ug),cn(this,Ev),cn(this,kg),cn(this,wv),cn(this,Wf),cn(this,zs),cn(this,Mv),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)+kB),cn(this,sc,[]),cn(this,Tv,1),cn(this,ka,[]),cn(this,za,[]),cn(this,Uu,!1),_n(this,Lg,rw).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 yv)to(this,Xt,new RB(t.target));else if(t.target instanceof nw)to(this,Xt,new Sv(t.target));else if(t.target instanceof AB)to(this,Xt,new DB(t.target));else throw new Error(`Invalid target: ${t.target}`);_n(this,kg,cw).call(this),_n(this,Ug,aw).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,Pg).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,zg).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,Pg).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,zg).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,Cv).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=bB(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(kO(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;Tv=new WeakMap;ka=new WeakMap;za=new WeakMap;Uu=new WeakMap;Lg=new WeakSet;rw=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 Nh))throw new TypeError("The target must be provided and an instance of Target.");if(t.video){if(!LB.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(!UB.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&&!zB.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.")};Ug=new WeakSet;aw=function(){if(pe(this,Xt).writeBox(UO({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,Rg(!1));else if(pe(this,Bt).fastStart!=="fragmented"){if(typeof pe(this,Bt).fastStart=="object"){let t=_n(this,Ev,lw).call(this);pe(this,Xt).seek(pe(this,Xt).pos+t)}to(this,qo,Rg(!0)),pe(this,Xt).writeBox(pe(this,qo))}_n(this,pc,ju).call(this)};Ev=new WeakSet;lw=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};kg=new WeakSet;cw=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,wv,uw).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}}};wv=new WeakSet;uw=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,Cv).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)};Mv=new WeakSet;dw=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=IO(this,Tv)._++;if(n===1){let u=Gf(e,pe(this,Zl),!0);pe(this,Xt).writeBox(u)}let i=pe(this,Xt).pos,r=hT(n,e);pe(this,Xt).writeBox(r);{let u=Rg(!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=hT(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 Sv&&pe(this,Xt).flush()};$f=new WeakSet;Pg=function(){if(pe(this,Uu))throw new Error("Cannot add new video or audio chunks after the file has been finalized.")};function Av(){return typeof window<"u"&&"VideoEncoder"in window&&"AudioEncoder"in window}async function Fg(t){const e=await t.arrayBuffer(),n=new(window.AudioContext||window.webkitAudioContext),i=await n.decodeAudioData(e);return n.close(),i}async function Og(t,e){if(t.sampleRate===e)return t;const n=new OfflineAudioContext(t.numberOfChannels,Math.ceil(t.duration*e),e),i=n.createBufferSource();return i.buffer=t,i.connect(n.destination),i.start(0),await n.startRendering()}async function yh(t,e){const n={codec:"mp4a.40.2",sampleRate:t,numberOfChannels:e,bitrate:128e3};if(typeof AudioEncoder<"u"&&"isConfigSupported"in AudioEncoder){try{if((await AudioEncoder.isConfigSupported(n)).supported)return n}catch(r){console.warn("AAC config check failed:",r)}const i={codec:"opus",sampleRate:48e3,numberOfChannels:e,bitrate:128e3};try{if((await AudioEncoder.isConfigSupported(i)).supported)return i}catch(r){console.warn("Opus config check failed:",r)}}return n}async function hw(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 PB(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 FB(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 OB(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(!Av())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...");let D=await Fg(n),W=await yh(D.sampleRate,D.numberOfChannels);W.codec==="opus"&&D.sampleRate!==48e3&&(T?.("Resampling audio to 48kHz for Opus support..."),D=await Og(D,48e3),W=await yh(D.sampleRate,D.numberOfChannels));const H=D.duration,V=Math.ceil(H*v),Z=new fw({target:new yv,video:{codec:"avc",width:e.width,height:e.height},audio:{codec:W.codec==="opus"?"opus":"aac",sampleRate:W.sampleRate,numberOfChannels:W.numberOfChannels},firstTimestampBehavior:"offset",fastStart:"in-memory"}),Q=(t.resolution==="1080p"?8e6:4e6)*(y==="high"?1.5:y==="low"?.5:1),ue=new VideoEncoder({output:(Fe,oe)=>{oe&&!oe.decoderConfig&&(oe.decoderConfig={codec:"avc1.4d002a",width:e.width,height:e.height,displayAspectWidth:e.width,displayAspectHeight:e.height}),Z.addVideoChunk(Fe,oe)},error:Fe=>{console.error("VideoEncoder error:",Fe),T?.(`VideoEncoder error: ${Fe.message}`)}});ue.configure({codec:"avc1.4d002a",width:e.width,height:e.height,bitrate:Q,framerate:v});const se=new AudioEncoder({output:(Fe,oe)=>Z.addAudioChunk(Fe,oe),error:Fe=>{console.error("AudioEncoder error:",Fe),T?.(`AudioEncoder error: ${Fe.message}`)}});se.configure(W),S(5,"Encoding Audio...");const Te=D.numberOfChannels,$e=D.sampleRate,X=$e,ve=D.length;for(let Fe=0;Fe10;)await new Promise(N=>setTimeout(N,10))}await se.flush(),S(10,"Rendering Frames...");const ie=e.getContext("2d",{desynchronized:!1});if(!ie)throw new Error("No canvas context");const nt=1/v*1e6,Ce=g.showVisualization?D.getChannelData(0):null,$=D.sampleRate;for(let Fe=0;Fe0,H,g,w,E,Qe,we);const N=Math.round(Fe*nt),ye=new VideoFrame(e,{timestamp:N,duration:Math.round(nt)});ue.encode(ye,{keyFrame:Fe%(v*2)===0}),ye.close();const xe=10+Fe/V*89;S(xe,`Rendering frame ${Fe}/${V}`),ue.encodeQueueSize>5&&await new Promise(Le=>{const st=()=>ue.encodeQueueSize<=2?Le(null):setTimeout(st,10);st()}),Fe%2===0&&await new Promise(Le=>setTimeout(Le,0))}S(99,"Finalizing frames..."),await ue.flush(),Z.finalize();const{buffer:be}=Z.target;return S(100,"Done!"),{blob:new Blob([be],{type:"video/mp4"}),duration:H,format:W.codec==="opus"?"mkv":"mp4"}}async function BB(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(!Av())throw new Error("WebCodecs API is not supported in this browser.");const T=()=>S?.aborted===!0||S?.current===!0;v(0,"Decoding first track...");let A=await Fg(t[0].audioFile),E=await yh(A.sampleRate,A.numberOfChannels);E.codec==="opus"&&A.sampleRate!==48e3&&(y?.("Resampling first track audio to 48kHz for Opus support..."),A=await Og(A,48e3),E=await yh(A.sampleRate,A.numberOfChannels));const w=A.sampleRate,I=A.numberOfChannels;v(2,"Initializing WebCodecs Playlist Render...");const L=new fw({target:new yv,video:{codec:"avc",width:n.width,height:n.height},audio:{codec:E.codec==="opus"?"opus":"aac",sampleRate:w,numberOfChannels:I},firstTimestampBehavior:"offset",fastStart:"in-memory"}),H=(e.resolution==="1080p"?8e6:4e6)*(g==="high"?1.5:g==="low"?.5:1),V=new VideoEncoder({output:(ue,se)=>{se&&!se.decoderConfig&&(se.decoderConfig={codec:"avc1.4d002a",width:n.width,height:n.height,displayAspectWidth:n.width,displayAspectHeight:n.height}),L.addVideoChunk(ue,se)},error:ue=>{console.error("VideoEncoder error:",ue),y?.(`VideoEncoder error: ${ue.message}`)}});V.configure({codec:"avc1.4d002a",width:n.width,height:n.height,bitrate:H,framerate:d});const Z=new AudioEncoder({output:(ue,se)=>L.addAudioChunk(ue,se),error:ue=>{console.error("AudioEncoder error:",ue),y?.(`AudioEncoder error: ${ue.message}`)}});Z.configure(E);let k=0,P=0;for(let ue=0;ue10&&await new Promise(xe=>setTimeout(xe,10))}const be=Math.ceil(ve*d),Fe=1/d*1e6,oe=n.getContext("2d");if(!oe)throw new Error("No canvas context");for(let Ae=0;Ae0,ve,h,$e,Te,N,ye);const xe=k+Math.round(Ae*Fe),Le=new VideoFrame(n,{timestamp:xe,duration:Math.round(Fe)});V.encode(Le,{keyFrame:Ae%(d*2)===0}),Le.close();const st=Ae/be,tt=(ue+st)/t.length*100;v(tt,`Song ${ue+1}/${t.length}: Rendering frame ${Ae}/${be}`),V.encodeQueueSize>5&&await new Promise(U=>{const Ee=()=>V.encodeQueueSize<=2?U(null):setTimeout(Ee,10);Ee()}),Ae%5===0&&await new Promise(U=>setTimeout(U,0))}k+=Math.round(ve*1e6)}v(99,"Flushing encoders..."),Z.state!=="closed"&&await Z.flush(),V.state!=="closed"&&await V.flush(),L.finalize();const{buffer:Q}=L.target;return v(100,"Done!"),{blob:new Blob([Q],{type:"video/mp4"}),duration:P,format:E.codec==="opus"?"mkv":"mp4"}}function VB(){const{toast:t,confirm:e}=Ou(),n=Re.useRef(null),i=Re.useRef(null),r=Re.useRef(null),a=Re.useRef(null),c=Re.useRef(null),u=Re.useRef({aborted:!1}),h=Re.useRef(()=>{});Re.useEffect(()=>{zU()},[]);const[d,g]=Re.useState(null),[v,y]=Re.useState(0),[S,T]=Re.useState({title:"No Audio Loaded",artist:"Select a file",coverUrl:null}),[A,E]=Re.useState([]),[w,I]=Re.useState([]),[L,D]=Re.useState(0),[W,H]=Re.useState(!1),[V,Z]=Re.useState("off"),[k,P]=Re.useState(0),[Q,ue]=Re.useState(0),[se,Te]=Re.useState(1),[$e,X]=Re.useState(!1),[ve,ie]=Re.useState(lo.PLAYER),[nt,Ce]=Re.useState(!1),[$,be]=Re.useState(!1),[Fe,oe]=Re.useState(!1),[Ae,Qe]=Re.useState(!1),[we,N]=Re.useState(!1),[ye,xe]=Re.useState(0),[Le,st]=Re.useState("16:9"),[tt,U]=Re.useState("1080p"),[Ee,Oe]=Re.useState("default"),[lt,We]=Re.useState(null),[gt,qe]=Re.useState(null),[q,C]=Re.useState(null),[te,le]=Re.useState("auto"),[Ne,De]=Re.useState(30),[rt,it]=Re.useState("med"),[F,ce]=Re.useState("mediarecorder"),[z,j]=Re.useState("h264"),[B,ae]=Re.useState(""),[Y,me]=Re.useState(!1),[ee,Xe]=Re.useState(!1),[M,J]=Re.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"}),fe=Re.useRef(M);Re.useEffect(()=>{fe.current=M},[M]);const de=Re.useRef(null),ke=Re.useRef(null),Je=M.backgroundBlurStrength>0,ht=Re.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(Ie=>MediaRecorder.isTypeSupported(Ie.value)),[]),[et,Se]=Re.useState([]),[Ke,Ve]=Re.useState(-1),[_t,Jt]=Re.useState(!1),Dt=()=>{const K=tt==="1080p";switch(Le){case"9:16":return K?{w:1080,h:1920}:{w:720,h:1280};case"3:4":return K?{w:1080,h:1440}:{w:720,h:960};case"4:3":return K?{w:1440,h:1080}:{w:960,h:720};case"1:1":return K?{w:1080,h:1080}:{w:720,h:720};case"1:2":return K?{w:1080,h:2160}:{w:720,h:1440};case"2:1":return K?{w:2160,h:1080}:{w:1440,h:720};case"2:3":return K?{w:1080,h:1620}:{w:720,h:1080};case"3:2":return K?{w:1620,h:1080}:{w:1080,h:720};case"4:5":return K?{w:1080,h:1350}:{w:720,h:900};case"20:9":return K?{w:2400,h:1080}:{w:1600,h:720};case"21:9":return K?{w:2560,h:1080}:{w:1720,h:720};default:return K?{w:1920,h:1080}:{w:1280,h:720}}},{w:Yt,h:Zt}=Dt(),[ti,Gi]=Re.useState(!0),[Si,ji]=Re.useState(!0),[fn,fi]=Re.useState(!1),Rt=Re.useMemo(()=>{const K=M.visualTransitionType||"none",Ie=M.visualTransitionDuration||1;return w.filter(Be=>Be.type==="audio"?!1:k>=Be.startTime&&k=Be.endTime&&k{const mt=(Be.layer||0)-(at.layer||0);return mt!==0?mt:Be.startTime-at.startTime})},[w,k,M.visualTransitionType,M.visualTransitionDuration]),tn=w.filter(K=>K.type==="audio"&&k>=K.startTime&&kL===0?A:A.map(K=>({...K,time:K.time+L,endTime:K.endTime!==void 0?K.endTime+L:void 0})),[A,L]),Mi=En.findIndex((K,Ie)=>{if(K.endTime!==void 0)return k>=K.time&&k=K.time&&(!dt||k{const Ie=K.target.files?.[0];if(Ie){d&&d.startsWith("blob:")&&URL.revokeObjectURL(d);const dt=URL.createObjectURL(Ie);g(dt);const Be={title:Ie.name.replace(/\.[^/.]+$/,""),artist:"Unknown Artist",coverUrl:null};T(Be),Ie.type.startsWith("audio/")?x0(()=>import("./jsmediatags.min-BZxB3j-v.js").then(at=>at.j),[]).then(at=>{at.read(Ie,{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)}})}):Ie.type.startsWith("video/")&&(Qe(!1),T({...Be,coverUrl:dt,backgroundType:"video"})),D(0),H(!1),P(0),Ve(-1),y(at=>at+1),r.current&&(r.current.scrollTop=0),n.current&&n.current.load()}K.target.value=""},ii=K=>{const Ie=K.target.files?.[0];if(Ie){const dt=URL.createObjectURL(Ie),Be=Ie.type.startsWith("video/");Be&&Qe(!1),T(at=>({...at,coverUrl:dt,backgroundType:Be?"video":"image"}))}K.target.value=""},Rs=async K=>{const Ie=K.target.files?.[0];if(Ie)try{const dt=await Ie.text(),Be=Ie.name.split(".").pop()?.toLowerCase();let at=[];Be==="lrc"?at=ea(dt):Be==="srt"?at=ta(dt):Be==="ttml"||Be==="xml"?at=Pa(dt):Be==="vtt"&&(at=Fa(dt)),at.some(mt=>mt.words&&mt.words.length>0)&&(J(mt=>({...mt,highlightEffect:"karaoke"})),t.success(`${Be?.toUpperCase()} loaded with word-level timing! Karaoke mode enabled.`)),E(at)}catch(dt){console.error("Failed to parse lyrics:",dt),t.error("Failed to parse lyric file.")}K.target.value=""};Re.useEffect(()=>{if(Ke!==-1&&et[Ke]){const K=et[Ke];E(K.parsedLyrics||[])}},[et,Ke]);const G=async K=>{const Ie=K.target.files?.[0];if(Ie){if(!window.FontFace||!document.fonts){t.error("Custom fonts are not supported in this browser.");return}try{const dt=URL.createObjectURL(Ie),Be=Ie.name.replace(/\.[^/.]+$/,""),at="CustomFont",mt=new FontFace(at,`url(${dt})`);await mt.load(),document.fonts.add(mt),We(Be),J(wt=>({...wt,fontFamily:at})),t.success(`Loaded font: ${Be}`)}catch(dt){console.error("Failed to load font:",dt),t.error("Failed to load font file.")}}K.target.value=""},_e=async K=>{const Ie=K.target.files?.[0];if(Ie){if(!window.FontFace||!document.fonts){t.error("Custom fonts are not supported in this browser.");return}try{const dt=URL.createObjectURL(Ie),Be=Ie.name.replace(/\.[^/.]+$/,""),at="ChannelFont",mt=new FontFace(at,`url(${dt})`);await mt.load(),document.fonts.add(mt),qe(Be),J(wt=>({...wt,channelInfoFontFamily:at})),t.success(`Loaded Channel font: ${Be}`)}catch(dt){console.error("Failed to load font:",dt),t.error("Failed to load channel font file.")}}K.target.value=""},Ge=async K=>{const Ie=K.target.files?.[0];if(Ie){if(!window.FontFace||!document.fonts){t.error("Custom fonts are not supported in this browser.");return}try{const dt=URL.createObjectURL(Ie),Be=Ie.name.replace(/\.[^/.]+$/,""),at="InfoFont",mt=new FontFace(at,`url(${dt})`);await mt.load(),document.fonts.add(mt),C(Be),J(wt=>({...wt,infoFontFamily:at})),t.success(`Loaded Info font: ${Be}`)}catch(dt){console.error("Failed to load font:",dt),t.error("Failed to load info font file.")}}K.target.value=""},He=Re.useCallback(async(K,Ie=!0,dt)=>{const Be=dt||et;if(K<0||K>=Be.length)return;const at=Be[K];d&&d.startsWith("blob:")&&URL.revokeObjectURL(d),H(!1),P(0),y(wt=>wt+1);const mt=URL.createObjectURL(at.audioFile);if(g(mt),T({title:at.metadata.title,artist:at.metadata.artist,coverUrl:at.metadata.coverUrl||null,backgroundType:at.metadata.backgroundType||"image"}),E([]),at.parsedLyrics&&at.parsedLyrics.length>0)E(at.parsedLyrics);else if(at.lyricFile)try{const wt=await at.lyricFile.text(),Ht=at.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),Ve(K),r.current&&(r.current.scrollTop=0),Ie?setTimeout(()=>{n.current&&(n.current.play().catch(wt=>console.log("Autoplay failed",wt)),H(!0))},150):(H(!1),n.current&&(n.current.pause(),n.current.currentTime=0))},[et,d]),ge=Re.useCallback(()=>{if(et.length===0)return;const K=(Ke+1)%et.length;He(K)},[et,Ke,He]),pt=Re.useCallback(()=>{if(et.length===0)return;const K=(Ke-1+et.length)%et.length;He(K)},[et,Ke,He]),yt=()=>{n.current&&(W?(n.current.pause(),H(!1)):!d&&et.length>0?He(0):(n.current.play().catch(console.error),H(!0)))},xt=Re.useCallback(()=>{n.current&&(n.current.pause(),n.current.currentTime=0,H(!1),P(0))},[]),Tt=()=>{Z(K=>K==="off"?"one":K==="one"?"all":K==="all"?"all_repeat":"off")},jt=()=>{document.fullscreenElement?(document.exitFullscreen(),Ce(!1)):(i.current?.requestFullscreen(),Ce(!0))},qt=K=>{if(we||K&&K.target.closest(".no-minimal-mode-toggle"))return;const Ie=!fn;fi(Ie),Ie&&oe(!0),t.success(`Minimal Mode: ${Ie?"On":"Off"}`,{id:"minimal-mode"})},kt=()=>{n.current&&(P(n.current.currentTime),we&&xe(n.current.currentTime/Q*100))},hn=()=>{n.current&&ue(n.current.duration)},pn=K=>{const Ie=parseFloat(K.target.value);n.current&&(n.current.currentTime=Ie,P(Ie))},Xn=K=>{if(!de.current||we||!Q)return;const Ie=de.current.getBoundingClientRect(),at=Math.max(0,Math.min(K-Ie.left,Ie.width))/Ie.width*Q;n.current&&(n.current.currentTime=at,P(at))},wn=K=>{const Ie=parseFloat(K.target.value);Te(Ie),n.current&&(n.current.volume=Ie),X(Ie===0)},Wt=K=>{if(!ke.current)return;const Ie=ke.current.getBoundingClientRect(),Be=Math.max(0,Math.min(K-Ie.left,Ie.width))/Ie.width;Te(Be),n.current&&(n.current.volume=Be),X(Be===0)},zt=async()=>{if(!n.current||!a.current)return;const K=M.renderMode==="playlist"&&et.length>0;console.log(`[Render] Starting Export. Mode: ${M.renderMode}, Playlist Items: ${et.length}, IsPlaylistRender: ${K}`),K?t.success(`Starting Playlist Render (${et.length} songs)...`):t.success("Starting Single Track Render...");const Ie=[];if(K)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);Ie.push({audioSrc:Mn,lyrics:Vt,metadata:At.metadata,isFileSource:!0})}else{if(!d)return;Ie.push({audioSrc:d,lyrics:En,metadata:S,isFileSource:!1})}if(Ie.length===0)return;const dt=K?`Start rendering ALL ${Ie.length} songs from the playlist? This will result in one continuous video.`:`Start rendering ${Le} (${tt}) video? This will play the song from start to finish.`;if(!await e(`${dt} Please do not switch tabs during rendering.`,"Start Rendering?")){K&&Ie.forEach(At=>At.isFileSource&&URL.revokeObjectURL(At.audioSrc));return}me(!1),N(!0),xe(0);const at={aborted:!1};u.current=at,xt(),Z("off"),hi.current&&clearTimeout(hi.current),be(!1),oe(!0),Li.current&&Li.current.pause();const mt=n.current,wt=Ee,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),at.aborted){N(!1),K&&Ie.forEach(At=>At.isFileSource&&URL.revokeObjectURL(At.audioSrc));return}const ni=a.current,re=ni.getContext("2d"),Mt=ni.captureStream(Ne);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}ZU();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=tt==="1080p"?8e6:4e6,fo=Ne>30?1.5:1,Uo=rt==="high"?2:rt==="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(at.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=K?`Playlist_${Ie.length}_Songs_${Le.replace(":","-")}.${Pn}`:`${Ie[0].metadata.title||"video"}_${Le.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),K&&Ie.forEach(At=>At.isFileSource&&URL.revokeObjectURL(At.audioSrc))};let bi=0,ms=[],Ns=S,Ko=0,qs=0;const sn=1e3/Ne,Ui=At=>{if(at.aborted)return;(si.state==="recording"||si.state==="paused")&&requestAnimationFrame(Ui);const Vt=At-qs;if(Vt0){const bt=Mn/Ko;if(K){const Yn=(bi+bt)/Ie.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)}}),re&&(un&&Vn&&jn&&(un.getByteFrequencyData(Vn),un.getByteTimeDomainData(jn)),Rh(re,ni.width,ni.height,Mn,ms,Ns,w,Ht,Pt,wt,lt,M.fontSizeScale,M.backgroundBlurStrength>0,Ko,M,M.renderMode==="current"||bi===Ie.length-1,M.renderMode==="current"||bi===0,Vn,jn))},Ka=async()=>{if(at.aborted){si.stop();return}if(bi>=Ie.length){await new Promise(Vt=>setTimeout(Vt,500)),si.stop();return}const At=Ie[bi];si.state==="recording"&&si.pause(),ms=At.lyrics,Ns=At.metadata,Ko=0,K&&Ve(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 ${Ie.length} items.`),Ie.length===0){t.error("Render queue is empty!"),N(!1);return}bi=0,await Ka()},Ci=async()=>{if(!a.current)return;const K=M.renderMode==="playlist"&&et.length>0;console.log(`[FFmpeg Render] Mode: ${M.renderMode}, Playlist: ${et.length}, IsPlaylist: ${K}`);let Ie=null,dt=En,Be=S;if(K&&et.length>0)Ie=et[0].audioFile,dt=et[0].parsedLyrics||[],Be=et[0].metadata;else if(et.length>0&&Ke>=0)Ie=et[Ke].audioFile;else if(d)try{Ie=await(await fetch(d)).blob()}catch(re){console.error("FFmpeg: Failed to fetch audio blob",re),t.error("Failed to load audio source for rendering.");return}else{t.error("Please load an audio file first.");return}if(!Ie){t.error("No audio file available for FFmpeg export.");return}const at=`Start FFmpeg rendering at ${tt} (${Le})? This uses frame-by-frame capture for higher quality. Rendering may take several minutes.`;if(!await e(at,"Start FFmpeg Rendering?"))return;me(!1),N(!0),xe(0),ae("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=(re,Mt)=>new Promise(Ft=>{const vt=new Image;vt.crossOrigin="anonymous",vt.onload=()=>{Nn.set(re,vt),Ft()},vt.onerror=()=>Ft(),vt.src=Mt}),ni=(re,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(re,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(re=>{re.type==="video"?$t.push(ni(re.id,re.url)):re.type!=="audio"&&$t.push(In(re.id,re.url))}),Be.coverUrl&&(Be.backgroundType==="video"?$t.push(ni("background",Be.coverUrl)):$t.push(In("cover",Be.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(K){const re=[];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)}re.push({audioFile:Lt.audioFile,lyrics:un,metadata:Lt.metadata})}const Mt=await MO(re,{canvas:Ht,visualSlides:w,imageMap:Nn,videoMap:ft,preset:Ee,customFontName:lt,renderConfig:M,resolution:tt,aspectRatio:Le,fps:Ne,quality:rt,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),ae(`Song ${Lt+1}/${un}: ${jn}`)}),Ft=`Playlist_${re.length}_Songs_${Le.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 re=await JE({canvas:Ht,audioFile:Ie,lyrics:dt,metadata:Be,visualSlides:w,imageMap:Nn,videoMap:ft,preset:Ee,customFontName:lt,renderConfig:M,resolution:tt,aspectRatio:Le,fps:Ne,quality:rt,codec:z,onProgress:(on,Lt)=>{xe(on),ae(Lt)},onLog:on=>console.log(on),abortSignal:wt,isFirstSong:!0,isLastSong:!0}),Mt=`${Be.title||"video"}_${Le.replace(":","-")}_ffmpeg.${re.format}`,Ft=URL.createObjectURL(re.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! (${re.format.toUpperCase()}, ${Math.round(re.duration)}s)`)}}catch(re){re.message!=="Render aborted"&&(console.error("FFmpeg render failed:",re),t.error(`FFmpeg render failed: ${re.message}`))}finally{N(!1),ae("")}},vn=async()=>{if(!a.current)return;const K=M.renderMode==="playlist"&&et.length>0;let Ie=null,dt=En,Be=S;if(K&&et.length>0)Ie=et[0].audioFile,dt=et[0].parsedLyrics||[],Be=et[0].metadata;else if(et.length>0&&Ke>=0)Ie=et[Ke].audioFile;else if(d)try{Ie=await(await fetch(d)).blob()}catch(re){console.error("WebCodecs: Failed to fetch audio blob",re),t.error("Failed to load audio source for rendering.");return}else{t.error("Please load an audio file first.");return}if(!Ie){t.error("No audio file available for export.");return}if(!Av()){t.error("WebCodecs is not supported in this browser.");return}const{w:at,h:mt}=Dt(),wt=`Start WebCodecs rendering at ${tt} @ ${Ne}fps? -Resolution: ${at}x${mt} - -This uses hardware acceleration and is very fast.`;if(!await e(wt,"Start WebCodecs Rendering?"))return;me(!1),N(!0),xe(0),ae("Initializing WebCodecs...");const Pt={aborted:!1};u.current=Pt,xt();const oi=a.current;oi.width=at,oi.height=mt;const Nn=new Map,ft=new Map,$t=[],In=(re,Mt)=>new Promise(Ft=>{const vt=new Image;vt.crossOrigin="anonymous",vt.onload=()=>{Nn.set(re,vt),Ft()},vt.onerror=()=>Ft(),vt.src=Mt}),ni=(re,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(re,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(re=>{re.type==="video"?$t.push(ni(re.id,re.url)):re.type!=="audio"&&$t.push(In(re.id,re.url))}),Be.coverUrl&&(Be.backgroundType==="video"?$t.push(ni("background",Be.coverUrl)):$t.push(In("cover",Be.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(K){const re=[];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)}re.push({audioFile:Lt.audioFile,lyrics:un,metadata:Lt.metadata})}const Mt=await BB(re,{canvas:oi,visualSlides:w,imageMap:Nn,videoMap:ft,preset:Ee,customFontName:lt,renderConfig:M,resolution:tt,aspectRatio:Le,fps:Ne,quality:rt,onProgress:(Lt,un)=>{xe(Lt),ae(un)},onLog:Lt=>console.log(Lt),abortSignal:Pt}),Ft=`Playlist_${re.length}_Songs_${Le.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 re=await OB({canvas:oi,audioFile:Ie,lyrics:dt,metadata:Be,visualSlides:w,imageMap:Nn,videoMap:ft,preset:Ee,customFontName:lt,renderConfig:M,resolution:tt,aspectRatio:Le,fps:Ne,quality:rt,onProgress:(on,Lt)=>{xe(on),ae(Lt)},abortSignal:Pt,isFirstSong:!0,isLastSong:!0}),Mt=`${Be.title||"video"}_${Le.replace(":","-")}_webcodecs.${re.format}`,Ft=URL.createObjectURL(re.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(re.duration)}s)`)}}catch(re){re.message!=="Render aborted"&&(console.error("WebCodecs render failed:",re),t.error(`Render failed: ${re.message}`))}finally{N(!1),ae("")}},Ji=async()=>{F==="ffmpeg"?await Ci():F==="webcodecs"?await vn():await zt()};Re.useEffect(()=>{h.current=Ji});const xo=Re.useCallback(()=>{u.current&&(u.current.aborted=!0),c.current&&c.current.state==="recording"?c.current.stop():N(!1),xt()},[xt]),Di=Re.useCallback(()=>{if(r.current){const K=n.current?.currentTime||0;if(Mi===-1&&K<2){r.current.scrollTo({top:0,behavior:"smooth"});return}if(Mi!==-1){const Ie=r.current.querySelector('[data-lyric-active="true"]');if(Ie){const dt=r.current;if(Ie.offsetHeight===0)return;const Be=Ie.offsetTop,at=Ie.offsetHeight,mt=dt.clientHeight;let wt=.5;M.contentPosition==="top"&&(wt=.25),M.contentPosition==="bottom"&&(wt=.75);const Ht=Be-mt*wt+at/2;dt.scrollTo({top:Ht,behavior:"smooth"})}}}},[Mi,Ee,M.contentPosition,M.marginTopScale,M.marginBottomScale]);Re.useEffect(()=>{Di()},[Di]),Re.useEffect(()=>{const K=setTimeout(()=>{Di()},550);return()=>clearTimeout(K)},[$,Fe,ti,Si,ve,_t,Di]);const hi=Re.useRef(null),Rn=Re.useCallback(()=>{if(be(!1),hi.current&&clearTimeout(hi.current),!we){const K=window.setTimeout(()=>{be(!0)},3e3);hi.current=K}},[we]),io=()=>{Rn()},qi=Re.useRef(0),pi=K=>{Rn();const Ie=Date.now();if(Ie-qi.current<300){if(K.target.closest(".no-minimal-mode-toggle"))return;qt(K)}qi.current=Ie};Re.useEffect(()=>{const K=Ie=>{const dt=Ie.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(),!(Ie.target instanceof HTMLInputElement||Ie.target instanceof HTMLTextAreaElement)){if(we){dt==="escape"&&xo();return}switch(Ie.key.toLowerCase()){case" ":case"k":Ie.preventDefault(),yt(),t.success(W?"Paused":"Playing",{id:"play-pause"});break;case"s":Ie.preventDefault(),xt(),t.success("Stopped",{id:"stop"});break;case"n":Ie.preventDefault(),ge(),t.success("Next Song",{id:"next-song"});break;case"o":Ie.preventDefault();const at=!fn;fi(at),at&&oe(!0),t.success(`Minimal Mode: ${at?"On":"Off"}`,{id:"minimal-mode"});break;case"b":Ie.preventDefault(),pt(),t.success("Previous Song",{id:"prev-song"});break;case"r":Ie.preventDefault(),Tt();const mt=V==="off"?"one":V==="one"?"all":V==="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":Ie.preventDefault();const Ht=!_t;Jt(Ht),Ht&&ie(lo.PLAYER);break;case"h":Ie.preventDefault();const Pt=!Fe;oe(Pt),t.success(Pt?"HUD: Always Visible":"HUD: Auto-Hide",{id:"hud-mode"});break;case"y":Ie.preventDefault(),Xe(sn=>!sn);break;case"g":Ie.preventDefault();const oi=F0.flatMap(sn=>sn.options.map(Ui=>Ui.value)),Nn=fe.current.lyricDisplayMode,$t=(oi.indexOf(Nn)+1)%oi.length,In=oi[$t];J(sn=>({...sn,lyricDisplayMode:In})),t.success(`Lyric Mode: ${In.replace("-"," ")}`,{id:"lyric-mode"});break;case"c":Ie.preventDefault();const ni=pE,re=fe.current.textCase,Ft=(ni.indexOf(re)+1)%ni.length,vt=ni[Ft];J(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":Ie.preventDefault(),me(sn=>!sn);break;case"t":_t?(Jt(!1),ie(lo.EDITOR)):ie(sn=>sn===lo.PLAYER?lo.EDITOR:lo.PLAYER);break;case"m":Ie.preventDefault();const on=!$e;X(on),t.success(on?"Muted":"Unmuted",{id:"mute"});break;case"x":Ie.preventDefault();const Lt=fe.current.highlightEffect==="none";J(sn=>({...sn,highlightEffect:sn.highlightEffect==="none"?"karaoke":"none"})),t.success(`Highlight: ${Lt?"On (Karaoke)":"Off"}`,{id:"highlight-toggle"});break;case"z":Ie.preventDefault();const un=P0.flatMap(sn=>sn.options.map(Ui=>Ui.value)),Vn=fe.current.highlightEffect||"none",jn=un.indexOf(Vn),_i=((jn===-1?0:jn)+1)%un.length,yo=un[_i],fo=Uf(yo);J(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":Ie.preventDefault();const Ye=(km.indexOf(Ee)+1)%km.length,si=km[Ye];Oe(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"};J(Ui=>({...Ui,...sn,...Qt}))}let bi=si;for(const sn of ev){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(Ie.preventDefault(),n.current){const sn=Math.max(0,n.current.currentTime-5);n.current.currentTime=sn,P(sn)}break;case"arrowright":if(Ie.preventDefault(),n.current){const sn=Math.min(Q,n.current.currentTime+5);n.current.currentTime=sn,P(sn)}break;case"arrowup":Ie.preventDefault(),r.current&&r.current.scrollBy({top:-100,behavior:"smooth"});break;case"arrowdown":Ie.preventDefault(),r.current&&r.current.scrollBy({top:100,behavior:"smooth"});break;case"+":case"=":Ie.preventDefault();const ms=fe.current.fontSizeScale,Ns=Math.min(ms+.1,3);J(sn=>({...sn,fontSizeScale:Ns})),t.success(`Font Size: ${(Ns*100).toFixed(0)}%`,{id:"font-size"});break;case"-":Ie.preventDefault();const Ko=fe.current.fontSizeScale,qs=Math.max(Ko-.1,.1);J(sn=>({...sn,fontSizeScale:qs})),t.success(`Font Size: ${(qs*100).toFixed(0)}%`,{id:"font-size"});break;case"e":(Ie.ctrlKey||Ie.metaKey)&&Ie.shiftKey&&(Ie.preventDefault(),h.current());break}}};return window.addEventListener("keydown",K),()=>window.removeEventListener("keydown",K)},[W,V,ve,we,Rn,xo,_t,ge,pt,t,fn,Ee,Fe,$e]),Re.useEffect(()=>{let K,Ie=0;const dt=1e3/30,Be=at=>{if(n.current&&!n.current.paused&&W){K=requestAnimationFrame(Be);const mt=at-Ie;mt>dt&&(Ie=at-mt%dt,P(n.current.currentTime))}};return W&&!we&&(K=requestAnimationFrame(Be)),()=>{K&&cancelAnimationFrame(K)}},[W,we]);const yi=ti&&(!$||Fe)&&!we,Lo=Si&&(!$||Fe)&&!we&&!fn,Ki=Rt.length>0?Rt[0]:null;Ki?`${Ki.url}`:S.coverUrl&&`${S.coverUrl}`;const Li=Re.useRef(null);return Re.useEffect(()=>{if(Rt.forEach(K=>{const Ie=K.layer||0;if(M.layerVisibility?.visual?.[Ie]!==!1&&K.type==="video"){const dt=document.getElementById(`video-preview-${K.id}`);if(dt)if(we)dt.paused||dt.pause();else{const Be=K.playbackRate||1;let at=(k-K.startTime)*Be+(K.mediaStartOffset||0);const mt=K.mediaDuration||dt.duration;mt&&mt>0&&at>=mt&&(at=at%mt),Math.abs(dt.playbackRate-Be)>.01&&(dt.playbackRate=Be),Math.abs(dt.currentTime-at)>.2&&(dt.currentTime=at);const wt=K.isMuted!==!1;dt.muted!==wt&&(dt.muted=wt);const Ht=K.volume!==void 0?K.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 K=Li.current;if(we)K.paused||K.pause();else{const Ie=K.duration||1,dt=k%Ie;Math.abs(K.currentTime-dt)>.1&&(K.currentTime=dt),W&&K.paused?K.play().catch(()=>{}):!W&&!K.paused&&K.pause()}}tn.forEach(K=>{const Ie=document.getElementById(`audio-preview-${K.id}`);if(Ie){const dt=K.playbackRate||1,Be=(k-K.startTime)*dt+(K.mediaStartOffset||0);Math.abs(Ie.playbackRate-dt)>.01&&(Ie.playbackRate=dt),Math.abs(Ie.currentTime-Be)>.2&&(Ie.currentTime=Be);const at=K.isMuted===!0;Ie.muted!==at&&(Ie.muted=at);const mt=K.volume!==void 0?K.volume:1;Math.abs(Ie.volume-mt)>.01&&(Ie.volume=mt),W&&Ie.paused?Ie.play().catch(()=>{}):!W&&!Ie.paused&&Ie.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 ${$&&!Fe?"cursor-none":""}`,children:[p.jsx("audio",{ref:n,src:d||void 0,loop:V==="one",muted:$e,onTimeUpdate:kt,onLoadedMetadata:hn,onEnded:()=>{if(we)return;const K=et.length>0;V==="one"||(V==="all_repeat"?K?ge():n.current?.play():V==="all"&&K&&Kep.jsx("audio",{id:`audio-preview-${K.id}`,src:K.url,className:"hidden",playsInline:!0},K.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 K=M.backgroundColor||"#312e81",Ie=parseInt(K.slice(1,3),16),dt=parseInt(K.slice(3,5),16),Be=parseInt(K.slice(5,7),16),at=`${Ie},${dt},${Be}`,mt=`${Math.floor(Ie*.6)},${Math.floor(dt*.6)},${Math.floor(Be*.6)}`;return`linear-gradient(to bottom right, rgb(${at}), 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 ${Ae?"opacity-60":"opacity-0"}`,muted:!0,loop:!we,playsInline:!0,preload:"auto",onLoadedData:()=>Qe(!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 K=M.backgroundColor||"#312e81",Ie=parseInt(K.slice(1,3),16),dt=parseInt(K.slice(3,5),16),Be=parseInt(K.slice(5,7),16),at=`${Ie},${dt},${Be}`,mt=`${Math.floor(Ie*.6)},${Math.floor(dt*.6)},${Math.floor(Be*.6)}`;return`linear-gradient(to bottom right, rgb(${at}), 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"&&!we&&p.jsx(gO,{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(K=>{const Ie=K.layer||0;if(M.layerVisibility?.visual?.[Ie]===!1)return null;const dt=M.visualTransitionType||"none",Be=M.visualTransitionDuration||1;let at=1;if(dt!=="none"){if(k=K.endTime){let mt=!1;if(dt==="crossfade"&&(mt=w.some(wt=>wt.id!==K.id&&(wt.layer||0)===(K.layer||0)&&wt.startTime>=K.endTime-.1&&wt.startTimeK.endTime-Be){const mt=(K.endTime-k)/Be;at=Math.min(at,Math.max(0,Math.min(1,mt)))}}return p.jsx("div",{className:"absolute inset-0 flex items-center justify-center overflow-hidden",style:{opacity:at},children:K.type==="video"?p.jsx("video",{id:`video-preview-${K.id}`,src:K.url,className:"w-full h-full object-cover",muted:K.isMuted!==!1,playsInline:!0}):p.jsx("div",{className:"w-full h-full bg-cover bg-center",style:{backgroundImage:`url(${K.url})`}})},K.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"}),!we&&p.jsx(QU,{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 K=M.channelInfoText.trim();return//i.test(K)?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:K}}):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:K=>K.currentTarget.play(),onMouseOut:K=>K.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:K=>K.currentTarget.play(),onMouseOut:K=>K.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/f72cc364-2af0-4d42-9e52-28ba3dff297c?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(!Fe),className:`p-2 rounded-full transition-colors ${Fe?"bg-purple-600/50 text-white":"bg-black/30 text-zinc-300 hover:bg-white/10"}`,title:"Bypass Auto-hide (H)",children:Fe?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(vb,{size:20})}),p.jsx("button",{onClick:()=>{const K=!_t;Jt(K),K&&ie(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),ie(ve===lo.PLAYER?lo.EDITOR:lo.PLAYER)},className:`p-2 rounded-full transition-colors ${ve===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(vT,{size:20})}),p.jsx("button",{onMouseDown:K=>{K.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:K=>{K.stopPropagation(),Xe(!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:nt?p.jsx(vb,{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)&&Ee!=="subtitle"?"linear-gradient(to bottom, transparent, black 10%, black 90%, transparent)":"none","--fs-scale":M.fontSizeScale||1,"--l-height":M.lyricLineHeight||1.2},children:[p.jsx("div",{className:`transition-all duration-500 ${M.contentPosition==="center"?ve===lo.EDITOR||_t?"h-[25vh]":!yi&&!Lo?"h-[50vh]":"h-[40vh]":"h-0"}`}),En.map((K,Ie)=>{const dt=Ie===Mi,Be=ve===lo.EDITOR||_t,at=["9:16","3:4","1:1","1:2","2:3"].includes(Le);if(M.lyricDisplayMode!=="all"){if(M.lyricDisplayMode==="active-only"&&Ie!==Mi)return p.jsx("p",{className:"hidden"},Ie);if(M.lyricDisplayMode==="next-only"&&(IeMi+1))return p.jsx("p",{className:"hidden"},Ie);if(M.lyricDisplayMode==="previous-next"&&Math.abs(Ie-Mi)>1)return p.jsx("p",{className:"hidden"},Ie)}else if(Ee==="none"||Ee==="just_video")return p.jsx("p",{className:"hidden"},Ie);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"))),Ee==="large"||Ee==="large_upper"){const Ft=at?Be?"text-4xl":"text-6xl":Be?"text-6xl":"text-8xl",vt=at?Be?"text-xl":"text-2xl":Be?"text-2xl":"text-3xl";mt=`${Ft} font-black text-white ${Ee==="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(Ee==="big_center"){const re=at?Be?"text-4xl":"text-5xl":Be?"text-6xl":"text-8xl",Mt=at?Be?"text-xl":"text-2xl":Be?"text-2xl":"text-3xl";mt=`${re} font-black text-white uppercase tracking-tight text-center`,wt=`${Mt} text-zinc-600/40 hover:text-zinc-400 text-center`}else if(Ee==="testing_up"){const re=at?Be?"text-4xl":"text-5xl":Be?"text-6xl":"text-8xl",Mt=at?Be?"text-xl":"text-2xl":Be?"text-2xl":"text-3xl";mt=`${re} text-white uppercase tracking-tight text-center`,wt=`${Mt} text-zinc-600/40 hover:text-zinc-400 text-center`}else if(Ee==="testing"){const re=at?Be?"text-4xl":"text-5xl":Be?"text-6xl":"text-8xl",Mt=at?Be?"text-xl":"text-2xl":Be?"text-2xl":"text-3xl";mt=`${re} text-white tracking-tight text-center`,wt=`${Mt} text-zinc-600/40 hover:text-zinc-400 text-center`}else if(Ee==="one_line_up"){const re=at?Be?"text-4xl":"text-5xl":Be?"text-6xl":"text-8xl",Mt=at?Be?"text-xl":"text-2xl":Be?"text-2xl":"text-3xl";mt=`${re} text-white uppercase tracking-tight text-center`,wt=`${Mt} text-zinc-600/40 hover:text-zinc-400 text-center`}else if(Ee==="one_line"){const re=at?Be?"text-4xl":"text-5xl":Be?"text-6xl":"text-8xl",Mt=at?Be?"text-xl":"text-2xl":Be?"text-2xl":"text-3xl";mt=`${re} text-white tracking-tight text-center`,wt=`${Mt} text-zinc-600/40 hover:text-zinc-400 text-center`}else if(Ee==="metal"){const re=at?Be?"text-4xl":"text-5xl":Be?"text-6xl":"text-8xl",Mt=at?Be?"text-xl":"text-2xl":Be?"text-2xl":"text-3xl";mt=`${re} 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(Ee==="kids"){const re=at?Be?"text-4xl":"text-5xl":Be?"text-6xl":"text-8xl",Mt=at?Be?"text-xl":"text-2xl":Be?"text-2xl":"text-3xl";mt=`${re} 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(Ee==="sad"){const re=at?Be?"text-4xl":"text-5xl":Be?"text-6xl":"text-7xl",Mt=at?Be?"text-lg":"text-xl":Be?"text-xl":"text-2xl";mt=`${re} text-zinc-200 tracking-wider text-center drop-shadow-md`,wt=`${Mt} text-zinc-600/60 hover:text-zinc-400 text-center`}else if(Ee==="romantic"){const re=at?Be?"text-4xl":"text-5xl":Be?"text-6xl":"text-7xl",Mt=at?Be?"text-lg":"text-xl":Be?"text-xl":"text-2xl";mt=`${re} 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(Ee==="tech"){const re=at?Be?"text-4xl":"text-5xl":Be?"text-6xl":"text-8xl",Mt=at?Be?"text-xl":"text-2xl":Be?"text-2xl":"text-3xl";mt=`${re} 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(Ee==="gothic"){const re=at?Be?"text-4xl":"text-5xl":Be?"text-6xl":"text-7xl",Mt=at?Be?"text-xl":"text-2xl":Be?"text-2xl":"text-3xl";mt=`${re} 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(Ee==="monospace"){const re=at?Be?"text-2xl":"text-3xl":Be?"text-3xl":"text-5xl",Mt=at?Be?"text-lg":"text-xl":Be?"text-xl":"text-2xl";mt=`${re} 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(Ee==="classic"){const re=at?Be?"text-2xl":"text-3xl":Be?"text-3xl":"text-6xl",Mt=at?Be?"text-lg":"text-xl":Be?"text-xl":"text-2xl";mt=`${re} 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(Ee==="slideshow"||Ee==="just_video")mt=`${at?Be?"text-2xl":"text-3xl":Be?"text-3xl":"text-4xl"} text-white tracking-wide text-center`,wt="hidden";else if(Ee==="subtitle"){mt=`${at?Be?"text-2xl":"text-3xl":Be?"text-3xl":"text-4xl"} text-white tracking-wide text-center whitespace-pre-wrap`,wt="hidden";let Mt="bottom-16";Be&&Lo?Mt="bottom-[560px]":Be?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(Ee==="custom"){const re=at?Be?"text-4xl":"text-5xl":Be?"text-6xl":"text-8xl",Mt=at?Be?"text-xl":"text-2xl":Be?"text-2xl":"text-3xl",Ft=M.textAlign==="center"?"text-center":M.textAlign==="right"?"text-right":"text-left";mt=`${re} tracking-tight ${Ft}`,wt=`${Mt} opacity-40 hover:opacity-100 ${Ft}`}else{const re=at?Be?"text-2xl":"text-3xl":Be?"text-3xl":"text-5xl",Mt=at?Be?"text-lg":"text-xl":Be?"text-xl":"text-2xl";mt=`${re} 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((Ee==="custom"||Ee==="default")&&dt&&M.textEffect!=="none"){const re=M.textEffect;re==="glow"?ft.textShadow=`0 0 10px ${M.fontColor}, 0 0 20px ${M.fontColor}`:re==="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}`:re==="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":re==="shadow"?ft.textShadow="3px 3px 6px rgba(0,0,0,0.7)":re==="outline"?ft.textShadow="-1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000":re==="3d"?ft.textShadow="1px 1px 0px #ccc, 2px 2px 0px #bbb, 3px 3px 0px #aaa, 4px 4px 0px rgba(0,0,0,0.5)":re==="emboss"?(ft.color="#ebebeb",ft.textShadow="1px 2px 3px rgba(255,255,255,0.8), -1px -2px 3px rgba(0,0,0,0.8)"):re==="gold"?(ft.background="linear-gradient(to bottom, #d4af37, #C5A028)",ft.WebkitBackgroundClip="text",ft.color="transparent"):re==="chrome"?(ft.background="linear-gradient(to bottom, #ebebeb 50%, #616161 50%, #ebebeb)",ft.WebkitBackgroundClip="text",ft.color="transparent"):re==="fire"?(ft.color="#fff",ft.textShadow="0 -5px 4px #FFC107, 2px -10px 6px #FF9800, -2px -15px 11px #FF5722, 2px -25px 18px #795548"):re==="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"):re==="vhs"?ft.textShadow="2px 0 0 rgba(255,0,0,0.7), -2px 0 0 rgba(0,0,255,0.7)":re==="gradient"?(ft.background=`linear-gradient(to right, ${M.fontColor}, #ffffff)`,ft.WebkitBackgroundClip="text",ft.color="transparent"):re==="rainbow"?(ft.background="linear-gradient(to left, violet, indigo, blue, green, yellow, orange, red)",ft.WebkitBackgroundClip="text",ft.color="transparent"):re==="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"):re==="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)"):re==="retro"?(ft.fontFamily="'Press Start 2P', cursive",ft.color="#ff00ff",ft.textShadow="4px 4px 0px #00ffff"):re==="cyberpunk"?(ft.color="#fcee0a",ft.textShadow="2px 2px 0px #000, -1px -1px 0 #05d9e8",ft.fontFamily="'Orbitron', sans-serif",ft.letterSpacing="1px"):re==="glitch-text"?(ft.animation="anim-glitch 0.4s infinite linear",ft.position="relative"):re==="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"):re==="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=K.text;const In=M.textCase;In==="upper"?$t=$t.toUpperCase():In==="lower"?$t=$t.toLowerCase():In==="title"?$t=$t.replace(/\w\S*/g,re=>re.charAt(0).toUpperCase()+re.substr(1).toLowerCase()):In==="sentence"?$t=$t.charAt(0).toUpperCase()+$t.slice(1).toLowerCase():In==="invert"&&($t=$t.replace(/\w\S*/g,re=>re.charAt(0).toLowerCase()+re.slice(1).toUpperCase())),$t=$t.replace(/\s*([-‐‑‒–—―])\s*/g,"$1"),dt&&M.textAnimation==="typewriter"&&($t=$t.substring(0,Math.max(0,Math.floor((k-K.time)*35))));let ni=$t;if(dt&&M.highlightEffect!=="none"){const re=M.highlightEffect,Mt=K.words&&K.words.length>0;if((re==="karaoke"||re?.startsWith("karaoke-"))&&Mt)ni=K.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"};if(M.textDecoration&&M.textDecoration!=="none"&&(Ye.textDecoration=M.textDecoration),!jn&&!js)re==="karaoke-smooth-white"?(Ye.opacity=1,Ye.color="#ffffff"):Ye.opacity=.5,Ye.transform="scale(1)";else if(js)if(re==="karaoke-fill"){const Qt=M.highlightBackground||"#fb923c";Ye.backgroundColor=Qt,Ye.color="#000",Ye.padding="2px 6px",Ye.borderRadius="4px",Ye.opacity=1}else re==="karaoke-smooth"||re==="karaoke-smooth-white"?(Ye.color=M.highlightColor||"#fb923c",Ye.opacity=1):(Ee==="custom"&&(Ye.color=M.fontColor),Ye.opacity=1);if(jn){const Qt=M.highlightColor||"#fb923c",bi=M.highlightBackground||"#fb923c";if(re==="karaoke-smooth"||re==="karaoke-smooth-white"){const ms=Ft.endTime-Ft.startTime,Ns=k-un,Ko=Math.min(100,Math.max(0,Ns/ms*100)),qs=re==="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 re==="karaoke"||re==="color"?(Ye.color=Qt,Ye.textShadow=`0 0 10px ${Qt}`):re==="karaoke-neon"?(Ye.color="#fff",Ye.textShadow=`0 0 5px #fff, 0 0 10px #fff, 0 0 20px ${Qt}, 0 0 35px ${Qt}`):re==="karaoke-scale"?(Ye.color=Qt,Ye.transform="scale(1.3)"):re==="karaoke-underline"?(Ye.color=Qt,Ye.textDecoration=(Ye.textDecoration||"")+" underline",Ye.textDecorationColor=Qt,Ye.textUnderlineOffset="4px"):re==="karaoke-bounce"?(Ye.color=Qt,Ye.transform="translateY(-10px)"):re==="karaoke-fill"?(Ye.backgroundColor=bi,Ye.color="#000",Ye.padding="2px 6px",Ye.borderRadius="4px"):re==="karaoke-outline"?(Ye.color="transparent",Ye.WebkitTextStroke=`2px ${Qt}`):re==="karaoke-shadow"?(Ye.color=Qt,Ye.textShadow="3px 3px 0 #000, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000"):re==="karaoke-gradient"?(Ye.background=`linear-gradient(90deg, ${Qt}, ${bi})`,Ye.WebkitBackgroundClip="text",Ye.WebkitTextFillColor="transparent"):re==="karaoke-wave"?(Ye.color=Qt,Ye.animation="bounce 0.3s ease infinite"):re==="karaoke-pill"?(Ye.backgroundColor=bi,Ye.color="#000",Ye.padding="4px 16px",Ye.borderRadius="9999px"):re==="karaoke-box"?(Ye.backgroundColor=bi,Ye.color="#000",Ye.padding="4px 8px",Ye.borderRadius="0"):re==="karaoke-rounded"?(Ye.backgroundColor=bi,Ye.color="#000",Ye.padding="4px 12px",Ye.padding="4px 12px",Ye.borderRadius="12px"):re==="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)"):re==="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"):re==="karaoke-soft-glow"?(Ye.color=Qt,Ye.textShadow=`0 0 5px ${Qt}, 0 0 15px ${Qt}, 0 0 30px ${Qt}`):re==="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)":re==="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)"):re==="karaoke-chrome"?(Ye.background="linear-gradient(to bottom, #ebebeb 50%, #616161 50%, #ebebeb)",Ye.WebkitBackgroundClip="text",Ye.color="transparent"):re==="karaoke-gold"?(Ye.background="linear-gradient(to bottom, #d4af37, #C5A028)",Ye.WebkitBackgroundClip="text",Ye.color="transparent"):re==="karaoke-fire"?(Ye.color="#fff",Ye.textShadow="0 -5px 4px #FFC107, 2px -10px 6px #FF9800, -2px -15px 11px #FF5722, 2px -25px 18px #795548"):re==="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"):re==="karaoke-rainbow"?(Ye.background="linear-gradient(to left, violet, indigo, blue, green, yellow, orange, red)",Ye.WebkitBackgroundClip="text",Ye.color="transparent"):re==="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)"):re==="karaoke-vhs"?Ye.textShadow="2px 0 0 rgba(255,0,0,0.7), -2px 0 0 rgba(0,0,255,0.7)":re==="karaoke-retro"?(Ye.fontFamily="'Press Start 2P', cursive",Ye.color="#ff00ff",Ye.textShadow="4px 4px 0px #00ffff"):re==="karaoke-cyberpunk"?(Ye.color="#fcee0a",Ye.textShadow="2px 2px 0px #000, -1px -1px 0 #05d9e8",Ye.fontFamily="'Orbitron', sans-serif"):re==="karaoke-hologram"?(Ye.color="rgba(0, 255, 255, 0.7)",Ye.textShadow="0 0 5px rgba(0,255,255,0.5)"):re==="karaoke-comic"?(Ye.fontFamily="'Bangers', cursive",Ye.color="#ffcc00",Ye.textShadow="2px 2px 0px #000, -1px -1px 0 #000"):re==="karaoke-glitch-text"?Ye.animation="anim-glitch 0.4s infinite linear":re==="karaoke-pulse"?Ye.animation="anim-pulse 1s infinite ease-in-out":re==="karaoke-breathe"?Ye.animation="anim-breathe 2s infinite ease-in-out":re==="karaoke-float"?Ye.animation="anim-float 2s infinite ease-in-out":re==="karaoke-sway"?Ye.animation="anim-sway 2s infinite ease-in-out":re==="karaoke-flicker"?Ye.animation="anim-flicker 2s infinite linear":re==="karaoke-shake"?Ye.animation="anim-shake 0.2s infinite linear":re==="karaoke-wobble"?Ye.animation="anim-wobble 1s infinite ease-in-out":re==="karaoke-jello"?Ye.animation="anim-jello 1s infinite":re==="karaoke-rubberband"?Ye.animation="anim-rubberband 1s infinite":re==="karaoke-heartbeat"?Ye.animation="anim-heartbeat 1.3s infinite ease-in-out":re==="karaoke-flash"?Ye.animation="anim-flash 1s infinite":re==="karaoke-tada"?Ye.animation="anim-tada 1s infinite":re==="karaoke-swing"?Ye.animation="anim-swing 2s infinite":re==="karaoke-rotate"?Ye.animation="anim-rotate 4s infinite linear":re==="karaoke-spin"?Ye.animation="anim-rotate 1s infinite linear":re==="karaoke-glitch"?Ye.animation="anim-glitch 0.3s infinite linear":re==="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"):re==="karaoke-fade"?Ye.animation="trans-fade-in 0.4s cubic-bezier(0.4, 0, 0.2, 1) forwards":re==="karaoke-slide"?Ye.animation="trans-slide-in 0.4s cubic-bezier(0.16, 1, 0.3, 1) forwards":re==="karaoke-drop"?Ye.animation="trans-drop-in 0.5s cubic-bezier(0.34, 1.56, 0.64, 1) forwards":re==="karaoke-lightspeed"?Ye.animation="trans-lightspeed-in 0.5s ease-out forwards":re==="karaoke-roll"?Ye.animation="trans-roll-in 0.5s ease-out forwards":re==="karaoke-zoom"?Ye.animation="trans-zoom-in 0.4s cubic-bezier(0.34, 1.56, 0.64, 1) forwards":re==="karaoke-elastic"?Ye.animation="trans-elastic-in 0.7s ease-out forwards":re==="karaoke-scale-rotate"?Ye.animation="trans-scale-rotate-in 0.5s ease-out forwards":re==="karaoke-flip"?Ye.animation="trans-flip-in 0.5s ease-out forwards":re==="karaoke-rotate-in"?Ye.animation="trans-rotate-in 0.5s ease-out forwards":re==="karaoke-spiral"?Ye.animation="trans-spiral-in 0.6s ease-out forwards":re==="karaoke-blur"?Ye.animation="trans-blur-in 0.4s ease-out forwards":re==="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(re||"")&&(Ye.color=Qt,Ye.textShadow=`0 0 10px ${Qt}`,re?.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(Vg.Fragment,{children:[si," "]},vt):si});else if(re==="karaoke"||re?.startsWith("karaoke-")){const Ft=M.highlightColor||"#fb923c",vt=M.highlightBackground||"#fb923c";ft.color=Ft,re==="karaoke-neon"&&(ft.textShadow=`0 0 10px ${Ft}, 0 0 20px ${Ft}`),re==="karaoke-scale"&&(ft.transform=(ft.transform||"")+" scale(1.1)"),re==="karaoke-underline"&&(ft.textDecoration="underline"),re==="karaoke-bounce"&&(ft.transform=(ft.transform||"")+" translateY(-5px)"),re==="karaoke-fill"&&(ft.backgroundColor=vt,ft.color="#000",ft.padding="4px 12px",ft.borderRadius="6px"),re==="karaoke-outline"&&(ft.color="transparent",ft.WebkitTextStroke=`2px ${Ft}`),re==="karaoke-shadow"&&(ft.textShadow="3px 3px 0 #000, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000"),re==="karaoke-gradient"&&(ft.background=`linear-gradient(90deg, ${Ft}, ${vt})`,ft.WebkitBackgroundClip="text",ft.WebkitTextFillColor="transparent"),["karaoke-pill","karaoke-box","karaoke-rounded"].includes(re)&&(ft.backgroundColor=vt,ft.color="#000",ft.padding="4px 16px",ft.borderRadius=re==="karaoke-pill"?"9999px":re==="karaoke-rounded"?"12px":"0"),re?.includes("glow")&&(ft.textShadow=`0 0 10px ${Ft}, 0 0 20px ${Ft}`)}else re==="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(K.text),t.success("Lyric copied to clipboard",1500)),n.current&&!we&&(n.current.currentTime=K.time,P(K.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})})},Ie)}),p.jsx("div",{className:`transition-all duration-500 ${M.contentPosition==="center"?ve===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&&Ee!=="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:de,className:"flex-1 h-1 bg-zinc-700/50 rounded-full relative cursor-pointer group-hover:h-2 transition-all touch-none",onPointerDown:K=>{K.currentTarget.setPointerCapture(K.pointerId),Xn(K.clientX)},onPointerMove:K=>{K.buttons===1&&Xn(K.clientX)},children:[p.jsx("div",{className:"absolute top-0 left-0 h-full bg-purple-500 rounded-full pointer-events-none",style:{width:`${k/Q*100}%`}}),p.jsx("input",{type:"range",name:"progress",id:"progress-bar","aria-label":"Seek Progress",min:"0",max:Q||0,value:k,onChange:pn,disabled:we,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(Q)}),p.jsxs("div",{className:"flex items-center gap-2 pl-4",children:[p.jsx("button",{onClick:()=>X(!$e),className:"text-zinc-400 hover:text-white",children:$e||se===0?p.jsx(jl,{size:16}):p.jsx(Zr,{size:16})}),p.jsxs("div",{ref:ke,className:"w-16 h-1 bg-zinc-700/50 rounded-full relative overflow-hidden group/vol cursor-pointer touch-none",onPointerDown:K=>{K.currentTarget.setPointerCapture(K.pointerId),Wt(K.clientX)},onPointerMove:K=>{K.buttons===1&&Wt(K.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:`${$e?0:se*100}%`}}),p.jsx("input",{type:"range",name:"volume",id:"volume-control","aria-label":"Volume Control",min:"0",max:"1",step:"0.05",value:$e?0:se,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:we})]}),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:we})]}),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:we,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(K=>parseFloat((K+.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:we,children:p.jsx(y0,{size:12})}),p.jsx("button",{onClick:()=>D(K=>parseFloat((K-.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:we,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 ${lt?"text-purple-400":"text-zinc-400 hover:text-white"}`,title:lt?`Custom Font: ${lt}`:"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:we})]}),lt&&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:we,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:()=>J(K=>({...K,fontSizeScale:Math.min(K.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:we,children:p.jsx(y0,{size:12})}),p.jsx("button",{onClick:()=>J(K=>({...K,fontSizeScale:Math.max(K.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:we,children:p.jsx(zu,{size:12})})]})]}),p.jsxs("div",{className:"relative group",children:[p.jsxs("select",{value:Ee,onChange:K=>{const Ie=K.target.value;Oe(Ie);const dt=oh[Ie];if(dt){const Be={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"};J(at=>({...at,...Be,...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:we,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:we,children:p.jsx(S0,{size:20,fill:"currentColor"})}),p.jsx("button",{className:"text-zinc-400 hover:text-white transition-colors disabled:opacity-50",disabled:we||et.length===0,onClick:pt,title:"Previous Song",children:p.jsx(kA,{size:24})}),p.jsx("button",{className:"text-zinc-400 hover:text-white transition-colors disabled:opacity-50",disabled:we,onClick:()=>n.current&&(n.current.currentTime-=5),title:"Rewind 5s",children:p.jsx(wA,{size:20})}),p.jsx("button",{onClick:yt,disabled:we,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(xT,{size:28,fill:"currentColor"}):p.jsx(_0,{size:28,fill:"currentColor",className:"ml-1"})}),p.jsx("button",{className:"text-zinc-400 hover:text-white transition-colors disabled:opacity-50",disabled:we,onClick:()=>n.current&&(n.current.currentTime+=5),title:"Fast Forward 5s",children:p.jsx(jC,{size:20})}),p.jsx("button",{className:"text-zinc-400 hover:text-white transition-colors disabled:opacity-50",disabled:we||et.length===0,onClick:ge,title:"Next Song",children:p.jsx(PA,{size:24})}),p.jsxs("button",{className:`transition-colors disabled:opacity-50 ${V!=="off"?"text-green-400 hover:text-green-300":"text-zinc-400 hover:text-white"}`,onClick:Tt,title:`Repeat: ${V==="off"?"Off":V==="one"?"One":V==="all"?"Play All (No Repeat)":"Loop All"} (R)`,disabled:we,children:[V==="one"&&p.jsx(SA,{size:20}),V==="all_repeat"&&p.jsx(xb,{size:20}),V==="all"&&p.jsx(Jf,{size:20}),V==="off"&&p.jsx(xb,{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:()=>J(K=>({...K,backgroundBlurStrength:K.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:we,children:Je?"BLUR":"SHARP"}),p.jsx("button",{onClick:()=>J(K=>({...K,highlightEffect:K.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(K=>K==="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:we,children:tt}),p.jsx("button",{onClick:()=>st(K=>K==="16:9"?"9:16":K==="9:16"?"3:4":K==="3:4"?"1:1":K==="1:1"?"1:2":K==="1:2"?"2:1":K==="2:1"?"2:3":K==="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:we,children:Le})]}),p.jsxs("div",{className:"relative group",children:[p.jsxs("select",{value:F,onChange:K=>ce(K.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:we,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:rt,onChange:K=>it(K.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:we,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:we||!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(kU,{playlist:et,setPlaylist:Se,currentTrackIndex:Ke,setCurrentTrackIndex:Ve,onPlayTrack:He,isPlaying:W,onTogglePlay:yt,currentTime:k,onSeek:K=>{n.current&&!we&&(n.current.currentTime=K,P(K))},onClearPlaylist:()=>{xt(),g(null),E([]),Ve(-1),T({title:"No Audio Loaded",artist:"Select a file",coverUrl:null,backgroundType:"image"})},onRemoveTrack:K=>{K===Ke?(xt(),g(null),E([]),Ve(-1),T({title:"No Audio Loaded",artist:"Select a file",coverUrl:null,backgroundType:"image"})):KIe-1),Se(Ie=>{const dt=[...Ie];return dt.splice(K,1),dt})},onClose:()=>Jt(!1)})}):ve===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(xR,{slides:w,setSlides:I,currentTime:k,duration:Q||60,lyrics:A,onSeek:K=>{n.current&&!we&&(n.current.currentTime=K,P(K))},onClose:()=>ie(lo.PLAYER),renderConfig:M,setRenderConfig:J})})]}),we&&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"," (",Le," ",tt,")"]}),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(S0,{size:16,fill:"currentColor"}),"Abort Rendering"]})]}),Y&&p.jsx(GU,{config:M,setConfig:J,preset:Ee,setPreset:Oe,onClose:()=>me(!1),isPlaylistMode:_t,hasPlaylist:et.length>0,onRender:Ji,customFontName:lt,onFontUpload:G,onClearCustomFont:()=>{We(null),J(K=>({...K,fontFamily:"ui-sans-serif, system-ui, sans-serif"}))},customChannelFontName:gt,onChannelFontUpload:_e,onClearChannelCustomFont:()=>{qe(null),J(K=>({...K,channelInfoFontFamily:void 0}))},customInfoFontName:q,onInfoFontUpload:Ge,onClearInfoCustomFont:()=>{C(null),J(K=>({...K,infoFontFamily:void 0}))},resolution:tt,setResolution:U,aspectRatio:Le,setAspectRatio:st,renderCodec:te,setRenderCodec:le,supportedCodecs:ht,renderQuality:rt,setRenderQuality:it,renderFps:Ne,setRenderFps:De,renderEngine:F,setRenderEngine:ce,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:()=>Xe(!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:K=>K.stopPropagation(),children:[p.jsx("button",{onClick:()=>Xe(!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 pw=document.getElementById("root");if(!pw)throw new Error("Could not find root element to mount to");const HB=hC.createRoot(pw);HB.render(p.jsx(Vg.StrictMode,{children:p.jsx(hR,{children:p.jsx(VB,{})})}));export{GB as c,pT as g};