hytopia 0.10.22-prerelease → 0.10.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/server.mjs +3 -3
package/server.mjs CHANGED
@@ -397,12 +397,12 @@ Instead, \`yield\` should either be called with a value, or not be called at all
397
397
  if (condition) { yield value; }`)};import{Buffer as Pq1}from"node:buffer";import{StringDecoder as Tq1}from"node:string_decoder";var VF=(Z,J,X)=>{if(X)return;if(Z)return{transform:Cq1.bind(void 0,new TextEncoder)};let $=new Tq1(J);return{transform:fq1.bind(void 0,$),final:kq1.bind(void 0,$)}},Cq1=function*(Z,J){if(Pq1.isBuffer(J))yield o7(J);else if(typeof J==="string")yield Z.encode(J);else yield J},fq1=function*(Z,J){yield _8(J)?Z.write(J):J},kq1=function*(Z){let J=Z.end();if(J!=="")yield J};import{callbackify as yy}from"node:util";var QM=yy(async(Z,J,X,$)=>{J.currentIterable=Z(...X);try{for await(let Y of J.currentIterable)$.push(Y)}finally{delete J.currentIterable}}),vF=async function*(Z,J,X){if(X===J.length){yield Z;return}let{transform:$=Iq1}=J[X];for await(let Y of $(Z))yield*vF(Y,J,X+1)},py=async function*(Z){for(let[J,{final:X}]of Object.entries(Z))yield*Eq1(X,Number(J),Z)},Eq1=async function*(Z,J,X){if(Z===void 0)return;for await(let $ of Z())yield*vF($,X,J+1)},iy=yy(async({currentIterable:Z},J)=>{if(Z!==void 0){await(J?Z.throw(J):Z.return());return}if(J)throw J}),Iq1=function*(Z){yield Z};var KM=(Z,J,X,$)=>{try{for(let Y of Z(...J))X.push(Y);$()}catch(Y){$(Y)}},gy=(Z,J)=>[...J.flatMap((X)=>[...N$(X,Z,0)]),...eW(Z)],N$=function*(Z,J,X){if(X===J.length){yield Z;return}let{transform:$=bq1}=J[X];for(let Y of $(Z))yield*N$(Y,J,X+1)},eW=function*(Z){for(let[J,{final:X}]of Object.entries(Z))yield*_q1(X,Number(J),Z)},_q1=function*(Z,J,X){if(Z===void 0)return;for(let $ of Z())yield*N$($,X,J+1)},bq1=function*(Z){yield Z};var WM=({value:Z,value:{transform:J,final:X,writableObjectMode:$,readableObjectMode:Y},optionName:Q},{encoding:K})=>{let W={},G=ay(Z,K,Q),z=O$(J),V=O$(X),H=z?QM.bind(void 0,vF,W):KM.bind(void 0,N$),v=z||V?QM.bind(void 0,py,W):KM.bind(void 0,eW),q=z||V?iy.bind(void 0,W):void 0;return{stream:new hq1({writableObjectMode:$,writableHighWaterMark:dy($),readableObjectMode:Y,readableHighWaterMark:dy(Y),transform(c,w,x){H([c,G,0],this,x)},flush(c){v([G],this,c)},destroy:q})}},HF=(Z,J,X,$)=>{let Y=J.filter(({type:K})=>K==="generator"),Q=$?Y.reverse():Y;for(let{value:K,optionName:W}of Q){let G=ay(K,X,W);Z=gy(G,Z)}return Z},ay=({transform:Z,final:J,binary:X,writableObjectMode:$,readableObjectMode:Y,preserveNewlines:Q},K,W)=>{let G={};return[{transform:my($,W)},VF(X,K,$),zF(X,Q,$,G),{transform:Z,final:J},{transform:uy(Y,W)},Ay({binary:X,preserveNewlines:Q,readableObjectMode:Y,state:G})].filter(Boolean)};var ny=(Z,J)=>{for(let X of Sq1(Z))Aq1(Z,X,J)},Sq1=(Z)=>new Set(Object.entries(Z).filter(([,{direction:J}])=>J==="input").map(([J])=>Number(J))),Aq1=(Z,J,X)=>{let{stdioItems:$}=Z[J],Y=$.filter(({contents:W})=>W!==void 0);if(Y.length===0)return;if(J!==0){let[{type:W,optionName:G}]=Y;throw new TypeError(`Only the \`stdin\` option, not \`${G}\`, can be ${EJ[W]} with synchronous methods.`)}let K=Y.map(({contents:W})=>W).map((W)=>mq1(W,$));X.input=gW(K)},mq1=(Z,J)=>{let X=HF(Z,J,"utf8",!0);return uq1(X),gW(X)},uq1=(Z)=>{let J=Z.find((X)=>typeof X!=="string"&&!_8(X));if(J!==void 0)throw new TypeError(`The \`stdin\` option is invalid: when passing objects as input, a transform must be used to serialize them to strings or Uint8Arrays: ${J}.`)};import{writeFileSync as iq1,appendFileSync as gq1}from"node:fs";var qF=({stdioItems:Z,encoding:J,verboseInfo:X,fdNumber:$})=>$!=="all"&&lQ(X,$)&&!E5.has(J)&&lq1($)&&(Z.some(({type:Y,value:Q})=>Y==="native"&&yq1.has(Q))||Z.every(({type:Y})=>V4.has(Y))),lq1=(Z)=>Z===1||Z===2,yq1=new Set(["pipe","overlapped"]),sy=async(Z,J,X,$)=>{for await(let Y of Z)if(!pq1(J))ry(Y,X,$)},oy=(Z,J,X)=>{for(let $ of Z)ry($,J,X)},pq1=(Z)=>Z._readableState.pipes.length>0,ry=(Z,J,X)=>{let $=Rq(Z);r9({type:"output",verboseMessage:$,fdNumber:J,verboseInfo:X})};var ty=({fileDescriptors:Z,syncResult:{output:J},options:X,isMaxBuffer:$,verboseInfo:Y})=>{if(J===null)return{output:Array.from({length:3})};let Q={},K=new Set([]);return{output:J.map((G,z)=>dq1({result:G,fileDescriptors:Z,fdNumber:z,state:Q,outputFiles:K,isMaxBuffer:$,verboseInfo:Y},X)),...Q}},dq1=({result:Z,fileDescriptors:J,fdNumber:X,state:$,outputFiles:Y,isMaxBuffer:Q,verboseInfo:K},{buffer:W,encoding:G,lines:z,stripFinalNewline:V,maxBuffer:H})=>{if(Z===null)return;let v=el(Z,Q,H),q=o7(v),{stdioItems:F,objectMode:c}=J[X],w=aq1([q],F,G,$),{serializedResult:x,finalResult:j=x}=nq1({chunks:w,objectMode:c,encoding:G,lines:z,stripFinalNewline:V,fdNumber:X});sq1({serializedResult:x,fdNumber:X,state:$,verboseInfo:K,encoding:G,stdioItems:F,objectMode:c});let B=W[X]?j:void 0;try{if($.error===void 0)oq1(x,F,Y);return B}catch(L){return $.error=L,B}},aq1=(Z,J,X,$)=>{try{return HF(Z,J,X,!1)}catch(Y){return $.error=Y,Z}},nq1=({chunks:Z,objectMode:J,encoding:X,lines:$,stripFinalNewline:Y,fdNumber:Q})=>{if(J)return{serializedResult:Z};if(X==="buffer")return{serializedResult:gW(Z)};let K=qm(Z,X);if($[Q])return{serializedResult:K,finalResult:YM(K,!Y[Q],J)};return{serializedResult:K}},sq1=({serializedResult:Z,fdNumber:J,state:X,verboseInfo:$,encoding:Y,stdioItems:Q,objectMode:K})=>{if(!qF({stdioItems:Q,encoding:Y,verboseInfo:$,fdNumber:J}))return;let W=YM(Z,!1,K);try{oy(W,J,$)}catch(G){X.error??=G}},oq1=(Z,J,X)=>{for(let{path:$,append:Y}of J.filter(({type:Q})=>WF.has(Q))){let Q=typeof $==="string"?$:$.toString();if(Y||X.has(Q))gq1($,Z);else X.add(Q),iq1($,Z)}};var ey=([,Z,J],X)=>{if(!X.all)return;if(Z===void 0)return J;if(J===void 0)return Z;if(Array.isArray(Z))return Array.isArray(J)?[...Z,...J]:[...Z,ZZ(J,X,"all")];if(Array.isArray(J))return[ZZ(Z,X,"all"),...J];if(_8(Z)&&_8(J))return qD([Z,J]);return`${Z}${J}`};import{once as GM}from"node:events";var Zp=async(Z,J)=>{let[X,$]=await rq1(Z);return J.isForcefullyTerminated??=!1,[X,$]},rq1=async(Z)=>{let[J,X]=await Promise.allSettled([GM(Z,"spawn"),GM(Z,"exit")]);if(J.status==="rejected")return[];return X.status==="rejected"?Jp(Z):X.value},Jp=async(Z)=>{try{return await GM(Z,"exit")}catch{return Jp(Z)}},Xp=async(Z)=>{let[J,X]=await Z;if(!tq1(J,X)&&zM(J,X))throw new t9;return[J,X]},tq1=(Z,J)=>Z===void 0&&J===void 0,zM=(Z,J)=>Z!==0||J!==null;var $p=({error:Z,status:J,signal:X,output:$},{maxBuffer:Y})=>{let Q=eq1(Z,J,X),K=Q?.code==="ETIMEDOUT",W=tl(Q,$,Y);return{resultError:Q,exitCode:J,signal:X,timedOut:K,isMaxBuffer:W}},eq1=(Z,J,X)=>{if(Z!==void 0)return Z;return zM(J,X)?new t9:void 0};var Yp=(Z,J,X)=>{let{file:$,commandArguments:Y,command:Q,escapedCommand:K,startTime:W,verboseInfo:G,options:z,fileDescriptors:V}=JF1(Z,J,X),H=YF1({file:$,commandArguments:Y,options:z,command:Q,escapedCommand:K,verboseInfo:G,fileDescriptors:V,startTime:W});return oQ(H,G,z)},JF1=(Z,J,X)=>{let{command:$,escapedCommand:Y,startTime:Q,verboseInfo:K}=Nq(Z,J,X),W=XF1(X),{file:G,commandArguments:z,options:V}=sq(Z,J,W);$F1(V);let H=_y(V,K);return{file:G,commandArguments:z,command:$,escapedCommand:Y,startTime:Q,verboseInfo:K,options:V,fileDescriptors:H}},XF1=(Z)=>Z.node&&!Z.ipc?{...Z,ipc:!1}:Z,$F1=({ipc:Z,ipcInput:J,detached:X,cancelSignal:$})=>{if(J)FF("ipcInput");if(Z)FF("ipc: true");if(X)FF("detached: true");if($)FF("cancelSignal")},FF=(Z)=>{throw new TypeError(`The "${Z}" option cannot be used with synchronous methods.`)},YF1=({file:Z,commandArguments:J,options:X,command:$,escapedCommand:Y,verboseInfo:Q,fileDescriptors:K,startTime:W})=>{let G=QF1({file:Z,commandArguments:J,options:X,command:$,escapedCommand:Y,fileDescriptors:K,startTime:W});if(G.failed)return G;let{resultError:z,exitCode:V,signal:H,timedOut:v,isMaxBuffer:q}=$p(G,X),{output:F,error:c=z}=ty({fileDescriptors:K,syncResult:G,options:X,isMaxBuffer:q,verboseInfo:Q}),w=F.map((j,B)=>ZZ(j,X,B)),x=ZZ(ey(F,X),X,"all");return WF1({error:c,exitCode:V,signal:H,timedOut:v,isMaxBuffer:q,stdio:w,all:x,options:X,command:$,escapedCommand:Y,startTime:W})},QF1=({file:Z,commandArguments:J,options:X,command:$,escapedCommand:Y,fileDescriptors:Q,startTime:K})=>{try{ny(Q,X);let W=KF1(X);return ZF1(Z,J,W)}catch(W){return sQ({error:W,command:$,escapedCommand:Y,fileDescriptors:Q,options:X,startTime:K,isSync:!0})}},KF1=({encoding:Z,maxBuffer:J,...X})=>({...X,encoding:"buffer",maxBuffer:$F(J)}),WF1=({error:Z,exitCode:J,signal:X,timedOut:$,isMaxBuffer:Y,stdio:Q,all:K,options:W,command:G,escapedCommand:z,startTime:V})=>Z===void 0?YF({command:G,escapedCommand:z,stdio:Q,all:K,ipcOutput:[],options:W,startTime:V}):tW({error:Z,command:G,escapedCommand:z,timedOut:$,isCanceled:!1,isGracefullyCanceled:!1,isMaxBuffer:Y,isForcefullyTerminated:!1,exitCode:J,signal:X,stdio:Q,all:K,ipcOutput:[],options:W,startTime:V,isSync:!0});import{setMaxListeners as nc1}from"node:events";import{spawn as sc1}from"node:child_process";import zp from"node:process";import{once as VM,on as GF1}from"node:events";var Qp=({anyProcess:Z,channel:J,isSubprocess:X,ipc:$},{reference:Y=!0,filter:Q}={})=>{return iQ({methodName:"getOneMessage",isSubprocess:X,ipc:$,isConnected:pq(Z)}),zF1({anyProcess:Z,channel:J,isSubprocess:X,filter:Q,reference:Y})},zF1=async({anyProcess:Z,channel:J,isSubprocess:X,filter:$,reference:Y})=>{mq(J,Y);let Q=kJ(Z,J,X),K=new AbortController;try{return await Promise.race([VF1(Q,$,K),vF1(Q,X,K),HF1(Q,X,K)])}catch(W){throw gQ(Z),W}finally{K.abort(),uq(J,Y)}},VF1=async(Z,J,{signal:X})=>{if(J===void 0){let[$]=await VM(Z,"message",{signal:X});return $}for await(let[$]of GF1(Z,"message",{signal:X}))if(J($))return $},vF1=async(Z,J,{signal:X})=>{await VM(Z,"disconnect",{signal:X}),iu(J)},HF1=async(Z,J,{signal:X})=>{let[$]=await VM(Z,"strict:error",{signal:X});throw hq($,J)};import{once as Wp,on as qF1}from"node:events";var Gp=({anyProcess:Z,channel:J,isSubprocess:X,ipc:$},{reference:Y=!0}={})=>vM({anyProcess:Z,channel:J,isSubprocess:X,ipc:$,shouldAwait:!X,reference:Y}),vM=({anyProcess:Z,channel:J,isSubprocess:X,ipc:$,shouldAwait:Y,reference:Q})=>{iQ({methodName:"getEachMessage",isSubprocess:X,ipc:$,isConnected:pq(Z)}),mq(J,Q);let K=kJ(Z,J,X),W=new AbortController,G={};return FF1(Z,K,W),cF1({ipcEmitter:K,isSubprocess:X,controller:W,state:G}),wF1({anyProcess:Z,channel:J,ipcEmitter:K,isSubprocess:X,shouldAwait:Y,controller:W,state:G,reference:Q})},FF1=async(Z,J,X)=>{try{await Wp(J,"disconnect",{signal:X.signal}),X.abort()}catch{}},cF1=async({ipcEmitter:Z,isSubprocess:J,controller:X,state:$})=>{try{let[Y]=await Wp(Z,"strict:error",{signal:X.signal});$.error=hq(Y,J),X.abort()}catch{}},wF1=async function*({anyProcess:Z,channel:J,ipcEmitter:X,isSubprocess:$,shouldAwait:Y,controller:Q,state:K,reference:W}){try{for await(let[G]of qF1(X,"message",{signal:Q.signal}))Kp(K),yield G}catch{Kp(K)}finally{if(Q.abort(),uq(J,W),!$)gQ(Z);if(Y)await Z}},Kp=({error:Z})=>{if(Z)throw Z};var Vp=(Z,{ipc:J})=>{Object.assign(Z,Hp(Z,!1,J))},vp=()=>{let Z=zp,J=!0,X=zp.channel!==void 0;return{...Hp(Z,!0,X),getCancelSignal:xl.bind(void 0,{anyProcess:Z,channel:Z.channel,isSubprocess:!0,ipc:X})}},Hp=(Z,J,X)=>({sendMessage:aq.bind(void 0,{anyProcess:Z,channel:Z.channel,isSubprocess:J,ipc:X}),getOneMessage:Qp.bind(void 0,{anyProcess:Z,channel:Z.channel,isSubprocess:J,ipc:X}),getEachMessage:Gp.bind(void 0,{anyProcess:Z,channel:Z.channel,isSubprocess:J,ipc:X})});import{ChildProcess as xF1}from"node:child_process";import{PassThrough as UF1,Readable as jF1,Writable as BF1,Duplex as LF1}from"node:stream";var qp=({error:Z,command:J,escapedCommand:X,fileDescriptors:$,options:Y,startTime:Q,verboseInfo:K})=>{JM($);let W=new xF1;DF1(W,$),Object.assign(W,{readable:MF1,writable:RF1,duplex:OF1});let G=sQ({error:Z,command:J,escapedCommand:X,fileDescriptors:$,options:Y,startTime:Q,isSync:!1}),z=NF1(G,K,Y);return{subprocess:W,promise:z}},DF1=(Z,J)=>{let X=ZG(),$=ZG(),Y=ZG(),Q=Array.from({length:J.length-3},ZG),K=ZG(),W=[X,$,Y,...Q];Object.assign(Z,{stdin:X,stdout:$,stderr:Y,all:K,stdio:W})},ZG=()=>{let Z=new UF1;return Z.end(),Z},MF1=()=>new jF1({read(){}}),RF1=()=>new BF1({write(){}}),OF1=()=>new LF1({read(){},write(){}}),NF1=async(Z,J,X)=>oQ(Z,J,X);import{createReadStream as Fp,createWriteStream as cp}from"node:fs";import{Buffer as PF1}from"node:buffer";import{Readable as JG,Writable as TF1,Duplex as CF1}from"node:stream";var xp=(Z,J)=>GF(fF1,Z,J,!1),XG=({type:Z,optionName:J})=>{throw new TypeError(`The \`${J}\` option cannot be ${EJ[Z]}.`)},wp={fileNumber:XG,generator:WM,asyncGenerator:WM,nodeStream:({value:Z})=>({stream:Z}),webTransform({value:{transform:Z,writableObjectMode:J,readableObjectMode:X}}){let $=J||X;return{stream:CF1.fromWeb(Z,{objectMode:$})}},duplex:({value:{transform:Z}})=>({stream:Z}),native(){}},fF1={input:{...wp,fileUrl:({value:Z})=>({stream:Fp(Z)}),filePath:({value:{file:Z}})=>({stream:Fp(Z)}),webStream:({value:Z})=>({stream:JG.fromWeb(Z)}),iterable:({value:Z})=>({stream:JG.from(Z)}),asyncIterable:({value:Z})=>({stream:JG.from(Z)}),string:({value:Z})=>({stream:JG.from(Z)}),uint8Array:({value:Z})=>({stream:JG.from(PF1.from(Z))})},output:{...wp,fileUrl:({value:Z})=>({stream:cp(Z)}),filePath:({value:{file:Z,append:J}})=>({stream:cp(Z,J?{flags:"a"}:{})}),webStream:({value:Z})=>({stream:TF1.fromWeb(Z)}),iterable:XG,asyncIterable:XG,string:XG,uint8Array:XG}};import{on as kF1,once as Up}from"node:events";import{PassThrough as EF1,getDefaultHighWaterMark as IF1}from"node:stream";import{finished as Lp}from"node:stream/promises";function P$(Z){if(!Array.isArray(Z))throw new TypeError(`Expected an array, got \`${typeof Z}\`.`);for(let Y of Z)HM(Y);let J=Z.some(({readableObjectMode:Y})=>Y),X=_F1(Z,J),$=new Dp({objectMode:J,writableHighWaterMark:X,readableHighWaterMark:X});for(let Y of Z)$.add(Y);return $}var _F1=(Z,J)=>{if(Z.length===0)return IF1(J);let X=Z.filter(({readableObjectMode:$})=>$===J).map(({readableHighWaterMark:$})=>$);return Math.max(...X)};class Dp extends EF1{#Z=new Set([]);#J=new Set([]);#$=new Set([]);#X;#Y=Symbol("unpipe");#V=new WeakMap;add(Z){if(HM(Z),this.#Z.has(Z))return;this.#Z.add(Z),this.#X??=bF1(this,this.#Z,this.#Y);let J=AF1({passThroughStream:this,stream:Z,streams:this.#Z,ended:this.#J,aborted:this.#$,onFinished:this.#X,unpipeEvent:this.#Y});this.#V.set(Z,J),Z.pipe(this,{end:!1})}async remove(Z){if(HM(Z),!this.#Z.has(Z))return!1;let J=this.#V.get(Z);if(J===void 0)return!1;return this.#V.delete(Z),Z.unpipe(this),await J,!0}}var bF1=async(Z,J,X)=>{cF(Z,jp);let $=new AbortController;try{await Promise.race([hF1(Z,$),SF1(Z,J,X,$)])}finally{$.abort(),cF(Z,-jp)}},hF1=async(Z,{signal:J})=>{try{await Lp(Z,{signal:J,cleanup:!0})}catch(X){throw Mp(Z,X),X}},SF1=async(Z,J,X,{signal:$})=>{for await(let[Y]of kF1(Z,"unpipe",{signal:$}))if(J.has(Y))Y.emit(X)},HM=(Z)=>{if(typeof Z?.pipe!=="function")throw new TypeError(`Expected a readable stream, got: \`${typeof Z}\`.`)},AF1=async({passThroughStream:Z,stream:J,streams:X,ended:$,aborted:Y,onFinished:Q,unpipeEvent:K})=>{cF(Z,Bp);let W=new AbortController;try{await Promise.race([mF1(Q,J,W),uF1({passThroughStream:Z,stream:J,streams:X,ended:$,aborted:Y,controller:W}),lF1({stream:J,streams:X,ended:$,aborted:Y,unpipeEvent:K,controller:W})])}finally{W.abort(),cF(Z,-Bp)}if(X.size>0&&X.size===$.size+Y.size)if($.size===0&&Y.size>0)qM(Z);else yF1(Z)},mF1=async(Z,J,{signal:X})=>{try{if(await Z,!X.aborted)qM(J)}catch($){if(!X.aborted)Mp(J,$)}},uF1=async({passThroughStream:Z,stream:J,streams:X,ended:$,aborted:Y,controller:{signal:Q}})=>{try{if(await Lp(J,{signal:Q,cleanup:!0,readable:!0,writable:!1}),X.has(J))$.add(J)}catch(K){if(Q.aborted||!X.has(J))return;if(Rp(K))Y.add(J);else Op(Z,K)}},lF1=async({stream:Z,streams:J,ended:X,aborted:$,unpipeEvent:Y,controller:{signal:Q}})=>{if(await Up(Z,Y,{signal:Q}),!Z.readable)return Up(Q,"abort",{signal:Q});J.delete(Z),X.delete(Z),$.delete(Z)},yF1=(Z)=>{if(Z.writable)Z.end()},Mp=(Z,J)=>{if(Rp(J))qM(Z);else Op(Z,J)},Rp=(Z)=>Z?.code==="ERR_STREAM_PREMATURE_CLOSE",qM=(Z)=>{if(Z.readable||Z.writable)Z.destroy()},Op=(Z,J)=>{if(!Z.destroyed)Z.once("error",pF1),Z.destroy(J)},pF1=()=>{},cF=(Z,J)=>{let X=Z.getMaxListeners();if(X!==0&&X!==Number.POSITIVE_INFINITY)Z.setMaxListeners(X+J)},jp=2,Bp=1;import{finished as Np}from"node:stream/promises";var tQ=(Z,J)=>{Z.pipe(J),iF1(Z,J),gF1(Z,J)},iF1=async(Z,J)=>{if(v9(Z)||v9(J))return;try{await Np(Z,{cleanup:!0,readable:!0,writable:!1})}catch{}FM(J)},FM=(Z)=>{if(Z.writable)Z.end()},gF1=async(Z,J)=>{if(v9(Z)||v9(J))return;try{await Np(J,{cleanup:!0,readable:!1,writable:!0})}catch{}cM(Z)},cM=(Z)=>{if(Z.readable)Z.destroy()};var Pp=(Z,J,X)=>{let $=new Map;for(let[Y,{stdioItems:Q,direction:K}]of Object.entries(J)){for(let{stream:W}of Q.filter(({type:G})=>V4.has(G)))dF1(Z,W,K,Y);for(let{stream:W}of Q.filter(({type:G})=>!V4.has(G)))nF1({subprocess:Z,stream:W,direction:K,fdNumber:Y,pipeGroups:$,controller:X})}for(let[Y,Q]of $.entries()){let K=Q.length===1?Q[0]:P$(Q);tQ(K,Y)}},dF1=(Z,J,X,$)=>{if(X==="output")tQ(Z.stdio[$],J);else tQ(J,Z.stdio[$]);let Y=aF1[$];if(Y!==void 0)Z[Y]=J;Z.stdio[$]=J},aF1=["stdin","stdout","stderr"],nF1=({subprocess:Z,stream:J,direction:X,fdNumber:$,pipeGroups:Y,controller:Q})=>{if(J===void 0)return;sF1(J,Q);let[K,W]=X==="output"?[J,Z.stdio[$]]:[Z.stdio[$],J],G=Y.get(K)??[];Y.set(K,[...G,W])},sF1=(Z,{signal:J})=>{if(v9(Z))M$(Z,oF1,J)},oF1=2;import{addAbortListener as eF1}from"node:events";var T$=[];T$.push("SIGHUP","SIGINT","SIGTERM");if(process.platform!=="win32")T$.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")T$.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var wF=(Z)=>!!Z&&typeof Z==="object"&&typeof Z.removeListener==="function"&&typeof Z.emit==="function"&&typeof Z.reallyExit==="function"&&typeof Z.listeners==="function"&&typeof Z.kill==="function"&&typeof Z.pid==="number"&&typeof Z.on==="function",wM=Symbol.for("signal-exit emitter"),xM=globalThis,rF1=Object.defineProperty.bind(Object);class Tp{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(xM[wM])return xM[wM];rF1(xM,wM,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(Z,J){this.listeners[Z].push(J)}removeListener(Z,J){let X=this.listeners[Z],$=X.indexOf(J);if($===-1)return;if($===0&&X.length===1)X.length=0;else X.splice($,1)}emit(Z,J,X){if(this.emitted[Z])return!1;this.emitted[Z]=!0;let $=!1;for(let Y of this.listeners[Z])$=Y(J,X)===!0||$;if(Z==="exit")$=this.emit("afterExit",J,X)||$;return $}}class jM{}var tF1=(Z)=>{return{onExit(J,X){return Z.onExit(J,X)},load(){return Z.load()},unload(){return Z.unload()}}};class Cp extends jM{onExit(){return()=>{}}load(){}unload(){}}class fp extends jM{#Z=UM.platform==="win32"?"SIGINT":"SIGHUP";#J=new Tp;#$;#X;#Y;#V={};#H=!1;constructor(Z){super();this.#$=Z,this.#V={};for(let J of T$)this.#V[J]=()=>{let X=this.#$.listeners(J),{count:$}=this.#J,Y=Z;if(typeof Y.__signal_exit_emitter__==="object"&&typeof Y.__signal_exit_emitter__.count==="number")$+=Y.__signal_exit_emitter__.count;if(X.length===$){this.unload();let Q=this.#J.emit("exit",null,J),K=J==="SIGHUP"?this.#Z:J;if(!Q)Z.kill(Z.pid,K)}};this.#Y=Z.reallyExit,this.#X=Z.emit}onExit(Z,J){if(!wF(this.#$))return()=>{};if(this.#H===!1)this.load();let X=J?.alwaysLast?"afterExit":"exit";return this.#J.on(X,Z),()=>{if(this.#J.removeListener(X,Z),this.#J.listeners.exit.length===0&&this.#J.listeners.afterExit.length===0)this.unload()}}load(){if(this.#H)return;this.#H=!0,this.#J.count+=1;for(let Z of T$)try{let J=this.#V[Z];if(J)this.#$.on(Z,J)}catch(J){}this.#$.emit=(Z,...J)=>{return this.#G(Z,...J)},this.#$.reallyExit=(Z)=>{return this.#W(Z)}}unload(){if(!this.#H)return;this.#H=!1,T$.forEach((Z)=>{let J=this.#V[Z];if(!J)throw new Error("Listener not defined for signal: "+Z);try{this.#$.removeListener(Z,J)}catch(X){}}),this.#$.emit=this.#X,this.#$.reallyExit=this.#Y,this.#J.count-=1}#W(Z){if(!wF(this.#$))return 0;return this.#$.exitCode=Z||0,this.#J.emit("exit",this.#$.exitCode,null),this.#Y.call(this.#$,this.#$.exitCode)}#G(Z,...J){let X=this.#X;if(Z==="exit"&&wF(this.#$)){if(typeof J[0]==="number")this.#$.exitCode=J[0];let $=X.call(this.#$,Z,...J);return this.#J.emit("exit",this.#$.exitCode,null),$}else return X.call(this.#$,Z,...J)}}var UM=globalThis.process,{onExit:kp,load:mL6,unload:uL6}=tF1(wF(UM)?new fp(UM):new Cp);var Ep=(Z,{cleanup:J,detached:X},{signal:$})=>{if(!J||X)return;let Y=kp(()=>{Z.kill()});eF1($,()=>{Y()})};var _p=({source:Z,sourcePromise:J,boundOptions:X,createNested:$},...Y)=>{let Q=Oq(),{destination:K,destinationStream:W,destinationError:G,from:z,unpipeSignal:V}=Zc1(X,$,Y),{sourceStream:H,sourceError:v}=Xc1(Z,z),{options:q,fileDescriptors:F}=Z7.get(Z);return{sourcePromise:J,sourceStream:H,sourceOptions:q,sourceError:v,destination:K,destinationStream:W,destinationError:G,unpipeSignal:V,fileDescriptors:F,startTime:Q}},Zc1=(Z,J,X)=>{try{let{destination:$,pipeOptions:{from:Y,to:Q,unpipeSignal:K}={}}=Jc1(Z,J,...X),W=Aq($,Q);return{destination:$,destinationStream:W,from:Y,unpipeSignal:K}}catch($){return{destinationError:$}}},Jc1=(Z,J,X,...$)=>{if(Array.isArray(X))return{destination:J(Ip,Z)(X,...$),pipeOptions:Z};if(typeof X==="string"||X instanceof URL||vD(X)){if(Object.keys(Z).length>0)throw new TypeError('Please use .pipe("file", ..., options) or .pipe(execa("file", ..., options)) instead of .pipe(options)("file", ...).');let[Y,Q,K]=cq(X,...$);return{destination:J(Ip)(Y,Q,K),pipeOptions:K}}if(Z7.has(X)){if(Object.keys(Z).length>0)throw new TypeError("Please use .pipe(options)`command` or .pipe($(options)`command`) instead of .pipe(options)($`command`).");return{destination:X,pipeOptions:$[0]}}throw new TypeError(`The first argument must be a template string, an options object, or an Execa subprocess: ${X}`)},Ip=({options:Z})=>({options:{...Z,stdin:"pipe",piped:!0}}),Xc1=(Z,J)=>{try{return{sourceStream:dQ(Z,J)}}catch(X){return{sourceError:X}}};var hp=({sourceStream:Z,sourceError:J,destinationStream:X,destinationError:$,fileDescriptors:Y,sourceOptions:Q,startTime:K})=>{let W=$c1({sourceStream:Z,sourceError:J,destinationStream:X,destinationError:$});if(W!==void 0)throw BM({error:W,fileDescriptors:Y,sourceOptions:Q,startTime:K})},$c1=({sourceStream:Z,sourceError:J,destinationStream:X,destinationError:$})=>{if(J!==void 0&&$!==void 0)return $;if($!==void 0)return cM(Z),$;if(J!==void 0)return FM(X),J},BM=({error:Z,fileDescriptors:J,sourceOptions:X,startTime:$})=>sQ({error:Z,command:bp,escapedCommand:bp,fileDescriptors:J,options:X,startTime:$,isSync:!1}),bp="source.pipe(destination)";var Sp=async(Z)=>{let[{status:J,reason:X,value:$=X},{status:Y,reason:Q,value:K=Q}]=await Z;if(!K.pipedFrom.includes($))K.pipedFrom.push($);if(Y==="rejected")throw K;if(J==="rejected")throw $;return K};import{finished as Yc1}from"node:stream/promises";var Ap=(Z,J,X)=>{let $=xF.has(J)?Kc1(Z,J):Qc1(Z,J);return M$(Z,Gc1,X.signal),M$(J,zc1,X.signal),Wc1(J),$},Qc1=(Z,J)=>{let X=P$([Z]);return tQ(X,J),xF.set(J,X),X},Kc1=(Z,J)=>{let X=xF.get(J);return X.add(Z),X},Wc1=async(Z)=>{try{await Yc1(Z,{cleanup:!0,readable:!1,writable:!0})}catch{}xF.delete(Z)},xF=new WeakMap,Gc1=2,zc1=1;import{aborted as Vc1}from"node:util";var mp=(Z,J)=>Z===void 0?[]:[vc1(Z,J)],vc1=async(Z,{sourceStream:J,mergedStream:X,fileDescriptors:$,sourceOptions:Y,startTime:Q})=>{await Vc1(Z,J),await X.remove(J);let K=new Error("Pipe canceled by `unpipeSignal` option.");throw BM({error:K,fileDescriptors:$,sourceOptions:Y,startTime:Q})};var UF=(Z,...J)=>{if(w8(J[0]))return UF.bind(void 0,{...Z,boundOptions:{...Z.boundOptions,...J[0]}});let{destination:X,...$}=_p(Z,...J),Y=Hc1({...$,destination:X});return Y.pipe=UF.bind(void 0,{...Z,source:X,sourcePromise:Y,boundOptions:{}}),Y},Hc1=async({sourcePromise:Z,sourceStream:J,sourceOptions:X,sourceError:$,destination:Y,destinationStream:Q,destinationError:K,unpipeSignal:W,fileDescriptors:G,startTime:z})=>{let V=qc1(Z,Y);hp({sourceStream:J,sourceError:$,destinationStream:Q,destinationError:K,fileDescriptors:G,sourceOptions:X,startTime:z});let H=new AbortController;try{let v=Ap(J,Q,H);return await Promise.race([Sp(V),...mp(W,{sourceStream:J,mergedStream:v,sourceOptions:X,fileDescriptors:G,startTime:z})])}finally{H.abort()}},qc1=(Z,J)=>Promise.allSettled([Z,J]);import{setImmediate as Bc1}from"node:timers/promises";import{on as Fc1}from"node:events";import{getDefaultHighWaterMark as cc1}from"node:stream";var jF=({subprocessStdout:Z,subprocess:J,binary:X,shouldEncode:$,encoding:Y,preserveNewlines:Q})=>{let K=new AbortController;return wc1(J,K),lp({stream:Z,controller:K,binary:X,shouldEncode:!Z.readableObjectMode&&$,encoding:Y,shouldSplit:!Z.readableObjectMode,preserveNewlines:Q})},wc1=async(Z,J)=>{try{await Z}catch{}finally{J.abort()}},LM=({stream:Z,onStreamEnd:J,lines:X,encoding:$,stripFinalNewline:Y,allMixed:Q})=>{let K=new AbortController;xc1(J,K,Z);let W=Z.readableObjectMode&&!Q;return lp({stream:Z,controller:K,binary:$==="buffer",shouldEncode:!W,encoding:$,shouldSplit:!W&&X,preserveNewlines:!Y})},xc1=async(Z,J,X)=>{try{await Z}catch{X.destroy()}finally{J.abort()}},lp=({stream:Z,controller:J,binary:X,shouldEncode:$,encoding:Y,shouldSplit:Q,preserveNewlines:K})=>{let W=Fc1(Z,"data",{signal:J.signal,highWaterMark:up,highWatermark:up});return Uc1({onStdoutChunk:W,controller:J,binary:X,shouldEncode:$,encoding:Y,shouldSplit:Q,preserveNewlines:K})},DM=cc1(!0),up=DM,Uc1=async function*({onStdoutChunk:Z,controller:J,binary:X,shouldEncode:$,encoding:Y,shouldSplit:Q,preserveNewlines:K}){let W=jc1({binary:X,shouldEncode:$,encoding:Y,shouldSplit:Q,preserveNewlines:K});try{for await(let[G]of Z)yield*N$(G,W,0)}catch(G){if(!J.signal.aborted)throw G}finally{yield*eW(W)}},jc1=({binary:Z,shouldEncode:J,encoding:X,shouldSplit:$,preserveNewlines:Y})=>[VF(Z,X,!J),zF(Z,Y,!$,{})].filter(Boolean);var yp=async({stream:Z,onStreamEnd:J,fdNumber:X,encoding:$,buffer:Y,maxBuffer:Q,lines:K,allMixed:W,stripFinalNewline:G,verboseInfo:z,streamInfo:V})=>{let H=Lc1({stream:Z,onStreamEnd:J,fdNumber:X,encoding:$,allMixed:W,verboseInfo:z,streamInfo:V});if(!Y){await Promise.all([Dc1(Z),H]);return}let v=XM(G,X),q=LM({stream:Z,onStreamEnd:J,lines:K,encoding:$,stripFinalNewline:v,allMixed:W}),[F]=await Promise.all([Mc1({stream:Z,iterable:q,fdNumber:X,encoding:$,maxBuffer:Q,lines:K}),H]);return F},Lc1=async({stream:Z,onStreamEnd:J,fdNumber:X,encoding:$,allMixed:Y,verboseInfo:Q,streamInfo:{fileDescriptors:K}})=>{if(!qF({stdioItems:K[X]?.stdioItems,encoding:$,verboseInfo:Q,fdNumber:X}))return;let W=LM({stream:Z,onStreamEnd:J,lines:!0,encoding:$,stripFinalNewline:!0,allMixed:Y});await sy(W,Z,X,Q)},Dc1=async(Z)=>{if(await Bc1(),Z.readableFlowing===null)Z.resume()},Mc1=async({stream:Z,stream:{readableObjectMode:J},iterable:X,fdNumber:$,encoding:Y,maxBuffer:Q,lines:K})=>{try{if(J||K)return await eq(X,{maxBuffer:Q});if(Y==="buffer")return new Uint8Array(await ZF(X,{maxBuffer:Q}));return await XF(X,{maxBuffer:Q})}catch(W){return pp(sl({error:W,stream:Z,readableObjectMode:J,lines:K,encoding:Y,fdNumber:$}))}},MM=async(Z)=>{try{return await Z}catch(J){return pp(J)}},pp=({bufferedData:Z})=>vm(Z)?new Uint8Array(Z):Z;import{finished as Rc1}from"node:stream/promises";var $G=async(Z,J,X,{isSameDirection:$,stopOnExit:Y=!1}={})=>{let Q=Oc1(Z,X),K=new AbortController;try{await Promise.race([...Y?[X.exitPromise]:[],Rc1(Z,{cleanup:!0,signal:K.signal})])}catch(W){if(!Q.stdinCleanedUp)Tc1(W,J,X,$)}finally{K.abort()}},Oc1=(Z,{originalStreams:[J],subprocess:X})=>{let $={stdinCleanedUp:!1};if(Z===J)Nc1(Z,X,$);return $},Nc1=(Z,J,X)=>{let{_destroy:$}=Z;Z._destroy=(...Y)=>{Pc1(J,X),$.call(Z,...Y)}},Pc1=({exitCode:Z,signalCode:J},X)=>{if(Z!==null||J!==null)X.stdinCleanedUp=!0},Tc1=(Z,J,X,$)=>{if(!Cc1(Z,J,X,$))throw Z},Cc1=(Z,J,X,$=!0)=>{if(X.propagating)return ip(Z)||BF(Z);return X.propagating=!0,RM(X,J)===$?ip(Z):BF(Z)},RM=({fileDescriptors:Z},J)=>J!=="all"&&Z[J].direction==="input",BF=(Z)=>Z?.code==="ERR_STREAM_PREMATURE_CLOSE",ip=(Z)=>Z?.code==="EPIPE";var gp=({subprocess:Z,encoding:J,buffer:X,maxBuffer:$,lines:Y,stripFinalNewline:Q,verboseInfo:K,streamInfo:W})=>Z.stdio.map((G,z)=>OM({stream:G,fdNumber:z,encoding:J,buffer:X[z],maxBuffer:$[z],lines:Y[z],allMixed:!1,stripFinalNewline:Q,verboseInfo:K,streamInfo:W})),OM=async({stream:Z,fdNumber:J,encoding:X,buffer:$,maxBuffer:Y,lines:Q,allMixed:K,stripFinalNewline:W,verboseInfo:G,streamInfo:z})=>{if(!Z)return;let V=$G(Z,J,z);if(RM(z,J)){await V;return}let[H]=await Promise.all([yp({stream:Z,onStreamEnd:V,fdNumber:J,encoding:X,buffer:$,maxBuffer:Y,lines:Q,allMixed:K,stripFinalNewline:W,verboseInfo:G,streamInfo:z}),V]);return H};var dp=({stdout:Z,stderr:J},{all:X})=>X&&(Z||J)?P$([Z,J].filter(Boolean)):void 0,ap=({subprocess:Z,encoding:J,buffer:X,maxBuffer:$,lines:Y,stripFinalNewline:Q,verboseInfo:K,streamInfo:W})=>OM({...fc1(Z,X),fdNumber:"all",encoding:J,maxBuffer:$[1]+$[2],lines:Y[1]||Y[2],allMixed:kc1(Z),stripFinalNewline:Q,verboseInfo:K,streamInfo:W}),fc1=({stdout:Z,stderr:J,all:X},[,$,Y])=>{let Q=$||Y;if(!Q)return{stream:X,buffer:Q};if(!$)return{stream:J,buffer:Q};if(!Y)return{stream:Z,buffer:Q};return{stream:X,buffer:Q}},kc1=({all:Z,stdout:J,stderr:X})=>Z&&J&&X&&J.readableObjectMode!==X.readableObjectMode;import{once as Ec1}from"node:events";var np=(Z)=>lQ(Z,"ipc"),sp=(Z,J)=>{let X=Rq(Z);r9({type:"ipc",verboseMessage:X,fdNumber:"ipc",verboseInfo:J})};var op=async({subprocess:Z,buffer:J,maxBuffer:X,ipc:$,ipcOutput:Y,verboseInfo:Q})=>{if(!$)return Y;let K=np(Q),W=r7(J,"ipc"),G=r7(X,"ipc");for await(let z of vM({anyProcess:Z,channel:Z.channel,isSubprocess:!1,ipc:$,shouldAwait:!1,reference:!0})){if(W)ol(Z,Y,G),Y.push(z);if(K)sp(z,Q)}return Y},rp=async(Z,J)=>{return await Promise.allSettled([Z]),J};var tp=async({subprocess:Z,options:{encoding:J,buffer:X,maxBuffer:$,lines:Y,timeoutDuration:Q,cancelSignal:K,gracefulCancel:W,forceKillAfterDelay:G,stripFinalNewline:z,ipc:V,ipcInput:H},context:v,verboseInfo:q,fileDescriptors:F,originalStreams:c,onInternalError:w,controller:x})=>{let j=Zp(Z,v),B={originalStreams:c,fileDescriptors:F,subprocess:Z,exitPromise:j,propagating:!1},L=gp({subprocess:Z,encoding:J,buffer:X,maxBuffer:$,lines:Y,stripFinalNewline:z,verboseInfo:q,streamInfo:B}),R=ap({subprocess:Z,encoding:J,buffer:X,maxBuffer:$,lines:Y,stripFinalNewline:z,verboseInfo:q,streamInfo:B}),M=[],O=op({subprocess:Z,buffer:X,maxBuffer:$,ipc:V,ipcOutput:M,verboseInfo:q}),P=Ic1(c,Z,B),N=_c1(F,B);try{return await Promise.race([Promise.all([{},Xp(j),Promise.all(L),R,O,Pl(Z,H),...P,...N]),w,bc1(Z,x),...Dl(Z,Q,v,x),...pu({subprocess:Z,cancelSignal:K,gracefulCancel:W,context:v,controller:x}),...Bl({subprocess:Z,cancelSignal:K,gracefulCancel:W,forceKillAfterDelay:G,context:v,controller:x})])}catch(_){return v.terminationReason??="other",Promise.all([{error:_},j,Promise.all(L.map((k)=>MM(k))),MM(R),rp(O,M),Promise.allSettled(P),Promise.allSettled(N)])}},Ic1=(Z,J,X)=>Z.map(($,Y)=>$===J.stdio[Y]?void 0:$G($,Y,X)),_c1=(Z,J)=>Z.flatMap(({stdioItems:X},$)=>X.filter(({value:Y,stream:Q=Y})=>q9(Q,{checkOpen:!1})&&!v9(Q)).map(({type:Y,value:Q,stream:K=Q})=>$G(K,$,J,{isSameDirection:V4.has(Y),stopOnExit:Y==="native"}))),bc1=async(Z,{signal:J})=>{let[X]=await Ec1(Z,"error",{signal:J});throw X};var ep=()=>({readableDestroy:new WeakMap,writableFinal:new WeakMap,writableDestroy:new WeakMap}),YG=(Z,J,X)=>{let $=Z[X];if(!$.has(J))$.set(J,[]);let Y=$.get(J),Q=e9();return Y.push(Q),{resolve:Q.resolve.bind(Q),promises:Y}},eQ=async({resolve:Z,promises:J},X)=>{Z();let[$]=await Promise.race([Promise.allSettled([!0,X]),Promise.all([!1,...J])]);return!$};import{Readable as hc1}from"node:stream";import{callbackify as Sc1}from"node:util";import{finished as Zi}from"node:stream/promises";var NM=async(Z)=>{if(Z===void 0)return;try{await PM(Z)}catch{}},Ji=async(Z)=>{if(Z===void 0)return;try{await TM(Z)}catch{}},PM=async(Z)=>{await Zi(Z,{cleanup:!0,readable:!1,writable:!0})},TM=async(Z)=>{await Zi(Z,{cleanup:!0,readable:!0,writable:!1})},LF=async(Z,J)=>{if(await Z,J)throw J},DF=(Z,J,X)=>{if(X&&!BF(X))Z.destroy(X);else if(J)Z.destroy()};var Xi=({subprocess:Z,concurrentStreams:J,encoding:X},{from:$,binary:Y=!0,preserveNewlines:Q=!0}={})=>{let K=Y||E5.has(X),{subprocessStdout:W,waitReadableDestroy:G}=CM(Z,$,J),{readableEncoding:z,readableObjectMode:V,readableHighWaterMark:H}=fM(W,K),{read:v,onStdoutDataDone:q}=kM({subprocessStdout:W,subprocess:Z,binary:K,encoding:X,preserveNewlines:Q}),F=new hc1({read:v,destroy:Sc1(IM.bind(void 0,{subprocessStdout:W,subprocess:Z,waitReadableDestroy:G})),highWaterMark:H,objectMode:V,encoding:z});return EM({subprocessStdout:W,onStdoutDataDone:q,readable:F,subprocess:Z}),F},CM=(Z,J,X)=>{let $=dQ(Z,J),Y=YG(X,$,"readableDestroy");return{subprocessStdout:$,waitReadableDestroy:Y}},fM=({readableEncoding:Z,readableObjectMode:J,readableHighWaterMark:X},$)=>$?{readableEncoding:Z,readableObjectMode:J,readableHighWaterMark:X}:{readableEncoding:Z,readableObjectMode:!0,readableHighWaterMark:DM},kM=({subprocessStdout:Z,subprocess:J,binary:X,encoding:$,preserveNewlines:Y})=>{let Q=e9(),K=jF({subprocessStdout:Z,subprocess:J,binary:X,shouldEncode:!X,encoding:$,preserveNewlines:Y});return{read(){Ac1(this,K,Q)},onStdoutDataDone:Q}},Ac1=async(Z,J,X)=>{try{let{value:$,done:Y}=await J.next();if(Y)X.resolve();else Z.push($)}catch{}},EM=async({subprocessStdout:Z,onStdoutDataDone:J,readable:X,subprocess:$,subprocessStdin:Y})=>{try{if(await TM(Z),await $,await NM(Y),await J,X.readable)X.push(null)}catch(Q){await NM(Y),$i(X,Q)}},IM=async({subprocessStdout:Z,subprocess:J,waitReadableDestroy:X},$)=>{if(await eQ(X,J))$i(Z,$),await LF(J,$)},$i=(Z,J)=>{DF(Z,Z.readable,J)};import{Writable as mc1}from"node:stream";import{callbackify as Yi}from"node:util";var Qi=({subprocess:Z,concurrentStreams:J},{to:X}={})=>{let{subprocessStdin:$,waitWritableFinal:Y,waitWritableDestroy:Q}=_M(Z,X,J),K=new mc1({...bM($,Z,Y),destroy:Yi(SM.bind(void 0,{subprocessStdin:$,subprocess:Z,waitWritableFinal:Y,waitWritableDestroy:Q})),highWaterMark:$.writableHighWaterMark,objectMode:$.writableObjectMode});return hM($,K),K},_M=(Z,J,X)=>{let $=Aq(Z,J),Y=YG(X,$,"writableFinal"),Q=YG(X,$,"writableDestroy");return{subprocessStdin:$,waitWritableFinal:Y,waitWritableDestroy:Q}},bM=(Z,J,X)=>({write:uc1.bind(void 0,Z),final:Yi(lc1.bind(void 0,Z,J,X))}),uc1=(Z,J,X,$)=>{if(Z.write(J,X))$();else Z.once("drain",$)},lc1=async(Z,J,X)=>{if(await eQ(X,J)){if(Z.writable)Z.end();await J}},hM=async(Z,J,X)=>{try{if(await PM(Z),J.writable)J.end()}catch($){await Ji(X),Ki(J,$)}},SM=async({subprocessStdin:Z,subprocess:J,waitWritableFinal:X,waitWritableDestroy:$},Y)=>{if(await eQ(X,J),await eQ($,J))Ki(Z,Y),await LF(J,Y)},Ki=(Z,J)=>{DF(Z,Z.writable,J)};import{Duplex as yc1}from"node:stream";import{callbackify as pc1}from"node:util";var Wi=({subprocess:Z,concurrentStreams:J,encoding:X},{from:$,to:Y,binary:Q=!0,preserveNewlines:K=!0}={})=>{let W=Q||E5.has(X),{subprocessStdout:G,waitReadableDestroy:z}=CM(Z,$,J),{subprocessStdin:V,waitWritableFinal:H,waitWritableDestroy:v}=_M(Z,Y,J),{readableEncoding:q,readableObjectMode:F,readableHighWaterMark:c}=fM(G,W),{read:w,onStdoutDataDone:x}=kM({subprocessStdout:G,subprocess:Z,binary:W,encoding:X,preserveNewlines:K}),j=new yc1({read:w,...bM(V,Z,H),destroy:pc1(ic1.bind(void 0,{subprocessStdout:G,subprocessStdin:V,subprocess:Z,waitReadableDestroy:z,waitWritableFinal:H,waitWritableDestroy:v})),readableHighWaterMark:c,writableHighWaterMark:V.writableHighWaterMark,readableObjectMode:F,writableObjectMode:V.writableObjectMode,encoding:q});return EM({subprocessStdout:G,onStdoutDataDone:x,readable:j,subprocess:Z,subprocessStdin:V}),hM(V,j,G),j},ic1=async({subprocessStdout:Z,subprocessStdin:J,subprocess:X,waitReadableDestroy:$,waitWritableFinal:Y,waitWritableDestroy:Q},K)=>{await Promise.all([IM({subprocessStdout:Z,subprocess:X,waitReadableDestroy:$},K),SM({subprocessStdin:J,subprocess:X,waitWritableFinal:Y,waitWritableDestroy:Q},K)])};var AM=(Z,J,{from:X,binary:$=!1,preserveNewlines:Y=!1}={})=>{let Q=$||E5.has(J),K=dQ(Z,X),W=jF({subprocessStdout:K,subprocess:Z,binary:Q,shouldEncode:!0,encoding:J,preserveNewlines:Y});return gc1(W,K,Z)},gc1=async function*(Z,J,X){try{yield*Z}finally{if(J.readable)J.destroy();await X}};var Gi=(Z,{encoding:J})=>{let X=ep();Z.readable=Xi.bind(void 0,{subprocess:Z,concurrentStreams:X,encoding:J}),Z.writable=Qi.bind(void 0,{subprocess:Z,concurrentStreams:X}),Z.duplex=Wi.bind(void 0,{subprocess:Z,concurrentStreams:X,encoding:J}),Z.iterable=AM.bind(void 0,Z,J),Z[Symbol.asyncIterator]=AM.bind(void 0,Z,J,{})};var zi=(Z,J)=>{for(let[X,$]of ac1){let Y=$.value.bind(J);Reflect.defineProperty(Z,X,{...$,value:Y})}},dc1=(async()=>{})().constructor.prototype,ac1=["then","catch","finally"].map((Z)=>[Z,Reflect.getOwnPropertyDescriptor(dc1,Z)]);var Vi=(Z,J,X,$)=>{let{file:Y,commandArguments:Q,command:K,escapedCommand:W,startTime:G,verboseInfo:z,options:V,fileDescriptors:H}=oc1(Z,J,X),{subprocess:v,promise:q}=tc1({file:Y,commandArguments:Q,options:V,startTime:G,verboseInfo:z,command:K,escapedCommand:W,fileDescriptors:H});return v.pipe=UF.bind(void 0,{source:v,sourcePromise:q,boundOptions:{},createNested:$}),zi(v,q),Z7.set(v,{options:V,fileDescriptors:H}),v},oc1=(Z,J,X)=>{let{command:$,escapedCommand:Y,startTime:Q,verboseInfo:K}=Nq(Z,J,X),{file:W,commandArguments:G,options:z}=sq(Z,J,X),V=rc1(z),H=xp(V,K);return{file:W,commandArguments:G,command:$,escapedCommand:Y,startTime:Q,verboseInfo:K,options:V,fileDescriptors:H}},rc1=({timeout:Z,signal:J,...X})=>{if(J!==void 0)throw new TypeError('The "signal" option has been renamed to "cancelSignal" instead.');return{...X,timeoutDuration:Z}},tc1=({file:Z,commandArguments:J,options:X,startTime:$,verboseInfo:Y,command:Q,escapedCommand:K,fileDescriptors:W})=>{let G;try{G=sc1(Z,J,X)}catch(F){return qp({error:F,command:Q,escapedCommand:K,fileDescriptors:W,options:X,startTime:$,verboseInfo:Y})}let z=new AbortController;nc1(Number.POSITIVE_INFINITY,z.signal);let V=[...G.stdio];Pp(G,W,z),Ep(G,X,z);let H={},v=e9();G.kill=lu.bind(void 0,{kill:G.kill.bind(G),options:X,onInternalError:v,context:H,controller:z}),G.all=dp(G,X),Gi(G,X),Vp(G,X);let q=ec1({subprocess:G,options:X,startTime:$,verboseInfo:Y,fileDescriptors:W,originalStreams:V,command:Q,escapedCommand:K,context:H,onInternalError:v,controller:z});return{subprocess:G,promise:q}},ec1=async({subprocess:Z,options:J,startTime:X,verboseInfo:$,fileDescriptors:Y,originalStreams:Q,command:K,escapedCommand:W,context:G,onInternalError:z,controller:V})=>{let[H,[v,q],F,c,w]=await tp({subprocess:Z,options:J,context:G,verboseInfo:$,fileDescriptors:Y,originalStreams:Q,onInternalError:z,controller:V});V.abort(),z.resolve();let x=F.map((L,R)=>ZZ(L,J,R)),j=ZZ(c,J,"all"),B=Zw1({errorInfo:H,exitCode:v,signal:q,stdio:x,all:j,ipcOutput:w,context:G,options:J,command:K,escapedCommand:W,startTime:X});return oQ(B,$,J)},Zw1=({errorInfo:Z,exitCode:J,signal:X,stdio:$,all:Y,ipcOutput:Q,context:K,options:W,command:G,escapedCommand:z,startTime:V})=>("error"in Z)?tW({error:Z.error,command:G,escapedCommand:z,timedOut:K.terminationReason==="timeout",isCanceled:K.terminationReason==="cancel"||K.terminationReason==="gracefulCancel",isGracefullyCanceled:K.terminationReason==="gracefulCancel",isMaxBuffer:Z.error instanceof t7,isForcefullyTerminated:K.isForcefullyTerminated,exitCode:J,signal:X,stdio:$,all:Y,ipcOutput:Q,options:W,startTime:V,isSync:!1}):YF({command:G,escapedCommand:z,stdio:$,all:Y,ipcOutput:Q,options:W,startTime:V});var MF=(Z,J)=>{let X=Object.fromEntries(Object.entries(J).map(([$,Y])=>[$,Jw1($,Z[$],Y)]));return{...Z,...X}},Jw1=(Z,J,X)=>{if(Xw1.has(Z)&&w8(J)&&w8(X))return{...J,...X};return X},Xw1=new Set(["env",...xD]);var IJ=(Z,J,X,$)=>{let Y=(K,W,G)=>IJ(K,W,X,G),Q=(...K)=>$w1({mapArguments:Z,deepOptions:X,boundOptions:J,setBoundExeca:$,createNested:Y},...K);if($!==void 0)$(Q,Y,J);return Q},$w1=({mapArguments:Z,deepOptions:J={},boundOptions:X={},setBoundExeca:$,createNested:Y},Q,...K)=>{if(w8(Q))return Y(Z,MF(X,Q),$);let{file:W,commandArguments:G,options:z,isSync:V}=Yw1({mapArguments:Z,firstArgument:Q,nextArguments:K,deepOptions:J,boundOptions:X});return V?Yp(W,G,z):Vi(W,G,z,Y)},Yw1=({mapArguments:Z,firstArgument:J,nextArguments:X,deepOptions:$,boundOptions:Y})=>{let Q=xm(J)?Um(J,X):[J,...X],[K,W,G]=cq(...Q),z=MF(MF($,Y),G),{file:V=K,commandArguments:H=W,options:v=z,isSync:q=!1}=Z({file:K,commandArguments:W,options:z});return{file:V,commandArguments:H,options:v,isSync:q}};var vi=({file:Z,commandArguments:J})=>qi(Z,J),Hi=({file:Z,commandArguments:J})=>({...qi(Z,J),isSync:!0}),qi=(Z,J)=>{if(J.length>0)throw new TypeError(`The command and its arguments must be passed as a single string: ${Z} ${J}.`);let[X,...$]=Qw1(Z);return{file:X,commandArguments:$}},Qw1=(Z)=>{if(typeof Z!=="string")throw new TypeError(`The command must be a string: ${String(Z)}.`);let J=Z.trim();if(J==="")return[];let X=[];for(let $ of J.split(Kw1)){let Y=X.at(-1);if(Y&&Y.endsWith("\\"))X[X.length-1]=`${Y.slice(0,-1)} ${$}`;else X.push($)}return X},Kw1=/ +/g;var Fi=(Z,J,X)=>{Z.sync=J(Ww1,X),Z.s=Z.sync},ci=({options:Z})=>wi(Z),Ww1=({options:Z})=>({...wi(Z),isSync:!0}),wi=(Z)=>({options:{...Gw1(Z),...Z}}),Gw1=({input:Z,inputFile:J,stdio:X})=>Z===void 0&&J===void 0&&X===void 0?{stdin:"inherit"}:{},xi={preferLocal:!0};var Ui=IJ(()=>({})),TR6=IJ(()=>({isSync:!0})),CR6=IJ(vi),fR6=IJ(Hi),kR6=IJ(Rl),ER6=IJ(ci,{},xi,Fi),{sendMessage:IR6,getOneMessage:_R6,getEachMessage:bR6,getCancelSignal:hR6}=vp();var Ai=t(fi(),1);var KG=(Z)=>{if(typeof Z!=="string")throw new TypeError("invalid pattern");if(Z.length>65536)throw new TypeError("pattern is too long")};var ww1={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},WG=(Z)=>Z.replace(/[[\]\\-]/g,"\\$&"),xw1=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),ki=(Z)=>Z.join(""),Ei=(Z,J)=>{let X=J;if(Z.charAt(X)!=="[")throw new Error("not in a brace expression");let $=[],Y=[],Q=X+1,K=!1,W=!1,G=!1,z=!1,V=X,H="";Z:while(Q<Z.length){let c=Z.charAt(Q);if((c==="!"||c==="^")&&Q===X+1){z=!0,Q++;continue}if(c==="]"&&K&&!G){V=Q+1;break}if(K=!0,c==="\\"){if(!G){G=!0,Q++;continue}}if(c==="["&&!G){for(let[w,[x,j,B]]of Object.entries(ww1))if(Z.startsWith(w,Q)){if(H)return["$.",!1,Z.length-X,!0];if(Q+=w.length,B)Y.push(x);else $.push(x);W=W||j;continue Z}}if(G=!1,H){if(c>H)$.push(WG(H)+"-"+WG(c));else if(c===H)$.push(WG(c));H="",Q++;continue}if(Z.startsWith("-]",Q+1)){$.push(WG(c+"-")),Q+=2;continue}if(Z.startsWith("-",Q+1)){H=c,Q+=2;continue}$.push(WG(c)),Q++}if(V<Q)return["",!1,0,!1];if(!$.length&&!Y.length)return["$.",!1,Z.length-X,!0];if(Y.length===0&&$.length===1&&/^\\?.$/.test($[0])&&!z){let c=$[0].length===2?$[0].slice(-1):$[0];return[xw1(c),!1,V-X,!1]}let v="["+(z?"^":"")+ki($)+"]",q="["+(z?"":"^")+ki(Y)+"]";return[$.length&&Y.length?"("+v+"|"+q+")":$.length?v:q,W,V-X,!0]};var F9=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/\[([^\/\\])\]/g,"$1"):Z.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1")};var Uw1=new Set(["!","?","+","*","@"]),Ii=(Z)=>Uw1.has(Z),jw1="(?!(?:^|/)\\.\\.?(?:$|/))",RF="(?!\\.)",Bw1=new Set(["[","."]),Lw1=new Set(["..","."]),Dw1=new Set("().*{}+?[]^$\\!"),Mw1=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),yM="[^/]",_i=yM+"*?",bi=yM+"+?";class Z6{type;#Z;#J;#$=!1;#X=[];#Y;#V;#H;#W=!1;#G;#z;#v=!1;constructor(Z,J,X={}){if(this.type=Z,Z)this.#J=!0;if(this.#Y=J,this.#Z=this.#Y?this.#Y.#Z:this,this.#G=this.#Z===this?X:this.#Z.#G,this.#H=this.#Z===this?[]:this.#Z.#H,Z==="!"&&!this.#Z.#W)this.#H.push(this);this.#V=this.#Y?this.#Y.#X.length:0}get hasMagic(){if(this.#J!==void 0)return this.#J;for(let Z of this.#X){if(typeof Z==="string")continue;if(Z.type||Z.hasMagic)return this.#J=!0}return this.#J}toString(){if(this.#z!==void 0)return this.#z;if(!this.type)return this.#z=this.#X.map((Z)=>String(Z)).join("");else return this.#z=this.type+"("+this.#X.map((Z)=>String(Z)).join("|")+")"}#Q(){if(this!==this.#Z)throw new Error("should only call on root");if(this.#W)return this;this.toString(),this.#W=!0;let Z;while(Z=this.#H.pop()){if(Z.type!=="!")continue;let J=Z,X=J.#Y;while(X){for(let $=J.#V+1;!X.type&&$<X.#X.length;$++)for(let Y of Z.#X){if(typeof Y==="string")throw new Error("string part in extglob AST??");Y.copyIn(X.#X[$])}J=X,X=J.#Y}}return this}push(...Z){for(let J of Z){if(J==="")continue;if(typeof J!=="string"&&!(J instanceof Z6&&J.#Y===this))throw new Error("invalid part: "+J);this.#X.push(J)}}toJSON(){let Z=this.type===null?this.#X.slice().map((J)=>typeof J==="string"?J:J.toJSON()):[this.type,...this.#X.map((J)=>J.toJSON())];if(this.isStart()&&!this.type)Z.unshift([]);if(this.isEnd()&&(this===this.#Z||this.#Z.#W&&this.#Y?.type==="!"))Z.push({});return Z}isStart(){if(this.#Z===this)return!0;if(!this.#Y?.isStart())return!1;if(this.#V===0)return!0;let Z=this.#Y;for(let J=0;J<this.#V;J++){let X=Z.#X[J];if(!(X instanceof Z6&&X.type==="!"))return!1}return!0}isEnd(){if(this.#Z===this)return!0;if(this.#Y?.type==="!")return!0;if(!this.#Y?.isEnd())return!1;if(!this.type)return this.#Y?.isEnd();let Z=this.#Y?this.#Y.#X.length:0;return this.#V===Z-1}copyIn(Z){if(typeof Z==="string")this.push(Z);else this.push(Z.clone(this))}clone(Z){let J=new Z6(this.type,Z);for(let X of this.#X)J.copyIn(X);return J}static#F(Z,J,X,$){let Y=!1,Q=!1,K=-1,W=!1;if(J.type===null){let v=X,q="";while(v<Z.length){let F=Z.charAt(v++);if(Y||F==="\\"){Y=!Y,q+=F;continue}if(Q){if(v===K+1){if(F==="^"||F==="!")W=!0}else if(F==="]"&&!(v===K+2&&W))Q=!1;q+=F;continue}else if(F==="["){Q=!0,K=v,W=!1,q+=F;continue}if(!$.noext&&Ii(F)&&Z.charAt(v)==="("){J.push(q),q="";let c=new Z6(F,J);v=Z6.#F(Z,c,v,$),J.push(c);continue}q+=F}return J.push(q),v}let G=X+1,z=new Z6(null,J),V=[],H="";while(G<Z.length){let v=Z.charAt(G++);if(Y||v==="\\"){Y=!Y,H+=v;continue}if(Q){if(G===K+1){if(v==="^"||v==="!")W=!0}else if(v==="]"&&!(G===K+2&&W))Q=!1;H+=v;continue}else if(v==="["){Q=!0,K=G,W=!1,H+=v;continue}if(Ii(v)&&Z.charAt(G)==="("){z.push(H),H="";let q=new Z6(v,z);z.push(q),G=Z6.#F(Z,q,G,$);continue}if(v==="|"){z.push(H),H="",V.push(z),z=new Z6(null,J);continue}if(v===")"){if(H===""&&J.#X.length===0)J.#v=!0;return z.push(H),H="",J.push(...V,z),G}H+=v}return J.type=null,J.#J=void 0,J.#X=[Z.substring(X-1)],G}static fromGlob(Z,J={}){let X=new Z6(null,void 0,J);return Z6.#F(Z,X,0,J),X}toMMPattern(){if(this!==this.#Z)return this.#Z.toMMPattern();let Z=this.toString(),[J,X,$,Y]=this.toRegExpSource();if(!($||this.#J||this.#G.nocase&&!this.#G.nocaseMagicOnly&&Z.toUpperCase()!==Z.toLowerCase()))return X;let K=(this.#G.nocase?"i":"")+(Y?"u":"");return Object.assign(new RegExp(`^${J}$`,K),{_src:J,_glob:Z})}get options(){return this.#G}toRegExpSource(Z){let J=Z??!!this.#G.dot;if(this.#Z===this)this.#Q();if(!this.type){let W=this.isStart()&&this.isEnd(),G=this.#X.map((v)=>{let[q,F,c,w]=typeof v==="string"?Z6.#c(v,this.#J,W):v.toRegExpSource(Z);return this.#J=this.#J||c,this.#$=this.#$||w,q}).join(""),z="";if(this.isStart()){if(typeof this.#X[0]==="string"){if(!(this.#X.length===1&&Lw1.has(this.#X[0]))){let q=Bw1,F=J&&q.has(G.charAt(0))||G.startsWith("\\.")&&q.has(G.charAt(2))||G.startsWith("\\.\\.")&&q.has(G.charAt(4)),c=!J&&!Z&&q.has(G.charAt(0));z=F?jw1:c?RF:""}}}let V="";if(this.isEnd()&&this.#Z.#W&&this.#Y?.type==="!")V="(?:$|\\/)";return[z+G+V,F9(G),this.#J=!!this.#J,this.#$]}let X=this.type==="*"||this.type==="+",$=this.type==="!"?"(?:(?!(?:":"(?:",Y=this.#w(J);if(this.isStart()&&this.isEnd()&&!Y&&this.type!=="!"){let W=this.toString();return this.#X=[W],this.type=null,this.#J=void 0,[W,F9(this.toString()),!1,!1]}let Q=!X||Z||J||!RF?"":this.#w(!0);if(Q===Y)Q="";if(Q)Y=`(?:${Y})(?:${Q})*?`;let K="";if(this.type==="!"&&this.#v)K=(this.isStart()&&!J?RF:"")+bi;else{let W=this.type==="!"?"))"+(this.isStart()&&!J&&!Z?RF:"")+_i+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&Q?")":this.type==="*"&&Q?")?":`)${this.type}`;K=$+Y+W}return[K,F9(Y),this.#J=!!this.#J,this.#$]}#w(Z){return this.#X.map((J)=>{if(typeof J==="string")throw new Error("string type in extglob ast??");let[X,$,Y,Q]=J.toRegExpSource(Z);return this.#$=this.#$||Q,X}).filter((J)=>!(this.isStart()&&this.isEnd())||!!J).join("|")}static#c(Z,J,X=!1){let $=!1,Y="",Q=!1;for(let K=0;K<Z.length;K++){let W=Z.charAt(K);if($){$=!1,Y+=(Dw1.has(W)?"\\":"")+W;continue}if(W==="\\"){if(K===Z.length-1)Y+="\\\\";else $=!0;continue}if(W==="["){let[G,z,V,H]=Ei(Z,K);if(V){Y+=G,Q=Q||z,K+=V-1,J=J||H;continue}}if(W==="*"){if(X&&Z==="*")Y+=bi;else Y+=_i;J=!0;continue}if(W==="?"){Y+=yM,J=!0;continue}Y+=Mw1(W)}return[Y,F9(Z),!!J,Q]}}var Z3=(Z,{windowsPathsNoEscape:J=!1}={})=>{return J?Z.replace(/[?*()[\]]/g,"[$&]"):Z.replace(/[?*()[\]\\]/g,"\\$&")};var b6=(Z,J,X={})=>{if(KG(J),!X.nocomment&&J.charAt(0)==="#")return!1;return new H4(J,X).match(Z)},Rw1=/^\*+([^+@!?\*\[\(]*)$/,Ow1=(Z)=>(J)=>!J.startsWith(".")&&J.endsWith(Z),Nw1=(Z)=>(J)=>J.endsWith(Z),Pw1=(Z)=>{return Z=Z.toLowerCase(),(J)=>!J.startsWith(".")&&J.toLowerCase().endsWith(Z)},Tw1=(Z)=>{return Z=Z.toLowerCase(),(J)=>J.toLowerCase().endsWith(Z)},Cw1=/^\*+\.\*+$/,fw1=(Z)=>!Z.startsWith(".")&&Z.includes("."),kw1=(Z)=>Z!=="."&&Z!==".."&&Z.includes("."),Ew1=/^\.\*+$/,Iw1=(Z)=>Z!=="."&&Z!==".."&&Z.startsWith("."),_w1=/^\*+$/,bw1=(Z)=>Z.length!==0&&!Z.startsWith("."),hw1=(Z)=>Z.length!==0&&Z!=="."&&Z!=="..",Sw1=/^\?+([^+@!?\*\[\(]*)?$/,Aw1=([Z,J=""])=>{let X=mi([Z]);if(!J)return X;return J=J.toLowerCase(),($)=>X($)&&$.toLowerCase().endsWith(J)},mw1=([Z,J=""])=>{let X=ui([Z]);if(!J)return X;return J=J.toLowerCase(),($)=>X($)&&$.toLowerCase().endsWith(J)},uw1=([Z,J=""])=>{let X=ui([Z]);return!J?X:($)=>X($)&&$.endsWith(J)},lw1=([Z,J=""])=>{let X=mi([Z]);return!J?X:($)=>X($)&&$.endsWith(J)},mi=([Z])=>{let J=Z.length;return(X)=>X.length===J&&!X.startsWith(".")},ui=([Z])=>{let J=Z.length;return(X)=>X.length===J&&X!=="."&&X!==".."},li=typeof process==="object"&&process?typeof process.env==="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",hi={win32:{sep:"\\"},posix:{sep:"/"}},yw1=li==="win32"?hi.win32.sep:hi.posix.sep;b6.sep=yw1;var J6=Symbol("globstar **");b6.GLOBSTAR=J6;var pw1="[^/]",iw1=pw1+"*?",gw1="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",dw1="(?:(?!(?:\\/|^)\\.).)*?",aw1=(Z,J={})=>(X)=>b6(X,Z,J);b6.filter=aw1;var v4=(Z,J={})=>Object.assign({},Z,J),nw1=(Z)=>{if(!Z||typeof Z!=="object"||!Object.keys(Z).length)return b6;let J=b6;return Object.assign(($,Y,Q={})=>J($,Y,v4(Z,Q)),{Minimatch:class $ extends J.Minimatch{constructor(Y,Q={}){super(Y,v4(Z,Q))}static defaults(Y){return J.defaults(v4(Z,Y)).Minimatch}},AST:class $ extends J.AST{constructor(Y,Q,K={}){super(Y,Q,v4(Z,K))}static fromGlob(Y,Q={}){return J.AST.fromGlob(Y,v4(Z,Q))}},unescape:($,Y={})=>J.unescape($,v4(Z,Y)),escape:($,Y={})=>J.escape($,v4(Z,Y)),filter:($,Y={})=>J.filter($,v4(Z,Y)),defaults:($)=>J.defaults(v4(Z,$)),makeRe:($,Y={})=>J.makeRe($,v4(Z,Y)),braceExpand:($,Y={})=>J.braceExpand($,v4(Z,Y)),match:($,Y,Q={})=>J.match($,Y,v4(Z,Q)),sep:J.sep,GLOBSTAR:J6})};b6.defaults=nw1;var yi=(Z,J={})=>{if(KG(Z),J.nobrace||!/\{(?:(?!\{).)*\}/.test(Z))return[Z];return Ai.default(Z)};b6.braceExpand=yi;var sw1=(Z,J={})=>new H4(Z,J).makeRe();b6.makeRe=sw1;var ow1=(Z,J,X={})=>{let $=new H4(J,X);if(Z=Z.filter((Y)=>$.match(Y)),$.options.nonull&&!Z.length)Z.push(J);return Z};b6.match=ow1;var Si=/[?*]|[+@!]\(.*?\)|\[|\]/,rw1=(Z)=>Z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");class H4{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(Z,J={}){if(KG(Z),J=J||{},this.options=J,this.pattern=Z,this.platform=J.platform||li,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!J.windowsPathsNoEscape||J.allowWindowsEscape===!1,this.windowsPathsNoEscape)this.pattern=this.pattern.replace(/\\/g,"/");this.preserveMultipleSlashes=!!J.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!J.nonegate,this.comment=!1,this.empty=!1,this.partial=!!J.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=J.windowsNoMagicRoot!==void 0?J.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let Z of this.set)for(let J of Z)if(typeof J!=="string")return!0;return!1}debug(...Z){}make(){let Z=this.pattern,J=this.options;if(!J.nocomment&&Z.charAt(0)==="#"){this.comment=!0;return}if(!Z){this.empty=!0;return}if(this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],J.debug)this.debug=(...Y)=>console.error(...Y);this.debug(this.pattern,this.globSet);let X=this.globSet.map((Y)=>this.slashSplit(Y));this.globParts=this.preprocess(X),this.debug(this.pattern,this.globParts);let $=this.globParts.map((Y,Q,K)=>{if(this.isWindows&&this.windowsNoMagicRoot){let W=Y[0]===""&&Y[1]===""&&(Y[2]==="?"||!Si.test(Y[2]))&&!Si.test(Y[3]),G=/^[a-z]:/i.test(Y[0]);if(W)return[...Y.slice(0,4),...Y.slice(4).map((z)=>this.parse(z))];else if(G)return[Y[0],...Y.slice(1).map((z)=>this.parse(z))]}return Y.map((W)=>this.parse(W))});if(this.debug(this.pattern,$),this.set=$.filter((Y)=>Y.indexOf(!1)===-1),this.isWindows)for(let Y=0;Y<this.set.length;Y++){let Q=this.set[Y];if(Q[0]===""&&Q[1]===""&&this.globParts[Y][2]==="?"&&typeof Q[3]==="string"&&/^[a-z]:$/i.test(Q[3]))Q[2]="?"}this.debug(this.pattern,this.set)}preprocess(Z){if(this.options.noglobstar){for(let X=0;X<Z.length;X++)for(let $=0;$<Z[X].length;$++)if(Z[X][$]==="**")Z[X][$]="*"}let{optimizationLevel:J=1}=this.options;if(J>=2)Z=this.firstPhasePreProcess(Z),Z=this.secondPhasePreProcess(Z);else if(J>=1)Z=this.levelOneOptimize(Z);else Z=this.adjascentGlobstarOptimize(Z);return Z}adjascentGlobstarOptimize(Z){return Z.map((J)=>{let X=-1;while((X=J.indexOf("**",X+1))!==-1){let $=X;while(J[$+1]==="**")$++;if($!==X)J.splice(X,$-X)}return J})}levelOneOptimize(Z){return Z.map((J)=>{return J=J.reduce((X,$)=>{let Y=X[X.length-1];if($==="**"&&Y==="**")return X;if($===".."){if(Y&&Y!==".."&&Y!=="."&&Y!=="**")return X.pop(),X}return X.push($),X},[]),J.length===0?[""]:J})}levelTwoFileOptimize(Z){if(!Array.isArray(Z))Z=this.slashSplit(Z);let J=!1;do{if(J=!1,!this.preserveMultipleSlashes){for(let $=1;$<Z.length-1;$++){let Y=Z[$];if($===1&&Y===""&&Z[0]==="")continue;if(Y==="."||Y==="")J=!0,Z.splice($,1),$--}if(Z[0]==="."&&Z.length===2&&(Z[1]==="."||Z[1]===""))J=!0,Z.pop()}let X=0;while((X=Z.indexOf("..",X+1))!==-1){let $=Z[X-1];if($&&$!=="."&&$!==".."&&$!=="**")J=!0,Z.splice(X-1,2),X-=2}}while(J);return Z.length===0?[""]:Z}firstPhasePreProcess(Z){let J=!1;do{J=!1;for(let X of Z){let $=-1;while(($=X.indexOf("**",$+1))!==-1){let Q=$;while(X[Q+1]==="**")Q++;if(Q>$)X.splice($+1,Q-$);let K=X[$+1],W=X[$+2],G=X[$+3];if(K!=="..")continue;if(!W||W==="."||W===".."||!G||G==="."||G==="..")continue;J=!0,X.splice($,1);let z=X.slice(0);z[$]="**",Z.push(z),$--}if(!this.preserveMultipleSlashes){for(let Q=1;Q<X.length-1;Q++){let K=X[Q];if(Q===1&&K===""&&X[0]==="")continue;if(K==="."||K==="")J=!0,X.splice(Q,1),Q--}if(X[0]==="."&&X.length===2&&(X[1]==="."||X[1]===""))J=!0,X.pop()}let Y=0;while((Y=X.indexOf("..",Y+1))!==-1){let Q=X[Y-1];if(Q&&Q!=="."&&Q!==".."&&Q!=="**"){J=!0;let W=Y===1&&X[Y+1]==="**"?["."]:[];if(X.splice(Y-1,2,...W),X.length===0)X.push("");Y-=2}}}}while(J);return Z}secondPhasePreProcess(Z){for(let J=0;J<Z.length-1;J++)for(let X=J+1;X<Z.length;X++){let $=this.partsMatch(Z[J],Z[X],!this.preserveMultipleSlashes);if($){Z[J]=[],Z[X]=$;break}}return Z.filter((J)=>J.length)}partsMatch(Z,J,X=!1){let $=0,Y=0,Q=[],K="";while($<Z.length&&Y<J.length)if(Z[$]===J[Y])Q.push(K==="b"?J[Y]:Z[$]),$++,Y++;else if(X&&Z[$]==="**"&&J[Y]===Z[$+1])Q.push(Z[$]),$++;else if(X&&J[Y]==="**"&&Z[$]===J[Y+1])Q.push(J[Y]),Y++;else if(Z[$]==="*"&&J[Y]&&(this.options.dot||!J[Y].startsWith("."))&&J[Y]!=="**"){if(K==="b")return!1;K="a",Q.push(Z[$]),$++,Y++}else if(J[Y]==="*"&&Z[$]&&(this.options.dot||!Z[$].startsWith("."))&&Z[$]!=="**"){if(K==="a")return!1;K="b",Q.push(J[Y]),$++,Y++}else return!1;return Z.length===J.length&&Q}parseNegate(){if(this.nonegate)return;let Z=this.pattern,J=!1,X=0;for(let $=0;$<Z.length&&Z.charAt($)==="!";$++)J=!J,X++;if(X)this.pattern=Z.slice(X);this.negate=J}matchOne(Z,J,X=!1){let $=this.options;if(this.isWindows){let F=typeof Z[0]==="string"&&/^[a-z]:$/i.test(Z[0]),c=!F&&Z[0]===""&&Z[1]===""&&Z[2]==="?"&&/^[a-z]:$/i.test(Z[3]),w=typeof J[0]==="string"&&/^[a-z]:$/i.test(J[0]),x=!w&&J[0]===""&&J[1]===""&&J[2]==="?"&&typeof J[3]==="string"&&/^[a-z]:$/i.test(J[3]),j=c?3:F?0:void 0,B=x?3:w?0:void 0;if(typeof j==="number"&&typeof B==="number"){let[L,R]=[Z[j],J[B]];if(L.toLowerCase()===R.toLowerCase()){if(J[B]=L,B>j)J=J.slice(B);else if(j>B)Z=Z.slice(j)}}}let{optimizationLevel:Y=1}=this.options;if(Y>=2)Z=this.levelTwoFileOptimize(Z);this.debug("matchOne",this,{file:Z,pattern:J}),this.debug("matchOne",Z.length,J.length);for(var Q=0,K=0,W=Z.length,G=J.length;Q<W&&K<G;Q++,K++){this.debug("matchOne loop");var z=J[K],V=Z[Q];if(this.debug(J,z,V),z===!1)return!1;if(z===J6){this.debug("GLOBSTAR",[J,z,V]);var H=Q,v=K+1;if(v===G){this.debug("** at the end");for(;Q<W;Q++)if(Z[Q]==="."||Z[Q]===".."||!$.dot&&Z[Q].charAt(0)===".")return!1;return!0}while(H<W){var q=Z[H];if(this.debug(`
398
398
  globstar while`,Z,H,J,v,q),this.matchOne(Z.slice(H),J.slice(v),X))return this.debug("globstar found match!",H,W,q),!0;else{if(q==="."||q===".."||!$.dot&&q.charAt(0)==="."){this.debug("dot detected!",Z,H,J,v);break}this.debug("globstar swallow a segment, and continue"),H++}}if(X){if(this.debug(`
399
399
  >>> no match, partial?`,Z,H,J,v),H===W)return!0}return!1}let F;if(typeof z==="string")F=V===z,this.debug("string match",z,V,F);else F=z.test(V),this.debug("pattern match",z,V,F);if(!F)return!1}if(Q===W&&K===G)return!0;else if(Q===W)return X;else if(K===G)return Q===W-1&&Z[Q]==="";else throw new Error("wtf?")}braceExpand(){return yi(this.pattern,this.options)}parse(Z){KG(Z);let J=this.options;if(Z==="**")return J6;if(Z==="")return"";let X,$=null;if(X=Z.match(_w1))$=J.dot?hw1:bw1;else if(X=Z.match(Rw1))$=(J.nocase?J.dot?Tw1:Pw1:J.dot?Nw1:Ow1)(X[1]);else if(X=Z.match(Sw1))$=(J.nocase?J.dot?mw1:Aw1:J.dot?uw1:lw1)(X);else if(X=Z.match(Cw1))$=J.dot?kw1:fw1;else if(X=Z.match(Ew1))$=Iw1;let Y=Z6.fromGlob(Z,this.options).toMMPattern();if($&&typeof Y==="object")Reflect.defineProperty(Y,"test",{value:$});return Y}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let Z=this.set;if(!Z.length)return this.regexp=!1,this.regexp;let J=this.options,X=J.noglobstar?iw1:J.dot?gw1:dw1,$=new Set(J.nocase?["i"]:[]),Y=Z.map((W)=>{let G=W.map((z)=>{if(z instanceof RegExp)for(let V of z.flags.split(""))$.add(V);return typeof z==="string"?rw1(z):z===J6?J6:z._src});return G.forEach((z,V)=>{let H=G[V+1],v=G[V-1];if(z!==J6||v===J6)return;if(v===void 0)if(H!==void 0&&H!==J6)G[V+1]="(?:\\/|"+X+"\\/)?"+H;else G[V]=X;else if(H===void 0)G[V-1]=v+"(?:\\/|"+X+")?";else if(H!==J6)G[V-1]=v+"(?:\\/|\\/"+X+"\\/)"+H,G[V+1]=J6}),G.filter((z)=>z!==J6).join("/")}).join("|"),[Q,K]=Z.length>1?["(?:",")"]:["",""];if(Y="^"+Q+Y+K+"$",this.negate)Y="^(?!"+Y+").+$";try{this.regexp=new RegExp(Y,[...$].join(""))}catch(W){this.regexp=!1}return this.regexp}slashSplit(Z){if(this.preserveMultipleSlashes)return Z.split("/");else if(this.isWindows&&/^\/\/[^\/]+/.test(Z))return["",...Z.split(/\/+/)];else return Z.split(/\/+/)}match(Z,J=this.partial){if(this.debug("match",Z,this.pattern),this.comment)return!1;if(this.empty)return Z==="";if(Z==="/"&&J)return!0;let X=this.options;if(this.isWindows)Z=Z.split("\\").join("/");let $=this.slashSplit(Z);this.debug(this.pattern,"split",$);let Y=this.set;this.debug(this.pattern,"set",Y);let Q=$[$.length-1];if(!Q)for(let K=$.length-2;!Q&&K>=0;K--)Q=$[K];for(let K=0;K<Y.length;K++){let W=Y[K],G=$;if(X.matchBase&&W.length===1)G=[Q];if(this.matchOne(G,W,J)){if(X.flipNegate)return!0;return!this.negate}}if(X.flipNegate)return!1;return this.negate}static defaults(Z){return b6.defaults(Z).Minimatch}}b6.AST=Z6;b6.Minimatch=H4;b6.escape=Z3;b6.unescape=F9;import{fileURLToPath as Cx1}from"node:url";var J3=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,ii=new Set,pM=typeof process==="object"&&!!process?process:{},gi=(Z,J,X,$)=>{typeof pM.emitWarning==="function"?pM.emitWarning(Z,J,X,$):console.error(`[${X}] ${J}: ${Z}`)},OF=globalThis.AbortController,pi=globalThis.AbortSignal;if(typeof OF==="undefined"){pi=class X{onabort;_onabort=[];reason;aborted=!1;addEventListener($,Y){this._onabort.push(Y)}},OF=class X{constructor(){J()}signal=new pi;abort($){if(this.signal.aborted)return;this.signal.reason=$,this.signal.aborted=!0;for(let Y of this.signal._onabort)Y($);this.signal.onabort?.($)}};let Z=pM.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",J=()=>{if(!Z)return;Z=!1,gi("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",J)}}var tw1=(Z)=>!ii.has(Z),JO6=Symbol("type"),_J=(Z)=>Z&&Z===Math.floor(Z)&&Z>0&&isFinite(Z),di=(Z)=>!_J(Z)?null:Z<=Math.pow(2,8)?Uint8Array:Z<=Math.pow(2,16)?Uint16Array:Z<=Math.pow(2,32)?Uint32Array:Z<=Number.MAX_SAFE_INTEGER?GG:null;class GG extends Array{constructor(Z){super(Z);this.fill(0)}}class X3{heap;length;static#Z=!1;static create(Z){let J=di(Z);if(!J)return[];X3.#Z=!0;let X=new X3(Z,J);return X3.#Z=!1,X}constructor(Z,J){if(!X3.#Z)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new J(Z),this.length=0}push(Z){this.heap[this.length++]=Z}pop(){return this.heap[--this.length]}}class zG{#Z;#J;#$;#X;#Y;#V;#H;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#W;#G;#z;#v;#Q;#F;#w;#c;#U;#P;#j;#T;#D;#L;#B;#O;#x;#f;static unsafeExposeInternals(Z){return{starts:Z.#D,ttls:Z.#L,sizes:Z.#T,keyMap:Z.#z,keyList:Z.#v,valList:Z.#Q,next:Z.#F,prev:Z.#w,get head(){return Z.#c},get tail(){return Z.#U},free:Z.#P,isBackgroundFetch:(J)=>Z.#q(J),backgroundFetch:(J,X,$,Y)=>Z.#b(J,X,$,Y),moveToTail:(J)=>Z.#A(J),indexes:(J)=>Z.#N(J),rindexes:(J)=>Z.#C(J),isStale:(J)=>Z.#R(J)}}get max(){return this.#Z}get maxSize(){return this.#J}get calculatedSize(){return this.#G}get size(){return this.#W}get fetchMethod(){return this.#V}get memoMethod(){return this.#H}get dispose(){return this.#$}get onInsert(){return this.#X}get disposeAfter(){return this.#Y}constructor(Z){let{max:J=0,ttl:X,ttlResolution:$=1,ttlAutopurge:Y,updateAgeOnGet:Q,updateAgeOnHas:K,allowStale:W,dispose:G,onInsert:z,disposeAfter:V,noDisposeOnSet:H,noUpdateTTL:v,maxSize:q=0,maxEntrySize:F=0,sizeCalculation:c,fetchMethod:w,memoMethod:x,noDeleteOnFetchRejection:j,noDeleteOnStaleGet:B,allowStaleOnFetchRejection:L,allowStaleOnFetchAbort:R,ignoreFetchAbort:M}=Z;if(J!==0&&!_J(J))throw new TypeError("max option must be a nonnegative integer");let O=J?di(J):Array;if(!O)throw new Error("invalid max value: "+J);if(this.#Z=J,this.#J=q,this.maxEntrySize=F||this.#J,this.sizeCalculation=c,this.sizeCalculation){if(!this.#J&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!=="function")throw new TypeError("sizeCalculation set to non-function")}if(x!==void 0&&typeof x!=="function")throw new TypeError("memoMethod must be a function if defined");if(this.#H=x,w!==void 0&&typeof w!=="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#V=w,this.#O=!!w,this.#z=new Map,this.#v=new Array(J).fill(void 0),this.#Q=new Array(J).fill(void 0),this.#F=new O(J),this.#w=new O(J),this.#c=0,this.#U=0,this.#P=X3.create(J),this.#W=0,this.#G=0,typeof G==="function")this.#$=G;if(typeof z==="function")this.#X=z;if(typeof V==="function")this.#Y=V,this.#j=[];else this.#Y=void 0,this.#j=void 0;if(this.#B=!!this.#$,this.#f=!!this.#X,this.#x=!!this.#Y,this.noDisposeOnSet=!!H,this.noUpdateTTL=!!v,this.noDeleteOnFetchRejection=!!j,this.allowStaleOnFetchRejection=!!L,this.allowStaleOnFetchAbort=!!R,this.ignoreFetchAbort=!!M,this.maxEntrySize!==0){if(this.#J!==0){if(!_J(this.#J))throw new TypeError("maxSize must be a positive integer if specified")}if(!_J(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#u()}if(this.allowStale=!!W,this.noDeleteOnStaleGet=!!B,this.updateAgeOnGet=!!Q,this.updateAgeOnHas=!!K,this.ttlResolution=_J($)||$===0?$:1,this.ttlAutopurge=!!Y,this.ttl=X||0,this.ttl){if(!_J(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#K()}if(this.#Z===0&&this.ttl===0&&this.#J===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#Z&&!this.#J){if(tw1("LRU_CACHE_UNBOUNDED"))ii.add("LRU_CACHE_UNBOUNDED"),gi("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",zG)}}getRemainingTTL(Z){return this.#z.has(Z)?1/0:0}#K(){let Z=new GG(this.#Z),J=new GG(this.#Z);this.#L=Z,this.#D=J,this.#k=(Y,Q,K=J3.now())=>{if(J[Y]=Q!==0?K:0,Z[Y]=Q,Q!==0&&this.ttlAutopurge){let W=setTimeout(()=>{if(this.#R(Y))this.#E(this.#v[Y],"expire")},Q+1);if(W.unref)W.unref()}},this.#I=(Y)=>{J[Y]=Z[Y]!==0?J3.now():0},this.#M=(Y,Q)=>{if(Z[Q]){let K=Z[Q],W=J[Q];if(!K||!W)return;Y.ttl=K,Y.start=W,Y.now=X||$();let G=Y.now-W;Y.remainingTTL=K-G}};let X=0,$=()=>{let Y=J3.now();if(this.ttlResolution>0){X=Y;let Q=setTimeout(()=>X=0,this.ttlResolution);if(Q.unref)Q.unref()}return Y};this.getRemainingTTL=(Y)=>{let Q=this.#z.get(Y);if(Q===void 0)return 0;let K=Z[Q],W=J[Q];if(!K||!W)return 1/0;let G=(X||$())-W;return K-G},this.#R=(Y)=>{let Q=J[Y],K=Z[Y];return!!K&&!!Q&&(X||$())-Q>K}}#I=()=>{};#M=()=>{};#k=()=>{};#R=()=>!1;#u(){let Z=new GG(this.#Z);this.#G=0,this.#T=Z,this.#_=(J)=>{this.#G-=Z[J],Z[J]=0},this.#l=(J,X,$,Y)=>{if(this.#q(X))return 0;if(!_J($))if(Y){if(typeof Y!=="function")throw new TypeError("sizeCalculation must be a function");if($=Y(X,J),!_J($))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return $},this.#h=(J,X,$)=>{if(Z[J]=X,this.#J){let Y=this.#J-Z[J];while(this.#G>Y)this.#S(!0)}if(this.#G+=Z[J],$)$.entrySize=X,$.totalCalculatedSize=this.#G}}#_=(Z)=>{};#h=(Z,J,X)=>{};#l=(Z,J,X,$)=>{if(X||$)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#N({allowStale:Z=this.allowStale}={}){if(this.#W)for(let J=this.#U;;){if(!this.#y(J))break;if(Z||!this.#R(J))yield J;if(J===this.#c)break;else J=this.#w[J]}}*#C({allowStale:Z=this.allowStale}={}){if(this.#W)for(let J=this.#c;;){if(!this.#y(J))break;if(Z||!this.#R(J))yield J;if(J===this.#U)break;else J=this.#F[J]}}#y(Z){return Z!==void 0&&this.#z.get(this.#v[Z])===Z}*entries(){for(let Z of this.#N())if(this.#Q[Z]!==void 0&&this.#v[Z]!==void 0&&!this.#q(this.#Q[Z]))yield[this.#v[Z],this.#Q[Z]]}*rentries(){for(let Z of this.#C())if(this.#Q[Z]!==void 0&&this.#v[Z]!==void 0&&!this.#q(this.#Q[Z]))yield[this.#v[Z],this.#Q[Z]]}*keys(){for(let Z of this.#N()){let J=this.#v[Z];if(J!==void 0&&!this.#q(this.#Q[Z]))yield J}}*rkeys(){for(let Z of this.#C()){let J=this.#v[Z];if(J!==void 0&&!this.#q(this.#Q[Z]))yield J}}*values(){for(let Z of this.#N())if(this.#Q[Z]!==void 0&&!this.#q(this.#Q[Z]))yield this.#Q[Z]}*rvalues(){for(let Z of this.#C())if(this.#Q[Z]!==void 0&&!this.#q(this.#Q[Z]))yield this.#Q[Z]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(Z,J={}){for(let X of this.#N()){let $=this.#Q[X],Y=this.#q($)?$.__staleWhileFetching:$;if(Y===void 0)continue;if(Z(Y,this.#v[X],this))return this.get(this.#v[X],J)}}forEach(Z,J=this){for(let X of this.#N()){let $=this.#Q[X],Y=this.#q($)?$.__staleWhileFetching:$;if(Y===void 0)continue;Z.call(J,Y,this.#v[X],this)}}rforEach(Z,J=this){for(let X of this.#C()){let $=this.#Q[X],Y=this.#q($)?$.__staleWhileFetching:$;if(Y===void 0)continue;Z.call(J,Y,this.#v[X],this)}}purgeStale(){let Z=!1;for(let J of this.#C({allowStale:!0}))if(this.#R(J))this.#E(this.#v[J],"expire"),Z=!0;return Z}info(Z){let J=this.#z.get(Z);if(J===void 0)return;let X=this.#Q[J],$=this.#q(X)?X.__staleWhileFetching:X;if($===void 0)return;let Y={value:$};if(this.#L&&this.#D){let Q=this.#L[J],K=this.#D[J];if(Q&&K){let W=Q-(J3.now()-K);Y.ttl=W,Y.start=Date.now()}}if(this.#T)Y.size=this.#T[J];return Y}dump(){let Z=[];for(let J of this.#N({allowStale:!0})){let X=this.#v[J],$=this.#Q[J],Y=this.#q($)?$.__staleWhileFetching:$;if(Y===void 0||X===void 0)continue;let Q={value:Y};if(this.#L&&this.#D){Q.ttl=this.#L[J];let K=J3.now()-this.#D[J];Q.start=Math.floor(Date.now()-K)}if(this.#T)Q.size=this.#T[J];Z.unshift([X,Q])}return Z}load(Z){this.clear();for(let[J,X]of Z){if(X.start){let $=Date.now()-X.start;X.start=J3.now()-$}this.set(J,X.value,X)}}set(Z,J,X={}){if(J===void 0)return this.delete(Z),this;let{ttl:$=this.ttl,start:Y,noDisposeOnSet:Q=this.noDisposeOnSet,sizeCalculation:K=this.sizeCalculation,status:W}=X,{noUpdateTTL:G=this.noUpdateTTL}=X,z=this.#l(Z,J,X.size||0,K);if(this.maxEntrySize&&z>this.maxEntrySize){if(W)W.set="miss",W.maxEntrySizeExceeded=!0;return this.#E(Z,"set"),this}let V=this.#W===0?void 0:this.#z.get(Z);if(V===void 0){if(V=this.#W===0?this.#U:this.#P.length!==0?this.#P.pop():this.#W===this.#Z?this.#S(!1):this.#W,this.#v[V]=Z,this.#Q[V]=J,this.#z.set(Z,V),this.#F[this.#U]=V,this.#w[V]=this.#U,this.#U=V,this.#W++,this.#h(V,z,W),W)W.set="add";if(G=!1,this.#f)this.#X?.(J,Z,"add")}else{this.#A(V);let H=this.#Q[V];if(J!==H){if(this.#O&&this.#q(H)){H.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:v}=H;if(v!==void 0&&!Q){if(this.#B)this.#$?.(v,Z,"set");if(this.#x)this.#j?.push([v,Z,"set"])}}else if(!Q){if(this.#B)this.#$?.(H,Z,"set");if(this.#x)this.#j?.push([H,Z,"set"])}if(this.#_(V),this.#h(V,z,W),this.#Q[V]=J,W){W.set="replace";let v=H&&this.#q(H)?H.__staleWhileFetching:H;if(v!==void 0)W.oldValue=v}}else if(W)W.set="update";if(this.#f)this.onInsert?.(J,Z,J===H?"update":"replace")}if($!==0&&!this.#L)this.#K();if(this.#L){if(!G)this.#k(V,$,Y);if(W)this.#M(W,V)}if(!Q&&this.#x&&this.#j){let H=this.#j,v;while(v=H?.shift())this.#Y?.(...v)}return this}pop(){try{while(this.#W){let Z=this.#Q[this.#c];if(this.#S(!0),this.#q(Z)){if(Z.__staleWhileFetching)return Z.__staleWhileFetching}else if(Z!==void 0)return Z}}finally{if(this.#x&&this.#j){let Z=this.#j,J;while(J=Z?.shift())this.#Y?.(...J)}}}#S(Z){let J=this.#c,X=this.#v[J],$=this.#Q[J];if(this.#O&&this.#q($))$.__abortController.abort(new Error("evicted"));else if(this.#B||this.#x){if(this.#B)this.#$?.($,X,"evict");if(this.#x)this.#j?.push([$,X,"evict"])}if(this.#_(J),Z)this.#v[J]=void 0,this.#Q[J]=void 0,this.#P.push(J);if(this.#W===1)this.#c=this.#U=0,this.#P.length=0;else this.#c=this.#F[J];return this.#z.delete(X),this.#W--,J}has(Z,J={}){let{updateAgeOnHas:X=this.updateAgeOnHas,status:$}=J,Y=this.#z.get(Z);if(Y!==void 0){let Q=this.#Q[Y];if(this.#q(Q)&&Q.__staleWhileFetching===void 0)return!1;if(!this.#R(Y)){if(X)this.#I(Y);if($)$.has="hit",this.#M($,Y);return!0}else if($)$.has="stale",this.#M($,Y)}else if($)$.has="miss";return!1}peek(Z,J={}){let{allowStale:X=this.allowStale}=J,$=this.#z.get(Z);if($===void 0||!X&&this.#R($))return;let Y=this.#Q[$];return this.#q(Y)?Y.__staleWhileFetching:Y}#b(Z,J,X,$){let Y=J===void 0?void 0:this.#Q[J];if(this.#q(Y))return Y;let Q=new OF,{signal:K}=X;K?.addEventListener("abort",()=>Q.abort(K.reason),{signal:Q.signal});let W={signal:Q.signal,options:X,context:$},G=(F,c=!1)=>{let{aborted:w}=Q.signal,x=X.ignoreFetchAbort&&F!==void 0;if(X.status)if(w&&!c){if(X.status.fetchAborted=!0,X.status.fetchError=Q.signal.reason,x)X.status.fetchAbortIgnored=!0}else X.status.fetchResolved=!0;if(w&&!x&&!c)return V(Q.signal.reason);let j=v;if(this.#Q[J]===v)if(F===void 0)if(j.__staleWhileFetching)this.#Q[J]=j.__staleWhileFetching;else this.#E(Z,"fetch");else{if(X.status)X.status.fetchUpdated=!0;this.set(Z,F,W.options)}return F},z=(F)=>{if(X.status)X.status.fetchRejected=!0,X.status.fetchError=F;return V(F)},V=(F)=>{let{aborted:c}=Q.signal,w=c&&X.allowStaleOnFetchAbort,x=w||X.allowStaleOnFetchRejection,j=x||X.noDeleteOnFetchRejection,B=v;if(this.#Q[J]===v){if(!j||B.__staleWhileFetching===void 0)this.#E(Z,"fetch");else if(!w)this.#Q[J]=B.__staleWhileFetching}if(x){if(X.status&&B.__staleWhileFetching!==void 0)X.status.returnedStale=!0;return B.__staleWhileFetching}else if(B.__returned===B)throw F},H=(F,c)=>{let w=this.#V?.(Z,Y,W);if(w&&w instanceof Promise)w.then((x)=>F(x===void 0?void 0:x),c);Q.signal.addEventListener("abort",()=>{if(!X.ignoreFetchAbort||X.allowStaleOnFetchAbort){if(F(void 0),X.allowStaleOnFetchAbort)F=(x)=>G(x,!0)}})};if(X.status)X.status.fetchDispatched=!0;let v=new Promise(H).then(G,z),q=Object.assign(v,{__abortController:Q,__staleWhileFetching:Y,__returned:void 0});if(J===void 0)this.set(Z,q,{...W.options,status:void 0}),J=this.#z.get(Z);else this.#Q[J]=q;return q}#q(Z){if(!this.#O)return!1;let J=Z;return!!J&&J instanceof Promise&&J.hasOwnProperty("__staleWhileFetching")&&J.__abortController instanceof OF}async fetch(Z,J={}){let{allowStale:X=this.allowStale,updateAgeOnGet:$=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,ttl:Q=this.ttl,noDisposeOnSet:K=this.noDisposeOnSet,size:W=0,sizeCalculation:G=this.sizeCalculation,noUpdateTTL:z=this.noUpdateTTL,noDeleteOnFetchRejection:V=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:H=this.allowStaleOnFetchRejection,ignoreFetchAbort:v=this.ignoreFetchAbort,allowStaleOnFetchAbort:q=this.allowStaleOnFetchAbort,context:F,forceRefresh:c=!1,status:w,signal:x}=J;if(!this.#O){if(w)w.fetch="get";return this.get(Z,{allowStale:X,updateAgeOnGet:$,noDeleteOnStaleGet:Y,status:w})}let j={allowStale:X,updateAgeOnGet:$,noDeleteOnStaleGet:Y,ttl:Q,noDisposeOnSet:K,size:W,sizeCalculation:G,noUpdateTTL:z,noDeleteOnFetchRejection:V,allowStaleOnFetchRejection:H,allowStaleOnFetchAbort:q,ignoreFetchAbort:v,status:w,signal:x},B=this.#z.get(Z);if(B===void 0){if(w)w.fetch="miss";let L=this.#b(Z,B,j,F);return L.__returned=L}else{let L=this.#Q[B];if(this.#q(L)){let N=X&&L.__staleWhileFetching!==void 0;if(w){if(w.fetch="inflight",N)w.returnedStale=!0}return N?L.__staleWhileFetching:L.__returned=L}let R=this.#R(B);if(!c&&!R){if(w)w.fetch="hit";if(this.#A(B),$)this.#I(B);if(w)this.#M(w,B);return L}let M=this.#b(Z,B,j,F),P=M.__staleWhileFetching!==void 0&&X;if(w){if(w.fetch=R?"stale":"refresh",P&&R)w.returnedStale=!0}return P?M.__staleWhileFetching:M.__returned=M}}async forceFetch(Z,J={}){let X=await this.fetch(Z,J);if(X===void 0)throw new Error("fetch() returned undefined");return X}memo(Z,J={}){let X=this.#H;if(!X)throw new Error("no memoMethod provided to constructor");let{context:$,forceRefresh:Y,...Q}=J,K=this.get(Z,Q);if(!Y&&K!==void 0)return K;let W=X(Z,K,{options:Q,context:$});return this.set(Z,W,Q),W}get(Z,J={}){let{allowStale:X=this.allowStale,updateAgeOnGet:$=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,status:Q}=J,K=this.#z.get(Z);if(K!==void 0){let W=this.#Q[K],G=this.#q(W);if(Q)this.#M(Q,K);if(this.#R(K)){if(Q)Q.get="stale";if(!G){if(!Y)this.#E(Z,"expire");if(Q&&X)Q.returnedStale=!0;return X?W:void 0}else{if(Q&&X&&W.__staleWhileFetching!==void 0)Q.returnedStale=!0;return X?W.__staleWhileFetching:void 0}}else{if(Q)Q.get="hit";if(G)return W.__staleWhileFetching;if(this.#A(K),$)this.#I(K);return W}}else if(Q)Q.get="miss"}#p(Z,J){this.#w[J]=Z,this.#F[Z]=J}#A(Z){if(Z!==this.#U){if(Z===this.#c)this.#c=this.#F[Z];else this.#p(this.#w[Z],this.#F[Z]);this.#p(this.#U,Z),this.#U=Z}}delete(Z){return this.#E(Z,"delete")}#E(Z,J){let X=!1;if(this.#W!==0){let $=this.#z.get(Z);if($!==void 0)if(X=!0,this.#W===1)this.#m(J);else{this.#_($);let Y=this.#Q[$];if(this.#q(Y))Y.__abortController.abort(new Error("deleted"));else if(this.#B||this.#x){if(this.#B)this.#$?.(Y,Z,J);if(this.#x)this.#j?.push([Y,Z,J])}if(this.#z.delete(Z),this.#v[$]=void 0,this.#Q[$]=void 0,$===this.#U)this.#U=this.#w[$];else if($===this.#c)this.#c=this.#F[$];else{let Q=this.#w[$];this.#F[Q]=this.#F[$];let K=this.#F[$];this.#w[K]=this.#w[$]}this.#W--,this.#P.push($)}}if(this.#x&&this.#j?.length){let $=this.#j,Y;while(Y=$?.shift())this.#Y?.(...Y)}return X}clear(){return this.#m("delete")}#m(Z){for(let J of this.#C({allowStale:!0})){let X=this.#Q[J];if(this.#q(X))X.__abortController.abort(new Error("deleted"));else{let $=this.#v[J];if(this.#B)this.#$?.(X,$,Z);if(this.#x)this.#j?.push([X,$,Z])}}if(this.#z.clear(),this.#Q.fill(void 0),this.#v.fill(void 0),this.#L&&this.#D)this.#L.fill(0),this.#D.fill(0);if(this.#T)this.#T.fill(0);if(this.#c=0,this.#U=0,this.#P.length=0,this.#G=0,this.#W=0,this.#x&&this.#j){let J=this.#j,X;while(X=J?.shift())this.#Y?.(...X)}}}import{posix as zx1,win32 as eM}from"node:path";import{fileURLToPath as Vx1}from"node:url";import{lstatSync as vx1,readdir as Hx1,readdirSync as qx1,readlinkSync as Fx1,realpathSync as cx1}from"fs";import*as wx1 from"node:fs";import{lstat as Ux1,readdir as jx1,readlink as Bx1,realpath as Lx1}from"node:fs/promises";import{EventEmitter as sM}from"node:events";import ri from"node:stream";import{StringDecoder as ew1}from"node:string_decoder";var ai=typeof process==="object"&&process?process:{stdout:null,stderr:null},Zx1=(Z)=>!!Z&&typeof Z==="object"&&(Z instanceof f$||Z instanceof ri||Jx1(Z)||Xx1(Z)),Jx1=(Z)=>!!Z&&typeof Z==="object"&&Z instanceof sM&&typeof Z.pipe==="function"&&Z.pipe!==ri.Writable.prototype.pipe,Xx1=(Z)=>!!Z&&typeof Z==="object"&&Z instanceof sM&&typeof Z.write==="function"&&typeof Z.end==="function",JZ=Symbol("EOF"),XZ=Symbol("maybeEmitEnd"),bJ=Symbol("emittedEnd"),NF=Symbol("emittingEnd"),VG=Symbol("emittedError"),PF=Symbol("closed"),ni=Symbol("read"),TF=Symbol("flush"),si=Symbol("flushChunk"),c9=Symbol("encoding"),$3=Symbol("decoder"),y8=Symbol("flowing"),vG=Symbol("paused"),Y3=Symbol("resume"),p8=Symbol("buffer"),h6=Symbol("pipes"),i8=Symbol("bufferLength"),iM=Symbol("bufferPush"),CF=Symbol("bufferShift"),c6=Symbol("objectMode"),x8=Symbol("destroyed"),gM=Symbol("error"),dM=Symbol("emitData"),oi=Symbol("emitEnd"),aM=Symbol("emitEnd2"),X7=Symbol("async"),nM=Symbol("abort"),fF=Symbol("aborted"),HG=Symbol("signal"),C$=Symbol("dataListeners"),I5=Symbol("discarded"),qG=(Z)=>Promise.resolve().then(Z),$x1=(Z)=>Z(),Yx1=(Z)=>Z==="end"||Z==="finish"||Z==="prefinish",Qx1=(Z)=>Z instanceof ArrayBuffer||!!Z&&typeof Z==="object"&&Z.constructor&&Z.constructor.name==="ArrayBuffer"&&Z.byteLength>=0,Kx1=(Z)=>!Buffer.isBuffer(Z)&&ArrayBuffer.isView(Z);class oM{src;dest;opts;ondrain;constructor(Z,J,X){this.src=Z,this.dest=J,this.opts=X,this.ondrain=()=>Z[Y3](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(Z){}end(){if(this.unpipe(),this.opts.end)this.dest.end()}}class ti extends oM{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(Z,J,X){super(Z,J,X);this.proxyErrors=($)=>J.emit("error",$),Z.on("error",this.proxyErrors)}}var Wx1=(Z)=>!!Z.objectMode,Gx1=(Z)=>!Z.objectMode&&!!Z.encoding&&Z.encoding!=="buffer";class f$ extends sM{[y8]=!1;[vG]=!1;[h6]=[];[p8]=[];[c6];[c9];[X7];[$3];[JZ]=!1;[bJ]=!1;[NF]=!1;[PF]=!1;[VG]=null;[i8]=0;[x8]=!1;[HG];[fF]=!1;[C$]=0;[I5]=!1;writable=!0;readable=!0;constructor(...Z){let J=Z[0]||{};super();if(J.objectMode&&typeof J.encoding==="string")throw new TypeError("Encoding and objectMode may not be used together");if(Wx1(J))this[c6]=!0,this[c9]=null;else if(Gx1(J))this[c9]=J.encoding,this[c6]=!1;else this[c6]=!1,this[c9]=null;if(this[X7]=!!J.async,this[$3]=this[c9]?new ew1(this[c9]):null,J&&J.debugExposeBuffer===!0)Object.defineProperty(this,"buffer",{get:()=>this[p8]});if(J&&J.debugExposePipes===!0)Object.defineProperty(this,"pipes",{get:()=>this[h6]});let{signal:X}=J;if(X)if(this[HG]=X,X.aborted)this[nM]();else X.addEventListener("abort",()=>this[nM]())}get bufferLength(){return this[i8]}get encoding(){return this[c9]}set encoding(Z){throw new Error("Encoding must be set at instantiation time")}setEncoding(Z){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[c6]}set objectMode(Z){throw new Error("objectMode must be set at instantiation time")}get["async"](){return this[X7]}set["async"](Z){this[X7]=this[X7]||!!Z}[nM](){this[fF]=!0,this.emit("abort",this[HG]?.reason),this.destroy(this[HG]?.reason)}get aborted(){return this[fF]}set aborted(Z){}write(Z,J,X){if(this[fF])return!1;if(this[JZ])throw new Error("write after end");if(this[x8])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;if(typeof J==="function")X=J,J="utf8";if(!J)J="utf8";let $=this[X7]?qG:$x1;if(!this[c6]&&!Buffer.isBuffer(Z)){if(Kx1(Z))Z=Buffer.from(Z.buffer,Z.byteOffset,Z.byteLength);else if(Qx1(Z))Z=Buffer.from(Z);else if(typeof Z!=="string")throw new Error("Non-contiguous data written to non-objectMode stream")}if(this[c6]){if(this[y8]&&this[i8]!==0)this[TF](!0);if(this[y8])this.emit("data",Z);else this[iM](Z);if(this[i8]!==0)this.emit("readable");if(X)$(X);return this[y8]}if(!Z.length){if(this[i8]!==0)this.emit("readable");if(X)$(X);return this[y8]}if(typeof Z==="string"&&!(J===this[c9]&&!this[$3]?.lastNeed))Z=Buffer.from(Z,J);if(Buffer.isBuffer(Z)&&this[c9])Z=this[$3].write(Z);if(this[y8]&&this[i8]!==0)this[TF](!0);if(this[y8])this.emit("data",Z);else this[iM](Z);if(this[i8]!==0)this.emit("readable");if(X)$(X);return this[y8]}read(Z){if(this[x8])return null;if(this[I5]=!1,this[i8]===0||Z===0||Z&&Z>this[i8])return this[XZ](),null;if(this[c6])Z=null;if(this[p8].length>1&&!this[c6])this[p8]=[this[c9]?this[p8].join(""):Buffer.concat(this[p8],this[i8])];let J=this[ni](Z||null,this[p8][0]);return this[XZ](),J}[ni](Z,J){if(this[c6])this[CF]();else{let X=J;if(Z===X.length||Z===null)this[CF]();else if(typeof X==="string")this[p8][0]=X.slice(Z),J=X.slice(0,Z),this[i8]-=Z;else this[p8][0]=X.subarray(Z),J=X.subarray(0,Z),this[i8]-=Z}if(this.emit("data",J),!this[p8].length&&!this[JZ])this.emit("drain");return J}end(Z,J,X){if(typeof Z==="function")X=Z,Z=void 0;if(typeof J==="function")X=J,J="utf8";if(Z!==void 0)this.write(Z,J);if(X)this.once("end",X);if(this[JZ]=!0,this.writable=!1,this[y8]||!this[vG])this[XZ]();return this}[Y3](){if(this[x8])return;if(!this[C$]&&!this[h6].length)this[I5]=!0;if(this[vG]=!1,this[y8]=!0,this.emit("resume"),this[p8].length)this[TF]();else if(this[JZ])this[XZ]();else this.emit("drain")}resume(){return this[Y3]()}pause(){this[y8]=!1,this[vG]=!0,this[I5]=!1}get destroyed(){return this[x8]}get flowing(){return this[y8]}get paused(){return this[vG]}[iM](Z){if(this[c6])this[i8]+=1;else this[i8]+=Z.length;this[p8].push(Z)}[CF](){if(this[c6])this[i8]-=1;else this[i8]-=this[p8][0].length;return this[p8].shift()}[TF](Z=!1){do;while(this[si](this[CF]())&&this[p8].length);if(!Z&&!this[p8].length&&!this[JZ])this.emit("drain")}[si](Z){return this.emit("data",Z),this[y8]}pipe(Z,J){if(this[x8])return Z;this[I5]=!1;let X=this[bJ];if(J=J||{},Z===ai.stdout||Z===ai.stderr)J.end=!1;else J.end=J.end!==!1;if(J.proxyErrors=!!J.proxyErrors,X){if(J.end)Z.end()}else if(this[h6].push(!J.proxyErrors?new oM(this,Z,J):new ti(this,Z,J)),this[X7])qG(()=>this[Y3]());else this[Y3]();return Z}unpipe(Z){let J=this[h6].find((X)=>X.dest===Z);if(J){if(this[h6].length===1){if(this[y8]&&this[C$]===0)this[y8]=!1;this[h6]=[]}else this[h6].splice(this[h6].indexOf(J),1);J.unpipe()}}addListener(Z,J){return this.on(Z,J)}on(Z,J){let X=super.on(Z,J);if(Z==="data"){if(this[I5]=!1,this[C$]++,!this[h6].length&&!this[y8])this[Y3]()}else if(Z==="readable"&&this[i8]!==0)super.emit("readable");else if(Yx1(Z)&&this[bJ])super.emit(Z),this.removeAllListeners(Z);else if(Z==="error"&&this[VG]){let $=J;if(this[X7])qG(()=>$.call(this,this[VG]));else $.call(this,this[VG])}return X}removeListener(Z,J){return this.off(Z,J)}off(Z,J){let X=super.off(Z,J);if(Z==="data"){if(this[C$]=this.listeners("data").length,this[C$]===0&&!this[I5]&&!this[h6].length)this[y8]=!1}return X}removeAllListeners(Z){let J=super.removeAllListeners(Z);if(Z==="data"||Z===void 0){if(this[C$]=0,!this[I5]&&!this[h6].length)this[y8]=!1}return J}get emittedEnd(){return this[bJ]}[XZ](){if(!this[NF]&&!this[bJ]&&!this[x8]&&this[p8].length===0&&this[JZ]){if(this[NF]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[PF])this.emit("close");this[NF]=!1}}emit(Z,...J){let X=J[0];if(Z!=="error"&&Z!=="close"&&Z!==x8&&this[x8])return!1;else if(Z==="data")return!this[c6]&&!X?!1:this[X7]?(qG(()=>this[dM](X)),!0):this[dM](X);else if(Z==="end")return this[oi]();else if(Z==="close"){if(this[PF]=!0,!this[bJ]&&!this[x8])return!1;let Y=super.emit("close");return this.removeAllListeners("close"),Y}else if(Z==="error"){this[VG]=X,super.emit(gM,X);let Y=!this[HG]||this.listeners("error").length?super.emit("error",X):!1;return this[XZ](),Y}else if(Z==="resume"){let Y=super.emit("resume");return this[XZ](),Y}else if(Z==="finish"||Z==="prefinish"){let Y=super.emit(Z);return this.removeAllListeners(Z),Y}let $=super.emit(Z,...J);return this[XZ](),$}[dM](Z){for(let X of this[h6])if(X.dest.write(Z)===!1)this.pause();let J=this[I5]?!1:super.emit("data",Z);return this[XZ](),J}[oi](){if(this[bJ])return!1;return this[bJ]=!0,this.readable=!1,this[X7]?(qG(()=>this[aM]()),!0):this[aM]()}[aM](){if(this[$3]){let J=this[$3].end();if(J){for(let X of this[h6])X.dest.write(J);if(!this[I5])super.emit("data",J)}}for(let J of this[h6])J.end();let Z=super.emit("end");return this.removeAllListeners("end"),Z}async collect(){let Z=Object.assign([],{dataLength:0});if(!this[c6])Z.dataLength=0;let J=this.promise();return this.on("data",(X)=>{if(Z.push(X),!this[c6])Z.dataLength+=X.length}),await J,Z}async concat(){if(this[c6])throw new Error("cannot concat in objectMode");let Z=await this.collect();return this[c9]?Z.join(""):Buffer.concat(Z,Z.dataLength)}async promise(){return new Promise((Z,J)=>{this.on(x8,()=>J(new Error("stream destroyed"))),this.on("error",(X)=>J(X)),this.on("end",()=>Z())})}[Symbol.asyncIterator](){this[I5]=!1;let Z=!1,J=async()=>{return this.pause(),Z=!0,{value:void 0,done:!0}};return{next:()=>{if(Z)return J();let $=this.read();if($!==null)return Promise.resolve({done:!1,value:$});if(this[JZ])return J();let Y,Q,K=(V)=>{this.off("data",W),this.off("end",G),this.off(x8,z),J(),Q(V)},W=(V)=>{this.off("error",K),this.off("end",G),this.off(x8,z),this.pause(),Y({value:V,done:!!this[JZ]})},G=()=>{this.off("error",K),this.off("data",W),this.off(x8,z),J(),Y({done:!0,value:void 0})},z=()=>K(new Error("stream destroyed"));return new Promise((V,H)=>{Q=H,Y=V,this.once(x8,z),this.once("error",K),this.once("end",G),this.once("data",W)})},throw:J,return:J,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[I5]=!1;let Z=!1,J=()=>{return this.pause(),this.off(gM,J),this.off(x8,J),this.off("end",J),Z=!0,{done:!0,value:void 0}},X=()=>{if(Z)return J();let $=this.read();return $===null?J():{done:!1,value:$}};return this.once("end",J),this.once(gM,J),this.once(x8,J),{next:X,throw:J,return:J,[Symbol.iterator](){return this}}}destroy(Z){if(this[x8]){if(Z)this.emit("error",Z);else this.emit(x8);return this}this[x8]=!0,this[I5]=!0,this[p8].length=0,this[i8]=0;let J=this;if(typeof J.close==="function"&&!this[PF])J.close();if(Z)this.emit("error",Z);else this.emit(x8);return this}static get isStream(){return Zx1}}var xx1=cx1.native,cG={lstatSync:vx1,readdir:Hx1,readdirSync:qx1,readlinkSync:Fx1,realpathSync:xx1,promises:{lstat:Ux1,readdir:jx1,readlink:Bx1,realpath:Lx1}},$g=(Z)=>!Z||Z===cG||Z===wx1?cG:{...cG,...Z,promises:{...cG.promises,...Z.promises||{}}},Yg=/^\\\\\?\\([a-z]:)\\?$/i,Dx1=(Z)=>Z.replace(/\//g,"\\").replace(Yg,"$1\\"),Mx1=/[\\\/]/,F4=0,Qg=1,Kg=2,$7=4,Wg=6,Gg=8,k$=10,zg=12,q4=15,FG=~q4,rM=16,ei=32,wG=64,w9=128,kF=256,IF=512,Zg=wG|w9|IF,Rx1=1023,tM=(Z)=>Z.isFile()?Gg:Z.isDirectory()?$7:Z.isSymbolicLink()?k$:Z.isCharacterDevice()?Kg:Z.isBlockDevice()?Wg:Z.isSocket()?zg:Z.isFIFO()?Qg:F4,Jg=new Map,xG=(Z)=>{let J=Jg.get(Z);if(J)return J;let X=Z.normalize("NFKD");return Jg.set(Z,X),X},Xg=new Map,EF=(Z)=>{let J=Xg.get(Z);if(J)return J;let X=xG(Z.toLowerCase());return Xg.set(Z,X),X};class ZR extends zG{constructor(){super({max:256})}}class Vg extends zG{constructor(Z=16384){super({maxSize:Z,sizeCalculation:(J)=>J.length+1})}}var vg=Symbol("PathScurry setAsCwd");class S6{name;root;roots;parent;nocase;isCWD=!1;#Z;#J;get dev(){return this.#J}#$;get mode(){return this.#$}#X;get nlink(){return this.#X}#Y;get uid(){return this.#Y}#V;get gid(){return this.#V}#H;get rdev(){return this.#H}#W;get blksize(){return this.#W}#G;get ino(){return this.#G}#z;get size(){return this.#z}#v;get blocks(){return this.#v}#Q;get atimeMs(){return this.#Q}#F;get mtimeMs(){return this.#F}#w;get ctimeMs(){return this.#w}#c;get birthtimeMs(){return this.#c}#U;get atime(){return this.#U}#P;get mtime(){return this.#P}#j;get ctime(){return this.#j}#T;get birthtime(){return this.#T}#D;#L;#B;#O;#x;#f;#K;#I;#M;#k;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(Z,J=F4,X,$,Y,Q,K){if(this.name=Z,this.#D=Y?EF(Z):xG(Z),this.#K=J&Rx1,this.nocase=Y,this.roots=$,this.root=X||this,this.#I=Q,this.#B=K.fullpath,this.#x=K.relative,this.#f=K.relativePosix,this.parent=K.parent,this.parent)this.#Z=this.parent.#Z;else this.#Z=$g(K.fs)}depth(){if(this.#L!==void 0)return this.#L;if(!this.parent)return this.#L=0;return this.#L=this.parent.depth()+1}childrenCache(){return this.#I}resolve(Z){if(!Z)return this;let J=this.getRootString(Z),$=Z.substring(J.length).split(this.splitSep);return J?this.getRoot(J).#R($):this.#R($)}#R(Z){let J=this;for(let X of Z)J=J.child(X);return J}children(){let Z=this.#I.get(this);if(Z)return Z;let J=Object.assign([],{provisional:0});return this.#I.set(this,J),this.#K&=~rM,J}child(Z,J){if(Z===""||Z===".")return this;if(Z==="..")return this.parent||this;let X=this.children(),$=this.nocase?EF(Z):xG(Z);for(let W of X)if(W.#D===$)return W;let Y=this.parent?this.sep:"",Q=this.#B?this.#B+Y+Z:void 0,K=this.newChild(Z,F4,{...J,parent:this,fullpath:Q});if(!this.canReaddir())K.#K|=w9;return X.push(K),K}relative(){if(this.isCWD)return"";if(this.#x!==void 0)return this.#x;let Z=this.name,J=this.parent;if(!J)return this.#x=this.name;let X=J.relative();return X+(!X||!J.parent?"":this.sep)+Z}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#f!==void 0)return this.#f;let Z=this.name,J=this.parent;if(!J)return this.#f=this.fullpathPosix();let X=J.relativePosix();return X+(!X||!J.parent?"":"/")+Z}fullpath(){if(this.#B!==void 0)return this.#B;let Z=this.name,J=this.parent;if(!J)return this.#B=this.name;let $=J.fullpath()+(!J.parent?"":this.sep)+Z;return this.#B=$}fullpathPosix(){if(this.#O!==void 0)return this.#O;if(this.sep==="/")return this.#O=this.fullpath();if(!this.parent){let $=this.fullpath().replace(/\\/g,"/");if(/^[a-z]:\//i.test($))return this.#O=`//?/${$}`;else return this.#O=$}let Z=this.parent,J=Z.fullpathPosix(),X=J+(!J||!Z.parent?"":"/")+this.name;return this.#O=X}isUnknown(){return(this.#K&q4)===F4}isType(Z){return this[`is${Z}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#K&q4)===Gg}isDirectory(){return(this.#K&q4)===$7}isCharacterDevice(){return(this.#K&q4)===Kg}isBlockDevice(){return(this.#K&q4)===Wg}isFIFO(){return(this.#K&q4)===Qg}isSocket(){return(this.#K&q4)===zg}isSymbolicLink(){return(this.#K&k$)===k$}lstatCached(){return this.#K&ei?this:void 0}readlinkCached(){return this.#M}realpathCached(){return this.#k}readdirCached(){let Z=this.children();return Z.slice(0,Z.provisional)}canReadlink(){if(this.#M)return!0;if(!this.parent)return!1;let Z=this.#K&q4;return!(Z!==F4&&Z!==k$||this.#K&kF||this.#K&w9)}calledReaddir(){return!!(this.#K&rM)}isENOENT(){return!!(this.#K&w9)}isNamed(Z){return!this.nocase?this.#D===xG(Z):this.#D===EF(Z)}async readlink(){let Z=this.#M;if(Z)return Z;if(!this.canReadlink())return;if(!this.parent)return;try{let J=await this.#Z.promises.readlink(this.fullpath()),X=(await this.parent.realpath())?.resolve(J);if(X)return this.#M=X}catch(J){this.#S(J.code);return}}readlinkSync(){let Z=this.#M;if(Z)return Z;if(!this.canReadlink())return;if(!this.parent)return;try{let J=this.#Z.readlinkSync(this.fullpath()),X=this.parent.realpathSync()?.resolve(J);if(X)return this.#M=X}catch(J){this.#S(J.code);return}}#u(Z){this.#K|=rM;for(let J=Z.provisional;J<Z.length;J++){let X=Z[J];if(X)X.#_()}}#_(){if(this.#K&w9)return;this.#K=(this.#K|w9)&FG,this.#h()}#h(){let Z=this.children();Z.provisional=0;for(let J of Z)J.#_()}#l(){this.#K|=IF,this.#N()}#N(){if(this.#K&wG)return;let Z=this.#K;if((Z&q4)===$7)Z&=FG;this.#K=Z|wG,this.#h()}#C(Z=""){if(Z==="ENOTDIR"||Z==="EPERM")this.#N();else if(Z==="ENOENT")this.#_();else this.children().provisional=0}#y(Z=""){if(Z==="ENOTDIR")this.parent.#N();else if(Z==="ENOENT")this.#_()}#S(Z=""){let J=this.#K;if(J|=kF,Z==="ENOENT")J|=w9;if(Z==="EINVAL"||Z==="UNKNOWN")J&=FG;if(this.#K=J,Z==="ENOTDIR"&&this.parent)this.parent.#N()}#b(Z,J){return this.#p(Z,J)||this.#q(Z,J)}#q(Z,J){let X=tM(Z),$=this.newChild(Z.name,X,{parent:this}),Y=$.#K&q4;if(Y!==$7&&Y!==k$&&Y!==F4)$.#K|=wG;return J.unshift($),J.provisional++,$}#p(Z,J){for(let X=J.provisional;X<J.length;X++){let $=J[X];if((this.nocase?EF(Z.name):xG(Z.name))!==$.#D)continue;return this.#A(Z,$,X,J)}}#A(Z,J,X,$){let Y=J.name;if(J.#K=J.#K&FG|tM(Z),Y!==Z.name)J.name=Z.name;if(X!==$.provisional){if(X===$.length-1)$.pop();else $.splice(X,1);$.unshift(J)}return $.provisional++,J}async lstat(){if((this.#K&w9)===0)try{return this.#E(await this.#Z.promises.lstat(this.fullpath())),this}catch(Z){this.#y(Z.code)}}lstatSync(){if((this.#K&w9)===0)try{return this.#E(this.#Z.lstatSync(this.fullpath())),this}catch(Z){this.#y(Z.code)}}#E(Z){let{atime:J,atimeMs:X,birthtime:$,birthtimeMs:Y,blksize:Q,blocks:K,ctime:W,ctimeMs:G,dev:z,gid:V,ino:H,mode:v,mtime:q,mtimeMs:F,nlink:c,rdev:w,size:x,uid:j}=Z;this.#U=J,this.#Q=X,this.#T=$,this.#c=Y,this.#W=Q,this.#v=K,this.#j=W,this.#w=G,this.#J=z,this.#V=V,this.#G=H,this.#$=v,this.#P=q,this.#F=F,this.#X=c,this.#H=w,this.#z=x,this.#Y=j;let B=tM(Z);if(this.#K=this.#K&FG|B|ei,B!==F4&&B!==$7&&B!==k$)this.#K|=wG}#m=[];#g=!1;#d(Z){this.#g=!1;let J=this.#m.slice();this.#m.length=0,J.forEach((X)=>X(null,Z))}readdirCB(Z,J=!1){if(!this.canReaddir()){if(J)Z(null,[]);else queueMicrotask(()=>Z(null,[]));return}let X=this.children();if(this.calledReaddir()){let Y=X.slice(0,X.provisional);if(J)Z(null,Y);else queueMicrotask(()=>Z(null,Y));return}if(this.#m.push(Z),this.#g)return;this.#g=!0;let $=this.fullpath();this.#Z.readdir($,{withFileTypes:!0},(Y,Q)=>{if(Y)this.#C(Y.code),X.provisional=0;else{for(let K of Q)this.#b(K,X);this.#u(X)}this.#d(X.slice(0,X.provisional));return})}#i;async readdir(){if(!this.canReaddir())return[];let Z=this.children();if(this.calledReaddir())return Z.slice(0,Z.provisional);let J=this.fullpath();if(this.#i)await this.#i;else{let X=()=>{};this.#i=new Promise(($)=>X=$);try{for(let $ of await this.#Z.promises.readdir(J,{withFileTypes:!0}))this.#b($,Z);this.#u(Z)}catch($){this.#C($.code),Z.provisional=0}this.#i=void 0,X()}return Z.slice(0,Z.provisional)}readdirSync(){if(!this.canReaddir())return[];let Z=this.children();if(this.calledReaddir())return Z.slice(0,Z.provisional);let J=this.fullpath();try{for(let X of this.#Z.readdirSync(J,{withFileTypes:!0}))this.#b(X,Z);this.#u(Z)}catch(X){this.#C(X.code),Z.provisional=0}return Z.slice(0,Z.provisional)}canReaddir(){if(this.#K&Zg)return!1;let Z=q4&this.#K;if(!(Z===F4||Z===$7||Z===k$))return!1;return!0}shouldWalk(Z,J){return(this.#K&$7)===$7&&!(this.#K&Zg)&&!Z.has(this)&&(!J||J(this))}async realpath(){if(this.#k)return this.#k;if((IF|kF|w9)&this.#K)return;try{let Z=await this.#Z.promises.realpath(this.fullpath());return this.#k=this.resolve(Z)}catch(Z){this.#l()}}realpathSync(){if(this.#k)return this.#k;if((IF|kF|w9)&this.#K)return;try{let Z=this.#Z.realpathSync(this.fullpath());return this.#k=this.resolve(Z)}catch(Z){this.#l()}}[vg](Z){if(Z===this)return;Z.isCWD=!1,this.isCWD=!0;let J=new Set([]),X=[],$=this;while($&&$.parent)J.add($),$.#x=X.join(this.sep),$.#f=X.join("/"),$=$.parent,X.push("..");$=Z;while($&&$.parent&&!J.has($))$.#x=void 0,$.#f=void 0,$=$.parent}}class _F extends S6{sep="\\";splitSep=Mx1;constructor(Z,J=F4,X,$,Y,Q,K){super(Z,J,X,$,Y,Q,K)}newChild(Z,J=F4,X={}){return new _F(Z,J,this.root,this.roots,this.nocase,this.childrenCache(),X)}getRootString(Z){return eM.parse(Z).root}getRoot(Z){if(Z=Dx1(Z.toUpperCase()),Z===this.root.name)return this.root;for(let[J,X]of Object.entries(this.roots))if(this.sameRoot(Z,J))return this.roots[Z]=X;return this.roots[Z]=new UG(Z,this).root}sameRoot(Z,J=this.root.name){return Z=Z.toUpperCase().replace(/\//g,"\\").replace(Yg,"$1\\"),Z===J}}class bF extends S6{splitSep="/";sep="/";constructor(Z,J=F4,X,$,Y,Q,K){super(Z,J,X,$,Y,Q,K)}getRootString(Z){return Z.startsWith("/")?"/":""}getRoot(Z){return this.root}newChild(Z,J=F4,X={}){return new bF(Z,J,this.root,this.roots,this.nocase,this.childrenCache(),X)}}class JR{root;rootPath;roots;cwd;#Z;#J;#$;nocase;#X;constructor(Z=process.cwd(),J,X,{nocase:$,childrenCacheSize:Y=16384,fs:Q=cG}={}){if(this.#X=$g(Q),Z instanceof URL||Z.startsWith("file://"))Z=Vx1(Z);let K=J.resolve(Z);this.roots=Object.create(null),this.rootPath=this.parseRootPath(K),this.#Z=new ZR,this.#J=new ZR,this.#$=new Vg(Y);let W=K.substring(this.rootPath.length).split(X);if(W.length===1&&!W[0])W.pop();if($===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=$,this.root=this.newRoot(this.#X),this.roots[this.rootPath]=this.root;let G=this.root,z=W.length-1,V=J.sep,H=this.rootPath,v=!1;for(let q of W){let F=z--;G=G.child(q,{relative:new Array(F).fill("..").join(V),relativePosix:new Array(F).fill("..").join("/"),fullpath:H+=(v?"":V)+q}),v=!0}this.cwd=G}depth(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.depth()}childrenCache(){return this.#$}resolve(...Z){let J="";for(let Y=Z.length-1;Y>=0;Y--){let Q=Z[Y];if(!Q||Q===".")continue;if(J=J?`${Q}/${J}`:Q,this.isAbsolute(Q))break}let X=this.#Z.get(J);if(X!==void 0)return X;let $=this.cwd.resolve(J).fullpath();return this.#Z.set(J,$),$}resolvePosix(...Z){let J="";for(let Y=Z.length-1;Y>=0;Y--){let Q=Z[Y];if(!Q||Q===".")continue;if(J=J?`${Q}/${J}`:Q,this.isAbsolute(Q))break}let X=this.#J.get(J);if(X!==void 0)return X;let $=this.cwd.resolve(J).fullpathPosix();return this.#J.set(J,$),$}relative(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.relative()}relativePosix(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.relativePosix()}basename(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.name}dirname(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return(Z.parent||Z).fullpath()}async readdir(Z=this.cwd,J={withFileTypes:!0}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof S6))J=Z,Z=this.cwd;let{withFileTypes:X}=J;if(!Z.canReaddir())return[];else{let $=await Z.readdir();return X?$:$.map((Y)=>Y.name)}}readdirSync(Z=this.cwd,J={withFileTypes:!0}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof S6))J=Z,Z=this.cwd;let{withFileTypes:X=!0}=J;if(!Z.canReaddir())return[];else if(X)return Z.readdirSync();else return Z.readdirSync().map(($)=>$.name)}async lstat(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.lstat()}lstatSync(Z=this.cwd){if(typeof Z==="string")Z=this.cwd.resolve(Z);return Z.lstatSync()}async readlink(Z=this.cwd,{withFileTypes:J}={withFileTypes:!1}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof S6))J=Z.withFileTypes,Z=this.cwd;let X=await Z.readlink();return J?X:X?.fullpath()}readlinkSync(Z=this.cwd,{withFileTypes:J}={withFileTypes:!1}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof S6))J=Z.withFileTypes,Z=this.cwd;let X=Z.readlinkSync();return J?X:X?.fullpath()}async realpath(Z=this.cwd,{withFileTypes:J}={withFileTypes:!1}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof S6))J=Z.withFileTypes,Z=this.cwd;let X=await Z.realpath();return J?X:X?.fullpath()}realpathSync(Z=this.cwd,{withFileTypes:J}={withFileTypes:!1}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof S6))J=Z.withFileTypes,Z=this.cwd;let X=Z.realpathSync();return J?X:X?.fullpath()}async walk(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof S6))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:$=!1,filter:Y,walkFilter:Q}=J,K=[];if(!Y||Y(Z))K.push(X?Z:Z.fullpath());let W=new Set,G=(V,H)=>{W.add(V),V.readdirCB((v,q)=>{if(v)return H(v);let F=q.length;if(!F)return H();let c=()=>{if(--F===0)H()};for(let w of q){if(!Y||Y(w))K.push(X?w:w.fullpath());if($&&w.isSymbolicLink())w.realpath().then((x)=>x?.isUnknown()?x.lstat():x).then((x)=>x?.shouldWalk(W,Q)?G(x,c):c());else if(w.shouldWalk(W,Q))G(w,c);else c()}},!0)},z=Z;return new Promise((V,H)=>{G(z,(v)=>{if(v)return H(v);V(K)})})}walkSync(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof S6))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:$=!1,filter:Y,walkFilter:Q}=J,K=[];if(!Y||Y(Z))K.push(X?Z:Z.fullpath());let W=new Set([Z]);for(let G of W){let z=G.readdirSync();for(let V of z){if(!Y||Y(V))K.push(X?V:V.fullpath());let H=V;if(V.isSymbolicLink()){if(!($&&(H=V.realpathSync())))continue;if(H.isUnknown())H.lstatSync()}if(H.shouldWalk(W,Q))W.add(H)}}return K}[Symbol.asyncIterator](){return this.iterate()}iterate(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof S6))J=Z,Z=this.cwd;return this.stream(Z,J)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof S6))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:$=!1,filter:Y,walkFilter:Q}=J;if(!Y||Y(Z))yield X?Z:Z.fullpath();let K=new Set([Z]);for(let W of K){let G=W.readdirSync();for(let z of G){if(!Y||Y(z))yield X?z:z.fullpath();let V=z;if(z.isSymbolicLink()){if(!($&&(V=z.realpathSync())))continue;if(V.isUnknown())V.lstatSync()}if(V.shouldWalk(K,Q))K.add(V)}}}stream(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof S6))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:$=!1,filter:Y,walkFilter:Q}=J,K=new f$({objectMode:!0});if(!Y||Y(Z))K.write(X?Z:Z.fullpath());let W=new Set,G=[Z],z=0,V=()=>{let H=!1;while(!H){let v=G.shift();if(!v){if(z===0)K.end();return}z++,W.add(v);let q=(c,w,x=!1)=>{if(c)return K.emit("error",c);if($&&!x){let j=[];for(let B of w)if(B.isSymbolicLink())j.push(B.realpath().then((L)=>L?.isUnknown()?L.lstat():L));if(j.length){Promise.all(j).then(()=>q(null,w,!0));return}}for(let j of w)if(j&&(!Y||Y(j))){if(!K.write(X?j:j.fullpath()))H=!0}z--;for(let j of w){let B=j.realpathCached()||j;if(B.shouldWalk(W,Q))G.push(B)}if(H&&!K.flowing)K.once("drain",V);else if(!F)V()},F=!0;v.readdirCB(q,!0),F=!1}};return V(),K}streamSync(Z=this.cwd,J={}){if(typeof Z==="string")Z=this.cwd.resolve(Z);else if(!(Z instanceof S6))J=Z,Z=this.cwd;let{withFileTypes:X=!0,follow:$=!1,filter:Y,walkFilter:Q}=J,K=new f$({objectMode:!0}),W=new Set;if(!Y||Y(Z))K.write(X?Z:Z.fullpath());let G=[Z],z=0,V=()=>{let H=!1;while(!H){let v=G.shift();if(!v){if(z===0)K.end();return}z++,W.add(v);let q=v.readdirSync();for(let F of q)if(!Y||Y(F)){if(!K.write(X?F:F.fullpath()))H=!0}z--;for(let F of q){let c=F;if(F.isSymbolicLink()){if(!($&&(c=F.realpathSync())))continue;if(c.isUnknown())c.lstatSync()}if(c.shouldWalk(W,Q))G.push(c)}}if(H&&!K.flowing)K.once("drain",V)};return V(),K}chdir(Z=this.cwd){let J=this.cwd;this.cwd=typeof Z==="string"?this.cwd.resolve(Z):Z,this.cwd[vg](J)}}class UG extends JR{sep="\\";constructor(Z=process.cwd(),J={}){let{nocase:X=!0}=J;super(Z,eM,"\\",{...J,nocase:X});this.nocase=X;for(let $=this.cwd;$;$=$.parent)$.nocase=this.nocase}parseRootPath(Z){return eM.parse(Z).root.toUpperCase()}newRoot(Z){return new _F(this.rootPath,$7,void 0,this.roots,this.nocase,this.childrenCache(),{fs:Z})}isAbsolute(Z){return Z.startsWith("/")||Z.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(Z)}}class jG extends JR{sep="/";constructor(Z=process.cwd(),J={}){let{nocase:X=!1}=J;super(Z,zx1,"/",{...J,nocase:X});this.nocase=X}parseRootPath(Z){return"/"}newRoot(Z){return new bF(this.rootPath,$7,void 0,this.roots,this.nocase,this.childrenCache(),{fs:Z})}isAbsolute(Z){return Z.startsWith("/")}}class hF extends jG{constructor(Z=process.cwd(),J={}){let{nocase:X=!0}=J;super(Z,{...J,nocase:X})}}var qO6=process.platform==="win32"?_F:bF,Hg=process.platform==="win32"?UG:process.platform==="darwin"?hF:jG;var Ox1=(Z)=>Z.length>=1,Nx1=(Z)=>Z.length>=1;class Q3{#Z;#J;#$;length;#X;#Y;#V;#H;#W;#G;#z=!0;constructor(Z,J,X,$){if(!Ox1(Z))throw new TypeError("empty pattern list");if(!Nx1(J))throw new TypeError("empty glob list");if(J.length!==Z.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=Z.length,X<0||X>=this.length)throw new TypeError("index out of range");if(this.#Z=Z,this.#J=J,this.#$=X,this.#X=$,this.#$===0){if(this.isUNC()){let[Y,Q,K,W,...G]=this.#Z,[z,V,H,v,...q]=this.#J;if(G[0]==="")G.shift(),q.shift();let F=[Y,Q,K,W,""].join("/"),c=[z,V,H,v,""].join("/");this.#Z=[F,...G],this.#J=[c,...q],this.length=this.#Z.length}else if(this.isDrive()||this.isAbsolute()){let[Y,...Q]=this.#Z,[K,...W]=this.#J;if(Q[0]==="")Q.shift(),W.shift();let G=Y+"/",z=K+"/";this.#Z=[G,...Q],this.#J=[z,...W],this.length=this.#Z.length}}}pattern(){return this.#Z[this.#$]}isString(){return typeof this.#Z[this.#$]==="string"}isGlobstar(){return this.#Z[this.#$]===J6}isRegExp(){return this.#Z[this.#$]instanceof RegExp}globString(){return this.#V=this.#V||(this.#$===0?this.isAbsolute()?this.#J[0]+this.#J.slice(1).join("/"):this.#J.join("/"):this.#J.slice(this.#$).join("/"))}hasMore(){return this.length>this.#$+1}rest(){if(this.#Y!==void 0)return this.#Y;if(!this.hasMore())return this.#Y=null;return this.#Y=new Q3(this.#Z,this.#J,this.#$+1,this.#X),this.#Y.#G=this.#G,this.#Y.#W=this.#W,this.#Y.#H=this.#H,this.#Y}isUNC(){let Z=this.#Z;return this.#W!==void 0?this.#W:this.#W=this.#X==="win32"&&this.#$===0&&Z[0]===""&&Z[1]===""&&typeof Z[2]==="string"&&!!Z[2]&&typeof Z[3]==="string"&&!!Z[3]}isDrive(){let Z=this.#Z;return this.#H!==void 0?this.#H:this.#H=this.#X==="win32"&&this.#$===0&&this.length>1&&typeof Z[0]==="string"&&/^[a-z]:$/i.test(Z[0])}isAbsolute(){let Z=this.#Z;return this.#G!==void 0?this.#G:this.#G=Z[0]===""&&Z.length>1||this.isDrive()||this.isUNC()}root(){let Z=this.#Z[0];return typeof Z==="string"&&this.isAbsolute()&&this.#$===0?Z:""}checkFollowGlobstar(){return!(this.#$===0||!this.isGlobstar()||!this.#z)}markFollowGlobstar(){if(this.#$===0||!this.isGlobstar()||!this.#z)return!1;return this.#z=!1,!0}}var Px1=typeof process==="object"&&process&&typeof process.platform==="string"?process.platform:"linux";class BG{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(Z,{nobrace:J,nocase:X,noext:$,noglobstar:Y,platform:Q=Px1}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=Q,this.mmopts={dot:!0,nobrace:J,nocase:X,noext:$,noglobstar:Y,optimizationLevel:2,platform:Q,nocomment:!0,nonegate:!0};for(let K of Z)this.add(K)}add(Z){let J=new H4(Z,this.mmopts);for(let X=0;X<J.set.length;X++){let $=J.set[X],Y=J.globParts[X];if(!$||!Y)throw new Error("invalid pattern object");while($[0]==="."&&Y[0]===".")$.shift(),Y.shift();let Q=new Q3($,Y,0,this.platform),K=new H4(Q.globString(),this.mmopts),W=Y[Y.length-1]==="**",G=Q.isAbsolute();if(G)this.absolute.push(K);else this.relative.push(K);if(W)if(G)this.absoluteChildren.push(K);else this.relativeChildren.push(K)}}ignored(Z){let J=Z.fullpath(),X=`${J}/`,$=Z.relative()||".",Y=`${$}/`;for(let Q of this.relative)if(Q.match($)||Q.match(Y))return!0;for(let Q of this.absolute)if(Q.match(J)||Q.match(X))return!0;return!1}childrenIgnored(Z){let J=Z.fullpath()+"/",X=(Z.relative()||".")+"/";for(let $ of this.relativeChildren)if($.match(X))return!0;for(let $ of this.absoluteChildren)if($.match(J))return!0;return!1}}class XR{store;constructor(Z=new Map){this.store=Z}copy(){return new XR(new Map(this.store))}hasWalked(Z,J){return this.store.get(Z.fullpath())?.has(J.globString())}storeWalked(Z,J){let X=Z.fullpath(),$=this.store.get(X);if($)$.add(J.globString());else this.store.set(X,new Set([J.globString()]))}}class qg{store=new Map;add(Z,J,X){let $=(J?2:0)|(X?1:0),Y=this.store.get(Z);this.store.set(Z,Y===void 0?$:$&Y)}entries(){return[...this.store.entries()].map(([Z,J])=>[Z,!!(J&2),!!(J&1)])}}class Fg{store=new Map;add(Z,J){if(!Z.canReaddir())return;let X=this.store.get(Z);if(X){if(!X.find(($)=>$.globString()===J.globString()))X.push(J)}else this.store.set(Z,[J])}get(Z){let J=this.store.get(Z);if(!J)throw new Error("attempting to walk unknown path");return J}entries(){return this.keys().map((Z)=>[Z,this.store.get(Z)])}keys(){return[...this.store.keys()].filter((Z)=>Z.canReaddir())}}class LG{hasWalkedCache;matches=new qg;subwalks=new Fg;patterns;follow;dot;opts;constructor(Z,J){this.opts=Z,this.follow=!!Z.follow,this.dot=!!Z.dot,this.hasWalkedCache=J?J.copy():new XR}processPatterns(Z,J){this.patterns=J;let X=J.map(($)=>[Z,$]);for(let[$,Y]of X){this.hasWalkedCache.storeWalked($,Y);let Q=Y.root(),K=Y.isAbsolute()&&this.opts.absolute!==!1;if(Q){$=$.resolve(Q==="/"&&this.opts.root!==void 0?this.opts.root:Q);let V=Y.rest();if(!V){this.matches.add($,!0,!1);continue}else Y=V}if($.isENOENT())continue;let W,G,z=!1;while(typeof(W=Y.pattern())==="string"&&(G=Y.rest()))$=$.resolve(W),Y=G,z=!0;if(W=Y.pattern(),G=Y.rest(),z){if(this.hasWalkedCache.hasWalked($,Y))continue;this.hasWalkedCache.storeWalked($,Y)}if(typeof W==="string"){let V=W===".."||W===""||W===".";this.matches.add($.resolve(W),K,V);continue}else if(W===J6){if(!$.isSymbolicLink()||this.follow||Y.checkFollowGlobstar())this.subwalks.add($,Y);let V=G?.pattern(),H=G?.rest();if(!G||(V===""||V===".")&&!H)this.matches.add($,K,V===""||V===".");else if(V===".."){let v=$.parent||$;if(!H)this.matches.add(v,K,!0);else if(!this.hasWalkedCache.hasWalked(v,H))this.subwalks.add(v,H)}}else if(W instanceof RegExp)this.subwalks.add($,Y)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new LG(this.opts,this.hasWalkedCache)}filterEntries(Z,J){let X=this.subwalks.get(Z),$=this.child();for(let Y of J)for(let Q of X){let K=Q.isAbsolute(),W=Q.pattern(),G=Q.rest();if(W===J6)$.testGlobstar(Y,Q,G,K);else if(W instanceof RegExp)$.testRegExp(Y,W,G,K);else $.testString(Y,W,G,K)}return $}testGlobstar(Z,J,X,$){if(this.dot||!Z.name.startsWith(".")){if(!J.hasMore())this.matches.add(Z,$,!1);if(Z.canReaddir()){if(this.follow||!Z.isSymbolicLink())this.subwalks.add(Z,J);else if(Z.isSymbolicLink()){if(X&&J.checkFollowGlobstar())this.subwalks.add(Z,X);else if(J.markFollowGlobstar())this.subwalks.add(Z,J)}}}if(X){let Y=X.pattern();if(typeof Y==="string"&&Y!==".."&&Y!==""&&Y!==".")this.testString(Z,Y,X.rest(),$);else if(Y===".."){let Q=Z.parent||Z;this.subwalks.add(Q,X)}else if(Y instanceof RegExp)this.testRegExp(Z,Y,X.rest(),$)}}testRegExp(Z,J,X,$){if(!J.test(Z.name))return;if(!X)this.matches.add(Z,$,!1);else this.subwalks.add(Z,X)}testString(Z,J,X,$){if(!Z.isNamed(J))return;if(!X)this.matches.add(Z,$,!1);else this.subwalks.add(Z,X)}}var Tx1=(Z,J)=>typeof Z==="string"?new BG([Z],J):Array.isArray(Z)?new BG(Z,J):Z;class $R{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#Z=[];#J;#$;signal;maxDepth;includeChildMatches;constructor(Z,J,X){if(this.patterns=Z,this.path=J,this.opts=X,this.#$=!X.posix&&X.platform==="win32"?"\\":"/",this.includeChildMatches=X.includeChildMatches!==!1,X.ignore||!this.includeChildMatches){if(this.#J=Tx1(X.ignore??[],X),!this.includeChildMatches&&typeof this.#J.add!=="function")throw new Error("cannot ignore child matches, ignore lacks add() method.")}if(this.maxDepth=X.maxDepth||1/0,X.signal)this.signal=X.signal,this.signal.addEventListener("abort",()=>{this.#Z.length=0})}#X(Z){return this.seen.has(Z)||!!this.#J?.ignored?.(Z)}#Y(Z){return!!this.#J?.childrenIgnored?.(Z)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let Z=void 0;while(!this.paused&&(Z=this.#Z.shift()))Z()}onResume(Z){if(this.signal?.aborted)return;if(!this.paused)Z();else this.#Z.push(Z)}async matchCheck(Z,J){if(J&&this.opts.nodir)return;let X;if(this.opts.realpath){if(X=Z.realpathCached()||await Z.realpath(),!X)return;Z=X}let Y=Z.isUnknown()||this.opts.stat?await Z.lstat():Z;if(this.opts.follow&&this.opts.nodir&&Y?.isSymbolicLink()){let Q=await Y.realpath();if(Q&&(Q.isUnknown()||this.opts.stat))await Q.lstat()}return this.matchCheckTest(Y,J)}matchCheckTest(Z,J){return Z&&(this.maxDepth===1/0||Z.depth()<=this.maxDepth)&&(!J||Z.canReaddir())&&(!this.opts.nodir||!Z.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!Z.isSymbolicLink()||!Z.realpathCached()?.isDirectory())&&!this.#X(Z)?Z:void 0}matchCheckSync(Z,J){if(J&&this.opts.nodir)return;let X;if(this.opts.realpath){if(X=Z.realpathCached()||Z.realpathSync(),!X)return;Z=X}let Y=Z.isUnknown()||this.opts.stat?Z.lstatSync():Z;if(this.opts.follow&&this.opts.nodir&&Y?.isSymbolicLink()){let Q=Y.realpathSync();if(Q&&(Q?.isUnknown()||this.opts.stat))Q.lstatSync()}return this.matchCheckTest(Y,J)}matchFinish(Z,J){if(this.#X(Z))return;if(!this.includeChildMatches&&this.#J?.add){let Y=`${Z.relativePosix()}/**`;this.#J.add(Y)}let X=this.opts.absolute===void 0?J:this.opts.absolute;this.seen.add(Z);let $=this.opts.mark&&Z.isDirectory()?this.#$:"";if(this.opts.withFileTypes)this.matchEmit(Z);else if(X){let Y=this.opts.posix?Z.fullpathPosix():Z.fullpath();this.matchEmit(Y+$)}else{let Y=this.opts.posix?Z.relativePosix():Z.relative(),Q=this.opts.dotRelative&&!Y.startsWith(".."+this.#$)?"."+this.#$:"";this.matchEmit(!Y?"."+$:Q+Y+$)}}async match(Z,J,X){let $=await this.matchCheck(Z,X);if($)this.matchFinish($,J)}matchSync(Z,J,X){let $=this.matchCheckSync(Z,X);if($)this.matchFinish($,J)}walkCB(Z,J,X){if(this.signal?.aborted)X();this.walkCB2(Z,J,new LG(this.opts),X)}walkCB2(Z,J,X,$){if(this.#Y(Z))return $();if(this.signal?.aborted)$();if(this.paused){this.onResume(()=>this.walkCB2(Z,J,X,$));return}X.processPatterns(Z,J);let Y=1,Q=()=>{if(--Y===0)$()};for(let[K,W,G]of X.matches.entries()){if(this.#X(K))continue;Y++,this.match(K,W,G).then(()=>Q())}for(let K of X.subwalkTargets()){if(this.maxDepth!==1/0&&K.depth()>=this.maxDepth)continue;Y++;let W=K.readdirCached();if(K.calledReaddir())this.walkCB3(K,W,X,Q);else K.readdirCB((G,z)=>this.walkCB3(K,z,X,Q),!0)}Q()}walkCB3(Z,J,X,$){X=X.filterEntries(Z,J);let Y=1,Q=()=>{if(--Y===0)$()};for(let[K,W,G]of X.matches.entries()){if(this.#X(K))continue;Y++,this.match(K,W,G).then(()=>Q())}for(let[K,W]of X.subwalks.entries())Y++,this.walkCB2(K,W,X.child(),Q);Q()}walkCBSync(Z,J,X){if(this.signal?.aborted)X();this.walkCB2Sync(Z,J,new LG(this.opts),X)}walkCB2Sync(Z,J,X,$){if(this.#Y(Z))return $();if(this.signal?.aborted)$();if(this.paused){this.onResume(()=>this.walkCB2Sync(Z,J,X,$));return}X.processPatterns(Z,J);let Y=1,Q=()=>{if(--Y===0)$()};for(let[K,W,G]of X.matches.entries()){if(this.#X(K))continue;this.matchSync(K,W,G)}for(let K of X.subwalkTargets()){if(this.maxDepth!==1/0&&K.depth()>=this.maxDepth)continue;Y++;let W=K.readdirSync();this.walkCB3Sync(K,W,X,Q)}Q()}walkCB3Sync(Z,J,X,$){X=X.filterEntries(Z,J);let Y=1,Q=()=>{if(--Y===0)$()};for(let[K,W,G]of X.matches.entries()){if(this.#X(K))continue;this.matchSync(K,W,G)}for(let[K,W]of X.subwalks.entries())Y++,this.walkCB2Sync(K,W,X.child(),Q);Q()}}class SF extends $R{matches=new Set;constructor(Z,J,X){super(Z,J,X)}matchEmit(Z){this.matches.add(Z)}async walk(){if(this.signal?.aborted)throw this.signal.reason;if(this.path.isUnknown())await this.path.lstat();return await new Promise((Z,J)=>{this.walkCB(this.path,this.patterns,()=>{if(this.signal?.aborted)J(this.signal.reason);else Z(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;if(this.path.isUnknown())this.path.lstatSync();return this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}}class AF extends $R{results;constructor(Z,J,X){super(Z,J,X);this.results=new f$({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(Z){if(this.results.write(Z),!this.results.flowing)this.pause()}stream(){let Z=this.path;if(Z.isUnknown())Z.lstat().then(()=>{this.walkCB(Z,this.patterns,()=>this.results.end())});else this.walkCB(Z,this.patterns,()=>this.results.end());return this.results}streamSync(){if(this.path.isUnknown())this.path.lstatSync();return this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}}var fx1=typeof process==="object"&&process&&typeof process.platform==="string"?process.platform:"linux";class Y7{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(Z,J){if(!J)throw new TypeError("glob options required");if(this.withFileTypes=!!J.withFileTypes,this.signal=J.signal,this.follow=!!J.follow,this.dot=!!J.dot,this.dotRelative=!!J.dotRelative,this.nodir=!!J.nodir,this.mark=!!J.mark,!J.cwd)this.cwd="";else if(J.cwd instanceof URL||J.cwd.startsWith("file://"))J.cwd=Cx1(J.cwd);if(this.cwd=J.cwd||"",this.root=J.root,this.magicalBraces=!!J.magicalBraces,this.nobrace=!!J.nobrace,this.noext=!!J.noext,this.realpath=!!J.realpath,this.absolute=J.absolute,this.includeChildMatches=J.includeChildMatches!==!1,this.noglobstar=!!J.noglobstar,this.matchBase=!!J.matchBase,this.maxDepth=typeof J.maxDepth==="number"?J.maxDepth:1/0,this.stat=!!J.stat,this.ignore=J.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof Z==="string")Z=[Z];if(this.windowsPathsNoEscape=!!J.windowsPathsNoEscape||J.allowWindowsEscape===!1,this.windowsPathsNoEscape)Z=Z.map((W)=>W.replace(/\\/g,"/"));if(this.matchBase){if(J.noglobstar)throw new TypeError("base matching requires globstar");Z=Z.map((W)=>W.includes("/")?W:`./**/${W}`)}if(this.pattern=Z,this.platform=J.platform||fx1,this.opts={...J,platform:this.platform},J.scurry){if(this.scurry=J.scurry,J.nocase!==void 0&&J.nocase!==J.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let W=J.platform==="win32"?UG:J.platform==="darwin"?hF:J.platform?jG:Hg;this.scurry=new W(this.cwd,{nocase:J.nocase,fs:J.fs})}this.nocase=this.scurry.nocase;let X=this.platform==="darwin"||this.platform==="win32",$={...J,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:X,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},Y=this.pattern.map((W)=>new H4(W,$)),[Q,K]=Y.reduce((W,G)=>{return W[0].push(...G.set),W[1].push(...G.globParts),W},[[],[]]);this.patterns=Q.map((W,G)=>{let z=K[G];if(!z)throw new Error("invalid pattern object");return new Q3(W,z,0,this.platform)})}async walk(){return[...await new SF(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new SF(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new AF(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new AF(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}}var YR=(Z,J={})=>{if(!Array.isArray(Z))Z=[Z];for(let X of Z)if(new H4(X,J).hasMagic())return!0;return!1};function uF(Z,J={}){return new Y7(Z,J).streamSync()}function wg(Z,J={}){return new Y7(Z,J).stream()}function xg(Z,J={}){return new Y7(Z,J).walkSync()}async function cg(Z,J={}){return new Y7(Z,J).walk()}function lF(Z,J={}){return new Y7(Z,J).iterateSync()}function Ug(Z,J={}){return new Y7(Z,J).iterate()}var kx1=uF,Ex1=Object.assign(wg,{sync:uF}),Ix1=lF,_x1=Object.assign(Ug,{sync:lF}),bx1=Object.assign(xg,{stream:uF,iterate:lF}),mF=Object.assign(cg,{glob:cg,globSync:xg,sync:bx1,globStream:wg,stream:Ex1,globStreamSync:uF,streamSync:kx1,globIterate:Ug,iterate:_x1,globIterateSync:lF,iterateSync:Ix1,Glob:Y7,hasMagic:YR,escape:Z3,unescape:F9});mF.glob=mF;class QR{constructor(){this._listeners={}}addEventListener(Z,J){let X=this._listeners;if(X[Z]===void 0)X[Z]=[];if(X[Z].indexOf(J)===-1)X[Z].push(J);return this}removeEventListener(Z,J){let $=this._listeners[Z];if($!==void 0){let Y=$.indexOf(J);if(Y!==-1)$.splice(Y,1)}return this}dispatchEvent(Z){let X=this._listeners[Z.type];if(X!==void 0){let $=X.slice(0);for(let Y=0,Q=$.length;Y<Q;Y++)$[Y].call(this,Z)}return this}dispose(){for(let Z in this._listeners)delete this._listeners[Z]}}class $Z{constructor(Z,J,X,$={}){if(this._name=void 0,this._parent=void 0,this._child=void 0,this._attributes=void 0,this._disposed=!1,this._name=Z,this._parent=J,this._child=X,this._attributes=$,!J.isOnGraph(X))throw new Error("Cannot connect disconnected graphs.")}getName(){return this._name}getParent(){return this._parent}getChild(){return this._child}setChild(Z){return this._child=Z,this}getAttributes(){return this._attributes}dispose(){if(this._disposed)return;this._parent._destroyRef(this),this._disposed=!0}isDisposed(){return this._disposed}}class yF extends QR{constructor(...Z){super(...Z);this._emptySet=new Set,this._edges=new Set,this._parentEdges=new Map,this._childEdges=new Map}listEdges(){return Array.from(this._edges)}listParentEdges(Z){return Array.from(this._childEdges.get(Z)||this._emptySet)}listParents(Z){let J=new Set;for(let X of this.listParentEdges(Z))J.add(X.getParent());return Array.from(J)}listChildEdges(Z){return Array.from(this._parentEdges.get(Z)||this._emptySet)}listChildren(Z){let J=new Set;for(let X of this.listChildEdges(Z))J.add(X.getChild());return Array.from(J)}disconnectParents(Z,J){for(let X of this.listParentEdges(Z))if(!J||J(X.getParent()))X.dispose();return this}_createEdge(Z,J,X,$){let Y=new $Z(Z,J,X,$);this._edges.add(Y);let Q=Y.getParent();if(!this._parentEdges.has(Q))this._parentEdges.set(Q,new Set);this._parentEdges.get(Q).add(Y);let K=Y.getChild();if(!this._childEdges.has(K))this._childEdges.set(K,new Set);return this._childEdges.get(K).add(Y),Y}_destroyEdge(Z){return this._edges.delete(Z),this._parentEdges.get(Z.getParent()).delete(Z),this._childEdges.get(Z.getChild()).delete(Z),this}}function DG(){return DG=Object.assign||function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var $ in X)if(Object.prototype.hasOwnProperty.call(X,$))Z[$]=X[$]}return Z},DG.apply(this,arguments)}class x9{constructor(Z){if(this.list=[],Z)for(let J of Z)this.list.push(J)}add(Z){this.list.push(Z)}remove(Z){let J=this.list.indexOf(Z);if(J>=0)this.list.splice(J,1)}removeChild(Z){let J=[];for(let X of this.list)if(X.getChild()===Z)J.push(X);for(let X of J)this.remove(X);return J}listRefsByChild(Z){let J=[];for(let X of this.list)if(X.getChild()===Z)J.push(X);return J}values(){return this.list}}class c1{constructor(Z){if(this.set=new Set,this.map=new Map,Z)for(let J of Z)this.add(J)}add(Z){let J=Z.getChild();this.removeChild(J),this.set.add(Z),this.map.set(J,Z)}remove(Z){this.set.delete(Z),this.map.delete(Z.getChild())}removeChild(Z){let J=this.map.get(Z)||null;if(J)this.remove(J);return J}getRefByChild(Z){return this.map.get(Z)||null}values(){return Array.from(this.set)}}class A6{constructor(Z){if(this.map={},Z)Object.assign(this.map,Z)}set(Z,J){this.map[Z]=J}delete(Z){delete this.map[Z]}get(Z){return this.map[Z]||null}keys(){return Object.keys(this.map)}values(){return Object.values(this.map)}}var H1=Symbol("attributes"),hJ=Symbol("immutableKeys");class pF extends QR{constructor(Z){super();this._disposed=!1,this.graph=void 0,this[H1]=void 0,this[hJ]=void 0,this.graph=Z,this[hJ]=new Set,this[H1]=this._createAttributes()}getDefaults(){return{}}_createAttributes(){let Z=this.getDefaults(),J={};for(let X in Z){let $=Z[X];if($ instanceof pF){let Y=this.graph._createEdge(X,this,$);this[hJ].add(X),J[X]=Y}else J[X]=$}return J}isOnGraph(Z){return this.graph===Z.graph}isDisposed(){return this._disposed}dispose(){if(this._disposed)return;this.graph.listChildEdges(this).forEach((Z)=>Z.dispose()),this.graph.disconnectParents(this),this._disposed=!0,this.dispatchEvent({type:"dispose"})}detach(){return this.graph.disconnectParents(this),this}swap(Z,J){for(let X in this[H1]){let $=this[H1][X];if($ instanceof $Z){let Y=$;if(Y.getChild()===Z)this.setRef(X,J,Y.getAttributes())}else if($ instanceof x9)for(let Y of $.listRefsByChild(Z)){let Q=Y.getAttributes();this.removeRef(X,Z),this.addRef(X,J,Q)}else if($ instanceof c1){let Y=$.getRefByChild(Z);if(Y){let Q=Y.getAttributes();this.removeRef(X,Z),this.addRef(X,J,Q)}}else if($ instanceof A6)for(let Y of $.keys()){let Q=$.get(Y);if(Q.getChild()===Z)this.setRefMap(X,Y,J,Q.getAttributes())}}return this}get(Z){return this[H1][Z]}set(Z,J){return this[H1][Z]=J,this.dispatchEvent({type:"change",attribute:Z})}getRef(Z){let J=this[H1][Z];return J?J.getChild():null}setRef(Z,J,X){if(this[hJ].has(Z))throw new Error(`Cannot overwrite immutable attribute, "${Z}".`);let $=this[H1][Z];if($)$.dispose();if(!J)return this;let Y=this.graph._createEdge(Z,this,J,X);return this[H1][Z]=Y,this.dispatchEvent({type:"change",attribute:Z})}listRefs(Z){return this.assertRefList(Z).values().map((X)=>X.getChild())}addRef(Z,J,X){let $=this.graph._createEdge(Z,this,J,X);return this.assertRefList(Z).add($),this.dispatchEvent({type:"change",attribute:Z})}removeRef(Z,J){let X=this.assertRefList(Z);if(X instanceof x9)for(let $ of X.listRefsByChild(J))$.dispose();else{let $=X.getRefByChild(J);if($)$.dispose()}return this}assertRefList(Z){let J=this[H1][Z];if(J instanceof x9||J instanceof c1)return J;throw new Error(`Expected RefList or RefSet for attribute "${Z}"`)}listRefMapKeys(Z){return this.assertRefMap(Z).keys()}listRefMapValues(Z){return this.assertRefMap(Z).values().map((J)=>J.getChild())}getRefMap(Z,J){let $=this.assertRefMap(Z).get(J);return $?$.getChild():null}setRefMap(Z,J,X,$){let Y=this.assertRefMap(Z),Q=Y.get(J);if(Q)Q.dispose();if(!X)return this;$=Object.assign($||{},{key:J});let K=this.graph._createEdge(Z,this,X,DG({},$,{key:J}));return Y.set(J,K),this.dispatchEvent({type:"change",attribute:Z,key:J})}assertRefMap(Z){let J=this[H1][Z];if(J instanceof A6)return J;throw new Error(`Expected RefMap for attribute "${Z}"`)}dispatchEvent(Z){return super.dispatchEvent(DG({},Z,{target:this})),this.graph.dispatchEvent(DG({},Z,{target:this,type:`node:${Z.type}`})),this}_destroyRef(Z){let J=Z.getName();if(this[H1][J]===Z){if(this[H1][J]=null,this[hJ].has(J))Z.getChild().dispose()}else if(this[H1][J]instanceof x9)this[H1][J].remove(Z);else if(this[H1][J]instanceof c1)this[H1][J].remove(Z);else if(this[H1][J]instanceof A6){let X=this[H1][J];for(let $ of X.keys())if(X.get($)===Z)X.delete($)}else return;this.graph._destroyEdge(Z),this.dispatchEvent({type:"change",attribute:J})}}var Og="v4.2.1",I$="@glb.bin",g;(function(Z){Z.ACCESSOR="Accessor",Z.ANIMATION="Animation",Z.ANIMATION_CHANNEL="AnimationChannel",Z.ANIMATION_SAMPLER="AnimationSampler",Z.BUFFER="Buffer",Z.CAMERA="Camera",Z.MATERIAL="Material",Z.MESH="Mesh",Z.PRIMITIVE="Primitive",Z.PRIMITIVE_TARGET="PrimitiveTarget",Z.NODE="Node",Z.ROOT="Root",Z.SCENE="Scene",Z.SKIN="Skin",Z.TEXTURE="Texture",Z.TEXTURE_INFO="TextureInfo"})(g||(g={}));var sF;(function(Z){Z.INTERLEAVED="interleaved",Z.SEPARATE="separate"})(sF||(sF={}));var b5;(function(Z){Z.ARRAY_BUFFER="ARRAY_BUFFER",Z.ELEMENT_ARRAY_BUFFER="ELEMENT_ARRAY_BUFFER",Z.INVERSE_BIND_MATRICES="INVERSE_BIND_MATRICES",Z.OTHER="OTHER",Z.SPARSE="SPARSE"})(b5||(b5={}));var V5;(function(Z){Z[Z.R=4096]="R",Z[Z.G=256]="G",Z[Z.B=16]="B",Z[Z.A=1]="A"})(V5||(V5={}));var YZ;(function(Z){Z.GLTF="GLTF",Z.GLB="GLB"})(YZ||(YZ={}));var AJ={"5120":Int8Array,"5121":Uint8Array,"5122":Int16Array,"5123":Uint16Array,"5125":Uint32Array,"5126":Float32Array};class E0{static createBufferFromDataURI(Z){if(typeof Buffer==="undefined"){let J=atob(Z.split(",")[1]),X=new Uint8Array(J.length);for(let $=0;$<J.length;$++)X[$]=J.charCodeAt($);return X}else{let J=Z.split(",")[1],X=Z.indexOf("base64")>=0;return Buffer.from(J,X?"base64":"utf8")}}static encodeText(Z){return new TextEncoder().encode(Z)}static decodeText(Z){return new TextDecoder().decode(Z)}static concat(Z){let J=0;for(let Y of Z)J+=Y.byteLength;let X=new Uint8Array(J),$=0;for(let Y of Z)X.set(Y,$),$+=Y.byteLength;return X}static pad(Z,J=0){let X=this.padNumber(Z.byteLength);if(X===Z.byteLength)return Z;let $=new Uint8Array(X);if($.set(Z),J!==0)for(let Y=Z.byteLength;Y<X;Y++)$[Y]=J;return $}static padNumber(Z){return Math.ceil(Z/4)*4}static equals(Z,J){if(Z===J)return!0;if(Z.byteLength!==J.byteLength)return!1;let X=Z.byteLength;while(X--)if(Z[X]!==J[X])return!1;return!0}static toView(Z,J=0,X=1/0){return new Uint8Array(Z.buffer,Z.byteOffset+J,Math.min(Z.byteLength,X))}static assertView(Z){if(Z&&!ArrayBuffer.isView(Z))throw new Error(`Method requires Uint8Array parameter; received "${typeof Z}".`);return Z}}class vR{static hexToFactor(Z,J){Z=Math.floor(Z);let X=J;return X[0]=(Z>>16&255)/255,X[1]=(Z>>8&255)/255,X[2]=(Z&255)/255,this.convertSRGBToLinear(J,J)}static factorToHex(Z){let J=[...Z],[X,$,Y]=this.convertLinearToSRGB(Z,J);return X*255<<16^$*255<<8^Y*255<<0}static convertSRGBToLinear(Z,J){let X=Z,$=J;for(let Y=0;Y<3;Y++)$[Y]=X[Y]<0.04045?X[Y]*0.0773993808:Math.pow(X[Y]*0.9478672986+0.0521327014,2.4);return J}static convertLinearToSRGB(Z,J){let X=Z,$=J;for(let Y=0;Y<3;Y++)$[Y]=X[Y]<0.0031308?X[Y]*12.92:1.055*Math.pow(X[Y],0.41666)-0.055;return J}}class Ng{match(Z){return Z.length>=3&&Z[0]===255&&Z[1]===216&&Z[2]===255}getSize(Z){let J=new DataView(Z.buffer,Z.byteOffset+4),X,$;while(J.byteLength){if(X=J.getUint16(0,!1),hx1(J,X),$=J.getUint8(X+1),$===192||$===193||$===194)return[J.getUint16(X+7,!1),J.getUint16(X+5,!1)];J=new DataView(Z.buffer,J.byteOffset+X+2)}throw new TypeError("Invalid JPG, no size found")}getChannels(Z){return 3}}class tF{match(Z){return Z.length>=8&&Z[0]===137&&Z[1]===80&&Z[2]===78&&Z[3]===71&&Z[4]===13&&Z[5]===10&&Z[6]===26&&Z[7]===10}getSize(Z){let J=new DataView(Z.buffer,Z.byteOffset);if(E0.decodeText(Z.slice(12,16))===tF.PNG_FRIED_CHUNK_NAME)return[J.getUint32(32,!1),J.getUint32(36,!1)];return[J.getUint32(16,!1),J.getUint32(20,!1)]}getChannels(Z){return 4}}tF.PNG_FRIED_CHUNK_NAME="CgBI";class _5{static registerFormat(Z,J){this.impls[Z]=J}static getMimeType(Z){for(let J in this.impls)if(this.impls[J].match(Z))return J;return null}static getSize(Z,J){if(!this.impls[J])return null;return this.impls[J].getSize(Z)}static getChannels(Z,J){if(!this.impls[J])return null;return this.impls[J].getChannels(Z)}static getVRAMByteLength(Z,J){if(!this.impls[J])return null;if(this.impls[J].getVRAMByteLength)return this.impls[J].getVRAMByteLength(Z);let X=0,$=4,Y=this.getSize(Z,J);if(!Y)return null;while(Y[0]>1||Y[1]>1)X+=Y[0]*Y[1]*$,Y[0]=Math.max(Math.floor(Y[0]/2),1),Y[1]=Math.max(Math.floor(Y[1]/2),1);return X+=1*$,X}static mimeTypeToExtension(Z){if(Z==="image/jpeg")return"jpg";return Z.split("/").pop()}static extensionToMimeType(Z){if(Z==="jpg")return"image/jpeg";if(!Z)return"";return`image/${Z}`}}_5.impls={"image/jpeg":new Ng,"image/png":new tF};function hx1(Z,J){if(J>Z.byteLength)throw new TypeError("Corrupt JPG, exceeded buffer limits");if(Z.getUint8(J)!==255)throw new TypeError("Invalid JPG, marker table corrupted");return Z}class QZ{static basename(Z){let J=Z.split(/[\\/]/).pop();return J.substring(0,J.lastIndexOf("."))}static extension(Z){if(Z.startsWith("data:image/")){let J=Z.match(/data:(image\/\w+)/)[1];return _5.mimeTypeToExtension(J)}else if(Z.startsWith("data:model/gltf+json"))return"gltf";else if(Z.startsWith("data:model/gltf-binary"))return"glb";else if(Z.startsWith("data:application/"))return"bin";return Z.split(/[\\/]/).pop().split(/[.]/).pop()}}var WR=typeof Float32Array!=="undefined"?Float32Array:Array;if(!Math.hypot)Math.hypot=function(){var Z=0,J=arguments.length;while(J--)Z+=arguments[J]*arguments[J];return Math.sqrt(Z)};function Sx1(){var Z=new WR(3);if(WR!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0;return Z}function KR(Z){var J=Z[0],X=Z[1],$=Z[2];return Math.hypot(J,X,$)}function Ax1(Z,J,X){var $=J[0],Y=J[1],Q=J[2],K=X[3]*$+X[7]*Y+X[11]*Q+X[15];return K=K||1,Z[0]=(X[0]*$+X[4]*Y+X[8]*Q+X[12])/K,Z[1]=(X[1]*$+X[5]*Y+X[9]*Q+X[13])/K,Z[2]=(X[2]*$+X[6]*Y+X[10]*Q+X[14])/K,Z}(function(){var Z=Sx1();return function(J,X,$,Y,Q,K){var W,G;if(!X)X=3;if(!$)$=0;if(Y)G=Math.min(Y*X+$,J.length);else G=J.length;for(W=$;W<G;W+=X)Z[0]=J[W],Z[1]=J[W+1],Z[2]=J[W+2],Q(Z,Z,K),J[W]=Z[0],J[W+1]=Z[1],J[W+2]=Z[2];return J}})();function OG(Z){let J=Pg(),X=Z.propertyType===g.NODE?[Z]:Z.listChildren();for(let $ of X)$.traverse((Y)=>{let Q=Y.getMesh();if(!Q)return;let K=mx1(Q,Y.getWorldMatrix());if(K.min.every(isFinite)&&K.max.every(isFinite))GR(K.min,J),GR(K.max,J)});return J}function mx1(Z,J){let X=Pg();for(let $ of Z.listPrimitives()){let Y=$.getAttribute("POSITION"),Q=$.getIndices();if(!Y)continue;let K=[0,0,0],W=[0,0,0];for(let G=0,z=Q?Q.getCount():Y.getCount();G<z;G++){let V=Q?Q.getScalar(G):G;K=Y.getElement(V,K),W=Ax1(W,K,J),GR(W,X)}}return X}function GR(Z,J){for(let X=0;X<3;X++)J.min[X]=Math.min(Z[X],J.min[X]),J.max[X]=Math.max(Z[X],J.max[X])}function Pg(){return{min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]}}var jg="https://null.example";class c4{static dirname(Z){let J=Z.lastIndexOf("/");if(J===-1)return"./";return Z.substring(0,J+1)}static basename(Z){return QZ.basename(new URL(Z,jg).pathname)}static extension(Z){return QZ.extension(new URL(Z,jg).pathname)}static resolve(Z,J){if(!this.isRelativePath(J))return J;let X=Z.split("/"),$=J.split("/");X.pop();for(let Y=0;Y<$.length;Y++){if($[Y]===".")continue;if($[Y]==="..")X.pop();else X.push($[Y])}return X.join("/")}static isAbsoluteURL(Z){return this.PROTOCOL_REGEXP.test(Z)}static isRelativePath(Z){return!/^(?:[a-zA-Z]+:)?\//.test(Z)}}c4.DEFAULT_INIT={};c4.PROTOCOL_REGEXP=/^[a-zA-Z]+:\/\//;function Bg(Z){return Object.prototype.toString.call(Z)==="[object Object]"}function E$(Z){if(Bg(Z)===!1)return!1;let J=Z.constructor;if(J===void 0)return!0;let X=J.prototype;if(Bg(X)===!1)return!1;if(Object.hasOwn(X,"isPrototypeOf")===!1)return!1;return!0}var zR,MG;(function(Z){Z[Z.SILENT=4]="SILENT",Z[Z.ERROR=3]="ERROR",Z[Z.WARN=2]="WARN",Z[Z.INFO=1]="INFO",Z[Z.DEBUG=0]="DEBUG"})(MG||(MG={}));class z5{constructor(Z){this.verbosity=void 0,this.verbosity=Z}debug(Z){if(this.verbosity<=z5.Verbosity.DEBUG)console.debug(Z)}info(Z){if(this.verbosity<=z5.Verbosity.INFO)console.info(Z)}warn(Z){if(this.verbosity<=z5.Verbosity.WARN)console.warn(Z)}error(Z){if(this.verbosity<=z5.Verbosity.ERROR)console.error(Z)}}zR=z5;z5.Verbosity=MG;z5.DEFAULT_INSTANCE=new zR(zR.Verbosity.INFO);function ux1(Z){var J=Z[0],X=Z[1],$=Z[2],Y=Z[3],Q=Z[4],K=Z[5],W=Z[6],G=Z[7],z=Z[8],V=Z[9],H=Z[10],v=Z[11],q=Z[12],F=Z[13],c=Z[14],w=Z[15],x=J*K-X*Q,j=J*W-$*Q,B=J*G-Y*Q,L=X*W-$*K,R=X*G-Y*K,M=$*G-Y*W,O=z*F-V*q,P=z*c-H*q,N=z*w-v*q,_=V*c-H*F,k=V*w-v*F,h=H*w-v*c;return x*h-j*k+B*_+L*N-R*P+M*O}function lx1(Z,J,X){var $=J[0],Y=J[1],Q=J[2],K=J[3],W=J[4],G=J[5],z=J[6],V=J[7],H=J[8],v=J[9],q=J[10],F=J[11],c=J[12],w=J[13],x=J[14],j=J[15],B=X[0],L=X[1],R=X[2],M=X[3];return Z[0]=B*$+L*W+R*H+M*c,Z[1]=B*Y+L*G+R*v+M*w,Z[2]=B*Q+L*z+R*q+M*x,Z[3]=B*K+L*V+R*F+M*j,B=X[4],L=X[5],R=X[6],M=X[7],Z[4]=B*$+L*W+R*H+M*c,Z[5]=B*Y+L*G+R*v+M*w,Z[6]=B*Q+L*z+R*q+M*x,Z[7]=B*K+L*V+R*F+M*j,B=X[8],L=X[9],R=X[10],M=X[11],Z[8]=B*$+L*W+R*H+M*c,Z[9]=B*Y+L*G+R*v+M*w,Z[10]=B*Q+L*z+R*q+M*x,Z[11]=B*K+L*V+R*F+M*j,B=X[12],L=X[13],R=X[14],M=X[15],Z[12]=B*$+L*W+R*H+M*c,Z[13]=B*Y+L*G+R*v+M*w,Z[14]=B*Q+L*z+R*q+M*x,Z[15]=B*K+L*V+R*F+M*j,Z}function yx1(Z,J){var X=J[0],$=J[1],Y=J[2],Q=J[4],K=J[5],W=J[6],G=J[8],z=J[9],V=J[10];return Z[0]=Math.hypot(X,$,Y),Z[1]=Math.hypot(Q,K,W),Z[2]=Math.hypot(G,z,V),Z}function px1(Z,J){var X=new WR(3);yx1(X,J);var $=1/X[0],Y=1/X[1],Q=1/X[2],K=J[0]*$,W=J[1]*Y,G=J[2]*Q,z=J[4]*$,V=J[5]*Y,H=J[6]*Q,v=J[8]*$,q=J[9]*Y,F=J[10]*Q,c=K+V+F,w=0;if(c>0)w=Math.sqrt(c+1)*2,Z[3]=0.25*w,Z[0]=(H-q)/w,Z[1]=(v-G)/w,Z[2]=(W-z)/w;else if(K>V&&K>F)w=Math.sqrt(1+K-V-F)*2,Z[3]=(H-q)/w,Z[0]=0.25*w,Z[1]=(W+z)/w,Z[2]=(v+G)/w;else if(V>F)w=Math.sqrt(1+V-K-F)*2,Z[3]=(v-G)/w,Z[0]=(W+z)/w,Z[1]=0.25*w,Z[2]=(H+q)/w;else w=Math.sqrt(1+F-K-V)*2,Z[3]=(W-z)/w,Z[0]=(v+G)/w,Z[1]=(H+q)/w,Z[2]=0.25*w;return Z}class I0{static identity(Z){return Z}static eq(Z,J,X=0.00001){if(Z.length!==J.length)return!1;for(let $=0;$<Z.length;$++)if(Math.abs(Z[$]-J[$])>X)return!1;return!0}static clamp(Z,J,X){if(Z<J)return J;if(Z>X)return X;return Z}static decodeNormalizedInt(Z,J){switch(J){case 5126:return Z;case 5123:return Z/65535;case 5121:return Z/255;case 5122:return Math.max(Z/32767,-1);case 5120:return Math.max(Z/127,-1);default:throw new Error("Invalid component type.")}}static encodeNormalizedInt(Z,J){switch(J){case 5126:return Z;case 5123:return Math.round(I0.clamp(Z,0,1)*65535);case 5121:return Math.round(I0.clamp(Z,0,1)*255);case 5122:return Math.round(I0.clamp(Z,-1,1)*32767);case 5120:return Math.round(I0.clamp(Z,-1,1)*127);default:throw new Error("Invalid component type.")}}static decompose(Z,J,X,$){let Y=KR([Z[0],Z[1],Z[2]]),Q=KR([Z[4],Z[5],Z[6]]),K=KR([Z[8],Z[9],Z[10]]);if(ux1(Z)<0)Y=-Y;J[0]=Z[12],J[1]=Z[13],J[2]=Z[14];let G=Z.slice(),z=1/Y,V=1/Q,H=1/K;G[0]*=z,G[1]*=z,G[2]*=z,G[4]*=V,G[5]*=V,G[6]*=V,G[8]*=H,G[9]*=H,G[10]*=H,px1(X,G),$[0]=Y,$[1]=Q,$[2]=K}static compose(Z,J,X,$){let Y=$,Q=J[0],K=J[1],W=J[2],G=J[3],z=Q+Q,V=K+K,H=W+W,v=Q*z,q=Q*V,F=Q*H,c=K*V,w=K*H,x=W*H,j=G*z,B=G*V,L=G*H,R=X[0],M=X[1],O=X[2];return Y[0]=(1-(c+x))*R,Y[1]=(q+L)*R,Y[2]=(F-B)*R,Y[3]=0,Y[4]=(q-L)*M,Y[5]=(1-(v+x))*M,Y[6]=(w+j)*M,Y[7]=0,Y[8]=(F+B)*O,Y[9]=(w-j)*O,Y[10]=(1-(v+c))*O,Y[11]=0,Y[12]=Z[0],Y[13]=Z[1],Y[14]=Z[2],Y[15]=1,Y}}function ix1(Z,J){if(!!Z!==!!J)return!1;let X=Z.getChild(),$=J.getChild();return X===$||X.equals($)}function gx1(Z,J){if(!!Z!==!!J)return!1;let X=Z.values(),$=J.values();if(X.length!==$.length)return!1;for(let Y=0;Y<X.length;Y++){let Q=X[Y],K=$[Y];if(Q.getChild()===K.getChild())continue;if(!Q.getChild().equals(K.getChild()))return!1}return!0}function dx1(Z,J){if(!!Z!==!!J)return!1;let X=Z.keys(),$=J.keys();if(X.length!==$.length)return!1;for(let Y of X){let Q=Z.get(Y),K=J.get(Y);if(!!Q!==!!K)return!1;let W=Q.getChild(),G=K.getChild();if(W===G)continue;if(!W.equals(G))return!1}return!0}function Tg(Z,J){if(Z===J)return!0;if(!!Z!==!!J||!Z||!J)return!1;if(Z.length!==J.length)return!1;for(let X=0;X<Z.length;X++)if(Z[X]!==J[X])return!1;return!0}function Cg(Z,J){if(Z===J)return!0;if(!!Z!==!!J)return!1;if(!E$(Z)||!E$(J))return Z===J;let X=Z,$=J,Y=0,Q=0,K;for(K in X)Y++;for(K in $)Q++;if(Y!==Q)return!1;for(K in X){let W=X[K],G=$[K];if(oF(W)&&oF(G)){if(!Tg(W,G))return!1}else if(E$(W)&&E$(G)){if(!Cg(W,G))return!1}else if(W!==G)return!1}return!0}function oF(Z){return Array.isArray(Z)||ArrayBuffer.isView(Z)}var Lg="23456789abdegjkmnpqrvwxyzABDEGJKMNPQRVWXYZ",ax1=999,nx1=6,Dg=new Set,sx1=function Z(){let J="";for(let X=0;X<nx1;X++)J+=Lg.charAt(Math.floor(Math.random()*Lg.length));return J},fg=function Z(){for(let J=0;J<ax1;J++){let X=sx1();if(!Dg.has(X))return Dg.add(X),X}return""},SJ=(Z)=>Z,ox1=new Set;class eF extends pF{constructor(Z,J=""){super(Z);this[H1].name=J,this.init(),this.dispatchEvent({type:"create"})}getGraph(){return this.graph}getDefaults(){return Object.assign(super.getDefaults(),{name:"",extras:{}})}set(Z,J){if(Array.isArray(J))J=J.slice();return super.set(Z,J)}getName(){return this.get("name")}setName(Z){return this.set("name",Z)}getExtras(){return this.get("extras")}setExtras(Z){return this.set("extras",Z)}clone(){return new this.constructor(this.graph).copy(this,SJ)}copy(Z,J=SJ){for(let X in this[H1]){let $=this[H1][X];if($ instanceof $Z){if(!this[hJ].has(X))$.dispose()}else if($ instanceof x9||$ instanceof c1)for(let Y of $.values())Y.dispose();else if($ instanceof A6)for(let Y of $.values())Y.dispose()}for(let X in Z[H1]){let $=this[H1][X],Y=Z[H1][X];if(Y instanceof $Z)if(this[hJ].has(X))$.getChild().copy(J(Y.getChild()),J);else this.setRef(X,J(Y.getChild()),Y.getAttributes());else if(Y instanceof c1||Y instanceof x9)for(let Q of Y.values())this.addRef(X,J(Q.getChild()),Q.getAttributes());else if(Y instanceof A6)for(let Q of Y.keys()){let K=Y.get(Q);this.setRefMap(X,Q,J(K.getChild()),K.getAttributes())}else if(E$(Y))this[H1][X]=JSON.parse(JSON.stringify(Y));else if(Array.isArray(Y)||Y instanceof ArrayBuffer||ArrayBuffer.isView(Y))this[H1][X]=Y.slice();else this[H1][X]=Y}return this}equals(Z,J=ox1){if(this===Z)return!0;if(this.propertyType!==Z.propertyType)return!1;for(let X in this[H1]){if(J.has(X))continue;let $=this[H1][X],Y=Z[H1][X];if($ instanceof $Z||Y instanceof $Z){if(!ix1($,Y))return!1}else if($ instanceof c1||Y instanceof c1||$ instanceof x9||Y instanceof x9){if(!gx1($,Y))return!1}else if($ instanceof A6||Y instanceof A6){if(!dx1($,Y))return!1}else if(E$($)||E$(Y)){if(!Cg($,Y))return!1}else if(oF($)||oF(Y)){if(!Tg($,Y))return!1}else if($!==Y)return!1}return!0}detach(){return this.graph.disconnectParents(this,(Z)=>Z.propertyType!=="Root"),this}listParents(){return this.graph.listParents(this)}}class x6 extends eF{getDefaults(){return Object.assign(super.getDefaults(),{extensions:new A6})}getExtension(Z){return this.getRefMap("extensions",Z)}setExtension(Z,J){if(J)J._validateParent(this);return this.setRefMap("extensions",Z,J)}listExtensions(){return this.listRefMapValues("extensions")}}class K0 extends x6{init(){this.propertyType=g.ACCESSOR}getDefaults(){return Object.assign(super.getDefaults(),{array:null,type:K0.Type.SCALAR,componentType:K0.ComponentType.FLOAT,normalized:!1,sparse:!1,buffer:null})}static getElementSize(Z){switch(Z){case K0.Type.SCALAR:return 1;case K0.Type.VEC2:return 2;case K0.Type.VEC3:return 3;case K0.Type.VEC4:return 4;case K0.Type.MAT2:return 4;case K0.Type.MAT3:return 9;case K0.Type.MAT4:return 16;default:throw new Error("Unexpected type: "+Z)}}static getComponentSize(Z){switch(Z){case K0.ComponentType.BYTE:return 1;case K0.ComponentType.UNSIGNED_BYTE:return 1;case K0.ComponentType.SHORT:return 2;case K0.ComponentType.UNSIGNED_SHORT:return 2;case K0.ComponentType.UNSIGNED_INT:return 4;case K0.ComponentType.FLOAT:return 4;default:throw new Error("Unexpected component type: "+Z)}}getMinNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),$=this.getComponentType();if(this.getMin(Z),J)for(let Y=0;Y<X;Y++)Z[Y]=I0.decodeNormalizedInt(Z[Y],$);return Z}getMin(Z){let J=this.getArray(),X=this.getCount(),$=this.getElementSize();for(let Y=0;Y<$;Y++)Z[Y]=1/0;for(let Y=0;Y<X*$;Y+=$)for(let Q=0;Q<$;Q++){let K=J[Y+Q];if(Number.isFinite(K))Z[Q]=Math.min(Z[Q],K)}return Z}getMaxNormalized(Z){let J=this.getNormalized(),X=this.getElementSize(),$=this.getComponentType();if(this.getMax(Z),J)for(let Y=0;Y<X;Y++)Z[Y]=I0.decodeNormalizedInt(Z[Y],$);return Z}getMax(Z){let J=this.get("array"),X=this.getCount(),$=this.getElementSize();for(let Y=0;Y<$;Y++)Z[Y]=-1/0;for(let Y=0;Y<X*$;Y+=$)for(let Q=0;Q<$;Q++){let K=J[Y+Q];if(Number.isFinite(K))Z[Q]=Math.max(Z[Q],K)}return Z}getCount(){let Z=this.get("array");return Z?Z.length/this.getElementSize():0}getType(){return this.get("type")}setType(Z){return this.set("type",Z)}getElementSize(){return K0.getElementSize(this.get("type"))}getComponentSize(){return this.get("array").BYTES_PER_ELEMENT}getComponentType(){return this.get("componentType")}getNormalized(){return this.get("normalized")}setNormalized(Z){return this.set("normalized",Z)}getScalar(Z){let J=this.getElementSize(),X=this.getComponentType(),$=this.getArray();if(this.getNormalized())return I0.decodeNormalizedInt($[Z*J],X);return $[Z*J]}setScalar(Z,J){let X=this.getElementSize(),$=this.getComponentType(),Y=this.getArray();if(this.getNormalized())Y[Z*X]=I0.encodeNormalizedInt(J,$);else Y[Z*X]=J;return this}getElement(Z,J){let X=this.getNormalized(),$=this.getElementSize(),Y=this.getComponentType(),Q=this.getArray();for(let K=0;K<$;K++)if(X)J[K]=I0.decodeNormalizedInt(Q[Z*$+K],Y);else J[K]=Q[Z*$+K];return J}setElement(Z,J){let X=this.getNormalized(),$=this.getElementSize(),Y=this.getComponentType(),Q=this.getArray();for(let K=0;K<$;K++)if(X)Q[Z*$+K]=I0.encodeNormalizedInt(J[K],Y);else Q[Z*$+K]=J[K];return this}getSparse(){return this.get("sparse")}setSparse(Z){return this.set("sparse",Z)}getBuffer(){return this.getRef("buffer")}setBuffer(Z){return this.setRef("buffer",Z)}getArray(){return this.get("array")}setArray(Z){return this.set("componentType",Z?rx1(Z):K0.ComponentType.FLOAT),this.set("array",Z),this}getByteLength(){let Z=this.get("array");return Z?Z.byteLength:0}}K0.Type={SCALAR:"SCALAR",VEC2:"VEC2",VEC3:"VEC3",VEC4:"VEC4",MAT2:"MAT2",MAT3:"MAT3",MAT4:"MAT4"};K0.ComponentType={BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,UNSIGNED_INT:5125,FLOAT:5126};function rx1(Z){switch(Z.constructor){case Float32Array:return K0.ComponentType.FLOAT;case Uint32Array:return K0.ComponentType.UNSIGNED_INT;case Uint16Array:return K0.ComponentType.UNSIGNED_SHORT;case Uint8Array:return K0.ComponentType.UNSIGNED_BYTE;case Int16Array:return K0.ComponentType.SHORT;case Int8Array:return K0.ComponentType.BYTE;default:throw new Error("Unknown accessor componentType.")}}class HR extends x6{init(){this.propertyType=g.ANIMATION}getDefaults(){return Object.assign(super.getDefaults(),{channels:new c1,samplers:new c1})}addChannel(Z){return this.addRef("channels",Z)}removeChannel(Z){return this.removeRef("channels",Z)}listChannels(){return this.listRefs("channels")}addSampler(Z){return this.addRef("samplers",Z)}removeSampler(Z){return this.removeRef("samplers",Z)}listSamplers(){return this.listRefs("samplers")}}class KZ extends x6{init(){this.propertyType=g.ANIMATION_CHANNEL}getDefaults(){return Object.assign(super.getDefaults(),{targetPath:null,targetNode:null,sampler:null})}getTargetPath(){return this.get("targetPath")}setTargetPath(Z){return this.set("targetPath",Z)}getTargetNode(){return this.getRef("targetNode")}setTargetNode(Z){return this.setRef("targetNode",Z)}getSampler(){return this.getRef("sampler")}setSampler(Z){return this.setRef("sampler",Z)}}KZ.TargetPath={TRANSLATION:"translation",ROTATION:"rotation",SCALE:"scale",WEIGHTS:"weights"};class mJ extends x6{init(){this.propertyType=g.ANIMATION_SAMPLER}getDefaultAttributes(){return Object.assign(super.getDefaults(),{interpolation:mJ.Interpolation.LINEAR,input:null,output:null})}getInterpolation(){return this.get("interpolation")}setInterpolation(Z){return this.set("interpolation",Z)}getInput(){return this.getRef("input")}setInput(Z){return this.setRef("input",Z,{usage:b5.OTHER})}getOutput(){return this.getRef("output")}setOutput(Z){return this.setRef("output",Z,{usage:b5.OTHER})}}mJ.Interpolation={LINEAR:"LINEAR",STEP:"STEP",CUBICSPLINE:"CUBICSPLINE"};class qR extends x6{init(){this.propertyType=g.BUFFER}getDefaults(){return Object.assign(super.getDefaults(),{uri:""})}getURI(){return this.get("uri")}setURI(Z){return this.set("uri",Z)}}class _$ extends x6{init(){this.propertyType=g.CAMERA}getDefaults(){return Object.assign(super.getDefaults(),{type:_$.Type.PERSPECTIVE,znear:0.1,zfar:100,aspectRatio:null,yfov:Math.PI*2*50/360,xmag:1,ymag:1})}getType(){return this.get("type")}setType(Z){return this.set("type",Z)}getZNear(){return this.get("znear")}setZNear(Z){return this.set("znear",Z)}getZFar(){return this.get("zfar")}setZFar(Z){return this.set("zfar",Z)}getAspectRatio(){return this.get("aspectRatio")}setAspectRatio(Z){return this.set("aspectRatio",Z)}getYFov(){return this.get("yfov")}setYFov(Z){return this.set("yfov",Z)}getXMag(){return this.get("xmag")}setXMag(Z){return this.set("xmag",Z)}getYMag(){return this.get("ymag")}setYMag(Z){return this.set("ymag",Z)}}_$.Type={PERSPECTIVE:"perspective",ORTHOGRAPHIC:"orthographic"};class N1 extends eF{_validateParent(Z){if(!this.parentTypes.includes(Z.propertyType))throw new Error(`Parent "${Z.propertyType}" invalid for child "${this.propertyType}".`)}}N1.EXTENSION_NAME=void 0;class F1 extends x6{init(){this.propertyType=g.TEXTURE_INFO}getDefaults(){return Object.assign(super.getDefaults(),{texCoord:0,magFilter:null,minFilter:null,wrapS:F1.WrapMode.REPEAT,wrapT:F1.WrapMode.REPEAT})}getTexCoord(){return this.get("texCoord")}setTexCoord(Z){return this.set("texCoord",Z)}getMagFilter(){return this.get("magFilter")}setMagFilter(Z){return this.set("magFilter",Z)}getMinFilter(){return this.get("minFilter")}setMinFilter(Z){return this.set("minFilter",Z)}getWrapS(){return this.get("wrapS")}setWrapS(Z){return this.set("wrapS",Z)}getWrapT(){return this.get("wrapT")}setWrapT(Z){return this.set("wrapT",Z)}}F1.WrapMode={CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497};F1.MagFilter={NEAREST:9728,LINEAR:9729};F1.MinFilter={NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987};var{R:iF,G:gF,B:dF,A:tx1}=V5;class Q7 extends x6{init(){this.propertyType=g.MATERIAL}getDefaults(){return Object.assign(super.getDefaults(),{alphaMode:Q7.AlphaMode.OPAQUE,alphaCutoff:0.5,doubleSided:!1,baseColorFactor:[1,1,1,1],baseColorTexture:null,baseColorTextureInfo:new F1(this.graph,"baseColorTextureInfo"),emissiveFactor:[0,0,0],emissiveTexture:null,emissiveTextureInfo:new F1(this.graph,"emissiveTextureInfo"),normalScale:1,normalTexture:null,normalTextureInfo:new F1(this.graph,"normalTextureInfo"),occlusionStrength:1,occlusionTexture:null,occlusionTextureInfo:new F1(this.graph,"occlusionTextureInfo"),roughnessFactor:1,metallicFactor:1,metallicRoughnessTexture:null,metallicRoughnessTextureInfo:new F1(this.graph,"metallicRoughnessTextureInfo")})}getDoubleSided(){return this.get("doubleSided")}setDoubleSided(Z){return this.set("doubleSided",Z)}getAlpha(){return this.get("baseColorFactor")[3]}setAlpha(Z){let J=this.get("baseColorFactor").slice();return J[3]=Z,this.set("baseColorFactor",J)}getAlphaMode(){return this.get("alphaMode")}setAlphaMode(Z){return this.set("alphaMode",Z)}getAlphaCutoff(){return this.get("alphaCutoff")}setAlphaCutoff(Z){return this.set("alphaCutoff",Z)}getBaseColorFactor(){return this.get("baseColorFactor")}setBaseColorFactor(Z){return this.set("baseColorFactor",Z)}getBaseColorTexture(){return this.getRef("baseColorTexture")}getBaseColorTextureInfo(){return this.getRef("baseColorTexture")?this.getRef("baseColorTextureInfo"):null}setBaseColorTexture(Z){return this.setRef("baseColorTexture",Z,{channels:iF|gF|dF|tx1,isColor:!0})}getEmissiveFactor(){return this.get("emissiveFactor")}setEmissiveFactor(Z){return this.set("emissiveFactor",Z)}getEmissiveTexture(){return this.getRef("emissiveTexture")}getEmissiveTextureInfo(){return this.getRef("emissiveTexture")?this.getRef("emissiveTextureInfo"):null}setEmissiveTexture(Z){return this.setRef("emissiveTexture",Z,{channels:iF|gF|dF,isColor:!0})}getNormalScale(){return this.get("normalScale")}setNormalScale(Z){return this.set("normalScale",Z)}getNormalTexture(){return this.getRef("normalTexture")}getNormalTextureInfo(){return this.getRef("normalTexture")?this.getRef("normalTextureInfo"):null}setNormalTexture(Z){return this.setRef("normalTexture",Z,{channels:iF|gF|dF})}getOcclusionStrength(){return this.get("occlusionStrength")}setOcclusionStrength(Z){return this.set("occlusionStrength",Z)}getOcclusionTexture(){return this.getRef("occlusionTexture")}getOcclusionTextureInfo(){return this.getRef("occlusionTexture")?this.getRef("occlusionTextureInfo"):null}setOcclusionTexture(Z){return this.setRef("occlusionTexture",Z,{channels:iF})}getRoughnessFactor(){return this.get("roughnessFactor")}setRoughnessFactor(Z){return this.set("roughnessFactor",Z)}getMetallicFactor(){return this.get("metallicFactor")}setMetallicFactor(Z){return this.set("metallicFactor",Z)}getMetallicRoughnessTexture(){return this.getRef("metallicRoughnessTexture")}getMetallicRoughnessTextureInfo(){return this.getRef("metallicRoughnessTexture")?this.getRef("metallicRoughnessTextureInfo"):null}setMetallicRoughnessTexture(Z){return this.setRef("metallicRoughnessTexture",Z,{channels:gF|dF})}}Q7.AlphaMode={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};class NG extends x6{init(){this.propertyType=g.MESH}getDefaults(){return Object.assign(super.getDefaults(),{weights:[],primitives:new c1})}addPrimitive(Z){return this.addRef("primitives",Z)}removePrimitive(Z){return this.removeRef("primitives",Z)}listPrimitives(){return this.listRefs("primitives")}getWeights(){return this.get("weights")}setWeights(Z){return this.set("weights",Z)}}class Zc extends x6{init(){this.propertyType=g.NODE}getDefaults(){return Object.assign(super.getDefaults(),{translation:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1],weights:[],camera:null,mesh:null,skin:null,children:new c1})}copy(Z,J=SJ){if(J===SJ)throw new Error("Node cannot be copied.");return super.copy(Z,J)}getTranslation(){return this.get("translation")}getRotation(){return this.get("rotation")}getScale(){return this.get("scale")}setTranslation(Z){return this.set("translation",Z)}setRotation(Z){return this.set("rotation",Z)}setScale(Z){return this.set("scale",Z)}getMatrix(){return I0.compose(this.get("translation"),this.get("rotation"),this.get("scale"),[])}setMatrix(Z){let J=this.get("translation").slice(),X=this.get("rotation").slice(),$=this.get("scale").slice();return I0.decompose(Z,J,X,$),this.set("translation",J).set("rotation",X).set("scale",$)}getWorldTranslation(){let Z=[0,0,0];return I0.decompose(this.getWorldMatrix(),Z,[0,0,0,1],[1,1,1]),Z}getWorldRotation(){let Z=[0,0,0,1];return I0.decompose(this.getWorldMatrix(),[0,0,0],Z,[1,1,1]),Z}getWorldScale(){let Z=[1,1,1];return I0.decompose(this.getWorldMatrix(),[0,0,0],[0,0,0,1],Z),Z}getWorldMatrix(){let Z=[];for(let $=this;$!=null;$=$.getParentNode())Z.push($);let J,X=Z.pop().getMatrix();while(J=Z.pop())lx1(X,X,J.getMatrix());return X}addChild(Z){let J=Z.getParentNode();if(J)J.removeChild(Z);for(let X of Z.listParents())if(X.propertyType===g.SCENE)X.removeChild(Z);return this.addRef("children",Z)}removeChild(Z){return this.removeRef("children",Z)}listChildren(){return this.listRefs("children")}getParentNode(){for(let Z of this.listParents())if(Z.propertyType===g.NODE)return Z;return null}getMesh(){return this.getRef("mesh")}setMesh(Z){return this.setRef("mesh",Z)}getCamera(){return this.getRef("camera")}setCamera(Z){return this.setRef("camera",Z)}getSkin(){return this.getRef("skin")}setSkin(Z){return this.setRef("skin",Z)}getWeights(){return this.get("weights")}setWeights(Z){return this.set("weights",Z)}traverse(Z){Z(this);for(let J of this.listChildren())J.traverse(Z);return this}}class g1 extends x6{init(){this.propertyType=g.PRIMITIVE}getDefaults(){return Object.assign(super.getDefaults(),{mode:g1.Mode.TRIANGLES,material:null,indices:null,attributes:new A6,targets:new c1})}getIndices(){return this.getRef("indices")}setIndices(Z){return this.setRef("indices",Z,{usage:b5.ELEMENT_ARRAY_BUFFER})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:b5.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}getMaterial(){return this.getRef("material")}setMaterial(Z){return this.setRef("material",Z)}getMode(){return this.get("mode")}setMode(Z){return this.set("mode",Z)}listTargets(){return this.listRefs("targets")}addTarget(Z){return this.addRef("targets",Z)}removeTarget(Z){return this.removeRef("targets",Z)}}g1.Mode={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6};class FR extends eF{init(){this.propertyType=g.PRIMITIVE_TARGET}getDefaults(){return Object.assign(super.getDefaults(),{attributes:new A6})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:b5.ARRAY_BUFFER})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}}function m6(){return m6=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var $ in X)({}).hasOwnProperty.call(X,$)&&(Z[$]=X[$])}return Z},m6.apply(null,arguments)}class K3 extends x6{init(){this.propertyType=g.SCENE}getDefaults(){return Object.assign(super.getDefaults(),{children:new c1})}copy(Z,J=SJ){if(J===SJ)throw new Error("Scene cannot be copied.");return super.copy(Z,J)}addChild(Z){let J=Z.getParentNode();if(J)J.removeChild(Z);return this.addRef("children",Z)}removeChild(Z){return this.removeRef("children",Z)}listChildren(){return this.listRefs("children")}traverse(Z){for(let J of this.listChildren())J.traverse(Z);return this}}class cR extends x6{init(){this.propertyType=g.SKIN}getDefaults(){return Object.assign(super.getDefaults(),{skeleton:null,inverseBindMatrices:null,joints:new c1})}getSkeleton(){return this.getRef("skeleton")}setSkeleton(Z){return this.setRef("skeleton",Z)}getInverseBindMatrices(){return this.getRef("inverseBindMatrices")}setInverseBindMatrices(Z){return this.setRef("inverseBindMatrices",Z,{usage:b5.INVERSE_BIND_MATRICES})}addJoint(Z){return this.addRef("joints",Z)}removeJoint(Z){return this.removeRef("joints",Z)}listJoints(){return this.listRefs("joints")}}class b$ extends x6{init(){this.propertyType=g.TEXTURE}getDefaults(){return Object.assign(super.getDefaults(),{image:null,mimeType:"",uri:""})}getMimeType(){return this.get("mimeType")||_5.extensionToMimeType(QZ.extension(this.get("uri")))}setMimeType(Z){return this.set("mimeType",Z)}getURI(){return this.get("uri")}setURI(Z){this.set("uri",Z);let J=_5.extensionToMimeType(QZ.extension(Z));if(J)this.set("mimeType",J);return this}getImage(){return this.get("image")}setImage(Z){return this.set("image",E0.assertView(Z))}getSize(){let Z=this.get("image");if(!Z)return null;return _5.getSize(Z,this.getMimeType())}}class W3 extends x6{init(){this.propertyType=g.ROOT}getDefaults(){return Object.assign(super.getDefaults(),{asset:{generator:`glTF-Transform ${Og}`,version:"2.0"},defaultScene:null,accessors:new c1,animations:new c1,buffers:new c1,cameras:new c1,materials:new c1,meshes:new c1,nodes:new c1,scenes:new c1,skins:new c1,textures:new c1})}constructor(Z){super(Z);this._extensions=new Set,Z.addEventListener("node:create",(J)=>{this._addChildOfRoot(J.target)})}clone(){throw new Error("Root cannot be cloned.")}copy(Z,J=SJ){if(J===SJ)throw new Error("Root cannot be copied.");this.set("asset",m6({},Z.get("asset"))),this.setName(Z.getName()),this.setExtras(m6({},Z.getExtras())),this.setDefaultScene(Z.getDefaultScene()?J(Z.getDefaultScene()):null);for(let X of Z.listRefMapKeys("extensions")){let $=Z.getExtension(X);this.setExtension(X,J($))}return this}_addChildOfRoot(Z){if(Z instanceof K3)this.addRef("scenes",Z);else if(Z instanceof Zc)this.addRef("nodes",Z);else if(Z instanceof _$)this.addRef("cameras",Z);else if(Z instanceof cR)this.addRef("skins",Z);else if(Z instanceof NG)this.addRef("meshes",Z);else if(Z instanceof Q7)this.addRef("materials",Z);else if(Z instanceof b$)this.addRef("textures",Z);else if(Z instanceof HR)this.addRef("animations",Z);else if(Z instanceof K0)this.addRef("accessors",Z);else if(Z instanceof qR)this.addRef("buffers",Z);return this}getAsset(){return this.get("asset")}listExtensionsUsed(){return Array.from(this._extensions)}listExtensionsRequired(){return this.listExtensionsUsed().filter((Z)=>Z.isRequired())}_enableExtension(Z){return this._extensions.add(Z),this}_disableExtension(Z){return this._extensions.delete(Z),this}listScenes(){return this.listRefs("scenes")}setDefaultScene(Z){return this.setRef("defaultScene",Z)}getDefaultScene(){return this.getRef("defaultScene")}listNodes(){return this.listRefs("nodes")}listCameras(){return this.listRefs("cameras")}listSkins(){return this.listRefs("skins")}listMeshes(){return this.listRefs("meshes")}listMaterials(){return this.listRefs("materials")}listTextures(){return this.listRefs("textures")}listAnimations(){return this.listRefs("animations")}listAccessors(){return this.listRefs("accessors")}listBuffers(){return this.listRefs("buffers")}}class w6{static fromGraph(Z){return w6._GRAPH_DOCUMENTS.get(Z)||null}constructor(){this._graph=new yF,this._root=new W3(this._graph),this._logger=z5.DEFAULT_INSTANCE,w6._GRAPH_DOCUMENTS.set(this._graph,this)}getRoot(){return this._root}getGraph(){return this._graph}getLogger(){return this._logger}setLogger(Z){return this._logger=Z,this}clone(){throw new Error("Use 'cloneDocument(source)' from '@gltf-transform/functions'.")}merge(Z){throw new Error("Use 'mergeDocuments(target, source)' from '@gltf-transform/functions'.")}async transform(...Z){let J=Z.map((X)=>X.name);for(let X of Z)await X(this,{stack:J});return this}createExtension(Z){let J=Z.EXTENSION_NAME;return this.getRoot().listExtensionsUsed().find(($)=>$.extensionName===J)||new Z(this)}createScene(Z=""){return new K3(this._graph,Z)}createNode(Z=""){return new Zc(this._graph,Z)}createCamera(Z=""){return new _$(this._graph,Z)}createSkin(Z=""){return new cR(this._graph,Z)}createMesh(Z=""){return new NG(this._graph,Z)}createPrimitive(){return new g1(this._graph)}createPrimitiveTarget(Z=""){return new FR(this._graph,Z)}createMaterial(Z=""){return new Q7(this._graph,Z)}createTexture(Z=""){return new b$(this._graph,Z)}createAnimation(Z=""){return new HR(this._graph,Z)}createAnimationChannel(Z=""){return new KZ(this._graph,Z)}createAnimationSampler(Z=""){return new mJ(this._graph,Z)}createAccessor(Z="",J=null){if(!J)J=this.getRoot().listBuffers()[0];return new K0(this._graph,Z).setBuffer(J)}createBuffer(Z=""){return new qR(this._graph,Z)}}w6._GRAPH_DOCUMENTS=new WeakMap;class P1{constructor(Z){this.extensionName="",this.prereadTypes=[],this.prewriteTypes=[],this.readDependencies=[],this.writeDependencies=[],this.document=void 0,this.required=!1,this.properties=new Set,this._listener=void 0,this.document=Z,Z.getRoot()._enableExtension(this),this._listener=(X)=>{let $=X,Y=$.target;if(Y instanceof N1&&Y.extensionName===this.extensionName){if($.type==="node:create")this._addExtensionProperty(Y);if($.type==="node:dispose")this._removeExtensionProperty(Y)}};let J=Z.getGraph();J.addEventListener("node:create",this._listener),J.addEventListener("node:dispose",this._listener)}dispose(){this.document.getRoot()._disableExtension(this);let Z=this.document.getGraph();Z.removeEventListener("node:create",this._listener),Z.removeEventListener("node:dispose",this._listener);for(let J of this.properties)J.dispose()}static register(){}isRequired(){return this.required}setRequired(Z){return this.required=Z,this}listProperties(){return Array.from(this.properties)}_addExtensionProperty(Z){return this.properties.add(Z),this}_removeExtensionProperty(Z){return this.properties.delete(Z),this}install(Z,J){return this}preread(Z,J){return this}prewrite(Z,J){return this}}P1.EXTENSION_NAME=void 0;class kg{constructor(Z){this.jsonDoc=void 0,this.buffers=[],this.bufferViews=[],this.bufferViewBuffers=[],this.accessors=[],this.textures=[],this.textureInfos=new Map,this.materials=[],this.meshes=[],this.cameras=[],this.nodes=[],this.skins=[],this.animations=[],this.scenes=[],this.jsonDoc=Z}setTextureInfo(Z,J){if(this.textureInfos.set(Z,J),J.texCoord!==void 0)Z.setTexCoord(J.texCoord);if(J.extras!==void 0)Z.setExtras(J.extras);let X=this.jsonDoc.json.textures[J.index];if(X.sampler===void 0)return;let $=this.jsonDoc.json.samplers[X.sampler];if($.magFilter!==void 0)Z.setMagFilter($.magFilter);if($.minFilter!==void 0)Z.setMinFilter($.minFilter);if($.wrapS!==void 0)Z.setWrapS($.wrapS);if($.wrapT!==void 0)Z.setWrapT($.wrapT)}}var Mg={logger:z5.DEFAULT_INSTANCE,extensions:[],dependencies:{}},ex1=new Set([g.BUFFER,g.TEXTURE,g.MATERIAL,g.MESH,g.PRIMITIVE,g.NODE,g.SCENE]);class Eg{static read(Z,J=Mg){let X=m6({},Mg,J),{json:$}=Z,Y=new w6().setLogger(X.logger);this.validate(Z,X);let Q=new kg(Z),K=$.asset,W=Y.getRoot().getAsset();if(K.copyright)W.copyright=K.copyright;if(K.extras)W.extras=K.extras;if($.extras!==void 0)Y.getRoot().setExtras(m6({},$.extras));let G=$.extensionsUsed||[],z=$.extensionsRequired||[];X.extensions.sort((M,O)=>M.EXTENSION_NAME>O.EXTENSION_NAME?1:-1);for(let M of X.extensions)if(G.includes(M.EXTENSION_NAME)){let O=Y.createExtension(M).setRequired(z.includes(M.EXTENSION_NAME)),P=O.prereadTypes.filter((N)=>!ex1.has(N));if(P.length)X.logger.warn(`Preread hooks for some types (${P.join()}), requested by extension ${O.extensionName}, are unsupported. Please file an issue or a PR.`);for(let N of O.readDependencies)O.install(N,X.dependencies[N])}let V=$.buffers||[];Y.getRoot().listExtensionsUsed().filter((M)=>M.prereadTypes.includes(g.BUFFER)).forEach((M)=>M.preread(Q,g.BUFFER)),Q.buffers=V.map((M)=>{let O=Y.createBuffer(M.name);if(M.extras)O.setExtras(M.extras);if(M.uri&&M.uri.indexOf("__")!==0)O.setURI(M.uri);return O});let H=$.bufferViews||[];Q.bufferViewBuffers=H.map((M,O)=>{if(!Q.bufferViews[O]){let P=Z.json.buffers[M.buffer],N=P.uri?Z.resources[P.uri]:Z.resources[I$],_=M.byteOffset||0;Q.bufferViews[O]=E0.toView(N,_,M.byteLength)}return Q.buffers[M.buffer]});let v=$.accessors||[];Q.accessors=v.map((M)=>{let O=Q.bufferViewBuffers[M.bufferView],P=Y.createAccessor(M.name,O).setType(M.type);if(M.extras)P.setExtras(M.extras);if(M.normalized!==void 0)P.setNormalized(M.normalized);if(M.bufferView===void 0)return P;return P.setArray(nF(M,Q)),P});let q=$.images||[],F=$.textures||[];Y.getRoot().listExtensionsUsed().filter((M)=>M.prereadTypes.includes(g.TEXTURE)).forEach((M)=>M.preread(Q,g.TEXTURE)),Q.textures=q.map((M)=>{let O=Y.createTexture(M.name);if(M.extras)O.setExtras(M.extras);if(M.bufferView!==void 0){let P=$.bufferViews[M.bufferView],N=Z.json.buffers[P.buffer],_=N.uri?Z.resources[N.uri]:Z.resources[I$],k=P.byteOffset||0,h=P.byteLength,f=_.slice(k,k+h);O.setImage(f)}else if(M.uri!==void 0){if(O.setImage(Z.resources[M.uri]),M.uri.indexOf("__")!==0)O.setURI(M.uri)}if(M.mimeType!==void 0)O.setMimeType(M.mimeType);else if(M.uri){let P=QZ.extension(M.uri);O.setMimeType(_5.extensionToMimeType(P))}return O}),Y.getRoot().listExtensionsUsed().filter((M)=>M.prereadTypes.includes(g.MATERIAL)).forEach((M)=>M.preread(Q,g.MATERIAL));let c=$.materials||[];Q.materials=c.map((M)=>{let O=Y.createMaterial(M.name);if(M.extras)O.setExtras(M.extras);if(M.alphaMode!==void 0)O.setAlphaMode(M.alphaMode);if(M.alphaCutoff!==void 0)O.setAlphaCutoff(M.alphaCutoff);if(M.doubleSided!==void 0)O.setDoubleSided(M.doubleSided);let P=M.pbrMetallicRoughness||{};if(P.baseColorFactor!==void 0)O.setBaseColorFactor(P.baseColorFactor);if(M.emissiveFactor!==void 0)O.setEmissiveFactor(M.emissiveFactor);if(P.metallicFactor!==void 0)O.setMetallicFactor(P.metallicFactor);if(P.roughnessFactor!==void 0)O.setRoughnessFactor(P.roughnessFactor);if(P.baseColorTexture!==void 0){let N=P.baseColorTexture,_=Q.textures[F[N.index].source];O.setBaseColorTexture(_),Q.setTextureInfo(O.getBaseColorTextureInfo(),N)}if(M.emissiveTexture!==void 0){let N=M.emissiveTexture,_=Q.textures[F[N.index].source];O.setEmissiveTexture(_),Q.setTextureInfo(O.getEmissiveTextureInfo(),N)}if(M.normalTexture!==void 0){let N=M.normalTexture,_=Q.textures[F[N.index].source];if(O.setNormalTexture(_),Q.setTextureInfo(O.getNormalTextureInfo(),N),M.normalTexture.scale!==void 0)O.setNormalScale(M.normalTexture.scale)}if(M.occlusionTexture!==void 0){let N=M.occlusionTexture,_=Q.textures[F[N.index].source];if(O.setOcclusionTexture(_),Q.setTextureInfo(O.getOcclusionTextureInfo(),N),M.occlusionTexture.strength!==void 0)O.setOcclusionStrength(M.occlusionTexture.strength)}if(P.metallicRoughnessTexture!==void 0){let N=P.metallicRoughnessTexture,_=Q.textures[F[N.index].source];O.setMetallicRoughnessTexture(_),Q.setTextureInfo(O.getMetallicRoughnessTextureInfo(),N)}return O}),Y.getRoot().listExtensionsUsed().filter((M)=>M.prereadTypes.includes(g.MESH)).forEach((M)=>M.preread(Q,g.MESH));let w=$.meshes||[];Y.getRoot().listExtensionsUsed().filter((M)=>M.prereadTypes.includes(g.PRIMITIVE)).forEach((M)=>M.preread(Q,g.PRIMITIVE)),Q.meshes=w.map((M)=>{let O=Y.createMesh(M.name);if(M.extras)O.setExtras(M.extras);if(M.weights!==void 0)O.setWeights(M.weights);return(M.primitives||[]).forEach((N)=>{let _=Y.createPrimitive();if(N.extras)_.setExtras(N.extras);if(N.material!==void 0)_.setMaterial(Q.materials[N.material]);if(N.mode!==void 0)_.setMode(N.mode);for(let[f,C]of Object.entries(N.attributes||{}))_.setAttribute(f,Q.accessors[C]);if(N.indices!==void 0)_.setIndices(Q.accessors[N.indices]);let k=M.extras&&M.extras.targetNames||[];(N.targets||[]).forEach((f,C)=>{let b=k[C]||C.toString(),I=Y.createPrimitiveTarget(b);for(let[a,s]of Object.entries(f))I.setAttribute(a,Q.accessors[s]);_.addTarget(I)}),O.addPrimitive(_)}),O});let x=$.cameras||[];Q.cameras=x.map((M)=>{let O=Y.createCamera(M.name).setType(M.type);if(M.extras)O.setExtras(M.extras);if(M.type===_$.Type.PERSPECTIVE){let P=M.perspective;if(O.setYFov(P.yfov),O.setZNear(P.znear),P.zfar!==void 0)O.setZFar(P.zfar);if(P.aspectRatio!==void 0)O.setAspectRatio(P.aspectRatio)}else{let P=M.orthographic;O.setZNear(P.znear).setZFar(P.zfar).setXMag(P.xmag).setYMag(P.ymag)}return O});let j=$.nodes||[];Y.getRoot().listExtensionsUsed().filter((M)=>M.prereadTypes.includes(g.NODE)).forEach((M)=>M.preread(Q,g.NODE)),Q.nodes=j.map((M)=>{let O=Y.createNode(M.name);if(M.extras)O.setExtras(M.extras);if(M.translation!==void 0)O.setTranslation(M.translation);if(M.rotation!==void 0)O.setRotation(M.rotation);if(M.scale!==void 0)O.setScale(M.scale);if(M.matrix!==void 0){let P=[0,0,0],N=[0,0,0,1],_=[1,1,1];I0.decompose(M.matrix,P,N,_),O.setTranslation(P),O.setRotation(N),O.setScale(_)}if(M.weights!==void 0)O.setWeights(M.weights);return O});let B=$.skins||[];Q.skins=B.map((M)=>{let O=Y.createSkin(M.name);if(M.extras)O.setExtras(M.extras);if(M.inverseBindMatrices!==void 0)O.setInverseBindMatrices(Q.accessors[M.inverseBindMatrices]);if(M.skeleton!==void 0)O.setSkeleton(Q.nodes[M.skeleton]);for(let P of M.joints)O.addJoint(Q.nodes[P]);return O}),j.map((M,O)=>{let P=Q.nodes[O];if((M.children||[]).forEach((_)=>P.addChild(Q.nodes[_])),M.mesh!==void 0)P.setMesh(Q.meshes[M.mesh]);if(M.camera!==void 0)P.setCamera(Q.cameras[M.camera]);if(M.skin!==void 0)P.setSkin(Q.skins[M.skin])});let L=$.animations||[];Q.animations=L.map((M)=>{let O=Y.createAnimation(M.name);if(M.extras)O.setExtras(M.extras);let N=(M.samplers||[]).map((k)=>{let h=Y.createAnimationSampler().setInput(Q.accessors[k.input]).setOutput(Q.accessors[k.output]).setInterpolation(k.interpolation||mJ.Interpolation.LINEAR);if(k.extras)h.setExtras(k.extras);return O.addSampler(h),h});return(M.channels||[]).forEach((k)=>{let h=Y.createAnimationChannel().setSampler(N[k.sampler]).setTargetPath(k.target.path);if(k.target.node!==void 0)h.setTargetNode(Q.nodes[k.target.node]);if(k.extras)h.setExtras(k.extras);O.addChannel(h)}),O});let R=$.scenes||[];if(Y.getRoot().listExtensionsUsed().filter((M)=>M.prereadTypes.includes(g.SCENE)).forEach((M)=>M.preread(Q,g.SCENE)),Q.scenes=R.map((M)=>{let O=Y.createScene(M.name);if(M.extras)O.setExtras(M.extras);return(M.nodes||[]).map((N)=>Q.nodes[N]).forEach((N)=>O.addChild(N)),O}),$.scene!==void 0)Y.getRoot().setDefaultScene(Q.scenes[$.scene]);return Y.getRoot().listExtensionsUsed().forEach((M)=>M.read(Q)),v.forEach((M,O)=>{let P=Q.accessors[O],N=!!M.sparse,_=!M.bufferView&&!P.getArray();if(N||_)P.setSparse(!0).setArray(JU1(M,Q))}),Y}static validate(Z,J){let X=Z.json;if(X.asset.version!=="2.0")throw new Error(`Unsupported glTF version, "${X.asset.version}".`);if(X.extensionsRequired){for(let $ of X.extensionsRequired)if(!J.extensions.find((Y)=>Y.EXTENSION_NAME===$))throw new Error(`Missing required extension, "${$}".`)}if(X.extensionsUsed){for(let $ of X.extensionsUsed)if(!J.extensions.find((Y)=>Y.EXTENSION_NAME===$))J.logger.warn(`Missing optional extension, "${$}".`)}}}function ZU1(Z,J){let X=J.jsonDoc,$=J.bufferViews[Z.bufferView],Y=X.json.bufferViews[Z.bufferView],Q=AJ[Z.componentType],K=K0.getElementSize(Z.type),W=Q.BYTES_PER_ELEMENT,G=Z.byteOffset||0,z=new Q(Z.count*K),V=new DataView($.buffer,$.byteOffset,$.byteLength),H=Y.byteStride;for(let v=0;v<Z.count;v++)for(let q=0;q<K;q++){let F=G+v*H+q*W,c;switch(Z.componentType){case K0.ComponentType.FLOAT:c=V.getFloat32(F,!0);break;case K0.ComponentType.UNSIGNED_INT:c=V.getUint32(F,!0);break;case K0.ComponentType.UNSIGNED_SHORT:c=V.getUint16(F,!0);break;case K0.ComponentType.UNSIGNED_BYTE:c=V.getUint8(F);break;case K0.ComponentType.SHORT:c=V.getInt16(F,!0);break;case K0.ComponentType.BYTE:c=V.getInt8(F);break;default:throw new Error(`Unexpected componentType "${Z.componentType}".`)}z[v*K+q]=c}return z}function nF(Z,J){let X=J.jsonDoc,$=J.bufferViews[Z.bufferView],Y=X.json.bufferViews[Z.bufferView],Q=AJ[Z.componentType],K=K0.getElementSize(Z.type),W=Q.BYTES_PER_ELEMENT,G=K*W;if(Y.byteStride!==void 0&&Y.byteStride!==G)return ZU1(Z,J);let z=$.byteOffset+(Z.byteOffset||0),V=Z.count*K*W;return new Q($.buffer.slice(z,z+V))}function JU1(Z,J){let X=AJ[Z.componentType],$=K0.getElementSize(Z.type),Y;if(Z.bufferView!==void 0)Y=nF(Z,J);else Y=new X(Z.count*$);let Q=Z.sparse;if(!Q)return Y;let K=Q.count,W=m6({},Z,Q.indices,{count:K,type:"SCALAR"}),G=m6({},Z,Q.values,{count:K}),z=nF(W,J),V=nF(G,J);for(let H=0;H<W.count;H++)for(let v=0;v<$;v++)Y[z[H]*$+v]=V[H*$+v];return Y}var RG;(function(Z){Z[Z.ARRAY_BUFFER=34962]="ARRAY_BUFFER",Z[Z.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER"})(RG||(RG={}));class w4{constructor(Z,J,X){this._doc=void 0,this.jsonDoc=void 0,this.options=void 0,this.accessorIndexMap=new Map,this.animationIndexMap=new Map,this.bufferIndexMap=new Map,this.cameraIndexMap=new Map,this.skinIndexMap=new Map,this.materialIndexMap=new Map,this.meshIndexMap=new Map,this.nodeIndexMap=new Map,this.imageIndexMap=new Map,this.textureDefIndexMap=new Map,this.textureInfoDefMap=new Map,this.samplerDefIndexMap=new Map,this.sceneIndexMap=new Map,this.imageBufferViews=[],this.otherBufferViews=new Map,this.otherBufferViewsIndexMap=new Map,this.extensionData={},this.bufferURIGenerator=void 0,this.imageURIGenerator=void 0,this.logger=void 0,this._accessorUsageMap=new Map,this.accessorUsageGroupedByParent=new Set(["ARRAY_BUFFER"]),this.accessorParents=new Map,this._doc=Z,this.jsonDoc=J,this.options=X;let $=Z.getRoot(),Y=$.listBuffers().length,Q=$.listTextures().length;this.bufferURIGenerator=new VR(Y>1,()=>X.basename||"buffer"),this.imageURIGenerator=new VR(Q>1,(K)=>XU1(Z,K)||X.basename||"texture"),this.logger=Z.getLogger()}createTextureInfoDef(Z,J){let X={magFilter:J.getMagFilter()||void 0,minFilter:J.getMinFilter()||void 0,wrapS:J.getWrapS(),wrapT:J.getWrapT()},$=JSON.stringify(X);if(!this.samplerDefIndexMap.has($))this.samplerDefIndexMap.set($,this.jsonDoc.json.samplers.length),this.jsonDoc.json.samplers.push(X);let Y={source:this.imageIndexMap.get(Z),sampler:this.samplerDefIndexMap.get($)},Q=JSON.stringify(Y);if(!this.textureDefIndexMap.has(Q))this.textureDefIndexMap.set(Q,this.jsonDoc.json.textures.length),this.jsonDoc.json.textures.push(Y);let K={index:this.textureDefIndexMap.get(Q)};if(J.getTexCoord()!==0)K.texCoord=J.getTexCoord();if(Object.keys(J.getExtras()).length>0)K.extras=J.getExtras();return this.textureInfoDefMap.set(J,K),K}createPropertyDef(Z){let J={};if(Z.getName())J.name=Z.getName();if(Object.keys(Z.getExtras()).length>0)J.extras=Z.getExtras();return J}createAccessorDef(Z){let J=this.createPropertyDef(Z);if(J.type=Z.getType(),J.componentType=Z.getComponentType(),J.count=Z.getCount(),this._doc.getGraph().listParentEdges(Z).some(($)=>$.getName()==="attributes"&&$.getAttributes().key==="POSITION"||$.getName()==="input"))J.max=Z.getMax([]).map(Math.fround),J.min=Z.getMin([]).map(Math.fround);if(Z.getNormalized())J.normalized=Z.getNormalized();return J}createImageData(Z,J,X){if(this.options.format===YZ.GLB)this.imageBufferViews.push(J),Z.bufferView=this.jsonDoc.json.bufferViews.length,this.jsonDoc.json.bufferViews.push({buffer:0,byteOffset:-1,byteLength:J.byteLength});else{let $=_5.mimeTypeToExtension(X.getMimeType());Z.uri=this.imageURIGenerator.createURI(X,$),this.assignResourceURI(Z.uri,J,!1)}}assignResourceURI(Z,J,X){let $=this.jsonDoc.resources;if(!(Z in $)){$[Z]=J;return}if(J===$[Z]){this.logger.warn(`Duplicate resource URI, "${Z}".`);return}let Y=`Resource URI "${Z}" already assigned to different data.`;if(!X){this.logger.warn(Y);return}throw new Error(Y)}getAccessorUsage(Z){let J=this._accessorUsageMap.get(Z);if(J)return J;if(Z.getSparse())return b5.SPARSE;for(let X of this._doc.getGraph().listParentEdges(Z)){let{usage:$}=X.getAttributes();if($)return $;if(X.getParent().propertyType!==g.ROOT)this.logger.warn(`Missing attribute ".usage" on edge, "${X.getName()}".`)}return b5.OTHER}addAccessorToUsageGroup(Z,J){let X=this._accessorUsageMap.get(Z);if(X&&X!==J)throw new Error(`Accessor with usage "${X}" cannot be reused as "${J}".`);return this._accessorUsageMap.set(Z,J),this}}w4.BufferViewTarget=RG;w4.BufferViewUsage=b5;w4.USAGE_TO_TARGET={[b5.ARRAY_BUFFER]:RG.ARRAY_BUFFER,[b5.ELEMENT_ARRAY_BUFFER]:RG.ELEMENT_ARRAY_BUFFER};class VR{constructor(Z,J){this.multiple=void 0,this.basename=void 0,this.counter={},this.multiple=Z,this.basename=J}createURI(Z,J){if(Z.getURI())return Z.getURI();else if(!this.multiple)return`${this.basename(Z)}.${J}`;else{let X=this.basename(Z);return this.counter[X]=this.counter[X]||1,`${X}_${this.counter[X]++}.${J}`}}}function XU1(Z,J){let X=Z.getGraph().listParentEdges(J).find(($)=>$.getParent()!==Z.getRoot());return X?X.getName().replace(/texture$/i,""):""}var{BufferViewUsage:aF}=w4,{UNSIGNED_INT:$U1,UNSIGNED_SHORT:YU1,UNSIGNED_BYTE:QU1}=K0.ComponentType,KU1=new Set([g.ACCESSOR,g.BUFFER,g.MATERIAL,g.MESH]);class Ig{static write(Z,J){let X=Z.getGraph(),$=Z.getRoot(),Y={asset:m6({generator:`glTF-Transform ${Og}`},$.getAsset()),extras:m6({},$.getExtras())},Q={json:Y,resources:{}},K=new w4(Z,Q,J),W=J.logger||z5.DEFAULT_INSTANCE,G=new Set(J.extensions.map((w)=>w.EXTENSION_NAME)),z=Z.getRoot().listExtensionsUsed().filter((w)=>G.has(w.extensionName)).sort((w,x)=>w.extensionName>x.extensionName?1:-1),V=Z.getRoot().listExtensionsRequired().filter((w)=>G.has(w.extensionName)).sort((w,x)=>w.extensionName>x.extensionName?1:-1);if(z.length<Z.getRoot().listExtensionsUsed().length)W.warn("Some extensions were not registered for I/O, and will not be written.");for(let w of z){let x=w.prewriteTypes.filter((j)=>!KU1.has(j));if(x.length)W.warn(`Prewrite hooks for some types (${x.join()}), requested by extension ${w.extensionName}, are unsupported. Please file an issue or a PR.`);for(let j of w.writeDependencies)w.install(j,J.dependencies[j])}function H(w,x,j,B){let L=[],R=0;for(let P of w){let N=K.createAccessorDef(P);N.bufferView=Y.bufferViews.length;let _=P.getArray(),k=E0.pad(E0.toView(_));N.byteOffset=R,R+=k.byteLength,L.push(k),K.accessorIndexMap.set(P,Y.accessors.length),Y.accessors.push(N)}let M=E0.concat(L),O={buffer:x,byteOffset:j,byteLength:M.byteLength};if(B)O.target=B;return Y.bufferViews.push(O),{buffers:L,byteLength:R}}function v(w,x,j){let B=w[0].getCount(),L=0;for(let N of w){let _=K.createAccessorDef(N);_.bufferView=Y.bufferViews.length,_.byteOffset=L;let k=N.getElementSize(),h=N.getComponentSize();L+=E0.padNumber(k*h),K.accessorIndexMap.set(N,Y.accessors.length),Y.accessors.push(_)}let R=B*L,M=new ArrayBuffer(R),O=new DataView(M);for(let N=0;N<B;N++){let _=0;for(let k of w){let h=k.getElementSize(),f=k.getComponentSize(),C=k.getComponentType(),b=k.getArray();for(let I=0;I<h;I++){let a=N*L+_+I*f,s=b[N*h+I];switch(C){case K0.ComponentType.FLOAT:O.setFloat32(a,s,!0);break;case K0.ComponentType.BYTE:O.setInt8(a,s);break;case K0.ComponentType.SHORT:O.setInt16(a,s,!0);break;case K0.ComponentType.UNSIGNED_BYTE:O.setUint8(a,s);break;case K0.ComponentType.UNSIGNED_SHORT:O.setUint16(a,s,!0);break;case K0.ComponentType.UNSIGNED_INT:O.setUint32(a,s,!0);break;default:throw new Error("Unexpected component type: "+C)}}_+=E0.padNumber(h*f)}}let P={buffer:x,byteOffset:j,byteLength:R,byteStride:L,target:w4.BufferViewTarget.ARRAY_BUFFER};return Y.bufferViews.push(P),{byteLength:R,buffers:[new Uint8Array(M)]}}function q(w,x,j){let B=[],L=0,R=new Map,M=-1/0,O=!1;for(let C of w){let b=K.createAccessorDef(C);Y.accessors.push(b),K.accessorIndexMap.set(C,Y.accessors.length-1);let I=[],a=[],s=[],Z0=new Array(C.getElementSize()).fill(0);for(let m0=0,O1=C.getCount();m0<O1;m0++){if(C.getElement(m0,s),I0.eq(s,Z0,0))continue;M=Math.max(m0,M),I.push(m0);for(let s0=0;s0<s.length;s0++)a.push(s[s0])}let o=I.length,M0={accessorDef:b,count:o};if(R.set(C,M0),o===0)continue;if(o>C.getCount()/2)O=!0;let R0=AJ[C.getComponentType()];M0.indices=I,M0.values=new R0(a)}if(!Number.isFinite(M))return{buffers:B,byteLength:L};if(O)W.warn("Some sparse accessors have >50% non-zero elements, which may increase file size.");let P=M<255?Uint8Array:M<65535?Uint16Array:Uint32Array,N=M<255?QU1:M<65535?YU1:$U1,_={buffer:x,byteOffset:j+L,byteLength:0};for(let C of w){let b=R.get(C);if(b.count===0)continue;b.indicesByteOffset=_.byteLength;let I=E0.pad(E0.toView(new P(b.indices)));B.push(I),L+=I.byteLength,_.byteLength+=I.byteLength}Y.bufferViews.push(_);let k=Y.bufferViews.length-1,h={buffer:x,byteOffset:j+L,byteLength:0};for(let C of w){let b=R.get(C);if(b.count===0)continue;b.valuesByteOffset=h.byteLength;let I=E0.pad(E0.toView(b.values));B.push(I),L+=I.byteLength,h.byteLength+=I.byteLength}Y.bufferViews.push(h);let f=Y.bufferViews.length-1;for(let C of w){let b=R.get(C);if(b.count===0)continue;b.accessorDef.sparse={count:b.count,indices:{bufferView:k,byteOffset:b.indicesByteOffset,componentType:N},values:{bufferView:f,byteOffset:b.valuesByteOffset}}}return{buffers:B,byteLength:L}}if(Y.accessors=[],Y.bufferViews=[],Y.samplers=[],Y.textures=[],Y.images=$.listTextures().map((w,x)=>{let j=K.createPropertyDef(w);if(w.getMimeType())j.mimeType=w.getMimeType();let B=w.getImage();if(B)K.createImageData(j,B,w);return K.imageIndexMap.set(w,x),j}),z.filter((w)=>w.prewriteTypes.includes(g.ACCESSOR)).forEach((w)=>w.prewrite(K,g.ACCESSOR)),$.listAccessors().forEach((w)=>{let{accessorUsageGroupedByParent:x,accessorParents:j}=K;if(K.accessorIndexMap.has(w))return;let B=K.getAccessorUsage(w);if(K.addAccessorToUsageGroup(w,B),x.has(B)){let L=X.listParents(w).find((R)=>R.propertyType!==g.ROOT);j.set(w,L)}}),z.filter((w)=>w.prewriteTypes.includes(g.BUFFER)).forEach((w)=>w.prewrite(K,g.BUFFER)),($.listAccessors().length>0||K.otherBufferViews.size>0||$.listTextures().length>0&&J.format===YZ.GLB)&&$.listBuffers().length===0)throw new Error("Buffer required for Document resources, but none was found.");if(Y.buffers=[],$.listBuffers().forEach((w,x)=>{let j=K.createPropertyDef(w),B=K.accessorUsageGroupedByParent,L=w.listParents().filter((h)=>h instanceof K0),R=new Set(L.map((h)=>K.accessorParents.get(h))),M=new Map(Array.from(R).map((h,f)=>[h,f])),O={};for(let h of L){var P;if(K.accessorIndexMap.has(h))continue;let f=K.getAccessorUsage(h),C=f;if(B.has(f)){let b=K.accessorParents.get(h);C+=`:${M.get(b)}`}O[P=C]||(O[P]={usage:f,accessors:[]}),O[C].accessors.push(h)}let N=[],_=Y.buffers.length,k=0;for(let{usage:h,accessors:f}of Object.values(O))if(h===aF.ARRAY_BUFFER&&J.vertexLayout===sF.INTERLEAVED){let C=v(f,_,k);k+=C.byteLength;for(let b of C.buffers)N.push(b)}else if(h===aF.ARRAY_BUFFER)for(let C of f){let b=v([C],_,k);k+=b.byteLength;for(let I of b.buffers)N.push(I)}else if(h===aF.SPARSE){let C=q(f,_,k);k+=C.byteLength;for(let b of C.buffers)N.push(b)}else if(h===aF.ELEMENT_ARRAY_BUFFER){let C=w4.BufferViewTarget.ELEMENT_ARRAY_BUFFER,b=H(f,_,k,C);k+=b.byteLength;for(let I of b.buffers)N.push(I)}else{let C=H(f,_,k);k+=C.byteLength;for(let b of C.buffers)N.push(b)}if(K.imageBufferViews.length&&x===0){for(let h=0;h<K.imageBufferViews.length;h++)if(Y.bufferViews[Y.images[h].bufferView].byteOffset=k,k+=K.imageBufferViews[h].byteLength,N.push(K.imageBufferViews[h]),k%8){let f=8-k%8;k+=f,N.push(new Uint8Array(f))}}if(K.otherBufferViews.has(w))for(let h of K.otherBufferViews.get(w))Y.bufferViews.push({buffer:_,byteOffset:k,byteLength:h.byteLength}),K.otherBufferViewsIndexMap.set(h,Y.bufferViews.length-1),k+=h.byteLength,N.push(h);if(k){let h;if(J.format===YZ.GLB)h=I$;else h=K.bufferURIGenerator.createURI(w,"bin"),j.uri=h;j.byteLength=k,K.assignResourceURI(h,E0.concat(N),!0)}Y.buffers.push(j),K.bufferIndexMap.set(w,x)}),$.listAccessors().find((w)=>!w.getBuffer()))W.warn("Skipped writing one or more Accessors: no Buffer assigned.");z.filter((w)=>w.prewriteTypes.includes(g.MATERIAL)).forEach((w)=>w.prewrite(K,g.MATERIAL)),Y.materials=$.listMaterials().map((w,x)=>{let j=K.createPropertyDef(w);if(w.getAlphaMode()!==Q7.AlphaMode.OPAQUE)j.alphaMode=w.getAlphaMode();if(w.getAlphaMode()===Q7.AlphaMode.MASK)j.alphaCutoff=w.getAlphaCutoff();if(w.getDoubleSided())j.doubleSided=!0;if(j.pbrMetallicRoughness={},!I0.eq(w.getBaseColorFactor(),[1,1,1,1]))j.pbrMetallicRoughness.baseColorFactor=w.getBaseColorFactor();if(!I0.eq(w.getEmissiveFactor(),[0,0,0]))j.emissiveFactor=w.getEmissiveFactor();if(w.getRoughnessFactor()!==1)j.pbrMetallicRoughness.roughnessFactor=w.getRoughnessFactor();if(w.getMetallicFactor()!==1)j.pbrMetallicRoughness.metallicFactor=w.getMetallicFactor();if(w.getBaseColorTexture()){let B=w.getBaseColorTexture(),L=w.getBaseColorTextureInfo();j.pbrMetallicRoughness.baseColorTexture=K.createTextureInfoDef(B,L)}if(w.getEmissiveTexture()){let B=w.getEmissiveTexture(),L=w.getEmissiveTextureInfo();j.emissiveTexture=K.createTextureInfoDef(B,L)}if(w.getNormalTexture()){let B=w.getNormalTexture(),L=w.getNormalTextureInfo(),R=K.createTextureInfoDef(B,L);if(w.getNormalScale()!==1)R.scale=w.getNormalScale();j.normalTexture=R}if(w.getOcclusionTexture()){let B=w.getOcclusionTexture(),L=w.getOcclusionTextureInfo(),R=K.createTextureInfoDef(B,L);if(w.getOcclusionStrength()!==1)R.strength=w.getOcclusionStrength();j.occlusionTexture=R}if(w.getMetallicRoughnessTexture()){let B=w.getMetallicRoughnessTexture(),L=w.getMetallicRoughnessTextureInfo();j.pbrMetallicRoughness.metallicRoughnessTexture=K.createTextureInfoDef(B,L)}return K.materialIndexMap.set(w,x),j}),z.filter((w)=>w.prewriteTypes.includes(g.MESH)).forEach((w)=>w.prewrite(K,g.MESH)),Y.meshes=$.listMeshes().map((w,x)=>{let j=K.createPropertyDef(w),B=null;if(j.primitives=w.listPrimitives().map((L)=>{let R={attributes:{}};R.mode=L.getMode();let M=L.getMaterial();if(M)R.material=K.materialIndexMap.get(M);if(Object.keys(L.getExtras()).length)R.extras=L.getExtras();let O=L.getIndices();if(O)R.indices=K.accessorIndexMap.get(O);for(let P of L.listSemantics())R.attributes[P]=K.accessorIndexMap.get(L.getAttribute(P));for(let P of L.listTargets()){let N={};for(let _ of P.listSemantics())N[_]=K.accessorIndexMap.get(P.getAttribute(_));R.targets=R.targets||[],R.targets.push(N)}if(L.listTargets().length&&!B)B=L.listTargets().map((P)=>P.getName());return R}),w.getWeights().length)j.weights=w.getWeights();if(B)j.extras=j.extras||{},j.extras.targetNames=B;return K.meshIndexMap.set(w,x),j}),Y.cameras=$.listCameras().map((w,x)=>{let j=K.createPropertyDef(w);if(j.type=w.getType(),j.type===_$.Type.PERSPECTIVE){j.perspective={znear:w.getZNear(),zfar:w.getZFar(),yfov:w.getYFov()};let B=w.getAspectRatio();if(B!==null)j.perspective.aspectRatio=B}else j.orthographic={znear:w.getZNear(),zfar:w.getZFar(),xmag:w.getXMag(),ymag:w.getYMag()};return K.cameraIndexMap.set(w,x),j}),Y.nodes=$.listNodes().map((w,x)=>{let j=K.createPropertyDef(w);if(!I0.eq(w.getTranslation(),[0,0,0]))j.translation=w.getTranslation();if(!I0.eq(w.getRotation(),[0,0,0,1]))j.rotation=w.getRotation();if(!I0.eq(w.getScale(),[1,1,1]))j.scale=w.getScale();if(w.getWeights().length)j.weights=w.getWeights();return K.nodeIndexMap.set(w,x),j}),Y.skins=$.listSkins().map((w,x)=>{let j=K.createPropertyDef(w),B=w.getInverseBindMatrices();if(B)j.inverseBindMatrices=K.accessorIndexMap.get(B);let L=w.getSkeleton();if(L)j.skeleton=K.nodeIndexMap.get(L);return j.joints=w.listJoints().map((R)=>K.nodeIndexMap.get(R)),K.skinIndexMap.set(w,x),j}),$.listNodes().forEach((w,x)=>{let j=Y.nodes[x],B=w.getMesh();if(B)j.mesh=K.meshIndexMap.get(B);let L=w.getCamera();if(L)j.camera=K.cameraIndexMap.get(L);let R=w.getSkin();if(R)j.skin=K.skinIndexMap.get(R);if(w.listChildren().length>0)j.children=w.listChildren().map((M)=>K.nodeIndexMap.get(M))}),Y.animations=$.listAnimations().map((w,x)=>{let j=K.createPropertyDef(w),B=new Map;return j.samplers=w.listSamplers().map((L,R)=>{let M=K.createPropertyDef(L);return M.input=K.accessorIndexMap.get(L.getInput()),M.output=K.accessorIndexMap.get(L.getOutput()),M.interpolation=L.getInterpolation(),B.set(L,R),M}),j.channels=w.listChannels().map((L)=>{let R=K.createPropertyDef(L);return R.sampler=B.get(L.getSampler()),R.target={node:K.nodeIndexMap.get(L.getTargetNode()),path:L.getTargetPath()},R}),K.animationIndexMap.set(w,x),j}),Y.scenes=$.listScenes().map((w,x)=>{let j=K.createPropertyDef(w);return j.nodes=w.listChildren().map((B)=>K.nodeIndexMap.get(B)),K.sceneIndexMap.set(w,x),j});let c=$.getDefaultScene();if(c)Y.scene=$.listScenes().indexOf(c);return Y.extensionsUsed=z.map((w)=>w.extensionName),Y.extensionsRequired=V.map((w)=>w.extensionName),z.forEach((w)=>w.write(K)),WU1(Y),Q}}function WU1(Z){let J=[];for(let X in Z){let $=Z[X];if(Array.isArray($)&&$.length===0)J.push(X);else if($===null||$==="")J.push(X);else if($&&typeof $==="object"&&Object.keys($).length===0)J.push(X)}for(let X of J)delete Z[X]}var rF;(function(Z){Z[Z.JSON=1313821514]="JSON",Z[Z.BIN=5130562]="BIN"})(rF||(rF={}));class _g{constructor(){this._logger=z5.DEFAULT_INSTANCE,this._extensions=new Set,this._dependencies={},this._vertexLayout=sF.INTERLEAVED,this.lastReadBytes=0,this.lastWriteBytes=0}setLogger(Z){return this._logger=Z,this}registerExtensions(Z){for(let J of Z)this._extensions.add(J),J.register();return this}registerDependencies(Z){return Object.assign(this._dependencies,Z),this}setVertexLayout(Z){return this._vertexLayout=Z,this}async read(Z){return await this.readJSON(await this.readAsJSON(Z))}async readAsJSON(Z){let J=await this.readURI(Z,"view");this.lastReadBytes=J.byteLength;let X=Rg(J)?this._binaryToJSON(J):{json:JSON.parse(E0.decodeText(J)),resources:{}};return await this._readResourcesExternal(X,this.dirname(Z)),this._readResourcesInternal(X),X}async readJSON(Z){return Z=this._copyJSON(Z),this._readResourcesInternal(Z),Eg.read(Z,{extensions:Array.from(this._extensions),dependencies:this._dependencies,logger:this._logger})}async binaryToJSON(Z){let J=this._binaryToJSON(E0.assertView(Z));this._readResourcesInternal(J);let X=J.json;if(X.buffers&&X.buffers.some(($)=>GU1(J,$)))throw new Error("Cannot resolve external buffers with binaryToJSON().");else if(X.images&&X.images.some(($)=>zU1(J,$)))throw new Error("Cannot resolve external images with binaryToJSON().");return J}async readBinary(Z){return this.readJSON(await this.binaryToJSON(E0.assertView(Z)))}async writeJSON(Z,J={}){if(J.format===YZ.GLB&&Z.getRoot().listBuffers().length>1)throw new Error("GLB must have 0–1 buffers.");return Ig.write(Z,{format:J.format||YZ.GLTF,basename:J.basename||"",logger:this._logger,vertexLayout:this._vertexLayout,dependencies:m6({},this._dependencies),extensions:Array.from(this._extensions)})}async writeBinary(Z){let{json:J,resources:X}=await this.writeJSON(Z,{format:YZ.GLB}),$=new Uint32Array([1179937895,2,12]),Y=JSON.stringify(J),Q=E0.pad(E0.encodeText(Y),32),K=E0.toView(new Uint32Array([Q.byteLength,1313821514])),W=E0.concat([K,Q]);$[$.length-1]+=W.byteLength;let G=Object.values(X)[0];if(!G||!G.byteLength)return E0.concat([E0.toView($),W]);let z=E0.pad(G,0),V=E0.toView(new Uint32Array([z.byteLength,5130562])),H=E0.concat([V,z]);return $[$.length-1]+=H.byteLength,E0.concat([E0.toView($),W,H])}async _readResourcesExternal(Z,J){var X=this;let $=Z.json.images||[],Y=Z.json.buffers||[],Q=[...$,...Y].map(async function(K){let W=K.uri;if(!W||W.match(/data:/))return Promise.resolve();Z.resources[W]=await X.readURI(X.resolve(J,W),"view"),X.lastReadBytes+=Z.resources[W].byteLength});await Promise.all(Q)}_readResourcesInternal(Z){function J(Y){if(!Y.uri)return;if(Y.uri in Z.resources){E0.assertView(Z.resources[Y.uri]);return}if(Y.uri.match(/data:/)){let Q=`__${fg()}.${QZ.extension(Y.uri)}`;Z.resources[Q]=E0.createBufferFromDataURI(Y.uri),Y.uri=Q}}(Z.json.images||[]).forEach((Y)=>{if(Y.bufferView===void 0&&Y.uri===void 0)throw new Error("Missing resource URI or buffer view.");J(Y)}),(Z.json.buffers||[]).forEach(J)}_copyJSON(Z){let{images:J,buffers:X}=Z.json;if(Z={json:m6({},Z.json),resources:m6({},Z.resources)},J)Z.json.images=J.map(($)=>m6({},$));if(X)Z.json.buffers=X.map(($)=>m6({},$));return Z}_binaryToJSON(Z){if(!Rg(Z))throw new Error("Invalid glTF 2.0 binary.");let J=new Uint32Array(Z.buffer,Z.byteOffset+12,2);if(J[1]!==rF.JSON)throw new Error("Missing required GLB JSON chunk.");let X=20,$=J[0],Y=E0.decodeText(E0.toView(Z,X,$)),Q=JSON.parse(Y),K=X+$;if(Z.byteLength<=K)return{json:Q,resources:{}};let W=new Uint32Array(Z.buffer,Z.byteOffset+K,2);if(W[1]!==rF.BIN)return{json:Q,resources:{}};let G=W[0],z=E0.toView(Z,K+8,G);return{json:Q,resources:{[I$]:z}}}}function GU1(Z,J){return J.uri!==void 0&&!(J.uri in Z.resources)}function zU1(Z,J){return J.uri!==void 0&&!(J.uri in Z.resources)&&J.bufferView===void 0}function Rg(Z){if(Z.byteLength<3*Uint32Array.BYTES_PER_ELEMENT)return!1;let J=new Uint32Array(Z.buffer,Z.byteOffset,3);return J[0]===1179937895&&J[1]===2}class wR extends _g{constructor(Z=null,J=c4.DEFAULT_INIT){super();this._fetch=void 0,this._fetchConfig=void 0,this._init=void 0,this._fetchEnabled=!1,this._fetch=Z,this._fetchConfig=J,this._init=this.init()}async init(){if(this._init)return this._init;return Promise.all([import("fs"),import("path")]).then(([Z,J])=>{this._fs=Z.promises,this._path=J})}setAllowNetwork(Z){if(Z&&!this._fetch)throw new Error("NodeIO requires a Fetch API implementation for HTTP requests.");return this._fetchEnabled=Z,this}async readURI(Z,J){if(await this.init(),c4.isAbsoluteURL(Z)){if(!this._fetchEnabled||!this._fetch)throw new Error("Network request blocked. Allow HTTP requests explicitly, if needed.");let X=await this._fetch(Z,this._fetchConfig);switch(J){case"view":return new Uint8Array(await X.arrayBuffer());case"text":return X.text()}}else switch(J){case"view":return this._fs.readFile(Z);case"text":return this._fs.readFile(Z,"utf8")}}resolve(Z,J){if(c4.isAbsoluteURL(Z)||c4.isAbsoluteURL(J))return c4.resolve(Z,J);return this._path.resolve(Z,decodeURIComponent(J))}dirname(Z){if(c4.isAbsoluteURL(Z))return c4.dirname(Z);return this._path.dirname(Z)}async write(Z,J){await this.init(),await(!!Z.match(/\.glb$/)?this._writeGLB(Z,J):this._writeGLTF(Z,J))}async _writeGLTF(Z,J){var X=this;this.lastWriteBytes=0;let{json:$,resources:Y}=await this.writeJSON(J,{format:YZ.GLTF,basename:QZ.basename(Z)}),{_fs:Q,_path:K}=this,W=K.dirname(Z),G=JSON.stringify($,null,2);await Q.writeFile(Z,G),this.lastWriteBytes+=G.length;for(let z of VU1(Object.keys(Y),10))await Promise.all(z.map(async function(V){if(c4.isAbsoluteURL(V)){if(c4.extension(V)==="bin")throw new Error(`Cannot write buffer to path "${V}".`);return}let H=K.join(W,decodeURIComponent(V));await Q.mkdir(K.dirname(H),{recursive:!0}),await Q.writeFile(H,Y[V]),X.lastWriteBytes+=Y[V].byteLength}))}async _writeGLB(Z,J){let X=await this.writeBinary(J);await this._fs.writeFile(Z,X),this.lastWriteBytes=X.byteLength}}function VU1(Z,J){let X=[];for(let $=0,Y=Z.length;$<Y;$+=J){let Q=[];for(let K=0;K<J&&$+K<Y;K++)Q.push(Z[$+K]);X.push(Q)}return X}var kn=t(xR(),1),En=t(Fn(),1),$D1=t(fn(),1);async function YD1(Z,J){if(!(Z instanceof Uint8Array))throw new Error("[ndarray-pixels] Input must be Uint8Array or Buffer.");let{data:X,info:$}=await En.default(Z).ensureAlpha().raw().toBuffer({resolveWithObject:!0});return kn.default(new Uint8Array(X),[$.width,$.height,4],[4,4*$.width|0,1],0)}async function In(Z,J){return YD1(Z)}var bn=163,hn=166;function QD1(){return{vkFormat:0,typeSize:1,pixelWidth:0,pixelHeight:0,pixelDepth:0,layerCount:0,faceCount:1,levelCount:0,supercompressionScheme:0,levels:[],dataFormatDescriptor:[{vendorId:0,descriptorType:0,versionNumber:2,colorModel:0,colorPrimaries:1,transferFunction:2,flags:0,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],keyValue:{},globalData:null}}class U3{constructor(Z,J,X,$){this._dataView=void 0,this._littleEndian=void 0,this._offset=void 0,this._dataView=new DataView(Z.buffer,Z.byteOffset+J,X),this._littleEndian=$,this._offset=0}_nextUint8(){let Z=this._dataView.getUint8(this._offset);return this._offset+=1,Z}_nextUint16(){let Z=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,Z}_nextUint32(){let Z=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,Z}_nextUint64(){let Z=this._dataView.getUint32(this._offset,this._littleEndian),J=this._dataView.getUint32(this._offset+4,this._littleEndian),X=Z+4294967296*J;return this._offset+=8,X}_nextInt32(){let Z=this._dataView.getInt32(this._offset,this._littleEndian);return this._offset+=4,Z}_nextUint8Array(Z){let J=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._offset,Z);return this._offset+=Z,J}_skip(Z){return this._offset+=Z,this}_scan(Z,J=0){let X=this._offset,$=0;while(this._dataView.getUint8(this._offset)!==J&&$<Z)$++,this._offset++;if($<Z)this._offset++;return new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+X,$)}}var nN6=new Uint8Array([0]),p6=[171,75,84,88,32,50,48,187,13,10,26,10];function _n(Z){return new TextDecoder().decode(Z)}function Dc(Z){let J=new Uint8Array(Z.buffer,Z.byteOffset,p6.length);if(J[0]!==p6[0]||J[1]!==p6[1]||J[2]!==p6[2]||J[3]!==p6[3]||J[4]!==p6[4]||J[5]!==p6[5]||J[6]!==p6[6]||J[7]!==p6[7]||J[8]!==p6[8]||J[9]!==p6[9]||J[10]!==p6[10]||J[11]!==p6[11])throw new Error("Missing KTX 2.0 identifier.");let X=QD1(),$=17*Uint32Array.BYTES_PER_ELEMENT,Y=new U3(Z,p6.length,$,!0);X.vkFormat=Y._nextUint32(),X.typeSize=Y._nextUint32(),X.pixelWidth=Y._nextUint32(),X.pixelHeight=Y._nextUint32(),X.pixelDepth=Y._nextUint32(),X.layerCount=Y._nextUint32(),X.faceCount=Y._nextUint32(),X.levelCount=Y._nextUint32(),X.supercompressionScheme=Y._nextUint32();let Q=Y._nextUint32(),K=Y._nextUint32(),W=Y._nextUint32(),G=Y._nextUint32(),z=Y._nextUint64(),V=Y._nextUint64(),H=Math.max(X.levelCount,1)*3*8,v=new U3(Z,p6.length+$,H,!0);for(let P8=0,q6=Math.max(X.levelCount,1);P8<q6;P8++)X.levels.push({levelData:new Uint8Array(Z.buffer,Z.byteOffset+v._nextUint64(),v._nextUint64()),uncompressedByteLength:v._nextUint64()});let q=new U3(Z,Q,K,!0);q._skip(4);let F=q._nextUint16(),c=q._nextUint16(),w=q._nextUint16(),x=q._nextUint16(),j=q._nextUint8(),B=q._nextUint8(),L=q._nextUint8(),R=q._nextUint8(),M=[q._nextUint8(),q._nextUint8(),q._nextUint8(),q._nextUint8()],O=[q._nextUint8(),q._nextUint8(),q._nextUint8(),q._nextUint8(),q._nextUint8(),q._nextUint8(),q._nextUint8(),q._nextUint8()],N={vendorId:F,descriptorType:c,versionNumber:w,colorModel:j,colorPrimaries:B,transferFunction:L,flags:R,texelBlockDimension:M,bytesPlane:O,samples:[]},_=6,k=4,h=(x/4-_)/k;for(let P8=0;P8<h;P8++){let q6={bitOffset:q._nextUint16(),bitLength:q._nextUint8(),channelType:q._nextUint8(),samplePosition:[q._nextUint8(),q._nextUint8(),q._nextUint8(),q._nextUint8()],sampleLower:Number.NEGATIVE_INFINITY,sampleUpper:Number.POSITIVE_INFINITY};if(q6.channelType&64)q6.sampleLower=q._nextInt32(),q6.sampleUpper=q._nextInt32();else q6.sampleLower=q._nextUint32(),q6.sampleUpper=q._nextUint32();N.samples[P8]=q6}X.dataFormatDescriptor.length=0,X.dataFormatDescriptor.push(N);let f=new U3(Z,W,G,!0);while(f._offset<G){let P8=f._nextUint32(),q6=f._scan(P8),fH=_n(q6);if(X.keyValue[fH]=f._nextUint8Array(P8-q6.byteLength-1),fH.match(/^ktx/i)){let jA=_n(X.keyValue[fH]);X.keyValue[fH]=jA.substring(0,jA.lastIndexOf("\x00"))}let LG1=P8%4?4-P8%4:0;f._skip(LG1)}if(V<=0)return X;let C=new U3(Z,z,V,!0),b=C._nextUint16(),I=C._nextUint16(),a=C._nextUint32(),s=C._nextUint32(),Z0=C._nextUint32(),o=C._nextUint32(),M0=[];for(let P8=0,q6=Math.max(X.levelCount,1);P8<q6;P8++)M0.push({imageFlags:C._nextUint32(),rgbSliceByteOffset:C._nextUint32(),rgbSliceByteLength:C._nextUint32(),alphaSliceByteOffset:C._nextUint32(),alphaSliceByteLength:C._nextUint32()});let R0=z+C._offset,m0=R0+a,O1=m0+s,s0=O1+Z0,j1=new Uint8Array(Z.buffer,Z.byteOffset+R0,a),W4=new Uint8Array(Z.buffer,Z.byteOffset+m0,s),NJ=new Uint8Array(Z.buffer,Z.byteOffset+O1,Z0),IQ=new Uint8Array(Z.buffer,Z.byteOffset+s0,o);return X.globalData={endpointCount:b,selectorCount:I,imageDescs:M0,endpointsData:j1,selectorsData:W4,tablesData:NJ,extendedData:IQ},X}var zZ="EXT_mesh_gpu_instancing",X6="EXT_meshopt_compression",SG="EXT_texture_webp",AG="EXT_texture_avif",s1="KHR_draco_mesh_compression",j4="KHR_lights_punctual",VZ="KHR_materials_anisotropy",vZ="KHR_materials_clearcoat",HZ="KHR_materials_diffuse_transmission",qZ="KHR_materials_dispersion",FZ="KHR_materials_emissive_strength",cZ="KHR_materials_ior",wZ="KHR_materials_iridescence",xZ="KHR_materials_pbrSpecularGlossiness",UZ="KHR_materials_sheen",jZ="KHR_materials_specular",BZ="KHR_materials_transmission",gJ="KHR_materials_unlit",LZ="KHR_materials_volume",U6="KHR_materials_variants",on="KHR_mesh_quantization",mG="KHR_texture_basisu",DZ="KHR_texture_transform",B4="KHR_xmp_json_ld",iR="INSTANCE_ATTRIBUTE";class dR extends N1{init(){this.extensionName=zZ,this.propertyType="InstancedMesh",this.parentTypes=[g.NODE]}getDefaults(){return Object.assign(super.getDefaults(),{attributes:new A6})}getAttribute(Z){return this.getRefMap("attributes",Z)}setAttribute(Z,J){return this.setRefMap("attributes",Z,J,{usage:iR})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}}dR.EXTENSION_NAME=zZ;class Oc extends P1{constructor(...Z){super(...Z);this.extensionName=zZ,this.provideTypes=[g.NODE],this.prewriteTypes=[g.ACCESSOR]}createInstancedMesh(){return new dR(this.document.getGraph())}read(Z){return(Z.jsonDoc.json.nodes||[]).forEach(($,Y)=>{if(!$.extensions||!$.extensions[zZ])return;let Q=$.extensions[zZ],K=this.createInstancedMesh();for(let W in Q.attributes)K.setAttribute(W,Z.accessors[Q.attributes[W]]);Z.nodes[Y].setExtension(zZ,K)}),this}prewrite(Z){Z.accessorUsageGroupedByParent.add(iR);for(let J of this.properties)for(let X of J.listAttributes())Z.addAccessorToUsageGroup(X,iR);return this}write(Z){let J=Z.jsonDoc;return this.document.getRoot().listNodes().forEach((X)=>{let $=X.getExtension(zZ);if($){let Y=Z.nodeIndexMap.get(X),Q=J.json.nodes[Y],K={attributes:{}};$.listSemantics().forEach((W)=>{let G=$.getAttribute(W);K.attributes[W]=Z.accessorIndexMap.get(G)}),Q.extensions=Q.extensions||{},Q.extensions[zZ]=K}}),this}}Oc.EXTENSION_NAME=zZ;function MZ(){return MZ=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var $ in X)({}).hasOwnProperty.call(X,$)&&(Z[$]=X[$])}return Z},MZ.apply(null,arguments)}var uG;(function(Z){Z.QUANTIZE="quantize",Z.FILTER="filter"})(uG||(uG={}));var j3;(function(Z){Z.ATTRIBUTES="ATTRIBUTES",Z.TRIANGLES="TRIANGLES",Z.INDICES="INDICES"})(j3||(j3={}));var $8;(function(Z){Z.NONE="NONE",Z.OCTAHEDRAL="OCTAHEDRAL",Z.QUATERNION="QUATERNION",Z.EXPONENTIAL="EXPONENTIAL"})($8||($8={}));function KD1(Z){if(!Z.extensions||!Z.extensions[X6])return!1;return!!Z.extensions[X6].fallback}var{BYTE:WD1,SHORT:Sn,FLOAT:GD1}=K0.ComponentType,{encodeNormalizedInt:An,decodeNormalizedInt:gR}=I0;function zD1(Z,J,X,$){let{filter:Y,bits:Q}=$,K={array:Z.getArray(),byteStride:Z.getElementSize()*Z.getComponentSize(),componentType:Z.getComponentType(),normalized:Z.getNormalized()};if(X!==j3.ATTRIBUTES)return K;if(Y!==$8.NONE){let W=Z.getNormalized()?VD1(Z):new Float32Array(K.array);switch(Y){case $8.EXPONENTIAL:K.byteStride=Z.getElementSize()*4,K.componentType=GD1,K.normalized=!1,K.array=J.encodeFilterExp(W,Z.getCount(),K.byteStride,Q);break;case $8.OCTAHEDRAL:K.byteStride=Q>8?8:4,K.componentType=Q>8?Sn:WD1,K.normalized=!0,W=Z.getElementSize()===3?HD1(W):W,K.array=J.encodeFilterOct(W,Z.getCount(),K.byteStride,Q);break;case $8.QUATERNION:K.byteStride=8,K.componentType=Sn,K.normalized=!0,K.array=J.encodeFilterQuat(W,Z.getCount(),K.byteStride,Q);break;default:throw new Error("Invalid filter.")}if(K.min=Z.getMin([]),K.max=Z.getMax([]),Z.getNormalized())K.min=K.min.map((G)=>gR(G,Z.getComponentType())),K.max=K.max.map((G)=>gR(G,Z.getComponentType()));if(K.normalized)K.min=K.min.map((G)=>An(G,K.componentType)),K.max=K.max.map((G)=>An(G,K.componentType))}else if(K.byteStride%4)K.array=vD1(K.array,Z.getElementSize()),K.byteStride=K.array.byteLength/Z.getCount();return K}function VD1(Z){let J=Z.getComponentType(),X=Z.getArray(),$=new Float32Array(X.length);for(let Y=0;Y<X.length;Y++)$[Y]=gR(X[Y],J);return $}function vD1(Z,J){let $=E0.padNumber(Z.BYTES_PER_ELEMENT*J)/Z.BYTES_PER_ELEMENT,Y=Z.length/J,Q=new Z.constructor(Y*$);for(let K=0;K*J<Z.length;K++)for(let W=0;W<J;W++)Q[K*$+W]=Z[K*J+W];return Q}function HD1(Z){let J=new Float32Array(Z.length*4/3);for(let X=0,$=Z.length/3;X<$;X++)J[X*4]=Z[X*3],J[X*4+1]=Z[X*3+1],J[X*4+2]=Z[X*3+2];return J}function qD1(Z,J){if(J===w4.BufferViewUsage.ELEMENT_ARRAY_BUFFER)return Z.listParents().some(($)=>{return $ instanceof g1&&$.getMode()===g1.Mode.TRIANGLES})?j3.TRIANGLES:j3.INDICES;return j3.ATTRIBUTES}function FD1(Z,J){let X=J.getGraph().listParentEdges(Z).filter(($)=>!($.getParent()instanceof W3));for(let $ of X){let Y=$.getName(),Q=$.getAttributes().key||"",K=$.getParent().propertyType===g.PRIMITIVE_TARGET;if(Y==="indices")return{filter:$8.NONE};if(Y==="attributes"){if(Q==="POSITION")return{filter:$8.NONE};if(Q==="TEXCOORD_0")return{filter:$8.NONE};if(Q.startsWith("JOINTS_"))return{filter:$8.NONE};if(Q.startsWith("WEIGHTS_"))return{filter:$8.NONE};if(Q==="NORMAL"||Q==="TANGENT")return K?{filter:$8.NONE}:{filter:$8.OCTAHEDRAL,bits:8}}if(Y==="output"){let W=rn(Z);if(W==="rotation")return{filter:$8.QUATERNION,bits:16};if(W==="translation")return{filter:$8.EXPONENTIAL,bits:12};if(W==="scale")return{filter:$8.EXPONENTIAL,bits:12};return{filter:$8.NONE}}if(Y==="input")return{filter:$8.NONE};if(Y==="inverseBindMatrices")return{filter:$8.NONE}}return{filter:$8.NONE}}function rn(Z){for(let J of Z.listParents()){if(!(J instanceof mJ))continue;for(let X of J.listParents()){if(!(X instanceof KZ))continue;return X.getTargetPath()}}return null}var mn={method:uG.QUANTIZE};class yG extends P1{constructor(...Z){super(...Z);this.extensionName=X6,this.prereadTypes=[g.BUFFER,g.PRIMITIVE],this.prewriteTypes=[g.BUFFER,g.ACCESSOR],this.readDependencies=["meshopt.decoder"],this.writeDependencies=["meshopt.encoder"],this._decoder=null,this._decoderFallbackBufferMap=new Map,this._encoder=null,this._encoderOptions=mn,this._encoderFallbackBuffer=null,this._encoderBufferViews={},this._encoderBufferViewData={},this._encoderBufferViewAccessors={}}install(Z,J){if(Z==="meshopt.decoder")this._decoder=J;if(Z==="meshopt.encoder")this._encoder=J;return this}setEncoderOptions(Z){return this._encoderOptions=MZ({},mn,Z),this}preread(Z,J){if(!this._decoder){if(!this.isRequired())return this;throw new Error(`[${X6}] Please install extension dependency, "meshopt.decoder".`)}if(!this._decoder.supported){if(!this.isRequired())return this;throw new Error(`[${X6}]: Missing WASM support.`)}if(J===g.BUFFER)this._prereadBuffers(Z);else if(J===g.PRIMITIVE)this._prereadPrimitives(Z);return this}_prereadBuffers(Z){let J=Z.jsonDoc;(J.json.bufferViews||[]).forEach(($,Y)=>{if(!$.extensions||!$.extensions[X6])return;let Q=$.extensions[X6],K=Q.byteOffset||0,W=Q.byteLength||0,G=Q.count,z=Q.byteStride,V=new Uint8Array(G*z),H=J.json.buffers[Q.buffer],v=H.uri?J.resources[H.uri]:J.resources[I$],q=E0.toView(v,K,W);this._decoder.decodeGltfBuffer(V,G,z,q,Q.mode,Q.filter),Z.bufferViews[Y]=V})}_prereadPrimitives(Z){let J=Z.jsonDoc;(J.json.bufferViews||[]).forEach(($)=>{if(!$.extensions||!$.extensions[X6])return;let Y=$.extensions[X6],Q=Z.buffers[Y.buffer],K=Z.buffers[$.buffer],W=J.json.buffers[$.buffer];if(KD1(W))this._decoderFallbackBufferMap.set(K,Q)})}read(Z){if(!this.isRequired())return this;for(let[J,X]of this._decoderFallbackBufferMap){for(let $ of J.listParents())if($ instanceof K0)$.swap(J,X);J.dispose()}return this}prewrite(Z,J){if(J===g.ACCESSOR)this._prewriteAccessors(Z);else if(J===g.BUFFER)this._prewriteBuffers(Z);return this}_prewriteAccessors(Z){let J=Z.jsonDoc.json,X=this._encoder,$=this._encoderOptions,Y=this.document.getGraph(),Q=this.document.createBuffer(),K=this.document.getRoot().listBuffers().indexOf(Q),W=1,G=new Map,z=(V)=>{for(let H of Y.listParents(V)){if(H.propertyType===g.ROOT)continue;let v=G.get(V);if(v===void 0)G.set(V,v=W++);return v}return-1};this._encoderFallbackBuffer=Q,this._encoderBufferViews={},this._encoderBufferViewData={},this._encoderBufferViewAccessors={};for(let V of this.document.getRoot().listAccessors()){if(rn(V)==="weights")continue;if(V.getSparse())continue;let H=Z.getAccessorUsage(V),v=Z.accessorUsageGroupedByParent.has(H)?z(V):null,q=qD1(V,H),F=$.method===uG.FILTER?FD1(V,this.document):{filter:$8.NONE},c=zD1(V,X,q,F),{array:w,byteStride:x}=c,j=V.getBuffer();if(!j)throw new Error(`${X6}: Missing buffer for accessor.`);let B=this.document.getRoot().listBuffers().indexOf(j),L=[H,v,q,F.filter,x,B].join(":"),R=this._encoderBufferViews[L],M=this._encoderBufferViewData[L],O=this._encoderBufferViewAccessors[L];if(!R||!M)O=this._encoderBufferViewAccessors[L]=[],M=this._encoderBufferViewData[L]=[],R=this._encoderBufferViews[L]={buffer:K,target:w4.USAGE_TO_TARGET[H],byteOffset:0,byteLength:0,byteStride:H===w4.BufferViewUsage.ARRAY_BUFFER?x:void 0,extensions:{[X6]:{buffer:B,byteOffset:0,byteLength:0,mode:q,filter:F.filter!==$8.NONE?F.filter:void 0,byteStride:x,count:0}}};let P=Z.createAccessorDef(V);if(P.componentType=c.componentType,P.normalized=c.normalized,P.byteOffset=R.byteLength,P.min&&c.min)P.min=c.min;if(P.max&&c.max)P.max=c.max;Z.accessorIndexMap.set(V,J.accessors.length),J.accessors.push(P),O.push(P),M.push(new Uint8Array(w.buffer,w.byteOffset,w.byteLength)),R.byteLength+=w.byteLength,R.extensions.EXT_meshopt_compression.count+=V.getCount()}}_prewriteBuffers(Z){let J=this._encoder;for(let X in this._encoderBufferViews){let $=this._encoderBufferViews[X],Y=this._encoderBufferViewData[X],Q=this.document.getRoot().listBuffers()[$.extensions[X6].buffer],K=Z.otherBufferViews.get(Q)||[],{count:W,byteStride:G,mode:z}=$.extensions[X6],V=E0.concat(Y),H=J.encodeGltfBuffer(V,W,G,z),v=E0.pad(H);$.extensions[X6].byteLength=H.byteLength,Y.length=0,Y.push(v),K.push(v),Z.otherBufferViews.set(Q,K)}}write(Z){let J=0;for(let Q in this._encoderBufferViews){let K=this._encoderBufferViews[Q],W=this._encoderBufferViewData[Q][0],G=Z.otherBufferViewsIndexMap.get(W),z=this._encoderBufferViewAccessors[Q];for(let q of z)q.bufferView=G;let V=Z.jsonDoc.json.bufferViews[G],H=V.byteOffset||0;Object.assign(V,K),V.byteOffset=J;let v=V.extensions[X6];v.byteOffset=H,J+=E0.padNumber(K.byteLength)}let X=this._encoderFallbackBuffer,$=Z.bufferIndexMap.get(X),Y=Z.jsonDoc.json.buffers[$];return Y.byteLength=J,Y.extensions={[X6]:{fallback:!0}},X.dispose(),this}}yG.EXTENSION_NAME=X6;yG.EncoderMethod=uG;class tn{match(Z){return Z.length>=12&&E0.decodeText(Z.slice(4,12))==="ftypavif"}getSize(Z){if(!this.match(Z))return null;let J=new DataView(Z.buffer,Z.byteOffset,Z.byteLength),X=un(J,0);if(!X)return null;let $=X.end;while(X=un(J,$))if(X.type==="meta")$=X.start+4;else if(X.type==="iprp"||X.type==="ipco")$=X.start;else if(X.type==="ispe")return[J.getUint32(X.start+4),J.getUint32(X.start+8)];else if(X.type==="mdat")break;else $=X.end;return null}getChannels(Z){return 4}}class Nc extends P1{constructor(...Z){super(...Z);this.extensionName=AG,this.prereadTypes=[g.TEXTURE]}static register(){_5.registerFormat("image/avif",new tn)}preread(Z){return(Z.jsonDoc.json.textures||[]).forEach((X)=>{if(X.extensions&&X.extensions[AG])X.source=X.extensions[AG].source}),this}read(Z){return this}write(Z){let J=Z.jsonDoc;return this.document.getRoot().listTextures().forEach((X)=>{if(X.getMimeType()==="image/avif"){let $=Z.imageIndexMap.get(X);(J.json.textures||[]).forEach((Q)=>{if(Q.source===$)Q.extensions=Q.extensions||{},Q.extensions[AG]={source:Q.source},delete Q.source})}}),this}}Nc.EXTENSION_NAME=AG;function un(Z,J){if(Z.byteLength<4+J)return null;let X=Z.getUint32(J);if(Z.byteLength<X+J||X<8)return null;return{type:E0.decodeText(new Uint8Array(Z.buffer,Z.byteOffset+J+4,4)),start:J+8,end:J+X}}class en{match(Z){return Z.length>=12&&Z[8]===87&&Z[9]===69&&Z[10]===66&&Z[11]===80}getSize(Z){let J=E0.decodeText(Z.slice(0,4)),X=E0.decodeText(Z.slice(8,12));if(J!=="RIFF"||X!=="WEBP")return null;let $=new DataView(Z.buffer,Z.byteOffset),Y=12;while(Y<$.byteLength){let Q=E0.decodeText(new Uint8Array([$.getUint8(Y),$.getUint8(Y+1),$.getUint8(Y+2),$.getUint8(Y+3)])),K=$.getUint32(Y+4,!0);if(Q==="VP8 "){let W=$.getInt16(Y+14,!0)&16383,G=$.getInt16(Y+16,!0)&16383;return[W,G]}else if(Q==="VP8L"){let W=$.getUint8(Y+9),G=$.getUint8(Y+10),z=$.getUint8(Y+11),V=$.getUint8(Y+12),H=1+((G&63)<<8|W),v=1+((V&15)<<10|z<<2|(G&192)>>6);return[H,v]}Y+=8+K+K%2}return null}getChannels(Z){return 4}}class Pc extends P1{constructor(...Z){super(...Z);this.extensionName=SG,this.prereadTypes=[g.TEXTURE]}static register(){_5.registerFormat("image/webp",new en)}preread(Z){return(Z.jsonDoc.json.textures||[]).forEach((X)=>{if(X.extensions&&X.extensions[SG])X.source=X.extensions[SG].source}),this}read(Z){return this}write(Z){let J=Z.jsonDoc;return this.document.getRoot().listTextures().forEach((X)=>{if(X.getMimeType()==="image/webp"){let $=Z.imageIndexMap.get(X);(J.json.textures||[]).forEach((Q)=>{if(Q.source===$)Q.extensions=Q.extensions||{},Q.extensions[SG]={source:Q.source},delete Q.source})}}),this}}Pc.EXTENSION_NAME=SG;var h8,Zs,Js;function cD1(Z,J){let X=new h8.DecoderBuffer;try{if(X.Init(J,J.length),Z.GetEncodedGeometryType(X)!==h8.TRIANGULAR_MESH)throw new Error(`[${s1}] Unknown geometry type.`);let Y=new h8.Mesh;if(!Z.DecodeBufferToMesh(X,Y).ok()||Y.ptr===0)throw new Error(`[${s1}] Decoding failure.`);return Y}finally{h8.destroy(X)}}function wD1(Z,J){let $=J.num_faces()*3,Y,Q;if(J.num_points()<=65534){let K=$*Uint16Array.BYTES_PER_ELEMENT;Y=h8._malloc(K),Z.GetTrianglesUInt16Array(J,K,Y),Q=new Uint16Array(h8.HEAPU16.buffer,Y,$).slice()}else{let K=$*Uint32Array.BYTES_PER_ELEMENT;Y=h8._malloc(K),Z.GetTrianglesUInt32Array(J,K,Y),Q=new Uint32Array(h8.HEAPU32.buffer,Y,$).slice()}return h8._free(Y),Q}function xD1(Z,J,X,$){let Y=Js[$.componentType],Q=Zs[$.componentType],K=X.num_components(),G=J.num_points()*K,z=G*Q.BYTES_PER_ELEMENT,V=h8._malloc(z);Z.GetAttributeDataArrayForAllPoints(J,X,Y,z,V);let H=new Q(h8.HEAPF32.buffer,V,G).slice();return h8._free(V),H}function UD1(Z){h8=Z,Zs={[K0.ComponentType.FLOAT]:Float32Array,[K0.ComponentType.UNSIGNED_INT]:Uint32Array,[K0.ComponentType.UNSIGNED_SHORT]:Uint16Array,[K0.ComponentType.UNSIGNED_BYTE]:Uint8Array,[K0.ComponentType.SHORT]:Int16Array,[K0.ComponentType.BYTE]:Int8Array},Js={[K0.ComponentType.FLOAT]:h8.DT_FLOAT32,[K0.ComponentType.UNSIGNED_INT]:h8.DT_UINT32,[K0.ComponentType.UNSIGNED_SHORT]:h8.DT_UINT16,[K0.ComponentType.UNSIGNED_BYTE]:h8.DT_UINT8,[K0.ComponentType.SHORT]:h8.DT_INT16,[K0.ComponentType.BYTE]:h8.DT_INT8}}var U4,lG;(function(Z){Z[Z.EDGEBREAKER=1]="EDGEBREAKER",Z[Z.SEQUENTIAL=0]="SEQUENTIAL"})(lG||(lG={}));var L4;(function(Z){Z.POSITION="POSITION",Z.NORMAL="NORMAL",Z.COLOR="COLOR",Z.TEX_COORD="TEX_COORD",Z.GENERIC="GENERIC"})(L4||(L4={}));var Xs={[L4.POSITION]:14,[L4.NORMAL]:10,[L4.COLOR]:8,[L4.TEX_COORD]:12,[L4.GENERIC]:12},ln={decodeSpeed:5,encodeSpeed:5,method:lG.EDGEBREAKER,quantizationBits:Xs,quantizationVolume:"mesh"};function jD1(Z){U4=Z}function BD1(Z,J=ln){let X=MZ({},ln,J);X.quantizationBits=MZ({},Xs,J.quantizationBits);let $=new U4.MeshBuilder,Y=new U4.Mesh,Q=new U4.ExpertEncoder(Y),K={},W=new U4.DracoInt8Array,G=Z.listTargets().length>0,z=!1;for(let c of Z.listSemantics()){let w=Z.getAttribute(c);if(w.getSparse()){z=!0;continue}let x=LD1(c),j=DD1($,w.getComponentType(),Y,U4[x],w.getCount(),w.getElementSize(),w.getArray());if(j===-1)throw new Error(`Error compressing "${c}" attribute.`);if(K[c]=j,X.quantizationVolume==="mesh"||c!=="POSITION")Q.SetAttributeQuantization(j,X.quantizationBits[x]);else if(typeof X.quantizationVolume==="object"){let{quantizationVolume:B}=X,L=Math.max(B.max[0]-B.min[0],B.max[1]-B.min[1],B.max[2]-B.min[2]);Q.SetAttributeExplicitQuantization(j,X.quantizationBits[x],w.getElementSize(),B.min,L)}else throw new Error("Invalid quantization volume state.")}let V=Z.getIndices();if(!V)throw new Mc("Primitive must have indices.");if($.AddFacesToMesh(Y,V.getCount()/3,V.getArray()),Q.SetSpeedOptions(X.encodeSpeed,X.decodeSpeed),Q.SetTrackEncodedProperties(!0),X.method===lG.SEQUENTIAL||G||z)Q.SetEncodingMethod(U4.MESH_SEQUENTIAL_ENCODING);else Q.SetEncodingMethod(U4.MESH_EDGEBREAKER_ENCODING);let H=Q.EncodeToDracoBuffer(!(G||z),W);if(H<=0)throw new Mc("Error applying Draco compression.");let v=new Uint8Array(H);for(let c=0;c<H;++c)v[c]=W.GetValue(c);let q=Q.GetNumberOfEncodedPoints(),F=Q.GetNumberOfEncodedFaces()*3;return U4.destroy(W),U4.destroy(Y),U4.destroy($),U4.destroy(Q),{numVertices:q,numIndices:F,data:v,attributeIDs:K}}function LD1(Z){if(Z==="POSITION")return L4.POSITION;else if(Z==="NORMAL")return L4.NORMAL;else if(Z.startsWith("COLOR_"))return L4.COLOR;else if(Z.startsWith("TEXCOORD_"))return L4.TEX_COORD;return L4.GENERIC}function DD1(Z,J,X,$,Y,Q,K){switch(J){case K0.ComponentType.UNSIGNED_BYTE:return Z.AddUInt8Attribute(X,$,Y,Q,K);case K0.ComponentType.BYTE:return Z.AddInt8Attribute(X,$,Y,Q,K);case K0.ComponentType.UNSIGNED_SHORT:return Z.AddUInt16Attribute(X,$,Y,Q,K);case K0.ComponentType.SHORT:return Z.AddInt16Attribute(X,$,Y,Q,K);case K0.ComponentType.UNSIGNED_INT:return Z.AddUInt32Attribute(X,$,Y,Q,K);case K0.ComponentType.FLOAT:return Z.AddFloatAttribute(X,$,Y,Q,K);default:throw new Error(`Unexpected component type, "${J}".`)}}class Mc extends Error{}class pG extends P1{constructor(...Z){super(...Z);this.extensionName=s1,this.prereadTypes=[g.PRIMITIVE],this.prewriteTypes=[g.ACCESSOR],this.readDependencies=["draco3d.decoder"],this.writeDependencies=["draco3d.encoder"],this._decoderModule=null,this._encoderModule=null,this._encoderOptions={}}install(Z,J){if(Z==="draco3d.decoder")this._decoderModule=J,UD1(this._decoderModule);if(Z==="draco3d.encoder")this._encoderModule=J,jD1(this._encoderModule);return this}setEncoderOptions(Z){return this._encoderOptions=Z,this}preread(Z){if(!this._decoderModule)throw new Error(`[${s1}] Please install extension dependency, "draco3d.decoder".`);let J=this.document.getLogger(),X=Z.jsonDoc,$=new Map;try{let Y=X.json.meshes||[];for(let Q of Y)for(let K of Q.primitives){if(!K.extensions||!K.extensions[s1])continue;let W=K.extensions[s1],[G,z]=$.get(W.bufferView)||[];if(!z||!G){let V=X.json.bufferViews[W.bufferView],H=X.json.buffers[V.buffer],v=H.uri?X.resources[H.uri]:X.resources[I$],q=V.byteOffset||0,F=V.byteLength,c=E0.toView(v,q,F);G=new this._decoderModule.Decoder,z=cD1(G,c),$.set(W.bufferView,[G,z]),J.debug(`[${s1}] Decompressed ${c.byteLength} bytes.`)}for(let V in W.attributes){let H=Z.jsonDoc.json.accessors[K.attributes[V]],v=G.GetAttributeByUniqueId(z,W.attributes[V]),q=xD1(G,z,v,H);Z.accessors[K.attributes[V]].setArray(q)}if(K.indices!==void 0)Z.accessors[K.indices].setArray(wD1(G,z))}}finally{for(let[Y,Q]of Array.from($.values()))this._decoderModule.destroy(Y),this._decoderModule.destroy(Q)}return this}read(Z){return this}prewrite(Z,J){if(!this._encoderModule)throw new Error(`[${s1}] Please install extension dependency, "draco3d.encoder".`);let X=this.document.getLogger();X.debug(`[${s1}] Compression options: ${JSON.stringify(this._encoderOptions)}`);let $=MD1(this.document),Y=new Map,Q="mesh";if(this._encoderOptions.quantizationVolume==="scene")if(this.document.getRoot().listScenes().length!==1)X.warn(`[${s1}]: quantizationVolume=scene requires exactly 1 scene.`);else Q=OG(this.document.getRoot().listScenes().pop());for(let K of Array.from($.keys())){let W=$.get(K);if(!W)throw new Error("Unexpected primitive.");if(Y.has(W)){Y.set(W,Y.get(W));continue}let G=K.getIndices(),z=Z.jsonDoc.json.accessors,V;try{V=BD1(K,MZ({},this._encoderOptions,{quantizationVolume:Q}))}catch(q){if(q instanceof Mc){X.warn(`[${s1}]: ${q.message} Skipping primitive compression.`);continue}throw q}Y.set(W,V);let H=Z.createAccessorDef(G);if(H.count=V.numIndices,Z.accessorIndexMap.set(G,z.length),z.push(H),V.numVertices>65534&&K0.getComponentSize(H.componentType)<=2)H.componentType=K0.ComponentType.UNSIGNED_INT;else if(V.numVertices>254&&K0.getComponentSize(H.componentType)<=1)H.componentType=K0.ComponentType.UNSIGNED_SHORT;for(let q of K.listSemantics()){let F=K.getAttribute(q);if(V.attributeIDs[q]===void 0)continue;let c=Z.createAccessorDef(F);c.count=V.numVertices,Z.accessorIndexMap.set(F,z.length),z.push(c)}let v=K.getAttribute("POSITION").getBuffer()||this.document.getRoot().listBuffers()[0];if(!Z.otherBufferViews.has(v))Z.otherBufferViews.set(v,[]);Z.otherBufferViews.get(v).push(V.data)}return X.debug(`[${s1}] Compressed ${$.size} primitives.`),Z.extensionData[s1]={primitiveHashMap:$,primitiveEncodingMap:Y},this}write(Z){let J=Z.extensionData[s1];for(let X of this.document.getRoot().listMeshes()){let $=Z.jsonDoc.json.meshes[Z.meshIndexMap.get(X)];for(let Y=0;Y<X.listPrimitives().length;Y++){let Q=X.listPrimitives()[Y],K=$.primitives[Y],W=J.primitiveHashMap.get(Q);if(!W)continue;let G=J.primitiveEncodingMap.get(W);if(!G)continue;K.extensions=K.extensions||{},K.extensions[s1]={bufferView:Z.otherBufferViewsIndexMap.get(G.data),attributes:G.attributeIDs}}}if(!J.primitiveHashMap.size){let X=Z.jsonDoc.json;X.extensionsUsed=(X.extensionsUsed||[]).filter(($)=>$!==s1),X.extensionsRequired=(X.extensionsRequired||[]).filter(($)=>$!==s1)}return this}}pG.EXTENSION_NAME=s1;pG.EncoderMethod=lG;function MD1(Z){let J=Z.getLogger(),X=new Set,$=new Set,Y=0,Q=0;for(let H of Z.getRoot().listMeshes())for(let v of H.listPrimitives())if(!v.getIndices())$.add(v),Y++;else if(v.getMode()!==g1.Mode.TRIANGLES)$.add(v),Q++;else X.add(v);if(Y>0)J.warn(`[${s1}] Skipping Draco compression of ${Y} non-indexed primitives.`);if(Q>0)J.warn(`[${s1}] Skipping Draco compression of ${Q} non-TRIANGLES primitives.`);let K=Z.getRoot().listAccessors(),W=new Map;for(let H=0;H<K.length;H++)W.set(K[H],H);let G=new Map,z=new Set,V=new Map;for(let H of Array.from(X)){let v=yn(H,W);if(z.has(v)){V.set(H,v);continue}if(G.has(H.getIndices())){let q=H.getIndices(),F=q.clone();W.set(F,Z.getRoot().listAccessors().length-1),H.swap(q,F)}for(let q of H.listAttributes())if(G.has(q)){let F=q.clone();W.set(F,Z.getRoot().listAccessors().length-1),H.swap(q,F)}v=yn(H,W),z.add(v),V.set(H,v),G.set(H.getIndices(),v);for(let q of H.listAttributes())G.set(q,v)}for(let H of Array.from(G.keys())){let v=new Set(H.listParents().map((q)=>q.propertyType));if(v.size!==2||!v.has(g.PRIMITIVE)||!v.has(g.ROOT))throw new Error(`[${s1}] Compressed accessors must only be used as indices or vertex attributes.`)}for(let H of Array.from(X)){let v=V.get(H),q=H.getIndices();if(G.get(q)!==v||H.listAttributes().some((F)=>G.get(F)!==v))throw new Error(`[${s1}] Draco primitives must share all, or no, accessors.`)}for(let H of Array.from($)){let v=H.getIndices();if(G.has(v)||H.listAttributes().some((q)=>G.has(q)))throw new Error(`[${s1}] Accessor cannot be shared by compressed and uncompressed primitives.`)}return V}function yn(Z,J){let X=[],$=Z.getIndices();X.push(J.get($));for(let Y of Z.listAttributes())X.push(J.get(Y));return X.sort().join("|")}class B3 extends N1{init(){this.extensionName=j4,this.propertyType="Light",this.parentTypes=[g.NODE]}getDefaults(){return Object.assign(super.getDefaults(),{color:[1,1,1],intensity:1,type:B3.Type.POINT,range:null,innerConeAngle:0,outerConeAngle:Math.PI/4})}getColor(){return this.get("color")}setColor(Z){return this.set("color",Z)}getIntensity(){return this.get("intensity")}setIntensity(Z){return this.set("intensity",Z)}getType(){return this.get("type")}setType(Z){return this.set("type",Z)}getRange(){return this.get("range")}setRange(Z){return this.set("range",Z)}getInnerConeAngle(){return this.get("innerConeAngle")}setInnerConeAngle(Z){return this.set("innerConeAngle",Z)}getOuterConeAngle(){return this.get("outerConeAngle")}setOuterConeAngle(Z){return this.set("outerConeAngle",Z)}}B3.EXTENSION_NAME=j4;B3.Type={POINT:"point",SPOT:"spot",DIRECTIONAL:"directional"};class aR extends P1{constructor(...Z){super(...Z);this.extensionName=j4}createLight(Z=""){return new B3(this.document.getGraph(),Z)}read(Z){let J=Z.jsonDoc;if(!J.json.extensions||!J.json.extensions[j4])return this;let Y=(J.json.extensions[j4].lights||[]).map((Q)=>{var K,W;let G=this.createLight().setName(Q.name||"").setType(Q.type);if(Q.color!==void 0)G.setColor(Q.color);if(Q.intensity!==void 0)G.setIntensity(Q.intensity);if(Q.range!==void 0)G.setRange(Q.range);if(((K=Q.spot)==null?void 0:K.innerConeAngle)!==void 0)G.setInnerConeAngle(Q.spot.innerConeAngle);if(((W=Q.spot)==null?void 0:W.outerConeAngle)!==void 0)G.setOuterConeAngle(Q.spot.outerConeAngle);return G});return J.json.nodes.forEach((Q,K)=>{if(!Q.extensions||!Q.extensions[j4])return;let W=Q.extensions[j4];Z.nodes[K].setExtension(j4,Y[W.light])}),this}write(Z){let J=Z.jsonDoc;if(this.properties.size===0)return this;let X=[],$=new Map;for(let Y of this.properties){let Q=Y,K={type:Q.getType()};if(!I0.eq(Q.getColor(),[1,1,1]))K.color=Q.getColor();if(Q.getIntensity()!==1)K.intensity=Q.getIntensity();if(Q.getRange()!=null)K.range=Q.getRange();if(Q.getName())K.name=Q.getName();if(Q.getType()===B3.Type.SPOT)K.spot={innerConeAngle:Q.getInnerConeAngle(),outerConeAngle:Q.getOuterConeAngle()};X.push(K),$.set(Q,X.length-1)}return this.document.getRoot().listNodes().forEach((Y)=>{let Q=Y.getExtension(j4);if(Q){let K=Z.nodeIndexMap.get(Y),W=J.json.nodes[K];W.extensions=W.extensions||{},W.extensions[j4]={light:$.get(Q)}}}),J.json.extensions=J.json.extensions||{},J.json.extensions[j4]={lights:X},this}}aR.EXTENSION_NAME=j4;var{R:RD1,G:OD1,B:ND1}=V5;class nR extends N1{init(){this.extensionName=VZ,this.propertyType="Anisotropy",this.parentTypes=[g.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{anisotropyStrength:0,anisotropyRotation:0,anisotropyTexture:null,anisotropyTextureInfo:new F1(this.graph,"anisotropyTextureInfo")})}getAnisotropyStrength(){return this.get("anisotropyStrength")}setAnisotropyStrength(Z){return this.set("anisotropyStrength",Z)}getAnisotropyRotation(){return this.get("anisotropyRotation")}setAnisotropyRotation(Z){return this.set("anisotropyRotation",Z)}getAnisotropyTexture(){return this.getRef("anisotropyTexture")}getAnisotropyTextureInfo(){return this.getRef("anisotropyTexture")?this.getRef("anisotropyTextureInfo"):null}setAnisotropyTexture(Z){return this.setRef("anisotropyTexture",Z,{channels:RD1|OD1|ND1})}}nR.EXTENSION_NAME=VZ;class sR extends P1{constructor(...Z){super(...Z);this.extensionName=VZ,this.prereadTypes=[g.MESH],this.prewriteTypes=[g.MESH]}createAnisotropy(){return new nR(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[VZ]){let K=this.createAnisotropy();Z.materials[Q].setExtension(VZ,K);let W=Y.extensions[VZ];if(W.anisotropyStrength!==void 0)K.setAnisotropyStrength(W.anisotropyStrength);if(W.anisotropyRotation!==void 0)K.setAnisotropyRotation(W.anisotropyRotation);if(W.anisotropyTexture!==void 0){let G=W.anisotropyTexture,z=Z.textures[$[G.index].source];K.setAnisotropyTexture(z),Z.setTextureInfo(K.getAnisotropyTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(VZ);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let K=Q.extensions[VZ]={};if($.getAnisotropyStrength()>0)K.anisotropyStrength=$.getAnisotropyStrength();if($.getAnisotropyRotation()!==0)K.anisotropyRotation=$.getAnisotropyRotation();if($.getAnisotropyTexture()){let W=$.getAnisotropyTexture(),G=$.getAnisotropyTextureInfo();K.anisotropyTexture=Z.createTextureInfoDef(W,G)}}}),this}}sR.EXTENSION_NAME=VZ;var{R:pn,G:gn,B:PD1}=V5;class oR extends N1{init(){this.extensionName=vZ,this.propertyType="Clearcoat",this.parentTypes=[g.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{clearcoatFactor:0,clearcoatTexture:null,clearcoatTextureInfo:new F1(this.graph,"clearcoatTextureInfo"),clearcoatRoughnessFactor:0,clearcoatRoughnessTexture:null,clearcoatRoughnessTextureInfo:new F1(this.graph,"clearcoatRoughnessTextureInfo"),clearcoatNormalScale:1,clearcoatNormalTexture:null,clearcoatNormalTextureInfo:new F1(this.graph,"clearcoatNormalTextureInfo")})}getClearcoatFactor(){return this.get("clearcoatFactor")}setClearcoatFactor(Z){return this.set("clearcoatFactor",Z)}getClearcoatTexture(){return this.getRef("clearcoatTexture")}getClearcoatTextureInfo(){return this.getRef("clearcoatTexture")?this.getRef("clearcoatTextureInfo"):null}setClearcoatTexture(Z){return this.setRef("clearcoatTexture",Z,{channels:pn})}getClearcoatRoughnessFactor(){return this.get("clearcoatRoughnessFactor")}setClearcoatRoughnessFactor(Z){return this.set("clearcoatRoughnessFactor",Z)}getClearcoatRoughnessTexture(){return this.getRef("clearcoatRoughnessTexture")}getClearcoatRoughnessTextureInfo(){return this.getRef("clearcoatRoughnessTexture")?this.getRef("clearcoatRoughnessTextureInfo"):null}setClearcoatRoughnessTexture(Z){return this.setRef("clearcoatRoughnessTexture",Z,{channels:gn})}getClearcoatNormalScale(){return this.get("clearcoatNormalScale")}setClearcoatNormalScale(Z){return this.set("clearcoatNormalScale",Z)}getClearcoatNormalTexture(){return this.getRef("clearcoatNormalTexture")}getClearcoatNormalTextureInfo(){return this.getRef("clearcoatNormalTexture")?this.getRef("clearcoatNormalTextureInfo"):null}setClearcoatNormalTexture(Z){return this.setRef("clearcoatNormalTexture",Z,{channels:pn|gn|PD1})}}oR.EXTENSION_NAME=vZ;class rR extends P1{constructor(...Z){super(...Z);this.extensionName=vZ,this.prereadTypes=[g.MESH],this.prewriteTypes=[g.MESH]}createClearcoat(){return new oR(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[vZ]){let K=this.createClearcoat();Z.materials[Q].setExtension(vZ,K);let W=Y.extensions[vZ];if(W.clearcoatFactor!==void 0)K.setClearcoatFactor(W.clearcoatFactor);if(W.clearcoatRoughnessFactor!==void 0)K.setClearcoatRoughnessFactor(W.clearcoatRoughnessFactor);if(W.clearcoatTexture!==void 0){let G=W.clearcoatTexture,z=Z.textures[$[G.index].source];K.setClearcoatTexture(z),Z.setTextureInfo(K.getClearcoatTextureInfo(),G)}if(W.clearcoatRoughnessTexture!==void 0){let G=W.clearcoatRoughnessTexture,z=Z.textures[$[G.index].source];K.setClearcoatRoughnessTexture(z),Z.setTextureInfo(K.getClearcoatRoughnessTextureInfo(),G)}if(W.clearcoatNormalTexture!==void 0){let G=W.clearcoatNormalTexture,z=Z.textures[$[G.index].source];if(K.setClearcoatNormalTexture(z),Z.setTextureInfo(K.getClearcoatNormalTextureInfo(),G),G.scale!==void 0)K.setClearcoatNormalScale(G.scale)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(vZ);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let K=Q.extensions[vZ]={clearcoatFactor:$.getClearcoatFactor(),clearcoatRoughnessFactor:$.getClearcoatRoughnessFactor()};if($.getClearcoatTexture()){let W=$.getClearcoatTexture(),G=$.getClearcoatTextureInfo();K.clearcoatTexture=Z.createTextureInfoDef(W,G)}if($.getClearcoatRoughnessTexture()){let W=$.getClearcoatRoughnessTexture(),G=$.getClearcoatRoughnessTextureInfo();K.clearcoatRoughnessTexture=Z.createTextureInfoDef(W,G)}if($.getClearcoatNormalTexture()){let W=$.getClearcoatNormalTexture(),G=$.getClearcoatNormalTextureInfo();if(K.clearcoatNormalTexture=Z.createTextureInfoDef(W,G),$.getClearcoatNormalScale()!==1)K.clearcoatNormalTexture.scale=$.getClearcoatNormalScale()}}}),this}}rR.EXTENSION_NAME=vZ;var{R:TD1,G:CD1,B:fD1,A:kD1}=V5;class tR extends N1{init(){this.extensionName=HZ,this.propertyType="DiffuseTransmission",this.parentTypes=[g.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{diffuseTransmissionFactor:0,diffuseTransmissionTexture:null,diffuseTransmissionTextureInfo:new F1(this.graph,"diffuseTransmissionTextureInfo"),diffuseTransmissionColorFactor:[1,1,1],diffuseTransmissionColorTexture:null,diffuseTransmissionColorTextureInfo:new F1(this.graph,"diffuseTransmissionColorTextureInfo")})}getDiffuseTransmissionFactor(){return this.get("diffuseTransmissionFactor")}setDiffuseTransmissionFactor(Z){return this.set("diffuseTransmissionFactor",Z)}getDiffuseTransmissionTexture(){return this.getRef("diffuseTransmissionTexture")}getDiffuseTransmissionTextureInfo(){return this.getRef("diffuseTransmissionTexture")?this.getRef("diffuseTransmissionTextureInfo"):null}setDiffuseTransmissionTexture(Z){return this.setRef("diffuseTransmissionTexture",Z,{channels:kD1})}getDiffuseTransmissionColorFactor(){return this.get("diffuseTransmissionColorFactor")}setDiffuseTransmissionColorFactor(Z){return this.set("diffuseTransmissionColorFactor",Z)}getDiffuseTransmissionColorTexture(){return this.getRef("diffuseTransmissionColorTexture")}getDiffuseTransmissionColorTextureInfo(){return this.getRef("diffuseTransmissionColorTexture")?this.getRef("diffuseTransmissionColorTextureInfo"):null}setDiffuseTransmissionColorTexture(Z){return this.setRef("diffuseTransmissionColorTexture",Z,{channels:TD1|CD1|fD1})}}tR.EXTENSION_NAME=HZ;class eR extends P1{constructor(...Z){super(...Z);this.extensionName=HZ}createDiffuseTransmission(){return new tR(this.document.getGraph())}read(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[HZ]){let K=this.createDiffuseTransmission();Z.materials[Q].setExtension(HZ,K);let W=Y.extensions[HZ];if(W.diffuseTransmissionFactor!==void 0)K.setDiffuseTransmissionFactor(W.diffuseTransmissionFactor);if(W.diffuseTransmissionColorFactor!==void 0)K.setDiffuseTransmissionColorFactor(W.diffuseTransmissionColorFactor);if(W.diffuseTransmissionTexture!==void 0){let G=W.diffuseTransmissionTexture,z=Z.textures[$[G.index].source];K.setDiffuseTransmissionTexture(z),Z.setTextureInfo(K.getDiffuseTransmissionTextureInfo(),G)}if(W.diffuseTransmissionColorTexture!==void 0){let G=W.diffuseTransmissionColorTexture,z=Z.textures[$[G.index].source];K.setDiffuseTransmissionColorTexture(z),Z.setTextureInfo(K.getDiffuseTransmissionColorTextureInfo(),G)}}}),this}write(Z){let J=Z.jsonDoc;for(let X of this.document.getRoot().listMaterials()){let $=X.getExtension(HZ);if(!$)continue;let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let K=Q.extensions[HZ]={diffuseTransmissionFactor:$.getDiffuseTransmissionFactor(),diffuseTransmissionColorFactor:$.getDiffuseTransmissionColorFactor()};if($.getDiffuseTransmissionTexture()){let W=$.getDiffuseTransmissionTexture(),G=$.getDiffuseTransmissionTextureInfo();K.diffuseTransmissionTexture=Z.createTextureInfoDef(W,G)}if($.getDiffuseTransmissionColorTexture()){let W=$.getDiffuseTransmissionColorTexture(),G=$.getDiffuseTransmissionColorTextureInfo();K.diffuseTransmissionColorTexture=Z.createTextureInfoDef(W,G)}}return this}}eR.EXTENSION_NAME=HZ;class ZO extends N1{init(){this.extensionName=qZ,this.propertyType="Dispersion",this.parentTypes=[g.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{dispersion:0})}getDispersion(){return this.get("dispersion")}setDispersion(Z){return this.set("dispersion",Z)}}ZO.EXTENSION_NAME=qZ;class JO extends P1{constructor(...Z){super(...Z);this.extensionName=qZ,this.prereadTypes=[g.MESH],this.prewriteTypes=[g.MESH]}createDispersion(){return new ZO(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach(($,Y)=>{if($.extensions&&$.extensions[qZ]){let Q=this.createDispersion();Z.materials[Y].setExtension(qZ,Q);let K=$.extensions[qZ];if(K.dispersion!==void 0)Q.setDispersion(K.dispersion)}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(qZ);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{},Q.extensions[qZ]={dispersion:$.getDispersion()}}}),this}}JO.EXTENSION_NAME=qZ;class XO extends N1{init(){this.extensionName=FZ,this.propertyType="EmissiveStrength",this.parentTypes=[g.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{emissiveStrength:1})}getEmissiveStrength(){return this.get("emissiveStrength")}setEmissiveStrength(Z){return this.set("emissiveStrength",Z)}}XO.EXTENSION_NAME=FZ;class $O extends P1{constructor(...Z){super(...Z);this.extensionName=FZ,this.prereadTypes=[g.MESH],this.prewriteTypes=[g.MESH]}createEmissiveStrength(){return new XO(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach(($,Y)=>{if($.extensions&&$.extensions[FZ]){let Q=this.createEmissiveStrength();Z.materials[Y].setExtension(FZ,Q);let K=$.extensions[FZ];if(K.emissiveStrength!==void 0)Q.setEmissiveStrength(K.emissiveStrength)}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(FZ);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{},Q.extensions[FZ]={emissiveStrength:$.getEmissiveStrength()}}}),this}}$O.EXTENSION_NAME=FZ;class YO extends N1{init(){this.extensionName=cZ,this.propertyType="IOR",this.parentTypes=[g.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{ior:1.5})}getIOR(){return this.get("ior")}setIOR(Z){return this.set("ior",Z)}}YO.EXTENSION_NAME=cZ;class Tc extends P1{constructor(...Z){super(...Z);this.extensionName=cZ,this.prereadTypes=[g.MESH],this.prewriteTypes=[g.MESH]}createIOR(){return new YO(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach(($,Y)=>{if($.extensions&&$.extensions[cZ]){let Q=this.createIOR();Z.materials[Y].setExtension(cZ,Q);let K=$.extensions[cZ];if(K.ior!==void 0)Q.setIOR(K.ior)}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(cZ);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{},Q.extensions[cZ]={ior:$.getIOR()}}}),this}}Tc.EXTENSION_NAME=cZ;var{R:ED1,G:ID1}=V5;class QO extends N1{init(){this.extensionName=wZ,this.propertyType="Iridescence",this.parentTypes=[g.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{iridescenceFactor:0,iridescenceTexture:null,iridescenceTextureInfo:new F1(this.graph,"iridescenceTextureInfo"),iridescenceIOR:1.3,iridescenceThicknessMinimum:100,iridescenceThicknessMaximum:400,iridescenceThicknessTexture:null,iridescenceThicknessTextureInfo:new F1(this.graph,"iridescenceThicknessTextureInfo")})}getIridescenceFactor(){return this.get("iridescenceFactor")}setIridescenceFactor(Z){return this.set("iridescenceFactor",Z)}getIridescenceTexture(){return this.getRef("iridescenceTexture")}getIridescenceTextureInfo(){return this.getRef("iridescenceTexture")?this.getRef("iridescenceTextureInfo"):null}setIridescenceTexture(Z){return this.setRef("iridescenceTexture",Z,{channels:ED1})}getIridescenceIOR(){return this.get("iridescenceIOR")}setIridescenceIOR(Z){return this.set("iridescenceIOR",Z)}getIridescenceThicknessMinimum(){return this.get("iridescenceThicknessMinimum")}setIridescenceThicknessMinimum(Z){return this.set("iridescenceThicknessMinimum",Z)}getIridescenceThicknessMaximum(){return this.get("iridescenceThicknessMaximum")}setIridescenceThicknessMaximum(Z){return this.set("iridescenceThicknessMaximum",Z)}getIridescenceThicknessTexture(){return this.getRef("iridescenceThicknessTexture")}getIridescenceThicknessTextureInfo(){return this.getRef("iridescenceThicknessTexture")?this.getRef("iridescenceThicknessTextureInfo"):null}setIridescenceThicknessTexture(Z){return this.setRef("iridescenceThicknessTexture",Z,{channels:ID1})}}QO.EXTENSION_NAME=wZ;class KO extends P1{constructor(...Z){super(...Z);this.extensionName=wZ,this.prereadTypes=[g.MESH],this.prewriteTypes=[g.MESH]}createIridescence(){return new QO(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[wZ]){let K=this.createIridescence();Z.materials[Q].setExtension(wZ,K);let W=Y.extensions[wZ];if(W.iridescenceFactor!==void 0)K.setIridescenceFactor(W.iridescenceFactor);if(W.iridescenceIor!==void 0)K.setIridescenceIOR(W.iridescenceIor);if(W.iridescenceThicknessMinimum!==void 0)K.setIridescenceThicknessMinimum(W.iridescenceThicknessMinimum);if(W.iridescenceThicknessMaximum!==void 0)K.setIridescenceThicknessMaximum(W.iridescenceThicknessMaximum);if(W.iridescenceTexture!==void 0){let G=W.iridescenceTexture,z=Z.textures[$[G.index].source];K.setIridescenceTexture(z),Z.setTextureInfo(K.getIridescenceTextureInfo(),G)}if(W.iridescenceThicknessTexture!==void 0){let G=W.iridescenceThicknessTexture,z=Z.textures[$[G.index].source];K.setIridescenceThicknessTexture(z),Z.setTextureInfo(K.getIridescenceThicknessTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(wZ);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let K=Q.extensions[wZ]={};if($.getIridescenceFactor()>0)K.iridescenceFactor=$.getIridescenceFactor();if($.getIridescenceIOR()!==1.3)K.iridescenceIor=$.getIridescenceIOR();if($.getIridescenceThicknessMinimum()!==100)K.iridescenceThicknessMinimum=$.getIridescenceThicknessMinimum();if($.getIridescenceThicknessMaximum()!==400)K.iridescenceThicknessMaximum=$.getIridescenceThicknessMaximum();if($.getIridescenceTexture()){let W=$.getIridescenceTexture(),G=$.getIridescenceTextureInfo();K.iridescenceTexture=Z.createTextureInfoDef(W,G)}if($.getIridescenceThicknessTexture()){let W=$.getIridescenceThicknessTexture(),G=$.getIridescenceThicknessTextureInfo();K.iridescenceThicknessTexture=Z.createTextureInfoDef(W,G)}}}),this}}KO.EXTENSION_NAME=wZ;var{R:dn,G:an,B:nn,A:sn}=V5;class WO extends N1{init(){this.extensionName=xZ,this.propertyType="PBRSpecularGlossiness",this.parentTypes=[g.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{diffuseFactor:[1,1,1,1],diffuseTexture:null,diffuseTextureInfo:new F1(this.graph,"diffuseTextureInfo"),specularFactor:[1,1,1],glossinessFactor:1,specularGlossinessTexture:null,specularGlossinessTextureInfo:new F1(this.graph,"specularGlossinessTextureInfo")})}getDiffuseFactor(){return this.get("diffuseFactor")}setDiffuseFactor(Z){return this.set("diffuseFactor",Z)}getDiffuseTexture(){return this.getRef("diffuseTexture")}getDiffuseTextureInfo(){return this.getRef("diffuseTexture")?this.getRef("diffuseTextureInfo"):null}setDiffuseTexture(Z){return this.setRef("diffuseTexture",Z,{channels:dn|an|nn|sn,isColor:!0})}getSpecularFactor(){return this.get("specularFactor")}setSpecularFactor(Z){return this.set("specularFactor",Z)}getGlossinessFactor(){return this.get("glossinessFactor")}setGlossinessFactor(Z){return this.set("glossinessFactor",Z)}getSpecularGlossinessTexture(){return this.getRef("specularGlossinessTexture")}getSpecularGlossinessTextureInfo(){return this.getRef("specularGlossinessTexture")?this.getRef("specularGlossinessTextureInfo"):null}setSpecularGlossinessTexture(Z){return this.setRef("specularGlossinessTexture",Z,{channels:dn|an|nn|sn})}}WO.EXTENSION_NAME=xZ;class Cc extends P1{constructor(...Z){super(...Z);this.extensionName=xZ,this.prereadTypes=[g.MESH],this.prewriteTypes=[g.MESH]}createPBRSpecularGlossiness(){return new WO(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[xZ]){let K=this.createPBRSpecularGlossiness();Z.materials[Q].setExtension(xZ,K);let W=Y.extensions[xZ];if(W.diffuseFactor!==void 0)K.setDiffuseFactor(W.diffuseFactor);if(W.specularFactor!==void 0)K.setSpecularFactor(W.specularFactor);if(W.glossinessFactor!==void 0)K.setGlossinessFactor(W.glossinessFactor);if(W.diffuseTexture!==void 0){let G=W.diffuseTexture,z=Z.textures[$[G.index].source];K.setDiffuseTexture(z),Z.setTextureInfo(K.getDiffuseTextureInfo(),G)}if(W.specularGlossinessTexture!==void 0){let G=W.specularGlossinessTexture,z=Z.textures[$[G.index].source];K.setSpecularGlossinessTexture(z),Z.setTextureInfo(K.getSpecularGlossinessTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(xZ);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let K=Q.extensions[xZ]={diffuseFactor:$.getDiffuseFactor(),specularFactor:$.getSpecularFactor(),glossinessFactor:$.getGlossinessFactor()};if($.getDiffuseTexture()){let W=$.getDiffuseTexture(),G=$.getDiffuseTextureInfo();K.diffuseTexture=Z.createTextureInfoDef(W,G)}if($.getSpecularGlossinessTexture()){let W=$.getSpecularGlossinessTexture(),G=$.getSpecularGlossinessTextureInfo();K.specularGlossinessTexture=Z.createTextureInfoDef(W,G)}}}),this}}Cc.EXTENSION_NAME=xZ;var{R:_D1,G:bD1,B:hD1,A:SD1}=V5;class GO extends N1{init(){this.extensionName=UZ,this.propertyType="Sheen",this.parentTypes=[g.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{sheenColorFactor:[0,0,0],sheenColorTexture:null,sheenColorTextureInfo:new F1(this.graph,"sheenColorTextureInfo"),sheenRoughnessFactor:0,sheenRoughnessTexture:null,sheenRoughnessTextureInfo:new F1(this.graph,"sheenRoughnessTextureInfo")})}getSheenColorFactor(){return this.get("sheenColorFactor")}setSheenColorFactor(Z){return this.set("sheenColorFactor",Z)}getSheenColorTexture(){return this.getRef("sheenColorTexture")}getSheenColorTextureInfo(){return this.getRef("sheenColorTexture")?this.getRef("sheenColorTextureInfo"):null}setSheenColorTexture(Z){return this.setRef("sheenColorTexture",Z,{channels:_D1|bD1|hD1,isColor:!0})}getSheenRoughnessFactor(){return this.get("sheenRoughnessFactor")}setSheenRoughnessFactor(Z){return this.set("sheenRoughnessFactor",Z)}getSheenRoughnessTexture(){return this.getRef("sheenRoughnessTexture")}getSheenRoughnessTextureInfo(){return this.getRef("sheenRoughnessTexture")?this.getRef("sheenRoughnessTextureInfo"):null}setSheenRoughnessTexture(Z){return this.setRef("sheenRoughnessTexture",Z,{channels:SD1})}}GO.EXTENSION_NAME=UZ;class zO extends P1{constructor(...Z){super(...Z);this.extensionName=UZ,this.prereadTypes=[g.MESH],this.prewriteTypes=[g.MESH]}createSheen(){return new GO(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[UZ]){let K=this.createSheen();Z.materials[Q].setExtension(UZ,K);let W=Y.extensions[UZ];if(W.sheenColorFactor!==void 0)K.setSheenColorFactor(W.sheenColorFactor);if(W.sheenRoughnessFactor!==void 0)K.setSheenRoughnessFactor(W.sheenRoughnessFactor);if(W.sheenColorTexture!==void 0){let G=W.sheenColorTexture,z=Z.textures[$[G.index].source];K.setSheenColorTexture(z),Z.setTextureInfo(K.getSheenColorTextureInfo(),G)}if(W.sheenRoughnessTexture!==void 0){let G=W.sheenRoughnessTexture,z=Z.textures[$[G.index].source];K.setSheenRoughnessTexture(z),Z.setTextureInfo(K.getSheenRoughnessTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(UZ);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let K=Q.extensions[UZ]={sheenColorFactor:$.getSheenColorFactor(),sheenRoughnessFactor:$.getSheenRoughnessFactor()};if($.getSheenColorTexture()){let W=$.getSheenColorTexture(),G=$.getSheenColorTextureInfo();K.sheenColorTexture=Z.createTextureInfoDef(W,G)}if($.getSheenRoughnessTexture()){let W=$.getSheenRoughnessTexture(),G=$.getSheenRoughnessTextureInfo();K.sheenRoughnessTexture=Z.createTextureInfoDef(W,G)}}}),this}}zO.EXTENSION_NAME=UZ;var{R:AD1,G:mD1,B:uD1,A:lD1}=V5;class VO extends N1{init(){this.extensionName=jZ,this.propertyType="Specular",this.parentTypes=[g.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{specularFactor:1,specularTexture:null,specularTextureInfo:new F1(this.graph,"specularTextureInfo"),specularColorFactor:[1,1,1],specularColorTexture:null,specularColorTextureInfo:new F1(this.graph,"specularColorTextureInfo")})}getSpecularFactor(){return this.get("specularFactor")}setSpecularFactor(Z){return this.set("specularFactor",Z)}getSpecularColorFactor(){return this.get("specularColorFactor")}setSpecularColorFactor(Z){return this.set("specularColorFactor",Z)}getSpecularTexture(){return this.getRef("specularTexture")}getSpecularTextureInfo(){return this.getRef("specularTexture")?this.getRef("specularTextureInfo"):null}setSpecularTexture(Z){return this.setRef("specularTexture",Z,{channels:lD1})}getSpecularColorTexture(){return this.getRef("specularColorTexture")}getSpecularColorTextureInfo(){return this.getRef("specularColorTexture")?this.getRef("specularColorTextureInfo"):null}setSpecularColorTexture(Z){return this.setRef("specularColorTexture",Z,{channels:AD1|mD1|uD1,isColor:!0})}}VO.EXTENSION_NAME=jZ;class fc extends P1{constructor(...Z){super(...Z);this.extensionName=jZ,this.prereadTypes=[g.MESH],this.prewriteTypes=[g.MESH]}createSpecular(){return new VO(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[jZ]){let K=this.createSpecular();Z.materials[Q].setExtension(jZ,K);let W=Y.extensions[jZ];if(W.specularFactor!==void 0)K.setSpecularFactor(W.specularFactor);if(W.specularColorFactor!==void 0)K.setSpecularColorFactor(W.specularColorFactor);if(W.specularTexture!==void 0){let G=W.specularTexture,z=Z.textures[$[G.index].source];K.setSpecularTexture(z),Z.setTextureInfo(K.getSpecularTextureInfo(),G)}if(W.specularColorTexture!==void 0){let G=W.specularColorTexture,z=Z.textures[$[G.index].source];K.setSpecularColorTexture(z),Z.setTextureInfo(K.getSpecularColorTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(jZ);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let K=Q.extensions[jZ]={};if($.getSpecularFactor()!==1)K.specularFactor=$.getSpecularFactor();if(!I0.eq($.getSpecularColorFactor(),[1,1,1]))K.specularColorFactor=$.getSpecularColorFactor();if($.getSpecularTexture()){let W=$.getSpecularTexture(),G=$.getSpecularTextureInfo();K.specularTexture=Z.createTextureInfoDef(W,G)}if($.getSpecularColorTexture()){let W=$.getSpecularColorTexture(),G=$.getSpecularColorTextureInfo();K.specularColorTexture=Z.createTextureInfoDef(W,G)}}}),this}}fc.EXTENSION_NAME=jZ;var{R:yD1}=V5;class vO extends N1{init(){this.extensionName=BZ,this.propertyType="Transmission",this.parentTypes=[g.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{transmissionFactor:0,transmissionTexture:null,transmissionTextureInfo:new F1(this.graph,"transmissionTextureInfo")})}getTransmissionFactor(){return this.get("transmissionFactor")}setTransmissionFactor(Z){return this.set("transmissionFactor",Z)}getTransmissionTexture(){return this.getRef("transmissionTexture")}getTransmissionTextureInfo(){return this.getRef("transmissionTexture")?this.getRef("transmissionTextureInfo"):null}setTransmissionTexture(Z){return this.setRef("transmissionTexture",Z,{channels:yD1})}}vO.EXTENSION_NAME=BZ;class HO extends P1{constructor(...Z){super(...Z);this.extensionName=BZ,this.prereadTypes=[g.MESH],this.prewriteTypes=[g.MESH]}createTransmission(){return new vO(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[BZ]){let K=this.createTransmission();Z.materials[Q].setExtension(BZ,K);let W=Y.extensions[BZ];if(W.transmissionFactor!==void 0)K.setTransmissionFactor(W.transmissionFactor);if(W.transmissionTexture!==void 0){let G=W.transmissionTexture,z=Z.textures[$[G.index].source];K.setTransmissionTexture(z),Z.setTextureInfo(K.getTransmissionTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(BZ);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let K=Q.extensions[BZ]={transmissionFactor:$.getTransmissionFactor()};if($.getTransmissionTexture()){let W=$.getTransmissionTexture(),G=$.getTransmissionTextureInfo();K.transmissionTexture=Z.createTextureInfoDef(W,G)}}}),this}}HO.EXTENSION_NAME=BZ;class qO extends N1{init(){this.extensionName=gJ,this.propertyType="Unlit",this.parentTypes=[g.MATERIAL]}}qO.EXTENSION_NAME=gJ;class kc extends P1{constructor(...Z){super(...Z);this.extensionName=gJ,this.prereadTypes=[g.MESH],this.prewriteTypes=[g.MESH]}createUnlit(){return new qO(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){return(Z.jsonDoc.json.materials||[]).forEach((X,$)=>{if(X.extensions&&X.extensions[gJ])Z.materials[$].setExtension(gJ,this.createUnlit())}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{if(X.getExtension(gJ)){let $=Z.materialIndexMap.get(X),Y=J.json.materials[$];Y.extensions=Y.extensions||{},Y.extensions[gJ]={}}}),this}}kc.EXTENSION_NAME=gJ;class FO extends N1{init(){this.extensionName=U6,this.propertyType="Mapping",this.parentTypes=["MappingList"]}getDefaults(){return Object.assign(super.getDefaults(),{material:null,variants:new c1})}getMaterial(){return this.getRef("material")}setMaterial(Z){return this.setRef("material",Z)}addVariant(Z){return this.addRef("variants",Z)}removeVariant(Z){return this.removeRef("variants",Z)}listVariants(){return this.listRefs("variants")}}FO.EXTENSION_NAME=U6;class cO extends N1{init(){this.extensionName=U6,this.propertyType="MappingList",this.parentTypes=[g.PRIMITIVE]}getDefaults(){return Object.assign(super.getDefaults(),{mappings:new c1})}addMapping(Z){return this.addRef("mappings",Z)}removeMapping(Z){return this.removeRef("mappings",Z)}listMappings(){return this.listRefs("mappings")}}cO.EXTENSION_NAME=U6;class Rc extends N1{init(){this.extensionName=U6,this.propertyType="Variant",this.parentTypes=["MappingList"]}}Rc.EXTENSION_NAME=U6;class wO extends P1{constructor(...Z){super(...Z);this.extensionName=U6}createMappingList(){return new cO(this.document.getGraph())}createVariant(Z=""){return new Rc(this.document.getGraph(),Z)}createMapping(){return new FO(this.document.getGraph())}listVariants(){return Array.from(this.properties).filter((Z)=>Z instanceof Rc)}read(Z){let J=Z.jsonDoc;if(!J.json.extensions||!J.json.extensions[U6])return this;let Y=(J.json.extensions[U6].variants||[]).map((K)=>this.createVariant().setName(K.name||""));return(J.json.meshes||[]).forEach((K,W)=>{let G=Z.meshes[W];(K.primitives||[]).forEach((V,H)=>{if(!V.extensions||!V.extensions[U6])return;let v=this.createMappingList(),q=V.extensions[U6];for(let F of q.mappings){let c=this.createMapping();if(F.material!==void 0)c.setMaterial(Z.materials[F.material]);for(let w of F.variants||[])c.addVariant(Y[w]);v.addMapping(c)}G.listPrimitives()[H].setExtension(U6,v)})}),this}write(Z){let J=Z.jsonDoc,X=this.listVariants();if(!X.length)return this;let $=[],Y=new Map;for(let Q of X)Y.set(Q,$.length),$.push(Z.createPropertyDef(Q));for(let Q of this.document.getRoot().listMeshes()){let K=Z.meshIndexMap.get(Q);Q.listPrimitives().forEach((W,G)=>{let z=W.getExtension(U6);if(!z)return;let V=Z.jsonDoc.json.meshes[K].primitives[G],H=z.listMappings().map((v)=>{let q=Z.createPropertyDef(v),F=v.getMaterial();if(F)q.material=Z.materialIndexMap.get(F);return q.variants=v.listVariants().map((c)=>Y.get(c)),q});V.extensions=V.extensions||{},V.extensions[U6]={mappings:H}})}return J.json.extensions=J.json.extensions||{},J.json.extensions[U6]={variants:$},this}}wO.EXTENSION_NAME=U6;var{G:pD1}=V5;class xO extends N1{init(){this.extensionName=LZ,this.propertyType="Volume",this.parentTypes=[g.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{thicknessFactor:0,thicknessTexture:null,thicknessTextureInfo:new F1(this.graph,"thicknessTexture"),attenuationDistance:1/0,attenuationColor:[1,1,1]})}getThicknessFactor(){return this.get("thicknessFactor")}setThicknessFactor(Z){return this.set("thicknessFactor",Z)}getThicknessTexture(){return this.getRef("thicknessTexture")}getThicknessTextureInfo(){return this.getRef("thicknessTexture")?this.getRef("thicknessTextureInfo"):null}setThicknessTexture(Z){return this.setRef("thicknessTexture",Z,{channels:pD1})}getAttenuationDistance(){return this.get("attenuationDistance")}setAttenuationDistance(Z){return this.set("attenuationDistance",Z)}getAttenuationColor(){return this.get("attenuationColor")}setAttenuationColor(Z){return this.set("attenuationColor",Z)}}xO.EXTENSION_NAME=LZ;class UO extends P1{constructor(...Z){super(...Z);this.extensionName=LZ,this.prereadTypes=[g.MESH],this.prewriteTypes=[g.MESH]}createVolume(){return new xO(this.document.getGraph())}read(Z){return this}write(Z){return this}preread(Z){let J=Z.jsonDoc,X=J.json.materials||[],$=J.json.textures||[];return X.forEach((Y,Q)=>{if(Y.extensions&&Y.extensions[LZ]){let K=this.createVolume();Z.materials[Q].setExtension(LZ,K);let W=Y.extensions[LZ];if(W.thicknessFactor!==void 0)K.setThicknessFactor(W.thicknessFactor);if(W.attenuationDistance!==void 0)K.setAttenuationDistance(W.attenuationDistance);if(W.attenuationColor!==void 0)K.setAttenuationColor(W.attenuationColor);if(W.thicknessTexture!==void 0){let G=W.thicknessTexture,z=Z.textures[$[G.index].source];K.setThicknessTexture(z),Z.setTextureInfo(K.getThicknessTextureInfo(),G)}}}),this}prewrite(Z){let J=Z.jsonDoc;return this.document.getRoot().listMaterials().forEach((X)=>{let $=X.getExtension(LZ);if($){let Y=Z.materialIndexMap.get(X),Q=J.json.materials[Y];Q.extensions=Q.extensions||{};let K=Q.extensions[LZ]={};if($.getThicknessFactor()>0)K.thicknessFactor=$.getThicknessFactor();if(Number.isFinite($.getAttenuationDistance()))K.attenuationDistance=$.getAttenuationDistance();if(!I0.eq($.getAttenuationColor(),[1,1,1]))K.attenuationColor=$.getAttenuationColor();if($.getThicknessTexture()){let W=$.getThicknessTexture(),G=$.getThicknessTextureInfo();K.thicknessTexture=Z.createTextureInfoDef(W,G)}}}),this}}UO.EXTENSION_NAME=LZ;class iG extends P1{constructor(...Z){super(...Z);this.extensionName=on}read(Z){return this}write(Z){return this}}iG.EXTENSION_NAME=on;class $s{match(Z){return Z[0]===171&&Z[1]===75&&Z[2]===84&&Z[3]===88&&Z[4]===32&&Z[5]===50&&Z[6]===48&&Z[7]===187&&Z[8]===13&&Z[9]===10&&Z[10]===26&&Z[11]===10}getSize(Z){let J=Dc(Z);return[J.pixelWidth,J.pixelHeight]}getChannels(Z){let X=Dc(Z).dataFormatDescriptor[0];if(X.colorModel===bn)return X.samples.length===2&&(X.samples[1].channelType&15)===15?4:3;else if(X.colorModel===hn)return(X.samples[0].channelType&15)===3?4:3;throw new Error(`Unexpected KTX2 colorModel, "${X.colorModel}".`)}getVRAMByteLength(Z){let J=Dc(Z),X=this.getChannels(Z)>3,$=0;for(let Y=0;Y<J.levels.length;Y++){let Q=J.levels[Y];if(Q.uncompressedByteLength)$+=Q.uncompressedByteLength;else{let K=Math.max(1,Math.floor(J.pixelWidth/Math.pow(2,Y))),W=Math.max(1,Math.floor(J.pixelHeight/Math.pow(2,Y))),G=X?16:8;$+=K/4*(W/4)*G}}return $}}class jO extends P1{constructor(...Z){super(...Z);this.extensionName=mG,this.prereadTypes=[g.TEXTURE]}static register(){_5.registerFormat("image/ktx2",new $s)}preread(Z){return Z.jsonDoc.json.textures.forEach((J)=>{if(J.extensions&&J.extensions[mG]){let X=J.extensions[mG];J.source=X.source}}),this}read(Z){return this}write(Z){let J=Z.jsonDoc;return this.document.getRoot().listTextures().forEach((X)=>{if(X.getMimeType()==="image/ktx2"){let $=Z.imageIndexMap.get(X);J.json.textures.forEach((Y)=>{if(Y.source===$)Y.extensions=Y.extensions||{},Y.extensions[mG]={source:Y.source},delete Y.source})}}),this}}jO.EXTENSION_NAME=mG;class BO extends N1{init(){this.extensionName=DZ,this.propertyType="Transform",this.parentTypes=[g.TEXTURE_INFO]}getDefaults(){return Object.assign(super.getDefaults(),{offset:[0,0],rotation:0,scale:[1,1],texCoord:null})}getOffset(){return this.get("offset")}setOffset(Z){return this.set("offset",Z)}getRotation(){return this.get("rotation")}setRotation(Z){return this.set("rotation",Z)}getScale(){return this.get("scale")}setScale(Z){return this.set("scale",Z)}getTexCoord(){return this.get("texCoord")}setTexCoord(Z){return this.set("texCoord",Z)}}BO.EXTENSION_NAME=DZ;class LO extends P1{constructor(...Z){super(...Z);this.extensionName=DZ}createTransform(){return new BO(this.document.getGraph())}read(Z){for(let[J,X]of Array.from(Z.textureInfos.entries())){if(!X.extensions||!X.extensions[DZ])continue;let $=this.createTransform(),Y=X.extensions[DZ];if(Y.offset!==void 0)$.setOffset(Y.offset);if(Y.rotation!==void 0)$.setRotation(Y.rotation);if(Y.scale!==void 0)$.setScale(Y.scale);if(Y.texCoord!==void 0)$.setTexCoord(Y.texCoord);J.setExtension(DZ,$)}return this}write(Z){let J=Array.from(Z.textureInfoDefMap.entries());for(let[X,$]of J){let Y=X.getExtension(DZ);if(!Y)continue;$.extensions=$.extensions||{};let Q={},K=I0.eq;if(!K(Y.getOffset(),[0,0]))Q.offset=Y.getOffset();if(Y.getRotation()!==0)Q.rotation=Y.getRotation();if(!K(Y.getScale(),[1,1]))Q.scale=Y.getScale();if(Y.getTexCoord()!=null)Q.texCoord=Y.getTexCoord();$.extensions[DZ]=Q}return this}}LO.EXTENSION_NAME=DZ;var iD1=[g.ROOT,g.SCENE,g.NODE,g.MESH,g.MATERIAL,g.TEXTURE,g.ANIMATION];class DO extends N1{init(){this.extensionName=B4,this.propertyType="Packet",this.parentTypes=iD1}getDefaults(){return Object.assign(super.getDefaults(),{context:{},properties:{}})}getContext(){return this.get("context")}setContext(Z){return this.set("context",MZ({},Z))}listProperties(){return Object.keys(this.get("properties"))}getProperty(Z){let J=this.get("properties");return Z in J?J[Z]:null}setProperty(Z,J){this._assertContext(Z);let X=MZ({},this.get("properties"));if(J)X[Z]=J;else delete X[Z];return this.set("properties",X)}toJSONLD(){let Z=pR(this.get("context")),J=pR(this.get("properties"));return MZ({"@context":Z},J)}fromJSONLD(Z){Z=pR(Z);let J=Z["@context"];if(J)this.set("context",J);return delete Z["@context"],this.set("properties",Z)}_assertContext(Z){if(!(Z.split(":")[0]in this.get("context")))throw new Error(`${B4}: Missing context for term, "${Z}".`)}}DO.EXTENSION_NAME=B4;function pR(Z){return JSON.parse(JSON.stringify(Z))}class MO extends P1{constructor(...Z){super(...Z);this.extensionName=B4}createPacket(){return new DO(this.document.getGraph())}listPackets(){return Array.from(this.properties)}read(Z){var J;let X=(J=Z.jsonDoc.json.extensions)==null?void 0:J[B4];if(!X||!X.packets)return this;let $=Z.jsonDoc.json,Y=this.document.getRoot(),Q=X.packets.map((G)=>this.createPacket().fromJSONLD(G)),K=[[$.asset],$.scenes,$.nodes,$.meshes,$.materials,$.images,$.animations],W=[[Y],Y.listScenes(),Y.listNodes(),Y.listMeshes(),Y.listMaterials(),Y.listTextures(),Y.listAnimations()];for(let G=0;G<K.length;G++){let z=K[G]||[];for(let V=0;V<z.length;V++){let H=z[V];if(H.extensions&&H.extensions[B4]){let v=H.extensions[B4];W[G][V].setExtension(B4,Q[v.packet])}}}return this}write(Z){let{json:J}=Z.jsonDoc,X=[];for(let $ of this.properties){X.push($.toJSONLD());for(let Y of $.listParents()){let Q;switch(Y.propertyType){case g.ROOT:Q=J.asset;break;case g.SCENE:Q=J.scenes[Z.sceneIndexMap.get(Y)];break;case g.NODE:Q=J.nodes[Z.nodeIndexMap.get(Y)];break;case g.MESH:Q=J.meshes[Z.meshIndexMap.get(Y)];break;case g.MATERIAL:Q=J.materials[Z.materialIndexMap.get(Y)];break;case g.TEXTURE:Q=J.images[Z.imageIndexMap.get(Y)];break;case g.ANIMATION:Q=J.animations[Z.animationIndexMap.get(Y)];break;default:Q=null,this.document.getLogger().warn(`[${B4}]: Unsupported parent property, "${Y.propertyType}"`);break}if(!Q)continue;Q.extensions=Q.extensions||{},Q.extensions[B4]={packet:X.length-1}}}if(X.length>0)J.extensions=J.extensions||{},J.extensions[B4]={packets:X};return this}}MO.EXTENSION_NAME=B4;var gD1=[pG,aR,sR,rR,eR,JO,$O,Tc,KO,Cc,fc,zO,HO,kc,wO,UO,iG,jO,LO,MO],tN6=[Oc,yG,Nc,Pc,...gD1];var dD1=t(xR(),1);function M3(){return M3=Object.assign?Object.assign.bind():function(Z){for(var J=1;J<arguments.length;J++){var X=arguments[J];for(var $ in X)({}).hasOwnProperty.call(X,$)&&(Z[$]=X[$])}return Z},M3.apply(null,arguments)}var{POINTS:Ys,LINES:Ec,LINE_STRIP:aD1,LINE_LOOP:nD1,TRIANGLES:Ic,TRIANGLE_STRIP:sD1,TRIANGLE_FAN:oD1}=g1.Mode;function l$(Z,J){return Object.defineProperty(J,"name",{value:Z}),J}function OZ(Z,J){let X=M3({},Z);for(let $ in J)if(J[$]!==void 0)X[$]=J[$];return X}function Ds(Z){let J=Z.getIndices(),X=Z.getAttribute("POSITION");switch(Z.getMode()){case g1.Mode.POINTS:return J?J.getCount():X.getCount();case g1.Mode.LINES:return J?J.getCount()/2:X.getCount()/2;case g1.Mode.LINE_LOOP:return J?J.getCount():X.getCount();case g1.Mode.LINE_STRIP:return J?J.getCount()-1:X.getCount()-1;case g1.Mode.TRIANGLES:return J?J.getCount()/3:X.getCount()/3;case g1.Mode.TRIANGLE_STRIP:case g1.Mode.TRIANGLE_FAN:return J?J.getCount()-2:X.getCount()-2;default:throw new Error("Unexpected mode: "+Z.getMode())}}var rD1=new Intl.NumberFormat(void 0,{maximumFractionDigits:0});function NO(Z){return rD1.format(Z)}function tD1(Z,J,X=2){let $=Z>J?"–":"+",Y="%";return $+(Math.abs(Z-J)/Z*100).toFixed(X)+"%"}function Ac(Z,J){return`${NO(Z)} → ${NO(J)} (${tD1(Z,J)})`}function mc(Z){let J=[];for(let X of Z.listAttributes())J.push(X);for(let X of Z.listTargets())for(let $ of X.listAttributes())J.push($);return Array.from(new Set(J))}function eD1(Z,J,X){Z.swap(J,X);for(let $ of Z.listTargets())$.swap(J,X)}function Ms(Z){let J=Z.getIndices(),X=mc(Z);if(Z.dispose(),J&&!PO(J))J.dispose();for(let $ of X)if(!PO($))$.dispose()}function RZ(Z,J){return Z.createAccessor(J.getName()).setArray(J.getArray()).setType(J.getType()).setBuffer(J.getBuffer()).setNormalized(J.getNormalized()).setSparse(J.getSparse())}function ZM1(Z,J=Z){let X=_O(Z,J);for(let $=0;$<X.length;$++)X[$]=$;return X}function _O(Z,J=Z){return J<=65534?new Uint16Array(Z):new Uint32Array(Z)}function PO(Z){return Z.listParents().some((J)=>J.propertyType!==g.ROOT)}function Rs(Z){for(let J in Z)return!1;return!0}function Os(Z){let J=w6.fromGraph(Z.getGraph()),X=Z.getMaterial(),$=J.getRoot().listMaterials().indexOf(X),Y=XM1[Z.getMode()],Q=!!Z.getIndices(),K=Z.listSemantics().sort().map((G)=>{let z=Z.getAttribute(G),V=z.getElementSize(),H=z.getComponentType();return`${G}:${V}:${H}`}).join("+"),W=Z.listTargets().map((G)=>{return G.listSemantics().sort().map((z)=>{let V=Z.getAttribute(z),H=V.getElementSize(),v=V.getComponentType();return`${z}:${H}:${v}`}).join("+")}).join("~");return`${$}|${Y}|${Q}|${K}|${W}`}function JM1(Z){return Math.pow(2,Math.ceil(Math.log(Z)/Math.LN2))}var XM1={[Ys]:Ys,[Ec]:Ec,[aD1]:Ec,[nD1]:Ec,[Ic]:Ic,[sD1]:Ic,[oD1]:Ic},L3="center",Qs={pivot:"center"};function Ns(Z=Qs){let J=OZ(Qs,Z);return l$(L3,(X)=>{let $=X.getLogger(),Y=X.getRoot(),Q=Y.listAnimations().length>0||Y.listSkins().length>0;X.getRoot().listScenes().forEach((K,W)=>{$.debug(`${L3}: Scene ${W+1} / ${Y.listScenes().length}.`);let G;if(typeof J.pivot==="string"){let V=OG(K);if(G=[(V.max[0]-V.min[0])/2+V.min[0],(V.max[1]-V.min[1])/2+V.min[1],(V.max[2]-V.min[2])/2+V.min[2]],J.pivot==="above")G[1]=V.max[1];if(J.pivot==="below")G[1]=V.min[1]}else G=J.pivot;$.debug(`${L3}: Pivot "${G.join(", ")}".`);let z=[-1*G[0],-1*G[1],-1*G[2]];if(Q){$.debug(`${L3}: Model contains animation or skin. Adding a wrapper node.`);let V=X.createNode("Pivot").setTranslation(z);K.listChildren().forEach((H)=>V.addChild(H)),K.addChild(V)}else $.debug(`${L3}: Skipping wrapper, offsetting all root nodes.`),K.listChildren().forEach((V)=>{let H=V.getTranslation();V.setTranslation([H[0]+z[0],H[1]+z[1],H[2]+z[2]])})}),$.debug(`${L3}: Complete.`)})}function $M1(Z){let J=new Set,X=Z,$;while($=X.getParentNode()){if(J.has($))throw new Error("Circular dependency in scene graph.");J.add($),X=$}return X.listParents().filter((Y)=>Y instanceof K3)}function YM1(Z){let J=$M1(Z),X=Z.getParentNode();if(!X)return Z;Z.setMatrix(Z.getWorldMatrix()),X.removeChild(Z);for(let $ of J)$.addChild(Z);return Z}var R3=typeof Float32Array!=="undefined"?Float32Array:Array;if(!Math.hypot)Math.hypot=function(){var Z=0,J=arguments.length;while(J--)Z+=arguments[J]*arguments[J];return Math.sqrt(Z)};function QM1(Z,J){var X=J[0],$=J[1],Y=J[2],Q=J[3],K=J[4],W=J[5],G=J[6],z=J[7],V=J[8],H=J[9],v=J[10],q=J[11],F=J[12],c=J[13],w=J[14],x=J[15],j=X*W-$*K,B=X*G-Y*K,L=X*z-Q*K,R=$*G-Y*W,M=$*z-Q*W,O=Y*z-Q*G,P=V*c-H*F,N=V*w-v*F,_=V*x-q*F,k=H*w-v*c,h=H*x-q*c,f=v*x-q*w,C=j*f-B*h+L*k+R*_-M*N+O*P;if(!C)return null;return C=1/C,Z[0]=(W*f-G*h+z*k)*C,Z[1]=(Y*h-$*f-Q*k)*C,Z[2]=(c*O-w*M+x*R)*C,Z[3]=(v*M-H*O-q*R)*C,Z[4]=(G*_-K*f-z*N)*C,Z[5]=(X*f-Y*_+Q*N)*C,Z[6]=(w*L-F*O-x*B)*C,Z[7]=(V*O-v*L+q*B)*C,Z[8]=(K*h-W*_+z*P)*C,Z[9]=($*_-X*h-Q*P)*C,Z[10]=(F*M-c*L+x*j)*C,Z[11]=(H*L-V*M-q*j)*C,Z[12]=(W*N-K*k-G*P)*C,Z[13]=(X*k-$*N+Y*P)*C,Z[14]=(c*B-F*R-w*j)*C,Z[15]=(V*R-H*B+v*j)*C,Z}function KM1(Z){var J=Z[0],X=Z[1],$=Z[2],Y=Z[3],Q=Z[4],K=Z[5],W=Z[6],G=Z[7],z=Z[8],V=Z[9],H=Z[10],v=Z[11],q=Z[12],F=Z[13],c=Z[14],w=Z[15],x=J*K-X*Q,j=J*W-$*Q,B=J*G-Y*Q,L=X*W-$*K,R=X*G-Y*K,M=$*G-Y*W,O=z*F-V*q,P=z*c-H*q,N=z*w-v*q,_=V*c-H*F,k=V*w-v*F,h=H*w-v*c;return x*h-j*k+B*_+L*N-R*P+M*O}function Ps(Z,J,X){var $=J[0],Y=J[1],Q=J[2],K=J[3],W=J[4],G=J[5],z=J[6],V=J[7],H=J[8],v=J[9],q=J[10],F=J[11],c=J[12],w=J[13],x=J[14],j=J[15],B=X[0],L=X[1],R=X[2],M=X[3];return Z[0]=B*$+L*W+R*H+M*c,Z[1]=B*Y+L*G+R*v+M*w,Z[2]=B*Q+L*z+R*q+M*x,Z[3]=B*K+L*V+R*F+M*j,B=X[4],L=X[5],R=X[6],M=X[7],Z[4]=B*$+L*W+R*H+M*c,Z[5]=B*Y+L*G+R*v+M*w,Z[6]=B*Q+L*z+R*q+M*x,Z[7]=B*K+L*V+R*F+M*j,B=X[8],L=X[9],R=X[10],M=X[11],Z[8]=B*$+L*W+R*H+M*c,Z[9]=B*Y+L*G+R*v+M*w,Z[10]=B*Q+L*z+R*q+M*x,Z[11]=B*K+L*V+R*F+M*j,B=X[12],L=X[13],R=X[14],M=X[15],Z[12]=B*$+L*W+R*H+M*c,Z[13]=B*Y+L*G+R*v+M*w,Z[14]=B*Q+L*z+R*q+M*x,Z[15]=B*K+L*V+R*F+M*j,Z}var j6;(function(Z){Z.RENDER="render",Z.RENDER_CACHED="render-cached",Z.UPLOAD="upload",Z.UPLOAD_NAIVE="upload-naive",Z.DISTINCT="distinct",Z.DISTINCT_POSITION="distinct-position",Z.UNUSED="unused"})(j6||(j6={}));function u$(Z,J){let X=Z.getAttribute("POSITION"),$=Z.getIndices();switch(J){case j6.RENDER:return $?$.getCount():X.getCount();case j6.RENDER_CACHED:return $?new Set($.getArray()).size:X.getCount();case j6.UPLOAD_NAIVE:case j6.UPLOAD:return X.getCount();case j6.DISTINCT:case j6.DISTINCT_POSITION:return WM1(J);case j6.UNUSED:return $?X.getCount()-new Set($.getArray()).size:0;default:return GM1(J)}}function WM1(Z){throw new Error(`Not implemented: ${Z}`)}function GM1(Z){throw new Error(`Unexpected value: ${Z}`)}var dJ=4294967295;class Ts{constructor(Z){this.attributes=[],this.u8=void 0,this.u32=void 0;let J=0;for(let X of mc(Z))J+=this._initAttribute(X);this.u8=new Uint8Array(J),this.u32=new Uint32Array(this.u8.buffer)}_initAttribute(Z){let J=Z.getArray(),X=new Uint8Array(J.buffer,J.byteOffset,J.byteLength),$=Z.getElementSize()*Z.getComponentSize(),Y=E0.padNumber($);return this.attributes.push({u8:X,byteStride:$,paddedByteStride:Y}),Y}hash(Z){let J=0;for(let{u8:X,byteStride:$,paddedByteStride:Y}of this.attributes){for(let Q=0;Q<Y;Q++)if(Q<$)this.u8[J+Q]=X[Z*$+Q];else this.u8[J+Q]=0;J+=Y}return zM1(0,this.u32)}equal(Z,J){for(let{u8:X,byteStride:$}of this.attributes)for(let Y=0;Y<$;Y++)if(X[Z*$+Y]!==X[J*$+Y])return!1;return!0}}function zM1(Z,J){for(let Y=0,Q=J.length;Y<Q;Y++){let K=J[Y];K=Math.imul(K,1540483477)>>>0,K=(K^K>>24)>>>0,K=Math.imul(K,1540483477)>>>0,Z=Math.imul(Z,1540483477)>>>0,Z=(Z^K)>>>0}return Z}function VM1(Z,J,X,$,Y=dJ){let Q=J-1,W=X.hash($)&Q;for(let G=0;G<=Q;G++){let z=Z[W];if(z===Y||X.equal(z,$))return W;W=W+G+1&Q}throw new Error("Hash table full.")}function dG(Z,J,X){let $=w6.fromGraph(Z.getGraph());if(!J||!X)[J,X]=vM1(Z);let Y=Z.getIndices(),Q=Y?Y.getArray():null,K=u$(Z,j6.RENDER),W=$.createAccessor(),G=K,z=_O(G,X);for(let H=0;H<G;H++)z[H]=J[Q?Q[H]:H];Z.setIndices(W.setArray(z));let V=mc(Z);for(let H of Z.listAttributes()){let v=RZ($,H);TO(H,Y,J,v,X),Z.swap(H,v)}for(let H of Z.listTargets())for(let v of H.listAttributes()){let q=RZ($,v);TO(v,Y,J,q,X),H.swap(v,q)}if(Y&&Y.listParents().length===1)Y.dispose();for(let H of V)if(H.listParents().length===1)H.dispose();return Z}function TO(Z,J,X,$,Y){let Q=Z.getElementSize(),K=Z.getArray(),W=J?J.getArray():null,G=J?J.getCount():Z.getCount(),z=new K.constructor(Y*Q),V=new Uint8Array(Y);for(let H=0;H<G;H++){let v=W?W[H]:H,q=X[v];if(V[q])continue;for(let F=0;F<Q;F++)z[q*Q+F]=K[v*Q+F];V[q]=1}return $.setArray(z)}function vM1(Z){let J=u$(Z,j6.UPLOAD),X=Z.getIndices(),$=X?X.getArray():null;if(!X||!$)return[ZM1(J,1e6),J];let Y=new Uint32Array(J).fill(dJ),Q=0;for(let K=0;K<$.length;K++){let W=$[K];if(Y[W]===dJ)Y[W]=Q++}return[Y,Q]}function HM1(){var Z=new R3(9);if(R3!=Float32Array)Z[1]=0,Z[2]=0,Z[3]=0,Z[5]=0,Z[6]=0,Z[7]=0;return Z[0]=1,Z[4]=1,Z[8]=1,Z}function qM1(Z,J){return Z[0]=J[0],Z[1]=J[1],Z[2]=J[2],Z[3]=J[4],Z[4]=J[5],Z[5]=J[6],Z[6]=J[8],Z[7]=J[9],Z[8]=J[10],Z}function FM1(Z,J){if(Z===J){var X=J[1],$=J[2],Y=J[5];Z[1]=J[3],Z[2]=J[6],Z[3]=X,Z[5]=J[7],Z[6]=$,Z[7]=Y}else Z[0]=J[0],Z[1]=J[3],Z[2]=J[6],Z[3]=J[1],Z[4]=J[4],Z[5]=J[7],Z[6]=J[2],Z[7]=J[5],Z[8]=J[8];return Z}function cM1(Z,J){var X=J[0],$=J[1],Y=J[2],Q=J[3],K=J[4],W=J[5],G=J[6],z=J[7],V=J[8],H=V*K-W*z,v=-V*Q+W*G,q=z*Q-K*G,F=X*H+$*v+Y*q;if(!F)return null;return F=1/F,Z[0]=H*F,Z[1]=(-V*$+Y*z)*F,Z[2]=(W*$-Y*K)*F,Z[3]=v*F,Z[4]=(V*X-Y*G)*F,Z[5]=(-W*X+Y*Q)*F,Z[6]=q*F,Z[7]=(-z*X+$*G)*F,Z[8]=(K*X-$*Q)*F,Z}function uc(){var Z=new R3(3);if(R3!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0;return Z}function wM1(Z,J,X){return Z[0]=J[0]*X[0],Z[1]=J[1]*X[1],Z[2]=J[2]*X[2],Z}function Cs(Z,J){var X=J[0],$=J[1],Y=J[2],Q=X*X+$*$+Y*Y;if(Q>0)Q=1/Math.sqrt(Q);return Z[0]=J[0]*Q,Z[1]=J[1]*Q,Z[2]=J[2]*Q,Z}function xM1(Z,J,X){var $=J[0],Y=J[1],Q=J[2],K=X[3]*$+X[7]*Y+X[11]*Q+X[15];return K=K||1,Z[0]=(X[0]*$+X[4]*Y+X[8]*Q+X[12])/K,Z[1]=(X[1]*$+X[5]*Y+X[9]*Q+X[13])/K,Z[2]=(X[2]*$+X[6]*Y+X[10]*Q+X[14])/K,Z}function UM1(Z,J,X){var $=J[0],Y=J[1],Q=J[2];return Z[0]=$*X[0]+Y*X[3]+Q*X[6],Z[1]=$*X[1]+Y*X[4]+Q*X[7],Z[2]=$*X[2]+Y*X[5]+Q*X[8],Z}var jM1=wM1;(function(){var Z=uc();return function(J,X,$,Y,Q,K){var W,G;if(!X)X=3;if(!$)$=0;if(Y)G=Math.min(Y*X+$,J.length);else G=J.length;for(W=$;W<G;W+=X)Z[0]=J[W],Z[1]=J[W+1],Z[2]=J[W+2],Q(Z,Z,K),J[W]=Z[0],J[W+1]=Z[1],J[W+2]=Z[2];return J}})();var CO="weld",bc={overwrite:!0};function bO(Z=bc){let J=OZ(bc,Z);return l$(CO,async(X)=>{let $=X.getLogger();for(let Y of X.getRoot().listMeshes()){for(let Q of Y.listPrimitives())if(lc(Q,J),u$(Q,j6.RENDER)===0)Ms(Q);if(Y.listPrimitives().length===0)Y.dispose()}$.debug(`${CO}: Complete.`)})}function lc(Z,J=bc){let X=Z.getGraph(),Y=w6.fromGraph(X).getLogger(),Q=M3({},bc,J);if(Z.getIndices()&&!Q.overwrite)return;if(Z.getMode()===g1.Mode.POINTS)return;let K=Z.getAttribute("POSITION").getCount(),W=Z.getIndices(),G=W==null?void 0:W.getArray(),z=W?W.getCount():K,V=new Ts(Z),H=JM1(K+K/4),v=new Uint32Array(H).fill(dJ),q=new Uint32Array(K).fill(dJ),F=0;for(let c=0;c<z;c++){let w=G?G[c]:c;if(q[w]!==dJ)continue;let x=VM1(v,H,V,w,dJ),j=v[x];if(j===dJ)v[x]=w,q[w]=F++;else q[w]=q[j]}Y.debug(`${CO}: ${Ac(K,F)} vertices.`),dG(Z,q,F)}var{FLOAT:BM1}=K0.ComponentType;function fs(Z,J){let X=Z.getAttribute("POSITION");if(X)Ks(J,X);let $=Z.getAttribute("NORMAL");if($)Ws(J,$);let Y=Z.getAttribute("TANGENT");if(Y)Gs(J,Y);for(let Q of Z.listTargets()){let K=Q.getAttribute("POSITION");if(K)Ks(J,K);let W=Q.getAttribute("NORMAL");if(W)Ws(J,W);let G=Q.getAttribute("TANGENT");if(G)Gs(J,G)}if(KM1(J)<0)LM1(Z)}function Ks(Z,J){let X=J.getComponentType(),$=J.getNormalized(),Y=J.getArray(),Q=X===BM1?Y:new Float32Array(Y.length),K=uc();for(let W=0,G=J.getCount();W<G;W++){if($)K[0]=I0.decodeNormalizedInt(Y[W*3],X),K[1]=I0.decodeNormalizedInt(Y[W*3+1],X),K[2]=I0.decodeNormalizedInt(Y[W*3+2],X);else K[0]=Y[W*3],K[1]=Y[W*3+1],K[2]=Y[W*3+2];xM1(K,K,Z),Q[W*3]=K[0],Q[W*3+1]=K[1],Q[W*3+2]=K[2]}J.setArray(Q).setNormalized(!1)}function Ws(Z,J){let X=J.getArray(),$=J.getNormalized(),Y=J.getComponentType(),Q=HM1();qM1(Q,Z),cM1(Q,Q),FM1(Q,Q);let K=uc();for(let W=0,G=J.getCount();W<G;W++){if($)K[0]=I0.decodeNormalizedInt(X[W*3],Y),K[1]=I0.decodeNormalizedInt(X[W*3+1],Y),K[2]=I0.decodeNormalizedInt(X[W*3+2],Y);else K[0]=X[W*3],K[1]=X[W*3+1],K[2]=X[W*3+2];if(UM1(K,K,Q),Cs(K,K),$)X[W*3]=I0.decodeNormalizedInt(K[0],Y),X[W*3+1]=I0.decodeNormalizedInt(K[1],Y),X[W*3+2]=I0.decodeNormalizedInt(K[2],Y);else X[W*3]=K[0],X[W*3+1]=K[1],X[W*3+2]=K[2]}}function Gs(Z,J){let X=J.getArray(),$=J.getNormalized(),Y=J.getComponentType(),Q=uc();for(let K=0,W=J.getCount();K<W;K++){if($)Q[0]=I0.decodeNormalizedInt(X[K*4],Y),Q[1]=I0.decodeNormalizedInt(X[K*4+1],Y),Q[2]=I0.decodeNormalizedInt(X[K*4+2],Y);else Q[0]=X[K*4],Q[1]=X[K*4+1],Q[2]=X[K*4+2];if(Q[0]=Z[0]*Q[0]+Z[4]*Q[1]+Z[8]*Q[2],Q[1]=Z[1]*Q[0]+Z[5]*Q[1]+Z[9]*Q[2],Q[2]=Z[2]*Q[0]+Z[6]*Q[1]+Z[10]*Q[2],Cs(Q,Q),$)X[K*4]=I0.decodeNormalizedInt(Q[0],Y),X[K*4+1]=I0.decodeNormalizedInt(Q[1],Y),X[K*4+2]=I0.decodeNormalizedInt(Q[2],Y);else X[K*4]=Q[0],X[K*4+1]=Q[1],X[K*4+2]=Q[2]}}function LM1(Z){if(Z.getMode()!==g1.Mode.TRIANGLES)return;if(!Z.getIndices())lc(Z);let J=Z.getIndices();for(let X=0,$=J.getCount();X<$;X+=3){let Y=J.getScalar(X),Q=J.getScalar(X+2);J.setScalar(X,Q),J.setScalar(X+2,Y)}}function DM1(Z,J){for(let X of Z.listPrimitives()){let $=MM1(X,Z);if(X!==$)Z.removePrimitive(X).addPrimitive($)}for(let X of Z.listPrimitives())dG(X),fs(X,J)}function MM1(Z,J){if(Z.listParents().some(($)=>$ instanceof NG&&$!==J))Z=Z.clone();for(let $ of Z.listTargets())if($.listParents().some((Q)=>Q instanceof g1&&Q!==Z))Z.removeTarget($).addTarget($.clone());return Z}var zs=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function ks(Z){let J=Z.getMesh(),X=Z.getMatrix();if(J&&!I0.eq(X,zs))DM1(J,X);for(let $ of Z.listChildren()){let Y=$.getMatrix();Ps(Y,Y,X),$.setMatrix(Y)}return Z.setMatrix(zs)}var{LINES:RM1,LINE_STRIP:OM1,LINE_LOOP:NM1,TRIANGLES:PM1,TRIANGLE_STRIP:TM1,TRIANGLE_FAN:CM1}=g1.Mode;function fM1(Z){let J=Z.getGraph(),X=w6.fromGraph(J);if(!Z.getIndices())lc(Z);let $=Z.getIndices(),Y=$.getArray(),Q=Ds(Z),W=new AJ[$.getComponentType()](Q*2),G=Z.getMode();if(G===OM1)for(let V=0;V<Q;V++)W[V*2]=Y[V],W[V*2+1]=Y[V+1];else if(G===NM1)for(let V=0;V<Q;V++)if(V<Q-1)W[V*2]=Y[V],W[V*2+1]=Y[V+1];else W[V*2]=Y[V],W[V*2+1]=Y[0];else throw new Error("Only LINE_STRIP and LINE_LOOP may be converted to LINES.");Z.setMode(RM1);let z=X.getRoot();if($.listParents().some((V)=>V!==z&&V!==Z))Z.setIndices(RZ(X,$).setArray(W));else $.setArray(W)}function Es(Z){let J=Z.getGraph(),X=w6.fromGraph(J);if(!Z.getIndices())lc(Z);let $=Z.getIndices(),Y=$.getArray(),Q=Ds(Z),W=new AJ[$.getComponentType()](Q*3),G=Z.getMode();if(G===TM1)for(let V=0,H=Y.length;V<H-2;V++)if(V%2)W[V*3]=Y[V+1],W[V*3+1]=Y[V],W[V*3+2]=Y[V+2];else W[V*3]=Y[V],W[V*3+1]=Y[V+1],W[V*3+2]=Y[V+2];else if(G===CM1)for(let V=0;V<Q;V++)W[V*3]=Y[0],W[V*3+1]=Y[V+1],W[V*3+2]=Y[V+2];else throw new Error("Only TRIANGLE_STRIP and TRIANGLE_FAN may be converted to TRIANGLES.");Z.setMode(PM1);let z=X.getRoot();if($.listParents().some((V)=>V!==z&&V!==Z))Z.setIndices(RZ(X,$).setArray(W));else $.setArray(W)}var YP6={keepUniqueNames:!1,propertyTypes:[g.ACCESSOR,g.MESH,g.TEXTURE,g.MATERIAL,g.SKIN]};var Vs="dequantize",hc={pattern:/^((?!JOINTS_).)*$/};function Is(Z=hc){let J=OZ(hc,Z);return l$(Vs,(X)=>{let $=X.getLogger();for(let Y of X.getRoot().listMeshes())for(let Q of Y.listPrimitives())kM1(Q,J);X.createExtension(iG).dispose(),$.debug(`${Vs}: Complete.`)})}function kM1(Z,J=hc){let X=OZ(hc,J);for(let $ of Z.listSemantics())if(X.pattern.test($))fO(Z.getAttribute($));for(let $ of Z.listTargets())for(let Y of $.listSemantics())if(X.pattern.test(Y))fO($.getAttribute(Y))}function fO(Z){let J=Z.getArray();if(!J)return;let X=Sc(J,Z.getComponentType(),Z.getNormalized());Z.setArray(X).setNormalized(!1)}function Sc(Z,J,X){let $=new Float32Array(Z.length);for(let Y=0,Q=Z.length;Y<Q;Y++)if(X)$[Y]=I0.decodeNormalizedInt(Z[Y],J);else $[Y]=Z[Y];return $}var{TEXTURE_INFO:_s,ROOT:QP6}=g;function bs(Z){let J=new w6().setLogger(Z.getLogger()),X=hO(J,Z);return EM1(J,Z,X),J.getRoot().copy(Z.getRoot(),X),J}function EM1(Z,J,X){X||(X=hO(Z,J));for(let $ of J.getRoot().listExtensionsUsed()){let Y=Z.createExtension($.constructor);if($.isRequired())Y.setRequired(!0)}return IM1(Z,J,_M1(J),X)}function IM1(Z,J,X,$){$||($=hO(Z,J));let Y=new Map;for(let Q of X)if(!Y.has(Q)&&Q.propertyType!==_s)Y.set(Q,$(Q));for(let[Q,K]of Y.entries())K.copy(Q,$);return Y}function hO(Z,J){let X=new Map([[J.getRoot(),Z.getRoot()]]);return($)=>{if($.propertyType===_s)return $;let Y=X.get($);if(!Y)Y=new $.constructor(Z.getGraph()),X.set($,Y);return Y}}function _M1(Z){let J=new Set;for(let X of Z.getGraph().listEdges())J.add(X.getChild());return Array.from(J)}function hs(){var Z=new R3(4);if(R3!=Float32Array)Z[0]=0,Z[1]=0,Z[2]=0,Z[3]=0;return Z}function bM1(Z,J,X){return Z[0]=J[0]+X[0],Z[1]=J[1]+X[1],Z[2]=J[2]+X[2],Z[3]=J[3]+X[3],Z}function hM1(Z,J,X){return Z[0]=J[0]-X[0],Z[1]=J[1]-X[1],Z[2]=J[2]-X[2],Z[3]=J[3]-X[3],Z}function SM1(Z,J,X){return Z[0]=J[0]*X[0],Z[1]=J[1]*X[1],Z[2]=J[2]*X[2],Z[3]=J[3]*X[3],Z}function AM1(Z,J,X){return Z[0]=J[0]*X,Z[1]=J[1]*X,Z[2]=J[2]*X,Z[3]=J[3]*X,Z}function mM1(Z){var J=Z[0],X=Z[1],$=Z[2],Y=Z[3];return Math.hypot(J,X,$,Y)}var Ss=hM1,uM1=SM1,As=mM1;(function(){var Z=hs();return function(J,X,$,Y,Q,K){var W,G;if(!X)X=4;if(!$)$=0;if(Y)G=Math.min(Y*X+$,J.length);else G=J.length;for(W=$;W<G;W+=X)Z[0]=J[W],Z[1]=J[W+1],Z[2]=J[W+2],Z[3]=J[W+3],Q(Z,Z,K),J[W]=Z[0],J[W+1]=Z[1],J[W+2]=Z[2],J[W+3]=Z[3];return J}})();var lM1=/color|emissive|diffuse/i;function yM1(Z){return Z.getGraph().listParentEdges(Z).some((Y)=>{return Y.getAttributes().isColor||lM1.test(Y.getName())})?"srgb":null}function pM1(Z){let J=Z.getGraph(),X=new Set,$=new Set;function Y(Q){let K=new Set;for(let W of J.listChildEdges(Q))if(W.getChild()instanceof b$)K.add(W.getName()+"Info");for(let W of J.listChildEdges(Q)){let G=W.getChild();if(X.has(G))continue;if(X.add(G),G instanceof F1&&K.has(W.getName()))$.add(G);else if(G instanceof N1)Y(G)}}return Y(Z),Array.from($)}function iM1(Z){let X=w6.fromGraph(Z.getGraph()).getRoot(),$=Z.getGraph().listParentEdges(Z).filter((Y)=>Y.getParent()!==X).map((Y)=>Y.getName());return Array.from(new Set($))}var D3="prune",kO=0.011764705882352941,vs={propertyTypes:[g.NODE,g.SKIN,g.MESH,g.CAMERA,g.PRIMITIVE,g.PRIMITIVE_TARGET,g.ANIMATION,g.MATERIAL,g.TEXTURE,g.ACCESSOR,g.BUFFER],keepLeaves:!1,keepAttributes:!1,keepIndices:!1,keepSolidTextures:!1,keepExtras:!1};function ms(Z=vs){let J=OZ(vs,Z),X=new Set(J.propertyTypes),$=J.keepExtras;return l$(D3,async(Y)=>{let Q=Y.getLogger(),K=Y.getRoot(),W=Y.getGraph(),G=new us,z=(V)=>G.dispose(V.target);if(W.addEventListener("node:dispose",z),X.has(g.MESH))for(let V of K.listMeshes()){if(V.listPrimitives().length>0)continue;V.dispose()}if(X.has(g.NODE)){if(!J.keepLeaves)for(let V of K.listScenes())ls(W,V,$);for(let V of K.listNodes())D4(V,$)}if(X.has(g.SKIN))for(let V of K.listSkins())D4(V,$);if(X.has(g.MESH))for(let V of K.listMeshes())D4(V,$);if(X.has(g.CAMERA))for(let V of K.listCameras())D4(V,$);if(X.has(g.PRIMITIVE))Hs(W,g.PRIMITIVE,$);if(X.has(g.PRIMITIVE_TARGET))Hs(W,g.PRIMITIVE_TARGET,$);if(!J.keepAttributes&&X.has(g.ACCESSOR)){let V=new Map;for(let H of K.listMeshes())for(let v of H.listPrimitives()){let q=v.getMaterial();if(!q)continue;let F=ys(Y,v,q),c=gM1(v,F);qs(v,c),v.listTargets().forEach((w)=>qs(w,c)),V.has(q)?V.get(q).add(v):V.set(q,new Set([v]))}for(let[H,v]of V)dM1(H,Array.from(v))}if(X.has(g.ANIMATION))for(let V of K.listAnimations()){for(let H of V.listChannels())if(!H.getTargetNode())H.dispose();if(!V.listChannels().length){let H=V.listSamplers();D4(V,$),H.forEach((v)=>D4(v,$))}else V.listSamplers().forEach((H)=>D4(H,$))}if(X.has(g.MATERIAL))K.listMaterials().forEach((V)=>D4(V,$));if(X.has(g.TEXTURE)){if(K.listTextures().forEach((V)=>D4(V,$)),!J.keepSolidTextures)await aM1(Y)}if(X.has(g.ACCESSOR))K.listAccessors().forEach((V)=>D4(V,$));if(X.has(g.BUFFER))K.listBuffers().forEach((V)=>D4(V,$));if(W.removeEventListener("node:dispose",z),!G.empty()){let V=G.entries().map(([H,v])=>`${H} (${v})`).join(", ");Q.info(`${D3}: Removed types... ${V}`)}else Q.debug(`${D3}: No unused properties found.`);Q.debug(`${D3}: Complete.`)})}class us{constructor(){this.disposed={}}empty(){for(let Z in this.disposed)return!1;return!0}entries(){return Object.entries(this.disposed)}dispose(Z){this.disposed[Z.propertyType]=this.disposed[Z.propertyType]||0,this.disposed[Z.propertyType]++}}function D4(Z,J){let X=Z.listParents().filter((Y)=>!(Y instanceof W3||Y instanceof KZ)),$=J&&!Rs(Z.getExtras());if(!X.length&&!$)Z.dispose()}function Hs(Z,J,X){for(let $ of Z.listEdges()){let Y=$.getParent();if(Y.propertyType===J)D4(Y,X)}}function ls(Z,J,X){if(J.listChildren().forEach((K)=>ls(Z,K,X)),J instanceof K3)return;let $=Z.listParentEdges(J).some((K)=>{let W=K.getParent().propertyType;return W!==g.ROOT&&W!==g.SCENE&&W!==g.NODE}),Y=Z.listChildren(J).length===0,Q=X&&!Rs(J.getExtras());if(Y&&!$&&!Q)J.dispose()}function qs(Z,J){for(let X of J)Z.setAttribute(X,null)}function gM1(Z,J){let X=[];for(let $ of Z.listSemantics())if($==="NORMAL"&&!J.has($))X.push($);else if($==="TANGENT"&&!J.has($))X.push($);else if($.startsWith("TEXCOORD_")&&!J.has($))X.push($);else if($.startsWith("COLOR_")&&$!=="COLOR_0")X.push($);return X}function ys(Z,J,X,$=new Set){let Q=Z.getGraph().listChildEdges(X),K=new Set;for(let z of Q)if(z.getChild()instanceof b$)K.add(z.getName());for(let z of Q){let V=z.getName(),H=z.getChild();if(H instanceof F1){if(K.has(V.replace(/Info$/,"")))$.add(`TEXCOORD_${H.getTexCoord()}`)}if(H instanceof b$&&V.match(/normalTexture/i))$.add("TANGENT");if(H instanceof N1)ys(Z,J,H,$)}let W=X instanceof Q7&&!X.getExtension("KHR_materials_unlit"),G=J.getMode()===g1.Mode.POINTS;if(W&&!G)$.add("NORMAL");return $}function dM1(Z,J){let X=pM1(Z),$=new Set(X.map((G)=>G.getTexCoord())),Y=Array.from($).sort(),Q=new Map(Y.map((G,z)=>[G,z])),K=new Map(Y.map((G,z)=>[`TEXCOORD_${G}`,`TEXCOORD_${z}`]));for(let G of X){let z=G.getTexCoord();G.setTexCoord(Q.get(z))}for(let G of J){let z=G.listSemantics().filter((V)=>V.startsWith("TEXCOORD_")).sort();W(G,z),G.listTargets().forEach((V)=>W(V,z))}function W(G,z){for(let V of z){let H=G.getAttribute(V);if(!H)continue;let v=K.get(V);if(v===V)continue;G.setAttribute(v,H),G.setAttribute(V,null)}}}async function aM1(Z){let J=Z.getRoot(),X=Z.getGraph(),$=Z.getLogger(),Q=J.listTextures().map(async(K)=>{var W;let G=await sM1(K);if(!G)return;if(yM1(K)==="srgb")vR.convertSRGBToLinear(G,G);let z=K.getName()||K.getURI(),V=(W=K.getSize())==null?void 0:W.join("x"),H=iM1(K);for(let v of X.listParentEdges(K)){let q=v.getParent();if(q!==J&&nM1(q,G,v.getName(),$))v.dispose()}if(K.listParents().length===1)K.dispose(),$.debug(`${D3}: Removed solid-color texture "${z}" (${V}px ${H.join(", ")})`)});await Promise.all(Q)}function nM1(Z,J,X,$){if(Z instanceof Q7)switch(X){case"baseColorTexture":return Z.setBaseColorFactor(uM1(J,J,Z.getBaseColorFactor())),!0;case"emissiveTexture":return Z.setEmissiveFactor(jM1([0,0,0],J.slice(0,3),Z.getEmissiveFactor())),!0;case"occlusionTexture":return Math.abs(J[0]-1)<=kO;case"metallicRoughnessTexture":return Z.setRoughnessFactor(J[1]*Z.getRoughnessFactor()),Z.setMetallicFactor(J[2]*Z.getMetallicFactor()),!0;case"normalTexture":return As(Ss(hs(),J,[0.5,0.5,1,1]))<=kO}return $.warn(`${D3}: Detected single-color ${X} texture. Pruning ${X} not yet supported.`),!1}async function sM1(Z){let J=await oM1(Z);if(!J)return null;let X=[1/0,1/0,1/0,1/0],$=[-1/0,-1/0,-1/0,-1/0],Y=[0,0,0,0],[Q,K]=J.shape;for(let W=0;W<Q;W++){for(let G=0;G<K;G++)for(let z=0;z<4;z++)X[z]=Math.min(X[z],J.get(W,G,z)),$[z]=Math.max($[z],J.get(W,G,z));if(As(Ss(Y,$,X))/255>kO)return null}return AM1(Y,bM1(Y,$,X),0.00196078431372549)}async function oM1(Z){try{return await In(Z.getImage(),Z.getMimeType())}catch(J){return null}}var RO="flatten",Fs={cleanup:!0};function ps(Z=Fs){let J=OZ(Fs,Z);return l$(RO,async(X)=>{let $=X.getRoot(),Y=X.getLogger(),Q=new Set;for(let z of $.listSkins())for(let V of z.listJoints())Q.add(V);let K=new Set;for(let z of $.listAnimations())for(let V of z.listChannels()){let H=V.getTargetNode();if(H&&V.getTargetPath()!=="weights")K.add(H)}let W=new Set,G=new Set;for(let z of $.listScenes())z.traverse((V)=>{let H=V.getParentNode();if(!H)return;if(Q.has(H)||W.has(H))W.add(V);if(K.has(H)||G.has(H))G.add(V)});for(let z of $.listScenes())z.traverse((V)=>{if(K.has(V))return;if(W.has(V))return;if(G.has(V))return;YM1(V)});if(K.size)Y.debug(`${RO}: Flattening node hierarchies with TRS animation not yet supported.`);if(J.cleanup)await X.transform(ms({propertyTypes:[g.NODE],keepLeaves:!1}));Y.debug(`${RO}: Complete.`)})}function is(Z){return OG(Z)}var rM1={skipValidation:!1},cs=4294967295,{LINE_STRIP:tM1,LINE_LOOP:eM1,TRIANGLE_STRIP:ZR1,TRIANGLE_FAN:JR1}=g1.Mode;function XR1(Z,J={}){let X=OZ(rM1,J),$=Z[0],Y=w6.fromGraph($.getGraph());if(!X.skipValidation&&new Set(Z.map(Os)).size>1)throw new Error("Requires >=2 Primitives, sharing the same Material and Mode, with compatible vertex attributes and indices.");for(let q of Z)switch(q.getMode()){case tM1:case eM1:fM1(q);break;case ZR1:case JR1:Es(q);break}let Q=[],K=new Uint32Array(Z.length),W=0,G=0;for(let q=0;q<Z.length;q++){let F=Z[q],c=F.getIndices(),w=F.getAttribute("POSITION").getCount(),x=c?c.getArray():null,j=c?c.getCount():w,B=new Uint32Array(w).fill(cs);for(let L=0;L<j;L++){let R=x?x[L]:L;if(B[R]===cs)B[R]=W++,K[q]++}Q.push(B),G+=j}let z=Y.createPrimitive().setMode($.getMode()).setMaterial($.getMaterial());for(let q of $.listSemantics()){let F=$.getAttribute(q),c=AJ[F.getComponentType()],w=RZ(Y,F).setArray(new c(W*F.getElementSize()));z.setAttribute(q,w)}let V=$.getIndices(),H=V?RZ(Y,V).setArray(_O(G,W)):null;z.setIndices(H);let v=0;for(let q=0;q<Q.length;q++){let F=Z[q],c=F.getIndices(),w=c?c.getCount():-1,x=Q[q];if(c&&H)YR1(c,x,H,v),v+=w;for(let j of z.listSemantics()){let B=F.getAttribute(j),L=z.getAttribute(j);$R1(B,c,x,L)}}return z}function $R1(Z,J,X,$){let Y=Z.getElementSize(),Q=J?J.getArray():null,K=Z.getCount(),W=Z.getArray(),G=$.getArray(),z=new Uint8Array(Z.getCount());for(let V=0,H=J?J.getCount():K;V<H;V++){let v=Q?Q[V]:V,q=X[v];if(z[q])continue;for(let F=0;F<Y;F++)G[q*Y+F]=W[v*Y+F];z[q]=1}}function YR1(Z,J,X,$){let Y=Z.getCount(),Q=Z.getArray(),K=X.getArray();for(let W=0;W<Y;W++){let G=Q[W],z=J[G];K[$+W]=z}}var EO="join",{ROOT:QR1,NODE:KR1,MESH:WR1,PRIMITIVE:GR1,ACCESSOR:zR1}=g,OO=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],ws={keepMeshes:!1,keepNamed:!1,cleanup:!0,filter:()=>!0};function gs(Z=ws){let J=OZ(ws,Z);return l$(EO,async(X)=>{let $=X.getRoot(),Y=X.getLogger();for(let Q of $.listScenes())xs(X,Q,J),Q.traverse((K)=>xs(X,K,J));if(J.cleanup)await X.transform(ms({propertyTypes:[KR1,WR1,GR1,zR1],keepAttributes:!0,keepIndices:!0,keepLeaves:!1}));Y.debug(`${EO}: Complete.`)})}function xs(Z,J,X){let $=Z.getLogger(),Y={},Q=J.listChildren();for(let G=0;G<Q.length;G++){let z=Q[G];if(!X.filter(z))continue;if(z.listParents().some((v)=>v instanceof KZ))continue;let H=z.getMesh();if(!H)continue;if(z.getExtension("EXT_mesh_gpu_instancing"))continue;if(z.getSkin())continue;for(let v of H.listPrimitives()){if(v.listTargets().length>0)continue;let q=v.getMaterial();if(q&&q.getExtension("KHR_materials_volume"))continue;dG(v),vR1(v);let F=Os(v),c=H.getName()||z.getName();if(X.keepMeshes||X.keepNamed&&c)F+=`|${G}`;if(!(F in Y))Y[F]={prims:[],primMeshes:[],primNodes:[],dstNode:z,dstMesh:void 0};let w=Y[F];w.prims.push(v),w.primNodes.push(z)}}let K=Object.values(Y).filter(({prims:G})=>G.length>1),W=new Set(K.flatMap((G)=>G.primNodes));for(let G of W){let z=G.getMesh();if(z.listParents().some((H)=>{return H.propertyType!==QR1&&G!==H}))G.setMesh(z.clone())}for(let G of K){let{dstNode:z,primNodes:V}=G;G.dstMesh=z.getMesh(),G.primMeshes=V.map((H)=>H.getMesh())}for(let G of K){let{prims:z,primNodes:V,primMeshes:H,dstNode:v,dstMesh:q}=G,F=v.getMatrix();for(let x=0;x<z.length;x++){let j=V[x],B=H[x],L=z[x];if(B.removePrimitive(L),PO(L))L=z[x]=VR1(z[x]);if(j!==v)Ps(OO,QM1(OO,F),j.getMatrix()),fs(L,OO)}let c=XR1(z),w=c.listAttributes()[0].getCount();q.addPrimitive(c),$.debug(`${EO}: Joined Primitives (${z.length}) containing ${NO(w)} vertices under Node "${v.getName()}".`)}}function VR1(Z){let J=Z.clone();for(let $ of J.listSemantics())J.setAttribute($,J.getAttribute($).clone());let X=J.getIndices();if(X)J.setIndices(X.clone());return J}function vR1(Z){for(let J of["POSITION","NORMAL","TANGENT"]){let X=Z.getAttribute(J);if(X)fO(X)}}var{TRANSLATION:KP6,ROTATION:WP6,SCALE:GP6,WEIGHTS:zP6}=KZ.TargetPath;var HR1={pattern:/.*/,quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeWeight:8,quantizeGeneric:12,normalizeWeights:!0,cleanup:!0};var VP6=M3({level:"high"},HR1);var qR1="unweld";function FR1(Z,J=new Map){let X=Z.getIndices();if(!X)return;let $=Z.getGraph(),Y=w6.fromGraph($),Q=Y.getLogger(),K=Z.getAttribute("POSITION").getCount();for(let G of Z.listAttributes())if(Z.swap(G,Us(Y,G,X,J)),G.listParents().length===1)G.dispose();for(let G of Z.listTargets())for(let z of G.listAttributes())if(G.swap(z,Us(Y,z,X,J)),z.listParents().length===1)z.dispose();let W=Z.getAttribute("POSITION").getCount();if(Q.debug(`${qR1}: ${Ac(K,W)} vertices.`),Z.setIndices(null),X.listParents().length===1)X.dispose()}function Us(Z,J,X,$){if($.has(J)&&$.get(J).has(X))return $.get(J).get(X);let Y=J.getArray(),K=new Y.constructor(X.getCount()*J.getElementSize()),W=X.getArray(),G=J.getElementSize();for(let V=0,H=X.getCount();V<H;V++)for(let v=0;v<G;v++)K[V*G+v]=Y[W[V]*G+v];if(!$.has(J))$.set(J,new Map);let z=RZ(Z,J).setArray(K);return $.get(J).set(X,z),z}var js;(function(Z){Z[Z.STEP=0]="STEP",Z[Z.LERP=1]="LERP",Z[Z.SLERP=2]="SLERP"})(js||(js={}));var cR1=0.000001;function wR1(Z,J,X,$=0.0001){let Y=J.length/Z.length,Q=new Array(Y).fill(0),K=new Array(Y).fill(0),W=new Array(Y).fill(0),G=new Array(Y).fill(0),z=Z.length-1,V=1;for(let H=1;H<z;++H){let v=Z[V-1],q=Z[H],F=Z[H+1],c=(q-v)/(F-v),w=!1;if(q!==F&&(H!==1||q!==Z[0])){if(gG(J,V-1,G),gG(J,H,K),gG(J,H+1,W),X==="slerp"){let x=jR1(Q,G,W,c),j=Ls(G,K)+Ls(K,W);w=!_c(K,x,$)||j+Number.EPSILON>=Math.PI}else if(X==="lerp"){let x=UR1(Q,G,W,c);w=!_c(K,x,$)}else if(X==="step")w=!_c(K,G)||!_c(K,W)}if(w){if(H!==V)Z[V]=Z[H],Bs(J,V,gG(J,H,Q));V++}}if(z>0)Z[V]=Z[z],Bs(J,V,gG(J,z,Q)),V++;return V}function gG(Z,J,X){for(let $=0,Y=X.length;$<Y;$++)X[$]=Z[J*Y+$];return X}function Bs(Z,J,X){for(let $=0,Y=X.length;$<Y;$++)Z[J*Y+$]=X[$]}function _c(Z,J,X=0){if(Z.length!==J.length)return!1;for(let $=0;$<Z.length;$++)if(Math.abs(Z[$]-J[$])>X)return!1;return!0}function xR1(Z,J,X){return Z*(1-X)+J*X}function UR1(Z,J,X,$){for(let Y=0;Y<J.length;Y++)Z[Y]=xR1(J[Y],X[Y],$);return Z}function jR1(Z,J,X,$){let Y=J[0],Q=J[1],K=J[2],W=J[3],G=X[0],z=X[1],V=X[2],H=X[3],v,q,F,c,w;if(q=Y*G+Q*z+K*V+W*H,q<0)q=-q,G=-G,z=-z,V=-V,H=-H;if(1-q>cR1)v=Math.acos(q),F=Math.sin(v),c=Math.sin((1-$)*v)/F,w=Math.sin($*v)/F;else c=1-$,w=$;return Z[0]=c*Y+w*G,Z[1]=c*Q+w*z,Z[2]=c*K+w*V,Z[3]=c*W+w*H,Z}function Ls(Z,J){let X=BR1(Z,J);return Math.acos(2*X*X-1)}function BR1(Z,J){return Z[0]*J[0]+Z[1]*J[1]+Z[2]*J[2]+Z[3]*J[3]}var vP6=new Float32Array(0),HP6={ready:Promise.resolve(),resample:wR1,tolerance:0.0001,cleanup:!0};var m$="simplify",{POINTS:ds,LINES:LR1,LINE_STRIP:DR1,LINE_LOOP:MR1,TRIANGLES:RR1,TRIANGLE_STRIP:as,TRIANGLE_FAN:ns}=g1.Mode,ss={ratio:0,error:0.0001,lockBorder:!1};function os(Z){let J=OZ(ss,Z),X=J.simplifier;if(!X)throw new Error(`${m$}: simplifier dependency required — install "meshoptimizer".`);return l$(m$,async($)=>{let Y=$.getLogger();await X.ready,await $.transform(bO({overwrite:!1}));let Q=0;for(let K of $.getRoot().listMeshes()){for(let W of K.listPrimitives()){let G=W.getMode();if(G!==RR1&&G!==as&&G!==ns&&G!==ds){Q++;continue}if(OR1(W,J),u$(W,j6.RENDER)===0)Ms(W)}if(K.listPrimitives().length===0)K.dispose()}if(Q>0)Y.warn(`${m$}: Skipped ${Q} primitives: Unsupported draw mode.`);Y.debug(`${m$}: Complete.`)})}function OR1(Z,J){let X=M3({},ss,J),$=X.simplifier,Y=Z.getGraph(),Q=w6.fromGraph(Y),K=Q.getLogger();switch(Z.getMode()){case ds:return NR1(Q,Z,X);case LR1:case DR1:case MR1:return K.warn(`${m$}: Skipping primitive simplification: Unsupported draw mode.`),Z;case as:case ns:Es(Z);break}let W=u$(Z,j6.UPLOAD),G=u$(Z,j6.RENDER);if(G<W/2)dG(Z);let z=Z.getAttribute("POSITION"),V=Z.getIndices(),H=z.getArray(),v=V.getArray();if(!(H instanceof Float32Array))H=Sc(H,z.getComponentType(),z.getNormalized());if(!(v instanceof Uint32Array))v=new Uint32Array(v);let q=Math.floor(X.ratio*G/3)*3,F=X.lockBorder?["LockBorder"]:[],[c,w]=$.simplify(v,H,3,q,X.error,F);if(Z.setIndices(RZ(Q,V).setArray(c)),V.listParents().length===1)V.dispose();dG(Z);let x=u$(Z,j6.UPLOAD);if(x<=65534)Z.getIndices().setArray(new Uint16Array(Z.getIndices().getArray()));return K.debug(`${m$}: ${Ac(W,x)} vertices, error: ${w.toFixed(4)}.`),Z}function NR1(Z,J,X){let $=X.simplifier,Y=Z.getLogger();if(J.getIndices())FR1(J);let K=J.getAttribute("POSITION"),W=J.getAttribute("COLOR_0"),G=K.getCount(),z=K.getArray(),V=W?W.getArray():void 0,H=W?W.getComponentSize():void 0;if(!(z instanceof Float32Array))z=Sc(z,K.getComponentType(),K.getNormalized());if(V&&!(V instanceof Float32Array))V=Sc(V,K.getComponentType(),K.getNormalized());let v=Math.floor(X.ratio*G),q=$.simplifyPoints(z,3,v,V,H),[F,c]=$.compactMesh(q);Y.debug(`${m$}: ${Ac(K.getCount(),c)} vertices.`);for(let w of mc(J)){let x=RZ(Z,w);if(TO(w,null,F,x,c),eD1(J,w,x),w.listParents().length===1)w.dispose()}return J}var IO;(function(Z){Z.LANCZOS3="lanczos3",Z.LANCZOS2="lanczos2"})(IO||(IO={}));var qP6={resizeFilter:IO.LANCZOS3,pattern:void 0,formats:void 0,slots:void 0,quality:void 0,effort:void 0,lossless:!1,nearLossless:!1,limitInputPixels:!0};var $o=t(Xo(),1);var NZ={OPTIMIZED_DIR:".optimized",CHECKSUM_EXT:".md5",DATA_SCHEMA_VERSION:1,DATA_EXT:".data.json",DIRECTORIES:[(()=>{try{return q5.dirname(i.resolve("@hytopia.com/assets"))}catch{return null}})(),q5.resolve(process.cwd(),"assets")].filter(Boolean),OPTIMIZER_RUNS:[{suffix:"",options:["--compress","false","--instance","false","--simplify","false"]},{suffix:"-named-nodes",options:["--compress","false","--instance","false","--simplify","false","--join","true","--join-named","false"]}]};class B6{static instance=new B6;optimize=!0;optimizeEveryStart=!1;_modelUriAnimationNames=new Map;_modelUriBoundingBoxes=new Map;_modelUriNodeNames=new Map;_modelUriTrimeshes=new Map;constructor(){}async preloadModels(){let Z=await this._getAbsoluteModelPaths();console.log(`ModelRegistry.preloadModels(): Preloading ${Z.length} models...`);let J=performance.now();for(let $ of Z){if(this.optimize)await this._resolveOptimizedModelPath($);await this._loadModelData($)}let X=performance.now();console.log(`ModelRegistry.preloadModels(): Preloaded ${Z.length} models in ${X-J}ms!`)}getAnimationNames(Z){let J=this._modelUriAnimationNames.get(Z);if(!J)p.fatalError(`ModelRegistry.getAnimationNames(): Model ${Z} not found!`);return J}getBoundingBox(Z){let J=this._modelUriBoundingBoxes.get(Z);if(!J)p.fatalError(`ModelRegistry.getBoundingBox(): Model ${Z} not found!`);return J}getDepth(Z){let J=this.getBoundingBox(Z);return J.max.z-J.min.z}getHeight(Z){let J=this.getBoundingBox(Z);return J.max.y-J.min.y}getNodeNames(Z){let J=this._modelUriNodeNames.get(Z);if(!J)p.fatalError(`ModelRegistry.getNodeNames(): Model ${Z} not found!`);return J}getTrimesh(Z,J=1){let X=this._modelUriTrimeshes.get(Z);if(!X){p.error(`ModelRegistry.getTrimesh(): Model ${Z} not found!`);return}let $=X.vertices;if(J!==1){$=new Float32Array($.length);for(let Y=0;Y<$.length;Y++)$[Y]=X.vertices[Y]*J}return{vertices:$,indices:X.indices}}getWidth(Z){let J=this.getBoundingBox(Z);return J.max.x-J.min.x}modelHasNode(Z,J){let X=this._modelUriNodeNames.get(Z);if(!X)p.fatalError(`ModelRegistry.modelHasNode(): Model ${Z} not found!`);return X.includes(J)}_absoluteModelPathToModelUri(Z){let J=q5.normalize(Z);for(let X of NZ.DIRECTORIES){let $=q5.normalize(X);if(J.startsWith($))return q5.relative($,J).replace(/\\/g,"/")}return q5.basename(J)}async _getAbsoluteModelPaths(){let Z=[];for(let J of NZ.DIRECTORIES){let X=q5.resolve(process.cwd(),J);if(!M4.existsSync(X))continue;let $=await mF("**/*.{gltf,glb}",{cwd:X,follow:!0});for(let Y of $)Z.push(q5.join(X,Y))}return Z}async _loadModelData(Z){let X=`${this._buildOptimizedModelPath(Z)}${NZ.DATA_EXT}`,$=this._absoluteModelPathToModelUri(Z),Y=this._calculateChecksum(Z),Q;if(M4.existsSync(X))try{let K=M4.readFileSync(X,"utf8"),W=JSON.parse(K);if(W?.schemaVersion!==NZ.DATA_SCHEMA_VERSION)throw new Error("ModelRegistry._loadModelData(): Schema version mismatch! Data will be regenerated..");if(W?.source?.sha256!==Y)throw new Error("ModelRegistry._loadModelData(): Checksum mismatch! Data will be regenerated..");Q=W}catch{}if(!Q){let K=await new wR().read(Z),W=is(K.getRoot().listScenes()[0]),G=K.getRoot().listNodes().map((H)=>H.getName()),z=K.getRoot().listAnimations().map((H)=>H.getName()),V=await this._buildTrimesh(K);Q={schemaVersion:NZ.DATA_SCHEMA_VERSION,source:{uri:$,sha256:Y},animationNames:z,boundingBox:{min:{x:W.min[0],y:W.min[1],z:W.min[2]},max:{x:W.max[0],y:W.max[1],z:W.max[2]}},nodeNames:G,trimesh:V?{vertices:Array.from(V.vertices),indices:Array.from(V.indices)}:void 0};try{let H=q5.dirname(X);M4.mkdirSync(H,{recursive:!0}),M4.writeFileSync(X,JSON.stringify(Q))}catch(H){p.warning(`ModelRegistry._loadModelData(): Failed to write data file for ${$}. Error: ${String(H)}`)}}this._modelUriAnimationNames.set($,Q.animationNames),this._modelUriBoundingBoxes.set($,Q.boundingBox),this._modelUriNodeNames.set($,Q.nodeNames),this._modelUriTrimeshes.set($,Q.trimesh?{vertices:new Float32Array(Q.trimesh.vertices),indices:new Uint32Array(Q.trimesh.indices)}:void 0)}async _resolveOptimizedModelPath(Z){let J=this._buildOptimizedModelPath(Z);if(!this.optimizeEveryStart&&this._isOptimizedVersionValid(Z))return J;return await this._optimizeModel(Z,J)}_isOptimizedVersionValid(Z){let J=`${this._buildOptimizedModelPath(Z)}${NZ.CHECKSUM_EXT}`;if(!M4.existsSync(J))return!1;let X=this._calculateChecksum(Z),$=M4.readFileSync(J,"utf8");return X===$}_calculateChecksum(Z){if(!M4.existsSync(Z))return"";let J=M4.readFileSync(Z);return kR1.createHash("sha256").update(J.toString("base64")).digest("hex")}_buildOptimizedModelPath(Z){let J=q5.basename(Z),X=J.replace(/\.[^/.]+$/,""),$=q5.dirname(Z),Y=q5.join($,NZ.OPTIMIZED_DIR,X);return q5.join(Y,J)}async _buildTrimesh(Z,J=1,X=0.001){let $=bs(Z);$.setLogger(new z5(MG.WARN)),await $.transform(Ns({pivot:"center"}),ps(),gs(),bO(),os({simplifier:$o.MeshoptSimplifier,ratio:J,error:X}),Is());for(let v of $.getRoot().listScenes())for(let q of v.listChildren())ks(q);let Y=[],Q=0,K=0;for(let v of $.getRoot().listMeshes())for(let q of v.listPrimitives()){let F=q.getAttribute("POSITION"),c=q.getIndices();if(!F||!c)continue;let w=F.getArray(),x=c.getArray(),j=x instanceof Uint32Array?x:new Uint32Array(x);if(w.length===0||j.length===0)continue;Y.push({vertices:w,indices:j}),Q+=w.length,K+=j.length}if(Y.length===0){p.error("ModelRegistry._buildTrimesh(): Model has no primitives with POSITION and INDICES!");return}let W=new Float32Array(Q),G=new Uint32Array(K),z=0,V=0,H=0;for(let v of Y){W.set(v.vertices,z);let q=v.vertices.length/3;for(let F=0;F<v.indices.length;F++)G[H+F]=v.indices[F]+V;z+=v.vertices.length,H+=v.indices.length,V+=q}return{vertices:W,indices:G}}async _optimizeModel(Z,J){let X=q5.dirname(J);M4.rmSync(X,{recursive:!0,force:!0}),M4.mkdirSync(X,{recursive:!0}),console.log(`ModelRegistry: Optimizing model ${this._absoluteModelPathToModelUri(Z)}...`);for(let $ of NZ.OPTIMIZER_RUNS){let Y=J.replace(/(\.[^/.]+)$/,`${$.suffix}$1`),{stderr:Q}=await Ui("npx",["@gltf-transform/cli","optimize",Z,Y,...$.options]);if(Q)return p.warning(`ModelRegistry._optimizeModel(): Error optimizing model ${this._absoluteModelPathToModelUri(Z)}, defaulting to unoptimized model. Error: ${Q}`),Z}return M4.writeFileSync(`${J}${NZ.CHECKSUM_EXT}`,this._calculateChecksum(Z)),J}}var rG;((Y)=>{Y.DYNAMIC="dynamic";Y.FIXED="fixed";Y.KINEMATIC_POSITION="kinematic_position";Y.KINEMATIC_VELOCITY="kinematic_velocity"})(rG||={});var lO=0.001,Yo="dynamic";class aJ extends j0{_additionalMass=0;_colliders=new Set;_explicitSleep=!1;_enabledPositions={x:!0,y:!0,z:!0};_enabledRotations={x:!0,y:!0,z:!0};_rigidBody;_rigidBodyDesc;_rigidBodyType;_simulation;constructor(Z){super();Z.type??=Yo,this._rigidBodyDesc=this._createRigidBodyDesc(Z),this._rigidBodyType=Z.type,this._applyRigidBodyOptions(Z),this._autoAddToSimulation(Z)}get additionalMass(){if(!this._requireNotRemoved("additionalMass"))return 0;return this._additionalMass}get additionalSolverIterations(){if(!this._requireNotRemoved("additionalSolverIterations"))return 0;return this._rigidBody?this._rigidBody.additionalSolverIterations():this._rigidBodyDesc.additionalSolverIterations}get angularDamping(){if(!this._requireNotRemoved("angularDamping"))return 0;return this._rigidBody?this._rigidBody.angularDamping():this._rigidBodyDesc.angularDamping}get angularVelocity(){if(!this._requireNotRemoved("angularVelocity"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.angvel():this._rigidBodyDesc.angvel}get colliders(){return this._colliders}get dominanceGroup(){if(!this._requireNotRemoved("dominanceGroup"))return 0;return this._rigidBody?this._rigidBody.dominanceGroup():this._rigidBodyDesc.dominanceGroup}get directionFromRotation(){let{x:Z,y:J,z:X,w:$}=this.rotation;return{x:-2*(Z*X+$*J),y:-2*(J*X-$*Z),z:-(1-2*(Z*Z+J*J))}}get effectiveAngularInertia(){if(!this._requireNotRemoved("effectiveAngularInertia"))return;return this._rigidBody?this._rigidBody.effectiveAngularInertia():void 0}get effectiveInverseMass(){if(!this._requireNotRemoved("effectiveInverseMass"))return;return this._rigidBody?this._rigidBody.effectiveInvMass():void 0}get enabledRotations(){if(!this._requireNotRemoved("enabledRotations"))return{x:!0,y:!0,z:!0};return this._enabledRotations}get enabledPositions(){if(!this._requireNotRemoved("enabledPositions"))return{x:!0,y:!0,z:!0};return this._enabledPositions}get gravityScale(){if(!this._requireNotRemoved("gravityScale"))return 0;return this._rigidBody?this._rigidBody.gravityScale():this._rigidBodyDesc.gravityScale}get inverseMass(){if(!this._requireNotRemoved("inverseMass"))return;return this._rigidBody?this._rigidBody.invMass():void 0}get isCcdEnabled(){if(!this._requireNotRemoved("isCcdEnabled"))return!1;return this._rigidBody?this._rigidBody.isCcdEnabled():this._rigidBodyDesc.ccdEnabled}get isDynamic(){if(!this._requireNotRemoved("isDynamic"))return!1;return this._rigidBodyType==="dynamic"}get isEnabled(){if(!this._requireNotRemoved("isEnabled"))return!1;return this._rigidBody?this._rigidBody.isEnabled():this._rigidBodyDesc.enabled}get isFixed(){if(!this._requireNotRemoved("isFixed"))return!1;return this._rigidBodyType==="fixed"}get isKinematic(){if(!this._requireNotRemoved("isKinematic"))return!1;return["kinematic_position","kinematic_velocity"].includes(this._rigidBodyType)}get isKinematicPositionBased(){if(!this._requireNotRemoved("isKinematicPositionBased"))return!1;return this._rigidBodyType==="kinematic_position"}get isKinematicVelocityBased(){if(!this._requireNotRemoved("isKinematicVelocityBased"))return!1;return this._rigidBodyType==="kinematic_velocity"}get isMoving(){if(!this._requireNotRemoved("isMoving"))return!1;return this._rigidBody?this._rigidBody.isMoving():!1}get isRemoved(){return!this._rigidBody&&!this._rigidBodyDesc}get isSimulated(){if(!this._requireNotRemoved("isSimulated"))return!1;return this._rigidBody?!0:!1}get isSleeping(){if(!this._requireNotRemoved("isSleeping"))return!1;return this._rigidBody?this._rigidBody.isSleeping():this._rigidBodyDesc.sleeping}get linearDamping(){if(!this._requireNotRemoved("linearDamping"))return 0;return this._rigidBody?this._rigidBody.linearDamping():this._rigidBodyDesc.linearDamping}get linearVelocity(){if(!this._requireNotRemoved("linearVelocity"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.linvel():this._rigidBodyDesc.linvel}get localCenterOfMass(){if(!this._requireNotRemoved("localCenterOfMass"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.localCom():this._rigidBodyDesc.centerOfMass}get mass(){if(!this._requireNotRemoved("mass"))return 0;return this._rigidBody?this._rigidBody.mass():this._rigidBodyDesc.mass}get nextKinematicRotation(){if(!this._requireNotRemoved("nextKinematicRotation"))return{x:0,y:0,z:0,w:1};return this._rigidBody?this._rigidBody.nextRotation():this._rigidBodyDesc.rotation}get nextKinematicPosition(){if(!this._requireNotRemoved("nextKinematicPosition"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.nextTranslation():this._rigidBodyDesc.translation}get numColliders(){return this._colliders.size}get principalAngularInertia(){if(!this._requireNotRemoved("principalAngularInertia"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.principalInertia():this._rigidBodyDesc.principalAngularInertia}get principalAngularInertiaLocalFrame(){if(!this._requireNotRemoved("principalAngularInertiaLocalFrame"))return;return this._rigidBody?this._rigidBody.principalInertiaLocalFrame():void 0}get position(){if(!this._requireNotRemoved("position"))return{x:0,y:0,z:0};return this._rigidBody?this._rigidBody.translation():this._rigidBodyDesc.translation}get rawRigidBody(){if(!this._requireNotRemoved("rawRigidBody"))return;return this._rigidBody}get rotation(){if(!this._requireNotRemoved("rotation"))return{x:0,y:0,z:0,w:1};return this._rigidBody?this._rigidBody.rotation():this._rigidBodyDesc.rotation}get softCcdPrediction(){if(!this._requireNotRemoved("softCcdPrediction"))return 0;return this._rigidBody?this._rigidBody.softCcdPrediction():this._rigidBodyDesc.softCcdPrediction}get type(){if(!this._requireNotRemoved("type"))return"dynamic";return this._rigidBodyType}get worldCenterOfMass(){if(!this._requireNotRemoved("worldCenterOfMass"))return;return this._rigidBody?this._rigidBody.worldCom():void 0}setAdditionalMass(Z){if(!this._requireDynamic("setAdditionalMass"))return;if(!this._requireNotRemoved("setAdditionalMass"))return;this._rigidBody?this._rigidBody.setAdditionalMass(Z,!this._explicitSleep):this._rigidBodyDesc.setAdditionalMass(Z)}setAdditionalMassProperties(Z){if(!this._requireDynamic("setAdditionalMassProperties"))return;if(!this._requireNotRemoved("setAdditionalMassProperties"))return;let{additionalMass:J,centerOfMass:X,principalAngularInertia:$,principalAngularInertiaLocalFrame:Y}=Z;this._rigidBody?this._rigidBody.setAdditionalMassProperties(J,X,$,Y,!this._explicitSleep):this._rigidBodyDesc.setAdditionalMassProperties(J,X,$,Y)}setAdditionalSolverIterations(Z){if(!this._requireDynamic("setAdditionalSolverIterations"))return;if(!this._requireNotRemoved("setAdditionalSolverIterations"))return;this._rigidBody?this._rigidBody.setAdditionalSolverIterations(Z):this._rigidBodyDesc.setAdditionalSolverIterations(Z)}setAngularDamping(Z){if(!this._requireDynamic("setAngularDamping"))return;if(!this._requireNotRemoved("setAngularDamping"))return;this._rigidBody?this._rigidBody.setAngularDamping(Z):this._rigidBodyDesc.setAngularDamping(Z)}setAngularVelocity(Z){if(!this._requireNotKinematicPositionBased("setAngularVelocity"))return;if(!this._requireNotRemoved("setAngularVelocity"))return;this._rigidBody?this._rigidBody.setAngvel(Z,!this._explicitSleep):this._rigidBodyDesc.setAngvel(Z)}setCcdEnabled(Z){if(!this._requireDynamic("setCcdEnabled"))return;if(!this._requireNotRemoved("setCcdEnabled"))return;this._rigidBody?this._rigidBody.enableCcd(Z):this._rigidBodyDesc.setCcdEnabled(Z)}setDominanceGroup(Z){if(!this._requireDynamic("setDominanceGroup"))return;if(!this._requireNotRemoved("setDominanceGroup"))return;this._rigidBody?this._rigidBody.setDominanceGroup(Z):this._rigidBodyDesc.setDominanceGroup(Z)}setEnabled(Z){if(!this._requireNotRemoved("setEnabled"))return;this._rigidBody?this._rigidBody.setEnabled(Z):this._rigidBodyDesc.setEnabled(Z)}setEnabledPositions(Z){if(!this._requireDynamic("setEnabledPositions"))return;if(!this._requireNotRemoved("setEnabledPositions"))return;this._rigidBody?this._rigidBody.setEnabledTranslations(Z.x,Z.y,Z.z,!this._explicitSleep):this._rigidBodyDesc.enabledTranslations(Z.x,Z.y,Z.z),this._enabledPositions=Z}setEnabledRotations(Z){if(!this._requireDynamic("setEnabledRotations"))return;if(!this._requireNotRemoved("setEnabledRotations"))return;this._rigidBody?this._rigidBody.setEnabledRotations(Z.x,Z.y,Z.z,!this._explicitSleep):this._rigidBodyDesc.enabledRotations(Z.x,Z.y,Z.z),this._enabledRotations=Z}setGravityScale(Z){if(!this._requireDynamic("setGravityScale"))return;if(!this._requireNotRemoved("setGravityScale"))return;this._rigidBody?this._rigidBody.setGravityScale(Z,!this._explicitSleep):this._rigidBodyDesc.setGravityScale(Z)}setLinearDamping(Z){if(!this._requireDynamic("setLinearDamping"))return;if(!this._requireNotRemoved("setLinearDamping"))return;this._rigidBody?this._rigidBody.setLinearDamping(Z):this._rigidBodyDesc.setLinearDamping(Z)}setLinearVelocity(Z){if(!this._requireNotKinematicPositionBased("setLinearVelocity"))return;if(!this._requireNotRemoved("setLinearVelocity"))return;this._rigidBody?this._rigidBody.setLinvel(Z,!this._explicitSleep):this._rigidBodyDesc.setLinvel(Z.x,Z.y,Z.z)}setNextKinematicRotation(Z){if(!this._requireKinematic("setNextKinematicRotation"))return;if(!this._requireNotRemoved("setNextKinematicRotation"))return;this._rigidBody?this._rigidBody.setNextKinematicRotation(Z):this._rigidBodyDesc.setRotation(Z)}setNextKinematicPosition(Z){if(!this._requireKinematic("setNextKinematicPosition"))return;if(!this._requireNotRemoved("setNextKinematicPosition"))return;this._rigidBody?this._rigidBody.setNextKinematicTranslation(Z):this._rigidBodyDesc.setTranslation(Z.x,Z.y,Z.z)}setPosition(Z){if(!this._requireNotRemoved("setPosition"))return;this._rigidBody?this._rigidBody.setTranslation(Z,!this._explicitSleep):this._rigidBodyDesc.setTranslation(Z.x,Z.y,Z.z)}setRotation(Z){if(!this._requireNotRemoved("setRotation"))return;this._rigidBody?this._rigidBody.setRotation(Z,!this._explicitSleep):this._rigidBodyDesc.setRotation(Z)}setSleeping(Z){if(!this._requireDynamic("setSleeping"))return;if(!this._requireNotRemoved("setSleeping"))return;this._rigidBody?Z?this._rigidBody.sleep():this._rigidBody.wakeUp():this._rigidBodyDesc.sleeping=Z,this._explicitSleep=Z}setSoftCcdPrediction(Z){if(!this._requireDynamic("setSoftCcdPrediction"))return;if(!this._requireNotRemoved("setSoftCcdPrediction"))return;this._rigidBody?this._rigidBody.setSoftCcdPrediction(Z):this._rigidBodyDesc.setSoftCcdPrediction(Z)}setCollisionGroupsForSolidColliders(Z){if(!this._requireNotRemoved("setCollisionGroupsForSolidColliders"))return;this._colliders.forEach((J)=>{if(J.isSensor)return;J.setCollisionGroups(Z)})}setCollisionGroupsForSensorColliders(Z){if(!this._requireNotRemoved("setCollisionGroupsForSensorColliders"))return;this._colliders.forEach((J)=>{if(!J.isSensor)return;J.setCollisionGroups(Z)})}setType(Z){if(!this._requireNotRemoved("setType"))return;let X={["dynamic"]:X1.RigidBodyType.Dynamic,["fixed"]:X1.RigidBodyType.Fixed,["kinematic_position"]:X1.RigidBodyType.KinematicPositionBased,["kinematic_velocity"]:X1.RigidBodyType.KinematicVelocityBased}[Z];if(X===void 0)return p.error(`Invalid RigidBodyType: ${Z}`);this._rigidBody?this._rigidBody.setBodyType(X,!this._explicitSleep):this._rigidBodyDesc.status=X,this._rigidBodyType=Z}addForce(Z){if(!this._requireNotRemoved("addForce"))return;if(!this._requireCreated("addForce"))return;if(!this._requireDynamic("addForce"))return;if(this._isNegligibleVector(Z))return;this._rigidBody.addForce(Z,!this._explicitSleep)}addTorque(Z){if(!this._requireNotRemoved("addTorque"))return;if(!this._requireCreated("addTorque"))return;if(!this._requireDynamic("addTorque"))return;if(this._isNegligibleVector(Z))return;this._rigidBody.addTorque(Z,!this._explicitSleep)}addChildColliderToSimulation(Z){if(!this._requireNotRemoved("addChildColliderToSimulation"))return;if(!this._requireCreated("addChildColliderToSimulation"))return;Z.addToSimulation(this._simulation,this)}addToSimulation(Z){if(!this._requireNotRemoved("addToSimulation"))return;if(this._rigidBody)return p.error("RigidBody.addToSimulation(): Rigid body already exists in the simulation!");this._simulation=Z,this._rigidBody=this._simulation.createRawRigidBody(this._rigidBodyDesc),this._colliders.forEach((J)=>{if(!J.isSimulated)J.addToSimulation(Z,this)})}applyImpulse(Z){if(!this._requireNotRemoved("applyImpulse"))return;if(!this._requireCreated("applyImpulse"))return;if(!this._requireDynamic("applyImpulse"))return;if(this._isNegligibleVector(Z))return;this._rigidBody.applyImpulse(Z,!this._explicitSleep)}applyImpulseAtPoint(Z,J){if(!this._requireNotRemoved("applyImpulseAtPoint"))return;if(!this._requireCreated("applyImpulseAtPoint"))return;if(!this._requireDynamic("applyImpulseAtPoint"))return;if(this._isNegligibleVector(Z))return;this._rigidBody.applyImpulseAtPoint(Z,J,!this._explicitSleep)}applyTorqueImpulse(Z){if(!this._requireNotRemoved("applyTorqueImpulse"))return;if(!this._requireCreated("applyTorqueImpulse"))return;if(!this._requireDynamic("applyTorqueImpulse"))return;this._rigidBody.applyTorqueImpulse(Z,!this._explicitSleep)}createAndAddChildCollider(Z){if(!this._requireNotRemoved("createAndAddChildCollider"))return null;return this._simulation?new A5({...Z,parentRigidBody:this,simulation:this._simulation}):this._createAndAddPendingChildCollider(Z)}createAndAddChildColliders(Z){let J=[];return Z.forEach((X)=>{let $=this.createAndAddChildCollider(X);if($)J.push($)}),J}getCollidersByTag(Z){let J=[];for(let X of this._colliders)if(X.tag===Z)J.push(X);return J}linkCollider(Z){if(!this._requireNotRemoved("linkCollider"))return;if(Z.parentRigidBody!==this)return p.error("RigidBody.linkCollider(): Collider cannot be linked because it is not a child of this rigid body!");this._colliders.add(Z)}lockAllRotations(){if(!this._requireNotRemoved("lockAllRotations"))return;this.setEnabledRotations({x:!1,y:!1,z:!1})}lockAllPositions(){if(!this._requireNotRemoved("lockAllPositions"))return;this.setEnabledPositions({x:!1,y:!1,z:!1})}removeFromSimulation(){if(!this._requireNotRemoved("removeFromSimulation"))return;if(!this._rigidBody)return p.error("RigidBody.removeFromSimulation(): Rigid body does not exist in the simulation!");this._colliders.forEach((Z)=>{Z.removeFromSimulation()}),this._simulation.removeRawRigidBody(this._rigidBody),this._simulation=void 0,this._rigidBody=void 0}unlinkCollider(Z){if(!this._requireNotRemoved("unlinkCollider"))return;if(!Z.isRemoved)return p.error("RigidBody.unlinkCollider(): Collider is still simulated and therefore cannot be unlinked from this rigid body!");this._colliders.delete(Z)}resetAngularVelocity(){if(!this._requireNotRemoved("resetAngularVelocity"))return;if(!this._requireCreated("resetAngularVelocity"))return;this.setAngularVelocity({x:0,y:0,z:0})}resetForces(){if(!this._requireNotRemoved("resetForces"))return;if(!this._requireCreated("resetForces"))return;this._rigidBody.resetForces(!this._explicitSleep)}resetLinearVelocity(){if(!this._requireNotRemoved("resetLinearVelocity"))return;if(!this._requireCreated("resetLinearVelocity"))return;this.setLinearVelocity({x:0,y:0,z:0})}resetTorques(){if(!this._requireNotRemoved("resetTorques"))return;if(!this._requireCreated("resetTorques"))return;this._rigidBody.resetTorques(!this._explicitSleep)}sleep(){if(!this._requireNotRemoved("sleep"))return;this.setSleeping(!0)}wakeUp(){if(!this._requireNotRemoved("wakeUp"))return;this.setSleeping(!1)}_applyRigidBodyOptions(Z){[["additionalMass",this.setAdditionalMass.bind(this)],["additionalMassProperties",this.setAdditionalMassProperties.bind(this)],["additionalSolverIterations",this.setAdditionalSolverIterations.bind(this)],["angularDamping",this.setAngularDamping.bind(this)],["angularVelocity",this.setAngularVelocity.bind(this)],["dominanceGroup",this.setDominanceGroup.bind(this)],["ccdEnabled",this.setCcdEnabled.bind(this)],["enabled",this.setEnabled.bind(this)],["enabledPositions",this.setEnabledPositions.bind(this)],["enabledRotations",this.setEnabledRotations.bind(this)],["gravityScale",this.setGravityScale.bind(this)],["linearDamping",this.setLinearDamping.bind(this)],["linearVelocity",this.setLinearVelocity.bind(this)],["position",this.setPosition.bind(this)],["rotation",this.setRotation.bind(this)],["sleeping",this.setSleeping.bind(this)],["softCcdPrediction",this.setSoftCcdPrediction.bind(this)]].forEach(([X,$])=>{if(X in Z)$(Z[X])})}_autoAddToSimulation(Z){if(Z.colliders)this._createAndAddPendingChildColliders(Z.colliders);if(Z.simulation)this.addToSimulation(Z.simulation)}_createAndAddPendingChildCollider(Z){if(!this._requireNotRemoved("createAndAddPendingChildCollider"))return null;if(!this._requireNotSimulated("createAndAddPendingChildCollider"))return null;let J=new A5(Z);return this._colliders.add(J),J}_createAndAddPendingChildColliders(Z){let J=[];return Z.forEach((X)=>{let $=this._createAndAddPendingChildCollider(X);if($)J.push($)}),J}_createRigidBodyDesc(Z){let J=Z.type??Yo;return{["dynamic"]:()=>X1.RigidBodyDesc.dynamic(),["fixed"]:()=>X1.RigidBodyDesc.fixed(),["kinematic_position"]:()=>X1.RigidBodyDesc.kinematicPositionBased(),["kinematic_velocity"]:()=>X1.RigidBodyDesc.kinematicVelocityBased()}[J]()}_requireCreated(Z){if(!this._rigidBody||!this._simulation)p.error(`RigidBody._requireCreated(): Rigid body has not been created and therefore does not support the invoked method: ${Z}()`);return!!this._rigidBody&&!!this._simulation}_requireDynamic(Z){if(!this.isDynamic)p.error(`RigidBody._requireDynamic(): Rigid body is not dynamic and therefore does not support the invoked method: ${Z}()`);return this.isDynamic}_requireKinematic(Z){if(!this.isKinematic)p.error(`RigidBody._requireKinematic(): Rigid body is not kinematic and therefore does not support the invoked method: ${Z}()`);return this.isKinematic}_requireNotKinematicPositionBased(Z){if(this.isKinematicPositionBased)p.error(`RigidBody._requireNotKinematicPositionBased(): Rigid body is kinematic position based and therefore does not support the invoked method: ${Z}()`);return!this.isKinematicPositionBased}_requireNotRemoved(Z){if(!this._rigidBody&&!this._rigidBodyDesc)p.error(`RigidBody._requireNotRemoved(): Rigid body has been removed and therefore does not support the invoked method: ${Z}()`);return!!this._rigidBody||!!this._rigidBodyDesc}_requireNotSimulated(Z){if(this.isSimulated)p.error(`RigidBody._requireNotSimulated(): Rigid body is simulated and therefore does not support the invoked method: ${Z}()`);return!this.isSimulated}_isNegligibleVector(Z){return Math.abs(Z.x)<lO&&Math.abs(Z.y)<lO&&Math.abs(Z.z)<lO}}var yO;((Y)=>{Y[Y.Average=0]="Average";Y[Y.Min=1]="Min";Y[Y.Multiply=2]="Multiply";Y[Y.Max=3]="Max"})(yO||={});var O3;((V)=>{V.NONE="none";V.BALL="ball";V.BLOCK="block";V.CAPSULE="capsule";V.CONE="cone";V.CYLINDER="cylinder";V.ROUND_CYLINDER="round-cylinder";V.TRIMESH="trimesh";V.VOXELS="voxels";V.WEDGE="wedge"})(O3||={});class A5 extends j0{_collider;_colliderDesc;_onCollision;_parentRigidBody;_relativePosition={x:0,y:0,z:0};_relativeRotation={x:0,y:0,z:0,w:1};_shape;_simulation;_tag;constructor(Z){super();this._colliderDesc=this._createColliderDesc(Z),this._shape=Z.shape,this._applyColliderOptions(Z),this._autoAddToSimulation(Z)}static optionsFromBlockHalfExtents(Z){return{shape:"block",halfExtents:Z}}static optionsFromModelUri(Z,J=1,X){let $=B6.instance.getBoundingBox(Z),Y=$.max.x-$.min.x,Q=$.max.y-$.min.y,K=$.max.z-$.min.z,W=Math.max(Y,K),G=Math.min(Y,K),z=W/G,V=W/Q,H=W*J/2,v=(j)=>Math.max(0.01,j),q=()=>({shape:"block",halfExtents:{x:v(Y*J/2),y:v(Q*J/2),z:v(K*J/2)}}),F=()=>({shape:"round-cylinder",radius:v(H),halfHeight:v(Q*J/2),borderRadius:v(H*0.1)}),c=()=>{let j=B6.instance.getTrimesh(Z,J);if(!j)return;return{shape:"trimesh",vertices:j.vertices,indices:j.indices}},w=()=>({shape:"wedge",extents:{x:Y*J,y:Q*J,z:K*J}}),x=()=>({shape:"capsule",radius:v(H),halfHeight:v(Q*J/2-H)});if(X)switch(X){case"block":return q();case"capsule":return x();case"round-cylinder":return F();case"trimesh":{let j=c();if(!j){p.error(`Collider.optionsFromModelUri(): Failed to create trimesh options for model ${Z}, falling back to generic shape!`);break}return j}case"wedge":return w();default:p.warning(`Collider.optionsFromModelUri(): Preferred shape ${X} is not yet supported with Collider.optionsFromModelUri(), defaulting to generic shape!`)}if(z>2)return q();if(V>1.5)return F();return x()}get bounciness(){if(!this._requireNotRemoved("bounciness"))return 0;return this._collider?this._collider.restitution():this._colliderDesc.restitution}get bouncinessCombineRule(){if(!this._requireNotRemoved("bouncinessCombineRule"))return 0;return this._collider?this._collider.restitutionCombineRule():this._colliderDesc.restitutionCombineRule}get collisionGroups(){if(!this._requireNotRemoved("collisionGroups"))return{belongsTo:[],collidesWith:[]};return this._collider?V9.decodeRawCollisionGroups(this._collider.collisionGroups()):V9.decodeRawCollisionGroups(this._colliderDesc.collisionGroups)}get friction(){if(!this._requireNotRemoved("friction"))return 0;return this._collider?this._collider.friction():this._colliderDesc.friction}get frictionCombineRule(){if(!this._requireNotRemoved("frictionCombineRule"))return 0;return this._collider?this._collider.frictionCombineRule():this._colliderDesc.frictionCombineRule}get isEnabled(){if(!this._requireNotRemoved("isEnabled"))return!1;return this._collider?this._collider.isEnabled():this._colliderDesc.enabled}get isRemoved(){return!this._collider&&!this._colliderDesc}get isSensor(){if(!this._requireNotRemoved("isSensor"))return!1;return this._collider?this._collider.isSensor():this._colliderDesc.isSensor}get isSimulated(){if(!this._requireNotRemoved("isSimulated"))return!1;return!!this._collider}get parentRigidBody(){if(!this._requireNotRemoved("parentRigidBody"))return;return this._parentRigidBody}get rawCollider(){if(!this._requireNotRemoved("rawCollider"))return;return this._collider}get rawShape(){if(!this._requireNotRemoved("rawShape"))return;return this._collider?this._collider.shape:this._colliderDesc.shape}get relativePosition(){if(!this._requireNotRemoved("relativePosition"))return{x:0,y:0,z:0};return this._relativePosition}get relativeRotation(){if(!this._requireNotRemoved("relativeRotation"))return{x:0,y:0,z:0,w:1};return this._relativeRotation}get shape(){if(!this._requireNotRemoved("shape"))return"none";return this._shape}get tag(){if(!this._requireNotRemoved("tag"))return;return this._tag}setBounciness(Z){if(!this._requireNotRemoved("setBounciness"))return;this._collider?this._collider.setRestitution(Z):this._colliderDesc.setRestitution(Z)}setBouncinessCombineRule(Z){if(!this._requireNotRemoved("setBouncinessCombineRule"))return;this._collider?this._collider.setRestitutionCombineRule(Z):this._colliderDesc.setRestitutionCombineRule(Z)}setCollisionGroups(Z){if(!this._requireNotRemoved("setCollisionGroups"))return;let J=V9.buildRawCollisionGroups(Z);this._collider?this._collider.setCollisionGroups(J):this._colliderDesc.setCollisionGroups(J)}setEnabled(Z){if(!this._requireNotRemoved("setEnabled"))return;this._collider?this._collider.setEnabled(Z):this._colliderDesc.setEnabled(Z)}setFriction(Z){if(!this._requireNotRemoved("setFriction"))return;this._collider?this._collider.setFriction(Z):this._colliderDesc.setFriction(Z)}setFrictionCombineRule(Z){if(!this._requireNotRemoved("setFrictionCombineRule"))return;this._collider?this._collider.setFrictionCombineRule(Z):this._colliderDesc.setFrictionCombineRule(Z)}setMass(Z){if(!this._requireNotRemoved("setMass"))return;this._collider?this._collider.setMass(Z):this._colliderDesc.setMass(Z)}setOnCollision(Z){if(!this._requireNotRemoved("setOnCollision"))return;if(this._onCollision=Z,this.isSimulated)if(this.enableCollisionEvents(!!Z),Z)this._simulation.colliderMap.setColliderCollisionCallback(this,Z);else this._simulation.colliderMap.removeColliderCollisionCallback(this)}setRelativeRotation(Z){if(!this._requireNotRemoved("setRelativeRotation"))return;this._relativeRotation=Z,this._collider?this._collider.parent()?this._collider.setRotationWrtParent(Z):this._collider.setRotation(Z):this._colliderDesc.setRotation(Z)}setRelativePosition(Z){if(!this._requireNotRemoved("setRelativePosition"))return;this._relativePosition=Z,this._collider?this._collider.parent()?this._collider.setTranslationWrtParent(Z):this._collider.setTranslation(Z):this._colliderDesc.setTranslation(Z.x,Z.y,Z.z)}setSensor(Z){if(!this._requireNotRemoved("setSensor"))return;this._collider?this._collider.setSensor(Z):this._colliderDesc.setSensor(Z)}setTag(Z){if(!this._requireNotRemoved("setTag"))return;this._tag=Z}setVoxel(Z,J){if(!this._requireNotRemoved("setVoxel"))return;if(!this._requireSimulated("setVoxel"))return;if(this.shape!=="voxels")return p.error("Collider.setVoxel(): Collider is not a voxels collider!");this._collider.setVoxel(Z.x,Z.y,Z.z,J)}addToSimulation(Z,J){if(!this._requireNotRemoved("addToSimulation"))return;if(!this._requireUnsimulated("addToSimulation"))return;if(J){if(!J.isSimulated)return p.error("Collider.addToSimulation(): Rigid body must be simulated before adding a collider to it!");if(J.type==="dynamic"&&this.shape==="trimesh")p.warning("Collider.addToSimulation(): Trimesh colliders are strongly discouraged to be used with dynamic rigid bodies, they will not contribute any mass!")}if(this._simulation=Z,this._parentRigidBody=J,this._collider=this._simulation.createRawCollider(this._colliderDesc,J?.rawRigidBody),this._colliderDesc=void 0,J)J.linkCollider(this);if(this._onCollision)this.setOnCollision(this._onCollision)}combineVoxelStates(Z){if(!this._requireNotRemoved("combineVoxelStates"))return;if(!this._requireSimulated("combineVoxelStates"))return;if(!Z.isSimulated)return p.error("Collider.combineVoxelStates(): Other collider is not simulated!");if(this.shape!=="voxels")return p.error("Collider.combineVoxelStates(): Collider is not a voxels collider!");if(Z.shape!=="voxels")return p.error("Collider.combineVoxelStates(): Other collider is not a voxels collider!");this._collider.combineVoxelStates(Z.rawCollider,0,0,0)}enableCollisionEvents(Z){if(!this._requireNotRemoved("enableCollisionEvents"))return;let J=this._collider?this._collider.activeEvents():this._colliderDesc.activeEvents,X=Z?J|X1.ActiveEvents.COLLISION_EVENTS:J&~X1.ActiveEvents.COLLISION_EVENTS;(this._collider??this._colliderDesc).setActiveEvents(X),this._setActiveCollisionTypes()}enableContactForceEvents(Z){if(!this._requireNotRemoved("enableContactForceEvents"))return;let J=this._collider?this._collider.activeEvents():this._colliderDesc.activeEvents,X=Z?J|X1.ActiveEvents.CONTACT_FORCE_EVENTS:J&~X1.ActiveEvents.CONTACT_FORCE_EVENTS;(this._collider??this._colliderDesc).setActiveEvents(X),this._setActiveCollisionTypes()}propagateVoxelChange(Z,J){if(!this._requireNotRemoved("propagateVoxelChange"))return;if(!this._requireSimulated("propagateVoxelChange"))return;if(!Z.isSimulated)return p.error("Collider.propagateVoxelChange(): Other collider is not simulated!");if(this.shape!=="voxels")return p.error("Collider.propagateVoxelChange(): Collider is not a voxels collider!");if(Z.shape!=="voxels")return p.error("Collider.propagateVoxelChange(): Other collider is not a voxels collider!");this._collider.propagateVoxelChange(Z.rawCollider,J.x,J.y,J.z,0,0,0)}removeFromSimulation(){if(!this._requireNotRemoved("removeFromSimulation"))return;if(!this._requireSimulated("removeFromSimulation"))return;if(this._simulation.removeRawCollider(this._collider),this._simulation=void 0,this._collider=void 0,this._parentRigidBody)this._parentRigidBody.unlinkCollider(this);this._parentRigidBody=void 0}scale(Z){if(!this._requireNotRemoved("scale"))return;switch(this.setRelativePosition({x:this.relativePosition.x*Z,y:this.relativePosition.y*Z,z:this.relativePosition.z*Z}),this._shape){case"ball":{if(this._collider)this._collider.setRadius(this._collider.radius()*Z);else this._colliderDesc.shape.radius*=Z;return}case"block":{if(this._collider){let J=this._collider.halfExtents();this._collider.setHalfExtents({x:J.x*Z,y:J.y*Z,z:J.z*Z})}else this._colliderDesc.shape.halfExtents.x*=Z,this._colliderDesc.shape.halfExtents.y*=Z,this._colliderDesc.shape.halfExtents.z*=Z;return}case"capsule":{if(this._collider)this._collider.setHalfHeight(this._collider.halfHeight()*Z),this._collider.setRadius(this._collider.radius()*Z);else this._colliderDesc.shape.halfHeight*=Z,this._colliderDesc.shape.radius*=Z;return}case"cone":{if(this._collider)this._collider.setHalfHeight(this._collider.halfHeight()*Z),this._collider.setRadius(this._collider.radius()*Z);else this._colliderDesc.shape.halfHeight*=Z,this._colliderDesc.shape.radius*=Z;return}case"cylinder":{if(this._collider)this._collider.setHalfHeight(this._collider.halfHeight()*Z),this._collider.setRadius(this._collider.radius()*Z);else this._colliderDesc.shape.halfHeight*=Z,this._colliderDesc.shape.radius*=Z;return}case"round-cylinder":{if(this._collider)this._collider.setHalfHeight(this._collider.halfHeight()*Z),this._collider.setRoundRadius(this._collider.roundRadius()*Z),this._collider.setRadius(this._collider.radius()*Z);else this._colliderDesc.shape.halfHeight=this._colliderDesc.shape.halfHeight*Z,this._colliderDesc.shape.borderRadius=this._colliderDesc.shape.borderRadius*Z,this._colliderDesc.shape.radius=this._colliderDesc.shape.radius*Z;return}case"trimesh":{p.error("Collider.setScale(): Trimesh colliders cannot be scaled!");return}case"voxels":{p.error("Collider.setScale(): Voxels colliders cannot be scaled!");return}case"wedge":{p.error("Collider.setScale(): Wedge colliders cannot be scaled!");return}default:p.fatalError(`Collider.setScale(): ${this._shape} is not a valid collider shape!`)}}_applyColliderOptions(Z){[["bounciness",this.setBounciness.bind(this)],["bouncinessCombineRule",this.setBouncinessCombineRule.bind(this)],["collisionGroups",this.setCollisionGroups.bind(this)],["enabled",this.setEnabled.bind(this)],["friction",this.setFriction.bind(this)],["frictionCombineRule",this.setFrictionCombineRule.bind(this)],["isSensor",this.setSensor.bind(this)],["mass",this.setMass.bind(this)],["onCollision",this.setOnCollision.bind(this)],["relativePosition",this.setRelativePosition.bind(this)],["relativeRotation",this.setRelativeRotation.bind(this)],["tag",this.setTag.bind(this)]].forEach(([X,$])=>{if(Z[X]!==void 0)$.call(this,Z[X])})}_autoAddToSimulation(Z){if(Z.simulation)this.addToSimulation(Z.simulation,Z.parentRigidBody)}_buildWedgeConvexHullVertices(Z){let{x:J,y:X,z:$}=Z,Y=J/2,Q=$/2,K=X/2;return new Float32Array([-Y,0-K,-Q,Y,0-K,-Q,Y,0-K,Q,-Y,0-K,Q,-Y,X-K,-Q,Y,X-K,-Q])}_createColliderDesc(Z){let{shape:J,flags:X}=Z;switch(J){case"ball":{if(!Z.radius)p.fatalError("Ball collider must have a radius!");return X1.ColliderDesc.ball(Z.radius)}case"block":{if(!Z.halfExtents)p.fatalError("Block collider must have halfExtents!");return X1.ColliderDesc.cuboid(Z.halfExtents.x,Z.halfExtents.y,Z.halfExtents.z)}case"capsule":{if(!Z.halfHeight||!Z.radius)p.fatalError("Capsule collider must have halfHeight and radius!");return X1.ColliderDesc.capsule(Z.halfHeight,Z.radius)}case"cone":{if(!Z.radius||!Z.halfHeight)p.fatalError("Cone collider must have radius and halfHeight!");return X1.ColliderDesc.cone(Z.halfHeight,Z.radius)}case"cylinder":{if(!Z.radius||!Z.halfHeight)p.fatalError("Cylinder collider must have radius and halfHeight!");return X1.ColliderDesc.cylinder(Z.halfHeight,Z.radius)}case"round-cylinder":{if(!Z.radius||!Z.halfHeight||!Z.borderRadius)p.fatalError("Round cylinder collider must have radius, halfHeight, and borderRadius!");return X1.ColliderDesc.roundCylinder(Z.halfHeight,Z.radius,Z.borderRadius)}case"trimesh":{if(!Z.indices||!Z.vertices)p.fatalError("Trimesh collider must have vertices and indices!");return X1.ColliderDesc.trimesh(Z.vertices,Z.indices,X)}case"voxels":{if(!Z.coordinates||!Z.size)p.fatalError("Voxels collider must have coordinates and size!");return X1.ColliderDesc.voxels(this._coordinatesToInt32Array(Z.coordinates),Z.size)}case"wedge":{if(!Z.extents)p.fatalError("Wedge collider must have extents!");let $=this._buildWedgeConvexHullVertices(Z.extents),Y=X1.ColliderDesc.convexHull($);if(!Y)throw p.fatalError("Failed to create convex hull for wedge collider!"),new Error("Convex hull creation failed");return Y}default:p.fatalError(`Collider._createColliderDesc(): ${J} is not a valid collider shape!`)}}_requireSimulated(Z){if(!this.isSimulated)p.error(`Collider._requireSimulated(): Collider is not simulated, invoked method: ${Z}()`);return this.isSimulated}_requireUnsimulated(Z){if(this.isSimulated)p.error(`Collider._requireUnsimulated(): Collider is already simulated, invoked method: ${Z}()`);return!this.isSimulated}_requireNotRemoved(Z){if(this.isRemoved)p.error(`Collider._requireNotRemoved(): Collider is removed, invoked method: ${Z}()`);return!this.isRemoved}_setActiveCollisionTypes(){(this._collider??this._colliderDesc).setActiveCollisionTypes(X1.ActiveCollisionTypes.DYNAMIC_DYNAMIC|X1.ActiveCollisionTypes.DYNAMIC_KINEMATIC|X1.ActiveCollisionTypes.DYNAMIC_FIXED|X1.ActiveCollisionTypes.KINEMATIC_KINEMATIC|X1.ActiveCollisionTypes.KINEMATIC_FIXED)}_coordinatesToInt32Array(Z){let J=new Int32Array(Z.length*3);for(let X=0;X<Z.length;X++){let $=Z[X],Y=X*3;J[Y]=Math.floor($.x),J[Y+1]=Math.floor($.y),J[Y+2]=Math.floor($.z)}return J}}var ER1={shape:"voxels"},pO;((X)=>{X.ENTITY_COLLISION="BLOCK_TYPE.ENTITY_COLLISION";X.ENTITY_CONTACT_FORCE="BLOCK_TYPE.ENTITY_CONTACT_FORCE"})(pO||={});class m5 extends j0{_id;_customColliderOptions;_halfExtents;_isLiquid;_lightLevel;_name;_textureUri;constructor(Z={id:-1,textureUri:"textures/missing.png",name:"Unknown"}){if(Z.id<0)p.fatalError("BlockType.constructor(): BlockType id not set.");super();this._id=Z.id,this._customColliderOptions=Z.customColliderOptions,this._halfExtents=Z.halfExtents??{x:0.5,y:0.5,z:0.5},this._isLiquid=Z.isLiquid??!1,this._name=Z.name,this._textureUri=Z.textureUri,this._lightLevel=Math.min(Z.lightLevel??0,15)}get id(){return this._id}get colliderOptions(){return{...this._customColliderOptions,...ER1}}get halfExtents(){return this._halfExtents}get isLiquid(){return this._isLiquid}get isMeshable(){return!this._customColliderOptions}get lightLevel(){return this._lightLevel}get name(){return this._name}get size(){return{x:this._halfExtents.x*2,y:this._halfExtents.y*2,z:this._halfExtents.z*2}}get textureUri(){return this._textureUri}createCollider(Z){let J=new A5({...this.colliderOptions,coordinates:Z,size:this.size});if(this.isLiquid)J.setSensor(!0);if(this.hasListeners("BLOCK_TYPE.ENTITY_COLLISION")||this.isLiquid)J.enableCollisionEvents(!0);if(this.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))J.enableContactForceEvents(!0);if(V9.isDefaultCollisionGroups(J.collisionGroups))J.setCollisionGroups({belongsTo:[1],collidesWith:[65535&~1]});return J}serialize(){return T0.serializeBlockType(this)}}var iO;((J)=>J.REGISTER_BLOCK_TYPE="BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE")(iO||={});class tG extends j0{_blockTypes=new Map;_world;constructor(Z){super();this._world=Z}get world(){return this._world}getAllBlockTypes(){return Array.from(this._blockTypes.values())}getBlockType(Z){let J=this._blockTypes.get(Z);if(!J)p.fatalError(`BlockTypeRegistry.getBlockType(): BlockType with id ${Z} not found.`);return J}registerGenericBlockType(Z){let X=new class extends m5{constructor($=Z){super($)}};return this.registerBlockType(X),X}registerBlockType(Z){this._blockTypes.set(Z.id,Z),this.emitWithWorld(this._world,"BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE",{blockTypeRegistry:this,id:Z.id,blockType:Z})}serialize(){return T0.serializeBlockTypeRegistry(this)}}var LP={};_Q(LP,{worldSchema:()=>BP,worldPacketDefinition:()=>t00,vectorSchema:()=>W1,vectorBooleanSchema:()=>fE1,uiSchema:()=>UP,uiPacketDefinition:()=>o00,uiDatasSchema:()=>jP,uiDatasPacketDefinition:()=>r00,uiDataSendPacketDefinition:()=>b00,uiDataSchema:()=>Dz,syncResponseSchema:()=>xP,syncResponsePacketDefinition:()=>s00,syncRequestSchema:()=>gN,syncRequestPacketDefinition:()=>_00,stateRequestSchema:()=>iN,stateRequestPacketDefinition:()=>I00,sceneUIsSchema:()=>wP,sceneUIsPacketDefinition:()=>n00,sceneUISchema:()=>cP,rgbColorSchema:()=>D6,registeredPackets:()=>kw,quaternionSchema:()=>$P,playersSchema:()=>FP,playersPacketDefinition:()=>a00,playerSchema:()=>qP,physicsDebugRenderSchema:()=>HP,physicsDebugRenderPacketDefinition:()=>g00,physicsDebugRaycastsSchema:()=>vP,physicsDebugRaycastsPacketDefinition:()=>d00,physicsDebugRaycastSchema:()=>VP,particleEmittersSchema:()=>zP,particleEmittersPacketDefinition:()=>i00,particleEmitterSchema:()=>GP,outboundPackets:()=>fw,modelNodeOverrideSchema:()=>XP,lightsSchema:()=>WP,lightsPacketDefinition:()=>p00,lightSchema:()=>KP,isValidPacket:()=>EE1,inputSchema:()=>pN,inputPacketDefinition:()=>E00,inboundPackets:()=>Cw,hexColorSchema:()=>lN,heartbeatSchema:()=>uN,heartbeatPacketDefinition:()=>C00,entitySchema:()=>YP,entitiesSchema:()=>QP,entitiesPacketDefinition:()=>y00,definePacket:()=>f0,debugConfigSchema:()=>yN,debugConfigPacketDefinition:()=>k00,createPacket:()=>BE1,connectionSchema:()=>mN,connectionPacketDefinition:()=>T00,chunksSchema:()=>JP,chunksPacketDefinition:()=>l00,chunkSchema:()=>ZP,chatMessagesSchema:()=>eN,chatMessagesPacketDefinition:()=>u00,chatMessageSendPacketDefinition:()=>f00,chatMessageSchema:()=>Lz,cameraSchema:()=>tN,cameraPacketDefinition:()=>m00,blocksSchema:()=>sN,blocksPacketDefinition:()=>S00,blockTypesSchema:()=>rN,blockTypesPacketDefinition:()=>A00,blockTypeSchema:()=>oN,blockSchema:()=>nN,bidirectionalPackets:()=>Tw,audiosSchema:()=>aN,audiosPacketDefinition:()=>h00,audioSchema:()=>dN,PacketId:()=>C1});var Tw={};_Q(Tw,{heartbeatPacketDefinition:()=>C00,connectionPacketDefinition:()=>T00});var SN=t(N00(),1);class AN extends SN.default{static instance=new SN.default}var C1;((N)=>{N[N.SYNC_REQUEST=0]="SYNC_REQUEST";N[N.INPUT=1]="INPUT";N[N.STATE_REQUEST=2]="STATE_REQUEST";N[N.CHAT_MESSAGE_SEND=3]="CHAT_MESSAGE_SEND";N[N.UI_DATA_SEND=4]="UI_DATA_SEND";N[N.SYNC_RESPONSE=32]="SYNC_RESPONSE";N[N.AUDIOS=33]="AUDIOS";N[N.BLOCKS=34]="BLOCKS";N[N.BLOCK_TYPES=35]="BLOCK_TYPES";N[N.CHAT_MESSAGES=36]="CHAT_MESSAGES";N[N.CHUNKS=37]="CHUNKS";N[N.ENTITIES=38]="ENTITIES";N[N.WORLD=39]="WORLD";N[N.CAMERA=40]="CAMERA";N[N.UI=41]="UI";N[N.UI_DATAS=42]="UI_DATAS";N[N.SCENE_UIS=43]="SCENE_UIS";N[N.LIGHTS=44]="LIGHTS";N[N.PLAYERS=45]="PLAYERS";N[N.PARTICLE_EMITTERS=46]="PARTICLE_EMITTERS";N[N.CONNECTION=116]="CONNECTION";N[N.HEARTBEAT=117]="HEARTBEAT";N[N.DEBUG_CONFIG=128]="DEBUG_CONFIG";N[N.PHYSICS_DEBUG_RENDER=192]="PHYSICS_DEBUG_RENDER";N[N.PHYSICS_DEBUG_RAYCASTS=193]="PHYSICS_DEBUG_RAYCASTS"})(C1||={});function BE1(Z,J,X){if(!Z.validate(J))throw new Error(`Invalid payload for packet with id ${Z.id}. Error: ${AN.instance.errorsText(Z.validate.errors)}`);let $=[Z.id,J];if(typeof X==="number")$.push(X);return $}function f0(Z,J){return{id:Z,schema:J,validate:AN.instance.compile(J)}}var LE1={type:"object",properties:{i:{type:"string"}},required:["i"],additionalProperties:!1},P00={type:"object",properties:{role:{type:"string",enum:["auto","client","server"],nullable:!0},fingerprints:{type:"array",items:{type:"object",properties:{algorithm:{type:"string",enum:["sha-1","sha-224","sha-256","sha-384","sha-512"]},value:{type:"string"}},required:["algorithm","value"]}}},required:["fingerprints"],additionalProperties:!1},DE1={type:"object",properties:{foundation:{type:"string"},priority:{type:"number"},ip:{type:"string"},address:{type:"string"},protocol:{type:"string",enum:["udp","tcp"]},port:{type:"number"},type:{type:"string",enum:["host"]},tcpType:{type:"string",enum:["passive"],nullable:!0}},required:["foundation","priority","ip","address","protocol","port","type"],additionalProperties:!1},ME1={type:"object",properties:{usernameFragment:{type:"string"},password:{type:"string"},iceLite:{type:"boolean",nullable:!0}},required:["usernameFragment","password"],additionalProperties:!1},RE1={type:"object",properties:{i:{type:"string"},l:{type:"string"}},required:["i","l"],additionalProperties:!1},OE1={type:"object",properties:{port:{type:"number"},OS:{type:"number"},MIS:{type:"number"},maxMessageSize:{type:"number"}},required:["port","OS","MIS","maxMessageSize"],additionalProperties:!0},NE1={type:"object",properties:{streamId:{type:"number"},ordered:{type:"boolean",nullable:!0},maxPacketLifeTime:{type:"number",nullable:!0},maxRetransmits:{type:"number",nullable:!0}},required:["streamId"],additionalProperties:!1},PE1={type:"object",properties:{i:{type:"string"},f:{type:"string",enum:["cs","sc"]},ip:ME1,ic:{type:"array",items:DE1},d:P00,s:OE1},required:["i","f","ip","ic","d","s"],additionalProperties:!1},TE1={type:"object",properties:{i:{type:"string"},d:P00},required:["i","d"],additionalProperties:!1},CE1={type:"object",properties:{i:{type:"string",nullable:!0},pi:{type:"string",nullable:!0},l:{type:"string"},s:NE1},required:["l","s"],additionalProperties:!1},mN={type:"object",properties:{i:{type:"string",nullable:!0},k:{type:"boolean",nullable:!0},c:{...TE1,nullable:!0},ca:{...LE1,nullable:!0},d:{type:"array",items:{...CE1},nullable:!0},pa:{...RE1,nullable:!0},t:{type:"array",items:{...PE1},nullable:!0}},additionalProperties:!1};var T00=f0(116,mN);var uN={type:"null",nullable:!0};var C00=f0(117,uN);var Cw={};_Q(Cw,{uiDataSendPacketDefinition:()=>b00,syncRequestPacketDefinition:()=>_00,stateRequestPacketDefinition:()=>I00,inputPacketDefinition:()=>E00,debugConfigPacketDefinition:()=>k00,chatMessageSendPacketDefinition:()=>f00});var lN={type:"string",pattern:"^[0-9A-Fa-f]{6}$"};var Lz={type:"object",properties:{m:{type:"string"},c:{...lN,nullable:!0},p:{type:"string",nullable:!0}},required:["m"],additionalProperties:!1};var f00=f0(3,Lz);var yN={type:"object",properties:{pdr:{type:"boolean",nullable:!0}},additionalProperties:!1};var k00=f0(128,yN);var pN={type:"object",properties:{"1":{type:"boolean",nullable:!0},"2":{type:"boolean",nullable:!0},"3":{type:"boolean",nullable:!0},"4":{type:"boolean",nullable:!0},"5":{type:"boolean",nullable:!0},"6":{type:"boolean",nullable:!0},"7":{type:"boolean",nullable:!0},"8":{type:"boolean",nullable:!0},"9":{type:"boolean",nullable:!0},"0":{type:"boolean",nullable:!0},w:{type:"boolean",nullable:!0},a:{type:"boolean",nullable:!0},s:{type:"boolean",nullable:!0},d:{type:"boolean",nullable:!0},q:{type:"boolean",nullable:!0},e:{type:"boolean",nullable:!0},r:{type:"boolean",nullable:!0},f:{type:"boolean",nullable:!0},z:{type:"boolean",nullable:!0},x:{type:"boolean",nullable:!0},c:{type:"boolean",nullable:!0},v:{type:"boolean",nullable:!0},u:{type:"boolean",nullable:!0},i:{type:"boolean",nullable:!0},o:{type:"boolean",nullable:!0},j:{type:"boolean",nullable:!0},k:{type:"boolean",nullable:!0},l:{type:"boolean",nullable:!0},n:{type:"boolean",nullable:!0},m:{type:"boolean",nullable:!0},sp:{type:"boolean",nullable:!0},sh:{type:"boolean",nullable:!0},tb:{type:"boolean",nullable:!0},ml:{type:"boolean",nullable:!0},mr:{type:"boolean",nullable:!0},cp:{type:"number",nullable:!0},cy:{type:"number",nullable:!0},sq:{type:"number",nullable:!0}},additionalProperties:!1};var E00=f0(1,pN);var iN={type:"object",properties:{},additionalProperties:!1};var I00=f0(2,iN);var gN={type:"null",nullable:!0};var _00=f0(0,gN);var Dz={type:"object",properties:{},additionalProperties:!0};var b00=f0(4,Dz);var fw={};_Q(fw,{worldPacketDefinition:()=>t00,uiPacketDefinition:()=>o00,uiDatasPacketDefinition:()=>r00,syncResponsePacketDefinition:()=>s00,sceneUIsPacketDefinition:()=>n00,playersPacketDefinition:()=>a00,physicsDebugRenderPacketDefinition:()=>g00,physicsDebugRaycastsPacketDefinition:()=>d00,particleEmittersPacketDefinition:()=>i00,lightsPacketDefinition:()=>p00,entitiesPacketDefinition:()=>y00,chunksPacketDefinition:()=>l00,chatMessagesPacketDefinition:()=>u00,cameraPacketDefinition:()=>m00,blocksPacketDefinition:()=>S00,blockTypesPacketDefinition:()=>A00,audiosPacketDefinition:()=>h00});var W1={type:"array",items:[{type:"number"},{type:"number"},{type:"number"}],minItems:3,maxItems:3};var dN={type:"object",properties:{i:{type:"number"},a:{type:"string",nullable:!0},cd:{type:"number",nullable:!0},d:{type:"number",nullable:!0},de:{type:"number",nullable:!0},di:{type:"number",minimum:0,nullable:!0},e:{type:"number",nullable:!0},l:{type:"boolean",nullable:!0},o:{type:"number",nullable:!0},p:{...W1,nullable:!0},pa:{type:"boolean",nullable:!0},pl:{type:"boolean",nullable:!0},pr:{type:"number",minimum:0,nullable:!0},r:{type:"boolean",nullable:!0},rd:{type:"number",nullable:!0},s:{type:"number",nullable:!0},v:{type:"number",minimum:0,maximum:1,nullable:!0}},required:["i"],additionalProperties:!1};var aN={type:"array",items:{...dN}};var h00=f0(33,aN);var nN={type:"object",properties:{i:{type:"number"},c:W1},required:["i","c"],additionalProperties:!1};var sN={type:"array",items:{...nN}};var S00=f0(34,sN);var oN={type:"object",properties:{i:{type:"number"},l:{type:"boolean",nullable:!0},ll:{type:"number",nullable:!0},n:{type:"string",nullable:!0},t:{type:"string",nullable:!0}},required:["i"],additionalProperties:!1};var rN={type:"array",items:{...oN}};var A00=f0(35,rN);var tN={type:"object",properties:{m:{type:"number",nullable:!0},e:{type:"number",nullable:!0},et:{type:"number",nullable:!0},fo:{type:"number",nullable:!0},ffo:{type:"number",nullable:!0},fv:{type:"number",nullable:!0},h:{type:"array",items:{type:"string"},nullable:!0},o:{...W1,nullable:!0},p:{...W1,nullable:!0},pt:{...W1,nullable:!0},pl:{...W1,nullable:!0},s:{type:"array",items:{type:"string"},nullable:!0},sa:{type:"number",nullable:!0},z:{type:"number",nullable:!0}},additionalProperties:!1};var eN={type:"array",items:{...Lz}};var ZP={type:"object",properties:{c:W1,b:{type:"array",items:{type:"number",minimum:0,maximum:255},minItems:4096,maxItems:4096,nullable:!0},rm:{type:"boolean",nullable:!0}},required:["c"],additionalProperties:!1};var JP={type:"array",items:{...ZP}};var D6={type:"array",items:[{type:"number",minimum:0,maximum:255},{type:"number",minimum:0,maximum:255},{type:"number",minimum:0,maximum:255}],minItems:3,maxItems:3};var XP={type:"object",properties:{n:{type:"string"},h:{type:"boolean",nullable:!0},o:{type:"number",minimum:0,maximum:1,nullable:!0},r:{type:"boolean",nullable:!0},s:{type:"number",nullable:!0},t:{...D6,nullable:!0}},required:["n"],additionalProperties:!1};var $P={type:"array",items:[{type:"number"},{type:"number"},{type:"number"},{type:"number"}],minItems:4,maxItems:4};var YP={type:"object",properties:{i:{type:"number"},al:{type:"array",items:{type:"string"},nullable:!0},ao:{type:"array",items:{type:"string"},nullable:!0},ap:{type:"number",nullable:!0},as:{type:"array",items:{type:"string"},nullable:!0},bh:{...W1,nullable:!0},bt:{type:"string",nullable:!0},h:{type:"array",items:{type:"string"},nullable:!0},m:{type:"string",nullable:!0},mo:{type:"array",items:{...XP},nullable:!0},mt:{type:"string",nullable:!0},n:{type:"string",nullable:!0},o:{type:"number",nullable:!0},p:{...W1,nullable:!0},pe:{type:"number",nullable:!0},pn:{type:"string",nullable:!0},r:{...$P,nullable:!0},rm:{type:"boolean",nullable:!0},s:{type:"number",nullable:!0},sn:{type:"array",items:{type:"string"},nullable:!0},t:{...D6,nullable:!0}},required:["i"],additionalProperties:!1};var QP={type:"array",items:{...YP}};var KP={type:"object",properties:{i:{type:"number"},a:{type:"number",nullable:!0},e:{type:"number",nullable:!0},c:{...D6,nullable:!0},d:{type:"number",nullable:!0},n:{type:"number",nullable:!0},o:{...W1,nullable:!0},p:{...W1,nullable:!0},pe:{type:"number",minimum:0,maximum:1,nullable:!0},rm:{type:"boolean",nullable:!0},t:{type:"number",nullable:!0},te:{type:"number",nullable:!0},tp:{...W1,nullable:!0}},required:["i"],additionalProperties:!1};var WP={type:"array",items:{...KP}};var GP={type:"object",properties:{i:{type:"number"},at:{type:"number",nullable:!0},b:{type:"number",nullable:!0},ce:{...D6,nullable:!0},cev:{...D6,nullable:!0},cs:{...D6,nullable:!0},csv:{...D6,nullable:!0},e:{type:"number",nullable:!0},en:{type:"string",nullable:!0},g:{...W1,nullable:!0},l:{type:"number",nullable:!0},lv:{type:"number",nullable:!0},mp:{type:"number",nullable:!0},o:{...W1,nullable:!0},oe:{type:"number",nullable:!0},oev:{type:"number",nullable:!0},os:{type:"number",nullable:!0},osv:{type:"number",nullable:!0},p:{...W1,nullable:!0},pa:{type:"boolean",nullable:!0},pv:{...W1,nullable:!0},r:{type:"number",nullable:!0},rv:{type:"number",nullable:!0},rm:{type:"boolean",nullable:!0},se:{type:"number",nullable:!0},sev:{type:"number",nullable:!0},ss:{type:"number",nullable:!0},ssv:{type:"number",nullable:!0},t:{type:"boolean",nullable:!0},tu:{type:"string",nullable:!0},v:{...W1,nullable:!0},vv:{...W1,nullable:!0}},required:["i"],additionalProperties:!1};var zP={type:"array",items:{...GP}};var VP={type:"object",properties:{o:{...W1},d:{...W1},l:{type:"number"},h:{type:"boolean"}},required:["o","d","l","h"],additionalProperties:!1};var vP={type:"array",items:{...VP}};var HP={type:"object",properties:{v:{type:"array",items:{type:"number"}},c:{type:"array",items:{type:"number"}}},required:["v","c"],additionalProperties:!1};var qP={type:"object",properties:{i:{type:"string"},p:{type:"string",nullable:!0},rm:{type:"boolean",nullable:!0},u:{type:"string",nullable:!0}},required:["i"],additionalProperties:!1};var FP={type:"array",items:{...qP}};var cP={type:"object",properties:{i:{type:"number"},e:{type:"number",nullable:!0},o:{...W1,nullable:!0},p:{...W1,nullable:!0},rm:{type:"boolean",nullable:!0},s:{type:"object",nullable:!0},t:{type:"string",nullable:!0},v:{type:"number",nullable:!0}},required:["i"],additionalProperties:!1};var wP={type:"array",items:{...cP}};var xP={type:"object",properties:{r:{type:"number"},s:{type:"number"},p:{type:"number"},n:{type:"number"}},required:["r","s","p","n"],additionalProperties:!1};var UP={type:"object",properties:{p:{type:"boolean",nullable:!0},u:{type:"string",nullable:!0}},additionalProperties:!1};var jP={type:"array",items:{...Dz}};var fE1={type:"array",items:[{type:"boolean"},{type:"boolean"},{type:"boolean"}],minItems:3,maxItems:3};var BP={type:"object",properties:{i:{type:"number"},ac:{...D6,nullable:!0},ai:{type:"number",nullable:!0},dc:{...D6,nullable:!0},di:{type:"number",nullable:!0},dp:{...W1,nullable:!0},fc:{...D6,nullable:!0},ff:{type:"number",nullable:!0},fn:{type:"number",nullable:!0},n:{type:"string",nullable:!0},s:{type:"string",nullable:!0},si:{type:"number",nullable:!0},t:{type:"number",nullable:!0}},required:["i"],additionalProperties:!1};var m00=f0(40,tN);var u00=f0(36,eN);var l00=f0(37,JP);var y00=f0(38,QP);var p00=f0(44,WP);var i00=f0(46,zP);var g00=f0(192,HP);var d00=f0(193,vP);var a00=f0(45,FP);var n00=f0(43,wP);var s00=f0(32,xP);var o00=f0(41,UP);var r00=f0(42,jP);var t00=f0(39,BP);var kw=new Map,kE1={...Tw,...Cw,...fw};for(let Z of Object.values(kE1))if("id"in Z&&"schema"in Z){let J=Z;if(kw.has(J.id))throw new Error(`Packet with id ${J.id} is already registered.`);kw.set(J.id,J)}function EE1(Z){if(typeof Z!=="object"||Z===null||typeof Z[0]!=="number"||Z[0]<0||Z[1]===void 0||Z[2]!==void 0&&(typeof Z[2]!=="number"||Z[2]<0))return!1;let J=kw.get(Z[0]);return!!J&&J.validate(Z[1])}var Y0=LP;var Y60=t(N10(),1);import e$ from"fs";import X60 from"path";var B_1=t(L80(),1),L_1=t(EP(),1),D_1=t(_P(),1),t$=t(yw(),1),lP=t(T80(),1);var C80=t$.default;function U5(Z){if(Z===null)return"null";if(Array.isArray(Z))return"array";return typeof Z}function YX(Z){return U5(Z)==="object"}function M_1(Z){return Array.isArray(Z)&&Z.length>0&&Z.every((J)=>("message"in J))}function yP(Z,J){return Z.length<124?Z:J}var f80="graphql-transport-ws";var l5=((Z)=>{return Z[Z.InternalServerError=4500]="InternalServerError",Z[Z.InternalClientError=4005]="InternalClientError",Z[Z.BadRequest=4400]="BadRequest",Z[Z.BadResponse=4004]="BadResponse",Z[Z.Unauthorized=4401]="Unauthorized",Z[Z.Forbidden=4403]="Forbidden",Z[Z.SubprotocolNotAcceptable=4406]="SubprotocolNotAcceptable",Z[Z.ConnectionInitialisationTimeout=4408]="ConnectionInitialisationTimeout",Z[Z.ConnectionAcknowledgementTimeout=4504]="ConnectionAcknowledgementTimeout",Z[Z.SubscriberAlreadyExists=4409]="SubscriberAlreadyExists",Z[Z.TooManyInitialisationRequests=4429]="TooManyInitialisationRequests",Z})(l5||{}),y5=((Z)=>{return Z.ConnectionInit="connection_init",Z.ConnectionAck="connection_ack",Z.Ping="ping",Z.Pong="pong",Z.Subscribe="subscribe",Z.Next="next",Z.Error="error",Z.Complete="complete",Z})(y5||{});function k80(Z){if(!YX(Z))throw new Error(`Message is expected to be an object, but got ${U5(Z)}`);if(!Z.type)throw new Error("Message is missing the 'type' property");if(typeof Z.type!=="string")throw new Error(`Message is expects the 'type' property to be a string, but got ${U5(Z.type)}`);switch(Z.type){case"connection_init":case"connection_ack":case"ping":case"pong":{if(Z.payload!=null&&!YX(Z.payload))throw new Error(`"${Z.type}" message expects the 'payload' property to be an object or nullish or missing, but got "${Z.payload}"`);break}case"subscribe":{if(typeof Z.id!=="string")throw new Error(`"${Z.type}" message expects the 'id' property to be a string, but got ${U5(Z.id)}`);if(!Z.id)throw new Error(`"${Z.type}" message requires a non-empty 'id' property`);if(!YX(Z.payload))throw new Error(`"${Z.type}" message expects the 'payload' property to be an object, but got ${U5(Z.payload)}`);if(typeof Z.payload.query!=="string")throw new Error(`"${Z.type}" message payload expects the 'query' property to be a string, but got ${U5(Z.payload.query)}`);if(Z.payload.variables!=null&&!YX(Z.payload.variables))throw new Error(`"${Z.type}" message payload expects the 'variables' property to be a an object or nullish or missing, but got ${U5(Z.payload.variables)}`);if(Z.payload.operationName!=null&&U5(Z.payload.operationName)!=="string")throw new Error(`"${Z.type}" message payload expects the 'operationName' property to be a string or nullish or missing, but got ${U5(Z.payload.operationName)}`);if(Z.payload.extensions!=null&&!YX(Z.payload.extensions))throw new Error(`"${Z.type}" message payload expects the 'extensions' property to be a an object or nullish or missing, but got ${U5(Z.payload.extensions)}`);break}case"next":{if(typeof Z.id!=="string")throw new Error(`"${Z.type}" message expects the 'id' property to be a string, but got ${U5(Z.id)}`);if(!Z.id)throw new Error(`"${Z.type}" message requires a non-empty 'id' property`);if(!YX(Z.payload))throw new Error(`"${Z.type}" message expects the 'payload' property to be an object, but got ${U5(Z.payload)}`);break}case"error":{if(typeof Z.id!=="string")throw new Error(`"${Z.type}" message expects the 'id' property to be a string, but got ${U5(Z.id)}`);if(!Z.id)throw new Error(`"${Z.type}" message requires a non-empty 'id' property`);if(!M_1(Z.payload))throw new Error(`"${Z.type}" message expects the 'payload' property to be an array of GraphQL errors, but got ${JSON.stringify(Z.payload)}`);break}case"complete":{if(typeof Z.id!=="string")throw new Error(`"${Z.type}" message expects the 'id' property to be a string, but got ${U5(Z.id)}`);if(!Z.id)throw new Error(`"${Z.type}" message requires a non-empty 'id' property`);break}default:throw new Error(`Invalid message 'type' property "${Z.type}"`)}return Z}function E80(Z,J){return k80(typeof Z==="string"?JSON.parse(Z,J):Z)}function i3(Z,J){return k80(Z),JSON.stringify(Z,J)}function iP(Z){let{url:J,connectionParams:X,lazy:$=!0,onNonLazyError:Y=console.error,lazyCloseTimeout:Q=0,keepAlive:K=0,disablePong:W,connectionAckWaitTimeout:G=0,retryAttempts:z=5,retryWait:V=async function C(b){let I=Math.pow(2,b);await new Promise((a)=>setTimeout(a,I*1000+Math.floor(Math.random()*2700+300)))},shouldRetry:H=pP,on:v,webSocketImpl:q,generateID:F=function C(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(b)=>{let I=Math.random()*16|0;return(b=="x"?I:I&3|8).toString(16)})},jsonMessageReplacer:c,jsonMessageReviver:w}=Z,x;if(q){if(!O_1(q))throw new Error("Invalid WebSocket implementation provided");x=q}else if(typeof WebSocket!=="undefined")x=WebSocket;else if(typeof global!=="undefined")x=global.WebSocket||global.MozWebSocket;else if(typeof window!=="undefined")x=window.WebSocket||window.MozWebSocket;if(!x)throw new Error("WebSocket implementation missing; on Node you can `import WebSocket from 'ws';` and pass `webSocketImpl: WebSocket` to `createClient`");let j=x,B=(()=>{let C=(()=>{let I={};return{on(a,s){return I[a]=s,()=>{delete I[a]}},emit(a){if("id"in a)I[a.id]?.(a)}}})(),b={connecting:v?.connecting?[v.connecting]:[],opened:v?.opened?[v.opened]:[],connected:v?.connected?[v.connected]:[],ping:v?.ping?[v.ping]:[],pong:v?.pong?[v.pong]:[],message:v?.message?[C.emit,v.message]:[C.emit],closed:v?.closed?[v.closed]:[],error:v?.error?[v.error]:[]};return{onMessage:C.on,on(I,a){let s=b[I];return s.push(a),()=>{s.splice(s.indexOf(a),1)}},emit(I,...a){for(let s of[...b[I]])s(...a)}}})();function L(C){let b=[B.on("error",(I)=>{b.forEach((a)=>a()),C(I)}),B.on("closed",(I)=>{b.forEach((a)=>a()),C(I)})]}let R,M=0,O,P=!1,N=0,_=!1;async function k(){clearTimeout(O);let[C,b]=await(R??(R=new Promise((s,Z0)=>(async()=>{if(P){if(await V(N),!M)return R=void 0,Z0({code:1000,reason:"All Subscriptions Gone"});N++}B.emit("connecting",P);let o=new j(typeof J==="function"?await J():J,f80),M0,R0;function m0(){if(isFinite(K)&&K>0)clearTimeout(R0),R0=setTimeout(()=>{if(o.readyState===j.OPEN)o.send(i3({type:y5.Ping})),B.emit("ping",!1,void 0)},K)}L((s0)=>{if(R=void 0,clearTimeout(M0),clearTimeout(R0),Z0(s0),s0 instanceof iw)o.close(4499,"Terminated"),o.onerror=null,o.onclose=null}),o.onerror=(s0)=>B.emit("error",s0),o.onclose=(s0)=>B.emit("closed",s0),o.onopen=async()=>{try{B.emit("opened",o);let s0=typeof X==="function"?await X():X;if(o.readyState!==j.OPEN)return;if(o.send(i3(s0?{type:y5.ConnectionInit,payload:s0}:{type:y5.ConnectionInit},c)),isFinite(G)&&G>0)M0=setTimeout(()=>{o.close(l5.ConnectionAcknowledgementTimeout,"Connection acknowledgement timeout")},G);m0()}catch(s0){B.emit("error",s0),o.close(l5.InternalClientError,yP(s0 instanceof Error?s0.message:String(s0),"Internal client error"))}};let O1=!1;o.onmessage=({data:s0})=>{try{let j1=E80(s0,w);if(B.emit("message",j1),j1.type==="ping"||j1.type==="pong"){if(B.emit(j1.type,!0,j1.payload),j1.type==="pong")m0();else if(!W)o.send(i3(j1.payload?{type:y5.Pong,payload:j1.payload}:{type:y5.Pong})),B.emit("pong",!1,j1.payload);return}if(O1)return;if(j1.type!==y5.ConnectionAck)throw new Error(`First message cannot be of type ${j1.type}`);clearTimeout(M0),O1=!0,B.emit("connected",o,j1.payload,P),P=!1,N=0,s([o,new Promise((W4,NJ)=>L(NJ))])}catch(j1){o.onmessage=null,B.emit("error",j1),o.close(l5.BadResponse,yP(j1 instanceof Error?j1.message:String(j1),"Bad response"))}}})())));if(C.readyState===j.CLOSING)await b;let I=()=>{},a=new Promise((s)=>I=s);return[C,I,Promise.race([a.then(()=>{if(!M){let s=()=>C.close(1000,"Normal Closure");if(isFinite(Q)&&Q>0)O=setTimeout(()=>{if(C.readyState===j.OPEN)s()},Q);else s()}}),b])]}function h(C){if(pP(C)&&(R_1(C.code)||[l5.InternalServerError,l5.InternalClientError,l5.BadRequest,l5.BadResponse,l5.Unauthorized,l5.SubprotocolNotAcceptable,l5.SubscriberAlreadyExists,l5.TooManyInitialisationRequests].includes(C.code)))throw C;if(_)return!1;if(pP(C)&&C.code===1000)return M>0;if(!z||N>=z)throw C;if(!H(C))throw C;return P=!0}if(!$)(async()=>{M++;for(;;)try{let[,,C]=await k();await C}catch(C){try{if(!h(C))return}catch(b){return Y?.(b)}}})();function f(C,b){let I=F(C),a=!1,s=!1,Z0=()=>{M--,a=!0};return(async()=>{M++;for(;;)try{let[o,M0,R0]=await k();if(a)return M0();let m0=B.onMessage(I,(O1)=>{switch(O1.type){case y5.Next:{b.next(O1.payload);return}case y5.Error:{s=!0,a=!0,b.error(O1.payload),Z0();return}case y5.Complete:{a=!0,Z0();return}}});o.send(i3({id:I,type:y5.Subscribe,payload:C},c)),Z0=()=>{if(!a&&o.readyState===j.OPEN)o.send(i3({id:I,type:y5.Complete},c));M--,a=!0,M0()},await R0.finally(m0);return}catch(o){if(!h(o))return}})().then(()=>{if(!s)b.complete()}).catch((o)=>{b.error(o)}),()=>{if(!a)Z0()}}return{on:B.on,subscribe:f,iterate(C){let b=[],I={done:!1,error:null,resolve:()=>{}},a=f(C,{next(Z0){b.push(Z0),I.resolve()},error(Z0){I.done=!0,I.error=Z0,I.resolve()},complete(){I.done=!0,I.resolve()}}),s=async function*Z0(){for(;;){if(!b.length)await new Promise((o)=>I.resolve=o);while(b.length)yield b.shift();if(I.error)throw I.error;if(I.done)return}}();return s.throw=async(Z0)=>{if(!I.done)I.done=!0,I.error=Z0,I.resolve();return{done:!0,value:void 0}},s.return=async()=>{return a(),{done:!0,value:void 0}},s},async dispose(){if(_=!0,R){let[C]=await R;C.close(1000,"Normal Closure")}},terminate(){if(R)B.emit("closed",new iw)}}}class iw extends Error{name="TerminatedCloseEvent";message="4499: Terminated";code=4499;reason="Terminated";wasClean=!1}function pP(Z){return YX(Z)&&"code"in Z&&"reason"in Z}function R_1(Z){if([1000,1001,1006,1005,1012,1013,1014].includes(Z))return!1;return Z>=1000&&Z<=1999}function O_1(Z){return typeof Z==="function"&&"constructor"in Z&&"CLOSED"in Z&&"CLOSING"in Z&&"CONNECTING"in Z&&"OPEN"in Z}var $60=t(J60(),1);var Ez="./dev/persistence";class F7{static instance=new F7;gameId=process.env.HYTOPIA_GAME_ID;lobbyId=process.env.HYTOPIA_LOBBY_ID;_creativeGateway;_gqlWs;constructor(){this._gqlWs=iP({url:"wss://prod.gql.hytopia.com/graphql",webSocketImpl:C80});try{this._creativeGateway=new $60.CreativeGateway}catch{console.warn(["━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━","\uD83D\uDEA8 HYTOPIA PLATFORM GATEWAY IS NOT INITIALIZED \uD83D\uDEA8","","\uD83D\uDD27 Local development is still possible, but these features will be disabled:"," • \uD83D\uDC64 Player Accounts"," • \uD83C\uDFAD Player Cosmetics"," • \uD83D\uDC1B Crash Analytics & Debug Logs","","\uD83D\uDCA1 These features will be enabled but modified:"," • \uD83D\uDCBE Player & Global Persisted Data - Data will be persisted"," locally in the ./dev/persistence directory of your project."," Player ids for data persistence will begin at 1 for the first "," player to join your local server, and increments for each"," additional player. This means that if you restart your"," server, the first player id will be 1 again. This is to ensure"," that data persistence across server restarts can be easily"," tested and debugged in local development.","","To enable the HYTOPIA Platform Gateway locally:"," 1. Set these environment variables:"," HYTOPIA_API_KEY, HYTOPIA_GAME_ID, HYTOPIA_LOBBY_ID"," 2. You can find these values at: https://create.hytopia.com","","Note: In production, these environment variables will be auto-populated ","& the HYTOPIA Platform Gateway will automatically be initialized \uD83D\uDE80","━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",""].join(`
400
- `))}}get isGatewayAvailable(){return!!this._creativeGateway}async getGlobalData(Z){if(!this._creativeGateway&&process.env.NODE_ENV==="production")return p.warning("PlatformGateway.getData(): You are running in production mode, but the Platform Gateway is not initialized! No data will be returned."),{error:{code:"gatewayError",message:"Platform Gateway is not initialized."}};return this._creativeGateway?await this._creativeGateway.kv.get(Z):this._readDevGlobalDataLocally(Z)}async getPlayerCosmetics(Z){let J=this._gqlWs.iterate({query:`{
400
+ `))}}get isGatewayAvailable(){return!!this._creativeGateway}async getGlobalData(Z){if(!this._creativeGateway&&process.env.NODE_ENV==="production")return p.warning("PlatformGateway.getGlobalData(): You are running in production mode, but the Platform Gateway is not initialized! No data will be returned."),{error:{code:"gatewayError",message:"Platform Gateway is not initialized."}};return this._creativeGateway?await this._creativeGateway.kv.get(Z):this._readDevGlobalDataLocally(Z)}async getPlayerCosmetics(Z){let J=this._gqlWs.iterate({query:`{
401
401
  userById(id: "${Z}") {
402
402
  characterSettings { skinTone hairColor eyeColor hairStyle }
403
403
  equippedItems { slot item { slots { flags type modelUrl textureUrl } } }
404
404
  }
405
- }`});try{let $=(await J.next()).value?.data?.userById;if(!$)return p.warning(`PlatformGateway.getPlayerCosmetics(): No cosmetic data returned for user id "${Z}".`);let Y=$.equippedItems.map((W)=>({slot:W.slot,item:W.item.slots.find((G)=>G.type===W.slot)})).filter((W)=>!!W.item),Q=Number($.characterSettings?.hairStyle?.split("_")[1]||1),K=`https://d3qkovarww0lj1.cloudfront.net/?skin_tone=${$.characterSettings?.skinTone||"SKIN_COLOR_1"}&clothing=${$.characterSettings?.clothing||"CLOTHING_1"}&hair_style=${$.characterSettings?.hairStyle||"HAIR_STYLE_1"}&hair_color=${$.characterSettings?.hairColor||"HAIR_COLOR_1"}&eye_color=${$.characterSettings?.eyeColor||"00FF00"}`;return{equippedItems:Y,hairStyle:Q,skinTextureUri:K}}finally{await J.return?.()}}async getPlayerSession(Z){if(!this._creativeGateway)return;return await this._creativeGateway.getSession(Z)}async setGlobalData(Z,J){if(J.error)return p.warning("PlatformGateway.setData(): Cannot set data with an error property.");if(!this._creativeGateway&&process.env.NODE_ENV==="production")return p.warning("PlatformGateway.setData(): You are running in production mode, but the Platform Gateway is not initialized! No data will be set.");return this._creativeGateway?await this._creativeGateway.kv.set(Z,J):this._writeDevGlobalDataLocally(Z,J)}_readDevGlobalDataLocally(Z){try{if(!e$.existsSync(Ez))return{error:{code:"keyNotFound",message:"Local data directory not found."}};let J=X60.join(Ez,`${Z}.json`);return JSON.parse(e$.readFileSync(J,"utf8"))}catch(J){return p.warning(`PlatformGateway._readDevDataLocally(): Failed to read data for key "${Z}": ${J}`),{error:{code:"gatewayError",message:"Failed to read data for key."}}}}_writeDevGlobalDataLocally(Z,J){try{if(!e$.existsSync(Ez))e$.mkdirSync(Ez,{recursive:!0});let X=X60.join(Ez,`${Z}.json`),$={};if(e$.existsSync(X))$=JSON.parse(e$.readFileSync(X,"utf8"));let Y={...$,...J};e$.writeFileSync(X,JSON.stringify(Y,null,2),"utf8")}catch(X){p.warning(`PlatformGateway._writeDevDataLocally(): Failed to write data for key "${Z}": ${X}`)}}}class g3{static instance=new g3;_saveStatesClient;_playerData=new Map;constructor(){this._saveStatesClient=new Y60.SaveStatesClient}async getGlobalData(Z,J=3){for(let X=0;X<=J;X++){let $=await F7.instance.getGlobalData(Z);if($&&!$.error)return $;if($.error.code==="keyNotFound")return{};if(X<J)p.warning(`PersistenceManager.getGlobalData(): Failed to get global data, retrying. Response: ${JSON.stringify($)}`),await new Promise((Y)=>setTimeout(Y,500))}p.warning(`PersistenceManager.getGlobalData(): Failed to get global data after ${J} attempts.`);return}async getPlayerData(Z){let J=this._playerData.get(Z.id);if(!J)J=await this._saveStatesClient.load(this._getPlayerKey(Z)),this._playerData.set(Z.id,J);return J}async setGlobalData(Z,J){let X=await F7.instance.setGlobalData(Z,J);if(!X||X.error){if(X?.error)p.warning(`PersistenceManager.setGlobalData(): ${X.error.message}`)}}async setPlayerData(Z,J){let X=await this.getPlayerData(Z);for(let[$,Y]of Object.entries(J))X[$]=Y}_getPlayerKey(Z){return`player-${Z.id}`}}var Q60;(($)=>{$[$.FIRST_PERSON=0]="FIRST_PERSON";$[$.THIRD_PERSON=1]="THIRD_PERSON";$[$.SPECTATOR=2]="SPECTATOR"})(Q60||={});var dP;((c)=>{c.LOOK_AT_ENTITY="PLAYER_CAMERA.LOOK_AT_ENTITY";c.LOOK_AT_POSITION="PLAYER_CAMERA.LOOK_AT_POSITION";c.SET_ATTACHED_TO_ENTITY="PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY";c.SET_ATTACHED_TO_POSITION="PLAYER_CAMERA.SET_ATTACHED_TO_POSITION";c.SET_FILM_OFFSET="PLAYER_CAMERA.SET_FILM_OFFSET";c.SET_FORWARD_OFFSET="PLAYER_CAMERA.SET_FORWARD_OFFSET";c.SET_FOV="PLAYER_CAMERA.SET_FOV";c.SET_MODEL_HIDDEN_NODES="PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES";c.SET_MODEL_SHOWN_NODES="PLAYER_CAMERA.SET_MODEL_SHOWN_NODES";c.SET_MODE="PLAYER_CAMERA.SET_MODE";c.SET_OFFSET="PLAYER_CAMERA.SET_OFFSET";c.SET_SHOULDER_ANGLE="PLAYER_CAMERA.SET_SHOULDER_ANGLE";c.SET_TRACKED_ENTITY="PLAYER_CAMERA.SET_TRACKED_ENTITY";c.SET_TRACKED_POSITION="PLAYER_CAMERA.SET_TRACKED_POSITION";c.SET_ZOOM="PLAYER_CAMERA.SET_ZOOM"})(dP||={});class Iz extends j0{player;_attachedToEntity;_attachedToPosition;_filmOffset=0;_forwardOffset=0;_fov=75;_modelHiddenNodes=new Set;_modelShownNodes=new Set;_mode=1;_offset={x:0,y:0,z:0};_orientation={pitch:0,yaw:0};_shoulderAngle=0;_trackedEntity;_trackedPosition;_zoom=1;constructor(Z){super();this.player=Z}get attachedToEntity(){return this._attachedToEntity}get attachedToPosition(){return this._attachedToPosition}get facingDirection(){return{x:-Math.sin(this._orientation.yaw)*Math.cos(this._orientation.pitch),y:Math.sin(this._orientation.pitch),z:-Math.cos(this._orientation.yaw)*Math.cos(this._orientation.pitch)}}get facingQuaternion(){let Z=this._orientation.pitch*0.5,J=this._orientation.yaw*0.5,X=Math.cos(Z),$=Math.sin(Z),Y=Math.cos(J),Q=Math.sin(J);return{x:$*Y,y:X*Q,z:-$*Q,w:X*Y}}get filmOffset(){return this._filmOffset}get forwardOffset(){return this._forwardOffset}get fov(){return this._fov}get modelHiddenNodes(){return this._modelHiddenNodes}get modelShownNodes(){return this._modelShownNodes}get mode(){return this._mode}get offset(){return this._offset}get orientation(){return this._orientation}get shoulderAngle(){return this._shoulderAngle}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get zoom(){return this._zoom}lookAtEntity(Z){if(!this._requirePlayerWorld("lookAtEntity"))return;this.emitWithWorld(this.player.world,"PLAYER_CAMERA.LOOK_AT_ENTITY",{playerCamera:this,entity:Z})}lookAtPosition(Z){if(!this._requirePlayerWorld("lookAtPosition"))return;this.emitWithWorld(this.player.world,"PLAYER_CAMERA.LOOK_AT_POSITION",{playerCamera:this,position:Z})}reset(){this._attachedToEntity=void 0,this._attachedToPosition=void 0,this._orientation={pitch:0,yaw:0},this._trackedEntity=void 0,this._trackedPosition=void 0}setAttachedToEntity(Z){if(!this._requirePlayerWorld("setAttachedToEntity"))return;if(!Z.isSpawned)return p.error(`PlayerCamera.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);this._attachedToEntity=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",{playerCamera:this,entity:Z})}setAttachedToPosition(Z){if(!this._requirePlayerWorld("setAttachedToPosition"))return;this._attachedToPosition=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",{playerCamera:this,position:Z})}setFilmOffset(Z){if(!this._requirePlayerWorld("setFilmOffset"))return;this._filmOffset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FILM_OFFSET",{playerCamera:this,filmOffset:Z})}setForwardOffset(Z){if(!this._requirePlayerWorld("setForwardOffset"))return;this._forwardOffset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FORWARD_OFFSET",{playerCamera:this,forwardOffset:Z})}setFov(Z){if(!this._requirePlayerWorld("setFov"))return;this._fov=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FOV",{playerCamera:this,fov:Z})}setModelHiddenNodes(Z){if(!this._requirePlayerWorld("setModelHiddenNodes"))return;this._modelHiddenNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",{playerCamera:this,modelHiddenNodes:this._modelHiddenNodes})}setModelShownNodes(Z){if(!this._requirePlayerWorld("setModelShownNodes"))return;this._modelShownNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",{playerCamera:this,modelShownNodes:this._modelShownNodes})}setMode(Z){if(!this._requirePlayerWorld("setMode"))return;this._mode=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODE",{playerCamera:this,mode:Z})}setOffset(Z){if(!this._requirePlayerWorld("setOffset"))return;this._offset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_OFFSET",{playerCamera:this,offset:Z})}setOrientationPitch(Z){this._orientation.pitch=Z}setOrientationYaw(Z){this._orientation.yaw=Z}setShoulderAngle(Z){if(!this._requirePlayerWorld("setShoulderAngle"))return;this._shoulderAngle=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_SHOULDER_ANGLE",{playerCamera:this,shoulderAngle:Z})}setTrackedEntity(Z){if(!this._requirePlayerWorld("setTrackedEntity"))return;this._trackedEntity=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_ENTITY",{playerCamera:this,entity:Z})}setTrackedPosition(Z){if(!this._requirePlayerWorld("setTrackedPosition"))return;this._trackedPosition=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_POSITION",{playerCamera:this,position:Z})}setZoom(Z){if(!this._requirePlayerWorld("setZoom"))return;this._zoom=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ZOOM",{playerCamera:this,zoom:Z})}serialize(){return T0.serializePlayerCamera(this)}_requirePlayerWorld(Z){if(!this.player.world)p.error(`PlayerCamera._requirePlayerWorld(): Player ${this.player.id} is not in a world, invoked method: ${Z}()`);return!!this.player.world}}var dw;((Y)=>{Y.DATA="PLAYER_UI.DATA";Y.LOAD="PLAYER_UI.LOAD";Y.LOCK_POINTER="PLAYER_UI.LOCK_POINTER";Y.SEND_DATA="PLAYER_UI.SEND_DATA"})(dw||={});class _z extends j0{player;constructor(Z){super();this.player=Z}load(Z){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.LOAD",{playerUI:this,htmlUri:Z})}lockPointer(Z){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.LOCK_POINTER",{playerUI:this,lock:Z})}sendData(Z){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.SEND_DATA",{playerUI:this,data:Z})}}var K60=["w","a","s","d","sp","sh","tb","ml","mr","q","e","r","f","z","x","c","v","u","i","o","j","k","l","n","m","1","2","3","4","5","6","7","8","9","0"],bz;((Q)=>{Q.CHAT_MESSAGE_SEND="PLAYER.CHAT_MESSAGE_SEND";Q.JOINED_WORLD="PLAYER.JOINED_WORLD";Q.LEFT_WORLD="PLAYER.LEFT_WORLD";Q.RECONNECTED_WORLD="PLAYER.RECONNECTED_WORLD";Q.REQUEST_SYNC="PLAYER.REQUEST_SYNC"})(bz||={});class d3 extends j0{static _devNextPlayerId=1;id;username;profilePictureUrl;camera;connection;cosmetics;ui;_input={};_lastUnreliableInputSequenceNumber=0;_persistedData;_world;_worldSwitched=!1;constructor(Z,J){super();this.id=J?.user.id??`player-${d3._devNextPlayerId++}`,this.username=J?.user.username??this.id,this.profilePictureUrl=J?.user.profilePictureURL??void 0,this.camera=new Iz(this),this.connection=Z,this.cosmetics=F7.instance.getPlayerCosmetics(this.id),this.ui=new _z(this),Z.onPacket(Y0.PacketId.CHAT_MESSAGE_SEND,this._onChatMessageSendPacket),Z.onPacket(Y0.PacketId.DEBUG_CONFIG,this._onDebugConfigPacket),Z.onPacket(Y0.PacketId.INPUT,this._onInputPacket),Z.onPacket(Y0.PacketId.SYNC_REQUEST,this._onSyncRequestPacket),Z.onPacket(Y0.PacketId.UI_DATA_SEND,this._onUIDataSendPacket)}get input(){return this._input}get world(){return this._world}disconnect(){this._leaveWorld(),this.connection.disconnect()}getPersistedData(){return this._persistedData&&Object.keys(this._persistedData).length>1?this._persistedData:void 0}joinWorld(Z){if(this._world===Z)return;if(!this._world)this._world=Z,this.emitWithWorld(this._world,"PLAYER.JOINED_WORLD",{player:this,world:this._world});else{for(let J of this._world.entityManager.getPlayerEntitiesByPlayer(this))if(J.isSpawned)J.despawn();this.disconnect(),this._world=Z,this._worldSwitched=!0}}async loadInitialPersistedData(){if(this._persistedData)return;this._persistedData=await g3.instance.getPlayerData(this)}reconnected(){if(!this._world)return;if(this._lastUnreliableInputSequenceNumber=0,!this._worldSwitched)this.emitWithWorld(this._world,"PLAYER.RECONNECTED_WORLD",{player:this,world:this._world});else this._worldSwitched=!1,this.emitWithWorld(this._world,"PLAYER.JOINED_WORLD",{player:this,world:this._world})}resetInputs(){this._input={}}setPersistedData(Z){if(!this._persistedData){p.warning(`Player.setPersistedData(): Persisted data not found for player ${this.id}`);return}for(let[J,X]of Object.entries(Z))this._persistedData[J]=X}serialize(){return T0.serializePlayer(this)}_leaveWorld(){if(!this._world)return;this.emitWithWorld(this._world,"PLAYER.LEFT_WORLD",{player:this,world:this._world}),this._world=void 0}_onChatMessageSendPacket=(Z)=>{if(!this._world)return;let J=Z[1].m;if(this._world.chatManager.handleCommand(this,J)){this._world.chatManager.sendPlayerMessage(this,`Command Entered: ${J}`,"CCCCCC");return}if(this.id.startsWith("guest")){this._world.chatManager.sendPlayerMessage(this,"You need to create a HYTOPIA account to send messages in chat.","FFAA00");return}this.emitWithWorld(this._world,"PLAYER.CHAT_MESSAGE_SEND",{player:this,message:J})};_onDebugConfigPacket=(Z)=>{console.log(Z)};_onInputPacket=(Z)=>{let J=Z[1];if(J.sq!==void 0){if(J.sq<this._lastUnreliableInputSequenceNumber)return;this._lastUnreliableInputSequenceNumber=J.sq}if(K60.forEach((X)=>{let $=X;if(J[$]!==void 0)this._input[$]=Boolean(J[$])}),J.cp!==void 0)this.camera.setOrientationPitch(J.cp);if(J.cy!==void 0)this.camera.setOrientationYaw(J.cy)};_onSyncRequestPacket=()=>{if(this._world)this.emitWithWorld(this._world,"PLAYER.REQUEST_SYNC",{player:this,receivedAt:Date.now(),receivedAtMs:performance.now()})};_onUIDataSendPacket=(Z)=>{this.ui.emit("PLAYER_UI.DATA",{playerUI:this.ui,data:Z[1]})}}var aP;((X)=>{X.BROADCAST_MESSAGE="CHAT.BROADCAST_MESSAGE";X.PLAYER_MESSAGE="CHAT.PLAYER_MESSAGE"})(aP||={});class hz extends j0{_commandCallbacks={};_world;constructor(Z){super();this._world=Z,this._subscribeToPlayerEvents()}registerCommand(Z,J){this._commandCallbacks[Z]=J}unregisterCommand(Z){delete this._commandCallbacks[Z]}sendBroadcastMessage(Z,J){this._sendBroadcastMessage(void 0,Z,J)}handleCommand(Z,J){let[X,...$]=J.split(" "),Y=this._commandCallbacks[X];if(Y)return Y(Z,$,J),!0;return!1}sendPlayerMessage(Z,J,X){this.emitWithWorld(this._world,"CHAT.PLAYER_MESSAGE",{player:Z,message:J,color:X})}_subscribeToPlayerEvents(){this._world.on("PLAYER.CHAT_MESSAGE_SEND",(Z)=>{let{player:J,message:X}=Z;this._sendBroadcastMessage(J,X)})}_sendBroadcastMessage(Z,J,X){this.emitWithWorld(this._world,"CHAT.BROADCAST_MESSAGE",{player:Z,message:J,color:X})}}var p5=16,nP=p5-1,r_1=p5**3;class j5{_blocks;_originCoordinate;constructor(Z){this._blocks=new Uint8Array(r_1),this._originCoordinate=Z}get blocks(){return this._blocks}get originCoordinate(){return this._originCoordinate}static blockIndexToLocalCoordinate(Z){return{x:Z%p5,y:(Z/p5|0)%p5,z:Z/(p5*p5)|0}}static globalCoordinateToLocalCoordinate(Z){return{x:Z.x&p5-1,y:Z.y&p5-1,z:Z.z&p5-1}}static globalCoordinateToOriginCoordinate(Z){return{x:Z.x&~(p5-1),y:Z.y&~(p5-1),z:Z.z&~(p5-1)}}getBlockId(Z){return this._blocks[this._getIndex(Z)]}hasBlock(Z){return this._blocks[this._getIndex(Z)]!==0}setBlock(Z,J){if(!this._isValidLocalCoordinate(Z))return p.error("Chunk.setBlock(): Block local coordinate is out of bounds");let X=this._getIndex(Z);this._blocks[X]=J}serialize(){return T0.serializeChunk(this)}_getIndex(Z){return Z.x+(Z.y<<4)+(Z.z<<8)}_isValidLocalCoordinate(Z){return Z.x>=0&&Z.x<=nP&&Z.y>=0&&Z.y<=nP&&Z.z>=0&&Z.z<=nP}}var sP;(($)=>{$.ADD_CHUNK="CHUNK_LATTICE.ADD_CHUNK";$.REMOVE_CHUNK="CHUNK_LATTICE.REMOVE_CHUNK";$.SET_BLOCK="CHUNK_LATTICE.SET_BLOCK"})(sP||={});class Sz extends j0{_blockTypeColliders=new Map;_blockTypeCounts=new Map;_chunks=new Map;_rigidBody;_world;constructor(Z){super();this._world=Z}get chunkCount(){return this._chunks.size}clear(){for(let Z of this._blockTypeColliders.values())this._world.simulation.colliderMap.removeColliderBlockType(Z),Z.removeFromSimulation();this._chunks.forEach((Z)=>{this.emitWithWorld(this._world,"CHUNK_LATTICE.REMOVE_CHUNK",{chunkLattice:this,chunk:Z})}),this._blockTypeColliders.clear(),this._blockTypeCounts.clear(),this._chunks.clear()}getBlockId(Z){let J=this.getChunk(j5.globalCoordinateToOriginCoordinate(Z));if(!J)return 0;return J.getBlockId(j5.globalCoordinateToLocalCoordinate(Z))}getBlockTypeCollider(Z){return this._blockTypeColliders.get(Z)}getBlockType(Z){let J=this.getBlockId(Z);return J?this._world.blockTypeRegistry.getBlockType(J):null}getBlockTypeCount(Z){return this._blockTypeCounts.get(Z)??0}getChunk(Z){return this._chunks.get(this._getChunkKey(j5.globalCoordinateToOriginCoordinate(Z)))}getOrCreateBlockTypeCollider(Z,J){let X=this._blockTypeColliders.get(Z);if(X)return X;let Y=this._world.blockTypeRegistry.getBlockType(Z).createCollider(J);return this._blockTypeColliders.set(Z,Y),Y}getOrCreateChunk(Z){let J=j5.globalCoordinateToOriginCoordinate(Z),X=this._chunks.get(this._getChunkKey(J));if(X)return X;return X=new j5(J),this._chunks.set(this._getChunkKey(J),X),this.emitWithWorld(this._world,"CHUNK_LATTICE.ADD_CHUNK",{chunkLattice:this,chunk:X}),X}getAllChunks(){return Array.from(this._chunks.values())}hasBlock(Z){let J=this.getChunk(j5.globalCoordinateToOriginCoordinate(Z));if(!J)return!1;return J.hasBlock(j5.globalCoordinateToLocalCoordinate(Z))}hasChunk(Z){let J=j5.globalCoordinateToOriginCoordinate(Z);return this._chunks.has(this._getChunkKey(J))}initializeBlocks(Z){if(this.clear(),!this._rigidBody)this._rigidBody=new aJ({type:"fixed"}),this._rigidBody.addToSimulation(this._world.simulation);for(let J in Z){let X=Number(J),$=Z[X];if($.length===0)continue;let Y=this.getOrCreateBlockTypeCollider(X,$);Y.addToSimulation(this._world.simulation,this._rigidBody);let Q=this._world.blockTypeRegistry.getBlockType(X);this._world.simulation.colliderMap.setColliderBlockType(Y,Q),this._blockTypeCounts.set(X,$.length);for(let K=0;K<$.length;K++){let W=$[K],G=j5.globalCoordinateToLocalCoordinate(W),z=this.getOrCreateChunk(W);z.setBlock(G,X),this.emitWithWorld(this._world,"CHUNK_LATTICE.SET_BLOCK",{chunkLattice:this,chunk:z,globalCoordinate:W,localCoordinate:G,blockTypeId:X})}this._combineVoxelStates(Y)}}setBlock(Z,J){let X=j5.globalCoordinateToLocalCoordinate(Z),$=this.getOrCreateChunk(Z),Y=$.getBlockId(X);if(Y===J)return;if($.setBlock(X,J),!this._rigidBody)this._rigidBody=new aJ({type:"fixed"}),this._rigidBody.addToSimulation(this._world.simulation);if(Y!==0){let Q=Math.max(0,(this._blockTypeCounts.get(Y)??0)-1),K=this.getBlockTypeCollider(Y);if(K)if(Q===0)this._world.simulation.colliderMap.removeColliderBlockType(K),K.removeFromSimulation(),this._blockTypeColliders.delete(Y);else K.setVoxel(Z,!1),this._propagateVoxelChange(K,Z);this._blockTypeCounts.set(Y,Q)}if(J!==0){let Q=(this._blockTypeCounts.get(J)??0)+1,K=this.getOrCreateBlockTypeCollider(J,[Z]);if(Q===1){let W=this._world.blockTypeRegistry.getBlockType(J);K.addToSimulation(this._world.simulation,this._rigidBody),this._world.simulation.colliderMap.setColliderBlockType(K,W),this._combineVoxelStates(K)}else K.setVoxel(Z,!0),this._propagateVoxelChange(K,Z);this._blockTypeCounts.set(J,Q)}this.emitWithWorld(this._world,"CHUNK_LATTICE.SET_BLOCK",{chunkLattice:this,chunk:$,globalCoordinate:Z,localCoordinate:X,blockTypeId:J})}_combineVoxelStates(Z){if(Z.isSensor)return;for(let J of this._blockTypeColliders.values()){if(J===Z||J.isSensor)continue;Z.combineVoxelStates(J)}}_getChunkKey(Z){return`${Z.x},${Z.y},${Z.z}`}_propagateVoxelChange(Z,J){if(Z.isSensor)return;for(let X of this._blockTypeColliders.values()){if(X===Z||X.isSensor)continue;Z.propagateVoxelChange(X,J)}}}class Az{_colliderHandleBlockTypeMap=new Map;_colliderHandleCollisionCallbackMap=new Map;_colliderHandleEntityMap=new Map;_cleanupBlockTypeColliderHandles=new Set;_pendingCleanupBlockTypeColliderHandles=new Set;_cleanupCollisionCallbackColliderHandles=new Set;_pendingCleanupCollisionCallbackColliderHandles=new Set;_cleanupEntityColliderHandles=new Set;_pendingCleanupEntityColliderHandles=new Set;getColliderBlockType(Z){if(!this._requireSimulatedCollider(Z))return;return this._colliderHandleBlockTypeMap.get(Z.rawCollider.handle)}getColliderCollisionCallback(Z){if(!this._requireSimulatedCollider(Z))return;return this._colliderHandleCollisionCallbackMap.get(Z.rawCollider.handle)}getColliderEntity(Z){if(!this._requireSimulatedCollider(Z))return;return this._colliderHandleEntityMap.get(Z.rawCollider.handle)}getColliderHandleBlockType(Z){return this._colliderHandleBlockTypeMap.get(Z)}getColliderHandleCollisionCallback(Z){return this._colliderHandleCollisionCallbackMap.get(Z)}getColliderHandleEntity(Z){return this._colliderHandleEntityMap.get(Z)}removeColliderBlockType(Z){if(!this._requireSimulatedCollider(Z))return;this.removeColliderHandleBlockType(Z.rawCollider.handle)}removeColliderCollisionCallback(Z){if(!this._requireSimulatedCollider(Z))return;this.removeColliderHandleCollisionCallback(Z.rawCollider.handle)}removeColliderEntity(Z){if(!this._requireSimulatedCollider(Z))return;this.removeColliderHandleEntity(Z.rawCollider.handle)}removeColliderHandleBlockType(Z){this._colliderHandleBlockTypeMap.delete(Z)}removeColliderHandleCollisionCallback(Z){this._colliderHandleCollisionCallbackMap.delete(Z)}removeColliderHandleEntity(Z){this._colliderHandleEntityMap.delete(Z)}setColliderBlockType(Z,J){if(!this._requireSimulatedCollider(Z))return;this.setColliderHandleBlockType(Z.rawCollider.handle,J)}setColliderCollisionCallback(Z,J){if(!this._requireSimulatedCollider(Z))return;this.setColliderHandleCollisionCallback(Z.rawCollider.handle,J)}setColliderEntity(Z,J){if(!this._requireSimulatedCollider(Z))return;this.setColliderHandleEntity(Z.rawCollider.handle,J)}setColliderHandleBlockType(Z,J){this._colliderHandleBlockTypeMap.set(Z,J),this._cleanupBlockTypeColliderHandles.delete(Z),this._pendingCleanupBlockTypeColliderHandles.delete(Z)}setColliderHandleCollisionCallback(Z,J){this._colliderHandleCollisionCallbackMap.set(Z,J),this._cleanupCollisionCallbackColliderHandles.delete(Z),this._pendingCleanupCollisionCallbackColliderHandles.delete(Z)}setColliderHandleEntity(Z,J){this._colliderHandleEntityMap.set(Z,J),this._cleanupEntityColliderHandles.delete(Z),this._pendingCleanupEntityColliderHandles.delete(Z)}queueColliderHandleForCleanup(Z){if(this._colliderHandleBlockTypeMap.has(Z))this._pendingCleanupBlockTypeColliderHandles.add(Z);if(this._colliderHandleCollisionCallbackMap.has(Z))this._pendingCleanupCollisionCallbackColliderHandles.add(Z);if(this._colliderHandleEntityMap.has(Z))this._pendingCleanupEntityColliderHandles.add(Z)}cleanup(){for(let Z of this._cleanupBlockTypeColliderHandles)this._colliderHandleBlockTypeMap.delete(Z);if(this._cleanupBlockTypeColliderHandles.size>0)this._cleanupBlockTypeColliderHandles.clear();for(let Z of this._cleanupCollisionCallbackColliderHandles)this._colliderHandleCollisionCallbackMap.delete(Z);if(this._cleanupCollisionCallbackColliderHandles.size>0)this._cleanupCollisionCallbackColliderHandles.clear();for(let Z of this._cleanupEntityColliderHandles)this._colliderHandleEntityMap.delete(Z);if(this._cleanupEntityColliderHandles.size>0)this._cleanupEntityColliderHandles.clear();for(let Z of this._pendingCleanupBlockTypeColliderHandles)this._cleanupBlockTypeColliderHandles.add(Z);if(this._pendingCleanupBlockTypeColliderHandles.size>0)this._pendingCleanupBlockTypeColliderHandles.clear();for(let Z of this._pendingCleanupCollisionCallbackColliderHandles)this._cleanupCollisionCallbackColliderHandles.add(Z);if(this._pendingCleanupCollisionCallbackColliderHandles.size>0)this._pendingCleanupCollisionCallbackColliderHandles.clear();for(let Z of this._pendingCleanupEntityColliderHandles)this._cleanupEntityColliderHandles.add(Z);if(this._pendingCleanupEntityColliderHandles.size>0)this._pendingCleanupEntityColliderHandles.clear()}_requireSimulatedCollider(Z){if(!Z.rawCollider)p.error("ColliderMap._requireSimulatedCollider(): Collider is not in the simulation.");return!!Z.rawCollider}}var W60={type:"dynamic",softCcdPrediction:1},G60=0.015625,z60=Math.cos(0.026),mz;((L)=>{L.BLOCK_COLLISION="ENTITY.BLOCK_COLLISION";L.BLOCK_CONTACT_FORCE="ENTITY.BLOCK_CONTACT_FORCE";L.DESPAWN="ENTITY.DESPAWN";L.ENTITY_COLLISION="ENTITY.ENTITY_COLLISION";L.ENTITY_CONTACT_FORCE="ENTITY.ENTITY_CONTACT_FORCE";L.SET_MODEL_ANIMATIONS_PLAYBACK_RATE="ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE";L.SET_MODEL_HIDDEN_NODES="ENTITY.SET_MODEL_HIDDEN_NODES";L.SET_MODEL_SCALE="ENTITY.SET_MODEL_SCALE";L.SET_MODEL_SHOWN_NODES="ENTITY.SET_MODEL_SHOWN_NODES";L.SET_MODEL_TEXTURE_URI="ENTITY.SET_MODEL_TEXTURE_URI";L.SET_OPACITY="ENTITY.SET_OPACITY";L.SET_PARENT="ENTITY.SET_PARENT";L.SET_TINT_COLOR="ENTITY.SET_TINT_COLOR";L.SPAWN="ENTITY.SPAWN";L.START_MODEL_LOOPED_ANIMATIONS="ENTITY.START_MODEL_LOOPED_ANIMATIONS";L.START_MODEL_ONESHOT_ANIMATIONS="ENTITY.START_MODEL_ONESHOT_ANIMATIONS";L.STOP_MODEL_ANIMATIONS="ENTITY.STOP_MODEL_ANIMATIONS";L.TICK="ENTITY.TICK";L.UPDATE_POSITION="ENTITY.UPDATE_POSITION";L.UPDATE_ROTATION="ENTITY.UPDATE_ROTATION"})(mz||={});class B8 extends aJ{_id;_blockHalfExtents;_blockTextureUri;_controller;_isEnvironmental=!1;_modelAnimationsPlaybackRate=1;_modelHiddenNodes=new Set;_modelLoopedAnimations=new Set;_modelOneshotAnimations=new Set;_modelPreferredShape;_modelScale=1;_modelShownNodes=new Set;_modelTextureUri;_modelUri;_name;_opacity;_parent;_parentNodeName;_tag;_tintColor;_lastUpdatedPosition={x:0,y:0,z:0};_lastUpdatedRotation={x:0,y:0,z:0,w:1};_lastParentlessType="dynamic";_world;_positionUpdateThresholdSq;_rotationUpdateThreshold;constructor(Z){let J="blockTextureUri"in Z,X="modelUri"in Z;if(!J===!X)p.fatalError("Entity.constructor(): Entity data must include a blockTextureUri or modelUri, but not both.");if(J&&!Z.blockHalfExtents)p.fatalError("Entity.constructor(): Block entity must have blockHalfExtents!");if(Z.parent&&!Z.parent.isSpawned)p.fatalError("Entity.constructor(): Parent entity must be spawned before child entity!");if(Z.parent?.modelUri&&Z.parentNodeName&&!B6.instance.modelHasNode(Z.parent.modelUri,Z.parentNodeName))p.fatalError(`Entity.constructor(): Parent node name ${Z.parentNodeName} not found in parent model ${Z.parent.modelUri}!`);super(Z.rigidBodyOptions??W60);if(J)this._blockHalfExtents=Z.blockHalfExtents,this._blockTextureUri=Z.blockTextureUri;if(X)this._modelAnimationsPlaybackRate=Z.modelAnimationsPlaybackRate??1,this._modelPreferredShape=Z.modelPreferredShape,this._modelScale=Z.modelScale??1,this._modelTextureUri=Z.modelTextureUri,this._modelUri=Z.modelUri,Z.modelHiddenNodes?.forEach(($)=>this._modelHiddenNodes.add($.toLowerCase())),Z.modelLoopedAnimations?.forEach(($)=>this._modelLoopedAnimations.add($)),Z.modelShownNodes?.forEach(($)=>this._modelShownNodes.add($.toLowerCase()));if(this._isEnvironmental=Z.isEnvironmental??!1,this._name=Z.name??"Nameless",this._opacity=Z.opacity??1,this._parent=Z.parent,this._parentNodeName=Z.parentNodeName,this._tag=Z.tag,this._tintColor=Z.tintColor,this._positionUpdateThresholdSq=G60,this._rotationUpdateThreshold=z60,Z.controller)this.setController(Z.controller)}get id(){return this._id}get blockHalfExtents(){return this._blockHalfExtents}get blockTextureUri(){return this._blockTextureUri}get controller(){return this._controller}get depth(){return this.isModelEntity?B6.instance.getDepth(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.z*2}get height(){return this.isModelEntity?B6.instance.getHeight(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.y*2}get modelAnimationsPlaybackRate(){return this._modelAnimationsPlaybackRate}get modelHiddenNodes(){return this._modelHiddenNodes}get modelLoopedAnimations(){return this._modelLoopedAnimations}get modelPreferredShape(){return this._modelPreferredShape}get modelScale(){return this._modelScale}get modelShownNodes(){return this._modelShownNodes}get modelTextureUri(){return this._modelTextureUri}get modelUri(){return this._modelUri}get name(){return this._name}get opacity(){return this._opacity}get parent(){return this._parent}get parentNodeName(){return this._parentNodeName}get tag(){return this._tag}get tintColor(){return this._tintColor}get isBlockEntity(){return!!this._blockTextureUri}get isEnvironmental(){return this._isEnvironmental}get isModelEntity(){return!!this._modelUri}get isSpawned(){return!!this._world}get width(){return this.isModelEntity?B6.instance.getWidth(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.x*2}get world(){return this._world}spawn(Z,J,X){if(this.isSpawned)return p.error(`Entity.spawn(): Entity ${this._name} is already spawned with id ${this._id}!`);if(!this.isSimulated)this.addToSimulation(Z.simulation);if(this._blockTextureUri&&this._blockHalfExtents&&this.numColliders===0)this.addChildColliderToSimulation(new A5(A5.optionsFromBlockHalfExtents(this._blockHalfExtents)));if(this._modelUri&&this.numColliders===0&&this._modelPreferredShape!=="none")this.addChildColliderToSimulation(new A5(A5.optionsFromModelUri(this._modelUri,this._modelScale,this._modelPreferredShape)));if(this.colliders.forEach(($)=>{if(this.hasListeners("ENTITY.BLOCK_COLLISION")||this.hasListeners("ENTITY.ENTITY_COLLISION"))$.enableCollisionEvents(!0);if(this.hasListeners("ENTITY.BLOCK_CONTACT_FORCE")||this.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))$.enableContactForceEvents(!0);if(V9.isDefaultCollisionGroups($.collisionGroups)){let Y=this.isEnvironmental?[8]:[$.isSensor?4:2],Q=this.isEnvironmental?[65535&~8&~1]:[65535];$.setCollisionGroups({belongsTo:Y,collidesWith:Q})}}),this.setPosition(J),X)this.setRotation(X);if(this._id=Z.entityManager.registerEntity(this),this._world=Z,this._controller)this._controller.spawn(this);if(this._parent)this.setParent(this._parent,this._parentNodeName,J,X);this.colliders.forEach(($)=>{Z.simulation.colliderMap.setColliderEntity($,this)}),this.emitWithWorld(Z,"ENTITY.SPAWN",{entity:this})}despawn(){if(!this._requireSpawned("despawn"))return;if(this._world.entityManager.getEntityChildren(this).forEach((Z)=>{Z.despawn()}),this._controller)this._controller.detach(this),this._controller.despawn(this);if(this.emitWithWorld(this._world,"ENTITY.DESPAWN",{entity:this}),this.isSimulated)this.removeFromSimulation();this._world.entityManager.unregisterEntity(this),this._world.audioManager.unregisterEntityAttachedAudios(this),this._world.lightManager.despawnEntityAttachedLights(this),this._world.particleEmitterManager.despawnEntityAttachedParticleEmitters(this),this._world.sceneUIManager.unloadEntityAttachedSceneUIs(this),this._id=void 0,this._world=void 0}setController(Z){if(this._controller===Z)return;if(this._controller)this._controller.detach(this);if(this._controller=Z,this._controller)this._controller.attach(this)}setModelAnimationsPlaybackRate(Z){if(!this._requireSpawned("setModelAnimationsPlaybackRate"))return;if(!this.isModelEntity||this._modelAnimationsPlaybackRate===Z)return;this._modelAnimationsPlaybackRate=Z,this.emitWithWorld(this._world,"ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",{entity:this,playbackRate:Z})}setModelHiddenNodes(Z){if(!this._requireSpawned("setModelHiddenNodes"))return;if(!this.isModelEntity)return;this._modelHiddenNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_HIDDEN_NODES",{entity:this,modelHiddenNodes:this._modelHiddenNodes})}setModelScale(Z){if(!this._requireSpawned("setModelScale"))return;if(!this.isModelEntity||this._modelScale===Z)return;let J=Z/this._modelScale;this._modelScale=Z,this.colliders.forEach((X)=>X.scale(J)),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_SCALE",{entity:this,modelScale:Z})}setModelShownNodes(Z){if(!this._requireSpawned("setModelShownNodes"))return;if(!this.isModelEntity)return;this._modelShownNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_SHOWN_NODES",{entity:this,modelShownNodes:this._modelShownNodes})}setModelTextureUri(Z){if(!this._requireSpawned("setModelTextureUri"))return;if(!this.isModelEntity||this._modelTextureUri===Z)return;this._modelTextureUri=Z,this.emitWithWorld(this._world,"ENTITY.SET_MODEL_TEXTURE_URI",{entity:this,modelTextureUri:Z})}setOpacity(Z){if(!this._requireSpawned("setOpacity"))return;if(this._opacity===Z)return;this._opacity=Z,this.emitWithWorld(this._world,"ENTITY.SET_OPACITY",{entity:this,opacity:Z})}setParent(Z,J,X,$){if(!this._requireSpawned("setParent"))return;if(Z&&!Z.isSpawned)return p.error("Entity.setParent(): Parent entity is not spawned, cannot set parent!");if(!this._parent&&Z)this._lastParentlessType=this.type;if(this._parent=Z,this._parentNodeName=J,this.colliders.forEach((Y)=>Y.setEnabled(!Z)),this.setType(!Z?this._lastParentlessType:"kinematic_velocity"),this.setPosition(X??{x:0,y:0,z:0}),this.setRotation($??{x:0,y:0,z:0,w:1}),!this.isKinematicPositionBased)this.resetAngularVelocity(),this.resetForces(),this.resetLinearVelocity(),this.resetTorques();this.emitWithWorld(this._world,"ENTITY.SET_PARENT",{entity:this,parent:Z,parentNodeName:J})}setTintColor(Z){if(!this._requireSpawned("setTintColor"))return;if(!Z&&!this._tintColor||Z&&this._tintColor&&Z.r===this._tintColor.r&&Z.g===this._tintColor.g&&Z.b===this._tintColor.b)return;this._tintColor=Z,this.emitWithWorld(this._world,"ENTITY.SET_TINT_COLOR",{entity:this,tintColor:Z})}startModelLoopedAnimations(Z){if(!this._requireSpawned("startModelLoopedAnimations"))return;if(!this.isModelEntity||!Z.length)return;if(!Z.some((J)=>!this._modelLoopedAnimations.has(J)))return;Z.forEach((J)=>{this._modelLoopedAnimations.add(J)}),this.emitWithWorld(this._world,"ENTITY.START_MODEL_LOOPED_ANIMATIONS",{entity:this,animations:new Set(Z)})}startModelOneshotAnimations(Z){if(!this._requireSpawned("startModelOneshotAnimations"))return;if(!this.isModelEntity||!Z.length)return;Z.forEach((J)=>{this._modelOneshotAnimations.add(J)}),this.emitWithWorld(this._world,"ENTITY.START_MODEL_ONESHOT_ANIMATIONS",{entity:this,animations:new Set(Z)})}stopAllModelAnimations(Z=[]){if(!this._requireSpawned("stopAllModelAnimations"))return;this._stopAnimationsFromSets([this._modelLoopedAnimations,this._modelOneshotAnimations],Z)}stopAllModelLoopedAnimations(Z=[]){if(!this._requireSpawned("stopAllModelLoopedAnimations"))return;this._stopAnimationsFromSets([this._modelLoopedAnimations],Z)}stopAllModelOneshotAnimations(Z=[]){if(!this._requireSpawned("stopAllModelOneshotAnimations"))return;this._stopAnimationsFromSets([this._modelOneshotAnimations],Z)}stopModelAnimations(Z){if(!this._requireSpawned("stopModelAnimations"))return;if(!this.isModelEntity||!Z.length)return;if(!Z.some((J)=>this._modelLoopedAnimations.has(J))&&!Z.some((J)=>this._modelOneshotAnimations.has(J)))return;Z.forEach((J)=>{this._modelLoopedAnimations.delete(J),this._modelOneshotAnimations.delete(J)}),this.emitWithWorld(this._world,"ENTITY.STOP_MODEL_ANIMATIONS",{entity:this,animations:new Set(Z)})}serialize(){return T0.serializeEntity(this)}tick(Z){if(this.emit("ENTITY.TICK",{entity:this,tickDeltaMs:Z}),this._controller)this._controller.tick(this,Z)}checkAndEmitUpdates(){if(!this._requireSpawned("checkAndEmitUpdates"))return;let Z=this.position,J=this.rotation;if(this._rotationExceedsThreshold(J,this._lastUpdatedRotation))this._lastUpdatedRotation=J,this.emitWithWorld(this._world,"ENTITY.UPDATE_ROTATION",{entity:this,rotation:J});if(this._positionExceedsThreshold(Z,this._lastUpdatedPosition))this._lastUpdatedPosition=Z,this.emitWithWorld(this._world,"ENTITY.UPDATE_POSITION",{entity:this,position:Z})}_positionExceedsThreshold(Z,J){let X=Z.x-J.x,$=Z.y-J.y,Y=Z.z-J.z;return X*X+$*$+Y*Y>this._positionUpdateThresholdSq}_requireSpawned(Z){if(!this.isSpawned)p.error(`Entity._requireSpawned(): Entity ${this._name} is not spawned, cannot invoke ${Z}()!`);return this.isSpawned}_rotationExceedsThreshold(Z,J){return Math.abs(Z.x*J.x+Z.y*J.y+Z.z*J.z+Z.w*J.w)<this._rotationUpdateThreshold}_stopAnimationsFromSets(Z,J=[]){if(!this.isModelEntity)return;let X=new Set(J),$=[];for(let Y of Z)for(let Q of Y)if(!X.has(Q))$.push(Q);if($.length>0)this.stopModelAnimations($)}}class b1 extends x${static BASE_ENTITY_HEIGHT=1.5;static GROUND_SENSOR_HEIGHT_SCALE=0.125;static GROUND_SENSOR_RADIUS_SCALE=0.23;static JUMP_LAND_HEAVY_VELOCITY_THRESHOLD=-12;static WALL_COLLIDER_HEIGHT_SCALE=0.33;static WALL_COLLIDER_RADIUS_SCALE=0.4;static MOVEMENT_ROTATIONS={wa:Math.PI/4,wd:-Math.PI/4,sa:Math.PI-Math.PI/4,sd:Math.PI+Math.PI/4,s:Math.PI,asd:Math.PI,a:Math.PI/2,d:-Math.PI/2};static EXTERNAL_IMPULSE_DECAY_RATE=0.253;static SWIM_UPWARD_COOLDOWN_MS=600;static SWIMMING_DRAG_FACTOR=0.05;static WATER_ENTRY_SINKING_FACTOR=0.8;static WATER_ENTRY_SINKING_MS=250;applyDirectionalMovementRotations=!0;autoCancelMouseLeftClick=!0;canJump=()=>!0;canRun=()=>!0;canSwim=()=>!0;canWalk=()=>!0;faceForwardOnStop=!0;idleLoopedAnimations=["idle-upper","idle-lower"];interactOneshotAnimations=["simple-interact"];jumpLandHeavyOneshotAnimations=["jump-post-heavy"];jumpLandLightOneshotAnimations=["jump-post-light"];jumpOneshotAnimations=["jump-loop"];jumpVelocity=10;runLoopedAnimations=["run-upper","run-lower"];runVelocity=8;sticksToPlatforms=!0;swimFastVelocity=5;swimGravity=0;swimIdleLoopedAnimations=["swim-idle"];swimLoopedAnimations=["swim-forward"];swimMaxGravityVelocity=-1;swimSlowVelocity=3;swimUpwardVelocity=2;walkLoopedAnimations=["walk-upper","walk-lower"];walkVelocity=4;_externalVelocity={x:0,y:0,z:0};_magnitudeYTracker=0;_groundContactCount=0;_internalApplyImpulse=()=>{};_isActivelyMoving=!1;_isFullySubmerged=!1;_justSubmergedUntil=0;_liquidContactCount=0;_platform;_reusableImpulse={x:0,y:0,z:0};_reusablePlatformVelocity={x:0,y:0,z:0};_reusableTargetVelocities={x:0,y:0,z:0};_reusableVelocityClamp={x:0,y:0,z:0};_stepAudio;_swimUpwardCooldownAt=0;constructor(Z={}){super();this.applyDirectionalMovementRotations=Z.applyDirectionalMovementRotations??this.applyDirectionalMovementRotations,this.autoCancelMouseLeftClick=Z.autoCancelMouseLeftClick??this.autoCancelMouseLeftClick,this.faceForwardOnStop=Z.faceForwardOnStop??this.faceForwardOnStop,this.sticksToPlatforms=Z.sticksToPlatforms??this.sticksToPlatforms,this.canJump=Z.canJump??this.canJump,this.canRun=Z.canRun??this.canRun,this.canSwim=Z.canSwim??this.canSwim,this.canWalk=Z.canWalk??this.canWalk,this.jumpVelocity=Z.jumpVelocity??this.jumpVelocity,this.runVelocity=Z.runVelocity??this.runVelocity,this.walkVelocity=Z.walkVelocity??this.walkVelocity,this.swimFastVelocity=Z.swimFastVelocity??this.swimFastVelocity,this.swimSlowVelocity=Z.swimSlowVelocity??this.swimSlowVelocity,this.swimUpwardVelocity=Z.swimUpwardVelocity??this.swimUpwardVelocity,this.swimGravity=Z.swimGravity??this.swimGravity,this.swimMaxGravityVelocity=Z.swimMaxGravityVelocity??this.swimMaxGravityVelocity,this.idleLoopedAnimations=Z.idleLoopedAnimations??this.idleLoopedAnimations,this.interactOneshotAnimations=Z.interactOneshotAnimations??this.interactOneshotAnimations,this.jumpOneshotAnimations=Z.jumpOneshotAnimations??this.jumpOneshotAnimations,this.jumpLandHeavyOneshotAnimations=Z.jumpLandHeavyOneshotAnimations??this.jumpLandHeavyOneshotAnimations,this.jumpLandLightOneshotAnimations=Z.jumpLandLightOneshotAnimations??this.jumpLandLightOneshotAnimations,this.runLoopedAnimations=Z.runLoopedAnimations??this.runLoopedAnimations,this.swimLoopedAnimations=Z.swimLoopedAnimations??this.swimLoopedAnimations,this.swimIdleLoopedAnimations=Z.swimIdleLoopedAnimations??this.swimIdleLoopedAnimations,this.walkLoopedAnimations=Z.walkLoopedAnimations??this.walkLoopedAnimations}get isActivelyMoving(){return this._isActivelyMoving}get isGrounded(){return this._groundContactCount>0}get isOnPlatform(){return!!this._platform}get isSwimming(){return this._liquidContactCount>0}get platform(){return this._platform}attach(Z){super.attach(Z),this._internalApplyImpulse=Z.applyImpulse.bind(Z),Z.applyImpulse=(J)=>{let X=Z.mass||1;this._externalVelocity.x+=J.x/X,this._externalVelocity.y+=J.y/X,this._externalVelocity.z+=J.z/X},this._stepAudio=new OW({uri:"audio/sfx/step/stone/stone-step-04.mp3",loop:!0,volume:0.1,referenceDistance:2,cutoffDistance:15,attachedToEntity:Z}),Z.setCcdEnabled(!0),Z.lockAllRotations(),Z.on("ENTITY.BLOCK_COLLISION",({blockType:J,started:X})=>{if(!J.isLiquid||!this.canSwim(this))return;if(this._liquidContactCount<=0&&X){let $=Z.linearVelocity;Z.setLinearVelocity({x:$.x*this.swimGravity,y:$.y*this.swimGravity,z:$.z*this.swimGravity})}if(this._liquidContactCount+=X?1:-1,this._liquidContactCount>0)Z.setGravityScale(this.swimGravity),Z.stopAllModelLoopedAnimations(this.swimLoopedAnimations),this._swimUpwardCooldownAt=performance.now()+b1.SWIM_UPWARD_COOLDOWN_MS;else Z.setGravityScale(1),Z.stopModelAnimations(this.swimLoopedAnimations)})}spawn(Z){if(!Z.isSpawned)return p.error("DefaultPlayerEntityController.spawn(): Entity is not spawned!");Z.createAndAddChildCollider({shape:"cylinder",radius:b1.GROUND_SENSOR_RADIUS_SCALE*(Z.height/b1.BASE_ENTITY_HEIGHT),halfHeight:b1.GROUND_SENSOR_HEIGHT_SCALE*(Z.height/b1.BASE_ENTITY_HEIGHT),collisionGroups:{belongsTo:[4],collidesWith:[1,2,8]},isSensor:!0,relativePosition:{x:0,y:-Z.height/2,z:0},tag:"groundSensor",onCollision:(J,X)=>{if(!Z.isSpawned)return;if(!(J instanceof m5)||!J.isLiquid){if(X&&this._groundContactCount===0&&Z.linearVelocity.y<-1)if(Z.linearVelocity.y<b1.JUMP_LAND_HEAVY_VELOCITY_THRESHOLD)Z.startModelOneshotAnimations(this.jumpLandHeavyOneshotAnimations);else Z.startModelOneshotAnimations(this.jumpLandLightOneshotAnimations);this._groundContactCount+=X?1:-1}if(!this._groundContactCount&&!this.isSwimming)Z.startModelOneshotAnimations(this.jumpOneshotAnimations);else Z.stopModelAnimations(this.jumpOneshotAnimations);if(!(J instanceof B8))return;if(X&&this.sticksToPlatforms)this._platform=J;else if(J===this._platform&&!X)this._platform=void 0}}),Z.createAndAddChildCollider({shape:"capsule",halfHeight:b1.WALL_COLLIDER_HEIGHT_SCALE*(Z.height/b1.BASE_ENTITY_HEIGHT),radius:b1.WALL_COLLIDER_RADIUS_SCALE*(Z.height/b1.BASE_ENTITY_HEIGHT),collisionGroups:{belongsTo:[4],collidesWith:[1,2,8]},friction:0,frictionCombineRule:1,tag:"wallCollider"})}tickWithPlayerInput(Z,J,X,$){if(!Z.isSpawned||!Z.world)return;if(super.tickWithPlayerInput(Z,J,X,$),Z.parent)return;let{w:Y,a:Q,s:K,d:W,c:G,sp:z,sh:V,ml:H}=J,{yaw:v}=X,q=Z.linearVelocity;this._reusableTargetVelocities.x=0,this._reusableTargetVelocities.y=0,this._reusableTargetVelocities.z=0,this._isActivelyMoving=!!(Y||Q||K||W);let F=V,c=Q&&W&&!Y&&!K||Y&&K&&!Q&&!W,w=F&&this.canRun(this)||!F&&this.canWalk(this);if(this.isSwimming&&!this._isFullySubmerged)this._isFullySubmerged=!0,this._justSubmergedUntil=performance.now()+b1.WATER_ENTRY_SINKING_MS;else if(!this.isSwimming)this._isFullySubmerged=!1,this._justSubmergedUntil=0;if(this.isGrounded&&!this.isSwimming&&this._isActivelyMoving&&!c&&w){let M=F?this.runLoopedAnimations:this.walkLoopedAnimations;Z.stopAllModelLoopedAnimations(M),Z.startModelLoopedAnimations(M),this._stepAudio?.setPlaybackRate(F?0.75:0.51),this._stepAudio?.play(Z.world,!this._stepAudio?.isPlaying)}else if(this._isFullySubmerged&&this.canSwim(this))if(this._stepAudio?.pause(),this._isActivelyMoving)Z.stopAllModelLoopedAnimations(this.swimLoopedAnimations),Z.startModelLoopedAnimations(this.swimLoopedAnimations);else Z.stopAllModelLoopedAnimations(this.swimIdleLoopedAnimations),Z.startModelLoopedAnimations(this.swimIdleLoopedAnimations);else this._stepAudio?.pause(),Z.stopAllModelLoopedAnimations(this.idleLoopedAnimations),Z.startModelLoopedAnimations(this.idleLoopedAnimations);let x;if(this.applyDirectionalMovementRotations&&w){if(Y&&Q&&!W&&!K)x=b1.MOVEMENT_ROTATIONS.wa;else if(Y&&W&&!Q&&!K)x=b1.MOVEMENT_ROTATIONS.wd;else if(K&&Q&&!Y&&!W)x=b1.MOVEMENT_ROTATIONS.sa;else if(K&&W&&!Y&&!Q)x=b1.MOVEMENT_ROTATIONS.sd;else if(K&&!Y&&!Q&&!W||Q&&K&&W&&!Y)x=b1.MOVEMENT_ROTATIONS.s;else if(Q&&!Y&&!K&&!W)x=b1.MOVEMENT_ROTATIONS.a;else if(W&&!Y&&!Q&&!K)x=b1.MOVEMENT_ROTATIONS.d}if(H)Z.startModelOneshotAnimations(this.interactOneshotAnimations),J.ml=!this.autoCancelMouseLeftClick;if(w){let M=!this.isSwimming?F?this.runVelocity:this.walkVelocity:F?this.swimFastVelocity:this.swimSlowVelocity,O=Math.sin(v),P=Math.cos(v);if(Y)this._reusableTargetVelocities.x-=M*O,this._reusableTargetVelocities.z-=M*P;if(K)this._reusableTargetVelocities.x+=M*O,this._reusableTargetVelocities.z+=M*P;if(Q)this._reusableTargetVelocities.x-=M*P,this._reusableTargetVelocities.z+=M*O;if(W)this._reusableTargetVelocities.x+=M*P,this._reusableTargetVelocities.z-=M*O;let N=Math.sqrt(this._reusableTargetVelocities.x*this._reusableTargetVelocities.x+this._reusableTargetVelocities.z*this._reusableTargetVelocities.z);if(N>M){let _=M/N;this._reusableTargetVelocities.x*=_,this._reusableTargetVelocities.z*=_}}if(this.isSwimming){if(q.y<this.swimMaxGravityVelocity)this._reusableVelocityClamp.x=q.x,this._reusableVelocityClamp.y=this.swimMaxGravityVelocity,this._reusableVelocityClamp.z=q.z,Z.setLinearVelocity(this._reusableVelocityClamp);if(q.y>this.swimUpwardVelocity*2)this._reusableVelocityClamp.x=q.x,this._reusableVelocityClamp.y=this.swimUpwardVelocity*2,this._reusableVelocityClamp.z=q.z,Z.setLinearVelocity(this._reusableVelocityClamp);if(G)this._reusableTargetVelocities.y=-this.swimUpwardVelocity;else if(performance.now()<this._justSubmergedUntil)this._reusableTargetVelocities.y=-this.swimUpwardVelocity*b1.WATER_ENTRY_SINKING_FACTOR;else if(!z)this._reusableTargetVelocities.y=-q.y*b1.SWIMMING_DRAG_FACTOR}if(z&&this.canJump(this)){if(this.isGrounded&&!this.isSwimming&&q.y>-0.001&&q.y<=3)this._reusableTargetVelocities.y=this.jumpVelocity;else if(this.isSwimming&&performance.now()>this._swimUpwardCooldownAt)this._reusableTargetVelocities.y=this.swimUpwardVelocity}let j=this._platform?.linearVelocity??this._reusablePlatformVelocity;if(this._externalVelocity.y!==0)this._magnitudeYTracker+=this._externalVelocity.y;if(this._externalVelocity.x!==0||this._externalVelocity.y!==0||this._externalVelocity.z!==0){if(this.isGrounded){let M=Math.sqrt(this._externalVelocity.x*this._externalVelocity.x+this._magnitudeYTracker*this._magnitudeYTracker+this._externalVelocity.z*this._externalVelocity.z);if(M>0.01){let P=Math.max(0,M-b1.EXTERNAL_IMPULSE_DECAY_RATE)/M;this._externalVelocity.x*=P,this._magnitudeYTracker*=P,this._externalVelocity.z*=P}else this._externalVelocity.x=0,this._externalVelocity.y=0,this._magnitudeYTracker=0,this._externalVelocity.z=0}}let B=this._reusableTargetVelocities.x+this._externalVelocity.x-q.x+j.x,L=this._reusableTargetVelocities.y+this._externalVelocity.y+j.y,R=this._reusableTargetVelocities.z+this._externalVelocity.z-q.z+j.z;if(this._externalVelocity.y=0,B!==0||L!==0||R!==0){let M=Z.mass;this._reusableImpulse.x=B*M,this._reusableImpulse.y=L*M,this._reusableImpulse.z=R*M,this._internalApplyImpulse(this._reusableImpulse)}if(v!==void 0&&(this.faceForwardOnStop||this.isActivelyMoving)){let O=(x!==void 0?v+x:v)*0.5;Z.setRotation({x:0,y:Math.sin(O),z:0,w:Math.cos(O)})}}}var oP;((W)=>{W.LOAD="SCENE_UI.LOAD";W.SET_ATTACHED_TO_ENTITY="SCENE_UI.SET_ATTACHED_TO_ENTITY";W.SET_OFFSET="SCENE_UI.SET_OFFSET";W.SET_POSITION="SCENE_UI.SET_POSITION";W.SET_STATE="SCENE_UI.SET_STATE";W.SET_VIEW_DISTANCE="SCENE_UI.SET_VIEW_DISTANCE";W.UNLOAD="SCENE_UI.UNLOAD"})(oP||={});class uz extends j0{_id;_attachedToEntity;_offset;_position;_state={};_templateId;_viewDistance;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)p.fatalError("Either attachedToEntity or position must be set, but not both");super();this._attachedToEntity=Z.attachedToEntity,this._offset=Z.offset,this._position=Z.position,this._state=Z.state??{},this._templateId=Z.templateId,this._viewDistance=Z.viewDistance}get id(){return this._id}get attachedToEntity(){return this._attachedToEntity}get isLoaded(){return this._id!==void 0}get offset(){return this._offset}get position(){return this._position}get state(){return this._state}get templateId(){return this._templateId}get viewDistance(){return this._viewDistance}get world(){return this._world}load(Z){if(this.isLoaded)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return p.error(`SceneUI.load(): Attached entity ${this._attachedToEntity.id} must be spawned before loading SceneUI!`);this._id=Z.sceneUIManager.registerSceneUI(this),this._world=Z,this.emitWithWorld(Z,"SCENE_UI.LOAD",{sceneUI:this})}setAttachedToEntity(Z){if(!Z.isSpawned)return p.error(`SceneUI.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_ATTACHED_TO_ENTITY",{sceneUI:this,entity:Z})}setOffset(Z){if(this._offset===Z)return;if(this._offset=Z,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_OFFSET",{sceneUI:this,offset:Z})}setPosition(Z){if(this._position===Z)return;if(this._attachedToEntity=void 0,this._position=Z,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_POSITION",{sceneUI:this,position:Z})}setState(Z){if(this._state={...this._state,...Z},this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_STATE",{sceneUI:this,state:this._state})}setViewDistance(Z){if(this._viewDistance=Z,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_VIEW_DISTANCE",{sceneUI:this,viewDistance:Z})}unload(){if(!this.isLoaded||!this._world)return;this._world.sceneUIManager.unregisterSceneUI(this),this.emitWithWorld(this._world,"SCENE_UI.UNLOAD",{sceneUI:this}),this._id=void 0,this._world=void 0}serialize(){return T0.serializeSceneUI(this)}}var V60=0.010000000000000002,v60=Math.cos(0.026);class c7 extends B8{player;nametagSceneUI;constructor(Z){super(Z);this._positionUpdateThresholdSq=V60,this._rotationUpdateThreshold=v60,this.player=Z.player,this.nametagSceneUI=new uz({templateId:"hytopia:nametag",attachedToEntity:this,offset:{x:0,y:1,z:0},viewDistance:15,state:{username:this.player.username,profilePictureUrl:this.player.profilePictureUrl}})}spawn(Z,J,X){super.spawn(Z,J,X),this.nametagSceneUI.load(Z),this.player.on("PLAYER.CHAT_MESSAGE_SEND",({message:$})=>{this.nametagSceneUI.setState({chat:$})})}tick(Z){if(!this.isSpawned||!this.world)return;if(!this.controller)return p.error(`PlayerEntity.tick(): PlayerEntity "${this.name}" must have a controller.`);let{input:J,camera:X}=this.player;this.controller.tickWithPlayerInput(this,J,X.orientation,Z),super.tick(Z)}}var H60="models/players/player.gltf",t_1={BACK:"back-anchor",HEAD:"head-anchor",LEFT_ARM:"arm-left-anchor",LEFT_FOOT:"foot-left-anchor",LEFT_HAND:"hand-left-anchor",LEFT_ITEM:"hand-left-anchor",LEFT_LEG:"leg-left-anchor",RIGHT_ARM:"arm-right-anchor",RIGHT_FOOT:"foot-right-anchor",RIGHT_HAND:"hand-right-anchor",RIGHT_ITEM:"hand-right-anchor",RIGHT_LEG:"leg-right-anchor",TORSO:"torso-anchor"};class rP extends c7{_cosmeticHiddenSlots;constructor(Z){super({modelUri:H60,modelLoopedAnimations:["idle_lower","idle_upper"],modelHiddenNodes:["hair-"],modelShownNodes:["hair-0003"],...Z});if(this._cosmeticHiddenSlots=Z.cosmeticHiddenSlots??[],!Z.controller)this.setController(new b1)}get cosmeticHiddenSlots(){return this._cosmeticHiddenSlots}spawn(Z,J,X){super.spawn(Z,J,X),this.player.cosmetics.then(($)=>{if(!$||!this.modelUri)return;let Y=this.modelShownNodes.values().toArray().filter((W)=>!W.includes("hair-"));if(!($.equippedItems.some((W)=>W.item.flags.includes("HIDES_HAIR"))&&!this._cosmeticHiddenSlots.includes("ALL")&&!this._cosmeticHiddenSlots.includes("HEAD")))Y.push(`hair-${String($.hairStyle).padStart(4,"0")}`);if(this.setModelShownNodes(Y),this.modelUri===H60)this.setModelTextureUri($.skinTextureUri);if(this._cosmeticHiddenSlots.includes("ALL"))return;let K=[];for(let W of $.equippedItems){let{item:G,slot:z}=W;if(this._cosmeticHiddenSlots.includes(z))continue;let V=t_1[z];if(!V||!B6.instance.modelHasNode(this.modelUri,V))continue;if(G.flags.includes("REPLACES_LIMB")){let v=V.split("-").slice(0,-1).join("-");K.push(`${v}-clothing`,`${v}-geometry`)}new B8({modelUri:G.modelUrl,modelPreferredShape:"none",parent:this,parentNodeName:V}).spawn(Z,{x:0,y:0,z:0})}if(K.length>0)this.setModelHiddenNodes([...this.modelHiddenNodes.values().toArray(),...K])}).catch(($)=>p.warning(`DefaultPlayerEntity.spawn(): Failed to get player cosmetics: ${$}`))}}class lz{_activeEntities=new Set;_entities=new Map;_nextEntityId=1;_world;constructor(Z){this._world=Z}get entityCount(){return this._entities.size}get world(){return this._world}registerEntity(Z){if(Z.id!==void 0)p.fatalError(`EntityManager.registerEntity(): Entity ${Z.name} is already assigned the id ${Z.id}!`);let J=this._nextEntityId;if(this._entities.set(J,Z),this._nextEntityId++,!Z.isEnvironmental)this._activeEntities.add(Z);return J}unregisterEntity(Z){if(Z.id===void 0)return p.error(`EntityManager.unregisterEntity(): Entity ${Z.name} is not assigned an id!`);if(this._entities.delete(Z.id),!Z.isEnvironmental)this._activeEntities.delete(Z)}getAllEntities(){return Array.from(this._entities.values())}getAllPlayerEntities(){let Z=[];return this._entities.forEach((J)=>{if(J instanceof c7)Z.push(J)}),Z}getPlayerEntitiesByPlayer(Z){let J=[];return this._entities.forEach((X)=>{if(X instanceof c7&&X.player===Z)J.push(X)}),J}getEntity(Z){return this._entities.get(Z)}getEntitiesByTag(Z){let J=[];return this._entities.forEach((X)=>{if(X.tag===Z)J.push(X)}),J}getEntitiesByTagSubstring(Z){let J=[];return this._entities.forEach((X)=>{if(X.tag?.includes(Z))J.push(X)}),J}getEntityChildren(Z){let J=[];return this._entities.forEach((X)=>{if(X.parent===Z)J.push(X)}),J}tickEntities(Z){for(let J of this._activeEntities)J.tick(Z)}checkAndEmitUpdates(){for(let Z of this._activeEntities)Z.checkAndEmitUpdates()}}import{gzipSync as oX6}from"zlib";var d6=t(w50(),1),_h6=d6.default.v1,bh6=d6.default.v1ToV6,hh6=d6.default.v3,x50=d6.default.v4,Sh6=d6.default.v5,Ah6=d6.default.v6,mh6=d6.default.v6ToV1,uh6=d6.default.v7,lh6=d6.default.NIL,yh6=d6.default.MAX,ph6=d6.default.version,ih6=d6.default.validate,gh6=d6.default.stringify,dh6=d6.default.parse;var QT;try{QT=new TextDecoder}catch(Z){}var X0,g5,m=0;var zT=[],JY=zT,iz=0,f1={},Y1,hZ,i5=0,P4=0,S8,SZ,L5=[],e0,U50={useRecords:!1,mapsAsObjects:!0};class Zx{}var VT=new Zx;VT.name="MessagePack 0xC1";var QX=!1,N50=2,KT,WT,GT;try{new Function("")}catch(Z){N50=1/0}class AZ{constructor(Z){if(Z){if(Z.useRecords===!1&&Z.mapsAsObjects===void 0)Z.mapsAsObjects=!0;if(Z.sequential&&Z.trusted!==!1){if(Z.trusted=!0,!Z.structures&&Z.useRecords!=!1){if(Z.structures=[],!Z.maxSharedStructures)Z.maxSharedStructures=0}}if(Z.structures)Z.structures.sharedLength=Z.structures.length;else if(Z.getStructures)(Z.structures=[]).uninitialized=!0,Z.structures.sharedLength=0;if(Z.int64AsNumber)Z.int64AsType="number"}Object.assign(this,Z)}unpack(Z,J){if(X0)return S50(()=>{return ew(),this?this.unpack(Z,J):AZ.prototype.unpack.call(U50,Z,J)});if(!Z.buffer&&Z.constructor===ArrayBuffer)Z=typeof Buffer!=="undefined"?Buffer.from(Z):new Uint8Array(Z);if(typeof J==="object")g5=J.end||Z.length,m=J.start||0;else m=0,g5=J>-1?J:Z.length;iz=0,P4=0,hZ=null,JY=zT,S8=null,X0=Z;try{e0=Z.dataView||(Z.dataView=new DataView(Z.buffer,Z.byteOffset,Z.byteLength))}catch(X){if(X0=null,Z instanceof Uint8Array)throw X;throw new Error("Source must be a Uint8Array or Buffer but was a "+(Z&&typeof Z=="object"?Z.constructor.name:typeof Z))}if(this instanceof AZ){if(f1=this,this.structures)return Y1=this.structures,rw(J);else if(!Y1||Y1.length>0)Y1=[]}else if(f1=U50,!Y1||Y1.length>0)Y1=[];return rw(J)}unpackMultiple(Z,J){let X,$=0;try{QX=!0;let Y=Z.length,Q=this?this.unpack(Z,Y):Jx.unpack(Z,Y);if(J){if(J(Q,$,m)===!1)return;while(m<Y)if($=m,J(rw(),$,m)===!1)return}else{X=[Q];while(m<Y)$=m,X.push(rw());return X}}catch(Y){throw Y.lastPosition=$,Y.values=X,Y}finally{QX=!1,ew()}}_mergeStructures(Z,J){if(WT)Z=WT.call(this,Z);if(Z=Z||[],Object.isFrozen(Z))Z=Z.map((X)=>X.slice(0));for(let X=0,$=Z.length;X<$;X++){let Y=Z[X];if(Y){if(Y.isShared=!0,X>=32)Y.highByte=X-32>>5}}Z.sharedLength=Z.length;for(let X in J||[])if(X>=0){let $=Z[X],Y=J[X];if(Y){if($)(Z.restoreStructures||(Z.restoreStructures=[]))[X]=$;Z[X]=Y}}return this.structures=Z}decode(Z,J){return this.unpack(Z,J)}}function rw(Z){try{if(!f1.trusted&&!QX){let X=Y1.sharedLength||0;if(X<Y1.length)Y1.length=X}let J;if(f1.randomAccessStructure&&X0[m]<64&&X0[m]>=32&&KT){if(J=KT(X0,m,g5,f1),X0=null,!(Z&&Z.lazy)&&J)J=J.toJSON();m=g5}else J=L8();if(S8)m=S8.postBundlePosition,S8=null;if(QX)Y1.restoreStructures=null;if(m==g5){if(Y1&&Y1.restoreStructures)j50();if(Y1=null,X0=null,SZ)SZ=null}else if(m>g5)throw new Error("Unexpected end of MessagePack data");else if(!QX){let X;try{X=JSON.stringify(J,($,Y)=>typeof Y==="bigint"?`${Y}n`:Y).slice(0,100)}catch($){X="(JSON view not available "+$+")"}throw new Error("Data read, but end of buffer not reached "+X)}return J}catch(J){if(Y1&&Y1.restoreStructures)j50();if(ew(),J instanceof RangeError||J.message.startsWith("Unexpected end of buffer")||m>g5)J.incomplete=!0;throw J}}function j50(){for(let Z in Y1.restoreStructures)Y1[Z]=Y1.restoreStructures[Z];Y1.restoreStructures=null}function L8(){let Z=X0[m++];if(Z<160)if(Z<128)if(Z<64)return Z;else{let J=Y1[Z&63]||f1.getStructures&&P50()[Z&63];if(J){if(!J.read)J.read=vT(J,Z&63);return J.read()}else return Z}else if(Z<144)if(Z-=128,f1.mapsAsObjects){let J={};for(let X=0;X<Z;X++){let $=b50();if($==="__proto__")$="__proto_";J[$]=L8()}return J}else{let J=new Map;for(let X=0;X<Z;X++)J.set(L8(),L8());return J}else{Z-=144;let J=new Array(Z);for(let X=0;X<Z;X++)J[X]=L8();if(f1.freezeData)return Object.freeze(J);return J}else if(Z<192){let J=Z-160;if(P4>=m)return hZ.slice(m-i5,(m+=J)-i5);if(P4==0&&g5<140){let X=J<16?HT(J):_50(J);if(X!=null)return X}return tw(J)}else{let J;switch(Z){case 192:return null;case 193:if(S8)if(J=L8(),J>0)return S8[1].slice(S8.position1,S8.position1+=J);else return S8[0].slice(S8.position0,S8.position0-=J);return VT;case 194:return!1;case 195:return!0;case 196:if(J=X0[m++],J===void 0)throw new Error("Unexpected end of buffer");return YT(J);case 197:return J=e0.getUint16(m),m+=2,YT(J);case 198:return J=e0.getUint32(m),m+=4,YT(J);case 199:return ZY(X0[m++]);case 200:return J=e0.getUint16(m),m+=2,ZY(J);case 201:return J=e0.getUint32(m),m+=4,ZY(J);case 202:if(J=e0.getFloat32(m),f1.useFloat32>2){let X=$Y[(X0[m]&127)<<1|X0[m+1]>>7];return m+=4,(X*J+(J>0?0.5:-0.5)>>0)/X}return m+=4,J;case 203:return J=e0.getFloat64(m),m+=8,J;case 204:return X0[m++];case 205:return J=e0.getUint16(m),m+=2,J;case 206:return J=e0.getUint32(m),m+=4,J;case 207:if(f1.int64AsType==="number")J=e0.getUint32(m)*4294967296,J+=e0.getUint32(m+4);else if(f1.int64AsType==="string")J=e0.getBigUint64(m).toString();else if(f1.int64AsType==="auto"){if(J=e0.getBigUint64(m),J<=BigInt(2)<<BigInt(52))J=Number(J)}else J=e0.getBigUint64(m);return m+=8,J;case 208:return e0.getInt8(m++);case 209:return J=e0.getInt16(m),m+=2,J;case 210:return J=e0.getInt32(m),m+=4,J;case 211:if(f1.int64AsType==="number")J=e0.getInt32(m)*4294967296,J+=e0.getUint32(m+4);else if(f1.int64AsType==="string")J=e0.getBigInt64(m).toString();else if(f1.int64AsType==="auto"){if(J=e0.getBigInt64(m),J>=BigInt(-2)<<BigInt(52)&&J<=BigInt(2)<<BigInt(52))J=Number(J)}else J=e0.getBigInt64(m);return m+=8,J;case 212:if(J=X0[m++],J==114)return O50(X0[m++]&63);else{let X=L5[J];if(X)if(X.read)return m++,X.read(L8());else if(X.noBuffer)return m++,X();else return X(X0.subarray(m,++m));else throw new Error("Unknown extension "+J)}case 213:if(J=X0[m],J==114)return m++,O50(X0[m++]&63,X0[m++]);else return ZY(2);case 214:return ZY(4);case 215:return ZY(8);case 216:return ZY(16);case 217:if(J=X0[m++],P4>=m)return hZ.slice(m-i5,(m+=J)-i5);return T50(J);case 218:if(J=e0.getUint16(m),m+=2,P4>=m)return hZ.slice(m-i5,(m+=J)-i5);return C50(J);case 219:if(J=e0.getUint32(m),m+=4,P4>=m)return hZ.slice(m-i5,(m+=J)-i5);return f50(J);case 220:return J=e0.getUint16(m),m+=2,L50(J);case 221:return J=e0.getUint32(m),m+=4,L50(J);case 222:return J=e0.getUint16(m),m+=2,D50(J);case 223:return J=e0.getUint32(m),m+=4,D50(J);default:if(Z>=224)return Z-256;if(Z===void 0){let X=new Error("Unexpected end of MessagePack data");throw X.incomplete=!0,X}throw new Error("Unknown MessagePack token "+Z)}}}var Ph1=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function vT(Z,J){function X(){if(X.count++>N50){let Y=Z.read=new Function("r","return function(){return "+(f1.freezeData?"Object.freeze":"")+"({"+Z.map((Q)=>Q==="__proto__"?"__proto_:r()":Ph1.test(Q)?Q+":r()":"["+JSON.stringify(Q)+"]:r()").join(",")+"})}")(L8);if(Z.highByte===0)Z.read=B50(J,Z.read);return Y()}let $={};for(let Y=0,Q=Z.length;Y<Q;Y++){let K=Z[Y];if(K==="__proto__")K="__proto_";$[K]=L8()}if(f1.freezeData)return Object.freeze($);return $}if(X.count=0,Z.highByte===0)return B50(J,X);return X}var B50=(Z,J)=>{return function(){let X=X0[m++];if(X===0)return J();let $=Z<32?-(Z+(X<<5)):Z+(X<<5),Y=Y1[$]||P50()[$];if(!Y)throw new Error("Record id is not defined for "+$);if(!Y.read)Y.read=vT(Y,Z);return Y.read()}};function P50(){let Z=S50(()=>{return X0=null,f1.getStructures()});return Y1=f1._mergeStructures(Z,Y1)}var tw=XY,T50=XY,C50=XY,f50=XY,k50=!1;function E50(Z){k50=!0,tw=J(1),T50=J(2),C50=J(3),f50=J(5);function J(X){return function $(Y){let Q=JY[iz++];if(Q==null){if(S8)return XY(Y);let W=X0.byteOffset,G=Z(m-X+W,g5+W,X0.buffer);if(typeof G=="string")Q=G,JY=zT;else if(JY=G,iz=1,P4=1,Q=JY[0],Q===void 0)throw new Error("Unexpected end of buffer")}let K=Q.length;if(K<=Y)return m+=Y,Q;return hZ=Q,i5=m,P4=m+K,m+=Y,Q.slice(0,Y)}}}function XY(Z){let J;if(Z<16){if(J=HT(Z))return J}if(Z>64&&QT)return QT.decode(X0.subarray(m,m+=Z));let X=m+Z,$=[];J="";while(m<X){let Y=X0[m++];if((Y&128)===0)$.push(Y);else if((Y&224)===192){let Q=X0[m++]&63;$.push((Y&31)<<6|Q)}else if((Y&240)===224){let Q=X0[m++]&63,K=X0[m++]&63;$.push((Y&31)<<12|Q<<6|K)}else if((Y&248)===240){let Q=X0[m++]&63,K=X0[m++]&63,W=X0[m++]&63,G=(Y&7)<<18|Q<<12|K<<6|W;if(G>65535)G-=65536,$.push(G>>>10&1023|55296),G=56320|G&1023;$.push(G)}else $.push(Y);if($.length>=4096)J+=a8.apply(String,$),$.length=0}if($.length>0)J+=a8.apply(String,$);return J}function I50(Z,J,X){let $=X0;X0=Z,m=J;try{return XY(X)}finally{X0=$}}function L50(Z){let J=new Array(Z);for(let X=0;X<Z;X++)J[X]=L8();if(f1.freezeData)return Object.freeze(J);return J}function D50(Z){if(f1.mapsAsObjects){let J={};for(let X=0;X<Z;X++){let $=b50();if($==="__proto__")$="__proto_";J[$]=L8()}return J}else{let J=new Map;for(let X=0;X<Z;X++)J.set(L8(),L8());return J}}var a8=String.fromCharCode;function _50(Z){let J=m,X=new Array(Z);for(let $=0;$<Z;$++){let Y=X0[m++];if((Y&128)>0){m=J;return}X[$]=Y}return a8.apply(String,X)}function HT(Z){if(Z<4)if(Z<2)if(Z===0)return"";else{let J=X0[m++];if((J&128)>1){m-=1;return}return a8(J)}else{let J=X0[m++],X=X0[m++];if((J&128)>0||(X&128)>0){m-=2;return}if(Z<3)return a8(J,X);let $=X0[m++];if(($&128)>0){m-=3;return}return a8(J,X,$)}else{let J=X0[m++],X=X0[m++],$=X0[m++],Y=X0[m++];if((J&128)>0||(X&128)>0||($&128)>0||(Y&128)>0){m-=4;return}if(Z<6)if(Z===4)return a8(J,X,$,Y);else{let Q=X0[m++];if((Q&128)>0){m-=5;return}return a8(J,X,$,Y,Q)}else if(Z<8){let Q=X0[m++],K=X0[m++];if((Q&128)>0||(K&128)>0){m-=6;return}if(Z<7)return a8(J,X,$,Y,Q,K);let W=X0[m++];if((W&128)>0){m-=7;return}return a8(J,X,$,Y,Q,K,W)}else{let Q=X0[m++],K=X0[m++],W=X0[m++],G=X0[m++];if((Q&128)>0||(K&128)>0||(W&128)>0||(G&128)>0){m-=8;return}if(Z<10)if(Z===8)return a8(J,X,$,Y,Q,K,W,G);else{let z=X0[m++];if((z&128)>0){m-=9;return}return a8(J,X,$,Y,Q,K,W,G,z)}else if(Z<12){let z=X0[m++],V=X0[m++];if((z&128)>0||(V&128)>0){m-=10;return}if(Z<11)return a8(J,X,$,Y,Q,K,W,G,z,V);let H=X0[m++];if((H&128)>0){m-=11;return}return a8(J,X,$,Y,Q,K,W,G,z,V,H)}else{let z=X0[m++],V=X0[m++],H=X0[m++],v=X0[m++];if((z&128)>0||(V&128)>0||(H&128)>0||(v&128)>0){m-=12;return}if(Z<14)if(Z===12)return a8(J,X,$,Y,Q,K,W,G,z,V,H,v);else{let q=X0[m++];if((q&128)>0){m-=13;return}return a8(J,X,$,Y,Q,K,W,G,z,V,H,v,q)}else{let q=X0[m++],F=X0[m++];if((q&128)>0||(F&128)>0){m-=14;return}if(Z<15)return a8(J,X,$,Y,Q,K,W,G,z,V,H,v,q,F);let c=X0[m++];if((c&128)>0){m-=15;return}return a8(J,X,$,Y,Q,K,W,G,z,V,H,v,q,F,c)}}}}}function M50(){let Z=X0[m++],J;if(Z<192)J=Z-160;else switch(Z){case 217:J=X0[m++];break;case 218:J=e0.getUint16(m),m+=2;break;case 219:J=e0.getUint32(m),m+=4;break;default:throw new Error("Expected string")}return XY(J)}function YT(Z){return f1.copyBuffers?Uint8Array.prototype.slice.call(X0,m,m+=Z):X0.subarray(m,m+=Z)}function ZY(Z){let J=X0[m++];if(L5[J]){let X;return L5[J](X0.subarray(m,X=m+=Z),($)=>{m=$;try{return L8()}finally{m=X}})}else throw new Error("Unknown extension type "+J)}var R50=new Array(4096);function b50(){let Z=X0[m++];if(Z>=160&&Z<192){if(Z=Z-160,P4>=m)return hZ.slice(m-i5,(m+=Z)-i5);else if(!(P4==0&&g5<180))return tw(Z)}else return m--,h50(L8());let J=(Z<<5^(Z>1?e0.getUint16(m):Z>0?X0[m]:0))&4095,X=R50[J],$=m,Y=m+Z-3,Q,K=0;if(X&&X.bytes==Z){while($<Y){if(Q=e0.getUint32($),Q!=X[K++]){$=1879048192;break}$+=4}Y+=3;while($<Y)if(Q=X0[$++],Q!=X[K++]){$=1879048192;break}if($===Y)return m=$,X.string;Y-=3,$=m}X=[],R50[J]=X,X.bytes=Z;while($<Y)Q=e0.getUint32($),X.push(Q),$+=4;Y+=3;while($<Y)Q=X0[$++],X.push(Q);let W=Z<16?HT(Z):_50(Z);if(W!=null)return X.string=W;return X.string=tw(Z)}function h50(Z){if(typeof Z==="string")return Z;if(typeof Z==="number"||typeof Z==="boolean"||typeof Z==="bigint")return Z.toString();if(Z==null)return Z+"";if(f1.allowArraysInMapKeys&&Array.isArray(Z)&&Z.flat().every((J)=>["string","number","boolean","bigint"].includes(typeof J)))return Z.flat().toString();throw new Error(`Invalid property type for record: ${typeof Z}`)}var O50=(Z,J)=>{let X=L8().map(h50),$=Z;if(J!==void 0)Z=Z<32?-((J<<5)+Z):(J<<5)+Z,X.highByte=J;let Y=Y1[Z];if(Y&&(Y.isShared||QX))(Y1.restoreStructures||(Y1.restoreStructures=[]))[Z]=Y;return Y1[Z]=X,X.read=vT(X,$),X.read()};L5[0]=()=>{};L5[0].noBuffer=!0;L5[66]=(Z)=>{let J=Z.length,X=BigInt(Z[0]&128?Z[0]-256:Z[0]);for(let $=1;$<J;$++)X<<=BigInt(8),X+=BigInt(Z[$]);return X};var Th1={Error,TypeError,ReferenceError};L5[101]=()=>{let Z=L8();return(Th1[Z[0]]||Error)(Z[1],{cause:Z[2]})};L5[105]=(Z)=>{if(f1.structuredClone===!1)throw new Error("Structured clone extension is disabled");let J=e0.getUint32(m-4);if(!SZ)SZ=new Map;let X=X0[m],$;if(X>=144&&X<160||X==220||X==221)$=[];else if(X>=128&&X<144||X==222||X==223)$=new Map;else if((X>=199&&X<=201||X>=212&&X<=216)&&X0[m+1]===115)$=new Set;else $={};let Y={target:$};SZ.set(J,Y);let Q=L8();if(!Y.used)return Y.target=Q;else Object.assign($,Q);if($ instanceof Map)for(let[K,W]of Q.entries())$.set(K,W);if($ instanceof Set)for(let K of Array.from(Q))$.add(K);return $};L5[112]=(Z)=>{if(f1.structuredClone===!1)throw new Error("Structured clone extension is disabled");let J=e0.getUint32(m-4),X=SZ.get(J);return X.used=!0,X.target};L5[115]=()=>new Set(L8());var qT=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map((Z)=>Z+"Array"),Ch1=typeof globalThis==="object"?globalThis:window;L5[116]=(Z)=>{let J=Z[0],X=Uint8Array.prototype.slice.call(Z,1).buffer,$=qT[J];if(!$){if(J===16)return X;if(J===17)return new DataView(X);throw new Error("Could not find typed array for code "+J)}return new Ch1[$](X)};L5[120]=()=>{let Z=L8();return new RegExp(Z[0],Z[1])};var fh1=[];L5[98]=(Z)=>{let J=(Z[0]<<24)+(Z[1]<<16)+(Z[2]<<8)+Z[3],X=m;return m+=J-Z.length,S8=fh1,S8=[M50(),M50()],S8.position0=0,S8.position1=0,S8.postBundlePosition=m,m=X,L8()};L5[255]=(Z)=>{if(Z.length==4)return new Date((Z[0]*16777216+(Z[1]<<16)+(Z[2]<<8)+Z[3])*1000);else if(Z.length==8)return new Date(((Z[0]<<22)+(Z[1]<<14)+(Z[2]<<6)+(Z[3]>>2))/1e6+((Z[3]&3)*4294967296+Z[4]*16777216+(Z[5]<<16)+(Z[6]<<8)+Z[7])*1000);else if(Z.length==12)return new Date(((Z[0]<<24)+(Z[1]<<16)+(Z[2]<<8)+Z[3])/1e6+((Z[4]&128?-281474976710656:0)+Z[6]*1099511627776+Z[7]*4294967296+Z[8]*16777216+(Z[9]<<16)+(Z[10]<<8)+Z[11])*1000);else return new Date("invalid")};function S50(Z){if(GT)GT();let J=g5,X=m,$=iz,Y=i5,Q=P4,K=hZ,W=JY,G=SZ,z=S8,V=new Uint8Array(X0.slice(0,g5)),H=Y1,v=Y1.slice(0,Y1.length),q=f1,F=QX,c=Z();return g5=J,m=X,iz=$,i5=Y,P4=Q,hZ=K,JY=W,SZ=G,S8=z,X0=V,QX=F,Y1=H,Y1.splice(0,Y1.length,...v),f1=q,e0=new DataView(X0.buffer,X0.byteOffset,X0.byteLength),c}function ew(){X0=null,SZ=null,Y1=null}var $Y=new Array(147);for(let Z=0;Z<256;Z++)$Y[Z]=+("1e"+Math.floor(45.15-Z*0.30103));var Jx=new AZ({useRecords:!1}),kh1=Jx.unpack,Eh1=Jx.unpackMultiple,Ih1=Jx.unpack,gz={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4},_h1=new Float32Array(1),nh6=new Uint8Array(_h1.buffer,0,4);function A50(Z,J,X){KT=Z,WT=J,GT=X}var $x;try{$x=new TextEncoder}catch(Z){}var wT,l50,az=typeof Buffer!=="undefined",Xx=az?function(Z){return Buffer.allocUnsafeSlow(Z)}:Uint8Array,y50=az?Buffer:Uint8Array,m50=az?4294967296:2144337920,n,dz,h1,y=0,a6,o1=null,p50,bh1=21760,hh1=/[\u0080-\uFFFF]/,w7=Symbol("record-id");class YY extends AZ{constructor(Z){super(Z);this.offset=0;let J,X,$,Y,Q,K=y50.prototype.utf8Write?function(f,C){return n.utf8Write(f,C,n.byteLength-C)}:$x&&$x.encodeInto?function(f,C){return $x.encodeInto(f,n.subarray(C)).written}:!1,W=this;if(!Z)Z={};let G=Z&&Z.sequential,z=Z.structures||Z.saveStructures,V=Z.maxSharedStructures;if(V==null)V=z?32:0;if(V>8160)throw new Error("Maximum maxSharedStructure is 8160");if(Z.structuredClone&&Z.moreTypes==null)this.moreTypes=!0;let H=Z.maxOwnStructures;if(H==null)H=z?32:64;if(!this.structures&&Z.useRecords!=!1)this.structures=[];let v=V>32||H+V>64,q=V+64,F=V+H+64;if(F>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let c=[],w=0,x=0;this.pack=this.encode=function(f,C){if(!n)n=new Xx(8192),h1=n.dataView||(n.dataView=new DataView(n.buffer,0,8192)),y=0;if(a6=n.length-10,a6-y<2048)n=new Xx(n.length),h1=n.dataView||(n.dataView=new DataView(n.buffer,0,n.length)),a6=n.length-10,y=0;else y=y+7&2147483640;if(X=y,C&ph1)y+=C&255;if(Q=W.structuredClone?new Map:null,W.bundleStrings&&typeof f!=="string")o1=[],o1.size=1/0;else o1=null;if(Y=W.structures,Y){if(Y.uninitialized)Y=W._mergeStructures(W.getStructures());let I=Y.sharedLength||0;if(I>V)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+Y.sharedLength);if(!Y.transitions){Y.transitions=Object.create(null);for(let a=0;a<I;a++){let s=Y[a];if(!s)continue;let Z0,o=Y.transitions;for(let M0=0,R0=s.length;M0<R0;M0++){let m0=s[M0];if(Z0=o[m0],!Z0)Z0=o[m0]=Object.create(null);o=Z0}o[w7]=a+64}this.lastNamedStructuresLength=I}if(!G)Y.nextId=I+64}if($)$=!1;let b;try{if(W.randomAccessStructure&&f&&f.constructor&&f.constructor===Object)h(f);else L(f);let I=o1;if(o1)u50(X,L,0);if(Q&&Q.idsToInsert){let a=Q.idsToInsert.sort((M0,R0)=>M0.offset>R0.offset?1:-1),s=a.length,Z0=-1;while(I&&s>0){let M0=a[--s].offset+X;if(M0<I.stringsPosition+X&&Z0===-1)Z0=0;if(M0>I.position+X){if(Z0>=0)Z0+=6}else{if(Z0>=0)h1.setUint32(I.position+X,h1.getUint32(I.position+X)+Z0),Z0=-1;I=I.previous,s++}}if(Z0>=0&&I)h1.setUint32(I.position+X,h1.getUint32(I.position+X)+Z0);if(y+=a.length*6,y>a6)N(y);W.offset=y;let o=Ah1(n.subarray(X,y),a);return Q=null,o}if(W.offset=y,C&lh1)return n.start=X,n.end=y,n;return n.subarray(X,y)}catch(I){throw b=I,I}finally{if(Y){if(j(),$&&W.saveStructures){let I=Y.sharedLength||0,a=n.subarray(X,y),s=i50(Y,W);if(!b){if(W.saveStructures(s,s.isCompatible)===!1)return W.pack(f,C);if(W.lastNamedStructuresLength=I,n.length>1073741824)n=null;return a}}}if(n.length>1073741824)n=null;if(C&yh1)y=X}};let j=()=>{if(x<10)x++;let f=Y.sharedLength||0;if(Y.length>f&&!G)Y.length=f;if(w>1e4){if(Y.transitions=null,x=0,w=0,c.length>0)c=[]}else if(c.length>0&&!G){for(let C=0,b=c.length;C<b;C++)c[C][w7]=0;c=[]}},B=(f)=>{var C=f.length;if(C<16)n[y++]=144|C;else if(C<65536)n[y++]=220,n[y++]=C>>8,n[y++]=C&255;else n[y++]=221,h1.setUint32(y,C),y+=4;for(let b=0;b<C;b++)L(f[b])},L=(f)=>{if(y>a6)n=N(y);var C=typeof f,b;if(C==="string"){let I=f.length;if(o1&&I>=4&&I<4096){if((o1.size+=I)>bh1){let o,M0=(o1[0]?o1[0].length*3+o1[1].length:0)+10;if(y+M0>a6)n=N(y+M0);let R0;if(o1.position)R0=o1,n[y]=200,y+=3,n[y++]=98,o=y-X,y+=4,u50(X,L,0),h1.setUint16(o+X-3,y-X-o);else n[y++]=214,n[y++]=98,o=y-X,y+=4;o1=["",""],o1.previous=R0,o1.size=0,o1.position=o}let Z0=hh1.test(f);o1[Z0?0:1]+=f,n[y++]=193,L(Z0?-I:I);return}let a;if(I<32)a=1;else if(I<256)a=2;else if(I<65536)a=3;else a=5;let s=I*3;if(y+s>a6)n=N(y+s);if(I<64||!K){let Z0,o,M0,R0=y+a;for(Z0=0;Z0<I;Z0++)if(o=f.charCodeAt(Z0),o<128)n[R0++]=o;else if(o<2048)n[R0++]=o>>6|192,n[R0++]=o&63|128;else if((o&64512)===55296&&((M0=f.charCodeAt(Z0+1))&64512)===56320)o=65536+((o&1023)<<10)+(M0&1023),Z0++,n[R0++]=o>>18|240,n[R0++]=o>>12&63|128,n[R0++]=o>>6&63|128,n[R0++]=o&63|128;else n[R0++]=o>>12|224,n[R0++]=o>>6&63|128,n[R0++]=o&63|128;b=R0-y-a}else b=K(f,y+a);if(b<32)n[y++]=160|b;else if(b<256){if(a<2)n.copyWithin(y+2,y+1,y+1+b);n[y++]=217,n[y++]=b}else if(b<65536){if(a<3)n.copyWithin(y+3,y+2,y+2+b);n[y++]=218,n[y++]=b>>8,n[y++]=b&255}else{if(a<5)n.copyWithin(y+5,y+3,y+3+b);n[y++]=219,h1.setUint32(y,b),y+=4}y+=b}else if(C==="number")if(f>>>0===f)if(f<32||f<128&&this.useRecords===!1||f<64&&!this.randomAccessStructure)n[y++]=f;else if(f<256)n[y++]=204,n[y++]=f;else if(f<65536)n[y++]=205,n[y++]=f>>8,n[y++]=f&255;else n[y++]=206,h1.setUint32(y,f),y+=4;else if(f>>0===f)if(f>=-32)n[y++]=256+f;else if(f>=-128)n[y++]=208,n[y++]=f+256;else if(f>=-32768)n[y++]=209,h1.setInt16(y,f),y+=2;else n[y++]=210,h1.setInt32(y,f),y+=4;else{let I;if((I=this.useFloat32)>0&&f<4294967296&&f>=-2147483648){n[y++]=202,h1.setFloat32(y,f);let a;if(I<4||(a=f*$Y[(n[y]&127)<<1|n[y+1]>>7])>>0===a){y+=4;return}else y--}n[y++]=203,h1.setFloat64(y,f),y+=8}else if(C==="object"||C==="function")if(!f)n[y++]=192;else{if(Q){let a=Q.get(f);if(a){if(!a.id){let s=Q.idsToInsert||(Q.idsToInsert=[]);a.id=s.push(a)}n[y++]=214,n[y++]=112,h1.setUint32(y,a.id),y+=4;return}else Q.set(f,{offset:y-X})}let I=f.constructor;if(I===Object)P(f);else if(I===Array)B(f);else if(I===Map)if(this.mapAsEmptyObject)n[y++]=128;else{if(b=f.size,b<16)n[y++]=128|b;else if(b<65536)n[y++]=222,n[y++]=b>>8,n[y++]=b&255;else n[y++]=223,h1.setUint32(y,b),y+=4;for(let[a,s]of f)L(a),L(s)}else{for(let a=0,s=wT.length;a<s;a++){let Z0=l50[a];if(f instanceof Z0){let o=wT[a];if(o.write){if(o.type)n[y++]=212,n[y++]=o.type,n[y++]=0;let s0=o.write.call(this,f);if(s0===f)if(Array.isArray(f))B(f);else P(f);else L(s0);return}let M0=n,R0=h1,m0=y;n=null;let O1;try{O1=o.pack.call(this,f,(s0)=>{if(n=M0,M0=null,y+=s0,y>a6)N(y);return{target:n,targetView:h1,position:y-s0}},L)}finally{if(M0)n=M0,h1=R0,y=m0,a6=n.length-10}if(O1){if(O1.length+y>a6)N(O1.length+y);y=Sh1(O1,n,y,o.type)}return}}if(Array.isArray(f))B(f);else{if(f.toJSON){let a=f.toJSON();if(a!==f)return L(a)}if(C==="function")return L(this.writeFunction&&this.writeFunction(f));P(f)}}}else if(C==="boolean")n[y++]=f?195:194;else if(C==="bigint"){if(f<9223372036854776000&&f>=-9223372036854776000)n[y++]=211,h1.setBigInt64(y,f);else if(f<18446744073709552000&&f>0)n[y++]=207,h1.setBigUint64(y,f);else if(this.largeBigIntToFloat)n[y++]=203,h1.setFloat64(y,Number(f));else if(this.largeBigIntToString)return L(f.toString());else if((this.useBigIntExtension||this.moreTypes)&&f<BigInt(2)**BigInt(1023)&&f>-(BigInt(2)**BigInt(1023))){n[y++]=199,y++,n[y++]=66;let I=[],a;do{let s=f&BigInt(255);a=(s&BigInt(128))===(f<BigInt(0)?BigInt(128):BigInt(0)),I.push(s),f>>=BigInt(8)}while(!((f===BigInt(0)||f===BigInt(-1))&&a));n[y-2]=I.length;for(let s=I.length;s>0;)n[y++]=Number(I[--s]);return}else throw new RangeError(f+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string");y+=8}else if(C==="undefined")if(this.encodeUndefinedAsNil)n[y++]=192;else n[y++]=212,n[y++]=0,n[y++]=0;else throw new Error("Unknown type: "+C)},R=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?(f)=>{let C;if(this.skipValues){C=[];for(let a in f)if((typeof f.hasOwnProperty!=="function"||f.hasOwnProperty(a))&&!this.skipValues.includes(f[a]))C.push(a)}else C=Object.keys(f);let b=C.length;if(b<16)n[y++]=128|b;else if(b<65536)n[y++]=222,n[y++]=b>>8,n[y++]=b&255;else n[y++]=223,h1.setUint32(y,b),y+=4;let I;if(this.coercibleKeyAsNumber)for(let a=0;a<b;a++){I=C[a];let s=Number(I);L(isNaN(s)?I:s),L(f[I])}else for(let a=0;a<b;a++)L(I=C[a]),L(f[I])}:(f)=>{n[y++]=222;let C=y-X;y+=2;let b=0;for(let I in f)if(typeof f.hasOwnProperty!=="function"||f.hasOwnProperty(I))L(I),L(f[I]),b++;if(b>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');n[C+++X]=b>>8,n[C+X]=b&255},M=this.useRecords===!1?R:Z.progressiveRecords&&!v?(f)=>{let C,b=Y.transitions||(Y.transitions=Object.create(null)),I=y++-X,a;for(let s in f)if(typeof f.hasOwnProperty!=="function"||f.hasOwnProperty(s)){if(C=b[s],C)b=C;else{let Z0=Object.keys(f),o=b;b=Y.transitions;let M0=0;for(let R0=0,m0=Z0.length;R0<m0;R0++){let O1=Z0[R0];if(C=b[O1],!C)C=b[O1]=Object.create(null),M0++;b=C}if(I+X+1==y)y--,_(b,Z0,M0);else k(b,Z0,I,M0);a=!0,b=o[s]}L(f[s])}if(!a){let s=b[w7];if(s)n[I+X]=s;else k(b,Object.keys(f),I,0)}}:(f)=>{let C,b=Y.transitions||(Y.transitions=Object.create(null)),I=0;for(let s in f)if(typeof f.hasOwnProperty!=="function"||f.hasOwnProperty(s)){if(C=b[s],!C)C=b[s]=Object.create(null),I++;b=C}let a=b[w7];if(a)if(a>=96&&v)n[y++]=((a-=96)&31)+96,n[y++]=a>>5;else n[y++]=a;else _(b,b.__keys__||Object.keys(f),I);for(let s in f)if(typeof f.hasOwnProperty!=="function"||f.hasOwnProperty(s))L(f[s])},O=typeof this.useRecords=="function"&&this.useRecords,P=O?(f)=>{O(f)?M(f):R(f)}:M,N=(f)=>{let C;if(f>16777216){if(f-X>m50)throw new Error("Packed buffer would be larger than maximum buffer size");C=Math.min(m50,Math.round(Math.max((f-X)*(f>67108864?1.25:2),4194304)/4096)*4096)}else C=(Math.max(f-X<<2,n.length-1)>>12)+1<<12;let b=new Xx(C);if(h1=b.dataView||(b.dataView=new DataView(b.buffer,0,C)),f=Math.min(f,n.length),n.copy)n.copy(b,0,X,f);else b.set(n.slice(X,f));return y-=X,X=0,a6=b.length-10,n=b},_=(f,C,b)=>{let I=Y.nextId;if(!I)I=64;if(I<q&&this.shouldShareStructure&&!this.shouldShareStructure(C)){if(I=Y.nextOwnId,!(I<F))I=q;Y.nextOwnId=I+1}else{if(I>=F)I=q;Y.nextId=I+1}let a=C.highByte=I>=96&&v?I-96>>5:-1;if(f[w7]=I,f.__keys__=C,Y[I-64]=C,I<q)if(C.isShared=!0,Y.sharedLength=I-63,$=!0,a>=0)n[y++]=(I&31)+96,n[y++]=a;else n[y++]=I;else{if(a>=0)n[y++]=213,n[y++]=114,n[y++]=(I&31)+96,n[y++]=a;else n[y++]=212,n[y++]=114,n[y++]=I;if(b)w+=x*b;if(c.length>=H)c.shift()[w7]=0;c.push(f),L(C)}},k=(f,C,b,I)=>{let a=n,s=y,Z0=a6,o=X;if(n=dz,y=0,X=0,!n)dz=n=new Xx(8192);a6=n.length-10,_(f,C,I),dz=n;let M0=y;if(n=a,y=s,a6=Z0,X=o,M0>1){let R0=y+M0-1;if(R0>a6)N(R0);let m0=b+X;n.copyWithin(m0+M0,m0+1,y),n.set(dz.slice(0,M0),m0),y=R0}else n[b+X]=dz[0]},h=(f)=>{let C=p50(f,n,X,y,Y,N,(b,I,a)=>{if(a)return $=!0;y=I;let s=n;if(L(b),j(),s!==n)return{position:y,targetView:h1,target:n};return y},this);if(C===0)return P(f);y=C}}useBuffer(Z){n=Z,n.dataView||(n.dataView=new DataView(n.buffer,n.byteOffset,n.byteLength)),y=0}set position(Z){y=Z}get position(){return y}clearSharedData(){if(this.structures)this.structures=[];if(this.typedStructs)this.typedStructs=[]}}l50=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,Zx];wT=[{pack(Z,J,X){let $=Z.getTime()/1000;if((this.useTimestamp32||Z.getMilliseconds()===0)&&$>=0&&$<4294967296){let{target:Y,targetView:Q,position:K}=J(6);Y[K++]=214,Y[K++]=255,Q.setUint32(K,$)}else if($>0&&$<4294967296){let{target:Y,targetView:Q,position:K}=J(10);Y[K++]=215,Y[K++]=255,Q.setUint32(K,Z.getMilliseconds()*4000000+($/1000/4294967296>>0)),Q.setUint32(K+4,$)}else if(isNaN($)){if(this.onInvalidDate)return J(0),X(this.onInvalidDate());let{target:Y,targetView:Q,position:K}=J(3);Y[K++]=212,Y[K++]=255,Y[K++]=255}else{let{target:Y,targetView:Q,position:K}=J(15);Y[K++]=199,Y[K++]=12,Y[K++]=255,Q.setUint32(K,Z.getMilliseconds()*1e6),Q.setBigInt64(K+4,BigInt(Math.floor($)))}}},{pack(Z,J,X){if(this.setAsEmptyObject)return J(0),X({});let $=Array.from(Z),{target:Y,position:Q}=J(this.moreTypes?3:0);if(this.moreTypes)Y[Q++]=212,Y[Q++]=115,Y[Q++]=0;X($)}},{pack(Z,J,X){let{target:$,position:Y}=J(this.moreTypes?3:0);if(this.moreTypes)$[Y++]=212,$[Y++]=101,$[Y++]=0;X([Z.name,Z.message,Z.cause])}},{pack(Z,J,X){let{target:$,position:Y}=J(this.moreTypes?3:0);if(this.moreTypes)$[Y++]=212,$[Y++]=120,$[Y++]=0;X([Z.source,Z.flags])}},{pack(Z,J){if(this.moreTypes)FT(Z,16,J);else cT(az?Buffer.from(Z):new Uint8Array(Z),J)}},{pack(Z,J){let X=Z.constructor;if(X!==y50&&this.moreTypes)FT(Z,qT.indexOf(X.name),J);else cT(Z,J)}},{pack(Z,J){if(this.moreTypes)FT(Z,17,J);else cT(az?Buffer.from(Z):new Uint8Array(Z),J)}},{pack(Z,J){let{target:X,position:$}=J(1);X[$]=193}}];function FT(Z,J,X,$){let Y=Z.byteLength;if(Y+1<256){var{target:Q,position:K}=X(4+Y);Q[K++]=199,Q[K++]=Y+1}else if(Y+1<65536){var{target:Q,position:K}=X(5+Y);Q[K++]=200,Q[K++]=Y+1>>8,Q[K++]=Y+1&255}else{var{target:Q,position:K,targetView:W}=X(7+Y);Q[K++]=201,W.setUint32(K,Y+1),K+=4}if(Q[K++]=116,Q[K++]=J,!Z.buffer)Z=new Uint8Array(Z);Q.set(new Uint8Array(Z.buffer,Z.byteOffset,Z.byteLength),K)}function cT(Z,J){let X=Z.byteLength;var $,Y;if(X<256){var{target:$,position:Y}=J(X+2);$[Y++]=196,$[Y++]=X}else if(X<65536){var{target:$,position:Y}=J(X+3);$[Y++]=197,$[Y++]=X>>8,$[Y++]=X&255}else{var{target:$,position:Y,targetView:Q}=J(X+5);$[Y++]=198,Q.setUint32(Y,X),Y+=4}$.set(Z,Y)}function Sh1(Z,J,X,$){let Y=Z.length;switch(Y){case 1:J[X++]=212;break;case 2:J[X++]=213;break;case 4:J[X++]=214;break;case 8:J[X++]=215;break;case 16:J[X++]=216;break;default:if(Y<256)J[X++]=199,J[X++]=Y;else if(Y<65536)J[X++]=200,J[X++]=Y>>8,J[X++]=Y&255;else J[X++]=201,J[X++]=Y>>24,J[X++]=Y>>16&255,J[X++]=Y>>8&255,J[X++]=Y&255}return J[X++]=$,J.set(Z,X),X+=Y,X}function Ah1(Z,J){let X,$=J.length*6,Y=Z.length-$;while(X=J.pop()){let{offset:Q,id:K}=X;Z.copyWithin(Q+$,Q,Y),$-=6;let W=Q+$;Z[W++]=214,Z[W++]=105,Z[W++]=K>>24,Z[W++]=K>>16&255,Z[W++]=K>>8&255,Z[W++]=K&255,Y=Q}return Z}function u50(Z,J,X){if(o1.length>0){h1.setUint32(o1.position+Z,y+X-o1.position-Z),o1.stringsPosition=y-Z;let $=o1;o1=null,J($[0]),J($[1])}}function i50(Z,J){return Z.isCompatible=(X)=>{let $=!X||(J.lastNamedStructuresLength||0)===X.length;if(!$)J._mergeStructures(X);return $},Z}function g50(Z,J){p50=Z,i50=J}var d50=new YY({useRecords:!1}),mh1=d50.pack,uh1=d50.pack;var lh1=512,yh1=1024,ph1=2048;var xT=3,n3=0,nz=2,Yx=1,jT=16,n50=["num","object","string","ascii"];n50[jT]="date";var gh1=[!1,!0,!0,!1,!1,!0,!0,!1],s50;try{new Function(""),s50=!0}catch(Z){}var QY,dh1=typeof Buffer!=="undefined",Qx,x7;try{Qx=new TextEncoder}catch(Z){}var ah1=dh1?function(Z,J,X){return Z.utf8Write(J,X,Z.byteLength-X)}:Qx&&Qx.encodeInto?function(Z,J,X){return Qx.encodeInto(J,Z.subarray(X)).written}:!1,$S6=Symbol("type"),YS6=Symbol("parent");g50(o50,th1);function o50(Z,J,X,$,Y,Q,K,W){let G=W.typedStructs||(W.typedStructs=[]),z=J.dataView,V=(G.lastStringStart||100)+$,H=J.length-10,v=$;if($>H)J=Q($),z=J.dataView,$-=X,v-=X,V-=X,X=0,H=J.length-10;let q,F=V,c=G.transitions||(G.transitions=Object.create(null)),w=G.nextId||G.length,x=w<15?1:w<240?2:w<61440?3:w<15728640?4:0;if(x===0)return 0;$+=x;let j=[],B,L=0;for(let M in Z){let O=Z[M],P=c[M];if(!P)c[M]=P={key:M,parent:c,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null};if($>H)J=Q($),z=J.dataView,$-=X,v-=X,V-=X,F-=X,X=0,H=J.length-10;switch(typeof O){case"number":let N=O;if(w<200||!P.num64){if(N>>0===N&&N<536870912&&N>-520093696){if(N<246&&N>=0&&(P.num8&&!(w>200&&P.num32)||N<32&&!P.num32))c=P.num8||D5(P,n3,1),J[$++]=N;else c=P.num32||D5(P,n3,4),z.setUint32($,N,!0),$+=4;break}else if(N<4294967296&&N>=-2147483648){if(z.setFloat32($,N,!0),gh1[J[$+3]>>>5]){let f;if((f=N*$Y[(J[$+3]&127)<<1|J[$+2]>>7])>>0===f){c=P.num32||D5(P,n3,4),$+=4;break}}}}c=P.num64||D5(P,n3,8),z.setFloat64($,N,!0),$+=8;break;case"string":let _=O.length;if(q=F-V,(_<<2)+F>H)J=Q((_<<2)+F),z=J.dataView,$-=X,v-=X,V-=X,F-=X,X=0,H=J.length-10;if(_>65280+q>>2){j.push(M,O,$-v);break}let k,h=F;if(_<64){let f,C,b;for(f=0;f<_;f++)if(C=O.charCodeAt(f),C<128)J[F++]=C;else if(C<2048)k=!0,J[F++]=C>>6|192,J[F++]=C&63|128;else if((C&64512)===55296&&((b=O.charCodeAt(f+1))&64512)===56320)k=!0,C=65536+((C&1023)<<10)+(b&1023),f++,J[F++]=C>>18|240,J[F++]=C>>12&63|128,J[F++]=C>>6&63|128,J[F++]=C&63|128;else k=!0,J[F++]=C>>12|224,J[F++]=C>>6&63|128,J[F++]=C&63|128}else F+=ah1(J,O,F),k=F-h>_;if(q<160||q<246&&(P.ascii8||P.string8)){if(k){if(!(c=P.string8))if(G.length>10&&(c=P.ascii8))c.__type=nz,P.ascii8=null,P.string8=c,K(null,0,!0);else c=D5(P,nz,1)}else if(q===0&&!B){B=!0,c=P.ascii0||D5(P,xT,0);break}else if(!(c=P.ascii8)&&!(G.length>10&&(c=P.string8)))c=D5(P,xT,1);J[$++]=q}else c=P.string16||D5(P,nz,2),z.setUint16($,q,!0),$+=2;break;case"object":if(O){if(O.constructor===Date)c=P.date64||D5(P,jT,8),z.setFloat64($,O.getTime(),!0),$+=8;else j.push(M,O,L);break}else if(P=a50(P,$,z,-10),P)c=P,$=QY;else j.push(M,O,L);break;case"boolean":c=P.num8||P.ascii8||D5(P,n3,1),J[$++]=O?249:248;break;case"undefined":if(P=a50(P,$,z,-9),P)c=P,$=QY;else j.push(M,O,L);break;default:j.push(M,O,L)}L++}for(let M=0,O=j.length;M<O;){let P=j[M++],N=j[M++],_=j[M++],k=c[P];if(!k)c[P]=k={key:P,parent:c,enumerationOffset:_-L,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null};let h;if(N){let f;if(q=F-V,q<65280)if(c=k.object16,c)f=2;else if(c=k.object32)f=4;else c=D5(k,Yx,2),f=2;else c=k.object32||D5(k,Yx,4),f=4;if(h=K(N,F),typeof h==="object")F=h.position,z=h.targetView,J=h.target,V-=X,$-=X,v-=X,X=0;else F=h;if(f===2)z.setUint16($,q,!0),$+=2;else z.setUint32($,q,!0),$+=4}else c=k.object16||D5(k,Yx,2),z.setInt16($,N===null?-10:-9,!0),$+=2;L++}let R=c[w7];if(R==null){R=W.typedStructs.length;let M=[],O=c,P,N;while((N=O.__type)!==void 0){let _=O.__size;O=O.__parent,P=O.key;let k=[N,_,P];if(O.enumerationOffset)k.push(O.enumerationOffset);M.push(k),O=O.parent}M.reverse(),c[w7]=R,W.typedStructs[R]=M,K(null,0,!0)}switch(x){case 1:if(R>=16)return 0;J[v]=R+32;break;case 2:if(R>=256)return 0;J[v]=56,J[v+1]=R;break;case 3:if(R>=65536)return 0;J[v]=57,z.setUint16(v+1,R,!0);break;case 4:if(R>=16777216)return 0;z.setUint32(v,(R<<8)+58,!0);break}if($<V){if(V===F)return $;J.copyWithin($,V,F),F+=$-V,G.lastStringStart=$-v}else if($>V){if(V===F)return $;return G.lastStringStart=$-v,o50(Z,J,X,v,Y,Q,K,W)}return F}function a50(Z,J,X,$){let Y;if(Y=Z.ascii8||Z.num8)return X.setInt8(J,$,!0),QY=J+1,Y;if(Y=Z.string16||Z.object16)return X.setInt16(J,$,!0),QY=J+2,Y;if(Y=Z.num32)return X.setUint32(J,3758096640+$,!0),QY=J+4,Y;if(Y=Z.num64)return X.setFloat64(J,NaN,!0),X.setInt8(J,$),QY=J+8,Y;QY=J;return}function D5(Z,J,X){let $=n50[J]+(X<<3),Y=Z[$]||(Z[$]=Object.create(null));return Y.__type=J,Y.__size=X,Y.__parent=Z,Y}function nh1(Z){if(!(Z instanceof Map))return Z;let J=Z.get("typed")||[];if(Object.isFrozen(J))J=J.map((Y)=>Y.slice(0));let X=Z.get("named"),$=Object.create(null);for(let Y=0,Q=J.length;Y<Q;Y++){let K=J[Y],W=$;for(let[G,z,V]of K){let H=W[V];if(!H)W[V]=H={key:V,parent:W,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null};W=D5(H,G,z)}W[w7]=Y}return J.transitions=$,this.typedStructs=J,this.lastTypedStructuresLength=J.length,X}var UT=Symbol.for("source");function sh1(Z,J,X,$){let Y=Z[J++]-32;if(Y>=24)switch(Y){case 24:Y=Z[J++];break;case 25:Y=Z[J++]+(Z[J++]<<8);break;case 26:Y=Z[J++]+(Z[J++]<<8)+(Z[J++]<<16);break;case 27:Y=Z[J++]+(Z[J++]<<8)+(Z[J++]<<16)+(Z[J++]<<24);break}let Q=$.typedStructs&&$.typedStructs[Y];if(!Q){if(Z=Uint8Array.prototype.slice.call(Z,J,X),X-=J,J=0,!$.getStructures)throw new Error(`Reference to shared structure ${Y} without getStructures method`);if($._mergeStructures($.getStructures()),!$.typedStructs)throw new Error("Could not find any shared typed structures");if($.lastTypedStructuresLength=$.typedStructs.length,Q=$.typedStructs[Y],!Q)throw new Error("Could not find typed structure "+Y)}var{construct:K,fullConstruct:W}=Q;if(!K){K=Q.construct=function q(){},W=Q.fullConstruct=function q(){},W.prototype=$.structPrototype??{};var G=K.prototype=$.structPrototype?Object.create($.structPrototype):{};let V=[],H=0,v;for(let q=0,F=Q.length;q<F;q++){let c=Q[q],[w,x,j,B]=c;if(j==="__proto__")j="__proto_";let L={key:j,offset:H};if(B)V.splice(q+B,0,L);else V.push(L);let R;switch(x){case 0:R=()=>0;break;case 1:R=(O,P)=>{let N=O.bytes[P+L.offset];return N>=246?a3(N):N};break;case 2:R=(O,P)=>{let N=O.bytes,k=(N.dataView||(N.dataView=new DataView(N.buffer,N.byteOffset,N.byteLength))).getUint16(P+L.offset,!0);return k>=65280?a3(k&255):k};break;case 4:R=(O,P)=>{let N=O.bytes,k=(N.dataView||(N.dataView=new DataView(N.buffer,N.byteOffset,N.byteLength))).getUint32(P+L.offset,!0);return k>=4294967040?a3(k&255):k};break}L.getRef=R,H+=x;let M;switch(w){case xT:if(v&&!v.next)v.next=L;v=L,L.multiGetCount=0,M=function(O){let{bytes:P,position:N}=O,_=H+N,k=R(O,N);if(typeof k!=="number")return k;let h,f=L.next;while(f){if(h=f.getRef(O,N),typeof h==="number")break;else h=null;f=f.next}if(h==null)h=O.bytesEnd-_;if(O.srcString)return O.srcString.slice(k,h);return I50(P,k+_,h-k)};break;case nz:case Yx:if(v&&!v.next)v.next=L;v=L,M=function(O){let P=O.position,N=H+P,_=R(O,P);if(typeof _!=="number")return _;let k=O.bytes,h,f=L.next;while(f){if(h=f.getRef(O,P),typeof h==="number")break;else h=null;f=f.next}if(h==null)h=O.bytesEnd-N;if(w===nz)return k.toString("utf8",_+N,h+N);else{x7=O;try{return $.unpack(k,{start:_+N,end:h+N})}finally{x7=null}}};break;case n3:switch(x){case 4:M=function(O){let P=O.bytes,N=P.dataView||(P.dataView=new DataView(P.buffer,P.byteOffset,P.byteLength)),_=O.position+L.offset,k=N.getInt32(_,!0);if(k<536870912){if(k>-520093696)return k;if(k>-536870912)return a3(k&255)}let h=N.getFloat32(_,!0),f=$Y[(P[_+3]&127)<<1|P[_+2]>>7];return(f*h+(h>0?0.5:-0.5)>>0)/f};break;case 8:M=function(O){let P=O.bytes,_=(P.dataView||(P.dataView=new DataView(P.buffer,P.byteOffset,P.byteLength))).getFloat64(O.position+L.offset,!0);if(isNaN(_)){let k=P[O.position+L.offset];if(k>=246)return a3(k)}return _};break;case 1:M=function(O){let N=O.bytes[O.position+L.offset];return N<246?N:a3(N)};break}break;case jT:M=function(O){let P=O.bytes,N=P.dataView||(P.dataView=new DataView(P.buffer,P.byteOffset,P.byteLength));return new Date(N.getFloat64(O.position+L.offset,!0))};break}L.get=M}if(s50){let q=[],F=[],c=0,w;for(let j of V){if($.alwaysLazyProperty&&$.alwaysLazyProperty(j.key)){w=!0;continue}Object.defineProperty(G,j.key,{get:oh1(j.get),enumerable:!0});let B="v"+c++;F.push(B),q.push("o["+JSON.stringify(j.key)+"]="+B+"(s)")}if(w)q.push("__proto__:this");let x=new Function(...F,"var c=this;return function(s){var o=new c();"+q.join(";")+";return o;}").apply(W,V.map((j)=>j.get));Object.defineProperty(G,"toJSON",{value(j){return x.call(this,this[UT])}})}else Object.defineProperty(G,"toJSON",{value(q){let F={};for(let c=0,w=V.length;c<w;c++){let x=V[c].key;F[x]=this[x]}return F}})}var z=new K;return z[UT]={bytes:Z,position:J,srcString:"",bytesEnd:X},z}function a3(Z){switch(Z){case 246:return null;case 247:return;case 248:return!1;case 249:return!0}throw new Error("Unknown constant")}function oh1(Z){return function(){return Z(this[UT])}}function rh1(){if(x7)x7.bytes=Uint8Array.prototype.slice.call(x7.bytes,x7.position,x7.bytesEnd),x7.position=0,x7.bytesEnd=x7.bytes.length}function th1(Z,J){if(J.typedStructs){let $=new Map;$.set("named",Z),$.set("typed",J.typedStructs),Z=$}let X=J.lastTypedStructuresLength||0;return Z.isCompatible=($)=>{let Y=!0;if($ instanceof Map){if(($.get("named")||[]).length!==(J.lastNamedStructuresLength||0))Y=!1;if(($.get("typed")||[]).length!==X)Y=!1}else if($ instanceof Array||Array.isArray($)){if($.length!==(J.lastNamedStructuresLength||0))Y=!1}if(!Y)J._mergeStructures($);return Y},J.lastTypedStructuresLength=J.typedStructs&&J.typedStructs.length,Z}A50(sh1,nh1,rh1);var JS1=process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase()==="true";if(!JS1){let Z;try{if(Z=i("msgpackr-extract"),Z)E50(Z.extractStrings)}catch(J){}}var QU=t(yY0(),1);import Mn1 from"http";import Rn1 from"https";import YU from"fs";import On1 from"path";import Nn1 from"url";var pY0=`-----BEGIN CERTIFICATE-----
405
+ }`});try{let $=(await J.next()).value?.data?.userById;if(!$)return p.warning(`PlatformGateway.getPlayerCosmetics(): No cosmetic data returned for user id "${Z}".`);let Y=$.equippedItems.map((W)=>({slot:W.slot,item:W.item.slots.find((G)=>G.type===W.slot)})).filter((W)=>!!W.item),Q=Number($.characterSettings?.hairStyle?.split("_")[1]||1),K=`https://d3qkovarww0lj1.cloudfront.net/?skin_tone=${$.characterSettings?.skinTone||"SKIN_COLOR_1"}&clothing=${$.characterSettings?.clothing||"CLOTHING_1"}&hair_style=${$.characterSettings?.hairStyle||"HAIR_STYLE_1"}&hair_color=${$.characterSettings?.hairColor||"HAIR_COLOR_1"}&eye_color=${$.characterSettings?.eyeColor||"00FF00"}`;return{equippedItems:Y,hairStyle:Q,skinTextureUri:K}}finally{await J.return?.()}}async getPlayerSession(Z){if(!this._creativeGateway)return;return await this._creativeGateway.getSession(Z)}async setGlobalData(Z,J){if(J.error)return p.warning("PlatformGateway.setGlobalData(): Cannot set data with an error property.");if(!this._creativeGateway&&process.env.NODE_ENV==="production")return p.warning("PlatformGateway.setGlobalData(): You are running in production mode, but the Platform Gateway is not initialized! No data will be set.");return this._creativeGateway?await this._creativeGateway.kv.set(Z,J):this._writeDevGlobalDataLocally(Z,J)}_readDevGlobalDataLocally(Z){try{if(!e$.existsSync(Ez))return{error:{code:"keyNotFound",message:"Local data directory not found."}};let J=X60.join(Ez,`${Z}.json`);return JSON.parse(e$.readFileSync(J,"utf8"))}catch(J){return p.warning(`PlatformGateway._readDevGlobalDataLocally(): Failed to read data for key "${Z}": ${J}`),{error:{code:"gatewayError",message:"Failed to read data for key."}}}}_writeDevGlobalDataLocally(Z,J){try{if(!e$.existsSync(Ez))e$.mkdirSync(Ez,{recursive:!0});let X=X60.join(Ez,`${Z}.json`),$={};if(e$.existsSync(X))$=JSON.parse(e$.readFileSync(X,"utf8"));let Y={...$,...J};e$.writeFileSync(X,JSON.stringify(Y,null,2),"utf8")}catch(X){p.warning(`PlatformGateway._writeDevGlobalDataLocally(): Failed to write data for key "${Z}": ${X}`)}}}class g3{static instance=new g3;_saveStatesClient;_playerData=new Map;constructor(){this._saveStatesClient=new Y60.SaveStatesClient}async getGlobalData(Z,J=3){for(let X=0;X<=J;X++){let $=await F7.instance.getGlobalData(Z);if($&&!$.error)return $;if($.error.code==="keyNotFound")return{};if(X<J)p.warning(`PersistenceManager.getGlobalData(): Failed to get global data, retrying. Response: ${JSON.stringify($)}`),await new Promise((Y)=>setTimeout(Y,500))}p.warning(`PersistenceManager.getGlobalData(): Failed to get global data after ${J} attempts.`);return}async getPlayerData(Z){let J=this._playerData.get(Z.id);if(!J){if(J=await this._saveStatesClient.load(this._getPlayerKey(Z)),!J)return p.warning(`PersistenceManager.getPlayerData(): Failed to get player data for player ${Z.id}. Persistence service may be down.`),{};this._playerData.set(Z.id,J)}return J}async setGlobalData(Z,J){let X=await F7.instance.setGlobalData(Z,J);if(!X||X.error){if(X?.error)p.warning(`PersistenceManager.setGlobalData(): ${X.error.message}`)}}async setPlayerData(Z,J){let X=await this.getPlayerData(Z);for(let[$,Y]of Object.entries(J))X[$]=Y}_getPlayerKey(Z){return`player-${Z.id}`}}var Q60;(($)=>{$[$.FIRST_PERSON=0]="FIRST_PERSON";$[$.THIRD_PERSON=1]="THIRD_PERSON";$[$.SPECTATOR=2]="SPECTATOR"})(Q60||={});var dP;((c)=>{c.LOOK_AT_ENTITY="PLAYER_CAMERA.LOOK_AT_ENTITY";c.LOOK_AT_POSITION="PLAYER_CAMERA.LOOK_AT_POSITION";c.SET_ATTACHED_TO_ENTITY="PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY";c.SET_ATTACHED_TO_POSITION="PLAYER_CAMERA.SET_ATTACHED_TO_POSITION";c.SET_FILM_OFFSET="PLAYER_CAMERA.SET_FILM_OFFSET";c.SET_FORWARD_OFFSET="PLAYER_CAMERA.SET_FORWARD_OFFSET";c.SET_FOV="PLAYER_CAMERA.SET_FOV";c.SET_MODEL_HIDDEN_NODES="PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES";c.SET_MODEL_SHOWN_NODES="PLAYER_CAMERA.SET_MODEL_SHOWN_NODES";c.SET_MODE="PLAYER_CAMERA.SET_MODE";c.SET_OFFSET="PLAYER_CAMERA.SET_OFFSET";c.SET_SHOULDER_ANGLE="PLAYER_CAMERA.SET_SHOULDER_ANGLE";c.SET_TRACKED_ENTITY="PLAYER_CAMERA.SET_TRACKED_ENTITY";c.SET_TRACKED_POSITION="PLAYER_CAMERA.SET_TRACKED_POSITION";c.SET_ZOOM="PLAYER_CAMERA.SET_ZOOM"})(dP||={});class Iz extends j0{player;_attachedToEntity;_attachedToPosition;_filmOffset=0;_forwardOffset=0;_fov=75;_modelHiddenNodes=new Set;_modelShownNodes=new Set;_mode=1;_offset={x:0,y:0,z:0};_orientation={pitch:0,yaw:0};_shoulderAngle=0;_trackedEntity;_trackedPosition;_zoom=1;constructor(Z){super();this.player=Z}get attachedToEntity(){return this._attachedToEntity}get attachedToPosition(){return this._attachedToPosition}get facingDirection(){return{x:-Math.sin(this._orientation.yaw)*Math.cos(this._orientation.pitch),y:Math.sin(this._orientation.pitch),z:-Math.cos(this._orientation.yaw)*Math.cos(this._orientation.pitch)}}get facingQuaternion(){let Z=this._orientation.pitch*0.5,J=this._orientation.yaw*0.5,X=Math.cos(Z),$=Math.sin(Z),Y=Math.cos(J),Q=Math.sin(J);return{x:$*Y,y:X*Q,z:-$*Q,w:X*Y}}get filmOffset(){return this._filmOffset}get forwardOffset(){return this._forwardOffset}get fov(){return this._fov}get modelHiddenNodes(){return this._modelHiddenNodes}get modelShownNodes(){return this._modelShownNodes}get mode(){return this._mode}get offset(){return this._offset}get orientation(){return this._orientation}get shoulderAngle(){return this._shoulderAngle}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get zoom(){return this._zoom}lookAtEntity(Z){if(!this._requirePlayerWorld("lookAtEntity"))return;this.emitWithWorld(this.player.world,"PLAYER_CAMERA.LOOK_AT_ENTITY",{playerCamera:this,entity:Z})}lookAtPosition(Z){if(!this._requirePlayerWorld("lookAtPosition"))return;this.emitWithWorld(this.player.world,"PLAYER_CAMERA.LOOK_AT_POSITION",{playerCamera:this,position:Z})}reset(){this._attachedToEntity=void 0,this._attachedToPosition=void 0,this._orientation={pitch:0,yaw:0},this._trackedEntity=void 0,this._trackedPosition=void 0}setAttachedToEntity(Z){if(!this._requirePlayerWorld("setAttachedToEntity"))return;if(!Z.isSpawned)return p.error(`PlayerCamera.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);this._attachedToEntity=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",{playerCamera:this,entity:Z})}setAttachedToPosition(Z){if(!this._requirePlayerWorld("setAttachedToPosition"))return;this._attachedToPosition=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",{playerCamera:this,position:Z})}setFilmOffset(Z){if(!this._requirePlayerWorld("setFilmOffset"))return;this._filmOffset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FILM_OFFSET",{playerCamera:this,filmOffset:Z})}setForwardOffset(Z){if(!this._requirePlayerWorld("setForwardOffset"))return;this._forwardOffset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FORWARD_OFFSET",{playerCamera:this,forwardOffset:Z})}setFov(Z){if(!this._requirePlayerWorld("setFov"))return;this._fov=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_FOV",{playerCamera:this,fov:Z})}setModelHiddenNodes(Z){if(!this._requirePlayerWorld("setModelHiddenNodes"))return;this._modelHiddenNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",{playerCamera:this,modelHiddenNodes:this._modelHiddenNodes})}setModelShownNodes(Z){if(!this._requirePlayerWorld("setModelShownNodes"))return;this._modelShownNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",{playerCamera:this,modelShownNodes:this._modelShownNodes})}setMode(Z){if(!this._requirePlayerWorld("setMode"))return;this._mode=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_MODE",{playerCamera:this,mode:Z})}setOffset(Z){if(!this._requirePlayerWorld("setOffset"))return;this._offset=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_OFFSET",{playerCamera:this,offset:Z})}setOrientationPitch(Z){this._orientation.pitch=Z}setOrientationYaw(Z){this._orientation.yaw=Z}setShoulderAngle(Z){if(!this._requirePlayerWorld("setShoulderAngle"))return;this._shoulderAngle=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_SHOULDER_ANGLE",{playerCamera:this,shoulderAngle:Z})}setTrackedEntity(Z){if(!this._requirePlayerWorld("setTrackedEntity"))return;this._trackedEntity=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_ENTITY",{playerCamera:this,entity:Z})}setTrackedPosition(Z){if(!this._requirePlayerWorld("setTrackedPosition"))return;this._trackedPosition=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_TRACKED_POSITION",{playerCamera:this,position:Z})}setZoom(Z){if(!this._requirePlayerWorld("setZoom"))return;this._zoom=Z,this.emitWithWorld(this.player.world,"PLAYER_CAMERA.SET_ZOOM",{playerCamera:this,zoom:Z})}serialize(){return T0.serializePlayerCamera(this)}_requirePlayerWorld(Z){if(!this.player.world)p.error(`PlayerCamera._requirePlayerWorld(): Player ${this.player.id} is not in a world, invoked method: ${Z}()`);return!!this.player.world}}var dw;((Y)=>{Y.DATA="PLAYER_UI.DATA";Y.LOAD="PLAYER_UI.LOAD";Y.LOCK_POINTER="PLAYER_UI.LOCK_POINTER";Y.SEND_DATA="PLAYER_UI.SEND_DATA"})(dw||={});class _z extends j0{player;constructor(Z){super();this.player=Z}load(Z){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.LOAD",{playerUI:this,htmlUri:Z})}lockPointer(Z){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.LOCK_POINTER",{playerUI:this,lock:Z})}sendData(Z){if(!this.player.world)return;this.emitWithWorld(this.player.world,"PLAYER_UI.SEND_DATA",{playerUI:this,data:Z})}}var K60=["w","a","s","d","sp","sh","tb","ml","mr","q","e","r","f","z","x","c","v","u","i","o","j","k","l","n","m","1","2","3","4","5","6","7","8","9","0"],bz;((Q)=>{Q.CHAT_MESSAGE_SEND="PLAYER.CHAT_MESSAGE_SEND";Q.JOINED_WORLD="PLAYER.JOINED_WORLD";Q.LEFT_WORLD="PLAYER.LEFT_WORLD";Q.RECONNECTED_WORLD="PLAYER.RECONNECTED_WORLD";Q.REQUEST_SYNC="PLAYER.REQUEST_SYNC"})(bz||={});class d3 extends j0{static _devNextPlayerId=1;id;username;profilePictureUrl;camera;connection;cosmetics;ui;_input={};_lastUnreliableInputSequenceNumber=0;_persistedData;_world;_worldSwitched=!1;constructor(Z,J){super();this.id=J?.user.id??`player-${d3._devNextPlayerId++}`,this.username=J?.user.username??this.id,this.profilePictureUrl=J?.user.profilePictureURL??void 0,this.camera=new Iz(this),this.connection=Z,this.cosmetics=F7.instance.getPlayerCosmetics(this.id),this.ui=new _z(this),Z.onPacket(Y0.PacketId.CHAT_MESSAGE_SEND,this._onChatMessageSendPacket),Z.onPacket(Y0.PacketId.DEBUG_CONFIG,this._onDebugConfigPacket),Z.onPacket(Y0.PacketId.INPUT,this._onInputPacket),Z.onPacket(Y0.PacketId.SYNC_REQUEST,this._onSyncRequestPacket),Z.onPacket(Y0.PacketId.UI_DATA_SEND,this._onUIDataSendPacket)}get input(){return this._input}get world(){return this._world}disconnect(){this._leaveWorld(),this.connection.disconnect()}getPersistedData(){if(!this._persistedData)return;let Z=Object.keys(this._persistedData);if(Z.length===0||Z.length===1&&Z[0]==="__version")return;return this._persistedData}joinWorld(Z){if(this._world===Z)return;if(!this._world)this._world=Z,this.emitWithWorld(this._world,"PLAYER.JOINED_WORLD",{player:this,world:this._world});else{for(let J of this._world.entityManager.getPlayerEntitiesByPlayer(this))if(J.isSpawned)J.despawn();this.disconnect(),this._world=Z,this._worldSwitched=!0}}async loadInitialPersistedData(){if(this._persistedData)return;this._persistedData=await g3.instance.getPlayerData(this)}reconnected(){if(!this._world)return;if(this._lastUnreliableInputSequenceNumber=0,!this._worldSwitched)this.emitWithWorld(this._world,"PLAYER.RECONNECTED_WORLD",{player:this,world:this._world});else this._worldSwitched=!1,this.emitWithWorld(this._world,"PLAYER.JOINED_WORLD",{player:this,world:this._world})}resetInputs(){this._input={}}setPersistedData(Z){if(!this._persistedData){p.warning(`Player.setPersistedData(): Persisted data not found for player ${this.id}`);return}for(let[J,X]of Object.entries(Z))this._persistedData[J]=X}serialize(){return T0.serializePlayer(this)}_leaveWorld(){if(!this._world)return;this.emitWithWorld(this._world,"PLAYER.LEFT_WORLD",{player:this,world:this._world}),this._world=void 0}_onChatMessageSendPacket=(Z)=>{if(!this._world)return;let J=Z[1].m;if(this._world.chatManager.handleCommand(this,J)){this._world.chatManager.sendPlayerMessage(this,`Command Entered: ${J}`,"CCCCCC");return}if(this.id.startsWith("guest")){this._world.chatManager.sendPlayerMessage(this,"You need to create a HYTOPIA account to send messages in chat.","FFAA00");return}this.emitWithWorld(this._world,"PLAYER.CHAT_MESSAGE_SEND",{player:this,message:J})};_onDebugConfigPacket=(Z)=>{console.log(Z)};_onInputPacket=(Z)=>{let J=Z[1];if(J.sq!==void 0){if(J.sq<this._lastUnreliableInputSequenceNumber)return;this._lastUnreliableInputSequenceNumber=J.sq}if(K60.forEach((X)=>{let $=X;if(J[$]!==void 0)this._input[$]=Boolean(J[$])}),J.cp!==void 0)this.camera.setOrientationPitch(J.cp);if(J.cy!==void 0)this.camera.setOrientationYaw(J.cy)};_onSyncRequestPacket=()=>{if(this._world)this.emitWithWorld(this._world,"PLAYER.REQUEST_SYNC",{player:this,receivedAt:Date.now(),receivedAtMs:performance.now()})};_onUIDataSendPacket=(Z)=>{this.ui.emit("PLAYER_UI.DATA",{playerUI:this.ui,data:Z[1]})}}var aP;((X)=>{X.BROADCAST_MESSAGE="CHAT.BROADCAST_MESSAGE";X.PLAYER_MESSAGE="CHAT.PLAYER_MESSAGE"})(aP||={});class hz extends j0{_commandCallbacks={};_world;constructor(Z){super();this._world=Z,this._subscribeToPlayerEvents()}registerCommand(Z,J){this._commandCallbacks[Z]=J}unregisterCommand(Z){delete this._commandCallbacks[Z]}sendBroadcastMessage(Z,J){this._sendBroadcastMessage(void 0,Z,J)}handleCommand(Z,J){let[X,...$]=J.split(" "),Y=this._commandCallbacks[X];if(Y)return Y(Z,$,J),!0;return!1}sendPlayerMessage(Z,J,X){this.emitWithWorld(this._world,"CHAT.PLAYER_MESSAGE",{player:Z,message:J,color:X})}_subscribeToPlayerEvents(){this._world.on("PLAYER.CHAT_MESSAGE_SEND",(Z)=>{let{player:J,message:X}=Z;this._sendBroadcastMessage(J,X)})}_sendBroadcastMessage(Z,J,X){this.emitWithWorld(this._world,"CHAT.BROADCAST_MESSAGE",{player:Z,message:J,color:X})}}var p5=16,nP=p5-1,r_1=p5**3;class j5{_blocks;_originCoordinate;constructor(Z){this._blocks=new Uint8Array(r_1),this._originCoordinate=Z}get blocks(){return this._blocks}get originCoordinate(){return this._originCoordinate}static blockIndexToLocalCoordinate(Z){return{x:Z%p5,y:(Z/p5|0)%p5,z:Z/(p5*p5)|0}}static globalCoordinateToLocalCoordinate(Z){return{x:Z.x&p5-1,y:Z.y&p5-1,z:Z.z&p5-1}}static globalCoordinateToOriginCoordinate(Z){return{x:Z.x&~(p5-1),y:Z.y&~(p5-1),z:Z.z&~(p5-1)}}getBlockId(Z){return this._blocks[this._getIndex(Z)]}hasBlock(Z){return this._blocks[this._getIndex(Z)]!==0}setBlock(Z,J){if(!this._isValidLocalCoordinate(Z))return p.error("Chunk.setBlock(): Block local coordinate is out of bounds");let X=this._getIndex(Z);this._blocks[X]=J}serialize(){return T0.serializeChunk(this)}_getIndex(Z){return Z.x+(Z.y<<4)+(Z.z<<8)}_isValidLocalCoordinate(Z){return Z.x>=0&&Z.x<=nP&&Z.y>=0&&Z.y<=nP&&Z.z>=0&&Z.z<=nP}}var sP;(($)=>{$.ADD_CHUNK="CHUNK_LATTICE.ADD_CHUNK";$.REMOVE_CHUNK="CHUNK_LATTICE.REMOVE_CHUNK";$.SET_BLOCK="CHUNK_LATTICE.SET_BLOCK"})(sP||={});class Sz extends j0{_blockTypeColliders=new Map;_blockTypeCounts=new Map;_chunks=new Map;_rigidBody;_world;constructor(Z){super();this._world=Z}get chunkCount(){return this._chunks.size}clear(){for(let Z of this._blockTypeColliders.values())this._world.simulation.colliderMap.removeColliderBlockType(Z),Z.removeFromSimulation();this._chunks.forEach((Z)=>{this.emitWithWorld(this._world,"CHUNK_LATTICE.REMOVE_CHUNK",{chunkLattice:this,chunk:Z})}),this._blockTypeColliders.clear(),this._blockTypeCounts.clear(),this._chunks.clear()}getBlockId(Z){let J=this.getChunk(j5.globalCoordinateToOriginCoordinate(Z));if(!J)return 0;return J.getBlockId(j5.globalCoordinateToLocalCoordinate(Z))}getBlockTypeCollider(Z){return this._blockTypeColliders.get(Z)}getBlockType(Z){let J=this.getBlockId(Z);return J?this._world.blockTypeRegistry.getBlockType(J):null}getBlockTypeCount(Z){return this._blockTypeCounts.get(Z)??0}getChunk(Z){return this._chunks.get(this._getChunkKey(j5.globalCoordinateToOriginCoordinate(Z)))}getOrCreateBlockTypeCollider(Z,J){let X=this._blockTypeColliders.get(Z);if(X)return X;let Y=this._world.blockTypeRegistry.getBlockType(Z).createCollider(J);return this._blockTypeColliders.set(Z,Y),Y}getOrCreateChunk(Z){let J=j5.globalCoordinateToOriginCoordinate(Z),X=this._chunks.get(this._getChunkKey(J));if(X)return X;return X=new j5(J),this._chunks.set(this._getChunkKey(J),X),this.emitWithWorld(this._world,"CHUNK_LATTICE.ADD_CHUNK",{chunkLattice:this,chunk:X}),X}getAllChunks(){return Array.from(this._chunks.values())}hasBlock(Z){let J=this.getChunk(j5.globalCoordinateToOriginCoordinate(Z));if(!J)return!1;return J.hasBlock(j5.globalCoordinateToLocalCoordinate(Z))}hasChunk(Z){let J=j5.globalCoordinateToOriginCoordinate(Z);return this._chunks.has(this._getChunkKey(J))}initializeBlocks(Z){if(this.clear(),!this._rigidBody)this._rigidBody=new aJ({type:"fixed"}),this._rigidBody.addToSimulation(this._world.simulation);for(let J in Z){let X=Number(J),$=Z[X];if($.length===0)continue;let Y=this.getOrCreateBlockTypeCollider(X,$);Y.addToSimulation(this._world.simulation,this._rigidBody);let Q=this._world.blockTypeRegistry.getBlockType(X);this._world.simulation.colliderMap.setColliderBlockType(Y,Q),this._blockTypeCounts.set(X,$.length);for(let K=0;K<$.length;K++){let W=$[K],G=j5.globalCoordinateToLocalCoordinate(W),z=this.getOrCreateChunk(W);z.setBlock(G,X),this.emitWithWorld(this._world,"CHUNK_LATTICE.SET_BLOCK",{chunkLattice:this,chunk:z,globalCoordinate:W,localCoordinate:G,blockTypeId:X})}this._combineVoxelStates(Y)}}setBlock(Z,J){let X=j5.globalCoordinateToLocalCoordinate(Z),$=this.getOrCreateChunk(Z),Y=$.getBlockId(X);if(Y===J)return;if($.setBlock(X,J),!this._rigidBody)this._rigidBody=new aJ({type:"fixed"}),this._rigidBody.addToSimulation(this._world.simulation);if(Y!==0){let Q=Math.max(0,(this._blockTypeCounts.get(Y)??0)-1),K=this.getBlockTypeCollider(Y);if(K)if(Q===0)this._world.simulation.colliderMap.removeColliderBlockType(K),K.removeFromSimulation(),this._blockTypeColliders.delete(Y);else K.setVoxel(Z,!1),this._propagateVoxelChange(K,Z);this._blockTypeCounts.set(Y,Q)}if(J!==0){let Q=(this._blockTypeCounts.get(J)??0)+1,K=this.getOrCreateBlockTypeCollider(J,[Z]);if(Q===1){let W=this._world.blockTypeRegistry.getBlockType(J);K.addToSimulation(this._world.simulation,this._rigidBody),this._world.simulation.colliderMap.setColliderBlockType(K,W),this._combineVoxelStates(K)}else K.setVoxel(Z,!0),this._propagateVoxelChange(K,Z);this._blockTypeCounts.set(J,Q)}this.emitWithWorld(this._world,"CHUNK_LATTICE.SET_BLOCK",{chunkLattice:this,chunk:$,globalCoordinate:Z,localCoordinate:X,blockTypeId:J})}_combineVoxelStates(Z){if(Z.isSensor)return;for(let J of this._blockTypeColliders.values()){if(J===Z||J.isSensor)continue;Z.combineVoxelStates(J)}}_getChunkKey(Z){return`${Z.x},${Z.y},${Z.z}`}_propagateVoxelChange(Z,J){if(Z.isSensor)return;for(let X of this._blockTypeColliders.values()){if(X===Z||X.isSensor)continue;Z.propagateVoxelChange(X,J)}}}class Az{_colliderHandleBlockTypeMap=new Map;_colliderHandleCollisionCallbackMap=new Map;_colliderHandleEntityMap=new Map;_cleanupBlockTypeColliderHandles=new Set;_pendingCleanupBlockTypeColliderHandles=new Set;_cleanupCollisionCallbackColliderHandles=new Set;_pendingCleanupCollisionCallbackColliderHandles=new Set;_cleanupEntityColliderHandles=new Set;_pendingCleanupEntityColliderHandles=new Set;getColliderBlockType(Z){if(!this._requireSimulatedCollider(Z))return;return this._colliderHandleBlockTypeMap.get(Z.rawCollider.handle)}getColliderCollisionCallback(Z){if(!this._requireSimulatedCollider(Z))return;return this._colliderHandleCollisionCallbackMap.get(Z.rawCollider.handle)}getColliderEntity(Z){if(!this._requireSimulatedCollider(Z))return;return this._colliderHandleEntityMap.get(Z.rawCollider.handle)}getColliderHandleBlockType(Z){return this._colliderHandleBlockTypeMap.get(Z)}getColliderHandleCollisionCallback(Z){return this._colliderHandleCollisionCallbackMap.get(Z)}getColliderHandleEntity(Z){return this._colliderHandleEntityMap.get(Z)}removeColliderBlockType(Z){if(!this._requireSimulatedCollider(Z))return;this.removeColliderHandleBlockType(Z.rawCollider.handle)}removeColliderCollisionCallback(Z){if(!this._requireSimulatedCollider(Z))return;this.removeColliderHandleCollisionCallback(Z.rawCollider.handle)}removeColliderEntity(Z){if(!this._requireSimulatedCollider(Z))return;this.removeColliderHandleEntity(Z.rawCollider.handle)}removeColliderHandleBlockType(Z){this._colliderHandleBlockTypeMap.delete(Z)}removeColliderHandleCollisionCallback(Z){this._colliderHandleCollisionCallbackMap.delete(Z)}removeColliderHandleEntity(Z){this._colliderHandleEntityMap.delete(Z)}setColliderBlockType(Z,J){if(!this._requireSimulatedCollider(Z))return;this.setColliderHandleBlockType(Z.rawCollider.handle,J)}setColliderCollisionCallback(Z,J){if(!this._requireSimulatedCollider(Z))return;this.setColliderHandleCollisionCallback(Z.rawCollider.handle,J)}setColliderEntity(Z,J){if(!this._requireSimulatedCollider(Z))return;this.setColliderHandleEntity(Z.rawCollider.handle,J)}setColliderHandleBlockType(Z,J){this._colliderHandleBlockTypeMap.set(Z,J),this._cleanupBlockTypeColliderHandles.delete(Z),this._pendingCleanupBlockTypeColliderHandles.delete(Z)}setColliderHandleCollisionCallback(Z,J){this._colliderHandleCollisionCallbackMap.set(Z,J),this._cleanupCollisionCallbackColliderHandles.delete(Z),this._pendingCleanupCollisionCallbackColliderHandles.delete(Z)}setColliderHandleEntity(Z,J){this._colliderHandleEntityMap.set(Z,J),this._cleanupEntityColliderHandles.delete(Z),this._pendingCleanupEntityColliderHandles.delete(Z)}queueColliderHandleForCleanup(Z){if(this._colliderHandleBlockTypeMap.has(Z))this._pendingCleanupBlockTypeColliderHandles.add(Z);if(this._colliderHandleCollisionCallbackMap.has(Z))this._pendingCleanupCollisionCallbackColliderHandles.add(Z);if(this._colliderHandleEntityMap.has(Z))this._pendingCleanupEntityColliderHandles.add(Z)}cleanup(){for(let Z of this._cleanupBlockTypeColliderHandles)this._colliderHandleBlockTypeMap.delete(Z);if(this._cleanupBlockTypeColliderHandles.size>0)this._cleanupBlockTypeColliderHandles.clear();for(let Z of this._cleanupCollisionCallbackColliderHandles)this._colliderHandleCollisionCallbackMap.delete(Z);if(this._cleanupCollisionCallbackColliderHandles.size>0)this._cleanupCollisionCallbackColliderHandles.clear();for(let Z of this._cleanupEntityColliderHandles)this._colliderHandleEntityMap.delete(Z);if(this._cleanupEntityColliderHandles.size>0)this._cleanupEntityColliderHandles.clear();for(let Z of this._pendingCleanupBlockTypeColliderHandles)this._cleanupBlockTypeColliderHandles.add(Z);if(this._pendingCleanupBlockTypeColliderHandles.size>0)this._pendingCleanupBlockTypeColliderHandles.clear();for(let Z of this._pendingCleanupCollisionCallbackColliderHandles)this._cleanupCollisionCallbackColliderHandles.add(Z);if(this._pendingCleanupCollisionCallbackColliderHandles.size>0)this._pendingCleanupCollisionCallbackColliderHandles.clear();for(let Z of this._pendingCleanupEntityColliderHandles)this._cleanupEntityColliderHandles.add(Z);if(this._pendingCleanupEntityColliderHandles.size>0)this._pendingCleanupEntityColliderHandles.clear()}_requireSimulatedCollider(Z){if(!Z.rawCollider)p.error("ColliderMap._requireSimulatedCollider(): Collider is not in the simulation.");return!!Z.rawCollider}}var W60={type:"dynamic",softCcdPrediction:1},G60=0.015625,z60=Math.cos(0.026),mz;((L)=>{L.BLOCK_COLLISION="ENTITY.BLOCK_COLLISION";L.BLOCK_CONTACT_FORCE="ENTITY.BLOCK_CONTACT_FORCE";L.DESPAWN="ENTITY.DESPAWN";L.ENTITY_COLLISION="ENTITY.ENTITY_COLLISION";L.ENTITY_CONTACT_FORCE="ENTITY.ENTITY_CONTACT_FORCE";L.SET_MODEL_ANIMATIONS_PLAYBACK_RATE="ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE";L.SET_MODEL_HIDDEN_NODES="ENTITY.SET_MODEL_HIDDEN_NODES";L.SET_MODEL_SCALE="ENTITY.SET_MODEL_SCALE";L.SET_MODEL_SHOWN_NODES="ENTITY.SET_MODEL_SHOWN_NODES";L.SET_MODEL_TEXTURE_URI="ENTITY.SET_MODEL_TEXTURE_URI";L.SET_OPACITY="ENTITY.SET_OPACITY";L.SET_PARENT="ENTITY.SET_PARENT";L.SET_TINT_COLOR="ENTITY.SET_TINT_COLOR";L.SPAWN="ENTITY.SPAWN";L.START_MODEL_LOOPED_ANIMATIONS="ENTITY.START_MODEL_LOOPED_ANIMATIONS";L.START_MODEL_ONESHOT_ANIMATIONS="ENTITY.START_MODEL_ONESHOT_ANIMATIONS";L.STOP_MODEL_ANIMATIONS="ENTITY.STOP_MODEL_ANIMATIONS";L.TICK="ENTITY.TICK";L.UPDATE_POSITION="ENTITY.UPDATE_POSITION";L.UPDATE_ROTATION="ENTITY.UPDATE_ROTATION"})(mz||={});class B8 extends aJ{_id;_blockHalfExtents;_blockTextureUri;_controller;_isEnvironmental=!1;_modelAnimationsPlaybackRate=1;_modelHiddenNodes=new Set;_modelLoopedAnimations=new Set;_modelOneshotAnimations=new Set;_modelPreferredShape;_modelScale=1;_modelShownNodes=new Set;_modelTextureUri;_modelUri;_name;_opacity;_parent;_parentNodeName;_tag;_tintColor;_lastUpdatedPosition={x:0,y:0,z:0};_lastUpdatedRotation={x:0,y:0,z:0,w:1};_lastParentlessType="dynamic";_world;_positionUpdateThresholdSq;_rotationUpdateThreshold;constructor(Z){let J="blockTextureUri"in Z,X="modelUri"in Z;if(!J===!X)p.fatalError("Entity.constructor(): Entity data must include a blockTextureUri or modelUri, but not both.");if(J&&!Z.blockHalfExtents)p.fatalError("Entity.constructor(): Block entity must have blockHalfExtents!");if(Z.parent&&!Z.parent.isSpawned)p.fatalError("Entity.constructor(): Parent entity must be spawned before child entity!");if(Z.parent?.modelUri&&Z.parentNodeName&&!B6.instance.modelHasNode(Z.parent.modelUri,Z.parentNodeName))p.fatalError(`Entity.constructor(): Parent node name ${Z.parentNodeName} not found in parent model ${Z.parent.modelUri}!`);super(Z.rigidBodyOptions??W60);if(J)this._blockHalfExtents=Z.blockHalfExtents,this._blockTextureUri=Z.blockTextureUri;if(X)this._modelAnimationsPlaybackRate=Z.modelAnimationsPlaybackRate??1,this._modelPreferredShape=Z.modelPreferredShape,this._modelScale=Z.modelScale??1,this._modelTextureUri=Z.modelTextureUri,this._modelUri=Z.modelUri,Z.modelHiddenNodes?.forEach(($)=>this._modelHiddenNodes.add($.toLowerCase())),Z.modelLoopedAnimations?.forEach(($)=>this._modelLoopedAnimations.add($)),Z.modelShownNodes?.forEach(($)=>this._modelShownNodes.add($.toLowerCase()));if(this._isEnvironmental=Z.isEnvironmental??!1,this._name=Z.name??"Nameless",this._opacity=Z.opacity??1,this._parent=Z.parent,this._parentNodeName=Z.parentNodeName,this._tag=Z.tag,this._tintColor=Z.tintColor,this._positionUpdateThresholdSq=G60,this._rotationUpdateThreshold=z60,Z.controller)this.setController(Z.controller)}get id(){return this._id}get blockHalfExtents(){return this._blockHalfExtents}get blockTextureUri(){return this._blockTextureUri}get controller(){return this._controller}get depth(){return this.isModelEntity?B6.instance.getDepth(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.z*2}get height(){return this.isModelEntity?B6.instance.getHeight(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.y*2}get modelAnimationsPlaybackRate(){return this._modelAnimationsPlaybackRate}get modelHiddenNodes(){return this._modelHiddenNodes}get modelLoopedAnimations(){return this._modelLoopedAnimations}get modelPreferredShape(){return this._modelPreferredShape}get modelScale(){return this._modelScale}get modelShownNodes(){return this._modelShownNodes}get modelTextureUri(){return this._modelTextureUri}get modelUri(){return this._modelUri}get name(){return this._name}get opacity(){return this._opacity}get parent(){return this._parent}get parentNodeName(){return this._parentNodeName}get tag(){return this._tag}get tintColor(){return this._tintColor}get isBlockEntity(){return!!this._blockTextureUri}get isEnvironmental(){return this._isEnvironmental}get isModelEntity(){return!!this._modelUri}get isSpawned(){return!!this._world}get width(){return this.isModelEntity?B6.instance.getWidth(this._modelUri)*(this._modelScale??1):this._blockHalfExtents.x*2}get world(){return this._world}spawn(Z,J,X){if(this.isSpawned)return p.error(`Entity.spawn(): Entity ${this._name} is already spawned with id ${this._id}!`);if(!this.isSimulated)this.addToSimulation(Z.simulation);if(this._blockTextureUri&&this._blockHalfExtents&&this.numColliders===0)this.addChildColliderToSimulation(new A5(A5.optionsFromBlockHalfExtents(this._blockHalfExtents)));if(this._modelUri&&this.numColliders===0&&this._modelPreferredShape!=="none")this.addChildColliderToSimulation(new A5(A5.optionsFromModelUri(this._modelUri,this._modelScale,this._modelPreferredShape)));if(this.colliders.forEach(($)=>{if(this.hasListeners("ENTITY.BLOCK_COLLISION")||this.hasListeners("ENTITY.ENTITY_COLLISION"))$.enableCollisionEvents(!0);if(this.hasListeners("ENTITY.BLOCK_CONTACT_FORCE")||this.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))$.enableContactForceEvents(!0);if(V9.isDefaultCollisionGroups($.collisionGroups)){let Y=this.isEnvironmental?[8]:[$.isSensor?4:2],Q=this.isEnvironmental?[65535&~8&~1]:[65535];$.setCollisionGroups({belongsTo:Y,collidesWith:Q})}}),this.setPosition(J),X)this.setRotation(X);if(this._id=Z.entityManager.registerEntity(this),this._world=Z,this._controller)this._controller.spawn(this);if(this._parent)this.setParent(this._parent,this._parentNodeName,J,X);this.colliders.forEach(($)=>{Z.simulation.colliderMap.setColliderEntity($,this)}),this.emitWithWorld(Z,"ENTITY.SPAWN",{entity:this})}despawn(){if(!this._requireSpawned("despawn"))return;if(this._world.entityManager.getEntityChildren(this).forEach((Z)=>{Z.despawn()}),this._controller)this._controller.detach(this),this._controller.despawn(this);if(this.emitWithWorld(this._world,"ENTITY.DESPAWN",{entity:this}),this.isSimulated)this.removeFromSimulation();this._world.entityManager.unregisterEntity(this),this._world.audioManager.unregisterEntityAttachedAudios(this),this._world.lightManager.despawnEntityAttachedLights(this),this._world.particleEmitterManager.despawnEntityAttachedParticleEmitters(this),this._world.sceneUIManager.unloadEntityAttachedSceneUIs(this),this._id=void 0,this._world=void 0}setController(Z){if(this._controller===Z)return;if(this._controller)this._controller.detach(this);if(this._controller=Z,this._controller)this._controller.attach(this)}setModelAnimationsPlaybackRate(Z){if(!this._requireSpawned("setModelAnimationsPlaybackRate"))return;if(!this.isModelEntity||this._modelAnimationsPlaybackRate===Z)return;this._modelAnimationsPlaybackRate=Z,this.emitWithWorld(this._world,"ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",{entity:this,playbackRate:Z})}setModelHiddenNodes(Z){if(!this._requireSpawned("setModelHiddenNodes"))return;if(!this.isModelEntity)return;this._modelHiddenNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_HIDDEN_NODES",{entity:this,modelHiddenNodes:this._modelHiddenNodes})}setModelScale(Z){if(!this._requireSpawned("setModelScale"))return;if(!this.isModelEntity||this._modelScale===Z)return;let J=Z/this._modelScale;this._modelScale=Z,this.colliders.forEach((X)=>X.scale(J)),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_SCALE",{entity:this,modelScale:Z})}setModelShownNodes(Z){if(!this._requireSpawned("setModelShownNodes"))return;if(!this.isModelEntity)return;this._modelShownNodes=new Set(Z.map((J)=>J.toLowerCase())),this.emitWithWorld(this._world,"ENTITY.SET_MODEL_SHOWN_NODES",{entity:this,modelShownNodes:this._modelShownNodes})}setModelTextureUri(Z){if(!this._requireSpawned("setModelTextureUri"))return;if(!this.isModelEntity||this._modelTextureUri===Z)return;this._modelTextureUri=Z,this.emitWithWorld(this._world,"ENTITY.SET_MODEL_TEXTURE_URI",{entity:this,modelTextureUri:Z})}setOpacity(Z){if(!this._requireSpawned("setOpacity"))return;if(this._opacity===Z)return;this._opacity=Z,this.emitWithWorld(this._world,"ENTITY.SET_OPACITY",{entity:this,opacity:Z})}setParent(Z,J,X,$){if(!this._requireSpawned("setParent"))return;if(Z&&!Z.isSpawned)return p.error("Entity.setParent(): Parent entity is not spawned, cannot set parent!");if(!this._parent&&Z)this._lastParentlessType=this.type;if(this._parent=Z,this._parentNodeName=J,this.colliders.forEach((Y)=>Y.setEnabled(!Z)),this.setType(!Z?this._lastParentlessType:"kinematic_velocity"),this.setPosition(X??{x:0,y:0,z:0}),this.setRotation($??{x:0,y:0,z:0,w:1}),!this.isKinematicPositionBased)this.resetAngularVelocity(),this.resetForces(),this.resetLinearVelocity(),this.resetTorques();this.emitWithWorld(this._world,"ENTITY.SET_PARENT",{entity:this,parent:Z,parentNodeName:J})}setTintColor(Z){if(!this._requireSpawned("setTintColor"))return;if(!Z&&!this._tintColor||Z&&this._tintColor&&Z.r===this._tintColor.r&&Z.g===this._tintColor.g&&Z.b===this._tintColor.b)return;this._tintColor=Z,this.emitWithWorld(this._world,"ENTITY.SET_TINT_COLOR",{entity:this,tintColor:Z})}startModelLoopedAnimations(Z){if(!this._requireSpawned("startModelLoopedAnimations"))return;if(!this.isModelEntity||!Z.length)return;if(!Z.some((J)=>!this._modelLoopedAnimations.has(J)))return;Z.forEach((J)=>{this._modelLoopedAnimations.add(J)}),this.emitWithWorld(this._world,"ENTITY.START_MODEL_LOOPED_ANIMATIONS",{entity:this,animations:new Set(Z)})}startModelOneshotAnimations(Z){if(!this._requireSpawned("startModelOneshotAnimations"))return;if(!this.isModelEntity||!Z.length)return;Z.forEach((J)=>{this._modelOneshotAnimations.add(J)}),this.emitWithWorld(this._world,"ENTITY.START_MODEL_ONESHOT_ANIMATIONS",{entity:this,animations:new Set(Z)})}stopAllModelAnimations(Z=[]){if(!this._requireSpawned("stopAllModelAnimations"))return;this._stopAnimationsFromSets([this._modelLoopedAnimations,this._modelOneshotAnimations],Z)}stopAllModelLoopedAnimations(Z=[]){if(!this._requireSpawned("stopAllModelLoopedAnimations"))return;this._stopAnimationsFromSets([this._modelLoopedAnimations],Z)}stopAllModelOneshotAnimations(Z=[]){if(!this._requireSpawned("stopAllModelOneshotAnimations"))return;this._stopAnimationsFromSets([this._modelOneshotAnimations],Z)}stopModelAnimations(Z){if(!this._requireSpawned("stopModelAnimations"))return;if(!this.isModelEntity||!Z.length)return;if(!Z.some((J)=>this._modelLoopedAnimations.has(J))&&!Z.some((J)=>this._modelOneshotAnimations.has(J)))return;Z.forEach((J)=>{this._modelLoopedAnimations.delete(J),this._modelOneshotAnimations.delete(J)}),this.emitWithWorld(this._world,"ENTITY.STOP_MODEL_ANIMATIONS",{entity:this,animations:new Set(Z)})}serialize(){return T0.serializeEntity(this)}tick(Z){if(this.emit("ENTITY.TICK",{entity:this,tickDeltaMs:Z}),this._controller)this._controller.tick(this,Z)}checkAndEmitUpdates(){if(!this._requireSpawned("checkAndEmitUpdates"))return;let Z=this.position,J=this.rotation;if(this._rotationExceedsThreshold(J,this._lastUpdatedRotation))this._lastUpdatedRotation=J,this.emitWithWorld(this._world,"ENTITY.UPDATE_ROTATION",{entity:this,rotation:J});if(this._positionExceedsThreshold(Z,this._lastUpdatedPosition))this._lastUpdatedPosition=Z,this.emitWithWorld(this._world,"ENTITY.UPDATE_POSITION",{entity:this,position:Z})}_positionExceedsThreshold(Z,J){let X=Z.x-J.x,$=Z.y-J.y,Y=Z.z-J.z;return X*X+$*$+Y*Y>this._positionUpdateThresholdSq}_requireSpawned(Z){if(!this.isSpawned)p.error(`Entity._requireSpawned(): Entity ${this._name} is not spawned, cannot invoke ${Z}()!`);return this.isSpawned}_rotationExceedsThreshold(Z,J){return Math.abs(Z.x*J.x+Z.y*J.y+Z.z*J.z+Z.w*J.w)<this._rotationUpdateThreshold}_stopAnimationsFromSets(Z,J=[]){if(!this.isModelEntity)return;let X=new Set(J),$=[];for(let Y of Z)for(let Q of Y)if(!X.has(Q))$.push(Q);if($.length>0)this.stopModelAnimations($)}}class b1 extends x${static BASE_ENTITY_HEIGHT=1.5;static GROUND_SENSOR_HEIGHT_SCALE=0.125;static GROUND_SENSOR_RADIUS_SCALE=0.23;static JUMP_LAND_HEAVY_VELOCITY_THRESHOLD=-12;static WALL_COLLIDER_HEIGHT_SCALE=0.33;static WALL_COLLIDER_RADIUS_SCALE=0.4;static MOVEMENT_ROTATIONS={wa:Math.PI/4,wd:-Math.PI/4,sa:Math.PI-Math.PI/4,sd:Math.PI+Math.PI/4,s:Math.PI,asd:Math.PI,a:Math.PI/2,d:-Math.PI/2};static EXTERNAL_IMPULSE_DECAY_RATE=0.253;static SWIM_UPWARD_COOLDOWN_MS=600;static SWIMMING_DRAG_FACTOR=0.05;static WATER_ENTRY_SINKING_FACTOR=0.8;static WATER_ENTRY_SINKING_MS=250;applyDirectionalMovementRotations=!0;autoCancelMouseLeftClick=!0;canJump=()=>!0;canRun=()=>!0;canSwim=()=>!0;canWalk=()=>!0;faceForwardOnStop=!0;idleLoopedAnimations=["idle-upper","idle-lower"];interactOneshotAnimations=["simple-interact"];jumpLandHeavyOneshotAnimations=["jump-post-heavy"];jumpLandLightOneshotAnimations=["jump-post-light"];jumpOneshotAnimations=["jump-loop"];jumpVelocity=10;runLoopedAnimations=["run-upper","run-lower"];runVelocity=8;sticksToPlatforms=!0;swimFastVelocity=5;swimGravity=0;swimIdleLoopedAnimations=["swim-idle"];swimLoopedAnimations=["swim-forward"];swimMaxGravityVelocity=-1;swimSlowVelocity=3;swimUpwardVelocity=2;walkLoopedAnimations=["walk-upper","walk-lower"];walkVelocity=4;_externalVelocity={x:0,y:0,z:0};_magnitudeYTracker=0;_groundContactCount=0;_internalApplyImpulse=()=>{};_isActivelyMoving=!1;_isFullySubmerged=!1;_justSubmergedUntil=0;_liquidContactCount=0;_platform;_reusableImpulse={x:0,y:0,z:0};_reusablePlatformVelocity={x:0,y:0,z:0};_reusableTargetVelocities={x:0,y:0,z:0};_reusableVelocityClamp={x:0,y:0,z:0};_stepAudio;_swimUpwardCooldownAt=0;constructor(Z={}){super();this.applyDirectionalMovementRotations=Z.applyDirectionalMovementRotations??this.applyDirectionalMovementRotations,this.autoCancelMouseLeftClick=Z.autoCancelMouseLeftClick??this.autoCancelMouseLeftClick,this.faceForwardOnStop=Z.faceForwardOnStop??this.faceForwardOnStop,this.sticksToPlatforms=Z.sticksToPlatforms??this.sticksToPlatforms,this.canJump=Z.canJump??this.canJump,this.canRun=Z.canRun??this.canRun,this.canSwim=Z.canSwim??this.canSwim,this.canWalk=Z.canWalk??this.canWalk,this.jumpVelocity=Z.jumpVelocity??this.jumpVelocity,this.runVelocity=Z.runVelocity??this.runVelocity,this.walkVelocity=Z.walkVelocity??this.walkVelocity,this.swimFastVelocity=Z.swimFastVelocity??this.swimFastVelocity,this.swimSlowVelocity=Z.swimSlowVelocity??this.swimSlowVelocity,this.swimUpwardVelocity=Z.swimUpwardVelocity??this.swimUpwardVelocity,this.swimGravity=Z.swimGravity??this.swimGravity,this.swimMaxGravityVelocity=Z.swimMaxGravityVelocity??this.swimMaxGravityVelocity,this.idleLoopedAnimations=Z.idleLoopedAnimations??this.idleLoopedAnimations,this.interactOneshotAnimations=Z.interactOneshotAnimations??this.interactOneshotAnimations,this.jumpOneshotAnimations=Z.jumpOneshotAnimations??this.jumpOneshotAnimations,this.jumpLandHeavyOneshotAnimations=Z.jumpLandHeavyOneshotAnimations??this.jumpLandHeavyOneshotAnimations,this.jumpLandLightOneshotAnimations=Z.jumpLandLightOneshotAnimations??this.jumpLandLightOneshotAnimations,this.runLoopedAnimations=Z.runLoopedAnimations??this.runLoopedAnimations,this.swimLoopedAnimations=Z.swimLoopedAnimations??this.swimLoopedAnimations,this.swimIdleLoopedAnimations=Z.swimIdleLoopedAnimations??this.swimIdleLoopedAnimations,this.walkLoopedAnimations=Z.walkLoopedAnimations??this.walkLoopedAnimations}get isActivelyMoving(){return this._isActivelyMoving}get isGrounded(){return this._groundContactCount>0}get isOnPlatform(){return!!this._platform}get isSwimming(){return this._liquidContactCount>0}get platform(){return this._platform}attach(Z){super.attach(Z),this._internalApplyImpulse=Z.applyImpulse.bind(Z),Z.applyImpulse=(J)=>{let X=Z.mass||1;this._externalVelocity.x+=J.x/X,this._externalVelocity.y+=J.y/X,this._externalVelocity.z+=J.z/X},this._stepAudio=new OW({uri:"audio/sfx/step/stone/stone-step-04.mp3",loop:!0,volume:0.1,referenceDistance:2,cutoffDistance:15,attachedToEntity:Z}),Z.setCcdEnabled(!0),Z.lockAllRotations(),Z.on("ENTITY.BLOCK_COLLISION",({blockType:J,started:X})=>{if(!J.isLiquid||!this.canSwim(this))return;if(this._liquidContactCount<=0&&X){let $=Z.linearVelocity;Z.setLinearVelocity({x:$.x*this.swimGravity,y:$.y*this.swimGravity,z:$.z*this.swimGravity})}if(this._liquidContactCount+=X?1:-1,this._liquidContactCount>0)Z.setGravityScale(this.swimGravity),Z.stopAllModelLoopedAnimations(this.swimLoopedAnimations),this._swimUpwardCooldownAt=performance.now()+b1.SWIM_UPWARD_COOLDOWN_MS;else Z.setGravityScale(1),Z.stopModelAnimations(this.swimLoopedAnimations)})}spawn(Z){if(!Z.isSpawned)return p.error("DefaultPlayerEntityController.spawn(): Entity is not spawned!");Z.createAndAddChildCollider({shape:"cylinder",radius:b1.GROUND_SENSOR_RADIUS_SCALE*(Z.height/b1.BASE_ENTITY_HEIGHT),halfHeight:b1.GROUND_SENSOR_HEIGHT_SCALE*(Z.height/b1.BASE_ENTITY_HEIGHT),collisionGroups:{belongsTo:[4],collidesWith:[1,2,8]},isSensor:!0,relativePosition:{x:0,y:-Z.height/2,z:0},tag:"groundSensor",onCollision:(J,X)=>{if(!Z.isSpawned)return;if(!(J instanceof m5)||!J.isLiquid){if(X&&this._groundContactCount===0&&Z.linearVelocity.y<-1)if(Z.linearVelocity.y<b1.JUMP_LAND_HEAVY_VELOCITY_THRESHOLD)Z.startModelOneshotAnimations(this.jumpLandHeavyOneshotAnimations);else Z.startModelOneshotAnimations(this.jumpLandLightOneshotAnimations);this._groundContactCount+=X?1:-1}if(!this._groundContactCount&&!this.isSwimming)Z.startModelOneshotAnimations(this.jumpOneshotAnimations);else Z.stopModelAnimations(this.jumpOneshotAnimations);if(!(J instanceof B8))return;if(X&&this.sticksToPlatforms)this._platform=J;else if(J===this._platform&&!X)this._platform=void 0}}),Z.createAndAddChildCollider({shape:"capsule",halfHeight:b1.WALL_COLLIDER_HEIGHT_SCALE*(Z.height/b1.BASE_ENTITY_HEIGHT),radius:b1.WALL_COLLIDER_RADIUS_SCALE*(Z.height/b1.BASE_ENTITY_HEIGHT),collisionGroups:{belongsTo:[4],collidesWith:[1,2,8]},friction:0,frictionCombineRule:1,tag:"wallCollider"})}tickWithPlayerInput(Z,J,X,$){if(!Z.isSpawned||!Z.world)return;if(super.tickWithPlayerInput(Z,J,X,$),Z.parent)return;let{w:Y,a:Q,s:K,d:W,c:G,sp:z,sh:V,ml:H}=J,{yaw:v}=X,q=Z.linearVelocity;this._reusableTargetVelocities.x=0,this._reusableTargetVelocities.y=0,this._reusableTargetVelocities.z=0,this._isActivelyMoving=!!(Y||Q||K||W);let F=V,c=Q&&W&&!Y&&!K||Y&&K&&!Q&&!W,w=F&&this.canRun(this)||!F&&this.canWalk(this);if(this.isSwimming&&!this._isFullySubmerged)this._isFullySubmerged=!0,this._justSubmergedUntil=performance.now()+b1.WATER_ENTRY_SINKING_MS;else if(!this.isSwimming)this._isFullySubmerged=!1,this._justSubmergedUntil=0;if(this.isGrounded&&!this.isSwimming&&this._isActivelyMoving&&!c&&w){let M=F?this.runLoopedAnimations:this.walkLoopedAnimations;Z.stopAllModelLoopedAnimations(M),Z.startModelLoopedAnimations(M),this._stepAudio?.setPlaybackRate(F?0.75:0.51),this._stepAudio?.play(Z.world,!this._stepAudio?.isPlaying)}else if(this._isFullySubmerged&&this.canSwim(this))if(this._stepAudio?.pause(),this._isActivelyMoving)Z.stopAllModelLoopedAnimations(this.swimLoopedAnimations),Z.startModelLoopedAnimations(this.swimLoopedAnimations);else Z.stopAllModelLoopedAnimations(this.swimIdleLoopedAnimations),Z.startModelLoopedAnimations(this.swimIdleLoopedAnimations);else this._stepAudio?.pause(),Z.stopAllModelLoopedAnimations(this.idleLoopedAnimations),Z.startModelLoopedAnimations(this.idleLoopedAnimations);let x;if(this.applyDirectionalMovementRotations&&w){if(Y&&Q&&!W&&!K)x=b1.MOVEMENT_ROTATIONS.wa;else if(Y&&W&&!Q&&!K)x=b1.MOVEMENT_ROTATIONS.wd;else if(K&&Q&&!Y&&!W)x=b1.MOVEMENT_ROTATIONS.sa;else if(K&&W&&!Y&&!Q)x=b1.MOVEMENT_ROTATIONS.sd;else if(K&&!Y&&!Q&&!W||Q&&K&&W&&!Y)x=b1.MOVEMENT_ROTATIONS.s;else if(Q&&!Y&&!K&&!W)x=b1.MOVEMENT_ROTATIONS.a;else if(W&&!Y&&!Q&&!K)x=b1.MOVEMENT_ROTATIONS.d}if(H)Z.startModelOneshotAnimations(this.interactOneshotAnimations),J.ml=!this.autoCancelMouseLeftClick;if(w){let M=!this.isSwimming?F?this.runVelocity:this.walkVelocity:F?this.swimFastVelocity:this.swimSlowVelocity,O=Math.sin(v),P=Math.cos(v);if(Y)this._reusableTargetVelocities.x-=M*O,this._reusableTargetVelocities.z-=M*P;if(K)this._reusableTargetVelocities.x+=M*O,this._reusableTargetVelocities.z+=M*P;if(Q)this._reusableTargetVelocities.x-=M*P,this._reusableTargetVelocities.z+=M*O;if(W)this._reusableTargetVelocities.x+=M*P,this._reusableTargetVelocities.z-=M*O;let N=Math.sqrt(this._reusableTargetVelocities.x*this._reusableTargetVelocities.x+this._reusableTargetVelocities.z*this._reusableTargetVelocities.z);if(N>M){let _=M/N;this._reusableTargetVelocities.x*=_,this._reusableTargetVelocities.z*=_}}if(this.isSwimming){if(q.y<this.swimMaxGravityVelocity)this._reusableVelocityClamp.x=q.x,this._reusableVelocityClamp.y=this.swimMaxGravityVelocity,this._reusableVelocityClamp.z=q.z,Z.setLinearVelocity(this._reusableVelocityClamp);if(q.y>this.swimUpwardVelocity*2)this._reusableVelocityClamp.x=q.x,this._reusableVelocityClamp.y=this.swimUpwardVelocity*2,this._reusableVelocityClamp.z=q.z,Z.setLinearVelocity(this._reusableVelocityClamp);if(G)this._reusableTargetVelocities.y=-this.swimUpwardVelocity;else if(performance.now()<this._justSubmergedUntil)this._reusableTargetVelocities.y=-this.swimUpwardVelocity*b1.WATER_ENTRY_SINKING_FACTOR;else if(!z)this._reusableTargetVelocities.y=-q.y*b1.SWIMMING_DRAG_FACTOR}if(z&&this.canJump(this)){if(this.isGrounded&&!this.isSwimming&&q.y>-0.001&&q.y<=3)this._reusableTargetVelocities.y=this.jumpVelocity;else if(this.isSwimming&&performance.now()>this._swimUpwardCooldownAt)this._reusableTargetVelocities.y=this.swimUpwardVelocity}let j=this._platform?.linearVelocity??this._reusablePlatformVelocity;if(this._externalVelocity.y!==0)this._magnitudeYTracker+=this._externalVelocity.y;if(this._externalVelocity.x!==0||this._externalVelocity.y!==0||this._externalVelocity.z!==0){if(this.isGrounded){let M=Math.sqrt(this._externalVelocity.x*this._externalVelocity.x+this._magnitudeYTracker*this._magnitudeYTracker+this._externalVelocity.z*this._externalVelocity.z);if(M>0.01){let P=Math.max(0,M-b1.EXTERNAL_IMPULSE_DECAY_RATE)/M;this._externalVelocity.x*=P,this._magnitudeYTracker*=P,this._externalVelocity.z*=P}else this._externalVelocity.x=0,this._externalVelocity.y=0,this._magnitudeYTracker=0,this._externalVelocity.z=0}}let B=this._reusableTargetVelocities.x+this._externalVelocity.x-q.x+j.x,L=this._reusableTargetVelocities.y+this._externalVelocity.y+j.y,R=this._reusableTargetVelocities.z+this._externalVelocity.z-q.z+j.z;if(this._externalVelocity.y=0,B!==0||L!==0||R!==0){let M=Z.mass;this._reusableImpulse.x=B*M,this._reusableImpulse.y=L*M,this._reusableImpulse.z=R*M,this._internalApplyImpulse(this._reusableImpulse)}if(v!==void 0&&(this.faceForwardOnStop||this.isActivelyMoving)){let O=(x!==void 0?v+x:v)*0.5;Z.setRotation({x:0,y:Math.sin(O),z:0,w:Math.cos(O)})}}}var oP;((W)=>{W.LOAD="SCENE_UI.LOAD";W.SET_ATTACHED_TO_ENTITY="SCENE_UI.SET_ATTACHED_TO_ENTITY";W.SET_OFFSET="SCENE_UI.SET_OFFSET";W.SET_POSITION="SCENE_UI.SET_POSITION";W.SET_STATE="SCENE_UI.SET_STATE";W.SET_VIEW_DISTANCE="SCENE_UI.SET_VIEW_DISTANCE";W.UNLOAD="SCENE_UI.UNLOAD"})(oP||={});class uz extends j0{_id;_attachedToEntity;_offset;_position;_state={};_templateId;_viewDistance;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)p.fatalError("Either attachedToEntity or position must be set, but not both");super();this._attachedToEntity=Z.attachedToEntity,this._offset=Z.offset,this._position=Z.position,this._state=Z.state??{},this._templateId=Z.templateId,this._viewDistance=Z.viewDistance}get id(){return this._id}get attachedToEntity(){return this._attachedToEntity}get isLoaded(){return this._id!==void 0}get offset(){return this._offset}get position(){return this._position}get state(){return this._state}get templateId(){return this._templateId}get viewDistance(){return this._viewDistance}get world(){return this._world}load(Z){if(this.isLoaded)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return p.error(`SceneUI.load(): Attached entity ${this._attachedToEntity.id} must be spawned before loading SceneUI!`);this._id=Z.sceneUIManager.registerSceneUI(this),this._world=Z,this.emitWithWorld(Z,"SCENE_UI.LOAD",{sceneUI:this})}setAttachedToEntity(Z){if(!Z.isSpawned)return p.error(`SceneUI.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_ATTACHED_TO_ENTITY",{sceneUI:this,entity:Z})}setOffset(Z){if(this._offset===Z)return;if(this._offset=Z,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_OFFSET",{sceneUI:this,offset:Z})}setPosition(Z){if(this._position===Z)return;if(this._attachedToEntity=void 0,this._position=Z,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_POSITION",{sceneUI:this,position:Z})}setState(Z){if(this._state={...this._state,...Z},this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_STATE",{sceneUI:this,state:this._state})}setViewDistance(Z){if(this._viewDistance=Z,this.isLoaded)this.emitWithWorld(this._world,"SCENE_UI.SET_VIEW_DISTANCE",{sceneUI:this,viewDistance:Z})}unload(){if(!this.isLoaded||!this._world)return;this._world.sceneUIManager.unregisterSceneUI(this),this.emitWithWorld(this._world,"SCENE_UI.UNLOAD",{sceneUI:this}),this._id=void 0,this._world=void 0}serialize(){return T0.serializeSceneUI(this)}}var V60=0.010000000000000002,v60=Math.cos(0.026);class c7 extends B8{player;nametagSceneUI;constructor(Z){super(Z);this._positionUpdateThresholdSq=V60,this._rotationUpdateThreshold=v60,this.player=Z.player,this.nametagSceneUI=new uz({templateId:"hytopia:nametag",attachedToEntity:this,offset:{x:0,y:1,z:0},viewDistance:15,state:{username:this.player.username,profilePictureUrl:this.player.profilePictureUrl}})}spawn(Z,J,X){super.spawn(Z,J,X),this.nametagSceneUI.load(Z),this.player.on("PLAYER.CHAT_MESSAGE_SEND",({message:$})=>{this.nametagSceneUI.setState({chat:$})})}tick(Z){if(!this.isSpawned||!this.world)return;if(!this.controller)return p.error(`PlayerEntity.tick(): PlayerEntity "${this.name}" must have a controller.`);let{input:J,camera:X}=this.player;this.controller.tickWithPlayerInput(this,J,X.orientation,Z),super.tick(Z)}}var H60="models/players/player.gltf",t_1={BACK:"back-anchor",HEAD:"head-anchor",LEFT_ARM:"arm-left-anchor",LEFT_FOOT:"foot-left-anchor",LEFT_HAND:"hand-left-anchor",LEFT_ITEM:"hand-left-anchor",LEFT_LEG:"leg-left-anchor",RIGHT_ARM:"arm-right-anchor",RIGHT_FOOT:"foot-right-anchor",RIGHT_HAND:"hand-right-anchor",RIGHT_ITEM:"hand-right-anchor",RIGHT_LEG:"leg-right-anchor",TORSO:"torso-anchor"};class rP extends c7{_cosmeticHiddenSlots;constructor(Z){super({modelUri:H60,modelLoopedAnimations:["idle_lower","idle_upper"],modelHiddenNodes:["hair-"],modelShownNodes:["hair-0003"],...Z});if(this._cosmeticHiddenSlots=Z.cosmeticHiddenSlots??[],!Z.controller)this.setController(new b1)}get cosmeticHiddenSlots(){return this._cosmeticHiddenSlots}spawn(Z,J,X){super.spawn(Z,J,X),this.player.cosmetics.then(($)=>{if(!$||!this.modelUri)return;let Y=this.modelShownNodes.values().toArray().filter((W)=>!W.includes("hair-"));if(!($.equippedItems.some((W)=>W.item.flags.includes("HIDES_HAIR"))&&!this._cosmeticHiddenSlots.includes("ALL")&&!this._cosmeticHiddenSlots.includes("HEAD")))Y.push(`hair-${String($.hairStyle).padStart(4,"0")}`);if(this.setModelShownNodes(Y),this.modelUri===H60)this.setModelTextureUri($.skinTextureUri);if(this._cosmeticHiddenSlots.includes("ALL"))return;let K=[];for(let W of $.equippedItems){let{item:G,slot:z}=W;if(this._cosmeticHiddenSlots.includes(z))continue;let V=t_1[z];if(!V||!B6.instance.modelHasNode(this.modelUri,V))continue;if(G.flags.includes("REPLACES_LIMB")){let v=V.split("-").slice(0,-1).join("-");K.push(`${v}-clothing`,`${v}-geometry`)}new B8({modelUri:G.modelUrl,modelPreferredShape:"none",parent:this,parentNodeName:V}).spawn(Z,{x:0,y:0,z:0})}if(K.length>0)this.setModelHiddenNodes([...this.modelHiddenNodes.values().toArray(),...K])}).catch(($)=>p.warning(`DefaultPlayerEntity.spawn(): Failed to get player cosmetics: ${$}`))}}class lz{_activeEntities=new Set;_entities=new Map;_nextEntityId=1;_world;constructor(Z){this._world=Z}get entityCount(){return this._entities.size}get world(){return this._world}registerEntity(Z){if(Z.id!==void 0)p.fatalError(`EntityManager.registerEntity(): Entity ${Z.name} is already assigned the id ${Z.id}!`);let J=this._nextEntityId;if(this._entities.set(J,Z),this._nextEntityId++,!Z.isEnvironmental)this._activeEntities.add(Z);return J}unregisterEntity(Z){if(Z.id===void 0)return p.error(`EntityManager.unregisterEntity(): Entity ${Z.name} is not assigned an id!`);if(this._entities.delete(Z.id),!Z.isEnvironmental)this._activeEntities.delete(Z)}getAllEntities(){return Array.from(this._entities.values())}getAllPlayerEntities(){let Z=[];return this._entities.forEach((J)=>{if(J instanceof c7)Z.push(J)}),Z}getPlayerEntitiesByPlayer(Z){let J=[];return this._entities.forEach((X)=>{if(X instanceof c7&&X.player===Z)J.push(X)}),J}getEntity(Z){return this._entities.get(Z)}getEntitiesByTag(Z){let J=[];return this._entities.forEach((X)=>{if(X.tag===Z)J.push(X)}),J}getEntitiesByTagSubstring(Z){let J=[];return this._entities.forEach((X)=>{if(X.tag?.includes(Z))J.push(X)}),J}getEntityChildren(Z){let J=[];return this._entities.forEach((X)=>{if(X.parent===Z)J.push(X)}),J}tickEntities(Z){for(let J of this._activeEntities)J.tick(Z)}checkAndEmitUpdates(){for(let Z of this._activeEntities)Z.checkAndEmitUpdates()}}import{gzipSync as oX6}from"zlib";var d6=t(w50(),1),_h6=d6.default.v1,bh6=d6.default.v1ToV6,hh6=d6.default.v3,x50=d6.default.v4,Sh6=d6.default.v5,Ah6=d6.default.v6,mh6=d6.default.v6ToV1,uh6=d6.default.v7,lh6=d6.default.NIL,yh6=d6.default.MAX,ph6=d6.default.version,ih6=d6.default.validate,gh6=d6.default.stringify,dh6=d6.default.parse;var QT;try{QT=new TextDecoder}catch(Z){}var X0,g5,m=0;var zT=[],JY=zT,iz=0,f1={},Y1,hZ,i5=0,P4=0,S8,SZ,L5=[],e0,U50={useRecords:!1,mapsAsObjects:!0};class Zx{}var VT=new Zx;VT.name="MessagePack 0xC1";var QX=!1,N50=2,KT,WT,GT;try{new Function("")}catch(Z){N50=1/0}class AZ{constructor(Z){if(Z){if(Z.useRecords===!1&&Z.mapsAsObjects===void 0)Z.mapsAsObjects=!0;if(Z.sequential&&Z.trusted!==!1){if(Z.trusted=!0,!Z.structures&&Z.useRecords!=!1){if(Z.structures=[],!Z.maxSharedStructures)Z.maxSharedStructures=0}}if(Z.structures)Z.structures.sharedLength=Z.structures.length;else if(Z.getStructures)(Z.structures=[]).uninitialized=!0,Z.structures.sharedLength=0;if(Z.int64AsNumber)Z.int64AsType="number"}Object.assign(this,Z)}unpack(Z,J){if(X0)return S50(()=>{return ew(),this?this.unpack(Z,J):AZ.prototype.unpack.call(U50,Z,J)});if(!Z.buffer&&Z.constructor===ArrayBuffer)Z=typeof Buffer!=="undefined"?Buffer.from(Z):new Uint8Array(Z);if(typeof J==="object")g5=J.end||Z.length,m=J.start||0;else m=0,g5=J>-1?J:Z.length;iz=0,P4=0,hZ=null,JY=zT,S8=null,X0=Z;try{e0=Z.dataView||(Z.dataView=new DataView(Z.buffer,Z.byteOffset,Z.byteLength))}catch(X){if(X0=null,Z instanceof Uint8Array)throw X;throw new Error("Source must be a Uint8Array or Buffer but was a "+(Z&&typeof Z=="object"?Z.constructor.name:typeof Z))}if(this instanceof AZ){if(f1=this,this.structures)return Y1=this.structures,rw(J);else if(!Y1||Y1.length>0)Y1=[]}else if(f1=U50,!Y1||Y1.length>0)Y1=[];return rw(J)}unpackMultiple(Z,J){let X,$=0;try{QX=!0;let Y=Z.length,Q=this?this.unpack(Z,Y):Jx.unpack(Z,Y);if(J){if(J(Q,$,m)===!1)return;while(m<Y)if($=m,J(rw(),$,m)===!1)return}else{X=[Q];while(m<Y)$=m,X.push(rw());return X}}catch(Y){throw Y.lastPosition=$,Y.values=X,Y}finally{QX=!1,ew()}}_mergeStructures(Z,J){if(WT)Z=WT.call(this,Z);if(Z=Z||[],Object.isFrozen(Z))Z=Z.map((X)=>X.slice(0));for(let X=0,$=Z.length;X<$;X++){let Y=Z[X];if(Y){if(Y.isShared=!0,X>=32)Y.highByte=X-32>>5}}Z.sharedLength=Z.length;for(let X in J||[])if(X>=0){let $=Z[X],Y=J[X];if(Y){if($)(Z.restoreStructures||(Z.restoreStructures=[]))[X]=$;Z[X]=Y}}return this.structures=Z}decode(Z,J){return this.unpack(Z,J)}}function rw(Z){try{if(!f1.trusted&&!QX){let X=Y1.sharedLength||0;if(X<Y1.length)Y1.length=X}let J;if(f1.randomAccessStructure&&X0[m]<64&&X0[m]>=32&&KT){if(J=KT(X0,m,g5,f1),X0=null,!(Z&&Z.lazy)&&J)J=J.toJSON();m=g5}else J=L8();if(S8)m=S8.postBundlePosition,S8=null;if(QX)Y1.restoreStructures=null;if(m==g5){if(Y1&&Y1.restoreStructures)j50();if(Y1=null,X0=null,SZ)SZ=null}else if(m>g5)throw new Error("Unexpected end of MessagePack data");else if(!QX){let X;try{X=JSON.stringify(J,($,Y)=>typeof Y==="bigint"?`${Y}n`:Y).slice(0,100)}catch($){X="(JSON view not available "+$+")"}throw new Error("Data read, but end of buffer not reached "+X)}return J}catch(J){if(Y1&&Y1.restoreStructures)j50();if(ew(),J instanceof RangeError||J.message.startsWith("Unexpected end of buffer")||m>g5)J.incomplete=!0;throw J}}function j50(){for(let Z in Y1.restoreStructures)Y1[Z]=Y1.restoreStructures[Z];Y1.restoreStructures=null}function L8(){let Z=X0[m++];if(Z<160)if(Z<128)if(Z<64)return Z;else{let J=Y1[Z&63]||f1.getStructures&&P50()[Z&63];if(J){if(!J.read)J.read=vT(J,Z&63);return J.read()}else return Z}else if(Z<144)if(Z-=128,f1.mapsAsObjects){let J={};for(let X=0;X<Z;X++){let $=b50();if($==="__proto__")$="__proto_";J[$]=L8()}return J}else{let J=new Map;for(let X=0;X<Z;X++)J.set(L8(),L8());return J}else{Z-=144;let J=new Array(Z);for(let X=0;X<Z;X++)J[X]=L8();if(f1.freezeData)return Object.freeze(J);return J}else if(Z<192){let J=Z-160;if(P4>=m)return hZ.slice(m-i5,(m+=J)-i5);if(P4==0&&g5<140){let X=J<16?HT(J):_50(J);if(X!=null)return X}return tw(J)}else{let J;switch(Z){case 192:return null;case 193:if(S8)if(J=L8(),J>0)return S8[1].slice(S8.position1,S8.position1+=J);else return S8[0].slice(S8.position0,S8.position0-=J);return VT;case 194:return!1;case 195:return!0;case 196:if(J=X0[m++],J===void 0)throw new Error("Unexpected end of buffer");return YT(J);case 197:return J=e0.getUint16(m),m+=2,YT(J);case 198:return J=e0.getUint32(m),m+=4,YT(J);case 199:return ZY(X0[m++]);case 200:return J=e0.getUint16(m),m+=2,ZY(J);case 201:return J=e0.getUint32(m),m+=4,ZY(J);case 202:if(J=e0.getFloat32(m),f1.useFloat32>2){let X=$Y[(X0[m]&127)<<1|X0[m+1]>>7];return m+=4,(X*J+(J>0?0.5:-0.5)>>0)/X}return m+=4,J;case 203:return J=e0.getFloat64(m),m+=8,J;case 204:return X0[m++];case 205:return J=e0.getUint16(m),m+=2,J;case 206:return J=e0.getUint32(m),m+=4,J;case 207:if(f1.int64AsType==="number")J=e0.getUint32(m)*4294967296,J+=e0.getUint32(m+4);else if(f1.int64AsType==="string")J=e0.getBigUint64(m).toString();else if(f1.int64AsType==="auto"){if(J=e0.getBigUint64(m),J<=BigInt(2)<<BigInt(52))J=Number(J)}else J=e0.getBigUint64(m);return m+=8,J;case 208:return e0.getInt8(m++);case 209:return J=e0.getInt16(m),m+=2,J;case 210:return J=e0.getInt32(m),m+=4,J;case 211:if(f1.int64AsType==="number")J=e0.getInt32(m)*4294967296,J+=e0.getUint32(m+4);else if(f1.int64AsType==="string")J=e0.getBigInt64(m).toString();else if(f1.int64AsType==="auto"){if(J=e0.getBigInt64(m),J>=BigInt(-2)<<BigInt(52)&&J<=BigInt(2)<<BigInt(52))J=Number(J)}else J=e0.getBigInt64(m);return m+=8,J;case 212:if(J=X0[m++],J==114)return O50(X0[m++]&63);else{let X=L5[J];if(X)if(X.read)return m++,X.read(L8());else if(X.noBuffer)return m++,X();else return X(X0.subarray(m,++m));else throw new Error("Unknown extension "+J)}case 213:if(J=X0[m],J==114)return m++,O50(X0[m++]&63,X0[m++]);else return ZY(2);case 214:return ZY(4);case 215:return ZY(8);case 216:return ZY(16);case 217:if(J=X0[m++],P4>=m)return hZ.slice(m-i5,(m+=J)-i5);return T50(J);case 218:if(J=e0.getUint16(m),m+=2,P4>=m)return hZ.slice(m-i5,(m+=J)-i5);return C50(J);case 219:if(J=e0.getUint32(m),m+=4,P4>=m)return hZ.slice(m-i5,(m+=J)-i5);return f50(J);case 220:return J=e0.getUint16(m),m+=2,L50(J);case 221:return J=e0.getUint32(m),m+=4,L50(J);case 222:return J=e0.getUint16(m),m+=2,D50(J);case 223:return J=e0.getUint32(m),m+=4,D50(J);default:if(Z>=224)return Z-256;if(Z===void 0){let X=new Error("Unexpected end of MessagePack data");throw X.incomplete=!0,X}throw new Error("Unknown MessagePack token "+Z)}}}var Ph1=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function vT(Z,J){function X(){if(X.count++>N50){let Y=Z.read=new Function("r","return function(){return "+(f1.freezeData?"Object.freeze":"")+"({"+Z.map((Q)=>Q==="__proto__"?"__proto_:r()":Ph1.test(Q)?Q+":r()":"["+JSON.stringify(Q)+"]:r()").join(",")+"})}")(L8);if(Z.highByte===0)Z.read=B50(J,Z.read);return Y()}let $={};for(let Y=0,Q=Z.length;Y<Q;Y++){let K=Z[Y];if(K==="__proto__")K="__proto_";$[K]=L8()}if(f1.freezeData)return Object.freeze($);return $}if(X.count=0,Z.highByte===0)return B50(J,X);return X}var B50=(Z,J)=>{return function(){let X=X0[m++];if(X===0)return J();let $=Z<32?-(Z+(X<<5)):Z+(X<<5),Y=Y1[$]||P50()[$];if(!Y)throw new Error("Record id is not defined for "+$);if(!Y.read)Y.read=vT(Y,Z);return Y.read()}};function P50(){let Z=S50(()=>{return X0=null,f1.getStructures()});return Y1=f1._mergeStructures(Z,Y1)}var tw=XY,T50=XY,C50=XY,f50=XY,k50=!1;function E50(Z){k50=!0,tw=J(1),T50=J(2),C50=J(3),f50=J(5);function J(X){return function $(Y){let Q=JY[iz++];if(Q==null){if(S8)return XY(Y);let W=X0.byteOffset,G=Z(m-X+W,g5+W,X0.buffer);if(typeof G=="string")Q=G,JY=zT;else if(JY=G,iz=1,P4=1,Q=JY[0],Q===void 0)throw new Error("Unexpected end of buffer")}let K=Q.length;if(K<=Y)return m+=Y,Q;return hZ=Q,i5=m,P4=m+K,m+=Y,Q.slice(0,Y)}}}function XY(Z){let J;if(Z<16){if(J=HT(Z))return J}if(Z>64&&QT)return QT.decode(X0.subarray(m,m+=Z));let X=m+Z,$=[];J="";while(m<X){let Y=X0[m++];if((Y&128)===0)$.push(Y);else if((Y&224)===192){let Q=X0[m++]&63;$.push((Y&31)<<6|Q)}else if((Y&240)===224){let Q=X0[m++]&63,K=X0[m++]&63;$.push((Y&31)<<12|Q<<6|K)}else if((Y&248)===240){let Q=X0[m++]&63,K=X0[m++]&63,W=X0[m++]&63,G=(Y&7)<<18|Q<<12|K<<6|W;if(G>65535)G-=65536,$.push(G>>>10&1023|55296),G=56320|G&1023;$.push(G)}else $.push(Y);if($.length>=4096)J+=a8.apply(String,$),$.length=0}if($.length>0)J+=a8.apply(String,$);return J}function I50(Z,J,X){let $=X0;X0=Z,m=J;try{return XY(X)}finally{X0=$}}function L50(Z){let J=new Array(Z);for(let X=0;X<Z;X++)J[X]=L8();if(f1.freezeData)return Object.freeze(J);return J}function D50(Z){if(f1.mapsAsObjects){let J={};for(let X=0;X<Z;X++){let $=b50();if($==="__proto__")$="__proto_";J[$]=L8()}return J}else{let J=new Map;for(let X=0;X<Z;X++)J.set(L8(),L8());return J}}var a8=String.fromCharCode;function _50(Z){let J=m,X=new Array(Z);for(let $=0;$<Z;$++){let Y=X0[m++];if((Y&128)>0){m=J;return}X[$]=Y}return a8.apply(String,X)}function HT(Z){if(Z<4)if(Z<2)if(Z===0)return"";else{let J=X0[m++];if((J&128)>1){m-=1;return}return a8(J)}else{let J=X0[m++],X=X0[m++];if((J&128)>0||(X&128)>0){m-=2;return}if(Z<3)return a8(J,X);let $=X0[m++];if(($&128)>0){m-=3;return}return a8(J,X,$)}else{let J=X0[m++],X=X0[m++],$=X0[m++],Y=X0[m++];if((J&128)>0||(X&128)>0||($&128)>0||(Y&128)>0){m-=4;return}if(Z<6)if(Z===4)return a8(J,X,$,Y);else{let Q=X0[m++];if((Q&128)>0){m-=5;return}return a8(J,X,$,Y,Q)}else if(Z<8){let Q=X0[m++],K=X0[m++];if((Q&128)>0||(K&128)>0){m-=6;return}if(Z<7)return a8(J,X,$,Y,Q,K);let W=X0[m++];if((W&128)>0){m-=7;return}return a8(J,X,$,Y,Q,K,W)}else{let Q=X0[m++],K=X0[m++],W=X0[m++],G=X0[m++];if((Q&128)>0||(K&128)>0||(W&128)>0||(G&128)>0){m-=8;return}if(Z<10)if(Z===8)return a8(J,X,$,Y,Q,K,W,G);else{let z=X0[m++];if((z&128)>0){m-=9;return}return a8(J,X,$,Y,Q,K,W,G,z)}else if(Z<12){let z=X0[m++],V=X0[m++];if((z&128)>0||(V&128)>0){m-=10;return}if(Z<11)return a8(J,X,$,Y,Q,K,W,G,z,V);let H=X0[m++];if((H&128)>0){m-=11;return}return a8(J,X,$,Y,Q,K,W,G,z,V,H)}else{let z=X0[m++],V=X0[m++],H=X0[m++],v=X0[m++];if((z&128)>0||(V&128)>0||(H&128)>0||(v&128)>0){m-=12;return}if(Z<14)if(Z===12)return a8(J,X,$,Y,Q,K,W,G,z,V,H,v);else{let q=X0[m++];if((q&128)>0){m-=13;return}return a8(J,X,$,Y,Q,K,W,G,z,V,H,v,q)}else{let q=X0[m++],F=X0[m++];if((q&128)>0||(F&128)>0){m-=14;return}if(Z<15)return a8(J,X,$,Y,Q,K,W,G,z,V,H,v,q,F);let c=X0[m++];if((c&128)>0){m-=15;return}return a8(J,X,$,Y,Q,K,W,G,z,V,H,v,q,F,c)}}}}}function M50(){let Z=X0[m++],J;if(Z<192)J=Z-160;else switch(Z){case 217:J=X0[m++];break;case 218:J=e0.getUint16(m),m+=2;break;case 219:J=e0.getUint32(m),m+=4;break;default:throw new Error("Expected string")}return XY(J)}function YT(Z){return f1.copyBuffers?Uint8Array.prototype.slice.call(X0,m,m+=Z):X0.subarray(m,m+=Z)}function ZY(Z){let J=X0[m++];if(L5[J]){let X;return L5[J](X0.subarray(m,X=m+=Z),($)=>{m=$;try{return L8()}finally{m=X}})}else throw new Error("Unknown extension type "+J)}var R50=new Array(4096);function b50(){let Z=X0[m++];if(Z>=160&&Z<192){if(Z=Z-160,P4>=m)return hZ.slice(m-i5,(m+=Z)-i5);else if(!(P4==0&&g5<180))return tw(Z)}else return m--,h50(L8());let J=(Z<<5^(Z>1?e0.getUint16(m):Z>0?X0[m]:0))&4095,X=R50[J],$=m,Y=m+Z-3,Q,K=0;if(X&&X.bytes==Z){while($<Y){if(Q=e0.getUint32($),Q!=X[K++]){$=1879048192;break}$+=4}Y+=3;while($<Y)if(Q=X0[$++],Q!=X[K++]){$=1879048192;break}if($===Y)return m=$,X.string;Y-=3,$=m}X=[],R50[J]=X,X.bytes=Z;while($<Y)Q=e0.getUint32($),X.push(Q),$+=4;Y+=3;while($<Y)Q=X0[$++],X.push(Q);let W=Z<16?HT(Z):_50(Z);if(W!=null)return X.string=W;return X.string=tw(Z)}function h50(Z){if(typeof Z==="string")return Z;if(typeof Z==="number"||typeof Z==="boolean"||typeof Z==="bigint")return Z.toString();if(Z==null)return Z+"";if(f1.allowArraysInMapKeys&&Array.isArray(Z)&&Z.flat().every((J)=>["string","number","boolean","bigint"].includes(typeof J)))return Z.flat().toString();throw new Error(`Invalid property type for record: ${typeof Z}`)}var O50=(Z,J)=>{let X=L8().map(h50),$=Z;if(J!==void 0)Z=Z<32?-((J<<5)+Z):(J<<5)+Z,X.highByte=J;let Y=Y1[Z];if(Y&&(Y.isShared||QX))(Y1.restoreStructures||(Y1.restoreStructures=[]))[Z]=Y;return Y1[Z]=X,X.read=vT(X,$),X.read()};L5[0]=()=>{};L5[0].noBuffer=!0;L5[66]=(Z)=>{let J=Z.length,X=BigInt(Z[0]&128?Z[0]-256:Z[0]);for(let $=1;$<J;$++)X<<=BigInt(8),X+=BigInt(Z[$]);return X};var Th1={Error,TypeError,ReferenceError};L5[101]=()=>{let Z=L8();return(Th1[Z[0]]||Error)(Z[1],{cause:Z[2]})};L5[105]=(Z)=>{if(f1.structuredClone===!1)throw new Error("Structured clone extension is disabled");let J=e0.getUint32(m-4);if(!SZ)SZ=new Map;let X=X0[m],$;if(X>=144&&X<160||X==220||X==221)$=[];else if(X>=128&&X<144||X==222||X==223)$=new Map;else if((X>=199&&X<=201||X>=212&&X<=216)&&X0[m+1]===115)$=new Set;else $={};let Y={target:$};SZ.set(J,Y);let Q=L8();if(!Y.used)return Y.target=Q;else Object.assign($,Q);if($ instanceof Map)for(let[K,W]of Q.entries())$.set(K,W);if($ instanceof Set)for(let K of Array.from(Q))$.add(K);return $};L5[112]=(Z)=>{if(f1.structuredClone===!1)throw new Error("Structured clone extension is disabled");let J=e0.getUint32(m-4),X=SZ.get(J);return X.used=!0,X.target};L5[115]=()=>new Set(L8());var qT=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map((Z)=>Z+"Array"),Ch1=typeof globalThis==="object"?globalThis:window;L5[116]=(Z)=>{let J=Z[0],X=Uint8Array.prototype.slice.call(Z,1).buffer,$=qT[J];if(!$){if(J===16)return X;if(J===17)return new DataView(X);throw new Error("Could not find typed array for code "+J)}return new Ch1[$](X)};L5[120]=()=>{let Z=L8();return new RegExp(Z[0],Z[1])};var fh1=[];L5[98]=(Z)=>{let J=(Z[0]<<24)+(Z[1]<<16)+(Z[2]<<8)+Z[3],X=m;return m+=J-Z.length,S8=fh1,S8=[M50(),M50()],S8.position0=0,S8.position1=0,S8.postBundlePosition=m,m=X,L8()};L5[255]=(Z)=>{if(Z.length==4)return new Date((Z[0]*16777216+(Z[1]<<16)+(Z[2]<<8)+Z[3])*1000);else if(Z.length==8)return new Date(((Z[0]<<22)+(Z[1]<<14)+(Z[2]<<6)+(Z[3]>>2))/1e6+((Z[3]&3)*4294967296+Z[4]*16777216+(Z[5]<<16)+(Z[6]<<8)+Z[7])*1000);else if(Z.length==12)return new Date(((Z[0]<<24)+(Z[1]<<16)+(Z[2]<<8)+Z[3])/1e6+((Z[4]&128?-281474976710656:0)+Z[6]*1099511627776+Z[7]*4294967296+Z[8]*16777216+(Z[9]<<16)+(Z[10]<<8)+Z[11])*1000);else return new Date("invalid")};function S50(Z){if(GT)GT();let J=g5,X=m,$=iz,Y=i5,Q=P4,K=hZ,W=JY,G=SZ,z=S8,V=new Uint8Array(X0.slice(0,g5)),H=Y1,v=Y1.slice(0,Y1.length),q=f1,F=QX,c=Z();return g5=J,m=X,iz=$,i5=Y,P4=Q,hZ=K,JY=W,SZ=G,S8=z,X0=V,QX=F,Y1=H,Y1.splice(0,Y1.length,...v),f1=q,e0=new DataView(X0.buffer,X0.byteOffset,X0.byteLength),c}function ew(){X0=null,SZ=null,Y1=null}var $Y=new Array(147);for(let Z=0;Z<256;Z++)$Y[Z]=+("1e"+Math.floor(45.15-Z*0.30103));var Jx=new AZ({useRecords:!1}),kh1=Jx.unpack,Eh1=Jx.unpackMultiple,Ih1=Jx.unpack,gz={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4},_h1=new Float32Array(1),nh6=new Uint8Array(_h1.buffer,0,4);function A50(Z,J,X){KT=Z,WT=J,GT=X}var $x;try{$x=new TextEncoder}catch(Z){}var wT,l50,az=typeof Buffer!=="undefined",Xx=az?function(Z){return Buffer.allocUnsafeSlow(Z)}:Uint8Array,y50=az?Buffer:Uint8Array,m50=az?4294967296:2144337920,n,dz,h1,y=0,a6,o1=null,p50,bh1=21760,hh1=/[\u0080-\uFFFF]/,w7=Symbol("record-id");class YY extends AZ{constructor(Z){super(Z);this.offset=0;let J,X,$,Y,Q,K=y50.prototype.utf8Write?function(f,C){return n.utf8Write(f,C,n.byteLength-C)}:$x&&$x.encodeInto?function(f,C){return $x.encodeInto(f,n.subarray(C)).written}:!1,W=this;if(!Z)Z={};let G=Z&&Z.sequential,z=Z.structures||Z.saveStructures,V=Z.maxSharedStructures;if(V==null)V=z?32:0;if(V>8160)throw new Error("Maximum maxSharedStructure is 8160");if(Z.structuredClone&&Z.moreTypes==null)this.moreTypes=!0;let H=Z.maxOwnStructures;if(H==null)H=z?32:64;if(!this.structures&&Z.useRecords!=!1)this.structures=[];let v=V>32||H+V>64,q=V+64,F=V+H+64;if(F>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let c=[],w=0,x=0;this.pack=this.encode=function(f,C){if(!n)n=new Xx(8192),h1=n.dataView||(n.dataView=new DataView(n.buffer,0,8192)),y=0;if(a6=n.length-10,a6-y<2048)n=new Xx(n.length),h1=n.dataView||(n.dataView=new DataView(n.buffer,0,n.length)),a6=n.length-10,y=0;else y=y+7&2147483640;if(X=y,C&ph1)y+=C&255;if(Q=W.structuredClone?new Map:null,W.bundleStrings&&typeof f!=="string")o1=[],o1.size=1/0;else o1=null;if(Y=W.structures,Y){if(Y.uninitialized)Y=W._mergeStructures(W.getStructures());let I=Y.sharedLength||0;if(I>V)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+Y.sharedLength);if(!Y.transitions){Y.transitions=Object.create(null);for(let a=0;a<I;a++){let s=Y[a];if(!s)continue;let Z0,o=Y.transitions;for(let M0=0,R0=s.length;M0<R0;M0++){let m0=s[M0];if(Z0=o[m0],!Z0)Z0=o[m0]=Object.create(null);o=Z0}o[w7]=a+64}this.lastNamedStructuresLength=I}if(!G)Y.nextId=I+64}if($)$=!1;let b;try{if(W.randomAccessStructure&&f&&f.constructor&&f.constructor===Object)h(f);else L(f);let I=o1;if(o1)u50(X,L,0);if(Q&&Q.idsToInsert){let a=Q.idsToInsert.sort((M0,R0)=>M0.offset>R0.offset?1:-1),s=a.length,Z0=-1;while(I&&s>0){let M0=a[--s].offset+X;if(M0<I.stringsPosition+X&&Z0===-1)Z0=0;if(M0>I.position+X){if(Z0>=0)Z0+=6}else{if(Z0>=0)h1.setUint32(I.position+X,h1.getUint32(I.position+X)+Z0),Z0=-1;I=I.previous,s++}}if(Z0>=0&&I)h1.setUint32(I.position+X,h1.getUint32(I.position+X)+Z0);if(y+=a.length*6,y>a6)N(y);W.offset=y;let o=Ah1(n.subarray(X,y),a);return Q=null,o}if(W.offset=y,C&lh1)return n.start=X,n.end=y,n;return n.subarray(X,y)}catch(I){throw b=I,I}finally{if(Y){if(j(),$&&W.saveStructures){let I=Y.sharedLength||0,a=n.subarray(X,y),s=i50(Y,W);if(!b){if(W.saveStructures(s,s.isCompatible)===!1)return W.pack(f,C);if(W.lastNamedStructuresLength=I,n.length>1073741824)n=null;return a}}}if(n.length>1073741824)n=null;if(C&yh1)y=X}};let j=()=>{if(x<10)x++;let f=Y.sharedLength||0;if(Y.length>f&&!G)Y.length=f;if(w>1e4){if(Y.transitions=null,x=0,w=0,c.length>0)c=[]}else if(c.length>0&&!G){for(let C=0,b=c.length;C<b;C++)c[C][w7]=0;c=[]}},B=(f)=>{var C=f.length;if(C<16)n[y++]=144|C;else if(C<65536)n[y++]=220,n[y++]=C>>8,n[y++]=C&255;else n[y++]=221,h1.setUint32(y,C),y+=4;for(let b=0;b<C;b++)L(f[b])},L=(f)=>{if(y>a6)n=N(y);var C=typeof f,b;if(C==="string"){let I=f.length;if(o1&&I>=4&&I<4096){if((o1.size+=I)>bh1){let o,M0=(o1[0]?o1[0].length*3+o1[1].length:0)+10;if(y+M0>a6)n=N(y+M0);let R0;if(o1.position)R0=o1,n[y]=200,y+=3,n[y++]=98,o=y-X,y+=4,u50(X,L,0),h1.setUint16(o+X-3,y-X-o);else n[y++]=214,n[y++]=98,o=y-X,y+=4;o1=["",""],o1.previous=R0,o1.size=0,o1.position=o}let Z0=hh1.test(f);o1[Z0?0:1]+=f,n[y++]=193,L(Z0?-I:I);return}let a;if(I<32)a=1;else if(I<256)a=2;else if(I<65536)a=3;else a=5;let s=I*3;if(y+s>a6)n=N(y+s);if(I<64||!K){let Z0,o,M0,R0=y+a;for(Z0=0;Z0<I;Z0++)if(o=f.charCodeAt(Z0),o<128)n[R0++]=o;else if(o<2048)n[R0++]=o>>6|192,n[R0++]=o&63|128;else if((o&64512)===55296&&((M0=f.charCodeAt(Z0+1))&64512)===56320)o=65536+((o&1023)<<10)+(M0&1023),Z0++,n[R0++]=o>>18|240,n[R0++]=o>>12&63|128,n[R0++]=o>>6&63|128,n[R0++]=o&63|128;else n[R0++]=o>>12|224,n[R0++]=o>>6&63|128,n[R0++]=o&63|128;b=R0-y-a}else b=K(f,y+a);if(b<32)n[y++]=160|b;else if(b<256){if(a<2)n.copyWithin(y+2,y+1,y+1+b);n[y++]=217,n[y++]=b}else if(b<65536){if(a<3)n.copyWithin(y+3,y+2,y+2+b);n[y++]=218,n[y++]=b>>8,n[y++]=b&255}else{if(a<5)n.copyWithin(y+5,y+3,y+3+b);n[y++]=219,h1.setUint32(y,b),y+=4}y+=b}else if(C==="number")if(f>>>0===f)if(f<32||f<128&&this.useRecords===!1||f<64&&!this.randomAccessStructure)n[y++]=f;else if(f<256)n[y++]=204,n[y++]=f;else if(f<65536)n[y++]=205,n[y++]=f>>8,n[y++]=f&255;else n[y++]=206,h1.setUint32(y,f),y+=4;else if(f>>0===f)if(f>=-32)n[y++]=256+f;else if(f>=-128)n[y++]=208,n[y++]=f+256;else if(f>=-32768)n[y++]=209,h1.setInt16(y,f),y+=2;else n[y++]=210,h1.setInt32(y,f),y+=4;else{let I;if((I=this.useFloat32)>0&&f<4294967296&&f>=-2147483648){n[y++]=202,h1.setFloat32(y,f);let a;if(I<4||(a=f*$Y[(n[y]&127)<<1|n[y+1]>>7])>>0===a){y+=4;return}else y--}n[y++]=203,h1.setFloat64(y,f),y+=8}else if(C==="object"||C==="function")if(!f)n[y++]=192;else{if(Q){let a=Q.get(f);if(a){if(!a.id){let s=Q.idsToInsert||(Q.idsToInsert=[]);a.id=s.push(a)}n[y++]=214,n[y++]=112,h1.setUint32(y,a.id),y+=4;return}else Q.set(f,{offset:y-X})}let I=f.constructor;if(I===Object)P(f);else if(I===Array)B(f);else if(I===Map)if(this.mapAsEmptyObject)n[y++]=128;else{if(b=f.size,b<16)n[y++]=128|b;else if(b<65536)n[y++]=222,n[y++]=b>>8,n[y++]=b&255;else n[y++]=223,h1.setUint32(y,b),y+=4;for(let[a,s]of f)L(a),L(s)}else{for(let a=0,s=wT.length;a<s;a++){let Z0=l50[a];if(f instanceof Z0){let o=wT[a];if(o.write){if(o.type)n[y++]=212,n[y++]=o.type,n[y++]=0;let s0=o.write.call(this,f);if(s0===f)if(Array.isArray(f))B(f);else P(f);else L(s0);return}let M0=n,R0=h1,m0=y;n=null;let O1;try{O1=o.pack.call(this,f,(s0)=>{if(n=M0,M0=null,y+=s0,y>a6)N(y);return{target:n,targetView:h1,position:y-s0}},L)}finally{if(M0)n=M0,h1=R0,y=m0,a6=n.length-10}if(O1){if(O1.length+y>a6)N(O1.length+y);y=Sh1(O1,n,y,o.type)}return}}if(Array.isArray(f))B(f);else{if(f.toJSON){let a=f.toJSON();if(a!==f)return L(a)}if(C==="function")return L(this.writeFunction&&this.writeFunction(f));P(f)}}}else if(C==="boolean")n[y++]=f?195:194;else if(C==="bigint"){if(f<9223372036854776000&&f>=-9223372036854776000)n[y++]=211,h1.setBigInt64(y,f);else if(f<18446744073709552000&&f>0)n[y++]=207,h1.setBigUint64(y,f);else if(this.largeBigIntToFloat)n[y++]=203,h1.setFloat64(y,Number(f));else if(this.largeBigIntToString)return L(f.toString());else if((this.useBigIntExtension||this.moreTypes)&&f<BigInt(2)**BigInt(1023)&&f>-(BigInt(2)**BigInt(1023))){n[y++]=199,y++,n[y++]=66;let I=[],a;do{let s=f&BigInt(255);a=(s&BigInt(128))===(f<BigInt(0)?BigInt(128):BigInt(0)),I.push(s),f>>=BigInt(8)}while(!((f===BigInt(0)||f===BigInt(-1))&&a));n[y-2]=I.length;for(let s=I.length;s>0;)n[y++]=Number(I[--s]);return}else throw new RangeError(f+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string");y+=8}else if(C==="undefined")if(this.encodeUndefinedAsNil)n[y++]=192;else n[y++]=212,n[y++]=0,n[y++]=0;else throw new Error("Unknown type: "+C)},R=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?(f)=>{let C;if(this.skipValues){C=[];for(let a in f)if((typeof f.hasOwnProperty!=="function"||f.hasOwnProperty(a))&&!this.skipValues.includes(f[a]))C.push(a)}else C=Object.keys(f);let b=C.length;if(b<16)n[y++]=128|b;else if(b<65536)n[y++]=222,n[y++]=b>>8,n[y++]=b&255;else n[y++]=223,h1.setUint32(y,b),y+=4;let I;if(this.coercibleKeyAsNumber)for(let a=0;a<b;a++){I=C[a];let s=Number(I);L(isNaN(s)?I:s),L(f[I])}else for(let a=0;a<b;a++)L(I=C[a]),L(f[I])}:(f)=>{n[y++]=222;let C=y-X;y+=2;let b=0;for(let I in f)if(typeof f.hasOwnProperty!=="function"||f.hasOwnProperty(I))L(I),L(f[I]),b++;if(b>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');n[C+++X]=b>>8,n[C+X]=b&255},M=this.useRecords===!1?R:Z.progressiveRecords&&!v?(f)=>{let C,b=Y.transitions||(Y.transitions=Object.create(null)),I=y++-X,a;for(let s in f)if(typeof f.hasOwnProperty!=="function"||f.hasOwnProperty(s)){if(C=b[s],C)b=C;else{let Z0=Object.keys(f),o=b;b=Y.transitions;let M0=0;for(let R0=0,m0=Z0.length;R0<m0;R0++){let O1=Z0[R0];if(C=b[O1],!C)C=b[O1]=Object.create(null),M0++;b=C}if(I+X+1==y)y--,_(b,Z0,M0);else k(b,Z0,I,M0);a=!0,b=o[s]}L(f[s])}if(!a){let s=b[w7];if(s)n[I+X]=s;else k(b,Object.keys(f),I,0)}}:(f)=>{let C,b=Y.transitions||(Y.transitions=Object.create(null)),I=0;for(let s in f)if(typeof f.hasOwnProperty!=="function"||f.hasOwnProperty(s)){if(C=b[s],!C)C=b[s]=Object.create(null),I++;b=C}let a=b[w7];if(a)if(a>=96&&v)n[y++]=((a-=96)&31)+96,n[y++]=a>>5;else n[y++]=a;else _(b,b.__keys__||Object.keys(f),I);for(let s in f)if(typeof f.hasOwnProperty!=="function"||f.hasOwnProperty(s))L(f[s])},O=typeof this.useRecords=="function"&&this.useRecords,P=O?(f)=>{O(f)?M(f):R(f)}:M,N=(f)=>{let C;if(f>16777216){if(f-X>m50)throw new Error("Packed buffer would be larger than maximum buffer size");C=Math.min(m50,Math.round(Math.max((f-X)*(f>67108864?1.25:2),4194304)/4096)*4096)}else C=(Math.max(f-X<<2,n.length-1)>>12)+1<<12;let b=new Xx(C);if(h1=b.dataView||(b.dataView=new DataView(b.buffer,0,C)),f=Math.min(f,n.length),n.copy)n.copy(b,0,X,f);else b.set(n.slice(X,f));return y-=X,X=0,a6=b.length-10,n=b},_=(f,C,b)=>{let I=Y.nextId;if(!I)I=64;if(I<q&&this.shouldShareStructure&&!this.shouldShareStructure(C)){if(I=Y.nextOwnId,!(I<F))I=q;Y.nextOwnId=I+1}else{if(I>=F)I=q;Y.nextId=I+1}let a=C.highByte=I>=96&&v?I-96>>5:-1;if(f[w7]=I,f.__keys__=C,Y[I-64]=C,I<q)if(C.isShared=!0,Y.sharedLength=I-63,$=!0,a>=0)n[y++]=(I&31)+96,n[y++]=a;else n[y++]=I;else{if(a>=0)n[y++]=213,n[y++]=114,n[y++]=(I&31)+96,n[y++]=a;else n[y++]=212,n[y++]=114,n[y++]=I;if(b)w+=x*b;if(c.length>=H)c.shift()[w7]=0;c.push(f),L(C)}},k=(f,C,b,I)=>{let a=n,s=y,Z0=a6,o=X;if(n=dz,y=0,X=0,!n)dz=n=new Xx(8192);a6=n.length-10,_(f,C,I),dz=n;let M0=y;if(n=a,y=s,a6=Z0,X=o,M0>1){let R0=y+M0-1;if(R0>a6)N(R0);let m0=b+X;n.copyWithin(m0+M0,m0+1,y),n.set(dz.slice(0,M0),m0),y=R0}else n[b+X]=dz[0]},h=(f)=>{let C=p50(f,n,X,y,Y,N,(b,I,a)=>{if(a)return $=!0;y=I;let s=n;if(L(b),j(),s!==n)return{position:y,targetView:h1,target:n};return y},this);if(C===0)return P(f);y=C}}useBuffer(Z){n=Z,n.dataView||(n.dataView=new DataView(n.buffer,n.byteOffset,n.byteLength)),y=0}set position(Z){y=Z}get position(){return y}clearSharedData(){if(this.structures)this.structures=[];if(this.typedStructs)this.typedStructs=[]}}l50=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,Zx];wT=[{pack(Z,J,X){let $=Z.getTime()/1000;if((this.useTimestamp32||Z.getMilliseconds()===0)&&$>=0&&$<4294967296){let{target:Y,targetView:Q,position:K}=J(6);Y[K++]=214,Y[K++]=255,Q.setUint32(K,$)}else if($>0&&$<4294967296){let{target:Y,targetView:Q,position:K}=J(10);Y[K++]=215,Y[K++]=255,Q.setUint32(K,Z.getMilliseconds()*4000000+($/1000/4294967296>>0)),Q.setUint32(K+4,$)}else if(isNaN($)){if(this.onInvalidDate)return J(0),X(this.onInvalidDate());let{target:Y,targetView:Q,position:K}=J(3);Y[K++]=212,Y[K++]=255,Y[K++]=255}else{let{target:Y,targetView:Q,position:K}=J(15);Y[K++]=199,Y[K++]=12,Y[K++]=255,Q.setUint32(K,Z.getMilliseconds()*1e6),Q.setBigInt64(K+4,BigInt(Math.floor($)))}}},{pack(Z,J,X){if(this.setAsEmptyObject)return J(0),X({});let $=Array.from(Z),{target:Y,position:Q}=J(this.moreTypes?3:0);if(this.moreTypes)Y[Q++]=212,Y[Q++]=115,Y[Q++]=0;X($)}},{pack(Z,J,X){let{target:$,position:Y}=J(this.moreTypes?3:0);if(this.moreTypes)$[Y++]=212,$[Y++]=101,$[Y++]=0;X([Z.name,Z.message,Z.cause])}},{pack(Z,J,X){let{target:$,position:Y}=J(this.moreTypes?3:0);if(this.moreTypes)$[Y++]=212,$[Y++]=120,$[Y++]=0;X([Z.source,Z.flags])}},{pack(Z,J){if(this.moreTypes)FT(Z,16,J);else cT(az?Buffer.from(Z):new Uint8Array(Z),J)}},{pack(Z,J){let X=Z.constructor;if(X!==y50&&this.moreTypes)FT(Z,qT.indexOf(X.name),J);else cT(Z,J)}},{pack(Z,J){if(this.moreTypes)FT(Z,17,J);else cT(az?Buffer.from(Z):new Uint8Array(Z),J)}},{pack(Z,J){let{target:X,position:$}=J(1);X[$]=193}}];function FT(Z,J,X,$){let Y=Z.byteLength;if(Y+1<256){var{target:Q,position:K}=X(4+Y);Q[K++]=199,Q[K++]=Y+1}else if(Y+1<65536){var{target:Q,position:K}=X(5+Y);Q[K++]=200,Q[K++]=Y+1>>8,Q[K++]=Y+1&255}else{var{target:Q,position:K,targetView:W}=X(7+Y);Q[K++]=201,W.setUint32(K,Y+1),K+=4}if(Q[K++]=116,Q[K++]=J,!Z.buffer)Z=new Uint8Array(Z);Q.set(new Uint8Array(Z.buffer,Z.byteOffset,Z.byteLength),K)}function cT(Z,J){let X=Z.byteLength;var $,Y;if(X<256){var{target:$,position:Y}=J(X+2);$[Y++]=196,$[Y++]=X}else if(X<65536){var{target:$,position:Y}=J(X+3);$[Y++]=197,$[Y++]=X>>8,$[Y++]=X&255}else{var{target:$,position:Y,targetView:Q}=J(X+5);$[Y++]=198,Q.setUint32(Y,X),Y+=4}$.set(Z,Y)}function Sh1(Z,J,X,$){let Y=Z.length;switch(Y){case 1:J[X++]=212;break;case 2:J[X++]=213;break;case 4:J[X++]=214;break;case 8:J[X++]=215;break;case 16:J[X++]=216;break;default:if(Y<256)J[X++]=199,J[X++]=Y;else if(Y<65536)J[X++]=200,J[X++]=Y>>8,J[X++]=Y&255;else J[X++]=201,J[X++]=Y>>24,J[X++]=Y>>16&255,J[X++]=Y>>8&255,J[X++]=Y&255}return J[X++]=$,J.set(Z,X),X+=Y,X}function Ah1(Z,J){let X,$=J.length*6,Y=Z.length-$;while(X=J.pop()){let{offset:Q,id:K}=X;Z.copyWithin(Q+$,Q,Y),$-=6;let W=Q+$;Z[W++]=214,Z[W++]=105,Z[W++]=K>>24,Z[W++]=K>>16&255,Z[W++]=K>>8&255,Z[W++]=K&255,Y=Q}return Z}function u50(Z,J,X){if(o1.length>0){h1.setUint32(o1.position+Z,y+X-o1.position-Z),o1.stringsPosition=y-Z;let $=o1;o1=null,J($[0]),J($[1])}}function i50(Z,J){return Z.isCompatible=(X)=>{let $=!X||(J.lastNamedStructuresLength||0)===X.length;if(!$)J._mergeStructures(X);return $},Z}function g50(Z,J){p50=Z,i50=J}var d50=new YY({useRecords:!1}),mh1=d50.pack,uh1=d50.pack;var lh1=512,yh1=1024,ph1=2048;var xT=3,n3=0,nz=2,Yx=1,jT=16,n50=["num","object","string","ascii"];n50[jT]="date";var gh1=[!1,!0,!0,!1,!1,!0,!0,!1],s50;try{new Function(""),s50=!0}catch(Z){}var QY,dh1=typeof Buffer!=="undefined",Qx,x7;try{Qx=new TextEncoder}catch(Z){}var ah1=dh1?function(Z,J,X){return Z.utf8Write(J,X,Z.byteLength-X)}:Qx&&Qx.encodeInto?function(Z,J,X){return Qx.encodeInto(J,Z.subarray(X)).written}:!1,$S6=Symbol("type"),YS6=Symbol("parent");g50(o50,th1);function o50(Z,J,X,$,Y,Q,K,W){let G=W.typedStructs||(W.typedStructs=[]),z=J.dataView,V=(G.lastStringStart||100)+$,H=J.length-10,v=$;if($>H)J=Q($),z=J.dataView,$-=X,v-=X,V-=X,X=0,H=J.length-10;let q,F=V,c=G.transitions||(G.transitions=Object.create(null)),w=G.nextId||G.length,x=w<15?1:w<240?2:w<61440?3:w<15728640?4:0;if(x===0)return 0;$+=x;let j=[],B,L=0;for(let M in Z){let O=Z[M],P=c[M];if(!P)c[M]=P={key:M,parent:c,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null};if($>H)J=Q($),z=J.dataView,$-=X,v-=X,V-=X,F-=X,X=0,H=J.length-10;switch(typeof O){case"number":let N=O;if(w<200||!P.num64){if(N>>0===N&&N<536870912&&N>-520093696){if(N<246&&N>=0&&(P.num8&&!(w>200&&P.num32)||N<32&&!P.num32))c=P.num8||D5(P,n3,1),J[$++]=N;else c=P.num32||D5(P,n3,4),z.setUint32($,N,!0),$+=4;break}else if(N<4294967296&&N>=-2147483648){if(z.setFloat32($,N,!0),gh1[J[$+3]>>>5]){let f;if((f=N*$Y[(J[$+3]&127)<<1|J[$+2]>>7])>>0===f){c=P.num32||D5(P,n3,4),$+=4;break}}}}c=P.num64||D5(P,n3,8),z.setFloat64($,N,!0),$+=8;break;case"string":let _=O.length;if(q=F-V,(_<<2)+F>H)J=Q((_<<2)+F),z=J.dataView,$-=X,v-=X,V-=X,F-=X,X=0,H=J.length-10;if(_>65280+q>>2){j.push(M,O,$-v);break}let k,h=F;if(_<64){let f,C,b;for(f=0;f<_;f++)if(C=O.charCodeAt(f),C<128)J[F++]=C;else if(C<2048)k=!0,J[F++]=C>>6|192,J[F++]=C&63|128;else if((C&64512)===55296&&((b=O.charCodeAt(f+1))&64512)===56320)k=!0,C=65536+((C&1023)<<10)+(b&1023),f++,J[F++]=C>>18|240,J[F++]=C>>12&63|128,J[F++]=C>>6&63|128,J[F++]=C&63|128;else k=!0,J[F++]=C>>12|224,J[F++]=C>>6&63|128,J[F++]=C&63|128}else F+=ah1(J,O,F),k=F-h>_;if(q<160||q<246&&(P.ascii8||P.string8)){if(k){if(!(c=P.string8))if(G.length>10&&(c=P.ascii8))c.__type=nz,P.ascii8=null,P.string8=c,K(null,0,!0);else c=D5(P,nz,1)}else if(q===0&&!B){B=!0,c=P.ascii0||D5(P,xT,0);break}else if(!(c=P.ascii8)&&!(G.length>10&&(c=P.string8)))c=D5(P,xT,1);J[$++]=q}else c=P.string16||D5(P,nz,2),z.setUint16($,q,!0),$+=2;break;case"object":if(O){if(O.constructor===Date)c=P.date64||D5(P,jT,8),z.setFloat64($,O.getTime(),!0),$+=8;else j.push(M,O,L);break}else if(P=a50(P,$,z,-10),P)c=P,$=QY;else j.push(M,O,L);break;case"boolean":c=P.num8||P.ascii8||D5(P,n3,1),J[$++]=O?249:248;break;case"undefined":if(P=a50(P,$,z,-9),P)c=P,$=QY;else j.push(M,O,L);break;default:j.push(M,O,L)}L++}for(let M=0,O=j.length;M<O;){let P=j[M++],N=j[M++],_=j[M++],k=c[P];if(!k)c[P]=k={key:P,parent:c,enumerationOffset:_-L,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null};let h;if(N){let f;if(q=F-V,q<65280)if(c=k.object16,c)f=2;else if(c=k.object32)f=4;else c=D5(k,Yx,2),f=2;else c=k.object32||D5(k,Yx,4),f=4;if(h=K(N,F),typeof h==="object")F=h.position,z=h.targetView,J=h.target,V-=X,$-=X,v-=X,X=0;else F=h;if(f===2)z.setUint16($,q,!0),$+=2;else z.setUint32($,q,!0),$+=4}else c=k.object16||D5(k,Yx,2),z.setInt16($,N===null?-10:-9,!0),$+=2;L++}let R=c[w7];if(R==null){R=W.typedStructs.length;let M=[],O=c,P,N;while((N=O.__type)!==void 0){let _=O.__size;O=O.__parent,P=O.key;let k=[N,_,P];if(O.enumerationOffset)k.push(O.enumerationOffset);M.push(k),O=O.parent}M.reverse(),c[w7]=R,W.typedStructs[R]=M,K(null,0,!0)}switch(x){case 1:if(R>=16)return 0;J[v]=R+32;break;case 2:if(R>=256)return 0;J[v]=56,J[v+1]=R;break;case 3:if(R>=65536)return 0;J[v]=57,z.setUint16(v+1,R,!0);break;case 4:if(R>=16777216)return 0;z.setUint32(v,(R<<8)+58,!0);break}if($<V){if(V===F)return $;J.copyWithin($,V,F),F+=$-V,G.lastStringStart=$-v}else if($>V){if(V===F)return $;return G.lastStringStart=$-v,o50(Z,J,X,v,Y,Q,K,W)}return F}function a50(Z,J,X,$){let Y;if(Y=Z.ascii8||Z.num8)return X.setInt8(J,$,!0),QY=J+1,Y;if(Y=Z.string16||Z.object16)return X.setInt16(J,$,!0),QY=J+2,Y;if(Y=Z.num32)return X.setUint32(J,3758096640+$,!0),QY=J+4,Y;if(Y=Z.num64)return X.setFloat64(J,NaN,!0),X.setInt8(J,$),QY=J+8,Y;QY=J;return}function D5(Z,J,X){let $=n50[J]+(X<<3),Y=Z[$]||(Z[$]=Object.create(null));return Y.__type=J,Y.__size=X,Y.__parent=Z,Y}function nh1(Z){if(!(Z instanceof Map))return Z;let J=Z.get("typed")||[];if(Object.isFrozen(J))J=J.map((Y)=>Y.slice(0));let X=Z.get("named"),$=Object.create(null);for(let Y=0,Q=J.length;Y<Q;Y++){let K=J[Y],W=$;for(let[G,z,V]of K){let H=W[V];if(!H)W[V]=H={key:V,parent:W,enumerationOffset:0,ascii0:null,ascii8:null,num8:null,string16:null,object16:null,num32:null,float64:null,date64:null};W=D5(H,G,z)}W[w7]=Y}return J.transitions=$,this.typedStructs=J,this.lastTypedStructuresLength=J.length,X}var UT=Symbol.for("source");function sh1(Z,J,X,$){let Y=Z[J++]-32;if(Y>=24)switch(Y){case 24:Y=Z[J++];break;case 25:Y=Z[J++]+(Z[J++]<<8);break;case 26:Y=Z[J++]+(Z[J++]<<8)+(Z[J++]<<16);break;case 27:Y=Z[J++]+(Z[J++]<<8)+(Z[J++]<<16)+(Z[J++]<<24);break}let Q=$.typedStructs&&$.typedStructs[Y];if(!Q){if(Z=Uint8Array.prototype.slice.call(Z,J,X),X-=J,J=0,!$.getStructures)throw new Error(`Reference to shared structure ${Y} without getStructures method`);if($._mergeStructures($.getStructures()),!$.typedStructs)throw new Error("Could not find any shared typed structures");if($.lastTypedStructuresLength=$.typedStructs.length,Q=$.typedStructs[Y],!Q)throw new Error("Could not find typed structure "+Y)}var{construct:K,fullConstruct:W}=Q;if(!K){K=Q.construct=function q(){},W=Q.fullConstruct=function q(){},W.prototype=$.structPrototype??{};var G=K.prototype=$.structPrototype?Object.create($.structPrototype):{};let V=[],H=0,v;for(let q=0,F=Q.length;q<F;q++){let c=Q[q],[w,x,j,B]=c;if(j==="__proto__")j="__proto_";let L={key:j,offset:H};if(B)V.splice(q+B,0,L);else V.push(L);let R;switch(x){case 0:R=()=>0;break;case 1:R=(O,P)=>{let N=O.bytes[P+L.offset];return N>=246?a3(N):N};break;case 2:R=(O,P)=>{let N=O.bytes,k=(N.dataView||(N.dataView=new DataView(N.buffer,N.byteOffset,N.byteLength))).getUint16(P+L.offset,!0);return k>=65280?a3(k&255):k};break;case 4:R=(O,P)=>{let N=O.bytes,k=(N.dataView||(N.dataView=new DataView(N.buffer,N.byteOffset,N.byteLength))).getUint32(P+L.offset,!0);return k>=4294967040?a3(k&255):k};break}L.getRef=R,H+=x;let M;switch(w){case xT:if(v&&!v.next)v.next=L;v=L,L.multiGetCount=0,M=function(O){let{bytes:P,position:N}=O,_=H+N,k=R(O,N);if(typeof k!=="number")return k;let h,f=L.next;while(f){if(h=f.getRef(O,N),typeof h==="number")break;else h=null;f=f.next}if(h==null)h=O.bytesEnd-_;if(O.srcString)return O.srcString.slice(k,h);return I50(P,k+_,h-k)};break;case nz:case Yx:if(v&&!v.next)v.next=L;v=L,M=function(O){let P=O.position,N=H+P,_=R(O,P);if(typeof _!=="number")return _;let k=O.bytes,h,f=L.next;while(f){if(h=f.getRef(O,P),typeof h==="number")break;else h=null;f=f.next}if(h==null)h=O.bytesEnd-N;if(w===nz)return k.toString("utf8",_+N,h+N);else{x7=O;try{return $.unpack(k,{start:_+N,end:h+N})}finally{x7=null}}};break;case n3:switch(x){case 4:M=function(O){let P=O.bytes,N=P.dataView||(P.dataView=new DataView(P.buffer,P.byteOffset,P.byteLength)),_=O.position+L.offset,k=N.getInt32(_,!0);if(k<536870912){if(k>-520093696)return k;if(k>-536870912)return a3(k&255)}let h=N.getFloat32(_,!0),f=$Y[(P[_+3]&127)<<1|P[_+2]>>7];return(f*h+(h>0?0.5:-0.5)>>0)/f};break;case 8:M=function(O){let P=O.bytes,_=(P.dataView||(P.dataView=new DataView(P.buffer,P.byteOffset,P.byteLength))).getFloat64(O.position+L.offset,!0);if(isNaN(_)){let k=P[O.position+L.offset];if(k>=246)return a3(k)}return _};break;case 1:M=function(O){let N=O.bytes[O.position+L.offset];return N<246?N:a3(N)};break}break;case jT:M=function(O){let P=O.bytes,N=P.dataView||(P.dataView=new DataView(P.buffer,P.byteOffset,P.byteLength));return new Date(N.getFloat64(O.position+L.offset,!0))};break}L.get=M}if(s50){let q=[],F=[],c=0,w;for(let j of V){if($.alwaysLazyProperty&&$.alwaysLazyProperty(j.key)){w=!0;continue}Object.defineProperty(G,j.key,{get:oh1(j.get),enumerable:!0});let B="v"+c++;F.push(B),q.push("o["+JSON.stringify(j.key)+"]="+B+"(s)")}if(w)q.push("__proto__:this");let x=new Function(...F,"var c=this;return function(s){var o=new c();"+q.join(";")+";return o;}").apply(W,V.map((j)=>j.get));Object.defineProperty(G,"toJSON",{value(j){return x.call(this,this[UT])}})}else Object.defineProperty(G,"toJSON",{value(q){let F={};for(let c=0,w=V.length;c<w;c++){let x=V[c].key;F[x]=this[x]}return F}})}var z=new K;return z[UT]={bytes:Z,position:J,srcString:"",bytesEnd:X},z}function a3(Z){switch(Z){case 246:return null;case 247:return;case 248:return!1;case 249:return!0}throw new Error("Unknown constant")}function oh1(Z){return function(){return Z(this[UT])}}function rh1(){if(x7)x7.bytes=Uint8Array.prototype.slice.call(x7.bytes,x7.position,x7.bytesEnd),x7.position=0,x7.bytesEnd=x7.bytes.length}function th1(Z,J){if(J.typedStructs){let $=new Map;$.set("named",Z),$.set("typed",J.typedStructs),Z=$}let X=J.lastTypedStructuresLength||0;return Z.isCompatible=($)=>{let Y=!0;if($ instanceof Map){if(($.get("named")||[]).length!==(J.lastNamedStructuresLength||0))Y=!1;if(($.get("typed")||[]).length!==X)Y=!1}else if($ instanceof Array||Array.isArray($)){if($.length!==(J.lastNamedStructuresLength||0))Y=!1}if(!Y)J._mergeStructures($);return Y},J.lastTypedStructuresLength=J.typedStructs&&J.typedStructs.length,Z}A50(sh1,nh1,rh1);var JS1=process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase()==="true";if(!JS1){let Z;try{if(Z=i("msgpackr-extract"),Z)E50(Z.extractStrings)}catch(J){}}var QU=t(yY0(),1);import Mn1 from"http";import Rn1 from"https";import YU from"fs";import On1 from"path";import Nn1 from"url";var pY0=`-----BEGIN CERTIFICATE-----
406
406
  MIIDRjCCAi6gAwIBAgIFOTEzNTIwDQYJKoZIhvcNAQELBQAwWDEQMA4GA1UEAxMH
407
407
  SFlUT1BJQTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNV
408
408
  BAcTB1NlYXR0bGUxEDAOBgNVBAoTB0hZVE9QSUEwHhcNMjQxMTEzMjIyMjEwWhcN
@@ -447,7 +447,7 @@ qYGMwU/HBVHkLAn5XvT2a9xM0mzZ558d+ahbw8qAgRxg7BZ+2PW/bf7F2WRBUk1f
447
447
  xauhAoGBALEspoxQozwohGQnP7EMF0/0JoKNpdNv0b0qCVvNiMo0+N297lI2mFQp
448
448
  6xYlW/1l9afLokklF/J2IsyBrTCZoY7SaEk/lMMrQSyra+y0z71ogZ8A4ny9fxsj
449
449
  0dDYJZGllL+3E/MQfd7k+KnOM/+A+cPoAnci76+L3vdkUb2P8SJk
450
- -----END RSA PRIVATE KEY-----`;var bf=process.env.PORT??8080,hf="0.10.22-prerelease",Sf;((Y)=>{Y.READY="WEBSERVER.READY";Y.STOPPED="WEBSERVER.STOPPED";Y.ERROR="WEBSERVER.ERROR";Y.UPGRADE="WEBSERVER.UPGRADE"})(Sf||={});class cK extends j0{static instance=new cK;_webserver=QU.default();_internalHttpServer;constructor(){super();this._webserver.use((Z,J,X)=>{J.header("Access-Control-Allow-Origin","*"),X()}),this._webserver.get("/",(Z,J)=>{J.json({status:"OK",version:hf,runtime:"node"})}),this._webserver.use(QU.default.static("assets",{dotfiles:"allow"}));try{this._webserver.use(QU.default.static(On1.dirname(i.resolve("/Users/arkdev/Desktop/HYTOPIA/hytopia/assets/release/index.js")),{dotfiles:"allow"}))}catch{}}start(){if(!this._internalHttpServer)this._internalHttpServer=process.env.NODE_ENV==="production"?Mn1.createServer(this._webserver):Rn1.createServer({key:YU.existsSync("assets/certs/localhost.key")?YU.readFileSync("assets/certs/localhost.key"):iY0,cert:YU.existsSync("assets/certs/localhost.crt")?YU.readFileSync("assets/certs/localhost.crt"):pY0},this._webserver),this._internalHttpServer.on("upgrade",this._onUpgrade),this._internalHttpServer.on("error",this._onError),this._internalHttpServer.on("close",this._onStopped);else p.warning("WebServer.start(): server already started!");this._internalHttpServer.listen(bf,this._onStarted),console.info(`WebServer.start(): Server running on port ${bf}.`)}stop(){if(this._internalHttpServer)return new Promise((Z,J)=>{this._internalHttpServer.close((X)=>{if(X)J(X);else Z(!0)})});else return p.warning("WebServer.stop(): server not started."),Promise.resolve(!1)}_onStarted=()=>{this.emitWithGlobal("WEBSERVER.READY",{})};_onUpgrade=async(Z,J,X)=>{let $=Nn1.parse(Z.url??"",!0).query,Y=$.connectionId?.toString(),Q=$.sessionToken?.toString()??"";if(Y&&R7.instance.isValidConnectionId(Y))Z.connectionId=Y;else{let K=await F7.instance.getPlayerSession(Q);if(K?.error){let W=`${K.error.code}: ${K.error.message}`;J.write(`HTTP/1.1 401 Unauthorized\r
450
+ -----END RSA PRIVATE KEY-----`;var bf=process.env.PORT??8080,hf="0.10.22",Sf;((Y)=>{Y.READY="WEBSERVER.READY";Y.STOPPED="WEBSERVER.STOPPED";Y.ERROR="WEBSERVER.ERROR";Y.UPGRADE="WEBSERVER.UPGRADE"})(Sf||={});class cK extends j0{static instance=new cK;_webserver=QU.default();_internalHttpServer;constructor(){super();this._webserver.use((Z,J,X)=>{J.header("Access-Control-Allow-Origin","*"),X()}),this._webserver.get("/",(Z,J)=>{J.json({status:"OK",version:hf,runtime:"node"})}),this._webserver.use(QU.default.static("assets",{dotfiles:"allow"}));try{this._webserver.use(QU.default.static(On1.dirname(i.resolve("/Users/arkdev/Desktop/HYTOPIA/hytopia/assets/release/index.js")),{dotfiles:"allow"}))}catch{}}start(){if(!this._internalHttpServer)this._internalHttpServer=process.env.NODE_ENV==="production"?Mn1.createServer(this._webserver):Rn1.createServer({key:YU.existsSync("assets/certs/localhost.key")?YU.readFileSync("assets/certs/localhost.key"):iY0,cert:YU.existsSync("assets/certs/localhost.crt")?YU.readFileSync("assets/certs/localhost.crt"):pY0},this._webserver),this._internalHttpServer.on("upgrade",this._onUpgrade),this._internalHttpServer.on("error",this._onError),this._internalHttpServer.on("close",this._onStopped);else p.warning("WebServer.start(): server already started!");this._internalHttpServer.listen(bf,this._onStarted),console.info(`WebServer.start(): Server running on port ${bf}.`)}stop(){if(this._internalHttpServer)return new Promise((Z,J)=>{this._internalHttpServer.close((X)=>{if(X)J(X);else Z(!0)})});else return p.warning("WebServer.stop(): server not started."),Promise.resolve(!1)}_onStarted=()=>{this.emitWithGlobal("WEBSERVER.READY",{})};_onUpgrade=async(Z,J,X)=>{let $=Nn1.parse(Z.url??"",!0).query,Y=$.connectionId?.toString(),Q=$.sessionToken?.toString()??"";if(Y&&R7.instance.isValidConnectionId(Y))Z.connectionId=Y;else{let K=await F7.instance.getPlayerSession(Q);if(K?.error){let W=`${K.error.code}: ${K.error.message}`;J.write(`HTTP/1.1 401 Unauthorized\r
451
451
  Content-Type: text/plain\r
452
452
  Content-Length: ${W.length}\r
453
453
  Connection: close\r